text
stringlengths 2
1.04M
| meta
dict |
---|---|
package org.pentaho.di.core.gui;
/**
* Classes implementing this interface have a chance to manage their internal representation states
* using the options dialog in Kettle.
*
* Instances of this class are automatically added to the EnterOptionsDialog.
* @author Alex Silva
*
*/
public interface GUIOption<E>
{
/**
* How the GUI should display the preference represented by this class.
* @author Alex Silva
*
*/
enum DisplayType {CHECK_BOX,TEXT_FIELD,ACTION_BUTTON};
public E getLastValue();
/**
* Sets the value; should also persist it.
* @param value
*/
public void setValue(E value);
public DisplayType getType();
String getLabelText();
}
| {
"content_hash": "e4953e427cffd184f121d110476a0509",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 99,
"avg_line_length": 19.11111111111111,
"alnum_prop": 0.7049418604651163,
"repo_name": "yintaoxue/read-open-source-code",
"id": "eefbcae1860c0e3340ceffea93a963c05fd0c880",
"size": "1590",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "kettle4.3/src/org/pentaho/di/core/gui/GUIOption.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C++",
"bytes": "40131"
},
{
"name": "CSS",
"bytes": "214256"
},
{
"name": "GAP",
"bytes": "32439"
},
{
"name": "Gnuplot",
"bytes": "7332"
},
{
"name": "HTML",
"bytes": "1600386"
},
{
"name": "Java",
"bytes": "87071709"
},
{
"name": "JavaScript",
"bytes": "1824173"
},
{
"name": "Lex",
"bytes": "480019"
},
{
"name": "Python",
"bytes": "274058"
},
{
"name": "XSLT",
"bytes": "1424"
}
],
"symlink_target": ""
} |
<?php
namespace MairieVoreppe\DemandeTravauxBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use MairieVoreppe\DemandeTravauxBundle\Model\PersonneMorale;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Entreprise
*
* Classe qui représente une entreprise.
*
* @ORM\Table()
* @ORM\Entity(repositoryClass="MairieVoreppe\DemandeTravauxBundle\Entity\EntrepriseRepository")
*/
class Entreprise extends PersonneMorale
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @var type Ville
*
* @ORM\OneToMany(targetEntity="MairieVoreppe\DemandeTravauxBundle\Entity\DemandeIntentionCT", mappedBy="entreprise")
*/
protected $dicts;
/**
* @var \
*
* Privé à cette classe.
*
* @ORM\ManyToOne(targetEntity="MairieVoreppe\DemandeTravauxBundle\Entity\Gerant", inversedBy="entreprise", cascade={"persist", "remove"})
* @Assert\Valid()
*/
private $gerant;
/**
* @var \
*
* Privé à cette classe.
*
* @ORM\ManyToOne(targetEntity="MairieVoreppe\DemandeTravauxBundle\Entity\StatutJuridique", inversedBy="entreprises")
* @ORM\JoinColumn(nullable=true)
*/
private $statutJuridique;
/**
* @var \Doctrine\Common\Collections\ArrayCollection()
*
*
*
* @ORM\OneToOne(targetEntity="MairieVoreppe\DemandeTravauxBundle\Entity\MOEPersonneMorale", cascade={"remove", "persist"}, orphanRemoval=true)
*/
private $moePersonneMorale;
/**
* @var boolean
*
*
* Toute entreprise peut prétendre à être prestataire ou non ! Les entreprise créé par défaut le son par défaut.
*
* @ORM\column(name="prestataire_dict", type="boolean", nullable=false)
*
*/
private $prestataireDICT;
/**
* Constructor
*/
public function __construct()
{
$this->dicts = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set gerant
*
* @param \MairieVoreppe\DemandeTravauxBundle\Entity\Gerant $gerant
*
* On ajoute un gérant à l'entreprise, il sera persisté en cascade lorsque l'entité sera hydratée
*
* @return Entreprise
*/
public function setGerant(\MairieVoreppe\DemandeTravauxBundle\Entity\Gerant $gerant = null)
{
$this->gerant = $gerant;
$gerant->addEntreprises($this);
return $this;
}
/**
* Get gerant
*
* @return \MairieVoreppe\DemandeTravauxBundle\Entity\Gerant
*/
public function getGerant()
{
return $this->gerant;
}
/**
* Set statutJuridique
*
* @param \MairieVoreppe\DemandeTravauxBundle\Entity\StatutJuridique $statutJuridique
* @return Entreprise
*/
public function setStatutJuridique(\MairieVoreppe\DemandeTravauxBundle\Entity\StatutJuridique $statutJuridique = null)
{
$this->statutJuridique = $statutJuridique;
return $this;
}
/**
* Get statutJuridique
*
* @return \MairieVoreppe\DemandeTravauxBundle\Entity\StatutJuridique
*/
public function getStatutJuridique()
{
return $this->statutJuridique;
}
/**
* Add dict
*
* @param \MairieVoreppe\DemandeTravauxBundle\Entity\DemandeIntentionCT $dict
* @return DemandeIntentionCT
*/
public function addDicts(\MairieVoreppe\DemandeTravauxBundle\Entity\DemandeIntentionCT $dict)
{
$this->dicts[] = $dict;
return $this;
}
/**
* Remove dict
*
* @param \MairieVoreppe\DemandeTravauxBundle\Entity\DemandeIntentionCT $dict
*/
public function removeDicts(\MairieVoreppe\DemandeTravauxBundle\Entity\DemandeIntentionCT $dict)
{
$this->dicts->removeElement($dict);
}
/**
* Get dtDict
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getDicts()
{
return $this->dicts;
}
public function __toString()
{
$toString = "";
$toString = $this->getRaisonSociale() . ' ' . $this->getStatutJuridique()->getAbreviation();
return $toString;
}
/**
* Add dict
*
* @param \MairieVoreppe\DemandeTravauxBundle\Entity\DemandeIntentionCT $dict
*
* @return Entreprise
*/
public function addDict(\MairieVoreppe\DemandeTravauxBundle\Entity\DemandeIntentionCT $dict)
{
$this->dicts[] = $dict;
return $this;
}
/**
* Remove dict
*
* @param \MairieVoreppe\DemandeTravauxBundle\Entity\DemandeIntentionCT $dict
*/
public function removeDict(\MairieVoreppe\DemandeTravauxBundle\Entity\DemandeIntentionCT $dict)
{
$this->dicts->removeElement($dict);
}
/**
* Set moePersonneMorale
*
* @param \MairieVoreppe\DemandeTravauxBundle\Entity\MOEPersonneMorale $moePersonneMorale
*
* @return Entreprise
*/
public function setMoePersonneMorale(\MairieVoreppe\DemandeTravauxBundle\Entity\MOEPersonneMorale $moePersonneMorale = null)
{
$this->moePersonneMorale = $moePersonneMorale;
return $this;
}
/**
* Get moePersonneMorale
*
* @return \MairieVoreppe\DemandeTravauxBundle\Entity\MOEPersonneMorale
*/
public function getMoePersonneMorale()
{
return $this->moePersonneMorale;
}
/**
* Set prestataireDICT
*
* @param boolean $prestataireDICT
*
* @return MOEPersonneMorale
*/
public function setPrestataireDICT($prestataireDICT)
{
$this->prestataireDICT = $prestataireDICT;
return $this;
}
/**
* Get prestataireDICT
*
* @return boolean
*/
public function getPrestataireDICT()
{
return $this->prestataireDICT;
}
}
| {
"content_hash": "7a46b36e54c6994092f4c0a327b0269c",
"timestamp": "",
"source": "github",
"line_count": 261,
"max_line_length": 147,
"avg_line_length": 23.337164750957854,
"alnum_prop": 0.6191101625348875,
"repo_name": "chadyred/demandeTravaux",
"id": "2e00ef7f5702d722831022e76a0fb6e27e99b72e",
"size": "6108",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/MairieVoreppe/DemandeTravauxBundle/Entity/Entreprise.php",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "3073"
},
{
"name": "CSS",
"bytes": "10366"
},
{
"name": "HTML",
"bytes": "322001"
},
{
"name": "JavaScript",
"bytes": "88052"
},
{
"name": "PHP",
"bytes": "668602"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html>
<head>
<title>OpenJava : Tutorial</title>
<meta http-equiv="Keywords" content="java, openjava, reflection">
</head>
<body bgcolor="white"
text="#000000" link="#007fff" vlink="#006fdf" alink="#ff0000">
<h2><!---------------------------------------------------------------------->
<center>
<h1><font color="Blue">OpenJava Tutorial</font></h1>
</center>
<!---------------------------------------------------------------------->
<hr width="100%">
<!---------------------------------------------------------------------->
7. <font color="blue">Synchronization of Translation</font>
</h2>
<p>
As the default behavior of OpenJava compiler, there is no assurance of
callee-side translation ordering. In the case that we make it sure to
translate a class <b>SubMyObject</b> after a class <b>MyObject</b>, we
can use the method <code>waitTranslation()</code> in
<b>java.lang.OJClass</b>.
<br><blockquote><pre>
public void waitTranslation(OJClass)
throws MOPException
</pre></blockquote>
At the invocation of this method, the translation on the current
class declaration stops and it return to continue after the
translation on the class given as the argument finished.
<h3>7.1. Simple Examples</h3>
<p>
Furthermore, the part where that class is used comes. There are
several part related to the use of class. i.e. object allocations,
method calls, field accesses, .. We call this kind of translation
<i>caller-side translation</i>.
<p>
For the convenience of explanation, suppose a base class
<b>MyObject</b> extended by a metaclass <b>MyClass</b>, like
following:
<br><blockquote><pre><font color=darkblue>
public class <font color=black>SubMyObject</font> instantiates <font color=black>SyncClass</font> extends <font color=black>MyObject</font>
{}
class <font color=black>MyObject</font> instantiates <font color=black>AnotherClass</font>
{}
class <font color=black>SubSubMyObject</font> instantiates <font color=black>SyncClass</font> extends <font color=black>SubMyObject</font>
{}
</font></pre></blockquote>
<br><blockquote><pre><font color=darkblue>
public class <font color=black>SyncClass</font> instantiates <font color=black>Metaclass</font> extends <font color=black>OJClass</font>
{
void translateDefinition() throws <font color=black>MOPException</font> {
<font color=black>OJClass</font> baseclazz = getSuperclass();
<font color=black>System</font>.out.println( getName() + "<i> is waiting for </i>" + base.getName() );
waitTranslation( baseclazz );
<font color=black>System</font>.out.println( getName() + "<i> finished</i>" );
}
}
</font></pre></blockquote>
We can see the following messages in running OpenJava compiler.
<br><blockquote><pre><font color=darkred>
MyObject is waiting for java.lang.Object
MyObject finished
SubSubMyObject is waiting for SubMyObject
SubMyObject is waiting for MyObject
SubMyObject finished
SubSubMyObject finished
</font></pre></blockquote>
<p>
<h3>7.2. Deadlocks</h3>
<p>
In the case of the system detects some deadlocks,
<code>waitTranslation()</code> throws an exception
<code>MOPException</code>. If already the translation of
a class <b>A</b> were waiting for the translation of a class <b>B</b>,
the invocation of <code>waitTranslation()</code> on the translation
of the class <b>B</b> would not block but throw an exception.
<p>
<!---------------------------------------------------------------------->
<hr width="100%">
<!---------------------------------------------------------------------->
<center>
Please send any message to :
<address>
[email protected]
</address><BR>
</center>
<font size=1>Copyright (C) 1999 by Michaki Tatsubori.</font><br>
<font size=1>Java(TM) is a trademark of Sun Microsystems, Inc.</font>
<!---------------------------------------------------------------------->
</body>
</html>
| {
"content_hash": "20d0695c2b23a6eeef9e2dd93250aeb0",
"timestamp": "",
"source": "github",
"line_count": 131,
"max_line_length": 139,
"avg_line_length": 29.770992366412212,
"alnum_prop": 0.6441025641025641,
"repo_name": "jeffoffutt/OJ",
"id": "6385a6bf27b2f32bc948f17a4eadfe5fbccbb83e",
"size": "3900",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tutorial_ORIGINAL_VERSION/Synchronize.html",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "1391"
},
{
"name": "Groovy",
"bytes": "75"
},
{
"name": "HTML",
"bytes": "9926985"
},
{
"name": "Java",
"bytes": "1862284"
},
{
"name": "Perl",
"bytes": "24319"
},
{
"name": "Scala",
"bytes": "71"
},
{
"name": "Shell",
"bytes": "6991"
}
],
"symlink_target": ""
} |
<div class="doc-content">
<header class="api-profile-header" >
<h2 class="md-display-1" >{{currentDoc.name}} API Documentation</h2>
</header>
<div layout="row" class="api-options-bar with-icon"></div>
<div class="api-profile-description">
<p><code><md-chips></code> is an input component for building lists of strings or objects. The list items are
displayed as 'chips'. This component can make use of an <code><input></code> element or an
<code><md-autocomplete></code> element.</p>
<h3 id="custom-templates">Custom templates</h3>
<p>A custom template may be provided to render the content of each chip. This is achieved by
specifying an <code><md-chip-template></code> element containing the custom content as a child of
<code><md-chips></code>.</p>
<p>Note: Any attributes on
<code><md-chip-template></code> will be dropped as only the innerHTML is used for the chip template. The
variables <code>$chip</code> and <code>$index</code> are available in the scope of <code><md-chip-template></code>, representing
the chip object and its index in the list of chips, respectively.
To override the chip delete control, include an element (ideally a button) with the attribute
<code>md-chip-remove</code>. A click listener to remove the chip will be added automatically. The element
is also placed as a sibling to the chip content (on which there are also click listeners) to
avoid a nested ng-click situation.</p>
<!-- Note: We no longer want to include this in the site docs; but it should remain here for
future developers and those looking at the documentation.
<h3> Pending Features </h3>
<ul style="padding-left:20px;">
<ul>Style
<li>Colours for hover, press states (ripple?).</li>
</ul>
<ul>Validation
<li>allow a validation callback</li>
<li>highlighting style for invalid chips</li>
</ul>
<ul>Item mutation
<li>Support `
<md-chip-edit>` template, show/hide the edit element on tap/click? double tap/double
click?
</li>
</ul>
<ul>Truncation and Disambiguation (?)
<li>Truncate chip text where possible, but do not truncate entries such that two are
indistinguishable.</li>
</ul>
<ul>Drag and Drop
<li>Drag and drop chips between related `<md-chips>` elements.
</li>
</ul>
</ul>
//-->
<p>Sometimes developers want to limit the amount of possible chips.<br/>
You can specify the maximum amount of chips by using the following markup.</p>
<hljs lang="html">
<md-chips
ng-model="myItems"
placeholder="Add an item"
md-max-chips="5">
</md-chips>
</hljs>
<p>In some cases, you have an autocomplete inside of the <code>md-chips</code>.<br/>
When the maximum amount of chips has been reached, you can also disable the autocomplete
selection.<br/>
Here is an example markup.</p>
<hljs lang="html">
<md-chips ng-model="myItems" md-max-chips="5">
<md-autocomplete ng-hide="myItems.length > 5" ...></md-autocomplete>
</md-chips>
</hljs>
<h3 id="accessibility">Accessibility</h3>
<p>The <code>md-chips</code> component supports keyboard and screen reader users since Version 1.1.2. In
order to achieve this, we modified the chips behavior to select newly appended chips for
<code>300ms</code> before re-focusing the input and allowing the user to type.</p>
<p>For most users, this delay is small enough that it will not be noticeable but allows certain
screen readers to function properly (JAWS and NVDA in particular).</p>
<p>We introduced a new <code>md-chip-append-delay</code> option to allow developers to better control this
behavior.</p>
<p>Please refer to the documentation of this option (below) for more information.</p>
</div>
<div>
<section class="api-section">
<h2 id="Usage">Usage</h2>
<hljs lang="html">
<md-chips
ng-model="myItems"
placeholder="Add an item"
readonly="isReadOnly">
</md-chips>
</hljs>
<p><h3>Validation</h3>
When using <a href="https://docs.angularjs.org/api/ngMessages">ngMessages</a>, you can show errors based
on our custom validators.</p>
<hljs lang="html">
<form name="userForm">
<md-chips
name="fruits"
ng-model="myItems"
placeholder="Add an item"
md-max-chips="5">
</md-chips>
<div ng-messages="userForm.fruits.$error" ng-if="userForm.$dirty">
<div ng-message="md-max-chips">You reached the maximum amount of chips</div>
</div>
</form>
</hljs>
</section>
<div class="api-param-section">
<h2>
Attributes
</h2>
<div class="api-param-table">
<table class="md-api-table">
<thead>
<tr>
<th>Parameter</th>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr class="api-params-item">
<td style="white-space: nowrap;">
<b>* ng-model</b>
<span hide show-sm>
<code class="api-type label type-hint type-hint-expression">expression</code></span>
</td>
<td style="white-space: nowrap;">
<code class="api-type label type-hint type-hint-expression">expression</code></td>
<td class="description">
<p>Assignable AngularJS expression to be data-bound to the list of
chips. The expression should evaluate to a <code>string</code> or <code>Object</code> Array. The type of this
array should align with the return value of <code>md-transform-chip</code>.</p>
</td>
</tr>
<tr class="api-params-item">
<td style="white-space: nowrap;">
<b>* md-transform-chip</b>
<span hide show-sm>
<code class="api-type label type-hint type-hint-expression">expression</code></span>
</td>
<td style="white-space: nowrap;">
<code class="api-type label type-hint type-hint-expression">expression</code></td>
<td class="description">
<p>An expression of form <code>myFunction($chip)</code> that when
called expects one of the following return values:</p>
<ul>
<li>an object representing the <code>$chip</code> input string</li>
<li><code>undefined</code> to simply add the <code>$chip</code> input string, or</li>
<li><code>null</code> to prevent the chip from being appended</li>
</ul>
</td>
</tr>
<tr class="api-params-item">
<td style="white-space: nowrap;">
ng-change
<span hide show-sm>
<code class="api-type label type-hint type-hint-expression">expression</code></span>
</td>
<td style="white-space: nowrap;">
<code class="api-type label type-hint type-hint-expression">expression</code></td>
<td class="description">
<p>AngularJS expression to be executed on chip addition, removal,
or content change.</p>
</td>
</tr>
<tr class="api-params-item">
<td style="white-space: nowrap;">
placeholder
<span hide show-sm>
<code class="api-type label type-hint type-hint-string">string</code></span>
</td>
<td style="white-space: nowrap;">
<code class="api-type label type-hint type-hint-string">string</code></td>
<td class="description">
<p>Placeholder text that will be forwarded to the input.</p>
</td>
</tr>
<tr class="api-params-item">
<td style="white-space: nowrap;">
secondary-placeholder
<span hide show-sm>
<code class="api-type label type-hint type-hint-string">string</code></span>
</td>
<td style="white-space: nowrap;">
<code class="api-type label type-hint type-hint-string">string</code></td>
<td class="description">
<p>Placeholder text that will be forwarded to the input,
displayed when there is at least one item in the list</p>
</td>
</tr>
<tr class="api-params-item">
<td style="white-space: nowrap;">
md-removable
<span hide show-sm>
<code class="api-type label type-hint type-hint-boolean">boolean</code></span>
</td>
<td style="white-space: nowrap;">
<code class="api-type label type-hint type-hint-boolean">boolean</code></td>
<td class="description">
<p>Enables or disables the deletion of chips through the
removal icon or the Delete/Backspace key. Defaults to true.</p>
</td>
</tr>
<tr class="api-params-item">
<td style="white-space: nowrap;">
readonly
<span hide show-sm>
<code class="api-type label type-hint type-hint-boolean">boolean</code></span>
</td>
<td style="white-space: nowrap;">
<code class="api-type label type-hint type-hint-boolean">boolean</code></td>
<td class="description">
<p>Disables list manipulation (deleting or adding list items), hiding
the input and delete buttons. If no <code>ng-model</code> is provided, the chips will automatically be
marked as readonly.<br/><br/>
When <code>md-removable</code> is not defined, the <code>md-remove</code> behavior will be overwritten and
disabled.</p>
</td>
</tr>
<tr class="api-params-item">
<td style="white-space: nowrap;">
md-enable-chip-edit
<span hide show-sm>
<code class="api-type label type-hint type-hint-boolean">boolean</code></span>
</td>
<td style="white-space: nowrap;">
<code class="api-type label type-hint type-hint-boolean">boolean</code></td>
<td class="description">
<p>Set this to <code>"true"</code> to enable editing of chip contents.
The user can go into edit mode by pressing the <code>space</code> or <code>enter</code> keys, or by double
clicking on the chip. Chip editing is only supported for chips using the basic template.
<strong>Note:</strong> This attribute is only evaluated once; it is not watched.</p>
</td>
</tr>
<tr class="api-params-item">
<td style="white-space: nowrap;">
ng-required
<span hide show-sm>
<code class="api-type label type-hint type-hint-boolean">boolean</code></span>
</td>
<td style="white-space: nowrap;">
<code class="api-type label type-hint type-hint-boolean">boolean</code></td>
<td class="description">
<p>Whether ng-model is allowed to be empty or not.</p>
</td>
</tr>
<tr class="api-params-item">
<td style="white-space: nowrap;">
md-max-chips
<span hide show-sm>
<code class="api-type label type-hint type-hint-number">number</code></span>
</td>
<td style="white-space: nowrap;">
<code class="api-type label type-hint type-hint-number">number</code></td>
<td class="description">
<p>The maximum number of chips allowed to add through user input.
<br/><br/>The validation property <code>md-max-chips</code> can be used when the max chips
amount is reached.</p>
</td>
</tr>
<tr class="api-params-item">
<td style="white-space: nowrap;">
md-add-on-blur
<span hide show-sm>
<code class="api-type label type-hint type-hint-boolean">boolean</code></span>
</td>
<td style="white-space: nowrap;">
<code class="api-type label type-hint type-hint-boolean">boolean</code></td>
<td class="description">
<p>When set to <code>"true"</code>, the remaining text inside of the input
will be converted into a new chip on blur.
<strong>Note:</strong> This attribute is only evaluated once; it is not watched.</p>
</td>
</tr>
<tr class="api-params-item">
<td style="white-space: nowrap;">
md-on-add
<span hide show-sm>
<code class="api-type label type-hint type-hint-expression">expression</code></span>
</td>
<td style="white-space: nowrap;">
<code class="api-type label type-hint type-hint-expression">expression</code></td>
<td class="description">
<p>An expression which will be called when a chip has been
added with <code>$chip</code> and <code>$index</code> available as parameters.</p>
</td>
</tr>
<tr class="api-params-item">
<td style="white-space: nowrap;">
md-on-remove
<span hide show-sm>
<code class="api-type label type-hint type-hint-expression">expression</code></span>
</td>
<td style="white-space: nowrap;">
<code class="api-type label type-hint type-hint-expression">expression</code></td>
<td class="description">
<p>An expression which will be called when a chip has been
removed with <code>$chip</code>, <code>$index</code>, and <code>$event</code> available as parameters.</p>
</td>
</tr>
<tr class="api-params-item">
<td style="white-space: nowrap;">
md-on-select
<span hide show-sm>
<code class="api-type label type-hint type-hint-expression">expression</code></span>
</td>
<td style="white-space: nowrap;">
<code class="api-type label type-hint type-hint-expression">expression</code></td>
<td class="description">
<p>An expression which will be called when a chip is selected.</p>
</td>
</tr>
<tr class="api-params-item">
<td style="white-space: nowrap;">
md-require-match
<span hide show-sm>
<code class="api-type label type-hint type-hint-boolean">boolean</code></span>
</td>
<td style="white-space: nowrap;">
<code class="api-type label type-hint type-hint-boolean">boolean</code></td>
<td class="description">
<p>If true, and the chips template contains an autocomplete,
only allow selection of pre-defined chips (i.e. you cannot add new ones).</p>
</td>
</tr>
<tr class="api-params-item">
<td style="white-space: nowrap;">
input-aria-describedby
<span hide show-sm>
<code class="api-type label type-hint type-hint-string">string</code></span>
</td>
<td style="white-space: nowrap;">
<code class="api-type label type-hint type-hint-string">string</code></td>
<td class="description">
<p>A space-separated list of element IDs. This should
contain the IDs of any elements that describe this autocomplete. Screen readers will read
the content of these elements at the end of announcing that the chips input has been
selected and describing its current state. The descriptive elements do not need to be
visible on the page.</p>
</td>
</tr>
<tr class="api-params-item">
<td style="white-space: nowrap;">
input-aria-labelledby
<span hide show-sm>
<code class="api-type label type-hint type-hint-string">string</code></span>
</td>
<td style="white-space: nowrap;">
<code class="api-type label type-hint type-hint-string">string</code></td>
<td class="description">
<p>A space-separated list of element IDs. The ideal use
case is that this would contain the ID of a <code><label></code> element that is associated with these
chips.<br><br>
For <code><label id="state">US State</label></code>, you would set this to
<code>input-aria-labelledby="state"</code>.</p>
</td>
</tr>
<tr class="api-params-item">
<td style="white-space: nowrap;">
input-aria-label
<span hide show-sm>
<code class="api-type label type-hint type-hint-string">string</code></span>
</td>
<td style="white-space: nowrap;">
<code class="api-type label type-hint type-hint-string">string</code></td>
<td class="description">
<p>A string read by screen readers to identify the input.
For static chips, this will be applied to the chips container.</p>
</td>
</tr>
<tr class="api-params-item">
<td style="white-space: nowrap;">
container-hint
<span hide show-sm>
<code class="api-type label type-hint type-hint-string">string</code></span>
</td>
<td style="white-space: nowrap;">
<code class="api-type label type-hint type-hint-string">string</code></td>
<td class="description">
<p>A string read by screen readers informing users of how to
navigate the chips when there are chips. Only applies when <code>ng-model</code> is defined.</p>
</td>
</tr>
<tr class="api-params-item">
<td style="white-space: nowrap;">
container-empty-hint
<span hide show-sm>
<code class="api-type label type-hint type-hint-string">string</code></span>
</td>
<td style="white-space: nowrap;">
<code class="api-type label type-hint type-hint-string">string</code></td>
<td class="description">
<p>A string read by screen readers informing users of how to
add chips when there are no chips. You will want to use this to override the default when
in a non-English locale. Only applies when <code>ng-model</code> is defined.</p>
</td>
</tr>
<tr class="api-params-item">
<td style="white-space: nowrap;">
delete-hint
<span hide show-sm>
<code class="api-type label type-hint type-hint-string">string</code></span>
</td>
<td style="white-space: nowrap;">
<code class="api-type label type-hint type-hint-string">string</code></td>
<td class="description">
<p>A string read by screen readers instructing users that pressing
the delete key will remove the chip. You will want to use this to override the default when
in a non-English locale.</p>
</td>
</tr>
<tr class="api-params-item">
<td style="white-space: nowrap;">
delete-button-label
<span hide show-sm>
<code class="api-type label type-hint type-hint-string">string</code></span>
</td>
<td style="white-space: nowrap;">
<code class="api-type label type-hint type-hint-string">string</code></td>
<td class="description">
<p>Text for the <code>aria-label</code> of the button with the
<code>md-chip-remove</code> class. If the chip is an Object, then this will be the only text in the
label. Otherwise, this is prepended to the string representation of the chip. Defaults to
"Remove", which would be "Remove Apple" for a chip that contained the string "Apple".
You will want to use this to override the default when in a non-English locale.</p>
</td>
</tr>
<tr class="api-params-item">
<td style="white-space: nowrap;">
md-removed-message
<span hide show-sm>
<code class="api-type label type-hint type-hint-string">string</code></span>
</td>
<td style="white-space: nowrap;">
<code class="api-type label type-hint type-hint-string">string</code></td>
<td class="description">
<p>Screen readers will announce this message following the
chips contents. The default is <code>"removed"</code>. If a chip with the content of "Apple" was
removed, the screen reader would read "Apple removed". You will want to use this to override
the default when in a non-English locale.</p>
</td>
</tr>
<tr class="api-params-item">
<td style="white-space: nowrap;">
md-added-message
<span hide show-sm>
<code class="api-type label type-hint type-hint-string">string</code></span>
</td>
<td style="white-space: nowrap;">
<code class="api-type label type-hint type-hint-string">string</code></td>
<td class="description">
<p>Screen readers will announce this message following the
chips contents. The default is <code>"added"</code>. If a chip with the content of "Apple" was
created, the screen reader would read "Apple added". You will want to use this to override
the default when in a non-English locale.</p>
</td>
</tr>
<tr class="api-params-item">
<td style="white-space: nowrap;">
md-separator-keys
<span hide show-sm>
<code class="api-type label type-hint type-hint-expression">expression</code></span>
</td>
<td style="white-space: nowrap;">
<code class="api-type label type-hint type-hint-expression">expression</code></td>
<td class="description">
<p>An array of key codes used to separate chips.</p>
</td>
</tr>
<tr class="api-params-item">
<td style="white-space: nowrap;">
md-chip-append-delay
<span hide show-sm>
<code class="api-type label type-hint type-hint-string">string</code></span>
</td>
<td style="white-space: nowrap;">
<code class="api-type label type-hint type-hint-string">string</code></td>
<td class="description">
<p>The number of milliseconds that the component will select
a newly appended chip before allowing a user to type into the input. This is <strong>necessary</strong>
for keyboard accessibility for screen readers. It defaults to 300ms and any number less than
300 can cause issues with screen readers (particularly JAWS and sometimes NVDA).</p>
<p> <em>Available since Version 1.1.2.</em></p>
<p> <strong>Note:</strong> You can safely set this to <code>0</code> in one of the following two instances:</p>
<ol>
<li><p>You are targeting an iOS or Safari-only application (where users would use VoiceOver) or
only ChromeVox users.</p>
</li>
<li><p>If you have utilized the <code>md-separator-keys</code> to disable the <code>enter</code> keystroke in
favor of another one (such as <code>,</code> or <code>;</code>).</p>
</li>
</ol>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
| {
"content_hash": "c8a74286db0f39ef49f89f6b9cdc6aaf",
"timestamp": "",
"source": "github",
"line_count": 749,
"max_line_length": 134,
"avg_line_length": 30.599465954606142,
"alnum_prop": 0.6068763907674855,
"repo_name": "angular/code.material.angularjs.org",
"id": "9ee7077cdaeaa9303ca67cc78c4f8298cfb3b2c4",
"size": "22919",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "1.2.0-rc.2/partials/api/material.components.chips/directive/mdChips.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "33810102"
},
{
"name": "HTML",
"bytes": "41451971"
},
{
"name": "JavaScript",
"bytes": "27787154"
},
{
"name": "SCSS",
"bytes": "461693"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<export><workspace name="4b-optic-mlw17"><query active="true" focus="true" mode="xquery" name="0 Intro">"
This workspace provides more involved examples of the Optic API, which is new in MarkLogic 9.
This API provides all of the query operators familiar to SQL or SPARQL developers,
but in within a programming language.
MarkLogic 9 provides the same Optic API in JavaScript, XQuery, and Java, so queries
that you write can be easily ported from one language to another, and will run the
same in any of the host languages, and regardless of whether the executing platform
is MarkLogic enode or a client-side system.
"</query><query active="true" focus="false" mode="xquery" name="5 Your Models">(: This is an Optic query, crafted to report on the models in your database. :)
import module namespace op = "http://marklogic.com/optic" at "/MarkLogic/optic.xqy";
let $es := op:prefixer("http://marklogic.com/entity-services#")
let $rdf := op:prefixer("http://www.w3.org/1999/02/22-rdf-syntax-ns#")
(: Thes variables will be used to assemble the various joins I need :)
let $model := op:col("model")
let $type := op:col("type")
let $property := op:col("property")
let $property2 := op:col("property2")
(: The entity services graph connects models to types to properties :)
return
(: The first from-triples block contains columns I expect in each row. :)
op:from-triples( (
(: from the model, get its metadata :)
op:pattern( $model, $rdf("type"), $es("Model") ),
op:pattern( $model, $es("definitions"), $type),
op:pattern( $model, $es("version"), op:col("version")),
op:pattern( $model, $es("title"), op:col("modelTitle")),
(: from the type, get the primary key and all the property objects :)
op:pattern( $type, $es("title"), op:col("typeTitle")),
op:pattern( $type, $es("primaryKey"), op:col("pk")),
op:pattern( $type, $es("property"), $property),
op:pattern( $property, $rdf("type"), $es("Property")),
op:pattern( $property, $es("title"), op:col("propertyLabel"))
))
(: join to information about relationships. outer join because not every property is a relationship :)
=>op:join-left-outer(
(: we need a union to get 'ref' from both arrays and singleton references. :)
op:union(
op:from-triples( (
op:pattern( $property2, $es("items"), op:col("items")),
op:pattern( op:col("items"), $es("ref"), op:col("referent")))),
op:from-triples( (
op:pattern( $property2, $es("ref"), op:col("referent")))))
(: join the referent from either items or directly in order to find the name of the propety :)
=>op:join-inner(
op:from-triples( (op:pattern( op:col("referent"), $es("title"), op:col("relationshipWith"))) ),
op:on(op:col("referent"), op:col("referent") )),
op:on($property, $property2))
=>op:where( op:eq(op:col("version"), "0.0.0"))
=>op:order-by(("version", "typeTitle", "propertyLabel"))
=>op:select( ("modelTitle", "version", "typeTitle", "propertyLabel", "relationshipWith"))
=>op:result()</query><query active="true" focus="false" mode="xquery" name="2 Triples - title,version">import module namespace op = "http://marklogic.com/optic" at "/MarkLogic/optic.xqy";
let $es := op:prefixer("http://marklogic.com/entity-services#")
let $rdf := op:prefixer("http://www.w3.org/1999/02/22-rdf-syntax-ns#")
let $model := op:col("model")
let $type := op:col("type")
return
op:from-triples( (
(: from the model, get its metadata :)
op:pattern( $model, $rdf("type"), $es("Model") ),
op:pattern( $model, $es("version"), op:col("version")),
op:pattern( $model, $es("title"), op:col("modelTitle"))
))
=>op:join-left-outer(
op:from-triples(
op:pattern( $model, $es("description"), op:col("description"))
))
=>op:order-by("version")
=>op:select( ("modelTitle", "version", "description"))
=>op:where-distinct()
=>op:result()</query><query active="true" focus="false" mode="xquery" name="3 Counting instances">import module namespace op = "http://marklogic.com/optic" at "/MarkLogic/optic.xqy";
let $es := op:prefixer("http://marklogic.com/entity-services#")
let $rdf := op:prefixer("http://www.w3.org/1999/02/22-rdf-syntax-ns#")
let $type := op:col("type")
return
op:from-triples( (
(: from the model, get its metadata :)
op:pattern( $type, $rdf("type"), $es("EntityType") ),
op:pattern( $type, $es("version"), op:col("version")),
op:pattern( $type, $es("title"), op:col("typeTitle"))
))
=>op:join-inner(
op:from-triples((
op:pattern( op:col("instanceIri"), $rdf("type"), $type)
))
=>op:group-by($type, op:count("ct")))
=>op:order-by("version")
=>op:select( ("typeTitle", "version", "ct"))
=>op:where-distinct()
=>op:result()</query><query active="true" focus="false" mode="xquery" name="4 lexicon">import module namespace op = "http://marklogic.com/optic" at "/MarkLogic/optic.xqy";
op:from-lexicons(
map:entry("total",
cts:path-reference(
"//es:instance/Order/orderLines/OrderLine/total",
"type=decimal",
map:entry("es", "http://marklogic.com/entity-services"))),
"myview")
(:
=>op:where( op:gt( "total", "80") )
=>op:order-by(op:desc("total"))
=>op:select( ("total") )
:)
=>op:result()
</query><query active="true" focus="false" mode="xquery" name="6 Export Plan">import module namespace op = "http://marklogic.com/optic" at "/MarkLogic/optic.xqy";
let $plan := op:from-view("ECommerce", "Order")
=>op:where( op:gt(op:col("orderDate"), xs:date("2016-04-11")))
=>op:order-by( op:col("id"))
=>op:select( ( "id", "shipDate", "paymentTerms"))
let $exported := $plan=>op:export()
let $result := $plan=>op:result()
let $run-exported := $plan=>op:result()
return (
$exported, $result, $run-exported
)
</query><query active="true" focus="false" mode="xquery" name="1 View Joins">xquery version "1.0-ml";
import module namespace op = "http://marklogic.com/optic" at "/MarkLogic/optic.xqy";
let $es := op:prefixer("http://marklogic.com/entity-services#")
let $rdf := op:prefixer("http://www.w3.org/1999/02/22-rdf-syntax-ns#")
let $order := op:from-view("ECommerce2", "Order")
let $order-lines := op:from-view("ECommerce2", "Order_orderLines")
let $customers := op:from-view("ECommerce2", "Customer")
let $product := op:from-view("ECommerce2", "Product")
return
$order
=>op:join-inner($order-lines,
op:on(
$order=>op:col("id"),
$order-lines=>op:col("id")))
=>op:join-inner($customers,
op:on("customer",
$order=>op:col("id")))
=>op:order-by( ($order=>op:col("id"), $customers=>op:col("lastName")) )
=>op:select( ($order=>op:col("id"), $order-lines=>op:col("total"), "orderDate", "firstName", "lastName" ) )
=>op:result()
(: Try taking out join-inners :)</query><query active="true" focus="false" mode="xquery" name="7 Project Docs">xquery version "1.0-ml";
import module namespace op = "http://marklogic.com/optic" at "/MarkLogic/optic.xqy";
import module namespace ofn="http://marklogic.com/optic/expression/fn" at "/MarkLogic/optic/optic-fn.xqy";
let $plan := op:from-view("ECommerce3", "Customer")
=>op:where( op:gt(op:col("id"), 1))
=>op:order-by( op:col("id"))
=>op:select((op:col("firstName"), op:col("email"),
op:as("doc",
op:json-document(
op:json-object((
op:prop("id", op:json-string(op:col("id"))),
op:prop("firstName", op:json-string(op:col("firstName"))),
op:prop("lastName", op:json-string(op:col("lastName"))),
op:prop("fullName", op:json-string(ofn:concat(("firstName", " ", "lastName"))))))))))
let $result := $plan=>op:result()
return $result</query></workspace></export> | {
"content_hash": "9404a7216b816eadbbc6c3f49ecdc3dc",
"timestamp": "",
"source": "github",
"line_count": 169,
"max_line_length": 190,
"avg_line_length": 46.01183431952663,
"alnum_prop": 0.6495627572016461,
"repo_name": "wpaven/gsd-workspaces",
"id": "db0ddc94d027e4d03487e23c2baf9867fdc7bb3d",
"size": "7776",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "xquery/pros/4b-optic-mlw17.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
package com.vaadin.v7.ui.components.calendar.handler;
import java.util.Date;
import com.vaadin.v7.ui.components.calendar.CalendarComponentEvents.EventMoveHandler;
import com.vaadin.v7.ui.components.calendar.CalendarComponentEvents.MoveEvent;
import com.vaadin.v7.ui.components.calendar.event.CalendarEvent;
import com.vaadin.v7.ui.components.calendar.event.EditableCalendarEvent;
/**
* Implements basic functionality needed to enable moving events.
*
* @since 7.1
* @author Vaadin Ltd.
*/
@SuppressWarnings("serial")
@Deprecated
public class BasicEventMoveHandler implements EventMoveHandler {
/*
* (non-Javadoc)
*
* @see
* com.vaadin.addon.calendar.ui.CalendarComponentEvents.EventMoveHandler
* #eventMove
* (com.vaadin.addon.calendar.ui.CalendarComponentEvents.MoveEvent)
*/
@Override
public void eventMove(MoveEvent event) {
CalendarEvent calendarEvent = event.getCalendarEvent();
if (calendarEvent instanceof EditableCalendarEvent) {
EditableCalendarEvent editableEvent = (EditableCalendarEvent) calendarEvent;
Date newFromTime = event.getNewStart();
// Update event dates
long length = editableEvent.getEnd().getTime()
- editableEvent.getStart().getTime();
setDates(editableEvent, newFromTime,
new Date(newFromTime.getTime() + length));
}
}
/**
* Set the start and end dates for the event.
*
* @param event
* The event that the start and end dates should be set
* @param start
* The start date
* @param end
* The end date
*/
protected void setDates(EditableCalendarEvent event, Date start, Date end) {
event.setStart(start);
event.setEnd(end);
}
}
| {
"content_hash": "a4cd12d9fd65c1add3e0c2ad9a9dfc2b",
"timestamp": "",
"source": "github",
"line_count": 61,
"max_line_length": 88,
"avg_line_length": 30.311475409836067,
"alnum_prop": 0.6646836127636561,
"repo_name": "asashour/framework",
"id": "3893450c24031a7a4b80a3632aad2825d2cfb644",
"size": "2444",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "compatibility-server/src/main/java/com/vaadin/v7/ui/components/calendar/handler/BasicEventMoveHandler.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "751129"
},
{
"name": "HTML",
"bytes": "102196"
},
{
"name": "Java",
"bytes": "24286594"
},
{
"name": "JavaScript",
"bytes": "131503"
},
{
"name": "Python",
"bytes": "33975"
},
{
"name": "Shell",
"bytes": "14720"
},
{
"name": "Smarty",
"bytes": "175"
}
],
"symlink_target": ""
} |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.cuongnt.qwap.web.bean;
import com.cuongnt.qwap.ejb.BaseService;
import com.cuongnt.qwap.entity.BaseEntity;
import com.cuongnt.qwap.web.pagging.PaginationHelper;
import com.cuongnt.qwap.web.util.JsfUtil;
import com.cuongnt.qwap.web.util.MessageUtil;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
import javax.faces.model.SelectItem;
import org.slf4j.Logger;
/**
* Abtrast class that implement all basic functionalities managed bean for
* entities.
*
* @author Nguyen Trong Cuong ([email protected])
* @since 16/09/2014
* @version 1.0
* @param <T> Entity Class Type
*/
public abstract class AbstractManagedBean<T extends BaseEntity> implements Serializable {
private static final long serialVersionUID = 8024568564171342875L;
protected T current;
private SelectItem[] selectItems;
private PaginationHelper<T> pagePaginationHelper;
private List<T> all;
public void resetEntity() {
current = null;
}
public void prepareEntity(T entity) {
current = entity;
}
/**
* Call back method persist action
*/
protected void onBeforePersist() {
}
/**
* Call back method persist action
*/
protected void onPersistSuccess() {
current = initEntity();
}
/**
* Persist entity to db
*/
public void persist() {
JsfUtil.processAction(e -> {
onBeforePersist();
getBaseService().persist(e);
onPersistSuccess();
}, current, MessageUtil.REQUEST_SUCCESS_MESSAGE,
MessageUtil.REQUEST_FAIL_MESSAGE);
current = null;
}
/**
* Call back method update action
*/
protected void onBeforeUpdate() {
}
/**
* Call back method update action
*/
protected void onUpdateSuccess() {
}
/**
* Update entity and save to db
*/
public void update() {
JsfUtil.processAction(e -> {
onBeforeUpdate();
getBaseService().update(e);
onUpdateSuccess();
}, current, MessageUtil.REQUEST_SUCCESS_MESSAGE, MessageUtil.REQUEST_FAIL_MESSAGE);
}
/**
* Call back method remove action
*
* @param entity
*/
protected void onBeforeRemove(T entity) {
}
/**
* Call back method remove action
*
* @param entity
*/
protected void onRemoveSuccess(T entity) {
}
/**
* Remove entity from db
*
* @param entity entity instance for removing
*/
public void remove(T entity) {
JsfUtil.processAction(e -> {
onBeforeRemove(e);
getBaseService().remove(e);
onRemoveSuccess(e);
}, entity, MessageUtil.REQUEST_SUCCESS_MESSAGE, MessageUtil.REQUEST_FAIL_MESSAGE);
}
/**
* Initilize a new instance of the entity;
*
* @return new instanse of entity
*/
protected abstract T initEntity();
/**
* Happy search!
* @return
*/
public PaginationHelper<T> getPagePaginationHelper() {
if (pagePaginationHelper == null) {
pagePaginationHelper = new PaginationHelper<T>() {
@Override
public List<T> load(int start, int range) {
return getBaseService().search(start, range, getOrderField(), isOrderAsc(), getMapFilter());
}
@Override
public int count() {
return getBaseService().count(getMapFilter());
}
};
}
return pagePaginationHelper;
}
/**
* Factory method for initilize a new instance of LazyDataModel (Primefaces)
*
* @return new instance of LazyDataModel for the entity.
*/
// protected LazyDataModel<T> initDataModel() {
// return new AbstractLazyDataModel<T>() {
// private static final long serialVersionUID = 1L;
//
// @Override
// protected BaseService<T> getService() {
// return getBaseService();
// }
//
// @Override
// protected void modifyModelFilters(Map<String, Object> filters) {
// super.modifyModelFilters(filters);
// alterModelFilters(filters);
// }
//
// };
// }
/**
* Factoty method for BasicService EJB
*
* @return BasicSerivce instanse
*/
protected abstract BaseService<T> getBaseService();
/* getters and setters */
public T getCurrent() {
if (current == null) {
current = initEntity();
}
return current;
}
public void setCurrent(T current) {
this.current = current;
}
// public LazyDataModel<T> getModel() {
// if (model == null) {
// model = initDataModel();
// }
// return model;
// }
//
// public void setModel(LazyDataModel<T> model) {
// this.model = model;
// }
public SelectItem[] getSelectItems() {
if (selectItems == null) {
selectItems = JsfUtil.getSelectItems(getBaseService().findAll(), false);
}
return selectItems;
}
public void setSelectItems(SelectItem[] selectItems) {
this.selectItems = selectItems;
}
public List<T> getAll() {
return getBaseService().findAll();
}
// pre-set criteria for filtering datatable.
protected void alterModelFilters(Map<String, Object> filters) {
}
protected abstract Logger getLogger();
protected Map<String, Object> getMapFilter() {return null;}
protected String getOrderField() {return null;}
protected boolean isOrderAsc() { return true;}
}
| {
"content_hash": "71ccb0a080f787c4707ac2a0e4e2e610",
"timestamp": "",
"source": "github",
"line_count": 231,
"max_line_length": 112,
"avg_line_length": 25.705627705627705,
"alnum_prop": 0.5904344897271808,
"repo_name": "cuongnt1987/qwap",
"id": "c7e1c615e172d9ab852cbda00b54975f2d8fc582",
"size": "5938",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/cuongnt/qwap/web/bean/AbstractManagedBean.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "27650"
},
{
"name": "HTML",
"bytes": "165830"
},
{
"name": "Java",
"bytes": "214751"
},
{
"name": "JavaScript",
"bytes": "63947"
}
],
"symlink_target": ""
} |
"""
Copyright (c) 2004-Present Pivotal Software, Inc.
This program and the accompanying materials are made available under
the terms of the 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.
"""
import os
import socket
import tinctest
import unittest2 as unittest
from tinctest.lib import local_path
from mpp.gpdb.tests.storage.lib import Database
from mpp.models import MPPTestCase
from tinctest.models.scenario import ScenarioTestCase
from mpp.gpdb.tests.storage.filerep_end_to_end import FilerepTestCase
class FilerepMiscTestCase(ScenarioTestCase, MPPTestCase):
"""
@gucs gp_create_table_random_default_distribution=off
"""
def test_verify_ctlog_xlog_consistency(self):
'''
@description : This test verifies consistency between xlog and changetracking logs.
The consistency can be lost due to non synchronous write patterns of these logs.
This can cause resync phase to fail due to inconsistency seen between actual data and changetracking
logs. Refer to MPP-23631 for more explanation.
The test increases the size of wal buffer to reduce frequency of writes to disk. This helps to push
changetracking log more frequently and thus tries to create inconsistency between them.
If the system works fine, it shouldn't get affected due to this behaviour. That's when the test passes.
@product_version gpdb:(4.3.1.0-4.3], gpdb:(4.2.8.0-4.2]
'''
list_wal_buf = []
list_wal_buf.append(("mpp.gpdb.tests.storage.filerep_end_to_end.FilerepTestCase.run_gpconfig", ['wal_buffers', '512', '512']))
self.test_case_scenario.append(list_wal_buf, serial=True)
list_gen_load = []
list_gen_load.append("mpp.gpdb.tests.storage.filerep.mpp23631.test_misc.ctlog_xlog_cons_setup")
list_gen_load.append("mpp.gpdb.tests.storage.filerep_end_to_end.runcheckpoint.runCheckPointSQL.runCheckPointTestCase")
self.test_case_scenario.append(list_gen_load, serial=True)
list = []
list.append(("mpp.gpdb.tests.storage.filerep_end_to_end.FilerepTestCase.method_run_failover",['primary']))
list.append("mpp.gpdb.tests.storage.filerep_end_to_end.FilerepTestCase.trigger_transition")
self.test_case_scenario.append(list,serial=True)
list_ct = []
list_ct.append("mpp.gpdb.tests.storage.filerep_end_to_end.runcheckpoint.runCheckPointSQL.runCheckPointTestCase")
list_ct.append(("mpp.gpdb.tests.storage.filerep_end_to_end.FilerepTestCase.inject_fault", ['checkpoint', 'async', 'skip', 'primary']))
self.test_case_scenario.append(list_ct,serial=True)
list_ct = []
list_ct.append(("mpp.gpdb.tests.storage.filerep_end_to_end.FilerepTestCase.inject_fault", ['fault_in_background_writer_main', 'async', 'suspend', 'primary']))
self.test_case_scenario.append(list_ct,serial=True)
list_ct = []
list_ct.append(("mpp.gpdb.tests.storage.filerep_end_to_end.FilerepTestCase.inject_fault", ['appendonly_insert', 'async', 'panic', 'primary', 'all', 'ao']))
list_ct.append("mpp.gpdb.tests.storage.filerep.mpp23631.test_misc.ctlog_xlog_cons_ct")
self.test_case_scenario.append(list_ct,serial=True)
list_ct_post_reset = []
list_ct_post_reset.append("mpp.gpdb.tests.storage.filerep.mpp23631.test_misc.ctlog_xlog_cons_post_reset_ct")
list_ct_post_reset.append(("mpp.gpdb.tests.storage.filerep_end_to_end.FilerepTestCase.run_gprecoverseg",['incr']))
list_ct_post_reset.append("mpp.gpdb.tests.storage.filerep_end_to_end.FilerepTestCase.wait_till_insync_transition")
# list_ct_post_reset.append("mpp.gpdb.tests.storage.filerep_end_to_end.FilerepTestCase.check_mirror_seg")
list_ct_post_reset.append(("mpp.gpdb.tests.storage.filerep_end_to_end.FilerepTestCase.do_gpcheckcat",{'outputFile':'test_verify_ctlog_xlog_consistency.out'}))
self.test_case_scenario.append(list_ct_post_reset,serial=True)
list_cleanup = []
list_cleanup.append("mpp.gpdb.tests.storage.filerep.mpp23631.test_misc.ctlog_xlog_cons_cleanup")
list_cleanup.append(("mpp.gpdb.tests.storage.filerep_end_to_end.FilerepTestCase.run_gpconfig", ['wal_buffers', '8', '8']))
self.test_case_scenario.append(list_cleanup, serial=True)
| {
"content_hash": "d2a55d8232d8ce04e6a937c088d1a7d6",
"timestamp": "",
"source": "github",
"line_count": 86,
"max_line_length": 166,
"avg_line_length": 55.348837209302324,
"alnum_prop": 0.7224789915966386,
"repo_name": "cjcjameson/gpdb",
"id": "a1d328604252cb7388470fba2309dd50955e0f81",
"size": "4760",
"binary": false,
"copies": "7",
"ref": "refs/heads/master",
"path": "src/test/tinc/tincrepo/mpp/gpdb/tests/storage/filerep/mpp23631/test_mpp23631.py",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "5665"
},
{
"name": "Batchfile",
"bytes": "11492"
},
{
"name": "C",
"bytes": "35862596"
},
{
"name": "C++",
"bytes": "3303631"
},
{
"name": "CMake",
"bytes": "17118"
},
{
"name": "CSS",
"bytes": "7407"
},
{
"name": "Csound Score",
"bytes": "179"
},
{
"name": "DTrace",
"bytes": "1160"
},
{
"name": "Fortran",
"bytes": "14777"
},
{
"name": "GDB",
"bytes": "576"
},
{
"name": "Gherkin",
"bytes": "736617"
},
{
"name": "HTML",
"bytes": "191406"
},
{
"name": "Java",
"bytes": "268244"
},
{
"name": "JavaScript",
"bytes": "23969"
},
{
"name": "Lex",
"bytes": "196275"
},
{
"name": "M4",
"bytes": "104559"
},
{
"name": "Makefile",
"bytes": "437242"
},
{
"name": "Objective-C",
"bytes": "41796"
},
{
"name": "PLSQL",
"bytes": "261677"
},
{
"name": "PLpgSQL",
"bytes": "5198576"
},
{
"name": "Perl",
"bytes": "3901323"
},
{
"name": "Perl 6",
"bytes": "8302"
},
{
"name": "Python",
"bytes": "8753134"
},
{
"name": "Roff",
"bytes": "51338"
},
{
"name": "Ruby",
"bytes": "26724"
},
{
"name": "SQLPL",
"bytes": "3895383"
},
{
"name": "Shell",
"bytes": "554130"
},
{
"name": "XS",
"bytes": "8405"
},
{
"name": "XSLT",
"bytes": "5779"
},
{
"name": "Yacc",
"bytes": "488779"
}
],
"symlink_target": ""
} |
.oo-ui-icon-arrowNext {
background-image: url('themes/wikimediaui/images/icons/arrowNext-ltr.png');
background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/arrowNext-ltr.svg');
}
.oo-ui-image-invert.oo-ui-icon-arrowNext {
background-image: url('themes/wikimediaui/images/icons/arrowNext-ltr-invert.png');
background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/arrowNext-ltr-invert.svg');
}
.oo-ui-image-progressive.oo-ui-icon-arrowNext {
background-image: url('themes/wikimediaui/images/icons/arrowNext-ltr-progressive.png');
background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/arrowNext-ltr-progressive.svg');
}
.oo-ui-icon-arrowPrevious {
background-image: url('themes/wikimediaui/images/icons/arrowPrevious-ltr.png');
background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/arrowPrevious-ltr.svg');
}
.oo-ui-image-invert.oo-ui-icon-arrowPrevious {
background-image: url('themes/wikimediaui/images/icons/arrowPrevious-ltr-invert.png');
background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/arrowPrevious-ltr-invert.svg');
}
.oo-ui-image-progressive.oo-ui-icon-arrowPrevious {
background-image: url('themes/wikimediaui/images/icons/arrowPrevious-ltr-progressive.png');
background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/arrowPrevious-ltr-progressive.svg');
}
.oo-ui-icon-collapse {
background-image: url('themes/wikimediaui/images/icons/collapse.png');
background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/collapse.svg');
}
.oo-ui-image-invert.oo-ui-icon-collapse {
background-image: url('themes/wikimediaui/images/icons/collapse-invert.png');
background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/collapse-invert.svg');
}
.oo-ui-image-progressive.oo-ui-icon-collapse {
background-image: url('themes/wikimediaui/images/icons/collapse-progressive.png');
background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/collapse-progressive.svg');
}
.oo-ui-icon-downTriangle {
background-image: url('themes/wikimediaui/images/icons/downTriangle.png');
background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/downTriangle.svg');
}
.oo-ui-image-invert.oo-ui-icon-downTriangle {
background-image: url('themes/wikimediaui/images/icons/downTriangle-invert.png');
background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/downTriangle-invert.svg');
}
.oo-ui-image-progressive.oo-ui-icon-downTriangle {
background-image: url('themes/wikimediaui/images/icons/downTriangle-progressive.png');
background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/downTriangle-progressive.svg');
}
.oo-ui-icon-draggable {
background-image: url('themes/wikimediaui/images/icons/draggable.png');
background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/draggable.svg');
}
.oo-ui-image-invert.oo-ui-icon-draggable {
background-image: url('themes/wikimediaui/images/icons/draggable-invert.png');
background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/draggable-invert.svg');
}
.oo-ui-image-progressive.oo-ui-icon-draggable {
background-image: url('themes/wikimediaui/images/icons/draggable-progressive.png');
background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/draggable-progressive.svg');
}
.oo-ui-icon-expand {
background-image: url('themes/wikimediaui/images/icons/expand.png');
background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/expand.svg');
}
.oo-ui-image-invert.oo-ui-icon-expand {
background-image: url('themes/wikimediaui/images/icons/expand-invert.png');
background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/expand-invert.svg');
}
.oo-ui-image-progressive.oo-ui-icon-expand {
background-image: url('themes/wikimediaui/images/icons/expand-progressive.png');
background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/expand-progressive.svg');
}
.oo-ui-icon-move {
background-image: url('themes/wikimediaui/images/icons/move.png');
background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/move.svg');
}
.oo-ui-image-invert.oo-ui-icon-move {
background-image: url('themes/wikimediaui/images/icons/move-invert.png');
background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/move-invert.svg');
}
.oo-ui-image-progressive.oo-ui-icon-move {
background-image: url('themes/wikimediaui/images/icons/move-progressive.png');
background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/move-progressive.svg');
}
.oo-ui-icon-next {
background-image: url('themes/wikimediaui/images/icons/next-ltr.png');
background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/next-ltr.svg');
}
.oo-ui-image-invert.oo-ui-icon-next {
background-image: url('themes/wikimediaui/images/icons/next-ltr-invert.png');
background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/next-ltr-invert.svg');
}
.oo-ui-image-progressive.oo-ui-icon-next {
background-image: url('themes/wikimediaui/images/icons/next-ltr-progressive.png');
background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/next-ltr-progressive.svg');
}
.oo-ui-icon-previous {
background-image: url('themes/wikimediaui/images/icons/previous-ltr.png');
background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/previous-ltr.svg');
}
.oo-ui-image-invert.oo-ui-icon-previous {
background-image: url('themes/wikimediaui/images/icons/previous-ltr-invert.png');
background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/previous-ltr-invert.svg');
}
.oo-ui-image-progressive.oo-ui-icon-previous {
background-image: url('themes/wikimediaui/images/icons/previous-ltr-progressive.png');
background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/previous-ltr-progressive.svg');
}
.oo-ui-icon-last {
background-image: url('themes/wikimediaui/images/icons/moveLast-ltr.png');
background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/moveLast-ltr.svg');
}
.oo-ui-image-invert.oo-ui-icon-last {
background-image: url('themes/wikimediaui/images/icons/moveLast-ltr-invert.png');
background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/moveLast-ltr-invert.svg');
}
.oo-ui-image-progressive.oo-ui-icon-last {
background-image: url('themes/wikimediaui/images/icons/moveLast-ltr-progressive.png');
background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/moveLast-ltr-progressive.svg');
}
.oo-ui-icon-first {
background-image: url('themes/wikimediaui/images/icons/moveFirst-ltr.png');
background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/moveFirst-ltr.svg');
}
.oo-ui-image-invert.oo-ui-icon-first {
background-image: url('themes/wikimediaui/images/icons/moveFirst-ltr-invert.png');
background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/moveFirst-ltr-invert.svg');
}
.oo-ui-image-progressive.oo-ui-icon-first {
background-image: url('themes/wikimediaui/images/icons/moveFirst-ltr-progressive.png');
background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/moveFirst-ltr-progressive.svg');
}
.oo-ui-icon-upTriangle {
background-image: url('themes/wikimediaui/images/icons/upTriangle.png');
background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/upTriangle.svg');
}
.oo-ui-image-invert.oo-ui-icon-upTriangle {
background-image: url('themes/wikimediaui/images/icons/upTriangle-invert.png');
background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/upTriangle-invert.svg');
}
.oo-ui-image-progressive.oo-ui-icon-upTriangle {
background-image: url('themes/wikimediaui/images/icons/upTriangle-progressive.png');
background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/upTriangle-progressive.svg');
}
| {
"content_hash": "e2ae2a9652742efd8ecff144d3b06a7e",
"timestamp": "",
"source": "github",
"line_count": 145,
"max_line_length": 149,
"avg_line_length": 64.1448275862069,
"alnum_prop": 0.7637888399096872,
"repo_name": "cdnjs/cdnjs",
"id": "ef8eb346253b6437dc26db9ebdb1bcf03ca4469e",
"size": "9523",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ajax/libs/oojs-ui/0.38.0/oojs-ui-wikimediaui-icons-movement.css",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
namespace Dealership.Models
{
using System;
using Dealership.Contracts;
using Dealership.Common;
using Dealership.Common.Enums;
using System.Text;
public class Car : Vehicle, ICar
{
public const int MinSeats = 1;
public const int MaxSeats = 10;
private int seats;
private int wheels = (int)VehicleType.Car;
public Car(string make, string model, decimal price, int seats)
: base(make, model, price)
{
this.Seats = seats;
base.Type = VehicleType.Car;
}
public override int Wheels
{
get
{
return this.wheels;
}
}
public int Seats
{
get
{
return this.seats;
}
protected set
{
Validator.ValidateDecimalRange(value
, MinSeats
, MaxSeats
, String.Format("Seats must be between {0} and {1}!"
, MinSeats, MaxSeats));
this.seats = value;
}
}
public override string ToString()
{
var sb = new StringBuilder();
sb.Append(base.ToString());
sb.AppendLine(String.Format(" Wheels: {0}", this.Wheels));
sb.AppendLine(String.Format(" Price: ${0}", this.Price));
sb.AppendLine(String.Format(" Seats: {0}", this.Seats));
return sb.ToString();
}
}
}
| {
"content_hash": "f47e34210a3a96c6ff2c5236e15c2c39",
"timestamp": "",
"source": "github",
"line_count": 62,
"max_line_length": 72,
"avg_line_length": 25.177419354838708,
"alnum_prop": 0.48110185778347214,
"repo_name": "iliyaST/TelerikAcademy",
"id": "acc399f17dc347677f74848f4e730fbc1ca5c1c3",
"size": "1563",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "OOP/7-Exams/11-July-2016-Evening/01.Dealership/Dealership-Skeleton/Dealership/Models/Car.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "303"
},
{
"name": "C#",
"bytes": "2931171"
},
{
"name": "CSS",
"bytes": "169885"
},
{
"name": "CoffeeScript",
"bytes": "1076"
},
{
"name": "HTML",
"bytes": "8977397"
},
{
"name": "JavaScript",
"bytes": "1658788"
},
{
"name": "PLSQL",
"bytes": "4342"
}
],
"symlink_target": ""
} |
package play.sbt
import sbt._
import sbt.Keys._
import play.twirl.sbt.Import.TwirlKeys
import com.typesafe.sbt.web.SbtWeb.autoImport._
import com.typesafe.sbt.packager.universal.UniversalPlugin.autoImport._
/**
* Play layout plugin to switch to the traditional Play web app layout instead of the standard Maven layout.
*
* This is enabled automatically with the PlayWeb plugin (as an AutoPlugin) but not with the PlayService plugin.
*/
object PlayLayoutPlugin extends AutoPlugin {
override def requires = PlayWeb
override def trigger = allRequirements
override def projectSettings = Seq(
target := baseDirectory.value / "target",
sourceDirectory in Compile := baseDirectory.value / "app",
sourceDirectory in Test := baseDirectory.value / "test",
resourceDirectory in Compile := baseDirectory.value / "conf",
scalaSource in Compile := baseDirectory.value / "app",
scalaSource in Test := baseDirectory.value / "test",
javaSource in Compile := baseDirectory.value / "app",
javaSource in Test := baseDirectory.value / "test",
sourceDirectories in (Compile, TwirlKeys.compileTemplates) := Seq((sourceDirectory in Compile).value),
sourceDirectories in (Test, TwirlKeys.compileTemplates) := Seq((sourceDirectory in Test).value),
// sbt-web
sourceDirectory in Assets := (sourceDirectory in Compile).value / "assets",
sourceDirectory in TestAssets := (sourceDirectory in Test).value / "assets",
resourceDirectory in Assets := baseDirectory.value / "public",
// Native packager
sourceDirectory in Universal := baseDirectory.value / "dist"
)
}
| {
"content_hash": "a6926e92a9f8ca3b20a3604a2d46faad",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 112,
"avg_line_length": 41.41025641025641,
"alnum_prop": 0.7380804953560371,
"repo_name": "wegtam/playframework",
"id": "29d3a3420ff0fe12ab8e2fb343cae14f61eb2d88",
"size": "1681",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "dev-mode/sbt-plugin/src/main/scala/play/sbt/PlayLayoutPlugin.scala",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "1174"
},
{
"name": "HTML",
"bytes": "44560"
},
{
"name": "Java",
"bytes": "1456522"
},
{
"name": "JavaScript",
"bytes": "6808"
},
{
"name": "Roff",
"bytes": "1298"
},
{
"name": "Scala",
"bytes": "3371461"
},
{
"name": "Shell",
"bytes": "10269"
},
{
"name": "TSQL",
"bytes": "643"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.yurib.neuroevo</groupId>
<artifactId>neuroevo</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.1</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.1</version>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>8</source>
<target>8</target>
</configuration>
</plugin>
</plugins>
</build>
</project> | {
"content_hash": "8ceb828aaf68229383d0f412ec51b3e6",
"timestamp": "",
"source": "github",
"line_count": 47,
"max_line_length": 108,
"avg_line_length": 28.829787234042552,
"alnum_prop": 0.548339483394834,
"repo_name": "yuribak/neuroevo",
"id": "a0eba4ad2e4388ef8ce95ae61f2ae164752458b8",
"size": "1355",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "pom.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "13442"
}
],
"symlink_target": ""
} |
"""Copyright 2008 Python Software Foundation, Ian Bicking, and Google."""
import cStringIO
import inspect
import mimetools
HTTP_PORT = 80
HTTPS_PORT = 443
_UNKNOWN = 'UNKNOWN'
# status codes
# informational
CONTINUE = 100
SWITCHING_PROTOCOLS = 101
PROCESSING = 102
# successful
OK = 200
CREATED = 201
ACCEPTED = 202
NON_AUTHORITATIVE_INFORMATION = 203
NO_CONTENT = 204
RESET_CONTENT = 205
PARTIAL_CONTENT = 206
MULTI_STATUS = 207
IM_USED = 226
# redirection
MULTIPLE_CHOICES = 300
MOVED_PERMANENTLY = 301
FOUND = 302
SEE_OTHER = 303
NOT_MODIFIED = 304
USE_PROXY = 305
TEMPORARY_REDIRECT = 307
# client error
BAD_REQUEST = 400
UNAUTHORIZED = 401
PAYMENT_REQUIRED = 402
FORBIDDEN = 403
NOT_FOUND = 404
METHOD_NOT_ALLOWED = 405
NOT_ACCEPTABLE = 406
PROXY_AUTHENTICATION_REQUIRED = 407
REQUEST_TIMEOUT = 408
CONFLICT = 409
GONE = 410
LENGTH_REQUIRED = 411
PRECONDITION_FAILED = 412
REQUEST_ENTITY_TOO_LARGE = 413
REQUEST_URI_TOO_LONG = 414
UNSUPPORTED_MEDIA_TYPE = 415
REQUESTED_RANGE_NOT_SATISFIABLE = 416
EXPECTATION_FAILED = 417
UNPROCESSABLE_ENTITY = 422
LOCKED = 423
FAILED_DEPENDENCY = 424
UPGRADE_REQUIRED = 426
# server error
INTERNAL_SERVER_ERROR = 500
NOT_IMPLEMENTED = 501
BAD_GATEWAY = 502
SERVICE_UNAVAILABLE = 503
GATEWAY_TIMEOUT = 504
HTTP_VERSION_NOT_SUPPORTED = 505
INSUFFICIENT_STORAGE = 507
NOT_EXTENDED = 510
# Mapping status codes to official W3C names
responses = {
100: 'Continue',
101: 'Switching Protocols',
200: 'OK',
201: 'Created',
202: 'Accepted',
203: 'Non-Authoritative Information',
204: 'No Content',
205: 'Reset Content',
206: 'Partial Content',
300: 'Multiple Choices',
301: 'Moved Permanently',
302: 'Found',
303: 'See Other',
304: 'Not Modified',
305: 'Use Proxy',
306: '(Unused)',
307: 'Temporary Redirect',
400: 'Bad Request',
401: 'Unauthorized',
402: 'Payment Required',
403: 'Forbidden',
404: 'Not Found',
405: 'Method Not Allowed',
406: 'Not Acceptable',
407: 'Proxy Authentication Required',
408: 'Request Timeout',
409: 'Conflict',
410: 'Gone',
411: 'Length Required',
412: 'Precondition Failed',
413: 'Request Entity Too Large',
414: 'Request-URI Too Long',
415: 'Unsupported Media Type',
416: 'Requested Range Not Satisfiable',
417: 'Expectation Failed',
500: 'Internal Server Error',
501: 'Not Implemented',
502: 'Bad Gateway',
503: 'Service Unavailable',
504: 'Gateway Timeout',
505: 'HTTP Version Not Supported',
}
# maximal amount of data to read at one time in _safe_read
MAXAMOUNT = 1048576
# maximal line length when calling readline().
_MAXLINE = 65536
# Can't get this symbol from socket since importing socket causes an import
# cycle though:
# google.net.proto.ProtocolBuffer imports...
# httplib imports ...
# socket imports ...
# remote_socket_service_pb imports ProtocolBuffer
_GLOBAL_DEFAULT_TIMEOUT = object()
_IMPLEMENTATION = 'gae'
class HTTPMessage(mimetools.Message):
# App Engine Note: This class has been copied almost unchanged from
# Python 2.7.2
def addheader(self, key, value):
"""Add header for field key handling repeats."""
prev = self.dict.get(key)
if prev is None:
self.dict[key] = value
else:
combined = ", ".join((prev, value))
self.dict[key] = combined
def addcontinue(self, key, more):
"""Add more field data from a continuation line."""
prev = self.dict[key]
self.dict[key] = prev + "\n " + more
def readheaders(self):
"""Read header lines.
Read header lines up to the entirely blank line that terminates them.
The (normally blank) line that ends the headers is skipped, but not
included in the returned list. If a non-header line ends the headers,
(which is an error), an attempt is made to backspace over it; it is
never included in the returned list.
The variable self.status is set to the empty string if all went well,
otherwise it is an error message. The variable self.headers is a
completely uninterpreted list of lines contained in the header (so
printing them will reproduce the header exactly as it appears in the
file).
If multiple header fields with the same name occur, they are combined
according to the rules in RFC 2616 sec 4.2:
Appending each subsequent field-value to the first, each separated
by a comma. The order in which header fields with the same field-name
are received is significant to the interpretation of the combined
field value.
"""
# XXX The implementation overrides the readheaders() method of
# rfc822.Message. The base class design isn't amenable to
# customized behavior here so the method here is a copy of the
# base class code with a few small changes.
self.dict = {}
self.unixfrom = ''
self.headers = hlist = []
self.status = ''
headerseen = ""
firstline = 1
startofline = unread = tell = None
if hasattr(self.fp, 'unread'):
unread = self.fp.unread
elif self.seekable:
tell = self.fp.tell
while True:
if tell:
try:
startofline = tell()
except IOError:
startofline = tell = None
self.seekable = 0
line = self.fp.readline(_MAXLINE + 1)
if len(line) > _MAXLINE:
raise LineTooLong("header line")
if not line:
self.status = 'EOF in headers'
break
# Skip unix From name time lines
if firstline and line.startswith('From '):
self.unixfrom = self.unixfrom + line
continue
firstline = 0
if headerseen and line[0] in ' \t':
# XXX Not sure if continuation lines are handled properly
# for http and/or for repeating headers
# It's a continuation line.
hlist.append(line)
self.addcontinue(headerseen, line.strip())
continue
elif self.iscomment(line):
# It's a comment. Ignore it.
continue
elif self.islast(line):
# Note! No pushback here! The delimiter line gets eaten.
break
headerseen = self.isheader(line)
if headerseen:
# It's a legal header line, save it.
hlist.append(line)
self.addheader(headerseen, line[len(headerseen)+1:].strip())
continue
else:
# It's not a header line; throw it back and stop here.
if not self.dict:
self.status = 'No headers'
else:
self.status = 'Non-header line where header expected'
# Try to undo the read.
if unread:
unread(line)
elif tell:
self.fp.seek(startofline)
else:
self.status = self.status + '; bad seek'
break
class HTTPResponse:
# App Engine Note: The public interface is identical to the interface provided
# in Python 2.7 except __init__ takes a
# google.appengine.api.urlfetch.Response instance rather than a socket.
def __init__(self,
fetch_response, # App Engine Note: fetch_response was "sock".
debuglevel=0,
strict=0,
method=None,
buffering=False):
self._fetch_response = fetch_response
self.fp = cStringIO.StringIO(fetch_response.content) # For the HTTP class.
self.debuglevel = debuglevel
self.strict = strict
self._method = method
self.msg = None
# from the Status-Line of the response
self.version = _UNKNOWN # HTTP-Version
self.status = _UNKNOWN # Status-Code
self.reason = _UNKNOWN # Reason-Phrase
self.chunked = _UNKNOWN # is "chunked" being used?
self.chunk_left = _UNKNOWN # bytes left to read in current chunk
self.length = _UNKNOWN # number of bytes left in response
self.will_close = _UNKNOWN # conn will close at end of response
def begin(self):
if self.msg is not None:
# we've already started reading the response
return
self.msg = self._fetch_response.header_msg
self.version = 11 # We can't get the real HTTP version so make one up.
self.status = self._fetch_response.status_code
self.reason = responses.get(self._fetch_response.status_code, 'Unknown')
# The following are implementation details and should not be read by
# clients - but set them to reasonable values just in case.
self.chunked = 0
self.chunk_left = None
self.length = None
self.will_close = 1
def close(self):
if self.fp:
self.fp.close()
self.fp = None
def isclosed(self):
return self.fp is None
def read(self, amt=None):
if self.fp is None:
return ''
if self._method == 'HEAD':
self.close()
return ''
if amt is None:
return self.fp.read()
else:
return self.fp.read(amt)
def fileno(self):
raise NotImplementedError('fileno is not supported')
def getheader(self, name, default=None):
if self.msg is None:
raise ResponseNotReady()
return self.msg.getheader(name, default)
def getheaders(self):
"""Return list of (header, value) tuples."""
if self.msg is None:
raise ResponseNotReady()
return self.msg.items()
class HTTPConnection:
# App Engine Note: The public interface is identical to the interface provided
# in Python 2.7.2 but the implementation uses
# google.appengine.api.urlfetch. Some methods are no-ops and set_tunnel
# raises NotImplementedError.
_protocol = 'http' # passed to urlfetch.
_http_vsn = 11
_http_vsn_str = 'HTTP/1.1'
response_class = HTTPResponse
default_port = HTTP_PORT
auto_open = 1
debuglevel = 0
strict = 0
_allow_truncated = True
_follow_redirects = False
def __init__(self, host, port=None, strict=None,
timeout=_GLOBAL_DEFAULT_TIMEOUT, source_address=None):
# net.proto.ProcotolBuffer relies on httplib so importing urlfetch at the
# module level causes a failure on prod. That means the import needs to be
# lazy.
from google.appengine.api import urlfetch
self._fetch = urlfetch.fetch
self._method_map = {
'GET': urlfetch.GET,
'POST': urlfetch.POST,
'HEAD': urlfetch.HEAD,
'PUT': urlfetch.PUT,
'DELETE': urlfetch.DELETE,
'PATCH': urlfetch.PATCH,
}
self.host = host
self.port = port
# With urllib2 in Python 2.6, an object can be passed here.
# The default is set to socket.GLOBAL_DEFAULT_TIMEOUT which is an object.
# We only accept float, int or long values, otherwise it can be
# silently ignored.
if not isinstance(timeout, (float, int, long)):
timeout = None
self.timeout = timeout
# Both 'strict' and 'source_address' are ignored.
self._method = self._url = None
self._body = ''
self.headers = []
def set_tunnel(self, host, port=None, headers=None):
""" Sets up the host and the port for the HTTP CONNECT Tunnelling.
The headers argument should be a mapping of extra HTTP headers
to send with the CONNECT request.
App Engine Note: This method is not supported.
"""
raise NotImplementedError('HTTP CONNECT Tunnelling is not supported')
def set_debuglevel(self, level):
pass
def connect(self):
"""Connect to the host and port specified in __init__.
App Engine Note: This method is a no-op.
"""
def close(self):
"""Close the connection to the HTTP server.
App Engine Note: This method is a no-op.
"""
def send(self, data):
"""Send `data' to the server."""
self._body += data
def putrequest(self, method, url, skip_host=0, skip_accept_encoding=0):
"""Send a request to the server.
`method' specifies an HTTP request method, e.g. 'GET'.
`url' specifies the object being requested, e.g. '/index.html'.
`skip_host' if True does not add automatically a 'Host:' header
`skip_accept_encoding' if True does not add automatically an
'Accept-Encoding:' header
App Engine Note: `skip_host' and `skip_accept_encoding' are not honored by
the urlfetch service.
"""
self._method = method
self._url = url
def putheader(self, header, *values):
"""Send a request header line to the server.
For example: h.putheader('Accept', 'text/html')
"""
hdr = '\r\n\t'.join([str(v) for v in values])
self.headers.append((header, hdr))
def endheaders(self, message_body=None):
"""Indicate that the last header line has been sent to the server.
This method sends the request to the server. The optional
message_body argument can be used to pass message body
associated with the request. The message body will be sent in
the same packet as the message headers if possible. The
message_body should be a string.
"""
if message_body is not None:
self.send(message_body)
def request(self, method, url, body=None, headers=None):
"""Send a complete request to the server."""
self._method = method
self._url = url
try: # 'body' can be a file.
self._body = body.read()
except AttributeError:
self._body = body
if headers is None:
headers = []
elif hasattr(headers, 'items'):
headers = headers.items()
self.headers = headers
@staticmethod
def _getargspec(callable_object):
assert callable(callable_object)
try:
# Methods and lambdas.
return inspect.getargspec(callable_object)
except TypeError:
# Class instances with __call__.
return inspect.getargspec(callable_object.__call__)
def getresponse(self, buffering=False):
"""Get the response from the server.
App Engine Note: buffering is ignored.
"""
# net.proto.ProcotolBuffer relies on httplib so importing urlfetch at the
# module level causes a failure on prod. That means the import needs to be
# lazy.
from google.appengine.api import urlfetch
import socket # Cannot be done at global scope due to circular import.
if self.port and self.port != self.default_port:
host = '%s:%s' % (self.host, self.port)
else:
host = self.host
if not self._url.startswith(self._protocol):
url = '%s://%s%s' % (self._protocol, host, self._url)
else:
url = self._url
headers = dict(self.headers)
if self.timeout in [_GLOBAL_DEFAULT_TIMEOUT,
socket._GLOBAL_DEFAULT_TIMEOUT]:
deadline = socket.getdefaulttimeout()
else:
deadline = self.timeout
try:
method = self._method_map[self._method.upper()]
except KeyError:
raise ValueError('%r is an unrecognized HTTP method' % self._method)
try:
# The Python Standard Library doesn't validate certificates so don't
# validate them here either. But some libraries (httplib2, possibly
# others) use an alternate technique where the fetch function does not
# have a validate_certificate argument so only provide it when supported.
argspec = self._getargspec(self._fetch)
extra_kwargs = (
{'validate_certificate': False}
if argspec.keywords or 'validate_certificate' in argspec.args
else {})
fetch_response = self._fetch(url,
self._body,
method, headers,
self._allow_truncated,
self._follow_redirects,
deadline,
**extra_kwargs)
except urlfetch.InvalidURLError, e:
raise InvalidURL(str(e))
except (urlfetch.ResponseTooLargeError, urlfetch.DeadlineExceededError), e:
raise HTTPException(str(e))
except urlfetch.SSLCertificateError, e:
# Should be ssl.SSLError but the ssl module isn't available.
# Continue to support this exception for versions of _fetch that do not
# support validate_certificates. Also, in production App Engine defers
# specific semantics so leaving this in just in case.
raise HTTPException(str(e))
except urlfetch.DownloadError, e:
# One of the following occured: UNSPECIFIED_ERROR, FETCH_ERROR
raise socket.error(
'An error occured while connecting to the server: %s' % e)
response = self.response_class(fetch_response, method=method)
response.begin()
self.close()
return response
class HTTPSConnection(HTTPConnection):
"This class allows communication via SSL."
# App Engine Note: The public interface is identical to the interface provided
# in Python 2.7.2 but the implementation does not support key and
# certificate files.
_protocol = 'https' # passed to urlfetch.
default_port = HTTPS_PORT
def __init__(self, host, port=None, key_file=None, cert_file=None,
strict=False, timeout=_GLOBAL_DEFAULT_TIMEOUT,
source_address=None):
if key_file is not None or cert_file is not None:
raise NotImplementedError(
'key_file and cert_file arguments are not implemented')
HTTPConnection.__init__(self, host, port, strict, timeout, source_address)
class HTTP:
"Compatibility class with httplib.py from 1.5."
# App Engine Note: The public interface is identical to the interface provided
# in Python 2.7.
_http_vsn = 10
_http_vsn_str = 'HTTP/1.0'
debuglevel = 0
_connection_class = HTTPConnection
def __init__(self, host='', port=None, strict=None):
"Provide a default host, since the superclass requires one."
# some joker passed 0 explicitly, meaning default port
if port == 0:
port = None
# Note that we may pass an empty string as the host; this will throw
# an error when we attempt to connect. Presumably, the client code
# will call connect before then, with a proper host.
self._setup(self._connection_class(host, port, strict))
def _setup(self, conn):
self._conn = conn
# set up delegation to flesh out interface
self.send = conn.send
self.putrequest = conn.putrequest
self.endheaders = conn.endheaders
self.set_debuglevel = conn.set_debuglevel
conn._http_vsn = self._http_vsn
conn._http_vsn_str = self._http_vsn_str
self.file = None
def connect(self, host=None, port=None):
"Accept arguments to set the host/port, since the superclass doesn't."
self.__init__(host, port)
def getfile(self):
"Provide a getfile, since the superclass' does not use this concept."
return self.file
def putheader(self, header, *values):
"The superclass allows only one value argument."
self._conn.putheader(header, '\r\n\t'.join([str(v) for v in values]))
def getreply(self, buffering=False):
"""Compat definition since superclass does not define it.
Returns a tuple consisting of:
- server status code (e.g. '200' if all goes well)
- server "reason" corresponding to status code
- any RFC822 headers in the response from the server
"""
response = self._conn.getresponse()
self.headers = response.msg
self.file = response.fp
return response.status, response.reason, response.msg
def close(self):
self._conn.close()
# note that self.file == response.fp, which gets closed by the
# superclass. just clear the object ref here.
### hmm. messy. if status==-1, then self.file is owned by us.
### well... we aren't explicitly closing, but losing this ref will
### do it
self.file = None
# Copy from Python's httplib implementation.
class HTTPS(HTTP):
"""Compatibility with 1.5 httplib interface
Python 1.5.2 did not have an HTTPS class, but it defined an
interface for sending http requests that is also useful for
https.
"""
# App Engine Note: The public interface is identical to the interface provided
# in Python 2.7 except that key and certificate files are not supported.
_connection_class = HTTPSConnection
def __init__(self, host='', port=None, key_file=None, cert_file=None,
strict=None):
if key_file is not None or cert_file is not None:
raise NotImplementedError(
'key_file and cert_file arguments are not implemented')
# provide a default host, pass the X509 cert info
# urf. compensate for bad input.
if port == 0:
port = None
self._setup(self._connection_class(host, port, key_file,
cert_file, strict))
# we never actually use these for anything, but we keep them
# here for compatibility with post-1.5.2 CVS.
self.key_file = key_file
self.cert_file = cert_file
class HTTPException(Exception):
# App Engine Note: This class has been copied unchanged from Python 2.7.2
# Subclasses that define an __init__ must call Exception.__init__
# or define self.args. Otherwise, str() will fail.
pass
class NotConnected(HTTPException):
# App Engine Note: This class has been copied unchanged from Python 2.7.2
pass
class InvalidURL(HTTPException):
# App Engine Note: This class has been copied unchanged from Python 2.7.2
pass
class UnknownProtocol(HTTPException):
# App Engine Note: This class has been copied unchanged from Python 2.7.2
def __init__(self, version):
self.args = version,
self.version = version
class UnknownTransferEncoding(HTTPException):
# App Engine Note: This class has been copied unchanged from Python 2.7.2
pass
class UnimplementedFileMode(HTTPException):
# App Engine Note: This class has been copied unchanged from Python 2.7.2
pass
class IncompleteRead(HTTPException):
# App Engine Note: This class has been copied unchanged from Python 2.7.2
def __init__(self, partial, expected=None):
self.args = partial,
self.partial = partial
self.expected = expected
def __repr__(self):
if self.expected is not None:
e = ', %i more expected' % self.expected
else:
e = ''
return 'IncompleteRead(%i bytes read%s)' % (len(self.partial), e)
def __str__(self):
return repr(self)
class ImproperConnectionState(HTTPException):
# App Engine Note: This class has been copied unchanged from Python 2.7.2
pass
class CannotSendRequest(ImproperConnectionState):
# App Engine Note: This class has been copied unchanged from Python 2.7.2
pass
class CannotSendHeader(ImproperConnectionState):
# App Engine Note: This class has been copied unchanged from Python 2.7.2
pass
class ResponseNotReady(ImproperConnectionState):
# App Engine Note: This class has been copied unchanged from Python 2.7.2
pass
class BadStatusLine(HTTPException):
# App Engine Note: This class has been copied unchanged from Python 2.7.2
def __init__(self, line):
if not line:
line = repr(line)
self.args = line,
self.line = line
class LineTooLong(HTTPException):
# App Engine Note: This class has been copied unchanged from Python 2.7.2
def __init__(self, line_type):
HTTPException.__init__(self, "got more than %d bytes when reading %s"
% (_MAXLINE, line_type))
# for backwards compatibility
error = HTTPException
class LineAndFileWrapper:
"""A limited file-like object for HTTP/0.9 responses."""
# App Engine Note: This class has been copied unchanged from Python 2.7.2
# The status-line parsing code calls readline(), which normally
# get the HTTP status line. For a 0.9 response, however, this is
# actually the first line of the body! Clients need to get a
# readable file object that contains that line.
def __init__(self, line, file):
self._line = line
self._file = file
self._line_consumed = 0
self._line_offset = 0
self._line_left = len(line)
def __getattr__(self, attr):
return getattr(self._file, attr)
def _done(self):
# called when the last byte is read from the line. After the
# call, all read methods are delegated to the underlying file
# object.
self._line_consumed = 1
self.read = self._file.read
self.readline = self._file.readline
self.readlines = self._file.readlines
def read(self, amt=None):
if self._line_consumed:
return self._file.read(amt)
assert self._line_left
if amt is None or amt > self._line_left:
s = self._line[self._line_offset:]
self._done()
if amt is None:
return s + self._file.read()
else:
return s + self._file.read(amt - len(s))
else:
assert amt <= self._line_left
i = self._line_offset
j = i + amt
s = self._line[i:j]
self._line_offset = j
self._line_left -= amt
if self._line_left == 0:
self._done()
return s
def readline(self):
if self._line_consumed:
return self._file.readline()
assert self._line_left
s = self._line[self._line_offset:]
self._done()
return s
def readlines(self, size=None):
if self._line_consumed:
return self._file.readlines(size)
assert self._line_left
L = [self._line[self._line_offset:]]
self._done()
if size is None:
return L + self._file.readlines()
else:
return L + self._file.readlines(size)
| {
"content_hash": "ccc7299329fce4cfb211f306df0b0ddc",
"timestamp": "",
"source": "github",
"line_count": 815,
"max_line_length": 80,
"avg_line_length": 30.80490797546012,
"alnum_prop": 0.6577710507448419,
"repo_name": "Kazade/NeHe-Website",
"id": "1edee85707013d9b822f42e1e575875869aa8b57",
"size": "25302",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "google_appengine/google/appengine/dist27/gae_override/httplib.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "407860"
},
{
"name": "C++",
"bytes": "20"
},
{
"name": "CSS",
"bytes": "504898"
},
{
"name": "Emacs Lisp",
"bytes": "4733"
},
{
"name": "JavaScript",
"bytes": "1013425"
},
{
"name": "PHP",
"bytes": "2269231"
},
{
"name": "Python",
"bytes": "62625909"
},
{
"name": "Shell",
"bytes": "40752"
},
{
"name": "TeX",
"bytes": "3149"
},
{
"name": "VimL",
"bytes": "5645"
}
],
"symlink_target": ""
} |
define([
'backbone',
'underscore',
'jquery',
'i18n!find/nls/bundle',
'text!find/templates/app/util/content-container.html'
], function (Backbone, _, $, i18n, contentContainerTemplate) {
return Backbone.View.extend({
contentContainerTemplate: _.template(contentContainerTemplate, {variable: 'data'}),
initialize: function(options) {
this.views = options.views;
this.model = options.model;
this.listenTo(this.model, 'change:selectedTab', this.selectTab);
},
render: function() {
this.$tabContent = $('<div class="tab-content"></div>');
var selectedTab = this.model.get('selectedTab');
_.each(this.views, function(viewData) {
var $viewElement = $(this.contentContainerTemplate(viewData))
.toggleClass('active', viewData.id === selectedTab)
.appendTo(this.$tabContent);
viewData.content = new viewData.Constructor(viewData.constructorArguments);
_.each(viewData.events, function(listener, eventName) {
this.listenTo(viewData.content, eventName, listener);
}, this);
viewData.content.setElement($viewElement);
}, this);
this.$el.empty().append(this.$tabContent);
this.selectTab();
},
selectTab: function() {
var tabId = this.model.get('selectedTab');
var viewData = _.findWhere(this.views, {id: tabId});
// Deactivate all tabs and activate the selected tab
this.$tabContent.find('.tab-pane').removeClass('active');
this.$tabContent.find('#' + viewData.uniqueId).addClass('active');
if (viewData) {
if (!viewData.rendered) {
viewData.content.render();
viewData.rendered = true;
}
if (viewData.content.update) {
viewData.content.update();
}
}
},
remove: function() {
_.chain(this.views)
.pluck('content')
.invoke('remove');
Backbone.View.prototype.remove.call(this);
}
});
});
| {
"content_hash": "57daf9ec73793d869e02376911c21097",
"timestamp": "",
"source": "github",
"line_count": 71,
"max_line_length": 91,
"avg_line_length": 32.38028169014085,
"alnum_prop": 0.5332753371030883,
"repo_name": "ExperisIT-rav/FindExperisIT",
"id": "ed2320cae67d3aae012e810e97fc1c3f71bbff4a",
"size": "2299",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "core/src/main/public/static/js/find/app/util/results-view-container.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "250209"
},
{
"name": "CoffeeScript",
"bytes": "5997"
},
{
"name": "HTML",
"bytes": "53144"
},
{
"name": "Java",
"bytes": "565369"
},
{
"name": "JavaScript",
"bytes": "815020"
},
{
"name": "Ruby",
"bytes": "206"
},
{
"name": "Shell",
"bytes": "4427"
}
],
"symlink_target": ""
} |
package org.gwtproject.gwt.worker.client;
import static org.gwtproject.gwt.worker.client.EventListeners.register;
import org.gwtproject.gwt.worker.shared.MessageHandler;
import org.gwtproject.gwt.worker.shared.MessagePortRef;
import org.gwtproject.gwt.worker.shared.Transferable;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.core.client.JsArrayUtils;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.EventListener;
import com.google.web.bindery.event.shared.HandlerRegistration;
public class MessagePortRefJsoImpl extends JavaScriptObject implements MessagePortRef {
protected MessagePortRefJsoImpl() {
}
@Override
public final native void postMessage(int message)/*-{
this.postMessage(message);
}-*/;
@Override
public final native void postMessage(String message)/*-{
this.postMessage(message);
}-*/;
@Override
public final native void postMessage(JavaScriptObject message)/*-{
this.postMessage(message);
}-*/;
@Override
public final void postMessage(int message, Transferable... t) {
JsArray<TransferableJsoImpl> ts = JsArrayUtils.readOnlyJsArray((TransferableJsoImpl[])t);
postMessage(message, ts);
}
private final native void postMessage(int message, JsArray<TransferableJsoImpl> ts)/*-{
this.postMessage(message, ts);
}-*/;
@Override
public final void postMessage(String message, Transferable... t) {
JsArray<TransferableJsoImpl> ts = JsArrayUtils.readOnlyJsArray((TransferableJsoImpl[])t);
postMessage(message, ts);
}
private final native void postMessage(String message, JsArray<TransferableJsoImpl> ts)/*-{
this.postMessage(message, ts);
}-*/;
@Override
public final void postMessage(JavaScriptObject message, Transferable... t) {
JsArray<TransferableJsoImpl> ts = JsArrayUtils.readOnlyJsArray((TransferableJsoImpl[])t);
postMessage(message, ts);
}
private final native void postMessage(JavaScriptObject message, JsArray<TransferableJsoImpl> ts)/*-{
this.postMessage(message, ts);
}-*/;
@Override
public final HandlerRegistration addMessageHandler(final MessageHandler handler) {
return register(this, "message", new EventListener() {
@Override
public void onBrowserEvent(Event event) {
handler.onMessage((MessageEventJsoImpl) event.cast());
}
});
}
}
| {
"content_hash": "a1d26171e09704a10e347eb217249d4e",
"timestamp": "",
"source": "github",
"line_count": 75,
"max_line_length": 101,
"avg_line_length": 31.346666666666668,
"alnum_prop": 0.7694598043385793,
"repo_name": "metteo/gwt-worker",
"id": "e29fbcadbe4ab6535c644a9390ab4b5518daffc9",
"size": "2351",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/org/gwtproject/gwt/worker/client/MessagePortRefJsoImpl.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "2706"
},
{
"name": "Java",
"bytes": "54706"
},
{
"name": "JavaScript",
"bytes": "18015"
}
],
"symlink_target": ""
} |
package com.linkedin.metadata.builders.search;
import com.linkedin.common.DatasetUrnArray;
import com.linkedin.common.FabricType;
import com.linkedin.common.urn.DataPlatformUrn;
import com.linkedin.common.urn.DataProcessUrn;
import com.linkedin.common.urn.DatasetUrn;
import com.linkedin.dataprocess.DataProcessInfo;
import com.linkedin.metadata.aspect.DataProcessAspect;
import com.linkedin.metadata.aspect.DataProcessAspectArray;
import com.linkedin.metadata.search.DataProcessDocument;
import com.linkedin.metadata.snapshot.DataProcessSnapshot;
import java.util.List;
import org.testng.annotations.Test;
import static org.testng.Assert.*;
public class DataProcessIndexBuilderTest {
@Test
public void testGetDocumentsToUpdateFromDataProcessSnapshot() {
DataProcessUrn dataProcessUrn = new DataProcessUrn("Azure Data Factory", "ADFJob1", FabricType.PROD);
DataProcessInfo dataProcessInfo = new DataProcessInfo();
DatasetUrn inputDatasetUrn = new DatasetUrn(new DataPlatformUrn("HIVE"), "SampleInputDataset", FabricType.DEV);
DatasetUrnArray inputs = new DatasetUrnArray();
inputs.add(inputDatasetUrn);
dataProcessInfo.setInputs(inputs);
DatasetUrn outputDatasetUrn = new DatasetUrn(new DataPlatformUrn("HIVE"), "SampleOutputDataset", FabricType.DEV);
DatasetUrnArray outputs = new DatasetUrnArray();
outputs.add(outputDatasetUrn);
dataProcessInfo.setOutputs(outputs);
DataProcessAspect dataProcessAspect = new DataProcessAspect();
dataProcessAspect.setDataProcessInfo(dataProcessInfo);
DataProcessAspectArray dataProcessAspectArray = new DataProcessAspectArray();
dataProcessAspectArray.add(dataProcessAspect);
DataProcessSnapshot dataProcessSnapshot =
new DataProcessSnapshot().setUrn(dataProcessUrn).setAspects(dataProcessAspectArray);
List<DataProcessDocument> actualDocs = new DataProcessIndexBuilder().getDocumentsToUpdate(dataProcessSnapshot);
assertEquals(actualDocs.size(), 2);
assertEquals(actualDocs.get(0).getInputs().get(0), inputDatasetUrn);
assertEquals(actualDocs.get(0).getOutputs().get(0), outputDatasetUrn);
assertEquals(actualDocs.get(0).getUrn(), dataProcessUrn);
assertEquals(actualDocs.get(1).getUrn(), dataProcessUrn);
}
}
| {
"content_hash": "41f7a8d9fcacfcf7e2341bcdc54e097a",
"timestamp": "",
"source": "github",
"line_count": 48,
"max_line_length": 117,
"avg_line_length": 46.916666666666664,
"alnum_prop": 0.8023978685612788,
"repo_name": "mars-lan/WhereHows",
"id": "f8ca80b9c778bb4434cb835cc15022af950049e1",
"size": "2252",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "metadata-builders/src/test/java/com/linkedin/metadata/builders/search/DataProcessIndexBuilderTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "104402"
},
{
"name": "Dockerfile",
"bytes": "2521"
},
{
"name": "HTML",
"bytes": "125023"
},
{
"name": "Java",
"bytes": "1431842"
},
{
"name": "JavaScript",
"bytes": "173397"
},
{
"name": "Python",
"bytes": "1419332"
},
{
"name": "Shell",
"bytes": "2470"
},
{
"name": "TypeScript",
"bytes": "559600"
}
],
"symlink_target": ""
} |
define(['react', './mixins', './table-heading', './table-body', './pager', './edit-controls'],
function (React, mixins, TableHeading, TableBody, Pager, EditControls) {
var TableTab = React.createClass({
displayName: 'TableTab',
getInitialState: function () {
return {
offset: 0,
size: 25,
total: 0,
selected: {},
query: {select: []}
};
},
mixins: [mixins.SetStateProperty, mixins.ComputableState],
computeState: function (props) {
var that = this
, type = props.list.type
, query = {from: type, where: [{path: type, op: 'IN', value: props.list.name}]};
props.service.fetchSummaryFields().then(function (sfs) {
query.select = ['id'].concat(sfs[type]);
that.setStateProperty('query', query);
});
},
render: function () {
return React.DOM.div(
null,
EditControls({
selected: this.state.selected
}),
Pager({
offset: this.state.offset,
size: this.state.size,
length: this.state.total,
selected: this.state.selected,
onAllSelected: this._onAllSelected,
back: this._goBack,
next: this._goNext
}),
React.DOM.table(
{className: 'table table-striped'},
TableHeading({
service: this.props.service,
view: this.state.query.select,
allSelected: this.state.selected.all,
onChangeAll: this._onAllSelected
}),
TableBody({
offset: this.state.offset,
size: this.state.size,
service: this.props.service,
filterTerm: this.props.filterTerm,
query: this.state.query,
selected: this.state.selected,
onItemSelected: this._selectItem,
onCount: this.setStateProperty.bind(this, 'total')
})));
},
_selectItem: function (id, isSelected) {
var state = this.state;
state.selected[id] = isSelected;
this.setState(state);
},
_onAllSelected: function (isSelected) {
this._selectItem('all', isSelected);
},
_goBack: function () {
this.setStateProperty('offset', Math.max(0, this.state.offset - this.state.size));
},
_goNext: function () {
var next = this.state.offset + this.state.size;
if (next < this.state.total) {
this.setStateProperty('offset', next);
}
}
});
return TableTab;
});
| {
"content_hash": "3593a587405f4e0bc8d872fe078c13a0",
"timestamp": "",
"source": "github",
"line_count": 92,
"max_line_length": 94,
"avg_line_length": 28.315217391304348,
"alnum_prop": 0.5366602687140115,
"repo_name": "intermine-tools/show-list-tool",
"id": "d28b324abbbcd741bf538062e92c4e77c2e2b0b7",
"size": "2605",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "js/table-tab.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "4141"
},
{
"name": "HTML",
"bytes": "4773"
},
{
"name": "JavaScript",
"bytes": "128240"
},
{
"name": "Shell",
"bytes": "266"
}
],
"symlink_target": ""
} |
package com.facebook.buck.haskell;
import static org.junit.Assert.assertThat;
import com.facebook.buck.cxx.CxxPlatformUtils;
import com.facebook.buck.cxx.CxxSourceRuleFactory;
import com.facebook.buck.cxx.Linker;
import com.facebook.buck.cxx.NativeLinkableInput;
import com.facebook.buck.model.BuildTarget;
import com.facebook.buck.model.BuildTargetFactory;
import com.facebook.buck.rules.BuildRuleResolver;
import com.facebook.buck.rules.DefaultTargetNodeToBuildRuleTransformer;
import com.facebook.buck.rules.FakeSourcePath;
import com.facebook.buck.rules.SourcePath;
import com.facebook.buck.rules.TargetGraph;
import com.facebook.buck.rules.args.Arg;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import org.hamcrest.Matchers;
import org.junit.Test;
public class PrebuiltHaskellLibraryDescriptionTest {
@Test
public void staticLibraries() throws Exception {
BuildRuleResolver resolver =
new BuildRuleResolver(TargetGraph.EMPTY, new DefaultTargetNodeToBuildRuleTransformer());
SourcePath lib = new FakeSourcePath("libfoo.a");
BuildTarget target = BuildTargetFactory.newInstance("//:rule");
PrebuiltHaskellLibrary library =
(PrebuiltHaskellLibrary) new PrebuiltHaskellLibraryBuilder(target)
.setStaticLibs(ImmutableList.of(lib))
.build(resolver);
NativeLinkableInput input =
library.getNativeLinkableInput(
CxxPlatformUtils.DEFAULT_PLATFORM,
Linker.LinkableDepType.STATIC);
assertThat(
FluentIterable.from(input.getArgs())
.transformAndConcat(Arg.getInputsFunction())
.toSet(),
Matchers.contains(lib));
}
@Test
public void sharedLibraries() throws Exception {
BuildRuleResolver resolver =
new BuildRuleResolver(TargetGraph.EMPTY, new DefaultTargetNodeToBuildRuleTransformer());
SourcePath lib = new FakeSourcePath("libfoo.so");
BuildTarget target = BuildTargetFactory.newInstance("//:rule");
PrebuiltHaskellLibrary library =
(PrebuiltHaskellLibrary) new PrebuiltHaskellLibraryBuilder(target)
.setSharedLibs(ImmutableMap.of("libfoo.so", lib))
.build(resolver);
NativeLinkableInput input =
library.getNativeLinkableInput(
CxxPlatformUtils.DEFAULT_PLATFORM,
Linker.LinkableDepType.SHARED);
assertThat(
FluentIterable.from(input.getArgs())
.transformAndConcat(Arg.getInputsFunction())
.toSet(),
Matchers.contains(lib));
}
@Test
public void staticInterfaces() throws Exception {
BuildRuleResolver resolver =
new BuildRuleResolver(TargetGraph.EMPTY, new DefaultTargetNodeToBuildRuleTransformer());
SourcePath interfaces = new FakeSourcePath("interfaces");
BuildTarget target = BuildTargetFactory.newInstance("//:rule");
PrebuiltHaskellLibrary library =
(PrebuiltHaskellLibrary) new PrebuiltHaskellLibraryBuilder(target)
.setStaticInterfaces(interfaces)
.build(resolver);
HaskellCompileInput input =
library.getCompileInput(
CxxPlatformUtils.DEFAULT_PLATFORM,
CxxSourceRuleFactory.PicType.PDC);
assertThat(
input.getIncludes(),
Matchers.contains(interfaces));
}
@Test
public void sharedInterfaces() throws Exception {
BuildRuleResolver resolver =
new BuildRuleResolver(TargetGraph.EMPTY, new DefaultTargetNodeToBuildRuleTransformer());
SourcePath interfaces = new FakeSourcePath("interfaces");
BuildTarget target = BuildTargetFactory.newInstance("//:rule");
PrebuiltHaskellLibrary library =
(PrebuiltHaskellLibrary) new PrebuiltHaskellLibraryBuilder(target)
.setSharedInterfaces(interfaces)
.build(resolver);
HaskellCompileInput input =
library.getCompileInput(
CxxPlatformUtils.DEFAULT_PLATFORM,
CxxSourceRuleFactory.PicType.PIC);
assertThat(
input.getIncludes(),
Matchers.contains(interfaces));
}
@Test
public void exportedLinkerFlags() throws Exception {
BuildRuleResolver resolver =
new BuildRuleResolver(TargetGraph.EMPTY, new DefaultTargetNodeToBuildRuleTransformer());
BuildTarget target = BuildTargetFactory.newInstance("//:rule");
String flag = "-exported-linker-flags";
PrebuiltHaskellLibrary library =
(PrebuiltHaskellLibrary) new PrebuiltHaskellLibraryBuilder(target)
.setExportedLinkerFlags(ImmutableList.of(flag))
.build(resolver);
NativeLinkableInput staticInput =
library.getNativeLinkableInput(
CxxPlatformUtils.DEFAULT_PLATFORM,
Linker.LinkableDepType.STATIC);
assertThat(
Arg.stringify(staticInput.getArgs()),
Matchers.contains(flag));
NativeLinkableInput sharedInput =
library.getNativeLinkableInput(
CxxPlatformUtils.DEFAULT_PLATFORM,
Linker.LinkableDepType.SHARED);
assertThat(
Arg.stringify(sharedInput.getArgs()),
Matchers.contains(flag));
}
@Test
public void exportedCompilerFlags() throws Exception {
BuildRuleResolver resolver =
new BuildRuleResolver(TargetGraph.EMPTY, new DefaultTargetNodeToBuildRuleTransformer());
String flag = "-exported-compiler-flags";
BuildTarget target = BuildTargetFactory.newInstance("//:rule");
PrebuiltHaskellLibrary library =
(PrebuiltHaskellLibrary) new PrebuiltHaskellLibraryBuilder(target)
.setExportedCompilerFlags(ImmutableList.of(flag))
.build(resolver);
HaskellCompileInput staticInput =
library.getCompileInput(
CxxPlatformUtils.DEFAULT_PLATFORM,
CxxSourceRuleFactory.PicType.PDC);
assertThat(
staticInput.getFlags(),
Matchers.contains(flag));
HaskellCompileInput sharedInput =
library.getCompileInput(
CxxPlatformUtils.DEFAULT_PLATFORM,
CxxSourceRuleFactory.PicType.PIC);
assertThat(
sharedInput.getFlags(),
Matchers.contains(flag));
}
}
| {
"content_hash": "f36439e5d27de6979ea21a69c8224877",
"timestamp": "",
"source": "github",
"line_count": 160,
"max_line_length": 96,
"avg_line_length": 38.61875,
"alnum_prop": 0.7184010357663052,
"repo_name": "Dominator008/buck",
"id": "7ecc8bd0c9f8ffedaed461ec2e968d4c9d3ea630",
"size": "6784",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/com/facebook/buck/haskell/PrebuiltHaskellLibraryDescriptionTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "579"
},
{
"name": "Batchfile",
"bytes": "726"
},
{
"name": "C",
"bytes": "248433"
},
{
"name": "C#",
"bytes": "237"
},
{
"name": "C++",
"bytes": "6074"
},
{
"name": "CSS",
"bytes": "54863"
},
{
"name": "D",
"bytes": "1017"
},
{
"name": "Go",
"bytes": "14733"
},
{
"name": "Groff",
"bytes": "440"
},
{
"name": "Groovy",
"bytes": "3362"
},
{
"name": "HTML",
"bytes": "5353"
},
{
"name": "Haskell",
"bytes": "590"
},
{
"name": "IDL",
"bytes": "128"
},
{
"name": "Java",
"bytes": "14177476"
},
{
"name": "JavaScript",
"bytes": "931960"
},
{
"name": "Lex",
"bytes": "2442"
},
{
"name": "Makefile",
"bytes": "1791"
},
{
"name": "Matlab",
"bytes": "47"
},
{
"name": "OCaml",
"bytes": "3060"
},
{
"name": "Objective-C",
"bytes": "124101"
},
{
"name": "Objective-C++",
"bytes": "34"
},
{
"name": "PowerShell",
"bytes": "244"
},
{
"name": "Python",
"bytes": "379114"
},
{
"name": "Rust",
"bytes": "938"
},
{
"name": "Scala",
"bytes": "898"
},
{
"name": "Shell",
"bytes": "35303"
},
{
"name": "Smalltalk",
"bytes": "897"
},
{
"name": "Standard ML",
"bytes": "15"
},
{
"name": "Swift",
"bytes": "3735"
},
{
"name": "Thrift",
"bytes": "2452"
},
{
"name": "Yacc",
"bytes": "323"
}
],
"symlink_target": ""
} |
using std::string;
using std::ifstream;
using std::istringstream;
using boost::algorithm::starts_with;
// The fields of the "cpu" line in /proc/stat
static constexpr int N_CPU_FIELDS = 10;
static const std::array<std::string, N_CPU_FIELDS> procStatCpuFields = { "CPU User", "CPU Nice", "CPU System", "CPU Idle",
"CPU Iowait", "CPU Irq", "CPU Softirq", "CPU Steal", "CPU Guest", "CPU Guest_nice" };
static const std::unordered_set<std::string> procStatCpuFieldsUsed =
{ "CPU User", "CPU Nice", "CPU System", "CPU Irq", "CPU Softirq", "CPU Steal", "CPU Guest", "CPU Guest_nice" };
PCProfiler :: PCProfiler(EventProcessor& profiler){
evGen = new PCProfilerImp(profiler);
}
PCProfilerImp::PCProfilerImp(EventProcessor& profiler) :
targetTime()
{
myProfiler.copy( profiler );
// Get the USER_HZ value that many values in /proc/stat are measured by.
// It is normally 100, so the values are normally measured in 1/100ths of a second.
const long user_hz = sysconf(_SC_CLK_TCK);
if( user_hz < 1000 ) {
const int64_t ratio = 1000 / user_hz;
cpuStatToMillis = [ratio] (int64_t val) { return val * ratio; };
}
else if (user_hz == 1000) {
// just the identity function
cpuStatToMillis = [] (int64_t val) { return val; };
}
else {
const int64_t ratio = user_hz / 1000;
cpuStatToMillis = [ratio] (int64_t val) { return val / ratio; };
}
}
void PCProfilerImp :: GetStatInfo( Json::Value & diff ) {
ifstream proc("/proc/stat");
Json::Value nStats;
string line;
// TODO: Change to "while" if we do multiple lines
if ( getline(proc, line) ) {
istringstream ss(line);
string rawType; // the type of line
ss >> rawType;
// Prefix with an asterisk so that it is easy to tell that this is
// non-waypoint information
string type = "_" + rawType;
if( rawType == "cpu" ) {
// CPU line
for( auto field : procStatCpuFields ) {
int64_t val;
ss >> val;
if( procStatCpuFieldsUsed.find(field) != procStatCpuFieldsUsed.end() ) {
val = cpuStatToMillis(val);
nStats[field][type] = (Json::Int64) val;
diff[field][type] = (Json::Int64) val - statInfo[field][type].asInt64();
}
}
}
// Add other types in the future if we want them
}
nStats.swap(statInfo);
}
void PCProfilerImp :: PreStart(void) {
clock_gettime(CLOCK_MONOTONIC, &targetTime);
Json::Value dummy;
GetStatInfo(dummy);
}
int PCProfilerImp::ProduceMessage(){
targetTime.tv_sec += 1;
while( clock_nanosleep( CLOCK_MONOTONIC, TIMER_ABSTIME, &targetTime, NULL ) != 0 ) {
// nothing
}
timespec wallTime;
timespec cpuTime;
clock_gettime(CLOCK_REALTIME, &wallTime);
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &cpuTime);
int64_t wall = (wallTime.tv_sec * 1000) + (wallTime.tv_nsec / 1000000);
int64_t cpu = (cpuTime.tv_sec * 1000) + (cpuTime.tv_nsec / 1000000);
Json::Value diff;
GetStatInfo(diff);
ProfileIntervalMessage_Factory(myProfiler, wall, cpu, diff);
return 0;
}
| {
"content_hash": "c1af5e0520f9c06111be040c8793a7a6",
"timestamp": "",
"source": "github",
"line_count": 103,
"max_line_length": 122,
"avg_line_length": 31.475728155339805,
"alnum_prop": 0.6067242442936459,
"repo_name": "tera-insights/grokit",
"id": "548da85b3de22a535553ab88af062813221833f3",
"size": "4231",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "src/Profiler/source/PCProfiler.cc",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Awk",
"bytes": "1859"
},
{
"name": "C",
"bytes": "51603"
},
{
"name": "C++",
"bytes": "1781744"
},
{
"name": "GAP",
"bytes": "76093"
},
{
"name": "PHP",
"bytes": "955669"
},
{
"name": "Python",
"bytes": "19509"
},
{
"name": "Ruby",
"bytes": "5653"
},
{
"name": "Shell",
"bytes": "31035"
}
],
"symlink_target": ""
} |
$projectName = "Peddler"
copy "src\${projectName}\${projectName}.csproj" "src\${projectName}\${projectName}.csproj.bak"
$project = New-Object XML
$project.Load("${pwd}\src\${projectName}\${projectName}.csproj")
$project.Project.PropertyGroup.DebugType = "full"
$project.Save("${pwd}\src\${projectName}\${projectName}.csproj")
| {
"content_hash": "8397ef00c0acdfc1edc3d2f260f96285",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 94,
"avg_line_length": 41,
"alnum_prop": 0.7195121951219512,
"repo_name": "invio/Peddler",
"id": "2591235a2fd030eaa05a2a56311b616eacea7a8f",
"size": "328",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "set-debug-type.ps1",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "487187"
},
{
"name": "PowerShell",
"bytes": "3044"
},
{
"name": "Shell",
"bytes": "273"
}
],
"symlink_target": ""
} |
<?php
namespace App\Support;
use League\Fractal\TransformerAbstract;
use Illuminate\Contracts\Routing\ResponseFactory;
use Symfony\Component\HttpFoundation\Response as HttpResponse;
class Response
{
/**
* HTTP Response.
*
* @var \Illuminate\Contracts\Routing\ResponseFactory
*/
private $response;
/**
* API transformer helper.
*
* @var \App\Support\Transform
*/
public $transform;
/**
* HTTP status code.
*
* @var int
*/
private $statusCode = HttpResponse::HTTP_OK;
/**
* Create a new class instance.
*
* @param ResponseFactory $response
* @param Transform $transform
*/
public function __construct(ResponseFactory $response, Transform $transform)
{
$this->response = $response;
$this->transform = $transform;
}
/**
* Return a 201 response with the given created resource.
*
* @param mixed|null $resource
* @param TransformerAbstract|null $transformer
*
* @return \Illuminate\Http\JsonResponse
*/
public function withCreated($resource = null, TransformerAbstract $transformer = null)
{
$this->setStatusCode(HttpResponse::HTTP_CREATED);
if (is_null($resource)) {
return $this->json();
}
return $this->item($resource, $transformer);
}
/**
* Return a 429 response.
*
* @param string $message
*
* @return \Illuminate\Http\JsonResponse
*/
public function withTooManyRequests($message = 'Too Many Requests')
{
return $this->setStatusCode(
HttpResponse::HTTP_TOO_MANY_REQUESTS
)->withError($message);
}
/**
* Return a 401 response.
*
* @param string $message
*
* @return \Illuminate\Http\JsonResponse
*/
public function withUnauthorized($message = 'Unauthorized')
{
return $this->setStatusCode(
HttpResponse::HTTP_UNAUTHORIZED
)->withError($message);
}
/**
* Return a 500 response.
*
* @param string $message
*
* @return \Illuminate\Http\JsonResponse
*/
public function withInternalServerError($message = 'Internal Server Error')
{
return $this->setStatusCode(
HttpResponse::HTTP_INTERNAL_SERVER_ERROR
)->withError($message);
}
/**
* Return a 404 response.
*
* @param string $message
*
* @return \Illuminate\Http\JsonResponse
*/
public function withNotFound($message = 'Not Found')
{
return $this->setStatusCode(
HttpResponse::HTTP_NOT_FOUND
)->withError($message);
}
/**
* Make a 204 response.
*
* @return \Illuminate\Http\JsonResponse
*/
public function withNoContent()
{
return $this->setStatusCode(
HttpResponse::HTTP_NO_CONTENT
)->json();
}
/**
* Make an error response.
*
* @param mixed $message
*
* @return \Illuminate\Http\JsonResponse
*/
public function withError($message)
{
return $this->json([
'messages' => (is_array($message) ? $message : [$message]),
]);
}
/**
* Make a JSON response with the transformed item.
*
* @param mixed $item
* @param TransformerAbstract|null $transformer
*
* @return \Illuminate\Http\JsonResponse
*/
public function item($item, TransformerAbstract $transformer = null)
{
return $this->json(
$this->transform->item($item, $transformer)
);
}
/**
* Make a JSON response with the transformed items.
*
* @param mixed $items
* @param TransformerAbstract|null $transformer
*
* @return \Illuminate\Http\JsonResponse
*/
public function collection($items, TransformerAbstract $transformer = null)
{
return $this->json(
$this->transform->collection($items, $transformer)
);
}
/**
* Make a JSON response.
*
* @param mixed $data
* @param array $headers
*
* @return \Illuminate\Http\JsonResponse
*/
public function json($data = [], array $headers = [])
{
return $this->response->json($data, $this->statusCode, $headers);
}
/**
* Set HTTP status code.
*
* @param int $statusCode
*
* @return self
*/
public function setStatusCode($statusCode)
{
$this->statusCode = $statusCode;
return $this;
}
/**
* Gets the HTTP status code.
*
* @return int
*/
public function getStatusCode()
{
return $this->statusCode;
}
}
| {
"content_hash": "4bb4304d89a68a1c23569d42092b40f2",
"timestamp": "",
"source": "github",
"line_count": 211,
"max_line_length": 90,
"avg_line_length": 22.819905213270143,
"alnum_prop": 0.5597092419522326,
"repo_name": "codecasts/spa-starter-kit",
"id": "10000788f320225823ed55269e454a567cc6c019",
"size": "4815",
"binary": false,
"copies": "2",
"ref": "refs/heads/develop",
"path": "webservice/app/Support/Response.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "553"
},
{
"name": "CSS",
"bytes": "2104"
},
{
"name": "HTML",
"bytes": "4626"
},
{
"name": "JavaScript",
"bytes": "43303"
},
{
"name": "PHP",
"bytes": "135830"
},
{
"name": "Vue",
"bytes": "40010"
}
],
"symlink_target": ""
} |
import unittest
from atbash_cipher import (
decode,
encode,
)
# Tests adapted from `problem-specifications//canonical-data.json`
class AtbashCipherTest(unittest.TestCase):
def test_encode_yes(self):
self.assertEqual(encode("yes"), "bvh")
def test_encode_no(self):
self.assertEqual(encode("no"), "ml")
def test_encode_omg(self):
self.assertEqual(encode("OMG"), "lnt")
def test_encode_spaces(self):
self.assertEqual(encode("O M G"), "lnt")
def test_encode_mindblowingly(self):
self.assertEqual(encode("mindblowingly"), "nrmwy oldrm tob")
def test_encode_numbers(self):
self.assertEqual(encode("Testing,1 2 3, testing."), "gvhgr mt123 gvhgr mt")
def test_encode_deep_thought(self):
self.assertEqual(encode("Truth is fiction."), "gifgs rhurx grlm")
def test_encode_all_the_letters(self):
self.assertEqual(
encode("The quick brown fox jumps over the lazy dog."),
"gsvjf rxpyi ldmul cqfnk hlevi gsvoz abwlt",
)
def test_decode_exercism(self):
self.assertEqual(decode("vcvix rhn"), "exercism")
def test_decode_a_sentence(self):
self.assertEqual(
decode("zmlyh gzxov rhlug vmzhg vkkrm thglm v"),
"anobstacleisoftenasteppingstone",
)
def test_decode_numbers(self):
self.assertEqual(decode("gvhgr mt123 gvhgr mt"), "testing123testing")
def test_decode_all_the_letters(self):
self.assertEqual(
decode("gsvjf rxpyi ldmul cqfnk hlevi gsvoz abwlt"),
"thequickbrownfoxjumpsoverthelazydog",
)
def test_decode_with_too_many_spaces(self):
self.assertEqual(decode("vc vix r hn"), "exercism")
def test_decode_with_no_spaces(self):
self.assertEqual(
decode("zmlyhgzxovrhlugvmzhgvkkrmthglmv"), "anobstacleisoftenasteppingstone"
)
if __name__ == "__main__":
unittest.main()
| {
"content_hash": "2505ca983cf53553c5c732bc6ce8a96d",
"timestamp": "",
"source": "github",
"line_count": 67,
"max_line_length": 88,
"avg_line_length": 29.388059701492537,
"alnum_prop": 0.638395124428644,
"repo_name": "exercism/python",
"id": "98c1072afc7b41930252b9043726d94000cf4db6",
"size": "1969",
"binary": false,
"copies": "2",
"ref": "refs/heads/main",
"path": "exercises/practice/atbash-cipher/atbash_cipher_test.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Jinja",
"bytes": "103144"
},
{
"name": "Python",
"bytes": "934764"
},
{
"name": "Shell",
"bytes": "2960"
}
],
"symlink_target": ""
} |
package org.apache.ignite.internal.portable.builder;
import org.apache.ignite.internal.portable.PortableWriterExImpl;
import org.apache.ignite.internal.processors.cache.portable.CacheObjectPortableProcessorImpl;
import org.apache.ignite.internal.util.typedef.internal.S;
/**
*
*/
class PortableValueWithType implements PortableLazyValue {
/** */
private byte type;
/** */
private Object val;
/**
* @param type Type
* @param val Value.
*/
PortableValueWithType(byte type, Object val) {
this.type = type;
this.val = val;
}
/** {@inheritDoc} */
@Override public void writeTo(PortableWriterExImpl writer, PortableBuilderSerializer ctx) {
if (val instanceof PortableBuilderSerializationAware)
((PortableBuilderSerializationAware)val).writeTo(writer, ctx);
else
ctx.writeValue(writer, val);
}
/** {@inheritDoc} */
public String typeName() {
return CacheObjectPortableProcessorImpl.fieldTypeName(type);
}
/** {@inheritDoc} */
@Override public Object value() {
if (val instanceof PortableLazyValue)
return ((PortableLazyValue)val).value();
return val;
}
/**
* @param val New value.
*/
public void value(Object val) {
this.val = val;
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(PortableValueWithType.class, this);
}
} | {
"content_hash": "fcd8633977116e22826bc1aa74e0eb8a",
"timestamp": "",
"source": "github",
"line_count": 60,
"max_line_length": 95,
"avg_line_length": 24.616666666666667,
"alnum_prop": 0.6398104265402843,
"repo_name": "vsisko/incubator-ignite",
"id": "2e031f06b330e963b14a525b8b1cc75319c545dc",
"size": "2279",
"binary": false,
"copies": "9",
"ref": "refs/heads/master",
"path": "modules/core/src/main/java/org/apache/ignite/internal/portable/builder/PortableValueWithType.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "31300"
},
{
"name": "C",
"bytes": "3323"
},
{
"name": "C#",
"bytes": "2610422"
},
{
"name": "C++",
"bytes": "864786"
},
{
"name": "CSS",
"bytes": "17517"
},
{
"name": "Groovy",
"bytes": "15092"
},
{
"name": "HTML",
"bytes": "4649"
},
{
"name": "Java",
"bytes": "20888957"
},
{
"name": "JavaScript",
"bytes": "1085"
},
{
"name": "PHP",
"bytes": "11079"
},
{
"name": "Scala",
"bytes": "653857"
},
{
"name": "Shell",
"bytes": "398313"
}
],
"symlink_target": ""
} |
'use strict';
//var AMQPClient = require('amqp10').Client;
var AMQPClient = require('../lib').Client,
Policy = require('../lib').Policy;
// Set the offset for the EventHub - this is where it should start receiving from, and is typically different for each partition
// Here, I'm setting a global offset, just to show you how it's done. See node-sbus-amqp10 for a wrapper library that will
// take care of this for you.
var filterOffset; // example filter offset value might be: 43350;
var filterOption; // todo:: need a x-opt-offset per partition.
if (filterOffset) {
filterOption = {
filter: {
'apache.org:selector-filter:string': AMQPClient.adapters.Translator(
['described', ['symbol', 'apache.org:selector-filter:string'], ['string', "amqp.annotation.x-opt-offset > '" + filterOffset + "'"]])
}
};
}
// Simple argument-checker, you can ignore.
function argCheck(settings, options) {
var missing = [];
for (var idx in options) {
if (settings[options[idx]] === undefined) missing.push(options[idx]);
}
if (missing.length > 0) {
throw new Error('Required settings ' + (missing.join(', ')) + ' missing.');
}
}
if (process.argv.length < 3) {
console.warn('Usage: node ' + process.argv[1] + ' <settings json file>');
} else {
var settingsFile = process.argv[2];
var settings = require('./' + settingsFile);
argCheck(settings, ['serviceBusHost', 'SASKeyName', 'SASKey', 'eventHubName', 'partitions']);
var protocol = settings.protocol || 'amqps';
var serviceBusHost = settings.serviceBusHost + '.servicebus.windows.net';
if (settings.serviceBusHost.indexOf(".") !== -1) {
serviceBusHost = settings.serviceBusHost;
}
var sasName = settings.SASKeyName;
var sasKey = settings.SASKey;
var eventHubName = settings.eventHubName;
var numPartitions = settings.partitions;
var uri = protocol + '://' + encodeURIComponent(sasName) + ':' + encodeURIComponent(sasKey) + '@' + serviceBusHost;
var sendAddr = eventHubName;
var recvAddr = eventHubName + '/ConsumerGroups/$default/Partitions/';
var msgVal = Math.floor(Math.random() * 1000000);
var errorHandler = function(myIdx, rx_err) {
console.warn('==> RX ERROR: ', rx_err);
};
var messageHandler = function (myIdx, msg) {
console.log('Recv(' + myIdx + '): ');
console.log(msg.body);
if (msg.annotations) {
console.log('Annotations:');
console.log(msg.annotations);
}
console.log('');
if (msg.body.DataValue === msgVal) {
client.disconnect().then(function () {
console.log("Disconnected, when we saw the value we'd inserted.");
process.exit(0);
});
}
};
var setupReceiver = function(curIdx, curRcvAddr, filterOption) {
client.createReceiver(curRcvAddr, filterOption)
.then(function (receiver) {
receiver.on('message', messageHandler.bind(null, curIdx));
receiver.on('errorReceived', errorHandler.bind(null, curIdx));
})
}
var client = new AMQPClient(Policy.EventHub);
client.connect(uri).then(function () {
for (var idx = 0; idx < numPartitions; ++idx) {
setupReceiver(idx, recvAddr + idx, filterOption) // TODO:: filterOption-> checkpoints are per partition.
}
// {'x-opt-partition-key': 'pk' + msgVal}
client.createSender(sendAddr).then(function (sender) {
sender.on('errorReceived', function (tx_err) {
console.warn('===> TX ERROR: ', tx_err);
});
sender.send({ "DataString": "From Node", "DataValue": msgVal }, { annotations: {'x-opt-partition-key': 'pk' + msgVal} }).then(function (state) {
console.log('State: ', state);
});
});
}).catch(function (e) {
console.warn('Failed to send due to ', e);
});
}
| {
"content_hash": "599971d8d9c4baf21866728cbbe915cf",
"timestamp": "",
"source": "github",
"line_count": 97,
"max_line_length": 150,
"avg_line_length": 38.48453608247423,
"alnum_prop": 0.6490758103402089,
"repo_name": "danlangford/node-amqp10",
"id": "63a8be5b84ba27c0677f12c0f3b730a95f690527",
"size": "4663",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "examples/simple_eventhub_test.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "395073"
},
{
"name": "Makefile",
"bytes": "1262"
}
],
"symlink_target": ""
} |
<?php
namespace MABI\Testing;
include_once __DIR__ . '/middleware/MiddlewareTestCase.php';
include_once __DIR__ . '/../middleware/APIApplicationOnlyAccess.php';
include_once __DIR__ . '/../middleware/SharedSecret.php';
class ErrorResponseTest extends MiddlewareTestCase {
/**
* @var \mabiTesting\ModelA
*/
protected $insertedModel;
public function testCustomError() {
$this->setUpApp(array('PATH_INFO' => '/justa/customerror'));
$this->app->call();
$this->assertJson($this->app->getResponse()->body());
$response = json_decode($this->app->getResponse()->body());
$this->assertEquals($response->error->code, 1);
$this->assertEquals($response->error->message, "New test error with a replacement string");
$this->assertEquals(401, $this->app->getResponse()->status());
}
public function testCustomError2() {
$this->setUpApp(array('PATH_INFO' => '/justa/customerror2'));
$this->app->call();
$this->assertJson($this->app->getResponse()->body());
$response = json_decode($this->app->getResponse()->body());
$this->assertEquals($response->error->code, 1);
$this->assertEquals($response->error->message, "Test error2");
$this->assertEquals(401, $this->app->getResponse()->status());
}
public function testCustomError3() {
$this->setUpApp(array('PATH_INFO' => '/justa/customerror3'));
$this->app->call();
$this->assertJson($this->app->getResponse()->body());
$response = json_decode($this->app->getResponse()->body());
$this->assertEquals($response->error->code, 1);
$this->assertEquals($response->error->message, "New test error with a replacement string");
$this->assertEquals(401, $this->app->getResponse()->status());
}
public function testErrorOverride() {
$middleware = new \MABI\Middleware\SharedSecret();
$middleware2 = new \MABI\Middleware\APIApplicationOnlyAccess();
$this->setUpApp(array('PATH_INFO' => '/justa/testfunc'), array($middleware, $middleware2));
$this->app->call();
$this->assertJson($this->app->getResponse()->body());
$response = json_decode($this->app->getResponse()->body());
$this->assertEquals($response->error->code, 1007);
$this->assertEquals($response->error->message, "Why don't you just get out of here, ok?");
$this->assertEquals(401, $this->app->getResponse()->status());
}
} | {
"content_hash": "6b8de97eea33c458d8f9eb7c39c27482",
"timestamp": "",
"source": "github",
"line_count": 65,
"max_line_length": 95,
"avg_line_length": 36.36923076923077,
"alnum_prop": 0.6582064297800339,
"repo_name": "prolificinteractive/mabi",
"id": "97caf11cb9ac6491239869687ee7426dd3996c5c",
"size": "2364",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/ErrorResponseTest.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "2553532"
},
{
"name": "C++",
"bytes": "30781"
},
{
"name": "CSS",
"bytes": "28902"
},
{
"name": "JavaScript",
"bytes": "60382"
},
{
"name": "Lua",
"bytes": "11887"
},
{
"name": "Objective-C",
"bytes": "470"
},
{
"name": "PHP",
"bytes": "500338"
},
{
"name": "Perl",
"bytes": "170502"
},
{
"name": "Ruby",
"bytes": "6978"
},
{
"name": "Shell",
"bytes": "19456"
},
{
"name": "Tcl",
"bytes": "273384"
},
{
"name": "XSLT",
"bytes": "303"
}
],
"symlink_target": ""
} |
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker: */
// {{{ Header
/**
* Generic date handling class for PEAR
*
* Handles time zones and changes from local standard to local Summer
* time (daylight-saving time) through the Date_TimeZone class.
* Supports several operations from Date_Calc on Date objects.
*
* PHP versions 4 and 5
*
* LICENSE:
*
* Copyright (c) 1997-2007 Baba Buehler, Pierre-Alain Joye, Firman
* Wandayandi, C.A. Woodcock
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted under the terms of the BSD License.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @category Date and Time
* @package Date
* @author Baba Buehler <[email protected]>
* @author Pierre-Alain Joye <[email protected]>
* @author Firman Wandayandi <[email protected]>
* @author C.A. Woodcock <[email protected]>
* @copyright 1997-2007 Baba Buehler, Pierre-Alain Joye, Firman Wandayandi, C.A. Woodcock
* @license http://www.opensource.org/licenses/bsd-license.php
* BSD License
* @version CVS: $Id: Date.php,v 1.89 2008/03/23 18:34:16 c01234 Exp $
* @link http://pear.php.net/package/Date
*/
// }}}
// {{{ Error constants
define('DATE_ERROR_INVALIDDATE', 1);
define('DATE_ERROR_INVALIDTIME', 2);
define('DATE_ERROR_INVALIDTIMEZONE', 3);
define('DATE_ERROR_INVALIDDATEFORMAT', 4);
define('DATE_ERROR_INVALIDFORMATSTRING', 5);
// }}}
// {{{ Includes
require_once 'PEAR.php';
/**
* Load Date_TimeZone
*/
require_once 'Date/TimeZone.php';
/**
* Load Date_Calc
*/
require_once 'Date/Calc.php';
/**
* Load Date_Span
*/
require_once 'Date/Span.php';
// }}}
// {{{ General constants
/**
* Whether to capture the micro-time (in microseconds) by default
* in calls to 'Date::setNow()'. Note that this makes a call to
* 'gettimeofday()', which may not work on all systems.
*
* @since Constant available since Release 1.5.0
*/
define('DATE_CAPTURE_MICROTIME_BY_DEFAULT', false);
/**
* Whether to correct, by adding the local Summer time offset, the
* specified time if it falls in the 'skipped hour' (encountered
* when the clocks go forward).
*
* N.B. if specified as 'false', and if a time zone that adjusts
* for Summer time is specified, then an object of this class will
* be set to a semi-invalid state if an invalid time is set. That
* is, an error will not be returned, unless the user then calls
* a function, directly or indirectly, that accesses the time
* part of the object. So, for example, if the user calls:
*
* <code>$date_object->format2('HH.MI.SS')</code> or:
* <code>$date->object->addSeconds(30)</code>,
*
* an error will be returned if the time is invalid. However,
* if the user calls:
*
* <code>$date->object->addDays(1)</code>,
*
* for example, such that the time is no longer invalid, then the
* object will no longer be in this invalid state. This behaviour
* is intended to minimize unexpected errors when a user uses the
* class to do addition with days only, and does not intend to
* access the time.
*
* Of course, this constant will be unused if the user chooses to
* work in UTC or a time zone without Summer time, in which case
* this situation will never arise.
*
* This constant is set to 'true' by default for backwards-compatibility
* reasons, however, you are recommended to set it to 'false'. Note that the
* behaviour is not intended to match that of previous versions of the class
* in terms of ignoring the Summer time offset when making calculations which
* involve dates in both standard and Summer time - this was recognized as a
* bug - but in terms of returning a PEAR error object when the user sets the
* object to an invalid date (i.e. a time in the hour which is skipped when
* the clocks go forwards, which in Europe would be a time such as 01.30).
* Backwards compatibility here means that the behaviour is the same as it
* used to be, less the bug.
*
* Note that this problem is not an issue for the user if:
*
* (a) the user uses a time zone that does not observe Summer time, e.g. UTC
* (b) the user never accesses the time, that is, he never makes a call to
* Date::getHour() or Date::format("%H"), for example, even if he sets
* the time to something invalid
* (c) the user sets DATE_CORRECTINVALIDTIME_DEFAULT to true
*
* @since Constant available since Release 1.5.0
*/
define('DATE_CORRECTINVALIDTIME_DEFAULT', true);
/**
* Whether to validate dates (i.e. day-month-year, ignoring the time) by
* disallowing invalid dates (e.g. 31st February) being set by the following
* functions:
*
* Date::setYear()
* Date::setMonth()
* Date::setDay()
*
* If the constant is set to 'true', then the date will be checked (by
* default), and if invalid, an error will be returned with the Date object
* left unmodified.
*
* This constant is set to 'false' by default for backwards-compatibility
* reasons, however, you are recommended to set it to 'true'.
*
* Note that setHour(), setMinute(), setSecond() and setPartSecond()
* allow an invalid date/time to be set regardless of the value of this
* constant.
*
* @since Constant available since Release 1.5.0
*/
define('DATE_VALIDATE_DATE_BY_DEFAULT', false);
/**
* Whether, by default, to accept times including leap seconds (i.e. '23.59.60')
* when setting the date/time, and whether to count leap seconds in the
* following functions:
*
* Date::addSeconds()
* Date::subtractSeconds()
* Date_Calc::addSeconds()
* Date::round()
* Date::roundSeconds()
*
* This constant is set to 'false' by default for backwards-compatibility
* reasons, however, you are recommended to set it to 'true'.
*
* Note that this constant does not affect Date::addSpan() and
* Date::subtractSpan() which will not count leap seconds in any case.
*
* @since Constant available since Release 1.5.0
*/
define('DATE_COUNT_LEAP_SECONDS', false);
// }}}
// {{{ Output format constants (used in 'Date::getDate()')
/**
* "YYYY-MM-DD HH:MM:SS"
*/
define('DATE_FORMAT_ISO', 1);
/**
* "YYYYMMSSTHHMMSS(Z|(+/-)HHMM)?"
*/
define('DATE_FORMAT_ISO_BASIC', 2);
/**
* "YYYY-MM-SSTHH:MM:SS(Z|(+/-)HH:MM)?"
*/
define('DATE_FORMAT_ISO_EXTENDED', 3);
/**
* "YYYY-MM-SSTHH:MM:SS(.S*)?(Z|(+/-)HH:MM)?"
*/
define('DATE_FORMAT_ISO_EXTENDED_MICROTIME', 6);
/**
* "YYYYMMDDHHMMSS"
*/
define('DATE_FORMAT_TIMESTAMP', 4);
/**
* long int, seconds since the unix epoch
*/
define('DATE_FORMAT_UNIXTIME', 5);
// }}}
// {{{ Class: Date
/**
* Generic date handling class for PEAR
*
* Supports time zones with the Date_TimeZone class. Supports several
* operations from Date_Calc on Date objects.
*
* Note to developers: the class stores the local time and date in the
* local standard time. That is, it does not store the time as the
* local Summer time when and if the time zone is in Summer time. It
* is much easier to store local standard time and remember to offset
* it when the user requests it.
*
* @category Date and Time
* @package Date
* @author Baba Buehler <[email protected]>
* @author Pierre-Alain Joye <[email protected]>
* @author Firman Wandayandi <[email protected]>
* @author C.A. Woodcock <[email protected]>
* @copyright 1997-2007 Baba Buehler, Pierre-Alain Joye, Firman Wandayandi, C.A. Woodcock
* @license http://www.opensource.org/licenses/bsd-license.php
* BSD License
* @version Release: 1.5.0a1
* @link http://pear.php.net/package/Date
*/
class Date
{
// {{{ Properties
/**
* The year
*
* @var int
* @access private
* @since Property available since Release 1.0
*/
var $year;
/**
* The month
*
* @var int
* @access private
* @since Property available since Release 1.0
*/
var $month;
/**
* The day
*
* @var int
* @access private
* @since Property available since Release 1.0
*/
var $day;
/**
* The hour
*
* @var int
* @access private
* @since Property available since Release 1.0
*/
var $hour;
/**
* The minute
*
* @var int
* @access private
* @since Property available since Release 1.0
*/
var $minute;
/**
* The second
*
* @var int
* @access private
* @since Property available since Release 1.0
*/
var $second;
/**
* The parts of a second
*
* @var float
* @access private
* @since Property available since Release 1.4.3
*/
var $partsecond;
/**
* The year in local standard time
*
* @var int
* @access private
* @since Property available since Release 1.5.0
*/
var $on_standardyear;
/**
* The month in local standard time
*
* @var int
* @access private
* @since Property available since Release 1.5.0
*/
var $on_standardmonth;
/**
* The day in local standard time
*
* @var int
* @access private
* @since Property available since Release 1.5.0
*/
var $on_standardday;
/**
* The hour in local standard time
*
* @var int
* @access private
* @since Property available since Release 1.5.0
*/
var $on_standardhour;
/**
* The minute in local standard time
*
* @var int
* @access private
* @since Property available since Release 1.5.0
*/
var $on_standardminute;
/**
* The second in local standard time
*
* @var int
* @access private
* @since Property available since Release 1.5.0
*/
var $on_standardsecond;
/**
* The part-second in local standard time
*
* @var float
* @access private
* @since Property available since Release 1.5.0
*/
var $on_standardpartsecond;
/**
* Whether the object should accept and count leap seconds
*
* @var bool
* @access private
* @since Property available since Release 1.5.0
*/
var $ob_countleapseconds;
/**
* Whether the time is valid as a local time (an invalid time
* is one that lies in the 'skipped hour' at the point that
* the clocks go forward)
*
* @var bool
* @access private
* @see Date::isTimeValid()
* @since Property available since Release 1.5.0
*/
var $ob_invalidtime = null;
/**
* Date_TimeZone object for this date
*
* @var object Date_TimeZone object
* @access private
* @since Property available since Release 1.0
*/
var $tz;
/**
* Defines the default weekday abbreviation length
*
* Formerly used by Date::format(), but now redundant - the abbreviation
* for the current locale of the machine is used.
*
* @var int
* @access private
* @since Property available since Release 1.4.4
*/
var $getWeekdayAbbrnameLength = 3;
// }}}
// {{{ Constructor
/**
* Constructor
*
* Creates a new Date Object initialized to the current date/time in the
* system-default timezone by default. A date optionally
* passed in may be in the ISO 8601, TIMESTAMP or UNIXTIME format,
* or another Date object. If no date is passed, the current date/time
* is used.
*
* If a date is passed and an exception is returned by 'setDate()'
* there is nothing that this function can do, so for this reason, it
* is advisable to pass no parameter and to make a separate call to
* 'setDate()'. A date/time should only be passed if known to be a
* valid ISO 8601 string or a valid Unix timestamp.
*
* @param mixed $date optional ISO 8601 date/time to initialize;
* or, a Unix time stamp
* @param bool $pb_countleapseconds whether to count leap seconds
* (defaults to DATE_COUNT_LEAP_SECONDS)
*
* @return void
* @access public
* @see Date::setDate()
*/
function Date($date = null,
$pb_countleapseconds = DATE_COUNT_LEAP_SECONDS)
{
$this->ob_countleapseconds = $pb_countleapseconds;
if (is_a($date, 'Date')) {
$this->copy($date);
} else {
if (!is_null($date)) {
// 'setDate()' expects a time zone to be already set:
//
$this->_setTZToDefault();
$this->setDate($date);
} else {
$this->setNow();
}
}
}
// }}}
// {{{ copy()
/**
* Copy values from another Date object
*
* Makes this Date a copy of another Date object. This is a
* PHP4-compatible implementation of '__clone()' in PHP5.
*
* @param object $date Date object to copy
*
* @return void
* @access public
*/
function copy($date)
{
$this->year = $date->year;
$this->month = $date->month;
$this->day = $date->day;
$this->hour = $date->hour;
$this->minute = $date->minute;
$this->second = $date->second;
$this->partsecond = $date->partsecond;
$this->on_standardyear = $date->on_standardyear;
$this->on_standardmonth = $date->on_standardmonth;
$this->on_standardday = $date->on_standardday;
$this->on_standardhour = $date->on_standardhour;
$this->on_standardminute = $date->on_standardminute;
$this->on_standardsecond = $date->on_standardsecond;
$this->on_standardpartsecond = $date->on_standardpartsecond;
$this->ob_countleapseconds = $date->ob_countleapseconds;
$this->ob_invalidtime = $date->ob_invalidtime;
$this->tz = new Date_TimeZone($date->getTZID());
$this->getWeekdayAbbrnameLength = $date->getWeekdayAbbrnameLength;
}
// }}}
// {{{ __clone()
/**
* Copy values from another Date object
*
* Makes this Date a copy of another Date object. For PHP5
* only.
*
* @return void
* @access public
* @see Date::copy()
*/
function __clone()
{
// This line of code would be preferable, but will only
// compile in PHP5:
//
// $this->tz = clone $this->tz;
$this->tz = new Date_TimeZone($this->getTZID());
}
// }}}
// {{{ setDate()
/**
* Sets the fields of a Date object based on the input date and format
*
* Format parameter should be one of the specified DATE_FORMAT_* constants:
*
* <code>DATE_FORMAT_ISO</code>
* - 'YYYY-MM-DD HH:MI:SS'
* <code>DATE_FORMAT_ISO_BASIC</code>
* - 'YYYYMMSSTHHMMSS(Z|(+/-)HHMM)?'
* <code>DATE_FORMAT_ISO_EXTENDED</code>
* - 'YYYY-MM-SSTHH:MM:SS(Z|(+/-)HH:MM)?'
* <code>DATE_FORMAT_ISO_EXTENDED_MICROTIME</code>
* - 'YYYY-MM-SSTHH:MM:SS(.S*)?(Z|(+/-)HH:MM)?'
* <code>DATE_FORMAT_TIMESTAMP</code>
* - 'YYYYMMDDHHMMSS'
* <code>DATE_FORMAT_UNIXTIME'</code>
* - long integer of the no of seconds since
* the Unix Epoch
* (1st January 1970 00.00.00 GMT)
*
* @param string $date input date
* @param int $format optional format constant
* (DATE_FORMAT_*) of the input date.
* This parameter is not needed,
* except to force the setting of the
* date from a Unix time-stamp
* (DATE_FORMAT_UNIXTIME).
* @param bool $pb_repeatedhourdefault value to return if repeated
* hour is specified (defaults
* to false)
*
* @return void
* @access public
*/
function setDate($date,
$format = DATE_FORMAT_ISO,
$pb_repeatedhourdefault = false)
{
if (preg_match('/^([0-9]{4,4})-?(0[1-9]|1[0-2])-?(0[1-9]|[12][0-9]|3[01])' .
'([T\s]?([01][0-9]|2[0-3]):?' . // [hh]
'([0-5][0-9]):?([0-5][0-9]|60)(\.\d+)?' . // [mi]:[ss]
'(Z|[+\-][0-9]{2,2}(:?[0-5][0-9])?)?)?$/i', // offset
$date, $regs) &&
$format != DATE_FORMAT_UNIXTIME
) {
// DATE_FORMAT_ISO, ISO_BASIC, ISO_EXTENDED, and TIMESTAMP
// These formats are extremely close to each other. This regex
// is very loose and accepts almost any butchered format you could
// throw at it. e.g. 2003-10-07 19:45:15 and 2003-10071945:15
// are the same thing in the eyes of this regex, even though the
// latter is not a valid ISO 8601 date.
if (!Date_Calc::isValidDate($regs[3], $regs[2], $regs[1])) {
return PEAR::raiseError("'" .
Date_Calc::dateFormat($regs[1],
$regs[2],
$regs[3],
"%Y-%m-%d") .
"' is invalid calendar date",
DATE_ERROR_INVALIDDATE);
}
if (isset($regs[9])) {
if ($regs[9] == "Z") {
$this->tz = new Date_TimeZone("UTC");
} else {
$this->tz = new Date_TimeZone("UTC" . $regs[9]);
}
}
$this->setLocalTime($regs[3],
$regs[2],
$regs[1],
isset($regs[5]) ? $regs[5] : 0,
isset($regs[6]) ? $regs[6] : 0,
isset($regs[7]) ? $regs[7] : 0,
isset($regs[8]) ? $regs[8] : 0.0,
$pb_repeatedhourdefault);
} else if (is_numeric($date)) {
// Unix Time; N.B. Unix Time is defined relative to GMT,
// so it needs to be adjusted for the current time zone;
// however we do not know if it is in Summer time until
// we have converted it from Unix time:
//
// Get current time zone details:
//
$hs_id = $this->getTZID();
// Input Unix time as UTC:
//
$this->tz = new Date_TimeZone("UTC");
$this->setDate(gmdate("Y-m-d H:i:s", $date));
// Convert back to correct time zone:
//
$this->convertTZByID($hs_id);
} else {
return PEAR::raiseError("Date not in ISO 8601 format",
DATE_ERROR_INVALIDDATEFORMAT);
}
}
// }}}
// {{{ setNow()
/**
* Sets to local current time and time zone
*
* @param bool $pb_setmicrotime whether to set micro-time (defaults to the
* value of the constant
* DATE_CAPTURE_MICROTIME_BY_DEFAULT)
*
* @return void
* @access public
* @since Method available since Release 1.5.0
*/
function setNow($pb_setmicrotime = DATE_CAPTURE_MICROTIME_BY_DEFAULT)
{
$this->_setTZToDefault();
if ($pb_setmicrotime) {
$ha_unixtime = gettimeofday();
} else {
$ha_unixtime = array("sec" => time());
}
$this->setDate(date("Y-m-d H:i:s", $ha_unixtime["sec"]) .
(isset($ha_unixtime["usec"]) ?
"." . sprintf("%06d", $ha_unixtime["usec"]) :
""));
}
// }}}
// {{{ round()
/**
* Rounds the date according to the specified precision (defaults
* to nearest day)
*
* The precision parameter must be one of the following constants:
*
* <code>DATE_PRECISION_YEAR</code>
* <code>DATE_PRECISION_MONTH</code>
* <code>DATE_PRECISION_DAY</code>
* <code>DATE_PRECISION_HOUR</code>
* <code>DATE_PRECISION_10MINUTES</code>
* <code>DATE_PRECISION_MINUTE</code>
* <code>DATE_PRECISION_10SECONDS</code>
* <code>DATE_PRECISION_SECOND</code>
*
* N.B. the default is DATE_PRECISION_DAY
*
* The precision can also be specified as an integral offset from
* one of these constants, where the offset reflects a precision
* of 10 to the power of the offset greater than the constant.
* For example:
*
* <code>DATE_PRECISION_YEAR - 1</code> rounds the date to the nearest 10
* years
* <code>DATE_PRECISION_YEAR - 3</code> rounds the date to the nearest 1000
* years
* <code>DATE_PRECISION_SECOND + 1</code> rounds the date to 1 decimal
* point of a second
* <code>DATE_PRECISION_SECOND + 3</code> rounds the date to 3 decimal
* points of a second
* <code>DATE_PRECISION_SECOND - 1</code> rounds the date to the nearest 10
* seconds (thus it is equivalent to
* DATE_PRECISION_10SECONDS)
*
* @param int $pn_precision a 'DATE_PRECISION_*' constant
* @param bool $pb_correctinvalidtime whether to correct, by adding the
* local Summer time offset, the rounded
* time if it falls in the skipped hour
* (defaults to
* DATE_CORRECTINVALIDTIME_DEFAULT)
*
* @return void
* @access public
* @since Method available since Release 1.5.0
*/
function round($pn_precision = DATE_PRECISION_DAY,
$pb_correctinvalidtime = DATE_CORRECTINVALIDTIME_DEFAULT)
{
if ($pn_precision <= DATE_PRECISION_DAY) {
list($hn_year,
$hn_month,
$hn_day,
$hn_hour,
$hn_minute,
$hn_secondraw) =
Date_Calc::round($pn_precision,
$this->day,
$this->month,
$this->year,
$this->hour,
$this->minute,
$this->partsecond == 0.0 ?
$this->second :
$this->second + $this->partsecond,
$this->ob_countleapseconds);
if (is_float($hn_secondraw)) {
$hn_second = intval($hn_secondraw);
$hn_partsecond = $hn_secondraw - $hn_second;
} else {
$hn_second = $hn_secondraw;
$hn_partsecond = 0.0;
}
$this->setLocalTime($hn_day,
$hn_month,
$hn_year,
$hn_hour,
$hn_minute,
$hn_second,
$hn_partsecond,
true, // This is unlikely anyway, but the
// day starts with the repeated hour
// the first time around
$pb_correctinvalidtime);
return;
}
// ($pn_precision >= DATE_PRECISION_HOUR)
//
if ($this->tz->getDSTSavings() % 3600000 == 0 ||
($this->tz->getDSTSavings() % 60000 == 0 &&
$pn_precision >= DATE_PRECISION_MINUTE)
) {
list($hn_year,
$hn_month,
$hn_day,
$hn_hour,
$hn_minute,
$hn_secondraw) =
Date_Calc::round($pn_precision,
$this->on_standardday,
$this->on_standardmonth,
$this->on_standardyear,
$this->on_standardhour,
$this->on_standardminute,
$this->on_standardpartsecond == 0.0 ?
$this->on_standardsecond :
$this->on_standardsecond +
$this->on_standardpartsecond,
$this->ob_countleapseconds);
if (is_float($hn_secondraw)) {
$hn_second = intval($hn_secondraw);
$hn_partsecond = $hn_secondraw - $hn_second;
} else {
$hn_second = $hn_secondraw;
$hn_partsecond = 0.0;
}
$this->setStandardTime($hn_day,
$hn_month,
$hn_year,
$hn_hour,
$hn_minute,
$hn_second,
$hn_partsecond);
return;
}
// Very unlikely anyway (as I write, the only time zone like this
// is Lord Howe Island in Australia (offset of half an hour)):
//
// (This algorithm could be better)
//
list($hn_year,
$hn_month,
$hn_day,
$hn_hour,
$hn_minute,
$hn_secondraw) =
Date_Calc::round($pn_precision,
$this->day,
$this->month,
$this->year,
$this->hour,
$this->minute,
$this->partsecond == 0.0 ?
$this->second :
$this->second + $this->partsecond,
$this->ob_countleapseconds);
if (is_float($hn_secondraw)) {
$hn_second = intval($hn_secondraw);
$hn_partsecond = $hn_secondraw - $hn_second;
} else {
$hn_second = $hn_secondraw;
$hn_partsecond = 0.0;
}
$this->setLocalTime($hn_day,
$hn_month,
$hn_year,
$hn_hour,
$hn_minute,
$hn_second,
$hn_partsecond,
false, // This will be right half the time
$pb_correctinvalidtime); // This will be right
// some of the time
// (depends on Summer
// time offset)
}
// }}}
// {{{ roundSeconds()
/**
* Rounds seconds up or down to the nearest specified unit
*
* N.B. this function is equivalent to calling:
* <code>'round(DATE_PRECISION_SECOND + $pn_precision)'</code>
*
* @param int $pn_precision number of digits after the decimal point
* @param bool $pb_correctinvalidtime whether to correct, by adding the
* local Summer time offset, the rounded
* time if it falls in the skipped hour
* (defaults to
* DATE_CORRECTINVALIDTIME_DEFAULT)
*
* @return void
* @access public
* @since Method available since Release 1.5.0
*/
function roundSeconds($pn_precision = 0,
$pb_correctinvalidtime = DATE_CORRECTINVALIDTIME_DEFAULT)
{
$this->round(DATE_PRECISION_SECOND + $pn_precision,
$pb_correctinvalidtime);
}
// }}}
// {{{ trunc()
/**
* Truncates the date according to the specified precision (by
* default, it truncates the time part of the date)
*
* The precision parameter must be one of the following constants:
*
* <code>DATE_PRECISION_YEAR</code>
* <code>DATE_PRECISION_MONTH</code>
* <code>DATE_PRECISION_DAY</code>
* <code>DATE_PRECISION_HOUR</code>
* <code>DATE_PRECISION_10MINUTES</code>
* <code>DATE_PRECISION_MINUTE</code>
* <code>DATE_PRECISION_10SECONDS</code>
* <code>DATE_PRECISION_SECOND</code>
*
* N.B. the default is DATE_PRECISION_DAY
*
* The precision can also be specified as an integral offset from
* one of these constants, where the offset reflects a precision
* of 10 to the power of the offset greater than the constant.
* For example:
*
* <code>DATE_PRECISION_YEAR</code> truncates the month, day and time
* part of the year
* <code>DATE_PRECISION_YEAR - 1</code> truncates the unit part of the
* year, e.g. 1987 becomes 1980
* <code>DATE_PRECISION_YEAR - 3</code> truncates the hundreds part of the
* year, e.g. 1987 becomes 1000
* <code>DATE_PRECISION_SECOND + 1</code> truncates the part of the second
* less than 0.1 of a second, e.g.
* 3.26301 becomes 3.2 seconds
* <code>DATE_PRECISION_SECOND + 3</code> truncates the part of the second
* less than 0.001 of a second, e.g.
* 3.26301 becomes 3.263 seconds
* <code>DATE_PRECISION_SECOND - 1</code> truncates the unit part of the
* seconds (thus it is equivalent to
* DATE_PRECISION_10SECONDS)
*
* @param int $pn_precision a 'DATE_PRECISION_*' constant
* @param bool $pb_correctinvalidtime whether to correct, by adding the
* local Summer time offset, the
* truncated time if it falls in the
* skipped hour (defaults to
* DATE_CORRECTINVALIDTIME_DEFAULT)
*
* @return void
* @access public
* @since Method available since Release 1.5.0
*/
function trunc($pn_precision = DATE_PRECISION_DAY,
$pb_correctinvalidtime = DATE_CORRECTINVALIDTIME_DEFAULT)
{
if ($pn_precision <= DATE_PRECISION_DAY) {
if ($pn_precision <= DATE_PRECISION_YEAR) {
$hn_month = 0;
$hn_day = 0;
$hn_hour = 0;
$hn_minute = 0;
$hn_second = 0;
$hn_partsecond = 0.0;
$hn_invprecision = DATE_PRECISION_YEAR - $pn_precision;
if ($hn_invprecision > 0) {
$hn_year = intval($this->year / pow(10, $hn_invprecision)) *
pow(10, $hn_invprecision);
//
// (Conversion to int necessary for PHP <= 4.0.6)
} else {
$hn_year = $this->year;
}
} else if ($pn_precision == DATE_PRECISION_MONTH) {
$hn_year = $this->year;
$hn_month = $this->month;
$hn_day = 0;
$hn_hour = 0;
$hn_minute = 0;
$hn_second = 0;
$hn_partsecond = 0.0;
} else if ($pn_precision == DATE_PRECISION_DAY) {
$hn_year = $this->year;
$hn_month = $this->month;
$hn_day = $this->day;
$hn_hour = 0;
$hn_minute = 0;
$hn_second = 0;
$hn_partsecond = 0.0;
}
$this->setLocalTime($hn_day,
$hn_month,
$hn_year,
$hn_hour,
$hn_minute,
$hn_second,
$hn_partsecond,
true, // This is unlikely anyway, but the
// day starts with the repeated
// hour the first time around
$pb_correctinvalidtime);
return;
}
// Precision is at least equal to DATE_PRECISION_HOUR
//
if ($pn_precision == DATE_PRECISION_HOUR) {
$this->addSeconds($this->partsecond == 0.0 ?
-$this->second :
-$this->second - $this->partsecond);
//
// (leap seconds irrelevant)
$this->addMinutes(-$this->minute);
} else if ($pn_precision <= DATE_PRECISION_MINUTE) {
if ($pn_precision == DATE_PRECISION_10MINUTES) {
$this->addMinutes(-$this->minute % 10);
}
$this->addSeconds($this->partsecond == 0.0 ?
-$this->second :
-$this->second - $this->partsecond);
//
// (leap seconds irrelevant)
} else if ($pn_precision == DATE_PRECISION_10SECONDS) {
$this->addSeconds($this->partsecond == 0.0 ?
-$this->second % 10 :
(-$this->second % 10) - $this->partsecond);
//
// (leap seconds irrelevant)
} else {
// Assume Summer time offset cannot be composed of part-seconds:
//
$hn_precision = $pn_precision - DATE_PRECISION_SECOND;
$hn_partsecond = intval($this->on_standardpartsecond *
pow(10, $hn_precision)) /
pow(10, $hn_precision);
$this->setStandardTime($this->on_standardday,
$this->on_standardmonth,
$this->on_standardyear,
$this->on_standardhour,
$this->on_standardminute,
$this->on_standardsecond,
$hn_partsecond);
}
}
// }}}
// {{{ truncSeconds()
/**
* Truncates seconds according to the specified precision
*
* N.B. this function is equivalent to calling:
* <code>'Date::trunc(DATE_PRECISION_SECOND + $pn_precision)'</code>
*
* @param int $pn_precision number of digits after the decimal point
* @param bool $pb_correctinvalidtime whether to correct, by adding the
* local Summer time offset, the
* truncated time if it falls in the
* skipped hour (defaults to
* DATE_CORRECTINVALIDTIME_DEFAULT)
*
* @return void
* @access public
* @since Method available since Release 1.5.0
*/
function truncSeconds($pn_precision = 0,
$pb_correctinvalidtime = DATE_CORRECTINVALIDTIME_DEFAULT)
{
$this->trunc(DATE_PRECISION_SECOND + $pn_precision,
$pb_correctinvalidtime);
}
// }}}
// {{{ getDate()
/**
* Gets a string (or other) representation of this date
*
* Returns a date in the format specified by the DATE_FORMAT_* constants.
*
* @param int $format format constant (DATE_FORMAT_*) of the output date
*
* @return string the date in the requested format
* @access public
*/
function getDate($format = DATE_FORMAT_ISO)
{
switch ($format) {
case DATE_FORMAT_ISO:
return $this->format("%Y-%m-%d %T");
break;
case DATE_FORMAT_ISO_BASIC:
$format = "%Y%m%dT%H%M%S";
if ($this->getTZID() == 'UTC') {
$format .= "Z";
}
return $this->format($format);
break;
case DATE_FORMAT_ISO_EXTENDED:
$format = "%Y-%m-%dT%H:%M:%S";
if ($this->getTZID() == 'UTC') {
$format .= "Z";
}
return $this->format($format);
break;
case DATE_FORMAT_ISO_EXTENDED_MICROTIME:
$format = "%Y-%m-%dT%H:%M:%s";
if ($this->getTZID() == 'UTC') {
$format .= "Z";
}
return $this->format($format);
break;
case DATE_FORMAT_TIMESTAMP:
return $this->format("%Y%m%d%H%M%S");
break;
case DATE_FORMAT_UNIXTIME:
// Enter a time in UTC, so use 'gmmktime()' (the alternative
// is to offset additionally by the local time, but the object
// is not necessarily using local time):
//
if ($this->ob_invalidtime)
return $this->_getErrorInvalidTime();
return gmmktime($this->on_standardhour,
$this->on_standardminute,
$this->on_standardsecond,
$this->on_standardmonth,
$this->on_standardday,
$this->on_standardyear) -
$this->tz->getRawOffset() / 1000; // N.B. Unix-time excludes
// leap seconds by
// definition
break;
}
}
// }}}
// {{{ format()
/**
* Date pretty printing, similar to strftime()
*
* Formats the date in the given format, much like
* strftime(). Most strftime() options are supported.<br><br>
*
* Formatting options:<br><br>
*
* <code>%a </code> abbreviated weekday name (Sun, Mon, Tue) <br>
* <code>%A </code> full weekday name (Sunday, Monday, Tuesday) <br>
* <code>%b </code> abbreviated month name (Jan, Feb, Mar) <br>
* <code>%B </code> full month name (January, February, March) <br>
* <code>%C </code> century number (the year divided by 100 and truncated
* to an integer, range 00 to 99) <br>
* <code>%d </code> day of month (range 00 to 31) <br>
* <code>%D </code> equivalent to "%m/%d/%y" <br>
* <code>%e </code> day of month without leading noughts (range 0 to 31) <br>
* <code>%E </code> Julian day - no of days since Monday, 24th November,
* 4714 B.C. (in the proleptic Gregorian calendar) <br>
* <code>%g </code> like %G, but without the century <br>
* <code>%G </code> the 4-digit year corresponding to the ISO week
* number (see %V). This has the same format and value
* as %Y, except that if the ISO week number belongs
* to the previous or next year, that year is used
* instead. <br>
* <code>%h </code> hour as decimal number without leading noughts (0
* to 23) <br>
* <code>%H </code> hour as decimal number (00 to 23) <br>
* <code>%i </code> hour as decimal number on 12-hour clock without
* leading noughts (1 to 12) <br>
* <code>%I </code> hour as decimal number on 12-hour clock (01 to 12) <br>
* <code>%j </code> day of year (range 001 to 366) <br>
* <code>%m </code> month as decimal number (range 01 to 12) <br>
* <code>%M </code> minute as a decimal number (00 to 59) <br>
* <code>%n </code> newline character ("\n") <br>
* <code>%o </code> raw timezone offset expressed as '+/-HH:MM' <br>
* <code>%O </code> dst-corrected timezone offset expressed as '+/-HH:MM' <br>
* <code>%p </code> either 'am' or 'pm' depending on the time <br>
* <code>%P </code> either 'AM' or 'PM' depending on the time <br>
* <code>%r </code> time in am/pm notation; equivalent to "%I:%M:%S %p" <br>
* <code>%R </code> time in 24-hour notation; equivalent to "%H:%M" <br>
* <code>%s </code> seconds including the micro-time (the decimal
* representation less than one second to six decimal
* places<br>
* <code>%S </code> seconds as a decimal number (00 to 59) <br>
* <code>%t </code> tab character ("\t") <br>
* <code>%T </code> current time; equivalent to "%H:%M:%S" <br>
* <code>%u </code> day of week as decimal (1 to 7; where 1 = Monday) <br>
* <code>%U </code> week number of the current year as a decimal
* number, starting with the first Sunday as the first
* day of the first week (i.e. the first full week of
* the year, and the week that contains 7th January)
* (00 to 53) <br>
* <code>%V </code> the ISO 8601:1988 week number of the current year
* as a decimal number, range 01 to 53, where week 1
* is the first week that has at least 4 days in the
* current year, and with Monday as the first day of
* the week. (Use %G or %g for the year component
* that corresponds to the week number for the
* specified timestamp.)
* <code>%w </code> day of week as decimal (0 to 6; where 0 = Sunday) <br>
* <code>%W </code> week number of the current year as a decimal
* number, starting with the first Monday as the first
* day of the first week (i.e. the first full week of
* the year, and the week that contains 7th January)
* (00 to 53) <br>
* <code>%y </code> year as decimal (range 00 to 99) <br>
* <code>%Y </code> year as decimal including century (range 0000 to
* 9999) <br>
* <code>%Z </code> Abbreviated form of time zone name, e.g. 'GMT', or
* the abbreviation for Summer time if the date falls
* in Summer time, e.g. 'BST'. <br>
* <code>%% </code> literal '%' <br>
* <br>
*
* The following codes render a different output to that of 'strftime()':
*
* <code>%e</code> in 'strftime()' a single digit is preceded by a space
* <code>%h</code> in 'strftime()' is equivalent to '%b'
* <code>%U</code> '%U' and '%W' are different in 'strftime()' in that
* if week 1 does not start on 1st January, '00' is
* returned, whereas this function returns '53', that is,
* the week is counted as the last of the previous year.
* <code>%W</code>
*
* @param string $format the format string for returned date/time
*
* @return string date/time in given format
* @access public
*/
function format($format)
{
$output = "";
$hn_isoyear = null;
$hn_isoweek = null;
$hn_isoday = null;
for ($strpos = 0; $strpos < strlen($format); $strpos++) {
$char = substr($format, $strpos, 1);
if ($char == "%") {
$nextchar = substr($format, $strpos + 1, 1);
switch ($nextchar) {
case "a":
$output .= Date_Calc::getWeekdayAbbrname($this->day,
$this->month, $this->year,
$this->getWeekdayAbbrnameLength);
break;
case "A":
$output .= Date_Calc::getWeekdayFullname($this->day,
$this->month, $this->year);
break;
case "b":
$output .= Date_Calc::getMonthAbbrname($this->month);
break;
case "B":
$output .= Date_Calc::getMonthFullname($this->month);
break;
case "C":
$output .= sprintf("%02d", intval($this->year / 100));
break;
case "d":
$output .= sprintf("%02d", $this->day);
break;
case "D":
$output .= sprintf("%02d/%02d/%02d", $this->month,
$this->day, $this->year);
break;
case "e":
$output .= $this->day;
break;
case "E":
$output .= Date_Calc::dateToDays($this->day, $this->month,
$this->year);
break;
case "g":
if (is_null($hn_isoyear))
list($hn_isoyear, $hn_isoweek, $hn_isoday) =
Date_Calc::isoWeekDate($this->day,
$this->month,
$this->year);
$output .= sprintf("%02d", $hn_isoyear % 100);
break;
case "G":
if (is_null($hn_isoyear))
list($hn_isoyear, $hn_isoweek, $hn_isoday) =
Date_Calc::isoWeekDate($this->day,
$this->month,
$this->year);
$output .= sprintf("%04d", $hn_isoyear);
break;
case 'h':
if ($this->ob_invalidtime)
return $this->_getErrorInvalidTime();
$output .= sprintf("%d", $this->hour);
break;
case "H":
if ($this->ob_invalidtime)
return $this->_getErrorInvalidTime();
$output .= sprintf("%02d", $this->hour);
break;
case "i":
case "I":
if ($this->ob_invalidtime)
return $this->_getErrorInvalidTime();
$hour = $this->hour + 1 > 12 ?
$this->hour - 12 :
$this->hour;
$output .= $hour == 0 ?
12 :
($nextchar == "i" ?
$hour :
sprintf('%02d', $hour));
break;
case "j":
$output .= sprintf("%03d",
Date_Calc::dayOfYear($this->day,
$this->month,
$this->year));
break;
case "m":
$output .= sprintf("%02d", $this->month);
break;
case "M":
$output .= sprintf("%02d", $this->minute);
break;
case "n":
$output .= "\n";
break;
case "O":
if ($this->ob_invalidtime)
return $this->_getErrorInvalidTime();
$offms = $this->getTZOffset();
$direction = $offms >= 0 ? "+" : "-";
$offmins = abs($offms) / 1000 / 60;
$hours = $offmins / 60;
$minutes = $offmins % 60;
$output .= sprintf("%s%02d:%02d", $direction, $hours, $minutes);
break;
case "o":
$offms = $this->tz->getRawOffset($this);
$direction = $offms >= 0 ? "+" : "-";
$offmins = abs($offms) / 1000 / 60;
$hours = $offmins / 60;
$minutes = $offmins % 60;
$output .= sprintf("%s%02d:%02d", $direction, $hours, $minutes);
break;
case "p":
if ($this->ob_invalidtime)
return $this->_getErrorInvalidTime();
$output .= $this->hour >= 12 ? "pm" : "am";
break;
case "P":
if ($this->ob_invalidtime)
return $this->_getErrorInvalidTime();
$output .= $this->hour >= 12 ? "PM" : "AM";
break;
case "r":
if ($this->ob_invalidtime)
return $this->_getErrorInvalidTime();
$hour = $this->hour + 1 > 12 ?
$this->hour - 12 :
$this->hour;
$output .= sprintf("%02d:%02d:%02d %s",
$hour == 0 ? 12 : $hour,
$this->minute,
$this->second,
$this->hour >= 12 ? "PM" : "AM");
break;
case "R":
if ($this->ob_invalidtime)
return $this->_getErrorInvalidTime();
$output .= sprintf("%02d:%02d", $this->hour, $this->minute);
break;
case "s":
$output .= str_replace(',',
'.',
sprintf("%09f",
(float)((float) $this->second +
$this->partsecond)));
break;
case "S":
$output .= sprintf("%02d", $this->second);
break;
case "t":
$output .= "\t";
break;
case "T":
if ($this->ob_invalidtime)
return $this->_getErrorInvalidTime();
$output .= sprintf("%02d:%02d:%02d",
$this->hour,
$this->minute,
$this->second);
break;
case "u":
$hn_dayofweek = $this->getDayOfWeek();
$output .= $hn_dayofweek == 0 ? 7 : $hn_dayofweek;
break;
case "U":
$ha_week = Date_Calc::weekOfYear7th($this->day,
$this->month,
$this->year,
0);
$output .= sprintf("%02d", $ha_week[1]);
break;
case "V":
if (is_null($hn_isoyear))
list($hn_isoyear, $hn_isoweek, $hn_isoday) =
Date_Calc::isoWeekDate($this->day,
$this->month,
$this->year);
$output .= $hn_isoweek;
break;
case "w":
$output .= $this->getDayOfWeek();
break;
case "W":
$ha_week = Date_Calc::weekOfYear7th($this->day,
$this->month,
$this->year,
1);
$output .= sprintf("%02d", $ha_week[1]);
break;
case 'y':
$output .= sprintf('%0' .
($this->year < 0 ? '3' : '2') .
'd',
$this->year % 100);
break;
case "Y":
$output .= sprintf('%0' .
($this->year < 0 ? '5' : '4') .
'd',
$this->year);
break;
case "Z":
if ($this->ob_invalidtime)
return $this->_getErrorInvalidTime();
$output .= $this->getTZShortName();
break;
case "%":
$output .= "%";
break;
default:
$output .= $char.$nextchar;
}
$strpos++;
} else {
$output .= $char;
}
}
return $output;
}
// }}}
// {{{ _getOrdinalSuffix()
/**
* Returns appropriate ordinal suffix (i.e. 'th', 'st', 'nd' or 'rd')
*
* @param int $pn_num number with which to determine suffix
* @param bool $pb_uppercase boolean specifying if the suffix should be
* capitalized
*
* @return string
* @access private
* @since Method available since Release 1.5.0
*/
function _getOrdinalSuffix($pn_num, $pb_uppercase = true)
{
switch (($pn_numabs = abs($pn_num)) % 100) {
case 11:
case 12:
case 13:
$hs_suffix = "th";
break;
default:
switch ($pn_numabs % 10) {
case 1:
$hs_suffix = "st";
break;
case 2:
$hs_suffix = "nd";
break;
case 3:
$hs_suffix = "rd";
break;
default:
$hs_suffix = "th";
}
}
return $pb_uppercase ? strtoupper($hs_suffix) : $hs_suffix;
}
// }}}
// {{{ _spellNumber()
/**
* Converts a number to its word representation
*
* Private helper function, particularly for 'format2()'. N.B. The
* second argument is the 'SP' code which can be specified in the
* format string for 'format2()' and is interpreted as follows:
* 'SP' - returns upper-case spelling, e.g. 'FOUR HUNDRED'
* 'Sp' - returns spelling with first character of each word
* capitalized, e.g. 'Four Hundred'
* 'sp' - returns lower-case spelling, e.g. 'four hundred'
*
* @param int $pn_num number to be converted to words
* @param bool $pb_ordinal boolean specifying if the number should
* be ordinal
* @param string $ps_capitalization string for specifying capitalization
* options
* @param string $ps_locale language name abbreviation used for
* formatting numbers as spelled-out words
*
* @return string
* @access private
* @since Method available since Release 1.5.0
*/
function _spellNumber($pn_num,
$pb_ordinal = false,
$ps_capitalization = "SP",
$ps_locale = "en_GB")
{
include_once "Numbers/Words.php";
$hs_words = Numbers_Words::toWords($pn_num, $ps_locale);
if (Pear::isError($hs_words)) {
return $hs_words;
}
if ($pb_ordinal && substr($ps_locale, 0, 2) == "en") {
if (($pn_rem = ($pn_numabs = abs($pn_num)) % 100) == 12) {
$hs_words = substr($hs_words, 0, -2) . "fth";
} else if ($pn_rem >= 11 && $pn_rem <= 15) {
$hs_words .= "th";
} else {
switch ($pn_numabs % 10) {
case 1:
$hs_words = substr($hs_words, 0, -3) . "first";
break;
case 2:
$hs_words = substr($hs_words, 0, -3) . "second";
break;
case 3:
$hs_words = substr($hs_words, 0, -3) . "ird";
break;
case 5:
$hs_words = substr($hs_words, 0, -2) . "fth";
break;
default:
switch (substr($hs_words, -1)) {
case "e":
$hs_words = substr($hs_words, 0, -1) . "th";
break;
case "t":
$hs_words .= "h";
break;
case "y":
$hs_words = substr($hs_words, 0, -1) . "ieth";
break;
default:
$hs_words .= "th";
}
}
}
}
if (($hs_char = substr($ps_capitalization, 0, 1)) ==
strtolower($hs_char)) {
$hb_upper = false;
$hs_words = strtolower($hs_words);
} else if (($hs_char = substr($ps_capitalization, 1, 1)) ==
strtolower($hs_char)) {
$hb_upper = false;
$hs_words = ucwords($hs_words);
} else {
$hb_upper = true;
$hs_words = strtoupper($hs_words);
}
return $hs_words;
}
// }}}
// {{{ _formatNumber()
/**
* Formats a number according to the specified format string
*
* Private helper function, for 'format2()', which interprets the
* codes 'SP' and 'TH' and the combination of the two as follows:
*
* <code>TH</code> Ordinal number
* <code>SP</code> Spelled cardinal number
* <code>SPTH</code> Spelled ordinal number (combination of 'SP' and 'TH'
* in any order)
* <code>THSP</code>
*
* Code 'SP' can have the following three variations (which can also be used
* in combination with 'TH'):
*
* <code>SP</code> returns upper-case spelling, e.g. 'FOUR HUNDRED'
* <code>Sp</code> returns spelling with first character of each word
* capitalized, e.g. 'Four Hundred'
* <code>sp</code> returns lower-case spelling, e.g. 'four hundred'
*
* Code 'TH' can have the following two variations (although in combination
* with code 'SP', the case specification of 'SP' takes precedence):
*
* <code>TH</code> returns upper-case ordinal suffix, e.g. 400TH
* <code>th</code> returns lower-case ordinal suffix, e.g. 400th
*
* N.B. The format string is passed by reference, in order to pass back
* the part of the format string that matches the valid codes 'SP' and
* 'TH'. If none of these are found, then it is set to an empty string;
* If both codes are found then a string is returned with code 'SP'
* preceding code 'TH' (i.e. 'SPTH', 'Spth' or 'spth').
*
* @param int $pn_num integer to be converted to words
* @param string &$ps_format string of formatting codes (max. length 4)
* @param int $pn_numofdigits no of digits to display if displayed as
* numeral (i.e. not spelled out), not
* including the sign (if negative); to
* allow all digits specify 0
* @param bool $pb_nopad boolean specifying whether to suppress
* padding with leading noughts (if displayed
* as numeral)
* @param bool $pb_nosign boolean specifying whether to suppress the
* display of the sign (if negative)
* @param string $ps_locale language name abbreviation used for
* formatting
* @param string $ps_thousandsep optional thousand-separator (e.g. a comma)
* numbers as spelled-out words
* @param int $pn_padtype optional integer to specify padding (if
* displayed as numeral) - can be
* STR_PAD_LEFT or STR_PAD_RIGHT
*
* @return string
* @access private
* @since Method available since Release 1.5.0
*/
function _formatNumber($pn_num,
&$ps_format,
$pn_numofdigits,
$pb_nopad = false,
$pb_nosign = false,
$ps_locale = "en_GB",
$ps_thousandsep = null,
$pn_padtype = STR_PAD_LEFT)
{
$hs_code1 = substr($ps_format, 0, 2);
$hs_code2 = substr($ps_format, 2, 2);
$hs_sp = null;
$hs_th = null;
if (strtoupper($hs_code1) == "SP") {
$hs_sp = $hs_code1;
if (strtoupper($hs_code2) == "TH") {
$hs_th = $hs_code2;
}
} else if (strtoupper($hs_code1) == "TH") {
$hs_th = $hs_code1;
if (strtoupper($hs_code2) == "SP") {
$hs_sp = $hs_code2;
}
}
$hn_absnum = abs($pn_num);
if ($pn_numofdigits > 0 && strlen($hn_absnum) > $pn_numofdigits) {
$hn_absnum = intval(substr($hn_absnum, -$pn_numofdigits));
}
$hs_num = $hn_absnum;
if (!is_null($hs_sp)) {
// Spell out number:
//
$ps_format = $hs_sp .
(is_null($hs_th) ? "" : ($hs_sp == "SP" ? "TH" : "th"));
return $this->_spellNumber(!$pb_nosign && $pn_num < 0 ?
$hn_absnum * -1 :
$hn_absnum,
!is_null($hs_th),
$hs_sp,
$ps_locale);
} else {
// Display number as Arabic numeral:
//
if (!$pb_nopad) {
$hs_num = str_pad($hs_num, $pn_numofdigits, "0", $pn_padtype);
}
if (!is_null($ps_thousandsep)) {
for ($i = strlen($hs_num) - 3; $i > 0; $i -= 3) {
$hs_num = substr($hs_num, 0, $i) .
$ps_thousandsep .
substr($hs_num, $i);
}
}
if (!$pb_nosign) {
if ($pn_num < 0)
$hs_num = "-" . $hs_num;
else if (!$pb_nopad)
$hs_num = " " . $hs_num;
}
if (!is_null($hs_th)) {
$ps_format = $hs_th;
return $hs_num .
$this->_getOrdinalSuffix($pn_num,
substr($hs_th, 0, 1) == "T");
} else {
$ps_format = "";
return $hs_num;
}
}
}
// }}}
// {{{ format2()
/**
* Extended version of 'format()' with variable-length formatting codes
*
* Most codes reproduce the no of digits equal to the length of the code,
* for example, 'YYY' will return the last 3 digits of the year, and so
* the year 2007 will produce '007', and the year 89 will produce '089',
* unless the no-padding code is used as in 'NPYYY', which will return
* '89'.
*
* For negative values, the sign will be discarded, unless the 'S' code
* is used in combination, but note that for positive values the value
* will be padded with a leading space unless it is suppressed with
* the no-padding modifier, for example for 2007:
*
* <code>YYYY</code> returns '2007'
* <code>SYYYY</code> returns ' 2007'
* <code>NPSYYYY</code> returns '2007'
*
* The no-padding modifier 'NP' can be used with numeric codes to
* suppress leading (or trailing in the case of code 'F') noughts, and
* with character-returning codes such as 'DAY' to suppress trailing
* spaces, which will otherwise be padded to the maximum possible length
* of the return-value of the code; for example, for Monday:
*
* <code>Day</code> returns 'Monday ' because the maximum length of
* this code is 'Wednesday';
* <code>NPDay</code> returns 'Monday'
*
* N.B. this code affects the code immediately following only, and
* without this code the default is always to apply padding.
*
* Most character-returning codes, such as 'MONTH', will
* set the capitalization according to the code, so for example:
*
* <code>MONTH</code> returns upper-case spelling, e.g. 'JANUARY'
* <code>Month</code> returns spelling with first character of each word
* capitalized, e.g. 'January'
* <code>month</code> returns lower-case spelling, e.g. 'january'
*
* Where it makes sense, numeric codes can be combined with a following
* 'SP' code which spells out the number, or with a 'TH' code, which
* renders the code as an ordinal ('TH' only works in English), for
* example, for 31st December:
*
* <code>DD</code> returns '31'
* <code>DDTH</code> returns '31ST'
* <code>DDth</code> returns '31st'
* <code>DDSP</code> returns 'THIRTY-ONE'
* <code>DDSp</code> returns 'Thirty-one'
* <code>DDsp</code> returns 'thirty-one'
* <code>DDSPTH</code> returns 'THIRTY-FIRST'
* <code>DDSpth</code> returns 'Thirty-first'
* <code>DDspth</code> returns 'thirty-first'
*
*
* All formatting options:
*
* <code>-</code> All punctuation and white-space is reproduced unchanged
* <code>/</code>
* <code>,</code>
* <code>.</code>
* <code>;</code>
* <code>:</code>
* <code> </code>
* <code>"text"</code> Quoted text is reproduced unchanged (escape using
* '\')
* <code>AD</code> AD indicator with or without full stops; N.B. if you
* are using 'Astronomical' year numbering then 'A.D./B.C.'
* indicators will be out for negative years
* <code>A.D.</code>
* <code>AM</code> Meridian indicator with or without full stops
* <code>A.M.</code>
* <code>BC</code> BC indicator with or without full stops
* <code>B.C.</code>
* <code>BCE</code> BCE indicator with or without full stops
* <code>B.C.E.</code>
* <code>CC</code> Century, i.e. the year divided by 100, discarding the
* remainder; 'S' prefixes negative years with a minus sign
* <code>SCC</code>
* <code>CE</code> CE indicator with or without full stops
* <code>C.E.</code>
* <code>D</code> Day of week (0-6), where 0 represents Sunday
* <code>DAY</code> Name of day, padded with blanks to display width of the
* widest name of day in the locale of the machine
* <code>DD</code> Day of month (1-31)
* <code>DDD</code> Day of year (1-366)
* <code>DY</code> Abbreviated name of day
* <code>FFF</code> Fractional seconds; no radix character is printed. The
* no of 'F's determines the no of digits of the
* part-second to return; e.g. 'HH:MI:SS.FF'
* <code>F[integer]</code> The integer after 'F' specifies the number of
* digits of the part-second to return. This is an
* alternative to using F[integer], and 'F3' is thus
* equivalent to using 'FFF'.
* <code>HH</code> Hour of day (0-23)
* <code>HH12</code> Hour of day (1-12)
* <code>HH24</code> Hour of day (0-23)
* <code>ID</code> Day of week (1-7) based on the ISO standard
* <code>IW</code> Week of year (1-52 or 1-53) based on the ISO standard
* <code>IYYY</code> 4-digit year based on the ISO 8601 standard; 'S'
* prefixes negative years with a minus sign
* <code>SIYYY</code>
* <code>IYY</code> Last 3, 2, or 1 digit(s) of ISO year
* <code>IY</code>
* <code>I</code>
* <code>J</code> Julian day - the number of days since Monday, 24th
* November, 4714 B.C. (proleptic Gregorian calendar)
* <code>MI</code> Minute (0-59)
* <code>MM</code> Month (01-12; January = 01)
* <code>MON</code> Abbreviated name of month
* <code>MONTH</code> Name of month, padded with blanks to display width of
* the widest name of month in the date language used for
* <code>PM</code> Meridian indicator with or without full stops
* <code>P.M.</code>
* <code>Q</code> Quarter of year (1, 2, 3, 4; January - March = 1)
* <code>RM</code> Roman numeral month (I-XII; January = I); N.B. padded
* with leading spaces.
* <code>SS</code> Second (0-59)
* <code>SSSSS</code> Seconds past midnight (0-86399)
* <code>TZC</code> Abbreviated form of time zone name, e.g. 'GMT', or the
* abbreviation for Summer time if the date falls in Summer
* time, e.g. 'BST'.
* N.B. this is not a unique identifier - for this purpose
* use the time zone region (code 'TZR').
* <code>TZH</code> Time zone hour; 'S' prefixes the hour with the correct
* sign, (+/-), which otherwise is not displayed. Note
* that the leading nought can be suppressed with the
* no-padding code 'NP'). Also note that if you combine
* with the 'SP' code, the sign will not be spelled out.
* (I.e. 'STZHSp' will produce '+One', for example, and
* not 'Plus One'.
* 'TZH:TZM' will produce, for example, '+05:30'. (Also
* see 'TZM' format code)
* <code>STZH</code>
* <code>TZI</code> Whether or not the date is in Summer time (daylight
* saving time). Returns '1' if Summer time, else '0'.
* <code>TZM</code> Time zone minute, without any +/- sign. (Also see
* 'TZH' format element)
* <code>TZN</code> Long form of time zone name, e.g.
* 'Greenwich Mean Time', or the name of the Summer time if
* the date falls in Summer time, e.g.
* 'British Summer Time'. N.B. this is not a unique
* identifier - for this purpose use the time zone region
* (code 'TZR').
* <code>TZO</code> Time zone offset in ISO 8601 form - that is, 'Z' if
* UTC, else [+/-][hh]:[mm] (which would be equivalent
* to 'STZH:TZM'). Note that this result is right padded
* with spaces by default, (i.e. if 'Z').
* <code>TZS</code> Time zone offset in seconds; 'S' prefixes negative
* sign with minus sign '-' if negative, and no sign if
* positive (i.e. -43200 to 50400).
* <code>STZS</code>
* <code>TZR</code> Time zone region, that is, the name or ID of the time
* zone e.g. 'Europe/London'. This value is unique for
* each time zone.
* <code>U</code> Seconds since the Unix Epoch -
* January 1 1970 00:00:00 GMT
* <code>W</code> 'Absolute' week of month (1-5), counting week 1 as
* 1st-7th of the year, regardless of the day
* <code>W1</code> Week of year (1-54), counting week 1 as the week that
* contains 1st January
* <code>W4</code> Week of year (1-53), counting week 1 as the week that
* contains 4th January (i.e. first week with at least 4
* days)
* <code>W7</code> Week of year (1-53), counting week 1 as the week that
* contains 7th January (i.e. first full week)
* <code>WW</code> 'Absolute' week of year (1-53), counting week 1 as
* 1st-7th of the year, regardless of the day
* <code>YEAR</code> Year, spelled out; 'S' prefixes negative years with
* 'MINUS'; N.B. 'YEAR' differs from 'YYYYSP' in that the
* first will render 1923, for example, as 'NINETEEN
* TWENTY-THREE, and the second as 'ONE THOUSAND NINE
* HUNDRED TWENTY-THREE'
* <code>SYEAR</code>
* <code>YYYY</code> 4-digit year; 'S' prefixes negative years with a minus
* sign
* <code>SYYYY</code>
* <code>YYY</code> Last 3, 2, or 1 digit(s) of year
* <code>YY</code>
* <code>Y</code>
* <code>Y,YYY</code> Year with thousands-separator in this position; five
* possible separators
* <code>Y.YYY</code>
* <code>Y�YYY</code> N.B. space-dot (mid-dot, interpunct) is valid only in
* ISO 8859-1 (so take care when using UTF-8 in
* particular)
* <code>Y'YYY</code>
* <code>Y YYY</code>
*
* In addition the following codes can be used in combination with other
* codes;
* Codes that modify the next code in the format string:
*
* <code>NP</code> 'No Padding' - Returns a value with no trailing blanks
* and no leading or trailing noughts; N.B. that the
* default is to include this padding in the return string.
* N.B. affects the code immediately following only.
*
* Codes that modify the previous code in the format string (can only
* be used with integral codes such as 'MM'):
*
* <code>TH</code> Ordinal number
* <code>SP</code> Spelled cardinal number
* <code>SPTH</code> Spelled ordinal number (combination of 'SP' and 'TH'
* in any order)
* <code>THSP</code>
*
* Code 'SP' can have the following three variations (which can also be used
* in combination with 'TH'):
*
* <code>SP</code> returns upper-case spelling, e.g. 'FOUR HUNDRED'
* <code>Sp</code> returns spelling with first character of each word
* capitalized, e.g. 'Four Hundred'
* <code>sp</code> returns lower-case spelling, e.g. 'four hundred'
*
* Code 'TH' can have the following two variations (although in combination
* with code 'SP', the case specification of 'SP' takes precedence):
*
* <code>TH</code> returns upper-case ordinal suffix, e.g. 400TH
* <code>th</code> returns lower-case ordinal suffix, e.g. 400th
*
* @param string $ps_format format string for returned date/time
* @param string $ps_locale language name abbreviation used for formatting
* numbers as spelled-out words
*
* @return string date/time in given format
* @access public
* @since Method available since Release 1.5.0
*/
function format2($ps_format, $ps_locale = "en_GB")
{
if (!preg_match('/^("([^"\\\\]|\\\\\\\\|\\\\")*"|(D{1,3}|S?C+|' .
'HH(12|24)?|I[DW]|S?IY*|J|M[IM]|Q|SS(SSS)?|S?TZ[HS]|' .
'TZM|U|W[W147]?|S?Y{1,3}([,.�\' ]?YYY)*)(SP(TH)?|' .
'TH(SP)?)?|AD|A\.D\.|AM|A\.M\.|BCE?|B\.C\.(E\.)?|CE|' .
'C\.E\.|DAY|DY|F(F*|[1-9][0-9]*)|MON(TH)?|NP|PM|' .
'P\.M\.|RM|TZ[CINOR]|S?YEAR|[^A-Z0-9"])*$/i',
$ps_format)) {
return PEAR::raiseError("Invalid date format '$ps_format'",
DATE_ERROR_INVALIDFORMATSTRING);
}
$ret = "";
$i = 0;
$hb_nopadflag = false;
$hb_showsignflag = false;
$hn_weekdaypad = null;
$hn_monthpad = null;
$hn_isoyear = null;
$hn_isoweek = null;
$hn_isoday = null;
$hn_tzoffset = null;
while ($i < strlen($ps_format)) {
$hb_lower = false;
if ($hb_nopadflag) {
$hb_nopad = true;
} else {
$hb_nopad = false;
}
if ($hb_showsignflag) {
$hb_nosign = false;
} else {
$hb_nosign = true;
}
$hb_nopadflag = false;
$hb_showsignflag = false;
switch ($hs_char = substr($ps_format, $i, 1)) {
case "-":
case "/":
case ",":
case ".":
case ";":
case ":":
case " ":
$ret .= $hs_char;
$i += 1;
break;
case "\"":
preg_match('/(([^"\\\\]|\\\\\\\\|\\\\")*)"/',
$ps_format,
$ha_matches,
PREG_OFFSET_CAPTURE,
$i + 1);
$ret .= str_replace(array('\\\\', '\\"'),
array('\\', '"'),
$ha_matches[1][0]);
$i += strlen($ha_matches[0][0]) + 1;
break;
case "a":
$hb_lower = true;
case "A":
if (strtoupper(substr($ps_format, $i, 4)) == "A.D.") {
$ret .= $this->year >= 0 ?
($hb_lower ? "a.d." : "A.D.") :
($hb_lower ? "b.c." : "B.C.");
$i += 4;
} else if (strtoupper(substr($ps_format, $i, 2)) == "AD") {
$ret .= $this->year >= 0 ?
($hb_lower ? "ad" : "AD") :
($hb_lower ? "bc" : "BC");
$i += 2;
} else {
if ($this->ob_invalidtime)
return $this->_getErrorInvalidTime();
if (strtoupper(substr($ps_format, $i, 4)) == "A.M.") {
$ret .= $this->hour < 12 ?
($hb_lower ? "a.m." : "A.M.") :
($hb_lower ? "p.m." : "P.M.");
$i += 4;
} else if (strtoupper(substr($ps_format, $i, 2)) == "AM") {
$ret .= $this->hour < 12 ?
($hb_lower ? "am" : "AM") :
($hb_lower ? "pm" : "PM");
$i += 2;
}
}
break;
case "b":
$hb_lower = true;
case "B":
// Check for 'B.C.E.' first:
//
if (strtoupper(substr($ps_format, $i, 6)) == "B.C.E.") {
if ($this->year >= 0) {
$hs_era = $hb_lower ? "c.e." : "C.E.";
$ret .= $hb_nopad ?
$hs_era :
str_pad($hs_era, 6, " ", STR_PAD_RIGHT);
} else {
$ret .= $hb_lower ? "b.c.e." : "B.C.E.";
}
$i += 6;
} else if (strtoupper(substr($ps_format, $i, 3)) == "BCE") {
if ($this->year >= 0) {
$hs_era = $hb_lower ? "ce" : "CE";
$ret .= $hb_nopad ?
$hs_era :
str_pad($hs_era, 3, " ", STR_PAD_RIGHT);
} else {
$ret .= $hb_lower ? "bce" : "BCE";
}
$i += 3;
} else if (strtoupper(substr($ps_format, $i, 4)) == "B.C.") {
$ret .= $this->year >= 0 ?
($hb_lower ? "a.d." : "A.D.") :
($hb_lower ? "b.c." : "B.C.");
$i += 4;
} else if (strtoupper(substr($ps_format, $i, 2)) == "BC") {
$ret .= $this->year >= 0 ?
($hb_lower ? "ad" : "AD") :
($hb_lower ? "bc" : "BC");
$i += 2;
}
break;
case "c":
$hb_lower = true;
case "C":
if (strtoupper(substr($ps_format, $i, 4)) == "C.E.") {
if ($this->year >= 0) {
$hs_era = $hb_lower ? "c.e." : "C.E.";
$ret .= $hb_nopad ?
$hs_era :
str_pad($hs_era, 6, " ", STR_PAD_RIGHT);
} else {
$ret .= $hb_lower ? "b.c.e." : "B.C.E.";
}
$i += 4;
} else if (strtoupper(substr($ps_format, $i, 2)) == "CE") {
if ($this->year >= 0) {
$hs_era = $hb_lower ? "ce" : "CE";
$ret .= $hb_nopad ?
$hs_era :
str_pad($hs_era, 3, " ", STR_PAD_RIGHT);
} else {
$ret .= $hb_lower ? "bce" : "BCE";
}
$i += 2;
} else {
// Code C(CCC...):
//
$hn_codelen = 1;
while (strtoupper(substr($ps_format,
$i + $hn_codelen,
1)) == "C")
++$hn_codelen;
// Check next code is not 'CE' or 'C.E.'
//
if ($hn_codelen > 1 &&
(strtoupper(substr($ps_format,
$i + $hn_codelen - 1,
4)) == "C.E." ||
strtoupper(substr($ps_format,
$i + $hn_codelen - 1,
2)) == "CE"
))
--$hn_codelen;
$hn_century = intval($this->year / 100);
$hs_numberformat = substr($ps_format, $i + $hn_codelen, 4);
$hs_century = $this->_formatNumber($hn_century,
$hs_numberformat,
$hn_codelen,
$hb_nopad,
$hb_nosign,
$ps_locale);
if (Pear::isError($hs_century))
return $hs_century;
$ret .= $hs_century;
$i += $hn_codelen + strlen($hs_numberformat);
}
break;
case "d":
$hb_lower = true;
case "D":
if (strtoupper(substr($ps_format, $i, 3)) == "DAY") {
$hs_day = Date_Calc::getWeekdayFullname($this->day,
$this->month,
$this->year);
if (!$hb_nopad) {
if (is_null($hn_weekdaypad)) {
// Set week-day padding variable:
//
$hn_weekdaypad = 0;
foreach (Date_Calc::getWeekDays() as $hs_weekday)
$hn_weekdaypad = max($hn_weekdaypad,
strlen($hs_weekday));
}
$hs_day = str_pad($hs_day,
$hn_weekdaypad,
" ",
STR_PAD_RIGHT);
}
$ret .= $hb_lower ?
strtolower($hs_day) :
(substr($ps_format, $i + 1, 1) == "A" ?
strtoupper($hs_day) :
$hs_day);
$i += 3;
} else if (strtoupper(substr($ps_format, $i, 2)) == "DY") {
$hs_day = Date_Calc::getWeekdayAbbrname($this->day,
$this->month,
$this->year);
$ret .= $hb_lower ?
strtolower($hs_day) :
(substr($ps_format, $i + 1, 1) == "Y" ?
strtoupper($hs_day) :
$hs_day);
$i += 2;
} else if (strtoupper(substr($ps_format, $i, 3)) == "DDD" &&
strtoupper(substr($ps_format, $i + 2, 3)) != "DAY" &&
strtoupper(substr($ps_format, $i + 2, 2)) != "DY"
) {
$hn_day = Date_Calc::dayOfYear($this->day,
$this->month,
$this->year);
$hs_numberformat = substr($ps_format, $i + 3, 4);
$hs_day = $this->_formatNumber($hn_day,
$hs_numberformat,
3,
$hb_nopad,
true,
$ps_locale);
if (Pear::isError($hs_day))
return $hs_day;
$ret .= $hs_day;
$i += 3 + strlen($hs_numberformat);
} else if (strtoupper(substr($ps_format, $i, 2)) == "DD" &&
strtoupper(substr($ps_format, $i + 1, 3)) != "DAY" &&
strtoupper(substr($ps_format, $i + 1, 2)) != "DY"
) {
$hs_numberformat = substr($ps_format, $i + 2, 4);
$hs_day = $this->_formatNumber($this->day,
$hs_numberformat,
2,
$hb_nopad,
true,
$ps_locale);
if (Pear::isError($hs_day))
return $hs_day;
$ret .= $hs_day;
$i += 2 + strlen($hs_numberformat);
} else {
// Code 'D':
//
$hn_day = Date_Calc::dayOfWeek($this->day,
$this->month,
$this->year);
$hs_numberformat = substr($ps_format, $i + 1, 4);
$hs_day = $this->_formatNumber($hn_day,
$hs_numberformat,
1,
$hb_nopad,
true,
$ps_locale);
if (Pear::isError($hs_day))
return $hs_day;
$ret .= $hs_day;
$i += 1 + strlen($hs_numberformat);
}
break;
case "f":
case "F":
if ($this->ob_invalidtime)
return $this->_getErrorInvalidTime();
$hn_codelen = 1;
if (is_numeric(substr($ps_format, $i + $hn_codelen, 1))) {
++$hn_codelen;
while (is_numeric(substr($ps_format, $i + $hn_codelen, 1)))
++$hn_codelen;
$hn_partsecdigits = substr($ps_format, $i + 1, $hn_codelen - 1);
} else {
while (strtoupper(substr($ps_format,
$i + $hn_codelen,
1)) == "F")
++$hn_codelen;
// Check next code is not F[numeric]:
//
if ($hn_codelen > 1 &&
is_numeric(substr($ps_format, $i + $hn_codelen, 1)))
--$hn_codelen;
$hn_partsecdigits = $hn_codelen;
}
$hs_partsec = (string) $this->partsecond;
if (preg_match('/^([0-9]+)(\.([0-9]+))?E-([0-9]+)$/i',
$hs_partsec,
$ha_matches)) {
$hs_partsec =
str_repeat("0", $ha_matches[4] - strlen($ha_matches[1])) .
$ha_matches[1] .
$ha_matches[3];
} else {
$hs_partsec = substr($hs_partsec, 2);
}
$hs_partsec = substr($hs_partsec, 0, $hn_partsecdigits);
// '_formatNumber() will not work for this because the
// part-second is an int, and we want it to behave like a float:
//
if ($hb_nopad) {
$hs_partsec = rtrim($hs_partsec, "0");
if ($hs_partsec == "")
$hs_partsec = "0";
} else {
$hs_partsec = str_pad($hs_partsec,
$hn_partsecdigits,
"0",
STR_PAD_RIGHT);
}
$ret .= $hs_partsec;
$i += $hn_codelen;
break;
case "h":
case "H":
if ($this->ob_invalidtime)
return $this->_getErrorInvalidTime();
if (strtoupper(substr($ps_format, $i, 4)) == "HH12") {
$hn_hour = $this->hour % 12;
if ($hn_hour == 0)
$hn_hour = 12;
$hn_codelen = 4;
} else {
// Code 'HH' or 'HH24':
//
$hn_hour = $this->hour;
$hn_codelen = strtoupper(substr($ps_format,
$i,
4)) == "HH24" ? 4 : 2;
}
$hs_numberformat = substr($ps_format, $i + $hn_codelen, 4);
$hs_hour = $this->_formatNumber($hn_hour,
$hs_numberformat,
2,
$hb_nopad,
true,
$ps_locale);
if (Pear::isError($hs_hour))
return $hs_hour;
$ret .= $hs_hour;
$i += $hn_codelen + strlen($hs_numberformat);
break;
case "i":
case "I":
if (is_null($hn_isoyear))
list($hn_isoyear, $hn_isoweek, $hn_isoday) =
Date_Calc::isoWeekDate($this->day,
$this->month,
$this->year);
if (strtoupper(substr($ps_format, $i, 2)) == "ID" &&
strtoupper(substr($ps_format, $i + 1, 3)) != "DAY"
) {
$hs_numberformat = substr($ps_format, $i + 2, 4);
$hs_isoday = $this->_formatNumber($hn_isoday,
$hs_numberformat,
1,
$hb_nopad,
true,
$ps_locale);
if (Pear::isError($hs_isoday))
return $hs_isoday;
$ret .= $hs_isoday;
$i += 2 + strlen($hs_numberformat);
} else if (strtoupper(substr($ps_format, $i, 2)) == "IW") {
$hs_numberformat = substr($ps_format, $i + 2, 4);
$hs_isoweek = $this->_formatNumber($hn_isoweek,
$hs_numberformat,
2,
$hb_nopad,
true,
$ps_locale);
if (Pear::isError($hs_isoweek))
return $hs_isoweek;
$ret .= $hs_isoweek;
$i += 2 + strlen($hs_numberformat);
} else {
// Code I(YYY...):
//
$hn_codelen = 1;
while (strtoupper(substr($ps_format,
$i + $hn_codelen,
1)) == "Y")
++$hn_codelen;
$hs_numberformat = substr($ps_format, $i + $hn_codelen, 4);
$hs_isoyear = $this->_formatNumber($hn_isoyear,
$hs_numberformat,
$hn_codelen,
$hb_nopad,
$hb_nosign,
$ps_locale);
if (Pear::isError($hs_isoyear))
return $hs_isoyear;
$ret .= $hs_isoyear;
$i += $hn_codelen + strlen($hs_numberformat);
}
break;
case "j":
case "J":
$hn_jd = Date_Calc::dateToDays($this->day,
$this->month,
$this->year);
$hs_numberformat = substr($ps_format, $i + 1, 4);
// Allow sign if negative; allow all digits (specify nought);
// suppress padding:
//
$hs_jd = $this->_formatNumber($hn_jd,
$hs_numberformat,
0,
true,
false,
$ps_locale);
if (Pear::isError($hs_jd))
return $hs_jd;
$ret .= $hs_jd;
$i += 1 + strlen($hs_numberformat);
break;
case "m":
$hb_lower = true;
case "M":
if (strtoupper(substr($ps_format, $i, 2)) == "MI") {
if ($this->ob_invalidtime)
return $this->_getErrorInvalidTime();
$hs_numberformat = substr($ps_format, $i + 2, 4);
$hs_minute = $this->_formatNumber($this->minute,
$hs_numberformat,
2,
$hb_nopad,
true,
$ps_locale);
if (Pear::isError($hs_minute))
return $hs_minute;
$ret .= $hs_minute;
$i += 2 + strlen($hs_numberformat);
} else if (strtoupper(substr($ps_format, $i, 2)) == "MM") {
$hs_numberformat = substr($ps_format, $i + 2, 4);
$hs_month = $this->_formatNumber($this->month,
$hs_numberformat,
2,
$hb_nopad,
true,
$ps_locale);
if (Pear::isError($hs_month))
return $hs_month;
$ret .= $hs_month;
$i += 2 + strlen($hs_numberformat);
} else if (strtoupper(substr($ps_format, $i, 5)) == "MONTH") {
$hs_month = Date_Calc::getMonthFullname($this->month);
if (!$hb_nopad) {
if (is_null($hn_monthpad)) {
// Set month padding variable:
//
$hn_monthpad = 0;
foreach (Date_Calc::getMonthNames() as $hs_monthofyear)
$hn_monthpad = max($hn_monthpad,
strlen($hs_monthofyear));
}
$hs_month = str_pad($hs_month,
$hn_monthpad,
" ",
STR_PAD_RIGHT);
}
$ret .= $hb_lower ?
strtolower($hs_month) :
(substr($ps_format, $i + 1, 1) == "O" ?
strtoupper($hs_month) :
$hs_month);
$i += 5;
} else if (strtoupper(substr($ps_format, $i, 3)) == "MON") {
$hs_month = Date_Calc::getMonthAbbrname($this->month);
$ret .= $hb_lower ?
strtolower($hs_month) :
(substr($ps_format, $i + 1, 1) == "O" ?
strtoupper($hs_month) :
$hs_month);
$i += 3;
}
break;
case "n":
case "N":
// No-Padding rule 'NP' applies to the next code (either trailing
// spaces or leading/trailing noughts):
//
$hb_nopadflag = true;
$i += 2;
break;
case "p":
$hb_lower = true;
case "P":
if ($this->ob_invalidtime)
return $this->_getErrorInvalidTime();
if (strtoupper(substr($ps_format, $i, 4)) == "P.M.") {
$ret .= $this->hour < 12 ?
($hb_lower ? "a.m." : "A.M.") :
($hb_lower ? "p.m." : "P.M.");
$i += 4;
} else if (strtoupper(substr($ps_format, $i, 2)) == "PM") {
$ret .= $this->hour < 12 ?
($hb_lower ? "am" : "AM") :
($hb_lower ? "pm" : "PM");
$i += 2;
}
break;
case "q":
case "Q":
// N.B. Current implementation ignores the day and year, but
// it is possible that a different implementation might be
// desired, so pass these parameters anyway:
//
$hn_quarter = Date_Calc::quarterOfYear($this->day,
$this->month,
$this->year);
$hs_numberformat = substr($ps_format, $i + 1, 4);
$hs_quarter = $this->_formatNumber($hn_quarter,
$hs_numberformat,
1,
$hb_nopad,
true,
$ps_locale);
if (Pear::isError($hs_quarter))
return $hs_quarter;
$ret .= $hs_quarter;
$i += 1 + strlen($hs_numberformat);
break;
case "r":
$hb_lower = true;
case "R":
// Code 'RM':
//
switch ($this->month) {
case 1:
$hs_monthroman = "i";
break;
case 2:
$hs_monthroman = "ii";
break;
case 3:
$hs_monthroman = "iii";
break;
case 4:
$hs_monthroman = "iv";
break;
case 5:
$hs_monthroman = "v";
break;
case 6:
$hs_monthroman = "vi";
break;
case 7:
$hs_monthroman = "vii";
break;
case 8:
$hs_monthroman = "viii";
break;
case 9:
$hs_monthroman = "ix";
break;
case 10:
$hs_monthroman = "x";
break;
case 11:
$hs_monthroman = "xi";
break;
case 12:
$hs_monthroman = "xii";
break;
}
$hs_monthroman = $hb_lower ?
$hs_monthroman :
strtoupper($hs_monthroman);
$ret .= $hb_nopad ?
$hs_monthroman :
str_pad($hs_monthroman, 4, " ", STR_PAD_LEFT);
$i += 2;
break;
case "s":
case "S":
// Check for 'SSSSS' before 'SS':
//
if (strtoupper(substr($ps_format, $i, 5)) == "SSSSS") {
if ($this->ob_invalidtime)
return $this->_getErrorInvalidTime();
$hs_numberformat = substr($ps_format, $i + 5, 4);
$hn_second = Date_Calc::secondsPastMidnight($this->hour,
$this->minute,
$this->second);
$hs_second = $this->_formatNumber($hn_second,
$hs_numberformat,
5,
$hb_nopad,
true,
$ps_locale);
if (Pear::isError($hs_second))
return $hs_second;
$ret .= $hs_second;
$i += 5 + strlen($hs_numberformat);
} else if (strtoupper(substr($ps_format, $i, 2)) == "SS") {
if ($this->ob_invalidtime)
return $this->_getErrorInvalidTime();
$hs_numberformat = substr($ps_format, $i + 2, 4);
$hs_second = $this->_formatNumber($this->second,
$hs_numberformat,
2,
$hb_nopad,
true,
$ps_locale);
if (Pear::isError($hs_second))
return $hs_second;
$ret .= $hs_second;
$i += 2 + strlen($hs_numberformat);
} else {
// One of the following codes:
// 'SC(CCC...)'
// 'SY(YYY...)'
// 'SIY(YYY...)'
// 'STZH'
// 'STZS'
// 'SYEAR'
//
$hb_showsignflag = true;
if ($hb_nopad)
$hb_nopadflag = true;
++$i;
}
break;
case "t":
case "T":
// Code TZ[...]:
//
if (strtoupper(substr($ps_format, $i, 3)) == "TZR") {
// This time-zone-related code can be called when the time is
// invalid, but the others should return an error:
//
$ret .= $this->getTZID();
$i += 3;
} else {
if ($this->ob_invalidtime)
return $this->_getErrorInvalidTime();
if (strtoupper(substr($ps_format, $i, 3)) == "TZC") {
$ret .= $this->getTZShortName();
$i += 3;
} else if (strtoupper(substr($ps_format, $i, 3)) == "TZH") {
if (is_null($hn_tzoffset))
$hn_tzoffset = $this->getTZOffset();
$hs_numberformat = substr($ps_format, $i + 3, 4);
$hn_tzh = intval($hn_tzoffset / 3600000);
// Suppress sign here (it is added later):
//
$hs_tzh = $this->_formatNumber($hn_tzh,
$hs_numberformat,
2,
$hb_nopad,
true,
$ps_locale);
if (Pear::isError($hs_tzh))
return $hs_tzh;
// Display sign, even if positive:
//
$ret .= ($hb_nosign ? "" : ($hn_tzh >= 0 ? '+' : '-')) .
$hs_tzh;
$i += 3 + strlen($hs_numberformat);
} else if (strtoupper(substr($ps_format, $i, 3)) == "TZI") {
$ret .= ($this->inDaylightTime() ? '1' : '0');
$i += 3;
} else if (strtoupper(substr($ps_format, $i, 3)) == "TZM") {
if (is_null($hn_tzoffset))
$hn_tzoffset = $this->getTZOffset();
$hs_numberformat = substr($ps_format, $i + 3, 4);
$hn_tzm = intval(($hn_tzoffset % 3600000) / 60000);
// Suppress sign:
//
$hs_tzm = $this->_formatNumber($hn_tzm,
$hs_numberformat,
2,
$hb_nopad,
true,
$ps_locale);
if (Pear::isError($hs_tzm))
return $hs_tzm;
$ret .= $hs_tzm;
$i += 3 + strlen($hs_numberformat);
} else if (strtoupper(substr($ps_format, $i, 3)) == "TZN") {
$ret .= $this->getTZLongName();
$i += 3;
} else if (strtoupper(substr($ps_format, $i, 3)) == "TZO") {
if (is_null($hn_tzoffset))
$hn_tzoffset = $this->getTZOffset();
$hn_tzh = intval(abs($hn_tzoffset) / 3600000);
$hn_tzm = intval((abs($hn_tzoffset) % 3600000) / 60000);
if ($hn_tzoffset == 0) {
$ret .= $hb_nopad ? "Z" : "Z ";
} else {
// Display sign, even if positive:
//
$ret .= ($hn_tzoffset >= 0 ? '+' : '-') .
sprintf("%02d", $hn_tzh) .
":" .
sprintf("%02d", $hn_tzm);
}
$i += 3;
} else if (strtoupper(substr($ps_format, $i, 3)) == "TZS") {
if (is_null($hn_tzoffset))
$hn_tzoffset = $this->getTZOffset();
$hs_numberformat = substr($ps_format, $i + 3, 4);
$hn_tzs = intval($hn_tzoffset / 1000);
$hs_tzs = $this->_formatNumber($hn_tzs,
$hs_numberformat,
5,
$hb_nopad,
$hb_nosign,
$ps_locale);
if (Pear::isError($hs_tzs))
return $hs_tzs;
$ret .= $hs_tzs;
$i += 3 + strlen($hs_numberformat);
}
}
break;
case "u":
case "U":
if ($this->ob_invalidtime)
return $this->_getErrorInvalidTime();
$hn_unixtime = $this->getTime();
$hs_numberformat = substr($ps_format, $i + 1, 4);
// Allow sign if negative; allow all digits (specify nought);
// suppress padding:
//
$hs_unixtime = $this->_formatNumber($hn_unixtime,
$hs_numberformat,
0,
true,
false,
$ps_locale);
if (Pear::isError($hs_unixtime))
return $hs_unixtime;
$ret .= $hs_unixtime;
$i += 1 + strlen($hs_numberformat);
break;
case "w":
case "W":
// Check for 'WW' before 'W':
//
if (strtoupper(substr($ps_format, $i, 2)) == "WW") {
$hn_week = Date_Calc::weekOfYearAbsolute($this->day,
$this->month,
$this->year);
$hs_numberformat = substr($ps_format, $i + 2, 4);
$hs_week = $this->_formatNumber($hn_week,
$hs_numberformat,
2,
$hb_nopad,
true,
$ps_locale);
if (Pear::isError($hs_week))
return $hs_week;
$ret .= $hs_week;
$i += 2 + strlen($hs_numberformat);
} else if (strtoupper(substr($ps_format, $i, 2)) == "W1") {
$hn_week = Date_Calc::weekOfYear1st($this->day,
$this->month,
$this->year);
$hs_numberformat = substr($ps_format, $i + 2, 4);
$hs_week = $this->_formatNumber($hn_week,
$hs_numberformat,
2,
$hb_nopad,
true,
$ps_locale);
if (Pear::isError($hs_week))
return $hs_week;
$ret .= $hs_week;
$i += 2 + strlen($hs_numberformat);
} else if (strtoupper(substr($ps_format, $i, 2)) == "W4") {
$ha_week = Date_Calc::weekOfYear4th($this->day,
$this->month,
$this->year);
$hn_week = $ha_week[1];
$hs_numberformat = substr($ps_format, $i + 2, 4);
$hs_week = $this->_formatNumber($hn_week,
$hs_numberformat,
2,
$hb_nopad,
true,
$ps_locale);
if (Pear::isError($hs_week))
return $hs_week;
$ret .= $hs_week;
$i += 2 + strlen($hs_numberformat);
} else if (strtoupper(substr($ps_format, $i, 2)) == "W7") {
$ha_week = Date_Calc::weekOfYear7th($this->day,
$this->month,
$this->year);
$hn_week = $ha_week[1];
$hs_numberformat = substr($ps_format, $i + 2, 4);
$hs_week = $this->_formatNumber($hn_week,
$hs_numberformat,
2,
$hb_nopad,
true,
$ps_locale);
if (Pear::isError($hs_week))
return $hs_week;
$ret .= $hs_week;
$i += 2 + strlen($hs_numberformat);
} else {
// Code 'W':
//
$hn_week = Date_Calc::weekOfMonthAbsolute($this->day,
$this->month,
$this->year);
$hs_numberformat = substr($ps_format, $i + 1, 4);
$hs_week = $this->_formatNumber($hn_week,
$hs_numberformat,
1,
$hb_nopad,
true,
$ps_locale);
if (Pear::isError($hs_week))
return $hs_week;
$ret .= $hs_week;
$i += 1 + strlen($hs_numberformat);
}
break;
case "y":
case "Y":
// Check for 'YEAR' first:
//
if (strtoupper(substr($ps_format, $i, 4)) == "YEAR") {
switch (substr($ps_format, $i, 2)) {
case "YE":
$hs_spformat = "SP";
break;
case "Ye":
$hs_spformat = "Sp";
break;
default:
$hs_spformat = "sp";
}
if (($hn_yearabs = abs($this->year)) < 100 ||
$hn_yearabs % 100 < 10) {
$hs_numberformat = $hs_spformat;
// Allow all digits (specify nought); padding irrelevant:
//
$hs_year = $this->_formatNumber($this->year,
$hs_numberformat,
0,
true,
$hb_nosign,
$ps_locale);
if (Pear::isError($hs_year))
return $hs_year;
$ret .= $hs_year;
} else {
// Year is spelled 'Nineteen Twelve' rather than
// 'One thousand Nine Hundred Twelve':
//
$hn_century = intval($this->year / 100);
$hs_numberformat = $hs_spformat;
// Allow all digits (specify nought); padding irrelevant:
//
$hs_century = $this->_formatNumber($hn_century,
$hs_numberformat,
0,
true,
$hb_nosign,
$ps_locale);
if (Pear::isError($hs_century))
return $hs_century;
$ret .= $hs_century . " ";
$hs_numberformat = $hs_spformat;
// Discard sign; padding irrelevant:
//
$hs_year = $this->_formatNumber($this->year,
$hs_numberformat,
2,
false,
true,
$ps_locale);
if (Pear::isError($hs_year))
return $hs_year;
$ret .= $hs_year;
}
$i += 4;
} else {
// Code Y(YYY...):
//
$hn_codelen = 1;
while (strtoupper(substr($ps_format,
$i + $hn_codelen,
1)) == "Y")
++$hn_codelen;
$hs_thousandsep = null;
$hn_thousandseps = 0;
if ($hn_codelen <= 3) {
while (preg_match('/([,.�\' ])YYY/i',
substr($ps_format,
$i + $hn_codelen,
4),
$ha_matches)) {
$hn_codelen += 4;
$hs_thousandsep = $ha_matches[1];
++$hn_thousandseps;
}
}
// Check next code is not 'YEAR'
//
if ($hn_codelen > 1 &&
strtoupper(substr($ps_format,
$i + $hn_codelen - 1,
4)) == "YEAR")
--$hn_codelen;
$hs_numberformat = substr($ps_format, $i + $hn_codelen, 4);
$hs_year = $this->_formatNumber($this->year,
$hs_numberformat,
$hn_codelen -
$hn_thousandseps,
$hb_nopad,
$hb_nosign,
$ps_locale,
$hs_thousandsep);
if (Pear::isError($hs_year))
return $hs_year;
$ret .= $hs_year;
$i += $hn_codelen + strlen($hs_numberformat);
}
break;
default:
$ret .= $hs_char;
++$i;
break;
}
}
return $ret;
}
// }}}
// {{{ format3()
/**
* Formats the date in the same way as 'format()', but using the
* formatting codes used by the PHP function 'date()'
*
* All 'date()' formatting options are supported except 'B'. This
* function also responds to the DATE_* constants, such as DATE_COOKIE,
* which are specified at:
*
* http://www.php.net/manual/en/ref.datetime.php#datetime.constants
*
*
* Formatting options:
*
* (Day)
*
* <code>d</code> Day of the month, 2 digits with leading zeros (01 to 31)
* <code>D</code> A textual representation of a day, three letters ('Mon'
* to 'Sun')
* <code>j</code> Day of the month without leading zeros (1 to 31)
* <code>l</code> [lowercase 'L'] A full textual representation of the day
* of the week ('Sunday' to 'Saturday')
* <code>N</code> ISO-8601 numeric representation of the day of the week
* (1 (for Monday) to 7 (for Sunday))
* <code>S</code> English ordinal suffix for the day of the month, 2
* characters ('st', 'nd', 'rd' or 'th')
* <code>w</code> Numeric representation of the day of the week (0 (for
* Sunday) to 6 (for Saturday))
* <code>z</code> The day of the year, starting from 0 (0 to 365)
*
* (Week)
*
* <code>W</code> ISO-8601 week number of year, weeks starting on Monday
* (00 to 53)
*
* (Month)
*
* <code>F</code> A full textual representation of a month ('January' to
* 'December')
* <code>m</code> Numeric representation of a month, with leading zeros
* (01 to 12)
* <code>M</code> A short textual representation of a month, three letters
* ('Jan' to 'Dec')
* <code>n</code> Numeric representation of a month, without leading zeros
* (1 to 12)
* <code>t</code> Number of days in the given month (28 to 31)
*
* (Year)
*
* <code>L</code> Whether it is a leap year (1 if it is a leap year, 0
* otherwise)
* <code>o</code> ISO-8601 year number. This has the same value as Y,
* except that if the ISO week number (W) belongs to the
* previous or next year, that year is used instead.
* <code>Y</code> A full numeric representation of a year, 4 digits (0000
* to 9999)
* <code>y</code> A two digit representation of a year (00 to 99)
*
* (Time)
*
* <code>a</code> Lowercase Ante meridiem and Post meridiem ('am' or
* 'pm')
* <code>A</code> Uppercase Ante meridiem and Post meridiem ('AM' or
* 'PM')
* <code>g</code> 12-hour format of an hour without leading zeros (1 to 12)
* <code>G</code> 24-hour format of an hour without leading zeros (0 to 23)
* <code>h</code> 12-hour format of an hour with leading zeros (01 to 12)
* <code>H</code> 24-hour format of an hour with leading zeros (00 to 23)
* <code>i</code> Minutes with leading zeros (00 to 59)
* <code>s</code> Seconds, with leading zeros (00 to 59)
* <code>u</code> Milliseconds, e.g. '54321'
*
* (Time Zone)
*
* <code>e</code> Timezone identifier, e.g. Europe/London
* <code>I</code> Whether or not the date is in Summer time (1 if Summer
* time, 0 otherwise)
* <code>O</code> Difference to Greenwich time (GMT) in hours, e.g. '+0200'
* <code>P</code> Difference to Greenwich time (GMT) with colon between
* hours and minutes, e.g. '+02:00'
* <code>T</code> Timezone abbreviation, e.g. 'GMT', 'EST'
* <code>Z</code> Timezone offset in seconds. The offset for timezones west
* of UTC is always negative, and for those east of UTC is
* always positive. (-43200 to 50400)
*
* (Full Date/Time)
*
* <code>c</code> ISO 8601 date, e.g. '2004-02-12T15:19:21+00:00'
* <code>r</code> RFC 2822 formatted date, e.g.
* 'Thu, 21 Dec 2000 16:01:07 +0200'
* <code>U</code> Seconds since the Unix Epoch
* (January 1 1970 00:00:00 GMT)
*
* @param string $ps_format the format string for returned date/time
*
* @return string date/time in given format
* @access public
* @since Method available since Release 1.5.0
*/
function format3($ps_format)
{
$hs_format2str = "";
for ($i = 0; $i < strlen($ps_format); ++$i) {
switch ($hs_char = substr($ps_format, $i, 1)) {
case 'd':
$hs_format2str .= 'DD';
break;
case 'D':
$hs_format2str .= 'NPDy';
break;
case 'j':
$hs_format2str .= 'NPDD';
break;
case 'l':
$hs_format2str .= 'NPDay';
break;
case 'N':
$hs_format2str .= 'ID';
break;
case 'S':
$hs_format2str .= 'th';
break;
case 'w':
$hs_format2str .= 'D';
break;
case 'z':
$hs_format2str .= '"' . ($this->getDayOfYear() - 1) . '"';
break;
case 'W':
$hs_format2str .= 'IW';
break;
case 'F':
$hs_format2str .= 'NPMonth';
break;
case 'm':
$hs_format2str .= 'MM';
break;
case 'M':
$hs_format2str .= 'NPMon';
break;
case 'n':
$hs_format2str .= 'NPMM';
break;
case 't':
$hs_format2str .= '"' . $this->getDaysInMonth() . '"';
break;
case 'L':
$hs_format2str .= '"' . ($this->isLeapYear() ? 1 : 0) . '"';
break;
case 'o':
$hs_format2str .= 'IYYY';
break;
case 'Y':
$hs_format2str .= 'YYYY';
break;
case 'y':
$hs_format2str .= 'YY';
break;
case 'a':
$hs_format2str .= 'am';
break;
case 'A':
$hs_format2str .= 'AM';
break;
case 'g':
$hs_format2str .= 'NPHH12';
break;
case 'G':
$hs_format2str .= 'NPHH24';
break;
case 'h':
$hs_format2str .= 'HH12';
break;
case 'H':
$hs_format2str .= 'HH24';
break;
case 'i':
$hs_format2str .= 'MI';
break;
case 's':
$hs_format2str .= 'SS';
break;
case 'u':
$hs_format2str .= 'SSFFF';
break;
case 'e':
$hs_format2str .= 'TZR';
break;
case 'I':
$hs_format2str .= 'TZI';
break;
case 'O':
$hs_format2str .= 'STZHTZM';
break;
case 'P':
$hs_format2str .= 'STZH:TZM';
break;
case 'T':
$hs_format2str .= 'TZC';
break;
case 'Z':
$hs_format2str .= 'TZS';
break;
case 'c':
$hs_format2str .= 'YYYY-MM-DD"T"HH24:MI:SSSTZH:TZM';
break;
case 'r':
$hs_format2str .= 'Dy, DD Mon YYYY HH24:MI:SS STZHTZM';
break;
case 'U':
$hs_format2str .= 'U';
break;
case '\\':
$hs_char = substr($ps_format, ++$i, 1);
$hs_format2str .= '"' . ($hs_char == '\\' ? '\\\\' : $hs_char) . '"';
break;
case '"':
$hs_format2str .= '"\\""';
break;
default:
$hs_format2str .= '"' . $hs_char . '"';
}
}
$ret = $this->format2($hs_format2str);
if (PEAR::isError($ret) &&
$ret->getCode() == DATE_ERROR_INVALIDFORMATSTRING) {
return PEAR::raiseError("Invalid date format '$ps_format'",
DATE_ERROR_INVALIDFORMATSTRING);
}
return $ret;
}
// }}}
// {{{ getTime()
/**
* Returns the date/time in Unix time() format
*
* Returns a representation of this date in Unix time() format. This may
* only be valid for dates from 1970 to ~2038.
*
* @return int number of seconds since the unix epoch
* @access public
*/
function getTime()
{
return $this->getDate(DATE_FORMAT_UNIXTIME);
}
// }}}
// {{{ getTZID()
/**
* Returns the unique ID of the time zone, e.g. 'America/Chicago'
*
* @return string the time zone ID
* @access public
* @since Method available since Release 1.5.0
*/
function getTZID()
{
return $this->tz->getID();
}
// }}}
// {{{ _setTZToDefault()
/**
* sets time zone to the default time zone
*
* If PHP version >= 5.1.0, uses the php.ini configuration directive
* 'date.timezone' if set and valid, else the value returned by
* 'date("e")' if valid, else the default specified if the global
* constant '$GLOBALS["_DATE_TIMEZONE_DEFAULT"]', which if itself
* left unset, defaults to "UTC".
*
* N.B. this is a private method; to set the time zone to the
* default publicly you should call 'setTZByID()', that is, with no
* parameter (or a parameter of null).
*
* @return void
* @access private
* @since Method available since Release 1.5.0
*/
function _setTZToDefault()
{
if (function_exists('version_compare') &&
version_compare(phpversion(), "5.1.0", ">=") &&
(Date_TimeZone::isValidID($hs_id = ini_get("date.timezone")) ||
Date_TimeZone::isValidID($hs_id = date("e"))
)
) {
$this->tz = new Date_TimeZone($hs_id);
} else {
$this->tz = Date_TimeZone::getDefault();
}
}
// }}}
// {{{ setTZ()
/**
* Sets the time zone of this Date
*
* Sets the time zone of this date with the given
* Date_TimeZone object. Does not alter the date/time,
* only assigns a new time zone. For conversion, use
* convertTZ().
*
* @param object $tz the Date_TimeZone object to use. If called with a
* parameter that is not a Date_TimeZone object, will
* fall through to setTZByID().
*
* @return void
* @access public
* @see Date::setTZByID()
*/
function setTZ($tz)
{
if (is_a($tz, 'Date_Timezone')) {
$this->setTZByID($tz->getID());
} else {
$res = $this->setTZByID($tz);
if (PEAR::isError($res))
return $res;
}
}
// }}}
// {{{ setTZByID()
/**
* Sets the time zone of this date with the given time zone ID
*
* The time zone IDs are drawn from the 'tz data-base' (see
* http://en.wikipedia.org/wiki/Zoneinfo), which is the de facto
* internet and IT standard. (There is no official standard, and
* the tz data-base is not intended to be a regulating body
* anyway.) Lists of valid IDs are maintained at:
*
* http://en.wikipedia.org/wiki/List_of_zoneinfo_timezones
* http://www.php.net/manual/en/timezones.php
*
* If no time-zone is specified and PHP version >= 5.1.0, the time
* zone is set automatically to the php.ini configuration directive
* 'date.timezone' if set and valid, else the value returned by
* 'date("e")' if valid, else the default specified if the global
* constant '$GLOBALS["_DATE_TIMEZONE_DEFAULT"]', which if itself
* left unset, defaults to "UTC".
*
* N.B. this function preserves the local date and time, that is,
* whether in local Summer time or local standard time. For example,
* if the time is set to 11.00 Summer time, and the time zone is then
* set to another time zone, using this function, in which the date
* falls in standard time, then the time will remain set to 11.00 UTC,
* and not 10.00. You can convert a date to another time zone by
* calling 'convertTZ()'.
*
* The ID can also be specified as a UTC offset in one of the following
* forms, i.e. an offset with no geographical or political base:
*
* UTC[+/-][h] - e.g. UTC-1 (the preferred form)
* UTC[+/-][hh] - e.g. UTC+03
* UTC[+/-][hh][mm] - e.g. UTC-0530
* UTC[+/-][hh]:[mm] - e.g. UTC+03:00
*
* N.B. 'UTC' seems to be technically preferred over 'GMT'. GMT-based
* IDs still exist in the tz data-base, but beware of POSIX-style
* offsets which are the opposite way round to what people normally
* expect.
*
* @param string $ps_id a valid time zone id, e.g. 'Europe/London'
*
* @return void
* @access public
* @see Date::convertTZByID(), Date_TimeZone::isValidID(),
* Date_TimeZone::Date_TimeZone()
*/
function setTZByID($ps_id = null)
{
// Whether the date is in Summer time forms the default for
// the new time zone (if needed, which is very unlikely anyway).
// This is mainly to prevent unexpected (defaulting) behaviour
// if the user is in the repeated hour, and switches to a time
// zone that is also in the repeated hour (e.g. 'Europe/London'
// and 'Europe/Lisbon').
//
$hb_insummertime = $this->inDaylightTime();
if (PEAR::isError($hb_insummertime)) {
if ($hb_insummertime->getCode() == DATE_ERROR_INVALIDTIME) {
$hb_insummertime = false;
} else {
return $hb_insummertime;
}
}
if (is_null($ps_id)) {
$this->_setTZToDefault();
} else if (Date_TimeZone::isValidID($ps_id)) {
$this->tz = new Date_TimeZone($ps_id);
} else {
return PEAR::raiseError("Invalid time zone ID '$ps_id'",
DATE_ERROR_INVALIDTIMEZONE);
}
$this->setLocalTime($this->day,
$this->month,
$this->year,
$this->hour,
$this->minute,
$this->second,
$this->partsecond,
$hb_insummertime);
}
// }}}
// {{{ getTZLongName()
/**
* Returns the long name of the time zone
*
* Returns long form of time zone name, e.g. 'Greenwich Mean Time'.
* N.B. if the date falls in Summer time, the Summer time name will be
* returned instead, e.g. 'British Summer Time'.
*
* N.B. this is not a unique identifier for the time zone - for this
* purpose use the time zone ID.
*
* @return string the long name of the time zone
* @access public
* @since Method available since Release 1.5.0
*/
function getTZLongName()
{
if ($this->ob_invalidtime)
return $this->_getErrorInvalidTime();
return $this->tz->getLongName($this->inDaylightTime());
}
// }}}
// {{{ getTZShortName()
/**
* Returns the short name of the time zone
*
* Returns abbreviated form of time zone name, e.g. 'GMT'. N.B. if the
* date falls in Summer time, the Summer time name will be returned
* instead, e.g. 'BST'.
*
* N.B. this is not a unique identifier - for this purpose use the
* time zone ID.
*
* @return string the short name of the time zone
* @access public
* @since Method available since Release 1.5.0
*/
function getTZShortName()
{
if ($this->ob_invalidtime)
return $this->_getErrorInvalidTime();
return $this->tz->getShortName($this->inDaylightTime());
}
// }}}
// {{{ getTZOffset()
/**
* Returns the DST-corrected offset from UTC for the given date
*
* Gets the offset to UTC for a given date/time, taking into
* account daylight savings time, if the time zone observes it and if
* it is in effect.
*
* N.B. that the offset is calculated historically
* and in the future according to the current Summer time rules,
* and so this function is proleptically correct, but not necessarily
* historically correct. (Although if you want to be correct about
* times in the distant past, this class is probably not for you
* because the whole notion of time zones does not apply, and
* historically there are so many time zone changes, Summer time
* rule changes, name changes, calendar changes, that calculating
* this sort of information is beyond the scope of this package
* altogether.)
*
* @return int the corrected offset to UTC in milliseconds
* @access public
* @since Method available since Release 1.5.0
*/
function getTZOffset()
{
if ($this->ob_invalidtime)
return $this->_getErrorInvalidTime();
return $this->tz->getOffset($this->inDaylightTime());
}
// }}}
// {{{ inDaylightTime()
/**
* Tests if this date/time is in DST
*
* Returns true if daylight savings time is in effect for
* this date in this date's time zone.
*
* @param bool $pb_repeatedhourdefault value to return if repeated hour is
* specified (defaults to false)
*
* @return boolean true if DST is in effect for this date
* @access public
*/
function inDaylightTime($pb_repeatedhourdefault = false)
{
if (!$this->tz->hasDaylightTime())
return false;
if ($this->ob_invalidtime)
return $this->_getErrorInvalidTime();
// The return value is 'cached' whenever the date/time is set:
//
return $this->hour != $this->on_standardhour ||
$this->minute != $this->on_standardminute ||
$this->second != $this->on_standardsecond ||
$this->partsecond != $this->on_standardpartsecond ||
$this->day != $this->on_standardday ||
$this->month != $this->on_standardmonth ||
$this->year != $this->on_standardyear;
//
// (these last 3 conditions are theoretical
// possibilities but normally will never occur)
}
// }}}
// {{{ convertTZ()
/**
* Converts this date to a new time zone
*
* Previously this might not have worked correctly if your system did
* not allow putenv() or if localtime() did not work in your
* environment, but this implementation is no longer used.
*
* @param object $tz Date_TimeZone object to convert to
*
* @return void
* @access public
* @see Date::convertTZByID()
*/
function convertTZ($tz)
{
if ($this->getTZID() == $tz->getID())
return;
if ($this->ob_invalidtime)
return $this->_getErrorInvalidTime();
$hn_rawoffset = $tz->getRawOffset() - $this->tz->getRawOffset();
//$hn_rawoffset = $tz->getOffset($tz->inDaylightTime($this)) - $this->tz->getRawOffset();
$this->tz = new Date_TimeZone($tz->getID());
list($hn_standardyear,
$hn_standardmonth,
$hn_standardday,
$hn_standardhour,
$hn_standardminute,
$hn_standardsecond,
$hn_standardpartsecond) =
$this->_addOffset($hn_rawoffset,
$this->on_standardday,
$this->on_standardmonth,
$this->on_standardyear,
$this->on_standardhour,
$this->on_standardminute,
$this->on_standardsecond,
$this->on_standardpartsecond);
$this->setStandardTime($hn_standardday,
$hn_standardmonth,
$hn_standardyear,
$hn_standardhour,
$hn_standardminute,
$hn_standardsecond,
$hn_standardpartsecond);
}
// }}}
// {{{ toUTC()
/**
* Converts this date to UTC and sets this date's timezone to UTC
*
* @return void
* @access public
*/
function toUTC()
{
if ($this->getTZID() == "UTC")
return;
if ($this->ob_invalidtime)
return $this->_getErrorInvalidTime();
$res = $this->convertTZ(new Date_TimeZone("UTC"));
if (PEAR::isError($res))
return $res;
}
// }}}
// {{{ convertTZByID()
/**
* Converts this date to a new time zone, given a valid time zone ID
*
* Previously this might not have worked correctly if your system did
* not allow putenv() or if localtime() does not work in your
* environment, but this implementation is no longer used.
*
* @param string $ps_id a valid time zone id, e.g. 'Europe/London'
*
* @return void
* @access public
* @see Date::setTZByID(), Date_TimeZone::isValidID(),
* Date_TimeZone::Date_TimeZone()
*/
function convertTZByID($ps_id)
{
if (!Date_TimeZone::isValidID($ps_id)) {
return PEAR::raiseError("Invalid time zone ID '$ps_id'",
DATE_ERROR_INVALIDTIMEZONE);
}
$res = $this->convertTZ(new Date_TimeZone($ps_id));
if (PEAR::isError($res))
return $res;
}
// }}}
// {{{ toUTCbyOffset()
/**
* Converts the date/time to UTC by the offset specified
*
* This function is no longer called from within the Date class
* itself because a time zone can be set using a pure offset
* (e.g. UTC+1), i.e. not a geographical time zone. However
* it is retained for backwards compaibility.
*
* @param string $ps_offset offset of the form '[+/-][hh]:[mm]',
* '[+/-][hh][mm]', or 'Z'
*
* @return bool
* @access private
*/
function toUTCbyOffset($ps_offset)
{
if ($ps_offset == "Z" ||
preg_match('/^[+\-](00:?00|0{1,2})$/', $ps_offset)) {
$hs_tzid = "UTC";
} else if (preg_match('/^[+\-]([0-9]{2,2}:?[0-5][0-9]|[0-9]{1,2})$/',
$ps_offset)) {
$hs_tzid = "UTC" . $ps_offset;
} else {
return PEAR::raiseError("Invalid offset '$ps_offset'");
}
// If the time is invalid, it does not matter here:
//
$this->setTZByID($hs_tzid);
// Now the time will be valid because it is a time zone that
// does not observe Summer time:
//
$this->toUTC();
}
// }}}
// {{{ addYears()
/**
* Converts the date to the specified no of years from the given date
*
* To subtract years use a negative value for the '$pn_years'
* parameter
*
* @param int $pn_years years to add
*
* @return void
* @access public
* @since Method available since Release 1.5.0
*/
function addYears($pn_years)
{
list($hs_year, $hs_month, $hs_day) =
explode(" ", Date_Calc::addYears($pn_years,
$this->day,
$this->month,
$this->year,
"%Y %m %d"));
$this->setLocalTime($hs_day,
$hs_month,
$hs_year,
$this->hour,
$this->minute,
$this->second,
$this->partsecond);
}
// }}}
// {{{ addMonths()
/**
* Converts the date to the specified no of months from the given date
*
* To subtract months use a negative value for the '$pn_months'
* parameter
*
* @param int $pn_months months to add
*
* @return void
* @access public
* @since Method available since Release 1.5.0
*/
function addMonths($pn_months)
{
list($hs_year, $hs_month, $hs_day) =
explode(" ", Date_Calc::addMonths($pn_months,
$this->day,
$this->month,
$this->year,
"%Y %m %d"));
$this->setLocalTime($hs_day,
$hs_month,
$hs_year,
$this->hour,
$this->minute,
$this->second,
$this->partsecond);
}
// }}}
// {{{ addDays()
/**
* Converts the date to the specified no of days from the given date
*
* To subtract days use a negative value for the '$pn_days' parameter
*
* @param int $pn_days days to add
*
* @return void
* @access public
* @since Method available since Release 1.5.0
*/
function addDays($pn_days)
{
list($hs_year, $hs_month, $hs_day) =
explode(" ", Date_Calc::addDays($pn_days,
$this->day,
$this->month,
$this->year,
"%Y %m %d"));
$this->setLocalTime($hs_day,
$hs_month,
$hs_year,
$this->hour,
$this->minute,
$this->second,
$this->partsecond);
}
// }}}
// {{{ addHours()
/**
* Converts the date to the specified no of hours from the given date
*
* To subtract hours use a negative value for the '$pn_hours' parameter
*
* @param int $pn_hours hours to add
*
* @return void
* @access public
* @since Method available since Release 1.5.0
*/
function addHours($pn_hours)
{
if ($this->ob_invalidtime)
return $this->_getErrorInvalidTime();
list($hn_standardyear,
$hn_standardmonth,
$hn_standardday,
$hn_standardhour) =
Date_Calc::addHours($pn_hours,
$this->on_standardday,
$this->on_standardmonth,
$this->on_standardyear,
$this->on_standardhour);
$this->setStandardTime($hn_standardday,
$hn_standardmonth,
$hn_standardyear,
$hn_standardhour,
$this->on_standardminute,
$this->on_standardsecond,
$this->on_standardpartsecond);
}
// }}}
// {{{ addMinutes()
/**
* Converts the date to the specified no of minutes from the given date
*
* To subtract minutes use a negative value for the '$pn_minutes' parameter
*
* @param int $pn_minutes minutes to add
*
* @return void
* @access public
* @since Method available since Release 1.5.0
*/
function addMinutes($pn_minutes)
{
if ($this->ob_invalidtime)
return $this->_getErrorInvalidTime();
list($hn_standardyear,
$hn_standardmonth,
$hn_standardday,
$hn_standardhour,
$hn_standardminute) =
Date_Calc::addMinutes($pn_minutes,
$this->on_standardday,
$this->on_standardmonth,
$this->on_standardyear,
$this->on_standardhour,
$this->on_standardminute);
$this->setStandardTime($hn_standardday,
$hn_standardmonth,
$hn_standardyear,
$hn_standardhour,
$hn_standardminute,
$this->on_standardsecond,
$this->on_standardpartsecond);
}
// }}}
// {{{ addSeconds()
/**
* Adds a given number of seconds to the date
*
* @param mixed $sec the no of seconds to add as integer or float
* @param bool $pb_countleap whether to count leap seconds (defaults to
* value of count-leap-second object property)
*
* @return void
* @access public
*/
function addSeconds($sec, $pb_countleap = null)
{
if ($this->ob_invalidtime)
return $this->_getErrorInvalidTime();
if (!is_int($sec) && !is_float($sec))
settype($sec, 'int');
if (!is_null($pb_countleap))
$pb_countleap = $this->ob_countleapseconds;
if ($pb_countleap) {
// Convert to UTC:
//
list($hn_standardyear,
$hn_standardmonth,
$hn_standardday,
$hn_standardhour,
$hn_standardminute,
$hn_standardsecond,
$hn_standardpartsecond) =
$this->_addOffset($this->tz->getRawOffset() * -1,
$this->on_standardday,
$this->on_standardmonth,
$this->on_standardyear,
$this->on_standardhour,
$this->on_standardminute,
$this->on_standardsecond,
$this->on_standardpartsecond);
list($hn_standardyear,
$hn_standardmonth,
$hn_standardday,
$hn_standardhour,
$hn_standardminute,
$hn_secondraw) =
Date_Calc::addSeconds($sec,
$hn_standardday,
$hn_standardmonth,
$hn_standardyear,
$hn_standardhour,
$hn_standardminute,
$hn_standardpartsecond == 0.0 ?
$hn_standardsecond :
$hn_standardsecond +
$hn_standardpartsecond,
$pb_countleap);
if (is_float($hn_secondraw)) {
$hn_standardsecond = intval($hn_secondraw);
$hn_standardpartsecond = $hn_secondraw - $hn_standardsecond;
} else {
$hn_standardsecond = $hn_secondraw;
$hn_standardpartsecond = 0.0;
}
list($hn_standardyear,
$hn_standardmonth,
$hn_standardday,
$hn_standardhour,
$hn_standardminute,
$hn_standardsecond,
$hn_standardpartsecond) =
$this->_addOffset($this->tz->getRawOffset(),
$hn_standardday,
$hn_standardmonth,
$hn_standardyear,
$hn_standardhour,
$hn_standardminute,
$hn_standardsecond,
$hn_standardpartsecond);
} else {
// Use local standard time:
//
list($hn_standardyear,
$hn_standardmonth,
$hn_standardday,
$hn_standardhour,
$hn_standardminute,
$hn_secondraw) =
Date_Calc::addSeconds($sec,
$this->on_standardday,
$this->on_standardmonth,
$this->on_standardyear,
$this->on_standardhour,
$this->on_standardminute,
$this->on_standardpartsecond == 0.0 ?
$this->on_standardsecond :
$this->on_standardsecond +
$this->on_standardpartsecond,
false);
if (is_float($hn_secondraw)) {
$hn_standardsecond = intval($hn_secondraw);
$hn_standardpartsecond = $hn_secondraw - $hn_standardsecond;
} else {
$hn_standardsecond = $hn_secondraw;
$hn_standardpartsecond = 0.0;
}
}
$this->setStandardTime($hn_standardday,
$hn_standardmonth,
$hn_standardyear,
$hn_standardhour,
$hn_standardminute,
$hn_standardsecond,
$hn_standardpartsecond);
}
// }}}
// {{{ subtractSeconds()
/**
* Subtracts a given number of seconds from the date
*
* @param mixed $sec the no of seconds to subtract as integer or
* float
* @param bool $pb_countleap whether to count leap seconds (defaults to
* value of count-leap-second object property)
*
* @return void
* @access public
*/
function subtractSeconds($sec, $pb_countleap = null)
{
if (is_null($pb_countleap))
$pb_countleap = $this->ob_countleapseconds;
$res = $this->addSeconds(-$sec, $pb_countleap);
if (PEAR::isError($res))
return $res;
}
// }}}
// {{{ addSpan()
/**
* Adds a time span to the date
*
* A time span is defined as a unsigned no of days, hours, minutes
* and seconds, where the no of minutes and seconds must be less than
* 60, and the no of hours must be less than 24.
*
* A span is added (and subtracted) according to the following logic:
*
* Hours, minutes and seconds are added such that if they fall over
* a leap second, the leap second is ignored, and not counted.
* For example, if a leap second occurred at 23.59.60, the
* following calculations:
*
* 23.59.59 + one second
* 23.59.00 + one minute
* 23.00.00 + one hour
*
* would all produce 00.00.00 the next day.
*
* A day is treated as equivalent to 24 hours, so if the clocks
* went backwards at 01.00, and one day was added to the time
* 00.30, the result would be 23.30 the same day.
*
* This is the implementation which is thought to yield the behaviour
* that the user is most likely to expect, or in another way of
* looking at it, it is the implementation that produces the least
* unexpected behaviour. It basically works in hours, that is, a day
* is treated as exactly equivalent to 24 hours, and minutes and
* seconds are treated as equivalent to 1/60th and 1/3600th of an
* hour. It should be obvious that working in days is impractical;
* working in seconds is problematic when it comes to adding days
* that fall over leap seconds, where it would appear to most users
* that the function adds only 23 hours, 59 minutes and 59 seconds.
* It is also problematic to work in any kind of mixture of days,
* hours, minutes, and seconds, because then the addition of a span
* would sometimes depend on which order you add the constituent
* parts, which undermines the concept of a span altogether.
*
* If you want alternative functionality, you must use a mixture of
* the following functions instead:
*
* addYears()
* addMonths()
* addDays()
* addHours()
* addMinutes()
* addSeconds()
*
* @param object $span the time span to add
*
* @return void
* @access public
*/
function addSpan($span)
{
if (!is_a($span, 'Date_Span')) {
return PEAR::raiseError("Invalid argument - not 'Date_Span' object");
} else if ($this->ob_invalidtime) {
return $this->_getErrorInvalidTime();
}
$hn_days = $span->day;
$hn_standardhour = $this->on_standardhour + $span->hour;
$hn_standardminute = $this->on_standardminute + $span->minute;
$hn_standardsecond = $this->on_standardsecond + $span->second;
if ($hn_standardsecond >= 60) {
++$hn_standardminute;
$hn_standardsecond -= 60;
}
if ($hn_standardminute >= 60) {
++$hn_standardhour;
$hn_standardminute -= 60;
}
if ($hn_standardhour >= 24) {
++$hn_days;
$hn_standardhour -= 24;
}
list($hn_standardyear, $hn_standardmonth, $hn_standardday) =
explode(" ",
Date_Calc::addDays($hn_days,
$this->on_standardday,
$this->on_standardmonth,
$this->on_standardyear,
"%Y %m %d"));
$this->setStandardTime($hn_standardday,
$hn_standardmonth,
$hn_standardyear,
$hn_standardhour,
$hn_standardminute,
$hn_standardsecond,
$this->on_standardpartsecond);
}
// }}}
// {{{ subtractSpan()
/**
* Subtracts a time span from the date
*
* N.B. it is impossible for this function to count leap seconds,
* because the result would be dependent on which order the consituent
* parts of the span are subtracted from the date. Therefore, leap
* seconds are ignored by this function. If you want to count leap
* seconds, use 'subtractSeconds()'.
*
* @param object $span the time span to subtract
*
* @return void
* @access public
*/
function subtractSpan($span)
{
if (!is_a($span, 'Date_Span')) {
return PEAR::raiseError("Invalid argument - not 'Date_Span' object");
} else if ($this->ob_invalidtime) {
return $this->_getErrorInvalidTime();
}
$hn_days = -$span->day;
$hn_standardhour = $this->on_standardhour - $span->hour;
$hn_standardminute = $this->on_standardminute - $span->minute;
$hn_standardsecond = $this->on_standardsecond - $span->second;
if ($hn_standardsecond < 0) {
--$hn_standardminute;
$hn_standardsecond += 60;
}
if ($hn_standardminute < 0) {
--$hn_standardhour;
$hn_standardminute += 60;
}
if ($hn_standardhour < 0) {
--$hn_days;
$hn_standardhour += 24;
}
list($hn_standardyear, $hn_standardmonth, $hn_standardday) =
explode(" ",
Date_Calc::addDays($hn_days,
$this->on_standardday,
$this->on_standardmonth,
$this->on_standardyear,
"%Y %m %d"));
$this->setStandardTime($hn_standardday,
$hn_standardmonth,
$hn_standardyear,
$hn_standardhour,
$hn_standardminute,
$hn_standardsecond,
$this->on_standardpartsecond);
}
// }}}
// {{{ dateDiff()
/**
* Subtract supplied date and return answer in days
*
* If the second parameter '$pb_ignoretime' is specified as false, the time
* parts of the two dates will be ignored, and the integral no of days
* between the day-month-year parts of the two dates will be returned. If
* either of the two dates have an invalid time, the integral no of days
* will also be returned, else the returned value will be the no of days as
* a float, with each hour being treated as 1/24th of a day and so on.
*
* For example,
* 21/11/2007 13.00 minus 21/11/2007 01.00
* returns 0.5
*
* Note that if the passed date is in the past, a positive value will be
* returned, and if it is in the future, a negative value will be returned.
*
* @param object $po_date date to subtract
* @param bool $pb_ignoretime whether to ignore the time values of the two
* dates in subtraction (defaults to false)
*
* @return mixed days between two dates as int or float
* @access public
* @since Method available since Release 1.5.0
*/
function dateDiff($po_date, $pb_ignoretime = false)
{
if ($pb_ignoretime || $this->ob_invalidtime) {
return Date_Calc::dateToDays($this->day,
$this->month,
$this->year) -
Date_Calc::dateToDays($po_date->getDay(),
$po_date->getMonth(),
$po_date->getYear());
}
$hn_secondscompare = $po_date->getStandardSecondsPastMidnight();
if (PEAR::isError($hn_secondscompare)) {
if ($hn_secondscompare->getCode() != DATE_ERROR_INVALIDTIME) {
return $hn_secondscompare;
}
return Date_Calc::dateToDays($this->day,
$this->month,
$this->year) -
Date_Calc::dateToDays($po_date->getDay(),
$po_date->getMonth(),
$po_date->getYear());
}
$hn_seconds = $this->getStandardSecondsPastMidnight();
// If time parts are equal, return int, else return float:
//
return Date_Calc::dateToDays($this->on_standardday,
$this->on_standardmonth,
$this->on_standardyear) -
Date_Calc::dateToDays($po_date->getStandardDay(),
$po_date->getStandardMonth(),
$po_date->getStandardYear()) +
($hn_seconds == $hn_secondscompare ? 0 :
($hn_seconds - $hn_secondscompare) / 86400);
}
// }}}
// {{{ inEquivalentTimeZones()
/**
* Tests whether two dates are in equivalent time zones
*
* Equivalence in this context consists in the time zones of the two dates
* having:
*
* an equal offset from UTC in both standard and Summer time (if
* the time zones observe Summer time)
* the same Summer time start and end rules, that is, the two time zones
* must switch from standard time to Summer time, and vice versa, on the
* same day and at the same time
*
* An example of two equivalent time zones is 'Europe/London' and
* 'Europe/Lisbon', which in London is known as GMT/BST, and in Lisbon as
* WET/WEST.
*
* @param object $po_date1 the first Date object to compare
* @param object $po_date2 the second Date object to compare
*
* @return bool true if the time zones are equivalent
* @access public
* @static
* @since Method available since Release 1.5.0
*/
function inEquivalentTimeZones($po_date1, $po_date2)
{
return $po_date1->tz->isEquivalent($po_date2->getTZID());
}
// }}}
// {{{ compare()
/**
* Compares two dates
*
* Suitable for use in sorting functions.
*
* @param object $od1 the first Date object to compare
* @param object $od2 the second Date object to compare
*
* @return int 0 if the dates are equal, -1 if '$od1' is
* before '$od2', 1 if '$od1' is after '$od2'
* @access public
* @static
*/
function compare($od1, $od2)
{
$d1 = new Date($od1);
$d2 = new Date($od2);
// If the time zones are equivalent, do nothing:
//
if (!Date::inEquivalentTimeZones($d1, $d2)) {
// Only a time zone with a valid time can be converted:
//
if ($d2->isTimeValid()) {
$d2->convertTZByID($d1->getTZID());
} else if ($d1->isTimeValid()) {
$d1->convertTZByID($d2->getTZID());
} else {
// No comparison can be made without guessing the time:
//
return PEAR::raiseError("Both dates have invalid time",
DATE_ERROR_INVALIDTIME);
}
}
$days1 = Date_Calc::dateToDays($d1->getDay(),
$d1->getMonth(),
$d1->getYear());
$days2 = Date_Calc::dateToDays($d2->getDay(),
$d2->getMonth(),
$d2->getYear());
if ($days1 < $days2)
return -1;
if ($days1 > $days2)
return 1;
$hn_hour1 = $d1->getStandardHour();
if (PEAR::isError($hn_hour1))
return $hn_hour1;
$hn_hour2 = $d2->getStandardHour();
if (PEAR::isError($hn_hour2))
return $hn_hour2;
if ($hn_hour1 < $hn_hour2) return -1;
if ($hn_hour1 > $hn_hour2) return 1;
if ($d1->getStandardMinute() < $d2->getStandardMinute()) return -1;
if ($d1->getStandardMinute() > $d2->getStandardMinute()) return 1;
if ($d1->getStandardSecond() < $d2->getStandardSecond()) return -1;
if ($d1->getStandardSecond() > $d2->getStandardSecond()) return 1;
if ($d1->getStandardPartSecond() < $d2->getStandardPartSecond()) return -1;
if ($d1->getStandardPartSecond() > $d2->getStandardPartSecond()) return 1;
return 0;
}
// }}}
// {{{ before()
/**
* Test if this date/time is before a certain date/time
*
* @param object $when the Date object to test against
*
* @return boolean true if this date is before $when
* @access public
*/
function before($when)
{
$hn_compare = Date::compare($this, $when);
if (PEAR::isError($hn_compare))
return $hn_compare;
if ($hn_compare == -1) {
return true;
} else {
return false;
}
}
// }}}
// {{{ after()
/**
* Test if this date/time is after a certain date/time
*
* @param object $when the Date object to test against
*
* @return boolean true if this date is after $when
* @access public
*/
function after($when)
{
$hn_compare = Date::compare($this, $when);
if (PEAR::isError($hn_compare))
return $hn_compare;
if ($hn_compare == 1) {
return true;
} else {
return false;
}
}
// }}}
// {{{ equals()
/**
* Test if this date/time is exactly equal to a certain date/time
*
* @param object $when the Date object to test against
*
* @return boolean true if this date is exactly equal to $when
* @access public
*/
function equals($when)
{
$hn_compare = Date::compare($this, $when);
if (PEAR::isError($hn_compare))
return $hn_compare;
if ($hn_compare == 0) {
return true;
} else {
return false;
}
}
// }}}
// {{{ isFuture()
/**
* Determine if this date is in the future
*
* @return boolean true if this date is in the future
* @access public
*/
function isFuture()
{
$now = new Date();
return $this->after($now);
}
// }}}
// {{{ isPast()
/**
* Determine if this date is in the past
*
* @return boolean true if this date is in the past
* @access public
*/
function isPast()
{
$now = new Date();
return $this->before($now);
}
// }}}
// {{{ isLeapYear()
/**
* Determine if the year in this date is a leap year
*
* @return boolean true if this year is a leap year
* @access public
*/
function isLeapYear()
{
return Date_Calc::isLeapYear($this->year);
}
// }}}
// {{{ getJulianDate()
/**
* Returns the no of days (1-366) since 31st December of the previous year
*
* N.B. this function does not return (and never has returned) the 'Julian
* Date', as described, for example, at:
*
* http://en.wikipedia.org/wiki/Julian_day
*
* If you want the day of the year (0-366), use 'getDayOfYear()' instead.
* If you want the true Julian Day, call one of the following:
*
* <code>format("%E")</code>
* <code>format2("J")</code>
*
* There currently is no function that calls the Julian Date (as opposed
* to the 'Julian Day'), although the Julian Day is an approximation.
*
* @return int the Julian date
* @access public
* @see Date::getDayOfYear()
* @deprecated Method deprecated in Release 1.5.0
*/
function getJulianDate()
{
return Date_Calc::julianDate($this->day, $this->month, $this->year);
}
// }}}
// {{{ getDayOfYear()
/**
* Returns the no of days (1-366) since 31st December of the previous year
*
* @return int an integer between 1 and 366
* @access public
* @since Method available since Release 1.5.0
*/
function getDayOfYear()
{
return Date_Calc::dayOfYear($this->day, $this->month, $this->year);
}
// }}}
// {{{ getDayOfWeek()
/**
* Gets the day of the week for this date (0 = Sunday)
*
* @return int the day of the week (0 = Sunday)
* @access public
*/
function getDayOfWeek()
{
return Date_Calc::dayOfWeek($this->day, $this->month, $this->year);
}
// }}}
// {{{ getWeekOfYear()
/**
* Gets the week of the year for this date
*
* @return int the week of the year
* @access public
*/
function getWeekOfYear()
{
return Date_Calc::weekOfYear($this->day, $this->month, $this->year);
}
// }}}
// {{{ getQuarterOfYear()
/**
* Gets the quarter of the year for this date
*
* @return int the quarter of the year (1-4)
* @access public
*/
function getQuarterOfYear()
{
return Date_Calc::quarterOfYear($this->day, $this->month, $this->year);
}
// }}}
// {{{ getDaysInMonth()
/**
* Gets number of days in the month for this date
*
* @return int number of days in this month
* @access public
*/
function getDaysInMonth()
{
return Date_Calc::daysInMonth($this->month, $this->year);
}
// }}}
// {{{ getWeeksInMonth()
/**
* Gets the number of weeks in the month for this date
*
* @return int number of weeks in this month
* @access public
*/
function getWeeksInMonth()
{
return Date_Calc::weeksInMonth($this->month, $this->year);
}
// }}}
// {{{ getDayName()
/**
* Gets the full name or abbreviated name of this weekday
*
* @param bool $abbr abbreviate the name
* @param int $length length of abbreviation
*
* @return string name of this day
* @access public
*/
function getDayName($abbr = false, $length = 3)
{
if ($abbr) {
return Date_Calc::getWeekdayAbbrname($this->day,
$this->month,
$this->year,
$length);
} else {
return Date_Calc::getWeekdayFullname($this->day,
$this->month,
$this->year);
}
}
// }}}
// {{{ getMonthName()
/**
* Gets the full name or abbreviated name of this month
*
* @param boolean $abbr abbreviate the name
*
* @return string name of this month
* @access public
*/
function getMonthName($abbr = false)
{
if ($abbr) {
return Date_Calc::getMonthAbbrname($this->month);
} else {
return Date_Calc::getMonthFullname($this->month);
}
}
// }}}
// {{{ getNextDay()
/**
* Get a Date object for the day after this one
*
* The time of the returned Date object is the same as this time.
*
* @return object Date object representing the next day
* @access public
*/
function getNextDay()
{
$ret = new Date($this);
$ret->addDays(1);
return $ret;
}
// }}}
// {{{ getPrevDay()
/**
* Get a Date object for the day before this one
*
* The time of the returned Date object is the same as this time.
*
* @return object Date object representing the previous day
* @access public
*/
function getPrevDay()
{
$ret = new Date($this);
$ret->addDays(-1);
return $ret;
}
// }}}
// {{{ getNextWeekday()
/**
* Get a Date object for the weekday after this one
*
* The time of the returned Date object is the same as this time.
*
* @return object Date object representing the next week-day
* @access public
*/
function getNextWeekday()
{
$ret = new Date($this);
list($hs_year, $hs_month, $hs_day) =
explode(" ", Date_Calc::nextWeekday($this->day,
$this->month,
$this->year,
"%Y %m %d"));
$ret->setDayMonthYear($hs_day, $hs_month, $hs_year);
return $ret;
}
// }}}
// {{{ getPrevWeekday()
/**
* Get a Date object for the weekday before this one
*
* The time of the returned Date object is the same as this time.
*
* @return object Date object representing the previous week-day
* @access public
*/
function getPrevWeekday()
{
$ret = new Date($this);
list($hs_year, $hs_month, $hs_day) =
explode(" ", Date_Calc::prevWeekday($this->day,
$this->month,
$this->year,
"%Y %m %d"));
$ret->setDayMonthYear($hs_day, $hs_month, $hs_year);
return $ret;
}
// }}}
// {{{ getYear()
/**
* Returns the year field of the date object
*
* @return int the year
* @access public
*/
function getYear()
{
return $this->year;
}
// }}}
// {{{ getMonth()
/**
* Returns the month field of the date object
*
* @return int the minute
* @access public
*/
function getMonth()
{
return $this->month;
}
// }}}
// {{{ getDay()
/**
* Returns the day field of the date object
*
* @return int the day
* @access public
*/
function getDay()
{
return $this->day;
}
// }}}
// {{{ _getErrorInvalidTime()
/**
* Returns invalid time PEAR Error
*
* @return object
* @access private
* @since Method available since Release 1.5.0
*/
function _getErrorInvalidTime()
{
return PEAR::raiseError("Invalid time '" .
sprintf("%02d.%02d.%02d",
$this->hour,
$this->minute,
$this->second) .
"' specified for date '" .
Date_Calc::dateFormat($this->day,
$this->month,
$this->year,
"%Y-%m-%d") .
"' and in this timezone",
DATE_ERROR_INVALIDTIME);
}
// }}}
// {{{ _secondsInDayIsValid()
/**
* If leap seconds are observed, checks if the seconds in the day is valid
*
* Note that only the local standard time is accessed.
*
* @return bool
* @access private
* @since Method available since Release 1.5.0
*/
function _secondsInDayIsValid()
{
if ($this->ob_countleapseconds) {
// Convert to UTC:
//
list($hn_year,
$hn_month,
$hn_day,
$hn_hour,
$hn_minute,
$hn_second,
$hn_partsecond) =
$this->_addOffset($this->tz->getRawOffset() * -1,
$this->on_standardday,
$this->on_standardmonth,
$this->on_standardyear,
$this->on_standardhour,
$this->on_standardminute,
$this->on_standardsecond,
$this->on_standardpartsecond);
return Date_Calc::secondsPastMidnight($hn_hour,
$hn_minute,
$hn_second +
$hn_partsecond) <
Date_Calc::getSecondsInDay($hn_day, $hn_month, $hn_year);
} else {
return $this->getStandardSecondsPastMidnight() < 86400;
}
}
// }}}
// {{{ isTimeValid()
/**
* Whether the stored time is valid as a local time
*
* An invalid time is one that lies in the 'skipped hour' at the point
* that the clocks go forward. Note that the stored date (i.e.
* the day/month/year, is always valid).
*
* The object is able to store an invalid time because a user might
* unwittingly and correctly store a valid time, and then add one day so
* as to put the object in the 'skipped' hour (when the clocks go forward).
* This could be corrected by a conversion to Summer time (by adding one
* hour); however, if the user then added another day, and had no need for
* or interest in the time anyway, the behaviour may be rather unexpected.
* And anyway in this situation, the time originally specified would now,
* two days on, be valid again.
*
* So this class allows an invalid time like this so long as the user does
* not in any way make use of or request the time while it is in this
* semi-invalid state, in order to allow for for the fact that he might be
* only interested in the date, and not the time, and in order not to behave
* in an unexpected way, especially without throwing an exception to tell
* the user about it.
*
* @return bool
* @access public
* @since Method available since Release 1.5.0
*/
function isTimeValid()
{
return !$this->ob_invalidtime;
}
// }}}
// {{{ getHour()
/**
* Returns the hour field of the date object
*
* @return int the hour
* @access public
*/
function getHour()
{
if ($this->ob_invalidtime)
return $this->_getErrorInvalidTime();
return $this->hour;
}
// }}}
// {{{ getMinute()
/**
* Returns the minute field of the date object
*
* @return int the minute
* @access public
*/
function getMinute()
{
if ($this->ob_invalidtime)
return $this->_getErrorInvalidTime();
return $this->minute;
}
// }}}
// {{{ getSecond()
/**
* Returns the second field of the date object
*
* @return int the second
* @access public
*/
function getSecond()
{
if ($this->ob_invalidtime)
return $this->_getErrorInvalidTime();
return $this->second;
}
// }}}
// {{{ getSecondsPastMidnight()
/**
* Returns the no of seconds since midnight (0-86400) as float
*
* @return float float which is at least 0 and less than 86400
* @access public
* @since Method available since Release 1.5.0
*/
function getSecondsPastMidnight()
{
if ($this->ob_invalidtime)
return $this->_getErrorInvalidTime();
return Date_Calc::secondsPastMidnight($this->hour,
$this->minute,
$this->second) +
$this->partsecond;
}
// }}}
// {{{ getPartSecond()
/**
* Returns the part-second field of the date object
*
* @return float the part-second
* @access protected
* @since Method available since Release 1.5.0
*/
function getPartSecond()
{
if ($this->ob_invalidtime)
return $this->_getErrorInvalidTime();
return $this->partsecond;
}
// }}}
// {{{ getStandardYear()
/**
* Returns the year field of the local standard time
*
* @return int the year
* @access public
* @since Method available since Release 1.5.0
*/
function getStandardYear()
{
if ($this->ob_invalidtime)
return $this->_getErrorInvalidTime();
return $this->on_standardyear;
}
// }}}
// {{{ getStandardMonth()
/**
* Returns the month field of the local standard time
*
* @return int the minute
* @access public
* @since Method available since Release 1.5.0
*/
function getStandardMonth()
{
if ($this->ob_invalidtime)
return $this->_getErrorInvalidTime();
return $this->on_standardmonth;
}
// }}}
// {{{ getStandardDay()
/**
* Returns the day field of the local standard time
*
* @return int the day
* @access public
* @since Method available since Release 1.5.0
*/
function getStandardDay()
{
if ($this->ob_invalidtime)
return $this->_getErrorInvalidTime();
return $this->on_standardday;
}
// }}}
// {{{ getStandardHour()
/**
* Returns the hour field of the local standard time
*
* @return int the hour
* @access public
* @since Method available since Release 1.5.0
*/
function getStandardHour()
{
if ($this->ob_invalidtime)
return $this->_getErrorInvalidTime();
return $this->on_standardhour;
}
// }}}
// {{{ getStandardMinute()
/**
* Returns the minute field of the local standard time
*
* @return int the minute
* @access public
* @since Method available since Release 1.5.0
*/
function getStandardMinute()
{
if ($this->ob_invalidtime)
return $this->_getErrorInvalidTime();
return $this->on_standardminute;
}
// }}}
// {{{ getStandardSecond()
/**
* Returns the second field of the local standard time
*
* @return int the second
* @access public
* @since Method available since Release 1.5.0
*/
function getStandardSecond()
{
if ($this->ob_invalidtime)
return $this->_getErrorInvalidTime();
return $this->on_standardsecond;
}
// }}}
// {{{ getStandardSecondsPastMidnight()
/**
* Returns the no of seconds since midnight (0-86400) of the
* local standard time as float
*
* @return float float which is at least 0 and less than 86400
* @access public
* @since Method available since Release 1.5.0
*/
function getStandardSecondsPastMidnight()
{
if ($this->ob_invalidtime)
return $this->_getErrorInvalidTime();
return Date_Calc::secondsPastMidnight($this->on_standardhour,
$this->on_standardminute,
$this->on_standardsecond) +
$this->on_standardpartsecond;
}
// }}}
// {{{ getStandardPartSecond()
/**
* Returns the part-second field of the local standard time
*
* @return float the part-second
* @access protected
* @since Method available since Release 1.5.0
*/
function getStandardPartSecond()
{
if ($this->ob_invalidtime)
return $this->_getErrorInvalidTime();
return $this->on_standardpartsecond;
}
// }}}
// {{{ _addOffset()
/**
* Add a time zone offset to the passed date/time
*
* @param int $pn_offset the offset to add in milliseconds
* @param int $pn_day the day
* @param int $pn_month the month
* @param int $pn_year the year
* @param int $pn_hour the hour
* @param int $pn_minute the minute
* @param int $pn_second the second
* @param float $pn_partsecond the part-second
*
* @return array array of year, month, day, hour, minute, second,
* and part-second
* @access private
* @static
* @since Method available since Release 1.5.0
*/
function _addOffset($pn_offset,
$pn_day,
$pn_month,
$pn_year,
$pn_hour,
$pn_minute,
$pn_second,
$pn_partsecond)
{
if ($pn_offset == 0) {
return array((int) $pn_year,
(int) $pn_month,
(int) $pn_day,
(int) $pn_hour,
(int) $pn_minute,
(int) $pn_second,
(float) $pn_partsecond);
}
if ($pn_offset % 3600000 == 0) {
list($hn_year,
$hn_month,
$hn_day,
$hn_hour) =
Date_Calc::addHours($pn_offset / 3600000,
$pn_day,
$pn_month,
$pn_year,
$pn_hour);
$hn_minute = (int) $pn_minute;
$hn_second = (int) $pn_second;
$hn_partsecond = (float) $pn_partsecond;
} else if ($pn_offset % 60000 == 0) {
list($hn_year,
$hn_month,
$hn_day,
$hn_hour,
$hn_minute) =
Date_Calc::addMinutes($pn_offset / 60000,
$pn_day,
$pn_month,
$pn_year,
$pn_hour,
$pn_minute);
$hn_second = (int) $pn_second;
$hn_partsecond = (float) $pn_partsecond;
} else {
list($hn_year,
$hn_month,
$hn_day,
$hn_hour,
$hn_minute,
$hn_secondraw) =
Date_Calc::addSeconds($pn_offset / 1000,
$pn_day,
$pn_month,
$pn_year,
$pn_hour,
$pn_partsecond == 0.0 ?
$pn_second :
$pn_second + $pn_partsecond,
false); // N.B. do not count
// leap seconds
if (is_float($hn_secondraw)) {
$hn_second = intval($hn_secondraw);
$hn_partsecond = $hn_secondraw - $hn_second;
} else {
$hn_second = $hn_secondraw;
$hn_partsecond = 0.0;
}
}
return array($hn_year,
$hn_month,
$hn_day,
$hn_hour,
$hn_minute,
$hn_second,
$hn_partsecond);
}
// }}}
// {{{ setLocalTime()
/**
* Sets local time (Summer-time-adjusted) and then calculates local
* standard time
*
* @param int $pn_day the day
* @param int $pn_month the month
* @param int $pn_year the year
* @param int $pn_hour the hour
* @param int $pn_minute the minute
* @param int $pn_second the second
* @param float $pn_partsecond the part-second
* @param bool $pb_repeatedhourdefault whether to assume Summer time if a
* repeated hour is specified (defaults
* to false)
* @param bool $pb_correctinvalidtime whether to correct, by adding the
* local Summer time offset, the
* specified time if it falls in the
* skipped hour (defaults to
* DATE_CORRECTINVALIDTIME_DEFAULT)
*
* @return void
* @access protected
* @see Date::setStandardTime()
* @since Method available since Release 1.5.0
*/
function setLocalTime($pn_day,
$pn_month,
$pn_year,
$pn_hour,
$pn_minute,
$pn_second,
$pn_partsecond,
$pb_repeatedhourdefault = false,
$pb_correctinvalidtime = DATE_CORRECTINVALIDTIME_DEFAULT)
{
settype($pn_day, "int");
settype($pn_month, "int");
settype($pn_year, "int");
settype($pn_hour, "int");
settype($pn_minute, "int");
settype($pn_second, "int");
settype($pn_partsecond, "float");
$hb_insummertime =
$this->tz->inDaylightTime(array($pn_day,
$pn_month, $pn_year, Date_Calc::secondsPastMidnight($pn_hour,
$pn_minute, $pn_second) + $pn_partsecond),
$pb_repeatedhourdefault);
if (PEAR::isError($hb_insummertime)) {
if ($hb_insummertime->getCode() != DATE_ERROR_INVALIDTIME) {
return $hb_insummertime;
} else if ($pb_correctinvalidtime) {
// Store passed time as local standard time:
//
$this->on_standardday = $pn_day;
$this->on_standardmonth = $pn_month;
$this->on_standardyear = $pn_year;
$this->on_standardhour = $pn_hour;
$this->on_standardminute = $pn_minute;
$this->on_standardsecond = $pn_second;
$this->on_standardpartsecond = $pn_partsecond;
// Add Summer time offset to passed time:
//
list($this->year,
$this->month,
$this->day,
$this->hour,
$this->minute,
$this->second,
$this->partsecond) =
$this->_addOffset($this->tz->getDSTSavings(),
$pn_day,
$pn_month,
$pn_year,
$pn_hour,
$pn_minute,
$pn_second,
$pn_partsecond);
$this->ob_invalidtime = !$this->_secondsInDayIsValid();
} else {
// Hedge bets - if the user adds/subtracts a day, then the time
// will be uncorrupted, and if the user does
// addition/subtraction with the time, or requests the time,
// then return an error at that point:
//
$this->day = $pn_day;
$this->month = $pn_month;
$this->year = $pn_year;
$this->hour = $pn_hour;
$this->minute = $pn_minute;
$this->second = $pn_second;
$this->partsecond = $pn_partsecond;
$this->ob_invalidtime = true;
}
return;
} else {
// Passed time is valid as local time:
//
$this->day = $pn_day;
$this->month = $pn_month;
$this->year = $pn_year;
$this->hour = $pn_hour;
$this->minute = $pn_minute;
$this->second = $pn_second;
$this->partsecond = $pn_partsecond;
}
$this->ob_invalidtime = !$this->_secondsInDayIsValid();
if ($hb_insummertime) {
// Calculate local standard time:
//
list($this->on_standardyear,
$this->on_standardmonth,
$this->on_standardday,
$this->on_standardhour,
$this->on_standardminute,
$this->on_standardsecond,
$this->on_standardpartsecond) =
$this->_addOffset($this->tz->getDSTSavings() * -1,
$pn_day,
$pn_month,
$pn_year,
$pn_hour,
$pn_minute,
$pn_second,
$pn_partsecond);
} else {
// Time is already local standard time:
//
$this->on_standardday = $pn_day;
$this->on_standardmonth = $pn_month;
$this->on_standardyear = $pn_year;
$this->on_standardhour = $pn_hour;
$this->on_standardminute = $pn_minute;
$this->on_standardsecond = $pn_second;
$this->on_standardpartsecond = $pn_partsecond;
}
}
// }}}
// {{{ setStandardTime()
/**
* Sets local standard time and then calculates local time (i.e.
* Summer-time-adjusted)
*
* @param int $pn_day the day
* @param int $pn_month the month
* @param int $pn_year the year
* @param int $pn_hour the hour
* @param int $pn_minute the minute
* @param int $pn_second the second
* @param float $pn_partsecond the part-second
*
* @return void
* @access protected
* @see Date::setLocalTime()
* @since Method available since Release 1.5.0
*/
function setStandardTime($pn_day,
$pn_month,
$pn_year,
$pn_hour,
$pn_minute,
$pn_second,
$pn_partsecond)
{
settype($pn_day, "int");
settype($pn_month, "int");
settype($pn_year, "int");
settype($pn_hour, "int");
settype($pn_minute, "int");
settype($pn_second, "int");
settype($pn_partsecond, "float");
$this->on_standardday = $pn_day;
$this->on_standardmonth = $pn_month;
$this->on_standardyear = $pn_year;
$this->on_standardhour = $pn_hour;
$this->on_standardminute = $pn_minute;
$this->on_standardsecond = $pn_second;
$this->on_standardpartsecond = $pn_partsecond;
$this->ob_invalidtime = !$this->_secondsInDayIsValid();
if ($this->tz->inDaylightTimeStandard(array($pn_day, $pn_month,
$pn_year, Date_Calc::secondsPastMidnight($pn_hour, $pn_minute,
$pn_second) + $pn_partsecond))) {
// Calculate local time:
//
list($this->year,
$this->month,
$this->day,
$this->hour,
$this->minute,
$this->second,
$this->partsecond) =
$this->_addOffset($this->tz->getDSTSavings(),
$pn_day,
$pn_month,
$pn_year,
$pn_hour,
$pn_minute,
$pn_second,
$pn_partsecond);
} else {
// Time is already local time:
//
$this->day = $pn_day;
$this->month = $pn_month;
$this->year = $pn_year;
$this->hour = $pn_hour;
$this->minute = $pn_minute;
$this->second = $pn_second;
$this->partsecond = $pn_partsecond;
}
}
// }}}
// {{{ setYear()
/**
* Sets the year field of the date object
*
* If specified year forms an invalid date, then PEAR error will be
* returned, unless the validation is over-ridden using the second
* parameter.
*
* @param int $y the year
* @param bool $pb_validate whether to check that the new date is valid
*
* @return void
* @access public
* @see Date::setDayMonthYear(), Date::setDateTime()
*/
function setYear($y, $pb_validate = DATE_VALIDATE_DATE_BY_DEFAULT)
{
if ($pb_validate && !Date_Calc::isValidDate($this->day, $this->month, $y)) {
return PEAR::raiseError("'" .
Date_Calc::dateFormat($this->day,
$this->month,
$y,
"%Y-%m-%d") .
"' is invalid calendar date",
DATE_ERROR_INVALIDDATE);
} else {
$this->setLocalTime($this->day,
$this->month,
$y,
$this->hour,
$this->minute,
$this->second,
$this->partsecond);
}
}
// }}}
// {{{ setMonth()
/**
* Sets the month field of the date object
*
* If specified year forms an invalid date, then PEAR error will be
* returned, unless the validation is over-ridden using the second
* parameter.
*
* @param int $m the month
* @param bool $pb_validate whether to check that the new date is valid
*
* @return void
* @access public
* @see Date::setDayMonthYear(), Date::setDateTime()
*/
function setMonth($m, $pb_validate = DATE_VALIDATE_DATE_BY_DEFAULT)
{
if ($pb_validate && !Date_Calc::isValidDate($this->day, $m, $this->year)) {
return PEAR::raiseError("'" .
Date_Calc::dateFormat($this->day,
$m,
$this->year,
"%Y-%m-%d") .
"' is invalid calendar date",
DATE_ERROR_INVALIDDATE);
} else {
$this->setLocalTime($this->day,
$m,
$this->year,
$this->hour,
$this->minute,
$this->second,
$this->partsecond);
}
}
// }}}
// {{{ setDay()
/**
* Sets the day field of the date object
*
* If specified year forms an invalid date, then PEAR error will be
* returned, unless the validation is over-ridden using the second
* parameter.
*
* @param int $d the day
* @param bool $pb_validate whether to check that the new date is valid
*
* @return void
* @access public
* @see Date::setDayMonthYear(), Date::setDateTime()
*/
function setDay($d, $pb_validate = DATE_VALIDATE_DATE_BY_DEFAULT)
{
if ($pb_validate && !Date_Calc::isValidDate($d, $this->month, $this->year)) {
return PEAR::raiseError("'" .
Date_Calc::dateFormat($d,
$this->month,
$this->year,
"%Y-%m-%d") .
"' is invalid calendar date",
DATE_ERROR_INVALIDDATE);
} else {
$this->setLocalTime($d,
$this->month,
$this->year,
$this->hour,
$this->minute,
$this->second,
$this->partsecond);
}
}
// }}}
// {{{ setDayMonthYear()
/**
* Sets the day, month and year fields of the date object
*
* If specified year forms an invalid date, then PEAR error will be
* returned. Note that setting each of these fields separately
* may unintentionally return a PEAR error if a transitory date is
* invalid between setting these fields.
*
* @param int $d the day
* @param int $m the month
* @param int $y the year
*
* @return void
* @access public
* @see Date::setDateTime()
* @since Method available since Release 1.5.0
*/
function setDayMonthYear($d, $m, $y)
{
if (!Date_Calc::isValidDate($d, $m, $y)) {
return PEAR::raiseError("'" .
Date_Calc::dateFormat($d,
$m,
$y,
"%Y-%m-%d") .
"' is invalid calendar date",
DATE_ERROR_INVALIDDATE);
} else {
$this->setLocalTime($d,
$m,
$y,
$this->hour,
$this->minute,
$this->second,
$this->partsecond);
}
}
// }}}
// {{{ setHour()
/**
* Sets the hour field of the date object
*
* Expects an hour in 24-hour format.
*
* @param int $h the hour
* @param bool $pb_repeatedhourdefault whether to assume Summer time if a
* repeated hour is specified (defaults
* to false)
*
* @return void
* @access public
* @see Date::setHourMinuteSecond(), Date::setDateTime()
*/
function setHour($h, $pb_repeatedhourdefault = false)
{
if ($h > 23 || $h < 0) {
return PEAR::raiseError("Invalid hour value '$h'");
} else {
$ret = $this->setHourMinuteSecond($h,
$this->minute,
$this->partsecond == 0.0 ?
$this->second :
$this->second + $this->partsecond,
$pb_repeatedhourdefault);
if (PEAR::isError($ret))
return $ret;
}
}
// }}}
// {{{ setMinute()
/**
* Sets the minute field of the date object
*
* @param int $m the minute
* @param bool $pb_repeatedhourdefault whether to assume Summer time if a
* repeated hour is specified (defaults
* to false)
*
* @return void
* @access public
* @see Date::setHourMinuteSecond(), Date::setDateTime()
*/
function setMinute($m, $pb_repeatedhourdefault = false)
{
if ($m > 59 || $m < 0) {
return PEAR::raiseError("Invalid minute value '$m'");
} else {
$ret = $this->setHourMinuteSecond($this->hour,
$m,
$this->partsecond == 0.0 ?
$this->second :
$this->second + $this->partsecond,
$pb_repeatedhourdefault);
if (PEAR::isError($ret))
return $ret;
}
}
// }}}
// {{{ setSecond()
/**
* Sets the second field of the date object
*
* @param mixed $s the second as integer or float
* @param bool $pb_repeatedhourdefault whether to assume Summer time if a
* repeated hour is specified
* (defaults to false)
*
* @return void
* @access public
* @see Date::setHourMinuteSecond(), Date::setDateTime()
*/
function setSecond($s, $pb_repeatedhourdefault = false)
{
if ($s > 60 || // Leap seconds possible
$s < 0) {
return PEAR::raiseError("Invalid second value '$s'");
} else {
$ret = $this->setHourMinuteSecond($this->hour,
$this->minute,
$s,
$pb_repeatedhourdefault);
if (PEAR::isError($ret))
return $ret;
}
}
// }}}
// {{{ setPartSecond()
/**
* Sets the part-second field of the date object
*
* @param float $pn_ps the part-second
* @param bool $pb_repeatedhourdefault whether to assume Summer time if a
* repeated hour is specified (defaults
* to false)
*
* @return void
* @access protected
* @see Date::setHourMinuteSecond(), Date::setDateTime()
* @since Method available since Release 1.5.0
*/
function setPartSecond($pn_ps, $pb_repeatedhourdefault = false)
{
if ($pn_ps >= 1 || $pn_ps < 0) {
return PEAR::raiseError("Invalid part-second value '$pn_ps'");
} else {
$ret = $this->setHourMinuteSecond($this->hour,
$this->minute,
$this->second + $pn_ps,
$pb_repeatedhourdefault);
if (PEAR::isError($ret))
return $ret;
}
}
// }}}
// {{{ setHourMinuteSecond()
/**
* Sets the hour, minute, second and part-second fields of the date object
*
* N.B. if the repeated hour, due to the clocks going back, is specified,
* the default is to assume local standard time.
*
* @param int $h the hour
* @param int $m the minute
* @param mixed $s the second as integer or float
* @param bool $pb_repeatedhourdefault whether to assume Summer time if a
* repeated hour is specified
* (defaults to false)
*
* @return void
* @access public
* @see Date::setDateTime()
* @since Method available since Release 1.5.0
*/
function setHourMinuteSecond($h, $m, $s, $pb_repeatedhourdefault = false)
{
// Split second into integer and part-second:
//
if (is_float($s)) {
$hn_second = intval($s);
$hn_partsecond = $s - $hn_second;
} else {
$hn_second = (int) $s;
$hn_partsecond = 0.0;
}
$this->setLocalTime($this->day,
$this->month,
$this->year,
$h,
$m,
$hn_second,
$hn_partsecond,
$pb_repeatedhourdefault);
}
// }}}
// {{{ setDateTime()
/**
* Sets all the fields of the date object (day, month, year, hour, minute
* and second)
*
* If specified year forms an invalid date, then PEAR error will be
* returned. Note that setting each of these fields separately
* may unintentionally return a PEAR error if a transitory date is
* invalid between setting these fields.
*
* N.B. if the repeated hour, due to the clocks going back, is specified,
* the default is to assume local standard time.
*
* @param int $pn_day the day
* @param int $pn_month the month
* @param int $pn_year the year
* @param int $pn_hour the hour
* @param int $pn_minute the minute
* @param mixed $pm_second the second as integer or float
* @param bool $pb_repeatedhourdefault whether to assume Summer time if a
* repeated hour is specified
* (defaults to false)
*
* @return void
* @access public
* @see Date::setDayMonthYear(), Date::setHourMinuteSecond()
* @since Method available since Release 1.5.0
*/
function setDateTime($pn_day,
$pn_month,
$pn_year,
$pn_hour,
$pn_minute,
$pm_second,
$pb_repeatedhourdefault = false)
{
if (!Date_Calc::isValidDate($d, $m, $y)) {
return PEAR::raiseError("'" .
Date_Calc::dateFormat($d,
$m,
$y,
"%Y-%m-%d") .
"' is invalid calendar date",
DATE_ERROR_INVALIDDATE);
} else {
// Split second into integer and part-second:
//
if (is_float($pm_second)) {
$hn_second = intval($pm_second);
$hn_partsecond = $pm_second - $hn_second;
} else {
$hn_second = (int) $pm_second;
$hn_partsecond = 0.0;
}
$this->setLocalTime($d,
$m,
$y,
$h,
$m,
$hn_second,
$hn_partsecond,
$pb_repeatedhourdefault);
}
}
// }}}
}
// }}}
/*
* Local variables:
* mode: php
* tab-width: 4
* c-basic-offset: 4
* c-hanging-comment-ender-p: nil
* End:
*/
?>
| {
"content_hash": "a9e211bf76be7a638c40b85f5ef6fe92",
"timestamp": "",
"source": "github",
"line_count": 5864,
"max_line_length": 97,
"avg_line_length": 37.497783083219645,
"alnum_prop": 0.42453623906824867,
"repo_name": "BigBlueHat/atmailopen",
"id": "7bfad49e3d59193bde96ccb3ff250590b9d7395b",
"size": "219893",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "libs/PEAR/Date.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "JavaScript",
"bytes": "417054"
},
{
"name": "PHP",
"bytes": "2039705"
},
{
"name": "Perl",
"bytes": "25877"
}
],
"symlink_target": ""
} |
'use strict';
const models = require('./index');
/**
* @class
* Initializes a new instance of the ApplicationGatewayWebApplicationFirewallConfiguration class.
* @constructor
* Application gateway web application firewall configuration.
*
* @member {boolean} enabled Whether the web application firewall is enabled or
* not.
*
* @member {string} firewallMode Web application firewall mode. Possible values
* include: 'Detection', 'Prevention'
*
* @member {string} ruleSetType The type of the web application firewall rule
* set. Possible values are: 'OWASP'.
*
* @member {string} ruleSetVersion The version of the rule set type.
*
* @member {array} [disabledRuleGroups] The disabled rule groups.
*
*/
class ApplicationGatewayWebApplicationFirewallConfiguration {
constructor() {
}
/**
* Defines the metadata of ApplicationGatewayWebApplicationFirewallConfiguration
*
* @returns {object} metadata of ApplicationGatewayWebApplicationFirewallConfiguration
*
*/
mapper() {
return {
required: false,
serializedName: 'ApplicationGatewayWebApplicationFirewallConfiguration',
type: {
name: 'Composite',
className: 'ApplicationGatewayWebApplicationFirewallConfiguration',
modelProperties: {
enabled: {
required: true,
serializedName: 'enabled',
type: {
name: 'Boolean'
}
},
firewallMode: {
required: true,
serializedName: 'firewallMode',
type: {
name: 'String'
}
},
ruleSetType: {
required: true,
serializedName: 'ruleSetType',
type: {
name: 'String'
}
},
ruleSetVersion: {
required: true,
serializedName: 'ruleSetVersion',
type: {
name: 'String'
}
},
disabledRuleGroups: {
required: false,
serializedName: 'disabledRuleGroups',
type: {
name: 'Sequence',
element: {
required: false,
serializedName: 'ApplicationGatewayFirewallDisabledRuleGroupElementType',
type: {
name: 'Composite',
className: 'ApplicationGatewayFirewallDisabledRuleGroup'
}
}
}
}
}
}
};
}
}
module.exports = ApplicationGatewayWebApplicationFirewallConfiguration;
| {
"content_hash": "b88c5aea7d7eae378df96441dbfdf0b1",
"timestamp": "",
"source": "github",
"line_count": 94,
"max_line_length": 97,
"avg_line_length": 27.51063829787234,
"alnum_prop": 0.5746326372776489,
"repo_name": "AuxMon/azure-sdk-for-node",
"id": "be8010229bea2b541da49e3d1ed1705d96bb9133",
"size": "2910",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "lib/services/networkManagement2/lib/models/applicationGatewayWebApplicationFirewallConfiguration.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "661"
},
{
"name": "JavaScript",
"bytes": "48689677"
},
{
"name": "Shell",
"bytes": "437"
}
],
"symlink_target": ""
} |
package com.teamderpy.victusludus.data.resources;
import com.badlogic.gdx.graphics.Color;
public class StarColorTuple {
private int temperature;
private Color color;
public StarColorTuple(final int temperature, final Color color){
this.temperature = temperature;
this.color = color;
}
public int getTemperature() {
return this.temperature;
}
public Color getColor() {
return this.color;
}
}
| {
"content_hash": "8a8d94620b6df256b638254ac1c2183f",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 65,
"avg_line_length": 18.772727272727273,
"alnum_prop": 0.7530266343825666,
"repo_name": "sabarjp/VictusLudus",
"id": "70e8adea71d7ae3a1b69efc3747c87f83864df06",
"size": "413",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "victusludus/src/com/teamderpy/victusludus/data/resources/StarColorTuple.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "10518"
},
{
"name": "C#",
"bytes": "869"
},
{
"name": "CSS",
"bytes": "54310"
},
{
"name": "Java",
"bytes": "436044"
},
{
"name": "JavaScript",
"bytes": "24"
}
],
"symlink_target": ""
} |
/*
This is just a starter for 10 equivalent for the HaemoBPaudit4 audit.
Lots missing for example
- only do this for the last 30 days?
- selecting patients with a current modality of HD
- filtering out null or 0 bps
- the 140 130 etc percentages
*/
WITH
blood_pressures AS (
SELECT
hd_sessions.id as session_id,
patients.id as patient_id,
hd_sessions.hospital_unit_id,
hd_sessions.document->'observations_before'->'blood_pressure'->>'systolic' as systolic_pre,
hd_sessions.document->'observations_before'->'blood_pressure'->>'diastolic' as diastolic_pre,
hd_sessions.document->'observations_after'->'blood_pressure'->>'systolic' as systolic_post,
hd_sessions.document->'observations_after'->'blood_pressure'->>'diastolic' as diastolic_post
FROM hd_sessions
INNER JOIN patients on patients.id = hd_sessions.patient_id
WHERE hd_sessions.signed_off_at IS NOT NULL
AND hd_sessions.deleted_at IS NULL
),
some_other_derived_table_variable AS (
SELECT 1 FROM blood_pressures
)
SELECT
hu.name as hospital_unit_name,
ROUND(AVG(systolic_pre::int)) as systolic_pre_avg,
ROUND(AVG(diastolic_pre::int)) as diastolic_pre_avg,
ROUND(AVG(systolic_post::int)) as systolic_post_avg,
ROUND(AVG(diastolic_post::int)) as distolic_post_avg
FROM blood_pressures
INNER JOIN hospital_units as hu on hu.id = blood_pressures.hospital_unit_id
GROUP BY hu.name
/*
Here is the original for reference
use audits;
DROP TABLE IF EXISTS hdbpdata;
DROP TABLE IF EXISTS hdpatbpavg;
DROP TABLE IF EXISTS hdpatbpsite;
DROP TABLE IF EXISTS HDpatBPsitemain;
SET @mintotal=6;
CREATE TEMPORARY TABLE hdbpdata SELECT hdsesszid, modalsite as currsite, sex,
year(CURDATE())-year(birthdate) as age, syst_pre, syst_post, diast_pre, diast_post FROM
renalware.hdsessiondata JOIN renalware.patientdata ON hdsesszid=patzid WHERE DATEDIFF(CURDATE(),
hdsessdate)<30 and patientdata.modalcode LIKE '%HD%';
CREATE TABLE hdpatbpavg as SELECT hdsesszid, currsite, ROUND(AVG(syst_pre),0) as avgpresyst,
ROUND(AVG(syst_post),0) as avgpostsyst, ROUND(AVG(diast_pre),0) as avgprediast,
ROUND(AVG(diast_post),0) as avgpostdiast, syst_pre, syst_post, diast_pre, diast_post FROM hdbpdata
GROUP BY hdsesszid;
CREATE TABLE hdpatbpsite as SELECT currsite as currentsite, count(hdsesszid) as patcount,
ROUND(AVG(avgpresyst),0) as presyst_avg,
round(100*(sum(IF(syst_pre<140, '1','0'))/count(hdsesszid)),1) as pctpresysless140,
ROUND(AVG(avgpostsyst),0) as postsys_avg,
round(100*(sum(IF(syst_post<130, '1','0'))/count(hdsesszid)),1) as pctpostsysless130,
ROUND(AVG(avgprediast),0) as prediast_avg,
round(100*(sum(IF(diast_pre<90, '1','0'))/count(hdsesszid)),1) as pctprediastless90,
ROUND(AVG(avgpostdiast),0) as postdiast_avg,
round(100*(sum(IF(diast_post<80, '1','0'))/count(hdsesszid)),1) as pctpostdiastless80
FROM hdpatbpavg GROUP BY currentsite
UNION
SELECT 'Total', count(hdsesszid) as patcount, ROUND(AVG(avgpresyst),0) as presyst_avg,
round(100*(sum(IF(syst_pre<140, '1','0'))/count(hdsesszid)),1) as pctpresysless140,
ROUND(AVG(avgpostsyst),0) as postsys_avg,
round(100*(sum(IF(syst_post<130, '1','0'))/count(hdsesszid)),1) as pctpostsysless130,
ROUND(AVG(avgprediast),0) as prediast_avg,
round(100*(sum(IF(diast_pre<90, '1','0'))/count(hdsesszid)),1) as pctprediastless90,
ROUND(AVG(avgpostdiast),0) as postdiast_avg,
round(100*(sum(IF(diast_post<80, '1','0'))/count(hdsesszid)),1) as pctpostdiastless80
FROM hdpatbpavg;
Create TABLE HDpatBPsitemain as select * from hdpatbpsite WHERE patcount>@mintotal
ORDER BY patcount DESC;
UPDATE auditslist SET lastrun=NOW() WHERE auditcode='hdbpaudit';
DROP TABLE IF EXISTS hdbpdata;
DROP TABLE IF EXISTS hdpatbpavg;
DROP TABLE IF EXISTS hdpatbpsite;
*/
| {
"content_hash": "69d6507150a70103f347f85570b820cd",
"timestamp": "",
"source": "github",
"line_count": 80,
"max_line_length": 99,
"avg_line_length": 46.425,
"alnum_prop": 0.7514808831448573,
"repo_name": "airslie/renalware-core",
"id": "1c0ef68169341212cc7a98c44f07cd01dbe78f49",
"size": "3714",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "db/views/reporting_hd_blood_pressures_audit_v02.sql",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "9251"
},
{
"name": "Dockerfile",
"bytes": "4123"
},
{
"name": "Gherkin",
"bytes": "114740"
},
{
"name": "HTML",
"bytes": "36757"
},
{
"name": "JavaScript",
"bytes": "1330952"
},
{
"name": "PLpgSQL",
"bytes": "790250"
},
{
"name": "Procfile",
"bytes": "287"
},
{
"name": "Rich Text Format",
"bytes": "629"
},
{
"name": "Ruby",
"bytes": "4090100"
},
{
"name": "SCSS",
"bytes": "145750"
},
{
"name": "Shell",
"bytes": "11142"
},
{
"name": "Slim",
"bytes": "758115"
}
],
"symlink_target": ""
} |
package org.accept.util.files;
import java.io.File;
import java.io.FileFilter;
public class FolderActions {
final FileFilter filenameFilter;
final File rootDir;
public FolderActions(final String rootDir, final String fileFilterRegex) {
this(new File(rootDir), new FileFilter() {
public boolean accept(File file) {
if (file.isDirectory()) {
return true;
}
return file.getName().matches(fileFilterRegex);
}
});
}
public FolderActions(final File rootDir, final FileFilter filenameFilter) {
this.rootDir = rootDir;
assert rootDir.exists();
this.filenameFilter = filenameFilter;
}
public void act(FileContentHandler fileContentHandler) {
File[] files = rootDir.listFiles(filenameFilter);
for(File f: files) {
if (f.isDirectory()) {
new FolderActions(f, filenameFilter).act(fileContentHandler);
} else {
fileContentHandler.handle(f, new FileIO().read(f));
}
}
}
public void act(FileHandler fileHandler) {
File[] files = rootDir.listFiles(filenameFilter);
for(File f: files) {
if (f.isDirectory()) {
new FolderActions(f, filenameFilter).act(fileHandler);
} else {
fileHandler.handle(f);
}
}
}
public static FolderActions eachFile(String rootDir, String fileFilterRegex) {
return new FolderActions(rootDir, fileFilterRegex);
}
public static interface FileHandler {
public void handle(File file);
}
public static interface FileContentHandler {
public void handle(File file, String content);
}
}
| {
"content_hash": "6be9d36c65ace0ed4619e83432382562",
"timestamp": "",
"source": "github",
"line_count": 67,
"max_line_length": 79,
"avg_line_length": 23.91044776119403,
"alnum_prop": 0.6697877652933832,
"repo_name": "erpframework/accept",
"id": "2e37b1577b927fb63aefb5466ec4b63f66a436d3",
"size": "1602",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/org/accept/util/files/FolderActions.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "24"
},
{
"name": "CSS",
"bytes": "6838"
},
{
"name": "HTML",
"bytes": "83242"
},
{
"name": "Java",
"bytes": "178935"
},
{
"name": "JavaScript",
"bytes": "14666"
}
],
"symlink_target": ""
} |
from unittest import main
from numpy.testing import assert_array_equal
import numpy as np
from calour._testing import Tests
from calour.filtering import _balanced_subsample
import calour as ca
class FTests(Tests):
def setUp(self):
super().setUp()
self.test2 = ca.read(self.test2_biom, self.test2_samp, self.test2_feat, normalize=None)
self.test1 = ca.read(self.test1_biom, self.test1_samp, self.test1_feat, normalize=None)
def test_balanced_subsample(self):
rand = np.random.RandomState(None)
d = rand.choice([0, 1, 2], 9)
for n in (1, 3, 6, 9, 10):
keep = _balanced_subsample(d, n, None)
d2 = d[keep]
uniq, counts = np.unique(d2, return_counts=True)
self.assertTrue(np.all(counts == n))
def test_downsample_unique(self):
# test on features, random method, not inplace
# since each taxonomy is unique, should have the same as original
newexp = self.test1.downsample('taxonomy', axis=1)
self.assertEqual(newexp.shape, self.test1.shape)
self.assertIsNot(newexp, self.test1)
def test_downsample_keep_1(self):
# test on samples, random method, not inplace
newexp = self.test1.downsample('group', keep=1, random_seed=2017)
self.assertEqual(newexp.shape[0], 3)
self.assertEqual(list(newexp.data[:, 7].todense().A1), [845, 859, 9])
self.assertEqual(newexp.shape[1], self.test1.shape[1])
self.assertIsNot(newexp, self.test1)
newexp = self.test1.downsample('group', keep=1, random_seed=2018)
self.assertNotEqual(list(newexp.data[:, 7].todense().A1), [845, 859, 9])
def test_downsample_sample(self):
obs = self.test2.downsample('group')
# should be down to 4 samples; feature number is the same
self.assertEqual(obs.shape, (4, 8))
sid = obs.sample_metadata.index.tolist()
all_sid = self.test2.sample_metadata.index.tolist()
exp = self.test2.reorder([all_sid.index(i) for i in sid])
self.assert_experiment_equal(obs, exp)
def test_downsample_feature(self):
obs = self.test2.downsample('oxygen', axis=1)
sid = obs.feature_metadata.index.tolist()
self.assertEqual(obs.shape, (9, 4))
all_sid = self.test2.feature_metadata.index.tolist()
exp = self.test2.reorder([all_sid.index(i) for i in sid], axis=1)
self.assertEqual(obs, exp)
def test_downsample_keep(self):
# test keeping num_keep samples, and inplace
obs = self.test1.downsample('group', keep=9, inplace=True)
# should be down to 2 groups (18 samples); feature number is the same
self.assertEqual(obs.shape, (18, 12))
self.assertEqual(set(obs.sample_metadata['group']), set(['1', '2']))
self.assertIs(obs, self.test1)
def test_filter_by_metadata_sample_edge_cases(self):
# no group 3 - none filtered
obs = self.test2.filter_by_metadata('group', [3])
self.assertEqual(obs.shape, (0, 8))
obs = self.test2.filter_by_metadata('group', [3], negate=True)
self.assert_experiment_equal(obs, self.test2)
# all samples are filtered
obs = self.test2.filter_by_metadata('group', [1, 2])
self.assert_experiment_equal(obs, self.test2)
obs = self.test2.filter_by_metadata('group', [1, 2], negate=True)
self.assertEqual(obs.shape, (0, 8))
def test_filter_by_metadata_sample(self):
for sparse, inplace in [(True, False), (True, True), (False, False), (False, True)]:
test2 = ca.read(self.test2_biom, self.test2_samp, self.test2_feat,
sparse=sparse, normalize=None)
# only filter samples bewtween 3 and 7.
obs = test2.filter_by_metadata(
'ori.order', lambda l: [7 > i > 3 for i in l], inplace=inplace)
self.assertEqual(obs.shape, (3, 8))
self.assertEqual(obs.sample_metadata.index.tolist(), ['S5', 'S6', 'S7'])
if inplace:
self.assertIs(obs, test2)
else:
self.assertIsNot(obs, test2)
def test_filter_by_metadata_feature_edge_cases(self):
# none filtered
obs = self.test2.filter_by_metadata('oxygen', ['facultative'], axis=1)
self.assertEqual(obs.shape, (9, 0))
obs = self.test2.filter_by_metadata('oxygen', ['facultative'], axis=1, negate=True)
self.assert_experiment_equal(obs, self.test2)
def test_filter_by_metadata_feature(self):
for sparse, inplace in [(True, False), (True, True), (False, False), (False, True)]:
test2 = ca.read(self.test2_biom, self.test2_samp, self.test2_feat, sparse=sparse, normalize=None)
# only filter samples with id bewtween 3 and 7.
obs = test2.filter_by_metadata('oxygen', ['anaerobic'], axis=1, inplace=inplace)
self.assertEqual(obs.shape, (9, 2))
self.assertListEqual(obs.feature_metadata.index.tolist(), ['TG', 'TC'])
if inplace:
self.assertIs(obs, test2)
else:
self.assertIsNot(obs, test2)
def test_filter_by_metadata_na(self):
test = self.test2 = ca.read(self.test2_biom, self.test2_samp, self.test2_feat,
normalize=None, feature_metadata_kwargs={'na_values': 'B'})
test_drop = test.filter_by_metadata('level1', select=None, axis='f')
self.assertEqual(self.test2.sample_metadata.index.tolist(),
test_drop.sample_metadata.index.tolist())
self.assertEqual(['AT', 'AG', 'AC', 'TA', 'TT', 'TC'],
test_drop.feature_metadata.index.tolist())
def test_filter_by_data_sample_edge_cases(self):
# all samples are filtered out
obs = self.test2.filter_by_data('abundance', axis=0, cutoff=100000, mean_or_sum='sum')
self.assertEqual(obs.shape, (0, 8))
# none is filtered out
obs = self.test2.filter_by_data('abundance', axis=0, cutoff=1, mean_or_sum='sum')
self.assert_experiment_equal(obs, self.test2)
self.assertIsNot(obs, self.test2)
def test_filter_by_data_sample(self):
for sparse, inplace in [(True, False), (True, True), (False, False), (False, True)]:
test2 = ca.read(self.test2_biom, self.test2_samp, self.test2_feat, sparse=sparse, normalize=None)
# filter out samples with abundance < 1200. only the last sample is filtered out.
obs = test2.filter_by_data('abundance', axis=0, inplace=inplace, cutoff=1200, mean_or_sum='sum')
self.assertEqual(obs.shape, (8, 8))
self.assertNotIn('S9', obs.sample_metadata)
for sid in obs.sample_metadata.index:
assert_array_equal(obs[sid, :], self.test2[sid, :])
if inplace:
self.assertIs(obs, test2)
else:
self.assertIsNot(obs, test2)
def test_filter_by_data_feature_edge_cases(self):
# all features are filtered out
obs = self.test2.filter_by_data('abundance', axis=1, cutoff=10000, mean_or_sum='sum')
self.assertEqual(obs.shape, (9, 0))
# none is filtered out
obs = self.test2.filter_by_data('abundance', axis=1, cutoff=1, mean_or_sum='sum')
self.assert_experiment_equal(obs, self.test2)
self.assertIsNot(obs, self.test2)
def test_filter_by_data_feature(self):
# one feature is filtered out when cutoff is set to 25
for inplace in [True, False]:
obs = self.test2.filter_by_data('abundance', axis=1, inplace=inplace, cutoff=25, mean_or_sum='sum')
self.assertEqual(obs.shape, (9, 7))
self.assertNotIn('TA', obs.feature_metadata)
for fid in obs.feature_metadata.index:
assert_array_equal(obs[:, fid], self.test2[:, fid])
if inplace:
self.assertIs(obs, self.test2)
else:
self.assertIsNot(obs, self.test2)
def test_filter_prevalence(self):
# this should filter all features because the upper limit is 100%
exp = self.test1.filter_prevalence(fraction=0.5)
fids = ['AA', 'AT', 'AG', 'TA', 'TT', 'TG', 'TC', 'GG']
self.assertListEqual(exp.feature_metadata.index.tolist(), fids)
self.assertEqual(exp.shape[0], self.test1.shape[0])
def test_filter_prevalence_zero(self):
# keep only features present at least in 0.5 the samples
exp = self.test1.filter_prevalence(fraction=1.01)
self.assertListEqual(exp.feature_metadata.index.tolist(), [])
self.assertEqual(exp.shape[0], self.test1.shape[0])
def test_filter_prevalence_check(self):
# filter over all samples always filter more or euqal features than
# filter over sample groups
frac = 0.001
exp = self.test1.filter_prevalence(fraction=frac)
n = exp.shape[1]
for i in self.test1.sample_metadata.columns:
x = self.test1.filter_prevalence(fraction=frac, field=i)
self.assertLessEqual(x.shape[1], n)
def test_filter_sum_abundance(self):
exp = self.test1.filter_sum_abundance(17008)
self.assertEqual(exp.shape[1], 2)
fids = ['TC', 'GG']
self.assertListEqual(exp.feature_metadata.index.tolist(), fids)
def test_filter_mean_abundance(self):
# default is 0.01 - keep features with mean abundance >= 1%
test1 = self.test1.normalize()
exp = test1.filter_mean_abundance()
fids = ['AT', 'TG', 'TC', 'GG']
self.assertListEqual(exp.feature_metadata.index.tolist(), fids)
self.assertEqual(exp.shape[0], self.test1.shape[0])
exp = test1.filter_mean_abundance(0.4, field=None)
fids = ['TC', 'GG']
self.assertListEqual(exp.feature_metadata.index.tolist(), fids)
exp = test1.filter_mean_abundance(0.6, field=None)
self.assertListEqual(exp.feature_metadata.index.tolist(), [])
exp = test1.filter_mean_abundance(0.6, field='group')
fids = ['GG']
self.assertListEqual(exp.feature_metadata.index.tolist(), fids)
def test_filter_mean_abundance_check(self):
# filter over all samples always filter more or euqal features than
# filter over sample groups
abund = 0.001
exp = self.test1.filter_mean_abundance(abund)
n = exp.shape[1]
for i in self.test1.sample_metadata.columns:
x = self.test1.filter_mean_abundance(abund, field=i)
self.assertLessEqual(x.shape[1], n)
def test_filter_ids_not_in_list(self):
fids = ['GG', 'pita']
exp = self.test1.filter_ids(fids)
self.assertListEqual(exp.feature_metadata.index.tolist(), ['GG'])
def test_filter_ids_default(self):
fids = ['GG', 'AA', 'TT']
exp = self.test1.filter_ids(fids)
self.assertListEqual(exp.feature_metadata.index.tolist(), fids)
self.assertIsNot(exp, self.test1)
def test_filter_ids_samples_inplace_negate(self):
badsamples = ['S1', 'S3', 'S5', 'S7', 'S9', 'S11', 'S13', 'S15', 'S17', 'S19']
oksamples = list(set(self.test1.sample_metadata.index.values).difference(set(badsamples)))
exp = self.test1.filter_ids(badsamples, axis=0, negate=True, inplace=True)
self.assertCountEqual(list(exp.sample_metadata.index.values), oksamples)
self.assertIs(exp, self.test1)
def test_filter_sample_group(self):
test = self.test1.filter_ids(['badsample'], axis=0, negate=True)
# does not filter anything
self.assert_experiment_equal(test.filter_sample_group('group', 9), test)
# filter group of 2
self.assert_experiment_equal(test.filter_sample_group('group', 10),
test.filter_samples('group', '1'))
def test_filter_samples_edge_cases(self):
# no group 3 - none filtered
test1 = ca.read(self.test1_biom, self.test1_samp, self.test1_feat, normalize=None)
# group dtype is O
obs = test1.filter_samples('group', ['3'])
self.assertEqual(obs.shape, (0, 12))
obs = test1.filter_samples('group', ['3'], negate=True)
self.assert_experiment_equal(obs, test1)
def test_filter_samples_na(self):
test1 = ca.read(self.test1_biom, self.test1_samp, self.test1_feat, normalize=None)
# filter na value in group column
obs = test1.filter_samples('group', None)
self.assertEqual(obs.shape, (20, 12))
self.assertEqual(test1.sample_metadata.dropna(axis=0).index.tolist(),
obs.sample_metadata.index.tolist())
def test_filter_samples(self):
for inplace in [True, False]:
test1 = ca.read(self.test1_biom, self.test1_samp, self.test1_feat, normalize=None)
# only filter samples from 11 to 14.
obs = test1.filter_samples('id', list(range(11, 15)), inplace=inplace)
self.assertEqual(obs.shape, (4, 12))
self.assertEqual(obs.sample_metadata.index.tolist(), ['S11', 'S12', 'S13', 'S14'])
if inplace:
self.assertIs(obs, test1)
else:
self.assertIsNot(obs, test1)
def test_filter_features_edge_cases(self):
# none filtered
obs = self.test2.filter_features('oxygen', ['facultative'])
self.assertEqual(obs.shape, (9, 0))
obs = self.test2.filter_features('oxygen', ['facultative'], negate=True)
self.assert_experiment_equal(obs, self.test2)
def test_filter_features(self):
for inplace in [True, False]:
test2 = ca.read(self.test2_biom, self.test2_samp, self.test2_feat, normalize=None)
obs = test2.filter_features('oxygen', ['anaerobic'], inplace=inplace)
self.assertEqual(obs.shape, (9, 2))
self.assertListEqual(obs.feature_metadata.index.tolist(), ['TG', 'TC'])
if inplace:
self.assertIs(obs, test2)
else:
self.assertIsNot(obs, test2)
if __name__ == '__main__':
main()
| {
"content_hash": "36dd78539930b9cd5ffc26c653e59a21",
"timestamp": "",
"source": "github",
"line_count": 306,
"max_line_length": 111,
"avg_line_length": 46.31699346405229,
"alnum_prop": 0.6118676356452409,
"repo_name": "RNAer/Calour",
"id": "2ab91da2a6fccd2c6d544f8c3bdd4516b9d49125",
"size": "14524",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "calour/tests/test_filtering.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Gherkin",
"bytes": "5338"
},
{
"name": "Jupyter Notebook",
"bytes": "270154"
},
{
"name": "Makefile",
"bytes": "927"
},
{
"name": "Python",
"bytes": "247846"
}
],
"symlink_target": ""
} |
/**
* Given a binary tree, find its minimum depth.
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*
* @param {TreeNode} treeNode
* @return {number}
*/
var minimumDepthOfBinaryTree = function(treeNode) {
return treeNode === null ?
0 :
1 + Math.min(minimumDepthOfBinaryTree(treeNode.left), minimumDepthOfBinaryTree(treeNode.right));
};
| {
"content_hash": "fa5385685c12b9afad0a1c7a4bb572ce",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 100,
"avg_line_length": 25.58823529411765,
"alnum_prop": 0.664367816091954,
"repo_name": "Dbz/Algorithms",
"id": "0a8e5cc805ebedc4614ec9c0af0b9d3242fa890e",
"size": "435",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "algorithms/minimum-depth-of-binary-tree.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "27629"
},
{
"name": "Python",
"bytes": "9783"
},
{
"name": "Ruby",
"bytes": "86502"
}
],
"symlink_target": ""
} |
/*
* 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.
*/
/*
* This code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.adexchangebuyer2.v2beta1.model;
/**
* Response message for listing all reasons that bid requests were filtered and not sent to the
* buyer.
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the Ad Exchange Buyer API II. For a detailed explanation
* see:
* <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a>
* </p>
*
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public final class ListFilteredBidRequestsResponse extends com.google.api.client.json.GenericJson {
/**
* List of rows, with counts of filtered bid requests aggregated by callout status.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<CalloutStatusRow> calloutStatusRows;
static {
// hack to force ProGuard to consider CalloutStatusRow used, since otherwise it would be stripped out
// see https://github.com/google/google-api-java-client/issues/543
com.google.api.client.util.Data.nullOf(CalloutStatusRow.class);
}
/**
* A token to retrieve the next page of results. Pass this value in the
* ListFilteredBidRequestsRequest.pageToken field in the subsequent call to the
* filteredBidRequests.list method to retrieve the next page of results.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String nextPageToken;
/**
* List of rows, with counts of filtered bid requests aggregated by callout status.
* @return value or {@code null} for none
*/
public java.util.List<CalloutStatusRow> getCalloutStatusRows() {
return calloutStatusRows;
}
/**
* List of rows, with counts of filtered bid requests aggregated by callout status.
* @param calloutStatusRows calloutStatusRows or {@code null} for none
*/
public ListFilteredBidRequestsResponse setCalloutStatusRows(java.util.List<CalloutStatusRow> calloutStatusRows) {
this.calloutStatusRows = calloutStatusRows;
return this;
}
/**
* A token to retrieve the next page of results. Pass this value in the
* ListFilteredBidRequestsRequest.pageToken field in the subsequent call to the
* filteredBidRequests.list method to retrieve the next page of results.
* @return value or {@code null} for none
*/
public java.lang.String getNextPageToken() {
return nextPageToken;
}
/**
* A token to retrieve the next page of results. Pass this value in the
* ListFilteredBidRequestsRequest.pageToken field in the subsequent call to the
* filteredBidRequests.list method to retrieve the next page of results.
* @param nextPageToken nextPageToken or {@code null} for none
*/
public ListFilteredBidRequestsResponse setNextPageToken(java.lang.String nextPageToken) {
this.nextPageToken = nextPageToken;
return this;
}
@Override
public ListFilteredBidRequestsResponse set(String fieldName, Object value) {
return (ListFilteredBidRequestsResponse) super.set(fieldName, value);
}
@Override
public ListFilteredBidRequestsResponse clone() {
return (ListFilteredBidRequestsResponse) super.clone();
}
}
| {
"content_hash": "f6b06d373de81b1c38b78875b7aeaa2a",
"timestamp": "",
"source": "github",
"line_count": 104,
"max_line_length": 182,
"avg_line_length": 38.42307692307692,
"alnum_prop": 0.744994994994995,
"repo_name": "googleapis/google-api-java-client-services",
"id": "7460abe3868e74b656556a2727fff03d685b37ab",
"size": "3996",
"binary": false,
"copies": "7",
"ref": "refs/heads/main",
"path": "clients/google-api-services-adexchangebuyer2/v2beta1/2.0.0/com/google/api/services/adexchangebuyer2/v2beta1/model/ListFilteredBidRequestsResponse.java",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<jobs xmlns="urn:arwo:choice1">
<job jobEnabled="true" jobName="job1">
<taskA attributeA="" taskEnabled="false" taskName=""/>
</job>
<job jobEnabled="false" jobName="job2">
<taskB attributeB="" taskEnabled="false" taskName=""/>
</job>
<job jobEnabled="true" jobName="job3">
<taskC attributeC="" taskEnabled="false" taskName=""/>
</job>
</jobs>
| {
"content_hash": "162625403427772cc7a0eec18010b90b",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 62,
"avg_line_length": 37.25,
"alnum_prop": 0.6129753914988815,
"repo_name": "greyp9/arwo",
"id": "45d54332d86455be9744579002c2b8b19f4dfe34",
"size": "447",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/test/core/resources/io/github/greyp9/arwo/xsd/choice1/choice1-A.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "7897"
},
{
"name": "HTML",
"bytes": "26765"
},
{
"name": "Java",
"bytes": "2570281"
},
{
"name": "XSLT",
"bytes": "25589"
}
],
"symlink_target": ""
} |
import React from 'react';
var id;
var name = "";
var time = "";
var pic = "";
var url = "";
var title = "";
var indexPlay;
var indexName;
var sourceIndex;
const History = React.createClass({
render(){
return null;
}
,
setId(id){
this.id = id;
},
getId(){
return this.id;
},
setName(name){
this.name = name;
},
getName(){
return this.name;
},
setTime(time){
this.time = time;
},
getTime(){
return this.time;
},
setPic(pic){
this.pic = pic;
},
getPic(){
return this.pic;
},
setUrl(url){
this.url = url;
},
getUrl(){
return this.url;
},
setTitle(title){
this.title = title;
},
getTitle(){
return this.title;
},
setIndexPlay(index){
this.indexPlay = index;
},
getIndexPlay(){
return this.indexPlay;
},
setIndexName(name){
this.indexName = name;
},
getIndexName(){
return this.indexName;
},
setSourceIndex(source){
this.sourceIndex = source;
},
getSourceIndex(){
return this.sourceIndex;
}
});
module.exports = History;
| {
"content_hash": "36c305988b92c60a5637f55e8110a9a5",
"timestamp": "",
"source": "github",
"line_count": 73,
"max_line_length": 35,
"avg_line_length": 16.767123287671232,
"alnum_prop": 0.5008169934640523,
"repo_name": "helengray/XiFan",
"id": "a9555365793ebf4762885734cb7100ca2f7c1555",
"size": "1225",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "js/db/History.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "16575"
},
{
"name": "JavaScript",
"bytes": "89146"
},
{
"name": "Objective-C",
"bytes": "5075"
},
{
"name": "Python",
"bytes": "1635"
},
{
"name": "Swift",
"bytes": "512"
}
],
"symlink_target": ""
} |
package neo.matrix.reversing.model;
import java.math.BigDecimal;
public interface Time {
BigDecimal getPosition();
}
| {
"content_hash": "20cc2b007f9ec32b14594dec423e13cf",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 35,
"avg_line_length": 13.88888888888889,
"alnum_prop": 0.752,
"repo_name": "timtish/matrix-world-emulator",
"id": "9960b158e5d5383c1feec48670e78fd284a82352",
"size": "125",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "core/src/main/java/neo/matrix/reversing/model/Time.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "6251"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<!-- Please enter language data in the fields below. All data should be entered in English -->
<ldml xmlns:sil="urn://www.sil.org/ldml/0.1">
<identity>
<version number="0.0.1"/>
<!-- name.en(pbi)="Parkwa" -->
<language type="pbi"/>
<special>
<sil:identity defaultRegion="CM" script="Latn"/>
</special>
</identity>
<localeDisplayNames>
<languages>
<language type="pbi">Gwaɗi Parəkwa</language>
</languages>
<special>
<sil:names>
<sil:name xml:lang="en">Parkwa</sil:name>
</sil:names>
</special>
</localeDisplayNames>
<characters>
<exemplarCharacters>[a b ɓ c d {dz} ɗ e ə f g {gw} h {hw} i ɨ j k {kw} l m {mb} n {nd} {ndz} {nj} ŋ {ŋg} {ŋgw} {ŋw} p r s {sh} {sl} t {ts} u v w y z {zh} {zl}]</exemplarCharacters>
<exemplarCharacters type="auxiliary">[o q x]</exemplarCharacters>
</characters>
<special>
<sil:external-resources>
<sil:font name="Charis SIL" types="default" features="cv43=0">
<sil:url>https://wirl.api.sil.org/CharisSILReg&type=ttf</sil:url>
</sil:font>
<sil:font name="Noto Sans"><!--types="ui"-->
<sil:url>https://github.com/googlefonts/noto-fonts/raw/main/hinted/ttf/NotoSans/NotoSans-Regular.ttf</sil:url>
</sil:font>
<sil:font name="Noto Serif">
<sil:url>https://github.com/googlefonts/noto-fonts/raw/main/hinted/ttf/NotoSerif/NotoSerif-Regular.ttf</sil:url>
</sil:font>
<sil:kbd id="sil_cameroon_azerty" type="kmp">
<sil:url draft="generated">https://keyman.com/go/keyboard/sil_cameroon_azerty/download/kmp</sil:url>
</sil:kbd>
<sil:kbd id="sil_cameroon_qwerty" type="kmp">
<sil:url draft="generated">https://keyman.com/go/keyboard/sil_cameroon_qwerty/download/kmp</sil:url>
</sil:kbd>
</sil:external-resources>
</special>
</ldml>
| {
"content_hash": "ae678b7e050788c10191ac065d733f05",
"timestamp": "",
"source": "github",
"line_count": 45,
"max_line_length": 182,
"avg_line_length": 39.84444444444444,
"alnum_prop": 0.6614612381483547,
"repo_name": "silnrsi/sldr",
"id": "2fffbb9095d1cbd5c07f76d500ca070be7592751",
"size": "1803",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "sldr/p/pbi.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "100863"
},
{
"name": "JavaScript",
"bytes": "99270"
},
{
"name": "Less",
"bytes": "486"
},
{
"name": "Makefile",
"bytes": "224"
},
{
"name": "Python",
"bytes": "28201"
},
{
"name": "Shell",
"bytes": "80"
}
],
"symlink_target": ""
} |
import clr
clr.AddReference('RevitAPI')
from Autodesk.Revit.DB import *
clr.AddReference("RevitNodes")
import Revit
clr.ImportExtensions(Revit.Elements)
def GetSheetSetViews(set):
if hasattr(set, 'Views'):
return [x.ToDSType(True) for x in set.Views]
else: return []
viewsheetsets = UnwrapElement(IN[0])
if isinstance(IN[0], list): OUT = [GetSheetSetViews(x) for x in viewsheetsets]
else: OUT = GetSheetSetViews(viewsheetsets) | {
"content_hash": "758a8cd289e73f62f8c2fc3655d815a3",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 78,
"avg_line_length": 25.529411764705884,
"alnum_prop": 0.7603686635944701,
"repo_name": "CAAD-RWTH/ClockworkForDynamo",
"id": "725ee11f7447ae3b71b4e5ee5af9e9c86b09a6f4",
"size": "434",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "nodes/2.x/python/ViewSheetSet.Views.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "316146"
}
],
"symlink_target": ""
} |
package org.dashbuilder.client.gallery;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.context.Dependent;
import javax.inject.Inject;
import org.dashbuilder.client.resources.i18n.AppConstants;
import org.dashbuilder.dataset.filter.FilterFactory;
import org.dashbuilder.displayer.DisplayerSettings;
import org.dashbuilder.displayer.DisplayerSettingsFactory;
import org.dashbuilder.dataset.DataSetFactory;
import org.dashbuilder.displayer.client.json.DisplayerSettingsJSONMarshaller;
import org.dashbuilder.renderer.client.DefaultRenderer;
import org.uberfire.mvp.PlaceRequest;
import org.uberfire.mvp.impl.DefaultPlaceRequest;
import static org.dashbuilder.dataset.group.DateIntervalType.*;
import static org.dashbuilder.dataset.filter.FilterFactory.*;
import static org.dashbuilder.dataset.sort.SortOrder.*;
import static org.dashbuilder.dataset.date.Month.*;
import static org.dashbuilder.shared.sales.SalesConstants.*;
import static org.dashbuilder.dataset.group.AggregateFunctionType.*;
/**
* The Gallery tree.
*/
@Dependent
public class GalleryTree {
private List<GalleryTreeNode> mainNodes = new ArrayList<GalleryTreeNode>();
@Inject DisplayerSettingsJSONMarshaller jsonHelper;
public List<GalleryTreeNode> getMainNodes() {
return mainNodes;
}
@PostConstruct
private void init() {
initBarChartCategory();
initPieChartCategory();
initLineChartCategory();
initAreaChartCategory();
initBubbleChartCategory();
initTableReportCategory();
initMeterChartCategory();
initMetricCategory();
initMapChartCategory();
initDashboardCategory();
}
private PlaceRequest createPlaceRequest(DisplayerSettings displayerSettings) {
String json = jsonHelper.toJsonString(displayerSettings);
Map<String,String> params = new HashMap<String,String>();
params.put("json", json);
params.put("edit", "false");
params.put("showRendererSelector", "true");
return new DefaultPlaceRequest("DisplayerScreen", params);
}
private PlaceRequest createPlaceRequest(String widgetId) {
Map<String,String> params = new HashMap<String,String>();
params.put("widgetId", widgetId);
return new DefaultPlaceRequest("GalleryWidgetScreen", params);
}
private void initBarChartCategory() {
GalleryTreeNodeList nodeList = new GalleryTreeNodeList(AppConstants.INSTANCE.gallerytree_bar());
mainNodes.add(nodeList);
nodeList.add(new GalleryPlaceRequest(AppConstants.INSTANCE.gallerytree_bar_horiz(), createPlaceRequest(
DisplayerSettingsFactory.newBarChartSettings()
.subType_Bar()
.dataset(SALES_OPPS)
.group(PRODUCT)
.column(PRODUCT, "Product")
.column(AMOUNT, SUM)
.expression("value/1000")
.format(AppConstants.INSTANCE.gallerytree_bar_horiz_column1(), "$ #,### K")
.title(AppConstants.INSTANCE.gallerytree_bar_horiz_title())
.width(600).height(400)
.resizableOn(1200, 800)
.margins(50, 80, 120, 120)
.filterOn(false, true, true)
.buildSettings()
)));
nodeList.add(new GalleryPlaceRequest(AppConstants.INSTANCE.gallerytree_bar_vert(), createPlaceRequest(
DisplayerSettingsFactory.newBarChartSettings()
.subType_Column()
.dataset(SALES_OPPS)
.group(PRODUCT)
.column(PRODUCT, "Product")
.column(AMOUNT, SUM).format(AppConstants.INSTANCE.gallerytree_bar_vert_column1(), "$ #,###")
.title(AppConstants.INSTANCE.gallerytree_bar_vert_title())
.set3d(true)
.width(600).height(400)
.resizableOn(1200, 800)
.margins(50, 80, 120, 120)
.filterOn(false, true, true)
.buildSettings()
)));
nodeList.add(new GalleryPlaceRequest(AppConstants.INSTANCE.gallerytree_bar_multi(), createPlaceRequest(
DisplayerSettingsFactory.newBarChartSettings()
.subType_Bar()
.dataset(SALES_OPPS)
.group(COUNTRY)
.column(COUNTRY, "Country")
.column(AMOUNT, MIN).format(AppConstants.INSTANCE.gallerytree_bar_multi_column1(), "$ #,###")
.column(AMOUNT, MAX).format(AppConstants.INSTANCE.gallerytree_bar_multi_column2(), "$ #,###")
.column(AMOUNT, AVERAGE).format(AppConstants.INSTANCE.gallerytree_bar_multi_column3(), "$ #,###")
.title(AppConstants.INSTANCE.gallerytree_bar_multi_title())
.width(700).height(600)
.resizableOn(1200, 800)
.margins(50, 80, 120, 120)
.filterOn(false, true, true)
.buildSettings()
)));
nodeList.add(new GalleryPlaceRequest(AppConstants.INSTANCE.gallerytree_bar_stacked(), createPlaceRequest(
DisplayerSettingsFactory.newBarChartSettings()
.subType_StackedColumn()
.dataset(SALES_OPPS)
.group(COUNTRY)
.column(COUNTRY, "Country")
.column(AMOUNT, MIN).format(AppConstants.INSTANCE.gallerytree_bar_multi_column1(), "$ #,###")
.column(AMOUNT, MAX).format(AppConstants.INSTANCE.gallerytree_bar_multi_column2(), "$ #,###")
.column(AMOUNT, AVERAGE).format(AppConstants.INSTANCE.gallerytree_bar_multi_column3(), "$ #,###")
.title(AppConstants.INSTANCE.gallerytree_bar_multi_title())
.width(800).height(400)
.margins(50, 80, 120, 120)
.legendOn("top")
.filterOn(false, true, true)
.buildSettings()
)));
nodeList.add(new GalleryPlaceRequest(AppConstants.INSTANCE.gallerytree_bar_vert_dd(), createPlaceRequest(
DisplayerSettingsFactory.newBarChartSettings()
.subType_Column()
.dataset(SALES_OPPS)
.group(PIPELINE)
.column(PIPELINE, "Pipeline")
.column(AMOUNT, SUM).format(AppConstants.INSTANCE.gallerytree_bar_vert_dd_column1(), "$ #,###")
.group(STATUS)
.column(STATUS, "Status")
.column(AMOUNT, SUM).format(AppConstants.INSTANCE.gallerytree_bar_vert_dd_column2(), "$ #,###")
.group(SALES_PERSON)
.column(SALES_PERSON, "Sales person")
.column(AMOUNT, SUM).format(AppConstants.INSTANCE.gallerytree_bar_vert_dd_column3(), "$ #,###")
.title(AppConstants.INSTANCE.gallerytree_bar_vert_dd_title())
.width(600).height(400)
.resizableOn(1200, 800)
.margins(50, 80, 120, 120)
.filterOn(true, false, false)
.buildSettings()
)));
}
private void initPieChartCategory() {
GalleryTreeNodeList nodeList = new GalleryTreeNodeList(AppConstants.INSTANCE.gallerytree_pie());
mainNodes.add(nodeList);
nodeList.add(new GalleryPlaceRequest(AppConstants.INSTANCE.gallerytree_pie_basic(), createPlaceRequest(
DisplayerSettingsFactory.newPieChartSettings()
.dataset(SALES_OPPS)
.group(STATUS)
.column(STATUS)
.column(AMOUNT, SUM).format(AppConstants.INSTANCE.gallerytree_pie_basic_column1(), "$ #,###")
.title(AppConstants.INSTANCE.gallerytree_pie_basic_title())
.width(500)
.margins(10, 10, 10, 150)
.subType_Pie()
.legendOn("right")
.resizableOn(1200, 800)
.filterOn(false, true, true)
.buildSettings()
)));
nodeList.add(new GalleryPlaceRequest(AppConstants.INSTANCE.gallerytree_pie_3d(), createPlaceRequest(
DisplayerSettingsFactory.newPieChartSettings()
.dataset(SALES_OPPS)
.group(STATUS)
.column(STATUS)
.column(AMOUNT, SUM).format(AppConstants.INSTANCE.gallerytree_pie_3d_column1(), "$ #,###")
.title(AppConstants.INSTANCE.gallerytree_pie_3d_title())
.width(500)
.margins(10, 10, 10, 150)
.subType_Pie_3d()
.legendOn("right")
.resizableOn(1200, 800)
.filterOn(false, true, true)
.buildSettings()
)));
nodeList.add(new GalleryPlaceRequest(AppConstants.INSTANCE.gallerytree_pie_donut(), createPlaceRequest(
DisplayerSettingsFactory.newPieChartSettings()
.dataset(SALES_OPPS)
.group(STATUS)
.column(STATUS)
.column(AMOUNT, SUM).format(AppConstants.INSTANCE.gallerytree_pie_donut_column1(), "$ #,###")
.title(AppConstants.INSTANCE.gallerytree_pie_donut_title())
.width(500)
.margins(10, 10, 10, 150)
.subType_Donut()
.legendOn("right")
.margins(10, 10, 10, 10)
.resizableOn(1200, 800)
.filterOn(false, true, true)
.buildSettings()
)));
nodeList.add(new GalleryPlaceRequest(AppConstants.INSTANCE.gallerytree_pie_dd(), createPlaceRequest(
DisplayerSettingsFactory.newPieChartSettings()
.dataset(SALES_OPPS)
.group(PIPELINE)
.column(PIPELINE, "Pipeline")
.column(AMOUNT, SUM).format(AppConstants.INSTANCE.gallerytree_pie_dd_column1(), "$ #,###")
.group(STATUS)
.column(STATUS, "Status")
.column(AMOUNT, SUM).format(AppConstants.INSTANCE.gallerytree_pie_dd_column2(), "$ #,###")
.group(SALES_PERSON)
.column(SALES_PERSON, "Sales person")
.column(AMOUNT, SUM).format(AppConstants.INSTANCE.gallerytree_pie_dd_column3(), "$ #,###")
.title(AppConstants.INSTANCE.gallerytree_pie_dd_title())
.margins(10, 10, 10, 10)
.resizableOn(1200, 800)
.filterOn(true, false, false)
.buildSettings()
)));
}
private void initLineChartCategory() {
GalleryTreeNodeList nodeList = new GalleryTreeNodeList(AppConstants.INSTANCE.gallerytree_line());
mainNodes.add(nodeList);
nodeList.add(new GalleryPlaceRequest(AppConstants.INSTANCE.gallerytree_line_basic(), createPlaceRequest(
DisplayerSettingsFactory.newLineChartSettings()
.dataset(SALES_OPPS)
.group(CLOSING_DATE).dynamic(12, MONTH, true)
.column(CLOSING_DATE).format(AppConstants.INSTANCE.gallerytree_line_basic_column1(), "MMM dd, yyyy")
.column(AMOUNT, SUM).format(AppConstants.INSTANCE.gallerytree_line_basic_column2(), "$ #,###")
.title(AppConstants.INSTANCE.gallerytree_line_basic_title())
.margins(20, 50, 100, 120)
.filterOn(false, true, true)
.buildSettings()
)));
nodeList.add(new GalleryPlaceRequest(AppConstants.INSTANCE.gallerytree_line_multi(), createPlaceRequest(
DisplayerSettingsFactory.newLineChartSettings()
.dataset(SALES_OPPS)
.group(COUNTRY)
.column(COUNTRY, "Country")
.column(AMOUNT, MIN).format(AppConstants.INSTANCE.gallerytree_line_multi_column1(), "$ #,###")
.column(AMOUNT, MAX).format(AppConstants.INSTANCE.gallerytree_line_multi_column2(), "$ #,###")
.column(AMOUNT, AVERAGE).format(AppConstants.INSTANCE.gallerytree_line_multi_column3(), "$ #,###")
.title(AppConstants.INSTANCE.gallerytree_line_multi_title())
.margins(30, 100, 80, 80)
.filterOn(false, true, true)
.buildSettings()
)));
nodeList.add(new GalleryPlaceRequest(AppConstants.INSTANCE.gallerytree_line_multi_static(), createPlaceRequest(
DisplayerSettingsFactory.newLineChartSettings()
.title(AppConstants.INSTANCE.gallerytree_line_multi_static_title())
.margins(20, 80, 50, 120)
.column("month", "Month")
.column("2014").format(AppConstants.INSTANCE.gallerytree_line_multi_static_column1(), "$ #,###")
.column("2015").format(AppConstants.INSTANCE.gallerytree_line_multi_static_column2(), "$ #,###")
.column("2016").format(AppConstants.INSTANCE.gallerytree_line_multi_static_column3(), "$ #,###")
.dataset(DataSetFactory.newDataSetBuilder()
.label("month")
.number("2014")
.number("2015")
.number("2016")
.row(JANUARY, 1000d, 2000d, 3000d)
.row(FEBRUARY, 1400d, 2300d, 2000d)
.row(MARCH, 1300d, 2000d, 1400d)
.row(APRIL, 900d, 2100d, 1500d)
.row(MAY, 1300d, 2300d, 1600d)
.row(JUNE, 1010d, 2000d, 1500d)
.row(JULY, 1050d, 2400d, 3000d)
.row(AUGUST, 2300d, 2000d, 3200d)
.row(SEPTEMBER, 1900d, 2700d, 3000d)
.row(OCTOBER, 1200d, 2200d, 3100d)
.row(NOVEMBER, 1400d, 2100d, 3100d)
.row(DECEMBER, 1100d, 2100d, 4200d)
.buildDataSet())
.buildSettings()
)));
// nodeList.add(new GalleryNodeDisplayer("Multiple (date)", ...)));
}
private void initAreaChartCategory() {
GalleryTreeNodeList nodeList = new GalleryTreeNodeList(AppConstants.INSTANCE.gallerytree_area());
mainNodes.add(nodeList);
nodeList.add(new GalleryPlaceRequest(AppConstants.INSTANCE.gallerytree_area_basic(), createPlaceRequest(
DisplayerSettingsFactory.newAreaChartSettings()
.dataset(SALES_OPPS)
.group(CLOSING_DATE).dynamic(24, MONTH, true)
.column(CLOSING_DATE, "Closing date")
.column(EXPECTED_AMOUNT, SUM).format(AppConstants.INSTANCE.gallerytree_area_basic_column1(), "$ #,###")
.title(AppConstants.INSTANCE.gallerytree_area_basic_title())
.width(700).height(300)
.margins(20, 50, 100, 120)
.filterOn(false, true, true)
.buildSettings()
)));
nodeList.add(new GalleryPlaceRequest(AppConstants.INSTANCE.gallerytree_area_fixed(), createPlaceRequest(
DisplayerSettingsFactory.newAreaChartSettings()
.dataset(SALES_OPPS)
.group(CLOSING_DATE).fixed(MONTH, true).firstMonth(JANUARY).asc()
.column(CLOSING_DATE).format(AppConstants.INSTANCE.gallerytree_area_fixed_column1())
.column(EXPECTED_AMOUNT, SUM).format(AppConstants.INSTANCE.gallerytree_area_fixed_column2(), "$ #,###")
.title(AppConstants.INSTANCE.gallerytree_area_fixed_title())
.margins(20, 80, 100, 100)
.filterOn(false, true, true)
.buildSettings()
)));
nodeList.add(new GalleryPlaceRequest(AppConstants.INSTANCE.gallerytree_area_dd(), createPlaceRequest(
DisplayerSettingsFactory.newAreaChartSettings()
.dataset(SALES_OPPS)
.group(CLOSING_DATE).dynamic(12, true)
.column(CLOSING_DATE).format(AppConstants.INSTANCE.gallerytree_area_dd_column1())
.column(EXPECTED_AMOUNT, SUM).format(AppConstants.INSTANCE.gallerytree_area_dd_column2(), "$ #,###")
.title(AppConstants.INSTANCE.gallerytree_area_dd_title())
.margins(20, 70, 100, 120)
.filterOn(true, true, true)
.buildSettings()
)));
}
private void initBubbleChartCategory() {
GalleryTreeNodeList nodeList = new GalleryTreeNodeList(AppConstants.INSTANCE.gallerytree_bubble());
mainNodes.add(nodeList);
nodeList.add(new GalleryPlaceRequest(AppConstants.INSTANCE.gallerytree_bubble_basic(), createPlaceRequest(
DisplayerSettingsFactory.newBubbleChartSettings()
.dataset(SALES_OPPS)
.group(COUNTRY)
.column(COUNTRY, "Country")
.column(COUNT, "#opps").format(AppConstants.INSTANCE.gallerytree_bubble_basic_column1(), "#,###")
.column(PROBABILITY, AVERAGE).format(AppConstants.INSTANCE.gallerytree_bubble_basic_column2(), "#,###")
.column(COUNTRY, AppConstants.INSTANCE.gallerytree_bubble_basic_column4())
.column(EXPECTED_AMOUNT, SUM).format(AppConstants.INSTANCE.gallerytree_bubble_basic_column3(), "$ #,###")
.title(AppConstants.INSTANCE.gallerytree_bubble_basic_title())
.width(700).height(400)
.margins(20, 50, 50, 0)
.filterOn(false, true, true)
.buildSettings()
)));
}
private void initMeterChartCategory() {
GalleryTreeNodeList nodeList = new GalleryTreeNodeList(AppConstants.INSTANCE.gallerytree_meter());
mainNodes.add(nodeList);
nodeList.add(new GalleryPlaceRequest(AppConstants.INSTANCE.gallerytree_meter_basic(), createPlaceRequest(
DisplayerSettingsFactory.newMeterChartSettings()
.title(AppConstants.INSTANCE.gallerytree_meter_basic_title())
.dataset(SALES_OPPS)
.column(AMOUNT, SUM)
.expression("value/1000")
.format(AppConstants.INSTANCE.gallerytree_meter_basic_column1(), "$ #,### K")
.width(400).height(200)
.meter(0, 15000, 25000, 35000)
.filterOn(false, true, true)
.buildSettings()
)));
nodeList.add(new GalleryPlaceRequest(AppConstants.INSTANCE.gallerytree_meter_multi(), createPlaceRequest(
DisplayerSettingsFactory.newMeterChartSettings()
.title(AppConstants.INSTANCE.gallerytree_meter_multi_title())
.dataset(SALES_OPPS)
.group(CREATION_DATE).dynamic(12, YEAR, true)
.column(CREATION_DATE, "Year")
.column(AMOUNT, SUM)
.expression("value/1000")
.format(AppConstants.INSTANCE.gallerytree_meter_multi_column1(), "$ #,###")
.width(600).height(200)
.meter(0, 1000, 3000, 5000)
.filterOn(false, true, true)
.buildSettings()
)));
nodeList.add(new GalleryPlaceRequest(AppConstants.INSTANCE.gallerytree_meter_multi_static(), createPlaceRequest(
DisplayerSettingsFactory.newMeterChartSettings()
.title(AppConstants.INSTANCE.gallerytree_meter_multi_static_title())
.width(500).height(200)
.meter(30, 160, 190, 220)
.column("person").format(AppConstants.INSTANCE.gallerytree_meter_multi_static_column1())
.column("heartRate").format(AppConstants.INSTANCE.gallerytree_meter_multi_static_column2(), "#,### bpm")
.dataset(DataSetFactory.newDataSetBuilder()
.label("person")
.number("heartRate")
.row("David", 52)
.row("Roger", 120)
.row("Mark", 74)
.row("Michael", 78)
.row("Kris", 74)
.buildDataSet())
.buildSettings()
)));
// nodeList.add(new GalleryNodeDisplayer("Multiple (date)", ...)));
}
private void initMetricCategory() {
GalleryTreeNodeList nodeList = new GalleryTreeNodeList(AppConstants.INSTANCE.gallerytree_metrics());
mainNodes.add(nodeList);
nodeList.add(new GalleryPlaceRequest(AppConstants.INSTANCE.gallerytree_metrics_basic(), createPlaceRequest(
DisplayerSettingsFactory.newMetricSettings()
.title(AppConstants.INSTANCE.gallerytree_metrics_basic_title())
.titleVisible(true)
.dataset(SALES_OPPS)
.filter(CLOSING_DATE, timeFrame("begin[quarter February] till now"))
.column(AMOUNT, SUM).expression("value/1000").format(AppConstants.INSTANCE.gallerytree_metrics_basic_column1(), "$ #,### K")
.width(300).height(200)
.margins(50, 50, 50, 50)
.backgroundColor("FDE8D4")
.filterOn(false, false, true)
.buildSettings()
)));
nodeList.add(new GalleryPlaceRequest(AppConstants.INSTANCE.gallerytree_metrics_basic_static(), createPlaceRequest(
DisplayerSettingsFactory.newMetricSettings()
.title(AppConstants.INSTANCE.gallerytree_metrics_basic_static_title())
.titleVisible(true)
.column("tweets").format(AppConstants.INSTANCE.gallerytree_metrics_basic_static_column1(), "#,###")
.width(300).height(200)
.margins(50, 50, 50, 50)
.backgroundColor("ADE8D4")
.filterOn(false, false, true)
.dataset(DataSetFactory.newDataSetBuilder()
.number("tweets")
.row(54213d)
.buildDataSet())
.buildSettings()
)));
}
private void initMapChartCategory() {
GalleryTreeNodeList nodeList = new GalleryTreeNodeList(AppConstants.INSTANCE.gallerytree_map());
mainNodes.add(nodeList);
nodeList.add(new GalleryPlaceRequest(AppConstants.INSTANCE.gallerytree_map_region(), createPlaceRequest(
DisplayerSettingsFactory.newMapChartSettings()
.dataset(SALES_OPPS)
.group(COUNTRY)
.column(COUNTRY, "Country")
.column(AMOUNT, SUM).format(AppConstants.INSTANCE.gallerytree_map_region_column1(), "$ #,###")
.title(AppConstants.INSTANCE.gallerytree_map_region_title())
.subType_Region_Map()
.width(700).height(500)
.margins(10, 10, 10, 10)
.filterOn(false, true, true)
.buildSettings()
)));
nodeList.add(new GalleryPlaceRequest(AppConstants.INSTANCE.gallerytree_map_marker(), createPlaceRequest(
DisplayerSettingsFactory.newMapChartSettings()
.dataset(SALES_OPPS)
.group(COUNTRY)
.column(COUNTRY, "Country")
.column(AMOUNT, SUM).format(AppConstants.INSTANCE.gallerytree_map_marker_column1(), "$ #,###")
.title(AppConstants.INSTANCE.gallerytree_map_marker_title())
.subType_Marker_Map()
.width(700).height(500)
.margins(10, 10, 10, 10)
.filterOn(false, true, true)
.buildSettings()
)));
}
private void initTableReportCategory() {
GalleryTreeNodeList nodeList = new GalleryTreeNodeList(AppConstants.INSTANCE.gallerytree_table());
mainNodes.add(nodeList);
nodeList.add(new GalleryPlaceRequest(AppConstants.INSTANCE.gallerytree_table_basic(), createPlaceRequest(
DisplayerSettingsFactory.newTableSettings()
.dataset(SALES_OPPS)
.column(COUNTRY, AppConstants.INSTANCE.gallerytree_table_basic_column1())
.column(CUSTOMER, AppConstants.INSTANCE.gallerytree_table_basic_column2())
.column(PRODUCT, AppConstants.INSTANCE.gallerytree_table_basic_column3())
.column(SALES_PERSON, AppConstants.INSTANCE.gallerytree_table_basic_column4())
.column(STATUS, AppConstants.INSTANCE.gallerytree_table_basic_column5())
.column(SOURCE, AppConstants.INSTANCE.gallerytree_table_basic_column6())
.column(CREATION_DATE, AppConstants.INSTANCE.gallerytree_table_basic_column7())
.column(EXPECTED_AMOUNT, AppConstants.INSTANCE.gallerytree_table_basic_column8())
.column(CLOSING_DATE).format(AppConstants.INSTANCE.gallerytree_table_basic_column9(), "MMM dd, yyyy")
.column(AMOUNT).format(AppConstants.INSTANCE.gallerytree_table_basic_column10(), "$ #,##0.00")
.title(AppConstants.INSTANCE.gallerytree_table_basic_title())
.tablePageSize(10)
.tableOrderEnabled(true)
.tableOrderDefault(AMOUNT, DESCENDING)
.filterOn(false, true, true)
.buildSettings()
)));
nodeList.add(new GalleryPlaceRequest(AppConstants.INSTANCE.gallerytree_table_filtered(), createPlaceRequest(
DisplayerSettingsFactory.newTableSettings()
.dataset(SALES_OPPS)
.column(CUSTOMER, AppConstants.INSTANCE.gallerytree_table_filtered_column1())
.column(PRODUCT, AppConstants.INSTANCE.gallerytree_table_filtered_column2())
.column(STATUS, AppConstants.INSTANCE.gallerytree_table_filtered_column3())
.column(SOURCE, AppConstants.INSTANCE.gallerytree_table_filtered_column4())
.column(CREATION_DATE, AppConstants.INSTANCE.gallerytree_table_filtered_column5())
.column(EXPECTED_AMOUNT).format(AppConstants.INSTANCE.gallerytree_table_filtered_column6(), "$ #,##0.00")
.column(CLOSING_DATE).format(AppConstants.INSTANCE.gallerytree_table_filtered_column7(), "MMM dd, yyyy")
.column(AMOUNT).format(AppConstants.INSTANCE.gallerytree_table_filtered_column8(), "$ #,##0.00")
.filter(COUNTRY, OR(equalsTo("United States"), equalsTo("Brazil")))
.title(AppConstants.INSTANCE.gallerytree_table_filtered_title())
.tablePageSize(10)
.tableOrderEnabled(true)
.tableOrderDefault(AMOUNT, DESCENDING)
.filterOn(false, true, true)
.buildSettings()
)));
nodeList.add(new GalleryPlaceRequest(AppConstants.INSTANCE.gallerytree_table_grouped(), createPlaceRequest(
DisplayerSettingsFactory.newTableSettings()
.dataset(SALES_OPPS)
.group(COUNTRY)
.column(COUNTRY, AppConstants.INSTANCE.gallerytree_table_grouped_column1())
.column(COUNT, "#Opps").format(AppConstants.INSTANCE.gallerytree_table_grouped_column2(), "#,##0")
.column(AMOUNT, MIN).format(AppConstants.INSTANCE.gallerytree_table_grouped_column3(), "$ #,###")
.column(AMOUNT, MAX).format(AppConstants.INSTANCE.gallerytree_table_grouped_column4(), "$ #,###")
.column(AMOUNT, AVERAGE).format(AppConstants.INSTANCE.gallerytree_table_grouped_column5(), "$ #,###")
.column(AMOUNT, SUM).format(AppConstants.INSTANCE.gallerytree_table_grouped_column6(), "$ #,###")
.sort("Total", DESCENDING)
.title(AppConstants.INSTANCE.gallerytree_table_grouped_title())
.tablePageSize(10)
.tableOrderEnabled(true)
.tableOrderDefault("Country", DESCENDING)
.filterOn(false, true, true)
.buildSettings()
)));
nodeList.add(new GalleryPlaceRequest(AppConstants.INSTANCE.gallerytree_table_default_dd(), createPlaceRequest(
DisplayerSettingsFactory.newTableSettings()
.dataset(SALES_OPPS)
.column(COUNTRY, AppConstants.INSTANCE.gallerytree_table_default_dd_column1())
.column(CUSTOMER, AppConstants.INSTANCE.gallerytree_table_default_dd_column2())
.column(PRODUCT, AppConstants.INSTANCE.gallerytree_table_default_dd_column3())
.column(SALES_PERSON, AppConstants.INSTANCE.gallerytree_table_default_dd_column4())
.column(STATUS, AppConstants.INSTANCE.gallerytree_table_default_dd_column5())
.column(SOURCE, AppConstants.INSTANCE.gallerytree_table_default_dd_column6())
.column(CREATION_DATE, AppConstants.INSTANCE.gallerytree_table_default_dd_column7())
.column(EXPECTED_AMOUNT).format(AppConstants.INSTANCE.gallerytree_table_default_dd_column8(), "$ #,###")
.column(CLOSING_DATE).format(AppConstants.INSTANCE.gallerytree_table_default_dd_column9(), "MMM dd, yyyy")
.column(AMOUNT).format(AppConstants.INSTANCE.gallerytree_table_default_dd_column10(), "$ #,###")
.title(AppConstants.INSTANCE.gallerytree_table_default_dd_title())
.tablePageSize(10)
.tableOrderEnabled(true)
.tableOrderDefault(AMOUNT, DESCENDING)
.filterOn(true, true, true)
.renderer(DefaultRenderer.UUID)
.buildSettings()
)));
}
private void initDashboardCategory() {
GalleryTreeNodeList nodeList = new GalleryTreeNodeList(AppConstants.INSTANCE.gallerytree_db());
mainNodes.add(nodeList);
nodeList.add(new GalleryPlaceRequest(AppConstants.INSTANCE.gallerytree_db_salesgoals(), createPlaceRequest("salesGoal")));
nodeList.add(new GalleryPlaceRequest(AppConstants.INSTANCE.gallerytree_db_salespipe(), createPlaceRequest("salesPipeline")));
nodeList.add(new GalleryPlaceRequest(AppConstants.INSTANCE.gallerytree_db_salespcountry(), createPlaceRequest("salesPerCountry")));
nodeList.add(new GalleryPlaceRequest(AppConstants.INSTANCE.gallerytree_db_salesreps(), createPlaceRequest("salesReports")));
nodeList.add(new GalleryPlaceRequest(AppConstants.INSTANCE.gallerytree_db_expreps(), createPlaceRequest("expenseReports")));
nodeList.add(new GalleryPlaceRequest(AppConstants.INSTANCE.gallerytree_db_clustermetrics(), createPlaceRequest("clusterMetrics")));
/*nodeList.add(new GalleryPlaceRequest("System metrics (real-time)", createPlaceRequest("metrics_realtime")));
nodeList.add(new GalleryPlaceRequest("System metrics (historic)", createPlaceRequest("metrics_analytic")));*/
}
}
| {
"content_hash": "429c1a16cc2c1023240bf0cc7a5a676c",
"timestamp": "",
"source": "github",
"line_count": 573,
"max_line_length": 148,
"avg_line_length": 58.64223385689354,
"alnum_prop": 0.5542824831855246,
"repo_name": "cristianonicolai/dashbuilder",
"id": "0d98b024d9ab5499b2a97ed41ff008c286391ef9",
"size": "34201",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "dashbuilder-webapp/src/main/java/org/dashbuilder/client/gallery/GalleryTree.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "117"
},
{
"name": "HTML",
"bytes": "21397"
},
{
"name": "Java",
"bytes": "2988090"
}
],
"symlink_target": ""
} |
using BusinessLayer;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JediTournamentConsole
{
class Program
{
static void Main(string[] args)
{
JediTournamentInterface consoleInterface = new JediTournamentInterface();
consoleInterface.launchMenu();
}
}
}
| {
"content_hash": "a4cf6c0c85f5f40dd843662e4a22ad26",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 85,
"avg_line_length": 22.88888888888889,
"alnum_prop": 0.6553398058252428,
"repo_name": "vmizoules/serviceReseau",
"id": "e9710ee9c1590bffa8cb0ab01794bbc1356c2770",
"size": "414",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "JediTournamentConsole/Program.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "162751"
}
],
"symlink_target": ""
} |
#include "extensions/filters/network/mongo_proxy/codec_impl.h"
#include <cstdint>
#include <list>
#include <memory>
#include <sstream>
#include <string>
#include "envoy/buffer/buffer.h"
#include "envoy/common/exception.h"
#include "common/common/assert.h"
#include "common/common/fmt.h"
#include "extensions/filters/network/mongo_proxy/bson_impl.h"
namespace Envoy {
namespace Extensions {
namespace NetworkFilters {
namespace MongoProxy {
std::string
MessageImpl::documentListToString(const std::list<Bson::DocumentSharedPtr>& documents) const {
std::stringstream out;
out << "[";
bool first = true;
for (const Bson::DocumentSharedPtr& document : documents) {
if (!first) {
out << ", ";
}
out << document->toString();
first = false;
}
out << "]";
return out.str();
}
void GetMoreMessageImpl::fromBuffer(uint32_t, Buffer::Instance& data) {
ENVOY_LOG(trace, "decoding get more message");
Bson::BufferHelper::removeInt32(data); // "zero" (unused)
full_collection_name_ = Bson::BufferHelper::removeCString(data);
number_to_return_ = Bson::BufferHelper::removeInt32(data);
cursor_id_ = Bson::BufferHelper::removeInt64(data);
ENVOY_LOG(trace, "{}", toString(true));
}
bool GetMoreMessageImpl::operator==(const GetMoreMessage& rhs) const {
return requestId() == rhs.requestId() && responseTo() == rhs.responseTo() &&
fullCollectionName() == rhs.fullCollectionName() &&
numberToReturn() == rhs.numberToReturn() && cursorId() == rhs.cursorId();
}
std::string GetMoreMessageImpl::toString(bool) const {
return fmt::format(
R"EOF({{"opcode": "OP_GET_MORE", "id": {}, "response_to": {}, "collection": "{}", "return": {}, )EOF"
R"EOF("cursor": {}}})EOF",
request_id_, response_to_, full_collection_name_, number_to_return_, cursor_id_);
}
void InsertMessageImpl::fromBuffer(uint32_t message_length, Buffer::Instance& data) {
ENVOY_LOG(trace, "decoding insert message");
uint64_t original_buffer_length = data.length();
ASSERT(message_length <= original_buffer_length);
flags_ = Bson::BufferHelper::removeInt32(data);
full_collection_name_ = Bson::BufferHelper::removeCString(data);
while (data.length() - (original_buffer_length - message_length) > 0) {
documents_.emplace_back(Bson::DocumentImpl::create(data));
}
ENVOY_LOG(trace, "{}", toString(true));
}
bool InsertMessageImpl::operator==(const InsertMessage& rhs) const {
if (!(requestId() == rhs.requestId() && responseTo() == rhs.responseTo() &&
flags() == rhs.flags() && fullCollectionName() == rhs.fullCollectionName() &&
documents().size() == rhs.documents().size())) {
return false;
}
for (auto i = documents().begin(), j = rhs.documents().begin(); i != documents().end();
i++, j++) {
if (!(**i == **j)) {
return false;
}
}
return true;
}
std::string InsertMessageImpl::toString(bool full) const {
return fmt::format(
R"EOF({{"opcode": "OP_INSERT", "id": {}, "response_to": {}, "flags": "{:#x}", "collection": "{}", )EOF"
R"EOF("documents": {}}})EOF",
request_id_, response_to_, flags_, full_collection_name_,
full ? documentListToString(documents_) : std::to_string(documents_.size()));
}
void KillCursorsMessageImpl::fromBuffer(uint32_t, Buffer::Instance& data) {
ENVOY_LOG(trace, "decoding kill cursors message");
Bson::BufferHelper::removeInt32(data); // zero
number_of_cursor_ids_ = Bson::BufferHelper::removeInt32(data);
for (int32_t i = 0; i < number_of_cursor_ids_; i++) {
cursor_ids_.push_back(Bson::BufferHelper::removeInt64(data));
}
ENVOY_LOG(trace, "{}", toString(true));
}
bool KillCursorsMessageImpl::operator==(const KillCursorsMessage& rhs) const {
return requestId() == rhs.requestId() && responseTo() == rhs.responseTo() &&
numberOfCursorIds() == rhs.numberOfCursorIds() && cursorIds() == rhs.cursorIds();
}
std::string KillCursorsMessageImpl::toString(bool) const {
std::stringstream cursors;
cursors << "[";
for (size_t i = 0; i < cursor_ids_.size(); i++) {
if (i > 0) {
cursors << ", ";
}
cursors << cursor_ids_[i];
}
cursors << "]";
return fmt::format(
R"EOF({{"opcode": "KILL_CURSORS", "id": {}, "response_to": "{:#x}", "num_cursors": "{}", )EOF"
R"EOF("cursors": {}}})EOF",
request_id_, response_to_, number_of_cursor_ids_, cursors.str());
}
void QueryMessageImpl::fromBuffer(uint32_t message_length, Buffer::Instance& data) {
ENVOY_LOG(trace, "decoding query message");
uint64_t original_buffer_length = data.length();
ASSERT(message_length <= original_buffer_length);
flags_ = Bson::BufferHelper::removeInt32(data);
full_collection_name_ = Bson::BufferHelper::removeCString(data);
number_to_skip_ = Bson::BufferHelper::removeInt32(data);
number_to_return_ = Bson::BufferHelper::removeInt32(data);
query_ = Bson::DocumentImpl::create(data);
if (data.length() - (original_buffer_length - message_length) > 0) {
return_fields_selector_ = Bson::DocumentImpl::create(data);
}
ENVOY_LOG(trace, "{}", toString(true));
}
bool QueryMessageImpl::operator==(const QueryMessage& rhs) const {
if (!(requestId() == rhs.requestId() && responseTo() == rhs.responseTo() &&
flags() == rhs.flags() && fullCollectionName() == rhs.fullCollectionName() &&
numberToSkip() == rhs.numberToSkip() && numberToReturn() == rhs.numberToReturn() &&
!query() == !rhs.query() && !returnFieldsSelector() == !rhs.returnFieldsSelector())) {
return false;
}
if (query()) {
if (!(*query() == *rhs.query())) {
return false;
}
}
if (returnFieldsSelector()) {
if (!(*returnFieldsSelector() == *rhs.returnFieldsSelector())) {
return false;
}
}
return true;
}
std::string QueryMessageImpl::toString(bool full) const {
return fmt::format(
R"EOF({{"opcode": "OP_QUERY", "id": {}, "response_to": {}, "flags": "{:#x}", "collection": "{}", )EOF"
R"EOF("skip": {}, "return": {}, "query": {}, "fields": {}}})EOF",
request_id_, response_to_, flags_, full_collection_name_, number_to_skip_, number_to_return_,
full ? query_->toString() : "\"{...}\"",
return_fields_selector_ ? return_fields_selector_->toString() : "{}");
}
void ReplyMessageImpl::fromBuffer(uint32_t, Buffer::Instance& data) {
ENVOY_LOG(trace, "decoding reply message");
flags_ = Bson::BufferHelper::removeInt32(data);
cursor_id_ = Bson::BufferHelper::removeInt64(data);
starting_from_ = Bson::BufferHelper::removeInt32(data);
number_returned_ = Bson::BufferHelper::removeInt32(data);
for (int32_t i = 0; i < number_returned_; i++) {
documents_.emplace_back(Bson::DocumentImpl::create(data));
}
ENVOY_LOG(trace, "{}", toString(true));
}
bool ReplyMessageImpl::operator==(const ReplyMessage& rhs) const {
if (!(requestId() == rhs.requestId() && responseTo() == rhs.responseTo() &&
flags() == rhs.flags() && cursorId() == rhs.cursorId() &&
startingFrom() == rhs.startingFrom() && numberReturned() == rhs.numberReturned())) {
return false;
}
for (auto i = documents().begin(), j = rhs.documents().begin(); i != documents().end();
i++, j++) {
if (!(**i == **j)) {
return false;
}
}
return true;
}
std::string ReplyMessageImpl::toString(bool full) const {
return fmt::format(
R"EOF({{"opcode": "OP_REPLY", "id": {}, "response_to": {}, "flags": "{:#x}", "cursor": "{}", )EOF"
R"EOF("from": {}, "returned": {}, "documents": {}}})EOF",
request_id_, response_to_, flags_, cursor_id_, starting_from_, number_returned_,
full ? documentListToString(documents_) : std::to_string(documents_.size()));
}
/*
* OP_COMMAND mongo message implementation.
*/
void CommandMessageImpl::fromBuffer(uint32_t message_length, Buffer::Instance& data) {
ENVOY_LOG(trace, "decoding COMMAND message");
const uint64_t original_data_length = data.length();
ASSERT(data.length() >= message_length); // See comment below about relationship.
database_ = Bson::BufferHelper::removeCString(data);
command_name_ = Bson::BufferHelper::removeCString(data);
metadata_ = Bson::DocumentImpl::create(data);
command_args_ = Bson::DocumentImpl::create(data);
// There may be additional docs.
// message_length is mongo message length. original_data_length contains
// mongo message and possibly first few bytes of next message.
while (data.length() - (original_data_length - message_length) > 0) {
input_docs_.emplace_back(Bson::DocumentImpl::create(data));
}
ENVOY_LOG(trace, "{}", toString(true));
}
std::string CommandMessageImpl::toString(bool full) const {
return fmt::format(
R"EOF({{"opcode": "OP_COMMAND", "id": {}, "response_to": {}, "database": "{}", )EOF"
R"EOF("commandName": "{}", "metadata": {}, )EOF"
R"EOF("commandArgs": {}, "inputDocs": {}}})EOF",
request_id_, response_to_, database_.c_str(), command_name_.c_str(), metadata_->toString(),
command_args_->toString(),
full ? documentListToString(input_docs_) : std::to_string(input_docs_.size()));
}
bool CommandMessageImpl::operator==(const CommandMessage& rhs) const {
if (!(requestId() == rhs.requestId() && responseTo() == rhs.responseTo() &&
database() == rhs.database() && commandName() == rhs.commandName() &&
!metadata() == !rhs.metadata() && !commandArgs() == !rhs.commandArgs() &&
inputDocs().size() == rhs.inputDocs().size())) {
return false;
}
// Compare documents now.
if (metadata()) {
if (!(*metadata() == *rhs.metadata())) {
return false;
}
}
if (commandArgs()) {
if (!(*commandArgs() == *rhs.commandArgs())) {
return false;
}
}
for (auto i = inputDocs().begin(), j = rhs.inputDocs().begin(); i != inputDocs().end();
i++, j++) {
if (!(**i == **j)) {
return false;
}
}
return true;
}
// OP_COMMANDREPLY implementation.
void CommandReplyMessageImpl::fromBuffer(uint32_t message_length, Buffer::Instance& data) {
ENVOY_LOG(trace, "decoding COMMAND REPLY message");
const uint64_t original_data_length = data.length();
ASSERT(data.length() >= message_length); // See comment below about relationship.
metadata_ = Bson::DocumentImpl::create(data);
command_reply_ = Bson::DocumentImpl::create(data);
// There may be additional docs.
// message_length is mongo message length. original_data_length contains
// mongo message and possibly first few bytes of next message.
while (data.length() - (original_data_length - message_length) > 0) {
output_docs_.emplace_back(Bson::DocumentImpl::create(data));
}
ENVOY_LOG(trace, "{}", toString(true));
}
std::string CommandReplyMessageImpl::toString(bool full) const {
return fmt::format(R"EOF({{"opcode": "OP_COMMANDREPLY", "id": {}, "response_to": {}, )EOF"
R"EOF("metadata": {}, "commandReply": {}, "outputDocs":{}}} )EOF",
request_id_, response_to_, metadata_->toString(), command_reply_->toString(),
full ? documentListToString(output_docs_)
: std::to_string(output_docs_.size()));
}
bool CommandReplyMessageImpl::operator==(const CommandReplyMessage& rhs) const {
if (!(requestId() == rhs.requestId() && responseTo() == rhs.responseTo() &&
!metadata() == !rhs.metadata() && !commandReply() == !rhs.commandReply() &&
outputDocs().size() == rhs.outputDocs().size())) {
return false;
}
// Compare documents now.
if (metadata()) {
if (!(*metadata() == *rhs.metadata())) {
return false;
}
}
if (commandReply()) {
if (!(*commandReply() == *rhs.commandReply())) {
return false;
}
}
for (auto i = outputDocs().begin(), j = rhs.outputDocs().begin(); i != outputDocs().end();
i++, j++) {
if (!(**i == **j)) {
return false;
}
}
return true;
}
bool DecoderImpl::decode(Buffer::Instance& data) {
// See if we have enough data for the message length.
ENVOY_LOG(trace, "decoding {} bytes", data.length());
if (data.length() < sizeof(int32_t)) {
return false;
}
uint32_t message_length = Bson::BufferHelper::peekInt32(data);
ENVOY_LOG(trace, "message is {} bytes", message_length);
if (data.length() < message_length) {
return false;
}
data.drain(sizeof(int32_t));
int32_t request_id = Bson::BufferHelper::removeInt32(data);
int32_t response_to = Bson::BufferHelper::removeInt32(data);
Message::OpCode op_code = static_cast<Message::OpCode>(Bson::BufferHelper::removeInt32(data));
ENVOY_LOG(trace, "message op: {}", static_cast<int32_t>(op_code));
// Some messages need to know how long they are to parse. Subtract the header that we have already
// parsed off before passing the final value.
message_length -= Message::MessageHeaderSize;
switch (op_code) {
case Message::OpCode::Reply: {
std::unique_ptr<ReplyMessageImpl> message(new ReplyMessageImpl(request_id, response_to));
message->fromBuffer(message_length, data);
callbacks_.decodeReply(std::move(message));
break;
}
case Message::OpCode::Query: {
std::unique_ptr<QueryMessageImpl> message(new QueryMessageImpl(request_id, response_to));
message->fromBuffer(message_length, data);
callbacks_.decodeQuery(std::move(message));
break;
}
case Message::OpCode::GetMore: {
std::unique_ptr<GetMoreMessageImpl> message(new GetMoreMessageImpl(request_id, response_to));
message->fromBuffer(message_length, data);
callbacks_.decodeGetMore(std::move(message));
break;
}
case Message::OpCode::Insert: {
std::unique_ptr<InsertMessageImpl> message(new InsertMessageImpl(request_id, response_to));
message->fromBuffer(message_length, data);
callbacks_.decodeInsert(std::move(message));
break;
}
case Message::OpCode::KillCursors: {
std::unique_ptr<KillCursorsMessageImpl> message(
new KillCursorsMessageImpl(request_id, response_to));
message->fromBuffer(message_length, data);
callbacks_.decodeKillCursors(std::move(message));
break;
}
case Message::OpCode::Command: {
std::unique_ptr<CommandMessageImpl> message(new CommandMessageImpl(request_id, response_to));
message->fromBuffer(message_length, data);
callbacks_.decodeCommand(std::move(message));
break;
}
case Message::OpCode::CommandReply: {
std::unique_ptr<CommandReplyMessageImpl> message(
new CommandReplyMessageImpl(request_id, response_to));
message->fromBuffer(message_length, data);
callbacks_.decodeCommandReply(std::move(message));
break;
}
default:
throw EnvoyException(fmt::format("invalid mongo op {}", static_cast<int32_t>(op_code)));
}
ENVOY_LOG(trace, "{} bytes remaining after decoding", data.length());
return true;
}
void DecoderImpl::onData(Buffer::Instance& data) {
while (data.length() > 0 && decode(data)) {
}
}
void EncoderImpl::encodeCommonHeader(int32_t total_size, const Message& message,
Message::OpCode op) {
Bson::BufferHelper::writeInt32(output_, total_size);
Bson::BufferHelper::writeInt32(output_, message.requestId());
Bson::BufferHelper::writeInt32(output_, message.responseTo());
Bson::BufferHelper::writeInt32(output_, static_cast<int32_t>(op));
}
void EncoderImpl::encodeGetMore(const GetMoreMessage& message) {
if (message.fullCollectionName().empty() || message.cursorId() == 0) {
throw EnvoyException("invalid get more message");
}
// https://docs.mongodb.org/manual/reference/mongodb-wire-protocol/#op-get-more
int32_t total_size = Message::MessageHeaderSize + Message::Int32Length +
message.fullCollectionName().size() + Message::StringPaddingLength +
Message::Int32Length + Message::Int64Length;
encodeCommonHeader(total_size, message, Message::OpCode::GetMore);
Bson::BufferHelper::writeInt32(output_, 0);
Bson::BufferHelper::writeCString(output_, message.fullCollectionName());
Bson::BufferHelper::writeInt32(output_, message.numberToReturn());
Bson::BufferHelper::writeInt64(output_, message.cursorId());
}
void EncoderImpl::encodeInsert(const InsertMessage& message) {
if (message.fullCollectionName().empty() || message.documents().empty()) {
throw EnvoyException("invalid insert message");
}
// https://docs.mongodb.org/manual/reference/mongodb-wire-protocol/#op-insert
int32_t total_size = Message::MessageHeaderSize + Message::Int32Length +
message.fullCollectionName().size() + Message::StringPaddingLength;
for (const Bson::DocumentSharedPtr& document : message.documents()) {
total_size += document->byteSize();
}
encodeCommonHeader(total_size, message, Message::OpCode::Insert);
Bson::BufferHelper::writeInt32(output_, message.flags());
Bson::BufferHelper::writeCString(output_, message.fullCollectionName());
for (const Bson::DocumentSharedPtr& document : message.documents()) {
document->encode(output_);
}
}
void EncoderImpl::encodeKillCursors(const KillCursorsMessage& message) {
if (message.numberOfCursorIds() == 0 ||
message.numberOfCursorIds() != static_cast<int32_t>(message.cursorIds().size())) {
throw EnvoyException("invalid kill cursors message");
}
// https://docs.mongodb.org/manual/reference/mongodb-wire-protocol/#op-kill-cursors
int32_t total_size =
Message::MessageHeaderSize + 2 * Message::Int32Length + (message.numberOfCursorIds() * 8);
encodeCommonHeader(total_size, message, Message::OpCode::KillCursors);
Bson::BufferHelper::writeInt32(output_, 0);
Bson::BufferHelper::writeInt32(output_, message.numberOfCursorIds());
for (int64_t cursor : message.cursorIds()) {
Bson::BufferHelper::writeInt64(output_, cursor);
}
}
void EncoderImpl::encodeQuery(const QueryMessage& message) {
if (message.fullCollectionName().empty() || !message.query()) {
throw EnvoyException("invalid query message");
}
// https://docs.mongodb.org/manual/reference/mongodb-wire-protocol/#op-query
int32_t total_size = Message::MessageHeaderSize + 3 * Message::Int32Length +
message.fullCollectionName().size() + Message::StringPaddingLength +
message.query()->byteSize();
if (message.returnFieldsSelector()) {
total_size += message.returnFieldsSelector()->byteSize();
}
encodeCommonHeader(total_size, message, Message::OpCode::Query);
Bson::BufferHelper::writeInt32(output_, message.flags());
Bson::BufferHelper::writeCString(output_, message.fullCollectionName());
Bson::BufferHelper::writeInt32(output_, message.numberToSkip());
Bson::BufferHelper::writeInt32(output_, message.numberToReturn());
message.query()->encode(output_);
if (message.returnFieldsSelector()) {
message.returnFieldsSelector()->encode(output_);
}
}
void EncoderImpl::encodeReply(const ReplyMessage& message) {
// https://docs.mongodb.org/manual/reference/mongodb-wire-protocol/#op-reply
int32_t total_size = Message::MessageHeaderSize + 3 * Message::Int32Length + Message::Int64Length;
for (const Bson::DocumentSharedPtr& document : message.documents()) {
total_size += document->byteSize();
}
encodeCommonHeader(total_size, message, Message::OpCode::Reply);
Bson::BufferHelper::writeInt32(output_, message.flags());
Bson::BufferHelper::writeInt64(output_, message.cursorId());
Bson::BufferHelper::writeInt32(output_, message.startingFrom());
Bson::BufferHelper::writeInt32(output_, message.numberReturned());
for (const Bson::DocumentSharedPtr& document : message.documents()) {
document->encode(output_);
}
}
void EncoderImpl::encodeCommand(const CommandMessage& message) {
int32_t total_size = Message::MessageHeaderSize;
total_size += message.database().size() + Message::StringPaddingLength;
total_size += message.commandName().size() + Message::StringPaddingLength;
total_size += message.metadata()->byteSize();
total_size += message.commandArgs()->byteSize();
for (const Bson::DocumentSharedPtr& document : message.inputDocs()) {
total_size += document->byteSize();
}
// Now encode.
encodeCommonHeader(total_size, message, Message::OpCode::Command);
Bson::BufferHelper::writeCString(output_, message.database());
Bson::BufferHelper::writeCString(output_, message.commandName());
message.metadata()->encode(output_);
message.commandArgs()->encode(output_);
for (const Bson::DocumentSharedPtr& document : message.inputDocs()) {
document->encode(output_);
}
}
void EncoderImpl::encodeCommandReply(const CommandReplyMessage& message) {
int32_t total_size = Message::MessageHeaderSize;
total_size += message.metadata()->byteSize();
total_size += message.commandReply()->byteSize();
for (const Bson::DocumentSharedPtr& document : message.outputDocs()) {
total_size += document->byteSize();
}
// Now encode.
encodeCommonHeader(total_size, message, Message::OpCode::CommandReply);
message.metadata()->encode(output_);
message.commandReply()->encode(output_);
for (const Bson::DocumentSharedPtr& document : message.outputDocs()) {
document->encode(output_);
}
}
} // namespace MongoProxy
} // namespace NetworkFilters
} // namespace Extensions
} // namespace Envoy
| {
"content_hash": "354e5ed5495be962c4fa85d267e4da2e",
"timestamp": "",
"source": "github",
"line_count": 578,
"max_line_length": 109,
"avg_line_length": 36.844290657439444,
"alnum_prop": 0.6636457550713749,
"repo_name": "jrajahalme/envoy",
"id": "d56fe7ff4e319a77b8352d08ee026a70b872eb03",
"size": "21296",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "source/extensions/filters/network/mongo_proxy/codec_impl.cc",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "13963"
},
{
"name": "C++",
"bytes": "17579767"
},
{
"name": "Dockerfile",
"bytes": "245"
},
{
"name": "Emacs Lisp",
"bytes": "966"
},
{
"name": "Go",
"bytes": "695"
},
{
"name": "PowerShell",
"bytes": "5725"
},
{
"name": "PureBasic",
"bytes": "472"
},
{
"name": "Python",
"bytes": "1441497"
},
{
"name": "Rust",
"bytes": "675"
},
{
"name": "Shell",
"bytes": "105335"
},
{
"name": "Thrift",
"bytes": "748"
}
],
"symlink_target": ""
} |
#include "defs.h"
#include "osabi.h"
#include "regcache.h"
#include "regset.h"
#include "arm-tdep.h"
/* Core file support. */
/* Sizeof `struct reg' in <machine/reg.h>. */
#define ARMBSD_SIZEOF_GREGS (17 * 4)
/* Sizeof `struct fpreg' in <machine/reg.h. */
#define ARMBSD_SIZEOF_FPREGS ((1 + (8 * 3)) * 4)
static int
armbsd_fpreg_offset (int regnum)
{
if (regnum == ARM_FPS_REGNUM)
return 0;
return 4 + (regnum - ARM_F0_REGNUM) * 12;
}
/* Supply register REGNUM from the buffer specified by FPREGS and LEN
in the floating-point register set REGSET to register cache
REGCACHE. If REGNUM is -1, do this for all registers in REGSET. */
static void
armbsd_supply_fpregset (const struct regset *regset,
struct regcache *regcache,
int regnum, const void *fpregs, size_t len)
{
const gdb_byte *regs = fpregs;
int i;
gdb_assert (len >= ARMBSD_SIZEOF_FPREGS);
for (i = ARM_F0_REGNUM; i <= ARM_FPS_REGNUM; i++)
{
if (regnum == i || regnum == -1)
regcache_raw_supply (regcache, i, regs + armbsd_fpreg_offset (i));
}
}
/* Supply register REGNUM from the buffer specified by GREGS and LEN
in the general-purpose register set REGSET to register cache
REGCACHE. If REGNUM is -1, do this for all registers in REGSET. */
static void
armbsd_supply_gregset (const struct regset *regset,
struct regcache *regcache,
int regnum, const void *gregs, size_t len)
{
const gdb_byte *regs = gregs;
int i;
gdb_assert (len >= ARMBSD_SIZEOF_GREGS);
for (i = ARM_A1_REGNUM; i <= ARM_PC_REGNUM; i++)
{
if (regnum == i || regnum == -1)
regcache_raw_supply (regcache, i, regs + i * 4);
}
if (regnum == ARM_PS_REGNUM || regnum == -1)
regcache_raw_supply (regcache, i, regs + 16 * 4);
if (len >= ARMBSD_SIZEOF_GREGS + ARMBSD_SIZEOF_FPREGS)
{
regs += ARMBSD_SIZEOF_GREGS;
len -= ARMBSD_SIZEOF_GREGS;
armbsd_supply_fpregset (regset, regcache, regnum, regs, len);
}
}
/* ARM register sets. */
static const struct regset armbsd_gregset =
{
NULL,
armbsd_supply_gregset
};
static const struct regset armbsd_fpregset =
{
NULL,
armbsd_supply_fpregset
};
/* Iterate over supported core file register note sections. */
void
armbsd_iterate_over_regset_sections (struct gdbarch *gdbarch,
iterate_over_regset_sections_cb *cb,
void *cb_data,
const struct regcache *regcache)
{
cb (".reg", ARMBSD_SIZEOF_GREGS, &armbsd_gregset, NULL, cb_data);
cb (".reg2", ARMBSD_SIZEOF_FPREGS, &armbsd_fpregset, NULL, cb_data);
}
| {
"content_hash": "f93423c136781aa892bedf09e8775d4a",
"timestamp": "",
"source": "github",
"line_count": 103,
"max_line_length": 71,
"avg_line_length": 24.815533980582526,
"alnum_prop": 0.6525821596244131,
"repo_name": "armoredsoftware/protocol",
"id": "7923cadd10109c09268449c9f1c8bae39f924b3c",
"size": "3331",
"binary": false,
"copies": "8",
"ref": "refs/heads/master",
"path": "measurer/gdb-7.9/gdb/armbsd-tdep.c",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Ada",
"bytes": "252822"
},
{
"name": "Assembly",
"bytes": "11210154"
},
{
"name": "Awk",
"bytes": "6556"
},
{
"name": "Batchfile",
"bytes": "79841"
},
{
"name": "C",
"bytes": "92554796"
},
{
"name": "C++",
"bytes": "29411093"
},
{
"name": "CSS",
"bytes": "96602"
},
{
"name": "D",
"bytes": "12894"
},
{
"name": "DIGITAL Command Language",
"bytes": "17168"
},
{
"name": "DTrace",
"bytes": "32201"
},
{
"name": "Emacs Lisp",
"bytes": "3647"
},
{
"name": "FORTRAN",
"bytes": "15411"
},
{
"name": "Go",
"bytes": "2202"
},
{
"name": "Groff",
"bytes": "2159080"
},
{
"name": "HTML",
"bytes": "14351037"
},
{
"name": "Haskell",
"bytes": "519183"
},
{
"name": "Java",
"bytes": "9276960"
},
{
"name": "JavaScript",
"bytes": "49539"
},
{
"name": "Lex",
"bytes": "16562"
},
{
"name": "Logos",
"bytes": "184506"
},
{
"name": "Makefile",
"bytes": "1431247"
},
{
"name": "Objective-C",
"bytes": "139451"
},
{
"name": "Pascal",
"bytes": "3521"
},
{
"name": "Perl",
"bytes": "180326"
},
{
"name": "Python",
"bytes": "305456"
},
{
"name": "R",
"bytes": "54"
},
{
"name": "Scheme",
"bytes": "2254611"
},
{
"name": "Scilab",
"bytes": "2316184"
},
{
"name": "Shell",
"bytes": "2184639"
},
{
"name": "TeX",
"bytes": "318429"
},
{
"name": "XSLT",
"bytes": "152406"
},
{
"name": "Yacc",
"bytes": "430581"
}
],
"symlink_target": ""
} |
..
Programmer(s): Daniel R. Reynolds @ SMU
----------------------------------------------------------------
Copyright (c) 2013, Southern Methodist University.
All rights reserved.
For details, see the LICENSE file.
----------------------------------------------------------------
:tocdepth: 3
.. _NVectors.NVParallel:
The NVECTOR_PARALLEL Module
================================
The NVECTOR_PARALLEL implementation of the NVECTOR module provided with
SUNDIALS is based on MPI. It defines the *content* field of a
``N_Vector`` to be a structure containing the global and local lengths
of the vector, a pointer to the beginning of a contiguous local data
array, an MPI communicator, an a boolean flag *own_data* indicating
ownership of the data array *data*.
.. code-block:: c
struct _N_VectorContent_Parallel {
long int local_length;
long int global_length;
booleantype own_data;
realtype *data;
MPI_Comm comm;
};
The following seven macros are provided to access the content of a
NVECTOR_PARALLEL vector. The suffix ``_P`` in the names denotes
parallel version.
.. c:macro:: NV_CONTENT_P(v)
This macro gives access to the contents of the parallel
``N_Vector`` *v*.
The assignment ``v_cont = NV_CONTENT_P(v)`` sets ``v_cont`` to be a
pointer to the ``N_Vector`` *content* structure of type ``struct
N_VectorParallelContent``.
Implementation:
.. code-block:: c
#define NV_CONTENT_P(v) ( (N_VectorContent_Parallel)(v->content) )
.. c:macro:: NV_OWN_DATA_P(v)
Access the *own_data* component of the parallel ``N_Vector`` *v*.
Implementation:
.. code-block:: c
#define NV_OWN_DATA_P(v) ( NV_CONTENT_P(v)->own_data )
.. c:macro:: NV_DATA_P(v)
The assignment ``v_data = NV_DATA_P(v)`` sets ``v_data`` to be a
pointer to the first component of the *local_data* for the
``N_Vector v``.
The assignment ``NV_DATA_P(v) = v_data`` sets the component array of
``v`` to be ``v_data`` by storing the pointer ``v_data`` into
*data*.
Implementation:
.. code-block:: c
#define NV_DATA_P(v) ( NV_CONTENT_P(v)->data )
.. c:macro:: NV_LOCLENGTH_P(v)
The assignment ``v_llen = NV_LOCLENGTH_P(v)`` sets ``v_llen`` to be
the length of the local part of ``v``.
The call ``NV_LOCLENGTH_P(v) = llen_v`` sets the *local_length* of
``v`` to be ``llen_v``.
Implementation:
.. code-block:: c
#define NV_LOCLENGTH_P(v) ( NV_CONTENT_P(v)->local_length )
.. c:macro:: NV_GLOBLENGTH_P(v)
The assignment ``v_glen = NV_GLOBLENGTH_P(v)`` sets ``v_glen`` to be
the *global_length* of the vector ``v``.
The call ``NV_GLOBLENGTH_P(v) = glen_v`` sets the *global_length*
of ``v`` to be ``glen_v``.
Implementation:
.. code-block:: c
#define NV_GLOBLENGTH_P(v) ( NV_CONTENT_P(v)->global_length )
.. c:macro:: NV_COMM_P(v)
This macro provides access to the MPI communicator used by the
parallel ``N_Vector`` *v*.
Implementation:
.. code-block:: c
#define NV_COMM_P(v) ( NV_CONTENT_P(v)->comm )
.. c:macro:: NV_Ith_P(v,i)
This macro gives access to the individual components of the
*local_data* array of an ``N_Vector``.
The assignment ``r = NV_Ith_P(v,i)`` sets ``r`` to be the value of
the ``i``-th component of the local part of ``v``.
The assignment ``NV_Ith_P(v,i) = r`` sets the value of the ``i``-th
component of the local part of ``v`` to be ``r``.
Here ``i`` ranges from 0 to :math:`n-1`, where :math:`n` is the
*local_length*.
Implementation:
.. code-block:: c
#define NV_Ith_P(v,i) ( NV_DATA_P(v)[i] )
The NVECTOR_PARALLEL module defines parallel implementations of all
vector operations listed in the section :ref:`NVectors.Ops`. Their
names are obtained from those that section by appending the suffix
``_Parallel``.
In addition, the module NVECTOR_PARALLEL provides the following
additional user-callable routines:
.. c:function:: N_Vector N_VNew_Parallel(MPI_Comm comm, long int local_length, long int global_length)
This function creates and allocates memory for a parallel vector
having global length *global_length*, having processor-local length
*local_length*, and using the MPI communicator *comm*.
.. c:function:: N_Vector N_VNewEmpty_Parallel(MPI_Comm comm, long int local_length, long int global_length)
This function creates a new parallel ``N_Vector`` with an empty
(``NULL``) data array.
.. c:function:: N_Vector N_VMake_Parallel(MPI_Comm comm, long int local_length, long int global_length, realtype* v_data)
This function creates and allocates memory for a parallel vector
with user-provided data array.
.. c:function:: N_Vector* N_VCloneVectorArray_Parallel(int count, N_Vector w)
This function creates (by cloning) an array of *count* parallel vectors.
.. c:function:: N_Vector* N_VCloneEmptyVectorArray_Parallel(int count, N_Vector w)
This function creates (by cloning) an array of *count* parallel
vectors, each with an empty (``NULL``) data array.
.. c:function:: void N_VDestroyVectorArray_Parallel(N_Vector* vs, int count)
This function frees memory allocated for the array of *count*
variables of type ``N_Vector`` created with
:c:func:`N_VCloneVectorArray_Parallel()` or with
:c:func:`N_VCloneEmptyVectorArray_Parallel()`.
.. c:function:: void N_VPrint_Parallel(N_Vector v)
This function prints the content of a parallel vector to ``stdout``.
**Notes**
* When looping over the components of an ``N_Vector v``, it is
more efficient to first obtain the local component array via ``v_data
= NV_DATA_P(v)`` and then access ``v_data[i]`` within the loop than it
is to use ``NV_Ith_P(v,i)`` within the loop.
* :c:func:`N_VNewEmpty_Parallel()`, :c:func:`N_VMake_Parallel()`, and
:c:func:`N_VCloneEmptyVectorArray_Parallel()` set the field *own_data* to
``FALSE``. The routines :c:func:`N_VDestroy_Parallel()` and
:c:func:`N_VDestroyVectorArray_Parallel()` will not attempt to free the
pointer data for any ``N_Vector`` with *own_data* set to
``FALSE``. In such a case, it is the user's responsibility to
deallocate the data pointer.
* To maximize efficiency, vector operations in the NVECTOR_PARALLEL
implementation that have more than one ``N_Vector`` argument do not
check for consistent internal representation of these vectors. It is
the user's responsibility to ensure that such routines are called
with ``N_Vector`` arguments that were all created with the same
internal representations.
| {
"content_hash": "000c809943cdde9966eebb68527f1cdf",
"timestamp": "",
"source": "github",
"line_count": 214,
"max_line_length": 121,
"avg_line_length": 30.911214953271028,
"alnum_prop": 0.6601662887377173,
"repo_name": "liuqx315/Sundials",
"id": "e73214a368a1e0a41125e309958c071f336d0603",
"size": "6615",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "doc/guide/source/nvectors/NVector_Parallel.rst",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "7584134"
},
{
"name": "C++",
"bytes": "55726"
},
{
"name": "CSS",
"bytes": "288961"
},
{
"name": "FORTRAN",
"bytes": "222761"
},
{
"name": "JavaScript",
"bytes": "112956"
},
{
"name": "Makefile",
"bytes": "37650"
},
{
"name": "Matlab",
"bytes": "1908"
},
{
"name": "Python",
"bytes": "51502"
},
{
"name": "Shell",
"bytes": "59018"
},
{
"name": "TeX",
"bytes": "3528323"
}
],
"symlink_target": ""
} |
var EnterKey = 13;
$.fn.isBound = function(type, fn) {
var data = this.data('events')[type];
if (data === undefined || data.length === 0) {
return false;
}
return (-1 !== $.inArray(fn, data));
};
$(document).ready(function() {
function runBind() {
$('.destroy').on('click', function(e) {
$currentListItem = $(this).closest('li');
$currentListItem.remove();
});
$('.toggle').on('click', function(e) {
var $currentListItemLabel = $(this).closest('li').find('label');
$(this).parent().parent().addClass('donebg');
/*
* Do this or add css and remove JS dynamic css.
*/
if ( $currentListItemLabel.attr('data') == 'done' ) {
$currentListItemLabel.attr('data', '');
$currentListItemLabel.css('text-decoration', 'none');
}
else {
$currentListItemLabel.attr('data', 'done');
$currentListItemLabel.css('text-decoration', 'line-through');
}
});
}
$todoList = $('#todo-list');
$('#new-todo').keypress(function(e) {
if (e.which === EnterKey) {
$('.destroy').off('click');
$('.toggle').off('click');
var todos = $todoList.html();
todos += ""+
"<li>" +
"<div class='view'>" +
"<input class='toggle' type='checkbox'>" +
"<label data=''>" + " " + $('#new-todo').val() + "</label>" +
"<a class='destroy'></a>" +
"</div>" +
"</li>";
$(this).val('');
$todoList.html(todos);
runBind();
$('#main').show();
}}); // end if
});
| {
"content_hash": "294c3ea670c17eb54ac20b273ee15372",
"timestamp": "",
"source": "github",
"line_count": 60,
"max_line_length": 76,
"avg_line_length": 26.3,
"alnum_prop": 0.4968314321926489,
"repo_name": "wliontb/ictez_source",
"id": "9439c6ce6ae9f37f55e9154ba155b340a8d5fc9a",
"size": "1578",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "public/admin/js/todos.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "95741"
},
{
"name": "HTML",
"bytes": "15582"
},
{
"name": "JavaScript",
"bytes": "95593"
},
{
"name": "PHP",
"bytes": "1915795"
}
],
"symlink_target": ""
} |
import "./combine";
import { Observable, Property } from "./observable";
export declare type FlattenedObservable<O> = O extends Observable<infer I> ? I : O;
export declare type DecodedValueOf<O> = FlattenedObservable<O[keyof O]>;
/** @hidden */
export declare function decode<T extends Record<any, any>>(src: Observable<keyof T>, cases: T): Property<DecodedValueOf<T>>;
export default decode;
| {
"content_hash": "5225f7651d1c9bd314ce47f21fc6b9e2",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 124,
"avg_line_length": 56.142857142857146,
"alnum_prop": 0.7430025445292621,
"repo_name": "baconjs/bacon.js",
"id": "e0a4c7f9ddd7fcd058c939d68a84231d41369d80",
"size": "393",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "types/decode.d.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "951"
},
{
"name": "JavaScript",
"bytes": "5339"
},
{
"name": "Shell",
"bytes": "1763"
},
{
"name": "TypeScript",
"bytes": "452534"
}
],
"symlink_target": ""
} |
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { RegisterComponent } from './register.component';
@NgModule({
imports: [
RouterModule.forChild([
{
path: '',
component: RegisterComponent
}
])
],
exports: [RouterModule]
})
export class RegisterRoutingModule { }
| {
"content_hash": "34f6cfbcddfcea29a9ea06e841d09425",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 57,
"avg_line_length": 20.823529411764707,
"alnum_prop": 0.632768361581921,
"repo_name": "demoiselle/generator-demoiselle",
"id": "2d02bfba64abec3fcd6108079700582c6ca0d0ca",
"size": "354",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Utils/templates/base/frontend/src/app/auth/register/register-routing.module.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "80382"
},
{
"name": "HTML",
"bytes": "70025"
},
{
"name": "Java",
"bytes": "46647"
},
{
"name": "JavaScript",
"bytes": "59608"
},
{
"name": "Shell",
"bytes": "147"
},
{
"name": "TypeScript",
"bytes": "65538"
}
],
"symlink_target": ""
} |
#include "RulePersister.h"
RulePersister::RulePersister()
{
}
RulePersister::~RulePersister() {
}
void RulePersister::saveRule(Rule* rule)
{
}
void RulePersister::loadRules()
{
}
void RulePersister::clearRules()
{
}
| {
"content_hash": "15c00aca1f03f2cc97d432696f8b1c90",
"timestamp": "",
"source": "github",
"line_count": 27,
"max_line_length": 40,
"avg_line_length": 8.444444444444445,
"alnum_prop": 0.6973684210526315,
"repo_name": "ADVANTECH-Corp/node-alljoyn",
"id": "c471848dd3bc77f18a5a092a52d3ff2861d025e8",
"size": "1212",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "alljoyn/alljoyn_core/samples/eventaction/SimpleRulesEngine/posix/RulePersister.cc",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "4995"
},
{
"name": "C",
"bytes": "638481"
},
{
"name": "C#",
"bytes": "775008"
},
{
"name": "C++",
"bytes": "12965271"
},
{
"name": "CSS",
"bytes": "17461"
},
{
"name": "Groff",
"bytes": "3068"
},
{
"name": "HTML",
"bytes": "45149"
},
{
"name": "Java",
"bytes": "4802386"
},
{
"name": "JavaScript",
"bytes": "606220"
},
{
"name": "Makefile",
"bytes": "42536"
},
{
"name": "Objective-C",
"bytes": "1829239"
},
{
"name": "Objective-C++",
"bytes": "856772"
},
{
"name": "Python",
"bytes": "559767"
},
{
"name": "Shell",
"bytes": "40697"
},
{
"name": "TeX",
"bytes": "817"
},
{
"name": "Visual Basic",
"bytes": "1285"
},
{
"name": "XSLT",
"bytes": "100471"
}
],
"symlink_target": ""
} |
title: 'Integer Break - Medium - L'
date: 2021-04-06
permalink: /dsa/2021/04/blog-post-9/
tags:
- Data Structures
- Algorithms
- Leetcode
- C++
- Medium
- L
---
# Question
- https://leetcode.com/problems/integer-break/
Given an integer n, break it into the sum of k positive integers, where k >= 2, and maximize the product of those integers.
Return the maximum product you can get.
# Approach
- Math
# Solution
```
class Solution {
public:
int integerBreak(int n) {
// n equals to 2 or 3 must be handled explicitly
if (n == 2 || n == 3) return (n-1);
// Keep removing parts of size 3 while n is greater than 4
int res = 1;
while (n > 4)
{
n -= 3;
res *= 3; // Keep multiplying 3 to res
}
return (n * res); // The last part multiplied by previous parts
}
};
``` | {
"content_hash": "ce66034aa67daffd355af196d8db59e3",
"timestamp": "",
"source": "github",
"line_count": 44,
"max_line_length": 123,
"avg_line_length": 20.022727272727273,
"alnum_prop": 0.5856980703745743,
"repo_name": "ashwinpathak20/ashwinpathak20.github.io",
"id": "bc43abc69a111dec3bf25a809b3d9b3ca37ec08c",
"size": "885",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "_dsa/2021-04-06-blog-post-3.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "18321"
},
{
"name": "HTML",
"bytes": "77717"
},
{
"name": "JavaScript",
"bytes": "131146"
},
{
"name": "Jupyter Notebook",
"bytes": "30796"
},
{
"name": "Python",
"bytes": "13849"
},
{
"name": "Ruby",
"bytes": "761"
},
{
"name": "SCSS",
"bytes": "64766"
}
],
"symlink_target": ""
} |
package model
// MangerInfo struct
type MangerInfo struct {
OID int64 `json:"id"`
Uname string `json:"username"`
}
| {
"content_hash": "300b3fe275b2afdf1eefe7a1c5c88775",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 31,
"avg_line_length": 17.285714285714285,
"alnum_prop": 0.7024793388429752,
"repo_name": "LQJJ/demo",
"id": "2ae3b55ae2bfd99cc97944a592c1d0fd45f6349c",
"size": "121",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "126-go-common-master/app/admin/main/usersuit/model/manager.go",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "5910716"
},
{
"name": "C++",
"bytes": "113072"
},
{
"name": "CSS",
"bytes": "10791"
},
{
"name": "Dockerfile",
"bytes": "934"
},
{
"name": "Go",
"bytes": "40121403"
},
{
"name": "Groovy",
"bytes": "347"
},
{
"name": "HTML",
"bytes": "359263"
},
{
"name": "JavaScript",
"bytes": "545384"
},
{
"name": "Makefile",
"bytes": "6671"
},
{
"name": "Mathematica",
"bytes": "14565"
},
{
"name": "Objective-C",
"bytes": "14900720"
},
{
"name": "Objective-C++",
"bytes": "20070"
},
{
"name": "PureBasic",
"bytes": "4152"
},
{
"name": "Python",
"bytes": "4490569"
},
{
"name": "Ruby",
"bytes": "44850"
},
{
"name": "Shell",
"bytes": "33251"
},
{
"name": "Swift",
"bytes": "463286"
},
{
"name": "TSQL",
"bytes": "108861"
}
],
"symlink_target": ""
} |
package com.stratuscom.harvester.classloading;
import java.util.logging.Logger;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import com.stratuscom.harvester.MessageNames;
/**
* A ClassPathEntry is used by the VirtualFileSystemClassLoader, and is a
combination of a ClasspathFilter and the fileObject that points to the entry's
jar file. It effectively represents an entry like 'container.jar(org.apache.ABC)',
which would mean 'the class org.apache.ABC contained inside the jar file
container.jar'. The idea is to include selected packages from a jar file on the
classpath,
* @author trasukg
*/
public class ClasspathEntry {
private ClasspathFilter classpathFilter=null;
private FileObject fileObject=null;
public ClasspathEntry(ClasspathFilter filter, FileObject fileObject) {
this.fileObject=fileObject;
this.classpathFilter=filter;
}
public FileObject resolveFile(String name) throws FileSystemException {
if ((classpathFilter.acceptsResource(name))) {
return fileObject.resolveFile(name);
}
return null;
}
@Override
public String toString() {
return fileObject.toString() + classpathFilter.toString();
}
}
| {
"content_hash": "8077ef1b10d3206af1412b47a71685fc",
"timestamp": "",
"source": "github",
"line_count": 40,
"max_line_length": 84,
"avg_line_length": 32.05,
"alnum_prop": 0.7371294851794071,
"repo_name": "trasukg/harvester-app-container",
"id": "9ef53234a9069465204298bf0aad17d95390aa53",
"size": "2086",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "harvester-container-core/src/main/java/com/stratuscom/harvester/classloading/ClasspathEntry.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "8035"
},
{
"name": "Groovy",
"bytes": "707"
},
{
"name": "HTML",
"bytes": "36907"
},
{
"name": "Java",
"bytes": "618971"
},
{
"name": "Shell",
"bytes": "959"
},
{
"name": "XSLT",
"bytes": "39779"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title> METADATA SCORRE HISTOGRAM</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<!-- Bar chart from http://bost.ocks.org/mike/bar/ modified to not use data imported from a file, to have X-axis label and chart title -->
<!-- Import D3.js -->
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<!-- Here's an SVG element -->
<svg class="chart"></svg>
<script src="js/index4.js"></script>
</body>
</html>
| {
"content_hash": "63c81f1e74af9877b3c28558d433710c",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 142,
"avg_line_length": 19.06451612903226,
"alnum_prop": 0.55668358714044,
"repo_name": "USCDataScience/polar.usc.edu",
"id": "649933c698486ed8abb54b733c95ab32f2033085",
"size": "591",
"binary": false,
"copies": "2",
"ref": "refs/heads/gh-pages",
"path": "html/team24ev/Histogram/index4.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "BlitzBasic",
"bytes": "57"
},
{
"name": "CSS",
"bytes": "112321"
},
{
"name": "CoffeeScript",
"bytes": "3349"
},
{
"name": "Common Lisp",
"bytes": "123"
},
{
"name": "DIGITAL Command Language",
"bytes": "293712"
},
{
"name": "HTML",
"bytes": "4670521"
},
{
"name": "Io",
"bytes": "1042"
},
{
"name": "JavaScript",
"bytes": "2939072"
},
{
"name": "Jupyter Notebook",
"bytes": "18308"
},
{
"name": "NewLisp",
"bytes": "1486"
},
{
"name": "PHP",
"bytes": "4021"
},
{
"name": "Perl",
"bytes": "694"
},
{
"name": "Python",
"bytes": "135257"
},
{
"name": "RenderScript",
"bytes": "49"
},
{
"name": "Roff",
"bytes": "1072580"
},
{
"name": "Ruby",
"bytes": "814"
},
{
"name": "Tcl",
"bytes": "52"
},
{
"name": "xBase",
"bytes": "2167"
}
],
"symlink_target": ""
} |
package org.apache.camel.component.servlet;
import org.apache.camel.component.http.CamelServlet;
import org.apache.camel.component.http.HttpConsumer;
/**
* Keeps track of HttpConsumers and CamelServlets and
* connects them to each other. In OSGi there should
* be one HttpRegistry per bundle.
*
* A CamelServlet that should serve more than one
* bundle should be registered as an OSGi service.
* The HttpRegistryImpl can then be configured to listen
* to service changes. See /tests/camel-itest-osgi/../servlet
* for an example how to use this.
*/
public interface HttpRegistry {
void register(HttpConsumer consumer);
void unregister(HttpConsumer consumer);
void register(CamelServlet provider);
void unregister(CamelServlet provider);
} | {
"content_hash": "f322a6198af64f1b47070191ffc38e30",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 61,
"avg_line_length": 28.571428571428573,
"alnum_prop": 0.73625,
"repo_name": "cexbrayat/camel",
"id": "acd4e1a8dc6542f995461c54c8e7ead8ce3b52df",
"size": "1618",
"binary": false,
"copies": "3",
"ref": "refs/heads/trunk",
"path": "components/camel-servlet/src/main/java/org/apache/camel/component/servlet/HttpRegistry.java",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<?php
namespace Chamilo\Application\Calendar\Extension\Personal\Integration\Chamilo\Libraries\Calendar\Event;
use Chamilo\Application\Calendar\Extension\Personal\Storage\DataClass\Publication;
use Chamilo\Libraries\Architecture\Application\Application;
use Chamilo\Libraries\File\Redirect;
/**
*
* @package Chamilo\Application\Calendar\Extension\Personal\Integration\Chamilo\Libraries\Calendar\Event
* @author Hans De Bisschop <[email protected]>
* @author Magali Gillard <[email protected]>
* @author Eduard Vossen <[email protected]>
*/
class EventParser
{
/**
*
* @var \Chamilo\Libraries\Calendar\Renderer\Service\CalendarRendererProvider
*/
private $calendarRendererProvider;
/**
*
* @var \Chamilo\Application\Calendar\Extension\Personal\Storage\DataClass\Publication
*/
private $publication;
/**
*
* @var integer
*/
private $fromDate;
/**
*
* @var integer
*/
private $toDate;
/**
*
* @param \Chamilo\Libraries\Calendar\Renderer\Service\CalendarRendererProvider $calendarRendererProvider
* @param \Chamilo\Application\Calendar\Extension\Personal\Storage\DataClass\Publication $publication
* @param integer $fromDate
* @param integer $toDate
*/
public function __construct(
\Chamilo\Libraries\Calendar\Renderer\Service\CalendarRendererProvider $calendarRendererProvider,
Publication $publication, $fromDate, $toDate)
{
$this->calendarRendererProvider = $calendarRendererProvider;
$this->publication = $publication;
$this->fromDate = $fromDate;
$this->toDate = $toDate;
}
/**
*
* @return \Chamilo\Libraries\Calendar\Renderer\Renderer
*/
public function getCalendarRendererProvider()
{
return $this->calendarRendererProvider;
}
/**
*
* @param \Chamilo\Libraries\Calendar\Renderer\Renderer $renderer
*/
public function setCalendarRendererProvider(
\Chamilo\Libraries\Calendar\Renderer\Service\CalendarRendererProvider $calendarRendererProvider)
{
$this->calendarRendererProvider = $calendarRendererProvider;
}
/**
*
* @return \Chamilo\Application\Calendar\Extension\Personal\Storage\DataClass\Publication
*/
public function getPublication()
{
return $this->publication;
}
/**
*
* @param \Chamilo\Application\Calendar\Extension\Personal\Storage\DataClass\Publication $publication
*/
public function setPublication($publication)
{
$this->publication = $publication;
}
/**
*
* @return integer
*/
public function getFromDate()
{
return $this->fromDate;
}
/**
*
* @param integer $fromDate
*/
public function setFromDate($fromDate)
{
$this->fromDate = $fromDate;
}
/**
*
* @return integer
*/
public function getToDate()
{
return $this->toDate;
}
/**
*
* @param integer $toDate
*/
public function setToDate($toDate)
{
$this->toDate = $toDate;
}
/**
*
* @return \Chamilo\Core\Repository\Integration\Chamilo\Libraries\Calendar\Event\Event[]
*/
public function getEvents()
{
$events = array();
$publisher = $this->getPublication()->get_publisher();
$publishingUser = $this->getPublication()->get_publication_publisher();
$parser = \Chamilo\Core\Repository\Integration\Chamilo\Libraries\Calendar\Event\EventParser::factory(
$this->getPublication()->get_publication_object(),
$this->getFromDate(),
$this->getToDate(),
Event::class_name());
$parsedEvents = $parser->getEvents();
foreach ($parsedEvents as &$parsedEvent)
{
if ($publisher != $this->getCalendarRendererProvider()->getViewingUser()->getId())
{
$parsedEvent->setTitle($parsedEvent->getTitle() . ' [' . $publishingUser->get_fullname() . ']');
}
$parsedEvent->setId($this->getPublication()->get_id());
$parsedEvent->setContext(\Chamilo\Application\Calendar\Extension\Personal\Manager::context());
$parameters = array();
$parameters[Application::PARAM_CONTEXT] = \Chamilo\Application\Calendar\Extension\Personal\Manager::context();
$parameters[\Chamilo\Application\Calendar\Extension\Personal\Manager::PARAM_ACTION] = \Chamilo\Application\Calendar\Extension\Personal\Manager::ACTION_VIEW;
$parameters[\Chamilo\Application\Calendar\Extension\Personal\Manager::PARAM_PUBLICATION_ID] = $this->getPublication()->get_id();
$redirect = new Redirect($parameters);
$parsedEvent->setUrl($redirect->getUrl());
$events[] = $parsedEvent;
}
return $events;
}
}
| {
"content_hash": "777811faf6cd30d544572748fe050fb3",
"timestamp": "",
"source": "github",
"line_count": 173,
"max_line_length": 168,
"avg_line_length": 29.121387283236995,
"alnum_prop": 0.6244541484716157,
"repo_name": "forelo/cosnics",
"id": "e941d5dae87a57ece0167ff4f4717e804773962f",
"size": "5038",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "src/Chamilo/Application/Calendar/Extension/Personal/Integration/Chamilo/Libraries/Calendar/Event/EventParser.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ActionScript",
"bytes": "262730"
},
{
"name": "C",
"bytes": "12354"
},
{
"name": "CSS",
"bytes": "1334431"
},
{
"name": "CoffeeScript",
"bytes": "41023"
},
{
"name": "Gherkin",
"bytes": "24033"
},
{
"name": "HTML",
"bytes": "1016812"
},
{
"name": "Hack",
"bytes": "424"
},
{
"name": "JavaScript",
"bytes": "10768095"
},
{
"name": "Less",
"bytes": "331253"
},
{
"name": "Makefile",
"bytes": "3221"
},
{
"name": "PHP",
"bytes": "23623996"
},
{
"name": "Python",
"bytes": "2408"
},
{
"name": "Ruby",
"bytes": "618"
},
{
"name": "SCSS",
"bytes": "163532"
},
{
"name": "Shell",
"bytes": "7965"
},
{
"name": "Smarty",
"bytes": "15750"
},
{
"name": "Twig",
"bytes": "388197"
},
{
"name": "TypeScript",
"bytes": "123212"
},
{
"name": "Vue",
"bytes": "454138"
},
{
"name": "XSLT",
"bytes": "43009"
}
],
"symlink_target": ""
} |
#pragma once
#include <string>
#include "envoy/server/filter_config.h"
#include "common/config/well_known_names.h"
#include "server/config/http/empty_http_filter_config.h"
namespace Envoy {
namespace Server {
namespace Configuration {
/**
* Config registration for the grpc HTTP1 bridge filter. @see NamedHttpFilterConfigFactory.
*/
class GrpcHttp1BridgeFilterConfig : public EmptyHttpFilterConfig {
public:
HttpFilterFactoryCb createFilter(const std::string&, FactoryContext& context) override;
std::string name() override { return Config::HttpFilterNames::get().GRPC_HTTP1_BRIDGE; }
};
} // namespace Configuration
} // namespace Server
} // namespace Envoy
| {
"content_hash": "631e11536786d676398755c447d8737c",
"timestamp": "",
"source": "github",
"line_count": 27,
"max_line_length": 91,
"avg_line_length": 24.962962962962962,
"alnum_prop": 0.7655786350148368,
"repo_name": "amalgam8/envoy",
"id": "d23f8d0dcd8675a6049bb88df3cf56e0fd1321d4",
"size": "674",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "source/server/config/http/grpc_http1_bridge.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "322"
},
{
"name": "C++",
"bytes": "4966381"
},
{
"name": "Makefile",
"bytes": "2341"
},
{
"name": "Python",
"bytes": "338195"
},
{
"name": "Shell",
"bytes": "60236"
},
{
"name": "Smarty",
"bytes": "435427"
}
],
"symlink_target": ""
} |
<!doctype html>
<html>
<head>
<title>Pie Chart</title>
<script src="../Chart.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body>
<div id="canvas-holder" style="width:50%">
<canvas id="chart-area" width="300" height="300" />
</div>
<button id="randomizeData">Randomize Data</button>
<button id="addDataset">Add Dataset</button>
<button id="removeDataset">Remove Dataset</button>
<script>
var randomScalingFactor = function() {
return Math.round(Math.random() * 100);
};
var randomColorFactor = function() {
return Math.round(Math.random() * 255);
};
var randomColor = function(opacity) {
return 'rgba(' + randomColorFactor() + ',' + randomColorFactor() + ',' + randomColorFactor() + ',' + (opacity || '.3') + ')';
};
var config = {
type: 'pie',
data: {
datasets: [{
data: [
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor(),
],
backgroundColor: [
"#F7464A",
"#46BFBD",
"#FDB45C",
"#949FB1",
"#4D5360",
],
}, {
data: [
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor(),
],
backgroundColor: [
"#F7464A",
"#46BFBD",
"#FDB45C",
"#949FB1",
"#4D5360",
],
}, {
data: [
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor(),
],
backgroundColor: [
"#F7464A",
"#46BFBD",
"#FDB45C",
"#949FB1",
"#4D5360",
],
}],
labels: [
"Red",
"Green",
"Yellow",
"Grey",
"Dark Grey"
]
},
options: {
responsive: true
}
};
window.onload = function() {
var ctx = document.getElementById("chart-area").getContext("2d");
window.myPie = new Chart(ctx, config);
};
$('#randomizeData').click(function() {
$.each(config.data.datasets, function(i, piece) {
$.each(piece.data, function(j, value) {
config.data.datasets[i].data[j] = randomScalingFactor();
//config.data.datasets.backgroundColor[i] = 'rgba(' + randomColorFactor() + ',' + randomColorFactor() + ',' + randomColorFactor() + ',.7)';
});
});
window.myPie.update();
});
$('#addDataset').click(function() {
var newDataset = {
backgroundColor: [randomColor(0.7), randomColor(0.7), randomColor(0.7), randomColor(0.7), randomColor(0.7)],
data: [randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor()]
};
config.data.datasets.push(newDataset);
window.myPie.update();
});
$('#removeDataset').click(function() {
config.data.datasets.splice(0, 1);
window.myPie.update();
});
</script>
</body>
</html>
| {
"content_hash": "ea1c3f3cec4ac616d83b5b6cae40fe07",
"timestamp": "",
"source": "github",
"line_count": 122,
"max_line_length": 155,
"avg_line_length": 31.450819672131146,
"alnum_prop": 0.44983059682043264,
"repo_name": "metodika/Chart.js",
"id": "3d05fc20c1967c2f3790fcdce8b7d426adb076e5",
"size": "3837",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "samples/pie.html",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "537231"
}
],
"symlink_target": ""
} |
var fs = require('graceful-fs')
var ncp = require('./_copy').ncp
var path = require('path')
var rimraf = require('rimraf')
var mkdirp = require('./mkdir').mkdirs
function mv(source, dest, options, callback){
if (typeof options === 'function') {
callback = options
options = {}
}
var shouldMkdirp = !!options.mkdirp
var clobber = options.clobber !== false
var limit = options.limit || 16
if (shouldMkdirp) {
mkdirs()
} else {
doRename()
}
function mkdirs() {
mkdirp(path.dirname(dest), function(err) {
if (err) return callback(err)
doRename()
})
}
function doRename() {
if (clobber) {
fs.rename(source, dest, function(err) {
if (!err) return callback()
if (err.code !== 'EXDEV') return callback(err)
moveFileAcrossDevice(source, dest, clobber, limit, callback)
})
} else {
fs.link(source, dest, function(err) {
if (err) {
if (err.code === 'EXDEV') {
moveFileAcrossDevice(source, dest, clobber, limit, callback)
return
}
if (err.code === 'EISDIR' || err.code === 'EPERM') {
moveDirAcrossDevice(source, dest, clobber, limit, callback)
return
}
callback(err)
return
}
fs.unlink(source, callback)
})
}
}
}
function moveFileAcrossDevice(source, dest, clobber, limit, callback) {
var outFlags = clobber ? 'w' : 'wx'
var ins = fs.createReadStream(source)
var outs = fs.createWriteStream(dest, {flags: outFlags})
ins.on('error', function(err) {
ins.destroy()
outs.destroy()
outs.removeListener('close', onClose)
if (err.code === 'EISDIR' || err.code === 'EPERM') {
moveDirAcrossDevice(source, dest, clobber, limit, callback)
} else {
callback(err)
}
})
outs.on('error', function(err) {
ins.destroy()
outs.destroy()
outs.removeListener('close', onClose)
callback(err)
})
outs.once('close', onClose)
ins.pipe(outs)
function onClose() {
fs.unlink(source, callback)
}
}
function moveDirAcrossDevice(source, dest, clobber, limit, callback) {
var options = {
stopOnErr: true,
clobber: false,
limit: limit,
}
function startNcp() {
ncp(source, dest, options, function(errList) {
if (errList) return callback(errList[0])
rimraf(source, callback)
})
}
if (clobber) {
rimraf(dest, function(err) {
if (err) return callback(err)
startNcp()
})
} else {
startNcp()
}
}
module.exports = mv
| {
"content_hash": "c9655ded0c89d488c6137007f7cb4714",
"timestamp": "",
"source": "github",
"line_count": 114,
"max_line_length": 72,
"avg_line_length": 22.640350877192983,
"alnum_prop": 0.5869817900038745,
"repo_name": "Voltir/scalacss",
"id": "40ec4b4cb88ac4874cfeffd403db96277bd53324",
"size": "2749",
"binary": false,
"copies": "7",
"ref": "refs/heads/master",
"path": "node_modules/gitbook-cli/node_modules/fs-extra/lib/move.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "410"
},
{
"name": "Java",
"bytes": "4508"
},
{
"name": "Scala",
"bytes": "616039"
},
{
"name": "Shell",
"bytes": "5646"
}
],
"symlink_target": ""
} |
Besides parsing and evaluating expressions, the expression parser supports
a number of features to customize processing and evaluation of expressions
and outputting expressions.
On this page:
- [Function transforms](#function-transforms)
- [Custom argument parsing](#custom-argument-parsing)
- [Custom LaTeX handlers](#custom-latex-handlers)
- [Custom HTML, LaTeX and string output](#custom-html-latex-and-string-output)
- [Customize supported characters](#customize-supported-characters)
## Function transforms
It is possible to preprocess function arguments and post process a functions
return value by writing a *transform* for the function. A transform is a
function wrapping around a function to be transformed or completely replaces
a function.
For example, the functions for math.js use zero-based matrix indices (as is
common in programing languages), but the expression parser uses one-based
indices. To enable this, all functions dealing with indices have a transform,
which changes input from one-based to zero-based, and transforms output (and
error message) from zero-based to one-based.
```js
// using plain JavaScript, indices are zero-based:
var a = [[1, 2], [3, 4]]; // a 2x2 matrix
math.subset(a, math.index(0, 1)); // returns 2
// using the expression parser, indices are transformed to one-based:
var a = [[1, 2], [3, 4]]; // a 2x2 matrix
var scope = {
a: a
};
math.eval('subset(a, index(1, 2))', scope); // returns 2
```
To create a transform for a function, the transform function must be attached
to the function as property `transform`:
```js
var math = require('../index');
// create a function
function addIt(a, b) {
return a + b;
}
// attach a transform function to the function addIt
addIt.transform = function (a, b) {
console.log('input: a=' + a + ', b=' + b);
// we can manipulate input here before executing addIt
var res = addIt(a, b);
console.log('result: ' + res);
// we can manipulate result here before returning
return res;
};
// import the function into math.js
math.import({
addIt: addIt
});
// use the function via the expression parser
console.log('Using expression parser:');
console.log('2+4=' + math.eval('addIt(2, 4)'));
// This will output:
//
// input: a=2, b=4
// result: 6
// 2+4=6
// when used via plain JavaScript, the transform is not invoked
console.log('');
console.log('Using plain JavaScript:');
console.log('2+4=' + math.addIt(2, 4));
// This will output:
//
// 6
```
Functions with a transform must be imported in the `math` namespace, as they
need to be processed at compile time. They are not supported when passed via a
scope at evaluation time.
## Custom argument parsing
The expression parser of math.js has support for letting functions
parse and evaluate arguments themselves, instead of calling them with
evaluated arguments. This is useful for example when creating a function
like `plot(f(x), x)` or `integrate(f(x), x, start, end)`, where some of the
arguments need to be processed in a special way. In these cases, the expression
`f(x)` will be evaluated repeatedly by the function, and `x` is not evaluated
but used to specify the variable looping over the function `f(x)`.
Functions having a property `rawArgs` with value `true` are treated in a special
way by the expression parser: they will be invoked with unevaluated arguments,
allowing the function to process the arguments in a customized way. Raw
functions are called as:
```
rawFunction(args: Node[], math: Object, scope: Object)
```
Where :
- `args` is an Array with nodes of the parsed arguments.
- `math` is the math namespace against which the expression was compiled.
- `scope` is the scope provided when evaluating the expression.
Raw functions must be imported in the `math` namespace, as they need to be
processed at compile time. They are not supported when passed via a scope
at evaluation time.
A simple example:
```js
function myFunction(args, math, scope) {
// get string representation of the arguments
var str = args.map(function (arg) {
return arg.toString();
})
// evaluate the arguments
var res = args.map(function (arg) {
return arg.compile().eval(scope);
});
return 'arguments: ' + str.join(',') + ', evaluated: ' + res.join(',');
}
// mark the function as "rawArgs", so it will be called with unevaluated arguments
myFunction.rawArgs = true;
// import the new function in the math namespace
math.import({
myFunction: myFunction
})
// use the function
math.eval('myFunction(2 + 3, sqrt(4))');
// returns 'arguments: 2 + 3, sqrt(4), evaluated: 5, 2'
```
## Custom LaTeX handlers
You can attach a `toTex` property to your custom functions before importing them to define their LaTeX output. This
`toTex` property can be a handler in the format described in the next section 'Custom LaTeX and String conversion'
or a template string similar to ES6 templates.
### Template syntax
- `${name}`: Gets replaced by the name of the function
- `${args}`: Gets replaced by a comma separated list of the arguments of the function.
- `${args[0]}`: Gets replaced by the first argument of a function
- `$$`: Gets replaced by `$`
#### Example
```js
var customFunctions = {
plus: function (a, b) {
return a + b;
},
minus: function (a, b) {
return a - b;
},
binom: function (n, k) {
return 1;
}
};
customFunctions.plus.toTex = '${args[0]}+${args[1]}'; //template string
customFunctions.binom.toTex = '\\mathrm{${name}}\\left(${args}\\right)'; //template string
customFunctions.minus.toTex = function (node, options) { //handler function
return node.args[0].toTex(options) + node.name + node.args[1].toTex(options);
};
math.import(customFunctions);
math.parse('plus(1,2)').toTex(); //'1+2'
math.parse('binom(1,2)').toTex(); // '\\mathrm{binom}\\left(1,2\\right)'
math.parse('minus(1,2)').toTex(); // '1minus2'
```
## Custom HTML, LaTeX and string output
All expression nodes have a method `toTex` and `toString` to output an expression respectively in HTML or LaTex format or as regular text .
The functions `toHTML`, `toTex` and `toString` accept an `options` argument to customise output. This object is of the following form:
```js
{
parenthesis: 'keep', // parenthesis option
handler: someHandler, // handler to change the output
implicit: 'hide' // how to treat implicit multiplication
}
```
### Parenthesis
The `parenthesis` option changes the way parentheses are used in the output. There are three options available:
- `keep` Keep the parentheses from the input and display them as is. This is the default.
- `auto` Only display parentheses that are necessary. Mathjs tries to get rid of as much parentheses as possible.
- `all` Display all parentheses that are given by the structure of the node tree. This makes the output precedence unambiguous.
There's two ways of passing callbacks:
1. Pass an object that maps function names to callbacks. Those callbacks will be used for FunctionNodes with
functions of that name.
2. Pass a function to `toTex`. This function will then be used for every node.
```js
var expression = math.parse('(1+1+1)');
expression.toString(); //(1 + 1 + 1)
expression.toString({parenthesis: 'keep'}); //(1 + 1 + 1)
expression.toString({parenthesis: 'auto'}); //1 + 1 + 1
expression.toString({parenthesis: 'all'}); //(1 + 1) + 1
```
### Handler
You can provide the `toTex` and `toString` functions of an expression with your own custom handlers that override the internal behaviour. This is especially useful to provide LaTeX/string output for your own custom functions. This can be done in two ways:
1. Pass an object that maps function names to callbacks. Those callbacks will be used for FunctionNodes that contain functions with that name.
2. Pass a callback directly. This callback will run for every node, so you can replace the output of anything you like.
A callback function has the following form:
```js
var callback = function (node, options) {
...
}
```
Where `options` is the object passed to `toHTML`/`toTex`/`toString`. Don't forget to pass this on to the child nodes, and `node` is a reference to the current node.
If a callback returns nothing, the standard output will be used. If your callback returns a string, this string will be used.
**Although the following examples use `toTex`, it works for `toString` and `toHTML` in the same way**
#### Examples for option 1
```js
var customFunctions = {
binomial: function (n, k) {
//calculate n choose k
// (do some stuff)
return result;
}
};
var customLaTeX = {
'binomial': function (node, options) { //provide toTex for your own custom function
return '\\binom{' + node.args[0].toTex(options) + '}{' + node.args[1].toTex(options) + '}';
},
'factorial': function (node, options) { //override toTex for builtin functions
return 'factorial\\left(' + node.args[0] + '\\right)';
}
};
```
You can simply use your custom toTex functions by passing them to `toTex`:
```js
math.import(customFunctions);
var expression = math.parse('binomial(factorial(2),1)');
var latex = expression.toTex({handler: customLaTeX});
//latex now contains "\binom{factorial\\left(2\\right)}{1}"
```
#### Examples for option 2:
```js
var customLaTeX = function (node, options) {
if ((node.type === 'OperatorNode') && (node.fn === 'add')) {
//don't forget to pass the options to the toTex functions
return node.args[0].toTex(options) + ' plus ' + node.args[1].toTex(options);
}
else if (node.type === 'ConstantNode') {
if (node.value == 0) {
return '\\mbox{zero}';
}
else if (node.value == 1) {
return '\\mbox{one}';
}
else if (node.value == 2) {
return '\\mbox{two}';
}
else {
return node.value;
}
}
};
var expression = math.parse('1+2');
var latex = expression.toTex({handler: customLaTeX});
//latex now contains '\mbox{one} plus \mbox{two}'
```
Another example in conjunction with custom functions:
```js
var customFunctions = {
binomial: function (n, k) {
//calculate n choose k
// (do some stuff)
return result;
}
};
var customLaTeX = function (node, options) {
if ((node.type === 'FunctionNode') && (node.name === 'binomial')) {
return '\\binom{' + node.args[0].toTex(options) + '}{' + node.args[1].toTex(options) + '}';
}
};
math.import(customFunctions);
var expression = math.parse('binomial(2,1)');
var latex = expression.toTex({handler: customLaTeX});
//latex now contains "\binom{2}{1}"
```
### Implicit multiplication
You can change the way that implicit multiplication is converted to a string or LaTeX. The two options are `hide`, to not show a multiplication operator for implicit multiplication and `show` to show it.
Example:
```js
var node = math.parse('2a');
node.toString(); //'2 a'
node.toString({implicit: 'hide'}); //'2 a'
node.toString({implicit: 'show'}); //'2 * a'
node.toTex(); //'2~ a'
node.toTex({implicit: 'hide'}); //'2~ a'
node.toTex({implicit: 'show'}); //'2\\cdot a'
```
## Customize supported characters
It is possible to customize the characters allowed in symbols and digits.
The `parse` function exposes the following test functions:
- `math.expression.parse.isAlpha(c, cPrev, cNext)`
- `math.expression.parse.isWhitespace(c, nestingLevel)`
- `math.expression.parse.isDecimalMark(c, cNext)`
- `math.expression.parse.isDigitDot(c)`
- `math.expression.parse.isDigit(c)`
The exact signature and implementation of these functions can be looked up in
the [source code of the parser](https://github.com/josdejong/mathjs/blob/master/lib/expression/parse.js). The allowed alpha characters are described here: [Constants and variables](syntax.md#constants-and-variables).
For example, the phone character <code>☎</code> is not supported by default. It can be enabled
by replacing the `isAlpha` function:
```js
var isAlphaOriginal = math.expression.parse.isAlpha;
math.expression.parse.isAlpha = function (c, cPrev, cNext) {
return isAlphaOriginal(c, cPrev, cNext) || (c === '\u260E');
};
// now we can use the \u260E (phone) character in expressions
var result = math.eval('\u260Efoo', {'\u260Efoo': 42}); // returns 42
console.log(result);
```
| {
"content_hash": "23aba9ebd915e3ad852637c100edf9e3",
"timestamp": "",
"source": "github",
"line_count": 374,
"max_line_length": 255,
"avg_line_length": 32.63903743315508,
"alnum_prop": 0.7032850004096011,
"repo_name": "ocadni/citychrone",
"id": "62dc1d9e8e4d5cf3cac71376f913adcf7dbae79c",
"size": "12224",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "node_modules/mathjs/docs/expressions/customization.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "46395"
},
{
"name": "HTML",
"bytes": "18635"
},
{
"name": "JavaScript",
"bytes": "183571"
},
{
"name": "Jupyter Notebook",
"bytes": "72"
},
{
"name": "Shell",
"bytes": "296"
}
],
"symlink_target": ""
} |
require "fairy/version"
#TODO: fix me
require 'eventmachine'
require 'em-websocket'
module Fairy
autoload :Server, 'fairy/server'
autoload :Connection, 'fairy/connection'
end
| {
"content_hash": "1aa707e26cf0a5d453fa727e8fbf0016",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 42,
"avg_line_length": 18.1,
"alnum_prop": 0.7569060773480663,
"repo_name": "darkleaf/fairy",
"id": "31d042c7c0022953ec69b8f2855cd239a6e8f225",
"size": "181",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/fairy.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "1043"
}
],
"symlink_target": ""
} |
:mod:`krypy.recycling.factories` - deflation vector factories
=============================================================
.. automodule:: krypy.recycling.factories
:members:
:undoc-members:
:show-inheritance:
.. autoclass:: krypy.recycling.factories._DeflationVectorFactory
:members:
:private-members:
| {
"content_hash": "0d3d260e88d99cfbe1eec9fc459df80c",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 64,
"avg_line_length": 29.636363636363637,
"alnum_prop": 0.588957055214724,
"repo_name": "highlando/krypy",
"id": "6cac3219d7e8ef32e88f9305a066224e2b02bfab",
"size": "326",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "docs/krypy.recycling.factories.rst",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "212929"
}
],
"symlink_target": ""
} |
local arg = arg
_G.arg = nil
dofile '../../../info.lua'
os.execute('mkdir -p ' .. Info.PackageName .. '/usr/bin')
for FileIndex = 2, #arg
do
os.execute('cp ' .. arg[FileIndex] .. ' ' .. Info.PackageName .. '/usr/bin')
end
os.execute('mkdir -p ' .. Info.PackageName .. '/usr/share/' .. Info.PackageName)
os.execute('cp ../../../data/* ' .. Info.PackageName .. '/usr/share/' .. Info.PackageName)
os.execute('mkdir -p ' .. Info.PackageName .. '/usr/share/doc/' .. Info.PackageName)
os.execute('cp ../../../license.txt ' .. Info.PackageName .. '/usr/share/doc/' .. Info.PackageName)
local InstalledSize = io.popen('du -s -BK ' .. Info.PackageName):read():gsub('[^%d].*$', '')
print('Installed size is ' .. InstalledSize)
os.execute('mkdir -p ' .. Info.PackageName .. '/DEBIAN')
io.open(Info.PackageName .. '/DEBIAN/control', 'w+'):write([[
Package: ]] .. Info.PackageName .. [[
Version: ]] .. Info.Version .. [[
Section: Graphics
Priority: Optional
Architecture: ]] .. arg[1] .. [[
Depends: libstdc++6 (>= 4.7.0-7ubuntu3), liblua5.2-0 (>= 5.2.0-2), libbz2-1.0 (>= 1.0.6-1), libgtk2.0-0 (>= 2.24.10-0ubuntu6)
Maintainer: ]] .. Info.Author .. ' <' .. Info.EMail .. [[>
Description: ]] .. Info.ExtendedDescription .. [[
Installed-Size: ]] .. InstalledSize .. [[
Homepage: ]] .. Info.Website .. [[
]]):close()
os.execute('fakeroot dpkg --build ' .. Info.PackageName .. ' .')
os.execute('rm -r ' .. Info.PackageName)
| {
"content_hash": "803f50b5e4eded7ae1e7373d09b64e55",
"timestamp": "",
"source": "github",
"line_count": 40,
"max_line_length": 125,
"avg_line_length": 35.5,
"alnum_prop": 0.6056338028169014,
"repo_name": "Rendaw/inscribist",
"id": "4a895ed1fcf07bf00fa60740b854d8ac1015d59e",
"size": "1435",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "packaging/ubuntu12/package.lua",
"mode": "33261",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "381"
},
{
"name": "C++",
"bytes": "112942"
},
{
"name": "Lua",
"bytes": "14597"
}
],
"symlink_target": ""
} |
The sources in this directory are unit test cases. Boost includes a
unit testing framework, and since bitcoin already uses boost, it makes
sense to simply use this framework rather than require developers to
configure some other framework (we want as few impediments to creating
unit tests as possible).
The build system is setup to compile an executable called "test_bitcoin"
that runs all of the unit tests. The main source file is called
test_bitcoin.cpp, which simply includes other files that contain the
actual unit tests (outside of a couple required preprocessor
directives). The pattern is to create one test file for each class or
source file for which you want to create unit tests. The file naming
convention is "<source_filename>_tests.cpp" and such files should wrap
their tests in a test suite called "<source_filename>_tests". For an
examples of this pattern, examine uint160_tests.cpp and
uint256_tests.cpp.
For further reading, I found the following website to be helpful in
explaining how the boost unit test framework works:
[http://www.alittlemadness.com/2009/03/31/c-unit-testing-with-boosttest/](http://www.alittlemadness.com/2009/03/31/c-unit-testing-with-boosttest/). | {
"content_hash": "9fad317bd35f83190393f6652014b76b",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 147,
"avg_line_length": 60.9,
"alnum_prop": 0.7857142857142857,
"repo_name": "SoyPay/soypay",
"id": "2c0d54d0ff589bb6cd805c67c7404928906b4cae",
"size": "1227",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/test/README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "1421861"
},
{
"name": "C++",
"bytes": "3070336"
},
{
"name": "Python",
"bytes": "79330"
},
{
"name": "Shell",
"bytes": "40489"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<com.manuelpeinado.imagelayout.ImageLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:custom="http://schemas.android.com/apk/res-auto"
android:id="@+id/image_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#aaa"
custom:fit="both"
custom:image="@drawable/boroughs"
custom:imageHeight="1744"
custom:imageWidth="1150">
<TextView
android:id="@+id/header"
style="@style/ImageText.Large"
custom:layout_centerX="318"
custom:layout_centerY="150"
custom:layout_maxWidth="440"
android:text="@string/choose_a_borough" />
<Button
android:id="@+id/manhattan"
style="@style/ImageText"
custom:layout_centerX="608"
custom:layout_centerY="595"
android:text="@string/manhattan"
android:onClick="onButtonClick"/>
</com.manuelpeinado.imagelayout.ImageLayout> | {
"content_hash": "132908b38ef797bd6c66db8e6b01e353",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 62,
"avg_line_length": 32.25806451612903,
"alnum_prop": 0.659,
"repo_name": "0359xiaodong/ImageLayout",
"id": "1deaead2fd6012404ec071d1962c10f3be615d6b",
"size": "1000",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "sample/res/layout/activity_change_image_dynamically.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
package com.baidu.rigel.biplatform.ac.util;
import com.baidu.rigel.biplatform.ac.annotation.GsonIgnore;
import com.baidu.rigel.biplatform.ac.model.Cube;
import com.baidu.rigel.biplatform.ac.model.Dimension;
import com.baidu.rigel.biplatform.ac.model.Level;
import com.baidu.rigel.biplatform.ac.model.Measure;
import com.baidu.rigel.biplatform.ac.model.Schema;
import com.baidu.rigel.biplatform.ac.query.data.DataSourceInfo;
import com.baidu.rigel.biplatform.ac.query.model.MetaCondition;
import com.baidu.rigel.biplatform.ac.util.deserialize.CubeDeserialize;
import com.baidu.rigel.biplatform.ac.util.deserialize.DataSourceInfoDeserialize;
import com.baidu.rigel.biplatform.ac.util.deserialize.DimensionDeserialize;
import com.baidu.rigel.biplatform.ac.util.deserialize.LevelDeserialize;
import com.baidu.rigel.biplatform.ac.util.deserialize.MeasureDeserialize;
import com.baidu.rigel.biplatform.ac.util.deserialize.MetaConditionDeserialize;
import com.baidu.rigel.biplatform.ac.util.deserialize.SchemaDeserialize;
import com.baidu.rigel.biplatform.ac.util.serialize.CubeSerialize;
import com.baidu.rigel.biplatform.ac.util.serialize.DataSourceInfoSerialize;
import com.baidu.rigel.biplatform.ac.util.serialize.DimensionSerialize;
import com.baidu.rigel.biplatform.ac.util.serialize.LevelSerialize;
import com.baidu.rigel.biplatform.ac.util.serialize.MeasureSerialize;
import com.baidu.rigel.biplatform.ac.util.serialize.MetaConditionSerialize;
import com.baidu.rigel.biplatform.ac.util.serialize.SchemaSerialize;
import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
/**
* answercore 常量
*
* @author xiaoming.chen
*
*/
public class AnswerCoreConstant {
/**
* GSON 忽略掉属性上加了GsonIgnore注解的属性
*/
public static final Gson GSON;
static {
GsonBuilder builder = new GsonBuilder()
.disableHtmlEscaping();
// 添加如果有GsonIgnore注解,忽略序列化
builder.addSerializationExclusionStrategy(new ExclusionStrategy() {
@Override
public boolean shouldSkipField(FieldAttributes f) {
GsonIgnore gsonIgnore = f.getAnnotation(GsonIgnore.class);
if (gsonIgnore != null) {
return gsonIgnore.ignore();
}
return false;
}
@Override
public boolean shouldSkipClass(Class<?> clazz) {
return false;
}
});
// 需要将对象的接口和实现都添加到类型映射中
builder.registerTypeAdapter(Dimension.class, new DimensionDeserialize());
builder.registerTypeAdapter(Level.class, new LevelDeserialize());
builder.registerTypeAdapter(Cube.class, new CubeDeserialize());
builder.registerTypeAdapter(Measure.class, new MeasureDeserialize());
builder.registerTypeAdapter(MetaCondition.class, new MetaConditionDeserialize());
builder.registerTypeAdapter(DataSourceInfo.class, new DataSourceInfoDeserialize());
builder.registerTypeAdapter(Dimension.class, new DimensionSerialize());
builder.registerTypeAdapter(Level.class, new LevelSerialize());
builder.registerTypeAdapter(Cube.class, new CubeSerialize());
builder.registerTypeAdapter(Schema.class, new SchemaSerialize());
builder.registerTypeAdapter(DataSourceInfo.class, new DataSourceInfoSerialize());
builder.registerTypeAdapter(Measure.class, new MeasureSerialize());
builder.registerTypeAdapter(MetaCondition.class, new MetaConditionSerialize());
builder.registerTypeAdapter(Schema.class, new SchemaDeserialize());
GSON = builder.create();
}
}
| {
"content_hash": "897dd3c91e4637f081aa8ec89ec5ea99",
"timestamp": "",
"source": "github",
"line_count": 82,
"max_line_length": 91,
"avg_line_length": 46,
"alnum_prop": 0.7309119830328739,
"repo_name": "gspandy/bi-platform",
"id": "b3beca7560c8934ffb77f53c3d8637832c9e72d9",
"size": "4506",
"binary": false,
"copies": "4",
"ref": "refs/heads/branch_1.7.0",
"path": "model/src/main/java/com/baidu/rigel/biplatform/ac/util/AnswerCoreConstant.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "923847"
},
{
"name": "HTML",
"bytes": "259523"
},
{
"name": "Java",
"bytes": "4573818"
},
{
"name": "JavaScript",
"bytes": "15825258"
},
{
"name": "Shell",
"bytes": "3420"
}
],
"symlink_target": ""
} |
package com.sqap.api.domain.audio.test.base;
public interface TestGroupEntityFactory {
TestGroupEntity create(TestGroupDto testGroupDto);
}
| {
"content_hash": "115eb82d43c88af5ddac8f8123f8074a",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 54,
"avg_line_length": 21,
"alnum_prop": 0.8027210884353742,
"repo_name": "MarcinMilewski/sqap",
"id": "ec262e6f946aef7b88e2a21c5cb453cd15945335",
"size": "147",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "sqap-api/src/main/java/com/sqap/api/domain/audio/test/base/TestGroupEntityFactory.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "73"
},
{
"name": "CSS",
"bytes": "4400"
},
{
"name": "Groovy",
"bytes": "12852"
},
{
"name": "HTML",
"bytes": "87909"
},
{
"name": "Java",
"bytes": "167325"
},
{
"name": "JavaScript",
"bytes": "83811"
},
{
"name": "PLpgSQL",
"bytes": "328"
},
{
"name": "Python",
"bytes": "3282"
},
{
"name": "Shell",
"bytes": "66"
},
{
"name": "TypeScript",
"bytes": "140323"
}
],
"symlink_target": ""
} |
package cz.tomkren.kutil2.kobjects;
import cz.tomkren.kutil2.core.KAtts;
import cz.tomkren.kutil2.core.KObject;
import cz.tomkren.kutil2.core.Kutil;
import cz.tomkren.kutil2.items.Int2D;
import cz.tomkren.kutil2.items.KItem;
import cz.tomkren.kutil2.kobjects.frame.Frame;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
/**
* Objekt virtuálního světa fungující jako součást GUI - tlačítko.
* Po kliknutí na tlačítko se provede specifikovaná akce.
* @author Tomáš Křen
*/
public class Button extends KObject {
private KItem<String> title;
private KItem<String> cmd;
private Int2D size;
private static final Font idFont = new Font( Font.SANS_SERIF , Font.PLAIN , 10 );
private static final Font buttonFont = new Font( Font.MONOSPACED , Font.PLAIN , 12 );
private static final Color bgColor = Color.white;
private static final Color textColor = Color.blue;
private static final Color textSelColor = new Color(85,26,139);
/**
* Vytvoří Button podle KAtts.
* Přidává položky title - nápis na tlačítku
* a cmd - příkaz, který se provede.
*/
public Button(KAtts kAtts, Kutil kutil){
super(kAtts, kutil);
setType("button");
title = items().addString( kAtts, "title", "" );
cmd = items().addString( kAtts, "cmd" , "" );
size = new Int2D( title.get().length()*7 + 16 , 20 );
setMovable(false);
setIsGuiStuff(true);
}
@Override
public void drawOutside(Graphics2D g , Int2D center , int frameDepth, double zoom, Int2D zoomCenter) {
Int2D drawPos = center.plus( pos() );
g.setColor( bgColor );
g.fillRect( drawPos.getX(), drawPos.getY() , size.getX() , size.getY() );
if( rucksack().showInfo() ){
g.setFont(idFont);
g.drawString( id() , drawPos.getX() , drawPos.getY()-3 );
}
if( isHighlighted() ){
g.setColor( Color.red );
g.drawRect( drawPos.getX(), drawPos.getY() , size.getX() , size.getY() );
g.setColor( textSelColor );
}
else{
g.setColor( textColor );
}
g.setFont(buttonFont);
g.drawString( title.get() , drawPos.getX()+8 , drawPos.getY()+12 );
g.drawLine( drawPos.getX()+8 , drawPos.getY()+15 , drawPos.getX()+size.getX()-10 , drawPos.getY()+15 );
}
@Override
public boolean isHit( Int2D clickPos , double zoom, Int2D center){
return Int2D.rectangleHit(clickPos, pos(), size.getX(), size.getY()) ;
}
@Override
public void click(Int2D clickPos) {
super.click(clickPos);
rucksack().cmd(cmd.get());
}
@Override
public void drag(Int2D clickPos, Int2D delta , Frame f) {
super.drag(clickPos, delta , f);
rucksack().cmd(cmd.get());
}
}
| {
"content_hash": "4f35116caa534c3057b95bc48ed3f705",
"timestamp": "",
"source": "github",
"line_count": 106,
"max_line_length": 111,
"avg_line_length": 27.18867924528302,
"alnum_prop": 0.6131158917418459,
"repo_name": "tomkren/pikater",
"id": "798fad1ca8b0bd481b73f414ce9f78f4693d3e8a",
"size": "2910",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/cz/tomkren/kutil2/kobjects/Button.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "2720"
},
{
"name": "CLIPS",
"bytes": "8093"
},
{
"name": "CSS",
"bytes": "17962"
},
{
"name": "HTML",
"bytes": "14268583"
},
{
"name": "Haskell",
"bytes": "1632"
},
{
"name": "Java",
"bytes": "17530800"
},
{
"name": "Makefile",
"bytes": "3240"
},
{
"name": "Shell",
"bytes": "1665"
}
],
"symlink_target": ""
} |
package eu.lunisolar.magma.func.supplier;
import eu.lunisolar.magma.func.*; // NOSONAR
import javax.annotation.Nonnull; // NOSONAR
import javax.annotation.Nullable; // NOSONAR
import java.util.Objects;// NOSONAR
import eu.lunisolar.magma.basics.meta.*; // NOSONAR
import eu.lunisolar.magma.basics.meta.functional.*; // NOSONAR
import eu.lunisolar.magma.basics.meta.functional.type.*; // NOSONAR
import eu.lunisolar.magma.basics.meta.functional.domain.*; // NOSONAR
import eu.lunisolar.magma.func.action.*; // NOSONAR
import eu.lunisolar.magma.func.consumer.*; // NOSONAR
import eu.lunisolar.magma.func.consumer.primitives.*; // NOSONAR
import eu.lunisolar.magma.func.consumer.primitives.bi.*; // NOSONAR
import eu.lunisolar.magma.func.consumer.primitives.obj.*; // NOSONAR
import eu.lunisolar.magma.func.consumer.primitives.tri.*; // NOSONAR
import eu.lunisolar.magma.func.function.*; // NOSONAR
import eu.lunisolar.magma.func.function.conversion.*; // NOSONAR
import eu.lunisolar.magma.func.function.from.*; // NOSONAR
import eu.lunisolar.magma.func.function.to.*; // NOSONAR
import eu.lunisolar.magma.func.operator.binary.*; // NOSONAR
import eu.lunisolar.magma.func.operator.ternary.*; // NOSONAR
import eu.lunisolar.magma.func.operator.unary.*; // NOSONAR
import eu.lunisolar.magma.func.predicate.*; // NOSONAR
import eu.lunisolar.magma.func.supplier.*; // NOSONAR
import org.testng.Assert;
import org.testng.annotations.*; //NOSONAR
import java.util.regex.Pattern; //NOSONAR
import java.text.ParseException; //NOSONAR
import eu.lunisolar.magma.basics.*; //NOSONAR
import eu.lunisolar.magma.basics.exceptions.*; //NOSONAR
import java.util.concurrent.atomic.AtomicInteger; //NOSONAR
import eu.lunisolar.magma.func.tuple.*; // NOSONAR
import java.util.function.*; // NOSONAR
/** The test obviously concentrate on the interface methods the function it self is very simple. */
public class LSrtSupplierTest {
private static final String ORIGINAL_MESSAGE = "Original message";
private static final String EXCEPTION_WAS_WRAPPED = "Exception was wrapped.";
private static final String NO_EXCEPTION_WERE_THROWN = "No exception were thrown.";
private short testValue = (short)100;
private LSrtSupplier sut = new LSrtSupplier(){
public short getAsSrtX() {
return testValue;
}
};
private LSrtSupplier sutAlwaysThrowing = LSrtSupplier.srtSup(() -> {
throw new ParseException(ORIGINAL_MESSAGE, 0);
});
private LSrtSupplier sutAlwaysThrowingUnchecked = LSrtSupplier.srtSup(() -> {
throw new IndexOutOfBoundsException(ORIGINAL_MESSAGE);
});
@Test
public void testTheResult() throws Throwable {
Assert.assertEquals(sut.getAsSrt(), testValue);
}
@Test
public void testTupleCall() throws Throwable {
LTuple.Void domainObject = Tuple4U.tuple();
Object result = sut.tupleGetAsSrt(domainObject);
Assert.assertEquals(result, testValue);
}
@Test
public void testNonNullGetAsSrt() throws Throwable {
Assert.assertEquals(sut.nonNullGetAsSrt(), testValue);
}
@Test
public void testNestingGetAsSrtUnchecked() throws Throwable {
// then
try {
sutAlwaysThrowingUnchecked.nestingGetAsSrt();
Assert.fail(NO_EXCEPTION_WERE_THROWN);
} catch (Exception e) {
Assert.assertEquals(e.getClass(), IndexOutOfBoundsException.class);
Assert.assertNull(e.getCause());
Assert.assertEquals(e.getMessage(), ORIGINAL_MESSAGE);
}
}
@Test
public void testShovingGetAsSrtUnchecked() throws Throwable {
// then
try {
sutAlwaysThrowingUnchecked.shovingGetAsSrt();
Assert.fail(NO_EXCEPTION_WERE_THROWN);
} catch (Exception e) {
Assert.assertEquals(e.getClass(), IndexOutOfBoundsException.class);
Assert.assertNull(e.getCause());
Assert.assertEquals(e.getMessage(), ORIGINAL_MESSAGE);
}
}
@Test
public void testFunctionalInterfaceDescription() throws Throwable {
Assert.assertEquals(sut.functionalInterfaceDescription(), "LSrtSupplier: short getAsSrt()");
}
@Test
public void testSrtSupMethod() throws Throwable {
Assert.assertTrue(LSrtSupplier.srtSup(() -> testValue ) instanceof LSrtSupplier);
}
// <editor-fold desc="then (functional)">
@Test
public void testToSup0() throws Throwable {
final ThreadLocal<Boolean> mainFunctionCalled = ThreadLocal.withInitial(()-> false);
final ThreadLocal<Boolean> thenFunctionCalled = ThreadLocal.withInitial(()-> false);
//given (+ some assertions)
LSrtSupplier sutO = () -> {
mainFunctionCalled.set(true);
return (short)90;
};
LSrtFunction<Integer> thenFunction = p -> {
thenFunctionCalled.set(true);
// short
Assert.assertEquals(p, (Object) (short)90);
// Integer
return 100;
};
//when
LSupplier<Integer> function = sutO.toSup(thenFunction);
Integer finalValue = function.get();
//then - finals
Assert.assertEquals(finalValue, (Object) 100);
Assert.assertTrue(mainFunctionCalled.get());
Assert.assertTrue(thenFunctionCalled.get());
}
@Test
public void testToByteSup1() throws Throwable {
final ThreadLocal<Boolean> mainFunctionCalled = ThreadLocal.withInitial(()-> false);
final ThreadLocal<Boolean> thenFunctionCalled = ThreadLocal.withInitial(()-> false);
//given (+ some assertions)
LSrtSupplier sutO = () -> {
mainFunctionCalled.set(true);
return (short)90;
};
LSrtToByteFunction thenFunction = p -> {
thenFunctionCalled.set(true);
// short
Assert.assertEquals(p, (Object) (short)90);
// byte
return (byte)100;
};
//when
LByteSupplier function = sutO.toByteSup(thenFunction);
byte finalValue = function.getAsByte();
//then - finals
Assert.assertEquals(finalValue, (Object) (byte)100);
Assert.assertTrue(mainFunctionCalled.get());
Assert.assertTrue(thenFunctionCalled.get());
}
@Test
public void testToSrtSup2() throws Throwable {
final ThreadLocal<Boolean> mainFunctionCalled = ThreadLocal.withInitial(()-> false);
final ThreadLocal<Boolean> thenFunctionCalled = ThreadLocal.withInitial(()-> false);
//given (+ some assertions)
LSrtSupplier sutO = () -> {
mainFunctionCalled.set(true);
return (short)90;
};
LSrtUnaryOperator thenFunction = p -> {
thenFunctionCalled.set(true);
// short
Assert.assertEquals(p, (Object) (short)90);
// short
return (short)100;
};
//when
LSrtSupplier function = sutO.toSrtSup(thenFunction);
short finalValue = function.getAsSrt();
//then - finals
Assert.assertEquals(finalValue, (Object) (short)100);
Assert.assertTrue(mainFunctionCalled.get());
Assert.assertTrue(thenFunctionCalled.get());
}
@Test
public void testToIntSup3() throws Throwable {
final ThreadLocal<Boolean> mainFunctionCalled = ThreadLocal.withInitial(()-> false);
final ThreadLocal<Boolean> thenFunctionCalled = ThreadLocal.withInitial(()-> false);
//given (+ some assertions)
LSrtSupplier sutO = () -> {
mainFunctionCalled.set(true);
return (short)90;
};
LSrtToIntFunction thenFunction = p -> {
thenFunctionCalled.set(true);
// short
Assert.assertEquals(p, (Object) (short)90);
// int
return 100;
};
//when
LIntSupplier function = sutO.toIntSup(thenFunction);
int finalValue = function.getAsInt();
//then - finals
Assert.assertEquals(finalValue, (Object) 100);
Assert.assertTrue(mainFunctionCalled.get());
Assert.assertTrue(thenFunctionCalled.get());
}
@Test
public void testToLongSup4() throws Throwable {
final ThreadLocal<Boolean> mainFunctionCalled = ThreadLocal.withInitial(()-> false);
final ThreadLocal<Boolean> thenFunctionCalled = ThreadLocal.withInitial(()-> false);
//given (+ some assertions)
LSrtSupplier sutO = () -> {
mainFunctionCalled.set(true);
return (short)90;
};
LSrtToLongFunction thenFunction = p -> {
thenFunctionCalled.set(true);
// short
Assert.assertEquals(p, (Object) (short)90);
// long
return 100L;
};
//when
LLongSupplier function = sutO.toLongSup(thenFunction);
long finalValue = function.getAsLong();
//then - finals
Assert.assertEquals(finalValue, (Object) 100L);
Assert.assertTrue(mainFunctionCalled.get());
Assert.assertTrue(thenFunctionCalled.get());
}
@Test
public void testToFltSup5() throws Throwable {
final ThreadLocal<Boolean> mainFunctionCalled = ThreadLocal.withInitial(()-> false);
final ThreadLocal<Boolean> thenFunctionCalled = ThreadLocal.withInitial(()-> false);
//given (+ some assertions)
LSrtSupplier sutO = () -> {
mainFunctionCalled.set(true);
return (short)90;
};
LSrtToFltFunction thenFunction = p -> {
thenFunctionCalled.set(true);
// short
Assert.assertEquals(p, (Object) (short)90);
// float
return 100f;
};
//when
LFltSupplier function = sutO.toFltSup(thenFunction);
float finalValue = function.getAsFlt();
//then - finals
Assert.assertEquals(finalValue, (Object) 100f);
Assert.assertTrue(mainFunctionCalled.get());
Assert.assertTrue(thenFunctionCalled.get());
}
@Test
public void testToDblSup6() throws Throwable {
final ThreadLocal<Boolean> mainFunctionCalled = ThreadLocal.withInitial(()-> false);
final ThreadLocal<Boolean> thenFunctionCalled = ThreadLocal.withInitial(()-> false);
//given (+ some assertions)
LSrtSupplier sutO = () -> {
mainFunctionCalled.set(true);
return (short)90;
};
LSrtToDblFunction thenFunction = p -> {
thenFunctionCalled.set(true);
// short
Assert.assertEquals(p, (Object) (short)90);
// double
return 100d;
};
//when
LDblSupplier function = sutO.toDblSup(thenFunction);
double finalValue = function.getAsDbl();
//then - finals
Assert.assertEquals(finalValue, (Object) 100d);
Assert.assertTrue(mainFunctionCalled.get());
Assert.assertTrue(thenFunctionCalled.get());
}
@Test
public void testToCharSup7() throws Throwable {
final ThreadLocal<Boolean> mainFunctionCalled = ThreadLocal.withInitial(()-> false);
final ThreadLocal<Boolean> thenFunctionCalled = ThreadLocal.withInitial(()-> false);
//given (+ some assertions)
LSrtSupplier sutO = () -> {
mainFunctionCalled.set(true);
return (short)90;
};
LSrtToCharFunction thenFunction = p -> {
thenFunctionCalled.set(true);
// short
Assert.assertEquals(p, (Object) (short)90);
// char
return '\u0100';
};
//when
LCharSupplier function = sutO.toCharSup(thenFunction);
char finalValue = function.getAsChar();
//then - finals
Assert.assertEquals(finalValue, (Object) '\u0100');
Assert.assertTrue(mainFunctionCalled.get());
Assert.assertTrue(thenFunctionCalled.get());
}
@Test
public void testToBoolSup8() throws Throwable {
final ThreadLocal<Boolean> mainFunctionCalled = ThreadLocal.withInitial(()-> false);
final ThreadLocal<Boolean> thenFunctionCalled = ThreadLocal.withInitial(()-> false);
//given (+ some assertions)
LSrtSupplier sutO = () -> {
mainFunctionCalled.set(true);
return (short)90;
};
LSrtPredicate thenFunction = p -> {
thenFunctionCalled.set(true);
// short
Assert.assertEquals(p, (Object) (short)90);
// boolean
return true;
};
//when
LBoolSupplier function = sutO.toBoolSup(thenFunction);
boolean finalValue = function.getAsBool();
//then - finals
Assert.assertEquals(finalValue, (Object) true);
Assert.assertTrue(mainFunctionCalled.get());
Assert.assertTrue(thenFunctionCalled.get());
}
// </editor-fold>
@Test(expectedExceptions = RuntimeException.class)
public void testShove() {
// given
LSrtSupplier sutThrowing = LSrtSupplier.srtSup(() -> {
throw new UnsupportedOperationException();
});
// when
sutThrowing.shovingGetAsSrt();
}
@Test
public void testToString() throws Throwable {
Assert.assertTrue(sut.toString().startsWith(this.getClass().getName()+"$"));
Assert.assertTrue(String.format("%s", sut).contains("LSrtSupplier: short getAsSrt()"));
}
@Test
public void isThrowing() {
Assert.assertFalse(sut.isThrowing());
}
}
| {
"content_hash": "813bb3236d2719b2ac4741e9fc4e8a42",
"timestamp": "",
"source": "github",
"line_count": 465,
"max_line_length": 100,
"avg_line_length": 30.150537634408604,
"alnum_prop": 0.6116262482168331,
"repo_name": "lunisolar/magma",
"id": "10210ef2e052e322b0363bff518c63fa81c1a770",
"size": "14691",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "magma-func/src/test/java/eu/lunisolar/magma/func/supplier/LSrtSupplierTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "23031222"
}
],
"symlink_target": ""
} |
/*
Copyright 2015 Dean Camera (dean [at] fourwalledcubicle [dot] com)
Permission to use, copy, modify, distribute, and sell this
software and its documentation for any purpose is hereby granted
without fee, provided that the above copyright notice appear in
all copies and that both that the copyright notice and this
permission notice and warranty disclaimer appear in supporting
documentation, and that the name of the author not be used in
advertising or publicity pertaining to distribution of the
software without specific, written prior permission.
The author disclaims all warranties with regard to this
software, including all implied warranties of merchantability
and fitness. In no event shall the author be liable for any
special, indirect or consequential damages or any damages
whatsoever resulting from loss of use, data or profits, whether
in an action of contract, negligence or other tortious action,
arising out of or in connection with the use or performance of
this software.
*/
/** \file
* \brief LUFA Custom Board Hardware Information Driver (Template)
*
* This is a stub driver header file, for implementing custom board
* layout hardware with compatible LUFA board specific drivers. If
* the library is configured to use the BOARD_USER board mode, this
* driver file should be completed and copied into the "/Board/" folder
* inside the application's folder.
*
* This stub is for the board-specific component of the LUFA Board Hardware
* information driver.
*/
#ifndef __BOARD_USER_H__
#define __BOARD_USER_H__
/* Includes: */
// TODO: Add any required includes here
/* Enable C linkage for C++ Compilers: */
#if defined(__cplusplus)
extern "C" {
#endif
/* Preprocessor Checks: */
#if !defined(__INCLUDE_FROM_BOARD_H)
#error Do not include this file directly. Include LUFA/Drivers/Board/Board.h instead.
#endif
/* Public Interface - May be used in end-application: */
/* Macros: */
/** Indicates the board has hardware Buttons mounted if defined. */
// #define BOARD_HAS_BUTTONS
/** Indicates the board has a hardware Dataflash mounted if defined. */
// #define BOARD_HAS_DATAFLASH
/** Indicates the board has a hardware Joystick mounted if defined. */
// #define BOARD_HAS_JOYSTICK
/** Indicates the board has hardware LEDs mounted if defined. */
// #define BOARD_HAS_LEDS
/* Disable C linkage for C++ Compilers: */
#if defined(__cplusplus)
}
#endif
#endif
/** @} */
| {
"content_hash": "a5f219c16454466e37e0819a50b72000",
"timestamp": "",
"source": "github",
"line_count": 76,
"max_line_length": 88,
"avg_line_length": 33.078947368421055,
"alnum_prop": 0.7275258552108194,
"repo_name": "patosai/ex2",
"id": "e064fff573b8fd6ae482de5b7b9c12f620e9c8e1",
"size": "2652",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "LUFA/CodeTemplates/DriverStubs/Board.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "3064"
},
{
"name": "C",
"bytes": "1422940"
},
{
"name": "C++",
"bytes": "977898"
},
{
"name": "CSS",
"bytes": "2461"
},
{
"name": "HTML",
"bytes": "1661"
},
{
"name": "Makefile",
"bytes": "66831"
},
{
"name": "Objective-C",
"bytes": "16838"
},
{
"name": "Python",
"bytes": "884"
},
{
"name": "XSLT",
"bytes": "54346"
}
],
"symlink_target": ""
} |
function MemoryCache() {
this.cache = {}
this.size = 0
}
MemoryCache.prototype.add = function(key, value, time, timeoutCallback) {
var old = this.cache[key]
var instance = this
var entry = {
value: value,
expire: time + Date.now(),
timeout: setTimeout(function() {
instance.delete(key)
return timeoutCallback && typeof timeoutCallback === 'function' && timeoutCallback(value, key)
}, time)
}
this.cache[key] = entry
this.size = Object.keys(this.cache).length
return entry
}
MemoryCache.prototype.delete = function(key) {
var entry = this.cache[key]
if (entry) {
clearTimeout(entry.timeout)
}
delete this.cache[key]
this.size = Object.keys(this.cache).length
return null
}
MemoryCache.prototype.get = function(key) {
var entry = this.cache[key]
return entry
}
MemoryCache.prototype.getValue = function(key) {
var entry = this.get(key)
return entry && entry.value
}
MemoryCache.prototype.clear = function() {
Object.keys(this.cache).forEach(function(key) {
this.delete(key)
}, this)
return true
}
module.exports = MemoryCache
| {
"content_hash": "a50220db2dfff1ad661d4ead81f036a5",
"timestamp": "",
"source": "github",
"line_count": 59,
"max_line_length": 100,
"avg_line_length": 18.983050847457626,
"alnum_prop": 0.675,
"repo_name": "wfrank2509/apicache",
"id": "464b6446fee770f6b6367b2c2d3c935755223c2a",
"size": "1120",
"binary": false,
"copies": "2",
"ref": "refs/heads/short-term-cache",
"path": "src/memory-cache.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "52238"
}
],
"symlink_target": ""
} |
Elasticsearch Query and ActiveRecord for Yii 2
==============================================
This extension provides the [elasticsearch](http://www.elasticsearch.org/) integration for the Yii2 framework.
It includes basic querying/search support and also implements the `ActiveRecord` pattern that allows you to store active
records in elasticsearch.
To use this extension, you have to configure the Connection class in your application configuration:
```php
return [
//....
'components' => [
'elasticsearch' => [
'class' => 'yii\elasticsearch\Connection',
'nodes' => [
['http_address' => '127.0.0.1:9200'],
// configure more hosts if you have a cluster
],
],
]
];
```
Installation
------------
The preferred way to install this extension is through [composer](http://getcomposer.org/download/).
Either run
```
php composer.phar require --prefer-dist yiisoft/yii2-elasticsearch "*"
```
or add
```json
"yiisoft/yii2-elasticsearch": "*"
```
to the require section of your composer.json.
Using the Query
---------------
TBD
> **NOTE:** elasticsearch limits the number of records returned by any query to 10 records by default.
> If you expect to get more records you should specify limit explicitly in relation definition.
Using the ActiveRecord
----------------------
For general information on how to use yii's ActiveRecord please refer to the [guide](https://github.com/yiisoft/yii2/blob/master/docs/guide/active-record.md).
For defining an elasticsearch ActiveRecord class your record class needs to extend from [[yii\elasticsearch\ActiveRecord]] and
implement at least the [[yii\elasticsearch\ActiveRecord::attributes()|attributes()]] method to define the attributes of the record.
The handling of primary keys is different in elasticsearch as the primary key (the `_id` field in elasticsearch terms)
is not part of the attributes by default. However it is possible to define a [path mapping](http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/mapping-id-field.html)
for the `_id` field to be part of the attributes.
See [elasticsearch docs](http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/mapping-id-field.html) on how to define it.
The `_id` field of a document/record can be accessed using [[yii\elasticsearch\ActiveRecord::getPrimaryKey()|getPrimaryKey()]] and
[[yii\elasticsearch\ActiveRecord::setPrimaryKey()|setPrimaryKey()]].
When path mapping is defined, the attribute name can be defined using the [[yii\elasticsearch\ActiveRecord::primaryKey()|primaryKey()]] method.
The following is an example model called `Customer`:
```php
class Customer extends \yii\elasticsearch\ActiveRecord
{
/**
* @return array the list of attributes for this record
*/
public function attributes()
{
// path mapping for '_id' is setup to field 'id'
return ['id', 'name', 'address', 'registration_date'];
}
/**
* @return ActiveQuery defines a relation to the Order record (can be in other database, e.g. redis or sql)
*/
public function getOrders()
{
return $this->hasMany(Order::className(), ['customer_id' => 'id'])->orderBy('id');
}
/**
* Defines a scope that modifies the `$query` to return only active(status = 1) customers
*/
public static function active($query)
{
$query->andWhere(['status' => 1]);
}
}
```
You may override [[yii\elasticsearch\ActiveRecord::index()|index()]] and [[yii\elasticsearch\ActiveRecord::type()|type()]]
to define the index and type this record represents.
The general usage of elasticsearch ActiveRecord is very similar to the database ActiveRecord as described in the
[guide](https://github.com/yiisoft/yii2/blob/master/docs/guide/active-record.md).
It supports the same interface and features except the following limitations and additions(*!*):
- As elasticsearch does not support SQL, the query API does not support `join()`, `groupBy()`, `having()` and `union()`.
Sorting, limit, offset and conditional where are all supported.
- [[yii\elasticsearch\ActiveQuery::from()|from()]] does not select the tables, but the
[index](http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/glossary.html#glossary-index)
and [type](http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/glossary.html#glossary-type) to query against.
- `select()` has been replaced with [[yii\elasticsearch\ActiveQuery::fields()|fields()]] which basically does the same but
`fields` is more elasticsearch terminology.
It defines the fields to retrieve from a document.
- [[yii\elasticsearch\ActiveQuery::via()|via]]-relations can not be defined via a table as there are no tables in elasticsearch. You can only define relations via other records.
- As elasticsearch is not only a data storage but also a search engine there is of course support added for searching your records.
There are
[[yii\elasticsearch\ActiveQuery::query()|query()]],
[[yii\elasticsearch\ActiveQuery::filter()|filter()]] and
[[yii\elasticsearch\ActiveQuery::addFacet()|addFacet()]] methods that allows to compose an elasticsearch query.
See the usage example below on how they work and check out the [Query DSL](http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl.html)
on how to compose `query` and `filter` parts.
- It is also possible to define relations from elasticsearch ActiveRecords to normal ActiveRecord classes and vice versa.
> **NOTE:** elasticsearch limits the number of records returned by any query to 10 records by default.
> If you expect to get more records you should specify limit explicitly in query **and also** relation definition.
> This is also important for relations that use via() so that if via records are limited to 10
> the relations records can also not be more than 10.
Usage example:
```php
$customer = new Customer();
$customer->primaryKey = 1; // in this case equivalent to $customer->id = 1;
$customer->attributes = ['name' => 'test'];
$customer->save();
$customer = Customer::get(1); // get a record by pk
$customers = Customer::mget([1,2,3]); // get multiple records by pk
$customer = Customer::find()->where(['name' => 'test'])->one(); // find by query
$customers = Customer::find()->active()->all(); // find all by query (using the `active` scope)
// http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-field-query.html
$result = Article::find()->query(["field" => ["title" => "yii"]])->all(); // articles whose title contains "yii"
// http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-flt-query.html
$query = Article::find()->query([
"fuzzy_like_this" => [
"fields" => ["title", "description"],
"like_text" => "This query will return articles that are similar to this text :-)",
"max_query_terms" : 12
]
]);
$query->all(); // gives you all the documents
// you can add facets to your search:
$query->addStatisticalFacet('click_stats', ['field' => 'visit_count']);
$query->search(); // gives you all the records + stats about the visit_count field. e.g. mean, sum, min, max etc...
```
And there is so much more in it. "it’s endless what you can build"[¹](http://www.elasticsearch.org/)
Using the elasticsearch DebugPanel
----------------------------------
The yii2 elasticsearch extensions provides a `DebugPanel` that can be integrated with the yii debug module
and shows the executed elasticsearch queries. It also allows to run these queries
and view the results.
Add the following to you application config to enable it (if you already have the debug module
enabled, it is sufficient to just add the panels configuration):
```php
// ...
'bootstrap' => ['debug'],
'modules' => [
'debug' => [
'class' => 'yii\\debug\\Module',
'panels' => [
'elasticsearch' => [
'class' => 'yii\\elasticsearch\\DebugPanel',
],
],
],
],
// ...
```

Relation definitions with records whose primary keys are not part of attributes
-------------------------------------------------------------------------------
TODO
Patterns
--------
### Fetching records from different indexes/types
TODO
| {
"content_hash": "ea167e9e6460f07bc79ba7a33313978c",
"timestamp": "",
"source": "github",
"line_count": 207,
"max_line_length": 184,
"avg_line_length": 40.130434782608695,
"alnum_prop": 0.6990489948236427,
"repo_name": "PHPBH/Yii2",
"id": "e952f0aba71f3832dd9b1760db3feac53e18ed1a",
"size": "8310",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "extensions/elasticsearch/README.md",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "49500"
},
{
"name": "JavaScript",
"bytes": "139658"
},
{
"name": "PHP",
"bytes": "4781788"
},
{
"name": "Perl",
"bytes": "4280"
},
{
"name": "Ruby",
"bytes": "207"
},
{
"name": "Shell",
"bytes": "11326"
}
],
"symlink_target": ""
} |
package event
import (
"fmt"
"mime"
"time"
)
// GetSpecVersion implements EventContextReader.GetSpecVersion
func (ec EventContextV03) GetSpecVersion() string {
return CloudEventsVersionV03
}
// GetDataContentType implements EventContextReader.GetDataContentType
func (ec EventContextV03) GetDataContentType() string {
if ec.DataContentType != nil {
return *ec.DataContentType
}
return ""
}
// GetDataMediaType implements EventContextReader.GetDataMediaType
func (ec EventContextV03) GetDataMediaType() (string, error) {
if ec.DataContentType != nil {
mediaType, _, err := mime.ParseMediaType(*ec.DataContentType)
if err != nil {
return "", err
}
return mediaType, nil
}
return "", nil
}
// GetType implements EventContextReader.GetType
func (ec EventContextV03) GetType() string {
return ec.Type
}
// GetSource implements EventContextReader.GetSource
func (ec EventContextV03) GetSource() string {
return ec.Source.String()
}
// GetSubject implements EventContextReader.GetSubject
func (ec EventContextV03) GetSubject() string {
if ec.Subject != nil {
return *ec.Subject
}
return ""
}
// GetTime implements EventContextReader.GetTime
func (ec EventContextV03) GetTime() time.Time {
if ec.Time != nil {
return ec.Time.Time
}
return time.Time{}
}
// GetID implements EventContextReader.GetID
func (ec EventContextV03) GetID() string {
return ec.ID
}
// GetDataSchema implements EventContextReader.GetDataSchema
func (ec EventContextV03) GetDataSchema() string {
if ec.SchemaURL != nil {
return ec.SchemaURL.String()
}
return ""
}
// DeprecatedGetDataContentEncoding implements EventContextReader.DeprecatedGetDataContentEncoding
func (ec EventContextV03) DeprecatedGetDataContentEncoding() string {
if ec.DataContentEncoding != nil {
return *ec.DataContentEncoding
}
return ""
}
// GetExtensions implements EventContextReader.GetExtensions
func (ec EventContextV03) GetExtensions() map[string]interface{} {
return ec.Extensions
}
// GetExtension implements EventContextReader.GetExtension
func (ec EventContextV03) GetExtension(key string) (interface{}, error) {
v, ok := caseInsensitiveSearch(key, ec.Extensions)
if !ok {
return "", fmt.Errorf("%q not found", key)
}
return v, nil
}
| {
"content_hash": "cb64a99291cea9edbf10caf54e04d803",
"timestamp": "",
"source": "github",
"line_count": 93,
"max_line_length": 98,
"avg_line_length": 24.172043010752688,
"alnum_prop": 0.7580071174377224,
"repo_name": "knative-sandbox/async-component",
"id": "8e6eec5caa373d33ea8a466ee98b1dbf55633473",
"size": "2248",
"binary": false,
"copies": "5",
"ref": "refs/heads/main",
"path": "vendor/github.com/cloudevents/sdk-go/v2/event/eventcontext_v03_reader.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "1002"
},
{
"name": "Go",
"bytes": "51152"
},
{
"name": "Shell",
"bytes": "15621"
}
],
"symlink_target": ""
} |
package org.elasticsearch.common.lucene.search;
import org.apache.lucene.analysis.core.KeywordAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.SortedDocValuesField;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.StringField;
import org.apache.lucene.index.*;
import org.apache.lucene.queries.FilterClause;
import org.apache.lucene.queries.TermFilter;
import org.apache.lucene.search.*;
import org.apache.lucene.store.Directory;
import org.apache.lucene.util.Bits;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.FixedBitSet;
import org.elasticsearch.common.lucene.Lucene;
import org.elasticsearch.test.ElasticsearchLuceneTestCase;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static org.apache.lucene.search.BooleanClause.Occur.*;
import static org.hamcrest.core.IsEqual.equalTo;
/**
*/
public class XBooleanFilterTests extends ElasticsearchLuceneTestCase {
private Directory directory;
private LeafReader reader;
private static final char[] distinctValues = new char[] {'a', 'b', 'c', 'd', 'v','z','y'};
@Before
public void setup() throws Exception {
super.setUp();
char[][] documentMatrix = new char[][] {
{'a', 'b', 'c', 'd', 'v'},
{'a', 'b', 'c', 'd', 'z'},
{'a', 'a', 'a', 'a', 'x'}
};
List<Document> documents = new ArrayList<>(documentMatrix.length);
for (char[] fields : documentMatrix) {
Document document = new Document();
for (int i = 0; i < fields.length; i++) {
document.add(new StringField(Integer.toString(i), String.valueOf(fields[i]), Field.Store.NO));
document.add(new SortedDocValuesField(Integer.toString(i), new BytesRef(String.valueOf(fields[i]))));
}
documents.add(document);
}
directory = newDirectory();
IndexWriter w = new IndexWriter(directory, new IndexWriterConfig(new KeywordAnalyzer()));
w.addDocuments(documents);
w.close();
reader = SlowCompositeReaderWrapper.wrap(DirectoryReader.open(directory));
}
@After
public void tearDown() throws Exception {
reader.close();
directory.close();
super.tearDown();
}
@Test
public void testWithTwoClausesOfEachOccur_allFixedBitDocIdSetFilters() throws Exception {
List<XBooleanFilter> booleanFilters = new ArrayList<>();
booleanFilters.add(createBooleanFilter(
newFilterClause(0, 'a', MUST, false), newFilterClause(1, 'b', MUST, false),
newFilterClause(2, 'c', SHOULD, false), newFilterClause(3, 'd', SHOULD, false),
newFilterClause(4, 'e', MUST_NOT, false), newFilterClause(5, 'f', MUST_NOT, false)
));
booleanFilters.add(createBooleanFilter(
newFilterClause(4, 'e', MUST_NOT, false), newFilterClause(5, 'f', MUST_NOT, false),
newFilterClause(0, 'a', MUST, false), newFilterClause(1, 'b', MUST, false),
newFilterClause(2, 'c', SHOULD, false), newFilterClause(3, 'd', SHOULD, false)
));
booleanFilters.add(createBooleanFilter(
newFilterClause(2, 'c', SHOULD, false), newFilterClause(3, 'd', SHOULD, false),
newFilterClause(4, 'e', MUST_NOT, false), newFilterClause(5, 'f', MUST_NOT, false),
newFilterClause(0, 'a', MUST, false), newFilterClause(1, 'b', MUST, false)
));
for (XBooleanFilter booleanFilter : booleanFilters) {
FixedBitSet result = new FixedBitSet(reader.maxDoc());
result.or(booleanFilter.getDocIdSet(reader.getContext(), reader.getLiveDocs()).iterator());
assertThat(result.cardinality(), equalTo(2));
assertThat(result.get(0), equalTo(true));
assertThat(result.get(1), equalTo(true));
assertThat(result.get(2), equalTo(false));
}
}
@Test
public void testWithTwoClausesOfEachOccur_allBitsBasedFilters() throws Exception {
List<XBooleanFilter> booleanFilters = new ArrayList<>();
booleanFilters.add(createBooleanFilter(
newFilterClause(0, 'a', MUST, true), newFilterClause(1, 'b', MUST, true),
newFilterClause(2, 'c', SHOULD, true), newFilterClause(3, 'd', SHOULD, true),
newFilterClause(4, 'e', MUST_NOT, true), newFilterClause(5, 'f', MUST_NOT, true)
));
booleanFilters.add(createBooleanFilter(
newFilterClause(4, 'e', MUST_NOT, true), newFilterClause(5, 'f', MUST_NOT, true),
newFilterClause(0, 'a', MUST, true), newFilterClause(1, 'b', MUST, true),
newFilterClause(2, 'c', SHOULD, true), newFilterClause(3, 'd', SHOULD, true)
));
booleanFilters.add(createBooleanFilter(
newFilterClause(2, 'c', SHOULD, true), newFilterClause(3, 'd', SHOULD, true),
newFilterClause(4, 'e', MUST_NOT, true), newFilterClause(5, 'f', MUST_NOT, true),
newFilterClause(0, 'a', MUST, true), newFilterClause(1, 'b', MUST, true)
));
for (XBooleanFilter booleanFilter : booleanFilters) {
FixedBitSet result = new FixedBitSet(reader.maxDoc());
result.or(booleanFilter.getDocIdSet(reader.getContext(), reader.getLiveDocs()).iterator());
assertThat(result.cardinality(), equalTo(2));
assertThat(result.get(0), equalTo(true));
assertThat(result.get(1), equalTo(true));
assertThat(result.get(2), equalTo(false));
}
}
@Test
public void testWithTwoClausesOfEachOccur_allFilterTypes() throws Exception {
List<XBooleanFilter> booleanFilters = new ArrayList<>();
booleanFilters.add(createBooleanFilter(
newFilterClause(0, 'a', MUST, true), newFilterClause(1, 'b', MUST, false),
newFilterClause(2, 'c', SHOULD, true), newFilterClause(3, 'd', SHOULD, false),
newFilterClause(4, 'e', MUST_NOT, true), newFilterClause(5, 'f', MUST_NOT, false)
));
booleanFilters.add(createBooleanFilter(
newFilterClause(4, 'e', MUST_NOT, true), newFilterClause(5, 'f', MUST_NOT, false),
newFilterClause(0, 'a', MUST, true), newFilterClause(1, 'b', MUST, false),
newFilterClause(2, 'c', SHOULD, true), newFilterClause(3, 'd', SHOULD, false)
));
booleanFilters.add(createBooleanFilter(
newFilterClause(2, 'c', SHOULD, true), newFilterClause(3, 'd', SHOULD, false),
newFilterClause(4, 'e', MUST_NOT, true), newFilterClause(5, 'f', MUST_NOT, false),
newFilterClause(0, 'a', MUST, true), newFilterClause(1, 'b', MUST, false)
));
for (XBooleanFilter booleanFilter : booleanFilters) {
FixedBitSet result = new FixedBitSet(reader.maxDoc());
result.or(booleanFilter.getDocIdSet(reader.getContext(), reader.getLiveDocs()).iterator());
assertThat(result.cardinality(), equalTo(2));
assertThat(result.get(0), equalTo(true));
assertThat(result.get(1), equalTo(true));
assertThat(result.get(2), equalTo(false));
}
booleanFilters.clear();
booleanFilters.add(createBooleanFilter(
newFilterClause(0, 'a', MUST, false), newFilterClause(1, 'b', MUST, true),
newFilterClause(2, 'c', SHOULD, false), newFilterClause(3, 'd', SHOULD, true),
newFilterClause(4, 'e', MUST_NOT, false), newFilterClause(5, 'f', MUST_NOT, true)
));
booleanFilters.add(createBooleanFilter(
newFilterClause(4, 'e', MUST_NOT, false), newFilterClause(5, 'f', MUST_NOT, true),
newFilterClause(0, 'a', MUST, false), newFilterClause(1, 'b', MUST, true),
newFilterClause(2, 'c', SHOULD, false), newFilterClause(3, 'd', SHOULD, true)
));
booleanFilters.add(createBooleanFilter(
newFilterClause(2, 'c', SHOULD, false), newFilterClause(3, 'd', SHOULD, true),
newFilterClause(4, 'e', MUST_NOT, false), newFilterClause(5, 'f', MUST_NOT, true),
newFilterClause(0, 'a', MUST, false), newFilterClause(1, 'b', MUST, true)
));
for (XBooleanFilter booleanFilter : booleanFilters) {
FixedBitSet result = new FixedBitSet(reader.maxDoc());
result.or(booleanFilter.getDocIdSet(reader.getContext(), reader.getLiveDocs()).iterator());
assertThat(result.cardinality(), equalTo(2));
assertThat(result.get(0), equalTo(true));
assertThat(result.get(1), equalTo(true));
assertThat(result.get(2), equalTo(false));
}
}
@Test
public void testWithTwoClausesOfEachOccur_singleClauseOptimisation() throws Exception {
List<XBooleanFilter> booleanFilters = new ArrayList<>();
booleanFilters.add(createBooleanFilter(
newFilterClause(1, 'b', MUST, true)
));
for (XBooleanFilter booleanFilter : booleanFilters) {
FixedBitSet result = new FixedBitSet(reader.maxDoc());
result.or(booleanFilter.getDocIdSet(reader.getContext(), reader.getLiveDocs()).iterator());
assertThat(result.cardinality(), equalTo(2));
assertThat(result.get(0), equalTo(true));
assertThat(result.get(1), equalTo(true));
assertThat(result.get(2), equalTo(false));
}
booleanFilters.clear();
booleanFilters.add(createBooleanFilter(
newFilterClause(1, 'c', MUST_NOT, true)
));
for (XBooleanFilter booleanFilter : booleanFilters) {
FixedBitSet result = new FixedBitSet(reader.maxDoc());
result.or(booleanFilter.getDocIdSet(reader.getContext(), reader.getLiveDocs()).iterator());
assertThat(result.cardinality(), equalTo(3));
assertThat(result.get(0), equalTo(true));
assertThat(result.get(1), equalTo(true));
assertThat(result.get(2), equalTo(true));
}
booleanFilters.clear();
booleanFilters.add(createBooleanFilter(
newFilterClause(2, 'c', SHOULD, true)
));
for (XBooleanFilter booleanFilter : booleanFilters) {
FixedBitSet result = new FixedBitSet(reader.maxDoc());
result.or(booleanFilter.getDocIdSet(reader.getContext(), reader.getLiveDocs()).iterator());
assertThat(result.cardinality(), equalTo(2));
assertThat(result.get(0), equalTo(true));
assertThat(result.get(1), equalTo(true));
assertThat(result.get(2), equalTo(false));
}
}
@Test
public void testOnlyShouldClauses() throws Exception {
List<XBooleanFilter> booleanFilters = new ArrayList<>();
// 2 slow filters
// This case caused: https://github.com/elasticsearch/elasticsearch/issues/2826
booleanFilters.add(createBooleanFilter(
newFilterClause(1, 'a', SHOULD, true),
newFilterClause(1, 'b', SHOULD, true)
));
// 2 fast filters
booleanFilters.add(createBooleanFilter(
newFilterClause(1, 'a', SHOULD, false),
newFilterClause(1, 'b', SHOULD, false)
));
// 1 fast filters, 1 slow filter
booleanFilters.add(createBooleanFilter(
newFilterClause(1, 'a', SHOULD, true),
newFilterClause(1, 'b', SHOULD, false)
));
for (XBooleanFilter booleanFilter : booleanFilters) {
FixedBitSet result = new FixedBitSet(reader.maxDoc());
result.or(booleanFilter.getDocIdSet(reader.getContext(), reader.getLiveDocs()).iterator());
assertThat(result.cardinality(), equalTo(3));
assertThat(result.get(0), equalTo(true));
assertThat(result.get(1), equalTo(true));
assertThat(result.get(2), equalTo(true));
}
}
@Test
public void testOnlyMustClauses() throws Exception {
List<XBooleanFilter> booleanFilters = new ArrayList<>();
// Slow filters
booleanFilters.add(createBooleanFilter(
newFilterClause(3, 'd', MUST, true),
newFilterClause(3, 'd', MUST, true)
));
// 2 fast filters
booleanFilters.add(createBooleanFilter(
newFilterClause(3, 'd', MUST, false),
newFilterClause(3, 'd', MUST, false)
));
// 1 fast filters, 1 slow filter
booleanFilters.add(createBooleanFilter(
newFilterClause(3, 'd', MUST, true),
newFilterClause(3, 'd', MUST, false)
));
for (XBooleanFilter booleanFilter : booleanFilters) {
FixedBitSet result = new FixedBitSet(reader.maxDoc());
result.or(booleanFilter.getDocIdSet(reader.getContext(), reader.getLiveDocs()).iterator());
assertThat(result.cardinality(), equalTo(2));
assertThat(result.get(0), equalTo(true));
assertThat(result.get(1), equalTo(true));
assertThat(result.get(2), equalTo(false));
}
}
@Test
public void testOnlyMustNotClauses() throws Exception {
List<XBooleanFilter> booleanFilters = new ArrayList<>();
// Slow filters
booleanFilters.add(createBooleanFilter(
newFilterClause(1, 'a', MUST_NOT, true),
newFilterClause(1, 'a', MUST_NOT, true)
));
// 2 fast filters
booleanFilters.add(createBooleanFilter(
newFilterClause(1, 'a', MUST_NOT, false),
newFilterClause(1, 'a', MUST_NOT, false)
));
// 1 fast filters, 1 slow filter
booleanFilters.add(createBooleanFilter(
newFilterClause(1, 'a', MUST_NOT, true),
newFilterClause(1, 'a', MUST_NOT, false)
));
for (XBooleanFilter booleanFilter : booleanFilters) {
FixedBitSet result = new FixedBitSet(reader.maxDoc());
result.or(booleanFilter.getDocIdSet(reader.getContext(), reader.getLiveDocs()).iterator());
assertThat(result.cardinality(), equalTo(2));
assertThat(result.get(0), equalTo(true));
assertThat(result.get(1), equalTo(true));
assertThat(result.get(2), equalTo(false));
}
}
@Test
public void testNonMatchingSlowShouldWithMatchingMust() throws Exception {
XBooleanFilter booleanFilter = createBooleanFilter(
newFilterClause(0, 'a', MUST, false),
newFilterClause(0, 'b', SHOULD, true)
);
DocIdSet docIdSet = booleanFilter.getDocIdSet(reader.getContext(), reader.getLiveDocs());
boolean empty = false;
if (docIdSet == null) {
empty = true;
} else {
DocIdSetIterator it = docIdSet.iterator();
if (it == null || it.nextDoc() == DocIdSetIterator.NO_MORE_DOCS) {
empty = true;
}
}
assertTrue(empty);
}
@Test
public void testSlowShouldClause_atLeastOneShouldMustMatch() throws Exception {
XBooleanFilter booleanFilter = createBooleanFilter(
newFilterClause(0, 'a', MUST, false),
newFilterClause(1, 'a', SHOULD, true)
);
FixedBitSet result = new FixedBitSet(reader.maxDoc());
result.or(booleanFilter.getDocIdSet(reader.getContext(), reader.getLiveDocs()).iterator());
assertThat(result.cardinality(), equalTo(1));
assertThat(result.get(0), equalTo(false));
assertThat(result.get(1), equalTo(false));
assertThat(result.get(2), equalTo(true));
booleanFilter = createBooleanFilter(
newFilterClause(0, 'a', MUST, false),
newFilterClause(1, 'a', SHOULD, true),
newFilterClause(4, 'z', SHOULD, true)
);
result = new FixedBitSet(reader.maxDoc());
result.or(booleanFilter.getDocIdSet(reader.getContext(), reader.getLiveDocs()).iterator());
assertThat(result.cardinality(), equalTo(2));
assertThat(result.get(0), equalTo(false));
assertThat(result.get(1), equalTo(true));
assertThat(result.get(2), equalTo(true));
}
@Test
// See issue: https://github.com/elasticsearch/elasticsearch/issues/4130
public void testOneFastMustNotOneFastShouldAndOneSlowShould() throws Exception {
XBooleanFilter booleanFilter = createBooleanFilter(
newFilterClause(4, 'v', MUST_NOT, false),
newFilterClause(4, 'z', SHOULD, false),
newFilterClause(4, 'x', SHOULD, true)
);
FixedBitSet result = new FixedBitSet(reader.maxDoc());
result.or(booleanFilter.getDocIdSet(reader.getContext(), reader.getLiveDocs()).iterator());
assertThat(result.cardinality(), equalTo(2));
assertThat(result.get(0), equalTo(false));
assertThat(result.get(1), equalTo(true));
assertThat(result.get(2), equalTo(true));
}
@Test
public void testOneFastShouldClauseAndOneSlowShouldClause() throws Exception {
XBooleanFilter booleanFilter = createBooleanFilter(
newFilterClause(4, 'z', SHOULD, false),
newFilterClause(4, 'x', SHOULD, true)
);
FixedBitSet result = new FixedBitSet(reader.maxDoc());
result.or(booleanFilter.getDocIdSet(reader.getContext(), reader.getLiveDocs()).iterator());
assertThat(result.cardinality(), equalTo(2));
assertThat(result.get(0), equalTo(false));
assertThat(result.get(1), equalTo(true));
assertThat(result.get(2), equalTo(true));
}
@Test
public void testOneMustClauseOneFastShouldClauseAndOneSlowShouldClause() throws Exception {
XBooleanFilter booleanFilter = createBooleanFilter(
newFilterClause(0, 'a', MUST, false),
newFilterClause(4, 'z', SHOULD, false),
newFilterClause(4, 'x', SHOULD, true)
);
FixedBitSet result = new FixedBitSet(reader.maxDoc());
result.or(booleanFilter.getDocIdSet(reader.getContext(), reader.getLiveDocs()).iterator());
assertThat(result.cardinality(), equalTo(2));
assertThat(result.get(0), equalTo(false));
assertThat(result.get(1), equalTo(true));
assertThat(result.get(2), equalTo(true));
}
private static FilterClause newFilterClause(int field, char character, BooleanClause.Occur occur, boolean slowerBitsBackedFilter) {
Filter filter;
if (slowerBitsBackedFilter) {
filter = new PrettyPrintFieldCacheTermsFilter(String.valueOf(field), String.valueOf(character));
} else {
Term term = new Term(String.valueOf(field), String.valueOf(character));
filter = new TermFilter(term);
}
return new FilterClause(filter, occur);
}
private static XBooleanFilter createBooleanFilter(FilterClause... clauses) {
XBooleanFilter booleanFilter = new XBooleanFilter();
for (FilterClause clause : clauses) {
booleanFilter.add(clause);
}
return booleanFilter;
}
@Test
public void testRandom() throws IOException {
int iterations = scaledRandomIntBetween(100, 1000); // don't worry that is fast!
for (int iter = 0; iter < iterations; iter++) {
int numClauses = 1 + random().nextInt(10);
FilterClause[] clauses = new FilterClause[numClauses];
BooleanQuery topLevel = new BooleanQuery();
BooleanQuery orQuery = new BooleanQuery();
boolean hasMust = false;
boolean hasShould = false;
boolean hasMustNot = false;
for(int i = 0; i < numClauses; i++) {
int field = random().nextInt(5);
char value = distinctValues[random().nextInt(distinctValues.length)];
switch(random().nextInt(10)) {
case 9:
case 8:
case 7:
case 6:
case 5:
hasMust = true;
if (rarely()) {
clauses[i] = new FilterClause(new EmptyFilter(), MUST);
topLevel.add(new BooleanClause(new MatchNoDocsQuery(), MUST));
} else {
clauses[i] = newFilterClause(field, value, MUST, random().nextBoolean());
topLevel.add(new BooleanClause(new TermQuery(new Term(String.valueOf(field), String.valueOf(value))), MUST));
}
break;
case 4:
case 3:
case 2:
case 1:
hasShould = true;
if (rarely()) {
clauses[i] = new FilterClause(new EmptyFilter(), SHOULD);
orQuery.add(new BooleanClause(new MatchNoDocsQuery(), SHOULD));
} else {
clauses[i] = newFilterClause(field, value, SHOULD, random().nextBoolean());
orQuery.add(new BooleanClause(new TermQuery(new Term(String.valueOf(field), String.valueOf(value))), SHOULD));
}
break;
case 0:
hasMustNot = true;
if (rarely()) {
clauses[i] = new FilterClause(new EmptyFilter(), MUST_NOT);
topLevel.add(new BooleanClause(new MatchNoDocsQuery(), MUST_NOT));
} else {
clauses[i] = newFilterClause(field, value, MUST_NOT, random().nextBoolean());
topLevel.add(new BooleanClause(new TermQuery(new Term(String.valueOf(field), String.valueOf(value))), MUST_NOT));
}
break;
}
}
if (orQuery.getClauses().length > 0) {
topLevel.add(new BooleanClause(orQuery, MUST));
}
if (hasMustNot && !hasMust && !hasShould) { // pure negative
topLevel.add(new BooleanClause(new MatchAllDocsQuery(), MUST));
}
XBooleanFilter booleanFilter = createBooleanFilter(clauses);
FixedBitSet leftResult = new FixedBitSet(reader.maxDoc());
FixedBitSet rightResult = new FixedBitSet(reader.maxDoc());
DocIdSet left = booleanFilter.getDocIdSet(reader.getContext(), reader.getLiveDocs());
DocIdSet right = new QueryWrapperFilter(topLevel).getDocIdSet(reader.getContext(), reader.getLiveDocs());
if (left == null || right == null) {
if (left == null && right != null) {
assertThat(errorMsg(clauses, topLevel), (right.iterator() == null ? DocIdSetIterator.NO_MORE_DOCS : right.iterator().nextDoc()), equalTo(DocIdSetIterator.NO_MORE_DOCS));
}
if (left != null && right == null) {
assertThat(errorMsg(clauses, topLevel), (left.iterator() == null ? DocIdSetIterator.NO_MORE_DOCS : left.iterator().nextDoc()), equalTo(DocIdSetIterator.NO_MORE_DOCS));
}
} else {
DocIdSetIterator leftIter = left.iterator();
DocIdSetIterator rightIter = right.iterator();
if (leftIter != null) {
leftResult.or(leftIter);
}
if (rightIter != null) {
rightResult.or(rightIter);
}
assertThat(leftResult.cardinality(), equalTo(rightResult.cardinality()));
for (int i = 0; i < reader.maxDoc(); i++) {
assertThat(errorMsg(clauses, topLevel) + " -- failed at index " + i, leftResult.get(i), equalTo(rightResult.get(i)));
}
}
}
}
private String errorMsg(FilterClause[] clauses, BooleanQuery query) {
return query.toString() + " vs. " + Arrays.toString(clauses);
}
public static final class PrettyPrintFieldCacheTermsFilter extends DocValuesTermsFilter {
private final String value;
private final String field;
public PrettyPrintFieldCacheTermsFilter(String field, String value) {
super(field, value);
this.field = field;
this.value = value;
}
@Override
public String toString(String field) {
return "SLOW(" + field + ":" + value + ")";
}
}
public final class EmptyFilter extends Filter {
@Override
public DocIdSet getDocIdSet(LeafReaderContext context, Bits acceptDocs) throws IOException {
return random().nextBoolean() ? new Empty() : null;
}
@Override
public String toString(String field) {
return "empty";
}
private class Empty extends DocIdSet {
@Override
public DocIdSetIterator iterator() throws IOException {
return null;
}
@Override
public long ramBytesUsed() {
return 0;
}
}
}
}
| {
"content_hash": "79303ba0420937df15e1be8d67163ded",
"timestamp": "",
"source": "github",
"line_count": 572,
"max_line_length": 189,
"avg_line_length": 44.93531468531469,
"alnum_prop": 0.5893086410146675,
"repo_name": "Asimov4/elasticsearch",
"id": "bc5db66cc03d1fe12169c16a0b9d3e1a49d4f68c",
"size": "26491",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/test/java/org/elasticsearch/common/lucene/search/XBooleanFilterTests.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ApacheConf",
"bytes": "87"
},
{
"name": "Groovy",
"bytes": "299"
},
{
"name": "HTML",
"bytes": "1210"
},
{
"name": "Java",
"bytes": "26459563"
},
{
"name": "Perl",
"bytes": "6858"
},
{
"name": "Python",
"bytes": "64868"
},
{
"name": "Ruby",
"bytes": "17776"
},
{
"name": "Shell",
"bytes": "35009"
},
{
"name": "XML",
"bytes": "6334"
}
],
"symlink_target": ""
} |
package com.alibaba.cobar.server.heartbeat;
import com.alibaba.cobar.net.handler.NIOHandler;
import com.alibaba.cobar.net.packet.EOFPacket;
import com.alibaba.cobar.net.packet.ErrorPacket;
import com.alibaba.cobar.net.packet.HandshakePacket;
import com.alibaba.cobar.net.packet.OkPacket;
import com.alibaba.cobar.net.packet.Reply323Packet;
import com.alibaba.cobar.net.util.CharsetUtil;
import com.alibaba.cobar.net.util.SecurityUtil;
/**
* @author xianmao.hexm
*/
public class MySQLDetectorAuth implements NIOHandler {
private final MySQLDetector detector;
public MySQLDetectorAuth(MySQLDetector detector) {
this.detector = detector;
}
@Override
public void handle(byte[] data) {
MySQLDetector detector = this.detector;
HandshakePacket hsp = detector.getHandshake();
if (hsp == null) {
// 设置握手数据包
hsp = new HandshakePacket();
hsp.read(data);
detector.setHandshake(hsp);
// 设置字符集编码
int charsetIndex = (hsp.serverCharsetIndex & 0xff);
String charset = CharsetUtil.getCharset(charsetIndex);
if (charset != null) {
detector.setCharsetIndex(charsetIndex);
} else {
throw new RuntimeException("Unknown charsetIndex:" + charsetIndex);
}
// 发送认证数据包
detector.authenticate();
} else {
switch (data[4]) {
case OkPacket.FIELD_COUNT:
detector.setHandler(new MySQLDetectorHandler(detector));
detector.setAuthenticated(true);
detector.heartbeat();// 成功后发起心跳。
break;
case ErrorPacket.FIELD_COUNT:
ErrorPacket err = new ErrorPacket();
err.read(data);
throw new RuntimeException(new String(err.message));
case EOFPacket.FIELD_COUNT:
auth323(data[3], hsp.seed);
break;
default:
throw new RuntimeException("Unknown packet");
}
}
}
/**
* 发送323响应认证数据包
*/
private void auth323(byte packetId, byte[] seed) {
Reply323Packet r323 = new Reply323Packet();
r323.packetId = ++packetId;
String pass = detector.getPassword();
if (pass != null && pass.length() > 0) {
r323.seed = SecurityUtil.scramble323(pass, new String(seed)).getBytes();
}
r323.write(detector);
}
}
| {
"content_hash": "c01270f29d7fc9109103592cca11a775",
"timestamp": "",
"source": "github",
"line_count": 77,
"max_line_length": 84,
"avg_line_length": 33.5974025974026,
"alnum_prop": 0.5782759953614225,
"repo_name": "lostdragon/cobar",
"id": "1593800af8e9b50cb041d0c5baadc5f2ca49c1d9",
"size": "3286",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "cobar-server/src/main/java/com/alibaba/cobar/server/heartbeat/MySQLDetectorAuth.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "2827229"
},
{
"name": "Shell",
"bytes": "6817"
}
],
"symlink_target": ""
} |
#include "sk_tool_utils.h"
#include "SampleCode.h"
#include "SkView.h"
#include "SkCanvas.h"
#include "SkPathMeasure.h"
#include "SkRandom.h"
#include "SkRRect.h"
#include "SkColorPriv.h"
#include "SkStrokerPriv.h"
#include "SkSurface.h"
static bool hittest(const SkPoint& target, SkScalar x, SkScalar y) {
const SkScalar TOL = 7;
return SkPoint::Distance(target, SkPoint::Make(x, y)) <= TOL;
}
static int getOnCurvePoints(const SkPath& path, SkPoint storage[]) {
SkPath::RawIter iter(path);
SkPoint pts[4];
SkPath::Verb verb;
int count = 0;
while ((verb = iter.next(pts)) != SkPath::kDone_Verb) {
switch (verb) {
case SkPath::kMove_Verb:
case SkPath::kLine_Verb:
case SkPath::kQuad_Verb:
case SkPath::kConic_Verb:
case SkPath::kCubic_Verb:
storage[count++] = pts[0];
break;
default:
break;
}
}
return count;
}
static void getContourCounts(const SkPath& path, SkTArray<int>* contourCounts) {
SkPath::RawIter iter(path);
SkPoint pts[4];
SkPath::Verb verb;
int count = 0;
while ((verb = iter.next(pts)) != SkPath::kDone_Verb) {
switch (verb) {
case SkPath::kMove_Verb:
case SkPath::kLine_Verb:
count += 1;
break;
case SkPath::kQuad_Verb:
case SkPath::kConic_Verb:
count += 2;
break;
case SkPath::kCubic_Verb:
count += 3;
break;
case SkPath::kClose_Verb:
contourCounts->push_back(count);
count = 0;
break;
default:
break;
}
}
if (count > 0) {
contourCounts->push_back(count);
}
}
static void erase(SkSurface* surface) {
surface->getCanvas()->clear(SK_ColorTRANSPARENT);
}
struct StrokeTypeButton {
SkRect fBounds;
char fLabel;
bool fEnabled;
};
struct CircleTypeButton : public StrokeTypeButton {
bool fFill;
};
class QuadStrokerView : public SampleView {
enum {
SKELETON_COLOR = 0xFF0000FF,
WIREFRAME_COLOR = 0x80FF0000
};
enum {
kCount = 15
};
SkPoint fPts[kCount];
SkRect fWeightControl;
SkRect fErrorControl;
SkRect fWidthControl;
SkRect fBounds;
SkMatrix fMatrix, fInverse;
SkAutoTUnref<SkShader> fShader;
SkAutoTUnref<SkSurface> fMinSurface;
SkAutoTUnref<SkSurface> fMaxSurface;
StrokeTypeButton fCubicButton;
StrokeTypeButton fConicButton;
StrokeTypeButton fQuadButton;
StrokeTypeButton fRRectButton;
CircleTypeButton fCircleButton;
StrokeTypeButton fTextButton;
SkString fText;
SkScalar fTextSize;
SkScalar fWeight;
SkScalar fWidth, fDWidth;
SkScalar fWidthScale;
int fW, fH, fZoom;
bool fAnimate;
bool fDrawRibs;
bool fDrawTangents;
#ifdef SK_DEBUG
#define kStrokerErrorMin 0.001f
#define kStrokerErrorMax 5
#endif
#define kWidthMin 1
#define kWidthMax 100
public:
QuadStrokerView() {
this->setBGColor(SK_ColorLTGRAY);
fPts[0].set(50, 200); // cubic
fPts[1].set(50, 100);
fPts[2].set(150, 50);
fPts[3].set(300, 50);
fPts[4].set(350, 200); // conic
fPts[5].set(350, 100);
fPts[6].set(450, 50);
fPts[7].set(150, 300); // quad
fPts[8].set(150, 200);
fPts[9].set(250, 150);
fPts[10].set(200, 200); // rrect
fPts[11].set(400, 400);
fPts[12].set(250, 250); // oval
fPts[13].set(450, 450);
fText = "a";
fTextSize = 12;
fWidth = 50;
fDWidth = 0.25f;
fWeight = 1;
fCubicButton.fLabel = 'C';
fCubicButton.fEnabled = false;
fConicButton.fLabel = 'K';
fConicButton.fEnabled = true;
fQuadButton.fLabel = 'Q';
fQuadButton.fEnabled = false;
fRRectButton.fLabel = 'R';
fRRectButton.fEnabled = false;
fCircleButton.fLabel = 'O';
fCircleButton.fEnabled = false;
fCircleButton.fFill = false;
fTextButton.fLabel = 'T';
fTextButton.fEnabled = false;
fAnimate = true;
setAsNeeded();
}
protected:
bool onQuery(SkEvent* evt) override {
if (SampleCode::TitleQ(*evt)) {
SampleCode::TitleR(evt, "QuadStroker");
return true;
}
SkUnichar uni;
if (fTextButton.fEnabled && SampleCode::CharQ(*evt, &uni)) {
switch (uni) {
case ' ':
fText = "";
break;
case '-':
fTextSize = SkTMax(1.0f, fTextSize - 1);
break;
case '+':
case '=':
fTextSize += 1;
break;
default:
fText.appendUnichar(uni);
}
this->inval(NULL);
return true;
}
return this->INHERITED::onQuery(evt);
}
void onSizeChange() override {
fWeightControl.setXYWH(this->width() - 150, 30, 30, 400);
fErrorControl.setXYWH(this->width() - 100, 30, 30, 400);
fWidthControl.setXYWH(this->width() - 50, 30, 30, 400);
int buttonOffset = 450;
fCubicButton.fBounds.setXYWH(this->width() - 50, SkIntToScalar(buttonOffset), 30, 30);
buttonOffset += 50;
fConicButton.fBounds.setXYWH(this->width() - 50, SkIntToScalar(buttonOffset), 30, 30);
buttonOffset += 50;
fQuadButton.fBounds.setXYWH(this->width() - 50, SkIntToScalar(buttonOffset), 30, 30);
buttonOffset += 50;
fRRectButton.fBounds.setXYWH(this->width() - 50, SkIntToScalar(buttonOffset), 30, 30);
buttonOffset += 50;
fCircleButton.fBounds.setXYWH(this->width() - 50, SkIntToScalar(buttonOffset), 30, 30);
buttonOffset += 50;
fTextButton.fBounds.setXYWH(this->width() - 50, SkIntToScalar(buttonOffset), 30, 30);
this->INHERITED::onSizeChange();
}
void copyMinToMax() {
erase(fMaxSurface);
SkCanvas* canvas = fMaxSurface->getCanvas();
canvas->save();
canvas->concat(fMatrix);
fMinSurface->draw(canvas, 0, 0, NULL);
canvas->restore();
SkPaint paint;
paint.setXfermodeMode(SkXfermode::kClear_Mode);
for (int iy = 1; iy < fH; ++iy) {
SkScalar y = SkIntToScalar(iy * fZoom);
canvas->drawLine(0, y - SK_ScalarHalf, 999, y - SK_ScalarHalf, paint);
}
for (int ix = 1; ix < fW; ++ix) {
SkScalar x = SkIntToScalar(ix * fZoom);
canvas->drawLine(x - SK_ScalarHalf, 0, x - SK_ScalarHalf, 999, paint);
}
}
void setWHZ(int width, int height, int zoom) {
fZoom = zoom;
fBounds.set(0, 0, SkIntToScalar(width * zoom), SkIntToScalar(height * zoom));
fMatrix.setScale(SkIntToScalar(zoom), SkIntToScalar(zoom));
fInverse.setScale(SK_Scalar1 / zoom, SK_Scalar1 / zoom);
fShader.reset(sk_tool_utils::create_checkerboard_shader(
0xFFCCCCCC, 0xFFFFFFFF, zoom));
SkImageInfo info = SkImageInfo::MakeN32Premul(width, height);
fMinSurface.reset(SkSurface::NewRaster(info));
info = info.makeWH(width * zoom, height * zoom);
fMaxSurface.reset(SkSurface::NewRaster(info));
}
void draw_points(SkCanvas* canvas, const SkPath& path, SkColor color,
bool show_lines) {
SkPaint paint;
paint.setColor(color);
paint.setAlpha(0x80);
paint.setAntiAlias(true);
int n = path.countPoints();
SkAutoSTArray<32, SkPoint> pts(n);
if (show_lines && fDrawTangents) {
SkTArray<int> contourCounts;
getContourCounts(path, &contourCounts);
SkPoint* ptPtr = pts.get();
for (int i = 0; i < contourCounts.count(); ++i) {
int count = contourCounts[i];
path.getPoints(ptPtr, count);
canvas->drawPoints(SkCanvas::kPolygon_PointMode, count, ptPtr, paint);
ptPtr += count;
}
} else {
n = getOnCurvePoints(path, pts.get());
}
paint.setStrokeWidth(5);
canvas->drawPoints(SkCanvas::kPoints_PointMode, n, pts.get(), paint);
}
void draw_ribs(SkCanvas* canvas, const SkPath& path, SkScalar width,
SkColor color) {
const SkScalar radius = width / 2;
SkPathMeasure meas(path, false);
SkScalar total = meas.getLength();
SkScalar delta = 8;
SkPaint paint;
paint.setColor(color);
SkPoint pos, tan;
for (SkScalar dist = 0; dist <= total; dist += delta) {
if (meas.getPosTan(dist, &pos, &tan)) {
tan.scale(radius);
tan.rotateCCW();
canvas->drawLine(pos.x() + tan.x(), pos.y() + tan.y(),
pos.x() - tan.x(), pos.y() - tan.y(), paint);
}
}
}
void draw_stroke(SkCanvas* canvas, const SkPath& path, SkScalar width, SkScalar scale,
bool drawText) {
if (path.isEmpty()) {
return;
}
SkRect bounds = path.getBounds();
this->setWHZ(SkScalarCeilToInt(bounds.right()), drawText
? SkScalarRoundToInt(scale * 3 / 2) : SkScalarRoundToInt(scale),
SkScalarRoundToInt(950.0f / scale));
erase(fMinSurface);
SkPaint paint;
paint.setColor(0x1f1f0f0f);
paint.setStyle(SkPaint::kStroke_Style);
paint.setStrokeWidth(width * scale * scale);
paint.setColor(0x3f0f1f3f);
if (drawText) {
fMinSurface->getCanvas()->drawPath(path, paint);
this->copyMinToMax();
fMaxSurface->draw(canvas, 0, 0, NULL);
}
paint.setAntiAlias(true);
paint.setStyle(SkPaint::kStroke_Style);
paint.setStrokeWidth(1);
paint.setColor(SKELETON_COLOR);
SkPath scaled;
SkMatrix matrix;
matrix.reset();
matrix.setScale(950 / scale, 950 / scale);
if (drawText) {
path.transform(matrix, &scaled);
} else {
scaled = path;
}
canvas->drawPath(scaled, paint);
draw_points(canvas, scaled, SKELETON_COLOR, true);
if (fDrawRibs) {
draw_ribs(canvas, scaled, width, 0xFF00FF00);
}
SkPath fill;
SkPaint p;
p.setStyle(SkPaint::kStroke_Style);
if (drawText) {
p.setStrokeWidth(width * scale * scale);
} else {
p.setStrokeWidth(width);
}
p.getFillPath(path, &fill);
SkPath scaledFill;
if (drawText) {
fill.transform(matrix, &scaledFill);
} else {
scaledFill = fill;
}
paint.setColor(WIREFRAME_COLOR);
canvas->drawPath(scaledFill, paint);
draw_points(canvas, scaledFill, WIREFRAME_COLOR, false);
}
void draw_fill(SkCanvas* canvas, const SkRect& rect, SkScalar width) {
if (rect.isEmpty()) {
return;
}
SkPaint paint;
paint.setColor(0x1f1f0f0f);
paint.setStyle(SkPaint::kStroke_Style);
paint.setStrokeWidth(width);
SkPath path;
SkScalar maxSide = SkTMax(rect.width(), rect.height()) / 2;
SkPoint center = { rect.fLeft + maxSide, rect.fTop + maxSide };
path.addCircle(center.fX, center.fY, maxSide);
canvas->drawPath(path, paint);
paint.setStyle(SkPaint::kFill_Style);
path.reset();
path.addCircle(center.fX, center.fY, maxSide - width / 2);
paint.setColor(0x3f0f1f3f);
canvas->drawPath(path, paint);
path.reset();
path.setFillType(SkPath::kEvenOdd_FillType);
path.addCircle(center.fX, center.fY, maxSide + width / 2);
SkRect outside = SkRect::MakeXYWH(center.fX - maxSide - width, center.fY - maxSide - width,
(maxSide + width) * 2, (maxSide + width) * 2);
path.addRect(outside);
canvas->drawPath(path, paint);
}
void draw_button(SkCanvas* canvas, const StrokeTypeButton& button) {
SkPaint paint;
paint.setAntiAlias(true);
paint.setStyle(SkPaint::kStroke_Style);
paint.setColor(button.fEnabled ? 0xFF3F0000 : 0x6F3F0000);
canvas->drawRect(button.fBounds, paint);
paint.setTextSize(25.0f);
paint.setColor(button.fEnabled ? 0xFF3F0000 : 0x6F3F0000);
paint.setTextAlign(SkPaint::kCenter_Align);
paint.setStyle(SkPaint::kFill_Style);
canvas->drawText(&button.fLabel, 1, button.fBounds.centerX(), button.fBounds.fBottom - 5,
paint);
}
void draw_control(SkCanvas* canvas, const SkRect& bounds, SkScalar value,
SkScalar min, SkScalar max, const char* name) {
SkPaint paint;
paint.setAntiAlias(true);
paint.setStyle(SkPaint::kStroke_Style);
canvas->drawRect(bounds, paint);
SkScalar scale = max - min;
SkScalar yPos = bounds.fTop + (value - min) * bounds.height() / scale;
paint.setColor(0xFFFF0000);
canvas->drawLine(bounds.fLeft - 5, yPos, bounds.fRight + 5, yPos, paint);
SkString label;
label.printf("%0.3g", value);
paint.setColor(0xFF000000);
paint.setTextSize(11.0f);
paint.setStyle(SkPaint::kFill_Style);
canvas->drawText(label.c_str(), label.size(), bounds.fLeft + 5, yPos - 5, paint);
paint.setTextSize(13.0f);
canvas->drawText(name, strlen(name), bounds.fLeft, bounds.bottom() + 11, paint);
}
void setForGeometry() {
fDrawRibs = true;
fDrawTangents = true;
fWidthScale = 1;
}
void setForText() {
fDrawRibs = fDrawTangents = false;
fWidthScale = 0.002f;
}
void setAsNeeded() {
if (fConicButton.fEnabled || fCubicButton.fEnabled || fQuadButton.fEnabled
|| fRRectButton.fEnabled || fCircleButton.fEnabled) {
setForGeometry();
} else {
setForText();
}
}
void onDrawContent(SkCanvas* canvas) override {
SkPath path;
SkScalar width = fWidth;
if (fCubicButton.fEnabled) {
path.moveTo(fPts[0]);
path.cubicTo(fPts[1], fPts[2], fPts[3]);
setForGeometry();
draw_stroke(canvas, path, width, 950, false);
}
if (fConicButton.fEnabled) {
path.moveTo(fPts[4]);
path.conicTo(fPts[5], fPts[6], fWeight);
setForGeometry();
draw_stroke(canvas, path, width, 950, false);
}
if (fQuadButton.fEnabled) {
path.reset();
path.moveTo(fPts[7]);
path.quadTo(fPts[8], fPts[9]);
setForGeometry();
draw_stroke(canvas, path, width, 950, false);
}
if (fRRectButton.fEnabled) {
SkScalar rad = 32;
SkRect r;
r.set(&fPts[10], 2);
path.reset();
SkRRect rr;
rr.setRectXY(r, rad, rad);
path.addRRect(rr);
setForGeometry();
draw_stroke(canvas, path, width, 950, false);
path.reset();
SkRRect rr2;
rr.inset(width/2, width/2, &rr2);
path.addRRect(rr2, SkPath::kCCW_Direction);
rr.inset(-width/2, -width/2, &rr2);
path.addRRect(rr2, SkPath::kCW_Direction);
SkPaint paint;
paint.setAntiAlias(true);
paint.setColor(0x40FF8844);
canvas->drawPath(path, paint);
}
if (fCircleButton.fEnabled) {
path.reset();
SkRect r;
r.set(&fPts[12], 2);
path.addOval(r);
setForGeometry();
if (fCircleButton.fFill) {
draw_fill(canvas, r, width);
} else {
draw_stroke(canvas, path, width, 950, false);
}
}
if (fTextButton.fEnabled) {
path.reset();
SkPaint paint;
paint.setAntiAlias(true);
paint.setTextSize(fTextSize);
paint.getTextPath(fText.c_str(), fText.size(), 0, fTextSize, &path);
setForText();
draw_stroke(canvas, path, width * fWidthScale / fTextSize, fTextSize, true);
}
if (fAnimate) {
fWidth += fDWidth;
if (fDWidth > 0 && fWidth > kWidthMax) {
fDWidth = -fDWidth;
} else if (fDWidth < 0 && fWidth < kWidthMin) {
fDWidth = -fDWidth;
}
}
setAsNeeded();
if (fConicButton.fEnabled) {
draw_control(canvas, fWeightControl, fWeight, 0, 5, "weight");
}
#ifdef SK_DEBUG
draw_control(canvas, fErrorControl, gDebugStrokerError, kStrokerErrorMin, kStrokerErrorMax,
"error");
#endif
draw_control(canvas, fWidthControl, fWidth * fWidthScale, kWidthMin * fWidthScale,
kWidthMax * fWidthScale, "width");
draw_button(canvas, fQuadButton);
draw_button(canvas, fCubicButton);
draw_button(canvas, fConicButton);
draw_button(canvas, fRRectButton);
draw_button(canvas, fCircleButton);
draw_button(canvas, fTextButton);
this->inval(NULL);
}
class MyClick : public Click {
public:
int fIndex;
MyClick(SkView* target, int index) : Click(target), fIndex(index) {}
};
virtual SkView::Click* onFindClickHandler(SkScalar x, SkScalar y,
unsigned modi) override {
for (size_t i = 0; i < SK_ARRAY_COUNT(fPts); ++i) {
if (hittest(fPts[i], x, y)) {
return new MyClick(this, (int)i);
}
}
const SkRect& rectPt = SkRect::MakeXYWH(x, y, 1, 1);
if (fWeightControl.contains(rectPt)) {
return new MyClick(this, (int) SK_ARRAY_COUNT(fPts) + 1);
}
#ifdef SK_DEBUG
if (fErrorControl.contains(rectPt)) {
return new MyClick(this, (int) SK_ARRAY_COUNT(fPts) + 2);
}
#endif
if (fWidthControl.contains(rectPt)) {
return new MyClick(this, (int) SK_ARRAY_COUNT(fPts) + 3);
}
if (fCubicButton.fBounds.contains(rectPt)) {
fCubicButton.fEnabled ^= true;
return new MyClick(this, (int) SK_ARRAY_COUNT(fPts) + 4);
}
if (fConicButton.fBounds.contains(rectPt)) {
fConicButton.fEnabled ^= true;
return new MyClick(this, (int) SK_ARRAY_COUNT(fPts) + 5);
}
if (fQuadButton.fBounds.contains(rectPt)) {
fQuadButton.fEnabled ^= true;
return new MyClick(this, (int) SK_ARRAY_COUNT(fPts) + 6);
}
if (fRRectButton.fBounds.contains(rectPt)) {
fRRectButton.fEnabled ^= true;
return new MyClick(this, (int) SK_ARRAY_COUNT(fPts) + 7);
}
if (fCircleButton.fBounds.contains(rectPt)) {
bool wasEnabled = fCircleButton.fEnabled;
fCircleButton.fEnabled = !fCircleButton.fFill;
fCircleButton.fFill = wasEnabled && !fCircleButton.fFill;
return new MyClick(this, (int) SK_ARRAY_COUNT(fPts) + 8);
}
if (fTextButton.fBounds.contains(rectPt)) {
fTextButton.fEnabled ^= true;
return new MyClick(this, (int) SK_ARRAY_COUNT(fPts) + 9);
}
return this->INHERITED::onFindClickHandler(x, y, modi);
}
static SkScalar MapScreenYtoValue(int y, const SkRect& control, SkScalar min,
SkScalar max) {
return (SkIntToScalar(y) - control.fTop) / control.height() * (max - min) + min;
}
bool onClick(Click* click) override {
int index = ((MyClick*)click)->fIndex;
if (index < (int) SK_ARRAY_COUNT(fPts)) {
fPts[index].offset(SkIntToScalar(click->fICurr.fX - click->fIPrev.fX),
SkIntToScalar(click->fICurr.fY - click->fIPrev.fY));
this->inval(NULL);
} else if (index == (int) SK_ARRAY_COUNT(fPts) + 1) {
fWeight = MapScreenYtoValue(click->fICurr.fY, fWeightControl, 0, 5);
}
#ifdef SK_DEBUG
else if (index == (int) SK_ARRAY_COUNT(fPts) + 2) {
gDebugStrokerError = SkTMax(FLT_EPSILON, MapScreenYtoValue(click->fICurr.fY,
fErrorControl, kStrokerErrorMin, kStrokerErrorMax));
gDebugStrokerErrorSet = true;
}
#endif
else if (index == (int) SK_ARRAY_COUNT(fPts) + 3) {
fWidth = SkTMax(FLT_EPSILON, MapScreenYtoValue(click->fICurr.fY, fWidthControl,
kWidthMin, kWidthMax));
fAnimate = fWidth <= kWidthMin;
}
return true;
}
private:
typedef SkView INHERITED;
};
///////////////////////////////////////////////////////////////////////////////
static SkView* F2() { return new QuadStrokerView; }
static SkViewRegister gR2(F2);
| {
"content_hash": "ddcc1361186e0e92c15eceae46d9c563",
"timestamp": "",
"source": "github",
"line_count": 632,
"max_line_length": 100,
"avg_line_length": 33.71835443037975,
"alnum_prop": 0.5547160957297044,
"repo_name": "Jichao/skia",
"id": "91a6a0f5d8327a40893c13f20ec24c6b8438bf10",
"size": "21453",
"binary": false,
"copies": "11",
"ref": "refs/heads/master",
"path": "samplecode/SampleQuadStroker.cpp",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Batchfile",
"bytes": "1133"
},
{
"name": "C",
"bytes": "810659"
},
{
"name": "C++",
"bytes": "27036339"
},
{
"name": "Go",
"bytes": "677"
},
{
"name": "HTML",
"bytes": "477"
},
{
"name": "Java",
"bytes": "26662"
},
{
"name": "JavaScript",
"bytes": "7593"
},
{
"name": "Lua",
"bytes": "25531"
},
{
"name": "Makefile",
"bytes": "8897"
},
{
"name": "Objective-C",
"bytes": "22088"
},
{
"name": "Objective-C++",
"bytes": "98026"
},
{
"name": "PHP",
"bytes": "116206"
},
{
"name": "Python",
"bytes": "378750"
},
{
"name": "Shell",
"bytes": "53652"
}
],
"symlink_target": ""
} |
INTERFACE gpiobus;
#
# Lock the gpio bus
#
METHOD void lock_bus {
device_t busdev;
};
#
# Unlock the gpio bus
#
METHOD void unlock_bus {
device_t busdev;
};
#
# Dedicate the gpio bus control for a child
#
METHOD void acquire_bus {
device_t busdev;
device_t dev;
};
#
# Release the bus
#
METHOD void release_bus {
device_t busdev;
device_t dev;
};
#
# Set value of pin specifed by pin_num
#
METHOD int pin_set {
device_t dev;
device_t child;
uint32_t pin_num;
uint32_t pin_value;
};
#
# Get value of pin specifed by pin_num
#
METHOD int pin_get {
device_t dev;
device_t child;
uint32_t pin_num;
uint32_t *pin_value;
};
#
# Toggle value of pin specifed by pin_num
#
METHOD int pin_toggle {
device_t dev;
device_t child;
uint32_t pin_num;
};
#
# Get pin capabilities
#
METHOD int pin_getcaps {
device_t dev;
device_t child;
uint32_t pin_num;
uint32_t *caps;
};
#
# Get pin flags
#
METHOD int pin_getflags {
device_t dev;
device_t child;
uint32_t pin_num;
uint32_t *flags;
};
#
# Set current configuration and capabilities
#
METHOD int pin_setflags {
device_t dev;
device_t child;
uint32_t pin_num;
uint32_t flags;
};
| {
"content_hash": "7ab240f35b46b072e68c83ae43c62f4b",
"timestamp": "",
"source": "github",
"line_count": 90,
"max_line_length": 44,
"avg_line_length": 12.844444444444445,
"alnum_prop": 0.6747404844290658,
"repo_name": "dcui/FreeBSD-9.3_kernel",
"id": "17ea9437ef804d8d2b2e56d9339e78561783f0d3",
"size": "2644",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "sys/dev/gpio/gpiobus_if.m",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Assembly",
"bytes": "1740660"
},
{
"name": "Awk",
"bytes": "135150"
},
{
"name": "Batchfile",
"bytes": "158"
},
{
"name": "C",
"bytes": "189969174"
},
{
"name": "C++",
"bytes": "2113755"
},
{
"name": "DTrace",
"bytes": "19810"
},
{
"name": "Forth",
"bytes": "188128"
},
{
"name": "Groff",
"bytes": "147703"
},
{
"name": "Lex",
"bytes": "65561"
},
{
"name": "Logos",
"bytes": "6310"
},
{
"name": "Makefile",
"bytes": "594606"
},
{
"name": "Mathematica",
"bytes": "9538"
},
{
"name": "Objective-C",
"bytes": "527964"
},
{
"name": "PHP",
"bytes": "2404"
},
{
"name": "Perl",
"bytes": "3348"
},
{
"name": "Python",
"bytes": "7091"
},
{
"name": "Shell",
"bytes": "43402"
},
{
"name": "SourcePawn",
"bytes": "253"
},
{
"name": "Yacc",
"bytes": "160534"
}
],
"symlink_target": ""
} |
package org.elasticsearch.search.internal;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import org.apache.lucene.search.Filter;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.Sort;
import org.apache.lucene.util.Counter;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.index.query.ParsedFilter;
import org.elasticsearch.search.Scroll;
import org.elasticsearch.search.aggregations.SearchContextAggregations;
import org.elasticsearch.search.fetch.FetchSearchResult;
import org.elasticsearch.search.fetch.fielddata.FieldDataFieldsContext;
import org.elasticsearch.search.fetch.innerhits.InnerHitsContext;
import org.elasticsearch.search.fetch.script.ScriptFieldsContext;
import org.elasticsearch.search.fetch.source.FetchSourceContext;
import org.elasticsearch.search.highlight.SearchContextHighlight;
import org.elasticsearch.search.lookup.SearchLookup;
import org.elasticsearch.search.query.QuerySearchResult;
import org.elasticsearch.search.rescore.RescoreSearchContext;
import org.elasticsearch.search.suggest.SuggestionSearchContext;
import java.util.List;
/**
*/
public class SubSearchContext extends FilteredSearchContext {
// By default return 3 hits per bucket. A higher default would make the response really large by default, since
// the to hits are returned per bucket.
private final static int DEFAULT_SIZE = 3;
private int from;
private int size = DEFAULT_SIZE;
private Sort sort;
private final FetchSearchResult fetchSearchResult;
private final QuerySearchResult querySearchResult;
private int[] docIdsToLoad;
private int docsIdsToLoadFrom;
private int docsIdsToLoadSize;
private List<String> fieldNames;
private FieldDataFieldsContext fieldDataFields;
private ScriptFieldsContext scriptFields;
private FetchSourceContext fetchSourceContext;
private SearchContextHighlight highlight;
private boolean explain;
private boolean trackScores;
private boolean version;
private InnerHitsContext innerHitsContext;
public SubSearchContext(SearchContext context) {
super(context);
this.fetchSearchResult = new FetchSearchResult();
this.querySearchResult = new QuerySearchResult();
}
@Override
protected void doClose() {
}
@Override
public void preProcess() {
}
@Override
public Filter searchFilter(String[] types) {
throw new UnsupportedOperationException("this context should be read only");
}
@Override
public SearchContext searchType(SearchType searchType) {
throw new UnsupportedOperationException("this context should be read only");
}
@Override
public SearchContext queryBoost(float queryBoost) {
throw new UnsupportedOperationException("Not supported");
}
@Override
public SearchContext scroll(Scroll scroll) {
throw new UnsupportedOperationException("Not supported");
}
@Override
public SearchContext aggregations(SearchContextAggregations aggregations) {
throw new UnsupportedOperationException("Not supported");
}
@Override
public SearchContextHighlight highlight() {
return highlight;
}
@Override
public void highlight(SearchContextHighlight highlight) {
this.highlight = highlight;
}
@Override
public void suggest(SuggestionSearchContext suggest) {
throw new UnsupportedOperationException("Not supported");
}
@Override
public void addRescore(RescoreSearchContext rescore) {
throw new UnsupportedOperationException("Not supported");
}
@Override
public boolean hasFieldDataFields() {
return fieldDataFields != null;
}
@Override
public FieldDataFieldsContext fieldDataFields() {
if (fieldDataFields == null) {
fieldDataFields = new FieldDataFieldsContext();
}
return this.fieldDataFields;
}
@Override
public boolean hasScriptFields() {
return scriptFields != null;
}
@Override
public ScriptFieldsContext scriptFields() {
if (scriptFields == null) {
scriptFields = new ScriptFieldsContext();
}
return this.scriptFields;
}
@Override
public boolean sourceRequested() {
return fetchSourceContext != null && fetchSourceContext.fetchSource();
}
@Override
public boolean hasFetchSourceContext() {
return fetchSourceContext != null;
}
@Override
public FetchSourceContext fetchSourceContext() {
return fetchSourceContext;
}
@Override
public SearchContext fetchSourceContext(FetchSourceContext fetchSourceContext) {
this.fetchSourceContext = fetchSourceContext;
return this;
}
@Override
public void timeoutInMillis(long timeoutInMillis) {
throw new UnsupportedOperationException("Not supported");
}
@Override
public void terminateAfter(int terminateAfter) {
throw new UnsupportedOperationException("Not supported");
}
@Override
public SearchContext minimumScore(float minimumScore) {
throw new UnsupportedOperationException("Not supported");
}
@Override
public SearchContext sort(Sort sort) {
this.sort = sort;
return this;
}
@Override
public Sort sort() {
return sort;
}
@Override
public SearchContext trackScores(boolean trackScores) {
this.trackScores = trackScores;
return this;
}
@Override
public boolean trackScores() {
return trackScores;
}
@Override
public SearchContext parsedPostFilter(ParsedFilter postFilter) {
throw new UnsupportedOperationException("Not supported");
}
@Override
public SearchContext updateRewriteQuery(Query rewriteQuery) {
throw new UnsupportedOperationException("Not supported");
}
@Override
public int from() {
return from;
}
@Override
public SearchContext from(int from) {
this.from = from;
return this;
}
@Override
public int size() {
return size;
}
@Override
public SearchContext size(int size) {
this.size = size;
return this;
}
@Override
public boolean hasFieldNames() {
return fieldNames != null;
}
@Override
public List<String> fieldNames() {
if (fieldNames == null) {
fieldNames = Lists.newArrayList();
}
return fieldNames;
}
@Override
public void emptyFieldNames() {
this.fieldNames = ImmutableList.of();
}
@Override
public boolean explain() {
return explain;
}
@Override
public void explain(boolean explain) {
this.explain = explain;
}
@Override
public void groupStats(List<String> groupStats) {
throw new UnsupportedOperationException("Not supported");
}
@Override
public boolean version() {
return version;
}
@Override
public void version(boolean version) {
this.version = version;
}
@Override
public int[] docIdsToLoad() {
return docIdsToLoad;
}
@Override
public int docIdsToLoadFrom() {
return docsIdsToLoadFrom;
}
@Override
public int docIdsToLoadSize() {
return docsIdsToLoadSize;
}
@Override
public SearchContext docIdsToLoad(int[] docIdsToLoad, int docsIdsToLoadFrom, int docsIdsToLoadSize) {
this.docIdsToLoad = docIdsToLoad;
this.docsIdsToLoadFrom = docsIdsToLoadFrom;
this.docsIdsToLoadSize = docsIdsToLoadSize;
return this;
}
@Override
public void accessed(long accessTime) {
throw new UnsupportedOperationException("Not supported");
}
@Override
public void keepAlive(long keepAlive) {
throw new UnsupportedOperationException("Not supported");
}
@Override
public void lastEmittedDoc(ScoreDoc doc) {
throw new UnsupportedOperationException("Not supported");
}
@Override
public QuerySearchResult queryResult() {
return querySearchResult;
}
@Override
public FetchSearchResult fetchResult() {
return fetchSearchResult;
}
private SearchLookup searchLookup;
@Override
public SearchLookup lookup() {
if (searchLookup == null) {
searchLookup = new SearchLookup(mapperService(), fieldData(), request().types());
}
return searchLookup;
}
@Override
public Counter timeEstimateCounter() {
throw new UnsupportedOperationException("Not supported");
}
@Override
public void innerHits(InnerHitsContext innerHitsContext) {
this.innerHitsContext = innerHitsContext;
}
@Override
public InnerHitsContext innerHits() {
return innerHitsContext;
}
}
| {
"content_hash": "f9f31801486040a0c549ec599d73a274",
"timestamp": "",
"source": "github",
"line_count": 349,
"max_line_length": 115,
"avg_line_length": 25.856733524355302,
"alnum_prop": 0.6881648936170213,
"repo_name": "sjohnr/elasticsearch",
"id": "ef7909f65601299a5afba8c42d0f2710e385c21c",
"size": "9812",
"binary": false,
"copies": "9",
"ref": "refs/heads/master",
"path": "src/main/java/org/elasticsearch/search/internal/SubSearchContext.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ApacheConf",
"bytes": "87"
},
{
"name": "Groovy",
"bytes": "451"
},
{
"name": "HTML",
"bytes": "1210"
},
{
"name": "Java",
"bytes": "26594861"
},
{
"name": "Perl",
"bytes": "6858"
},
{
"name": "Python",
"bytes": "64984"
},
{
"name": "Ruby",
"bytes": "17776"
},
{
"name": "Shell",
"bytes": "35009"
}
],
"symlink_target": ""
} |
package org.drools.guvnor.client.asseteditor.drools.modeldriven.ui.templates;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.jar.JarInputStream;
import org.drools.guvnor.client.widgets.drools.decoratedgrid.CellValue;
import org.drools.guvnor.client.widgets.drools.decoratedgrid.data.DynamicData;
import org.drools.ide.common.client.modeldriven.SuggestionCompletionEngine;
import org.drools.ide.common.client.modeldriven.brl.ActionFieldValue;
import org.drools.ide.common.client.modeldriven.brl.ActionInsertFact;
import org.drools.ide.common.client.modeldriven.brl.BaseSingleFieldConstraint;
import org.drools.ide.common.client.modeldriven.brl.FactPattern;
import org.drools.ide.common.client.modeldriven.brl.IAction;
import org.drools.ide.common.client.modeldriven.brl.IPattern;
import org.drools.ide.common.client.modeldriven.brl.SingleFieldConstraint;
import org.drools.ide.common.client.modeldriven.brl.templates.TemplateModel;
import org.drools.ide.common.server.rules.SuggestionCompletionLoader;
import org.drools.lang.dsl.DSLTokenizedMappingFile;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import com.google.gwt.cell.client.Cell.Context;
public class TemplateDropDownManagerTests {
private DynamicData data;
private TemplateModel model;
private TemplateDropDownManager manager;
private SuggestionCompletionEngine sce;
@Before
public void setup() {
//---Setup model---
model = new TemplateModel();
//Setup LHS
model.lhs = new IPattern[3];
//Both fields are Template Keys
FactPattern fp0 = new FactPattern();
fp0.setFactType( "FT0" );
SingleFieldConstraint sfc0p0 = new SingleFieldConstraint();
sfc0p0.setConstraintValueType( BaseSingleFieldConstraint.TYPE_TEMPLATE );
sfc0p0.setFieldBinding( "$sfc0p0" );
sfc0p0.setFactType( "FT0" );
sfc0p0.setFieldName( "sfc0p0" );
sfc0p0.setFieldType( SuggestionCompletionEngine.TYPE_STRING );
sfc0p0.setOperator( "==" );
sfc0p0.setValue( "sfc0p0Value" );
fp0.addConstraint( sfc0p0 );
SingleFieldConstraint sfc1p0 = new SingleFieldConstraint();
sfc1p0.setConstraintValueType( BaseSingleFieldConstraint.TYPE_TEMPLATE );
sfc1p0.setFieldBinding( "$sfc1p0" );
sfc1p0.setFactType( "FT0" );
sfc1p0.setFieldName( "sfc1p0" );
sfc1p0.setFieldType( SuggestionCompletionEngine.TYPE_STRING );
sfc1p0.setOperator( "==" );
sfc1p0.setValue( "sfc1p0Value" );
fp0.addConstraint( sfc1p0 );
model.lhs[0] = fp0;
//One field is a Template Key the other is a literal
FactPattern fp1 = new FactPattern();
fp1.setFactType( "FT1" );
SingleFieldConstraint sfc0p1 = new SingleFieldConstraint();
sfc0p1.setConstraintValueType( BaseSingleFieldConstraint.TYPE_TEMPLATE );
sfc0p1.setFieldBinding( "$sfc0p1" );
sfc0p1.setFactType( "FT1" );
sfc0p1.setFieldName( "sfc0p1" );
sfc0p1.setFieldType( SuggestionCompletionEngine.TYPE_STRING );
sfc0p1.setOperator( "==" );
sfc0p1.setValue( "sfc0p1Value" );
fp1.addConstraint( sfc0p1 );
SingleFieldConstraint sfc1p1 = new SingleFieldConstraint();
sfc1p1.setConstraintValueType( BaseSingleFieldConstraint.TYPE_LITERAL );
sfc1p1.setFieldBinding( "$sfc1p1" );
sfc1p1.setFactType( "FT1" );
sfc1p1.setFieldName( "sfc1p1" );
sfc1p1.setFieldType( SuggestionCompletionEngine.TYPE_STRING );
sfc1p1.setOperator( "==" );
sfc1p1.setValue( "sfc1p1Value" );
fp1.addConstraint( sfc1p1 );
model.lhs[1] = fp1;
//Dependent enumerations
FactPattern fp2 = new FactPattern();
fp2.setFactType( "Fact" );
SingleFieldConstraint sfc0p2 = new SingleFieldConstraint();
sfc0p2.setConstraintValueType( BaseSingleFieldConstraint.TYPE_TEMPLATE );
sfc0p2.setFieldBinding( "$sfc0p2" );
sfc0p2.setFactType( "Fact" );
sfc0p2.setFieldName( "field1" );
sfc0p2.setFieldType( SuggestionCompletionEngine.TYPE_STRING );
sfc0p2.setOperator( "==" );
sfc0p2.setValue( "enum1" );
fp2.addConstraint( sfc0p2 );
SingleFieldConstraint sfc1p2 = new SingleFieldConstraint();
sfc1p2.setConstraintValueType( BaseSingleFieldConstraint.TYPE_TEMPLATE );
sfc1p2.setFieldBinding( "$sfc1p2" );
sfc1p2.setFactType( "Fact" );
sfc1p2.setFieldName( "field2" );
sfc1p2.setFieldType( SuggestionCompletionEngine.TYPE_STRING );
sfc1p2.setOperator( "==" );
sfc1p2.setValue( "enum2" );
fp2.addConstraint( sfc1p2 );
SingleFieldConstraint sfc2p2 = new SingleFieldConstraint();
sfc2p2.setConstraintValueType( BaseSingleFieldConstraint.TYPE_TEMPLATE );
sfc2p2.setFieldBinding( "$sfc2p2" );
sfc2p2.setFactType( "Fact" );
sfc2p2.setFieldName( "field3" );
sfc2p2.setFieldType( SuggestionCompletionEngine.TYPE_STRING );
sfc2p2.setOperator( "==" );
sfc2p2.setValue( "enum3" );
fp2.addConstraint( sfc2p2 );
model.lhs[2] = fp2;
//Setup RHS
model.rhs = new IAction[2];
//Both fields are Template Keys
ActionInsertFact aif0 = new ActionInsertFact( "AIF0" );
ActionFieldValue aif0f0 = new ActionFieldValue( "AIF0F0",
"AIF0F0Value",
SuggestionCompletionEngine.TYPE_STRING );
aif0f0.setNature( BaseSingleFieldConstraint.TYPE_TEMPLATE );
aif0.addFieldValue( aif0f0 );
ActionFieldValue aif0f1 = new ActionFieldValue( "AIF0F1",
"AIF0F1Value",
SuggestionCompletionEngine.TYPE_STRING );
aif0f1.setNature( BaseSingleFieldConstraint.TYPE_TEMPLATE );
aif0.addFieldValue( aif0f1 );
model.rhs[0] = aif0;
//Dependent enumerations
ActionInsertFact aif1 = new ActionInsertFact( "Fact" );
ActionFieldValue aif1f0 = new ActionFieldValue( "field1",
"AIF1F0Value",
SuggestionCompletionEngine.TYPE_STRING );
aif1f0.setNature( BaseSingleFieldConstraint.TYPE_TEMPLATE );
aif1.addFieldValue( aif1f0 );
ActionFieldValue aif1f1 = new ActionFieldValue( "field2",
"AIF1F1Value",
SuggestionCompletionEngine.TYPE_STRING );
aif1f1.setNature( BaseSingleFieldConstraint.TYPE_TEMPLATE );
aif1.addFieldValue( aif1f1 );
ActionFieldValue aif1f2 = new ActionFieldValue( "field3",
"AIF1F2Value",
SuggestionCompletionEngine.TYPE_STRING );
aif1f2.setNature( BaseSingleFieldConstraint.TYPE_TEMPLATE );
aif1.addFieldValue( aif1f2 );
model.rhs[1] = aif1;
//---Setup data---
data = new DynamicData();
data.addRow();
data.addRow();
data.addColumn( 0,
makeColumnData( new String[]{"r0c0", "r1c0"} ),
true );
data.addColumn( 1,
makeColumnData( new String[]{"r0c1", "r1c1"} ),
true );
data.addColumn( 2,
makeColumnData( new String[]{"r0c2", "r1c2"} ),
true );
data.addColumn( 3,
makeColumnData( new String[]{"val1", "val1"} ),
true );
data.addColumn( 4,
makeColumnData( new String[]{"val1a", "val1b"} ),
true );
data.addColumn( 5,
makeColumnData( new String[]{"val1a1", "val1b1"} ),
true );
data.addColumn( 6,
makeColumnData( new String[]{"r0c3", "r1c3"} ),
true );
data.addColumn( 7,
makeColumnData( new String[]{"r0c4", "r1c4"} ),
true );
data.addColumn( 8,
makeColumnData( new String[]{"val1", "val1"} ),
true );
data.addColumn( 9,
makeColumnData( new String[]{"val1a", "val1b"} ),
true );
data.addColumn( 10,
makeColumnData( new String[]{"val1a1", "val1b1"} ),
true );
//---Setup SCE---
SuggestionCompletionLoader loader = new SuggestionCompletionLoader();
List<String> enums = new ArrayList<String>();
final String enumDefinition = "'Fact.field1' : ['val1', 'val2'], "
+ "'Fact.field2[field1=val1]' : ['val1a', 'val1b'], "
+ "'Fact.field3[field2=val1a]' : ['val1a1', 'val1a2'], "
+ "'Fact.field3[field2=val1b]' : ['val1b1', 'val1b2']";
enums.add( enumDefinition );
sce = loader.getSuggestionEngine( "",
new ArrayList<JarInputStream>(),
new ArrayList<DSLTokenizedMappingFile>(),
enums );
//---Setup manager---
manager = new TemplateDropDownManager( model,
data,
sce );
}
private List<CellValue< ? extends Comparable< ? >>> makeColumnData(final String[] values) {
final List<CellValue< ? extends Comparable< ? >>> columnData = new ArrayList<CellValue< ? extends Comparable< ? >>>();
for ( String value : values ) {
columnData.add( new CellValue<String>( value ) );
}
return columnData;
}
@Test
public void testConstraints() {
Context context;
Map<String, String> values;
//Row 0, Column 0
context = new Context( 0,
0,
null );
values = manager.getCurrentValueMap( context );
assertNotNull( values );
assertEquals( 2,
values.size() );
assertTrue( values.containsKey( "sfc0p0" ) );
assertNotNull( values.get( "sfc0p0" ) );
assertEquals( "r0c0",
values.get( "sfc0p0" ) );
assertTrue( values.containsKey( "sfc1p0" ) );
assertNotNull( values.get( "sfc1p0" ) );
assertEquals( "r0c1",
values.get( "sfc1p0" ) );
//Row 1, Column 0
context = new Context( 1,
0,
null );
values = manager.getCurrentValueMap( context );
assertNotNull( values );
assertEquals( 2,
values.size() );
assertTrue( values.containsKey( "sfc0p0" ) );
assertNotNull( values.get( "sfc0p0" ) );
assertEquals( "r1c0",
values.get( "sfc0p0" ) );
assertTrue( values.containsKey( "sfc1p0" ) );
assertNotNull( values.get( "sfc1p0" ) );
assertEquals( "r1c1",
values.get( "sfc1p0" ) );
//Row 0, Column 1
context = new Context( 0,
1,
null );
values = manager.getCurrentValueMap( context );
assertNotNull( values );
assertEquals( 2,
values.size() );
assertTrue( values.containsKey( "sfc0p0" ) );
assertNotNull( values.get( "sfc0p0" ) );
assertEquals( "r0c0",
values.get( "sfc0p0" ) );
assertTrue( values.containsKey( "sfc1p0" ) );
assertNotNull( values.get( "sfc1p0" ) );
assertEquals( "r0c1",
values.get( "sfc1p0" ) );
//Row 1, Column 1
context = new Context( 1,
1,
null );
values = manager.getCurrentValueMap( context );
assertNotNull( values );
assertEquals( 2,
values.size() );
assertTrue( values.containsKey( "sfc0p0" ) );
assertNotNull( values.get( "sfc0p0" ) );
assertEquals( "r1c0",
values.get( "sfc0p0" ) );
assertTrue( values.containsKey( "sfc1p0" ) );
assertNotNull( values.get( "sfc1p0" ) );
assertEquals( "r1c1",
values.get( "sfc1p0" ) );
//Row 0, Column 2
context = new Context( 0,
2,
null );
values = manager.getCurrentValueMap( context );
assertNotNull( values );
assertEquals( 2,
values.size() );
assertTrue( values.containsKey( "sfc0p1" ) );
assertNotNull( values.get( "sfc0p1" ) );
assertEquals( "r0c2",
values.get( "sfc0p1" ) );
assertTrue( values.containsKey( "sfc1p1" ) );
assertNotNull( values.get( "sfc1p1" ) );
assertEquals( "sfc1p1Value",
values.get( "sfc1p1" ) );
//Row 1, Column 2
context = new Context( 1,
2,
null );
values = manager.getCurrentValueMap( context );
assertNotNull( values );
assertEquals( 2,
values.size() );
assertTrue( values.containsKey( "sfc0p1" ) );
assertNotNull( values.get( "sfc0p1" ) );
assertEquals( "r1c2",
values.get( "sfc0p1" ) );
assertTrue( values.containsKey( "sfc1p1" ) );
assertNotNull( values.get( "sfc1p1" ) );
assertEquals( "sfc1p1Value",
values.get( "sfc1p1" ) );
}
@Test
public void testActions() {
Context context;
Map<String, String> values;
//Row 0, Column 6
context = new Context( 0,
6,
null );
values = manager.getCurrentValueMap( context );
assertNotNull( values );
assertEquals( 2,
values.size() );
assertTrue( values.containsKey( "AIF0F0" ) );
assertNotNull( values.get( "AIF0F0" ) );
assertEquals( "r0c3",
values.get( "AIF0F0" ) );
assertTrue( values.containsKey( "AIF0F1" ) );
assertNotNull( values.get( "AIF0F1" ) );
assertEquals( "r0c4",
values.get( "AIF0F1" ) );
//Row 1, Column 6
context = new Context( 1,
6,
null );
values = manager.getCurrentValueMap( context );
assertNotNull( values );
assertEquals( 2,
values.size() );
assertTrue( values.containsKey( "AIF0F0" ) );
assertNotNull( values.get( "AIF0F0" ) );
assertEquals( "r1c3",
values.get( "AIF0F0" ) );
assertTrue( values.containsKey( "AIF0F1" ) );
assertNotNull( values.get( "AIF0F1" ) );
assertEquals( "r1c4",
values.get( "AIF0F1" ) );
//Row 0, Column 7
context = new Context( 0,
7,
null );
values = manager.getCurrentValueMap( context );
assertNotNull( values );
assertEquals( 2,
values.size() );
assertTrue( values.containsKey( "AIF0F0" ) );
assertNotNull( values.get( "AIF0F0" ) );
assertEquals( "r0c3",
values.get( "AIF0F0" ) );
assertTrue( values.containsKey( "AIF0F1" ) );
assertNotNull( values.get( "AIF0F1" ) );
assertEquals( "r0c4",
values.get( "AIF0F1" ) );
//Row 1, Column 7
context = new Context( 1,
7,
null );
values = manager.getCurrentValueMap( context );
assertNotNull( values );
assertEquals( 2,
values.size() );
assertTrue( values.containsKey( "AIF0F0" ) );
assertNotNull( values.get( "AIF0F0" ) );
assertEquals( "r1c3",
values.get( "AIF0F0" ) );
assertTrue( values.containsKey( "AIF0F1" ) );
assertNotNull( values.get( "AIF0F1" ) );
assertEquals( "r1c4",
values.get( "AIF0F1" ) );
}
@Test
public void testConstraintsEnumDependencies() {
Context context;
Set<Integer> columns;
context = new Context( 0,
3,
null );
columns = manager.getDependentColumnIndexes( context );
assertNotNull( columns );
assertEquals( 2,
columns.size() );
assertTrue( columns.contains( new Integer( 4 ) ) );
assertTrue( columns.contains( new Integer( 5 ) ) );
context = new Context( 0,
4,
null );
columns = manager.getDependentColumnIndexes( context );
assertNotNull( columns );
assertEquals( 1,
columns.size() );
assertTrue( columns.contains( new Integer( 5 ) ) );
}
@Test
public void testActionsEnumDependencies() {
Context context;
Set<Integer> columns;
context = new Context( 0,
8,
null );
columns = manager.getDependentColumnIndexes( context );
assertNotNull( columns );
assertEquals( 2,
columns.size() );
assertTrue( columns.contains( new Integer( 9 ) ) );
assertTrue( columns.contains( new Integer( 10 ) ) );
context = new Context( 0,
9,
null );
columns = manager.getDependentColumnIndexes( context );
assertNotNull( columns );
assertEquals( 1,
columns.size() );
assertTrue( columns.contains( new Integer( 10 ) ) );
}
}
| {
"content_hash": "fafba38bcbb4571da6522ab0da7f54a6",
"timestamp": "",
"source": "github",
"line_count": 493,
"max_line_length": 126,
"avg_line_length": 38.1764705882353,
"alnum_prop": 0.5293023750066416,
"repo_name": "cristianonicolai/guvnor",
"id": "032bb35773c1ded1c4bf2f88058e70e07dd53349",
"size": "19412",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "guvnor-webapp-drools/src/test/java/org/drools/guvnor/client/asseteditor/drools/modeldriven/ui/templates/TemplateDropDownManagerTests.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ActionScript",
"bytes": "408232"
},
{
"name": "Java",
"bytes": "10079290"
},
{
"name": "JavaScript",
"bytes": "13541"
},
{
"name": "Shell",
"bytes": "1177"
}
],
"symlink_target": ""
} |
CKEDITOR.plugins.setLang( 'maximize', 'ko', {
maximize: 'Maximize', // MISSING
minimize: 'Minimize' // MISSING
});
| {
"content_hash": "e8b0940b66779d13eca7f79748343a76",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 45,
"avg_line_length": 24.8,
"alnum_prop": 0.6290322580645161,
"repo_name": "webmasterETSI/web",
"id": "3dead8ddbedc0a0068e03447ed2a9cdb70b58c65",
"size": "273",
"binary": false,
"copies": "9",
"ref": "refs/heads/master",
"path": "web/ckeditor/plugins/maximize/lang/ko.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "4357402"
},
{
"name": "PHP",
"bytes": "185061"
},
{
"name": "Perl",
"bytes": "26"
},
{
"name": "Shell",
"bytes": "213"
}
],
"symlink_target": ""
} |
package org.lwjgl.opengles;
import java.nio.*;
import org.lwjgl.system.*;
import static org.lwjgl.system.Checks.*;
import static org.lwjgl.system.JNI.*;
import static org.lwjgl.system.MemoryUtil.*;
/**
* Native bindings to the <a target="_blank" href="https://www.khronos.org/registry/OpenGL/extensions/NV/NV_sample_locations.txt">NV_sample_locations</a> extension.
*
* <p>This extension allows an application to modify the locations of samples within a pixel used in multisample rasterization. Additionally, it allows
* applications to specify different sample locations for each pixel in a group of adjacent pixels, which may increase antialiasing quality (particularly
* if a custom resolve shader is used that takes advantage of these different locations).</p>
*
* <p>It is common for implementations to optimize the storage of depth values by storing values that can be used to reconstruct depth at each sample
* location, rather than storing separate depth values for each sample. For example, the depth values from a single triangle can be represented using
* plane equations. When the depth value for a sample is needed, it is automatically evaluated at the sample location. Modifying the sample locations
* causes the reconstruction to no longer evaluate the same depth values as when the samples were originally generated. This extension provides a command
* to "resolve" and store per-sample depth values using the currently programmed sample locations, which allows the application to manage this issue
* if/when necessary.</p>
*
* <p>The programmable sample locations are used during rasterization and for evaluation of depth functions during normal geometric rendering. The
* programmable locations are associated with a framebuffer object rather than an individual depth buffer, so if the depth buffer is used as a texture the
* texture sampling may be done at the standard sample locations. Additionally, commands that do not render geometric primitives (e.g. ReadPixels,
* BlitFramebuffer, CopyTexSubImage2D, etc.) may use the standard sample locations to resolve depth functions rather than the programmable locations. If a
* single depth buffer is used at different times with different sample locations, the depth functions may be interpreted using the current sample
* locations.</p>
*/
public class NVSampleLocations {
static { GLES.initialize(); }
/** Accepted by the {@code pname} parameter of GetBooleanv, GetIntegerv, GetInteger64v, GetFloatv, and GetDoublev. */
public static final int
GL_SAMPLE_LOCATION_SUBPIXEL_BITS_NV = 0x933D,
GL_SAMPLE_LOCATION_PIXEL_GRID_WIDTH_NV = 0x933E,
GL_SAMPLE_LOCATION_PIXEL_GRID_HEIGHT_NV = 0x933F,
GL_PROGRAMMABLE_SAMPLE_LOCATION_TABLE_SIZE_NV = 0x9340;
/** Accepted by the {@code pname} parameter of GetMultisamplefv. */
public static final int
GL_SAMPLE_LOCATION_NV = 0x8E50,
GL_PROGRAMMABLE_SAMPLE_LOCATION_NV = 0x9341;
/** Accepted by the {@code pname} parameter of FramebufferParameteri, GetFramebufferParameteriv. */
public static final int
GL_FRAMEBUFFER_PROGRAMMABLE_SAMPLE_LOCATIONS_NV = 0x9342,
GL_FRAMEBUFFER_SAMPLE_LOCATION_PIXEL_GRID_NV = 0x9343;
protected NVSampleLocations() {
throw new UnsupportedOperationException();
}
// --- [ glFramebufferSampleLocationsfvNV ] ---
public static native void nglFramebufferSampleLocationsfvNV(int target, int start, int count, long v);
public static void glFramebufferSampleLocationsfvNV(@NativeType("GLenum") int target, @NativeType("GLuint") int start, @NativeType("GLfloat const *") FloatBuffer v) {
nglFramebufferSampleLocationsfvNV(target, start, v.remaining(), memAddress(v));
}
// --- [ glNamedFramebufferSampleLocationsfvNV ] ---
public static native void nglNamedFramebufferSampleLocationsfvNV(int framebuffer, int start, int count, long v);
public static void glNamedFramebufferSampleLocationsfvNV(@NativeType("GLuint") int framebuffer, @NativeType("GLuint") int start, @NativeType("GLfloat const *") FloatBuffer v) {
nglNamedFramebufferSampleLocationsfvNV(framebuffer, start, v.remaining(), memAddress(v));
}
// --- [ glResolveDepthValuesNV ] ---
public static native void glResolveDepthValuesNV();
/** Array version of: {@link #glFramebufferSampleLocationsfvNV FramebufferSampleLocationsfvNV} */
public static void glFramebufferSampleLocationsfvNV(@NativeType("GLenum") int target, @NativeType("GLuint") int start, @NativeType("GLfloat const *") float[] v) {
long __functionAddress = GLES.getICD().glFramebufferSampleLocationsfvNV;
if (CHECKS) {
check(__functionAddress);
}
callPV(target, start, v.length, v, __functionAddress);
}
/** Array version of: {@link #glNamedFramebufferSampleLocationsfvNV NamedFramebufferSampleLocationsfvNV} */
public static void glNamedFramebufferSampleLocationsfvNV(@NativeType("GLuint") int framebuffer, @NativeType("GLuint") int start, @NativeType("GLfloat const *") float[] v) {
long __functionAddress = GLES.getICD().glNamedFramebufferSampleLocationsfvNV;
if (CHECKS) {
check(__functionAddress);
}
callPV(framebuffer, start, v.length, v, __functionAddress);
}
} | {
"content_hash": "c05c54ac39b52a177405e104109c472d",
"timestamp": "",
"source": "github",
"line_count": 96,
"max_line_length": 180,
"avg_line_length": 56.020833333333336,
"alnum_prop": 0.7394942357753812,
"repo_name": "code-disaster/lwjgl3",
"id": "551851eeca8d791ce245f92006639801c9853cf5",
"size": "5512",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "modules/lwjgl/opengles/src/generated/java/org/lwjgl/opengles/NVSampleLocations.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Assembly",
"bytes": "14340"
},
{
"name": "C",
"bytes": "12123701"
},
{
"name": "C++",
"bytes": "1982042"
},
{
"name": "GLSL",
"bytes": "1703"
},
{
"name": "Java",
"bytes": "71118728"
},
{
"name": "Kotlin",
"bytes": "18559115"
},
{
"name": "Objective-C",
"bytes": "14684"
},
{
"name": "Objective-C++",
"bytes": "2004"
}
],
"symlink_target": ""
} |
/**
* Provides classes and interfaces to deal with injectable targets.
*/
package io.inkstand.scribble.inject;
| {
"content_hash": "d0dddf54e7b29d338c8ce79c17e7a5be",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 67,
"avg_line_length": 19.166666666666668,
"alnum_prop": 0.7478260869565218,
"repo_name": "inkstand-io/scribble",
"id": "9c3c551bb00d7d29372ea91a854f6dba6a6a1610",
"size": "732",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "scribble-inject/src/main/java/io/inkstand/scribble/inject/package-info.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "123"
},
{
"name": "Java",
"bytes": "660939"
}
],
"symlink_target": ""
} |
require_relative '../../test_helper'
describe Timeup::Base do
end
| {
"content_hash": "fbb60a8441d1c30d446c0e99bbd277bf",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 36,
"avg_line_length": 16.75,
"alnum_prop": 0.7164179104477612,
"repo_name": "adamdawkins/timeup",
"id": "586ba453aca0f09554256effb1aee7a7c4807e1a",
"size": "67",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/lib/timeup/base_test.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "1755"
}
],
"symlink_target": ""
} |
package org.reveno.atp.core.api.channel;
import java.util.function.Consumer;
public interface Channel extends AutoCloseable {
long size();
long position();
boolean isReadAvailable();
Buffer read();
void write(Consumer<Buffer> channelBuffer, boolean flush);
boolean isOpen();
void close();
}
| {
"content_hash": "193b00417a01177ae231bec4fee3aa4b",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 62,
"avg_line_length": 15.666666666666666,
"alnum_prop": 0.6899696048632219,
"repo_name": "dmart28/reveno",
"id": "16bdb201a9f5062d289dcaecd652b29027ff9d7c",
"size": "329",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "reveno-core/src/main/java/org/reveno/atp/core/api/channel/Channel.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "494809"
}
],
"symlink_target": ""
} |
class AddProgrammmingLanguageExtension < ActiveRecord::Migration
def self.up
#add_column( :programming_languages, :extension, :string, :null => false )
end
def self.down
#remove_column( :programming_languages, :extension )
end
end
| {
"content_hash": "2abfdf947f4bdd0b2e90e3c380907694",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 78,
"avg_line_length": 27.555555555555557,
"alnum_prop": 0.7298387096774194,
"repo_name": "mikehelmick/CascadeLMS",
"id": "e5471879232889ef993358a2c998c15443f37183",
"size": "248",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "db/migrate/038_add_programmming_language_extension.rb",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ApacheConf",
"bytes": "1338"
},
{
"name": "CSS",
"bytes": "62822"
},
{
"name": "HTML",
"bytes": "863454"
},
{
"name": "JavaScript",
"bytes": "354708"
},
{
"name": "Ruby",
"bytes": "1094030"
},
{
"name": "Shell",
"bytes": "861"
}
],
"symlink_target": ""
} |
===========
Development
===========
Tests
-----
To run the test suite, do::
./manage.py test django_easyfilters
This requires that the directory containing the ``django_easyfilters`` directory
is on your Python path (virtualenv recommended), and Django is installed.
Alternatively, to run it on all supported platforms, install tox and do::
tox
This will create all the necessary virtualenvs for you, and is the preferred way
of working, but will take longer initially. Once you have run it once, you can
activate a specific virtualenv by doing, for example::
. .tox/py33-django15/bin/activate
Editing test fixtures
---------------------
To edit the test fixtures, you can edit the fixtures in
django_easyfilters/tests/fixtures/, or you can do it via an admin interface:
First create an empty db::
rm tests.db
./manage.py syncdb
Then load with current test fixture::
./manage.py loaddata django_easyfilters_tests
Then edit in admin at http://localhost:8000/admin/ ::
./manage.py runserver
Or from a Python shell.
Then dump data::
./manage.py dumpdata tests --format=json --indent=2 > django_easyfilters/tests/fixtures/django_easyfilters_tests.json
Demo
----
Once the test fixtures have been loaded into the DB, and the devserver is
running, as above, you can view a test page at http://localhost:8000/books/
| {
"content_hash": "9ef8dad1ca5b5f7932e6529f3a89121d",
"timestamp": "",
"source": "github",
"line_count": 56,
"max_line_length": 119,
"avg_line_length": 24.178571428571427,
"alnum_prop": 0.7259970457902511,
"repo_name": "ionelmc/django-easyfilters",
"id": "99944016cceea7ba539ca1c6059ca4af69a59b25",
"size": "1354",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/develop.rst",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "3388"
},
{
"name": "Python",
"bytes": "108325"
}
],
"symlink_target": ""
} |
/* @flow */
import {
warn,
once,
isDef,
isUndef,
isTrue,
isObject,
hasSymbol
} from 'core/util/index'
import { createEmptyVNode } from 'core/vdom/vnode'
function ensureCtor (comp: any, base) {
if (
comp.__esModule ||
(hasSymbol && comp[Symbol.toStringTag] === 'Module')
) {
comp = comp.default
}
return isObject(comp)
? base.extend(comp)
: comp
}
export function createAsyncPlaceholder (
factory: Function,
data: ?VNodeData,
context: Component,
children: ?Array<VNode>,
tag: ?string
): VNode {
const node = createEmptyVNode()
node.asyncFactory = factory
node.asyncMeta = { data, context, children, tag }
return node
}
export function resolveAsyncComponent (
factory: Function,
baseCtor: Class<Component>,
context: Component
): Class<Component> | void {
if (isTrue(factory.error) && isDef(factory.errorComp)) {
return factory.errorComp
}
if (isDef(factory.resolved)) {
return factory.resolved
}
if (isTrue(factory.loading) && isDef(factory.loadingComp)) {
return factory.loadingComp
}
if (isDef(factory.contexts)) {
// already pending
factory.contexts.push(context)
} else {
const contexts = factory.contexts = [context]
let sync = true
const forceRender = (renderCompleted: boolean) => {
for (let i = 0, l = contexts.length; i < l; i++) {
contexts[i].$forceUpdate()
}
if (renderCompleted) {
contexts.length = 0
}
}
const resolve = once((res: Object | Class<Component>) => {
// cache resolved
factory.resolved = ensureCtor(res, baseCtor)
// invoke callbacks only if this is not a synchronous resolve
// (async resolves are shimmed as synchronous during SSR)
if (!sync) {
forceRender(true)
} else {
contexts.length = 0
}
})
const reject = once(reason => {
process.env.NODE_ENV !== 'production' && warn(
`Failed to resolve async component: ${String(factory)}` +
(reason ? `\nReason: ${reason}` : '')
)
if (isDef(factory.errorComp)) {
factory.error = true
forceRender(true)
}
})
const res = factory(resolve, reject)
if (isObject(res)) {
if (typeof res.then === 'function') {
// () => Promise
if (isUndef(factory.resolved)) {
res.then(resolve, reject)
}
} else if (isDef(res.component) && typeof res.component.then === 'function') {
res.component.then(resolve, reject)
if (isDef(res.error)) {
factory.errorComp = ensureCtor(res.error, baseCtor)
}
if (isDef(res.loading)) {
factory.loadingComp = ensureCtor(res.loading, baseCtor)
if (res.delay === 0) {
factory.loading = true
} else {
setTimeout(() => {
if (isUndef(factory.resolved) && isUndef(factory.error)) {
factory.loading = true
forceRender(false)
}
}, res.delay || 200)
}
}
if (isDef(res.timeout)) {
setTimeout(() => {
if (isUndef(factory.resolved)) {
reject(
process.env.NODE_ENV !== 'production'
? `timeout (${res.timeout}ms)`
: null
)
}
}, res.timeout)
}
}
}
sync = false
// return in case resolved synchronously
return factory.loading
? factory.loadingComp
: factory.resolved
}
}
| {
"content_hash": "36a331b1b1636235fd88757c64c11512",
"timestamp": "",
"source": "github",
"line_count": 146,
"max_line_length": 84,
"avg_line_length": 24.36986301369863,
"alnum_prop": 0.5626756604834177,
"repo_name": "Qinjianbo/blog",
"id": "4dbefd91fbc9357708c0a509cd8c81e468cef60c",
"size": "3558",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "node_modules/vue/src/core/vdom/helpers/resolve-async-component.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Blade",
"bytes": "16961"
},
{
"name": "PHP",
"bytes": "113595"
},
{
"name": "Shell",
"bytes": "702"
},
{
"name": "Vue",
"bytes": "13591"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/mainAppBarLayout1">
<android.support.v7.widget.Toolbar
android:id="@+id/标题栏"
app:elevation="4dp"
android:layout_height="?attr/actionBarSize"
android:layout_width="match_parent"
android:background="?attr/colorPrimary"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
app:layout_scrollFlags="scroll|enterAlways|snap"/>
</android.support.design.widget.AppBarLayout>
<ListView
android:layout_height="match_parent"
android:layout_width="match_parent"
android:id="@+id/jsz_listview"/>
</LinearLayout>
| {
"content_hash": "8868fd42bcadb5f31a7a03a971511c96",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 64,
"avg_line_length": 33.225806451612904,
"alnum_prop": 0.7378640776699029,
"repo_name": "nihaocun/kirbydownload",
"id": "0ca587f040934dc2e4871d4906fd15351420c73f",
"size": "1036",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/res/layout/activity_jsz.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "117698"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<sem:triples uri="http://www.lds.org/vrl/specific-people/latter-day-figures/carlson-vicki-lynn-martens" xmlns:sem="http://marklogic.com/semantics">
<sem:triple>
<sem:subject>http://www.lds.org/vrl/specific-people/latter-day-figures/carlson-vicki-lynn-martens</sem:subject>
<sem:predicate>http://www.w3.org/2004/02/skos/core#prefLabel</sem:predicate>
<sem:object datatype="xsd:string" xml:lang="eng">Carlson, Vicki Lynn Martens</sem:object>
</sem:triple>
<sem:triple>
<sem:subject>http://www.lds.org/vrl/specific-people/latter-day-figures/carlson-vicki-lynn-martens</sem:subject>
<sem:predicate>http://www.w3.org/2004/02/skos/core#inScheme</sem:predicate>
<sem:object datatype="sem:iri">http://www.lds.org/concept-scheme/vrl</sem:object>
</sem:triple>
<sem:triple>
<sem:subject>http://www.lds.org/vrl/specific-people/latter-day-figures/carlson-vicki-lynn-martens</sem:subject>
<sem:predicate>http://www.lds.org/core#entityType</sem:predicate>
<sem:object datatype="sem:iri">http://www.schema.org/Place</sem:object>
</sem:triple>
</sem:triples>
| {
"content_hash": "e64b27ce659715753ab8338766b8e446",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 147,
"avg_line_length": 62.77777777777778,
"alnum_prop": 0.7256637168141593,
"repo_name": "freshie/ml-taxonomies",
"id": "1062f61e66a86551e848571fcd1e7b7487e43351",
"size": "1130",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "roxy/data/gospel-topical-explorer-v2/taxonomies/vrl/specific-people/latter-day-figures/carlson-vicki-lynn-martens.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "4422"
},
{
"name": "CSS",
"bytes": "38665"
},
{
"name": "HTML",
"bytes": "356"
},
{
"name": "JavaScript",
"bytes": "411651"
},
{
"name": "Ruby",
"bytes": "259121"
},
{
"name": "Shell",
"bytes": "7329"
},
{
"name": "XQuery",
"bytes": "857170"
},
{
"name": "XSLT",
"bytes": "13753"
}
],
"symlink_target": ""
} |
import { Express, Request, Response } from 'express';
import * as path from 'path';
/**
* Provides a way to return mock data for URLs that would normally go to the middleware server.
*/
export function configureMockMiddleware(app: Express) {
app.get('/api/registration/status', (req, res: Response) => {
res.sendFile(path.join(__dirname, './mock-middleware-data/registration-status-response.json'));
});
app.get('/api/registration/randompassword_n', (req: Request, res: Response) => {
const num: number = Number(req.query.num);
const passwordList: string[] = [];
for (let i = 1; i <= num; i++) {
passwordList.push('random-' + i);
}
res.json({
"passwords": passwordList
});
});
}
| {
"content_hash": "a61f8f777216ddb8617d03c3d3350448",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 103,
"avg_line_length": 32.541666666666664,
"alnum_prop": 0.6030729833546735,
"repo_name": "MicroFocus/CX",
"id": "8f07aec954614ef92dea9ee05b37f156f1602211",
"size": "781",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "self-registration/build_scripts/mock-middleware.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "122592"
},
{
"name": "Dockerfile",
"bytes": "3597"
},
{
"name": "HTML",
"bytes": "68705"
},
{
"name": "JavaScript",
"bytes": "516067"
},
{
"name": "Jsonnet",
"bytes": "84637"
},
{
"name": "Python",
"bytes": "37887"
},
{
"name": "Shell",
"bytes": "1056"
},
{
"name": "TSQL",
"bytes": "15975"
},
{
"name": "TypeScript",
"bytes": "112259"
}
],
"symlink_target": ""
} |
<?php
/**
* @namespace
*/
namespace Zend\Feed\PubSubHubbub;
/**
* @uses \Zend\Feed\PubSubHubbub\Callback
* @uses \Zend\Feed\PubSubHubbub\Exception
* @uses \Zend\Feed\PubSubHubbub\HttpResponse
* @category Zend
* @package Zend_Feed_Pubsubhubbub
* @subpackage Callback
* @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
abstract class AbstractCallback implements Callback
{
/**
* An instance of Zend_Feed_Pubsubhubbub_Model_SubscriptionPersistence used
* to background save any verification tokens associated with a subscription
* or other.
*
* @var \Zend\Feed\PubSubHubbub\Model\SubscriptionPersistence
*/
protected $_storage = null;
/**
* An instance of a class handling Http Responses. This is implemented in
* Zend\Feed\Pubsubhubbub\HttpResponse which shares an unenforced interface with
* (i.e. not inherited from) Zend\Controller\Response\Http.
*
* @var Zend_Feed_Pubsubhubbub_HttpResponse|\Zend\Controller\Response\Http
*/
protected $_httpResponse = null;
/**
* The number of Subscribers for which any updates are on behalf of.
*
* @var int
*/
protected $_subscriberCount = 1;
/**
* Constructor; accepts an array or Zend\Config instance to preset
* options for the Subscriber without calling all supported setter
* methods in turn.
*
* @param array|\Zend\Config\Config $options Options array or \Zend\Config\Config instance
*/
public function __construct($config = null)
{
if ($config !== null) {
$this->setConfig($config);
}
}
/**
* Process any injected configuration options
*
* @param array|\Zend\Config\Config $options Options array or \Zend\Config\Config instance
* @return \Zend\Feed\PubSubHubbub\AbstractCallback
*/
public function setConfig($config)
{
if ($config instanceof \Zend\Config\Config) {
$config = $config->toArray();
} elseif (!is_array($config)) {
throw new Exception('Array or Zend_Config object'
. 'expected, got ' . gettype($config));
}
if (array_key_exists('storage', $config)) {
$this->setStorage($config['storage']);
}
return $this;
}
/**
* Send the response, including all headers.
* If you wish to handle this via Zend_Controller, use the getter methods
* to retrieve any data needed to be set on your HTTP Response object, or
* simply give this object the HTTP Response instance to work with for you!
*
* @return void
*/
public function sendResponse()
{
$this->getHttpResponse()->sendResponse();
}
/**
* Sets an instance of Zend\Feed\Pubsubhubbub\Model\SubscriptionPersistence used
* to background save any verification tokens associated with a subscription
* or other.
*
* @param \Zend\Feed\PubSubHubbub\Model\SubscriptionPersistence $storage
* @return \Zend\Feed\PubSubHubbub\AbstractCallback
*/
public function setStorage(Model\SubscriptionPersistence $storage)
{
$this->_storage = $storage;
return $this;
}
/**
* Gets an instance of Zend\Feed\Pubsubhubbub\Model\SubscriptionPersistence used
* to background save any verification tokens associated with a subscription
* or other.
*
* @return \Zend\Feed\PubSubHubbub\Model\SubscriptionPersistence
*/
public function getStorage()
{
if ($this->_storage === null) {
throw new Exception('No storage object has been'
. ' set that subclasses Zend\Feed\Pubsubhubbub\Model\SubscriptionPersistence');
}
return $this->_storage;
}
/**
* An instance of a class handling Http Responses. This is implemented in
* Zend\Feed\Pubsubhubbub\HttpResponse which shares an unenforced interface with
* (i.e. not inherited from) Zend\Controller\Response\Http.
*
* @param Zend\Feed\Pubsubhubbub\HttpResponse|\Zend\Controller\Response\Http $httpResponse
* @return \Zend\Feed\PubSubHubbub\AbstractCallback
*/
public function setHttpResponse($httpResponse)
{
if (!is_object($httpResponse)
|| (!$httpResponse instanceof HttpResponse
&& !$httpResponse instanceof \Zend\Controller\Response\Http)
) {
throw new Exception('HTTP Response object must'
. ' implement one of Zend\Feed\Pubsubhubbub\HttpResponse or'
. ' Zend\Controller\Response\Http');
}
$this->_httpResponse = $httpResponse;
return $this;
}
/**
* An instance of a class handling Http Responses. This is implemented in
* Zend\Feed\Pubsubhubbub\HttpResponse which shares an unenforced interface with
* (i.e. not inherited from) Zend\Controller\Response\Http.
*
* @return Zend\Feed\Pubsubhubbub\HttpResponse|\Zend\Controller\Response\Http
*/
public function getHttpResponse()
{
if ($this->_httpResponse === null) {
$this->_httpResponse = new HttpResponse;
}
return $this->_httpResponse;
}
/**
* Sets the number of Subscribers for which any updates are on behalf of.
* In other words, is this class serving one or more subscribers? How many?
* Defaults to 1 if left unchanged.
*
* @param string|int $count
* @return \Zend\Feed\PubSubHubbub\AbstractCallback
*/
public function setSubscriberCount($count)
{
$count = intval($count);
if ($count <= 0) {
throw new Exception('Subscriber count must be'
. ' greater than zero');
}
$this->_subscriberCount = $count;
return $this;
}
/**
* Gets the number of Subscribers for which any updates are on behalf of.
* In other words, is this class serving one or more subscribers? How many?
*
* @return int
*/
public function getSubscriberCount()
{
return $this->_subscriberCount;
}
/**
* Attempt to detect the callback URL (specifically the path forward)
*/
protected function _detectCallbackUrl()
{
$callbackUrl = '';
if (isset($_SERVER['HTTP_X_REWRITE_URL'])) {
$callbackUrl = $_SERVER['HTTP_X_REWRITE_URL'];
} elseif (isset($_SERVER['REQUEST_URI'])) {
$callbackUrl = $_SERVER['REQUEST_URI'];
$scheme = 'http';
if ($_SERVER['HTTPS'] == 'on') {
$scheme = 'https';
}
$schemeAndHttpHost = $scheme . '://' . $this->_getHttpHost();
if (strpos($callbackUrl, $schemeAndHttpHost) === 0) {
$callbackUrl = substr($callbackUrl, strlen($schemeAndHttpHost));
}
} elseif (isset($_SERVER['ORIG_PATH_INFO'])) {
$callbackUrl= $_SERVER['ORIG_PATH_INFO'];
if (!empty($_SERVER['QUERY_STRING'])) {
$callbackUrl .= '?' . $_SERVER['QUERY_STRING'];
}
}
return $callbackUrl;
}
/**
* Get the HTTP host
*
* @return string
*/
protected function _getHttpHost()
{
if (!empty($_SERVER['HTTP_HOST'])) {
return $_SERVER['HTTP_HOST'];
}
$scheme = 'http';
if ($_SERVER['HTTPS'] == 'on') {
$scheme = 'https';
}
$name = $_SERVER['SERVER_NAME'];
$port = $_SERVER['SERVER_PORT'];
if (($scheme == 'http' && $port == 80)
|| ($scheme == 'https' && $port == 443)
) {
return $name;
} else {
return $name . ':' . $port;
}
}
/**
* Retrieve a Header value from either $_SERVER or Apache
*
* @param string $header
*/
protected function _getHeader($header)
{
$temp = strtoupper(str_replace('-', '_', $header));
if (!empty($_SERVER[$temp])) {
return $_SERVER[$temp];
}
$temp = 'HTTP_' . strtoupper(str_replace('-', '_', $header));
if (!empty($_SERVER[$temp])) {
return $_SERVER[$temp];
}
if (function_exists('apache_request_headers')) {
$headers = apache_request_headers();
if (!empty($headers[$header])) {
return $headers[$header];
}
}
return false;
}
/**
* Return the raw body of the request
*
* @return string|false Raw body, or false if not present
*/
protected function _getRawBody()
{
$body = file_get_contents('php://input');
if (strlen(trim($body)) == 0 && isset($GLOBALS['HTTP_RAW_POST_DATA'])) {
$body = $GLOBALS['HTTP_RAW_POST_DATA'];
}
if (strlen(trim($body)) > 0) {
return $body;
}
return false;
}
}
| {
"content_hash": "dbd04191efe1d3b92be2e4a871e6088d",
"timestamp": "",
"source": "github",
"line_count": 282,
"max_line_length": 95,
"avg_line_length": 32.145390070921984,
"alnum_prop": 0.5801434087148373,
"repo_name": "TrafeX/zf2",
"id": "f5b8c32a16c1fec0b7e27ba3a6611957ed82a701",
"size": "9772",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "library/Zend/Feed/PubSubHubbub/AbstractCallback.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
package io.enmasse.systemtest.bases;
import io.enmasse.systemtest.clients.ClientUtils;
import io.enmasse.systemtest.logs.CustomLogger;
import io.enmasse.systemtest.manager.ResourceManager;
import io.enmasse.systemtest.model.address.AddressType;
import io.enmasse.systemtest.model.addressspace.AddressSpaceType;
import io.enmasse.systemtest.platform.Kubernetes;
import org.slf4j.Logger;
public interface ITestBase {
ClientUtils clientUtils = new ClientUtils();
Logger LOGGER = CustomLogger.getLogger();
Kubernetes kubernetes = Kubernetes.getInstance();
default ClientUtils getClientUtils() {
return clientUtils;
}
default AddressSpaceType getAddressSpaceType() {
return null;
}
default String getDefaultPlan(AddressType addressType) {
return null;
}
default String getDefaultAddressSpacePlan() {
return null;
}
default String getDefaultAddrSpaceIdentifier() {
return "default";
}
default ResourceManager getResourceManager() {
return null;
}
}
| {
"content_hash": "ab8e2fca3890925b99252be83948a37a",
"timestamp": "",
"source": "github",
"line_count": 40,
"max_line_length": 65,
"avg_line_length": 26.5,
"alnum_prop": 0.7349056603773585,
"repo_name": "jenmalloy/enmasse",
"id": "b3a925f2d35c54d4d68aa411124accdc82026d14",
"size": "1204",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "systemtests/src/main/java/io/enmasse/systemtest/bases/ITestBase.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "946"
},
{
"name": "Dockerfile",
"bytes": "8306"
},
{
"name": "Go",
"bytes": "1208268"
},
{
"name": "Groovy",
"bytes": "8925"
},
{
"name": "HTML",
"bytes": "3345"
},
{
"name": "Java",
"bytes": "4217294"
},
{
"name": "JavaScript",
"bytes": "922369"
},
{
"name": "Makefile",
"bytes": "23788"
},
{
"name": "Python",
"bytes": "6730"
},
{
"name": "Ragel",
"bytes": "3778"
},
{
"name": "Shell",
"bytes": "73871"
},
{
"name": "TSQL",
"bytes": "2790"
},
{
"name": "TypeScript",
"bytes": "407558"
},
{
"name": "XSLT",
"bytes": "11077"
},
{
"name": "Yacc",
"bytes": "5306"
}
],
"symlink_target": ""
} |
package org.apache.tomcat.util.bcel.classfile;
/**
* Represents a Java class, i.e., the data structures, constant pool,
* fields, methods and commands contained in a Java .class file.
* See <a href="ftp://java.sun.com/docs/specs/">JVM specification</a> for details.
* The intent of this class is to represent a parsed or otherwise existing
* class file. Those interested in programatically generating classes
* should see the <a href="../generic/ClassGen.html">ClassGen</a> class.
* @author <A HREF="mailto:[email protected]">M. Dahm</A>
*/
public class JavaClass {
private final int access_flags;
private final String class_name;
private final String superclass_name;
private final String[] interface_names;
private final Annotations runtimeVisibleAnnotations; // "RuntimeVisibleAnnotations" attribute defined in the class
/**
* Constructor gets all contents as arguments.
*
* @param class_name Name of this class.
* @param superclass_name Name of this class's superclass.
* @param access_flags Access rights defined by bit flags
* @param constant_pool Array of constants
* @param interfaces Implemented interfaces
* @param runtimeVisibleAnnotations "RuntimeVisibleAnnotations" attribute defined on the Class, or null
*/
JavaClass(String class_name, String superclass_name,
int access_flags, ConstantPool constant_pool, String[] interface_names,
Annotations runtimeVisibleAnnotations) {
this.access_flags = access_flags;
this.runtimeVisibleAnnotations = runtimeVisibleAnnotations;
this.class_name = class_name;
this.superclass_name = superclass_name;
this.interface_names = interface_names;
}
/**
* @return Access flags of the object aka. "modifiers".
*/
public final int getAccessFlags() {
return access_flags;
}
/**
* Return annotations entries from "RuntimeVisibleAnnotations" attribute on
* the class, if there is any.
*
* @return An array of entries or {@code null}
*/
public AnnotationEntry[] getAnnotationEntries() {
if (runtimeVisibleAnnotations != null) {
return runtimeVisibleAnnotations.getAnnotationEntries();
}
return null;
}
/**
* @return Class name.
*/
public String getClassName() {
return class_name;
}
/**
* @return Names of implemented interfaces.
*/
public String[] getInterfaceNames() {
return interface_names;
}
/**
* returns the super class name of this class. In the case that this class is
* java.lang.Object, it will return itself (java.lang.Object). This is probably incorrect
* but isn't fixed at this time to not break existing clients.
*
* @return Superclass name.
*/
public String getSuperclassName() {
return superclass_name;
}
}
| {
"content_hash": "543eeb675cfb3958e07941b1b933f864",
"timestamp": "",
"source": "github",
"line_count": 88,
"max_line_length": 118,
"avg_line_length": 33.35227272727273,
"alnum_prop": 0.668824531516184,
"repo_name": "byronka/xenos",
"id": "7e5bd778c15669b71f94bfea333c09d0a7633314",
"size": "3751",
"binary": false,
"copies": "8",
"ref": "refs/heads/master",
"path": "lib/lib_src/apache-tomcat-8.0.14-src/java/org/apache/tomcat/util/bcel/classfile/JavaClass.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "102953"
},
{
"name": "C++",
"bytes": "436"
},
{
"name": "CSS",
"bytes": "482910"
},
{
"name": "HTML",
"bytes": "220459885"
},
{
"name": "Java",
"bytes": "31611126"
},
{
"name": "JavaScript",
"bytes": "19708"
},
{
"name": "NSIS",
"bytes": "38770"
},
{
"name": "PLSQL",
"bytes": "19219"
},
{
"name": "Perl",
"bytes": "23704"
},
{
"name": "Python",
"bytes": "3299"
},
{
"name": "SQLPL",
"bytes": "54633"
},
{
"name": "Shell",
"bytes": "192465"
},
{
"name": "XSLT",
"bytes": "499720"
}
],
"symlink_target": ""
} |
package channelconfig
import (
"fmt"
"github.com/golang/protobuf/proto"
"github.com/hyperledger/fabric/msp"
"github.com/hyperledger/fabric/msp/cache"
mspprotos "github.com/hyperledger/fabric/protos/msp"
"github.com/pkg/errors"
)
type pendingMSPConfig struct {
mspConfig *mspprotos.MSPConfig
msp msp.MSP
}
// MSPConfigHandler
type MSPConfigHandler struct {
version msp.MSPVersion
idMap map[string]*pendingMSPConfig
}
func NewMSPConfigHandler(mspVersion msp.MSPVersion) *MSPConfigHandler {
return &MSPConfigHandler{
version: mspVersion,
idMap: make(map[string]*pendingMSPConfig),
}
}
// ProposeValue called when an org defines an MSP
func (bh *MSPConfigHandler) ProposeMSP(mspConfig *mspprotos.MSPConfig) (msp.MSP, error) {
var theMsp msp.MSP
var err error
switch mspConfig.Type {
case int32(msp.FABRIC):
// create the bccsp msp instance
mspInst, err := msp.New(&msp.BCCSPNewOpts{NewBaseOpts: msp.NewBaseOpts{Version: bh.version}})
if err != nil {
return nil, errors.WithMessage(err, "creating the MSP manager failed")
}
// add a cache layer on top
theMsp, err = cache.New(mspInst)
if err != nil {
return nil, errors.WithMessage(err, "creating the MSP cache failed")
}
case int32(msp.IDEMIX):
// create the idemix msp instance
theMsp, err = msp.New(&msp.IdemixNewOpts{msp.NewBaseOpts{Version: bh.version}})
if err != nil {
return nil, errors.WithMessage(err, "creating the MSP manager failed")
}
default:
return nil, errors.New(fmt.Sprintf("Setup error: unsupported msp type %d", mspConfig.Type))
}
// set it up
err = theMsp.Setup(mspConfig)
if err != nil {
return nil, errors.WithMessage(err, "setting up the MSP manager failed")
}
// add the MSP to the map of pending MSPs
mspID, _ := theMsp.GetIdentifier()
existingPendingMSPConfig, ok := bh.idMap[mspID]
if ok && !proto.Equal(existingPendingMSPConfig.mspConfig, mspConfig) {
return nil, errors.New(fmt.Sprintf("Attempted to define two different versions of MSP: %s", mspID))
}
if !ok {
bh.idMap[mspID] = &pendingMSPConfig{
mspConfig: mspConfig,
msp: theMsp,
}
}
return theMsp, nil
}
func (bh *MSPConfigHandler) CreateMSPManager() (msp.MSPManager, error) {
mspList := make([]msp.MSP, len(bh.idMap))
i := 0
for _, pendingMSP := range bh.idMap {
mspList[i] = pendingMSP.msp
i++
}
manager := msp.NewMSPManager()
err := manager.Setup(mspList)
return manager, err
}
| {
"content_hash": "28ebe5fe6fefb5c0c4cd33d850eaa258",
"timestamp": "",
"source": "github",
"line_count": 96,
"max_line_length": 101,
"avg_line_length": 25.416666666666668,
"alnum_prop": 0.7135245901639344,
"repo_name": "lukehuangch/fabric",
"id": "90d177017042a183c247ae0a79a919d7dfdb7a92",
"size": "2523",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "common/channelconfig/msp.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "937"
},
{
"name": "Gherkin",
"bytes": "43102"
},
{
"name": "Go",
"bytes": "5077668"
},
{
"name": "HTML",
"bytes": "11100"
},
{
"name": "Java",
"bytes": "100958"
},
{
"name": "JavaScript",
"bytes": "116066"
},
{
"name": "Makefile",
"bytes": "21590"
},
{
"name": "Protocol Buffer",
"bytes": "102982"
},
{
"name": "Python",
"bytes": "288066"
},
{
"name": "Ruby",
"bytes": "3701"
},
{
"name": "Shell",
"bytes": "136545"
}
],
"symlink_target": ""
} |
// ----------------------------------------------------------------------------
// Copyright © Aleksey Nemiro, 2016. All rights reserved.
//
// 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.
// ----------------------------------------------------------------------------
using System.ComponentModel;
namespace TwitterExample
{
public delegate void MeadiaUploadEventHandler(object sender, ProgressChangedEventArgs e);
} | {
"content_hash": "7c3b364607ad59e55e2c3ac7823c0faa",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 91,
"avg_line_length": 40.34782608695652,
"alnum_prop": 0.6314655172413793,
"repo_name": "alekseynemiro/nemiro.oauth.dll",
"id": "f00d80c6f6aa45f30012e9d6ede9708902210eca",
"size": "931",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "examples/TwitterExample/MeadiaUploadEventHandler.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "243"
},
{
"name": "C#",
"bytes": "781686"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "1b764dd06ff03a47b2f4f197a2caff72",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "bc39c8a0f688b16a7846dcb30e8a9df0acc23f7a",
"size": "176",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Gentianales/Apocynaceae/Gymnema/Gymnema chalmersii/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<!DOCTYPE html>
<html>
<head>
<title>BrickBreaker</title>
<meta charset="UTF-8">
<meta name="description" content="We remake brickbreaker to see if we can do it.">
<meta name="keywords" content="Justin Pallo, Daniel Randall, BrickBreaker, Brick Breaker, Brick, Breaker, Projects, Danny Randall">
<meta name="author" content="Daniel Randall and Justin Pallo">
<link rel="stylesheet" type="text/css" href="css/main.css"/>
<script src="js/main.js"></script>
</head>
<body>
<canvas id="game"></canvas>
</body>
</html>
| {
"content_hash": "1496384d37ae883d35f991b29a26f9a7",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 139,
"avg_line_length": 31.473684210526315,
"alnum_prop": 0.6153846153846154,
"repo_name": "dgrandall/brickbreaker",
"id": "eb108ec6edbf380f73bedeb910753849f7d07ae6",
"size": "598",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "index.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "233"
},
{
"name": "HTML",
"bytes": "598"
},
{
"name": "JavaScript",
"bytes": "7966"
}
],
"symlink_target": ""
} |
import sys
import argparse
import os
import urllib
import requests
from daypicts import get_picture_url, get_picture_urls
from daypicts import validate_date, gen_dates, picture_type
from daypicts import NoPictureForDate
from daypicts import REMOTE_PICT_BASE_URL, PICT_EXCEPTIONS
FIXTURE_DOC_DIR = 'fixture/docroot/'
FIXTURE_TEMPLATE_POTD_DIR = FIXTURE_DOC_DIR + 'Template-POTD/'
def parse_args(argv):
parser = argparse.ArgumentParser(description=main.__doc__)
date_help = 'YYYY-MM-DD or YYYY-MM or YYYY: year, month and day'
parser.add_argument('date', help=date_help)
parser.add_argument('-u', '--url_only', action='store_true',
help='get picture URLS only')
args = parser.parse_args(argv)
try:
iso_parts = validate_date(args.date)
except ValueError as exc:
print('error:', exc.args[0])
parser.print_usage()
sys.exit(2)
dates = list(gen_dates(iso_parts))
if len(dates) == 1:
print('-> Date: ', dates[0])
else:
fmt = '-> {} days: {}...{}'
print(fmt.format(len(dates), dates[0], dates[-1]))
return dates, args
def save_picture_urls(dates, save_path):
for date in dates:
try:
url = get_picture_url(date)
except NoPictureForDate as exc:
snippet = repr(exc)
else:
snippet = url.replace('http://', 'src="//') + '"'
print(date, end=' ')
print(snippet)
with open(os.path.join(save_path, date), 'w') as fp:
fp.write(snippet)
def save_pictures(dates, save_path, verbose=False):
urls_ok = []
for date, url in get_picture_urls(dates, verbose):
response = requests.get(url)
file_path = os.path.join(save_path,
url.replace(REMOTE_PICT_BASE_URL, ''))
file_path = urllib.parse.unquote(file_path)
octets = response.content
# http://en.wikipedia.org/wiki/Template:POTD/2013-06-15
if date not in PICT_EXCEPTIONS:
assert picture_type(octets) is not None, url
try:
os.makedirs(os.path.dirname(file_path))
except FileExistsError:
pass
with open(file_path, 'wb') as fp:
fp.write(octets)
print(file_path)
return urls_ok
def main(argv):
"""Build test fixture from Wikipedia "POTD" data"""
try:
os.makedirs(FIXTURE_TEMPLATE_POTD_DIR)
except FileExistsError:
pass
dates, args = parse_args(argv)
if args.url_only:
save_picture_urls(dates, FIXTURE_TEMPLATE_POTD_DIR)
else:
save_pictures(dates, FIXTURE_DOC_DIR)
if __name__ == '__main__':
main(sys.argv[1:])
| {
"content_hash": "4af1144db9c51fd8562693d0f4956e3a",
"timestamp": "",
"source": "github",
"line_count": 97,
"max_line_length": 71,
"avg_line_length": 27.917525773195877,
"alnum_prop": 0.5997045790251108,
"repo_name": "oxfordyang2016/learnfluentpython",
"id": "dece76b34bbdff2027f1f9c8104cda66fa6ed1a4",
"size": "2708",
"binary": false,
"copies": "7",
"ref": "refs/heads/master",
"path": "attic/concurrency/wikipedia/build_fixture.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "5651"
},
{
"name": "Java",
"bytes": "3443"
},
{
"name": "JavaScript",
"bytes": "323"
},
{
"name": "Python",
"bytes": "553429"
},
{
"name": "Shell",
"bytes": "946"
}
],
"symlink_target": ""
} |
@interface BlackKeyView : KeyView {
}
- (id)initWithFrame:(CGRect)frame withKey:(int)keyNumber;
@end | {
"content_hash": "abdd4cc1ab0e591412d3e36278d1dd7c",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 57,
"avg_line_length": 15,
"alnum_prop": 0.7238095238095238,
"repo_name": "fracmode/mobilesynth-swift",
"id": "f3885066c6698b9c8cf524b6bce59ecd06c950bc",
"size": "284",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "mobilesynth/Classes/BlackKeyView.h",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
package com.example.npc.myweather2.ui;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.npc.myweather2.R;
import com.example.npc.myweather2.util.BaseActivity;
import com.example.npc.myweather2.util.MyUtil;
public class AboutUsActivity extends BaseActivity implements View.OnClickListener {
private TextView vision;
private TextView update_log;
private TextView contactEmail;
private TextView contactQQ;
private TextView contactWeibo;
private TextView title_licenseTx;
private TextView licenseTx;
private Button backBu_about;
private ImageView icon;
private int count;
private Resources rs;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Build.VERSION.SDK_INT >= 21) {
View decorView = getWindow().getDecorView();
int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
decorView.setSystemUiVisibility(option);
getWindow().setStatusBarColor(Color.TRANSPARENT);
}
setContentView(R.layout.activity_about_us);
init();
String log = "☞天气API-和风天气\n\n☞'生活建议'图标-https://icons8.com\n\n☞默认背景图片-http://www.coolapk.com" +
"\n\n☞'关于我们'图标-http://iconfont.cn\n\n" + "☞高德地图定位服务\n\n";
update_log.setText(log);
backBu_about.setOnClickListener(this);
title_licenseTx.setOnClickListener(this);
contactEmail.setOnClickListener(this);
contactQQ.setOnClickListener(this);
contactWeibo.setOnClickListener(this);
licenseTx.setOnClickListener(this);
icon.setOnClickListener(this);
count = 0;
}
public void onClick(View view) {
Uri uri;
Intent intent;
Bitmap bitmap = BitmapFactory.decodeResource(rs, R.mipmap.ic_catcat);
switch (view.getId()) {
case R.id.licenseTx:
intent = new Intent(AboutUsActivity.this, LicenseActivity.class);
startActivity(intent);
break;
case R.id.title_licenseTx:
intent = new Intent(AboutUsActivity.this, LicenseActivity.class);
startActivity(intent);
break;
case R.id.contactEmail:
uri = Uri.parse("mailto:[email protected]");
intent = new Intent(Intent.ACTION_SENDTO, uri);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
} else {
textCopy(contactEmail.getText().toString());
}
break;
case R.id.contactQQ:
uri = Uri.parse("mqqwpa://im/chat?chat_type=wpa&uin=" + contactQQ.getText().toString());
intent = new Intent(Intent.ACTION_VIEW, uri);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
} else {
textCopy(contactQQ.getText().toString());
}
break;
case R.id.contactWeibo:
uri = Uri.parse("http://m.weibo.cn/u/5872633972");
intent = new Intent(Intent.ACTION_VIEW, uri);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
} else {
textCopy(contactWeibo.getText().toString());
}
break;
case R.id.backBu_about:
finish();
break;
case R.id.icon_about:
switch (count) {
case 0:
bitmap = BitmapFactory.decodeResource(rs, R.mipmap.ic_catangry);
count++;
break;
case 1:
bitmap = BitmapFactory.decodeResource(rs, R.mipmap.ic_catrun);
count++;
break;
case 2:
bitmap = BitmapFactory.decodeResource(rs, R.mipmap.ic_catback);
count++;
break;
case 3:
bitmap = BitmapFactory.decodeResource(rs, R.mipmap.ic_catsweat);
count++;
break;
case 4:
bitmap = BitmapFactory.decodeResource(rs, R.mipmap.ic_catturn);
count++;
break;
case 5:
bitmap = BitmapFactory.decodeResource(rs, R.mipmap.ic_cathead);
count++;
break;
}
break;
}
if (count >= 6)
count = 0;
icon.setImageBitmap(bitmap);
}
public void init() {
backBu_about = (Button) findViewById(R.id.backBu_about);
vision = (TextView) findViewById(R.id.vision);
update_log = (TextView) findViewById(R.id.update_log);
contactEmail = (TextView) findViewById(R.id.contactEmail);
rs = getResources();
contactQQ = (TextView) findViewById(R.id.contactQQ);
contactWeibo = (TextView) findViewById(R.id.contactWeibo);
title_licenseTx = (TextView) findViewById(R.id.title_licenseTx);
licenseTx = (TextView) findViewById(R.id.licenseTx);
icon = (ImageView) findViewById(R.id.icon_about);
}
public void textCopy(String text) {
ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
clipboardManager.setPrimaryClip(ClipData.newPlainText(null, text));
MyUtil.showToast( text + " 已复制到剪切板");
}
}
| {
"content_hash": "1181533b5062c8f06869af98e3c89b6a",
"timestamp": "",
"source": "github",
"line_count": 159,
"max_line_length": 107,
"avg_line_length": 39.42138364779874,
"alnum_prop": 0.5684428844926611,
"repo_name": "dw12278/Raining",
"id": "56a6c4c44f453d113aee99105ce4ebb280679150",
"size": "6356",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/java/com/example/npc/myweather2/ui/AboutUsActivity.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "184278"
}
],
"symlink_target": ""
} |
from numpy import loadtxt, append, array, arange;
from predictors import NaiveBayes;
from pickle import load, dump;
from sys import argv;
import os, urllib, json, time;
os_brack = '/'; #directory separator for os engine is running on
def loadData(datSRC, path, delim, typ):
return loadtxt(path + os_brack + datSRC, delimiter=delim, dtype = typ);
def saveData(data, name, svType,dst = '.'):
f = open( dst + os_brack + name , svType);
f.write(data);
f.close();
def googleSearch(search):
'google search api'
query = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=%s";#search api? free to use
results = urllib.urlopen( query % (search) );
json_res = json.loads( results.read() );
return int(json_res['responseData']['cursor']['estimatedResultCount']); #returns number of estimated search results
def loadClassifier(objFile = 'classifier.pickle', path = '.'):
'loads an already trained classifier. If no classifier is passed as \
parameter then it uses the default path and name'
if os.path.isfile( (path + os_brack + objFile) ):
return load( open(path + os_brack + objFile) );
else:
#print path + os_brack + objFile;
print '\n[!NO CLASSIFIFER IS SAVED YET!]\n'
return None;
def makeClassifier(data):
'trains a classifier with a given training data'
nv = NaiveBayes();
nv.summarizeByClass(data); #train classififer
f = open( 'classifier.pickle', 'wb');
dump(nv, f); #save trained classififer as python pickle
f.close();
return nv; #return trained classififer
def discretizeFreq(frequency, cats = [1250, 4500, 8000, 16000, 35000]):
'categorizes result hits from a google saerch query \
if no categories are passed, it uses the default defined'
#print cats;
for i in range( len(cats) ):
if frequency < cats[i]:
return i+1;
return len(cats)+1;
def discretizeTarget(data, threshold):
rows, cols = data.shape;
for i in range(rows):
if (data[i][-1] >= threshold): data[i][-1] = 1;
else: data[i][-1] = 0;
return data;
def discretizeLang(lang, languages):
index = 1;
for l in languages:
if l == lang:
return index;
index += 1;
return None;
def testClassifier(examples, trnprt, tstprt, size):
trnset = examples[:trnprt];
tstset = examples[tstprt:];
classifier = makeClassifier(trnset);
falses = 0.0;
avgLvl = 0.0;
for e in tstset:
label, prob = classifier.predict( e[:-1] );
avgLvl += prob * 100;
#print 'expected output: %d\t|predicted output: %d\t|confidence lvl: %f' % (label, e[-1], prob);
if (label != e[-1]):
falses += 1;
#print '\n>> Training data dimensions: %d' % ( len(examples[0][:-1]) )
#print '>> Prediction accuracy is: %f' % (1 - falses/(size-trnprt))
#print '>> For %d training examples and %d testing examples' % (len(trnset), len(tstset))
#print '>> Overall data size is %d\n\n' % size;
return (1 - falses/(size-trnprt)), (avgLvl/len(tstset));
def getWordCountDif(txt1, txt2, delim =' '):
return abs( len(txt1.split(delim)) - len(txt2.split(delim)) );
def main():
#setup classifier
thresh = 0.65;
classifier = loadClassifier();
if classifier is None:
path = '..' + os_brack + 'training-data' + os_brack + '3-dimensional';
examples = loadData('data-random.csv' , path, ',', float);
examples = discretizeTarget(examples, thresh);
trnprt = len(examples)/3;
trnset = examples[:trnprt];
classifier = makeClassifier(trnset);
#junk -> name of this python file, not needed but automatically passed by interpreter
#srcTxt -> source text user translated
#dstTxt -> translated text
#srcLng -> language of source txt
#dstTtxt -> language source text was translated to
#srcTxt, dstTxt, srcLng, dstLng = loadData(argv[1], '../input', '\n', str); #use this interface for basic testing
junk, srcTxt, dstTxt, srcLng, dstLng = argv; #use this interface for production
#setup input data
frequency = discretizeFreq( googleSearch(dstTxt) );
wordDif = getWordCountDif(srcTxt, dstTxt);
txtlen = len(srcTxt);
#make prediction
label, prob = classifier.predict( [txtlen, frequency, wordDif] );
prediction = ''; prob *= 100; #convert prob to a percentage
if label == 1: prediction = 'good';
else: prediction = 'bad';
#display prediction
print '\nPredicted translation type: %s' % prediction;
print 'Prediction confidence percentage: %f' % prob;
print 'Classifier\'s word-to-word equivalence threshold percentage %f\n' % (thresh * 100);
if __name__ == '__main__':
main();
#################Code reserved for classifier intensive testing##################
# datOrder = 'random'
# accurDat = '';
# confiDat = '';
# for j in arange(0.5, 1, 0.1): #threashold increases
# for k in arange(2.0,6): #training data decreases
# accurDat += '%f %f ' % ((1/k), j);
# confiDat += '%f %f ' % ((1/k), j);
# for i in range(1,4): #dimensions increase
# path = '..' + os_brack +'training-data' + os_brack + '%d-dimensional' % (i+1);
# examples = loadData('data-%s.csv' % datOrder, path, ',', float);
# examples = discretizeTarget(examples, j);
# size = len(examples);
# trnprt = size/k;
# tstprt = trnprt;
# accuracy, confidence = testClassifier(examples, trnprt, tstprt, size);
# accurDat += '%f ' % (accuracy);
# confiDat += '%f ' % (confidence);
# accurDat += '\n';
# confiDat += '\n';
# saveData(accurDat, ('acur-%s.dat' % datOrder), 'w');
# saveData(confiDat, ('conf-%s.dat' % datOrder), 'w');
# print 'data organization is %s\n' % datOrder; | {
"content_hash": "1dd4a1fa239bb84a1b96c09bcaf68eaf",
"timestamp": "",
"source": "github",
"line_count": 155,
"max_line_length": 116,
"avg_line_length": 34.81290322580645,
"alnum_prop": 0.6643810229799851,
"repo_name": "parejadan/accurp-engine",
"id": "88e651a0d9357652ab9faa41968432dbc4cebcc8",
"size": "5414",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/engine.py",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "11303"
}
],
"symlink_target": ""
} |
<html>
<head>
<title>PxObstacle Class Reference</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<LINK HREF="NVIDIA.css" REL="stylesheet" TYPE="text/css">
</head>
<body bgcolor="#FFFFFF">
<div id="header">
<hr class="first">
<img alt="" src="images/PhysXlogo.png" align="middle"> <br>
<center>
<a class="qindex" href="main.html">Main Page</a>
<a class="qindex" href="hierarchy.html">Class Hierarchy</a>
<a class="qindex" href="annotated.html">Compound List</a>
<a class="qindex" href="functions.html">Compound Members</a>
</center>
<hr class="second">
</div>
<!-- Generated by Doxygen 1.8.3.1 -->
</div><!-- top -->
<div class="header">
<div class="summary">
<a href="#pub-methods">Public Member Functions</a> |
<a href="#pub-attribs">Public Attributes</a> |
<a href="#pro-methods">Protected Member Functions</a> |
<a href="#pro-attribs">Protected Attributes</a> |
<a href="classPxObstacle-members.html">List of all members</a> </div>
<div class="headertitle">
<div class="title">PxObstacle Class Reference<div class="ingroups"><a class="el" href="group__character.html">Character</a></div></div> </div>
</div><!--header-->
<div class="contents">
<p>Base class for obstacles.
<a href="classPxObstacle.html#details">More...</a></p>
<p><code>#include <<a class="el" href="PxControllerObstacles_8h_source.html">PxControllerObstacles.h</a>></code></p>
<div class="dynheader">
Inheritance diagram for PxObstacle:</div>
<div class="dyncontent">
<div class="center"><img src="classPxObstacle__inherit__graph.png" border="0" usemap="#PxObstacle_inherit__map" alt="Inheritance graph"/></div>
<map name="PxObstacle_inherit__map" id="PxObstacle_inherit__map">
</map>
<center><span class="legend">[<a href="graph_legend.html">legend</a>]</span></center></div>
<div class="dynheader">
Collaboration diagram for PxObstacle:</div>
<div class="dyncontent">
<div class="center"><img src="classPxObstacle__coll__graph.png" border="0" usemap="#PxObstacle_coll__map" alt="Collaboration graph"/></div>
<map name="PxObstacle_coll__map" id="PxObstacle_coll__map">
</map>
<center><span class="legend">[<a href="graph_legend.html">legend</a>]</span></center></div>
<table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pub-methods"></a>
Public Member Functions</h2></td></tr>
<tr class="memitem:a7cf9794dae4affdf3fecdf93fdae82f4"><td class="memItemLeft" align="right" valign="top"><a class="el" href="group__foundation.html#ga6a774eed3cad34b0f636332a3d28c6bb">PX_FORCE_INLINE</a> <br class="typebreak"/>
<a class="el" href="structPxGeometryType.html#aefc79f72c4c479192ac19d41a6f30ed5">PxGeometryType::Enum</a> </td><td class="memItemRight" valign="bottom"><a class="el" href="classPxObstacle.html#a7cf9794dae4affdf3fecdf93fdae82f4">getType</a> () const </td></tr>
<tr class="separator:a7cf9794dae4affdf3fecdf93fdae82f4"><td class="memSeparator" colspan="2"> </td></tr>
</table><table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pub-attribs"></a>
Public Attributes</h2></td></tr>
<tr class="memitem:a28876b57c2615b1a7f9c4c294beae29e"><td class="memItemLeft" align="right" valign="top">void * </td><td class="memItemRight" valign="bottom"><a class="el" href="classPxObstacle.html#a28876b57c2615b1a7f9c4c294beae29e">mUserData</a></td></tr>
<tr class="separator:a28876b57c2615b1a7f9c4c294beae29e"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a38a6e859d30d4a9ca9f8e9e5c7f640fa"><td class="memItemLeft" align="right" valign="top"><a class="el" href="structPxExtendedVec3.html">PxExtendedVec3</a> </td><td class="memItemRight" valign="bottom"><a class="el" href="classPxObstacle.html#a38a6e859d30d4a9ca9f8e9e5c7f640fa">mPos</a></td></tr>
<tr class="separator:a38a6e859d30d4a9ca9f8e9e5c7f640fa"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a2cb5e36de356b0efaa65723eb71bf0c3"><td class="memItemLeft" align="right" valign="top"><a class="el" href="classPxQuat.html">PxQuat</a> </td><td class="memItemRight" valign="bottom"><a class="el" href="classPxObstacle.html#a2cb5e36de356b0efaa65723eb71bf0c3">mRot</a></td></tr>
<tr class="separator:a2cb5e36de356b0efaa65723eb71bf0c3"><td class="memSeparator" colspan="2"> </td></tr>
</table><table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pro-methods"></a>
Protected Member Functions</h2></td></tr>
<tr class="memitem:a5d833a794c92cf49451ca56cc0a82ba6"><td class="memItemLeft" align="right" valign="top"> </td><td class="memItemRight" valign="bottom"><a class="el" href="classPxObstacle.html#a5d833a794c92cf49451ca56cc0a82ba6">PxObstacle</a> ()</td></tr>
<tr class="separator:a5d833a794c92cf49451ca56cc0a82ba6"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a1a51f63f502f8d34badc6a6519b5c9bf"><td class="memItemLeft" align="right" valign="top"> </td><td class="memItemRight" valign="bottom"><a class="el" href="classPxObstacle.html#a1a51f63f502f8d34badc6a6519b5c9bf">~PxObstacle</a> ()</td></tr>
<tr class="separator:a1a51f63f502f8d34badc6a6519b5c9bf"><td class="memSeparator" colspan="2"> </td></tr>
</table><table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pro-attribs"></a>
Protected Attributes</h2></td></tr>
<tr class="memitem:aa590cde0ccabd81504049b2ae8718962"><td class="memItemLeft" align="right" valign="top"><a class="el" href="structPxGeometryType.html#aefc79f72c4c479192ac19d41a6f30ed5">PxGeometryType::Enum</a> </td><td class="memItemRight" valign="bottom"><a class="el" href="classPxObstacle.html#aa590cde0ccabd81504049b2ae8718962">mType</a></td></tr>
<tr class="separator:aa590cde0ccabd81504049b2ae8718962"><td class="memSeparator" colspan="2"> </td></tr>
</table>
<a name="details" id="details"></a><h2 class="groupheader">Detailed Description</h2>
<div class="textblock"><p>Base class for obstacles. </p>
<dl class="section see"><dt>See Also</dt><dd><a class="el" href="classPxBoxObstacle.html" title="A box obstacle.">PxBoxObstacle</a> <a class="el" href="classPxCapsuleObstacle.html" title="A capsule obstacle.">PxCapsuleObstacle</a> <a class="el" href="classPxObstacleContext.html" title="Context class for obstacles.">PxObstacleContext</a> </dd></dl>
</div><h2 class="groupheader">Constructor & Destructor Documentation</h2>
<a class="anchor" id="a5d833a794c92cf49451ca56cc0a82ba6"></a>
<div class="memitem">
<div class="memproto">
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname">PxObstacle::PxObstacle </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td></td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">inline</span><span class="mlabel">protected</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
</div>
</div>
<a class="anchor" id="a1a51f63f502f8d34badc6a6519b5c9bf"></a>
<div class="memitem">
<div class="memproto">
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname">PxObstacle::~PxObstacle </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td></td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">inline</span><span class="mlabel">protected</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
</div>
</div>
<h2 class="groupheader">Member Function Documentation</h2>
<a class="anchor" id="a7cf9794dae4affdf3fecdf93fdae82f4"></a>
<div class="memitem">
<div class="memproto">
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname"><a class="el" href="group__foundation.html#ga6a774eed3cad34b0f636332a3d28c6bb">PX_FORCE_INLINE</a> <a class="el" href="structPxGeometryType.html#aefc79f72c4c479192ac19d41a6f30ed5">PxGeometryType::Enum</a> PxObstacle::getType </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td> const</td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">inline</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
</div>
</div>
<h2 class="groupheader">Member Data Documentation</h2>
<a class="anchor" id="a38a6e859d30d4a9ca9f8e9e5c7f640fa"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname"><a class="el" href="structPxExtendedVec3.html">PxExtendedVec3</a> PxObstacle::mPos</td>
</tr>
</table>
</div><div class="memdoc">
</div>
</div>
<a class="anchor" id="a2cb5e36de356b0efaa65723eb71bf0c3"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname"><a class="el" href="classPxQuat.html">PxQuat</a> PxObstacle::mRot</td>
</tr>
</table>
</div><div class="memdoc">
</div>
</div>
<a class="anchor" id="aa590cde0ccabd81504049b2ae8718962"></a>
<div class="memitem">
<div class="memproto">
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname"><a class="el" href="structPxGeometryType.html#aefc79f72c4c479192ac19d41a6f30ed5">PxGeometryType::Enum</a> PxObstacle::mType</td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">protected</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
</div>
</div>
<a class="anchor" id="a28876b57c2615b1a7f9c4c294beae29e"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">void* PxObstacle::mUserData</td>
</tr>
</table>
</div><div class="memdoc">
</div>
</div>
<hr/>The documentation for this class was generated from the following file:<ul>
<li><a class="el" href="PxControllerObstacles_8h_source.html">PxControllerObstacles.h</a></li>
</ul>
</div><!-- contents -->
<hr style="width: 100%; height: 2px;"><br>
Copyright © 2008-2015 NVIDIA Corporation, 2701 San Tomas Expressway, Santa Clara, CA 95050 U.S.A. All rights reserved. <a href="http://www.nvidia.com ">www.nvidia.com</a>
</body>
</html>
| {
"content_hash": "0913e29538492826e0e13924ba648706",
"timestamp": "",
"source": "github",
"line_count": 218,
"max_line_length": 357,
"avg_line_length": 48.31651376146789,
"alnum_prop": 0.684515332763695,
"repo_name": "LiangYue1981816/CrossEngine",
"id": "8e403e19f92f55e157451d3f12f88b4c39d33db5",
"size": "10533",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "PhysX-3.3/PhysXSDK/Documentation/PhysXAPI/files/classPxObstacle.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "30761"
},
{
"name": "C",
"bytes": "84933432"
},
{
"name": "C++",
"bytes": "92458842"
},
{
"name": "CMake",
"bytes": "10937"
},
{
"name": "Cuda",
"bytes": "319314"
},
{
"name": "GLSL",
"bytes": "108168"
},
{
"name": "HTML",
"bytes": "174058"
},
{
"name": "Java",
"bytes": "563"
},
{
"name": "LLVM",
"bytes": "3292"
},
{
"name": "Makefile",
"bytes": "7764848"
},
{
"name": "Objective-C",
"bytes": "304372"
},
{
"name": "Objective-C++",
"bytes": "90267"
},
{
"name": "PAWN",
"bytes": "15882"
},
{
"name": "R",
"bytes": "14754"
},
{
"name": "Shell",
"bytes": "14659"
},
{
"name": "Visual Basic",
"bytes": "3046"
}
],
"symlink_target": ""
} |
import * as React from 'react'
import {
Dialog,
DialogContent,
DialogFooter,
DefaultDialogFooter,
} from '../dialog'
import { Dispatcher } from '../dispatcher'
import {
RepositoryWithGitHubRepository,
isRepositoryWithForkedGitHubRepository,
} from '../../models/repository'
import { OkCancelButtonGroup } from '../dialog/ok-cancel-button-group'
import { sendNonFatalException } from '../../lib/helpers/non-fatal-exception'
import { Account } from '../../models/account'
import { API } from '../../lib/api'
import { LinkButton } from '../lib/link-button'
import { PopupType } from '../../models/popup'
interface ICreateForkDialogProps {
readonly dispatcher: Dispatcher
readonly repository: RepositoryWithGitHubRepository
readonly account: Account
readonly onDismissed: () => void
}
interface ICreateForkDialogState {
readonly loading: boolean
readonly error?: Error
}
/**
* Dialog offering to create a fork of the given repository
*/
export class CreateForkDialog extends React.Component<
ICreateForkDialogProps,
ICreateForkDialogState
> {
public constructor(props: ICreateForkDialogProps) {
super(props)
this.state = { loading: false }
}
/**
* Starts fork process on GitHub!
*/
private onSubmit = async () => {
this.setState({ loading: true })
const { gitHubRepository } = this.props.repository
const api = API.fromAccount(this.props.account)
try {
const fork = await api.forkRepository(
gitHubRepository.owner.login,
gitHubRepository.name
)
this.props.dispatcher.recordForkCreated()
const updatedRepository =
await this.props.dispatcher.convertRepositoryToFork(
this.props.repository,
fork
)
this.setState({ loading: false })
this.props.onDismissed()
if (isRepositoryWithForkedGitHubRepository(updatedRepository)) {
this.props.dispatcher.showPopup({
type: PopupType.ChooseForkSettings,
repository: updatedRepository,
})
}
} catch (e) {
log.error(`Fork creation through API failed (${e})`)
sendNonFatalException('forkCreation', e)
this.setState({ error: e, loading: false })
}
}
public render() {
return (
<Dialog
title="Do you want to fork this repository?"
onDismissed={this.props.onDismissed}
onSubmit={this.state.error ? undefined : this.onSubmit}
dismissable={!this.state.loading}
loading={this.state.loading}
type={this.state.error ? 'error' : 'normal'}
key={this.props.repository.name}
id="create-fork"
>
{this.state.error !== undefined
? renderCreateForkDialogError(
this.props.repository,
this.props.account,
this.state.error
)
: renderCreateForkDialogContent(
this.props.repository,
this.props.account,
this.state.loading
)}
</Dialog>
)
}
}
/** Standard (non-error) message and buttons for `CreateForkDialog` */
function renderCreateForkDialogContent(
repository: RepositoryWithGitHubRepository,
account: Account,
loading: boolean
) {
return (
<>
<DialogContent>
<p>
{`It looks like you don’t have write access to `}
<strong>{repository.gitHubRepository.fullName}</strong>
{`. If you should, please check with a repository administrator.`}
</p>
<p>
{` Do you want to create a fork of this repository at `}
<strong>
{`${account.login}/${repository.gitHubRepository.name}`}
</strong>
{` to continue?`}
</p>
</DialogContent>
<DialogFooter>
<OkCancelButtonGroup
destructive={true}
okButtonText={
__DARWIN__ ? 'Fork This Repository' : 'Fork this repository'
}
okButtonDisabled={loading}
cancelButtonDisabled={loading}
/>
</DialogFooter>
</>
)
}
/** Error state message (and buttons) for `CreateForkDialog` */
function renderCreateForkDialogError(
repository: RepositoryWithGitHubRepository,
account: Account,
error: Error
) {
const suggestion =
repository.gitHubRepository.htmlURL !== null ? (
<>
{`You can try `}
<LinkButton uri={repository.gitHubRepository.htmlURL}>
creating the fork manually on GitHub
</LinkButton>
.
</>
) : undefined
return (
<>
<DialogContent>
<div>
{`Creating your fork `}
<strong>
{`${account.login}/${repository.gitHubRepository.name}`}
</strong>
{` failed. `}
{suggestion}
</div>
<details>
<summary>Error details</summary>
<pre className="error">{error.message}</pre>
</details>
</DialogContent>
<DefaultDialogFooter />
</>
)
}
| {
"content_hash": "508cc262ccc9c397564d4c9fa970ff98",
"timestamp": "",
"source": "github",
"line_count": 176,
"max_line_length": 77,
"avg_line_length": 28.289772727272727,
"alnum_prop": 0.6149829282988551,
"repo_name": "desktop/desktop",
"id": "30490ffba933764b6205575d3cfc2809b1870c33",
"size": "4981",
"binary": false,
"copies": "2",
"ref": "refs/heads/development",
"path": "app/src/ui/forks/create-fork-dialog.tsx",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "116"
},
{
"name": "CSS",
"bytes": "9585"
},
{
"name": "HTML",
"bytes": "141"
},
{
"name": "JavaScript",
"bytes": "22770"
},
{
"name": "PowerShell",
"bytes": "1447"
},
{
"name": "SCSS",
"bytes": "267730"
},
{
"name": "Shell",
"bytes": "4612"
},
{
"name": "TypeScript",
"bytes": "4454417"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.