text
stringlengths 2
1.04M
| meta
dict |
---|---|
namespace makuappu{
export class IconForm extends ComponentForm{
constructor(){
super();
// group main
let groupMain: GroupField = new GroupField();
groupMain.name = "Main";
groupMain.fields.push(new InputText("mainWidth", "width"));
groupMain.fields.push(new InputText("mainHeight", "height"));
groupMain.fields.push(new InputText("mainMinWidth", "min width"));
groupMain.fields.push(new InputText("mainScale", "scale"));
groupMain.fields.push(new InputText("mainPadding", "padding"));
this.groups.push(groupMain);
//
this.skinElements = ["main","mainOver"];
}
}
} | {
"content_hash": "5958fed3a0298652a495fbec316cb142",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 78,
"avg_line_length": 32.64,
"alnum_prop": 0.5159313725490197,
"repo_name": "ruihbanki/makuappu",
"id": "db28e9f03340934ed1bc696dc8216af0aa99d4a3",
"size": "874",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "makuappu-icon/src/makuappu/IconForm.ts",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "JavaScript",
"bytes": "287083"
},
{
"name": "TypeScript",
"bytes": "266589"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "b45ca830ac6e487b2ba53a07da6ae308",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "c7a631a44637c499ed3ac7097926f226f74fc58d",
"size": "179",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Culcitium albifolium/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
package org.apache.lucene.search;
import java.io.IOException;
import org.apache.lucene.index.*;
abstract class PhraseScorer extends Scorer {
private Weight weight;
protected byte[] norms;
protected float value;
private boolean firstTime = true;
private boolean more = true;
protected PhraseQueue pq;
protected PhrasePositions first, last;
private float freq;
PhraseScorer(Weight weight, TermPositions[] tps, int[] positions, Similarity similarity,
byte[] norms) {
super(similarity);
this.norms = norms;
this.weight = weight;
this.value = weight.getValue();
// convert tps to a list
for (int i = 0; i < tps.length; i++) {
PhrasePositions pp = new PhrasePositions(tps[i], positions[i]);
if (last != null) { // add next to end of list
last.next = pp;
} else
first = pp;
last = pp;
}
pq = new PhraseQueue(tps.length); // construct empty pq
}
public int doc() { return first.doc; }
public boolean next() throws IOException {
if (firstTime) {
init();
firstTime = false;
} else if (more) {
more = last.next(); // trigger further scanning
}
return doNext();
}
// next without initial increment
private boolean doNext() throws IOException {
while (more) {
while (more && first.doc < last.doc) { // find doc w/ all the terms
more = first.skipTo(last.doc); // skip first upto last
firstToLast(); // and move it to the end
}
if (more) {
// found a doc with all of the terms
freq = phraseFreq(); // check for phrase
if (freq == 0.0f) // no match
more = last.next(); // trigger further scanning
else
return true; // found a match
}
}
return false; // no more matches
}
public float score() throws IOException {
//System.out.println("scoring " + first.doc);
float raw = getSimilarity().tf(freq) * value; // raw score
return raw * Similarity.decodeNorm(norms[first.doc]); // normalize
}
public boolean skipTo(int target) throws IOException {
for (PhrasePositions pp = first; more && pp != null; pp = pp.next) {
more = pp.skipTo(target);
}
if (more)
sort(); // re-sort
return doNext();
}
protected abstract float phraseFreq() throws IOException;
private void init() throws IOException {
for (PhrasePositions pp = first; more && pp != null; pp = pp.next)
more = pp.next();
if(more)
sort();
}
private void sort() {
pq.clear();
for (PhrasePositions pp = first; pp != null; pp = pp.next)
pq.put(pp);
pqToList();
}
protected final void pqToList() {
last = first = null;
while (pq.top() != null) {
PhrasePositions pp = (PhrasePositions) pq.pop();
if (last != null) { // add next to end of list
last.next = pp;
} else
first = pp;
last = pp;
pp.next = null;
}
}
protected final void firstToLast() {
last.next = first; // move first to end of list
last = first;
first = first.next;
last.next = null;
}
public Explanation explain(final int doc) throws IOException {
Explanation tfExplanation = new Explanation();
while (next() && doc() < doc) {}
float phraseFreq = (doc() == doc) ? freq : 0.0f;
tfExplanation.setValue(getSimilarity().tf(phraseFreq));
tfExplanation.setDescription("tf(phraseFreq=" + phraseFreq + ")");
return tfExplanation;
}
public String toString() { return "scorer(" + weight + ")"; }
}
| {
"content_hash": "aafb4e6d6e6a687cfdc3870d340ef60d",
"timestamp": "",
"source": "github",
"line_count": 140,
"max_line_length": 90,
"avg_line_length": 27.35,
"alnum_prop": 0.5625489683990598,
"repo_name": "lpxz/grail-lucene358684",
"id": "311b20e5122f62870fb52f4539566aa4a1b3bc99",
"size": "4443",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/java/org/apache/lucene/search/PhraseScorer.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C++",
"bytes": "5884"
},
{
"name": "CSS",
"bytes": "461"
},
{
"name": "HTML",
"bytes": "88327"
},
{
"name": "Java",
"bytes": "2068869"
},
{
"name": "JavaScript",
"bytes": "18776"
},
{
"name": "Makefile",
"bytes": "3991"
},
{
"name": "Shell",
"bytes": "363"
}
],
"symlink_target": ""
} |
/**
*
* @author xiaoping ([email protected])
* @type js
*
*/
const
koa = require('koa'),
onerror = require('koa-onerror'),
cors = require('koa-cors'),
requestLog = require('./middlewares/requestLog'),
execTime = require('./middlewares/execTime'),
api = require('./routes/api'),
config = require('./config'),
logger = require('./common/logger'),
app = koa()
onerror(app)
app.use(cors({
credentials: true,
})) // cors
// log execution time
app.use(execTime)
// log request
app.use(requestLog)
api.forEach((route) => {
app.use(route.routes())
app.use(route.allowedMethods())
})
// app.use(router.routes())
app.on('error', (err, ctx) => {
logger.error('server error', err, ctx)
})
app.listen(config.port, () => {
logger.log('server listening on port', config.port)
logger.log('')
})
| {
"content_hash": "428b72ba36051e704694237f31b82b29",
"timestamp": "",
"source": "github",
"line_count": 42,
"max_line_length": 53,
"avg_line_length": 19.571428571428573,
"alnum_prop": 0.6326034063260341,
"repo_name": "excaliburhan/api-es6",
"id": "d4a1cc45f01c7af4798005ec82f6d7209606a899",
"size": "822",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/app.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "246"
},
{
"name": "Makefile",
"bytes": "850"
}
],
"symlink_target": ""
} |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr"
lang="fr" dir="ltr">
<!-- Mirrored from 2012.pgday.fr/utilisation_de_foreign_data_wrappers_dans_differents_contextes?do=index by HTTrack Website Copier/3.x [XR&CO'2014], Mon, 17 Apr 2017 07:27:17 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=utf-8" /><!-- /Added by HTTrack -->
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>
Utilisation de foreign data wrappers dans différents contextes [PostgreSQL Day France 2012]
</title>
<meta name="generator" content="DokuWiki"/>
<meta name="robots" content="noindex,nofollow"/>
<link rel="search" type="application/opensearchdescription+xml" href="http://2012.pgday.fr/lib/exe/opensearch.php" title="PostgreSQL Day France 2012"/>
<link rel="start" href="http://2012.pgday.fr/"/>
<link rel="contents" href="http://2012.pgday.fr/utilisation_de_foreign_data_wrappers_dans_differents_contextes?do=index" title="Index"/>
<link rel="alternate" type="application/rss+xml" title="Recent Changes" href="http://2012.pgday.fr/feed.php"/>
<link rel="alternate" type="application/rss+xml" title="Current Namespace" href="http://2012.pgday.fr/feed.php?mode=list&ns="/>
<link rel="alternate" type="text/html" title="Plain HTML" href="http://2012.pgday.fr/_export/xhtml/utilisation_de_foreign_data_wrappers_dans_differents_contextes"/>
<link rel="alternate" type="text/plain" title="Wiki Markup" href="http://2012.pgday.fr/_export/raw/utilisation_de_foreign_data_wrappers_dans_differents_contextes"/>
<link rel="stylesheet" type="text/css" href="http://2012.pgday.fr/lib/exe/css.php?t=pgday&tseed=1368603377"/>
<script type="text/javascript">/*<![CDATA[*/var NS='';var JSINFO = {"id":"utilisation_de_foreign_data_wrappers_dans_differents_contextes","namespace":""};
/*!]]>*/</script>
<script type="text/javascript" charset="utf-8" src="http://2012.pgday.fr/lib/exe/js.php?tseed=1368603377"></script>
<script type="text/javascript" src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php/fr_FR"></script>
<script type="text/javascript">/*<![CDATA[*/FB.init("9ec02de6127d88bbcc6103da6a44a6b0");
/*!]]>*/</script>
<link rel="shortcut icon" href="http://2012.pgday.fr/lib/tpl/pgday/images/favicon.ico" />
<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
var pageTracker = _gat._getTracker("UA-1345454-8");
pageTracker._initData();
pageTracker._trackPageview();
</script>
</head>
<body>
<div class="dokuwiki">
<div class="header">
<div id="top"><div id="pgHeader">
<span id="pgHeaderLogoLeft">
<a href="http://2012.pgday.fr/" title="European PGDay"><img src="http://2012.pgday.fr/lib/tpl/pgday/images/hdr_left.png" width="230" height="80" alt="PostgreSQL" /></a>
</span>
<span id="pgHeaderLogoRight">
<a href="http://2012.pgday.fr/" title="European PGDay, 6-7 nov 2009"><img src="http://2012.pgday.fr/lib/tpl/pgday/images/hdr_right.png" width="210" height="80" /></a>
</span>
</div></div>
</div><!-- end of header -->
<div id="nav">
<div class="flp">
<ul>
<li class="level1"><div class="li"> <span class="curid"><a href="http://2012.pgday.fr/start" class="wikilink1" title="start">Accueil</a></span> |</div>
</li>
<li class="level1"><div class="li"> <a href="http://2012.pgday.fr/inscriptions" class="wikilink1" title="inscriptions">Inscriptions</a> |</div>
</li>
<li class="level1"><div class="li"> <a href="http://2012.pgday.fr/programme" class="wikilink1" title="programme">Programme</a> |</div>
</li>
<li class="level1"><div class="li"> <a href="http://2012.pgday.fr/sponsors" class="wikilink1" title="sponsors">Sponsors</a> | </div>
</li>
<li class="level1"><div class="li"> <a href="http://2012.pgday.fr/participez" class="wikilink1" title="participez">Participer</a> |</div>
</li>
<li class="level1"><div class="li"> <a href="http://2012.pgday.fr/contact" class="wikilink1" title="contact">Contact</a></div>
</li>
</ul>
</div>
<div class="cb"></div>
</div>
<!-- end of nav -->
<div class="colmask threecol">
<div class="colmid">
<div class="colleft">
<div class="colone">
<!-- Column 1 start -->
<div class="page">
<!-- wikipage start -->
<h1 class="sectionedit1" id="plan_du_site">Plan du site</h1>
<div class="level1">
<p>
Voici un plan du site de toutes les pages disponibles, triées par <a href="http://www.dokuwiki.org/fr%3Anamespaces" class="interwiki iw_doku" title="http://www.dokuwiki.org/fr%3Anamespaces">catégories</a>.
</p>
</div>
<div id="index__tree">
<ul class="idx">
<li class="closed"><div class="li"><a href="http://2012.pgday.fr/utilisation_de_foreign_data_wrappers_dans_differents_contextes?idx=old" title="old" class="idx_dir"><strong>old</strong></a></div></li>
<li class="closed"><div class="li"><a href="http://2012.pgday.fr/utilisation_de_foreign_data_wrappers_dans_differents_contextes?idx=wiki" title="wiki" class="idx_dir"><strong>wiki</strong></a></div></li>
<li class="level1"><div class="li"><a href="http://2012.pgday.fr/appel_a_orateurs" class="wikilink1" title="appel_a_orateurs">Appel à Orateurs</a></div></li>
<li class="level1"><div class="li"><a href="http://2012.pgday.fr/banners" class="wikilink1" title="banners">Banners</a></div></li>
<li class="level1"><div class="li"><a href="http://2012.pgday.fr/benchmark_tsung_pour_postgresql" class="wikilink1" title="benchmark_tsung_pour_postgresql">Benchmark Tsung pour PostgreSQL</a></div></li>
<li class="level1"><div class="li"><a href="http://2012.pgday.fr/boxes" class="wikilink1" title="boxes">boxes</a></div></li>
<li class="level1"><div class="li"><a href="http://2012.pgday.fr/call_for_papers" class="wikilink1" title="call_for_papers">PG Day France: Call for papers</a></div></li>
<li class="level1"><div class="li"><a href="http://2012.pgday.fr/campagne_de_partenariat" class="wikilink1" title="campagne_de_partenariat">Campagne de partenariat</a></div></li>
<li class="level1"><div class="li"><a href="http://2012.pgday.fr/contact" class="wikilink1" title="contact">Contact</a></div></li>
<li class="level1"><div class="li"><a href="http://2012.pgday.fr/disponibilite_et_durabilite_architectures_et_replications" class="wikilink1" title="disponibilite_et_durabilite_architectures_et_replications">Disponibilité et Durabilité : Architectures et Réplications</a></div></li>
<li class="level1"><div class="li"><a href="http://2012.pgday.fr/e-maj_..._par_l_image" class="wikilink1" title="e-maj_..._par_l_image">E-Maj ... par l'image</a></div></li>
<li class="level1"><div class="li"><a href="http://2012.pgday.fr/hotels" class="wikilink1" title="hotels">Hôtels</a></div></li>
<li class="level1"><div class="li"><a href="http://2012.pgday.fr/inscriptions" class="wikilink1" title="inscriptions">Inscriptions</a></div></li>
<li class="level1"><div class="li"><a href="http://2012.pgday.fr/maps" class="wikilink1" title="maps">Maps</a></div></li>
<li class="level1"><div class="li"><a href="http://2012.pgday.fr/nav" class="wikilink1" title="nav">nav</a></div></li>
<li class="level1"><div class="li"><a href="http://2012.pgday.fr/participez" class="wikilink1" title="participez">Participer</a></div></li>
<li class="level1"><div class="li"><a href="http://2012.pgday.fr/partners" class="wikilink1" title="partners">Partenaires Gold</a></div></li>
<li class="level1"><div class="li"><a href="http://2012.pgday.fr/plan" class="wikilink1" title="plan">Plan d'accès</a></div></li>
<li class="level1"><div class="li"><a href="http://2012.pgday.fr/postgis_2.0_la_geo_nouvelle_generation" class="wikilink1" title="postgis_2.0_la_geo_nouvelle_generation">PostGIS 2.0 : la géo nouvelle génération</a></div></li>
<li class="level1"><div class="li"><a href="http://2012.pgday.fr/postgresql-f" class="wikilink1" title="postgresql-f">PostgreSQL-f</a></div></li>
<li class="level1"><div class="li"><a href="http://2012.pgday.fr/postgresql_postgis_en_collectivite_territoriale" class="wikilink1" title="postgresql_postgis_en_collectivite_territoriale">Postgresql, PostGis en collectivité territoriale</a></div></li>
<li class="level1"><div class="li"><a href="http://2012.pgday.fr/presse" class="wikilink1" title="presse">Presse</a></div></li>
<li class="level1"><div class="li"><a href="http://2012.pgday.fr/programme" class="wikilink1" title="programme">Programme</a></div></li>
<li class="level1"><div class="li"><a href="http://2012.pgday.fr/sponsoring_campaign" class="wikilink1" title="sponsoring_campaign">Sponsorship Campaign</a></div></li>
<li class="level1"><div class="li"><a href="http://2012.pgday.fr/sponsors" class="wikilink1" title="sponsors">Sponsors</a></div></li>
<li class="level1"><div class="li"><a href="http://2012.pgday.fr/start" class="wikilink1" title="start">PG Day France 2012</a></div></li>
<li class="level1"><div class="li"><span class="curid"><a href="http://2012.pgday.fr/utilisation_de_foreign_data_wrappers_dans_differents_contextes" class="wikilink1" title="utilisation_de_foreign_data_wrappers_dans_differents_contextes">Utilisation de foreign data wrappers dans différents contextes</a></span></div></li>
</ul>
</div>
<!-- wikipage stop -->
</div>
<!-- Column 1 end -->
</div>
<div class="coltwo">
<!-- Column 2 start -->
<p>
<p><div class="noteinfo">
<strong>Infos Pratiques</strong>
</p>
<hr />
<p>
<a href="http://2012.pgday.fr/plan" class="wikilink1" title="plan">Plan d'accès</a><br/>
<a href="http://2012.pgday.fr/hotels" class="wikilink1" title="hotels">Hôtels</a><br/>
<a href="http://2012.pgday.fr/presse" class="wikilink1" title="presse">Presse</a>
</div></p>
</p>
<p>
<p><div class="noteparticipate">
<strong>Participez !</strong>
</p>
<hr />
<p>
<a href="http://2012.pgday.fr/participez#volontaires" class="wikilink1" title="participez">Bénévoles</a><br/>
<a href="http://2012.pgday.fr/participez#sponsoring" class="wikilink1" title="participez">Sponsors</a><br/>
<a href="http://2012.pgday.fr/participez#orateurs" class="wikilink1" title="participez">Orateurs</a><br/>
<a href="http://2012.pgday.fr/contact" class="wikilink1" title="contact">Contactez-nous</a><br/>
</div></p>
</p>
<div style="width:260px; padding: 0; margin: 0.5em; float: left"><fb:fan profile_id="292653214121228"
stream="0"
connections="10"
logobar="0"
width="260"
height="400"></fb:fan></div>
<p>
<p><div class="notearchive">
<strong>Archive</strong>
</p>
<hr />
<p>
<a href="http://2009.pgday.fr/" class="urlextern" title="http://2009.pgday.fr" rel="nofollow">PGDay.fr 2009</a><br/>
<a href="http://2008.pgday.fr/" class="urlextern" title="http://2008.pgday.fr" rel="nofollow">PGDay.fr 2008</a><br/>
</div></p>
</p>
<!-- Column 2 end -->
</div>
<div class="colthree">
<!-- Column 3 start -->
<h1 class="sectionedit1" id="partenaires_gold">Partenaires Gold</h1>
<div class="level1">
<p>
<a href="http://2ndquadrant.fr/" class="media" title="http://2ndquadrant.fr" rel="nofollow"><img src="http://2012.pgday.fr/_media/logo-2ndquadrant.png" class="media" title=" 2ndQuadrant : Expertise PostgreSQL " alt=" 2ndQuadrant : Expertise PostgreSQL " /></a>
</p>
<p>
<a href="http://dalibo.com/" class="media" title="http://dalibo.com" rel="nofollow"><img src="http://2012.pgday.fr/_media/dalibo_big_.png?w=200&tok=e09658" class="medialeft" title=" Audit PostgreSQL, Formation PostgreSQL, Support PostgreSQL" alt=" Audit PostgreSQL, Formation PostgreSQL, Support PostgreSQL" width="200" /></a>
</p>
</div>
<!-- EDIT1 SECTION "Partenaires Gold" [12-244] -->
<h1 class="sectionedit2" id="partenaire_silver">Partenaire Silver</h1>
<div class="level1">
<p>
<a href="http://www.enterprisedb.com/" class="media" title="http://www.enterprisedb.com" rel="nofollow"><img src="http://2012.pgday.fr/_media/edb_logo_bluebk_rgb_300.jpg?w=200&tok=9cd6b9" class="media" alt="" width="200" /></a>
</p>
</div>
<!-- EDIT2 SECTION "Partenaire Silver" [245-348] -->
<h1 class="sectionedit3" id="organise_par">Organisé par</h1>
<div class="level1">
<p>
<a href="http://www.postgresql.fr/" class="media" title="http://www.postgresql.fr" rel="nofollow"><img src="http://2012.pgday.fr/_media/pgfr.png" class="media" title="PostgreSQLFR" alt="PostgreSQLFR" /></a>
</p>
<p>
<a href="http://www.insa-lyon.fr/" class="media" title="http://www.insa-lyon.fr" rel="nofollow"><img src="http://2012.pgday.fr/_media/team_insa-lyon_logo_insa.jpg?w=120&tok=54b1ef" class="media" alt="" width="120" /></a>
</p>
</div>
<!-- EDIT3 SECTION "Organisé par" [349-] --> <!-- Column 3 end -->
</div>
</div>
</div>
</div>
<div class="clearer"> </div>
<div class="footer">
<div id="bar__bottom">
<div class="bar-left" id="bar__bottomleft">
© Copyright 2012 <a href="http://asso.postgresql.fr/" alt="PostgreSQLfr">PostgreSQLFr</a>
</div>
<div id="bar__bottomright">
<a href="http://2012.pgday.fr/utilisation_de_foreign_data_wrappers_dans_differents_contextes" class="action show" accesskey="v" rel="nofollow" title="Afficher la page [V]">Afficher la page</a> <a href="http://2012.pgday.fr/utilisation_de_foreign_data_wrappers_dans_differents_contextes?do=login&sectok=c2ad7f6c554e800e7670347d8e91f0e8" class="action login" rel="nofollow" title="Connexion">Connexion</a> </div>
<div class="clearer"></div>
</div>
</div>
<!-- footer -->
</div>
<div class="no"><img src="http://2012.pgday.fr/lib/exe/indexer.php?id=utilisation_de_foreign_data_wrappers_dans_differents_contextes&1492414013" width="2" height="1" alt="" /></div>
</body>
<!-- Mirrored from 2012.pgday.fr/utilisation_de_foreign_data_wrappers_dans_differents_contextes?do=index by HTTrack Website Copier/3.x [XR&CO'2014], Mon, 17 Apr 2017 07:27:17 GMT -->
</html>
| {
"content_hash": "d1c602c5475117283fa964f1959fa168",
"timestamp": "",
"source": "github",
"line_count": 262,
"max_line_length": 444,
"avg_line_length": 54.545801526717554,
"alnum_prop": 0.6779091736057659,
"repo_name": "postgresqlfr/2012.pgday.fr",
"id": "f93a454fe9774af2035ccd52e183b382b92931a8",
"size": "14311",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "utilisation_de_foreign_data_wrappers_dans_differents_contextesdecf.html",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "HTML",
"bytes": "2855343"
},
{
"name": "Makefile",
"bytes": "11168"
},
{
"name": "PHP",
"bytes": "458907"
}
],
"symlink_target": ""
} |
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Gradient Fill 1</title>
<link rel="stylesheet" href="../include/style.css">
</head>
<body>
<header>
Example from <a href="http://amzn.com/1430236655?tag=html5anim-20"><em>Foundation HTML5 Animation with JavaScript</em></a>
</header>
<canvas id="canvas" width="400" height="400"></canvas>
<script>
window.onload = function () {
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d'),
pt1 = {x: 0, y: 0}, //gradient start point
pt2 = {x: 100, y: 100}, //gradient end point
gradient = context.createLinearGradient(pt1.x, pt1.y, pt2.x, pt2.y);
//white to red
gradient.addColorStop(0, "#ffffff");
gradient.addColorStop(1, "#ff0000");
context.fillStyle = gradient;
context.fillRect(0, 0, 100, 100);
};
</script>
</body>
</html>
| {
"content_hash": "1863a0bb1816f9ea2153ed5ea9cb82bc",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 128,
"avg_line_length": 31.225806451612904,
"alnum_prop": 0.5785123966942148,
"repo_name": "yangjunjun/examples",
"id": "cf9f3be1598bf4111ecc30ab30f1139f5842e925",
"size": "968",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "source-from-book/html5-animation-source-code/examples/ch04/07-gradient-fill-1.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "252332"
},
{
"name": "HTML",
"bytes": "546699"
},
{
"name": "JavaScript",
"bytes": "770240"
}
],
"symlink_target": ""
} |
package org.apache.cassandra.tools;
import java.io.IOException;
import java.io.PrintStream;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.lang.management.MemoryUsage;
import java.lang.management.RuntimeMXBean;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Map.Entry;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.locks.Condition;
import javax.management.*;
import javax.management.openmbean.CompositeData;
import javax.management.remote.JMXConnectionNotification;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import javax.management.openmbean.TabularData;
import com.google.common.base.Function;
import com.google.common.collect.Iterables;
import com.google.common.collect.Sets;
import com.yammer.metrics.reporting.JmxReporter;
import org.apache.cassandra.concurrent.JMXEnabledThreadPoolExecutorMBean;
import org.apache.cassandra.db.ColumnFamilyStoreMBean;
import org.apache.cassandra.db.HintedHandOffManager;
import org.apache.cassandra.db.HintedHandOffManagerMBean;
import org.apache.cassandra.db.compaction.CompactionManager;
import org.apache.cassandra.db.compaction.CompactionManagerMBean;
import org.apache.cassandra.gms.FailureDetector;
import org.apache.cassandra.gms.FailureDetectorMBean;
import org.apache.cassandra.locator.EndpointSnitchInfoMBean;
import org.apache.cassandra.net.MessagingService;
import org.apache.cassandra.net.MessagingServiceMBean;
import org.apache.cassandra.service.*;
import org.apache.cassandra.streaming.StreamState;
import org.apache.cassandra.streaming.StreamManagerMBean;
import org.apache.cassandra.streaming.management.StreamStateCompositeData;
import org.apache.cassandra.utils.concurrent.SimpleCondition;
import org.apache.cassandra.utils.JVMStabilityInspector;
/**
* JMX client operations for Cassandra.
*/
public class NodeProbe implements AutoCloseable
{
private static final String fmtUrl = "service:jmx:rmi:///jndi/rmi://[%s]:%d/jmxrmi";
private static final String ssObjName = "org.apache.cassandra.db:type=StorageService";
private static final int defaultPort = 7199;
final String host;
final int port;
private String username;
private String password;
private JMXConnector jmxc;
private MBeanServerConnection mbeanServerConn;
private CompactionManagerMBean compactionProxy;
private StorageServiceMBean ssProxy;
private MemoryMXBean memProxy;
private GCInspectorMXBean gcProxy;
private RuntimeMXBean runtimeProxy;
private StreamManagerMBean streamProxy;
public MessagingServiceMBean msProxy;
private FailureDetectorMBean fdProxy;
private CacheServiceMBean cacheService;
private StorageProxyMBean spProxy;
private HintedHandOffManagerMBean hhProxy;
private boolean failed;
/**
* Creates a NodeProbe using the specified JMX host, port, username, and password.
*
* @param host hostname or IP address of the JMX agent
* @param port TCP port of the remote JMX agent
* @throws IOException on connection failures
*/
public NodeProbe(String host, int port, String username, String password) throws IOException
{
assert username != null && !username.isEmpty() && password != null && !password.isEmpty()
: "neither username nor password can be blank";
this.host = host;
this.port = port;
this.username = username;
this.password = password;
connect();
}
/**
* Creates a NodeProbe using the specified JMX host and port.
*
* @param host hostname or IP address of the JMX agent
* @param port TCP port of the remote JMX agent
* @throws IOException on connection failures
*/
public NodeProbe(String host, int port) throws IOException
{
this.host = host;
this.port = port;
connect();
}
/**
* Creates a NodeProbe using the specified JMX host and default port.
*
* @param host hostname or IP address of the JMX agent
* @throws IOException on connection failures
*/
public NodeProbe(String host) throws IOException
{
this.host = host;
this.port = defaultPort;
connect();
}
/**
* Create a connection to the JMX agent and setup the M[X]Bean proxies.
*
* @throws IOException on connection failures
*/
private void connect() throws IOException
{
JMXServiceURL jmxUrl = new JMXServiceURL(String.format(fmtUrl, host, port));
Map<String,Object> env = new HashMap<String,Object>();
if (username != null)
{
String[] creds = { username, password };
env.put(JMXConnector.CREDENTIALS, creds);
}
jmxc = JMXConnectorFactory.connect(jmxUrl, env);
mbeanServerConn = jmxc.getMBeanServerConnection();
try
{
ObjectName name = new ObjectName(ssObjName);
ssProxy = JMX.newMBeanProxy(mbeanServerConn, name, StorageServiceMBean.class);
name = new ObjectName(MessagingService.MBEAN_NAME);
msProxy = JMX.newMBeanProxy(mbeanServerConn, name, MessagingServiceMBean.class);
name = new ObjectName(StreamManagerMBean.OBJECT_NAME);
streamProxy = JMX.newMBeanProxy(mbeanServerConn, name, StreamManagerMBean.class);
name = new ObjectName(CompactionManager.MBEAN_OBJECT_NAME);
compactionProxy = JMX.newMBeanProxy(mbeanServerConn, name, CompactionManagerMBean.class);
name = new ObjectName(FailureDetector.MBEAN_NAME);
fdProxy = JMX.newMBeanProxy(mbeanServerConn, name, FailureDetectorMBean.class);
name = new ObjectName(CacheService.MBEAN_NAME);
cacheService = JMX.newMBeanProxy(mbeanServerConn, name, CacheServiceMBean.class);
name = new ObjectName(StorageProxy.MBEAN_NAME);
spProxy = JMX.newMBeanProxy(mbeanServerConn, name, StorageProxyMBean.class);
name = new ObjectName(HintedHandOffManager.MBEAN_NAME);
hhProxy = JMX.newMBeanProxy(mbeanServerConn, name, HintedHandOffManagerMBean.class);
name = new ObjectName(GCInspector.MBEAN_NAME);
gcProxy = JMX.newMBeanProxy(mbeanServerConn, name, GCInspectorMXBean.class);
}
catch (MalformedObjectNameException e)
{
throw new RuntimeException(
"Invalid ObjectName? Please report this as a bug.", e);
}
memProxy = ManagementFactory.newPlatformMXBeanProxy(mbeanServerConn,
ManagementFactory.MEMORY_MXBEAN_NAME, MemoryMXBean.class);
runtimeProxy = ManagementFactory.newPlatformMXBeanProxy(
mbeanServerConn, ManagementFactory.RUNTIME_MXBEAN_NAME, RuntimeMXBean.class);
}
public void close() throws IOException
{
jmxc.close();
}
public int forceKeyspaceCleanup(String keyspaceName, String... columnFamilies) throws IOException, ExecutionException, InterruptedException
{
return ssProxy.forceKeyspaceCleanup(keyspaceName, columnFamilies);
}
public int scrub(boolean disableSnapshot, boolean skipCorrupted, String keyspaceName, String... columnFamilies) throws IOException, ExecutionException, InterruptedException
{
return ssProxy.scrub(disableSnapshot, skipCorrupted, keyspaceName, columnFamilies);
}
public int upgradeSSTables(String keyspaceName, boolean excludeCurrentVersion, String... columnFamilies) throws IOException, ExecutionException, InterruptedException
{
return ssProxy.upgradeSSTables(keyspaceName, excludeCurrentVersion, columnFamilies);
}
public void forceKeyspaceCleanup(PrintStream out, String keyspaceName, String... columnFamilies) throws IOException, ExecutionException, InterruptedException
{
if (forceKeyspaceCleanup(keyspaceName, columnFamilies) != 0)
{
failed = true;
out.println("Aborted cleaning up atleast one column family in keyspace "+keyspaceName+", check server logs for more information.");
}
}
public void scrub(PrintStream out, boolean disableSnapshot, boolean skipCorrupted, String keyspaceName, String... columnFamilies) throws IOException, ExecutionException, InterruptedException
{
if (scrub(disableSnapshot, skipCorrupted, keyspaceName, columnFamilies) != 0)
{
failed = true;
out.println("Aborted scrubbing atleast one column family in keyspace "+keyspaceName+", check server logs for more information.");
}
}
public void upgradeSSTables(PrintStream out, String keyspaceName, boolean excludeCurrentVersion, String... columnFamilies) throws IOException, ExecutionException, InterruptedException
{
if (upgradeSSTables(keyspaceName, excludeCurrentVersion, columnFamilies) != 0)
{
failed = true;
out.println("Aborted upgrading sstables for atleast one column family in keyspace "+keyspaceName+", check server logs for more information.");
}
}
public void forceKeyspaceCompaction(String keyspaceName, String... columnFamilies) throws IOException, ExecutionException, InterruptedException
{
ssProxy.forceKeyspaceCompaction(keyspaceName, columnFamilies);
}
public void forceKeyspaceFlush(String keyspaceName, String... columnFamilies) throws IOException, ExecutionException, InterruptedException
{
ssProxy.forceKeyspaceFlush(keyspaceName, columnFamilies);
}
public void forceRepairAsync(final PrintStream out, final String keyspaceName, boolean isSequential, Collection<String> dataCenters, Collection<String> hosts, boolean primaryRange, boolean fullRepair, String... columnFamilies) throws IOException
{
RepairRunner runner = new RepairRunner(out, keyspaceName, columnFamilies);
try
{
jmxc.addConnectionNotificationListener(runner, null, null);
ssProxy.addNotificationListener(runner, null, null);
if (!runner.repairAndWait(ssProxy, isSequential, dataCenters, hosts, primaryRange, fullRepair))
failed = true;
}
catch (Exception e)
{
throw new IOException(e) ;
}
finally
{
try
{
ssProxy.removeNotificationListener(runner);
jmxc.removeConnectionNotificationListener(runner);
}
catch (Throwable t)
{
JVMStabilityInspector.inspectThrowable(t);
out.println("Exception occurred during clean-up. " + t);
}
}
}
public void forceRepairRangeAsync(final PrintStream out, final String keyspaceName, boolean isSequential, Collection<String> dataCenters, Collection<String> hosts, final String startToken, final String endToken, boolean fullRepair, String... columnFamilies) throws IOException
{
RepairRunner runner = new RepairRunner(out, keyspaceName, columnFamilies);
try
{
jmxc.addConnectionNotificationListener(runner, null, null);
ssProxy.addNotificationListener(runner, null, null);
if (!runner.repairRangeAndWait(ssProxy, isSequential, dataCenters, hosts, startToken, endToken, fullRepair))
failed = true;
}
catch (Exception e)
{
throw new IOException(e) ;
}
finally
{
try
{
ssProxy.removeNotificationListener(runner);
jmxc.removeConnectionNotificationListener(runner);
}
catch (Throwable e)
{
out.println("Exception occurred during clean-up. " + e);
}
}
}
public void invalidateCounterCache()
{
cacheService.invalidateCounterCache();
}
public void invalidateKeyCache()
{
cacheService.invalidateKeyCache();
}
public void invalidateRowCache()
{
cacheService.invalidateRowCache();
}
public void drain() throws IOException, InterruptedException, ExecutionException
{
ssProxy.drain();
}
public Map<String, String> getTokenToEndpointMap()
{
return ssProxy.getTokenToEndpointMap();
}
public List<String> getLiveNodes()
{
return ssProxy.getLiveNodes();
}
public List<String> getJoiningNodes()
{
return ssProxy.getJoiningNodes();
}
public List<String> getLeavingNodes()
{
return ssProxy.getLeavingNodes();
}
public List<String> getMovingNodes()
{
return ssProxy.getMovingNodes();
}
public List<String> getUnreachableNodes()
{
return ssProxy.getUnreachableNodes();
}
public Map<String, String> getLoadMap()
{
return ssProxy.getLoadMap();
}
public Map<InetAddress, Float> getOwnership()
{
return ssProxy.getOwnership();
}
public Map<InetAddress, Float> effectiveOwnership(String keyspace) throws IllegalStateException
{
return ssProxy.effectiveOwnership(keyspace);
}
public CacheServiceMBean getCacheServiceMBean()
{
String cachePath = "org.apache.cassandra.db:type=Caches";
try
{
return JMX.newMBeanProxy(mbeanServerConn, new ObjectName(cachePath), CacheServiceMBean.class);
}
catch (MalformedObjectNameException e)
{
throw new RuntimeException(e);
}
}
public double[] getAndResetGCStats()
{
return gcProxy.getAndResetStats();
}
public Iterator<Map.Entry<String, ColumnFamilyStoreMBean>> getColumnFamilyStoreMBeanProxies()
{
try
{
return new ColumnFamilyStoreMBeanIterator(mbeanServerConn);
}
catch (MalformedObjectNameException e)
{
throw new RuntimeException("Invalid ObjectName? Please report this as a bug.", e);
}
catch (IOException e)
{
throw new RuntimeException("Could not retrieve list of stat mbeans.", e);
}
}
public CompactionManagerMBean getCompactionManagerProxy()
{
return compactionProxy;
}
public List<String> getTokens()
{
return ssProxy.getTokens();
}
public List<String> getTokens(String endpoint)
{
try
{
return ssProxy.getTokens(endpoint);
}
catch (UnknownHostException e)
{
throw new RuntimeException(e);
}
}
public String getLocalHostId()
{
return ssProxy.getLocalHostId();
}
public Map<String, String> getHostIdMap()
{
return ssProxy.getHostIdMap();
}
public String getLoadString()
{
return ssProxy.getLoadString();
}
public String getReleaseVersion()
{
return ssProxy.getReleaseVersion();
}
public int getCurrentGenerationNumber()
{
return ssProxy.getCurrentGenerationNumber();
}
public long getUptime()
{
return runtimeProxy.getUptime();
}
public MemoryUsage getHeapMemoryUsage()
{
return memProxy.getHeapMemoryUsage();
}
/**
* Take a snapshot of all the keyspaces, optionally specifying only a specific column family.
*
* @param snapshotName the name of the snapshot.
* @param columnFamily the column family to snapshot or all on null
* @param keyspaces the keyspaces to snapshot
*/
public void takeSnapshot(String snapshotName, String columnFamily, String... keyspaces) throws IOException
{
if (columnFamily != null)
{
if (keyspaces.length != 1)
{
throw new IOException("When specifying the column family for a snapshot, you must specify one and only one keyspace");
}
ssProxy.takeColumnFamilySnapshot(keyspaces[0], columnFamily, snapshotName);
}
else
ssProxy.takeSnapshot(snapshotName, keyspaces);
}
/**
* Remove all the existing snapshots.
*/
public void clearSnapshot(String tag, String... keyspaces) throws IOException
{
ssProxy.clearSnapshot(tag, keyspaces);
}
public Map<String, TabularData> getSnapshotDetails()
{
return ssProxy.getSnapshotDetails();
}
public long trueSnapshotsSize()
{
return ssProxy.trueSnapshotsSize();
}
public boolean isJoined()
{
return ssProxy.isJoined();
}
public void joinRing() throws IOException
{
ssProxy.joinRing();
}
public void decommission() throws InterruptedException
{
ssProxy.decommission();
}
public void move(String newToken) throws IOException
{
ssProxy.move(newToken);
}
public void removeNode(String token)
{
ssProxy.removeNode(token);
}
public String getRemovalStatus()
{
return ssProxy.getRemovalStatus();
}
public void forceRemoveCompletion()
{
ssProxy.forceRemoveCompletion();
}
public Iterator<Map.Entry<String, JMXEnabledThreadPoolExecutorMBean>> getThreadPoolMBeanProxies()
{
try
{
return new ThreadPoolProxyMBeanIterator(mbeanServerConn);
}
catch (MalformedObjectNameException e)
{
throw new RuntimeException("Invalid ObjectName? Please report this as a bug.", e);
}
catch (IOException e)
{
throw new RuntimeException("Could not retrieve list of stat mbeans.", e);
}
}
/**
* Set the compaction threshold
*
* @param minimumCompactionThreshold minimum compaction threshold
* @param maximumCompactionThreshold maximum compaction threshold
*/
public void setCompactionThreshold(String ks, String cf, int minimumCompactionThreshold, int maximumCompactionThreshold)
{
ColumnFamilyStoreMBean cfsProxy = getCfsProxy(ks, cf);
cfsProxy.setCompactionThresholds(minimumCompactionThreshold, maximumCompactionThreshold);
}
public void disableAutoCompaction(String ks, String ... columnFamilies) throws IOException
{
ssProxy.disableAutoCompaction(ks, columnFamilies);
}
public void enableAutoCompaction(String ks, String ... columnFamilies) throws IOException
{
ssProxy.enableAutoCompaction(ks, columnFamilies);
}
public void setIncrementalBackupsEnabled(boolean enabled)
{
ssProxy.setIncrementalBackupsEnabled(enabled);
}
public void setCacheCapacities(int keyCacheCapacity, int rowCacheCapacity, int counterCacheCapacity)
{
try
{
String keyCachePath = "org.apache.cassandra.db:type=Caches";
CacheServiceMBean cacheMBean = JMX.newMBeanProxy(mbeanServerConn, new ObjectName(keyCachePath), CacheServiceMBean.class);
cacheMBean.setKeyCacheCapacityInMB(keyCacheCapacity);
cacheMBean.setRowCacheCapacityInMB(rowCacheCapacity);
cacheMBean.setCounterCacheCapacityInMB(counterCacheCapacity);
}
catch (MalformedObjectNameException e)
{
throw new RuntimeException(e);
}
}
public void setCacheKeysToSave(int keyCacheKeysToSave, int rowCacheKeysToSave, int counterCacheKeysToSave)
{
try
{
String keyCachePath = "org.apache.cassandra.db:type=Caches";
CacheServiceMBean cacheMBean = JMX.newMBeanProxy(mbeanServerConn, new ObjectName(keyCachePath), CacheServiceMBean.class);
cacheMBean.setKeyCacheKeysToSave(keyCacheKeysToSave);
cacheMBean.setRowCacheKeysToSave(rowCacheKeysToSave);
cacheMBean.setCounterCacheKeysToSave(counterCacheKeysToSave);
}
catch (MalformedObjectNameException e)
{
throw new RuntimeException(e);
}
}
public void setHintedHandoffThrottleInKB(int throttleInKB)
{
ssProxy.setHintedHandoffThrottleInKB(throttleInKB);
}
public List<InetAddress> getEndpoints(String keyspace, String cf, String key)
{
return ssProxy.getNaturalEndpoints(keyspace, cf, key);
}
public List<String> getSSTables(String keyspace, String cf, String key)
{
ColumnFamilyStoreMBean cfsProxy = getCfsProxy(keyspace, cf);
return cfsProxy.getSSTablesForKey(key);
}
public Set<StreamState> getStreamStatus()
{
return Sets.newHashSet(Iterables.transform(streamProxy.getCurrentStreams(), new Function<CompositeData, StreamState>()
{
public StreamState apply(CompositeData input)
{
return StreamStateCompositeData.fromCompositeData(input);
}
}));
}
public String getOperationMode()
{
return ssProxy.getOperationMode();
}
public void truncate(String keyspaceName, String cfName)
{
try
{
ssProxy.truncate(keyspaceName, cfName);
}
catch (TimeoutException e)
{
throw new RuntimeException("Error while executing truncate", e);
}
catch (IOException e)
{
throw new RuntimeException("Error while executing truncate", e);
}
}
public EndpointSnitchInfoMBean getEndpointSnitchInfoProxy()
{
try
{
return JMX.newMBeanProxy(mbeanServerConn, new ObjectName("org.apache.cassandra.db:type=EndpointSnitchInfo"), EndpointSnitchInfoMBean.class);
}
catch (MalformedObjectNameException e)
{
throw new RuntimeException(e);
}
}
public ColumnFamilyStoreMBean getCfsProxy(String ks, String cf)
{
ColumnFamilyStoreMBean cfsProxy = null;
try
{
String type = cf.contains(".") ? "IndexColumnFamilies" : "ColumnFamilies";
Set<ObjectName> beans = mbeanServerConn.queryNames(
new ObjectName("org.apache.cassandra.db:type=*" + type +",keyspace=" + ks + ",columnfamily=" + cf), null);
if (beans.isEmpty())
throw new MalformedObjectNameException("couldn't find that bean");
assert beans.size() == 1;
for (ObjectName bean : beans)
cfsProxy = JMX.newMBeanProxy(mbeanServerConn, bean, ColumnFamilyStoreMBean.class);
}
catch (MalformedObjectNameException mone)
{
System.err.println("ColumnFamilyStore for " + ks + "/" + cf + " not found.");
System.exit(1);
}
catch (IOException e)
{
System.err.println("ColumnFamilyStore for " + ks + "/" + cf + " not found: " + e);
System.exit(1);
}
return cfsProxy;
}
public StorageProxyMBean getSpProxy()
{
return spProxy;
}
public String getEndpoint()
{
// Try to find the endpoint using the local token, doing so in a crazy manner
// to maintain backwards compatibility with the MBean interface
String stringToken = ssProxy.getTokens().get(0);
Map<String, String> tokenToEndpoint = ssProxy.getTokenToEndpointMap();
for (Map.Entry<String, String> pair : tokenToEndpoint.entrySet())
{
if (pair.getKey().equals(stringToken))
{
return pair.getValue();
}
}
throw new RuntimeException("Could not find myself in the endpoint list, something is very wrong! Is the Cassandra node fully started?");
}
public String getDataCenter()
{
try
{
return getEndpointSnitchInfoProxy().getDatacenter(getEndpoint());
}
catch (UnknownHostException e)
{
return "Unknown";
}
}
public String getRack()
{
try
{
return getEndpointSnitchInfoProxy().getRack(getEndpoint());
}
catch (UnknownHostException e)
{
return "Unknown";
}
}
public List<String> getKeyspaces()
{
return ssProxy.getKeyspaces();
}
public String getClusterName()
{
return ssProxy.getClusterName();
}
public String getPartitioner()
{
return ssProxy.getPartitionerName();
}
public void disableHintedHandoff()
{
spProxy.setHintedHandoffEnabled(false);
}
public void enableHintedHandoff()
{
spProxy.setHintedHandoffEnabled(true);
}
public void enableHintedHandoff(String dcNames)
{
spProxy.setHintedHandoffEnabledByDCList(dcNames);
}
public void pauseHintsDelivery()
{
hhProxy.pauseHintsDelivery(true);
}
public void resumeHintsDelivery()
{
hhProxy.pauseHintsDelivery(false);
}
public void truncateHints(final String host)
{
hhProxy.deleteHintsForEndpoint(host);
}
public void truncateHints()
{
try
{
hhProxy.truncateAllHints();
}
catch (ExecutionException e)
{
throw new RuntimeException("Error while executing truncate hints", e);
}
catch (InterruptedException e)
{
throw new RuntimeException("Error while executing truncate hints", e);
}
}
public void stopNativeTransport()
{
ssProxy.stopNativeTransport();
}
public void startNativeTransport()
{
ssProxy.startNativeTransport();
}
public boolean isNativeTransportRunning()
{
return ssProxy.isNativeTransportRunning();
}
public void stopGossiping()
{
ssProxy.stopGossiping();
}
public void startGossiping()
{
ssProxy.startGossiping();
}
public boolean isGossipRunning()
{
return ssProxy.isGossipRunning();
}
public void stopThriftServer()
{
ssProxy.stopRPCServer();
}
public void startThriftServer()
{
ssProxy.startRPCServer();
}
public boolean isThriftServerRunning()
{
return ssProxy.isRPCServerRunning();
}
public void stopCassandraDaemon()
{
ssProxy.stopDaemon();
}
public boolean isInitialized()
{
return ssProxy.isInitialized();
}
public void setCompactionThroughput(int value)
{
ssProxy.setCompactionThroughputMbPerSec(value);
}
public int getCompactionThroughput()
{
return ssProxy.getCompactionThroughputMbPerSec();
}
public int getStreamThroughput()
{
return ssProxy.getStreamThroughputMbPerSec();
}
public int getExceptionCount()
{
return ssProxy.getExceptionCount();
}
public Map<String, Integer> getDroppedMessages()
{
return msProxy.getDroppedMessages();
}
public void loadNewSSTables(String ksName, String cfName)
{
ssProxy.loadNewSSTables(ksName, cfName);
}
public void rebuildIndex(String ksName, String cfName, String... idxNames)
{
ssProxy.rebuildSecondaryIndex(ksName, cfName, idxNames);
}
public String getGossipInfo()
{
return fdProxy.getAllEndpointStates();
}
public void stop(String string)
{
compactionProxy.stopCompaction(string);
}
public void setStreamThroughput(int value)
{
ssProxy.setStreamThroughputMbPerSec(value);
}
public void setTraceProbability(double value)
{
ssProxy.setTraceProbability(value);
}
public String getSchemaVersion()
{
return ssProxy.getSchemaVersion();
}
public List<String> describeRing(String keyspaceName) throws IOException
{
return ssProxy.describeRingJMX(keyspaceName);
}
public void rebuild(String sourceDc)
{
ssProxy.rebuild(sourceDc);
}
public List<String> sampleKeyRange()
{
return ssProxy.sampleKeyRange();
}
public void resetLocalSchema() throws IOException
{
ssProxy.resetLocalSchema();
}
public boolean isFailed()
{
return failed;
}
public long getReadRepairAttempted()
{
return spProxy.getReadRepairAttempted();
}
public long getReadRepairRepairedBlocking()
{
return spProxy.getReadRepairRepairedBlocking();
}
public long getReadRepairRepairedBackground()
{
return spProxy.getReadRepairRepairedBackground();
}
// JMX getters for the o.a.c.metrics API below.
/**
* Retrieve cache metrics based on the cache type (KeyCache, RowCache, or CounterCache)
* @param cacheType KeyCach, RowCache, or CounterCache
* @param metricName Capacity, Entries, HitRate, Size, Requests or Hits.
*/
public Object getCacheMetric(String cacheType, String metricName)
{
try
{
switch(metricName)
{
case "Capacity":
case "Entries":
case "HitRate":
case "Size":
return JMX.newMBeanProxy(mbeanServerConn,
new ObjectName("org.apache.cassandra.metrics:type=Cache,scope=" + cacheType + ",name=" + metricName),
JmxReporter.GaugeMBean.class).getValue();
case "Requests":
case "Hits":
return JMX.newMBeanProxy(mbeanServerConn,
new ObjectName("org.apache.cassandra.metrics:type=Cache,scope=" + cacheType + ",name=" + metricName),
JmxReporter.MeterMBean.class).getCount();
default:
throw new RuntimeException("Unknown cache metric name.");
}
}
catch (MalformedObjectNameException e)
{
throw new RuntimeException(e);
}
}
/**
* Retrieve ColumnFamily metrics
* @param ks Keyspace for which stats are to be displayed.
* @param cf ColumnFamily for which stats are to be displayed.
* @param metricName View {@link org.apache.cassandra.metrics.ColumnFamilyMetrics}.
*/
public Object getColumnFamilyMetric(String ks, String cf, String metricName)
{
try
{
String type = cf.contains(".") ? "IndexColumnFamily": "ColumnFamily";
ObjectName oName = new ObjectName(String.format("org.apache.cassandra.metrics:type=%s,keyspace=%s,scope=%s,name=%s", type, ks, cf, metricName));
switch(metricName)
{
case "BloomFilterDiskSpaceUsed":
case "BloomFilterFalsePositives":
case "BloomFilterFalseRatio":
case "CompressionRatio":
case "EstimatedColumnCountHistogram":
case "EstimatedRowSizeHistogram":
case "KeyCacheHitRate":
case "LiveSSTableCount":
case "MaxRowSize":
case "MeanRowSize":
case "MemtableColumnsCount":
case "MemtableLiveDataSize":
case "MinRowSize":
case "RecentBloomFilterFalsePositives":
case "RecentBloomFilterFalseRatio":
case "SnapshotsSize":
return JMX.newMBeanProxy(mbeanServerConn, oName, JmxReporter.GaugeMBean.class).getValue();
case "LiveDiskSpaceUsed":
case "MemtableSwitchCount":
case "SpeculativeRetries":
case "TotalDiskSpaceUsed":
case "WriteTotalLatency":
case "ReadTotalLatency":
case "PendingFlushes":
return JMX.newMBeanProxy(mbeanServerConn, oName, JmxReporter.CounterMBean.class).getCount();
case "ReadLatency":
case "CoordinatorReadLatency":
case "CoordinatorScanLatency":
case "WriteLatency":
return JMX.newMBeanProxy(mbeanServerConn, oName, JmxReporter.TimerMBean.class);
case "LiveScannedHistogram":
case "SSTablesPerReadHistogram":
case "TombstoneScannedHistogram":
return JMX.newMBeanProxy(mbeanServerConn, oName, JmxReporter.HistogramMBean.class);
default:
throw new RuntimeException("Unknown column family metric.");
}
}
catch (MalformedObjectNameException e)
{
throw new RuntimeException(e);
}
}
/**
* Retrieve Proxy metrics
* @param scope RangeSlice, Read or Write
*/
public JmxReporter.TimerMBean getProxyMetric(String scope)
{
try
{
return JMX.newMBeanProxy(mbeanServerConn,
new ObjectName("org.apache.cassandra.metrics:type=ClientRequest,scope=" + scope + ",name=Latency"),
JmxReporter.TimerMBean.class);
}
catch (MalformedObjectNameException e)
{
throw new RuntimeException(e);
}
}
/**
* Retrieve Proxy metrics
* @param metricName CompletedTasks, PendingTasks, BytesCompacted or TotalCompactionsCompleted.
*/
public Object getCompactionMetric(String metricName)
{
try
{
switch(metricName)
{
case "BytesCompacted":
return JMX.newMBeanProxy(mbeanServerConn,
new ObjectName("org.apache.cassandra.metrics:type=Compaction,name=" + metricName),
JmxReporter.CounterMBean.class);
case "CompletedTasks":
case "PendingTasks":
return JMX.newMBeanProxy(mbeanServerConn,
new ObjectName("org.apache.cassandra.metrics:type=Compaction,name=" + metricName),
JmxReporter.GaugeMBean.class).getValue();
case "TotalCompactionsCompleted":
return JMX.newMBeanProxy(mbeanServerConn,
new ObjectName("org.apache.cassandra.metrics:type=Compaction,name=" + metricName),
JmxReporter.MeterMBean.class);
default:
throw new RuntimeException("Unknown compaction metric.");
}
}
catch (MalformedObjectNameException e)
{
throw new RuntimeException(e);
}
}
/**
* Retrieve Proxy metrics
* @param metricName Exceptions, Load, TotalHints or TotalHintsInProgress.
*/
public long getStorageMetric(String metricName)
{
try
{
return JMX.newMBeanProxy(mbeanServerConn,
new ObjectName("org.apache.cassandra.metrics:type=Storage,name=" + metricName),
JmxReporter.CounterMBean.class).getCount();
}
catch (MalformedObjectNameException e)
{
throw new RuntimeException(e);
}
}
public double[] metricPercentilesAsArray(JmxReporter.HistogramMBean metric)
{
return new double[]{ metric.get50thPercentile(),
metric.get75thPercentile(),
metric.get95thPercentile(),
metric.get98thPercentile(),
metric.get99thPercentile(),
metric.getMin(),
metric.getMax()};
}
public TabularData getCompactionHistory()
{
return compactionProxy.getCompactionHistory();
}
public void reloadTriggers()
{
spProxy.reloadTriggerClasses();
}
public void setLoggingLevel(String classQualifier, String level)
{
try
{
ssProxy.setLoggingLevel(classQualifier, level);
}
catch (Exception e)
{
throw new RuntimeException("Error setting log for " + classQualifier +" on level " + level +". Please check logback configuration and ensure to have <jmxConfigurator /> set", e);
}
}
public Map<String, String> getLoggingLevels()
{
return ssProxy.getLoggingLevels();
}
}
class ColumnFamilyStoreMBeanIterator implements Iterator<Map.Entry<String, ColumnFamilyStoreMBean>>
{
private MBeanServerConnection mbeanServerConn;
Iterator<Entry<String, ColumnFamilyStoreMBean>> mbeans;
public ColumnFamilyStoreMBeanIterator(MBeanServerConnection mbeanServerConn)
throws MalformedObjectNameException, NullPointerException, IOException
{
this.mbeanServerConn = mbeanServerConn;
List<Entry<String, ColumnFamilyStoreMBean>> cfMbeans = getCFSMBeans(mbeanServerConn, "ColumnFamilies");
cfMbeans.addAll(getCFSMBeans(mbeanServerConn, "IndexColumnFamilies"));
Collections.sort(cfMbeans, new Comparator<Entry<String, ColumnFamilyStoreMBean>>()
{
public int compare(Entry<String, ColumnFamilyStoreMBean> e1, Entry<String, ColumnFamilyStoreMBean> e2)
{
//compare keyspace, then CF name, then normal vs. index
int keyspaceNameCmp = e1.getKey().compareTo(e2.getKey());
if(keyspaceNameCmp != 0)
return keyspaceNameCmp;
// get CF name and split it for index name
String e1CF[] = e1.getValue().getColumnFamilyName().split("\\.");
String e2CF[] = e2.getValue().getColumnFamilyName().split("\\.");
assert e1CF.length <= 2 && e2CF.length <= 2 : "unexpected split count for column family name";
//if neither are indexes, just compare CF names
if(e1CF.length == 1 && e2CF.length == 1)
return e1CF[0].compareTo(e2CF[0]);
//check if it's the same CF
int cfNameCmp = e1CF[0].compareTo(e2CF[0]);
if(cfNameCmp != 0)
return cfNameCmp;
// if both are indexes (for the same CF), compare them
if(e1CF.length == 2 && e2CF.length == 2)
return e1CF[1].compareTo(e2CF[1]);
//if length of e1CF is 1, it's not an index, so sort it higher
return e1CF.length == 1 ? 1 : -1;
}
});
mbeans = cfMbeans.iterator();
}
private List<Entry<String, ColumnFamilyStoreMBean>> getCFSMBeans(MBeanServerConnection mbeanServerConn, String type)
throws MalformedObjectNameException, IOException
{
ObjectName query = new ObjectName("org.apache.cassandra.db:type=" + type +",*");
Set<ObjectName> cfObjects = mbeanServerConn.queryNames(query, null);
List<Entry<String, ColumnFamilyStoreMBean>> mbeans = new ArrayList<Entry<String, ColumnFamilyStoreMBean>>(cfObjects.size());
for(ObjectName n : cfObjects)
{
String keyspaceName = n.getKeyProperty("keyspace");
ColumnFamilyStoreMBean cfsProxy = JMX.newMBeanProxy(mbeanServerConn, n, ColumnFamilyStoreMBean.class);
mbeans.add(new AbstractMap.SimpleImmutableEntry<String, ColumnFamilyStoreMBean>(keyspaceName, cfsProxy));
}
return mbeans;
}
public boolean hasNext()
{
return mbeans.hasNext();
}
public Entry<String, ColumnFamilyStoreMBean> next()
{
return mbeans.next();
}
public void remove()
{
throw new UnsupportedOperationException();
}
}
class ThreadPoolProxyMBeanIterator implements Iterator<Map.Entry<String, JMXEnabledThreadPoolExecutorMBean>>
{
private final Iterator<ObjectName> resIter;
private final MBeanServerConnection mbeanServerConn;
public ThreadPoolProxyMBeanIterator(MBeanServerConnection mbeanServerConn)
throws MalformedObjectNameException, NullPointerException, IOException
{
Set<ObjectName> requests = mbeanServerConn.queryNames(new ObjectName("org.apache.cassandra.request:type=*"), null);
Set<ObjectName> internal = mbeanServerConn.queryNames(new ObjectName("org.apache.cassandra.internal:type=*"), null);
resIter = Iterables.concat(requests, internal).iterator();
this.mbeanServerConn = mbeanServerConn;
}
public boolean hasNext()
{
return resIter.hasNext();
}
public Map.Entry<String, JMXEnabledThreadPoolExecutorMBean> next()
{
ObjectName objectName = resIter.next();
String poolName = objectName.getKeyProperty("type");
JMXEnabledThreadPoolExecutorMBean threadPoolProxy = JMX.newMBeanProxy(mbeanServerConn, objectName, JMXEnabledThreadPoolExecutorMBean.class);
return new AbstractMap.SimpleImmutableEntry<String, JMXEnabledThreadPoolExecutorMBean>(poolName, threadPoolProxy);
}
public void remove()
{
throw new UnsupportedOperationException();
}
}
class RepairRunner implements NotificationListener
{
private final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss,SSS");
private final Condition condition = new SimpleCondition();
private final PrintStream out;
private final String keyspace;
private final String[] columnFamilies;
private int cmd;
private volatile boolean success = true;
private volatile Exception error = null;
RepairRunner(PrintStream out, String keyspace, String... columnFamilies)
{
this.out = out;
this.keyspace = keyspace;
this.columnFamilies = columnFamilies;
}
public boolean repairAndWait(StorageServiceMBean ssProxy, boolean isSequential, Collection<String> dataCenters, Collection<String> hosts, boolean primaryRangeOnly, boolean fullRepair) throws Exception
{
cmd = ssProxy.forceRepairAsync(keyspace, isSequential, dataCenters, hosts, primaryRangeOnly, fullRepair, columnFamilies);
waitForRepair();
return success;
}
public boolean repairRangeAndWait(StorageServiceMBean ssProxy, boolean isSequential, Collection<String> dataCenters, Collection<String> hosts, String startToken, String endToken, boolean fullRepair) throws Exception
{
cmd = ssProxy.forceRepairRangeAsync(startToken, endToken, keyspace, isSequential, dataCenters, hosts, fullRepair, columnFamilies);
waitForRepair();
return success;
}
private void waitForRepair() throws Exception
{
if (cmd > 0)
{
condition.await();
}
else
{
String message = String.format("[%s] Nothing to repair for keyspace '%s'", format.format(System.currentTimeMillis()), keyspace);
out.println(message);
}
if (error != null)
{
throw error;
}
}
public void handleNotification(Notification notification, Object handback)
{
if ("repair".equals(notification.getType()))
{
int[] status = (int[]) notification.getUserData();
assert status.length == 2;
if (cmd == status[0])
{
String message = String.format("[%s] %s", format.format(notification.getTimeStamp()), notification.getMessage());
out.println(message);
// repair status is int array with [0] = cmd number, [1] = status
if (status[1] == ActiveRepairService.Status.SESSION_FAILED.ordinal())
success = false;
else if (status[1] == ActiveRepairService.Status.FINISHED.ordinal())
condition.signalAll();
}
}
else if (JMXConnectionNotification.NOTIFS_LOST.equals(notification.getType()))
{
String message = String.format("[%s] Lost notification. You should check server log for repair status of keyspace %s",
format.format(notification.getTimeStamp()),
keyspace);
out.println(message);
}
else if (JMXConnectionNotification.FAILED.equals(notification.getType())
|| JMXConnectionNotification.CLOSED.equals(notification.getType()))
{
String message = String.format("JMX connection closed. You should check server log for repair status of keyspace %s"
+ "(Subsequent keyspaces are not going to be repaired).",
keyspace);
error = new IOException(message);
condition.signalAll();
}
}
}
| {
"content_hash": "95b18fd00c11039e603735e48dbfa25b",
"timestamp": "",
"source": "github",
"line_count": 1339,
"max_line_length": 280,
"avg_line_length": 33.42419716206124,
"alnum_prop": 0.6386102111495923,
"repo_name": "guanxi55nba/db-improvement",
"id": "d495786bd9c1979e46a056d76e04f4ab7d2c6960",
"size": "45560",
"binary": false,
"copies": "2",
"ref": "refs/heads/db-improvement",
"path": "src/java/org/apache/cassandra/tools/NodeProbe.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "AGS Script",
"bytes": "3742"
},
{
"name": "CSS",
"bytes": "3325"
},
{
"name": "GAP",
"bytes": "90502"
},
{
"name": "Java",
"bytes": "11860446"
},
{
"name": "PigLatin",
"bytes": "4600"
},
{
"name": "PowerShell",
"bytes": "53765"
},
{
"name": "Python",
"bytes": "226851"
},
{
"name": "Shell",
"bytes": "166230"
},
{
"name": "Thrift",
"bytes": "40240"
}
],
"symlink_target": ""
} |
import { Http, Response, Headers,RequestOptions } from '@angular/http';
import 'rxjs/add/operator/map'
import { Observable } from 'rxjs/Observable';
import {Injectable} from '@angular/core';
import {Configuration} from './config';
@Injectable()
export class EventService {
private config = new Configuration();
static get parameters() {
return [[Http]];
}
constructor(private http: Http) {
}
getPublicEvents(): Observable<Response> {
let headers = new Headers({ 'Content-Type': ['application/x-www-form-urlencoded'] });//application/json
let options = new RequestOptions({ headers: headers });
return this.http.get(this.config.getApiUrl() + '/publicevents', options);
}
getSessions(eventID): Observable<Response> {
let headers = new Headers({ 'Content-Type': ['application/x-www-form-urlencoded'] });//application/json
let body = "event=" + eventID;
let options = new RequestOptions({ headers: headers });
return this.http.post(this.config.getApiUrl() + '/sessions',body, options);
}
getIntervents(sessionID): Observable<Response> {
let headers = new Headers({ 'Content-Type': ['application/x-www-form-urlencoded'] });//application/json
let body = "session=" + sessionID;
let options = new RequestOptions({ headers: headers });
return this.http.post(this.config.getApiUrl() + '/intervents',body, options);
}
getPersonalEvents(): Observable<Response> {
let headers = new Headers({ 'Content-Type': ['application/x-www-form-urlencoded'] });//application/json
headers.append("Authorization",window.localStorage.getItem("token"));
let options = new RequestOptions({ headers: headers });
return this.http.get(this.config.getApiUrl() + '/personalevents', options);
}
getObservedEvents(): Observable<Response> {
let headers = new Headers({ 'Content-Type': ['application/x-www-form-urlencoded'] });//application/json
headers.append("Authorization",window.localStorage.getItem("token"));
let options = new RequestOptions({ headers: headers });
return this.http.get(this.config.getApiUrl() + '/observedevents', options);
}
getJoinedEvents(): Observable<Response> {
let headers = new Headers({ 'Content-Type': ['application/x-www-form-urlencoded'] });//application/json
headers.append("Authorization",window.localStorage.getItem("token"));
let options = new RequestOptions({ headers: headers });
return this.http.get(this.config.getApiUrl() + '/joinedevents', options);
}
createEvent(event): Observable<Response>{
console.log(event);
let headers = new Headers({ 'Content-Type': ['application/x-www-form-urlencoded'] });//application/json
let body = "title="+ event.title + "&startDate="+ event.startDate + "&endDate="+ event.endDate + "&location=" + event.location + "&organizer=" + event.organizer + "&status=" + event.status;
headers.append("Authorization",window.localStorage.getItem("token"));
let options = new RequestOptions({ headers: headers });
return this.http.post(this.config.getApiUrl() + '/createevent', body, options);
}
createSession(session): Observable<Response>{
console.log(session);
let headers = new Headers({ 'Content-Type': ['application/x-www-form-urlencoded'] });//application/json
let body = "title="+ session.title + "&startDate="+ session.startDate + "&endDate="+ session.endDate + "&speakers=" + session.speakers +"&status=" + session.status +"&event=" + session.event;
console.log(body);
headers.append("Authorization",window.localStorage.getItem("token"));
let options = new RequestOptions({ headers: headers });
return this.http.post(this.config.getApiUrl() + '/createsession', body, options);
}
createIntervent(intervent): Observable<Response>{
console.log(intervent);
let headers = new Headers({ 'Content-Type': ['application/x-www-form-urlencoded'] });//application/json
let body = "title="+ intervent.title + "&date="+ intervent.date + "&duration="+ intervent.duration + "&speaker=" + intervent.speaker + "&session=" + intervent.session + "&status=" + intervent.status;
console.log(body);
headers.append("Authorization",window.localStorage.getItem("token"));
let options = new RequestOptions({ headers: headers });
return this.http.post(this.config.getApiUrl() + '/createintervent', body, options);
}
updateEvent(event): Observable<Response>{
console.log(event);
let headers = new Headers({ 'Content-Type': ['application/x-www-form-urlencoded'] });//application/json
let body = "id=" + event._id +"&title="+ event.title + "&startDate="+ event.startDate + "&endDate="+ event.endDate + "&location=" + event.location;
console.log(body);
headers.append("Authorization",window.localStorage.getItem("token"));
let options = new RequestOptions({ headers: headers });
return this.http.post(this.config.getApiUrl() + '/updateevent', body, options);
}
updateSession(session): Observable<Response>{
console.log(session);
let headers = new Headers({ 'Content-Type': ['application/x-www-form-urlencoded'] });//application/json
let body = "id=" + session._id +"&title="+ session.title + "&startDate="+ session.startDate + "&endDate="+ session.endDate;
console.log(body);
headers.append("Authorization",window.localStorage.getItem("token"));
let options = new RequestOptions({ headers: headers });
return this.http.post(this.config.getApiUrl() + '/updatesession', body, options);
}
updateIntervent(intervent): Observable<Response>{
console.log(intervent);
let headers = new Headers({ 'Content-Type': ['application/x-www-form-urlencoded'] });//application/json
let body = "id=" + intervent._id +"&title="+ intervent.title + "&date="+ intervent.date + "&duration=" + intervent.duration + "&speaker="+ intervent.speaker;
console.log(body);
headers.append("Authorization",window.localStorage.getItem("token"));
let options = new RequestOptions({ headers: headers });
return this.http.post(this.config.getApiUrl() + '/updateintervent', body, options);
}
deleteEvent(eventID): Observable<Response>{
let headers = new Headers({ 'Content-Type': ['application/x-www-form-urlencoded'] });//application/json
let body = "id=" + eventID;
console.log(body);
headers.append("Authorization",window.localStorage.getItem("token"));
let options = new RequestOptions({ headers: headers });
return this.http.post(this.config.getApiUrl() + '/deleteevent', body, options);
}
deleteSession(sessionID): Observable<Response>{
let headers = new Headers({ 'Content-Type': ['application/x-www-form-urlencoded'] });//application/json
let body = "id=" + sessionID;
console.log(body);
headers.append("Authorization",window.localStorage.getItem("token"));
let options = new RequestOptions({ headers: headers });
return this.http.post(this.config.getApiUrl() + '/deletesession', body, options);
}
deleteIntervent(interventID): Observable<Response>{
let headers = new Headers({ 'Content-Type': ['application/x-www-form-urlencoded'] });//application/json
let body = "id=" + interventID;
console.log(body);
headers.append("Authorization",window.localStorage.getItem("token"));
let options = new RequestOptions({ headers: headers });
return this.http.post(this.config.getApiUrl() + '/deleteintervent', body, options);
}
openServer(interventID): Observable<Response>{
let headers = new Headers({ 'Content-Type': ['application/x-www-form-urlencoded'] });//application/json
let body = "id=" + interventID;
console.log(body);
headers.append("Authorization",window.localStorage.getItem("token"));
let options = new RequestOptions({ headers: headers });
return this.http.post(this.config.getApiUrl() + '/openserver', body, options);
}
saveInterventText(intervent): Observable<Response>{
let headers = new Headers({ 'Content-Type': ['application/x-www-form-urlencoded'] });//application/json
let body = "id=" + intervent._id + "&text="+ intervent.text;
console.log(body);
headers.append("Authorization",window.localStorage.getItem("token"));
let options = new RequestOptions({ headers: headers });
return this.http.post(this.config.getApiUrl() + '/saveinterventtext', body, options);
}
addQuestion(intervent, question): Observable<Response>{
let headers = new Headers({ 'Content-Type': ['application/x-www-form-urlencoded'] });//application/json
let body = "id=" + intervent._id + "&question="+ question.text + "&user="+ question.user;
console.log(body);
headers.append("Authorization",window.localStorage.getItem("token"));
let options = new RequestOptions({ headers: headers });
return this.http.post(this.config.getApiUrl() + '/addquestion', body, options);
}
} | {
"content_hash": "62f582653f042f7537b453f065d9698d",
"timestamp": "",
"source": "github",
"line_count": 157,
"max_line_length": 209,
"avg_line_length": 59.6687898089172,
"alnum_prop": 0.6520068317677199,
"repo_name": "collab-uniba/scriba",
"id": "884869ab303a955594d777040b38021d258c7a12",
"size": "9368",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "client/src/services/event-services.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "6969"
},
{
"name": "Dockerfile",
"bytes": "1441"
},
{
"name": "Go",
"bytes": "364"
},
{
"name": "HTML",
"bytes": "73086"
},
{
"name": "JavaScript",
"bytes": "60949"
},
{
"name": "TypeScript",
"bytes": "88923"
}
],
"symlink_target": ""
} |
import pandas as pd
import numpy as np
data = pd.read_csv("data.csv")
# TODO: Separate the features and the labels into arrays called X and y
X = None
y = None | {
"content_hash": "5a9490456d2cffd854669be7f22bd0da",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 71,
"avg_line_length": 18,
"alnum_prop": 0.7222222222222222,
"repo_name": "hetaodie/hetaodie.github.io",
"id": "2015822421b9ed892cd2c214ebe8e24a6a46bbad",
"size": "162",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "assets/media/uda-ml/code/numpy/quiz.py",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "6473"
},
{
"name": "HTML",
"bytes": "3209874"
},
{
"name": "JavaScript",
"bytes": "5139"
},
{
"name": "Jupyter Notebook",
"bytes": "12180442"
},
{
"name": "Python",
"bytes": "161358"
},
{
"name": "Shell",
"bytes": "6554"
}
],
"symlink_target": ""
} |
module Pageflow
module ActiveAdminPatches
module Views
module AttributesTable
def boolean_status_tag_row(name, yes_state = :warning)
status_tag_row(name,
[I18n.t('active_admin.status_tag.yes'), '-'],
[yes_state, nil])
end
private
def status_tag_row(name, texts, types)
row(name, class: 'status_tag_row') do |record|
value = record.send(name)
status = value ? 'yes' : 'no'
text = value ? texts.first : texts.last
type = value ? types.first : types.last
if type
status_tag(status, class: [type, name.to_s.gsub(/\?$/, '')].join(' '), label: text)
else
text
end
end
end
end
end
end
end
| {
"content_hash": "3560f7bc8107be8b6359e8a997462b63",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 97,
"avg_line_length": 27.161290322580644,
"alnum_prop": 0.48812351543942994,
"repo_name": "codevise/pageflow",
"id": "cf2dce10fac624c77d5b6bdf36be5966b4791704",
"size": "842",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "lib/pageflow/active_admin_patches/views/attributes_table.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "107551"
},
{
"name": "EJS",
"bytes": "25300"
},
{
"name": "HTML",
"bytes": "55111"
},
{
"name": "JavaScript",
"bytes": "2717843"
},
{
"name": "Procfile",
"bytes": "128"
},
{
"name": "Ruby",
"bytes": "1864453"
},
{
"name": "SCSS",
"bytes": "304354"
},
{
"name": "Shell",
"bytes": "1438"
}
],
"symlink_target": ""
} |
@charset "UTF-8";
/* CSS Document */
<style type="text/css">
#tfheader{
background-color:#c3dfef;
}
#tfnewsearch{
float:right;
padding:20px;
}
.tftextinput{
margin: 0;
padding: 5px 15px;
font-family: Arial, Helvetica, sans-serif;
font-size:14px;
border:1px solid #0076a3; border-right:0px;
border-top-left-radius: 5px 5px;
border-bottom-left-radius: 5px 5px;
}
.tfbutton {
margin: 0;
padding: 5px 15px;
font-family: Arial, Helvetica, sans-serif;
font-size:14px;
outline: none;
cursor: pointer;
text-align: center;
text-decoration: none;
color: #000;
border: solid 1px #0076a3; border-right:0px;
background: #0095cd;
background: -webkit-gradient(linear, left top, left bottom, from(#fff), to(#ef9cb0));
background: -moz-linear-gradient(top, #fff, #ef9cb0);
border-top-right-radius: 5px 5px;
border-bottom-right-radius: 5px 5px;
}
.tfbutton:hover {
text-decoration: none;
background: #007ead;
background: -webkit-gradient(linear, left top, left bottom, from(#ef9cb0), to(#fff));
background: -moz-linear-gradient(top, #ef9cb0, #fff);
}
/* Fixes submit button height problem in Firefox */
.tfbutton::-moz-focus-inner {
border: 0;
}
.tfclear{
clear:both;
}
</style> | {
"content_hash": "8711cca2758849182ffe688bff1c90db",
"timestamp": "",
"source": "github",
"line_count": 51,
"max_line_length": 87,
"avg_line_length": 24.372549019607842,
"alnum_prop": 0.6790024135156878,
"repo_name": "guy00030/ecommerce-website",
"id": "8e8b5026bb8050f005aeec7a06338062f8dedd35",
"size": "1243",
"binary": false,
"copies": "1",
"ref": "refs/heads/gh-pages",
"path": "_includes/css/search-field.css",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "14285"
}
],
"symlink_target": ""
} |
close all
data_load = 0;
if data_load ~= 0
load_data;
end
% get the models from test data set
[linear_model,linear_lower_limit,linear_upper_limit,...
non_linear_model,ref_levels,ref_indexes] = calculate_pixel_models(model_pixels,light_level);
figure('Name','Linear model');
plot(linear_model);
figure('Name','Non-linear model');
plot(non_linear_model); | {
"content_hash": "6ce99430bdac00a9c95dce386b21d784",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 96,
"avg_line_length": 25.857142857142858,
"alnum_prop": 0.7209944751381215,
"repo_name": "danielojames/4yp",
"id": "8a0cd7146467f6d24aaf1c8733518d42798ad917",
"size": "362",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ShiftingMethod/test_calculate_pixel_models.m",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Matlab",
"bytes": "35629"
}
],
"symlink_target": ""
} |
* Add a config for the method name (#6)
### [ver 0.0.2](https://github.com/shiraji/new-instance-inspection/releases/tag/v0.0.2)
* Fix #2
### [ver 0.0.1](https://github.com/shiraji/new-instance-inspection/releases/tag/v0.0.1)
* Initial release
| {
"content_hash": "86ba849482536b63bf3b0ea119e14280",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 87,
"avg_line_length": 27.444444444444443,
"alnum_prop": 0.6923076923076923,
"repo_name": "shiraji/new-instance-inspection",
"id": "4df547b4c0447fc1737d9dee19a86539df221d75",
"size": "336",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "CHANGELOG.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "119"
},
{
"name": "Java",
"bytes": "7171"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<com.ce.game.myapplication.view.pincode.RippleView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/pin_code_keyboard_button_ripple"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:paddingBottom="@dimen/keyboard_button_padding"
android:paddingTop="@dimen/keyboard_button_padding"
app:rv_centered="true"
app:rv_color="@android:color/white"
app:rv_rippleDuration="@integer/ripple_effect_duration"
app:rv_ripplePadding="@dimen/keyboard_button_ripple_padding">
<TextView
android:id="@+id/keyboard_button_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:singleLine="true"
android:textColor="@color/white"
android:textSize="@dimen/keyboard_button_text_size"
/>
<ImageView
android:id="@+id/keyboard_button_imageview"
android:layout_width="@dimen/keyboard_button_size"
android:layout_height="@dimen/keyboard_button_size"
android:layout_centerInParent="true"
android:src="@drawable/unlockscreen_circle"
/>
</com.ce.game.myapplication.view.pincode.RippleView> | {
"content_hash": "fcc2a25cd794eeb11733ffbf90146bff",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 65,
"avg_line_length": 40.6764705882353,
"alnum_prop": 0.6999276934201012,
"repo_name": "KyleCe/MyTestApplication",
"id": "ed000d31892c9d96020e55e2904c494ac12bb4b5",
"size": "1383",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/res/layout/password_view_keyboard_button.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "584658"
},
{
"name": "Kotlin",
"bytes": "351"
}
],
"symlink_target": ""
} |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "shell.h"
#include "jerryscript.h"
#include "jerryscript-ext/handler.h"
#include "jerryscript-port.h"
/**
* Standalone Jerry exit codes
*/
#define JERRY_STANDALONE_EXIT_CODE_OK (0)
#define JERRY_STANDALONE_EXIT_CODE_FAIL (1)
/**
* Register a JavaScript function in the global object.
*/
static void
register_js_function (const char *name_p, /**< name of the function */
jerry_external_handler_t handler_p) /**< function callback */
{
jerry_value_t result_val = jerryx_handler_register_global ((const jerry_char_t *) name_p, handler_p);
if (jerry_value_is_error (result_val))
{
printf ("Warning: failed to register '%s' method.", name_p);
}
jerry_release_value (result_val);
} /* register_js_function */
/**
* Jerryscript simple test
*/
int test_jerry (int argc, char **argv)
{
/* Suppress compiler errors */
(void) argc;
(void) argv;
jerry_value_t ret_value = jerry_create_undefined ();
const jerry_char_t script[] = "print ('Hello, World!');";
printf ("This test run the following script code: [%s]\n\n", script);
/* Initialize engine */
jerry_init (JERRY_INIT_EMPTY);
/* Register the print function in the global object. */
register_js_function ("print", jerryx_handler_print);
/* Setup Global scope code */
ret_value = jerry_parse (NULL, 0, script, sizeof (script) - 1, JERRY_PARSE_NO_OPTS);
if (!jerry_value_is_error (ret_value))
{
/* Execute the parsed source code in the Global scope */
ret_value = jerry_run (ret_value);
}
int ret_code = JERRY_STANDALONE_EXIT_CODE_OK;
if (jerry_value_is_error (ret_value))
{
printf ("Script Error!");
ret_code = JERRY_STANDALONE_EXIT_CODE_FAIL;
}
jerry_release_value (ret_value);
/* Cleanup engine */
jerry_cleanup ();
return ret_code;
} /* test_jerry */
const shell_command_t shell_commands[] = {
{ "test", "Jerryscript Hello World test", test_jerry },
{ NULL, NULL, NULL }
};
int main (void)
{
union { double d; unsigned u; } now = { .d = jerry_port_get_current_time () };
srand (now.u);
printf ("You are running RIOT on a(n) %s board.\n", RIOT_BOARD);
printf ("This board features a(n) %s MCU.\n", RIOT_MCU);
/* start the shell */
char line_buf[SHELL_DEFAULT_BUFSIZE];
shell_run (shell_commands, line_buf, SHELL_DEFAULT_BUFSIZE);
return 0;
}
| {
"content_hash": "a095bb990cf525f04f13312cecf8ed8b",
"timestamp": "",
"source": "github",
"line_count": 98,
"max_line_length": 103,
"avg_line_length": 24.53061224489796,
"alnum_prop": 0.6501663893510815,
"repo_name": "akosthekiss/jerryscript",
"id": "28b9df84ad9ed35924024b9410af73f2e362269b",
"size": "3036",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "targets/riot-stm32f4/source/main-riotos.c",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "3218"
},
{
"name": "Batchfile",
"bytes": "2634"
},
{
"name": "C",
"bytes": "4532832"
},
{
"name": "C++",
"bytes": "367565"
},
{
"name": "CMake",
"bytes": "58961"
},
{
"name": "JavaScript",
"bytes": "2360905"
},
{
"name": "Makefile",
"bytes": "12683"
},
{
"name": "Python",
"bytes": "215296"
},
{
"name": "Riot",
"bytes": "2201"
},
{
"name": "Shell",
"bytes": "47305"
},
{
"name": "Tcl",
"bytes": "47435"
}
],
"symlink_target": ""
} |
// Copyright David Abrahams 2002.
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef FROM_PYTHON_AUX_DATA_DWA2002128_HPP
# define FROM_PYTHON_AUX_DATA_DWA2002128_HPP
# include <boost/python/converter/constructor_function.hpp>
# include <boost/python/detail/referent_storage.hpp>
# include <boost/python/detail/destroy.hpp>
# include <boost/python/detail/type_traits.hpp>
# include <boost/static_assert.hpp>
# include <cstddef>
// Data management for potential rvalue conversions from Python to C++
// types. When a client requests a conversion to T* or T&, we
// generally require that an object of type T exists in the source
// Python object, and the code here does not apply**. This implements
// conversions which may create new temporaries of type T. The classic
// example is a conversion which converts a Python tuple to a
// std::vector. Since no std::vector lvalue exists in the Python
// object -- it must be created "on-the-fly" by the converter, and
// which must manage the lifetime of the created object.
//
// Note that the client is not precluded from using a registered
// lvalue conversion to T in this case. In other words, we will
// happily accept a Python object which /does/ contain a std::vector
// lvalue, provided an appropriate converter is registered. So, while
// this is an rvalue conversion from the client's point-of-view, the
// converter registry may serve up lvalue or rvalue conversions for
// the target type.
//
// ** C++ argument from_python conversions to T const& are an
// exception to the rule for references: since in C++, const
// references can bind to temporary rvalues, we allow rvalue
// converters to be chosen when the target type is T const& for some
// T.
namespace boost { namespace python { namespace converter {
// Conversions begin by filling in and returning a copy of this
// structure. The process looks up a converter in the rvalue converter
// registry for the target type. It calls the convertible() function
// of each registered converter, passing the source PyObject* as an
// argument, until a non-null result is returned. This result goes in
// the convertible field, and the converter's construct() function is
// stored in the construct field.
//
// If no appropriate converter is found, conversion fails and the
// convertible field is null. When used in argument conversion for
// wrapped C++ functions, it causes overload resolution to reject the
// current function but not to fail completely. If an exception is
// thrown, overload resolution stops and the exception propagates back
// through the caller.
//
// If an lvalue converter is matched, its convertible() function is
// expected to return a pointer to the stored T object; its
// construct() function will be NULL. The convertible() function of
// rvalue converters may return any non-singular pointer; the actual
// target object will only be available once the converter's
// construct() function is called.
struct rvalue_from_python_stage1_data
{
void* convertible;
constructor_function construct;
};
// Augments rvalue_from_python_stage1_data by adding storage for
// constructing an object of remove_reference<T>::type. The
// construct() function of rvalue converters (stored in m_construct
// above) will cast the rvalue_from_python_stage1_data to an
// appropriate instantiation of this template in order to access that
// storage.
template <class T>
struct rvalue_from_python_storage
{
rvalue_from_python_stage1_data stage1;
// Storage for the result, in case an rvalue must be constructed
typename python::detail::referent_storage<
typename boost::python::detail::add_lvalue_reference<T>::type
>::type storage;
};
// Augments rvalue_from_python_storage<T> with a destructor. If
// stage1.convertible == storage.bytes, it indicates that an object of
// remove_reference<T>::type has been constructed in storage and
// should will be destroyed in ~rvalue_from_python_data(). It is
// crucial that successful rvalue conversions establish this equality
// and that unsuccessful ones do not.
template <class T>
struct rvalue_from_python_data : rvalue_from_python_storage<T>
{
# if (!defined(__MWERKS__) || __MWERKS__ >= 0x3000) \
&& (!defined(__EDG_VERSION__) || __EDG_VERSION__ >= 245) \
&& (!defined(__DECCXX_VER) || __DECCXX_VER > 60590014) \
&& !defined(BOOST_PYTHON_SYNOPSIS) /* Synopsis' OpenCXX has trouble parsing this */
// This must always be a POD struct with m_data its first member.
BOOST_STATIC_ASSERT(BOOST_PYTHON_OFFSETOF(rvalue_from_python_storage<T>,stage1) == 0);
# endif
// The usual constructor
rvalue_from_python_data(rvalue_from_python_stage1_data const&);
// This constructor just sets m_convertible -- used by
// implicitly_convertible<> to perform the final step of the
// conversion, where the construct() function is already known.
rvalue_from_python_data(void* convertible);
// Destroys any object constructed in the storage.
~rvalue_from_python_data();
private:
typedef typename boost::python::detail::add_lvalue_reference<
typename boost::python::detail::add_cv<T>::type>::type ref_type;
};
//
// Implementataions
//
template <class T>
inline rvalue_from_python_data<T>::rvalue_from_python_data(rvalue_from_python_stage1_data const& _stage1)
{
this->stage1 = _stage1;
}
template <class T>
inline rvalue_from_python_data<T>::rvalue_from_python_data(void* convertible)
{
this->stage1.convertible = convertible;
}
template <class T>
inline rvalue_from_python_data<T>::~rvalue_from_python_data()
{
if (this->stage1.convertible == this->storage.bytes)
python::detail::destroy_referent<ref_type>(this->storage.bytes);
}
}}} // namespace boost::python::converter
#endif // FROM_PYTHON_AUX_DATA_DWA2002128_HPP
| {
"content_hash": "91a6eef0c4eac8c52555843945de0299",
"timestamp": "",
"source": "github",
"line_count": 140,
"max_line_length": 105,
"avg_line_length": 43.45,
"alnum_prop": 0.7167516028275522,
"repo_name": "Owldream/Ginseng",
"id": "0b446e39561340e12e6b708b8b932776552dd437",
"size": "6083",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "include/ginseng/3rd-party/boost/python/converter/rvalue_from_python_data.hpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "2144"
},
{
"name": "C++",
"bytes": "612615"
},
{
"name": "CMake",
"bytes": "21889"
},
{
"name": "Objective-C++",
"bytes": "398"
}
],
"symlink_target": ""
} |
package at.ac.tuwien.inso.integration_tests;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import at.ac.tuwien.inso.entity.Course;
import at.ac.tuwien.inso.entity.Grade;
import at.ac.tuwien.inso.entity.Lecturer;
import at.ac.tuwien.inso.entity.Mark;
import at.ac.tuwien.inso.entity.Role;
import at.ac.tuwien.inso.entity.Semester;
import at.ac.tuwien.inso.entity.SemesterType;
import at.ac.tuwien.inso.entity.Student;
import at.ac.tuwien.inso.entity.Subject;
import at.ac.tuwien.inso.entity.UserAccount;
import at.ac.tuwien.inso.repository.CourseRepository;
import at.ac.tuwien.inso.repository.GradeRepository;
import at.ac.tuwien.inso.repository.LecturerRepository;
import at.ac.tuwien.inso.repository.SemesterRepository;
import at.ac.tuwien.inso.repository.StudentRepository;
import at.ac.tuwien.inso.repository.SubjectRepository;
import static java.util.Arrays.asList;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.anonymous;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model;
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
@ActiveProfiles("test")
@Transactional
public class PublicGradeTests {
@Autowired
private MockMvc mockMvc;
@Autowired
private GradeRepository gradeRepository;
@Autowired
private SubjectRepository subjectRepository;
@Autowired
private SemesterRepository semesterRepository;
@Autowired
private CourseRepository courseRepository;
@Autowired
private LecturerRepository lecturerRepository;
@Autowired
private StudentRepository studentRepository;
private Grade grade;
@Before
public void setUp() {
Subject subject = new Subject("Test", new BigDecimal(3));
subjectRepository.save(subject);
Semester semester = new Semester(2017, SemesterType.SummerSemester);
semesterRepository.save(semester);
Course course = new Course(subject, semester);
courseRepository.save(course);
Lecturer lecturer = new Lecturer("123", "TestLecturer", "[email protected]");
lecturerRepository.save(lecturer);
Student student = new Student("456", "TestStudent", "[email protected]");
studentRepository.save(student);
grade = gradeRepository.save(new Grade(course, lecturer, student, Mark.EXCELLENT));
grade.getId();
}
@Test
public void generateGradePDFTest() throws Exception {
grade = gradeRepository.findOne(grade.getId());
mockMvc.perform(
get("/public/grade?identifier=" + grade.getUrlIdentifier())
.with(anonymous())
.accept(MediaType.APPLICATION_PDF)
).andExpect(
model().attribute("grade", grade)
);
}
}
| {
"content_hash": "a72c6ab0ae2249d605a65a5468515200",
"timestamp": "",
"source": "github",
"line_count": 103,
"max_line_length": 115,
"avg_line_length": 34.76699029126213,
"alnum_prop": 0.7581681094666294,
"repo_name": "university-information-system/uis",
"id": "17e8c307046994305241b15ffc72d68e3ef27716",
"size": "3581",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/test/java/at/ac/tuwien/inso/integration_tests/PublicGradeTests.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "5006"
},
{
"name": "CSS",
"bytes": "4074"
},
{
"name": "HTML",
"bytes": "129874"
},
{
"name": "Java",
"bytes": "730794"
},
{
"name": "JavaScript",
"bytes": "10099"
},
{
"name": "Shell",
"bytes": "7058"
}
],
"symlink_target": ""
} |
(function() {
'use strict';
angular
.module('localbiz.wordpress', [
'ionic',
'localbiz.common'
])
.config(function($stateProvider) {
$stateProvider
.state('app.wordpress-articles', {
url: '/wordpress-articles',
views: {
'menuContent': {
templateUrl: 'scripts/wordpress/wordpress-articles.html',
controller: 'WordpressArticlesController as vm'
}
}
})
.state('app.wordpress-article', {
url: '/wordpress-articles/:articleId',
views: {
'menuContent': {
templateUrl: 'scripts/wordpress/wordpress-article.html',
controller: 'WordpressArticleController as vm'
}
}
});
});
})(); | {
"content_hash": "7209928117da71c32bd6c3d6d8ad2d7e",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 64,
"avg_line_length": 22.933333333333334,
"alnum_prop": 0.5988372093023255,
"repo_name": "skounis/ionic-stage",
"id": "e50e5e003dbe92c89e52237f2381e2145d661ca6",
"size": "688",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "stage/e20/scripts/wordpress/wordpress.module.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "516876"
},
{
"name": "HTML",
"bytes": "5094"
},
{
"name": "JavaScript",
"bytes": "2788685"
}
],
"symlink_target": ""
} |
package gov.hhs.fha.nhinc.docsubmission.adapter.deferred.response;
import javax.annotation.Resource;
import javax.xml.ws.BindingType;
import javax.xml.ws.WebServiceContext;
import javax.xml.ws.soap.Addressing;
/**
*
* @author JHOPPESC
*/
@BindingType(value = javax.xml.ws.soap.SOAPBinding.SOAP12HTTP_BINDING)
@Addressing(enabled = true)
public class AdapterXDRResponse implements gov.hhs.fha.nhinc.adapterxdrresponse.AdapterXDRResponsePortType {
@Resource
private WebServiceContext context;
public gov.hhs.healthit.nhin.XDRAcknowledgementType provideAndRegisterDocumentSetBResponse(
gov.hhs.fha.nhinc.common.nhinccommonadapter.AdapterRegistryResponseType body) {
return new AdapterXDRResponseImpl().provideAndRegisterDocumentSetBResponse(body, context);
}
}
| {
"content_hash": "23a5a0449dc32e732477d8ea6601bbaa",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 108,
"avg_line_length": 34.869565217391305,
"alnum_prop": 0.7955112219451371,
"repo_name": "AurionProject/Aurion",
"id": "f239dee4dd55f3be228d0697c2b59b3694ac07ea",
"size": "2494",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "Product/Production/Adapters/DocumentSubmission_a0/src/main/java/gov/hhs/fha/nhinc/docsubmission/adapter/deferred/response/AdapterXDRResponse.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Batchfile",
"bytes": "2465"
},
{
"name": "CSS",
"bytes": "62138"
},
{
"name": "Groovy",
"bytes": "1641"
},
{
"name": "HTML",
"bytes": "170838"
},
{
"name": "Java",
"bytes": "15665942"
},
{
"name": "JavaScript",
"bytes": "6991"
},
{
"name": "PLSQL",
"bytes": "110879"
},
{
"name": "Python",
"bytes": "773"
},
{
"name": "SQLPL",
"bytes": "1363363"
},
{
"name": "Shell",
"bytes": "30106"
},
{
"name": "XSLT",
"bytes": "35057"
}
],
"symlink_target": ""
} |
"""Invoke tasks. To run a task, run ``$ invoke <COMMAND>``. To see a list of
commands, run ``$ invoke --list``.
"""
import os
import sys
import json
import platform
import subprocess
import logging
from time import sleep
import invoke
from invoke import Collection
from website import settings
from .utils import pip_install, bin_prefix
logging.getLogger('invoke').setLevel(logging.CRITICAL)
# gets the root path for all the scripts that rely on it
HERE = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..'))
WHEELHOUSE_PATH = os.environ.get('WHEELHOUSE')
CONSTRAINTS_PATH = os.path.join(HERE, 'requirements', 'constraints.txt')
ns = Collection()
try:
from admin import tasks as admin_tasks
ns.add_collection(Collection.from_module(admin_tasks), name='admin')
except ImportError:
pass
def task(*args, **kwargs):
"""Behaves the same way as invoke.task. Adds the task
to the root namespace.
"""
if len(args) == 1 and callable(args[0]):
new_task = invoke.task(args[0])
ns.add_task(new_task)
return new_task
def decorator(f):
new_task = invoke.task(f, *args, **kwargs)
ns.add_task(new_task)
return new_task
return decorator
@task
def server(ctx, host=None, port=5000, debug=True, gitlogs=False):
"""Run the app server."""
if os.environ.get('WERKZEUG_RUN_MAIN') == 'true' or not debug:
if os.environ.get('WEB_REMOTE_DEBUG', None):
import pydevd
# e.g. '127.0.0.1:5678'
remote_parts = os.environ.get('WEB_REMOTE_DEBUG').split(':')
pydevd.settrace(remote_parts[0], port=int(remote_parts[1]), suspend=False, stdoutToServer=True, stderrToServer=True)
if gitlogs:
git_logs(ctx)
from website.app import init_app
os.environ['DJANGO_SETTINGS_MODULE'] = 'api.base.settings'
app = init_app(set_backends=True, routes=True)
settings.API_SERVER_PORT = port
else:
from framework.flask import app
context = None
if settings.SECURE_MODE:
context = (settings.OSF_SERVER_CERT, settings.OSF_SERVER_KEY)
app.run(host=host, port=port, debug=debug, threaded=debug, extra_files=[settings.ASSET_HASH_PATH], ssl_context=context)
@task
def git_logs(ctx, branch=None):
from scripts.meta import gatherer
gatherer.main(branch=branch)
@task
def apiserver(ctx, port=8000, wait=True, autoreload=True, host='127.0.0.1', pty=True):
"""Run the API server."""
env = os.environ.copy()
cmd = 'DJANGO_SETTINGS_MODULE=api.base.settings {} manage.py runserver {}:{} --nothreading'\
.format(sys.executable, host, port)
if not autoreload:
cmd += ' --noreload'
if settings.SECURE_MODE:
cmd = cmd.replace('runserver', 'runsslserver')
cmd += ' --certificate {} --key {}'.format(settings.OSF_SERVER_CERT, settings.OSF_SERVER_KEY)
if wait:
return ctx.run(cmd, echo=True, pty=pty)
from subprocess import Popen
return Popen(cmd, shell=True, env=env)
@task
def adminserver(ctx, port=8001, host='127.0.0.1', pty=True):
"""Run the Admin server."""
env = 'DJANGO_SETTINGS_MODULE="admin.base.settings"'
cmd = '{} python manage.py runserver {}:{} --nothreading'.format(env, host, port)
if settings.SECURE_MODE:
cmd = cmd.replace('runserver', 'runsslserver')
cmd += ' --certificate {} --key {}'.format(settings.OSF_SERVER_CERT, settings.OSF_SERVER_KEY)
ctx.run(cmd, echo=True, pty=pty)
@task
def shell(ctx, transaction=True, print_sql=False, notebook=False):
cmd = 'DJANGO_SETTINGS_MODULE="api.base.settings" python manage.py osf_shell'
if print_sql:
cmd += ' --print-sql'
if notebook:
cmd += ' --notebook'
if not transaction:
cmd += ' --no-transaction'
return ctx.run(cmd, pty=True, echo=True)
@task(aliases=['mongo'])
def mongoserver(ctx, daemon=False, config=None):
"""Run the mongod process.
"""
if not config:
platform_configs = {
'darwin': '/usr/local/etc/tokumx.conf', # default for homebrew install
'linux': '/etc/tokumx.conf',
}
platform = str(sys.platform).lower()
config = platform_configs.get(platform)
port = settings.DB_PORT
cmd = 'mongod --port {0}'.format(port)
if config:
cmd += ' --config {0}'.format(config)
if daemon:
cmd += ' --fork'
ctx.run(cmd, echo=True)
@task(aliases=['mongoshell'])
def mongoclient(ctx):
"""Run the mongo shell for the OSF database."""
db = settings.DB_NAME
port = settings.DB_PORT
ctx.run('mongo {db} --port {port}'.format(db=db, port=port), pty=True)
@task
def mongodump(ctx, path):
"""Back up the contents of the running OSF database"""
db = settings.DB_NAME
port = settings.DB_PORT
cmd = 'mongodump --db {db} --port {port} --out {path}'.format(
db=db,
port=port,
path=path,
pty=True)
if settings.DB_USER:
cmd += ' --username {0}'.format(settings.DB_USER)
if settings.DB_PASS:
cmd += ' --password {0}'.format(settings.DB_PASS)
ctx.run(cmd, echo=True)
print()
print('To restore from the dumped database, run `invoke mongorestore {0}`'.format(
os.path.join(path, settings.DB_NAME)))
@task
def mongorestore(ctx, path, drop=False):
"""Restores the running OSF database with the contents of the database at
the location given its argument.
By default, the contents of the specified database are added to
the existing database. The `--drop` option will cause the existing database
to be dropped.
A caveat: if you `invoke mongodump {path}`, you must restore with
`invoke mongorestore {path}/{settings.DB_NAME}, as that's where the
database dump will be stored.
"""
db = settings.DB_NAME
port = settings.DB_PORT
cmd = 'mongorestore --db {db} --port {port}'.format(
db=db,
port=port,
pty=True)
if settings.DB_USER:
cmd += ' --username {0}'.format(settings.DB_USER)
if settings.DB_PASS:
cmd += ' --password {0}'.format(settings.DB_PASS)
if drop:
cmd += ' --drop'
cmd += ' ' + path
ctx.run(cmd, echo=True)
@task
def sharejs(ctx, host=None, port=None, db_url=None, cors_allow_origin=None):
"""Start a local ShareJS server."""
if host:
os.environ['SHAREJS_SERVER_HOST'] = host
if port:
os.environ['SHAREJS_SERVER_PORT'] = port
if db_url:
os.environ['SHAREJS_DB_URL'] = db_url
if cors_allow_origin:
os.environ['SHAREJS_CORS_ALLOW_ORIGIN'] = cors_allow_origin
if settings.SENTRY_DSN:
os.environ['SHAREJS_SENTRY_DSN'] = settings.SENTRY_DSN
share_server = os.path.join(settings.ADDON_PATH, 'wiki', 'shareServer.js')
ctx.run('node {0}'.format(share_server))
@task(aliases=['celery'])
def celery_worker(ctx, level='debug', hostname=None, beat=False, queues=None, concurrency=None, max_tasks_per_child=None):
"""Run the Celery process."""
os.environ['DJANGO_SETTINGS_MODULE'] = 'api.base.settings'
cmd = 'celery worker -A framework.celery_tasks -Ofair -l {0}'.format(level)
if hostname:
cmd = cmd + ' --hostname={}'.format(hostname)
# beat sets up a cron like scheduler, refer to website/settings
if beat:
cmd = cmd + ' --beat'
if queues:
cmd = cmd + ' --queues={}'.format(queues)
if concurrency:
cmd = cmd + ' --concurrency={}'.format(concurrency)
if max_tasks_per_child:
cmd = cmd + ' --maxtasksperchild={}'.format(max_tasks_per_child)
ctx.run(bin_prefix(cmd), pty=True)
@task(aliases=['beat'])
def celery_beat(ctx, level='debug', schedule=None):
"""Run the Celery process."""
os.environ['DJANGO_SETTINGS_MODULE'] = 'api.base.settings'
# beat sets up a cron like scheduler, refer to website/settings
cmd = 'celery beat -A framework.celery_tasks -l {0} --pidfile='.format(level)
if schedule:
cmd = cmd + ' --schedule={}'.format(schedule)
ctx.run(bin_prefix(cmd), pty=True)
@task
def rabbitmq(ctx):
"""Start a local rabbitmq server.
NOTE: this is for development only. The production environment should start
the server as a daemon.
"""
ctx.run('rabbitmq-server', pty=True)
@task(aliases=['elastic'])
def elasticsearch(ctx):
"""Start a local elasticsearch server
NOTE: Requires that elasticsearch is installed. See README for instructions
"""
import platform
if platform.linux_distribution()[0] == 'Ubuntu':
ctx.run('sudo service elasticsearch start')
elif platform.system() == 'Darwin': # Mac OSX
ctx.run('elasticsearch')
else:
print('Your system is not recognized, you will have to start elasticsearch manually')
@task
def migrate_search(ctx, delete=False, index=settings.ELASTIC_INDEX):
"""Migrate the search-enabled models."""
from website.app import init_app
init_app(routes=False, set_backends=False)
from website.search_migration.migrate import migrate
# NOTE: Silence the warning:
# "InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised."
SILENT_LOGGERS = ['py.warnings']
for logger in SILENT_LOGGERS:
logging.getLogger(logger).setLevel(logging.ERROR)
migrate(delete, index=index)
@task
def rebuild_search(ctx):
"""Delete and recreate the index for elasticsearch"""
from website.app import init_app
import requests
from website import settings
init_app(routes=False, set_backends=True)
if not settings.ELASTIC_URI.startswith('http'):
protocol = 'http://' if settings.DEBUG_MODE else 'https://'
else:
protocol = ''
url = '{protocol}{uri}/{index}'.format(
protocol=protocol,
uri=settings.ELASTIC_URI.rstrip('/'),
index=settings.ELASTIC_INDEX,
)
print('Deleting index {}'.format(settings.ELASTIC_INDEX))
print('----- DELETE {}*'.format(url))
requests.delete(url + '*')
print('Creating index {}'.format(settings.ELASTIC_INDEX))
print('----- PUT {}'.format(url))
requests.put(url)
migrate_search(ctx)
@task
def mailserver(ctx, port=1025):
"""Run a SMTP test server."""
cmd = 'python -m smtpd -n -c DebuggingServer localhost:{port}'.format(port=port)
ctx.run(bin_prefix(cmd), pty=True)
@task
def jshint(ctx):
"""Run JSHint syntax check"""
js_folder = os.path.join(HERE, 'website', 'static', 'js')
jshint_bin = os.path.join(HERE, 'node_modules', '.bin', 'jshint')
cmd = '{} {}'.format(jshint_bin, js_folder)
ctx.run(cmd, echo=True)
@task(aliases=['flake8'])
def flake(ctx):
ctx.run('flake8 .', echo=True)
@task(aliases=['req'])
def requirements(ctx, base=False, addons=False, release=False, dev=False, quick=False):
"""Install python dependencies.
Examples:
inv requirements
inv requirements --quick
Quick requirements are, in order, addons, dev and the base requirements. You should be able to use --quick for
day to day development.
By default, base requirements will run. However, if any set of addons, release, or dev are chosen, base
will have to be mentioned explicitly in order to run. This is to remain compatible with previous usages. Release
requirements will prevent dev, and base from running.
"""
if quick:
base = True
addons = True
dev = True
if not(addons or dev):
base = True
if release or addons:
addon_requirements(ctx)
# "release" takes precedence
if release:
req_file = os.path.join(HERE, 'requirements', 'release.txt')
ctx.run(
pip_install(req_file, constraints_file=CONSTRAINTS_PATH),
echo=True
)
else:
if dev: # then dev requirements
req_file = os.path.join(HERE, 'requirements', 'dev.txt')
ctx.run(
pip_install(req_file, constraints_file=CONSTRAINTS_PATH),
echo=True
)
if base: # then base requirements
req_file = os.path.join(HERE, 'requirements.txt')
ctx.run(
pip_install(req_file, constraints_file=CONSTRAINTS_PATH),
echo=True
)
# fix URITemplate name conflict h/t @github
ctx.run('pip uninstall uritemplate.py --yes || true')
ctx.run('pip install --no-cache-dir uritemplate.py==0.3.0')
@task
def test_module(ctx, module=None, numprocesses=None, nocapture=False, params=None):
"""Helper for running tests.
"""
os.environ['DJANGO_SETTINGS_MODULE'] = 'osf_tests.settings'
import pytest
if not numprocesses:
from multiprocessing import cpu_count
numprocesses = cpu_count()
# NOTE: Subprocess to compensate for lack of thread safety in the httpretty module.
# https://github.com/gabrielfalcao/HTTPretty/issues/209#issue-54090252
if nocapture:
args = []
else:
args = ['-s']
if numprocesses > 1:
args += ['-n {}'.format(numprocesses), '--max-slave-restart=0']
modules = [module] if isinstance(module, basestring) else module
args.extend(modules)
if params:
params = [params] if isinstance(params, basestring) else params
args.extend(params)
retcode = pytest.main(args)
sys.exit(retcode)
OSF_TESTS = [
'osf_tests',
]
ELSE_TESTS = [
'tests',
]
API_TESTS1 = [
'api_tests/identifiers',
'api_tests/institutions',
'api_tests/licenses',
'api_tests/logs',
'api_tests/metaschemas',
'api_tests/preprint_providers',
'api_tests/preprints',
'api_tests/registrations',
'api_tests/users',
]
API_TESTS2 = [
'api_tests/nodes',
]
API_TESTS3 = [
'api_tests/addons_tests',
'api_tests/applications',
'api_tests/base',
'api_tests/collections',
'api_tests/comments',
'api_tests/files',
'api_tests/guids',
'api_tests/reviews',
'api_tests/search',
'api_tests/taxonomies',
'api_tests/test',
'api_tests/tokens',
'api_tests/view_only_links',
'api_tests/wikis',
]
ADDON_TESTS = [
'addons',
]
ADMIN_TESTS = [
'admin_tests',
]
@task
def test_osf(ctx, numprocesses=None):
"""Run the OSF test suite."""
print('Testing modules "{}"'.format(OSF_TESTS))
test_module(ctx, module=OSF_TESTS, numprocesses=numprocesses)
@task
def test_else(ctx, numprocesses=None):
"""Run the old test suite."""
print('Testing modules "{}"'.format(ELSE_TESTS))
test_module(ctx, module=ELSE_TESTS, numprocesses=numprocesses)
@task
def test_api1(ctx, numprocesses=None):
"""Run the API test suite."""
print('Testing modules "{}"'.format(API_TESTS1 + ADMIN_TESTS))
test_module(ctx, module=API_TESTS1 + ADMIN_TESTS, numprocesses=numprocesses)
@task
def test_api2(ctx, numprocesses=None):
"""Run the API test suite."""
print('Testing modules "{}"'.format(API_TESTS2))
test_module(ctx, module=API_TESTS2, numprocesses=numprocesses)
@task
def test_api3(ctx, numprocesses=None):
"""Run the API test suite."""
print('Testing modules "{}"'.format(API_TESTS3 + OSF_TESTS))
test_module(ctx, module=API_TESTS3 + OSF_TESTS, numprocesses=numprocesses)
@task
def test_admin(ctx, numprocesses=None):
"""Run the Admin test suite."""
print('Testing module "admin_tests"')
test_module(ctx, module=ADMIN_TESTS, numprocesses=numprocesses)
@task
def test_addons(ctx, numprocesses=None):
"""Run all the tests in the addons directory.
"""
print('Testing modules "{}"'.format(ADDON_TESTS))
test_module(ctx, module=ADDON_TESTS, numprocesses=numprocesses)
@task
def test_varnish(ctx):
"""Run the Varnish test suite."""
proc = apiserver(ctx, wait=False, autoreload=False)
try:
sleep(5)
test_module(ctx, module='api/caching/tests/test_caching.py')
finally:
proc.kill()
@task
def test(ctx, all=False, syntax=False):
"""
Run unit tests: OSF (always), plus addons and syntax checks (optional)
"""
if syntax:
flake(ctx)
jshint(ctx)
test_else(ctx) # /tests
test_api1(ctx)
test_api2(ctx)
test_api3(ctx) # also /osf_tests
if all:
test_addons(ctx)
# TODO: Enable admin tests
test_admin(ctx)
karma(ctx)
@task
def test_js(ctx):
jshint(ctx)
karma(ctx)
@task
def test_travis_addons(ctx, numprocesses=None):
"""
Run half of the tests to help travis go faster. Lints and Flakes happen everywhere to keep from wasting test time.
"""
flake(ctx)
jshint(ctx)
test_addons(ctx, numprocesses=numprocesses)
@task
def test_travis_else(ctx, numprocesses=None):
"""
Run other half of the tests to help travis go faster. Lints and Flakes happen everywhere to keep from
wasting test time.
"""
flake(ctx)
jshint(ctx)
test_else(ctx, numprocesses=numprocesses)
@task
def test_travis_api1_and_js(ctx, numprocesses=None):
flake(ctx)
jshint(ctx)
karma(ctx)
test_api1(ctx, numprocesses=numprocesses)
@task
def test_travis_api2(ctx, numprocesses=None):
flake(ctx)
jshint(ctx)
test_api2(ctx, numprocesses=numprocesses)
@task
def test_travis_api3_and_osf(ctx, numprocesses=None):
flake(ctx)
jshint(ctx)
test_api3(ctx, numprocesses=numprocesses)
@task
def test_travis_varnish(ctx):
"""
Run the fast and quirky JS tests and varnish tests in isolation
"""
flake(ctx)
jshint(ctx)
test_js(ctx)
test_varnish(ctx)
@task
def karma(ctx):
"""Run JS tests with Karma. Requires Chrome to be installed."""
ctx.run('yarn test', echo=True)
@task
def wheelhouse(ctx, addons=False, release=False, dev=False, pty=True):
"""Build wheels for python dependencies.
Examples:
inv wheelhouse --dev
inv wheelhouse --addons
inv wheelhouse --release
"""
if release or addons:
for directory in os.listdir(settings.ADDON_PATH):
path = os.path.join(settings.ADDON_PATH, directory)
if os.path.isdir(path):
req_file = os.path.join(path, 'requirements.txt')
if os.path.exists(req_file):
cmd = 'pip wheel --find-links={} -r {} --wheel-dir={} -c {}'.format(
WHEELHOUSE_PATH, req_file, WHEELHOUSE_PATH, CONSTRAINTS_PATH,
)
ctx.run(cmd, pty=pty)
if release:
req_file = os.path.join(HERE, 'requirements', 'release.txt')
elif dev:
req_file = os.path.join(HERE, 'requirements', 'dev.txt')
else:
req_file = os.path.join(HERE, 'requirements.txt')
cmd = 'pip wheel --find-links={} -r {} --wheel-dir={} -c {}'.format(
WHEELHOUSE_PATH, req_file, WHEELHOUSE_PATH, CONSTRAINTS_PATH,
)
ctx.run(cmd, pty=pty)
@task
def addon_requirements(ctx):
"""Install all addon requirements."""
for directory in os.listdir(settings.ADDON_PATH):
path = os.path.join(settings.ADDON_PATH, directory)
requirements_file = os.path.join(path, 'requirements.txt')
if os.path.isdir(path) and os.path.isfile(requirements_file):
print('Installing requirements for {0}'.format(directory))
ctx.run(
pip_install(requirements_file, constraints_file=CONSTRAINTS_PATH),
echo=True
)
print('Finished installing addon requirements')
@task
def travis_addon_settings(ctx):
for directory in os.listdir(settings.ADDON_PATH):
path = os.path.join(settings.ADDON_PATH, directory, 'settings')
if os.path.isdir(path):
try:
open(os.path.join(path, 'local-travis.py'))
ctx.run('cp {path}/local-travis.py {path}/local.py'.format(path=path))
except IOError:
pass
@task
def copy_addon_settings(ctx):
for directory in os.listdir(settings.ADDON_PATH):
path = os.path.join(settings.ADDON_PATH, directory, 'settings')
if os.path.isdir(path) and not os.path.isfile(os.path.join(path, 'local.py')):
try:
open(os.path.join(path, 'local-dist.py'))
ctx.run('cp {path}/local-dist.py {path}/local.py'.format(path=path))
except IOError:
pass
@task
def copy_settings(ctx, addons=False):
# Website settings
if not os.path.isfile('website/settings/local.py'):
print('Creating local.py file')
ctx.run('cp website/settings/local-dist.py website/settings/local.py')
# Addon settings
if addons:
copy_addon_settings(ctx)
@task(aliases=['bower'])
def bower_install(ctx):
print('Installing bower-managed packages')
bower_bin = os.path.join(HERE, 'node_modules', '.bin', 'bower')
ctx.run('{} prune --allow-root'.format(bower_bin), echo=True)
ctx.run('{} install --allow-root'.format(bower_bin), echo=True)
@task
def docker_init(ctx):
"""Initial docker setup"""
print('You will be asked for your sudo password to continue...')
if platform.system() == 'Darwin': # Mac OSX
ctx.run('sudo ifconfig lo0 alias 192.168.168.167')
else:
print('Your system is not recognized, you will have to setup docker manually')
def ensure_docker_env_setup(ctx):
if hasattr(os.environ, 'DOCKER_ENV_SETUP') and os.environ['DOCKER_ENV_SETUP'] == '1':
pass
else:
os.environ['WEB_REMOTE_DEBUG'] = '192.168.168.167:11000'
os.environ['API_REMOTE_DEBUG'] = '192.168.168.167:12000'
os.environ['WORKER_REMOTE_DEBUG'] = '192.168.168.167:13000'
os.environ['DOCKER_ENV_SETUP'] = '1'
docker_init(ctx)
@task
def docker_requirements(ctx):
ensure_docker_env_setup(ctx)
ctx.run('docker-compose up requirements requirements_mfr requirements_wb')
@task
def docker_appservices(ctx):
ensure_docker_env_setup(ctx)
ctx.run('docker-compose up assets fakecas elasticsearch tokumx postgres')
@task
def docker_osf(ctx):
ensure_docker_env_setup(ctx)
ctx.run('docker-compose up mfr wb web api')
@task
def clear_sessions(ctx, months=1, dry_run=False):
from website.app import init_app
init_app(routes=False, set_backends=True)
from scripts import clear_sessions
clear_sessions.clear_sessions_relative(months=months, dry_run=dry_run)
# Release tasks
@task
def hotfix(ctx, name, finish=False, push=False):
"""Rename hotfix branch to hotfix/<next-patch-version> and optionally
finish hotfix.
"""
print('Checking out master to calculate curent version')
ctx.run('git checkout master')
latest_version = latest_tag_info()['current_version']
print('Current version is: {}'.format(latest_version))
major, minor, patch = latest_version.split('.')
next_patch_version = '.'.join([major, minor, str(int(patch) + 1)])
print('Bumping to next patch version: {}'.format(next_patch_version))
print('Renaming branch...')
new_branch_name = 'hotfix/{}'.format(next_patch_version)
ctx.run('git checkout {}'.format(name), echo=True)
ctx.run('git branch -m {}'.format(new_branch_name), echo=True)
if finish:
ctx.run('git flow hotfix finish {}'.format(next_patch_version), echo=True, pty=True)
if push:
ctx.run('git push origin master', echo=True)
ctx.run('git push --tags', echo=True)
ctx.run('git push origin develop', echo=True)
@task
def feature(ctx, name, finish=False, push=False):
"""Rename the current branch to a feature branch and optionally finish it."""
print('Renaming branch...')
ctx.run('git branch -m feature/{}'.format(name), echo=True)
if finish:
ctx.run('git flow feature finish {}'.format(name), echo=True)
if push:
ctx.run('git push origin develop', echo=True)
# Adapted from bumpversion
def latest_tag_info():
try:
# git-describe doesn't update the git-index, so we do that
# subprocess.check_output(["git", "update-index", "--refresh"])
# get info about the latest tag in git
describe_out = subprocess.check_output([
'git',
'describe',
'--dirty',
'--tags',
'--long',
'--abbrev=40'
], stderr=subprocess.STDOUT
).decode().split('-')
except subprocess.CalledProcessError as err:
raise err
# logger.warn("Error when running git describe")
return {}
info = {}
if describe_out[-1].strip() == 'dirty':
info['dirty'] = True
describe_out.pop()
info['commit_sha'] = describe_out.pop().lstrip('g')
info['distance_to_latest_tag'] = int(describe_out.pop())
info['current_version'] = describe_out.pop().lstrip('v')
# assert type(info["current_version"]) == str
assert 0 == len(describe_out)
return info
# Tasks for generating and bundling SSL certificates
# See http://cosdev.readthedocs.org/en/latest/osf/ops.html for details
@task
def generate_key(ctx, domain, bits=2048):
cmd = 'openssl genrsa -des3 -out {0}.key {1}'.format(domain, bits)
ctx.run(cmd)
@task
def generate_key_nopass(ctx, domain):
cmd = 'openssl rsa -in {domain}.key -out {domain}.key.nopass'.format(
domain=domain
)
ctx.run(cmd)
@task
def generate_csr(ctx, domain):
cmd = 'openssl req -new -key {domain}.key.nopass -out {domain}.csr'.format(
domain=domain
)
ctx.run(cmd)
@task
def request_ssl_cert(ctx, domain):
"""Generate a key, a key with password removed, and a signing request for
the specified domain.
Usage:
> invoke request_ssl_cert pizza.osf.io
"""
generate_key(ctx, domain)
generate_key_nopass(ctx, domain)
generate_csr(ctx, domain)
@task
def bundle_certs(ctx, domain, cert_path):
"""Concatenate certificates from NameCheap in the correct order. Certificate
files must be in the same directory.
"""
cert_files = [
'{0}.crt'.format(domain),
'COMODORSADomainValidationSecureServerCA.crt',
'COMODORSAAddTrustCA.crt',
'AddTrustExternalCARoot.crt',
]
certs = ' '.join(
os.path.join(cert_path, cert_file)
for cert_file in cert_files
)
cmd = 'cat {certs} > {domain}.bundle.crt'.format(
certs=certs,
domain=domain,
)
ctx.run(cmd)
@task
def clean_assets(ctx):
"""Remove built JS files."""
public_path = os.path.join(HERE, 'website', 'static', 'public')
js_path = os.path.join(public_path, 'js')
ctx.run('rm -rf {0}'.format(js_path), echo=True)
@task(aliases=['pack'])
def webpack(ctx, clean=False, watch=False, dev=False, colors=False):
"""Build static assets with webpack."""
if clean:
clean_assets(ctx)
args = ['yarn run webpack-{}'.format('dev' if dev else 'prod')]
args += ['--progress']
if watch:
args += ['--watch']
if colors:
args += ['--colors']
command = ' '.join(args)
ctx.run(command, echo=True)
@task()
def build_js_config_files(ctx):
from website import settings
print('Building JS config files...')
with open(os.path.join(settings.STATIC_FOLDER, 'built', 'nodeCategories.json'), 'wb') as fp:
json.dump(settings.NODE_CATEGORY_MAP, fp)
print('...Done.')
@task()
def assets(ctx, dev=False, watch=False, colors=False):
"""Install and build static assets."""
command = 'yarn install --frozen-lockfile'
if not dev:
command += ' --production'
ctx.run(command, echo=True)
bower_install(ctx)
build_js_config_files(ctx)
# Always set clean=False to prevent possible mistakes
# on prod
webpack(ctx, clean=False, watch=watch, dev=dev, colors=colors)
@task
def generate_self_signed(ctx, domain):
"""Generate self-signed SSL key and certificate.
"""
cmd = (
'openssl req -x509 -nodes -days 365 -newkey rsa:2048'
' -keyout {0}.key -out {0}.crt'
).format(domain)
ctx.run(cmd)
@task
def update_citation_styles(ctx):
from scripts import parse_citation_styles
total = parse_citation_styles.main()
print('Parsed {} styles'.format(total))
@task
def clean(ctx, verbose=False):
ctx.run('find . -name "*.pyc" -delete', echo=True)
@task(default=True)
def usage(ctx):
ctx.run('invoke --list')
### Maintenance Tasks ###
@task
def set_maintenance(ctx, message='', level=1, start=None, end=None):
from website.app import setup_django
setup_django()
from website.maintenance import set_maintenance
"""Display maintenance notice across OSF applications (incl. preprints, registries, etc.)
start - Start time for the maintenance period
end - End time for the mainteance period
NOTE: If no start or end values are provided, default to starting now
and ending 24 hours from now.
message - Message to display. If omitted, will be:
"The site will undergo maintenance between <localized start time> and <localized end time>. Thank you
for your patience."
level - Severity level. Modifies the color of the displayed notice. Must be one of 1 (info), 2 (warning), 3 (danger).
Examples:
invoke set_maintenance --start 2016-03-16T15:41:00-04:00 --end 2016-03-16T15:42:00-04:00
invoke set_maintenance --message 'The OSF is experiencing issues connecting to a 3rd party service' --level 2 --start 2016-03-16T15:41:00-04:00 --end 2016-03-16T15:42:00-04:00
"""
state = set_maintenance(message, level, start, end)
print('Maintenance notice up {} to {}.'.format(state['start'], state['end']))
@task
def unset_maintenance(ctx):
from website.app import setup_django
setup_django()
from website.maintenance import unset_maintenance
print('Taking down maintenance notice...')
unset_maintenance()
print('...Done.')
| {
"content_hash": "5f468d1ea3d274bef4d23eb84e2f69d5",
"timestamp": "",
"source": "github",
"line_count": 985,
"max_line_length": 183,
"avg_line_length": 30.363451776649747,
"alnum_prop": 0.6368530159154742,
"repo_name": "crcresearch/osf.io",
"id": "63845570742f64c9a1392a1d26b6686bd5d97276",
"size": "29954",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "tasks/__init__.py",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "110148"
},
{
"name": "HTML",
"bytes": "225000"
},
{
"name": "JavaScript",
"bytes": "1807027"
},
{
"name": "Mako",
"bytes": "642435"
},
{
"name": "Python",
"bytes": "7499660"
},
{
"name": "VCL",
"bytes": "13885"
}
],
"symlink_target": ""
} |
using System;
using System.Linq;
using System.Text.RegularExpressions;
/*Write a program that extracts from given HTML file its title (if available), and its body text without the HTML tags.
Example input: Output:
<html>
<head><title>News</title></head> Title: News
<body><p><a href="http://academy.telerik.com">Telerik Text: Telerik Academy aims to provide
Academy</a>aims to provide free real-world practical free real-world practical training
training for young people who want to turn into for young people who want to turn
skilful .NET software engineers.</p></body> into skilful .NET software engineers.
</html> */
class ExtractTextFromHTML
{
static void Main()
{
string text = "<html><head><title>News</title></head><body><p><a href=\"http://academy.telerik.com\">Telerik Academy</a>aims to provide free real-world practical training for young people who want to turn into skilful .NET software engineers.</p></body></html>";
MatchCollection tags = Regex.Matches(text, @"((?<=^|>)[^><]+?(?=<|$))");
int count = 1;
foreach (Match tag in tags)
{
if (count == 1)
{
Console.WriteLine("Title: {0}", tag);
Console.Write("Text: ");
}
else
{
Console.Write(tag + " ");
}
count++;
}
Console.WriteLine();
}
}
| {
"content_hash": "66de58f8f272e2aa26738026af8ddbbe",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 270,
"avg_line_length": 42.17948717948718,
"alnum_prop": 0.5252279635258359,
"repo_name": "baretata/CSharpPartTwo",
"id": "15858837048edd5cd0df4e1044f6e2199f9da231",
"size": "1647",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "StringsAndTextProcessing/25.ExtractTextFromHTML/ExtractTextFromHTML.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "272750"
}
],
"symlink_target": ""
} |
package com.corejsf.util;
import javax.el.MethodExpression;
import javax.faces.component.UIComponent;
import javax.faces.event.FacesEvent;
import javax.faces.event.FacesListener;
public class MethodEvent extends FacesEvent {
private MethodExpression method;
private Object[] args;
public MethodEvent(UIComponent source, MethodExpression method, Object... args) {
super(source);
this.method = method;
this.args = args;
}
@Override public boolean isAppropriateListener(FacesListener listener) {
return listener instanceof MethodListener;
}
@Override public void processListener(FacesListener listener) {
((MethodListener) listener).process(method, args);
}
} | {
"content_hash": "427a53d4020212a217cabc9aa6c7e16d",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 84,
"avg_line_length": 28.72,
"alnum_prop": 0.745125348189415,
"repo_name": "thescouser89/snippets",
"id": "ba3f605dbfcfcee1a32f540461ab7678123c08d0",
"size": "735",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "jsf/javaee/ch11/spinner2/src/java/com/corejsf/util/MethodEvent.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "426"
},
{
"name": "CSS",
"bytes": "6738"
},
{
"name": "Java",
"bytes": "240783"
},
{
"name": "JavaScript",
"bytes": "12295"
},
{
"name": "Python",
"bytes": "596"
},
{
"name": "Ruby",
"bytes": "2346"
},
{
"name": "Shell",
"bytes": "5499"
}
],
"symlink_target": ""
} |
UPDATE meta SET meta_value='61' WHERE meta_key='schema_version';
# Patch identifier
INSERT INTO meta (species_id, meta_key, meta_value)
VALUES (NULL, 'patch', 'patch_60_61_a.sql|schema_version');
| {
"content_hash": "a66388c43c514fa7ef4abe58a038bcc7",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 64,
"avg_line_length": 39.8,
"alnum_prop": 0.7236180904522613,
"repo_name": "willmclaren/ensembl",
"id": "fa3ee1c9747c8def8cf6b82a9f2bd9e2e45b189c",
"size": "985",
"binary": false,
"copies": "1",
"ref": "refs/heads/release/75",
"path": "sql/patch_60_61_a.sql",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "7944"
},
{
"name": "Perl",
"bytes": "6178011"
},
{
"name": "Shell",
"bytes": "5007"
}
],
"symlink_target": ""
} |
.. Pysllo documentation master file, created by
sphinx-quickstart on Tue May 31 19:45:48 2016.
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.
Welcome to Pysllo's documentation!
**********************************
Pysllo is set of useful python logging extenders that give possibility to
bind additional data to logs, raising all logs if error occurs or flow tracks
with tools like Elastic Stack or other monitoring tools based on document databases.
The most important benefit of using pysllo is that it's is just extension to
normal python logging library. It not requiring from you to change whole logs
implementation in your application. You can easy change just part of logging
configuration and use this tool in that part of code. It's really simple to
start working with Pysllo.
###########
Quick start
###########
.. code:: bash
pip install pysllo
Features
--------
- :class:`pysllo.loggers.StructuredLogger`
Logger class that make available binding data to logs
- :class:`pysllo.loggers.PropagationLogger`
Logger class that make possible to propagate log level between few code block
- :class:`pysllo.loggers.TrackingLogger`
Logger that add functionality to track logs on all levels and push it if error
occurs ignoring normal level configuration
- :class:`pysllo.utils.factory.LoggersFactory`
Is class that can create you Logger class with functionality from
classes above you want
- :class:`pysllo.formatters.JsonFormatter`
It's formatter class that convert your log records into JSON objects
- :class:`pysllo.handlers.ElasticSearchUDPHandler`
It's handler class that send your logs into Elastic cluster
Usage example
-------------
.. code:: python
from pysllo.handlers import ElasticSearchUDPHandler
from pysllo.formatters import JsonFormatter
from pysllo.utils import LoggersFactory
# configuration
host, port = 'localhost', 9000
handler = ElasticSearchUDPHandler([(host, port)])
formatter = JsonFormatter()
handler.setFormatter(formatter)
MixedLogger = LoggersFactory.make(
tracking_logger=True,
propagation_logger=True,
structured_logger=True
)
logger = MixedLogger('test')
logger.addHandler(handler)
# examlpe usage
msg = "TEST"
logger.bind(ip='127.0.0.1')
logger.debug(msg, user=request.user)
#######
Loggers
#######
.. autoclass:: pysllo.loggers.StructuredLogger
:members: bind, unbind, get
:show-inheritance:
.. autoclass:: pysllo.loggers.PropagationLogger
:members: set_propagation, reset_level, level_propagation, force_level, __init__
:show-inheritance:
.. autoclass:: pysllo.loggers.TrackingLogger
:members: trace, enable_tracking, disable_tracking, exit_with_exc, __init__
:show-inheritance:
.. autoclass:: pysllo.utils.factory.LoggersFactory
:members:
########
Handlers
########
.. autoclass:: pysllo.handlers.ElasticSearchUDPHandler
:members: set_backup_path, enable_backup, disable_backup, set_limit, emit, __init__
:show-inheritance:
##########
Formatters
##########
.. autoclass:: pysllo.formatters.JsonFormatter
:members: format, __init__
:show-inheritance:
##################
Indices and tables
##################
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`
| {
"content_hash": "38c9fd04dc178db4a2506fb588dc6a05",
"timestamp": "",
"source": "github",
"line_count": 112,
"max_line_length": 86,
"avg_line_length": 30.089285714285715,
"alnum_prop": 0.7056379821958457,
"repo_name": "kivio/pysllo",
"id": "5e6b778285feabf54d8a0b1c1a3b4b633445ecc9",
"size": "3370",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "docs/index.rst",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Python",
"bytes": "57576"
}
],
"symlink_target": ""
} |
package main
import (
"fmt"
"time"
"github.com/golang/glog"
"github.com/yangsf5/claw/center"
"github.com/yangsf5/claw/service"
"github.com/yangsf5/moba/server/handler"
"github.com/yangsf5/moba/server/hero"
myService "github.com/yangsf5/moba/server/service"
"github.com/yangsf5/moba/server/service/room"
)
var ()
func main() {
glog.Info("MOBA server start!")
service.Register()
myService.Register()
handler.RegisterHandler()
hero.ReadConfig("client/resource/config/hero.json")
willUseServices := []string{"Error", "Web", "MobaWebsocket", "MobaHall"}
for i := 1; i <= room.RoomCount; i++ {
name := fmt.Sprintf("MobaRoom%d", i)
willUseServices = append(willUseServices, name)
}
center.Use(willUseServices)
for {
time.Sleep(100 * time.Millisecond)
}
glog.Info("MOBA server exit!")
glog.Flush()
}
| {
"content_hash": "f2e421c63823f967cda7d19ae250badf",
"timestamp": "",
"source": "github",
"line_count": 43,
"max_line_length": 73,
"avg_line_length": 19.348837209302324,
"alnum_prop": 0.7055288461538461,
"repo_name": "yangsf5/moba",
"id": "1f85749bfefb7301839ba885eeea59eff1b05aef",
"size": "832",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "moba.go",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Go",
"bytes": "22469"
},
{
"name": "HTML",
"bytes": "2391"
},
{
"name": "Python",
"bytes": "169"
},
{
"name": "TypeScript",
"bytes": "30222"
}
],
"symlink_target": ""
} |
import numpy as np
import matplotlib.pyplot as plt
GREEN = '#009900'
# Read the training data into a numpy array.
data = np.loadtxt('train.csv', delimiter=',', skiprows=1)
# Extract elevation and classes.
elevations = data[:,1]
classes = data[:,55]
# Plot.
plt.plot(elevations, classes, color=GREEN, linestyle='None', marker='o')
plt.axis([1500, 4000, 0, 8])
plt.xlabel('Elevation')
plt.ylabel('Forest Cover Type')
# Output.
# plt.savefig('elevation.png')
plt.show()
| {
"content_hash": "8ee8ffce6e7cb64ac6fc10b3b709f9aa",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 72,
"avg_line_length": 22.476190476190474,
"alnum_prop": 0.7033898305084746,
"repo_name": "aclissold/Forest-Cover",
"id": "61ea62253421036ed89fc0c85236cebf607bf191",
"size": "538",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "elevation.py",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "3433"
}
],
"symlink_target": ""
} |
#include "tensorflow/lite/micro/all_ops_resolver.h"
#include "tensorflow/lite/micro/kernels/micro_ops.h"
namespace tflite {
namespace ops {
namespace micro {
namespace custom {
TfLiteRegistration* Register_ETHOSU();
const char* GetString_ETHOSU();
} // namespace custom
} // namespace micro
} // namespace ops
AllOpsResolver::AllOpsResolver() {
// Please keep this list of Builtin Operators in alphabetical order.
AddAbs();
AddAdd();
AddArgMax();
AddArgMin();
AddAveragePool2D();
AddCeil();
AddConcatenation();
AddConv2D();
AddCos();
AddDepthwiseConv2D();
AddDequantize();
AddEqual();
AddFloor();
AddFullyConnected();
AddGreater();
AddGreaterEqual();
AddHardSwish();
AddL2Normalization();
AddLess();
AddLessEqual();
AddLog();
AddLogicalAnd();
AddLogicalNot();
AddLogicalOr();
AddLogistic();
AddMaximum();
AddMaxPool2D();
AddMean();
AddMinimum();
AddMul();
AddNeg();
AddNotEqual();
AddPack();
AddPad();
AddPadV2();
AddPrelu();
AddQuantize();
AddReduceMax();
AddRelu();
AddRelu6();
AddReshape();
AddResizeNearestNeighbor();
AddRound();
AddRsqrt();
AddSin();
AddSoftmax();
AddSplit();
AddSplitV();
AddSqrt();
AddSquare();
AddStridedSlice();
AddSub();
AddSvdf();
AddTanh();
AddUnpack();
// TODO(b/159644355): Figure out if custom Ops belong in AllOpsResolver.
TfLiteRegistration* registration =
tflite::ops::micro::custom::Register_ETHOSU();
if (registration) {
AddCustom(tflite::ops::micro::custom::GetString_ETHOSU(), registration);
}
}
} // namespace tflite
| {
"content_hash": "a9e0db2de180538634198b44216c79ca",
"timestamp": "",
"source": "github",
"line_count": 83,
"max_line_length": 76,
"avg_line_length": 19.253012048192772,
"alnum_prop": 0.6714643304130162,
"repo_name": "davidzchen/tensorflow",
"id": "d722ec146fb5ac9a982319c5edb936785f9c7c72",
"size": "2263",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tensorflow/lite/micro/all_ops_resolver.cc",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "32240"
},
{
"name": "Batchfile",
"bytes": "55269"
},
{
"name": "C",
"bytes": "887514"
},
{
"name": "C#",
"bytes": "8562"
},
{
"name": "C++",
"bytes": "81865221"
},
{
"name": "CMake",
"bytes": "6500"
},
{
"name": "Dockerfile",
"bytes": "112853"
},
{
"name": "Go",
"bytes": "1867241"
},
{
"name": "HTML",
"bytes": "4686483"
},
{
"name": "Java",
"bytes": "971474"
},
{
"name": "Jupyter Notebook",
"bytes": "549437"
},
{
"name": "LLVM",
"bytes": "6536"
},
{
"name": "MLIR",
"bytes": "1921657"
},
{
"name": "Makefile",
"bytes": "65901"
},
{
"name": "Objective-C",
"bytes": "116558"
},
{
"name": "Objective-C++",
"bytes": "316967"
},
{
"name": "PHP",
"bytes": "4236"
},
{
"name": "Pascal",
"bytes": "318"
},
{
"name": "Pawn",
"bytes": "19963"
},
{
"name": "Perl",
"bytes": "7536"
},
{
"name": "Python",
"bytes": "37285698"
},
{
"name": "RobotFramework",
"bytes": "1779"
},
{
"name": "Roff",
"bytes": "2705"
},
{
"name": "Ruby",
"bytes": "7464"
},
{
"name": "SWIG",
"bytes": "8992"
},
{
"name": "Shell",
"bytes": "700629"
},
{
"name": "Smarty",
"bytes": "35540"
},
{
"name": "Starlark",
"bytes": "3604653"
},
{
"name": "Swift",
"bytes": "62814"
},
{
"name": "Vim Snippet",
"bytes": "58"
}
],
"symlink_target": ""
} |
package com.github.pockethub.android.ui.issue;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import com.meisolsson.githubsdk.model.Repository;
import com.github.pockethub.android.R;
import com.github.pockethub.android.ui.repo.RepositoryViewActivity;
import com.github.pockethub.android.ui.roboactivities.RoboAppCompatActivity;
import com.github.pockethub.android.util.AvatarLoader;
import com.github.pockethub.android.util.InfoUtils;
import com.github.pockethub.android.util.ToastUtils;
import com.google.inject.Inject;
import static android.app.SearchManager.APP_DATA;
import static android.app.SearchManager.QUERY;
import static android.content.Intent.ACTION_SEARCH;
import static android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP;
import static android.content.Intent.FLAG_ACTIVITY_SINGLE_TOP;
import static com.github.pockethub.android.Intents.EXTRA_REPOSITORY;
/**
* Activity to search issues
*/
public class IssueSearchActivity extends RoboAppCompatActivity {
@Inject
private AvatarLoader avatars;
private Repository repository;
private SearchIssueListFragment issueFragment;
private String lastQuery;
private SearchView searchView;
@Override
public boolean onCreateOptionsMenu(Menu options) {
getMenuInflater().inflate(R.menu.activity_search, options);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
MenuItem searchItem = options.findItem(R.id.m_search);
searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
Bundle args = new Bundle();
args.putParcelable(EXTRA_REPOSITORY, repository);
searchView.setAppSearchData(args);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.m_search:
searchView.post(() -> searchView.setQuery(lastQuery, false));
return true;
case R.id.m_clear:
IssueSearchSuggestionsProvider.clear(this);
ToastUtils.show(this, R.string.search_history_cleared);
return true;
case android.R.id.home:
Intent intent = RepositoryViewActivity.createIntent(repository);
intent.addFlags(FLAG_ACTIVITY_CLEAR_TOP | FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_issue_search);
setSupportActionBar((Toolbar) findViewById(R.id.toolbar));
ActionBar actionBar = getSupportActionBar();
Bundle appData = getIntent().getBundleExtra(APP_DATA);
if (appData != null) {
repository = appData.getParcelable(EXTRA_REPOSITORY);
if (repository != null) {
actionBar.setSubtitle(InfoUtils.createRepoId(repository));
actionBar.setDisplayHomeAsUpEnabled(true);
avatars.bind(actionBar, repository.owner());
}
}
issueFragment = (SearchIssueListFragment) getSupportFragmentManager()
.findFragmentById(android.R.id.list);
handleIntent(getIntent());
}
@Override
protected void onNewIntent(Intent intent) {
setIntent(intent);
issueFragment.setListShown(false);
handleIntent(intent);
issueFragment.refresh();
}
private void handleIntent(Intent intent) {
if (ACTION_SEARCH.equals(intent.getAction())) {
search(intent.getStringExtra(QUERY));
}
}
private void search(final String query) {
lastQuery = query;
getSupportActionBar().setTitle(query);
IssueSearchSuggestionsProvider.save(this, query);
issueFragment.setQuery(query);
}
}
| {
"content_hash": "92e121f1b83b272f8d3008336b013ff7",
"timestamp": "",
"source": "github",
"line_count": 127,
"max_line_length": 95,
"avg_line_length": 34.61417322834646,
"alnum_prop": 0.6956323930846224,
"repo_name": "KishorAndroid/PocketHub",
"id": "55b9cf02007fabaa485ec48b646a34f01b0c9f6e",
"size": "4992",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/java/com/github/pockethub/android/ui/issue/IssueSearchActivity.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "10700"
},
{
"name": "HTML",
"bytes": "540"
},
{
"name": "Java",
"bytes": "1161936"
},
{
"name": "JavaScript",
"bytes": "2333"
}
],
"symlink_target": ""
} |
#ifndef __ARRAY_H__
#define __ARRAY_H__
#include <stdexcept>
#include <iostream>
#include <sstream>
#include <initializer_list>
#include "exception.h"
/* Fierz ****************************
Diese Art den Array zu implementieren ist nicht sehr flexible, da Array's nur compatible sind, falls sie dieselbe Länge haben.
Beispiel:
Array<int,10> ia1;
Array<int,11> ia2;
das folgende Statement führt zu einem Fehler:
ia1 = ia2;
************************************/
template <class T = int, std::size_t nElements = 100>
class Array
{
public:
// Type definitions
typedef T& reference;
typedef const T& const_reference;
typedef T* iterator;
typedef const T* const_iterator;
// Constructor / desctructor
Array() {}
Array(std::initializer_list<T> elements)
{
std::size_t i = 0;
/* Fierz *********************************
Was passiert, falls mehr Elemente als nElements??
**************************************/
for (auto&& e : elements) {
m_array[i] = e;
++i;
}
while (i < nElements) {
m_array[i] = {};
++i;
}
}
virtual ~Array() {}
// Iterator
iterator begin()
{
return m_array;
}
const_iterator begin() const
{
return m_array;
}
iterator end()
{
return m_array + nElements;
}
const_iterator end() const
{
return m_array + nElements;
}
// Operators
reference operator [] (std::size_t nIndex)
{
this->checkIndex(nIndex);
return m_array[nIndex];
}
const_reference operator [] (std::size_t nIndex) const
{
this->checkIndex(nIndex);
return m_array[nIndex];
}
// Functions
reference at(std::size_t nIndex)
{
this->checkIndex(nIndex);
return m_array[nIndex];
}
const_reference at(std::size_t nIndex) const
{
this->checkIndex(nIndex);
return m_array[nIndex];
}
reference front()
{
return m_array[0];
}
const_reference front() const
{
return m_array[0];
}
reference back()
{
return m_array[nElements - 1];
}
const_reference back() const
{
return m_array[nElements - 1];
}
static std::size_t size()
{
return nElements;
}
const bool empty()
{
return false;
/*
bool isEmpty = true;
for (std::size_t i = 0; i < nElements; ++i) {
if (m_array[i]) {
isEmpty = false;
break;
}
}
return isEmpty;
*/
}
void swap(Array<T, nElements>& src)
{
for (std::size_t i = 0; i < nElements; ++i) {
std::swap(m_array[i], src.m_array[i]);
}
}
const T* data() const
{
return m_array;
}
T* data()
{
return m_array;
}
void fill(const T& value)
{
std::fill_n(begin(), size(), value);
}
private:
T m_array[nElements];
void checkIndex(std::size_t nIndex)
{
if (nIndex < 0 || nIndex > nElements) {
std::cout << nIndex << std::endl;
std::stringstream strStream;
strStream << "Given index out of boundaries (" << nElements << ")!";
std::out_of_range ex(strStream.str());
throw(OutOfBoundsException(ex));
}
}
};
#endif
| {
"content_hash": "45bd694c2101560697baca47cd59926c",
"timestamp": "",
"source": "github",
"line_count": 183,
"max_line_length": 129,
"avg_line_length": 22.781420765027324,
"alnum_prop": 0.41400815543295755,
"repo_name": "sosterwalder/bti7503",
"id": "e0b29701b75961361ed67232d571e4c9c4713a9a",
"size": "4171",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "exercise_02/02/array.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "2298"
},
{
"name": "C++",
"bytes": "36522"
},
{
"name": "Python",
"bytes": "5199"
}
],
"symlink_target": ""
} |
using System.ComponentModel;
using DotNetNuke.UI.WebControls;
#endregion
namespace DotNetNuke.Security.Membership
{
/// -----------------------------------------------------------------------------
/// Project: DotNetNuke
/// Namespace: DotNetNuke.Security.Membership
/// Class: MembershipProviderConfig
/// -----------------------------------------------------------------------------
/// <summary>
/// The MembershipProviderConfig class provides a wrapper to the Membership providers
/// configuration
/// </summary>
/// <remarks>
/// </remarks>
/// -----------------------------------------------------------------------------
public class MembershipProviderConfig
{
#region "Private Shared Members"
private static readonly MembershipProvider memberProvider = MembershipProvider.Instance();
#endregion
#region "Public Shared Properties"
/// -----------------------------------------------------------------------------
/// <summary>
/// Gets whether the Provider Properties can be edited
/// </summary>
/// <returns>A Boolean</returns>
/// -----------------------------------------------------------------------------
[Browsable(false)]
public static bool CanEditProviderProperties
{
get
{
return memberProvider.CanEditProviderProperties;
}
}
/// -----------------------------------------------------------------------------
/// <summary>
/// Gets and sets the maximum number of invlaid attempts to login are allowed
/// </summary>
/// <returns>A Boolean.</returns>
/// -----------------------------------------------------------------------------
[SortOrder(8), Category("Password")]
public static int MaxInvalidPasswordAttempts
{
get
{
return memberProvider.MaxInvalidPasswordAttempts;
}
set
{
memberProvider.MaxInvalidPasswordAttempts = value;
}
}
/// -----------------------------------------------------------------------------
/// <summary>
/// Gets and sets the Mimimum no of Non AlphNumeric characters required
/// </summary>
/// <returns>An Integer.</returns>
/// -----------------------------------------------------------------------------
[SortOrder(5), Category("Password")]
public static int MinNonAlphanumericCharacters
{
get
{
return memberProvider.MinNonAlphanumericCharacters;
}
set
{
memberProvider.MinNonAlphanumericCharacters = value;
}
}
/// -----------------------------------------------------------------------------
/// <summary>
/// Gets and sets the Mimimum Password Length
/// </summary>
/// <returns>An Integer.</returns>
/// -----------------------------------------------------------------------------
[SortOrder(4), Category("Password")]
public static int MinPasswordLength
{
get
{
return memberProvider.MinPasswordLength;
}
set
{
memberProvider.MinPasswordLength = value;
}
}
/// -----------------------------------------------------------------------------
/// <summary>
/// Gets and sets the window in minutes that the maxium attempts are tracked for
/// </summary>
/// <returns>A Boolean.</returns>
/// -----------------------------------------------------------------------------
[SortOrder(9), Category("Password")]
public static int PasswordAttemptWindow
{
get
{
return memberProvider.PasswordAttemptWindow;
}
set
{
memberProvider.PasswordAttemptWindow = value;
}
}
/// -----------------------------------------------------------------------------
/// <summary>
/// Gets and sets the Password Format
/// </summary>
/// <returns>A PasswordFormat enumeration.</returns>
/// -----------------------------------------------------------------------------
[SortOrder(1), Category("Password")]
public static PasswordFormat PasswordFormat
{
get
{
return memberProvider.PasswordFormat;
}
set
{
memberProvider.PasswordFormat = value;
}
}
/// -----------------------------------------------------------------------------
/// <summary>
/// Gets and sets whether the Users's Password can be reset
/// </summary>
/// <returns>A Boolean.</returns>
/// -----------------------------------------------------------------------------
[SortOrder(3), Category("Password")]
public static bool PasswordResetEnabled
{
get
{
return memberProvider.PasswordResetEnabled;
}
set
{
memberProvider.PasswordResetEnabled = value;
}
}
/// -----------------------------------------------------------------------------
/// <summary>
/// Gets and sets whether the Users's Password can be retrieved
/// </summary>
/// <returns>A Boolean.</returns>
/// -----------------------------------------------------------------------------
[SortOrder(2), Category("Password")]
public static bool PasswordRetrievalEnabled
{
get
{
bool enabled = memberProvider.PasswordRetrievalEnabled;
//If password format is hashed the password cannot be retrieved
if (memberProvider.PasswordFormat == PasswordFormat.Hashed)
{
enabled = false;
}
return enabled;
}
set
{
memberProvider.PasswordRetrievalEnabled = value;
}
}
/// -----------------------------------------------------------------------------
/// <summary>
/// Gets and sets a Regular Expression that determines the strength of the password
/// </summary>
/// <returns>A String.</returns>
/// -----------------------------------------------------------------------------
[SortOrder(7), Category("Password")]
public static string PasswordStrengthRegularExpression
{
get
{
return memberProvider.PasswordStrengthRegularExpression;
}
set
{
memberProvider.PasswordStrengthRegularExpression = value;
}
}
/// -----------------------------------------------------------------------------
/// <summary>
/// Gets and sets whether a Question/Answer is required for Password retrieval
/// </summary>
/// <returns>A Boolean.</returns>
/// -----------------------------------------------------------------------------
[SortOrder(6), Category("Password")]
public static bool RequiresQuestionAndAnswer
{
get
{
return memberProvider.RequiresQuestionAndAnswer;
}
set
{
memberProvider.RequiresQuestionAndAnswer = value;
}
}
/// -----------------------------------------------------------------------------
/// <summary>
/// Gets and sets whether a Unique Email is required
/// </summary>
/// <returns>A Boolean.</returns>
/// -----------------------------------------------------------------------------
[SortOrder(0), Category("User")]
public static bool RequiresUniqueEmail
{
get
{
return memberProvider.RequiresUniqueEmail;
}
set
{
memberProvider.RequiresUniqueEmail = value;
}
#endregion
}
}
}
| {
"content_hash": "5794b305e409dfdb457723471d926b0e",
"timestamp": "",
"source": "github",
"line_count": 245,
"max_line_length": 98,
"avg_line_length": 34.7265306122449,
"alnum_prop": 0.3804654442877292,
"repo_name": "robsiera/Dnn.Platform",
"id": "0b2a500d80abf329e1e48dcfdf7e7b5916d28c79",
"size": "9733",
"binary": false,
"copies": "2",
"ref": "refs/heads/development",
"path": "DNN Platform/Library/Security/Membership/MembershipProviderConfig.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "572469"
},
{
"name": "Batchfile",
"bytes": "405"
},
{
"name": "C#",
"bytes": "21903627"
},
{
"name": "CSS",
"bytes": "1653926"
},
{
"name": "HTML",
"bytes": "528314"
},
{
"name": "JavaScript",
"bytes": "8361433"
},
{
"name": "PLpgSQL",
"bytes": "53478"
},
{
"name": "PowerShell",
"bytes": "10762"
},
{
"name": "Smalltalk",
"bytes": "2410"
},
{
"name": "TSQL",
"bytes": "56906"
},
{
"name": "Visual Basic",
"bytes": "139195"
},
{
"name": "XSLT",
"bytes": "11388"
}
],
"symlink_target": ""
} |
Promise based queue with rich API.
[](https://travis-ci.org/lividum/promise-que)
[](https://coveralls.io/github/lividum/promise-que?branch=master)
[](https://snyk.io/test/npm/name)
[](https://www.bithound.io/github/lividum/promise-que/master/dependencies/npm)
[](https://www.bithound.io/github/lividum/promise-que/master/dependencies/npm)
[](https://www.bithound.io/github/lividum/promise-que)
## Installation
```$ npm install promise-que --save```
## Example
### Create Queue Object
Create basic queue job.
```
import { Queue } from 'promise-que';
// or use require for CommonJS Module
// const Queue = require('promise-que').Queue;
// create queue object use default number of worker and default delay
const queue = new Queue();
// define task
const task1 = () => Promise.resolve('task 1');
const task2 = () => Promise.resolve('task 2');
// push/ inject tasks to queue object
queue.push([task1, task2]);
// or we can push it one by one
queue.push(task1);
queue.push(task2);
```
Set number of worker. Number of worker is representing how many maximum asynchronous task(s) will be executed at a time.
```
// create queue object with `4` number of worker (default is 1).
const queue = new Queue(4);
```
Set delay. There is 3 kind of delay.
1. `delay` is how long the next task is executed, and also become fallback of `error delay`.
2. `error delay`, is how long the next task is executed if previous task is return error.
3. `loop delay`, how long the queue object check for next task when there is still any task(s) running.
```
const queue = new Queue(
// number of worker
4,
// delay
100,
// error delay
500,
// loop delay
100
);
```
### Task
Each function that return a Promise that pushed to queue object will be converted to `Task` object. Task it self have it's own behavior.
Only one task with same `identity` that will be processed and pushed to `tasks list`. So we can create better un-duplication task by giving pre-defined `identifier` for each of tasks.
```
import { Queue, Task } from 'promise-que';
// or use require for CommonJS Module
// const Queue = require('promise-que').Queue;
// const Task = require('promise-que').Task;
// create tasks with same identifier
const task1 = new Task(() => Promise.resolve('task 1'), 'sameid');
const task2 = new Task(() => Promise.resolve('task 2'), 'sameid');
// push/ inject tasks to queue object
queue.push([task1, task2]);
```
At above example, `task2` will not be processed, since it have same identifier with `task1`, and `task1` is pushed first.
### Drain
Get the result when all of the tasks is done. It's like `Promise.all` so if one or more tasks is failed, it will return an error.
```
queue
.drain(ress => {
console.log(ress[0] === 'task1');
console.log(ress[1] === 'task2');
// should print true twice.
})
// handle error
.catch(err => console.error);
```
### Pause and Resume
Hold and resuming tasks process.
```
// define task
const task1 = () => Promise.resolve('task 1');
const task2 = () => Promise.resolve('task 2');
// pause queue
queue.pause();
// push/ inject tasks to queue object
queue.push([task1, task2]);
// at this moment no tasks will be executed, we can do something here.
console.log(queue.tasks.length);
// should be print `2`, since we pushed 2 tasks to queue object.
// we can resume the process anytime.
queue.resume();
// now queue object will processing all tasks.
```
## API and Documentation
[APIDoc Details](https://lividum.github.io/promise-que/docs/)
### Queue
Is class (constructor function) to create queue object which is represent number of worker (concurrent) and delay each succeed or failed tasks. If failed delay is not specified, succeed delay will be used.
Example:
```
const queue = new Queue(number_of_worker, succeed_delay, failed_delay);
```
### Task
Represent a function that return a Promise (**not a promise object it self**). Task can be pushed to queue object as a function it self or as a task object. The difference is, when we create task by creating task object, we can define it's identifier which means, in a single queue object, identifier must be unique, so if we define exactly same identifier when creating a task, it will ignored when current identifier is still available on current tasks list.
Example:
```
// use function that return a promise
const task1 = () => Promise.resolve('task 1');
queue.push(task1);
// by creating task object
import { Task } from 'promise-que';
const task2 = new Task(() => Promise.resolve('task 2'), 'id-task-2`);
queue.push(task2);
```
## License
[MIT](https://github.com/lividum/promise-que/blob/master/LICENSE)
| {
"content_hash": "68e7c5be5a08a09bc7d298ca69fe31dd",
"timestamp": "",
"source": "github",
"line_count": 154,
"max_line_length": 460,
"avg_line_length": 33.62987012987013,
"alnum_prop": 0.7165475960610156,
"repo_name": "lividum/promise-que",
"id": "55efff747a899ebb90bf2495a94d410b029f7c7d",
"size": "5193",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "17363"
}
],
"symlink_target": ""
} |
//Version: 002
/* NOTE: When compiling on windows, ensure that the linker search paths
include both freeglut\bin and freeglut\lib
*/
#include "Game.h"
#include <time.h>
void runMainLoop( int val );
/*
Pre Condition:
-Initialized freeGLUT
Post Condition:
-Calls the main loop functions and sets itself to be called back in 1000 / SCREEN_FPS milliseconds
Side Effects:
-Sets glutTimerFunc
*/
int main( int argc, char* args[] )
{
//Initialize randon number generator
srand (time(NULL));
//Initialize FreeGLUT
glutInit( &argc, args );
//Create OpenGL 2.1 context
glutInitContextVersion( 2, 1 );
//Create Double Buffered Window
glutInitDisplayMode( GLUT_DOUBLE );
glutInitWindowSize( SCREEN_WIDTH, SCREEN_HEIGHT );
glutCreateWindow( "OpenGL" );
//glutFullScreen(); //Alt+F4 to exit
//Do post window/context creation initialization
if( !initGL() )
{
printf( "Unable to initialize graphics library!\n" );
return 1;
}
//Set keyboard handler
glutKeyboardFunc( handleKeyDown );
glutKeyboardUpFunc( handleKeyUp );
//Set rendering function (This is required, else crash with error "No display callback registered for window 1"
glutDisplayFunc( render );
//Set main loop
glutTimerFunc( 1000 / SCREEN_FPS, runMainLoop, 0 );
initGamespace();
//Start GLUT main loop
glutMainLoop();
return 0;
}
void runMainLoop( int val )
{
int timeNowMs = glutGet(GLUT_ELAPSED_TIME);
//Frame logic
update(timeNowMs);
render();
//Run frame one more time
glutTimerFunc( 1000 / SCREEN_FPS, runMainLoop, val );
}
| {
"content_hash": "02e25dfc3282a0e13d367f93d48c5300",
"timestamp": "",
"source": "github",
"line_count": 74,
"max_line_length": 115,
"avg_line_length": 22.445945945945947,
"alnum_prop": 0.6688741721854304,
"repo_name": "dshavoc/StarSpar",
"id": "32e80426182d788c3deaed22583ff7f9d9eec458",
"size": "1787",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "main.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "1659"
},
{
"name": "C++",
"bytes": "38661"
}
],
"symlink_target": ""
} |
/**
* Module dependencies.
*/
var Task = require('./task')
, Namespace = require('./namespace')
, TargetCtx = require('./targetctx')
, debug = require('debug')('rivet');
/**
* `Rivet` constructor.
*
* @api public
*/
function Rivet() {
this.argv = {};
this.scratch = {};
this._tasks = {};
this._desc = null;
this._ns = [];
this._ns.push(new Namespace());
};
Rivet.prototype.desc = function(desc) {
this._desc = desc;
}
/**
* Declare task `name` to execute `fn`, with optional `prereqs`.
*
* @param {String} name
* @param {Array|String} prereqs
* @param {Function} fn
* @api public
*/
Rivet.prototype.task = function(name, prereqs, fn) {
if (typeof prereqs == 'function') {
fn = prereqs;
prereqs = [];
}
if (typeof prereqs == 'string') {
prereqs = prereqs.split(' ');
}
var ns = this._ns[this._ns.length - 1]
, qname = ns.qname(name)
, qprereqs = prereqs.map(function(n) { return Namespace.resolve(ns.qname(), n); });
debug('declared task: %s', qname);
for (var i = 0, len = qprereqs.length; i < len; i++) {
debug(' prereq: %s', qprereqs[i])
}
var t = (this._tasks[qname] = this._tasks[qname] || new Task(qname, this._desc));
t.prereqs(qprereqs)
t.fn(fn);
this._desc = null;
};
/**
* Create namespace in which to organize tasks.
*
* @param {String} name
* @param {Function} block
* @api public
*/
Rivet.prototype.namespace = function(name, block) {
var ns = this._ns[this._ns.length - 1];
this._ns.push(new Namespace(name, ns));
block && block.call(this);
this._ns.pop();
}
/**
* Declare target `name` with defining `block`.
*
* A target is a task with a set of sequential steps. When the task is executed,
* these steps are invoked sequentially, one after the other.
*
* Declaring targets and steps is syntactic sugar. It is equivalent to to
* declaring the same task multiple times with different functions; each
* function is additive, and will be invoked in the order declared.
*
* @param {String} name
* @param {Array|String} prereqs
* @param {Function} fn
* @api public
*/
Rivet.prototype.target = function(name, prereqs, block) {
if (typeof prereqs == 'function') {
block = prereqs;
prereqs = [];
}
// declare task, empty set of functions
this.task(name, prereqs);
// apply block, within target context
var ctx = new TargetCtx(this, name);
block.apply(ctx);
}
/**
* Alias `tasks` to `name`.
*
* An alias is a convenient way to assign a name to a task or set of tasks.
*
* Declaring an alias is syntactic sugar. It is equivalent to declaring a task
* with prerequisites.
*
* @param {String} name
* @param {Array|String} tasks
* @api public
*/
Rivet.prototype.alias = function(name, tasks) {
this.task(name, tasks);
}
/**
* Run `tasks`.
*
* @param {Array|String} tasks
* @param {Function} cb
* @api protected
*/
Rivet.prototype.run = function(tasks, options, cb) {
if (typeof tasks == 'string') {
tasks = tasks.split(' ');
}
if (typeof options == 'function') {
cb = options;
options = {};
}
cb = cb || function() {};
this.argv = options;
this._queue = tasks;
var self = this;
(function pass(i, err) {
if (err) { return cb(err); }
var name = self._queue[i];
if (!name) { return cb(); } // done
var task = self._tasks[name]
if (!task) { return cb(new Error('No task named "' + name + '"')); }
task.exec(self, function(e) {
pass(i + 1, e);
});
})(0);
}
/**
* Export default singleton.
*
* @api public
*/
exports = module.exports = new Rivet();
/**
* Framework version.
*/
require('pkginfo')(module, 'version');
/**
* Expose constructors.
*/
exports.Rivet = Rivet;
/**
* Expose CLI.
*
* @api private
*/
exports.cli = require('./cli');
exports.utils = require('./utils');
| {
"content_hash": "78c8f527ff3307df9b916446e1c78955",
"timestamp": "",
"source": "github",
"line_count": 181,
"max_line_length": 87,
"avg_line_length": 21.276243093922652,
"alnum_prop": 0.6055569981822904,
"repo_name": "jaredhanson/rivet",
"id": "c3e16f5f970f8a996825f54fc4573b5dfbdc6d19",
"size": "3851",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/index.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "39991"
}
],
"symlink_target": ""
} |
namespace morphie {
namespace util {
using std::vector;
// A Record object consists of a vector of strings and a status object. If the
// status is ok(), the vector contains fields obtained by parsing one line of
// CSV input. If the status is not ok(), an error occurred when the Record was
// being populated. Both fields and status are set by the CSV parser and cannot
// be modified by the client.
class Record {
public:
// Functions that enable range-based iteration over fields.
vector<string>::const_iterator begin() const { return fields_.begin(); }
vector<string>::const_iterator end() const { return fields_.end(); }
const vector<string>& fields() const { return fields_; }
bool ok() const { return status_.ok(); }
private:
friend class CSVParser;
vector<string> fields_;
util::Status status_;
};
// The CSVParser extracts fields, line by line, from an input stream. At any
// given time, the parser only stores fields extracted from a single line in
// memory, so processing CSV input with a large number of lines is not an issue.
//
// The parser owns the input stream and provides an iterator interface for
// processing the stream. There can only be one, non-end position.
class CSVParser {
public:
// An iterator class for traversing the processed input stream.
class Iterator : public std::iterator<std::input_iterator_tag, Record> {
public:
// The field 'is_end' is used internally to determine if an iterator points
// to the end of a stream.
explicit Iterator(CSVParser* parser, bool is_end)
: parser_(parser), is_end_(is_end) {}
// Parse the next line of the input. Does nothing if already at the end.
Iterator& operator++();
const Record& operator*() { return parser_->record_; }
const Record* operator->() { return &parser_->record_; }
// Two iterators are equal if they are defined by the same parser and both
// are end iterators or neither is an end iterator. Since the parser only
// provides accesse to one non-end position in the stream, two non-end
// iterators defined by the same parser must be equal.
bool operator==(const Iterator& that) const {
// There are two ways in which an iterator might point to the end of the
// input. One is that it was created as an end iterator, in which case the
// 'is_end_' flag is true. Another way is by incrementing an iterator from
// parser.begin() till the end. In this case, the 'is_end_' flag will be
// initialized to false, and the end position is detected by checking that
// there is no more data. The checks below cannot be simplified by
// updating the value of 'is_end_' in an iterator because there may be
// multiple iterators that point to non-end positions.
bool this_at_end = is_end_ || parser_->state_ == State::kOutputEmpty;
bool that_at_end =
that.is_end_ || that.parser_->state_ == State::kOutputEmpty;
return (parser_ == that.parser_ && this_at_end == that_at_end);
}
bool operator!=(const Iterator& that) const { return !(*this == that); }
private:
CSVParser* const parser_;
bool is_end_;
};
// The CSVParser takes ownership of 'input', consumes its contents and
// eventually destroys it.
explicit CSVParser(std::istream* input);
// Creates a CSVParser that uses 'delim' as the field delimiter.
CSVParser(std::istream* input, char delim);
Iterator begin() const { return begin_iter_; }
Iterator end() const { return end_iter_; }
private:
// The state of the parser. The parser is one step ahead of the client reading
// parsed fields, so it needs to track when the input has been exhaused but
// the last Record extracted from the input has not yet been read.
enum class State {
// Reading and parsing input.
kReading,
// Raw input is exhaused but there is one Record in the parsed input.
kInputEmpty,
// All parsed input has been consumed.
kOutputEmpty,
};
void Init(std::istream* istream);
// Parses the next line of the input and updates the parser's state.
void Advance();
std::unique_ptr<std::istream> input_;
const char delim_;
Record record_;
Iterator begin_iter_;
Iterator end_iter_;
State state_;
};
} // namespace util
} // namespace morphie
#endif // LOGLE_UTIL_CSV_H_
| {
"content_hash": "ede7fdb37be62dd3bf28e01298f2d5f4",
"timestamp": "",
"source": "github",
"line_count": 111,
"max_line_length": 80,
"avg_line_length": 39.090090090090094,
"alnum_prop": 0.6888684028578014,
"repo_name": "google/morphie",
"id": "8ea09be0848d59a0885410a08eac24d1f2709bd0",
"size": "6410",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "util/csv.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "791"
},
{
"name": "C++",
"bytes": "580176"
},
{
"name": "CMake",
"bytes": "13850"
},
{
"name": "Protocol Buffer",
"bytes": "15342"
}
],
"symlink_target": ""
} |
package com.haxademic.core.draw.image;
import com.haxademic.core.app.P;
import com.haxademic.core.draw.context.PG;
import processing.core.PConstants;
import processing.core.PGraphics;
public class TiledGrid {
protected PGraphics gridCell;
protected int tileSize;
protected int colorBg;
protected int colorStroke;
protected float strokeWeight;
protected float offsetX = 0;
protected float offsetY = 0;
public TiledGrid(int tileSize, int colorBg, int colorStroke, float strokeWeight) {
this.tileSize = tileSize;
this.colorBg = colorBg;
this.colorStroke = colorStroke;
this.strokeWeight = strokeWeight;
// draw repeating grid cell
gridCell = PG.newPG(tileSize, tileSize, false, true);
gridCell.beginDraw();
gridCell.noStroke();
gridCell.background(colorBg);
gridCell.fill(colorStroke);
gridCell.rect(0, 0, gridCell.width, strokeWeight);
gridCell.rect(0, 0, strokeWeight, gridCell.height);
gridCell.endDraw();
}
public void draw(PGraphics pg, float cols, float rows) {
draw(pg, cols, rows, false);
}
public void draw(PGraphics pg, float cols, float rows, boolean drawOutline) {
int prevRectMode = pg.rectMode;
PG.setTextureRepeat(pg, true);
pg.pushMatrix();
float drawW = cols * tileSize + strokeWeight;
float drawH = rows * tileSize + strokeWeight;
pg.noStroke();
pg.beginShape();
pg.textureMode(P.IMAGE);
pg.texture(gridCell);
if(prevRectMode == PConstants.CENTER) pg.translate(P.round(-drawW/2), P.round(-drawH/2));
pg.vertex(0, 0, 0, offsetX * tileSize + 0, offsetY * tileSize + 0);
pg.vertex(drawW, 0, 0, offsetX * tileSize + drawW, offsetY * tileSize + 0);
pg.vertex(drawW, drawH, 0, offsetX * tileSize + drawW, offsetY * tileSize + drawH);
pg.vertex(0, drawH, 0, offsetX * tileSize + 0, offsetY * tileSize + drawH);
pg.endShape();
if(drawOutline) {
pg.rectMode(PConstants.CORNER); // make sure rect is drawing from the same top left
pg.fill(colorStroke);
pg.rect(0, 0, drawW, strokeWeight); // top
pg.rect(0, drawH - strokeWeight, drawW, strokeWeight); // bottom
pg.rect(0, 0, strokeWeight, drawH); // left
pg.rect(drawW - strokeWeight, 0, strokeWeight, drawH); // right
pg.rectMode(prevRectMode); // reset rect mode to whatever it was before
}
pg.popMatrix();
}
// public
public int tileSize() {
return tileSize;
}
public float offsetX() {
return offsetX;
}
public TiledGrid offsetX(float offsetX) {
this.offsetX = offsetX;
return this;
}
public float offsetY() {
return offsetY;
}
public TiledGrid offsetY(float offsetY) {
this.offsetY = offsetY;
return this;
}
}
| {
"content_hash": "cdd35fc6577c4e7e3a62249c5e83aeb3",
"timestamp": "",
"source": "github",
"line_count": 95,
"max_line_length": 91,
"avg_line_length": 27.789473684210527,
"alnum_prop": 0.7003787878787879,
"repo_name": "cacheflowe/haxademic",
"id": "b9dd25be639ef18cc428cd95f7e13cc3e032badb",
"size": "2640",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/com/haxademic/core/draw/image/TiledGrid.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "34147"
},
{
"name": "C++",
"bytes": "34435"
},
{
"name": "CSS",
"bytes": "23727"
},
{
"name": "GLSL",
"bytes": "622199"
},
{
"name": "HTML",
"bytes": "24364"
},
{
"name": "Java",
"bytes": "4079383"
},
{
"name": "JavaScript",
"bytes": "131793"
},
{
"name": "PHP",
"bytes": "56930"
},
{
"name": "Scala",
"bytes": "3061"
},
{
"name": "Shell",
"bytes": "8555"
},
{
"name": "SuperCollider",
"bytes": "1231"
},
{
"name": "VBScript",
"bytes": "246"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
namespace Linq2TwitterSample
{
// The UIApplicationDelegate for the application. This class is responsible for launching the
// User Interface of the application, as well as listening (and optionally responding) to
// application events from iOS.
[Register ("AppDelegate")]
public partial class AppDelegate : UIApplicationDelegate
{
// class-level declarations
public override UIWindow Window {
get;
set;
}
// This method is invoked when the application is about to move from active to inactive state.
// OpenGL applications should use this method to pause.
public override void OnResignActivation (UIApplication application)
{
}
// This method should be used to release shared resources and it should store the application state.
// If your application supports background exection this method is called instead of WillTerminate
// when the user quits.
public override void DidEnterBackground (UIApplication application)
{
}
// This method is called as part of the transiton from background to active state.
public override void WillEnterForeground (UIApplication application)
{
}
// This method is called when the application is about to terminate. Save data, if needed.
public override void WillTerminate (UIApplication application)
{
}
}
}
| {
"content_hash": "dcc28da19aa0881a6b9bc1aa83aad202",
"timestamp": "",
"source": "github",
"line_count": 47,
"max_line_length": 102,
"avg_line_length": 30.595744680851062,
"alnum_prop": 0.7600834492350487,
"repo_name": "SotoiGhost/Linq2TwitterSample",
"id": "4197deb07c8adc0a020d77dec7abc30d27d93584",
"size": "1440",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Linq2TwitterSample/AppDelegate.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "6431"
}
],
"symlink_target": ""
} |
layout: update
date: 2018-07-12
title: Windows images update on July 12, 2018
platform: windows
---
## What's new
* [#2508](https://github.com/appveyor/ci/issues/2508) .NET Core 2.1.2
* [#2509](https://github.com/appveyor/ci/issues/2509) PostgreSQL 9.6.9 and 10.4
* [#2510](https://github.com/appveyor/ci/issues/2510) Fixed: Python 3.7 is missing virtualenv
* [#2511](https://github.com/appveyor/ci/issues/2511) Fixed: Qt latest doesn't point to 5.11.1
* [#2512](https://github.com/appveyor/ci/issues/2512) Visual Studio 2017 version 15.7.5
* [#2513](https://github.com/appveyor/ci/issues/2513) pwsh.exe should load AppVeyor module on start
* [#2515](https://github.com/appveyor/ci/issues/2515) Visual Studio 2017 version 15.8 Preview 4
## Previous worker images
There are build worker images available from previous deployment. You can use them in case of any issues with the current images:
* `Previous Visual Studio 2015`
* `Previous Visual Studio 2017`
You can select build worker image in "Build worker image" dropdown on Environment tab of project settings or if you use `appveyor.yml`:
```yaml
image: Previous Visual Studio 2017
``` | {
"content_hash": "8871967dd1f54fef3a25bdfa48db125b",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 135,
"avg_line_length": 40.92857142857143,
"alnum_prop": 0.7452006980802792,
"repo_name": "appveyor/website",
"id": "1ad1f6e2e596edf5c6dacccb963fd6f62102d2e1",
"size": "1150",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/_updates/2018-07-12.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP.NET",
"bytes": "96"
},
{
"name": "CSS",
"bytes": "26771"
},
{
"name": "HTML",
"bytes": "156285"
},
{
"name": "JavaScript",
"bytes": "12325"
},
{
"name": "Ruby",
"bytes": "190"
}
],
"symlink_target": ""
} |
<?php
namespace SilverStripe\CMS\Tests\Model;
use Page;
use SilverStripe\CMS\Model\SiteTree;
use SilverStripe\Control\HTTPResponse_Exception;
use SilverStripe\Dev\FunctionalTest;
use SilverStripe\Security\Group;
use SilverStripe\Security\Member;
use SilverStripe\Security\Security;
use SilverStripe\SiteConfig\SiteConfig;
use SilverStripe\Subsites\Extensions\SiteTreeSubsites;
use SilverStripe\Versioned\Versioned;
/**
* @todo Test canAddChildren()
* @todo Test canCreate()
*/
class SiteTreePermissionsTest extends FunctionalTest
{
protected static $fixture_file = "SiteTreePermissionsTest.yml";
protected static $illegal_extensions = [
SiteTree::class => [SiteTreeSubsites::class],
];
protected function setUp(): void
{
parent::setUp();
// we're testing HTTP status codes before being redirected to login forms
$this->autoFollowRedirection = false;
// Ensure all pages are published
/** @var Page $page */
foreach (Page::get() as $page) {
if ($page->URLSegment !== 'draft-only') {
$page->publishSingle();
}
}
}
public function testAccessingStageWithBlankStage()
{
$this->autoFollowRedirection = false;
/** @var Page $draftOnlyPage */
$draftOnlyPage = $this->objFromFixture(Page::class, 'draftOnlyPage');
$this->logOut();
$response = $this->get($draftOnlyPage->URLSegment . '?stage=Live');
$this->assertEquals($response->getStatusCode(), '404');
$response = $this->get($draftOnlyPage->URLSegment);
$this->assertEquals($response->getStatusCode(), '404');
// should be prompted for a login
try {
$response = $this->get($draftOnlyPage->URLSegment . '?stage=Stage');
} catch (HTTPResponse_Exception $responseException) {
$response = $responseException->getResponse();
}
$this->assertEquals($response->getStatusCode(), '302');
$this->assertStringContainsString(
Security::config()->get('login_url'),
$response->getHeader('Location')
);
$this->logInWithPermission('ADMIN');
$response = $this->get($draftOnlyPage->URLSegment . '?stage=Live');
$this->assertEquals('404', $response->getStatusCode());
$response = $this->get($draftOnlyPage->URLSegment . '?stage=Stage');
$this->assertEquals('200', $response->getStatusCode());
$draftOnlyPage->publishSingle();
$response = $this->get($draftOnlyPage->URLSegment);
$this->assertEquals('200', $response->getStatusCode());
}
public function testPermissionCheckingWorksOnDeletedPages()
{
// Set up fixture - a published page deleted from draft
$this->logInWithPermission("ADMIN");
$page = $this->objFromFixture(Page::class, 'restrictedEditOnlySubadminGroup');
$pageID = $page->ID;
$this->assertTrue($page->publishRecursive());
$page->delete();
// Re-fetch the page from the live site
$page = Versioned::get_one_by_stage(SiteTree::class, 'Live', "\"SiteTree\".\"ID\" = $pageID");
// subadmin has edit rights on that page
$member = $this->objFromFixture(Member::class, 'subadmin');
Security::setCurrentUser($member);
// Test can_edit_multiple
$this->assertEquals(
[ $pageID => true ],
SiteTree::getPermissionChecker()->canEditMultiple([$pageID], $member)
);
// Test canEdit
Security::setCurrentUser($member);
$this->assertTrue($page->canEdit());
}
public function testPermissionCheckingWorksOnUnpublishedPages()
{
// Set up fixture - an unpublished page
$this->logInWithPermission("ADMIN");
$page = $this->objFromFixture(Page::class, 'restrictedEditOnlySubadminGroup');
$pageID = $page->ID;
$page->doUnpublish();
// subadmin has edit rights on that page
$member = $this->objFromFixture(Member::class, 'subadmin');
Security::setCurrentUser($member);
// Test can_edit_multiple
$this->assertEquals(
[ $pageID => true ],
SiteTree::getPermissionChecker()->canEditMultiple([$pageID], $member)
);
// Test canEdit
Security::setCurrentUser($member);
$this->assertTrue($page->canEdit());
}
public function testCanEditOnPageDeletedFromStageAndLiveReturnsFalse()
{
// Find a page that exists and delete it from both stage and published
$this->logInWithPermission("ADMIN");
$page = $this->objFromFixture(Page::class, 'restrictedEditOnlySubadminGroup');
$pageID = $page->ID;
$page->doUnpublish();
$page->delete();
// We'll need to resurrect the page from the version cache to test this case
$page = Versioned::get_latest_version(SiteTree::class, $pageID);
// subadmin had edit rights on that page, but now it's gone
$member = $this->objFromFixture(Member::class, 'subadmin');
Security::setCurrentUser($member);
$this->assertFalse($page->canEdit());
}
public function testCanViewStage()
{
// Get page & make sure it exists on Live
/** @var Page $page */
$page = $this->objFromFixture(Page::class, 'standardpage');
$page->publishSingle();
// Then make sure there's a new version on Stage
$page->Title = 1;
$page->write();
$editor = $this->objFromFixture(Member::class, 'editor');
$websiteuser = $this->objFromFixture(Member::class, 'websiteuser');
$this->assertTrue($page->canViewStage('Live', $websiteuser));
$this->assertFalse($page->canViewStage('Stage', $websiteuser));
$this->assertTrue($page->canViewStage('Live', $editor));
$this->assertTrue($page->canViewStage('Stage', $editor));
}
public function testAccessTabOnlyDisplaysWithGrantAccessPermissions()
{
$page = $this->objFromFixture(Page::class, 'standardpage');
$subadminuser = $this->objFromFixture(Member::class, 'subadmin');
Security::setCurrentUser($subadminuser);
$fields = $page->getSettingsFields();
$this->assertFalse(
$fields->dataFieldByName('CanViewType')->isReadonly(),
'Users with SITETREE_GRANT_ACCESS permission can change "view" permissions in cms fields'
);
$this->assertFalse(
$fields->dataFieldByName('CanEditType')->isReadonly(),
'Users with SITETREE_GRANT_ACCESS permission can change "edit" permissions in cms fields'
);
$editoruser = $this->objFromFixture(Member::class, 'editor');
Security::setCurrentUser($editoruser);
$fields = $page->getSettingsFields();
$this->assertTrue(
$fields->dataFieldByName('CanViewType')->isReadonly(),
'Users without SITETREE_GRANT_ACCESS permission cannot change "view" permissions in cms fields'
);
$this->assertTrue(
$fields->dataFieldByName('CanEditType')->isReadonly(),
'Users without SITETREE_GRANT_ACCESS permission cannot change "edit" permissions in cms fields'
);
$this->logOut();
}
public function testRestrictedViewLoggedInUsers()
{
$page = $this->objFromFixture(Page::class, 'restrictedViewLoggedInUsers');
// unauthenticated users
$this->assertFalse(
$page->canView(false),
'Unauthenticated members cant view a page marked as "Viewable for any logged in users"'
);
$this->logOut();
$response = $this->get($page->RelativeLink());
$this->assertEquals(
$response->getStatusCode(),
302,
'Unauthenticated members cant view a page marked as "Viewable for any logged in users"'
);
// website users
$websiteuser = $this->objFromFixture(Member::class, 'websiteuser');
$this->assertTrue(
$page->canView($websiteuser),
'Authenticated members can view a page marked as "Viewable for any logged in users" even if they dont have access to the CMS'
);
$this->logInAs($websiteuser);
$response = $this->get($page->RelativeLink());
$this->assertEquals(
$response->getStatusCode(),
200,
'Authenticated members can view a page marked as "Viewable for any logged in users" even if they dont have access to the CMS'
);
$this->logOut();
}
public function testRestrictedViewOnlyTheseUsers()
{
$page = $this->objFromFixture(Page::class, 'restrictedViewOnlyWebsiteUsers');
// unauthenticcated users
$this->assertFalse(
$page->canView(false),
'Unauthenticated members cant view a page marked as "Viewable by these groups"'
);
$this->logOut();
$response = $this->get($page->RelativeLink());
$this->assertEquals(
$response->getStatusCode(),
302,
'Unauthenticated members cant view a page marked as "Viewable by these groups"'
);
// subadmin users
$subadminuser = $this->objFromFixture(Member::class, 'subadmin');
$this->assertFalse(
$page->canView($subadminuser),
'Authenticated members cant view a page marked as "Viewable by these groups" if theyre not in the listed groups'
);
$this->LogInAs($subadminuser);
$response = $this->get($page->RelativeLink());
$this->assertEquals(
$response->getStatusCode(),
403,
'Authenticated members cant view a page marked as "Viewable by these groups" if theyre not in the listed groups'
);
$this->logOut();
// website users
$websiteuser = $this->objFromFixture(Member::class, 'websiteuser');
$this->assertTrue(
$page->canView($websiteuser),
'Authenticated members can view a page marked as "Viewable by these groups" if theyre in the listed groups'
);
$this->logInAs($websiteuser);
$response = $this->get($page->RelativeLink());
$this->assertEquals(
$response->getStatusCode(),
200,
'Authenticated members can view a page marked as "Viewable by these groups" if theyre in the listed groups'
);
$this->logOut();
}
public function testRestrictedEditLoggedInUsers()
{
$page = $this->objFromFixture(Page::class, 'restrictedEditLoggedInUsers');
// unauthenticcated users
$this->assertFalse(
$page->canEdit(false),
'Unauthenticated members cant edit a page marked as "Editable by logged in users"'
);
// website users
$websiteuser = $this->objFromFixture(Member::class, 'websiteuser');
Security::setCurrentUser($websiteuser);
$this->assertFalse(
$page->canEdit($websiteuser),
'Authenticated members cant edit a page marked as "Editable by logged in users" if they dont have cms permissions'
);
// subadmin users
$subadminuser = $this->objFromFixture(Member::class, 'subadmin');
$this->assertTrue(
$page->canEdit($subadminuser),
'Authenticated members can edit a page marked as "Editable by logged in users" if they have cms permissions and belong to any of these groups'
);
}
public function testRestrictedEditOnlySubadminGroup()
{
$page = $this->objFromFixture(Page::class, 'restrictedEditOnlySubadminGroup');
// unauthenticated users
$this->assertFalse(
$page->canEdit(false),
'Unauthenticated members cant edit a page marked as "Editable by these groups"'
);
// subadmin users
$subadminuser = $this->objFromFixture(Member::class, 'subadmin');
$this->assertTrue(
$page->canEdit($subadminuser),
'Authenticated members can view a page marked as "Editable by these groups" if theyre in the listed groups'
);
// website users
$websiteuser = $this->objFromFixture(Member::class, 'websiteuser');
$this->assertFalse(
$page->canEdit($websiteuser),
'Authenticated members cant edit a page marked as "Editable by these groups" if theyre not in the listed groups'
);
}
public function testRestrictedViewInheritance()
{
$parentPage = $this->objFromFixture(Page::class, 'parent_restrictedViewOnlySubadminGroup');
$childPage = $this->objFromFixture(Page::class, 'child_restrictedViewOnlySubadminGroup');
// unauthenticated users
$this->assertFalse(
$childPage->canView(false),
'Unauthenticated members cant view a page marked as "Viewable by these groups" by inherited permission'
);
$this->logOut();
$response = $this->get($childPage->RelativeLink());
$this->assertEquals(
$response->getStatusCode(),
302,
'Unauthenticated members cant view a page marked as "Viewable by these groups" by inherited permission'
);
// subadmin users
$subadminuser = $this->objFromFixture(Member::class, 'subadmin');
$this->assertTrue(
$childPage->canView($subadminuser),
'Authenticated members can view a page marked as "Viewable by these groups" if theyre in the listed groups by inherited permission'
);
$this->logInAs($subadminuser);
$response = $this->get($childPage->RelativeLink());
$this->assertEquals(
$response->getStatusCode(),
200,
'Authenticated members can view a page marked as "Viewable by these groups" if theyre in the listed groups by inherited permission'
);
$this->logOut();
}
public function testRestrictedEditInheritance()
{
$parentPage = $this->objFromFixture(Page::class, 'parent_restrictedEditOnlySubadminGroup');
$childPage = $this->objFromFixture(Page::class, 'child_restrictedEditOnlySubadminGroup');
// unauthenticated users
$this->assertFalse(
$childPage->canEdit(false),
'Unauthenticated members cant edit a page marked as "Editable by these groups" by inherited permission'
);
// subadmin users
$subadminuser = $this->objFromFixture(Member::class, 'subadmin');
$this->assertTrue(
$childPage->canEdit($subadminuser),
'Authenticated members can edit a page marked as "Editable by these groups" if theyre in the listed groups by inherited permission'
);
}
public function testDeleteRestrictedChild()
{
$parentPage = $this->objFromFixture(Page::class, 'deleteTestParentPage');
$childPage = $this->objFromFixture(Page::class, 'deleteTestChildPage');
// unauthenticated users
$this->assertFalse(
$parentPage->canDelete(false),
'Unauthenticated members cant delete a page if it doesnt have delete permissions on any of its descendants'
);
$this->assertFalse(
$childPage->canDelete(false),
'Unauthenticated members cant delete a child page marked as "Editable by these groups"'
);
}
public function testRestrictedEditLoggedInUsersDeletedFromStage()
{
$page = $this->objFromFixture(Page::class, 'restrictedEditLoggedInUsers');
$pageID = $page->ID;
$this->logInWithPermission("ADMIN");
$page->publishRecursive();
$page->deleteFromStage('Stage');
// Get the live version of the page
$page = Versioned::get_one_by_stage(SiteTree::class, Versioned::LIVE, "\"SiteTree\".\"ID\" = $pageID");
$this->assertTrue(is_object($page), 'Versioned::get_one_by_stage() is returning an object');
// subadmin users
$subadminuser = $this->objFromFixture(Member::class, 'subadmin');
$this->assertTrue(
$page->canEdit($subadminuser),
'Authenticated members can edit a page that was deleted from stage and marked as "Editable by logged in users" if they have cms permissions and belong to any of these groups'
);
}
public function testInheritCanViewFromSiteConfig()
{
$page = $this->objFromFixture(Page::class, 'inheritWithNoParent');
$siteconfig = $this->objFromFixture(SiteConfig::class, 'default');
$editor = $this->objFromFixture(Member::class, 'editor');
$editorGroup = $this->objFromFixture(Group::class, 'editorgroup');
$siteconfig->CanViewType = 'Anyone';
$siteconfig->write();
$this->assertTrue($page->canView(false), 'Anyone can view a page when set to inherit from the SiteConfig, and SiteConfig has canView set to LoggedInUsers');
$siteconfig->CanViewType = 'LoggedInUsers';
$siteconfig->write();
$this->assertFalse($page->canView(false), 'Anonymous can\'t view a page when set to inherit from the SiteConfig, and SiteConfig has canView set to LoggedInUsers');
$siteconfig->CanViewType = 'LoggedInUsers';
$siteconfig->write();
$this->assertTrue($page->canView($editor), 'Users can view a page when set to inherit from the SiteConfig, and SiteConfig has canView set to LoggedInUsers');
$siteconfig->CanViewType = 'OnlyTheseUsers';
$siteconfig->ViewerGroups()->add($editorGroup);
$siteconfig->write();
$this->assertTrue($page->canView($editor), 'Editors can view a page when set to inherit from the SiteConfig, and SiteConfig has canView set to OnlyTheseUsers');
$this->assertFalse($page->canView(false), 'Anonymous can\'t view a page when set to inherit from the SiteConfig, and SiteConfig has canView set to OnlyTheseUsers');
}
public function testInheritCanEditFromSiteConfig()
{
$page = $this->objFromFixture(Page::class, 'inheritWithNoParent');
$siteconfig = $this->objFromFixture(SiteConfig::class, 'default');
$editor = $this->objFromFixture(Member::class, 'editor');
$user = $this->objFromFixture(Member::class, 'websiteuser');
$editorGroup = $this->objFromFixture(Group::class, 'editorgroup');
$siteconfig->CanEditType = 'LoggedInUsers';
$siteconfig->write();
$this->assertFalse($page->canEdit(false), 'Anonymous can\'t edit a page when set to inherit from the SiteConfig, and SiteConfig has canEdit set to LoggedInUsers');
Security::setCurrentUser($editor);
$this->assertTrue($page->canEdit(), 'Users can edit a page when set to inherit from the SiteConfig, and SiteConfig has canEdit set to LoggedInUsers');
$siteconfig->CanEditType = 'OnlyTheseUsers';
$siteconfig->EditorGroups()->add($editorGroup);
$siteconfig->write();
$this->assertTrue($page->canEdit($editor), 'Editors can edit a page when set to inherit from the SiteConfig, and SiteConfig has canEdit set to OnlyTheseUsers');
Security::setCurrentUser(null);
$this->assertFalse($page->canEdit(false), 'Anonymous can\'t edit a page when set to inherit from the SiteConfig, and SiteConfig has canEdit set to OnlyTheseUsers');
Security::setCurrentUser($user);
$this->assertFalse($page->canEdit($user), 'Website user can\'t edit a page when set to inherit from the SiteConfig, and SiteConfig has canEdit set to OnlyTheseUsers');
}
}
| {
"content_hash": "8c60bc303a43a1e9547db5e1e4593e23",
"timestamp": "",
"source": "github",
"line_count": 478,
"max_line_length": 186,
"avg_line_length": 41.12970711297071,
"alnum_prop": 0.631586978636826,
"repo_name": "silverstripe/silverstripe-cms",
"id": "24f1cb2b617a8f4736d1eafff74bda30d2057ce0",
"size": "19660",
"binary": false,
"copies": "1",
"ref": "refs/heads/4",
"path": "tests/php/Model/SiteTreePermissionsTest.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Gherkin",
"bytes": "38314"
},
{
"name": "JavaScript",
"bytes": "204088"
},
{
"name": "PHP",
"bytes": "751900"
},
{
"name": "SCSS",
"bytes": "6182"
},
{
"name": "Scheme",
"bytes": "22139"
}
],
"symlink_target": ""
} |
package org.codehaus.griffon.runtime.rmi;
import griffon.annotations.core.Nonnull;
import griffon.annotations.core.Nullable;
import griffon.plugins.rmi.RmiClient;
import griffon.plugins.rmi.RmiClientCallback;
import griffon.plugins.rmi.RmiClientFactory;
import griffon.plugins.rmi.RmiClientStorage;
import griffon.plugins.rmi.RmiHandler;
import griffon.plugins.rmi.exceptions.RmiException;
import javax.inject.Inject;
import java.util.Map;
import static griffon.util.GriffonNameUtils.requireNonBlank;
import static java.util.Objects.requireNonNull;
/**
* @author Andres Almiray
*/
public class DefaultRmiHandler implements RmiHandler {
private static final String ERROR_PARAMS_NULL = "Argument 'params' must not be null";
private static final String ERROR_CALLBACK_NULL = "Argument 'callback' must not be null";
private static final String KEY_ID = "id";
private final RmiClientFactory rmiClientFactory;
private final RmiClientStorage rmiClientStorage;
@Inject
public DefaultRmiHandler(@Nonnull RmiClientFactory rmiClientFactory, @Nonnull RmiClientStorage rmiClientStorage) {
this.rmiClientFactory = rmiClientFactory;
this.rmiClientStorage = rmiClientStorage;
}
@Nullable
@Override
public <R> R withRmi(@Nonnull Map<String, Object> params, @Nonnull RmiClientCallback<R> callback) throws RmiException {
requireNonNull(callback, ERROR_CALLBACK_NULL);
try {
RmiClient client = getRmiClient(params);
return callback.handle(params, client);
} catch (Exception e) {
throw new RmiException("An error occurred while executing RMI call", e);
}
}
@Nonnull
private RmiClient getRmiClient(@Nonnull Map<String, Object> params) {
requireNonNull(params, ERROR_PARAMS_NULL);
if (params.containsKey(KEY_ID)) {
String id = String.valueOf(params.remove(KEY_ID));
RmiClient client = rmiClientStorage.get(id);
if (client == null) {
client = rmiClientFactory.create(params, id);
rmiClientStorage.set(id, client);
}
return client;
}
return rmiClientFactory.create(params, null);
}
@Override
public void destroyRmiClient(@Nonnull String clientId) {
requireNonBlank(clientId, "Argument 'clientId' must not be blank");
RmiClient rmiClient = rmiClientStorage.get(clientId);
try {
if (rmiClient != null) {
rmiClientFactory.destroy(rmiClient);
}
} finally {
rmiClientStorage.remove(clientId);
}
}
}
| {
"content_hash": "a4ae380ddeecbc0fcfecc8e2b59da4c0",
"timestamp": "",
"source": "github",
"line_count": 75,
"max_line_length": 123,
"avg_line_length": 35.38666666666666,
"alnum_prop": 0.6857573474001507,
"repo_name": "griffon-plugins/griffon-rmi-plugin",
"id": "b1f72b3970df0d031f13db78dbac288c830cd589",
"size": "3320",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "subprojects/griffon-rmi-core/src/main/java/org/codehaus/griffon/runtime/rmi/DefaultRmiHandler.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "40168"
},
{
"name": "Groovy",
"bytes": "7133"
},
{
"name": "Java",
"bytes": "46166"
}
],
"symlink_target": ""
} |
SYNONYM
#### According to
Index Fungorum
#### Published in
Lich. Exkurs. Vestra Becking 17 (1872)
#### Original name
Bacidia antricola Hulting
### Remarks
null | {
"content_hash": "aedb63721590523a9bd9c3c83ae78eca",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 38,
"avg_line_length": 12.538461538461538,
"alnum_prop": 0.7177914110429447,
"repo_name": "mdoering/backbone",
"id": "dbda24152252648eecb76bc7b48b410a85bb6992",
"size": "212",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Fungi/Ascomycota/Lecanoromycetes/Lecanorales/Ramalinaceae/Bacidia/Bacidia carneoglauca/ Syn. Bacidia antricola/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Runtime.InteropServices;
namespace FlashGame
{
/// <summary>
/// GameWindow.xaml 的交互逻辑
/// </summary>
public partial class GameWindow : Elysium.Controls.Window
{
public GameWindow(string path):base()
{
InitializeComponent();
string flashPath = path;
flashShow.Movie = flashPath;
flashShow.ScaleMode = 2;
flashShow.FSCommand += new AxShockwaveFlashObjects._IShockwaveFlashEvents_FSCommandEventHandler(flashShow_FSCommand);
this.Wpr = new FlaWndProc(this.FlashWndProc);
this.OldWndProc = SetWindowLong(flashShow.Handle, GWL_WNDPROC, this.Wpr);
}
public GameWindow()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
//WindowsFormsHost host = new WindowsFormsHost();
//AxShockwaveFlashObjects.AxShockwaveFlash flash = new AxShockwaveFlashObjects.AxShockwaveFlash();
//host.Child = flash;
//myGrid.Children.Add(host);
//string flashPath = Environment.CurrentDirectory;
//flashPath += @"\game\car.swf";
//flash.Movie = flashPath;
//缩放模式
//0 ——相当于 Scale 取 "ShowAll"
//1 ——相当于 Scale 取 "NoBorder"
//2 ——相当于 Scale 取 "ExactFit"
//flash.ScaleMode = 2;
//this.Wpr = new FlaWndProc(this.FlashWndProc);
//this.OldWndProc = SetWindowLong(flash.Handle, GWL_WNDPROC, this.Wpr);
}
//屏蔽FLash菜单
private const int GWL_WNDPROC = -4;
public delegate IntPtr FlaWndProc(IntPtr hWnd, int msg, IntPtr wParam, IntPtr iParam);
private IntPtr OldWndProc = IntPtr.Zero;
private FlaWndProc Wpr = null;
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr SetWindowLong(IntPtr hWnd, int nIndex, FlaWndProc wndProc);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr CallWindowProc(IntPtr wmdProc, IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);
private IntPtr FlashWndProc(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam)
{
if (msg == 516)
return (IntPtr)0;
return CallWindowProc(OldWndProc, hWnd, msg, wParam, lParam);
}
private void Button_Click(object sender, RoutedEventArgs e)
{
SettingWindow sw = new SettingWindow();
sw.Owner = this;
sw.ShowDialog();
}
protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
{
//MessageBoxResult result = MessageBox.Show(this, "确定要退出游戏吗", "信息提示", MessageBoxButton.YesNo, MessageBoxImage.Information);
//if(result == MessageBoxResult.Yes)
//{
// flashShow.Dispose();
//}
//else
//{
// e.Cancel = true;
//}
ConfirmWindow cw=new ConfirmWindow();
cw.Owner = this;
bool? result = cw.ShowDialog();
if (result == true)
{
flashShow.Dispose();
}
else
{
e.Cancel = true;
}
}
void flashShow_FSCommand(object sender, AxShockwaveFlashObjects._IShockwaveFlashEvents_FSCommandEvent e)
{
}
}
}
| {
"content_hash": "23a9fd9f51e73aabf86a9c21b56748ec",
"timestamp": "",
"source": "github",
"line_count": 121,
"max_line_length": 135,
"avg_line_length": 31.677685950413224,
"alnum_prop": 0.588051134881294,
"repo_name": "changweihua/ProjectStudy",
"id": "fca005eeafbba5a164509e748bbd446174f08582",
"size": "3921",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "FlashGame/GameWindow.xaml.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "238513"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<resources>
<dimen name="list_text_size">16dp</dimen>
<dimen name="list_time_text_size">16dp</dimen>
<dimen name="date_text_size">12pt</dimen>
</resources> | {
"content_hash": "bf6512ec8e409dd625693f1766e5bbba",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 50,
"avg_line_length": 34.5,
"alnum_prop": 0.6570048309178744,
"repo_name": "xtien/motogymkhana-android",
"id": "8b97c76691cf7912ddc87c5e75d5ce1c99a6ff71",
"size": "207",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/res/values-large-hdpi/dimens.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "436563"
}
],
"symlink_target": ""
} |
namespace rubinius {
class SharedState;
namespace agent {
class VariableAccess;
class Output;
}
class Thread;
class QueryAgent : public thread::Thread {
struct Client {
enum State {
eUnknown,
eWaitingAuth,
eRunning
} state;
int socket;
int auth_key;
Client(int s)
: state(eUnknown)
, socket(s)
{}
void set_running() {
state = eRunning;
}
bool needs_auth_p() {
return state == eWaitingAuth;
}
void begin_auth(int key) {
auth_key = key;
state = eWaitingAuth;
}
};
private:
SharedState& shared_;
State state_;
bool running_;
int port_;
int server_fd_;
bool verbose_;
fd_set fds_;
int max_fd_;
bool exit_;
int control_[2];
int loopback_[2];
int a2r_[2];
int r2a_[2];
std::vector<Client> sockets_;
agent::VariableAccess* vars_;
bool local_only_;
bool use_password_;
std::string password_;
uint32_t tmp_key_;
const static int cBackLog = 10;
public:
QueryAgent(SharedState& shared, STATE);
~QueryAgent();
void set_verbose() {
verbose_ = true;
}
bool running() {
return running_;
}
int port() {
return port_;
}
State* state() {
return &state_;
}
void add_fd(int fd) {
FD_SET((int_fd_t)fd, &fds_);
if(fd > max_fd_) max_fd_ = fd;
}
void remove_fd(int fd) {
FD_CLR((int_fd_t)fd, &fds_);
}
int loopback_socket() {
return loopback_[1];
}
int read_control() {
return control_[0];
}
int write_control() {
return control_[1];
}
int a2r_agent() {
return a2r_[1];
}
int a2r_ruby() {
return a2r_[0];
}
int r2a_agent() {
return r2a_[0];
}
int r2a_ruby() {
return r2a_[1];
}
void wakeup();
bool setup_local();
bool bind(int port);
void make_discoverable();
virtual void perform();
bool check_password(Client& client);
bool check_file_auth(Client& client);
bool process_commands(Client& client);
void on_fork();
void cleanup();
static void shutdown(STATE);
void shutdown_i();
};
}
| {
"content_hash": "67d1cd899e7f7fd8560c4a00e7f6e3e7",
"timestamp": "",
"source": "github",
"line_count": 145,
"max_line_length": 44,
"avg_line_length": 15.827586206896552,
"alnum_prop": 0.5246187363834423,
"repo_name": "takano32/rubinius",
"id": "9c71beeb90759867e8570ee9c9b69942b1eab56e",
"size": "2422",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "vm/agent.hpp",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
package hu.sch.postprocessing.db;
import com.sun.identity.authentication.spi.AuthLoginException;
import com.sun.identity.shared.debug.Debug;
import java.sql.Connection;
import java.sql.SQLException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
/**
*
* @author aldaris
*/
public class VirDatabaseConnectionFactory {
private static volatile VirDatabaseConnectionFactory INSTANCE = null;
private final Debug debug = Debug.getInstance("PostProcess");
private final String jndi;
private VirDatabaseConnectionFactory(final String jndiName) {
jndi = jndiName;
}
public static synchronized VirDatabaseConnectionFactory getInstance(final String jndiName) {
if (INSTANCE == null) {
INSTANCE = new VirDatabaseConnectionFactory(jndiName);
}
return INSTANCE;
}
public Connection getConnection() throws AuthLoginException {
if (jndi != null && !jndi.isEmpty()) {
try {
final Context initctx = new InitialContext();
final DataSource ds = (DataSource) initctx.lookup(jndi);
debug.message("Datasource Acquired: " + ds.toString());
return ds.getConnection();
} catch (NamingException ex) {
debug.error("Unable to look up JNDI datasource", ex);
throw new AuthLoginException("vipAuthVir", "virError", null);
} catch (SQLException ex) {
debug.error("SQL Exception while retrieving connection", ex);
throw new AuthLoginException("vipAuthVir", "virError", null);
}
}
throw new IllegalStateException("Unable to create database connectionpool");
}
}
| {
"content_hash": "6d8c009a4d70b90a54757974404bacfb",
"timestamp": "",
"source": "github",
"line_count": 50,
"max_line_length": 96,
"avg_line_length": 36,
"alnum_prop": 0.6633333333333333,
"repo_name": "kir-dev/vir_postprocessing",
"id": "c97464ba1c93ec2867ce2b48be27432c96779593",
"size": "1800",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/hu/sch/postprocessing/db/VirDatabaseConnectionFactory.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "22922"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_80) on Thu Jun 18 14:08:37 EDT 2015 -->
<title>org.apache.cassandra.db.context Class Hierarchy (apache-cassandra API)</title>
<meta name="date" content="2015-06-18">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="org.apache.cassandra.db.context Class Hierarchy (apache-cassandra API)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li>Use</li>
<li class="navBarCell1Rev">Tree</li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../org/apache/cassandra/db/compaction/package-tree.html">Prev</a></li>
<li><a href="../../../../../org/apache/cassandra/db/filter/package-tree.html">Next</a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/apache/cassandra/db/context/package-tree.html" target="_top">Frames</a></li>
<li><a href="package-tree.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h1 class="title">Hierarchy For Package org.apache.cassandra.db.context</h1>
<span class="strong">Package Hierarchies:</span>
<ul class="horizontal">
<li><a href="../../../../../overview-tree.html">All Packages</a></li>
</ul>
</div>
<div class="contentContainer">
<h2 title="Class Hierarchy">Class Hierarchy</h2>
<ul>
<li type="circle">java.lang.Object
<ul>
<li type="circle">org.apache.cassandra.db.context.<a href="../../../../../org/apache/cassandra/db/context/CounterContext.html" title="class in org.apache.cassandra.db.context"><span class="strong">CounterContext</span></a> (implements org.apache.cassandra.db.context.<a href="../../../../../org/apache/cassandra/db/context/IContext.html" title="interface in org.apache.cassandra.db.context">IContext</a>)</li>
<li type="circle">org.apache.cassandra.db.context.<a href="../../../../../org/apache/cassandra/db/context/CounterContext.ContextState.html" title="class in org.apache.cassandra.db.context"><span class="strong">CounterContext.ContextState</span></a></li>
</ul>
</li>
</ul>
<h2 title="Interface Hierarchy">Interface Hierarchy</h2>
<ul>
<li type="circle">org.apache.cassandra.db.context.<a href="../../../../../org/apache/cassandra/db/context/IContext.html" title="interface in org.apache.cassandra.db.context"><span class="strong">IContext</span></a></li>
</ul>
<h2 title="Enum Hierarchy">Enum Hierarchy</h2>
<ul>
<li type="circle">java.lang.Object
<ul>
<li type="circle">java.lang.Enum<E> (implements java.lang.Comparable<T>, java.io.Serializable)
<ul>
<li type="circle">org.apache.cassandra.db.context.<a href="../../../../../org/apache/cassandra/db/context/IContext.ContextRelationship.html" title="enum in org.apache.cassandra.db.context"><span class="strong">IContext.ContextRelationship</span></a></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li>Use</li>
<li class="navBarCell1Rev">Tree</li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../org/apache/cassandra/db/compaction/package-tree.html">Prev</a></li>
<li><a href="../../../../../org/apache/cassandra/db/filter/package-tree.html">Next</a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/apache/cassandra/db/context/package-tree.html" target="_top">Frames</a></li>
<li><a href="package-tree.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2015 The Apache Software Foundation</small></p>
</body>
</html>
| {
"content_hash": "7cc8335fbd2bf60b4a540a9ba0b146af",
"timestamp": "",
"source": "github",
"line_count": 146,
"max_line_length": 409,
"avg_line_length": 40.17123287671233,
"alnum_prop": 0.6363171355498721,
"repo_name": "anuragkapur/cassandra-2.1.2-ak-skynet",
"id": "d83c6bc69ca5ccb3f6247519ae5dd561a8cf6302",
"size": "5865",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "apache-cassandra-2.0.16/javadoc/org/apache/cassandra/db/context/package-tree.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "59670"
},
{
"name": "PowerShell",
"bytes": "37758"
},
{
"name": "Python",
"bytes": "622552"
},
{
"name": "Shell",
"bytes": "100474"
},
{
"name": "Thrift",
"bytes": "78926"
}
],
"symlink_target": ""
} |
<?php
/**
* Doctrine_Search_Analyzer
*
* @package Doctrine
* @subpackage Search
* @author Konsta Vesterinen <[email protected]>
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @version $Revision$
* @link www.doctrine-project.org
* @since 1.0
*/
class Doctrine_Search_Analyzer implements Doctrine_Search_Analyzer_Interface
{
protected $_options = array();
public function __construct($options = array())
{
$this->_options = $options;
}
public function analyze($text, $encoding = null)
{
return $text;
}
} | {
"content_hash": "c7408a39915b5458f2775fe3b5daa4b3",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 76,
"avg_line_length": 22.928571428571427,
"alnum_prop": 0.5950155763239875,
"repo_name": "hybmg57/jobeet",
"id": "18ce2ba0c33bcd9a71ccf22d30e2c35f0fe37f32",
"size": "1646",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/plugins/sfDoctrinePlugin/lib/vendor/doctrine/Doctrine/Search/Analyzer.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "25098"
},
{
"name": "JavaScript",
"bytes": "4841"
},
{
"name": "PHP",
"bytes": "3609090"
},
{
"name": "Shell",
"bytes": "1960"
}
],
"symlink_target": ""
} |
 2
To use the casino skill, try saying...
* *Alexa, ask casino game to bet on 5*
* *Alexa, ask casino game to place bet on 5*
* *Alexa, ask casino game for wager on 5*
You really need a break from all this buying time to time. So thanks to Alexa, you can bet on the roulette easily, and win/loose. All that for the fun of it really ! Nice distraction to have.
This little game will enable you to play with Alexa roulette. Bet on numbers from 0 to 36, Win .. and Loose ! Are you lucky today? Test it and bet with Alexa.
***
### Skill Details
* **Invocation Name:** casino game
* **Category:** null
* **ID:** amzn1.ask.skill.6fd379f7-fb16-4e9f-85d1-6dbab2c43a6d
* **ASIN:** B01N1G1W78
* **Author:** TFP/GIMO
* **Release Date:** November 25, 2016 @ 03:36:53
* **In-App Purchasing:** No
| {
"content_hash": "1c49871b4d35346677000587d51dd0f8",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 274,
"avg_line_length": 42.56,
"alnum_prop": 0.6823308270676691,
"repo_name": "dale3h/alexa-skills-list",
"id": "8f218ed8d11b7dc99e186e6faaf03922cb3a2a72",
"size": "1161",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "skills/B01N1G1W78/README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "16985"
}
],
"symlink_target": ""
} |
package gong.audio;
/**
* This represents the audio data exception.
* @version 4.2, 13/05/2011
* @author Gibson Lam
*/
public class AudioDataException extends Exception {
/**
* Creates a new instance of the exception
* @param message the error message
*/
public AudioDataException(String message) {
super(message);
}
}
| {
"content_hash": "ebaca6e1efae2d77d9e513183a2b5644",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 51,
"avg_line_length": 19.6,
"alnum_prop": 0.6045918367346939,
"repo_name": "obiba/nanogong",
"id": "fbce893de78238aeed42052e7556a21e974e13a9",
"size": "1034",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/gong/audio/AudioDataException.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "3966"
},
{
"name": "Java",
"bytes": "360113"
}
],
"symlink_target": ""
} |
<?php
namespace app\controllers;
use Yii;
use yii\web\Controller;
use app\services\ToolService;
class HtmlController extends Controller
{
public function actionIndex()
{
$post = $_POST;
$html = $post['html'] ? $post['html'] : '';
$html = ToolService::noxxs($html);
return $this->render('index', [
'html' => $html
]);
}
} | {
"content_hash": "8bc8e94634fff0baf7f556eececc9db7",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 51,
"avg_line_length": 20.31578947368421,
"alnum_prop": 0.5647668393782384,
"repo_name": "flyflyhe/yii2-test",
"id": "aa13e4041a296d0116b4d3579a8537254d3e9c96",
"size": "386",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "controllers/HtmlController.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Batchfile",
"bytes": "1030"
},
{
"name": "CSS",
"bytes": "2046"
},
{
"name": "HTML",
"bytes": "13351"
},
{
"name": "JavaScript",
"bytes": "3305"
},
{
"name": "PHP",
"bytes": "157122"
}
],
"symlink_target": ""
} |
package org.elasticsearch.search.runtime;
import static org.hamcrest.Matchers.equalTo;
public class GeoPointScriptFieldExistsQueryTests extends AbstractGeoPointScriptFieldQueryTestCase<GeoPointScriptFieldExistsQuery> {
@Override
protected GeoPointScriptFieldExistsQuery createTestInstance() {
return new GeoPointScriptFieldExistsQuery(randomScript(), leafFactory, randomAlphaOfLength(5));
}
@Override
protected GeoPointScriptFieldExistsQuery copy(GeoPointScriptFieldExistsQuery orig) {
return new GeoPointScriptFieldExistsQuery(orig.script(), leafFactory, orig.fieldName());
}
@Override
protected GeoPointScriptFieldExistsQuery mutate(GeoPointScriptFieldExistsQuery orig) {
if (randomBoolean()) {
new GeoPointScriptFieldExistsQuery(randomValueOtherThan(orig.script(), this::randomScript), leafFactory, orig.fieldName());
}
return new GeoPointScriptFieldExistsQuery(orig.script(), leafFactory, orig.fieldName() + "modified");
}
@Override
public void testMatches() {
assertTrue(createTestInstance().matches(new long[] { 1L }, randomIntBetween(1, Integer.MAX_VALUE)));
assertFalse(createTestInstance().matches(new long[0], 0));
assertFalse(createTestInstance().matches(new long[1], 0));
}
@Override
protected void assertToString(GeoPointScriptFieldExistsQuery query) {
assertThat(query.toString(query.fieldName()), equalTo("GeoPointScriptFieldExistsQuery"));
}
}
| {
"content_hash": "43b78bcf481c48eeaac5c1d9300c4a7b",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 135,
"avg_line_length": 40.86486486486486,
"alnum_prop": 0.7453703703703703,
"repo_name": "robin13/elasticsearch",
"id": "4099fc9df7675c4174f5e261609de74b00d41a23",
"size": "1865",
"binary": false,
"copies": "26",
"ref": "refs/heads/master",
"path": "server/src/test/java/org/elasticsearch/search/runtime/GeoPointScriptFieldExistsQueryTests.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "11082"
},
{
"name": "Batchfile",
"bytes": "14049"
},
{
"name": "Emacs Lisp",
"bytes": "3341"
},
{
"name": "FreeMarker",
"bytes": "45"
},
{
"name": "Groovy",
"bytes": "315863"
},
{
"name": "HTML",
"bytes": "3399"
},
{
"name": "Java",
"bytes": "40107206"
},
{
"name": "Perl",
"bytes": "7271"
},
{
"name": "Python",
"bytes": "54437"
},
{
"name": "Shell",
"bytes": "108937"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html>
<head>
<script src="../jspsych.js"></script>
<script src="../plugins/jspsych-survey-text.js"></script>
<link rel="stylesheet" href="../css/jspsych.css"></link>
</head>
<body></body>
<script>
var survey_page1 = {
type: 'survey-text',
questions: [
{prompt: 'How old are you?', columns: 3, required: true, name: 'Age'},
{prompt: 'Where were you born?', placeholder: 'City, State/Province, Country', columns: 50, name: 'BirthLocation'}
],
randomize_question_order: true
};
var survey_page2 = {
type: 'survey-text',
questions: [
{prompt: 'Tell me about your day', placeholder: 'How did it start?', rows:10, columns: 50}
]
}
jsPsych.init({
timeline: [survey_page1, survey_page2],
on_finish: function() { jsPsych.data.displayData(); }
});
</script>
</html>
| {
"content_hash": "1d95ccd2f06e2503017767a4fd89a75c",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 120,
"avg_line_length": 26.470588235294116,
"alnum_prop": 0.5777777777777777,
"repo_name": "prosodylab/prosodylab-experimenter",
"id": "6702255d252bbdad3bdbf255b06295631af951e2",
"size": "900",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "javascripts/jspsych-6.1.0/examples/jspsych-survey-text.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "718859"
},
{
"name": "Matlab",
"bytes": "70300"
},
{
"name": "Objective-C",
"bytes": "817"
}
],
"symlink_target": ""
} |
<?php
declare(strict_types=1);
namespace BEAR\Resource\Module;
use BEAR\Resource\Anchor;
use BEAR\Resource\AnchorInterface;
use BEAR\Resource\ExtraMethodInvoker;
use BEAR\Resource\Factory;
use BEAR\Resource\FactoryInterface;
use BEAR\Resource\HalLink;
use BEAR\Resource\Invoker;
use BEAR\Resource\InvokerInterface;
use BEAR\Resource\Linker;
use BEAR\Resource\LinkerInterface;
use BEAR\Resource\LoggerInterface;
use BEAR\Resource\NamedParameter;
use BEAR\Resource\NamedParameterInterface;
use BEAR\Resource\NamedParamMetas;
use BEAR\Resource\NamedParamMetasInterface;
use BEAR\Resource\NullLogger;
use BEAR\Resource\NullReverseLink;
use BEAR\Resource\OptionsMethods;
use BEAR\Resource\OptionsRenderer;
use BEAR\Resource\PrettyJsonRenderer;
use BEAR\Resource\RenderInterface;
use BEAR\Resource\Resource;
use BEAR\Resource\ResourceInterface;
use BEAR\Resource\ReverseLinkInterface;
use BEAR\Resource\SchemeCollectionInterface;
use BEAR\Resource\UriFactory;
use Ray\Di\AbstractModule;
use Ray\Di\Exception\NotFound;
use Ray\Di\Scope;
/**
* Provides ResourceInterface and derived bindings
*
* The following module is installed:
*
* UriFactory
* ResourceInterface
* InvokerInterface
* LinkerInterface
* FactoryInterface
* SchemeCollectionInterface
* AnchorInterface
* NamedParameterInterface
* RenderInterface
* RenderInterface-options
* OptionsMethods
* NamedParamMetasInterface
* ExtraMethodInvoker
* HalLink
* ReverseLinkInterface
* LoggerInterface
*
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
final class ResourceClientModule extends AbstractModule
{
/**
* {@inheritdoc}
*
* @throws NotFound
*/
protected function configure(): void
{
$this->bind(UriFactory::class);
$this->bind(ResourceInterface::class)->to(Resource::class)->in(Scope::SINGLETON);
$this->bind(InvokerInterface::class)->to(Invoker::class);
$this->bind(LinkerInterface::class)->to(Linker::class);
$this->bind(FactoryInterface::class)->to(Factory::class);
$this->bind(SchemeCollectionInterface::class)->toProvider(SchemeCollectionProvider::class);
$this->bind(AnchorInterface::class)->to(Anchor::class);
$this->bind(NamedParameterInterface::class)->to(NamedParameter::class);
$this->bind(RenderInterface::class)->to(PrettyJsonRenderer::class)->in(Scope::SINGLETON);
/** @psalm-suppress DeprecatedClass */
$this->bind(RenderInterface::class)->annotatedWith('options')->to(OptionsRenderer::class);
$this->bind(OptionsMethods::class);
$this->bind(NamedParamMetasInterface::class)->to(NamedParamMetas::class);
$this->bind(ExtraMethodInvoker::class);
$this->bind(HalLink::class);
$this->bind(ReverseLinkInterface::class)->to(NullReverseLink::class);
$this->bind(LoggerInterface::class)->to(NullLogger::class);
}
}
| {
"content_hash": "236bfd7a965830a4821d9efa32e32fd7",
"timestamp": "",
"source": "github",
"line_count": 88,
"max_line_length": 99,
"avg_line_length": 32.72727272727273,
"alnum_prop": 0.7472222222222222,
"repo_name": "bearsunday/BEAR.Resource",
"id": "8848918a037e3b27d87984e54b5ac0c19d58905f",
"size": "2880",
"binary": false,
"copies": "1",
"ref": "refs/heads/1.x",
"path": "src/Module/ResourceClientModule.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "345985"
}
],
"symlink_target": ""
} |
package Paws::ElasticBeanstalk::DescribeEnvironmentHealthResult;
use Moose;
has ApplicationMetrics => (is => 'ro', isa => 'Paws::ElasticBeanstalk::ApplicationMetrics');
has Causes => (is => 'ro', isa => 'ArrayRef[Str|Undef]');
has Color => (is => 'ro', isa => 'Str');
has EnvironmentName => (is => 'ro', isa => 'Str');
has HealthStatus => (is => 'ro', isa => 'Str');
has InstancesHealth => (is => 'ro', isa => 'Paws::ElasticBeanstalk::InstanceHealthSummary');
has RefreshedAt => (is => 'ro', isa => 'Str');
has Status => (is => 'ro', isa => 'Str');
has _request_id => (is => 'ro', isa => 'Str');
1;
### main pod documentation begin ###
=head1 NAME
Paws::ElasticBeanstalk::DescribeEnvironmentHealthResult
=head1 ATTRIBUTES
=head2 ApplicationMetrics => L<Paws::ElasticBeanstalk::ApplicationMetrics>
Application request metrics for the environment.
=head2 Causes => ArrayRef[Str|Undef]
Descriptions of the data that contributed to the environment's current
health status.
=head2 Color => Str
The health color of the environment.
=head2 EnvironmentName => Str
The environment's name.
=head2 HealthStatus => Str
The health status of the environment. For example, C<Ok>.
=head2 InstancesHealth => L<Paws::ElasticBeanstalk::InstanceHealthSummary>
Summary health information for the instances in the environment.
=head2 RefreshedAt => Str
The date and time that the health information was retrieved.
=head2 Status => Str
The environment's operational status. C<Ready>, C<Launching>,
C<Updating>, C<Terminating>, or C<Terminated>.
Valid values are: C<"Green">, C<"Yellow">, C<"Red">, C<"Grey">
=head2 _request_id => Str
=cut
| {
"content_hash": "bcb1b75050218a9c1e68585ce0d52092",
"timestamp": "",
"source": "github",
"line_count": 70,
"max_line_length": 94,
"avg_line_length": 23.84285714285714,
"alnum_prop": 0.6932294787297784,
"repo_name": "ioanrogers/aws-sdk-perl",
"id": "6748c278f9d379282345c0e77d752717b83cce5a",
"size": "1670",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "auto-lib/Paws/ElasticBeanstalk/DescribeEnvironmentHealthResult.pm",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Makefile",
"bytes": "1292"
},
{
"name": "Perl",
"bytes": "20360380"
},
{
"name": "Perl 6",
"bytes": "99393"
},
{
"name": "Shell",
"bytes": "445"
}
],
"symlink_target": ""
} |
wid=$(xdotool search --classname urxvtq)
if [ -z "$wid" ]; then
urxvt -name urxvtq -geometry 80x28 &
sleep 0.1
wid=$(xdotool search --classname urxvtq)
xdotool windowactive $wid
xdotool windowmove $wid 0 0
xdotool windowfocus $wid
#xdotool key Control_L+l
elif [ -z "$(xdotool search --onlyvisible --classname urxvtq 2>/dev/null)" ]; then
xdotool windowmap $wid
xdotool windowfocus $wid
xdotool windowmove $wid 0 0
else
xdotool windowunmap $wid
fi
| {
"content_hash": "c6a95a400a3aca21b42f4241d9940809",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 82,
"avg_line_length": 27.705882352941178,
"alnum_prop": 0.7133757961783439,
"repo_name": "moraisaugusto/another-dotfiles",
"id": "5193fc7eb8a564735a042822a7cc1ebecd7fc057",
"size": "484",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "scripts/bin/urxvt-launcher.sh",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "AppleScript",
"bytes": "2357"
},
{
"name": "C",
"bytes": "6410"
},
{
"name": "Lua",
"bytes": "10190"
},
{
"name": "Makefile",
"bytes": "428"
},
{
"name": "Python",
"bytes": "14135"
},
{
"name": "Shell",
"bytes": "231488"
},
{
"name": "Vim Script",
"bytes": "409733"
},
{
"name": "Vim Snippet",
"bytes": "28019"
}
],
"symlink_target": ""
} |
package org.tensorflow.demo.video.video;
import java.io.IOException;
import org.tensorflow.demo.video.SessionBuilder;
import org.tensorflow.demo.video.rtp.H263Packetizer;
import android.graphics.ImageFormat;
import android.hardware.Camera.CameraInfo;
import android.media.MediaRecorder;
import android.service.textservice.SpellCheckerService.Session;
/**
* A class for streaming H.263 from the camera of an android device using RTP.
* You should use a {@link Session} instantiated with {@link SessionBuilder} instead of using this class directly.
* Call {@link #setDestinationAddress(InetAddress)}, {@link #setDestinationPorts(int)} and {@link #setVideoQuality(VideoQuality)}
* to configure the stream. You can then call {@link #start()} to start the RTP stream.
* Call {@link #stop()} to stop the stream.
*/
public class H263Stream extends VideoStream {
/**
* Constructs the H.263 stream.
* Uses CAMERA_FACING_BACK by default.
* @throws IOException
*/
public H263Stream() throws IOException {
this(CameraInfo.CAMERA_FACING_BACK);
}
/**
* Constructs the H.263 stream.
* @param cameraId Can be either CameraInfo.CAMERA_FACING_BACK or CameraInfo.CAMERA_FACING_FRONT
* @throws IOException
*/
public H263Stream(int cameraId) {
super(cameraId);
mCameraImageFormat = ImageFormat.NV21;
mVideoEncoder = MediaRecorder.VideoEncoder.H263;
mPacketizer = new H263Packetizer();
}
/**
* Starts the stream.
*/
public synchronized void start() throws IllegalStateException, IOException {
if (!mStreaming) {
configure();
super.start();
}
}
public synchronized void configure() throws IllegalStateException, IOException {
super.configure();
mMode = MODE_MEDIARECORDER_API;
mQuality = mRequestedQuality.clone();
}
/**
* Returns a description of the stream using SDP. It can then be included in an SDP file.
*/
public String getSessionDescription() {
return "m=video "+String.valueOf(getDestinationPorts()[0])+" RTP/AVP 96\r\n" +
"a=rtpmap:96 H263-1998/90000\r\n";
}
}
| {
"content_hash": "45d3e2a5bcd7e7e7ed1f504a2b61c774",
"timestamp": "",
"source": "github",
"line_count": 68,
"max_line_length": 129,
"avg_line_length": 30,
"alnum_prop": 0.7357843137254902,
"repo_name": "ran5515/DeepDecision",
"id": "3031ec415d0260c9cce7f7a2ba1fbf9e871549ba",
"size": "2911",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "tensorflow/examples/android/src/org/tensorflow/demo/video/video/H263Stream.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "7666"
},
{
"name": "C",
"bytes": "194862"
},
{
"name": "C++",
"bytes": "27276074"
},
{
"name": "CMake",
"bytes": "177556"
},
{
"name": "Go",
"bytes": "929281"
},
{
"name": "Java",
"bytes": "1014731"
},
{
"name": "Jupyter Notebook",
"bytes": "1833675"
},
{
"name": "LLVM",
"bytes": "6536"
},
{
"name": "Makefile",
"bytes": "37293"
},
{
"name": "Objective-C",
"bytes": "7056"
},
{
"name": "Objective-C++",
"bytes": "63210"
},
{
"name": "Protocol Buffer",
"bytes": "251242"
},
{
"name": "PureBasic",
"bytes": "24932"
},
{
"name": "Python",
"bytes": "23846933"
},
{
"name": "Ruby",
"bytes": "327"
},
{
"name": "Shell",
"bytes": "337229"
}
],
"symlink_target": ""
} |
package org.frameworkset.nosql.mongodb;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
import com.frameworkset.util.StringUtil;
import com.mongodb.Bytes;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoClientOptions.Builder;
import com.mongodb.MongoCredential;
import com.mongodb.ReadPreference;
import com.mongodb.ServerAddress;
import com.mongodb.WriteConcern;
import com.mongodb.WriteConcernException;
import com.mongodb.WriteResult;
public class MongoDB {
private static Logger log = Logger.getLogger(MongoDB.class);
private String serverAddresses;
private String option;
private String writeConcern;
private String readPreference;
private Mongo mongoclient;
private String mode = null;
private boolean autoConnectRetry = true;
private int connectionsPerHost = 500;
private int maxWaitTime = 120000;
private int socketTimeout = 0;
private int connectTimeout = 15000;
private int threadsAllowedToBlockForConnectionMultiplier = 50;
private boolean socketKeepAlive = true;
private List<ClientMongoCredential> credentials;
private List<MongoCredential> mongoCredentials;
public Mongo getMongoClient()
{
// try {
// Mongo mongoClient = new Mongo(Arrays.asList(new ServerAddress("10.0.15.134", 27017),
// new ServerAddress("10.0.15.134", 27018),
// new ServerAddress("10.0.15.38", 27017),new ServerAddress("10.0.15.39", 27017)
// ));
// mongoClient.addOption( Bytes.QUERYOPTION_SLAVEOK );
// mongoClient.setWriteConcern(WriteConcern.JOURNAL_SAFE);
//// ReadPreference.secondaryPreferred();
// mongoClient.setReadPreference(ReadPreference.nearest());
//// mongoClient.setReadPreference(ReadPreference.primaryPreferred());
// return mongoClient;
// } catch (Exception e) {
// throw new java.lang.RuntimeException(e);
// }
return mongoclient;
}
private List<ServerAddress> parserAddress() throws NumberFormatException, UnknownHostException
{
if(StringUtil.isEmpty(serverAddresses))
return null;
serverAddresses = serverAddresses.trim();
List<ServerAddress> trueaddresses = new ArrayList<ServerAddress>();
if(mode != null && mode.equals("simple"))
{
String info[] = serverAddresses.split(":");
ServerAddress ad = new ServerAddress(info[0].trim(),Integer.parseInt(info[1].trim()));
trueaddresses.add(ad);
return trueaddresses;
}
String[] addresses = this.serverAddresses.split("\n");
for(String address:addresses)
{
address = address.trim();
String info[] = address.split(":");
ServerAddress ad = new ServerAddress(info[0].trim(),Integer.parseInt(info[1].trim()));
trueaddresses.add(ad);
}
return trueaddresses;
}
private int[] parserOption() throws NumberFormatException, UnknownHostException
{
if(StringUtil.isEmpty(this.option))
return null;
option = option.trim();
String[] options = this.option.split("\r\n");
int[] ret = new int[options.length];
int i = 0;
for(String op:options)
{
op = op.trim();
ret[i] = _getOption( op);
i ++;
}
return ret;
}
private int _getOption(String op)
{
if(op.equals("QUERYOPTION_TAILABLE"))
return Bytes.QUERYOPTION_TAILABLE;
else if(op.equals("QUERYOPTION_SLAVEOK"))
return Bytes.QUERYOPTION_SLAVEOK;
else if(op.equals("QUERYOPTION_OPLOGREPLAY"))
return Bytes.QUERYOPTION_OPLOGREPLAY;
else if(op.equals("QUERYOPTION_NOTIMEOUT"))
return Bytes.QUERYOPTION_NOTIMEOUT;
else if(op.equals("QUERYOPTION_AWAITDATA"))
return Bytes.QUERYOPTION_AWAITDATA;
else if(op.equals("QUERYOPTION_EXHAUST"))
return Bytes.QUERYOPTION_EXHAUST;
else if(op.equals("QUERYOPTION_PARTIAL"))
return Bytes.QUERYOPTION_PARTIAL;
else if(op.equals("RESULTFLAG_CURSORNOTFOUND"))
return Bytes.RESULTFLAG_CURSORNOTFOUND;
else if(op.equals("RESULTFLAG_ERRSET"))
return Bytes.RESULTFLAG_ERRSET;
else if(op.equals("RESULTFLAG_SHARDCONFIGSTALE"))
return Bytes.RESULTFLAG_SHARDCONFIGSTALE;
else if(op.equals("RESULTFLAG_AWAITCAPABLE"))
return Bytes.RESULTFLAG_AWAITCAPABLE;
throw new RuntimeException("未知的option:"+op);
}
public static void main(String[] args)
{
String aa = "REPLICA_ACKNOWLEDGED(10)";
int idx = aa.indexOf("(") ;
String n = aa.substring(idx + 1,aa.length() - 1);
System.out.println(n);
}
private WriteConcern _getWriteConcern()
{
if(StringUtil.isEmpty(this.writeConcern))
return null;
writeConcern=writeConcern.trim();
if(this.writeConcern.equals("NONE"))
return WriteConcern.UNACKNOWLEDGED;
else if(this.writeConcern.equals("NORMAL"))
return WriteConcern.NORMAL;
else if(this.writeConcern.equals("SAFE"))
return WriteConcern.SAFE;
else if(this.writeConcern.equals("MAJORITY"))
return WriteConcern.MAJORITY;
else if(this.writeConcern.equals("FSYNC_SAFE"))
return WriteConcern.FSYNC_SAFE;
else if(this.writeConcern.equals("JOURNAL_SAFE"))
return WriteConcern.JOURNAL_SAFE;
else if(this.writeConcern.equals("REPLICAS_SAFE"))
return WriteConcern.REPLICAS_SAFE;
else if(this.writeConcern.startsWith("REPLICA_ACKNOWLEDGED"))
{
int idx = writeConcern.indexOf("(") ;
if(idx < 0)
{
return WriteConcern.REPLICA_ACKNOWLEDGED;
}
else
{
String n = this.writeConcern.substring(idx + 1,writeConcern.length() - 1);
try {
if(n.indexOf(",") < 0)
{
int N = Integer.parseInt(n);
return new WriteConcern(N);
}
else
{
String[] p = n.split(",");
n = p[0];
String _wtimeout = p[1];
int N = Integer.parseInt(n);
int wtimeout = Integer.parseInt(_wtimeout);
return new WriteConcern(N,wtimeout,false);
}
} catch (NumberFormatException e) {
return WriteConcern.REPLICA_ACKNOWLEDGED;
}
}
}
else if(this.writeConcern.equals("ACKNOWLEDGED"))
return WriteConcern.ACKNOWLEDGED;
else if(this.writeConcern.equals("UNACKNOWLEDGED"))
return WriteConcern.UNACKNOWLEDGED;
else if(this.writeConcern.equals("FSYNCED"))
return WriteConcern.FSYNCED;
else if(this.writeConcern.equals("JOURNALED"))
return WriteConcern.JOURNALED;
else if(this.writeConcern.equals("ERRORS_IGNORED"))
return WriteConcern.UNACKNOWLEDGED;
throw new RuntimeException("未知的WriteConcern:"+writeConcern);
}
private ReadPreference _getReadPreference()
{
if(StringUtil.isEmpty(this.readPreference))
return null;
if(readPreference.equals("PRIMARY"))
return ReadPreference.primary();
else if(readPreference.equals("SECONDARY"))
return ReadPreference.secondary();
else if(readPreference.equals("SECONDARY_PREFERRED"))
return ReadPreference.secondaryPreferred();
else if(readPreference.equals("PRIMARY_PREFERRED"))
return ReadPreference.primaryPreferred();
else if(readPreference.equals("NEAREST"))
return ReadPreference.nearest();
throw new RuntimeException("未知的ReadPreference:"+readPreference);
}
private void buildCredentials()
{
if(this.credentials != null && this.credentials.size() > 0)
{
this.mongoCredentials = new ArrayList<MongoCredential>();
for(ClientMongoCredential clientMongoCredential:this.credentials)
{
if(StringUtil.isEmpty(clientMongoCredential.getMechanism())
||clientMongoCredential.getMechanism().equals(MongoCredential.MONGODB_CR_MECHANISM))
{
mongoCredentials.add(MongoCredential.createMongoCRCredential(clientMongoCredential.getUserName(), clientMongoCredential.getDatabase(),clientMongoCredential.getPassword().toCharArray()));
}
else if(clientMongoCredential.getMechanism().equals(MongoCredential.PLAIN_MECHANISM))
{
mongoCredentials.add(MongoCredential.createPlainCredential(clientMongoCredential.getUserName(), clientMongoCredential.getDatabase(),clientMongoCredential.getPassword().toCharArray()));
}
else if(clientMongoCredential.getMechanism().equals(MongoCredential.MONGODB_X509_MECHANISM))
{
mongoCredentials.add(MongoCredential.createMongoX509Credential(clientMongoCredential.getUserName()));
}
else if(clientMongoCredential.getMechanism().equals(MongoCredential.GSSAPI_MECHANISM))
{
mongoCredentials.add(MongoCredential.createGSSAPICredential(clientMongoCredential.getUserName()));
}
}
}
}
public void init()
{
try {
buildCredentials();
if(mode != null && mode.equals("simple"))
{
this.initsimple();
}
else
{
// options.autoConnectRetry = autoConnectRetry;
// options.connectionsPerHost = connectionsPerHost;
// options.maxWaitTime = maxWaitTime;
// options.socketTimeout = socketTimeout;
// options.connectTimeout = connectTimeout;
// options.threadsAllowedToBlockForConnectionMultiplier = threadsAllowedToBlockForConnectionMultiplier;
// options.socketKeepAlive=socketKeepAlive;
Builder builder = MongoClientOptions.builder();
builder.autoConnectRetry( autoConnectRetry);
builder.connectionsPerHost( connectionsPerHost);
builder.maxWaitTime( maxWaitTime);
builder.socketTimeout( socketTimeout);
builder.connectTimeout( connectTimeout);
builder.threadsAllowedToBlockForConnectionMultiplier( threadsAllowedToBlockForConnectionMultiplier);
builder.socketKeepAlive(socketKeepAlive);
MongoClientOptions options = builder.build();//new MongoClientOptions();
MongoClient mongoClient = null;
if(mongoCredentials == null || mongoCredentials.size() == 0)
{
mongoClient = new MongoClient(parserAddress(),options);
}
else
{
mongoClient = new MongoClient(parserAddress(),mongoCredentials,options);
}
int[] ops = parserOption();
for(int i = 0; ops != null && i < ops.length; i ++)
mongoClient.addOption( ops[i] );
WriteConcern wc = this._getWriteConcern();
if(wc != null)
mongoClient.setWriteConcern(wc);
//ReadPreference.secondaryPreferred();
ReadPreference rf = _getReadPreference();
if(rf != null)
mongoClient.setReadPreference(ReadPreference.nearest());
// mongoClient.setReadPreference(ReadPreference.primaryPreferred());
this.mongoclient = mongoClient;
}
} catch (RuntimeException e) {
log.error("初始化mongodb client failed.", e);
throw e;
}
catch (Exception e) {
log.error("初始化mongodb client failed.", e);
throw new RuntimeException(e);
}
}
public void initsimple() throws Exception
{
try {
// MongoOptions options = new MongoOptions();
// options.autoConnectRetry = autoConnectRetry;
// options.connectionsPerHost = connectionsPerHost;
// options.maxWaitTime = maxWaitTime;
// options.socketTimeout = socketTimeout;
// options.connectTimeout = connectTimeout;
// options.threadsAllowedToBlockForConnectionMultiplier = threadsAllowedToBlockForConnectionMultiplier;
// options.socketKeepAlive=socketKeepAlive;
// Mongo mongoClient = new Mongo(parserAddress().get(0),options);
Builder builder = MongoClientOptions.builder();
builder.autoConnectRetry( autoConnectRetry);
builder.connectionsPerHost( connectionsPerHost);
builder.maxWaitTime( maxWaitTime);
builder.socketTimeout( socketTimeout);
builder.connectTimeout( connectTimeout);
builder.threadsAllowedToBlockForConnectionMultiplier( threadsAllowedToBlockForConnectionMultiplier);
builder.socketKeepAlive(socketKeepAlive);
MongoClientOptions options = builder.build();//new MongoClientOptions();
MongoClient mongoClient = null;
if(mongoCredentials == null || mongoCredentials.size() == 0)
{
mongoClient = new MongoClient(parserAddress().get(0),options);
}
else
{
mongoClient = new MongoClient(parserAddress().get(0),mongoCredentials,options);
}
int[] ops = parserOption();
for(int i = 0; ops != null && i < ops.length; i ++)
mongoClient.addOption( ops[i] );
WriteConcern wc = this._getWriteConcern();
if(wc != null)
mongoClient.setWriteConcern(wc);
//ReadPreference.secondaryPreferred();
// mongoClient.setReadPreference(ReadPreference.primaryPreferred());
this.mongoclient = mongoClient;
} catch (RuntimeException e) {
throw e;
}
catch (Exception e) {
throw e;
}
}
public void close()
{
if(this.mongoclient != null)
this.mongoclient.close();
}
public static WriteResult update(DBCollection collection, DBObject q , DBObject o )
{
try
{
WriteResult wr = collection.update(q, o);
return wr;
}
catch(WriteConcernException e)
{
log.debug("update:",e);
return null;
}
}
public static WriteResult update(DBCollection collection, DBObject q , DBObject o , WriteConcern concern)
{
WriteResult wr = collection.update(q, o, false , false,concern );
return wr;
}
public static DBObject findAndModify( DBCollection collection,DBObject query , DBObject update )
{
try
{
DBObject object = collection.findAndModify(query,update);
return object;
}
catch(WriteConcernException e)
{
log.debug("findAndModify:",e);
return null;
}
}
public static DBObject findAndRemove(DBCollection collection, DBObject query )
{
try
{
DBObject object = collection.findAndRemove(query);
return object;
}
catch(WriteConcernException e)
{
log.debug("findAndRemove:",e);
return null;
}
}
public static WriteResult insert(DBCollection collection,DBObject ... arr)
{
try
{
return collection.insert(arr);
}
catch(WriteConcernException e)
{
log.debug("insert:",e);
return null;
}
}
public static WriteResult insert(WriteConcern concern ,DBCollection collection,DBObject ... arr)
{
return collection.insert(arr,concern);
}
public static WriteResult remove(DBCollection collection, DBObject o )
{
try
{
return collection.remove(o);
}
catch(WriteConcernException e)
{
log.debug("remove:",e);
return null;
}
}
public static WriteResult remove(DBCollection collection, DBObject o , WriteConcern concern ){
return collection.remove(o,concern);
}
}
| {
"content_hash": "c150008e3fd49f7930538795ab6d64ad",
"timestamp": "",
"source": "github",
"line_count": 458,
"max_line_length": 191,
"avg_line_length": 32.751091703056765,
"alnum_prop": 0.6788666666666666,
"repo_name": "lewis-ing/bbossgroups-3.5",
"id": "052b0f2624e3f9d9396123833f1bf5d2cf625ff8",
"size": "15030",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "bboss-security/src-token/org/frameworkset/nosql/mongodb/MongoDB.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "27079"
},
{
"name": "C",
"bytes": "227968"
},
{
"name": "CSS",
"bytes": "1423767"
},
{
"name": "HTML",
"bytes": "296717"
},
{
"name": "Java",
"bytes": "22428368"
},
{
"name": "JavaScript",
"bytes": "2522565"
},
{
"name": "PHP",
"bytes": "4843"
},
{
"name": "PLSQL",
"bytes": "3714"
},
{
"name": "Perl",
"bytes": "9821"
},
{
"name": "Python",
"bytes": "3285"
},
{
"name": "Shell",
"bytes": "13557"
},
{
"name": "XSLT",
"bytes": "219158"
}
],
"symlink_target": ""
} |
module Pageflow
# Options to be defined in the pageflow initializer of the main app.
class Configuration
# Default options for paperclip attachments which are supposed to
# use filesystem storage.
attr_accessor :paperclip_filesystem_default_options
# Default options for paperclip attachments which are supposed to use
# s3 storage.
attr_accessor :paperclip_s3_default_options
# String to interpolate into paths of files generated by paperclip
# preprocessors. This allows to refresh cdn caches after
# reprocessing attachments.
attr_accessor :paperclip_attachments_version
# Path to the location in the filesystem where attachments shall
# be stored. The value of this option is available via the
# pageflow_filesystem_root paperclip interpolation.
attr_accessor :paperclip_filesystem_root
# Refer to the pageflow initializer template for a list of
# supported options.
attr_accessor :zencoder_options
# A constraint used by the pageflow engine to restrict access to
# the editor related HTTP end points. This can be used to ensure
# the editor is only accessable via a certain host when different
# CNAMES are used to access the public end points of pageflow.
attr_accessor :editor_route_constraint
# The email address to use as from header in invitation mails to
# new users
attr_accessor :mailer_sender
# Extend the configuration based on feature flags set for accounts
# or entries.
#
# @example
#
# Make a page type only available if a feature flag is set on the
# entry or its account
#
# config.features.register('some_special_page_type' do |config
# config.page_types.register(Pageflow::SomeSpecial.page_type)
# end
#
# @since 0.9
# @returns [Features}
attr_reader :features
# Subscribe to hooks in order to be notified of events. Any object
# with a call method can be a subscriber
#
# Example:
#
# config.hooks.subscribe(:submit_file, -> { do_something })
#
attr_reader :hooks
# Limit the use of certain resources. Any object implementing the
# interface of Pageflow::Quota can be registered.
#
# Example:
#
# config.quotas.register(:users, UserQuota)
#
attr_accessor :quotas
# Additional themes can be registered to use custom css.
#
# Example:
#
# config.themes.register(:custom)
#
# @return [Themes]
attr_reader :themes
# Register new types of pages.
# @return [PageTypes]
# @since 0.9
attr_reader :page_types
# List of {FileType} instances provided by page types.
# @return [FileTypes]
attr_reader :file_types
# Used to register new types of widgets to be displayed in entries.
# @return [WidgetTypes]
attr_reader :widget_types
# Used to add new sections to the help dialog displayed in the
# editor.
#
# @exmaple
#
# config.help_entries.register('pageflow.rainbow.help_entries.colors', priority: 11)
# config.help_entries.register('pageflow.rainbow.help_entries.colors.blue',
# parent: 'pageflow.rainbow.help_entries.colors')
#
# @since 0.7
# @return [HelpEntries]
attr_reader :help_entries
# Paperclip style definitions of thumbnails used by Pageflow.
# @return Hash
attr_accessor :thumbnail_styles
# Names of Paperclip styles that shall be rendered into entry
# specific stylesheets.
# @return Array<Symbol>
attr_accessor :css_rendered_thumbnail_styles
# Either a lambda or an object with a `match?` method, to restrict
# access to the editor routes defined by Pageflow.
#
# This can be used if published entries shall be available under
# different CNAMES but the admin and the editor shall only be
# accessible via one official url.
attr_accessor :editor_routing_constraint
# Either a lambda or an object with a `call` method taking two
# parameters: An `ActiveRecord` scope of {Pageflow::Theming} records
# and an {ActionDispatch::Request} object. Has to return the scope
# in which to find themings.
#
# Defaults to {CnameThemingRequestScope} which finds themings
# based on the request subdomain. Can be used to alter the logic
# of finding a theming whose home_url to redirect to when visiting
# the public root path.
#
# Example:
#
# config.theming_request_scope = lambda do |themings, request|
# themings.where(id: Pageflow::Account.find_by_name!(request.subdomain).default_theming_id)
# end
attr_accessor :theming_request_scope
# Either a lambda or an object with a `call` method taking two
# parameters: An `ActiveRecord` scope of `Pageflow::Entry` records
# and an `ActionDispatch::Request` object. Has to return the scope
# in which to find entries.
#
# Used by all public actions that display entries to restrict the
# available entries by hostname or other request attributes.
#
# Use {#public_entry_url_options} to make sure urls of published
# entries conform twith the restrictions.
#
# Example:
#
# # Only make entries of one account available under <account.name>.example.com
# config.public_entry_request_scope = lambda do |entries, request|
# entries.includes(:account).where(pageflow_accounts: {name: request.subdomain})
# end
attr_accessor :public_entry_request_scope
# Either a lambda or an object with a `call` method taking a
# {Theming} as paramater and returing a hash of options used to
# construct the url of a published entry.
#
# Can be used to change the host of the url under which entries
# are available.
#
# Example:
#
# config.public_entry_url_options = lambda do |theming|
# {host: "#{theming.account.name}.example.com"}
# end
attr_accessor :public_entry_url_options
# Either a lambda or an object with a `call` method taking a
# {Theming} as paramater and returing a hash of options used to
# construct the embed url of a published entry.
attr_accessor :entry_embed_url_options
# Submit video/audio encoding jobs only after the user has
# explicitly confirmed in the editor. Defaults to false.
attr_accessor :confirm_encoding_jobs
# Used by Pageflow extensions to provide new tabs to be displayed
# in the admin.
#
# @example
#
# config.admin_resource_tabs.register(:entry, Admin::CustomTab)
#
# @return [Admin::Tabs]
attr_reader :admin_resource_tabs
# Add custom form fields to admin forms.
#
# @example
#
# config.admin_form_inputs.register(:entry, :custom_field) do
#
# @since 0.9
# @return [Admin::FormInputs]
attr_reader :admin_form_inputs
# Insert additional rows into admin attributes tables.
#
# @example
#
# config.admin_attributes_table_rows.register(:entry, :custom)
# config.admin_attributes_table_rows.register(:entry, :my_attribute, after: :title)
# config.admin_attributes_table_rows.register(:entry, :some_attribute, before: :updated_at)
#
# @example Custom content
#
# config.admin_attributes_table_rows.register(:entry, :custom) do |entry|
# span(entry.custom_attribute)
# end
#
# @since edge
# @return [Admin::AttributesTableRows]
attr_reader :admin_attributes_table_rows
# Array of locales which can be chosen as interface language by a
# user. Defaults to `[:en, :de]`.
# @since 0.7
attr_accessor :available_locales
# Array of locales which can be chosen as interface language for
# an entry. Defaults to the locales supported by the
# `pageflow-public-i18n` gem.
# @since 0.10
attr_accessor :available_public_locales
# How to handle https requests for URLs which will have assets in the page.
# If you wish to serve all assets over http and prevent mixed-content warnings,
# you can force a redirect to http. The inverse is also true: you can force
# a redirect to https for all http requests.
#
# @example
#
# config.public_https_mode = :prevent (default) # => redirects https to http
# config.public_https_mode = :enforce # => redirects http to https
# config.public_https_mode = :ignore # => does nothing
# @since 0.9
attr_accessor :public_https_mode
# Meta tag defaults.
#
# These defaults will be included in the page <head> unless overriden by the Entry.
# If you set these to <tt>nil</tt> or <tt>""</tt> the meta tag won't be included.
# @since 0.10
attr_accessor :default_keywords_meta_tag
attr_accessor :default_author_meta_tag
attr_accessor :default_publisher_meta_tag
# Whether a user can be deleted.
#
# @example
#
# config.authorize_user_deletion =
# lambda do |user_to_delete|
# if user_to_delete.accounts.all? { |account| account.users.size > 1 }
# true
# else
# 'Last user on account. Permission denied'
# end
# end
# @since 0.11
attr_accessor :authorize_user_deletion
# Array of values that the `kind` attribute on text tracks can
# take. Defaults to `[:captions, :subtitles, :descriptions]`.
attr_reader :available_text_track_kinds
# Allow one user to be member of multiple accounts. Defaults to
# true.
# @since 12.1
attr_accessor :allow_multiaccount_users
# Options hash for account admin menu. Options from config precede
# defaults.
# @since 12.1
attr_accessor :account_admin_menu_options
# Sublayer for permissions related config.
# @since 12.1
attr_reader :permissions
# Defines the editor lock polling interval.
# @return [number]
# @since 12.1
attr_accessor :edit_lock_polling_interval
# News collection to add items to. Can be used to integrate
# Pageflow with Krant (see https://github.com/codevise/krant).
# @return [#item]
# @since edge
attr_accessor :news
def initialize
@paperclip_filesystem_default_options = {validate_media_type: false}
@paperclip_s3_default_options = {validate_media_type: false}
@zencoder_options = {}
@mailer_sender = '[email protected]'
@features = Features.new
@hooks = Hooks.new
@quotas = Quotas.new
@themes = Themes.new
@page_types = PageTypes.new
@file_types = FileTypes.new(page_types)
@widget_types = WidgetTypes.new
@help_entries = HelpEntries.new
@thumbnail_styles = {}
@css_rendered_thumbnail_styles = Pageflow::PagesHelper::CSS_RENDERED_THUMBNAIL_STYLES
@theming_request_scope = CnameThemingRequestScope.new
@public_entry_request_scope = lambda { |entries, request| entries }
@public_entry_url_options = Pageflow::ThemingsHelper::DEFAULT_PUBLIC_ENTRY_OPTIONS
@entry_embed_url_options = {protocol: 'https'}
@confirm_encoding_jobs = false
@admin_resource_tabs = Pageflow::Admin::Tabs.new
@admin_form_inputs = Pageflow::Admin::FormInputs.new
@admin_attributes_table_rows = Pageflow::Admin::AttributesTableRows.new
@available_locales = [:en, :de]
@available_public_locales = PublicI18n.available_locales
@public_https_mode = :prevent
@default_keywords_meta_tag = 'pageflow, multimedia, reportage'
@default_author_meta_tag = 'Pageflow'
@default_publisher_meta_tag = 'Pageflow'
@authorize_user_deletion = lambda { |_user| true }
@available_text_track_kinds = [:captions, :subtitles, :descriptions]
@allow_multiaccount_users = true
@account_admin_menu_options = {}
@permissions = Permissions.new
@edit_lock_polling_interval = 15.seconds
end
# Activate a plugin.
#
# @param [Plugin] plugin
# @since 0.7
def plugin(plugin)
plugin.configure(self)
end
# @deprecated Use `config.page_types.register` instead.
def register_page_type(page_type)
ActiveSupport::Deprecation.warn('Pageflow::Configuration#register_page_type is deprecated. Use config.page_types.register instead.', caller)
page_types.register(page_type)
end
def revision_components
page_types.map(&:revision_components).flatten.uniq
end
# @api private
def lint!
@features.lint!
end
# @api private
def theming_url_options(theming)
options = public_entry_url_options
options.respond_to?(:call) ? options.call(theming) : options
end
# @api private
def enable_features(names)
features.enable(names, FeatureLevelConfiguration.new(self))
end
# @api private
def enable_all_features
features.enable_all(FeatureLevelConfiguration.new(self))
end
# Restricts the configuration interface to those parts which can
# be used from inside features.
class FeatureLevelConfiguration < Struct.new(:config)
delegate :page_types, to: :config
delegate :widget_types, to: :config
delegate :help_entries, to: :config
delegate :admin_form_inputs, to: :config
delegate :admin_attributes_table_rows, to: :config
delegate :themes, to: :config
end
end
end
| {
"content_hash": "cefcf8766e49c91bdd9bcd6d1707c6ba",
"timestamp": "",
"source": "github",
"line_count": 399,
"max_line_length": 146,
"avg_line_length": 33.65413533834587,
"alnum_prop": 0.6662198391420912,
"repo_name": "Modularfield/pageflow",
"id": "7e72c22f6e1fcf8e04bafea505de7bbd8eddd66a",
"size": "13428",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/pageflow/configuration.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "292481"
},
{
"name": "HTML",
"bytes": "57410"
},
{
"name": "JavaScript",
"bytes": "1044671"
},
{
"name": "Ruby",
"bytes": "1164557"
},
{
"name": "Shell",
"bytes": "42"
}
],
"symlink_target": ""
} |
require 'spec_helper'
describe SlackRubyBot::Commands do
let! :command do
Class.new(SlackRubyBot::Commands::Base) do
command 'nil_text'
def self.call(_client, data, _match)
send_message cilent, data.channel, nil
end
end
end
def app
SlackRubyBot::App.new
end
let(:client) { app.send(:client) }
it 'ignores nil messages' do
allow(Giphy).to receive(:random)
expect(SlackRubyBot::Commands::Base).to_not receive(:send_message_with_gif)
expect(SlackRubyBot::Commands::Base).to_not receive(:send_gif)
app.send(:message, client, text: nil, channel: 'channel', user: 'user')
end
end
| {
"content_hash": "85f609d2e4e8edd581a001c2112a19e4",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 79,
"avg_line_length": 28,
"alnum_prop": 0.672360248447205,
"repo_name": "maclover7/slack-ruby-bot",
"id": "ec11abd043195d8566c723b2b4a3c8c99a65ef8a",
"size": "644",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "spec/slack-ruby-bot/commands/nil_message_spec.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "24115"
}
],
"symlink_target": ""
} |
class AddCaloriesToBeer < ActiveRecord::Migration
def change
add_column :beers, :calories, :integer
end
end
| {
"content_hash": "db8287a68644812c952bb2f640be1d19",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 49,
"avg_line_length": 23.2,
"alnum_prop": 0.75,
"repo_name": "Linell/BrewData",
"id": "981f41cddfc3b3ac0af53e98dcd3e708111de534",
"size": "116",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "db/migrate/20150305132333_add_calories_to_beer.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "386"
},
{
"name": "Cucumber",
"bytes": "50157"
},
{
"name": "HTML",
"bytes": "8549"
},
{
"name": "Ruby",
"bytes": "69824"
}
],
"symlink_target": ""
} |
import sys, os
# If your extensions are in another directory, add it here. If the directory
# is relative to the documentation root, use os.path.abspath to make it
# absolute, like shown here.
sys.path.insert(0, os.path.abspath('../../lib'))
sys.path.insert(0, os.path.abspath('../../examples'))
sys.path.insert(0, os.path.abspath('.'))
import sqlalchemy
# General configuration
# ---------------------
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
#extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode',
# 'sphinx.ext.doctest', 'builder.builders']
extensions = ['sphinx.ext.autodoc',
'sphinx.ext.doctest', 'builder.builders']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['templates']
# The suffix of source filenames.
source_suffix = '.rst'
template_bridge = "builder.builders.MakoBridge"
# The encoding of source files.
#source_encoding = 'utf-8'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'SQLAlchemy'
copyright = u'2007, 2008, 2009, 2010, the SQLAlchemy authors and contributors'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = sqlalchemy.__version__
# The full version, including alpha/beta/rc tags.
release = sqlalchemy.__version__
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of documents that shouldn't be included in the build.
unused_docs = ['copyright']
# List of directories, relative to source directory, that shouldn't be searched
# for source files.
exclude_trees = ['build']
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# Options for HTML output
# -----------------------
# The style sheet to use for HTML and HTML Help pages. A file of that name
# must exist either in Sphinx' static/ path, or in one of the custom paths
# given in html_static_path.
html_style = 'default.css'
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
html_title = "%s %s Documentation" % (project, release)
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
html_last_updated_fmt = '%m/%d/%Y %H:%M:%S'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
html_use_modindex = False
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, the reST sources are included in the HTML build as _sources/<name>.
#html_copy_source = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = ''
# Output file base name for HTML help builder.
htmlhelp_basename = 'FooBardoc'
#autoclass_content = 'both'
# Options for LaTeX output
# ------------------------
# The paper size ('letter' or 'a4').
#latex_paper_size = 'letter'
# The font size ('10pt', '11pt' or '12pt').
#latex_font_size = '10pt'
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, document class [howto/manual]).
latex_documents = [
('index', 'sqlalchemy_%s.tex' % release.replace('.', '_'), ur'SQLAlchemy Documentation',
ur'Mike Bayer', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# Additional stuff for the LaTeX preamble.
# sets TOC depth to 2.
latex_preamble = '\setcounter{tocdepth}{3}'
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_use_modindex = True
| {
"content_hash": "7d1a60d2e8eda9ee274383f03793242e",
"timestamp": "",
"source": "github",
"line_count": 186,
"max_line_length": 90,
"avg_line_length": 32.446236559139784,
"alnum_prop": 0.7143330571665286,
"repo_name": "simplegeo/sqlalchemy",
"id": "64d5c3ed32b08073476b890c1dfa043caa352c2b",
"size": "6522",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "doc/build/conf.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "30110"
},
{
"name": "JavaScript",
"bytes": "26336"
},
{
"name": "Python",
"bytes": "5012225"
}
],
"symlink_target": ""
} |
package com.esri.samples.statistical_query_group_and_sort;
import javafx.beans.binding.Bindings;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import com.esri.arcgisruntime.data.QueryParameters;
/**
* Convenience bean class for representing OrderBy in a TableView row. The sortOrder property can be bound to a
* ComboBoxTableCell for changing the sortOrder with a ComboBox.
*/
class OrderByField {
private final SimpleStringProperty fieldName;
private final SimpleObjectProperty<QueryParameters.SortOrder> sortOrder;
private final SimpleObjectProperty<QueryParameters.OrderBy> orderBy;
OrderByField(QueryParameters.OrderBy orderBy) {
this.fieldName = new SimpleStringProperty(orderBy.getFieldName());
this.sortOrder = new SimpleObjectProperty<>(orderBy.getSortOrder());
this.orderBy = new SimpleObjectProperty<>();
this.orderBy.bind(Bindings.createObjectBinding(() -> new QueryParameters.OrderBy(this.fieldName.get(), this
.sortOrder.get()), this.fieldName, this.sortOrder));
}
String getFieldName() {
return fieldName.get();
}
SimpleStringProperty fieldNameProperty() {
return fieldName;
}
public void setFieldName(String fieldName) {
this.fieldName.set(fieldName);
}
public QueryParameters.SortOrder getSortOrder() {
return sortOrder.get();
}
SimpleObjectProperty<QueryParameters.SortOrder> sortOrderProperty() {
return sortOrder;
}
public void setSortOrder(QueryParameters.SortOrder sortOrder) {
this.sortOrder.set(sortOrder);
}
QueryParameters.OrderBy getOrderBy() {
return orderBy.get();
}
public SimpleObjectProperty<QueryParameters.OrderBy> orderByProperty() {
return orderBy;
}
public void setOrderBy(QueryParameters.OrderBy orderBy) {
this.orderBy.set(orderBy);
}
}
| {
"content_hash": "0f818516a2a72706963b69296fa71db3",
"timestamp": "",
"source": "github",
"line_count": 62,
"max_line_length": 111,
"avg_line_length": 29.903225806451612,
"alnum_prop": 0.7621359223300971,
"repo_name": "Esri/arcgis-runtime-samples-java",
"id": "5ad83ccb75b50c169ab2714d877c6d534111ade5",
"size": "1854",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "feature_layers/statistical-query-group-and-sort/src/main/java/com/esri/samples/statistical_query_group_and_sort/OrderByField.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "28447"
},
{
"name": "Java",
"bytes": "1787508"
}
],
"symlink_target": ""
} |
<?php
namespace Waldo\OpenIdConnect\ProviderBundle\Tests\Handler;
use Waldo\OpenIdConnect\ProviderBundle\Handler\AuthenticationSuccessHandler;
use Symfony\Component\HttpFoundation\Request;
/**
* AuthenticationSuccessHandlerTest
*
* @author valérian Girard <[email protected]>
*/
class AuthenticationSuccessHandlerTest extends \PHPUnit_Framework_TestCase
{
private $httpUtils;
private $securityContext;
private $token;
public function testHasClientId()
{
$logoutSuccessHandler = $this->getAuthenticationSuccessHandler();
$request = new Request();
$request->query->set('client_id', 'my_client_id');
$this->httpUtils->expects($this->once())
->method("createRedirectResponse")
->with($this->callback(function($o) {
return $o instanceof \Symfony\Component\HttpFoundation\Request &&
$o->attributes->get("clientId") === 'my_client_id';
}), $this->equalTo("oicp_authentication_scope"))
->will($this->returnValue("ok"));
$res = $logoutSuccessHandler->onAuthenticationSuccess($request, $this->token);
$this->assertEquals("ok", $res);
}
public function testHasSession()
{
$logoutSuccessHandler = $this->getAuthenticationSuccessHandler();
$request = new Request();
$session = $this->getMock("Symfony\Component\HttpFoundation\Session\Session");
$session->expects($this->once())
->method("has")
->with($this->equalTo("_security.securitytest.target_path"))
->will($this->returnValue(true));
$session->expects($this->once())
->method("get")
->with($this->equalTo("_security.securitytest.target_path"))
->will($this->returnValue("session_value"));
$request->setSession($session);
$this->token->expects($this->once())
->method("getProviderKey")
->will($this->returnValue("securitytest"));
$this->httpUtils->expects($this->once())
->method("createRedirectResponse")
->with($this->callback(function($o) {
return $o instanceof \Symfony\Component\HttpFoundation\Request;
}), $this->equalTo("session_value"))
->will($this->returnValue("ok"));
$res = $logoutSuccessHandler->onAuthenticationSuccess($request, $this->token);
$this->assertEquals("ok", $res);
}
public function testIsAdmin()
{
$logoutSuccessHandler = $this->getAuthenticationSuccessHandler();
$this->securityContext->expects($this->once())
->method("isGranted")
->with($this->equalTo("ROLE_ADMIN"))
->will($this->returnValue(true));
$request = new Request();
$session = $this->getMock("Symfony\Component\HttpFoundation\Session\Session");
$session->expects($this->once())
->method("has")
->with($this->equalTo("_security.securitytest.target_path"))
->will($this->returnValue(false));
$request->setSession($session);
$this->token->expects($this->once())
->method("getProviderKey")
->will($this->returnValue("securitytest"));
$this->httpUtils->expects($this->once())
->method("createRedirectResponse")
->with($this->callback(function($o) {
return $o instanceof \Symfony\Component\HttpFoundation\Request;
}), $this->equalTo("oicp_admin_index"))
->will($this->returnValue("ok"));
$res = $logoutSuccessHandler->onAuthenticationSuccess($request, $this->token);
$this->assertEquals("ok", $res);
}
public function testIsSimpleUser()
{
$logoutSuccessHandler = $this->getAuthenticationSuccessHandler();
$this->securityContext->expects($this->once())
->method("isGranted")
->with($this->equalTo("ROLE_ADMIN"))
->will($this->returnValue(false));
$request = new Request();
$session = $this->getMock("Symfony\Component\HttpFoundation\Session\Session");
$session->expects($this->once())
->method("has")
->with($this->equalTo("_security.securitytest.target_path"))
->will($this->returnValue(false));
$request->setSession($session);
$this->token->expects($this->once())
->method("getProviderKey")
->will($this->returnValue("securitytest"));
$this->httpUtils->expects($this->once())
->method("createRedirectResponse")
->with($this->callback(function($o) {
return $o instanceof \Symfony\Component\HttpFoundation\Request;
}), $this->equalTo("oicp_account_index"))
->will($this->returnValue("ok"));
$res = $logoutSuccessHandler->onAuthenticationSuccess($request, $this->token);
$this->assertEquals("ok", $res);
}
private function getAuthenticationSuccessHandler()
{
$this->securityContext = $this->getMock("Symfony\Component\Security\Core\SecurityContextInterface");
$this->httpUtils = $this->getMock("Symfony\Component\Security\Http\HttpUtils");
$this->token = $this->getMockBuilder("Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken")
->disableOriginalConstructor()
->getMock();
return new AuthenticationSuccessHandler($this->securityContext, $this->httpUtils);
}
}
| {
"content_hash": "3a81b7dc414d2df85ea8a19cf5a65e32",
"timestamp": "",
"source": "github",
"line_count": 150,
"max_line_length": 122,
"avg_line_length": 38.94,
"alnum_prop": 0.5749015579524054,
"repo_name": "waldo2188/OpenIdConnectProvider",
"id": "94356a16b78e59a6c4c9cbf84352ab2762140b53",
"size": "5842",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Waldo/OpenIdConnect/ProviderBundle/Tests/Handler/AuthenticationSuccessHandlerTest.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "3041"
},
{
"name": "CSS",
"bytes": "3759"
},
{
"name": "JavaScript",
"bytes": "278"
},
{
"name": "Makefile",
"bytes": "1679"
},
{
"name": "PHP",
"bytes": "551859"
}
],
"symlink_target": ""
} |
package com.p4u.android.utils;
/**
* @ClassName: LogUtils
*
* @Description: Log的工具类
*
* @author ShaoZhen
*
* @date 2015-2-25 上午11:10:20
*/
public class LogUtils {
// log开关
public static boolean isDebug = true;
public static void v(String tag, String msg) {
if (isDebug)
android.util.Log.v(tag, msg);
}
public static void v(String tag, String msg, Throwable t) {
if (isDebug)
android.util.Log.v(tag, msg, t);
}
public static void d(String tag, String msg) {
if (isDebug)
android.util.Log.d(tag, msg);
}
public static void d(String tag, String msg, Throwable t) {
if (isDebug)
android.util.Log.d(tag, msg, t);
}
public static void i(String tag, String msg) {
if (isDebug)
android.util.Log.i(tag, msg);
}
public static void i(String tag, String msg, Throwable t) {
if (isDebug)
android.util.Log.i(tag, msg, t);
}
public static void w(String tag, String msg) {
if (isDebug)
android.util.Log.w(tag, msg);
}
public static void w(String tag, String msg, Throwable t) {
if (isDebug)
android.util.Log.w(tag, msg, t);
}
public static void e(String tag, String msg) {
if (isDebug)
android.util.Log.e(tag, msg);
}
public static void e(String tag, String msg, Throwable t) {
if (isDebug)
android.util.Log.e(tag, msg, t);
}
}
| {
"content_hash": "52667cd7a66baccfc02b0b141abd0fdd",
"timestamp": "",
"source": "github",
"line_count": 66,
"max_line_length": 60,
"avg_line_length": 20.045454545454547,
"alnum_prop": 0.6439909297052154,
"repo_name": "ShaoZhen1005/DemoList",
"id": "0a6c559911690dfff861ed20db94e7337c3c84a3",
"size": "1359",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/java/com/p4u/android/utils/LogUtils.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "153918"
}
],
"symlink_target": ""
} |
DRY_RUN=${DRY_RUN:-0}
GPG="gpg --pinentry-mode loopback --no-tty --batch"
YETUS_VERSION=${YETUS_VERSION:-0.11.1}
set -x
function error {
echo "$*"
exit 1
}
function read_config {
local PROMPT="$1"
local DEFAULT="$2"
local REPLY=
read -p "$PROMPT [$DEFAULT]: " REPLY
local RETVAL="${REPLY:-$DEFAULT}"
if [ -z "$RETVAL" ]; then
error "$PROMPT is must be provided."
fi
echo "$RETVAL"
}
function parse_version {
grep -e '<version>.*</version>' | \
head -n 2 | tail -n 1 | cut -d'>' -f2 | cut -d '<' -f1
}
function run_silent {
local BANNER="$1"
local LOG_FILE="$2"
shift 2
echo "========================"
echo "= $BANNER"
echo "Command: $*"
echo "Log file: $LOG_FILE"
"$@" 1>"$LOG_FILE" 2>&1
local EC=$?
if [ $EC != 0 ]; then
echo "Command FAILED. Check full logs for details."
tail "$LOG_FILE"
exit $EC
fi
}
function fcreate_secure {
local FPATH="$1"
rm -f "$FPATH"
touch "$FPATH"
chmod 600 "$FPATH"
}
function check_for_tag {
curl -s --head --fail "$ASF_GITHUB_REPO/releases/tag/$1" > /dev/null
}
# API compare version.
function get_api_diff_version {
local version=$1
local rev=$(echo "$version" | cut -d . -f 3)
local api_diff_tag
if [ $rev != 0 ]; then
local short_version=$(echo "$version" | cut -d . -f 1-2)
api_diff_tag="rel/${short_version}.$((rev - 1))"
else
local major=$(echo "$version" | cut -d . -f 1)
local minor=$(echo "$version" | cut -d . -f 2)
if [ $minor != 0 ]; then
api_diff_tag="rel/${major}.$((minor - 1)).0)"
else
api_diff_tag="rel/$((major - 1)).0.0)"
fi
fi
api_diff_tag=$(read_config "api_diff_tag", "$api_diff_tag")
echo $api_diff_tag
}
# Get all branches that begin with 'branch-', the hbase convention for
# release branches, sort them and then pop off the most recent.
function get_release_info {
export PROJECT=$(read_config "PROJECT" "$PROJECT")
if [[ -z "${ASF_REPO}" ]]; then
ASF_REPO="https://gitbox.apache.org/repos/asf/${PROJECT}.git"
fi
if [[ -z "${ASF_REPO_WEBUI}" ]]; then
ASF_REPO_WEBUI="https://gitbox.apache.org/repos/asf?p=${PROJECT}.git"
fi
if [[ -z "${ASF_GITHUB_REPO}" ]]; then
ASF_GITHUB_REPO="https://github.com/apache/${PROJECT}"
fi
if [ -z "$GIT_BRANCH" ]; then
# If no branch is specified, find out the latest branch from the repo.
GIT_BRANCH=$(git ls-remote --heads "$ASF_REPO" |
grep refs/heads/branch- |
awk '{print $2}' |
sort -r |
head -n 1 |
cut -d/ -f3)
fi
export GIT_BRANCH=$(read_config "GIT_BRANCH" "$GIT_BRANCH")
# Find the current version for the branch.
local VERSION=$(curl -s "$ASF_REPO_WEBUI;a=blob_plain;f=pom.xml;hb=refs/heads/$GIT_BRANCH" |
parse_version)
echo "Current branch VERSION is $VERSION."
NEXT_VERSION="$VERSION"
RELEASE_VERSION=""
SHORT_VERSION=$(echo "$VERSION" | cut -d . -f 1-2)
if [[ ! $VERSION =~ .*-SNAPSHOT ]]; then
RELEASE_VERSION="$VERSION"
else
RELEASE_VERSION="${VERSION/-SNAPSHOT/}"
fi
local REV=$(echo "$VERSION" | cut -d . -f 3)
# Find out what RC is being prepared.
# - If the current version is "x.y.0", then this is RC0 of the "x.y.0" release.
# - If not, need to check whether the previous version has been already released or not.
# - If it has, then we're building RC0 of the current version.
# - If it has not, we're building the next RC of the previous version.
local RC_COUNT
if [ $REV != 0 ]; then
local PREV_REL_REV=$((REV - 1))
PREV_REL_TAG="rel/${SHORT_VERSION}.${PREV_REL_REV}"
if check_for_tag "$PREV_REL_TAG"; then
RC_COUNT=0
REV=$((REV + 1))
NEXT_VERSION="${SHORT_VERSION}.${REV}-SNAPSHOT"
else
RELEASE_VERSION="${SHORT_VERSION}.${PREV_REL_REV}"
RC_COUNT=$(git ls-remote --tags "$ASF_REPO" "${RELEASE_VERSION}RC*" | wc -l)
# This makes a 'number' of it.
RC_COUNT=$((RC_COUNT))
fi
else
REV=$((REV + 1))
NEXT_VERSION="${SHORT_VERSION}.${REV}-SNAPSHOT"
RC_COUNT=0
fi
export RELEASE_VERSION=$(read_config "RELEASE_VERSION" "$RELEASE_VERSION")
export NEXT_VERSION=$(read_config "NEXT_VERSION" "$NEXT_VERSION")
RC_COUNT=$(read_config "RC_COUNT" "$RC_COUNT")
# Check if the RC already exists, and if re-creating the RC, skip tag creation.
RELEASE_TAG="${RELEASE_VERSION}RC${RC_COUNT}"
SKIP_TAG=0
if check_for_tag "$RELEASE_TAG"; then
read -p "$RELEASE_TAG already exists. Continue anyway [y/n]? " ANSWER
if [ "$ANSWER" != "y" ]; then
error "Exiting."
fi
SKIP_TAG=1
fi
export RELEASE_TAG
GIT_REF="$RELEASE_TAG"
if is_dry_run; then
echo "This is a dry run. Please confirm the ref that will be built for testing."
GIT_REF=$(read_config "GIT_REF" "$GIT_REF")
fi
export GIT_REF
export PACKAGE_VERSION="$RELEASE_TAG"
export API_DIFF_TAG=$(get_api_diff_version $RELEASE_VERSION)
# Gather some user information.
export ASF_USERNAME=$(read_config "ASF_USERNAME" "$LOGNAME")
GIT_NAME=$(git config user.name || echo "")
export GIT_NAME=$(read_config "GIT_NAME" "$GIT_NAME")
export GIT_EMAIL="[email protected]"
export GPG_KEY=$(read_config "GPG_KEY" "$GIT_EMAIL")
cat <<EOF
================
Release details:
GIT_BRANCH: $GIT_BRANCH
RELEASE_VERSION: $RELEASE_VERSION
RELEASE_TAG: $RELEASE_TAG
NEXT_VERSION: $NEXT_VERSION
API_DIFF_TAG: $API_DIFF_TAG
ASF_USERNAME: $ASF_USERNAME
GPG_KEY: $GPG_KEY
GIT_NAME: $GIT_NAME
GIT_EMAIL: $GIT_EMAIL
================
EOF
read -p "Is this info correct [y/n]? " ANSWER
if [ "$ANSWER" != "y" ]; then
echo "Exiting."
exit 1
fi
if ! is_dry_run; then
if [ -z "$ASF_PASSWORD" ]; then
stty -echo && printf "ASF_PASSWORD: " && read ASF_PASSWORD && printf '\n' && stty echo
fi
else
ASF_PASSWORD="***INVALID***"
fi
if [ -z "$GPG_PASSPHRASE" ]; then
stty -echo && printf "GPG_PASSPHRASE: " && read GPG_PASSPHRASE && printf '\n' && stty echo
export GPG_TTY=$(tty)
fi
export ASF_PASSWORD
export GPG_PASSPHRASE
}
function is_dry_run {
[[ $DRY_RUN = 1 ]]
}
# Initializes JAVA_VERSION to the version of the JVM in use.
function init_java {
if [ -z "$JAVA_HOME" ]; then
error "JAVA_HOME is not set."
fi
JAVA_VERSION=$("${JAVA_HOME}"/bin/javac -version 2>&1 | cut -d " " -f 2)
echo "java version: $JAVA_VERSION"
export JAVA_VERSION
}
function init_python {
if ! [ -x "$(command -v python2)" ]; then
echo 'Error: python2 needed by yetus. Install or add link? E.g: sudo ln -sf /usr/bin/python2.7 /usr/local/bin/python2' >&2
exit 1
fi
echo "python version: `python2 --version`"
}
# Set MVN
function init_mvn {
if [ -n "$MAVEN_HOME" ]; then
MVN=${MAVEN_HOME}/bin/mvn
elif [ $(type -P mvn) ]; then
MVN=mvn
else
error "MAVEN_HOME is not set nor is mvn on the current path."
fi
echo "mvn version: `$MVN --version`"
# Add timestamped logging.
MVN="${MVN} -B"
export MVN
}
# Writes report into cwd!
function generate_api_report {
local project="$1"
local previous_tag="$2"
local release_tag="$3"
# Generate api report.
${project}/dev-support/checkcompatibility.py --annotation \
org.apache.yetus.audience.InterfaceAudience.Public \
$previous_tag $release_tag
local previous_version=$(echo ${previous_tag} | sed -e 's/rel\///')
cp ${project}/target/compat-check/report.html "./api_compare_${previous_version}_to_${release_tag}.html"
}
# Update the CHANGES.md
# DOES NOT DO COMMITS! Caller should do that.
# yetus requires python2 to be on the path.
function update_releasenotes {
local project="$1"
local release_version="$2"
local yetus="apache-yetus-${YETUS_VERSION}"
wget -qO- "https://www.apache.org/dyn/mirrors/mirrors.cgi?action=download&filename=/yetus/${YETUS_VERSION}/${yetus}-bin.tar.gz" | \
tar xvz -C . || exit
cd ./${yetus} || exit
./bin/releasedocmaker -p HBASE --fileversions -v ${release_version} -l --sortorder=newer --skip-credits
# First clear out the changes written by previous RCs.
pwd
sed -i -e "/^## Release ${release_version}/,/^## Release/ {//!d; /^## Release ${release_version}/d;}" \
${project}/CHANGES.md || true
sed -i -e "/^# HBASE ${release_version} Release Notes/,/^# HBASE/{//!d; /^# HBASE ${release_version} Release Notes/d;}" \
${project}/RELEASENOTES.md || true
# The above generates RELEASENOTES.X.X.X.md and CHANGELOG.X.X.X.md.
# To insert into project CHANGES.me...need to cut the top off the
# CHANGELOG.X.X.X.md file removing license and first line and then
# insert it after the license comment closing where we have a
# DO NOT REMOVE marker text!
sed -i -e '/## Release/,$!d' CHANGELOG.${release_version}.md
sed -i -e "/DO NOT REMOVE/r CHANGELOG.${release_version}.md" ${project}/CHANGES.md
# Similar for RELEASENOTES but slightly different.
sed -i -e '/Release Notes/,$!d' RELEASENOTES.${release_version}.md
sed -i -e "/DO NOT REMOVE/r RELEASENOTES.${release_version}.md" ${project}/RELEASENOTES.md
cd .. || exit
}
# Make src release.
# Takes as arguments first the project name -- e.g. hbase or hbase-operator-tools
# -- and then the version string. Expects to find checkout adjacent to this script
# named for 'project', the first arg passed.
# Expects the following three defines in the environment:
# - GPG needs to be defined, with the path to GPG: defaults 'gpg'.
# - The passphrase in the GPG_PASSPHRASE variable: no default (we don't make .asc file).
# - GIT_REF which is the tag to create the tgz from: defaults to 'master'.
# For example:
# $ GPG_PASSPHRASE="XYZ" GIT_REF="master" make_src_release hbase-operator-tools 1.0.0
make_src_release() {
# Tar up the src and sign and hash it.
project="${1}"
version="${2}"
basename="${project}-${version}"
rm -rf "${basename}-src*"
tgz="${basename}-src.tar.gz"
cd "${project}" || exit
git clean -d -f -x
git archive --format=tar.gz --output="../${tgz}" --prefix="${basename}/" "${GIT_REF:-master}"
cd .. || exit
echo "$GPG_PASSPHRASE" | $GPG --passphrase-fd 0 --armour --output "${tgz}.asc" \
--detach-sig "${tgz}"
echo "$GPG_PASSPHRASE" | $GPG --passphrase-fd 0 --print-md SHA512 "${tgz}" > "${tgz}.sha512"
}
# Make binary release.
# Takes as arguments first the project name -- e.g. hbase or hbase-operator-tools
# -- and then the version string. Expects to find checkout adjacent to this script
# named for 'project', the first arg passed.
# Expects the following three defines in the environment:
# - GPG needs to be defined, with the path to GPG: defaults 'gpg'.
# - The passphrase in the GPG_PASSPHRASE variable: no default (we don't make .asc file).
# - GIT_REF which is the tag to create the tgz from: defaults to 'master'.
# - MVN Default is 'mvn'.
# For example:
# $ GPG_PASSPHRASE="XYZ" GIT_REF="master" make_src_release hbase-operator-tools 1.0.0
make_binary_release() {
project="${1}"
version="${2}"
basename="${project}-${version}"
rm -rf "${basename}-bin*"
cd $project || exit
git clean -d -f -x
# Three invocations of maven. This seems to work. One to
# populate the repo, another to build the site, and then
# a third to assemble the binary artifact. Trying to do
# all in the one invocation fails; a problem in our
# assembly spec to in maven. TODO. Meantime, three invocations.
MAVEN_OPTS="${MAVEN_OPTS}" ${MVN} --settings $tmp_settings clean install -DskipTests \
-Dmaven.repo.local="${tmp_repo}"
MAVEN_OPTS="${MAVEN_OPTS}" ${MVN} --settings $tmp_settings site -DskipTests \
-Dmaven.repo.local="${tmp_repo}"
MAVEN_OPTS="${MAVEN_OPTS}" ${MVN} --settings $tmp_settings install assembly:single -DskipTests \
-Dcheckstyle.skip=true "${PUBLISH_PROFILES}" -Dmaven.repo.local="${tmp_repo}"
# Check there is a bin gz output. The build may not produce one: e.g. hbase-thirdparty.
f_bin_tgz="./${PROJECT}-assembly/target/${basename}*-bin.tar.gz"
if ls ${f_bin_tgz} &>/dev/null; then
cp ${f_bin_tgz} ..
cd .. || exit
for i in "${basename}"*-bin.tar.gz; do
echo "$GPG_PASSPHRASE" | $GPG --passphrase-fd 0 --armour --output "$i.asc" --detach-sig "$i"
echo "$GPG_PASSPHRASE" | $GPG --passphrase-fd 0 --print-md SHA512 "${i}" > "$i.sha512"
done
else
cd .. || exit
echo "No ${f_bin_tgz} product; expected?"
fi
}
| {
"content_hash": "6380209b7fb90e77e667fc912d08cbbb",
"timestamp": "",
"source": "github",
"line_count": 375,
"max_line_length": 133,
"avg_line_length": 32.84,
"alnum_prop": 0.6361347949654892,
"repo_name": "francisliu/hbase",
"id": "471e7b2dfd72bdc94fca34dfda67211747f2e266",
"size": "13120",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "dev-support/create-release/release-util.sh",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "25343"
},
{
"name": "C",
"bytes": "28534"
},
{
"name": "C++",
"bytes": "56085"
},
{
"name": "CMake",
"bytes": "13186"
},
{
"name": "CSS",
"bytes": "37063"
},
{
"name": "Dockerfile",
"bytes": "15673"
},
{
"name": "Groovy",
"bytes": "42572"
},
{
"name": "HTML",
"bytes": "17275"
},
{
"name": "Java",
"bytes": "36671577"
},
{
"name": "JavaScript",
"bytes": "9342"
},
{
"name": "Makefile",
"bytes": "1359"
},
{
"name": "PHP",
"bytes": "8385"
},
{
"name": "Perl",
"bytes": "383739"
},
{
"name": "Python",
"bytes": "127994"
},
{
"name": "Ruby",
"bytes": "696921"
},
{
"name": "Shell",
"bytes": "305875"
},
{
"name": "Thrift",
"bytes": "55223"
},
{
"name": "XSLT",
"bytes": "6764"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="de">
<head>
<!-- Generated by javadoc (version 1.7.0_65) on Sat Jan 10 13:59:26 CET 2015 -->
<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>Uses of Class com.haw.projecthorse.level.Level</title>
<meta name="date" content="2015-01-10">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class com.haw.projecthorse.level.Level";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../com/haw/projecthorse/level/Level.html" title="class in com.haw.projecthorse.level">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?com/haw/projecthorse/level/class-use/Level.html" target="_top">Frames</a></li>
<li><a href="Level.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class com.haw.projecthorse.level.Level" class="title">Uses of Class<br>com.haw.projecthorse.level.Level</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../com/haw/projecthorse/level/Level.html" title="class in com.haw.projecthorse.level">Level</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#com.haw.projecthorse.level.game">com.haw.projecthorse.level.game</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="#com.haw.projecthorse.level.game.applerun">com.haw.projecthorse.level.game.applerun</a></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="#com.haw.projecthorse.level.game.memoryspiel">com.haw.projecthorse.level.game.memoryspiel</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="#com.haw.projecthorse.level.game.parcours">com.haw.projecthorse.level.game.parcours</a></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="#com.haw.projecthorse.level.game.puzzle">com.haw.projecthorse.level.game.puzzle</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="#com.haw.projecthorse.level.game.thimblerig">com.haw.projecthorse.level.game.thimblerig</a></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="#com.haw.projecthorse.level.menu">com.haw.projecthorse.level.menu</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="#com.haw.projecthorse.level.menu.city">com.haw.projecthorse.level.menu.city</a></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="#com.haw.projecthorse.level.menu.credits">com.haw.projecthorse.level.menu.credits</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="#com.haw.projecthorse.level.menu.lootgallery">com.haw.projecthorse.level.menu.lootgallery</a></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="#com.haw.projecthorse.level.menu.mainmenu">com.haw.projecthorse.level.menu.mainmenu</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="#com.haw.projecthorse.level.menu.playermenu">com.haw.projecthorse.level.menu.playermenu</a></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="#com.haw.projecthorse.level.menu.worldmap">com.haw.projecthorse.level.menu.worldmap</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="#com.haw.projecthorse.level.util.overlay">com.haw.projecthorse.level.util.overlay</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="com.haw.projecthorse.level.game">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../com/haw/projecthorse/level/Level.html" title="class in com.haw.projecthorse.level">Level</a> in <a href="../../../../../com/haw/projecthorse/level/game/package-summary.html">com.haw.projecthorse.level.game</a></h3>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing subclasses, and an explanation">
<caption><span>Subclasses of <a href="../../../../../com/haw/projecthorse/level/Level.html" title="class in com.haw.projecthorse.level">Level</a> in <a href="../../../../../com/haw/projecthorse/level/game/package-summary.html">com.haw.projecthorse.level.game</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><strong><a href="../../../../../com/haw/projecthorse/level/game/Game.html" title="class in com.haw.projecthorse.level.game">Game</a></strong></code>
<div class="block">Abstraktion für alle Spiele.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="com.haw.projecthorse.level.game.applerun">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../com/haw/projecthorse/level/Level.html" title="class in com.haw.projecthorse.level">Level</a> in <a href="../../../../../com/haw/projecthorse/level/game/applerun/package-summary.html">com.haw.projecthorse.level.game.applerun</a></h3>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing subclasses, and an explanation">
<caption><span>Subclasses of <a href="../../../../../com/haw/projecthorse/level/Level.html" title="class in com.haw.projecthorse.level">Level</a> in <a href="../../../../../com/haw/projecthorse/level/game/applerun/package-summary.html">com.haw.projecthorse.level.game.applerun</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><strong><a href="../../../../../com/haw/projecthorse/level/game/applerun/AppleRun.html" title="class in com.haw.projecthorse.level.game.applerun">AppleRun</a></strong></code>
<div class="block">AppleRun Game.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="com.haw.projecthorse.level.game.memoryspiel">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../com/haw/projecthorse/level/Level.html" title="class in com.haw.projecthorse.level">Level</a> in <a href="../../../../../com/haw/projecthorse/level/game/memoryspiel/package-summary.html">com.haw.projecthorse.level.game.memoryspiel</a></h3>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing subclasses, and an explanation">
<caption><span>Subclasses of <a href="../../../../../com/haw/projecthorse/level/Level.html" title="class in com.haw.projecthorse.level">Level</a> in <a href="../../../../../com/haw/projecthorse/level/game/memoryspiel/package-summary.html">com.haw.projecthorse.level.game.memoryspiel</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><strong><a href="../../../../../com/haw/projecthorse/level/game/memoryspiel/MemorySpiel.html" title="class in com.haw.projecthorse.level.game.memoryspiel">MemorySpiel</a></strong></code>
<div class="block">identische Paare von Karten finden.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="com.haw.projecthorse.level.game.parcours">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../com/haw/projecthorse/level/Level.html" title="class in com.haw.projecthorse.level">Level</a> in <a href="../../../../../com/haw/projecthorse/level/game/parcours/package-summary.html">com.haw.projecthorse.level.game.parcours</a></h3>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing subclasses, and an explanation">
<caption><span>Subclasses of <a href="../../../../../com/haw/projecthorse/level/Level.html" title="class in com.haw.projecthorse.level">Level</a> in <a href="../../../../../com/haw/projecthorse/level/game/parcours/package-summary.html">com.haw.projecthorse.level.game.parcours</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><strong><a href="../../../../../com/haw/projecthorse/level/game/parcours/Parcours.html" title="class in com.haw.projecthorse.level.game.parcours">Parcours</a></strong></code>
<div class="block">Die Klasse Parcours enthält die Methoden, die das Framework auf der von
Screen ableitenden Klasse aufruft.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="com.haw.projecthorse.level.game.puzzle">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../com/haw/projecthorse/level/Level.html" title="class in com.haw.projecthorse.level">Level</a> in <a href="../../../../../com/haw/projecthorse/level/game/puzzle/package-summary.html">com.haw.projecthorse.level.game.puzzle</a></h3>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing subclasses, and an explanation">
<caption><span>Subclasses of <a href="../../../../../com/haw/projecthorse/level/Level.html" title="class in com.haw.projecthorse.level">Level</a> in <a href="../../../../../com/haw/projecthorse/level/game/puzzle/package-summary.html">com.haw.projecthorse.level.game.puzzle</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><strong><a href="../../../../../com/haw/projecthorse/level/game/puzzle/PuzzleManager.html" title="class in com.haw.projecthorse.level.game.puzzle">PuzzleManager</a></strong></code>
<div class="block">Die Klasse repräsentiert die Bilderauswahl vor dem Spielanfang.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="com.haw.projecthorse.level.game.thimblerig">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../com/haw/projecthorse/level/Level.html" title="class in com.haw.projecthorse.level">Level</a> in <a href="../../../../../com/haw/projecthorse/level/game/thimblerig/package-summary.html">com.haw.projecthorse.level.game.thimblerig</a></h3>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing subclasses, and an explanation">
<caption><span>Subclasses of <a href="../../../../../com/haw/projecthorse/level/Level.html" title="class in com.haw.projecthorse.level">Level</a> in <a href="../../../../../com/haw/projecthorse/level/game/thimblerig/package-summary.html">com.haw.projecthorse.level.game.thimblerig</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><strong><a href="../../../../../com/haw/projecthorse/level/game/thimblerig/Thimblerig.html" title="class in com.haw.projecthorse.level.game.thimblerig">Thimblerig</a></strong></code>
<div class="block">Richtiges Huetchen finden, unter dem das Pferd versteckt ist.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="com.haw.projecthorse.level.menu">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../com/haw/projecthorse/level/Level.html" title="class in com.haw.projecthorse.level">Level</a> in <a href="../../../../../com/haw/projecthorse/level/menu/package-summary.html">com.haw.projecthorse.level.menu</a></h3>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing subclasses, and an explanation">
<caption><span>Subclasses of <a href="../../../../../com/haw/projecthorse/level/Level.html" title="class in com.haw.projecthorse.level">Level</a> in <a href="../../../../../com/haw/projecthorse/level/menu/package-summary.html">com.haw.projecthorse.level.menu</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><strong><a href="../../../../../com/haw/projecthorse/level/menu/Menu.html" title="class in com.haw.projecthorse.level.menu">Menu</a></strong></code>
<div class="block">Abstraktion für alle Menüs.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="com.haw.projecthorse.level.menu.city">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../com/haw/projecthorse/level/Level.html" title="class in com.haw.projecthorse.level">Level</a> in <a href="../../../../../com/haw/projecthorse/level/menu/city/package-summary.html">com.haw.projecthorse.level.menu.city</a></h3>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing subclasses, and an explanation">
<caption><span>Subclasses of <a href="../../../../../com/haw/projecthorse/level/Level.html" title="class in com.haw.projecthorse.level">Level</a> in <a href="../../../../../com/haw/projecthorse/level/menu/city/package-summary.html">com.haw.projecthorse.level.menu.city</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><strong><a href="../../../../../com/haw/projecthorse/level/menu/city/City.html" title="class in com.haw.projecthorse.level.menu.city">City</a></strong></code>
<div class="block">Dies ist ein Generisches City Level.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="com.haw.projecthorse.level.menu.credits">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../com/haw/projecthorse/level/Level.html" title="class in com.haw.projecthorse.level">Level</a> in <a href="../../../../../com/haw/projecthorse/level/menu/credits/package-summary.html">com.haw.projecthorse.level.menu.credits</a></h3>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing subclasses, and an explanation">
<caption><span>Subclasses of <a href="../../../../../com/haw/projecthorse/level/Level.html" title="class in com.haw.projecthorse.level">Level</a> in <a href="../../../../../com/haw/projecthorse/level/menu/credits/package-summary.html">com.haw.projecthorse.level.menu.credits</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><strong><a href="../../../../../com/haw/projecthorse/level/menu/credits/Credits.html" title="class in com.haw.projecthorse.level.menu.credits">Credits</a></strong></code>
<div class="block">Stellt einen einfachen Credit Screen dar, bestehend aus einem automatisch
herabscrollenden Scrolleelement.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="com.haw.projecthorse.level.menu.lootgallery">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../com/haw/projecthorse/level/Level.html" title="class in com.haw.projecthorse.level">Level</a> in <a href="../../../../../com/haw/projecthorse/level/menu/lootgallery/package-summary.html">com.haw.projecthorse.level.menu.lootgallery</a></h3>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing subclasses, and an explanation">
<caption><span>Subclasses of <a href="../../../../../com/haw/projecthorse/level/Level.html" title="class in com.haw.projecthorse.level">Level</a> in <a href="../../../../../com/haw/projecthorse/level/menu/lootgallery/package-summary.html">com.haw.projecthorse.level.menu.lootgallery</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><strong><a href="../../../../../com/haw/projecthorse/level/menu/lootgallery/LootGallery.html" title="class in com.haw.projecthorse.level.menu.lootgallery">LootGallery</a></strong></code>
<div class="block">Die LootGallery in der alle gesammelten Loots betrachtet werden können.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="com.haw.projecthorse.level.menu.mainmenu">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../com/haw/projecthorse/level/Level.html" title="class in com.haw.projecthorse.level">Level</a> in <a href="../../../../../com/haw/projecthorse/level/menu/mainmenu/package-summary.html">com.haw.projecthorse.level.menu.mainmenu</a></h3>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing subclasses, and an explanation">
<caption><span>Subclasses of <a href="../../../../../com/haw/projecthorse/level/Level.html" title="class in com.haw.projecthorse.level">Level</a> in <a href="../../../../../com/haw/projecthorse/level/menu/mainmenu/package-summary.html">com.haw.projecthorse.level.menu.mainmenu</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><strong><a href="../../../../../com/haw/projecthorse/level/menu/mainmenu/MainMenu.html" title="class in com.haw.projecthorse.level.menu.mainmenu">MainMenu</a></strong></code>
<div class="block">Dies ist das MainMenü welches beim Spielstart aufgerufen wird und wo der user
seinen Spielstand auswählen kann.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="com.haw.projecthorse.level.menu.playermenu">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../com/haw/projecthorse/level/Level.html" title="class in com.haw.projecthorse.level">Level</a> in <a href="../../../../../com/haw/projecthorse/level/menu/playermenu/package-summary.html">com.haw.projecthorse.level.menu.playermenu</a></h3>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing subclasses, and an explanation">
<caption><span>Subclasses of <a href="../../../../../com/haw/projecthorse/level/Level.html" title="class in com.haw.projecthorse.level">Level</a> in <a href="../../../../../com/haw/projecthorse/level/menu/playermenu/package-summary.html">com.haw.projecthorse.level.menu.playermenu</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><strong><a href="../../../../../com/haw/projecthorse/level/menu/playermenu/PlayerMenu.html" title="class in com.haw.projecthorse.level.menu.playermenu">PlayerMenu</a></strong></code>
<div class="block">Menü zum Wählen der Pferderasse.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="com.haw.projecthorse.level.menu.worldmap">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../com/haw/projecthorse/level/Level.html" title="class in com.haw.projecthorse.level">Level</a> in <a href="../../../../../com/haw/projecthorse/level/menu/worldmap/package-summary.html">com.haw.projecthorse.level.menu.worldmap</a></h3>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing subclasses, and an explanation">
<caption><span>Subclasses of <a href="../../../../../com/haw/projecthorse/level/Level.html" title="class in com.haw.projecthorse.level">Level</a> in <a href="../../../../../com/haw/projecthorse/level/menu/worldmap/package-summary.html">com.haw.projecthorse.level.menu.worldmap</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><strong><a href="../../../../../com/haw/projecthorse/level/menu/worldmap/WorldMap.html" title="class in com.haw.projecthorse.level.menu.worldmap">WorldMap</a></strong></code>
<div class="block">Diese Klasse erzeugt eine Weltkarte, auf der der Spieler sein Pferd von Stadt
zu Stadt bewgegen und diese dann betreten kann.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="com.haw.projecthorse.level.util.overlay">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../com/haw/projecthorse/level/Level.html" title="class in com.haw.projecthorse.level">Level</a> in <a href="../../../../../com/haw/projecthorse/level/util/overlay/package-summary.html">com.haw.projecthorse.level.util.overlay</a></h3>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../com/haw/projecthorse/level/util/overlay/package-summary.html">com.haw.projecthorse.level.util.overlay</a> that return <a href="../../../../../com/haw/projecthorse/level/Level.html" title="class in com.haw.projecthorse.level">Level</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../com/haw/projecthorse/level/Level.html" title="class in com.haw.projecthorse.level">Level</a></code></td>
<td class="colLast"><span class="strong">Overlay.</span><code><strong><a href="../../../../../com/haw/projecthorse/level/util/overlay/Overlay.html#getLevel()">getLevel</a></strong>()</code>
<div class="block">Liefert die Referenz auf das Level über welchem das Overlay liegt.</div>
</td>
</tr>
</tbody>
</table>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing constructors, and an explanation">
<caption><span>Constructors in <a href="../../../../../com/haw/projecthorse/level/util/overlay/package-summary.html">com.haw.projecthorse.level.util.overlay</a> with parameters of type <a href="../../../../../com/haw/projecthorse/level/Level.html" title="class in com.haw.projecthorse.level">Level</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colLast"><code><strong><a href="../../../../../com/haw/projecthorse/level/util/overlay/Overlay.html#Overlay(com.badlogic.gdx.utils.viewport.Viewport,%20com.badlogic.gdx.graphics.g2d.SpriteBatch,%20com.haw.projecthorse.level.Level)">Overlay</a></strong>(com.badlogic.gdx.utils.viewport.Viewport viewport,
com.badlogic.gdx.graphics.g2d.SpriteBatch spriteBatch,
<a href="../../../../../com/haw/projecthorse/level/Level.html" title="class in com.haw.projecthorse.level">Level</a> levelPara)</code>
<div class="block">Dies ist der Konstruktor für ein neues Overlay.</div>
</td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../com/haw/projecthorse/level/Level.html" title="class in com.haw.projecthorse.level">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?com/haw/projecthorse/level/class-use/Level.html" target="_top">Frames</a></li>
<li><a href="Level.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| {
"content_hash": "34c209aade8af052bf671732c146fbd6",
"timestamp": "",
"source": "github",
"line_count": 489,
"max_line_length": 352,
"avg_line_length": 55.42740286298569,
"alnum_prop": 0.6805268595041323,
"repo_name": "PhilippGrulich/HAW-SE2-projecthorse",
"id": "9d29dcc7cb324ced60b1cac5895cd084b8b655f3",
"size": "27116",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Dokumentation/JavaDoc/com/haw/projecthorse/level/class-use/Level.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "17821"
},
{
"name": "Java",
"bytes": "483769"
},
{
"name": "JavaScript",
"bytes": "48"
}
],
"symlink_target": ""
} |
class EventFlagHistory < ApplicationRecord
include AlertTags
has_paper_trail
belongs_to :event
belongs_to :user
def status=(string)
raise StandardError if (string != 'Active') && (string != 'Closed')
self.is_active = true if string == 'Active'
self.is_active = false if string == 'Closed'
end
end
| {
"content_hash": "46de577e8f6e5084ff8ad4dae6a28ad3",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 71,
"avg_line_length": 21.666666666666668,
"alnum_prop": 0.676923076923077,
"repo_name": "ConOnRails/ConOnRails",
"id": "3cc4a6647a37f15a29079c95df01ed7413c94035",
"size": "2497",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "app/models/event_flag_history.rb",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "64"
},
{
"name": "CoffeeScript",
"bytes": "11372"
},
{
"name": "Dockerfile",
"bytes": "733"
},
{
"name": "HTML",
"bytes": "38898"
},
{
"name": "JavaScript",
"bytes": "5822"
},
{
"name": "Procfile",
"bytes": "40"
},
{
"name": "Ruby",
"bytes": "355380"
},
{
"name": "SCSS",
"bytes": "26641"
},
{
"name": "Shell",
"bytes": "30"
},
{
"name": "Slim",
"bytes": "42387"
}
],
"symlink_target": ""
} |
const int ABOUTDIALOG_COPYRIGHT_YEAR = 2013;
AboutDialog::AboutDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::AboutDialog)
{
ui->setupUi(this);
// Set current copyright year
ui->copyrightLabel->setText(tr("Copyright") + QString(" © 2009-%1 ").arg(COPYRIGHT_YEAR) + tr("The Bitcoin developers") + QString("<br>") + tr("Copyright") + QString(" © ") + tr("2011-%1 The MyBroCoin developers").arg(ABOUTDIALOG_COPYRIGHT_YEAR));
}
void AboutDialog::setModel(ClientModel *model)
{
if(model)
{
ui->versionLabel->setText(model->formatFullVersion());
}
}
AboutDialog::~AboutDialog()
{
delete ui;
}
void AboutDialog::on_buttonBox_accepted()
{
close();
}
| {
"content_hash": "9d083eee8e7d2f7fe97b6442a43bd81e",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 261,
"avg_line_length": 24.551724137931036,
"alnum_prop": 0.6615168539325843,
"repo_name": "mybrocoin/mybrocoin",
"id": "40170e78f124ecf7d76413228a4fa283f55af73e",
"size": "921",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/qt/aboutdialog.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "103297"
},
{
"name": "C++",
"bytes": "11770325"
},
{
"name": "CSS",
"bytes": "1127"
},
{
"name": "IDL",
"bytes": "47697"
},
{
"name": "Objective-C",
"bytes": "5864"
},
{
"name": "Python",
"bytes": "3776"
},
{
"name": "Shell",
"bytes": "1144"
},
{
"name": "TypeScript",
"bytes": "5242609"
}
],
"symlink_target": ""
} |
<?php
namespace Longman\TelegramBot\Commands\AdminCommands;
use Longman\TelegramBot\Request;
use Longman\TelegramBot\Conversation;
use Longman\TelegramBot\Commands\AdminCommand;
use Longman\TelegramBot\Entities\Message;
use Longman\TelegramBot\Entities\ReplyKeyboardHide;
use Longman\TelegramBot\Entities\ReplyKeyboardMarkup;
use Longman\TelegramBot\Exception\TelegramException;
class SendtochannelCommand extends AdminCommand
{
/**#@+
* {@inheritdoc}
*/
protected $name = 'sendtochannel';
protected $description = 'Send message to a channel';
protected $usage = '/sendtochannel <message to send>';
protected $version = '0.1.4';
protected $need_mysql = true;
/**#@-*/
/**
* Conversation Object
*
* @var Longman\TelegramBot\Conversation
*/
protected $conversation;
/**
* {@inheritdoc}
*/
public function execute()
{
$message = $this->getMessage();
$chat_id = $message->getChat()->getId();
$user_id = $message->getFrom()->getId();
$type = $message->getType();
// 'Cast' the command type into message this protect the machine state
// if the commmad is recolled when the conversation is already started
$type = ($type == 'command') ? 'Message' : $type;
$text = trim($message->getText(true));
$data = [];
$data['chat_id'] = $chat_id;
// Conversation
$this->conversation = new Conversation($user_id, $chat_id, $this->getName());
$channels = (array) $this->getConfig('your_channel');
if (!isset($this->conversation->notes['state'])) {
$state = (count($channels) == 0) ? -1 : 0;
$this->conversation->notes['last_message_id'] = $message->getMessageId();
} else {
$state = $this->conversation->notes['state'];
}
switch ($state) {
case -1:
// getConfig has not been configured asking for channel to administer
if ($type != 'Message' || empty($text)) {
$this->conversation->notes['state'] = -1;
$this->conversation->update();
$data['text'] = 'Insert the channel name: (@yourchannel)';
$data['reply_markup'] = new ReplyKeyBoardHide(['selective' => true]);
$result = Request::sendMessage($data);
break;
}
$this->conversation->notes['channel'] = $text;
$this->conversation->notes['last_message_id'] = $message->getMessageId();
// Jump to state 1
goto insert;
// no break
default:
case 0:
// getConfig has been configured choose channel
if ($type != 'Message' || !in_array($text, $channels)) {
$this->conversation->notes['state'] = 0;
$this->conversation->update();
$keyboard = [];
foreach ($channels as $channel) {
$keyboard[] = [$channel];
}
$reply_keyboard_markup = new ReplyKeyboardMarkup(
[
'keyboard' => $keyboard ,
'resize_keyboard' => true,
'one_time_keyboard' => true,
'selective' => true
]
);
$data['reply_markup'] = $reply_keyboard_markup;
$data['text'] = 'Select a channel';
if ($type != 'Message' || !in_array($text, $channels)) {
$data['text'] = 'Select a channel from the keyboard:';
}
$result = Request::sendMessage($data);
break;
}
$this->conversation->notes['channel'] = $text;
$this->conversation->notes['last_message_id'] = $message->getMessageId();
// no break
case 1:
insert:
if ($this->conversation->notes['last_message_id'] == $message->getMessageId() || ($type == 'Message' && empty($text))) {
$this->conversation->notes['state'] = 1;
$this->conversation->update();
$data['reply_markup'] = new ReplyKeyBoardHide(['selective' => true]);
$data['text'] = 'Insert the content you want to share: text, photo, audio...';
$result = Request::sendMessage($data);
break;
}
$this->conversation->notes['last_message_id'] = $message->getMessageId();
$this->conversation->notes['message'] = $message->reflect();
$this->conversation->notes['message_type'] = $type;
// no break
case 2:
if ($this->conversation->notes['last_message_id'] == $message->getMessageId() || !($text == 'Yes' || $text == 'No')) {
$this->conversation->notes['state'] = 2;
$this->conversation->update();
// Execute this just with object that allow caption
if ($this->conversation->notes['message_type'] == 'Video' || $this->conversation->notes['message_type'] == 'Photo') {
$keyboard = [['Yes', 'No']];
$reply_keyboard_markup = new ReplyKeyboardMarkup(
[
'keyboard' => $keyboard ,
'resize_keyboard' => true,
'one_time_keyboard' => true,
'selective' => true
]
);
$data['reply_markup'] = $reply_keyboard_markup;
$data['text'] = 'Would you insert caption?';
if ($this->conversation->notes['last_message_id'] != $message->getMessageId() && !($text == 'Yes' || $text == 'No')) {
$data['text'] = 'Would you insert a caption?' . "\n" . 'Type Yes or No';
}
$result = Request::sendMessage($data);
break;
}
}
$this->conversation->notes['set_caption'] = false;
if ($text == 'Yes') {
$this->conversation->notes['set_caption'] = true;
}
$this->conversation->notes['last_message_id'] = $message->getMessageId();
// no break
case 3:
if (($this->conversation->notes['last_message_id'] == $message->getMessageId() || $type != 'Message' ) && $this->conversation->notes['set_caption']) {
$this->conversation->notes['state'] = 3;
$this->conversation->update();
$data['text'] = 'Insert caption:';
$data['reply_markup'] = new ReplyKeyBoardHide(['selective' => true]);
$result = Request::sendMessage($data);
break;
}
$this->conversation->notes['last_message_id'] = $message->getMessageId();
$this->conversation->notes['caption'] = $text;
// no break
case 4:
if ($this->conversation->notes['last_message_id'] == $message->getMessageId() || !($text == 'Yes' || $text == 'No')) {
$this->conversation->notes['state'] = 4;
$this->conversation->update();
$data['text'] = 'Message will look like this:';
$result = Request::sendMessage($data);
if ($this->conversation->notes['message_type'] != 'command') {
if ($this->conversation->notes['set_caption']) {
$data['caption'] = $this->conversation->notes['caption'];
}
$result = $this->sendBack(new Message($this->conversation->notes['message'], 'thisbot'), $data);
$data['text'] = 'Would you post it?';
if ($this->conversation->notes['last_message_id'] != $message->getMessageId() && !($text == 'Yes' || $text == 'No')) {
$data['text'] = 'Would you post it?' . "\n" . 'Press Yes or No';
}
$keyboard = [['Yes', 'No']];
$reply_keyboard_markup = new ReplyKeyboardMarkup(
[
'keyboard' => $keyboard ,
'resize_keyboard' => true,
'one_time_keyboard' => true,
'selective' => true
]
);
$data['reply_markup'] = $reply_keyboard_markup;
$result = Request::sendMessage($data);
}
break;
}
$this->conversation->notes['post_message'] = false;
if ($text == 'Yes') {
$this->conversation->notes['post_message'] = true;
}
$this->conversation->notes['last_message_id'] = $message->getMessageId();
// no break
case 5:
$data['reply_markup'] = new ReplyKeyBoardHide(['selective' => true]);
if ($this->conversation->notes['post_message']) {
$data['text'] = $this->publish(
new Message($this->conversation->notes['message'], 'anystring'),
$this->conversation->notes['channel'],
$this->conversation->notes['caption']
);
} else {
$data['text'] = 'Abort by user, message not sent..';
}
$this->conversation->stop();
$result = Request::sendMessage($data);
}
return $result;
}
/**
* {@inheritdoc}
*/
public function executeNoDb()
{
$message = $this->getMessage();
$text = trim($message->getText(true));
$chat_id = $message->getChat()->getId();
$data = [];
$data['chat_id'] = $chat_id;
if (empty($text)) {
$data['text'] = 'Usage: /sendtochannel <text>';
} else {
$channels = (array) $this->getConfig('your_channel');
$first_channel = $channels[0];
$data['text'] = $this->publish(new Message($message->reflect(), 'anystring'), $first_channel);
}
return Request::sendMessage($data);
}
/**
* Publish a message to a channel and return success or failure message
*
* @param Entities\Message $message
* @param int $channel
* @param string|null $caption
*
* @return string
*/
protected function publish(Message $message, $channel, $caption = null)
{
$data = [
'chat_id' => $channel,
'caption' => $caption,
];
if ($this->sendBack($message, $data)->isOk()) {
$response = 'Message sent successfully to: ' . $channel;
} else {
$response = 'Message not sent to: ' . $channel . "\n" .
'- Does the channel exist?' . "\n" .
'- Is the bot an admin of the channel?';
}
return $response;
}
/**
* SendBack
*
* Received a message, the bot can send a copy of it to another chat/channel.
* You don't have to care about the type of the message, the function detect it and use the proper
* REQUEST:: function to send it.
* $data include all the var that you need to send the message to the proper chat
*
* @todo This method will be moved at an higher level maybe in AdminCommand or Command
* @todo Looking for a more significative name
*
* @param Entities\Message $message
* @param array $data
*
* @return Entities\ServerResponse
*/
protected function sendBack(Message $message, array $data)
{
$type = $message->getType();
$type = ($type == 'command') ? 'Message' : $type;
if ($type == 'Message') {
$data['text'] = $message->getText(true);
} elseif ($type == 'Audio') {
$data['audio'] = $message->getAudio()->getFileId();
$data['duration'] = $message->getAudio()->getDuration();
$data['performer'] = $message->getAudio()->getPerformer();
$data['title'] = $message->getAudio()->getTitle();
} elseif ($type == 'Document') {
$data['document'] = $message->getDocument()->getFileId();
} elseif ($type == 'Photo') {
$data['photo'] = $message->getPhoto()[0]->getFileId();
} elseif ($type == 'Sticker') {
$data['sticker'] = $message->getSticker()->getFileId();
} elseif ($type == 'Video') {
$data['video'] = $message->getVideo()->getFileId();
} elseif ($type == 'Voice') {
$data['voice'] = $message->getVoice()->getFileId();
} elseif ($type == 'Location') {
$data['latitude'] = $message->getLocation()->getLatitude();
$data['longitude'] = $message->getLocation()->getLongitude();
}
$callback_path = 'Longman\TelegramBot\Request';
$callback_function = 'send' . $type;
if (! method_exists($callback_path, $callback_function)) {
throw new TelegramException('Methods: ' . $callback_function . ' not found in class Request.');
}
return call_user_func_array($callback_path . '::' . $callback_function, [$data]);
}
}
| {
"content_hash": "f52b32aa96850545730cff0fd68a0d04",
"timestamp": "",
"source": "github",
"line_count": 326,
"max_line_length": 166,
"avg_line_length": 42.9079754601227,
"alnum_prop": 0.47369173577352014,
"repo_name": "mrXCray/XCrataPult.php",
"id": "0b4164becb86c98b8191356a5f6d9ff7a8ddd1f3",
"size": "14238",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "3rdparty/telegram-bot/Commands/AdminCommands/SendtochannelCommand.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "423973"
}
],
"symlink_target": ""
} |
import sys
import os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.append(os.path.abspath('..'))
os.environ['DJANGO_SETTINGS_MODULE'] = 'example.settings'
import categories # noqa
# -- General configuration -----------------------------------------------------
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = []
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
# ource_encoding = 'utf-8'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = 'Django Categories'
copyright = '2010-2012, Corey Oordt'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = categories.get_version(short=True)
# The full version, including alpha/beta/rc tags.
release = categories.get_version()
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
# anguage = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
# oday = ''
# Else, today_fmt is used as the format for a strftime call.
# oday_fmt = '%B %d, %Y'
# List of documents that shouldn't be included in the build.
# nused_docs = []
# List of directories, relative to source directory, that shouldn't be searched
# for source files.
exclude_trees = ['_build']
# The reST default role (used for this markup: `text`) to use for all documents.
# efault_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
# dd_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
# dd_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
# how_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
# odindex_common_prefix = []
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. Major themes that come with
# Sphinx are currently 'default' and 'sphinxdoc'.
html_theme = 'default'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
# tml_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
# tml_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
# tml_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
# tml_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
# tml_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
# tml_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
# tml_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
# tml_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
# tml_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
# tml_additional_pages = {}
# If false, no module index is generated.
# tml_use_modindex = True
# If false, no index is generated.
# tml_use_index = True
# If true, the index is split into individual pages for each letter.
# tml_split_index = False
# If true, links to the reST sources are added to the pages.
# tml_show_sourcelink = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
# tml_use_opensearch = ''
# If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml").
# tml_file_suffix = ''
# Output file base name for HTML help builder.
htmlhelp_basename = 'DjangoCategoriesdoc'
# -- Options for LaTeX output --------------------------------------------------
# The paper size ('letter' or 'a4').
# atex_paper_size = 'letter'
# The font size ('10pt', '11pt' or '12pt').
# atex_font_size = '10pt'
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'DjangoCategories.tex', 'Django Categories Documentation', 'CoreyOordt', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
# atex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
# atex_use_parts = False
# Additional stuff for the LaTeX preamble.
# atex_preamble = ''
# Documents to append as an appendix to all manuals.
# atex_appendices = []
# If false, no module index is generated.
# atex_use_modindex = True
| {
"content_hash": "d0b43185dd16486700776f9a649c959c",
"timestamp": "",
"source": "github",
"line_count": 184,
"max_line_length": 97,
"avg_line_length": 32.86413043478261,
"alnum_prop": 0.7082851000496114,
"repo_name": "epicserve/django-categories",
"id": "0ffb72f78f23bd63818432b7e20f55826a3db3fc",
"size": "6475",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "doc_src/conf.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "3091"
},
{
"name": "CSS",
"bytes": "17443"
},
{
"name": "HTML",
"bytes": "18445"
},
{
"name": "JavaScript",
"bytes": "28087"
},
{
"name": "Makefile",
"bytes": "3637"
},
{
"name": "Python",
"bytes": "162081"
}
],
"symlink_target": ""
} |
<!-- Services Section -->
<section id="services">
<div class="container">
<div class="row">
<div class="col-lg-12 text-center">
<h2 class="section-heading">Waarom kijkdoos?</h2>
<h3 class="section-subheading text-muted"></h3>
</div>
</div>
<div class="row text-center">
<div class="col-md-4">
<span class="fa-stack fa-4x">
<i class="fa fa-circle fa-stack-2x text-primary"></i>
<i class="fa fa-money fa-stack-1x fa-inverse"></i>
</span>
<h4 class="service-heading">We zijn goedkoop</h4>
<p class="text-muted">Wij kosten niet zo veel en we leveren echt topwerk. </p>
</div>
<div class="col-md-4">
<span class="fa-stack fa-4x">
<i class="fa fa-circle fa-stack-2x text-primary"></i>
<i class="fa fa-camera fa-stack-1x fa-inverse"></i>
</span>
<h4 class="service-heading">Fucking goed</h4>
<p class="text-muted">Wij zijn een redelijke big deal in de filmwereld. Zoek op wikipedia over filmproductie en dan kom je bij 'kijkdoos'. </p>
</div>
<div class="col-md-4">
<span class="fa-stack fa-4x">
<i class="fa fa-circle fa-stack-2x text-primary"></i>
<i class="fa fa-beer fa-stack-1x fa-inverse"></i>
</span>
<h4 class="service-heading">fijne gasten</h4>
<p class="text-muted">Met ons kun je gewoon een biertje doen als de opdracht af is.</p>
</div>
</div>
</div>
</section> | {
"content_hash": "3d39d90f61228cbbfb1468b4d3586baf",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 163,
"avg_line_length": 51.108108108108105,
"alnum_prop": 0.45901639344262296,
"repo_name": "antoinekooren/antoinekooren.github.io",
"id": "21191605974b2c4668597ad33c6598a471891ce8",
"size": "1891",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "_includes/services.html",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "17598"
},
{
"name": "HTML",
"bytes": "21281"
},
{
"name": "JavaScript",
"bytes": "42756"
},
{
"name": "PHP",
"bytes": "1092"
},
{
"name": "Ruby",
"bytes": "715"
}
],
"symlink_target": ""
} |
@implementation NSString (Fish)
+ (NSString *)generateRandomFishWithLength:(NSUInteger)length {
NSString *dictString = @"Уравнение времени мгновенно Часовой угол а там действительно могли быть видны звезды о чем свидетельствует Фукидид жизненно меняет экваториальный перигелий Движение несмотря на внешние воздействия пространственно ищет случайный космический мусор Зенит однородно меняет далекий параметр Весеннее равноденствие ищет непреложный Тукан У планет-гигантов нет твёрдой поверхности таким образом Юпитер жизненно представляет собой болид и в этом вопросе достигнута такая точность расчетов что начиная с того дня как мы видим указанного Эннием и записанного в было вычислено время предшествовавших затмений солнца начиная с того которое в квинктильские ноны произошло в царствование Ромула";
NSArray *rawWords = [dictString componentsSeparatedByString:@" "];
NSMutableArray *words = [NSMutableArray arrayWithCapacity:[rawWords count]];
for (NSString *candidate in rawWords) {
if (candidate.length > 3) {
[words addObject:candidate];
}
}
NSInteger newLength = 0;
NSUInteger dictCount = [words count];
NSString *newFrase = @"";
while (newLength < length) {
NSUInteger index = arc4random_uniform((uint32_t) dictCount);
NSString *w = [words objectAtIndex:index];
newLength += w.length + 1;
if (newLength > length) break;
newFrase = [[newFrase stringByAppendingString:w] stringByAppendingString:@" "];
}
return newFrase;
}
@end
| {
"content_hash": "9e7fe6e89a04807583d7abd032588139",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 712,
"avg_line_length": 54.41379310344828,
"alnum_prop": 0.7319391634980988,
"repo_name": "DimaAvvakumov/DMTableTools",
"id": "9042ef247620b5512287c58095e1103e7ae8eee5",
"size": "2348",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "classes/categories/Fish/NSString+Fish.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "41458"
},
{
"name": "Ruby",
"bytes": "769"
}
],
"symlink_target": ""
} |
<?php
namespace Jy_Test\Controller;
use Think\Controller;
use Think\Model;
class ChannelDataController extends Controller {
public function index(){
//统计时间
$time = strtotime('2017-12-18',time());
$day = 24*60*60;
$model = new Model();
//渠道列表
$ChannelInfo = D('Jy_script/ChannelInfo');
$ChannelList = $ChannelInfo->ChannelList();
if(!$ChannelList){
die('不存在渠道');
}
while (true){
$EndTime = date('Y-m-d H:i:s',$time+$day);
$StartTime = date('Y-m-d H:i:s',$time);
$DateTime = date('Y-m-d',$time);
if($DateTime == '2017-10-01'){
break;
}
$ChannelIn = $ChannelList['ChannelIn'] ;
$ChannelData = D('Jy_script/ChannelData');
$gameLoginActionSort = $ChannelData->gameLoginAction($ChannelIn,$StartTime,$EndTime);
$UsersOrderSort = $ChannelData->UsersOrder($ChannelIn,$StartTime,$EndTime);
$GameAccountOldSort = $ChannelData->GameAccountOld($ChannelIn,$StartTime,$EndTime);
$EquipmentAndroidSort = $ChannelData->EquipmentAndroid($ChannelIn,$StartTime,$EndTime);
$EquipmentIosSort = $ChannelData->EquipmentIos($ChannelIn,$StartTime,$EndTime);
$info = array();
foreach ($ChannelList['ChannelList'] as $k=>$v){
$info[$k]['Channel'] = $v['GroupChannel'];
//活跃 ios
if($gameLoginActionSort[$v['GroupChannel']]){
$info[$k]['ActiveNum'] = $gameLoginActionSort[$v['GroupChannel']]['ActiveNum'] ;
}else{
$info[$k]['ActiveNum'] = 0;
}
//注册 ios
$EquipmentRegNum = 0;
$RegNum = 0;
if($EquipmentIosSort[$v['GroupChannel']]){
$EquipmentRegNum = $EquipmentIosSort[$v['GroupChannel']]['ios']+$EquipmentRegNum;
$RegNum = $EquipmentIosSort[$v['GroupChannel']]['RegNum']+$RegNum;
}
//注册 android
if($EquipmentAndroidSort[$v['GroupChannel']]){
$EquipmentRegNum = $EquipmentAndroidSort[$v['GroupChannel']]['android']+$EquipmentRegNum;
$RegNum = $EquipmentAndroidSort[$v['GroupChannel']]['RegNum']+$RegNum;
}
$info[$k]['RegNum'] = $RegNum;
$info[$k]['EquipmentRegNum'] = $EquipmentRegNum;
//支付
if($UsersOrderSort[$v['GroupChannel']]){
$info[$k]['Success'] = $UsersOrderSort[$v['GroupChannel']]['Success'] ;
$info[$k]['OrderTotal'] = $UsersOrderSort[$v['GroupChannel']]['OrderTotal'] ;
$info[$k]['TotalMoney'] = $UsersOrderSort[$v['GroupChannel']]['TotalMoney'] ;
$info[$k]['PayNum'] = $UsersOrderSort[$v['GroupChannel']]['PayNum'] ;
$info[$k]['UserPayNum'] = $UsersOrderSort[$v['GroupChannel']]['UserPayNum'] ;
$info[$k]['alipay'] = $UsersOrderSort[$v['GroupChannel']]['alipay'] ;
$info[$k]['weixin'] = $UsersOrderSort[$v['GroupChannel']]['weixin'] ;
$info[$k]['iappay'] = $UsersOrderSort[$v['GroupChannel']]['iappay'] ;
$info[$k]['JinPay'] = $UsersOrderSort[$v['GroupChannel']]['JinPay'] ;
$info[$k]['First'] = $UsersOrderSort[$v['GroupChannel']]['First'] ;
$info[$k]['FirstMoney'] = $UsersOrderSort[$v['GroupChannel']]['FirstMoney'] ;
}else{
$info[$k]['Success'] = 0 ;
$info[$k]['OrderTotal'] = 0 ;
$info[$k]['TotalMoney'] = 0 ;
$info[$k]['PayNum'] = 0 ;
$info[$k]['UserPayNum'] = 0 ;
$info[$k]['alipay'] = 0 ;
$info[$k]['weixin'] = 0 ;
$info[$k]['iappay'] = 0 ;
$info[$k]['JinPay'] = 0 ;
$info[$k]['First'] = 0 ;
$info[$k]['FirstMoney'] = 0 ;
}
if($GameAccountOldSort[$v['GroupChannel']]){
$info[$k]['UserPayNumOld'] = $GameAccountOldSort[$v['GroupChannel']]['UserPayNumOld'] ;
$info[$k]['OrderTotalOld'] = $GameAccountOldSort[$v['GroupChannel']]['OrderTotalOld'] ;
}else{
$info[$k]['UserPayNumOld'] = 0;
$info[$k]['OrderTotalOld'] = 0;
}
$info[$k]['UsersOneNum'] = 0.00;
$info[$k]['UsersTowNum'] = 0.00;
$info[$k]['UsersThreeNum'] = 0.00;
$info[$k]['UsersSevenNum'] = 0.00;
$info[$k]['UsersFifteenNum'] = 0.00;
$info[$k]['UsersThirtyNum'] = 0.00;
$info[$k]['DateTime'] = $StartTime;
}
print_r($info);die;
//添加数据
$addStatisticsUsersPay = $model
->table('jy_statistics_users_pay')
->addAll($info);
$time = $time-$day;
}
exit();
}
//
} | {
"content_hash": "cb7c93c06ad169632a437c348bc71a4e",
"timestamp": "",
"source": "github",
"line_count": 108,
"max_line_length": 110,
"avg_line_length": 49.601851851851855,
"alnum_prop": 0.4584655590815755,
"repo_name": "YeGithubAdmin/JYHD",
"id": "de26776fae9afe7573a951e014899dcade0fe07e",
"size": "5407",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Application/Jy_Test/Controller/ChannelDataController.class.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "31784"
},
{
"name": "C#",
"bytes": "16030"
},
{
"name": "CSS",
"bytes": "466387"
},
{
"name": "HTML",
"bytes": "2846807"
},
{
"name": "Java",
"bytes": "137421"
},
{
"name": "JavaScript",
"bytes": "6094306"
},
{
"name": "PHP",
"bytes": "7185371"
},
{
"name": "Smarty",
"bytes": "8297"
}
],
"symlink_target": ""
} |
//
// KCSCachedStore.h
// KinveyKit
//
// Copyright (c) 2012-2013 Kinvey, Inc. All rights reserved.
//
// This software is licensed to you under the Kinvey terms of service located at
// http://www.kinvey.com/terms-of-use. By downloading, accessing and/or using this
// software, you hereby accept such terms of service (and any agreement referenced
// therein) and agree that you have read, understand and agree to be bound by such
// terms of service and are of legal age to agree to such terms with Kinvey.
//
// This software contains valuable confidential and proprietary information of
// KINVEY, INC and is subject to applicable licensing agreements.
// Unauthorized reproduction, transmission or distribution of this file and its
// contents is a violation of applicable laws.
//
#import <Foundation/Foundation.h>
#import "KCSStore.h"
#import "KCSAppdataStore.h"
#import "KCSOfflineSaveStore.h"
/** Cache Policies. These constants determine the caching behavior when used with KCSChacedStore query. */
typedef enum KCSCachePolicy {
/** No Caching - all queries are sent to the server */
KCSCachePolicyNone,
KCSCachePolicyLocalOnly,
KCSCachePolicyLocalFirst,
KCSCachePolicyNetworkFirst,
KCSCachePolicyBoth,
KCSCachePolicyReadOnceAndSaveLocal_Xperimental //for caching assests that change infrequently (e.g. ui assets, names of presidents, etc)
} KCSCachePolicy;
#define KCSStoreKeyCachePolicy @"cachePolicy"
//internal use
#define KCSStoreKeyLocalCacheTimeout @"localcache.timeout"
#define KCSStoreKeyLocalCachePersistanceKey_Xperimental @"localcache.persistenceid"
/**
This application data store caches queries, depending on the policy.
Available caching policies:
- `KCSCachePolicyNone` - No caching, all queries are sent to the server.
- `KCSCachePolicyLocalOnly` - Only the cache is queried, the server is never called. If a result is not in the cache, an error is returned.
- `KCSCachePolicyLocalFirst` - The cache is queried and if the result is stored, the `completionBlock` is called with that value. The cache is then updated in the background. If the cache does not contain a result for the query, then the server is queried first.
- `KCSCachePolicyNetworkFirst` - The network is queried and the cache is updated with each result. The cached value is only returned when the network is unavailable.
- `KCSCachePolicyBoth` - If available, the cached value is returned to `completionBlock`. The network is then queried and cache updated, afterwards. The `completionBlock` will be called again with the updated result from the server.
For an individual store, the cache policy can inherit from the defaultCachePolicy, be set using storeWithOptions: factory constructor, supplying the enum for the key `KCSStoreKeyCahcePolicy`.
This store also provides offline save semantics. To enable offline save, supply a unique string for this store for the `KCSStoreKeyUniqueOfflineSaveIdentifier` key in the options dictionary passed in class factory method ([KCSAppdataStore storeWithCollection:options:]. You can also supply an optional `KCSStoreKeyOfflineSaveDelegate` to intercept or be notified when those saves happen when the application becomes online.
If offline save is enabled, and the application is offline when the `saveObject:withCompletionBlock:withProgressBlock` method processes the saves, the completionBlock will be called with a networking error, but the saves will be queued to be saved when the application becomes online. This completion block will _not_ be called when those queued saves are processed. Instead, the the offline save delegate will be called. The completion block `errorOrNil` object will have in addition to the error information, an array in its `userInfo` for the `KCS_ERROR_UNSAVED_OBJECT_IDS_KEY` containing the `_id`s of the unsaved objects. If the objects haven't been assigned an `_id` yet, the value will be a `NSNull`, in order to keep the array count reliable.
For more information about offline saving, see KCSOfflineSaveStore and our iOS developer's user guide at docs.kinvey.com.
*/
@interface KCSCachedStore : KCSAppdataStore <KCSOfflineSaveStore>
/** @name Cache Policy */
/** The cache policy used, by default, for this store */
@property (nonatomic, readwrite) KCSCachePolicy cachePolicy;
#pragma mark - Default Cache Policy
/** gets the default cache policy for all new KCSCachedStore's */
+ (KCSCachePolicy) defaultCachePolicy;
/** Sets the default cache policy for all new KCSCachedStore's.
@param cachePolicy the default `KCSCachePolicy` for all new stores.
*/
+ (void) setDefaultCachePolicy:(KCSCachePolicy)cachePolicy;
/** @name Querying/Fetching */
/** Load objects from the store with the given IDs (optional cache policy).
@param objectID this is an individual ID or an array of IDs to load
@param completionBlock A block that gets invoked when all objects are loaded
@param progressBlock A block that is invoked whenever the store can offer an update on the progress of the operation.
@param cachePolicy override the object's cachePolicy for this load only.
@see [KCSAppdataStore loadObjectWithID:withCompletionBlock:withProgressBlock:]
*/
- (void)loadObjectWithID:(id)objectID
withCompletionBlock:(KCSCompletionBlock)completionBlock
withProgressBlock:(KCSProgressBlock)progressBlock
cachePolicy:(KCSCachePolicy)cachePolicy;
/** Query or fetch an object (or objects) in the store (optional cache policy).
This method takes a query object and returns the value from the server or cache, depending on the supplied `cachePolicy`.
This method might be used when you know the network is unavailable and you want to use `KCSCachePolicyLocalOnly` until the network connection is reestablished, and then go back to using the store's normal policy.
@param query A query to act on a store. The store defines the type of queries it accepts, an object of type "KCSAllObjects" causes all objects to be returned.
@param completionBlock A block that gets invoked when the query/fetch is "complete" (as defined by the store)
@param progressBlock A block that is invoked whenever the store can offer an update on the progress of the operation.
@param cachePolicy the policy for to use for this query only.
*/
- (void)queryWithQuery:(id)query withCompletionBlock:(KCSCompletionBlock)completionBlock withProgressBlock:(KCSProgressBlock)progressBlock cachePolicy:(KCSCachePolicy)cachePolicy;
/*! Aggregate objects in the store and apply a function to all members in that group (optional cache policy).
This method will find the objects in the store, collect them with other other objects that have the same value for the specified fields, and then apply the supplied function on those objects. Right now the types of functions that can be applied are simple mathematical operations. See KCSReduceFunction for more information on the types of functions available.
@param fieldOrFields The array of fields to group by (or a single `NSString` field name). If multiple field names are supplied the groups will be made from objects that form the intersection of the field values. For instance, if you have two fields "a" and "b", and objects "{a:1,b:1},{a:1,b:1},{a:1,b:2},{a:2,b:2}" and apply the `COUNT` function, the returned KCSGroup object will have an array of 3 objects: "{a:1,b:1,count:2},{a:1,b:2,count:1},{a:2,b:2,count:1}". For objects that don't have a value for a given field, the value used will be `NSNull`.
@param function This is the function that is applied to the items in the group. If you do not want to apply a function, just use queryWithQuery:withCompletionBlock:withProgressBlock: instead and query for items that match specific field values.
@param condition This is a KCSQuery object that is used to filter the objects before grouping. Only groupings with at least one object that matches the condition will appear in the resultant KCSGroup object.
@param completionBlock A block that is invoked when the grouping is complete, or an error occurs.
@param progressBlock A block that is invoked whenever the store can offer an update on the progress of the operation.
@param cachePolicy override the object's cachePolicy for this group query only.
@see [KCSAppdataStore group:reduce:condition:completionBlock:progressBlock:]
*/
- (void)group:(id)fieldOrFields reduce:(KCSReduceFunction *)function condition:(KCSQuery *)condition completionBlock:(KCSGroupCompletionBlock)completionBlock progressBlock:(KCSProgressBlock)progressBlock cachePolicy:(KCSCachePolicy)cachePolicy;
@end
| {
"content_hash": "d71f3852d6613f78e50f2fcb8304eb14",
"timestamp": "",
"source": "github",
"line_count": 116,
"max_line_length": 752,
"avg_line_length": 74.05172413793103,
"alnum_prop": 0.7881257275902211,
"repo_name": "KinveyApps/Scrumptious-iOS",
"id": "68d5ea3cb6859a0d3fddbde2fba049b557e889b6",
"size": "8590",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Kinvey/KinveyKit.framework/Versions/A/Headers/KCSCachedStore.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "63697"
},
{
"name": "C++",
"bytes": "1746"
},
{
"name": "Objective-C",
"bytes": "790515"
}
],
"symlink_target": ""
} |
#pragma once
#include <aws/imagebuilder/Imagebuilder_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/imagebuilder/model/EbsVolumeType.h>
#include <utility>
namespace Aws
{
namespace Utils
{
namespace Json
{
class JsonValue;
class JsonView;
} // namespace Json
} // namespace Utils
namespace imagebuilder
{
namespace Model
{
/**
* <p>Amazon EBS-specific block device mapping specifications.</p><p><h3>See
* Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/imagebuilder-2019-12-02/EbsInstanceBlockDeviceSpecification">AWS
* API Reference</a></p>
*/
class AWS_IMAGEBUILDER_API EbsInstanceBlockDeviceSpecification
{
public:
EbsInstanceBlockDeviceSpecification();
EbsInstanceBlockDeviceSpecification(Aws::Utils::Json::JsonView jsonValue);
EbsInstanceBlockDeviceSpecification& operator=(Aws::Utils::Json::JsonView jsonValue);
Aws::Utils::Json::JsonValue Jsonize() const;
/**
* <p>Use to configure device encryption.</p>
*/
inline bool GetEncrypted() const{ return m_encrypted; }
/**
* <p>Use to configure device encryption.</p>
*/
inline bool EncryptedHasBeenSet() const { return m_encryptedHasBeenSet; }
/**
* <p>Use to configure device encryption.</p>
*/
inline void SetEncrypted(bool value) { m_encryptedHasBeenSet = true; m_encrypted = value; }
/**
* <p>Use to configure device encryption.</p>
*/
inline EbsInstanceBlockDeviceSpecification& WithEncrypted(bool value) { SetEncrypted(value); return *this;}
/**
* <p>Use to configure delete on termination of the associated device.</p>
*/
inline bool GetDeleteOnTermination() const{ return m_deleteOnTermination; }
/**
* <p>Use to configure delete on termination of the associated device.</p>
*/
inline bool DeleteOnTerminationHasBeenSet() const { return m_deleteOnTerminationHasBeenSet; }
/**
* <p>Use to configure delete on termination of the associated device.</p>
*/
inline void SetDeleteOnTermination(bool value) { m_deleteOnTerminationHasBeenSet = true; m_deleteOnTermination = value; }
/**
* <p>Use to configure delete on termination of the associated device.</p>
*/
inline EbsInstanceBlockDeviceSpecification& WithDeleteOnTermination(bool value) { SetDeleteOnTermination(value); return *this;}
/**
* <p>Use to configure device IOPS.</p>
*/
inline int GetIops() const{ return m_iops; }
/**
* <p>Use to configure device IOPS.</p>
*/
inline bool IopsHasBeenSet() const { return m_iopsHasBeenSet; }
/**
* <p>Use to configure device IOPS.</p>
*/
inline void SetIops(int value) { m_iopsHasBeenSet = true; m_iops = value; }
/**
* <p>Use to configure device IOPS.</p>
*/
inline EbsInstanceBlockDeviceSpecification& WithIops(int value) { SetIops(value); return *this;}
/**
* <p>Use to configure the KMS key to use when encrypting the device.</p>
*/
inline const Aws::String& GetKmsKeyId() const{ return m_kmsKeyId; }
/**
* <p>Use to configure the KMS key to use when encrypting the device.</p>
*/
inline bool KmsKeyIdHasBeenSet() const { return m_kmsKeyIdHasBeenSet; }
/**
* <p>Use to configure the KMS key to use when encrypting the device.</p>
*/
inline void SetKmsKeyId(const Aws::String& value) { m_kmsKeyIdHasBeenSet = true; m_kmsKeyId = value; }
/**
* <p>Use to configure the KMS key to use when encrypting the device.</p>
*/
inline void SetKmsKeyId(Aws::String&& value) { m_kmsKeyIdHasBeenSet = true; m_kmsKeyId = std::move(value); }
/**
* <p>Use to configure the KMS key to use when encrypting the device.</p>
*/
inline void SetKmsKeyId(const char* value) { m_kmsKeyIdHasBeenSet = true; m_kmsKeyId.assign(value); }
/**
* <p>Use to configure the KMS key to use when encrypting the device.</p>
*/
inline EbsInstanceBlockDeviceSpecification& WithKmsKeyId(const Aws::String& value) { SetKmsKeyId(value); return *this;}
/**
* <p>Use to configure the KMS key to use when encrypting the device.</p>
*/
inline EbsInstanceBlockDeviceSpecification& WithKmsKeyId(Aws::String&& value) { SetKmsKeyId(std::move(value)); return *this;}
/**
* <p>Use to configure the KMS key to use when encrypting the device.</p>
*/
inline EbsInstanceBlockDeviceSpecification& WithKmsKeyId(const char* value) { SetKmsKeyId(value); return *this;}
/**
* <p>The snapshot that defines the device contents.</p>
*/
inline const Aws::String& GetSnapshotId() const{ return m_snapshotId; }
/**
* <p>The snapshot that defines the device contents.</p>
*/
inline bool SnapshotIdHasBeenSet() const { return m_snapshotIdHasBeenSet; }
/**
* <p>The snapshot that defines the device contents.</p>
*/
inline void SetSnapshotId(const Aws::String& value) { m_snapshotIdHasBeenSet = true; m_snapshotId = value; }
/**
* <p>The snapshot that defines the device contents.</p>
*/
inline void SetSnapshotId(Aws::String&& value) { m_snapshotIdHasBeenSet = true; m_snapshotId = std::move(value); }
/**
* <p>The snapshot that defines the device contents.</p>
*/
inline void SetSnapshotId(const char* value) { m_snapshotIdHasBeenSet = true; m_snapshotId.assign(value); }
/**
* <p>The snapshot that defines the device contents.</p>
*/
inline EbsInstanceBlockDeviceSpecification& WithSnapshotId(const Aws::String& value) { SetSnapshotId(value); return *this;}
/**
* <p>The snapshot that defines the device contents.</p>
*/
inline EbsInstanceBlockDeviceSpecification& WithSnapshotId(Aws::String&& value) { SetSnapshotId(std::move(value)); return *this;}
/**
* <p>The snapshot that defines the device contents.</p>
*/
inline EbsInstanceBlockDeviceSpecification& WithSnapshotId(const char* value) { SetSnapshotId(value); return *this;}
/**
* <p>Use to override the device's volume size.</p>
*/
inline int GetVolumeSize() const{ return m_volumeSize; }
/**
* <p>Use to override the device's volume size.</p>
*/
inline bool VolumeSizeHasBeenSet() const { return m_volumeSizeHasBeenSet; }
/**
* <p>Use to override the device's volume size.</p>
*/
inline void SetVolumeSize(int value) { m_volumeSizeHasBeenSet = true; m_volumeSize = value; }
/**
* <p>Use to override the device's volume size.</p>
*/
inline EbsInstanceBlockDeviceSpecification& WithVolumeSize(int value) { SetVolumeSize(value); return *this;}
/**
* <p>Use to override the device's volume type.</p>
*/
inline const EbsVolumeType& GetVolumeType() const{ return m_volumeType; }
/**
* <p>Use to override the device's volume type.</p>
*/
inline bool VolumeTypeHasBeenSet() const { return m_volumeTypeHasBeenSet; }
/**
* <p>Use to override the device's volume type.</p>
*/
inline void SetVolumeType(const EbsVolumeType& value) { m_volumeTypeHasBeenSet = true; m_volumeType = value; }
/**
* <p>Use to override the device's volume type.</p>
*/
inline void SetVolumeType(EbsVolumeType&& value) { m_volumeTypeHasBeenSet = true; m_volumeType = std::move(value); }
/**
* <p>Use to override the device's volume type.</p>
*/
inline EbsInstanceBlockDeviceSpecification& WithVolumeType(const EbsVolumeType& value) { SetVolumeType(value); return *this;}
/**
* <p>Use to override the device's volume type.</p>
*/
inline EbsInstanceBlockDeviceSpecification& WithVolumeType(EbsVolumeType&& value) { SetVolumeType(std::move(value)); return *this;}
private:
bool m_encrypted;
bool m_encryptedHasBeenSet;
bool m_deleteOnTermination;
bool m_deleteOnTerminationHasBeenSet;
int m_iops;
bool m_iopsHasBeenSet;
Aws::String m_kmsKeyId;
bool m_kmsKeyIdHasBeenSet;
Aws::String m_snapshotId;
bool m_snapshotIdHasBeenSet;
int m_volumeSize;
bool m_volumeSizeHasBeenSet;
EbsVolumeType m_volumeType;
bool m_volumeTypeHasBeenSet;
};
} // namespace Model
} // namespace imagebuilder
} // namespace Aws
| {
"content_hash": "6c3a9c4eac198b385a2788cd5ffb02eb",
"timestamp": "",
"source": "github",
"line_count": 261,
"max_line_length": 135,
"avg_line_length": 31.78544061302682,
"alnum_prop": 0.6674300867888139,
"repo_name": "awslabs/aws-sdk-cpp",
"id": "8d2c0c5ee884f4c4b06e6078ad30badbd5aecf08",
"size": "8415",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "aws-cpp-sdk-imagebuilder/include/aws/imagebuilder/model/EbsInstanceBlockDeviceSpecification.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "7596"
},
{
"name": "C++",
"bytes": "61740540"
},
{
"name": "CMake",
"bytes": "337520"
},
{
"name": "Java",
"bytes": "223122"
},
{
"name": "Python",
"bytes": "47357"
}
],
"symlink_target": ""
} |
package thesis.pointsandlinesmethods;
//A method to implement an Approximation Algorithm for reconstruction of heavy point configurations. See Ray Grossman's Princeton senior thesis for details.
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
public class intersectionAlgorithm {
public static void main(String[] args) throws FileNotFoundException, IOException {
//Initialize variables for I/O
String fileName = "Elkies3.txt";
String line = null;
//Input how many points you want, and how many points each line should be incident to in our configuration in command line
int goalSize= Integer.parseInt(args[0]);
int goalIncidence= Integer.parseInt(args[1]);
//Set of points
Point[] pointSet = new Point[goalSize];
//HashMap for point search
HashMap<Point, Integer> pointHash = new HashMap<Point, Integer>();
int pointCounter = 0;
//HashMap for checking if lines are already defined in our configuration. Keys are lines, values are incidences.
//Could have stored a point array to improve running time later. Time-space tradeoff.
HashMap<Line, Integer> linesHash = new HashMap<Line, Integer>();
//HashMap for query by how many points each line is incident to.
HashMap<Integer, ArrayList<Line>> incidenceHash = new HashMap<Integer, ArrayList<Line>>();
//read in from specified file the initial point configuration
try {
FileReader fileReader =
new FileReader(fileName);
BufferedReader bufferedReader =
new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null) {
String[] argSplit = line.split(",");
// The algorithm currently only accepts points in the real plane for input. If you want inputs in the projective plane,
//simply modify your input file and parse more arguments.
double xValue = Double.parseDouble(argSplit[0]);
double yValue = Double.parseDouble(argSplit[1]);
Point thisPoint = new Point (xValue, yValue, 0, false, false);
// Put it in our point sets
pointSet[pointCounter] = thisPoint;
pointHash.put(thisPoint, 0);
pointCounter++;
}
bufferedReader.close();
}
//catch any problems
catch(FileNotFoundException ex) {
System.out.println(
"Unable to open file '" +
fileName + "'");
}
catch(IOException ex) {
System.out.println(
"Error reading file '"
+ fileName + "'");
}
//for testing purposes
// for (int i=0;i<goalSize; i++) {
// if(pointSet[i]!= null) {
// Point.Print(pointSet[i]);
// }
// }
// for (Point key : pointHash.keySet()) {
// Point.Print(key);
// }
//variables for finding lines defined by initial configuration
Line newLine = null;
int incidenceCount=2;
// Initialize the set of lines defined by our configuration. For each point, look at every other point for lines.
//This slow brute force implementation could likely be improved; be wary of inputting computationally
//large text files for fear of potential O(n^3/6) runtime. However, in practice, this will likely run much faster.
for (int i=0; i<pointCounter; i++) {
for(int j = i+1; j<pointCounter; j++) {
incidenceCount = 2;
newLine = Point.getLine(pointSet[i], pointSet[j]);
// If we already found that line, move on
if(linesHash.containsKey(newLine)) {
continue;
}
// If we haven't; find how many points it is incident to
else {
for(int k = 0; k<pointCounter; k++) {
if(!(k==i) && !(k == j)) {
if(Line.onLine(newLine, pointSet[k])) {
incidenceCount++;
}
}
}
}
// put our new line into our two hashmaps
linesHash.put(newLine, incidenceCount);
//initialize the ArrayList for incidence incidenceCount if there is no such ArrayList in our hashmap.
if(!incidenceHash.containsKey(incidenceCount)) {
ArrayList<Line> arrToAdd = new ArrayList<Line>(10);
arrToAdd.add(newLine);
incidenceHash.put(incidenceCount, arrToAdd);
}
else {
incidenceHash.get(incidenceCount).add(newLine);
}
}
}
// for testing purposes
// for (Line key : linesHash.keySet()) {
// String keyString =Line.toString(key);
// System.out.println(keyString + " "+ linesHash.get(key));
// }
// for (int key : incidenceHash.keySet()) {
// String ikey = Integer.toString(key);
// for (Line item : incidenceHash.get(key)) {
// String lvalue = Line.toString(item);
// System.out.println(lvalue + " "+ ikey);
// }
// }
//
//Now we have initialized a pair of hashes; one sorted by lines, the other sorted by incidence values.
//So, let's begin implementation.
Line firstLine;
Line secondLine;
Point currentPoint;
//add points until we have our desired amount
while(pointCounter < goalSize) {
//find our intersection point
//set breakpoint pick lines in sequential order, descending by incidence
breakpoint1:
for(int i = goalIncidence -1; i>=2; i--) {
//if we have a line of incidence i...
if(incidenceHash.containsKey(i)) {
//copy the array of all lines of that incidence from our incidence hash.
ArrayList<Line> copiedListI = new ArrayList<Line>(incidenceHash.get(i));
//shuffle it randomly
Collections.shuffle(copiedListI);
//begin iterating through items for a new point to add to our configuration
for (Line item: copiedListI) {
firstLine = item;
//for testing
// String x = Line.toString(firstLine);
// System.out.println(x);
//Select a second line by copying list j starting from the same incidence as i, looking at lists again in descending order,
//and shuffling the pointers for a "random" approach
for(int j= i; j>=2; j--) {
ArrayList<Line> copiedListJ = new ArrayList<Line>(incidenceHash.get(j));
Collections.shuffle(copiedListJ);
//Look through our new random order for a usable point of intersection. If we don't find one, go back up to the
//next item.
for(Line item2: copiedListJ) {
secondLine= item2;
//for testing
// String x1 = Line.toString(secondLine);
// System.out.println(x1);
//
if(secondLine.equals(firstLine)) {
continue;
}
else {
currentPoint = Line.getIntersection(firstLine,secondLine);
//for testing
// Point.Print(currentPoint);
//if we have the point in our configuration already, continue with the next item
if(pointHash.get(currentPoint) != null) {
continue;
}
//otherwise put it into our point set and add the lines defined by it/update incidences of current lines.
//again, be wary, this section has potential running time O(n^2) as I chose not to keep an array of point incidences in my line HashMap.
//in practice likely faster
else {
pointHash.put(currentPoint, 0);
pointSet[pointCounter]= currentPoint;
//example running time improvement- hold an array of values, they cannot be on more than one line, and update that value
//when you find the line it is on.
boolean[] pointCheck = new boolean[goalSize];
//find all of the adjacent lines
for(int j1 = 0; j1<pointCounter; j1++) {
if(pointCheck[j1]) {
continue;
}
pointCheck[j1]=true;
incidenceCount = 2;
newLine = Point.getLine(currentPoint, pointSet[j1]);
// find incidences for each adjacent line
for(int k1 = j1+1; k1 <pointCounter; k1++) {
if(k1 != j1) {
if(Line.onLine(newLine, pointSet[k1])) {
incidenceCount++;
pointCheck[k1]=true;
}
}
}
// If we already have that line, update it to have higher incidence and move on
//first take it out of it's current bucket
if(linesHash.containsKey(newLine)) {
if (incidenceHash.get((incidenceCount-1)) != null){
while(incidenceHash.get((incidenceCount-1)).remove(newLine));
}
//updates the hash with lines as keys
linesHash.put(newLine, incidenceCount);
//make a new bucket or put it in its current bucket
if(!incidenceHash.containsKey((incidenceCount))) {
ArrayList<Line> arrToAdd = new ArrayList<Line>(10);
arrToAdd.add(newLine);
incidenceHash.put(incidenceCount, arrToAdd);
}
else {
incidenceHash.get(incidenceCount).add(newLine);
}
}
// If we don't have the line in our configuration
else {
// put our new line into our two hashmaps in the proper places.
linesHash.put(newLine, incidenceCount);
if(!incidenceHash.containsKey(incidenceCount)) {
ArrayList<Line> arrToAdd = new ArrayList<Line>(10);
arrToAdd.add(newLine);
incidenceHash.put(incidenceCount, arrToAdd);
}
else {
incidenceHash.get(incidenceCount).add(newLine);
}
}
}
//we have found a point, break back to the breakpoint, and continue our while loop
//until we have our desired number of points.
pointCounter++;
break breakpoint1;
}
}
}
}
}
}
}
}
//Print out our results, formatted for piping straight to LaTeX
System.out.println("\\textbf{Point set:}");
for (int i=0;i<goalSize; i++) {
Point.Print(pointSet[i]);
}
System.out.println("\\\\ \\textbf{High Incidence Line Set:}");
int highIncidenceLines = 0;
for (int key : incidenceHash.keySet()) {
if(key>=goalIncidence) {
String ikey = Integer.toString(key);
for (Line item : incidenceHash.get(key)) {
highIncidenceLines++;
String lvalue = Line.toString(item);
System.out.println(lvalue + ", Incident to: "+ ikey + " points.");
}
}
}
// System.out.println("\\\\ \\textbf{High Incidence Line Set:}");
// int highIncidenceLines = 0;
// for (Line key : linesHash.keySet()) {
// int curr = linesHash.get(key);
// if(( curr >= goalIncidence)) {
// String iKey = Integer.toString(curr);
// highIncidenceLines++;
// String lvalue = Line.toString(key);
// System.out.println(lvalue + ", Incident to: "+ iKey + " points.");
// }
// }
//
System.out.println("\\\\ \\textbf{Point set of size:} " + Integer.toString(goalSize) +
". \\textbf{High incidence lines of minimum richness " + Integer.toString(goalIncidence)
+ ":} "+ Integer.toString(highIncidenceLines) +".");
return;
}
}
| {
"content_hash": "4c202dab4baab4ae0d09ee4eb2fe6bcd",
"timestamp": "",
"source": "github",
"line_count": 324,
"max_line_length": 156,
"avg_line_length": 40.46913580246913,
"alnum_prop": 0.5250152532031727,
"repo_name": "Ray-Gr/On-Finding-and-Recovering-Heavy-Point-Configurations-Algorithmically",
"id": "3d0994e54591fac8e881fb27bd4d17e220dbd976",
"size": "13112",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "intersectionAlgorithm.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "27740"
}
],
"symlink_target": ""
} |
{% load i18n %}
<div class="image_select">
<div class="row">
{% for choice_with_image in choices_with_images %}
{% with choice=choice_with_image.0 image=choice_with_image.1 %}
<div class="image_select-item">
<input id="{{ choice.id_for_label }}" name="{{ choice.data.name }}" class="filled-in" type="checkbox" value="{{ choice.data.value }}" {% if choice.data.selected %}checked{% endif %}>
<label for="{{ choice.id_for_label }}"></label>
<img id="{{ choice.id_for_label }}" class="responsive-img" src="{{ image.image.thumbnail.255x255 }}" srcset="{{ image.image.thumbnail.255x255 }} 1x" alt="">
<div id="{{ choice.id_for_label }}" class="image_select-item-overlay{% if choice.data.selected %} checked{% endif %}"></div>
</div>
{% endwith %}
{% endfor %}
</div>
{% for error in field.errors %}
<p class="help-block materialize-red-text">{{ error }}</p>
{% endfor %}
{% if field.help_text %}
<p class="help-block">{{ field.help_text|safe }}</p>
{% endif %}
</div>
| {
"content_hash": "ca078f44fd2c8f4107f4dd5de19854b2",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 192,
"avg_line_length": 48.18181818181818,
"alnum_prop": 0.5858490566037736,
"repo_name": "UITools/saleor",
"id": "376e90f1558a03385e51b38418d429076f422630",
"size": "1060",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "templates/dashboard/product/product_variant/_image_select.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "96006"
},
{
"name": "Dockerfile",
"bytes": "1859"
},
{
"name": "HTML",
"bytes": "556961"
},
{
"name": "JavaScript",
"bytes": "64679"
},
{
"name": "Python",
"bytes": "2316144"
},
{
"name": "Shell",
"bytes": "1265"
},
{
"name": "TypeScript",
"bytes": "2526265"
}
],
"symlink_target": ""
} |
'use strict';
var mailgun = require('../lib/mailgun.js');
/*
======== A Handy Little Nodeunit Reference ========
https://github.com/caolan/nodeunit
Test methods:
test.expect(numAssertions)
test.done()
Test assertions:
test.ok(value, [message])
test.equal(actual, expected, [message])
test.notEqual(actual, expected, [message])
test.deepEqual(actual, expected, [message])
test.notDeepEqual(actual, expected, [message])
test.strictEqual(actual, expected, [message])
test.notStrictEqual(actual, expected, [message])
test.throws(block, [error], [message])
test.doesNotThrow(block, [error], [message])
test.ifError(value)
*/
exports['awesome'] = {
setUp: function(done) {
// setup here
done();
},
'no args': function(test) {
test.expect(1);
// tests here
test.equal(mailgun.awesome(), 'awesome', 'should be awesome.');
test.done();
},
};
| {
"content_hash": "379490f5f80ab46e5a6a3a4340fcf93e",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 67,
"avg_line_length": 25.694444444444443,
"alnum_prop": 0.6367567567567568,
"repo_name": "feltnerm/node-mailgun",
"id": "3981a8b4e12bbe7137e6f30abe2c10814706e4ea",
"size": "925",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/mailgun_test.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "4520"
}
],
"symlink_target": ""
} |
require 'arjdbc/railtie'
ArJdbc.deprecate "require 'arjdbc/railtie' instead of 'arjdbc/jdbc/railtie'" | {
"content_hash": "23bfc48e67eeb922da226949582b43d0",
"timestamp": "",
"source": "github",
"line_count": 2,
"max_line_length": 76,
"avg_line_length": 50.5,
"alnum_prop": 0.801980198019802,
"repo_name": "keeguon/activerecord-jdbc-adapter",
"id": "b15c3a5759fb0477a9dbae647bb7431cc311b5ae",
"size": "101",
"binary": false,
"copies": "1",
"ref": "refs/heads/1-3-stable",
"path": "lib/arjdbc/jdbc/railtie.rb",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Java",
"bytes": "366459"
},
{
"name": "Ruby",
"bytes": "1118391"
},
{
"name": "Shell",
"bytes": "259"
}
],
"symlink_target": ""
} |
<?php
namespace Drupal\diff\Form;
use Drupal\Component\Utility\Xss;
use Drupal\Core\Entity\Query\QueryFactory;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Language\LanguageManagerInterface;
use Drupal\Core\Link;
use Drupal\diff\DiffEntityComparison;
use Drupal\diff\DiffLayoutManager;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Datetime\DateFormatter;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
use Drupal\Core\Render\RendererInterface;
/**
* Provides a form for revision overview page.
*/
class RevisionOverviewForm extends FormBase {
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* The current user service.
*
* @var \Drupal\Core\Session\AccountInterface
*/
protected $currentUser;
/**
* The date service.
*
* @var \Drupal\Core\Datetime\DateFormatter
*/
protected $date;
/**
* The renderer service.
*
* @var \Drupal\Core\Render\RendererInterface
*/
protected $renderer;
/**
* The language manager.
*
* @var \Drupal\Core\Language\LanguageManagerInterface
*/
protected $languageManager;
/**
* Wrapper object for simple configuration from diff.settings.yml.
*
* @var \Drupal\Core\Config\ImmutableConfig
*/
protected $config;
/**
* The field diff layout plugin manager service.
*
* @var \Drupal\diff\DiffLayoutManager
*/
protected $diffLayoutManager;
/**
* The diff entity comparison service.
*
* @var \Drupal\diff\DiffEntityComparison
*/
protected $entityComparison;
/**
* The entity query factory service.
*
* @var \Drupal\Core\Entity\Query\QueryFactory
*/
protected $entityQuery;
/**
* Constructs a RevisionOverviewForm object.
*
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager.
* @param \Drupal\Core\Session\AccountInterface $current_user
* The current user.
* @param \Drupal\Core\Datetime\DateFormatter $date
* The date service.
* @param \Drupal\Core\Render\RendererInterface $renderer
* The renderer service.
* @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
* The language manager.
* @param \Drupal\diff\DiffLayoutManager $diff_layout_manager
* The diff layout service.
* @param \Drupal\diff\DiffEntityComparison $entity_comparison
* The diff entity comparison service.
* @param \Drupal\Core\Entity\Query\QueryFactory $entity_query
* The entity query factory.
*/
public function __construct(EntityTypeManagerInterface $entity_type_manager, AccountInterface $current_user, DateFormatter $date, RendererInterface $renderer, LanguageManagerInterface $language_manager, DiffLayoutManager $diff_layout_manager, DiffEntityComparison $entity_comparison, QueryFactory $entity_query) {
$this->entityTypeManager = $entity_type_manager;
$this->currentUser = $current_user;
$this->date = $date;
$this->renderer = $renderer;
$this->languageManager = $language_manager;
$this->config = $this->config('diff.settings');
$this->diffLayoutManager = $diff_layout_manager;
$this->entityComparison = $entity_comparison;
$this->entityQuery = $entity_query;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('entity_type.manager'),
$container->get('current_user'),
$container->get('date.formatter'),
$container->get('renderer'),
$container->get('language_manager'),
$container->get('plugin.manager.diff.layout'),
$container->get('diff.entity_comparison'),
$container->get('entity.query')
);
}
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'revision_overview_form';
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state, $node = NULL) {
$account = $this->currentUser;
/** @var \Drupal\node\NodeInterface $node */
$langcode = $node->language()->getId();
$langname = $node->language()->getName();
$languages = $node->getTranslationLanguages();
$has_translations = (count($languages) > 1);
$node_storage = $this->entityTypeManager->getStorage('node');
$type = $node->getType();
$pagerLimit = $this->config->get('general_settings.revision_pager_limit');
$query = $this->entityQuery->get('node')
->condition($node->getEntityType()->getKey('id'), $node->id())
->pager($pagerLimit)
->allRevisions()
->sort($node->getEntityType()->getKey('revision'), 'DESC')
->execute();
$vids = array_keys($query);
$revision_count = count($vids);
$build['#title'] = $has_translations ? $this->t('@langname revisions for %title', [
'@langname' => $langname,
'%title' => $node->label(),
]) : $this->t('Revisions for %title', [
'%title' => $node->label(),
]);
$build['nid'] = array(
'#type' => 'hidden',
'#value' => $node->id(),
);
$table_header = [];
$table_header['revision'] = $this->t('Revision');
// Allow comparisons only if there are 2 or more revisions.
if ($revision_count > 1) {
$table_header += array(
'select_column_one' => '',
'select_column_two' => '',
);
}
$table_header['operations'] = $this->t('Operations');
$rev_revert_perm = $account->hasPermission("revert $type revisions") ||
$account->hasPermission('revert all revisions') ||
$account->hasPermission('administer nodes');
$rev_delete_perm = $account->hasPermission("delete $type revisions") ||
$account->hasPermission('delete all revisions') ||
$account->hasPermission('administer nodes');
$revert_permission = $rev_revert_perm && $node->access('update');
$delete_permission = $rev_delete_perm && $node->access('delete');
// Contains the table listing the revisions.
$build['node_revisions_table'] = array(
'#type' => 'table',
'#header' => $table_header,
'#attributes' => array('class' => array('diff-revisions')),
);
$build['node_revisions_table']['#attached']['library'][] = 'diff/diff.general';
$build['node_revisions_table']['#attached']['drupalSettings']['diffRevisionRadios'] = $this->config->get('general_settings.radio_behavior');
$default_revision = $node->getRevisionId();
// Add rows to the table.
foreach ($vids as $key => $vid) {
$previous_revision = NULL;
if (isset($vids[$key + 1])) {
$previous_revision = $node_storage->loadRevision($vids[$key + 1]);
}
/** @var \Drupal\Core\Entity\ContentEntityInterface $revision */
if ($revision = $node_storage->loadRevision($vid)) {
if ($revision->hasTranslation($langcode) && $revision->getTranslation($langcode)->isRevisionTranslationAffected()) {
$username = array(
'#theme' => 'username',
'#account' => $revision->getRevisionAuthor(),
);
$revision_date = $this->date->format($revision->getRevisionCreationTime(), 'short');
// Use revision link to link to revisions that are not active.
if ($vid != $node->getRevisionId()) {
$link = Link::fromTextAndUrl($revision_date, new Url('entity.node.revision', ['node' => $node->id(), 'node_revision' => $vid]));
}
else {
$link = $node->toLink($revision_date);
}
if ($vid == $default_revision) {
$row = [
'revision' => $this->buildRevision($link, $username, $revision, $previous_revision),
];
// Allow comparisons only if there are 2 or more revisions.
if ($revision_count > 1) {
$row += [
'select_column_one' => $this->buildSelectColumn('radios_left', $vid, FALSE),
'select_column_two' => $this->buildSelectColumn('radios_right', $vid, $vid),
];
}
$row['operations'] = array(
'#prefix' => '<em>',
'#markup' => $this->t('Current revision'),
'#suffix' => '</em>',
'#attributes' => array(
'class' => array('revision-current'),
),
);
$row['#attributes'] = [
'class' => ['revision-current'],
];
}
else {
$route_params = array(
'node' => $node->id(),
'node_revision' => $vid,
'langcode' => $langcode,
);
$links = array();
if ($revert_permission) {
$links['revert'] = [
'title' => $vid < $node->getRevisionId() ? $this->t('Revert') : $this->t('Set as current revision'),
'url' => $has_translations ?
Url::fromRoute('node.revision_revert_translation_confirm', ['node' => $node->id(), 'node_revision' => $vid, 'langcode' => $langcode]) :
Url::fromRoute('node.revision_revert_confirm', ['node' => $node->id(), 'node_revision' => $vid]),
];
}
if ($delete_permission) {
$links['delete'] = array(
'title' => $this->t('Delete'),
'url' => Url::fromRoute('node.revision_delete_confirm', $route_params),
);
}
// Here we don't have to deal with 'only one revision' case because
// if there's only one revision it will also be the default one,
// entering on the first branch of this if else statement.
$row = [
'revision' => $this->buildRevision($link, $username, $revision, $previous_revision),
'select_column_one' => $this->buildSelectColumn('radios_left', $vid,
isset($vids[1]) ? $vids[1] : FALSE),
'select_column_two' => $this->buildSelectColumn('radios_right', $vid, FALSE),
'operations' => [
'#type' => 'operations',
'#links' => $links,
],
];
}
// Add the row to the table.
$build['node_revisions_table'][] = $row;
}
}
}
// Allow comparisons only if there are 2 or more revisions.
if ($revision_count > 1) {
$build['submit'] = array(
'#type' => 'submit',
'#button_type' => 'primary',
'#value' => t('Compare selected revisions'),
'#attributes' => array(
'class' => array(
'diff-button',
),
),
);
}
$build['pager'] = array(
'#type' => 'pager',
);
$build['#attached']['library'][] = 'node/drupal.node.admin';
return $build;
}
/**
* Set column attributes and return config array.
*
* @param string $name
* Name attribute.
* @param string $return_val
* Return value attribute.
* @param string $default_val
* Default value attribute.
*
* @return array
* Configuration array.
*/
protected function buildSelectColumn($name, $return_val, $default_val) {
return [
'#type' => 'radio',
'#title_display' => 'invisible',
'#name' => $name,
'#return_value' => $return_val,
'#default_value' => $default_val,
];
}
/**
* Set and return configuration for revision.
*
* @param \Drupal\Core\Link $link
* Link attribute.
* @param string $username
* Username attribute.
* @param \Drupal\Core\Entity\ContentEntityInterface $revision
* Revision parameter for getRevisionDescription function.
* @param \Drupal\Core\Entity\ContentEntityInterface $previous_revision
* (optional) Previous revision for getRevisionDescription function.
* Defaults to NULL.
*
* @return array
* Configuration for revision.
*/
protected function buildRevision(Link $link, $username, ContentEntityInterface $revision, ContentEntityInterface $previous_revision = NULL) {
return [
'#type' => 'inline_template',
'#template' => '{% trans %}{{ date }} by {{ username }}{% endtrans %}{% if message %}<p class="revision-log">{{ message }}</p>{% endif %}',
'#context' => [
'date' => $link->toString(),
'username' => $this->renderer->renderPlain($username),
'message' => [
'#markup' => $this->entityComparison->getRevisionDescription($revision, $previous_revision),
'#allowed_tags' => Xss::getAdminTagList(),
],
],
];
}
/**
* {@inheritdoc}
*/
public function validateForm(array &$form, FormStateInterface $form_state) {
$input = $form_state->getUserInput();
if (count($form_state->getValue('node_revisions_table')) <= 1) {
$form_state->setErrorByName('node_revisions_table', $this->t('Multiple revisions are needed for comparison.'));
}
elseif (!isset($input['radios_left']) || !isset($input['radios_right'])) {
$form_state->setErrorByName('node_revisions_table', $this->t('Select two revisions to compare.'));
}
elseif ($input['radios_left'] == $input['radios_right']) {
// @todo Radio-boxes selection resets if there are errors.
$form_state->setErrorByName('node_revisions_table', $this->t('Select different revisions to compare.'));
}
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$input = $form_state->getUserInput();
$vid_left = $input['radios_left'];
$vid_right = $input['radios_right'];
$nid = $input['nid'];
// Always place the older revision on the left side of the comparison
// and the newer revision on the right side (however revisions can be
// compared both ways if we manually change the order of the parameters).
if ($vid_left > $vid_right) {
$aux = $vid_left;
$vid_left = $vid_right;
$vid_right = $aux;
}
// Builds the redirect Url.
$redirect_url = Url::fromRoute(
'diff.revisions_diff',
array(
'node' => $nid,
'left_revision' => $vid_left,
'right_revision' => $vid_right,
'filter' => $this->diffLayoutManager->getDefaultLayout(),
)
);
$form_state->setRedirectUrl($redirect_url);
}
}
| {
"content_hash": "b253100e22d25e5626839e36b859ea49",
"timestamp": "",
"source": "github",
"line_count": 422,
"max_line_length": 315,
"avg_line_length": 34.355450236966824,
"alnum_prop": 0.5942198923989516,
"repo_name": "rlnorthcutt/acquia-cd-demo",
"id": "fcb6d50ed94644a312c5b35d3a6736972814951e",
"size": "14498",
"binary": false,
"copies": "12",
"ref": "refs/heads/master",
"path": "docroot/modules/contrib/diff/src/Form/RevisionOverviewForm.php",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "593326"
},
{
"name": "Gherkin",
"bytes": "47803"
},
{
"name": "HTML",
"bytes": "725686"
},
{
"name": "JavaScript",
"bytes": "1153521"
},
{
"name": "Makefile",
"bytes": "3570"
},
{
"name": "PHP",
"bytes": "40105732"
},
{
"name": "Ruby",
"bytes": "910"
},
{
"name": "Shell",
"bytes": "58234"
}
],
"symlink_target": ""
} |
{% extends "bootstrap/base.html" %}
{% import "bootstrap/wtf.html" as wtf %}
{% block title %}
Demeter - AskMe SEO Service
{% endblock %}
{% block navbar %}
<div class="navbar navbar-inverse" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="/">SEO Service</a>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="/seo/content">Content Service<span class="caret"></span></a>
<ul class="dropdown-menu">
<li><a href="/seo/content/add_content">Add Content</a></li>
</ul>
</li>
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="/seo/meta">Meta Service<span class="caret"></span></a>
<ul class="dropdown-menu">
<li><a href="/seo/meta/add_meta_data">Add Meta Data</a></li>
</ul>
</li>
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="/seo/keyword">Keyword Service<span class="caret"></span></a>
<ul class="dropdown-menu">
<li><a href="/seo/keyword/keywordtool">KeywordTool Data</a></li>
<li><a href="/seo/keyword/google_suggest">Get Google Suggestions</a></li>
</ul>
</li>
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="/seo/mapper">Mapper Service<span class="caret"></span></a>
<ul class="dropdown-menu">
<li><a href="/seo/mapper/create_custom_landing_page">Create Custom Landing Page</a></li>
</ul>
</li>
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="/seo/redis">Redis Service<span class="caret"></span></a>
<ul class="dropdown-menu">
<li><a href="/seo/redis/meta_data">Push Meta Data to Redis</a></li>
<li><a href="/seo/redis/content_data">Push Content Data to Redis</a></li>
<li><a href="/seo/redis/mapper_data">Push Mapper Data to Redis</a></li>
</ul>
</li>
</ul>
</div>
</div>
</div>
{% endblock %} | {
"content_hash": "51256a68d7e65bc10806aa026fec3cd9",
"timestamp": "",
"source": "github",
"line_count": 60,
"max_line_length": 136,
"avg_line_length": 49,
"alnum_prop": 0.4931972789115646,
"repo_name": "nitinmanchanda/demeter-ui",
"id": "5d275cee9c187e58ec88cd606483a8f2119123f5",
"size": "2940",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/templates/header.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "12061"
},
{
"name": "Python",
"bytes": "19494"
}
],
"symlink_target": ""
} |
mcollective_server_package = 'mcollective-1.3.1-2.el6'
mcollective_server_filename = 'mcollective-1.3.1-2.el6.noarch.rpm'
mcollective_server_local_path = "#{Chef::Config[:file_cache_path]}/#{mcollective_server_filename}"
mcollective_server_remote_path = "#{node[:mcollective][:package_host]}/#{mcollective_server_filename}"
remote_file mcollective_server_local_path do
source mcollective_server_remote_path
action :create_if_missing
end
package mcollective_server_package do
action :install
source mcollective_server_local_path
provider Chef::Provider::Package::Rpm
end
template "/etc/mcollective/server.cfg" do
source "server.cfg.erb"
owner "root"
group "root"
mode "0644"
end
service "mcollective" do
action [:enable, :start]
supports :status => true, :restart => true
subscribes :restart, resources(:template => "/etc/mcollective/server.cfg")
end
| {
"content_hash": "3dd6e92decbe2940de6754f8ac598a6b",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 102,
"avg_line_length": 31.857142857142858,
"alnum_prop": 0.7376681614349776,
"repo_name": "tomcz/aws_rb",
"id": "01d2b21d5659d8027f7334a7345b4ecd43851bd7",
"size": "892",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "chef/cookbooks/mcollective/recipes/server.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "12877"
},
{
"name": "Shell",
"bytes": "164"
}
],
"symlink_target": ""
} |
package com.teamwizardry.inhumanresources.common.entity.render;
import net.minecraft.client.Minecraft;
import net.minecraft.client.model.ModelSlime;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.entity.RenderLiving;
import net.minecraft.util.ResourceLocation;
import com.teamwizardry.inhumanresources.common.entity.mobs.MobSlime;
public class RenderSlime extends RenderLiving<MobSlime>
{
private static final ResourceLocation SLIME_TEXTURES = new ResourceLocation("textures/entity/slime/slime.png");
public RenderSlime()
{
super(Minecraft.getMinecraft().getRenderManager(), new ModelSlime(16), 0);
this.addLayer(new LayerSlimeGel(this));
}
@Override
public void doRender(MobSlime entity, double x, double y, double z, float entityYaw, float partialTicks)
{
this.shadowSize = 0.25F * entity.getSlimeSize();
super.doRender(entity, x, y, z, entityYaw, partialTicks);
}
@Override
protected void preRenderCallback(MobSlime entity, float partialTicks)
{
float f = 0.999F;
GlStateManager.scale(f, f, f);
float f1 = entity.getSlimeSize();
float f2 = (entity.prevSquishFactor + (entity.squishFactor - entity.prevSquishFactor) * partialTicks) / (f1 * 0.5F + 1);
float f3 = 1F / (f2 + 1);
GlStateManager.scale(f3 * f1, 1F / f3 * f1, f3 * f1);
}
@Override
protected ResourceLocation getEntityTexture(MobSlime entity)
{
return SLIME_TEXTURES;
}
}
| {
"content_hash": "d7346da4693500642d3fcc867206af51",
"timestamp": "",
"source": "github",
"line_count": 43,
"max_line_length": 122,
"avg_line_length": 33.06976744186046,
"alnum_prop": 0.7623066104078763,
"repo_name": "murapix/Essence-Armory-2",
"id": "19e8a24c094787334366267aa9e6ed1a7668bb56",
"size": "1422",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/main/java/com/teamwizardry/inhumanresources/common/entity/render/RenderSlime.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "162177"
}
],
"symlink_target": ""
} |
from typing import List
import collections
class Solution:
def leastInterval(self, tasks: List[str], n: int) -> int:
histogram = collections.Counter(tasks)
sorted_histogram = histogram.most_common()
_, max_num_occ = sorted_histogram[0]
num_shared_occ = 0
for _, num_occ in sorted_histogram:
if num_occ != max_num_occ:
break
num_shared_occ += 1
return max(
(max_num_occ + ((max_num_occ-1) * n)) + (num_shared_occ - 1),
len(tasks),
)
| {
"content_hash": "064a3e9494d0a0a1eba59d44f69297a2",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 73,
"avg_line_length": 31,
"alnum_prop": 0.5448028673835126,
"repo_name": "AustinTSchaffer/DailyProgrammer",
"id": "58a373e817a58bab3d9496edfa16a4f0016a9da1",
"size": "558",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "LeetCode/TaskScheduler/app.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "9482"
},
{
"name": "C#",
"bytes": "11127"
},
{
"name": "Dockerfile",
"bytes": "308"
},
{
"name": "F#",
"bytes": "26762"
},
{
"name": "HCL",
"bytes": "2461"
},
{
"name": "HTML",
"bytes": "824"
},
{
"name": "Java",
"bytes": "22830"
},
{
"name": "Julia",
"bytes": "3416"
},
{
"name": "Lua",
"bytes": "6296"
},
{
"name": "Python",
"bytes": "284314"
},
{
"name": "Rust",
"bytes": "1517"
},
{
"name": "Shell",
"bytes": "871"
}
],
"symlink_target": ""
} |
using System.Collections.Generic;
using UnityEngine;
namespace GameBuilder
{
// Some utilities for terrain.
public static class TerrainUtil
{
public const int BlockEdgeLength = 10;
public const int InstancesPerBlock = BlockEdgeLength * BlockEdgeLength * BlockEdgeLength;
const int L = BlockEdgeLength;
const float Lf = (float)BlockEdgeLength;
public class RenderingBlock
{
short nextFreeSlot = 0;
public Matrix4x4[] transforms = new Matrix4x4[InstancesPerBlock];
// If it's -1, the cell is unoccupied. Otherwise, it's an index into the 'transforms' array.
short[] cellToSlot = new short[InstancesPerBlock];
short[] slotToCell = new short[InstancesPerBlock];
public RenderingBlock()
{
for (int i = 0; i < InstancesPerBlock; i++)
{
cellToSlot[i] = -1;
slotToCell[i] = -1;
}
}
public void Set(Int3 u, Matrix4x4 transform)
{
short cell = (short)(u.x * L * L + u.y * L + u.z);
if (cellToSlot[cell] != -1)
{
// Replacing.
// Use the same transform slot.
short slot = cellToSlot[cell];
transforms[slot] = transform;
}
else
{
// New.
short slot = nextFreeSlot++;
cellToSlot[cell] = slot;
slotToCell[slot] = cell;
transforms[slot] = transform;
}
}
public short GetNumOccupied()
{
return nextFreeSlot;
}
public Matrix4x4[] GetTransforms()
{
return transforms;
}
public void Clear(Int3 u)
{
if (GetNumOccupied() == 0)
{
return;
}
short cell = (short)(u.x * L * L + u.y * L + u.z);
short slot = cellToSlot[cell];
if (slot != -1)
{
// Move the last slot to this slot.
short lastSlot = (short)(nextFreeSlot - 1);
short lastCell = slotToCell[lastSlot];
transforms[slot] = transforms[lastSlot];
cellToSlot[lastCell] = slot;
slotToCell[slot] = lastCell;
slotToCell[lastSlot] = -1;
cellToSlot[cell] = -1;
nextFreeSlot = lastSlot;
}
}
public bool CheckInvariants()
{
for (int slot = 0; slot < InstancesPerBlock; slot++)
{
if (slot < nextFreeSlot)
{
// Expect some valid value
if (slotToCell[slot] == -1)
{
return false;
}
int cell = slotToCell[slot];
if (cellToSlot[cell] != slot)
{
return false;
}
}
else
{
// Expect nothing set
if (slotToCell[slot] != -1)
{
return false;
}
}
}
// Expect an exact number of valid cellToSlot entries.
int usedCells = 0;
for (int i = 0; i < InstancesPerBlock; i++)
{
if (cellToSlot[i] != -1)
{
usedCells++;
}
}
if (usedCells != nextFreeSlot)
{
return false;
}
return true;
}
}
// Provides a set/clear(int3, matrix) interface, backed by an efficiently
// managed set of blocks. Each block is below a max size and is spatially
// coherent. Only addressed blocks are actually allocated.
public class BlockManager
{
public Dictionary<Int3, RenderingBlock> blocksTable = new Dictionary<Int3, RenderingBlock>();
public void ClearAll()
{
blocksTable.Clear();
}
public void Set(Int3 u, Matrix4x4 transform)
{
Int3 blockNum = Int3.Floor(u / Lf);
RenderingBlock block = null;
if (!blocksTable.TryGetValue(blockNum, out block))
{
block = new RenderingBlock();
blocksTable.Add(blockNum, block);
}
Int3 blockCell = u - (blockNum * L);
Debug.Assert(blockCell.x >= 0);
Debug.Assert(blockCell.x < L);
Debug.Assert(blockCell.y >= 0);
Debug.Assert(blockCell.y < L);
Debug.Assert(blockCell.z >= 0);
Debug.Assert(blockCell.z < L);
block.Set(blockCell, transform);
}
// TODO possible optimization: keep a pool of rendering blocks, so if we
// fully clear a block, we don't just toss it to garbage or leave the
// memory wasted.
public void Clear(Int3 u)
{
Int3 blockNum = Int3.Floor(u / Lf);
RenderingBlock block = null;
if (!blocksTable.TryGetValue(blockNum, out block))
{
return;
}
Int3 blockCell = u - (blockNum * L);
Debug.Assert(blockCell.x >= 0);
Debug.Assert(blockCell.x < L);
Debug.Assert(blockCell.y >= 0);
Debug.Assert(blockCell.y < L);
Debug.Assert(blockCell.z >= 0);
Debug.Assert(blockCell.z < L);
block.Clear(blockCell);
// TODO if a block is totally cleared, free it (back into a pool!)
}
public void ForEachBlock(System.Action<RenderingBlock> process)
{
foreach (var pair in blocksTable)
{
process(pair.Value);
}
}
}
}
}
| {
"content_hash": "d3491b43dc0744249d2ec8b205d67bf9",
"timestamp": "",
"source": "github",
"line_count": 199,
"max_line_length": 99,
"avg_line_length": 26.628140703517587,
"alnum_prop": 0.5299113040196264,
"repo_name": "googlearchive/gamebuilder",
"id": "a03c7db548516f14f69c9c7b8009467e569b3604",
"size": "5893",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Assets/Scripts/Util/TerrainUtil.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "9226"
},
{
"name": "C#",
"bytes": "2578007"
},
{
"name": "C++",
"bytes": "65377"
},
{
"name": "HTML",
"bytes": "280"
},
{
"name": "Perl",
"bytes": "14805"
},
{
"name": "Python",
"bytes": "54710"
},
{
"name": "ShaderLab",
"bytes": "419944"
},
{
"name": "Shell",
"bytes": "9793"
}
],
"symlink_target": ""
} |
namespace palo {
const char* ExprContext::_s_llvm_class_name = "class.palo::ExprContext";
ExprContext::ExprContext(Expr* root) :
_fn_contexts_ptr(NULL),
_root(root),
_is_clone(false),
_prepared(false),
_opened(false),
_closed(false) {
}
ExprContext::~ExprContext() {
DCHECK(!_prepared || _closed);
for (int i = 0; i < _fn_contexts.size(); ++i) {
delete _fn_contexts[i];
}
}
// TODO(zc): memory tracker
Status ExprContext::prepare(RuntimeState* state, const RowDescriptor& row_desc,
MemTracker* tracker) {
DCHECK(tracker != NULL) << std::endl << get_stack_trace();
DCHECK(_pool.get() == NULL);
_prepared = true;
// TODO: use param tracker to replace instance_mem_tracker
// _pool.reset(new MemPool(new MemTracker(-1)));
_pool.reset(new MemPool(state->instance_mem_tracker()));
return _root->prepare(state, row_desc, this);
}
Status ExprContext::open(RuntimeState* state) {
DCHECK(_prepared);
if (_opened) {
return Status::OK;
}
_opened = true;
// Fragment-local state is only initialized for original contexts. Clones inherit the
// original's fragment state and only need to have thread-local state initialized.
FunctionContext::FunctionStateScope scope =
_is_clone? FunctionContext::THREAD_LOCAL : FunctionContext::FRAGMENT_LOCAL;
return _root->open(state, this, scope);
}
void ExprContext::close(RuntimeState* state) {
DCHECK(!_closed);
FunctionContext::FunctionStateScope scope =
_is_clone? FunctionContext::THREAD_LOCAL : FunctionContext::FRAGMENT_LOCAL;
_root->close(state, this, scope);
for (int i = 0; i < _fn_contexts.size(); ++i) {
_fn_contexts[i]->impl()->close();
}
// _pool can be NULL if Prepare() was never called
if (_pool != NULL) {
_pool->free_all();
}
_closed = true;
}
int ExprContext::register_func(
RuntimeState* state,
const palo_udf::FunctionContext::TypeDesc& return_type,
const std::vector<palo_udf::FunctionContext::TypeDesc>& arg_types,
int varargs_buffer_size) {
_fn_contexts.push_back(FunctionContextImpl::create_context(
state, _pool.get(), return_type, arg_types, varargs_buffer_size, false));
_fn_contexts_ptr = &_fn_contexts[0];
return _fn_contexts.size() - 1;
}
Status ExprContext::clone(RuntimeState* state, ExprContext** new_ctx) {
DCHECK(_prepared);
DCHECK(_opened);
DCHECK(*new_ctx == NULL);
*new_ctx = state->obj_pool()->add(new ExprContext(_root));
(*new_ctx)->_pool.reset(new MemPool(_pool->mem_tracker()));
for (int i = 0; i < _fn_contexts.size(); ++i) {
(*new_ctx)->_fn_contexts.push_back(
_fn_contexts[i]->impl()->clone((*new_ctx)->_pool.get()));
}
(*new_ctx)->_fn_contexts_ptr = &((*new_ctx)->_fn_contexts[0]);
(*new_ctx)->_is_clone = true;
(*new_ctx)->_prepared = true;
(*new_ctx)->_opened = true;
return _root->open(state, *new_ctx, FunctionContext::THREAD_LOCAL);
}
Status ExprContext::clone(RuntimeState* state, ExprContext** new_ctx, Expr* root) {
DCHECK(_prepared);
DCHECK(_opened);
DCHECK(*new_ctx == NULL);
*new_ctx = state->obj_pool()->add(new ExprContext(root));
(*new_ctx)->_pool.reset(new MemPool(_pool->mem_tracker()));
for (int i = 0; i < _fn_contexts.size(); ++i) {
(*new_ctx)->_fn_contexts.push_back(
_fn_contexts[i]->impl()->clone((*new_ctx)->_pool.get()));
}
(*new_ctx)->_fn_contexts_ptr = &((*new_ctx)->_fn_contexts[0]);
(*new_ctx)->_is_clone = true;
(*new_ctx)->_prepared = true;
(*new_ctx)->_opened = true;
return root->open(state, *new_ctx, FunctionContext::THREAD_LOCAL);
}
void ExprContext::free_local_allocations() {
free_local_allocations(_fn_contexts);
}
void ExprContext::free_local_allocations(const std::vector<ExprContext*>& ctxs) {
for (int i = 0; i < ctxs.size(); ++i) {
ctxs[i]->free_local_allocations();
}
}
void ExprContext::free_local_allocations(const std::vector<FunctionContext*>& fn_ctxs) {
for (int i = 0; i < fn_ctxs.size(); ++i) {
if (fn_ctxs[i]->impl()->closed()) {
continue;
}
fn_ctxs[i]->impl()->free_local_allocations();
}
}
void ExprContext::get_value(TupleRow* row, bool as_ascii, TColumnValue* col_val) {
#if 0
void* value = get_value(row);
if (as_ascii) {
RawValue::print_value(value, _root->_type, _root->_output_scale, &col_val->string_val);
col_val->__isset.string_val = true;
return;
}
if (value == NULL) {
return;
}
StringValue* string_val = NULL;
std::string tmp;
switch (_root->_type.type) {
case TYPE_BOOLEAN:
col_val->__set_bool_val(*reinterpret_cast<bool*>(value));
break;
case TYPE_TINYINT:
col_val->__set_byte_val(*reinterpret_cast<int8_t*>(value));
break;
case TYPE_SMALLINT:
col_val->__set_short_val(*reinterpret_cast<int16_t*>(value));
break;
case TYPE_INT:
col_val->__set_int_val(*reinterpret_cast<int32_t*>(value));
break;
case TYPE_BIGINT:
col_val->__set_long_val(*reinterpret_cast<int64_t*>(value));
break;
case TYPE_FLOAT:
col_val->__set_double_val(*reinterpret_cast<float*>(value));
break;
case TYPE_DOUBLE:
col_val->__set_double_val(*reinterpret_cast<double*>(value));
break;
#if 0
case TYPE_DECIMAL:
switch (_root->_type.GetByteSize()) {
case 4:
col_val->string_val =
reinterpret_cast<Decimal4Value*>(value)->ToString(_root->_type);
break;
case 8:
col_val->string_val =
reinterpret_cast<Decimal8Value*>(value)->ToString(_root->_type);
break;
case 16:
col_val->string_val =
reinterpret_cast<Decimal16Value*>(value)->ToString(_root->_type);
break;
default:
DCHECK(false) << "Bad Type: " << _root->_type;
}
col_val->__isset.string_val = true;
break;
case TYPE_VARCHAR:
string_val = reinterpret_cast<StringValue*>(value);
tmp.assign(static_cast<char*>(string_val->ptr), string_val->len);
col_val->string_val.swap(tmp);
col_val->__isset.string_val = true;
break;
case TYPE_CHAR:
tmp.assign(StringValue::CharSlotToPtr(value, _root->_type), _root->_type.len);
col_val->string_val.swap(tmp);
col_val->__isset.string_val = true;
break;
case TYPE_TIMESTAMP:
RawValue::print_value(
value, _root->_type, _root->_output_scale_, &col_val->string_val);
col_val->__isset.string_val = true;
break;
#endif
default:
DCHECK(false) << "bad get_value() type: " << _root->_type;
}
#endif
}
void* ExprContext::get_value(TupleRow* row) {
if (_root->is_slotref()) {
return SlotRef::get_value(_root, row);
}
return get_value(_root, row);
}
bool ExprContext::is_nullable() {
if (_root->is_slotref()) {
return SlotRef::is_nullable(_root);
}
return false;
}
void* ExprContext::get_value(Expr* e, TupleRow* row) {
switch (e->_type.type) {
case TYPE_NULL: {
return NULL;
}
case TYPE_BOOLEAN: {
palo_udf::BooleanVal v = e->get_boolean_val(this, row);
if (v.is_null) {
return NULL;
}
_result.bool_val = v.val;
return &_result.bool_val;
}
case TYPE_TINYINT: {
palo_udf::TinyIntVal v = e->get_tiny_int_val(this, row);
if (v.is_null) {
return NULL;
}
_result.tinyint_val = v.val;
return &_result.tinyint_val;
}
case TYPE_SMALLINT: {
palo_udf::SmallIntVal v = e->get_small_int_val(this, row);
if (v.is_null) {
return NULL;
}
_result.smallint_val = v.val;
return &_result.smallint_val;
}
case TYPE_INT: {
palo_udf::IntVal v = e->get_int_val(this, row);
if (v.is_null) {
return NULL;
}
_result.int_val = v.val;
return &_result.int_val;
}
case TYPE_BIGINT: {
palo_udf::BigIntVal v = e->get_big_int_val(this, row);
if (v.is_null) {
return NULL;
}
_result.bigint_val = v.val;
return &_result.bigint_val;
}
case TYPE_LARGEINT: {
palo_udf::LargeIntVal v = e->get_large_int_val(this, row);
if (v.is_null) {
return NULL;
}
_result.large_int_val = v.val;
return &_result.large_int_val;
}
case TYPE_FLOAT: {
palo_udf::FloatVal v = e->get_float_val(this, row);
if (v.is_null) {
return NULL;
}
_result.float_val = v.val;
return &_result.float_val;
}
case TYPE_DOUBLE: {
palo_udf::DoubleVal v = e->get_double_val(this, row);
if (v.is_null) {
return NULL;
}
_result.double_val = v.val;
return &_result.double_val;
}
case TYPE_CHAR:
case TYPE_VARCHAR:
case TYPE_HLL: {
palo_udf::StringVal v = e->get_string_val(this, row);
if (v.is_null) {
return NULL;
}
_result.string_val.ptr = reinterpret_cast<char*>(v.ptr);
_result.string_val.len = v.len;
return &_result.string_val;
}
#if 0
case TYPE_CHAR: {
palo_udf::StringVal v = e->get_string_val(this, row);
if (v.is_null) {
return NULL;
}
_result.string_val.ptr = reinterpret_cast<char*>(v.ptr);
_result.string_val.len = v.len;
if (e->_type.IsVarLenStringType()) {
return &_result.string_val;
} else {
return _result.string_val.ptr;
}
}
#endif
case TYPE_DATE:
case TYPE_DATETIME: {
palo_udf::DateTimeVal v = e->get_datetime_val(this, row);
if (v.is_null) {
return NULL;
}
_result.datetime_val = DateTimeValue::from_datetime_val(v);
return &_result.datetime_val;
}
case TYPE_DECIMAL: {
DecimalVal v = e->get_decimal_val(this, row);
if (v.is_null) {
return NULL;
}
_result.decimal_val = DecimalValue::from_decimal_val(v);
return &_result.decimal_val;
}
#if 0
case TYPE_ARRAY:
case TYPE_MAP: {
palo_udf::ArrayVal v = e->GetArrayVal(this, row);
if (v.is_null) return NULL;
_result.array_val.ptr = v.ptr;
_result.array_val.num_tuples = v.num_tuples;
return &_result.array_val;
}
#endif
default:
DCHECK(false) << "Type not implemented: " << e->_type;
return NULL;
}
}
void ExprContext::print_value(TupleRow* row, std::string* str) {
RawValue::print_value(get_value(row), _root->type(), _root->_output_scale, str);
}
void ExprContext::print_value(void* value, std::string* str) {
RawValue::print_value(value, _root->type(), _root->_output_scale, str);
}
void ExprContext::print_value(void* value, std::stringstream* stream) {
RawValue::print_value(value, _root->type(), _root->_output_scale, stream);
}
void ExprContext::print_value(TupleRow* row, std::stringstream* stream) {
RawValue::print_value(get_value(row), _root->type(), _root->_output_scale, stream);
}
BooleanVal ExprContext::get_boolean_val(TupleRow* row) {
return _root->get_boolean_val(this, row);
}
TinyIntVal ExprContext::get_tiny_int_val(TupleRow* row) {
return _root->get_tiny_int_val(this, row);
}
SmallIntVal ExprContext::get_small_int_val(TupleRow* row) {
return _root->get_small_int_val(this, row);
}
IntVal ExprContext::get_int_val(TupleRow* row) {
return _root->get_int_val(this, row);
}
BigIntVal ExprContext::get_big_int_val(TupleRow* row) {
return _root->get_big_int_val(this, row);
}
FloatVal ExprContext::get_float_val(TupleRow* row) {
return _root->get_float_val(this, row);
}
DoubleVal ExprContext::get_double_val(TupleRow* row) {
return _root->get_double_val(this, row);
}
StringVal ExprContext::get_string_val(TupleRow* row) {
return _root->get_string_val(this, row);
}
// TODO(zc)
// ArrayVal ExprContext::GetArrayVal(TupleRow* row) {
// return _root->GetArrayVal(this, row);
// }
DateTimeVal ExprContext::get_datetime_val(TupleRow* row) {
return _root->get_datetime_val(this, row);
}
DecimalVal ExprContext::get_decimal_val(TupleRow* row) {
return _root->get_decimal_val(this, row);
}
}
| {
"content_hash": "646e38f9f3e80a0e3984a35a57ddc004",
"timestamp": "",
"source": "github",
"line_count": 414,
"max_line_length": 95,
"avg_line_length": 30.497584541062803,
"alnum_prop": 0.5799144622208142,
"repo_name": "lingbin/palo",
"id": "594a3962c8ac93a9a7a626b8d91ab40b21e14ecb",
"size": "13825",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "be/src/exprs/expr_context.cpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "434038"
},
{
"name": "C++",
"bytes": "9318216"
},
{
"name": "CMake",
"bytes": "59815"
},
{
"name": "CSS",
"bytes": "3843"
},
{
"name": "Java",
"bytes": "6152346"
},
{
"name": "JavaScript",
"bytes": "5625"
},
{
"name": "Lex",
"bytes": "28991"
},
{
"name": "Makefile",
"bytes": "9065"
},
{
"name": "Python",
"bytes": "124341"
},
{
"name": "Shell",
"bytes": "32156"
},
{
"name": "Thrift",
"bytes": "168087"
},
{
"name": "Yacc",
"bytes": "97015"
}
],
"symlink_target": ""
} |
set -e
ROOTDIR=$(dirname "$0")/..
TARGET="${TARGET:-"//:scion"}"
bazel build $TARGET
DSTDIR=${1:-$ROOTDIR/licenses/data}
EXECROOT=$(bazel info execution_root 2>/dev/null)
rm -rf $DSTDIR
(cd $EXECROOT/external; find -L . -iregex '.*\(LICENSE\|COPYING\).*') | while IFS= read -r path ; do
dst=$DSTDIR/$(dirname $path)
mkdir -p $dst
cp $EXECROOT/external/$path $dst
done
# Bazel tools are used only for building.
# We don't need these licenses to be distributed with the containers.
rm -rf $DSTDIR/bazel_tools
# These are not actual licenses.
rm -rf $DSTDIR/com_github_spf13_cobra/cobra
rm -rf $DSTDIR/com_github_uber_jaeger_client_go/scripts
rm -rf $DSTDIR/com_github_uber_jaeger_lib/scripts
rm -rf $DSTDIR/com_github_prometheus_procfs/scripts
rm -rf $DSTDIR/org_uber_go_zap/checklicense.sh
| {
"content_hash": "985c8511626f28549f5bdfe2a652ad9e",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 100,
"avg_line_length": 28.857142857142858,
"alnum_prop": 0.7091584158415841,
"repo_name": "Oncilla/scion",
"id": "41510f46599c524c877a4c59b1c1d5a3de5ce356",
"size": "821",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tools/licenses.sh",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "1823"
},
{
"name": "Cap'n Proto",
"bytes": "21118"
},
{
"name": "Dockerfile",
"bytes": "1131"
},
{
"name": "Go",
"bytes": "3882939"
},
{
"name": "Lua",
"bytes": "28958"
},
{
"name": "Makefile",
"bytes": "2863"
},
{
"name": "Python",
"bytes": "138023"
},
{
"name": "Ruby",
"bytes": "2895"
},
{
"name": "Shell",
"bytes": "96267"
},
{
"name": "Standard ML",
"bytes": "936"
},
{
"name": "Starlark",
"bytes": "268566"
}
],
"symlink_target": ""
} |
http://ssokurenko.github.io/iphone-chats-app/
## Screenshot
![iphone chats screenshot][iphone]
[iphone]: /image_src/iphone-chats.png "iphone chats screenshot"
## Usage
1. Press the home button to reset
2. Type a message text to the input field and press enter or click the "Send" button
3. Create some messages
4. When ready press the camera button at the left of the input field to take the screenshot
5. Right click on the screenshot image for saving it using the "Save image as..." command
Optionally you could redefine the Carrier ("Telenor") and the Sender ("Friend") values by clicking the items
## Build instructions
1. Clone the project
2. Open the project folder
```
cd iphone-chats
```
3. Update dependencies
```
sudo npm update
bower update
```
4. Build the app (compressed code will be available in the dist folder)
```
grunt build
``` | {
"content_hash": "c4ceba45a1ef9d50017672dc91828b3e",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 108,
"avg_line_length": 29.7,
"alnum_prop": 0.7171717171717171,
"repo_name": "ssokurenko/iphone-chats-app",
"id": "306fe63a6fd6896c0b6efc98dd9f62c623031c12",
"size": "940",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "24139"
},
{
"name": "CSS",
"bytes": "9261"
},
{
"name": "HTML",
"bytes": "9327"
},
{
"name": "JavaScript",
"bytes": "242811"
}
],
"symlink_target": ""
} |
<?php
namespace Zend\Math;
use RandomLib;
/**
* Pseudorandom number generator (PRNG)
*/
abstract class Rand
{
/**
* Alternative random byte generator using RandomLib
*
* @var RandomLib\Generator
*/
protected static $generator = null;
/**
* Generate random bytes using OpenSSL or Mcrypt and mt_rand() as fallback
*
* @param int $length
* @param bool $strong true if you need a strong random generator (cryptography)
* @return string
* @throws Exception\RuntimeException
*/
public static function getBytes($length, $strong = false)
{
if ($length <= 0) {
return false;
}
$bytes = '';
if (function_exists('openssl_random_pseudo_bytes')
&& (version_compare(PHP_VERSION, '5.3.4') >= 0
|| strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN')
) {
$bytes = openssl_random_pseudo_bytes($length, $usable);
if (true === $usable) {
return $bytes;
}
}
if (function_exists('mcrypt_create_iv')
&& (version_compare(PHP_VERSION, '5.3.7') >= 0
|| strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN')
) {
$bytes = mcrypt_create_iv($length, MCRYPT_DEV_URANDOM);
if ($bytes !== false && strlen($bytes) === $length) {
return $bytes;
}
}
$checkAlternatives = (file_exists('/dev/urandom') && is_readable('/dev/urandom'))
|| class_exists('\\COM', false);
if (true === $strong && false === $checkAlternatives) {
throw new Exception\RuntimeException (
'This PHP environment doesn\'t support secure random number generation. ' .
'Please consider installing the OpenSSL and/or Mcrypt extensions'
);
}
$generator = self::getAlternativeGenerator();
return $generator->generate($length);
}
/**
* Retrieve a fallback/alternative RNG generator
*
* @return RandomLib\Generator
*/
public static function getAlternativeGenerator()
{
if (!is_null(self::$generator)) {
return self::$generator;
}
if (!class_exists('RandomLib\\Factory')) {
throw new Exception\RuntimeException(
'The RandomLib fallback pseudorandom number generator (PRNG) '
. ' must be installed in the absence of the OpenSSL and '
. 'Mcrypt extensions'
);
}
$factory = new RandomLib\Factory;
$factory->registerSource(
'HashTiming',
'Zend\Math\Source\HashTiming'
);
self::$generator = $factory->getMediumStrengthGenerator();
return self::$generator;
}
/**
* Generate random boolean
*
* @param bool $strong true if you need a strong random generator (cryptography)
* @return bool
*/
public static function getBoolean($strong = false)
{
$byte = static::getBytes(1, $strong);
return (bool) (ord($byte) % 2);
}
/**
* Generate a random integer between $min and $max
*
* @param int $min
* @param int $max
* @param bool $strong true if you need a strong random generator (cryptography)
* @return int
* @throws Exception\DomainException
*/
public static function getInteger($min, $max, $strong = false)
{
if ($min > $max) {
throw new Exception\DomainException(
'The min parameter must be lower than max parameter'
);
}
$range = $max - $min;
if ($range == 0) {
return $max;
} elseif ($range > PHP_INT_MAX || is_float($range)) {
throw new Exception\DomainException(
'The supplied range is too great to generate'
);
}
$log = log($range, 2);
$bytes = (int) ($log / 8) + 1;
$bits = (int) $log + 1;
$filter = (int) (1 << $bits) - 1;
do {
$rnd = hexdec(bin2hex(self::getBytes($bytes, $strong)));
$rnd = $rnd & $filter;
} while ($rnd > $range);
return ($min + $rnd);
}
/**
* Generate random float (0..1)
* This function generates floats with platform-dependent precision
*
* PHP uses double precision floating-point format (64-bit) which has
* 52-bits of significand precision. We gather 7 bytes of random data,
* and we fix the exponent to the bias (1023). In this way we generate
* a float of 1.mantissa.
*
* @param bool $strong true if you need a strong random generator (cryptography)
* @return float
*/
public static function getFloat($strong = false)
{
$bytes = static::getBytes(7, $strong);
$bytes[6] = $bytes[6] | chr(0xF0);
$bytes .= chr(63); // exponent bias (1023)
list(, $float) = unpack('d', $bytes);
return ($float - 1);
}
/**
* Generate a random string of specified length.
*
* Uses supplied character list for generating the new string.
* If no character list provided - uses Base 64 character set.
*
* @param int $length
* @param string|null $charlist
* @param bool $strong true if you need a strong random generator (cryptography)
* @return string
* @throws Exception\DomainException
*/
public static function getString($length, $charlist = null, $strong = false)
{
if ($length < 1) {
throw new Exception\DomainException('Length should be >= 1');
}
// charlist is empty or not provided
if (empty($charlist)) {
$numBytes = ceil($length * 0.75);
$bytes = static::getBytes($numBytes, $strong);
return substr(rtrim(base64_encode($bytes), '='), 0, $length);
}
$listLen = strlen($charlist);
if ($listLen == 1) {
return str_repeat($charlist, $length);
}
$bytes = static::getBytes($length, $strong);
$pos = 0;
$result = '';
for ($i = 0; $i < $length; $i++) {
$pos = ($pos + ord($bytes[$i])) % $listLen;
$result .= $charlist[$pos];
}
return $result;
}
}
| {
"content_hash": "b34df15527e094e8773ffa64ac425749",
"timestamp": "",
"source": "github",
"line_count": 202,
"max_line_length": 91,
"avg_line_length": 32.48019801980198,
"alnum_prop": 0.5206523395823808,
"repo_name": "trivan/ZF2-Dynamic-Routing",
"id": "393a64ce25b89d3b76ba32dcf4b668d9050821dc",
"size": "6869",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "vendor/ZF2/library/Zend/Math/Rand.php",
"mode": "33261",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "137753"
},
{
"name": "JavaScript",
"bytes": "58458"
},
{
"name": "PHP",
"bytes": "10781"
},
{
"name": "Perl",
"bytes": "175"
}
],
"symlink_target": ""
} |
<!doctype html public "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html>
<head>
<title>PHPXRef 0.7.1 : Unnamed Project : Variable Reference: $packet</title>
<link rel="stylesheet" href="../sample.css" type="text/css">
<link rel="stylesheet" href="../sample-print.css" type="text/css" media="print">
<style id="hilight" type="text/css"></style>
<meta http-equiv="content-type" content="text/html;charset=iso-8859-1">
</head>
<body bgcolor="#ffffff" text="#000000" link="#801800" vlink="#300540" alink="#ffffff">
<table class="pagetitle" width="100%">
<tr>
<td valign="top" class="pagetitle">
[ <a href="../index.html">Index</a> ]
</td>
<td align="right" class="pagetitle">
<h2 style="margin-bottom: 0px">PHP Cross Reference of Unnamed Project</h2>
</td>
</tr>
</table>
<!-- Generated by PHPXref 0.7.1 at Thu Oct 23 19:15:14 2014 -->
<!-- PHPXref (c) 2000-2010 Gareth Watts - [email protected] -->
<!-- http://phpxref.sourceforge.net/ -->
<script src="../phpxref.js" type="text/javascript"></script>
<script language="JavaScript" type="text/javascript">
<!--
ext='.html';
relbase='../';
subdir='_variables';
filename='index.html';
cookiekey='phpxref';
handleNavFrame(relbase, subdir, filename);
logVariable('packet');
// -->
</script>
<script language="JavaScript" type="text/javascript">
if (gwGetCookie('xrefnav')=='off')
document.write('<p class="navlinks">[ <a href="javascript:navOn()">Show Explorer<\/a> ]<\/p>');
else
document.write('<p class="navlinks">[ <a href="javascript:navOff()">Hide Explorer<\/a> ]<\/p>');
</script>
<noscript>
<p class="navlinks">
[ <a href="../nav.html" target="_top">Show Explorer</a> ]
[ <a href="index.html" target="_top">Hide Navbar</a> ]
</p>
</noscript>
[<a href="../index.html">Top level directory</a>]<br>
<script language="JavaScript" type="text/javascript">
<!--
document.writeln('<table align="right" class="searchbox-link"><tr><td><a class="searchbox-link" href="javascript:void(0)" onMouseOver="showSearchBox()">Search</a><br>');
document.writeln('<table border="0" cellspacing="0" cellpadding="0" class="searchbox" id="searchbox">');
document.writeln('<tr><td class="searchbox-title">');
document.writeln('<a class="searchbox-title" href="javascript:showSearchPopup()">Search History +</a>');
document.writeln('<\/td><\/tr>');
document.writeln('<tr><td class="searchbox-body" id="searchbox-body">');
document.writeln('<form name="search" style="margin:0px; padding:0px" onSubmit=\'return jump()\'>');
document.writeln('<a class="searchbox-body" href="../_classes/index.html">Class<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="classname"><br>');
document.writeln('<a id="funcsearchlink" class="searchbox-body" href="../_functions/index.html">Function<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="funcname"><br>');
document.writeln('<a class="searchbox-body" href="../_variables/index.html">Variable<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="varname"><br>');
document.writeln('<a class="searchbox-body" href="../_constants/index.html">Constant<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="constname"><br>');
document.writeln('<a class="searchbox-body" href="../_tables/index.html">Table<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="tablename"><br>');
document.writeln('<input type="submit" class="searchbox-button" value="Search">');
document.writeln('<\/form>');
document.writeln('<\/td><\/tr><\/table>');
document.writeln('<\/td><\/tr><\/table>');
// -->
</script>
<div id="search-popup" class="searchpopup"><p id="searchpopup-title" class="searchpopup-title">title</p><div id="searchpopup-body" class="searchpopup-body">Body</div><p class="searchpopup-close"><a href="javascript:gwCloseActive()">[close]</a></p></div>
<h3>Variable Cross Reference</h3>
<h2><a href="index.html#packet">$packet</a></h2>
<br><b>Referenced 4 times:</b><ul>
<li><a href="../tests/simpletest/http.php.html">/tests/simpletest/http.php</a> -> <a href="../tests/simpletest/http.php.source.html#l621"> line 621</a></li>
<li><a href="../tests/simpletest/http.php.html">/tests/simpletest/http.php</a> -> <a href="../tests/simpletest/http.php.source.html#l622"> line 622</a></li>
<li><a href="../tests/simpletest/http.php.html">/tests/simpletest/http.php</a> -> <a href="../tests/simpletest/http.php.source.html#l623"> line 623</a></li>
<li><a href="../tests/simpletest/http.php.html">/tests/simpletest/http.php</a> -> <a href="../tests/simpletest/http.php.source.html#l625"> line 625</a></li>
</ul>
<!-- A link to the phpxref site in your customized footer file is appreciated ;-) -->
<br><hr>
<table width="100%">
<tr><td>Generated: Thu Oct 23 19:15:14 2014</td>
<td align="right"><i>Cross-referenced by <a href="http://phpxref.sourceforge.net/">PHPXref 0.7.1</a></i></td>
</tr>
</table>
</body></html>
| {
"content_hash": "3a408ec11c4fdb26fabf086b4c9af43c",
"timestamp": "",
"source": "github",
"line_count": 96,
"max_line_length": 253,
"avg_line_length": 51.916666666666664,
"alnum_prop": 0.6663322632423756,
"repo_name": "inputx/code-ref-doc",
"id": "c493aba14bc93da2c745fa88f171288c32d8b480",
"size": "4984",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "rebbit/_variables/packet.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "17952"
},
{
"name": "JavaScript",
"bytes": "255489"
}
],
"symlink_target": ""
} |
{% if site.owner.disqus-shortname %}
<script type="text/javascript">
/* * * CONFIGURATION VARIABLES: EDIT BEFORE PASTING INTO YOUR WEBPAGE * * */
//var disqus_shortname = 'leopoemaepapel'; // required: replace example with your forum shortname
var disqus_shortname = '{{ site.owner.disqus-shortname }}'; // required: replace example with your forum
/* * * DON'T EDIT BELOW THIS LINE * * */
(function() {
var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
/* * * DON'T EDIT BELOW THIS LINE * * */
(function () {
var s = document.createElement('script'); s.async = true;
s.type = 'text/javascript';
s.src = '//' + disqus_shortname + '.disqus.com/count.js';
(document.getElementsByTagName('HEAD')[0] || document.getElementsByTagName('BODY')[0]).appendChild(s);
}());
</script>
<noscript>Please enable JavaScript to view the <a href="http://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
<a href="http://disqus.com" class="dsq-brlink">comments powered by <span class="logo-disqus">Disqus</span></a>
{% endif %} | {
"content_hash": "a922f165d87fcd6a188af1ab14622102",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 131,
"avg_line_length": 53.4,
"alnum_prop": 0.6449438202247191,
"repo_name": "leopoemaepapel/leopoemaepapel.github.io",
"id": "bf765514bacacb22daf9a1e1e25c99942abc3ddf",
"size": "1335",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "_includes/disqus_comments.html",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "45409"
},
{
"name": "JavaScript",
"bytes": "150625"
},
{
"name": "PHP",
"bytes": "312"
},
{
"name": "Ruby",
"bytes": "2157"
}
],
"symlink_target": ""
} |
package kvq
import (
"sync"
"testing"
"time"
"github.com/johnsto/go-kvq/kvq/backend"
"github.com/johnsto/go-kvq/kvq/internal"
"github.com/stretchr/testify/assert"
)
type MockBucket struct {
mutex sync.Mutex
data map[string][]byte
}
func NewMockBucket() *MockBucket {
return &MockBucket{
data: map[string][]byte{},
}
}
func (b *MockBucket) ForEach(fn func(k, v []byte) error) error {
b.mutex.Lock()
defer b.mutex.Unlock()
for k, v := range b.data {
if err := fn([]byte(k), v); err != nil {
return err
}
}
return nil
}
func (b *MockBucket) Batch(fn func(backend.Batch) error) error {
b.mutex.Lock()
defer b.mutex.Unlock()
batch := NewMockBatch()
if err := fn(batch); err != nil {
return err
}
for k, v := range batch.puts {
b.data[k] = v
}
for k, _ := range batch.deletes {
delete(b.data, k)
}
return nil
}
func (b *MockBucket) Get(k []byte) ([]byte, error) {
b.mutex.Lock()
defer b.mutex.Unlock()
return b.data[string(k)], nil
}
func (b *MockBucket) Clear() error {
b.mutex.Lock()
defer b.mutex.Unlock()
b.data = map[string][]byte{}
return nil
}
type MockBatch struct {
puts map[string][]byte
deletes map[string]bool
}
func NewMockBatch() *MockBatch {
return &MockBatch{
puts: map[string][]byte{},
deletes: map[string]bool{},
}
}
func (m *MockBatch) Put(k, v []byte) error {
m.puts[string(k)] = v
return nil
}
func (m *MockBatch) Delete(k []byte) error {
m.deletes[string(k)] = true
return nil
}
func (m *MockBatch) Close() {
m.puts = map[string][]byte{}
m.deletes = map[string]bool{}
}
func Test_Queue_Internals(t *testing.T) {
bucket := NewMockBucket()
queue := &Queue{
bucket: bucket,
mutex: &sync.Mutex{},
ids: internal.NewIDHeap(),
c: make(chan struct{}, 3),
}
// Test initial (empty) state
assert.Equal(t, 0, queue.Size(), "queue should be empty")
assert.Empty(t, queue.getKeys(1),
"queue should not immediately return any keys")
assert.Empty(t, queue.awaitKeys(1, 0),
"queue should not eventually return any keys")
assert.Empty(t, queue.awaitKeys(1, 50*time.Millisecond),
"queue should not eventually return any keys")
// Clear and check still empty
assert.NoError(t, queue.Clear())
assert.Equal(t, 0, queue.Size(), "queue should be empty after clear")
assert.Empty(t, queue.getKeys(1),
"queue should not immediately return any keys after clear")
assert.Empty(t, queue.awaitKeys(1, 50*time.Millisecond),
"queue should not eventually return any keys after clear")
// Put an ID on the queue, check it becomes available
n, err := queue.putKey(internal.ID(1))
assert.Equal(t, 1, n)
assert.NoError(t, err)
assert.Equal(t, 1, queue.Size(), "queue should be of size 1")
assert.Len(t, queue.getKeys(1), 1,
"queue should immediately return 1 of requested 1 key")
n, err = queue.putKey(internal.ID(1))
assert.Equal(t, 1, n)
assert.NoError(t, err)
assert.Len(t, queue.awaitKeys(1, 50*time.Millisecond), 1,
"queue should not eventually return 1 of requested 1 key")
// Take more keys than actually available
n, err = queue.putKey(internal.ID(1))
assert.Equal(t, 1, n)
assert.NoError(t, err)
assert.Equal(t, 1, queue.Size(), "queue should be of size 1")
assert.Len(t, queue.getKeys(2), 1,
"queue should immediately return 1 of requested 2 keys")
n, err = queue.putKey(internal.ID(1))
assert.Equal(t, 1, n)
assert.NoError(t, err)
assert.Len(t, queue.awaitKeys(2, 50*time.Millisecond), 1,
"queue should not eventually return 1 of requested 2 keys")
// Put more keys than there is room available for
n, err = queue.putKey(internal.ID(1))
assert.Equal(t, 1, n)
assert.NoError(t, err)
assert.Equal(t, 1, queue.Size(), "queue should contain 1 key")
n, err = queue.putKey(internal.ID(2), internal.ID(3))
assert.Equal(t, 2, n)
assert.NoError(t, err)
assert.Equal(t, 3, queue.Size(), "queue should contain 3 keys")
n, err = queue.putKey(internal.ID(2), internal.ID(3))
assert.Equal(t, 0, n, "4th key should be rejected")
assert.Equal(t, err, ErrInsufficientCapacity,
"4th key should return capacity error")
assert.Equal(t, 3, queue.Size(), "queue should still contain 3 keys")
assert.Len(t, queue.getKeys(4), 3,
"queue should immediately return 3 of requested 4 keys")
// Enact a change to underlying bucket
kv1 := kv{[]byte("k1"), []byte("v1")}
kv2 := kv{[]byte("k2"), []byte("v2")}
kv3 := kv{[]byte("k3"), []byte("v3")}
assert.NoError(t, queue.enact([]kv{kv1, kv2, kv3}, nil),
"queue should enact puts s without error")
assert.EqualValues(t, "v1", bucket.data["k1"], "bucket should contain put kv1")
assert.EqualValues(t, "v2", bucket.data["k2"], "bucket should contain put kv2")
assert.EqualValues(t, "v3", bucket.data["k3"], "bucket should contain put kv3")
assert.NoError(t, queue.enact(nil, []kv{kv1, kv2, kv3}),
"queue should enact takes without error")
assert.Nil(t, bucket.data["k1"], "bucket should no longer contain kv1")
assert.Nil(t, bucket.data["k2"], "bucket should no longer contain kv2")
assert.Nil(t, bucket.data["k3"], "bucket should no longer contain kv3")
// Take keys
kv1 = kv{internal.ID(1).Key(), []byte("v1")}
kv2 = kv{internal.ID(2).Key(), []byte("v2")}
kv3 = kv{internal.ID(3).Key(), []byte("v3")}
assert.NoError(t, queue.enact([]kv{kv1, kv2}, nil),
"queue should enact puts without error")
n, err = queue.putKey(internal.ID(1), internal.ID(2), internal.ID(3))
assert.Equal(t, 3, n, "3 keys should be accepted")
assert.NoError(t, err)
n, err = queue.putKey(internal.ID(4))
assert.Equal(t, 0, n, "4th key should be rejected")
ids, keys, values, err := queue.take(2, 0)
assert.NoError(t, err, "take should not error")
assert.Equal(t, []internal.ID{internal.ID(1), internal.ID(2)}, ids)
assert.Equal(t, [][]byte{internal.ID(1).Key(), internal.ID(2).Key()}, keys)
assert.Equal(t, [][]byte{kv1.v, kv2.v}, values)
}
func Test_Queue_Transaction(t *testing.T) {
bucket := NewMockBucket()
queue := &Queue{
bucket: bucket,
mutex: &sync.Mutex{},
ids: internal.NewIDHeap(),
c: make(chan struct{}, 3),
}
// Create and close txn
txn := queue.Transaction()
assert.NoError(t, txn.Close(), "txn should close without error")
// Create, put and close txn
txn = queue.Transaction()
assert.NoError(t, txn.Put([]byte("v1")), "txn put should not error")
assert.Equal(t, 0, queue.ids.Len(), "queue should remain empty before commit")
assert.Equal(t, 1, txn.puts.Len(), "txn should contain 1 put ID")
assert.Len(t, txn.putValues, 1, "txn should contain 1 put value")
assert.NoError(t, txn.Close(), "txn should close without error")
assert.Equal(t, 0, txn.puts.Len(), "txn should be empty after close")
assert.Len(t, txn.putValues, 0, "txn should contain 1 put value")
// Create, put, take and close txn
txn = queue.Transaction()
assert.NoError(t, txn.Put([]byte("v1")), "txn put should not error")
assert.Equal(t, 0, queue.ids.Len(), "queue should remain empty before commit")
v, err := txn.Take()
assert.NoError(t, err, "txn take should not error")
assert.Nil(t, v, "put value should not be taken from txn")
assert.NoError(t, txn.Close(), "txn should close without error")
// Create and commit txn
txn = queue.Transaction()
assert.NoError(t, txn.Put([]byte("v1")), "txn put should not error")
assert.Equal(t, 0, queue.ids.Len(),
"queue should remain empty before commit")
v, err = txn.Take()
assert.NoError(t, err, "txn take should not error")
assert.Nil(t, v, "put value should not be taken from txn")
assert.NoError(t, txn.Commit(), "txn should commit without error")
assert.Equal(t, 1, queue.ids.Len(),
"queue should contain single item after commit")
assert.NoError(t, txn.Commit(), "empty txn should commit without error")
assert.Equal(t, 1, queue.ids.Len(),
"queue should still contain single item after empty commit")
v, err = txn.Take()
assert.NoError(t, err, "txn take should not error")
assert.Equal(t, []byte("v1"), v, "taken value should match put value")
assert.NoError(t, txn.Commit(), "txn should commit without error")
assert.Equal(t, 0, queue.ids.Len(), "queue should be empty after take")
// Create and take exact number of available items
txn = queue.Transaction()
assert.NoError(t, txn.Put([]byte("v1")), "txn put should not error")
assert.NoError(t, txn.Put([]byte("v2")), "txn put should not error")
assert.NoError(t, txn.Commit(), "commit without error")
vs, err := txn.TakeN(2, time.Minute)
assert.NoError(t, err, "take 2 within 1 minute should be without error")
assert.EqualValues(t, vs, [][]byte{[]byte("v1"), []byte("v2")})
// Create and commit excessive txn
txn = queue.Transaction()
assert.NoError(t, txn.Put([]byte("v1")), "txn put should not error")
assert.NoError(t, txn.Put([]byte("v2")), "txn put should not error")
assert.NoError(t, txn.Put([]byte("v3")), "txn put should not error")
assert.NoError(t, txn.Put([]byte("v4")), "txn put should not error")
assert.EqualError(t, txn.Commit(), "insufficient queue capacity",
"txn put should fail with insufficient capacity")
}
| {
"content_hash": "76e9b7a3ef136b7a0b3bd09ecd1c1645",
"timestamp": "",
"source": "github",
"line_count": 262,
"max_line_length": 80,
"avg_line_length": 34.30534351145038,
"alnum_prop": 0.6779038718291055,
"repo_name": "johnsto/go-kvq",
"id": "dc2e96f30dd479c7e92a5a96fe7103e7d6271536",
"size": "8988",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "kvq/txn_test.go",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Go",
"bytes": "45243"
}
],
"symlink_target": ""
} |
import { Meteor } from 'meteor/meteor';
import { TemplateRenderer } from './../server_side_templates/TemplateRenderer';
import { MailFactory } from './MailFactory';
import { GlobalSettings } from '../config/GlobalSettings';
import { InfoItemFactory } from '../InfoItemFactory';
import { Topic } from '../topic';
export class TopicItemsMailHandler {
constructor(sender, recipients, minute, templateName) {
this._recipients = recipients;
this._sender = sender;
this._minute = minute;
this._templateName = templateName;
this._currentRecipient = '';
this._sendOneMailToAllRecipients = GlobalSettings.isTrustedIntranetInstallation();
}
send() {
if (this._sendOneMailToAllRecipients) {
this._currentRecipient = this._recipients;
this._sendMail();
this._mailer = null;
} else {
this._recipients.forEach((recipient) => {
this._currentRecipient = recipient;
this._sendMail();
this._mailer = null;
});
}
}
_sendMail() {
throw new Meteor.Error('illegal-state', 'abstract method _sendMail not implemented.');
}
_getCurrentMailAddress() {
if (typeof this._currentRecipient === 'string') {
return this._currentRecipient;
} else if (this._currentRecipient.hasOwnProperty('address')) {
return this._currentRecipient.address;
} else {
// we should send the mail to multiple recipients -> return array of strings
return this._currentRecipient.map(recipient => {
return (typeof recipient === 'string')
? recipient
: recipient.address;
});
}
}
_getSubject() {
return this._getSubjectPrefix();
}
_getSubjectPrefix() {
return '[' + this._minute.parentMeetingSeries().project + '] '
+ this._minute.parentMeetingSeries().name + ' on '
+ this._minute.date;
}
_buildMail(subject, emailData) {
this._getMailer().setSubject(subject);
let tmplRenderer = this._getTmplRenderer();
tmplRenderer.addDataObject(emailData);
let context = this;
tmplRenderer.addHelper('hasLabels', function() {
return (this.labels.length > 0);
});
tmplRenderer.addHelper('formatLabels', function(parentTopicId) {
let parentTopic = new Topic(context._minute, parentTopicId);
let infoItemId = this._id;
let infoItem = InfoItemFactory.createInfoItem(parentTopic, infoItemId);
let labels = infoItem.getLabels(context._minute.parentMeetingSeriesID());
let result = '';
let first = true;
labels.forEach(label => {
if (first) {
first = false;
} else {
result += ', ';
}
result += '#'+label.getName();
});
return result;
});
this._getMailer().setHtml(tmplRenderer.render());
this._getMailer().send();
}
_getTmplRenderer() {
let recipientsName = (this._currentRecipient.hasOwnProperty('name'))
? this._currentRecipient.name
: '';
return (new TemplateRenderer(this._templateName, 'server_templates/email')).addData('name', recipientsName);
}
_getMailer() {
if (!this._mailer) {
this._mailer = MailFactory.getMailer(this._sender, this._getCurrentMailAddress());
}
return this._mailer;
}
} | {
"content_hash": "986b770c84775c8640d29552ab511a50",
"timestamp": "",
"source": "github",
"line_count": 106,
"max_line_length": 116,
"avg_line_length": 34.56603773584906,
"alnum_prop": 0.5646834061135371,
"repo_name": "Huggle77/4minitz",
"id": "4a5972daaedc90214be24a9b945d5108de26c3b1",
"size": "3664",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "imports/mail/TopicItemsMailHandler.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "15287"
},
{
"name": "HTML",
"bytes": "195982"
},
{
"name": "JavaScript",
"bytes": "921129"
},
{
"name": "Shell",
"bytes": "9610"
}
],
"symlink_target": ""
} |
/**
* window.c.AdminExternalAction component
* Makes arbitrary ajax requests and update underlying
* data from source endpoint.
*
* Example:
* m.component(c.AdminExternalAction, {
* data: {},
* item: rowFromDatabase
* })
*/
import m from 'mithril';
import _ from 'underscore';
import h from '../h';
const adminExternalAction = {
controller(args) {
let builder = args.data,
complete = m.prop(false),
error = m.prop(false),
fail = m.prop(false),
data = {},
item = args.item;
builder.requestOptions.config = (xhr) => {
if (h.authenticityToken()) {
xhr.setRequestHeader('X-CSRF-Token', h.authenticityToken());
}
};
const reload = _.compose(builder.model.getRowWithToken, h.idVM.id(item[builder.updateKey]).parameters),
l = m.prop(false);
const reloadItem = () => reload().then(updateItem);
const requestError = (err) => {
l(false);
complete(true);
error(true);
};
const updateItem = (res) => {
_.extend(item, res[0]);
complete(true);
error(false);
};
const submit = () => {
l(true);
m.request(builder.requestOptions).then(reloadItem, requestError);
return false;
};
const unload = (el, isinit, context) => {
context.onunload = function() {
complete(false);
error(false);
};
};
return {
l: l,
complete: complete,
error: error,
submit: submit,
toggler: h.toggleProp(false, true),
unload: unload
};
},
view(ctrl, args) {
const data = args.data,
btnValue = (ctrl.l()) ? 'please wait...' : data.callToAction;
return m('.w-col.w-col-2', [
m('button.btn.btn-small.btn-terciary', {
onclick: ctrl.toggler.toggle
}, data.outerLabel), (ctrl.toggler()) ?
m('.dropdown-list.card.u-radius.dropdown-list-medium.zindex-10', {
config: ctrl.unload
}, [
m('form.w-form', {
onsubmit: ctrl.submit
}, (!ctrl.complete()) ? [
m('label', data.innerLabel),
m('input.w-button.btn.btn-small[type="submit"][value="' + btnValue + '"]')
] : (!ctrl.error()) ? [
m('.w-form-done[style="display:block;"]', [
m('p', 'Request successful.')
])
] : [
m('.w-form-error[style="display:block;"]', [
m('p', 'There was a problem with the request.')
])
])
]) : ''
]);
}
};
export default adminExternalAction;
| {
"content_hash": "86d530d6fa25d003840c861fa6321e48",
"timestamp": "",
"source": "github",
"line_count": 100,
"max_line_length": 111,
"avg_line_length": 29.7,
"alnum_prop": 0.463973063973064,
"repo_name": "mikesmayer/citizensupported_english.js",
"id": "0040fec5aff09e0b9b7817c7f37b1beceffaa71f",
"size": "2970",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/c/admin-external-action.js",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "4584"
},
{
"name": "JavaScript",
"bytes": "1180042"
}
],
"symlink_target": ""
} |
echo "Restoring BigQuery output"
cp data/data_top30_projects_20200101_20210101.csv data/unlimited.csv
echo "Adding Linux kernel data"
ruby add_linux.rb data/unlimited.csv data/data_linux.csv 2020-01-01 2021-01-01
# Don't forget to add exception to map/ranges.csv when adding projects pulled with different BigQuery (specially with 0s for issues, PRs etc)
echo "Adding/Updating CNCF Projects"
ruby merger.rb data/unlimited.csv data/data_cncf_projects_20200101_20210101.csv
#echo "Adding GitLab data"
#ruby add_external.rb data/unlimited.csv data/data_gitlab.csv 2020-01-01 2021-01-01 gitlab gitlab/GitLab
echo "Adding/Updating Cloud Foundry Projects"
# This uses "force" mode to update Cloud Foundry values to lower ones (this is because we have special query output for CF projects which skips more bots, so lower values are expected)
ruby merger.rb data/unlimited.csv data/data_cf_projects_20200101_20210101.csv force
#echo "Adding/Updating OpenStack case"
#ruby merger.rb data/unlimited.csv openstack/data_openstack_2020-01-01_2021-01-01.csv
echo "Adding/Updating Apache case"
ruby merger.rb data/unlimited.csv data/data_apache_projects_20200101_20210101.csv
#echo "Adding/Updating Chromium case"
#ruby merger.rb data/unlimited.csv data/data_chromium_projects_20200101_20210101.csv
echo "Adding/Updating OpenSUSE case"
ruby merger.rb data/unlimited.csv data/data_opensuse_projects_20200101_20210101.csv
echo "Adding/Updating AGL case"
ruby merger.rb data/unlimited.csv data/data_agl_projects_20200101_20210101.csv
#echo "Adding/Updating LibreOffice case"
#ruby merger.rb data/unlimited.csv data/data_libreoffice_projects_20200101_20210101.csv
echo "Adding/Updating FreeBSD case"
ruby merger.rb data/unlimited.csv data/data_freebsd_projects_20200101_20210101.csv
echo "Analysis"
# This is for merged OpenStack into a single project
cp map/defmaps.csv map/defmaps_oo.csv
cat map/defmaps_merged_openstack.csv >> map/defmaps_oo.csv
# ruby analysis.rb data/unlimited.csv projects/unlimited_both.csv map/hints.csv map/urls.csv map/defmaps.csv map/skip.csv map/ranges_sane.csv
ruby analysis.rb data/unlimited.csv projects/unlimited_both.csv map/hints.csv map/urls.csv map/defmaps_oo.csv map/skip.csv map/ranges_sane.csv
echo "Take some time for manual fixes in projects/unlimited_both.csv file"
read a
echo "Updating Apache Projects using Jira data"
ruby update_projects.rb projects/unlimited_both.csv data/data_apache_jira_20200101_20210101.csv -1
#echo "Updating OpenStack projects using their bug tracking data"
#ruby update_projects.rb projects/unlimited_both.csv data/data_openstack_bugs_20200101_20210101.csv -1
# This is for merged OpenStack into a single project
#ruby update_projects.rb projects/unlimited_both.csv data/data_openstack_bugs_20200101_20210101.csv -1
#echo "Updating Chromium project using their bug tracking data"
#ruby update_projects.rb projects/unlimited_both.csv data/data_chromium_bugtracker_20200101_20210101.csv -1
#echo "Updating LibreOffice project using their git repo"
#ruby update_projects.rb projects/unlimited_both.csv data/data_libreoffice_git_20200101_20210101.csv -1
echo "Updating FreeBSD data from SVN logs"
ruby update_projects.rb projects/unlimited_both.csv ./data/data_freebsd_svn_20200101_20210101.csv -1
echo "Prioritizing LF projects data"
PROJFMT=1 ruby update_projects.rb projects/unlimited_both.csv ./projects/projects_lf_20200101_20210101.csv -1
echo "Prioritizing CNCF projects data"
PROJFMT=1 ruby update_projects.rb projects/unlimited_both.csv ./projects/projects_cncf_20200101_20210101.csv -1
echo "Generating Projects Ranks statistics"
./shells/report_cncf_project_ranks.sh
./shells/report_other_project_ranks.sh
./report_top_projects.sh
echo "Truncating results to Top 500"
cat ./projects/unlimited_both.csv | head -n 501 > tmp && mv tmp ./projects/unlimited.csv
echo "Copying reports to a separate directory"
rm -rf ./reports/20200101_20210101
mkdir ./reports/20200101_20210101
cp projects/unlimited.csv ./reports/top_projects_by_*.txt ./reports/*_projects_ranks.txt ./reports/20200101_20210101/
echo "All done"
| {
"content_hash": "74a1e64a32323911e869f0279dc6aa88",
"timestamp": "",
"source": "github",
"line_count": 61,
"max_line_length": 184,
"avg_line_length": 66.67213114754098,
"alnum_prop": 0.8082124416031473,
"repo_name": "cncf/velocity",
"id": "82ebfe94377be81c2e89cd7e1560b1129311bd9a",
"size": "4077",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "shells/unlimited_20200101_20210101.sh",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "22812"
},
{
"name": "JavaScript",
"bytes": "808"
},
{
"name": "Python",
"bytes": "13833"
},
{
"name": "Ruby",
"bytes": "60142"
},
{
"name": "Shell",
"bytes": "78987"
}
],
"symlink_target": ""
} |
Editable Lists for Meteor
-------------------------
This package provides a widget for rendering the array (of strings) fields of documents as editable lists.
Example app: [http://editable-text-demo.meteor.com](http://editable-text-demo.meteor.com) (the tags on posts are editable lists)
Example app repo: [https://github.com/JackAdams/editable-text-demo](https://github.com/JackAdams/editable-text-demo)
Minimal example app: [Meteorpad](http://meteorpad.com/pad/yM49AHwC3yYrYCEqs/editable-list)
#### Quick Start
meteor add babrahams:editable-list
You can then drop an editable list widget into any Blaze template as follows:
{{> editableList collection="posts" field="tags"}}
where "posts" is the name of the mongo collection and "tags" is the name of a document field for the `posts` collection (this field is an array of strings).
`collection` and `field` are the only mandatory parameters.
Note: The widget assumes that the data context is that of a single document from the `posts` collection (with _id value included).
You can also set the data context explicitly as follows:
{{> editableList context=singlePostDocument collection="posts" field="author"}}
where `singlePostDocument` can be a single post document already set in the current context, or provided by a template helper from the template that the widget was dropped into.
(You can use `document`, `doc`, `object`, `obj`, `data` or `dataContext` instead of `context` - go with whichever you prefer.)
#### Options
There are a number of parameters you can pass to the widget that affect its behaviour:
`class="text-class"` will change the class attribute of the `span` element (inside the `li` element) that wraps the text of a list item
`style=dynamicStyle` can be used if you need to have more dynamic control over the style of the `span` elements wrapping editable list text (use a template helper to give the `dynamicStyle`) e.g.
dynamicStyle : function() {
return 'color:' + Session.get('currentColor') + ';';
}
To set a class/style on the `li` element of list items, use something like `liClass="my-list-item-class"` or `liStyle="margin: 5px 5px 0 0;"`. This is particularly useful for putting a margin on horizontal list items. (Don't set padding with these if you have a horizontal list -- it messes with the drag and drop. Set padding using `class=...` or `style=...`.)
Use `editStyle` or `editClass` to style the `input` element used to edit a list item.
`inputClass="input-class"` will change the class attribute of the `input` element once the text is being edited
`inputStyle=dynamicInputStyle` same as above, but for the `input` element used for adding list items
`userCanEdit=userCanEdit` is a way to tell the widget whether the current user can edit the text or only view it (using a template helper) e.g.
userCanEdit : function() {
return this.user_id === Meteor.userId();
}
(Of course, to make this work, you'll have to save your documents with a `user_id` field that has a value equal to Meteor.userId() of the creator.)
`placeholder="New post"` will be the placeholder for the `input` element that allows users to enter new items into the list
`saveOnFocusout=false` will prevent a particular widget instance from saving the text being edited on a `focusout` event (the default is to save the text, which can be changed via `EditableList.saveOnFocusout`)
`trustHTML=true` will make a particular widget instance render its text as HTML (default is `false`, which can be changed via `EditableList.trustHTML`)
`allowPasteMultiple=true` will mean that `\n` separated items being pasted into the input box will automatically become separate items in the list
`allowDuplicates=true` lets that user add items with identical text to the list (default is to not allow duplicates - i.e. use mongo's `$addToSet` rather than `$push`)
#### Configuration
You can change the behaviour of the widget by setting certain properties of `EditableText`, which is a variable exposed by `babrahams:editable-text` which this package builds upon.
#### Transactions
There is built-in support for the `babrahams:transactions` package, if you want everything to be undo/redo-able. To enable this:
meteor add babrahams:transactions
and in your app (in some config file on both client and server), add:
EditableText.useTransactions = true;
Or if you only want transactions on particular instances of the widget, pass `useTransaction=true` or `useTransaction=false` to override the default that was set via `EditableText.useTransactions`, but this will only work if you also set `EditableText.clientControlsTransactions=true` (by default it is `false`). If you set the `EditableText.useTransactions` value on the server, without changing `EditableText.clientControlsTransactions`, it doesn't matter what you set on the client (or pass from the client), you will always get the behaviour as set on the server.
__Note:__ you can set `objectTypeText="tag"` to make the transaction description say "added tag" instead of "added list item". (Replace "tag" with the name of whatever type of item is in the list.)
#### Security
To control whether certain users can edit text on certain documents/fields, you can (and _should_) overwrite the function `EditableText.userCanEdit` (which has the data used to initialize the widget as `this` and the document and collection as parameters). e.g. (to only allow users to edit their own documents):
EditableText.userCanEdit = function(doc,Collection) {
return doc.user_id === Meteor.userId();
}
Setting `EditableText.useMethods=false` will mean that all changes to documents are made on the client, so they are subject to the allow and deny rules you've defined for your collections. In this case, it is a good idea to make the `EditableText.userCanEdit` function and your allow and deny functions share the same logic to the greatest degree possible.
__Note:__ the default setting is `EditableText.useMethods=true`, meaning updates are processed server side and bypass your allow and deny rules. If you're happy with this (and you should be), then all you need to do for consistency between client and server permission checks is overwrite the `EditableText.userCanEdit` function in a file that is shared by both client and server. Note again that this function receives the widget data context as `this` and the document and collection as the parameters.
__Warning:__ if you set `EditableText.useMethods=false`, your data updates are being done on the client and you don't get html sanitization by default -- you'll have to sort this out or yourself via collection hooks or something. When `EditableText.useMethods=true` (the default setting) all data going into the database is passed through [htmlSantizer](https://github.com/punkave/sanitize-html).
__Bigger warning:__ it doesn't really matter what you set `EditableText.useMethods` to -- you still need to lock down your collections using appropriate `allow` and `deny` rules. A malicious user can just type `EditableText.useMethods=false` into the browser console and this package will start making client side changes that are persisted or not entirely on the basis of your `allow` and `deny` rules. | {
"content_hash": "36885869eeb35a50623bc4868eb42005",
"timestamp": "",
"source": "github",
"line_count": 104,
"max_line_length": 567,
"avg_line_length": 69.46153846153847,
"alnum_prop": 0.767718715393134,
"repo_name": "rclai/meteor-editable-list",
"id": "5b9b7cca65e1f215caa8ca71cc463abe095a578b",
"size": "7224",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "419"
},
{
"name": "HTML",
"bytes": "2479"
},
{
"name": "JavaScript",
"bytes": "9291"
}
],
"symlink_target": ""
} |
namespace remoting {
BackoffTimer::BackoffTimer() = default;
BackoffTimer::~BackoffTimer() = default;
void BackoffTimer::Start(const base::Location& posted_from,
base::TimeDelta delay,
base::TimeDelta max_delay,
const base::RepeatingClosure& user_task) {
backoff_policy_.multiply_factor = 2;
backoff_policy_.initial_delay_ms = delay.InMilliseconds();
backoff_policy_.maximum_backoff_ms = max_delay.InMilliseconds();
backoff_policy_.entry_lifetime_ms = -1;
backoff_entry_ = std::make_unique<net::BackoffEntry>(&backoff_policy_);
posted_from_ = posted_from;
user_task_ = user_task;
StartTimer();
}
void BackoffTimer::Stop() {
timer_.Stop();
user_task_.Reset();
backoff_entry_.reset();
}
void BackoffTimer::StartTimer() {
timer_.Start(
posted_from_, backoff_entry_->GetTimeUntilRelease(),
base::BindOnce(&BackoffTimer::OnTimerFired, base::Unretained(this)));
}
void BackoffTimer::OnTimerFired() {
DCHECK(IsRunning());
DCHECK(!user_task_.is_null());
backoff_entry_->InformOfRequest(false);
StartTimer();
// Running the user task may destroy this object, so don't reference
// any fields of this object after running it.
base::RepeatingClosure user_task(user_task_);
user_task.Run();
}
} // namespace remoting
| {
"content_hash": "964e9c7585c7ca2a37c5e326324fe4d5",
"timestamp": "",
"source": "github",
"line_count": 46,
"max_line_length": 75,
"avg_line_length": 29.17391304347826,
"alnum_prop": 0.6698956780923994,
"repo_name": "nwjs/chromium.src",
"id": "e4046e7ccab4378d0718a35b3ffd843e36cf1477",
"size": "1590",
"binary": false,
"copies": "6",
"ref": "refs/heads/nw70",
"path": "remoting/host/backoff_timer.cc",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
using System;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using OrchardCore.Environment.Shell;
using OrchardCore.Environment.Shell.Scope;
namespace OrchardCore.Data.Documents
{
/// <summary>
/// A singleton service using the file system to store document files under the tenant folder, and that is in sync
/// with the ambient transaction, any file is updated after a successful <see cref="IDocumentStore.CommitAsync"/>.
/// </summary>
public class FileDocumentStore : IFileDocumentStore
{
private readonly string _tenantPath;
private readonly SemaphoreSlim _semaphore = new SemaphoreSlim(1);
public FileDocumentStore(IOptions<ShellOptions> shellOptions, ShellSettings shellSettings)
{
_tenantPath = Path.Combine(
shellOptions.Value.ShellsApplicationDataPath,
shellOptions.Value.ShellsContainerName,
shellSettings.Name) + "/";
Directory.CreateDirectory(_tenantPath);
}
/// <inheritdoc />
public async Task<T> GetOrCreateMutableAsync<T>(Func<Task<T>> factoryAsync = null) where T : class, new()
{
var loaded = ShellScope.Get<T>(typeof(T));
if (loaded != null)
{
return loaded;
}
var document = await GetDocumentAsync<T>()
?? await (factoryAsync?.Invoke() ?? Task.FromResult((T)null))
?? new T();
ShellScope.Set(typeof(T), document);
return document;
}
/// <inheritdoc />
public async Task<(bool, T)> GetOrCreateImmutableAsync<T>(Func<Task<T>> factoryAsync = null) where T : class, new()
{
var loaded = ShellScope.Get<T>(typeof(T));
if (loaded != null)
{
// Return the already loaded document but indicating that it should not be cached.
return (false, loaded as T);
}
return (true, await GetDocumentAsync<T>() ?? await (factoryAsync?.Invoke() ?? Task.FromResult((T)null)) ?? new T());
}
/// <inheritdoc />
public Task UpdateAsync<T>(T document, Func<T, Task> updateCache, bool checkConcurrency = false)
{
DocumentStore.AfterCommitSuccess<T>(async () =>
{
await SaveDocumentAsync(document);
ShellScope.Set(typeof(T), null);
await updateCache(document);
});
return Task.CompletedTask;
}
public Task CancelAsync() => DocumentStore.CancelAsync();
public void AfterCommitSuccess<T>(DocumentStoreCommitSuccessDelegate afterCommitSuccess) => DocumentStore.AfterCommitSuccess<T>(afterCommitSuccess);
public void AfterCommitFailure<T>(DocumentStoreCommitFailureDelegate afterCommitFailure) => DocumentStore.AfterCommitFailure<T>(afterCommitFailure);
public Task CommitAsync() => throw new NotImplementedException();
private async Task<T> GetDocumentAsync<T>()
{
var typeName = typeof(T).Name;
var attribute = typeof(T).GetCustomAttribute<FileDocumentStoreAttribute>();
if (attribute != null)
{
typeName = attribute.FileName ?? typeName;
}
var filename = _tenantPath + typeName + ".json";
if (!File.Exists(filename))
{
return default;
}
await _semaphore.WaitAsync();
try
{
T document;
using var file = File.OpenText(filename);
var serializer = new JsonSerializer();
document = (T)serializer.Deserialize(file, typeof(T));
return document;
}
finally
{
_semaphore.Release();
}
}
private async Task SaveDocumentAsync<T>(T document)
{
var typeName = typeof(T).Name;
var attribute = typeof(T).GetCustomAttribute<FileDocumentStoreAttribute>();
if (attribute != null)
{
typeName = attribute.FileName ?? typeName;
}
var filename = _tenantPath + typeName + ".json";
await _semaphore.WaitAsync();
try
{
using var file = File.CreateText(filename);
var serializer = new JsonSerializer
{
Formatting = Formatting.Indented
};
serializer.Serialize(file, document);
}
finally
{
_semaphore.Release();
}
}
private static IDocumentStore DocumentStore => ShellScope.Services.GetRequiredService<IDocumentStore>();
}
}
| {
"content_hash": "35d221dd4ec127cd673b2adcf08347b4",
"timestamp": "",
"source": "github",
"line_count": 150,
"max_line_length": 156,
"avg_line_length": 33.486666666666665,
"alnum_prop": 0.5707744375870993,
"repo_name": "xkproject/Orchard2",
"id": "cf039840bdc7ebbd343d9640e26dbc883572bad8",
"size": "5023",
"binary": false,
"copies": "3",
"ref": "refs/heads/master_PCCOM",
"path": "src/OrchardCore/OrchardCore.Data/Documents/FileDocumentStore.cs",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C#",
"bytes": "7779422"
},
{
"name": "CSS",
"bytes": "2900240"
},
{
"name": "Dockerfile",
"bytes": "424"
},
{
"name": "HTML",
"bytes": "1472436"
},
{
"name": "JavaScript",
"bytes": "2184254"
},
{
"name": "Liquid",
"bytes": "43273"
},
{
"name": "PHP",
"bytes": "2484"
},
{
"name": "PowerShell",
"bytes": "142165"
},
{
"name": "Pug",
"bytes": "55503"
},
{
"name": "SCSS",
"bytes": "215570"
},
{
"name": "TypeScript",
"bytes": "41644"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.gzuddas.excangerates.MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="@layout/content_main" />
</android.support.design.widget.CoordinatorLayout>
| {
"content_hash": "2815ee67b7a8b4ef6c37397dd8fa94ca",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 107,
"avg_line_length": 41.44,
"alnum_prop": 0.696911196911197,
"repo_name": "gzuddas/currency-excange-rates",
"id": "944ec65153c570e0e7a1d9452a01f8addeacbffb",
"size": "1036",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "excange-rates/app/src/main/res/layout/activity_main.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "31501"
}
],
"symlink_target": ""
} |
package org.apache.camel.component.bean;
import javax.naming.Context;
import org.apache.camel.ContextTestSupport;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.support.jndi.JndiContext;
import org.junit.Test;
public class BeanImplicitMethodTest extends ContextTestSupport {
@Test
public void testRoute() throws Exception {
String stringBody = "stringBody";
String stringResponse = (String)template.requestBody("direct:in", stringBody);
assertEquals(stringBody, stringResponse);
Integer intBody = 1;
Integer intResponse = (Integer)template.requestBody("direct:in", intBody);
assertEquals(1, intResponse.intValue());
}
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
public void configure() {
from("direct:in").to("bean:myBean");
}
};
}
@Override
protected Context createJndiContext() throws Exception {
JndiContext answer = new JndiContext();
answer.bind("myBean", new MyBean());
return answer;
}
public static class MyBean {
public Integer intRequest(Integer request) {
return request;
}
public String stringRequest(String request) {
return request;
}
}
}
| {
"content_hash": "78b2aaf179b30da37c23c3ed482ad923",
"timestamp": "",
"source": "github",
"line_count": 52,
"max_line_length": 86,
"avg_line_length": 25.865384615384617,
"alnum_prop": 0.6490706319702603,
"repo_name": "kevinearls/camel",
"id": "d024f36f6fff317201102fb3ec8169a5ec311ee2",
"size": "2148",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "camel-core/src/test/java/org/apache/camel/component/bean/BeanImplicitMethodTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Apex",
"bytes": "6519"
},
{
"name": "Batchfile",
"bytes": "6512"
},
{
"name": "CSS",
"bytes": "30373"
},
{
"name": "Elm",
"bytes": "10852"
},
{
"name": "FreeMarker",
"bytes": "11410"
},
{
"name": "Groovy",
"bytes": "54390"
},
{
"name": "HTML",
"bytes": "190929"
},
{
"name": "Java",
"bytes": "70990879"
},
{
"name": "JavaScript",
"bytes": "90399"
},
{
"name": "Makefile",
"bytes": "513"
},
{
"name": "Python",
"bytes": "36"
},
{
"name": "Ruby",
"bytes": "4802"
},
{
"name": "Scala",
"bytes": "323982"
},
{
"name": "Shell",
"bytes": "23616"
},
{
"name": "Tcl",
"bytes": "4974"
},
{
"name": "Thrift",
"bytes": "6979"
},
{
"name": "XQuery",
"bytes": "546"
},
{
"name": "XSLT",
"bytes": "285105"
}
],
"symlink_target": ""
} |
package engine
import (
"encoding/json"
)
// transform node.value, node.**.nodes[].value, prevNode.value, prevNode.**.nodes[].value.
func (engine *Engine) TransformEtcdJsonResponse(jsonData []byte) ([]byte, error) {
var data interface{}
json.Unmarshal(jsonData, &data)
root, ok := data.(map[string]interface{})
if !ok {
return jsonData, nil
}
if nodeRaw, ok := root["node"]; ok {
if node, ok := nodeRaw.(map[string]interface{}); ok {
engine.transformEtcdJsonResponse0(&node, 0)
}
}
if nodeRaw, ok := root["prevNode"]; ok {
if node, ok := nodeRaw.(map[string]interface{}); ok {
engine.transformEtcdJsonResponse0(&node, 0)
}
}
return json.Marshal(data)
}
func (engine *Engine) transformEtcdJsonResponse0(nodePtr *map[string]interface{}, depth int) {
if depth > 100 {
return
}
node := *nodePtr
if value, ok := node["value"]; ok {
if str, ok := value.(string); ok {
newValue, container, err := engine.TransformAndParse(str)
if err == nil {
node["value"] = newValue
if container != nil {
node["_etcvault"] = map[string]interface{}{
"version": container.Version(),
"container": container,
}
}
} else {
node["_etcvault_error"] = err.Error()
}
}
}
if nodesRaw, ok := node["nodes"]; ok {
if nodes, ok := nodesRaw.([]interface{}); ok {
for _, subNodeRaw := range nodes {
subNode, ok := subNodeRaw.(map[string]interface{})
if !ok {
continue
}
engine.transformEtcdJsonResponse0(&subNode, depth+1)
}
}
}
return
}
| {
"content_hash": "63e2d5875cc1c71b9eb5b1b989635f93",
"timestamp": "",
"source": "github",
"line_count": 70,
"max_line_length": 94,
"avg_line_length": 21.942857142857143,
"alnum_prop": 0.6236979166666666,
"repo_name": "sorah/etcvault",
"id": "762c94d29fff18a23d7154b641d227ab461e8f64",
"size": "1536",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "engine/json.go",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Go",
"bytes": "113514"
},
{
"name": "Shell",
"bytes": "262"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.