text stringlengths 2 1.04M | meta dict |
|---|---|
import { strictEqual } from "assert";
export const name = module.id;
export const promise = import("./mutual-a").then(a => {
strictEqual(a.name, "/imports/mutual-a.js");
return a;
});
| {
"content_hash": "a4fd6e1ab8068c3f39ca31bc3fe00238",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 55,
"avg_line_length": 31.333333333333332,
"alnum_prop": 0.6648936170212766,
"repo_name": "Hansoft/meteor",
"id": "d8d46bff104c2a6bae2b434aa6cfaed8679cf2ca",
"size": "188",
"binary": false,
"copies": "9",
"ref": "refs/heads/fav-96944",
"path": "tools/tests/apps/dynamic-import/imports/mutual-b.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "6635"
},
{
"name": "C",
"bytes": "235849"
},
{
"name": "C#",
"bytes": "21958"
},
{
"name": "C++",
"bytes": "203156"
},
{
"name": "CSS",
"bytes": "39463"
},
{
"name": "CoffeeScript",
"bytes": "34256"
},
{
"name": "HTML",
"bytes": "147018"
},
{
"name": "JavaScript",
"bytes": "5528500"
},
{
"name": "PowerShell",
"bytes": "7750"
},
{
"name": "Python",
"bytes": "10313"
},
{
"name": "Shell",
"bytes": "41497"
}
],
"symlink_target": ""
} |
package com.finki.emt.bookstore.repository.search;
import org.apache.lucene.search.Query;
import org.hibernate.search.jpa.FullTextEntityManager;
import org.hibernate.search.jpa.FullTextQuery;
import org.hibernate.search.jpa.Search;
import org.hibernate.search.query.dsl.BooleanJunction;
import org.hibernate.search.query.dsl.PhraseMatchingContext;
import org.hibernate.search.query.dsl.QueryBuilder;
import org.hibernate.search.query.dsl.TermMatchingContext;
import org.springframework.stereotype.Repository;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;
@Repository
public class SearchRepository {
@PersistenceContext
private EntityManager entityManager;
@SuppressWarnings("unchecked")
public <T> List<T> searchKeyword(Class<T> entity, String keyword, String... fields) {
FullTextEntityManager fullTextEntityManager =
Search.getFullTextEntityManager(entityManager);
QueryBuilder qb = fullTextEntityManager.getSearchFactory()
.buildQueryBuilder().forEntity(entity).get();
Query query = getKeywordQuery(qb, keyword, fields);
FullTextQuery fullTextQuery = fullTextEntityManager.createFullTextQuery(query, entity);
return (List<T>) fullTextQuery.getResultList();
}
/**
* Search for the given model by a phrase.
*
* @param entityClass the entity class that will be searched
* @param phrase the phrase for which the entity will be searched
* @param offset the starting index from which the results should be taken
* @param limit the maximum number of results to be retrieved
* @param fields the fields from the entity that will be searched
* @param <T> the entity class
* @return the search result list
*/
@SuppressWarnings("unchecked")
public <T> List<T> searchPhrase(Class<T> entityClass, String phrase,
int offset, int limit, String... fields) {
// get the full text entity manager
FullTextEntityManager fullTextEntityManager =
Search.getFullTextEntityManager(entityManager);
// create the query using Hibernate Search query DSL
QueryBuilder qb = fullTextEntityManager.getSearchFactory()
.buildQueryBuilder().forEntity(entityClass).get();
Query query;
BooleanJunction<BooleanJunction> bool = qb.bool();
if (phrase.contains(" ")) {
String[] tokens = phrase.split(" ");
// For every word in the phrase create a new keyword query that
// matches for every field
for (int i = 0; i < tokens.length - 1; i++) {
bool.should(getKeywordQuery(qb, tokens[i], fields))
.boostedTo(.5f);
}
// Add wildcard to the last word that allows the sentence to be unfinished
bool.should(getWildcardQuery(qb, tokens[tokens.length - 1] + "*", fields))
.boostedTo(.3f);
// Search for exact or approximate sentences to the given phrase
bool.should(getPhraseQuery(qb, phrase, fields))
.boostedTo(3f);
query = bool.createQuery();
} else {
// Add a wildcard to the phrase
bool.should(getWildcardQuery(qb, phrase.toLowerCase() + "*", fields))
.boostedTo(2f);
// Add a fuzzy query that searches for approximate keywords for the fields
bool.should(getFuzzyQuery(qb, phrase, fields));
query = bool.createQuery();
}
FullTextQuery fullTextQuery =
fullTextEntityManager.createFullTextQuery(query, entityClass)
.setFirstResult(offset)
.setMaxResults(limit);
return (List<T>) fullTextQuery.getResultList();
}
/**
* Create a new keyword query.
*/
private Query getKeywordQuery(QueryBuilder qb, String keyword, String... fields) {
return qb.keyword()
.onFields(fields)
.matching(keyword)
.createQuery();
}
/**
* Crate a new fuzzy query that searcher for words that differ with characters up to 1.
*/
private Query getFuzzyQuery(QueryBuilder qb, String keyword, String... fields) {
return qb.keyword().fuzzy()
.withEditDistanceUpTo(1)
.onFields(fields)
.matching(keyword)
.createQuery();
}
/**
* Create a phrase query that searches for exact or approximate sentences
*/
private Query getPhraseQuery(QueryBuilder qb, String sentence,
String... fields) {
PhraseMatchingContext phraseQuery = qb.phrase().onField(fields[0]);
for (int i = 1; i < fields.length; i++) {
phraseQuery = phraseQuery.andField(fields[i]);
}
return phraseQuery
.sentence(sentence)
.createQuery();
}
/**
* Create a wildcard query that lets the keyword to be unfinished.
*/
private Query getWildcardQuery(QueryBuilder qb, String keyword,
String... fields) {
TermMatchingContext phraseQuery = qb.keyword().wildcard().onField(fields[0]);
for (int i = 1; i < fields.length; i++) {
phraseQuery = phraseQuery.andField(fields[i]);
}
return phraseQuery
.matching(keyword)
.createQuery();
}
}
| {
"content_hash": "0a03421b2b7543926b4c49628b6ad0ae",
"timestamp": "",
"source": "github",
"line_count": 146,
"max_line_length": 95,
"avg_line_length": 38.52054794520548,
"alnum_prop": 0.6175320056899004,
"repo_name": "bohap/emt-book-store",
"id": "3f166b0131075abe4c3012c19cd8263b8c35dcff",
"size": "5624",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/finki/emt/bookstore/repository/search/SearchRepository.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "5186"
},
{
"name": "HTML",
"bytes": "58520"
},
{
"name": "Java",
"bytes": "234218"
},
{
"name": "JavaScript",
"bytes": "174100"
}
],
"symlink_target": ""
} |
package io.reactivex;
import java.util.*;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.infra.Blackhole;
@BenchmarkMode(Mode.Throughput)
@Warmup(iterations = 5)
@Measurement(iterations = 5, time = 5, timeUnit = TimeUnit.SECONDS)
@OutputTimeUnit(TimeUnit.SECONDS)
@Fork(value = 1)
@State(Scope.Thread)
public class RxVsStreamPerf {
@Param({ "1", "1000", "1000000" })
public int times;
Observable<Integer> range;
NbpObservable<Integer> rangeNbp;
Observable<Integer> rangeFlatMap;
NbpObservable<Integer> rangeNbpFlatMap;
List<Integer> values;
@Setup
public void setup() {
range = Observable.range(1, times);
rangeFlatMap = range.flatMap(v -> Observable.range(v, 2));
rangeNbp = NbpObservable.range(1, times);
rangeNbpFlatMap = rangeNbp.flatMap(v -> NbpObservable.range(v, 2));
values = range.toList().toBlocking().first();
}
@Benchmark
public void range(Blackhole bh) {
range.subscribe(new LatchedObserver<>(bh));
}
@Benchmark
public void rangeNbp(Blackhole bh) {
rangeNbp.subscribe(new LatchedNbpObserver<>(bh));
}
@Benchmark
public void rangeFlatMap(Blackhole bh) {
rangeFlatMap.subscribe(new LatchedObserver<>(bh));
}
@Benchmark
public void rangeNbpFlatMap(Blackhole bh) {
rangeNbpFlatMap.subscribe(new LatchedNbpObserver<>(bh));
}
@Benchmark
public void stream(Blackhole bh) {
values.stream().forEach(bh::consume);
}
@Benchmark
public void streamFlatMap(Blackhole bh) {
values.stream()
.flatMap(v -> Arrays.asList(v, v + 1).stream())
.forEach(bh::consume);
}
@Benchmark
public void streamParallel(Blackhole bh) {
values.stream().parallel().forEach(bh::consume);
}
@Benchmark
public void streamParallelFlatMap(Blackhole bh) {
values.stream()
.flatMap(v -> Arrays.asList(v, v + 1).stream())
.parallel()
.forEach(bh::consume);
}
} | {
"content_hash": "265dce8ee248b31eccae491b0f44cce5",
"timestamp": "",
"source": "github",
"line_count": 88,
"max_line_length": 75,
"avg_line_length": 24.227272727272727,
"alnum_prop": 0.6322701688555347,
"repo_name": "spoon-bot/RxJava",
"id": "46adab65750ca7063fcaf77088a4957a0d2a01bf",
"size": "2719",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/perf/java/io/reactivex/RxVsStreamPerf.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "4853541"
},
{
"name": "Shell",
"bytes": "1136"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>pixi-viewport API Documentation</title>
<meta name="description" content="Documentation for pixi-viewport library" />
<meta name="keywords" content="docs, documentation, html5, javascript, jsdoc, camera, viewport, bounce, snap, 2d" />
<meta name="keyword" content="docs, documentation, html5, javascript, jsdoc, camera, viewport, bounce, snap, 2d" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="scripts/prettify/prettify.js"></script>
<script src="scripts/prettify/lang-css.js"></script>
<script src="scripts/jquery.min.js"></script>
<!--[if lt IE 9]>
<script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link href="https://fonts.googleapis.com/css?family=Libre+Franklin:400,700" rel="stylesheet">
<link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css">
<link type="text/css" rel="stylesheet" href="styles/bootstrap.min.css">
<link type="text/css" rel="stylesheet" href="styles/main.css">
<script>
var config = {"monospaceLinks":false,"cleverLinks":false,"default":{"outputSourceFiles":true},"applicationName":"pixi-viewport","footer":"by YOPEY YOPEY LLC (yopeyopey.com)","copyright":"Copyright © 2019 YOPEY YOPEY LLC.","meta":{"title":"pixi-viewport API Documentation","description":"Documentation for pixi-viewport library","keyword":"docs, documentation, html5, javascript, jsdoc, camera, viewport, bounce, snap, 2d"}};
</script>
</head>
<body>
<div id="wrap" class="clearfix">
<div class="navigation">
<h3 class="applicationName"><a href="index.html">pixi-viewport</a></h3>
<button id="menuToggle" class="btn btn-link btn-lg menu-toggle">
<span class="glyphicon glyphicon-menu-hamburger"></span>
</button>
<div class="search">
<input id="search" type="text" class="form-control input-md" placeholder="Search...">
</div>
<ul class="list">
<li class="item" data-name="Animate">
<span class="title ">
<a href="Animate.html">Animate</a>
</span>
<ul class="members itemMembers">
<span class="subtitle">Members</span>
<li class="parent " data-name="Animate#deltaHeight"><a href="Animate.html#deltaHeight">deltaHeight</a></li>
<li class="parent " data-name="Animate#deltaWidth"><a href="Animate.html#deltaWidth">deltaWidth</a></li>
<li class="parent " data-name="Animate#height"><a href="Animate.html#height">height</a></li>
<li class="parent " data-name="Animate#startHeight"><a href="Animate.html#startHeight">startHeight</a></li>
<li class="parent " data-name="Animate#startWidth"><a href="Animate.html#startWidth">startWidth</a></li>
<li class="parent " data-name="Animate#time"><a href="Animate.html#time">time</a></li>
<li class="parent " data-name="Animate#width"><a href="Animate.html#width">width</a></li>
</ul>
<ul class="typedefs itemMembers">
</ul>
<ul class="typedefs itemMembers">
</ul>
<ul class="methods itemMembers">
<span class="subtitle">Methods</span>
<li class="parent " data-name="Animate#setupPosition"><a href="Animate.html#setupPosition">setupPosition</a></li>
<li class="parent " data-name="Animate#setupZoom"><a href="Animate.html#setupZoom">setupZoom</a></li>
</ul>
<ul class="events itemMembers">
</ul>
</li>
<li class="item" data-name="Bounce">
<span class="title ">
<a href="Bounce.html">Bounce</a>
</span>
<ul class="members itemMembers">
</ul>
<ul class="typedefs itemMembers">
</ul>
<ul class="typedefs itemMembers">
</ul>
<ul class="methods itemMembers">
<span class="subtitle">Methods</span>
<li class="parent " data-name="Bounce#calcUnderflowX"><a href="Bounce.html#calcUnderflowX">calcUnderflowX</a></li>
<li class="parent " data-name="Bounce#calcUnderflowY"><a href="Bounce.html#calcUnderflowY">calcUnderflowY</a></li>
</ul>
<ul class="events itemMembers">
</ul>
</li>
<li class="item" data-name="Clamp">
<span class="title ">
<a href="Clamp.html">Clamp</a>
</span>
<ul class="members itemMembers">
</ul>
<ul class="typedefs itemMembers">
</ul>
<ul class="typedefs itemMembers">
</ul>
<ul class="methods itemMembers">
</ul>
<ul class="events itemMembers">
</ul>
</li>
<li class="item" data-name="ClampZoom">
<span class="title ">
<a href="ClampZoom.html">ClampZoom</a>
</span>
<ul class="members itemMembers">
</ul>
<ul class="typedefs itemMembers">
</ul>
<ul class="typedefs itemMembers">
</ul>
<ul class="methods itemMembers">
<span class="subtitle">Methods</span>
<li class="parent " data-name="ClampZoom#clamp"><a href="ClampZoom.html#clamp">clamp</a></li>
</ul>
<ul class="events itemMembers">
</ul>
</li>
<li class="item" data-name="Decelerate">
<span class="title ">
<a href="Decelerate.html">Decelerate</a>
</span>
<ul class="members itemMembers">
</ul>
<ul class="typedefs itemMembers">
</ul>
<ul class="typedefs itemMembers">
</ul>
<ul class="methods itemMembers">
<span class="subtitle">Methods</span>
<li class="parent " data-name="Decelerate#activate"><a href="Decelerate.html#activate">activate</a></li>
<li class="parent " data-name="Decelerate#moved"><a href="Decelerate.html#moved">moved</a></li>
</ul>
<ul class="events itemMembers">
</ul>
</li>
<li class="item" data-name="Drag">
<span class="title ">
<a href="Drag.html">Drag</a>
</span>
<ul class="members itemMembers">
</ul>
<ul class="typedefs itemMembers">
</ul>
<ul class="typedefs itemMembers">
</ul>
<ul class="methods itemMembers">
<span class="subtitle">Methods</span>
<li class="parent " data-name="Drag#checkButtons"><a href="Drag.html#checkButtons">checkButtons</a></li>
<li class="parent " data-name="Drag#checkKeyPress"><a href="Drag.html#checkKeyPress">checkKeyPress</a></li>
<li class="parent " data-name="Drag#handleKeyPresses"><a href="Drag.html#handleKeyPresses">handleKeyPresses</a></li>
<li class="parent " data-name="Drag#mouseButtons"><a href="Drag.html#mouseButtons">mouseButtons</a></li>
</ul>
<ul class="events itemMembers">
</ul>
</li>
<li class="item" data-name="Follow">
<span class="title ">
<a href="Follow.html">Follow</a>
</span>
<ul class="members itemMembers">
</ul>
<ul class="typedefs itemMembers">
</ul>
<ul class="typedefs itemMembers">
</ul>
<ul class="methods itemMembers">
</ul>
<ul class="events itemMembers">
</ul>
</li>
<li class="item" data-name="MouseEdges#MouseEdges">
<span class="title ">
<a href="MouseEdges_MouseEdges.html">MouseEdges#MouseEdges</a>
</span>
<ul class="members itemMembers">
</ul>
<ul class="typedefs itemMembers">
</ul>
<ul class="typedefs itemMembers">
</ul>
<ul class="methods itemMembers">
</ul>
<ul class="events itemMembers">
</ul>
</li>
<li class="item" data-name="Pinch">
<span class="title ">
<a href="Pinch.html">Pinch</a>
</span>
<ul class="members itemMembers">
<span class="subtitle">Members</span>
<li class="parent " data-name="Pinch#active"><a href="Pinch.html#active">active</a></li>
<li class="parent " data-name="Pinch#pinching"><a href="Pinch.html#pinching">pinching</a></li>
</ul>
<ul class="typedefs itemMembers">
</ul>
<ul class="typedefs itemMembers">
</ul>
<ul class="methods itemMembers">
</ul>
<ul class="events itemMembers">
</ul>
</li>
<li class="item" data-name="Plugin">
<span class="title ">
<a href="Plugin.html">Plugin</a>
</span>
<ul class="members itemMembers">
</ul>
<ul class="typedefs itemMembers">
</ul>
<ul class="typedefs itemMembers">
</ul>
<ul class="methods itemMembers">
<span class="subtitle">Methods</span>
<li class="parent " data-name="Plugin#destroy"><a href="Plugin.html#destroy">destroy</a></li>
<li class="parent " data-name="Plugin#down"><a href="Plugin.html#down">down</a></li>
<li class="parent " data-name="Plugin#move"><a href="Plugin.html#move">move</a></li>
<li class="parent " data-name="Plugin#pause"><a href="Plugin.html#pause">pause</a></li>
<li class="parent " data-name="Plugin#reset"><a href="Plugin.html#reset">reset</a></li>
<li class="parent " data-name="Plugin#resize"><a href="Plugin.html#resize">resize</a></li>
<li class="parent " data-name="Plugin#resume"><a href="Plugin.html#resume">resume</a></li>
<li class="parent " data-name="Plugin#up"><a href="Plugin.html#up">up</a></li>
<li class="parent " data-name="Plugin#update"><a href="Plugin.html#update">update</a></li>
<li class="parent " data-name="Plugin#wheel"><a href="Plugin.html#wheel">wheel</a></li>
</ul>
<ul class="events itemMembers">
</ul>
</li>
<li class="item" data-name="PluginManager">
<span class="title ">
<a href="PluginManager.html">PluginManager</a>
</span>
<ul class="members itemMembers">
</ul>
<ul class="typedefs itemMembers">
</ul>
<ul class="typedefs itemMembers">
</ul>
<ul class="methods itemMembers">
<span class="subtitle">Methods</span>
<li class="parent " data-name="PluginManager#add"><a href="PluginManager.html#add">add</a></li>
<li class="parent " data-name="PluginManager#get"><a href="PluginManager.html#get">get</a></li>
<li class="parent " data-name="PluginManager#pause"><a href="PluginManager.html#pause">pause</a></li>
<li class="parent " data-name="PluginManager#remove"><a href="PluginManager.html#remove">remove</a></li>
<li class="parent " data-name="PluginManager#removeAll"><a href="PluginManager.html#removeAll">removeAll</a></li>
<li class="parent " data-name="PluginManager#reset"><a href="PluginManager.html#reset">reset</a></li>
<li class="parent " data-name="PluginManager#resume"><a href="PluginManager.html#resume">resume</a></li>
</ul>
<ul class="events itemMembers">
</ul>
</li>
<li class="item" data-name="Snap#Snap">
<span class="title ">
<a href="Snap_Snap.html">Snap#Snap</a>
</span>
<ul class="members itemMembers">
</ul>
<ul class="typedefs itemMembers">
</ul>
<ul class="typedefs itemMembers">
</ul>
<ul class="methods itemMembers">
</ul>
<ul class="events itemMembers">
</ul>
</li>
<li class="item" data-name="SnapZoom#SnapZoom">
<span class="title ">
<a href="SnapZoom_SnapZoom.html">SnapZoom#SnapZoom</a>
</span>
<ul class="members itemMembers">
</ul>
<ul class="typedefs itemMembers">
</ul>
<ul class="typedefs itemMembers">
</ul>
<ul class="methods itemMembers">
</ul>
<ul class="events itemMembers">
</ul>
</li>
<li class="item" data-name="Viewport">
<span class="title ">
<a href="Viewport.html">Viewport</a>
</span>
<ul class="members itemMembers">
<span class="subtitle">Members</span>
<li class="parent " data-name="Viewport#bottom"><a href="Viewport.html#bottom">bottom</a></li>
<li class="parent " data-name="Viewport#center"><a href="Viewport.html#center">center</a></li>
<li class="parent " data-name="Viewport#corner"><a href="Viewport.html#corner">corner</a></li>
<li class="parent " data-name="Viewport#dirty"><a href="Viewport.html#dirty">dirty</a></li>
<li class="parent " data-name="Viewport#forceHitArea"><a href="Viewport.html#forceHitArea">forceHitArea</a></li>
<li class="parent " data-name="Viewport#left"><a href="Viewport.html#left">left</a></li>
<li class="parent " data-name="Viewport#pause"><a href="Viewport.html#pause">pause</a></li>
<li class="parent " data-name="Viewport#right"><a href="Viewport.html#right">right</a></li>
<li class="parent " data-name="Viewport#scaled"><a href="Viewport.html#scaled">scaled</a></li>
<li class="parent " data-name="Viewport#screenHeightInWorldPixels"><a href="Viewport.html#screenHeightInWorldPixels">screenHeightInWorldPixels</a></li>
<li class="parent " data-name="Viewport#screenWidthInWorldPixels"><a href="Viewport.html#screenWidthInWorldPixels">screenWidthInWorldPixels</a></li>
<li class="parent " data-name="Viewport#screenWorldHeight"><a href="Viewport.html#screenWorldHeight">screenWorldHeight</a></li>
<li class="parent " data-name="Viewport#screenWorldWidth"><a href="Viewport.html#screenWorldWidth">screenWorldWidth</a></li>
<li class="parent " data-name="Viewport#top"><a href="Viewport.html#top">top</a></li>
<li class="parent " data-name="Viewport#worldHeight"><a href="Viewport.html#worldHeight">worldHeight</a></li>
<li class="parent " data-name="Viewport#worldScreenHeight"><a href="Viewport.html#worldScreenHeight">worldScreenHeight</a></li>
<li class="parent " data-name="Viewport#worldScreenWidth"><a href="Viewport.html#worldScreenWidth">worldScreenWidth</a></li>
<li class="parent " data-name="Viewport#worldWidth"><a href="Viewport.html#worldWidth">worldWidth</a></li>
</ul>
<ul class="typedefs itemMembers">
</ul>
<ul class="typedefs itemMembers">
</ul>
<ul class="methods itemMembers">
<span class="subtitle">Methods</span>
<li class="parent " data-name="Viewport#animate"><a href="Viewport.html#animate">animate</a></li>
<li class="parent " data-name="Viewport#bounce"><a href="Viewport.html#bounce">bounce</a></li>
<li class="parent " data-name="Viewport#clamp"><a href="Viewport.html#clamp">clamp</a></li>
<li class="parent " data-name="Viewport#clampZoom"><a href="Viewport.html#clampZoom">clampZoom</a></li>
<li class="parent " data-name="Viewport#decelerate"><a href="Viewport.html#decelerate">decelerate</a></li>
<li class="parent " data-name="Viewport#destroy"><a href="Viewport.html#destroy">destroy</a></li>
<li class="parent " data-name="Viewport#drag"><a href="Viewport.html#drag">drag</a></li>
<li class="parent " data-name="Viewport#ensureVisible"><a href="Viewport.html#ensureVisible">ensureVisible</a></li>
<li class="parent " data-name="Viewport#findCover"><a href="Viewport.html#findCover">findCover</a></li>
<li class="parent " data-name="Viewport#findFit"><a href="Viewport.html#findFit">findFit</a></li>
<li class="parent " data-name="Viewport#findFitHeight"><a href="Viewport.html#findFitHeight">findFitHeight</a></li>
<li class="parent " data-name="Viewport#findFitWidth"><a href="Viewport.html#findFitWidth">findFitWidth</a></li>
<li class="parent " data-name="Viewport#fit"><a href="Viewport.html#fit">fit</a></li>
<li class="parent " data-name="Viewport#fitHeight"><a href="Viewport.html#fitHeight">fitHeight</a></li>
<li class="parent " data-name="Viewport#fitWidth"><a href="Viewport.html#fitWidth">fitWidth</a></li>
<li class="parent " data-name="Viewport#fitWorld"><a href="Viewport.html#fitWorld">fitWorld</a></li>
<li class="parent " data-name="Viewport#follow"><a href="Viewport.html#follow">follow</a></li>
<li class="parent " data-name="Viewport#getVisibleBounds"><a href="Viewport.html#getVisibleBounds">getVisibleBounds</a></li>
<li class="parent " data-name="Viewport#mouseEdges"><a href="Viewport.html#mouseEdges">mouseEdges</a></li>
<li class="parent " data-name="Viewport#moveCenter"><a href="Viewport.html#moveCenter">moveCenter</a></li>
<li class="parent " data-name="Viewport#moveCorner"><a href="Viewport.html#moveCorner">moveCorner</a></li>
<li class="parent " data-name="Viewport#OOB"><a href="Viewport.html#OOB">OOB</a></li>
<li class="parent " data-name="Viewport#pinch"><a href="Viewport.html#pinch">pinch</a></li>
<li class="parent " data-name="Viewport#resize"><a href="Viewport.html#resize">resize</a></li>
<li class="parent " data-name="Viewport#setZoom"><a href="Viewport.html#setZoom">setZoom</a></li>
<li class="parent " data-name="Viewport#snap"><a href="Viewport.html#snap">snap</a></li>
<li class="parent " data-name="Viewport#snapZoom"><a href="Viewport.html#snapZoom">snapZoom</a></li>
<li class="parent " data-name="Viewport#toScreen"><a href="Viewport.html#toScreen">toScreen</a></li>
<li class="parent " data-name="Viewport#toWorld"><a href="Viewport.html#toWorld">toWorld</a></li>
<li class="parent " data-name="Viewport#update"><a href="Viewport.html#update">update</a></li>
<li class="parent " data-name="Viewport#wheel"><a href="Viewport.html#wheel">wheel</a></li>
<li class="parent " data-name="Viewport#zoom"><a href="Viewport.html#zoom">zoom</a></li>
<li class="parent " data-name="Viewport#zoomPercent"><a href="Viewport.html#zoomPercent">zoomPercent</a></li>
</ul>
<ul class="events itemMembers">
<span class="subtitle">Events</span>
<li class="parent" data-name="Viewport#event:bounce-x-end"><a href="Viewport.html#event:bounce-x-end">bounce-x-end</a></li>
<li class="parent" data-name="Viewport#event:bounce-x-start"><a href="Viewport.html#event:bounce-x-start">bounce-x-start</a></li>
<li class="parent" data-name="Viewport#event:bounce-y-end"><a href="Viewport.html#event:bounce-y-end">bounce-y-end</a></li>
<li class="parent" data-name="Viewport#event:bounce-y-start"><a href="Viewport.html#event:bounce-y-start">bounce-y-start</a></li>
<li class="parent" data-name="Viewport#event:clicked"><a href="Viewport.html#event:clicked">clicked</a></li>
<li class="parent" data-name="Viewport#event:drag-end"><a href="Viewport.html#event:drag-end">drag-end</a></li>
<li class="parent" data-name="Viewport#event:drag-start"><a href="Viewport.html#event:drag-start">drag-start</a></li>
<li class="parent" data-name="Viewport#event:frame-end"><a href="Viewport.html#event:frame-end">frame-end</a></li>
<li class="parent" data-name="Viewport#event:mouse-edge-end"><a href="Viewport.html#event:mouse-edge-end">mouse-edge-end</a></li>
<li class="parent" data-name="Viewport#event:mouse-edge-start"><a href="Viewport.html#event:mouse-edge-start">mouse-edge-start</a></li>
<li class="parent" data-name="Viewport#event:moved"><a href="Viewport.html#event:moved">moved</a></li>
<li class="parent" data-name="Viewport#event:moved-end"><a href="Viewport.html#event:moved-end">moved-end</a></li>
<li class="parent" data-name="Viewport#event:pinch-end"><a href="Viewport.html#event:pinch-end">pinch-end</a></li>
<li class="parent" data-name="Viewport#event:pinch-start"><a href="Viewport.html#event:pinch-start">pinch-start</a></li>
<li class="parent" data-name="Viewport#event:snap-end"><a href="Viewport.html#event:snap-end">snap-end</a></li>
<li class="parent" data-name="Viewport#event:snap-start"><a href="Viewport.html#event:snap-start">snap-start</a></li>
<li class="parent" data-name="Viewport#event:snap-zoom-end"><a href="Viewport.html#event:snap-zoom-end">snap-zoom-end</a></li>
<li class="parent" data-name="Viewport#event:snap-zoom-start"><a href="Viewport.html#event:snap-zoom-start">snap-zoom-start</a></li>
<li class="parent" data-name="Viewport#event:wheel"><a href="Viewport.html#event:wheel">wheel</a></li>
<li class="parent" data-name="Viewport#event:wheel-scroll"><a href="Viewport.html#event:wheel-scroll">wheel-scroll</a></li>
<li class="parent" data-name="Viewport#event:zoomed"><a href="Viewport.html#event:zoomed">zoomed</a></li>
<li class="parent" data-name="Viewport#event:zoomed-end"><a href="Viewport.html#event:zoomed-end">zoomed-end</a></li>
</ul>
</li>
<li class="item" data-name="Wheel#Wheel">
<span class="title ">
<a href="Wheel_Wheel.html">Wheel#Wheel</a>
</span>
<ul class="members itemMembers">
</ul>
<ul class="typedefs itemMembers">
</ul>
<ul class="typedefs itemMembers">
</ul>
<ul class="methods itemMembers">
</ul>
<ul class="events itemMembers">
</ul>
</li>
</ul>
</div>
<div class="main">
<h1 class="page-title" data-filename="Viewport">Class: Animate</h1>
<section>
<header>
<div class="header content-size">
<h2>Animate
</h2>
<div class="class-description"><p>Animation plugin.</p></div>
</div>
</header>
<article class="content-size">
<div class="container-overview">
<dt>
<div class="nameContainer">
<h4 class="name" id="Animate">
<a class="share-icon" href="#Animate"><span class="glyphicon glyphicon-link"></span></a>
<span class="">
new Animate
</span>
<span class="signature">(parent, options)</span>
</h4>
<div class="tag-source">
<a href="js_plugins_Animate.js.html#line15">Animate.js:15</a>
</div>
</div>
</dt>
<dd>
<div class="description">
<p>This is called by Viewport.animate.</p>
</div>
<table class="params">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th class="last">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="name"><code>parent</code></td>
<td class="type">
</td>
<td class="description last">
</td>
</tr>
<tr>
<td class="name"><code>options</code></td>
<td class="type">
</td>
<td class="description last">
</td>
</tr>
</tbody>
</table>
<dl class="details">
<dt class="tag-see">See:</dt>
<dd class="tag-see">
<ul>
<li><a href="Viewport.html#animate">Viewport#animate</a></li>
</ul>
</dd>
</dl>
<h5>Fires:</h5>
<ul>
<li>event:animate-end</li>
</ul>
</dd>
</div>
<h3 class="subsection-title">Classes</h3>
<dl class="clearfix summary-list list-classes">
<dt class=""><a href="Animate.html">Animate</a></dt>
</dl>
<h3 class="subsection-title">Members</h3>
<dl class="list-members">
<dt>
<div class="nameContainer">
<h4 class="name" id="deltaHeight">
<a class="share-icon" href="#deltaHeight"><span class="glyphicon glyphicon-link"></span></a>
<span class="">deltaHeight</span>
</h4>
</div>
</dt>
<dd>
<div class="description">
<p>The change in the viewport's height through the animation.</p>
</div>
<dl class="details">
</dl>
</dd>
<dt>
<div class="nameContainer">
<h4 class="name" id="deltaWidth">
<a class="share-icon" href="#deltaWidth"><span class="glyphicon glyphicon-link"></span></a>
<span class="">deltaWidth</span>
</h4>
</div>
</dt>
<dd>
<div class="description">
<p>The change in the viewport's width through the animation.</p>
</div>
<dl class="details">
</dl>
</dd>
<dt>
<div class="nameContainer">
<h4 class="name" id="height">
<a class="share-icon" href="#height"><span class="glyphicon glyphicon-link"></span></a>
<span class="">height</span>
</h4>
</div>
</dt>
<dd>
<div class="description">
<p>The viewport's height post-animation.</p>
</div>
<dl class="details">
</dl>
</dd>
<dt>
<div class="nameContainer">
<h4 class="name" id="startHeight">
<a class="share-icon" href="#startHeight"><span class="glyphicon glyphicon-link"></span></a>
<span class="">startHeight</span>
</h4>
</div>
</dt>
<dd>
<div class="description">
<p>The starting viewport height.</p>
</div>
<dl class="details">
</dl>
</dd>
<dt>
<div class="nameContainer">
<h4 class="name" id="startWidth">
<a class="share-icon" href="#startWidth"><span class="glyphicon glyphicon-link"></span></a>
<span class="">startWidth</span>
</h4>
</div>
</dt>
<dd>
<div class="description">
<p>The starting viewport width.</p>
</div>
<dl class="details">
</dl>
</dd>
<dt>
<div class="nameContainer">
<h4 class="name" id="time">
<a class="share-icon" href="#time"><span class="glyphicon glyphicon-link"></span></a>
<span class="">time</span>
</h4>
</div>
</dt>
<dd>
<div class="description">
<p>The time since the animation started.</p>
</div>
<dl class="details">
</dl>
</dd>
<dt>
<div class="nameContainer">
<h4 class="name" id="width">
<a class="share-icon" href="#width"><span class="glyphicon glyphicon-link"></span></a>
<span class="">width</span>
</h4>
</div>
</dt>
<dd>
<div class="description">
<p>The viewport's width post-animation.</p>
</div>
<dl class="details">
</dl>
</dd>
</dl>
<h3 class="subsection-title">Methods</h3>
<dl class="list-methods">
<dt>
<div class="nameContainer">
<h4 class="name" id="setupPosition">
<a class="share-icon" href="#setupPosition"><span class="glyphicon glyphicon-link"></span></a>
<span class="">
setupPosition
</span>
<span class="signature">()</span>
</h4>
<div class="tag-source">
<a href="js_plugins_Animate.js.html#line49">Animate.js:49</a>
</div>
</div>
</dt>
<dd>
<div class="description">
<p>Setup <code>startX</code>, <code>startY</code>, <code>deltaX</code>, <code>deltaY</code>, <code>keepCenter</code>.</p>
<p>This is called during construction.</p>
</div>
<dl class="details">
</dl>
</dd>
<dt>
<div class="nameContainer">
<h4 class="name" id="setupZoom">
<a class="share-icon" href="#setupZoom"><span class="glyphicon glyphicon-link"></span></a>
<span class="">
setupZoom
</span>
<span class="signature">()</span>
</h4>
<div class="tag-source">
<a href="js_plugins_Animate.js.html#line66">Animate.js:66</a>
</div>
</div>
</dt>
<dd>
<div class="description">
<p>Setup <code>startWidth, </code>startHeight<code>, </code>deltaWidth, <code>deltaHeight, </code>width<code>, </code>height`.</p>
<p>This is called during construction.</p>
</div>
<dl class="details">
</dl>
</dd>
</dl>
</article>
</section>
<footer class="content-size">
<div class="footer">
Documentation generated by <a target="_blank" href="https://github.com/jsdoc3/jsdoc">JSDoc 3.6.11</a> on Sun Oct 23 2022 07:02:33 GMT-0700 (Pacific Daylight Time)
</div>
</footer>
</div>
</div>
<script>prettyPrint();</script>
<script src="scripts/main.js"></script>
</body>
</html> | {
"content_hash": "693b3aa628ef93ea11708cd4d53dd30a",
"timestamp": "",
"source": "github",
"line_count": 1378,
"max_line_length": 428,
"avg_line_length": 25.8033381712627,
"alnum_prop": 0.4738869983406924,
"repo_name": "davidfig/pixi-viewport",
"id": "e34cb84e4467c92a33e0a77edf6c8b98c615e900",
"size": "35558",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/jsdoc/Animate.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "20336"
},
{
"name": "TypeScript",
"bytes": "166963"
}
],
"symlink_target": ""
} |
package test
import (
"fmt"
"os"
"path/filepath"
"sync/atomic"
"testing"
"sync"
_OS "github.com/gamejolt/joltron/os"
)
const (
// Dir is the directory where tests are executed
Dir = "test-dir"
)
var (
nextID uint32
// OS is an os interface scoped to the test dir
OS = createOS()
)
func createOS() _OS.OS {
os2, err := _OS.NewFileScope(Dir, false)
if err != nil {
panic(err.Error())
}
os2.SetVerbose(true)
return os2
}
// DoOrDie takes an operation in the form of a channel that will send an error on failure, and will panic if it receives one.
// It can work in parallel by passing in a wait group. Pass in nil for no parallelism
func DoOrDie(ch <-chan error, wg *sync.WaitGroup) *sync.WaitGroup {
// If no wait group is passed, make a new one.
if wg == nil {
wg = &sync.WaitGroup{}
}
wg.Add(1)
go func() {
defer wg.Done()
if err := <-ch; err != nil {
panic(err.Error())
}
}()
return wg
}
// PrepareNextTest creates a new test dir and gets an unused port to use for the network stuff.
// This ensures that tests can be parallelized without conflicting.
func PrepareNextTest(t *testing.T) (port uint16, dir string) {
// t.Parallel()
return prepareNextTest(t)
}
// PrepareNextBenchTest works just like PrepareNextTest only for benchmarks
func PrepareNextBenchTest(b *testing.B) (port uint16, dir string) {
return prepareNextTest(b)
}
func prepareNextTest(tb testing.TB) (port uint16, dir string) {
port = GetNextPort()
dir, err := filepath.Abs(filepath.Join(Dir, fmt.Sprintf("patch-%d", port)))
if err != nil {
tb.Fatal(fmt.Sprintf("Test dir could not be resolved: %s", err.Error()))
}
if err = os.RemoveAll(dir); err != nil {
tb.Fatal(fmt.Sprintf("Test dir could not be removed: %s", err.Error()))
}
return port, dir
}
// GetNextPort gets and increments the next port. This allows a single test to use multiple ports without conflict.
func GetNextPort() (port uint16) {
id := atomic.AddUint32(&nextID, 1)
return 1024 + uint16(id)
}
| {
"content_hash": "c1c02719e061cea5f591f2ec9c966c4f",
"timestamp": "",
"source": "github",
"line_count": 88,
"max_line_length": 125,
"avg_line_length": 22.761363636363637,
"alnum_prop": 0.6889665501747378,
"repo_name": "gamejolt/joltron",
"id": "ad1fcc7d0c042a4f1c08aec7264d9327690b338c",
"size": "2003",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/test.go",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "1269"
},
{
"name": "Go",
"bytes": "437226"
},
{
"name": "Shell",
"bytes": "1216"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>exact-real-arithmetic: Not compatible 👼</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.7.0 / exact-real-arithmetic - 8.6.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
exact-real-arithmetic
<small>
8.6.0
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-07-19 01:29:24 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-07-19 01:29:24 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-num base Num library distributed with the OCaml compiler
base-threads base
base-unix base
camlp5 7.14 Preprocessor-pretty-printer of OCaml
conf-findutils 1 Virtual package relying on findutils
conf-perl 2 Virtual package relying on perl
coq 8.7.0 Formal proof management system
num 0 The Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.03.0 The OCaml compiler (virtual package)
ocaml-base-compiler 4.03.0 Official 4.03.0 release
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.5 A library manager for OCaml
# opam file:
opam-version: "2.0"
maintainer: "Hugo.Herbelin@inria.fr"
homepage: "https://github.com/coq-contribs/exact-real-arithmetic"
license: "LGPL 2.1"
build: [make "-j%{jobs}%"]
install: [make "install"]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/ExactRealArithmetic"]
depends: [
"ocaml"
"coq" {>= "8.6" & < "8.7~"}
]
tags: [ "keyword: correctness" "keyword: real numbers" "keyword: arithmetic" "category: Mathematics/Arithmetic and Number Theory/Real numbers" ]
authors: [ "Jérôme Creci" ]
bug-reports: "https://github.com/coq-contribs/exact-real-arithmetic/issues"
dev-repo: "git+https://github.com/coq-contribs/exact-real-arithmetic.git"
synopsis: "Exact Real Arithmetic"
description: """
This contribution contains a proof of correctness
of some exact real arithmetic algorithms from the PhD thesis of
Valérie Ménissier-Morain"""
flags: light-uninstall
url {
src:
"https://github.com/coq-contribs/exact-real-arithmetic/archive/v8.6.0.tar.gz"
checksum: "md5=0286dd584cfca1f955924feae67845d8"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install 🏜️</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-exact-real-arithmetic.8.6.0 coq.8.7.0</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.7.0).
The following dependencies couldn't be met:
- coq-exact-real-arithmetic -> coq < 8.7~ -> ocaml < 4.03.0
base of this switch (use `--unlock-base' to force)
Your request can't be satisfied:
- No available version of coq satisfies the constraints
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-exact-real-arithmetic.8.6.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| {
"content_hash": "4158d6aebda6f90334da65559a1a2f60",
"timestamp": "",
"source": "github",
"line_count": 169,
"max_line_length": 184,
"avg_line_length": 42.4792899408284,
"alnum_prop": 0.550494497840925,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "3bde638205092892cdebaa2291b501719e227a6e",
"size": "7208",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.03.0-2.0.5/released/8.7.0/exact-real-arithmetic/8.6.0.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
package com.codecompiler.vo;
import java.util.Date;
/**
* Created by Manohar Prabhu on 5/28/2016.
*/
public class Response<T> {
private final Date timestamp;
private final T data;
public Response(T data) {
this.timestamp = new Date();
this.data = data;
}
public Date getTimestamp() {
return timestamp;
}
public T getData() {
return data;
}
@SuppressWarnings("unchecked")
public static Response createEmptyResponse() {
return new Response(null);
}
}
| {
"content_hash": "5ada83a394ba7815ffe9f5673abc06d2",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 50,
"avg_line_length": 18.655172413793103,
"alnum_prop": 0.6136783733826248,
"repo_name": "manoharprabhu/CodeCompiler",
"id": "77b51fe5638729306493817c827b33a7a9cc95a5",
"size": "541",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "common/src/main/java/com/codecompiler/vo/Response.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1529"
},
{
"name": "HTML",
"bytes": "10942"
},
{
"name": "Java",
"bytes": "64537"
},
{
"name": "JavaScript",
"bytes": "22238"
},
{
"name": "Shell",
"bytes": "5164"
}
],
"symlink_target": ""
} |
#include "optionsdialog.h"
#include "ui_optionsdialog.h"
#include "bitcoinunits.h"
#include "monitoreddatamapper.h"
#include "netbase.h"
#include "optionsmodel.h"
#include <QDir>
#include <QIntValidator>
#include <QLocale>
#include <QMessageBox>
OptionsDialog::OptionsDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::OptionsDialog),
model(0),
mapper(0),
fRestartWarningDisplayed_Proxy(false),
fRestartWarningDisplayed_Lang(false),
fProxyIpValid(true)
{
ui->setupUi(this);
/* Network elements init */
#ifndef USE_UPNP
ui->mapPortUpnp->setEnabled(false);
#endif
ui->proxyIp->setEnabled(false);
ui->proxyPort->setEnabled(false);
ui->proxyPort->setValidator(new QIntValidator(1, 65535, this));
ui->socksVersion->setEnabled(false);
ui->socksVersion->addItem("5", 5);
ui->socksVersion->addItem("4", 4);
ui->socksVersion->setCurrentIndex(0);
connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->proxyIp, SLOT(setEnabled(bool)));
connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->proxyPort, SLOT(setEnabled(bool)));
connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->socksVersion, SLOT(setEnabled(bool)));
connect(ui->connectSocks, SIGNAL(clicked(bool)), this, SLOT(showRestartWarning_Proxy()));
ui->proxyIp->installEventFilter(this);
/* Window elements init */
#ifdef Q_OS_MAC
/* remove Window tab on Mac */
ui->tabWidget->removeTab(ui->tabWidget->indexOf(ui->tabWindow));
#endif
/* Display elements init */
QDir translations(":translations");
ui->lang->addItem(QString("(") + tr("default") + QString(")"), QVariant(""));
foreach(const QString &langStr, translations.entryList())
{
QLocale locale(langStr);
/** check if the locale name consists of 2 parts (language_country) */
if(langStr.contains("_"))
{
#if QT_VERSION >= 0x040800
/** display language strings as "native language - native country (locale name)", e.g. "Deutsch - Deutschland (de)" */
ui->lang->addItem(locale.nativeLanguageName() + QString(" - ") + locale.nativeCountryName() + QString(" (") + langStr + QString(")"), QVariant(langStr));
#else
/** display language strings as "language - country (locale name)", e.g. "German - Germany (de)" */
ui->lang->addItem(QLocale::languageToString(locale.language()) + QString(" - ") + QLocale::countryToString(locale.country()) + QString(" (") + langStr + QString(")"), QVariant(langStr));
#endif
}
else
{
#if QT_VERSION >= 0x040800
/** display language strings as "native language (locale name)", e.g. "Deutsch (de)" */
ui->lang->addItem(locale.nativeLanguageName() + QString(" (") + langStr + QString(")"), QVariant(langStr));
#else
/** display language strings as "language (locale name)", e.g. "German (de)" */
ui->lang->addItem(QLocale::languageToString(locale.language()) + QString(" (") + langStr + QString(")"), QVariant(langStr));
#endif
}
}
ui->unit->setModel(new BitcoinUnits(this));
/* Widget-to-option mapper */
mapper = new MonitoredDataMapper(this);
mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit);
mapper->setOrientation(Qt::Vertical);
/* enable apply button when data modified */
connect(mapper, SIGNAL(viewModified()), this, SLOT(enableApplyButton()));
/* disable apply button when new data loaded */
connect(mapper, SIGNAL(currentIndexChanged(int)), this, SLOT(disableApplyButton()));
/* setup/change UI elements when proxy IP is invalid/valid */
connect(this, SIGNAL(proxyIpValid(QValidatedLineEdit *, bool)), this, SLOT(handleProxyIpValid(QValidatedLineEdit *, bool)));
}
OptionsDialog::~OptionsDialog()
{
delete ui;
}
void OptionsDialog::setModel(OptionsModel *model)
{
this->model = model;
if(model)
{
connect(model, SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));
mapper->setModel(model);
setMapper();
mapper->toFirst();
}
/* update the display unit, to not use the default ("CFN") */
updateDisplayUnit();
/* warn only when language selection changes by user action (placed here so init via mapper doesn't trigger this) */
connect(ui->lang, SIGNAL(valueChanged()), this, SLOT(showRestartWarning_Lang()));
/* disable apply button after settings are loaded as there is nothing to save */
disableApplyButton();
}
void OptionsDialog::setMapper()
{
/* Main */
mapper->addMapping(ui->transactionFee, OptionsModel::Fee);
mapper->addMapping(ui->bitcoinAtStartup, OptionsModel::StartAtStartup);
/* Network */
mapper->addMapping(ui->mapPortUpnp, OptionsModel::MapPortUPnP);
mapper->addMapping(ui->connectSocks, OptionsModel::ProxyUse);
mapper->addMapping(ui->proxyIp, OptionsModel::ProxyIP);
mapper->addMapping(ui->proxyPort, OptionsModel::ProxyPort);
mapper->addMapping(ui->socksVersion, OptionsModel::ProxySocksVersion);
/* Window */
#ifndef Q_OS_MAC
mapper->addMapping(ui->minimizeToTray, OptionsModel::MinimizeToTray);
mapper->addMapping(ui->minimizeOnClose, OptionsModel::MinimizeOnClose);
#endif
/* Display */
mapper->addMapping(ui->lang, OptionsModel::Language);
mapper->addMapping(ui->unit, OptionsModel::DisplayUnit);
mapper->addMapping(ui->displayAddresses, OptionsModel::DisplayAddresses);
mapper->addMapping(ui->coinControlFeatures, OptionsModel::CoinControlFeatures);
}
void OptionsDialog::enableApplyButton()
{
ui->applyButton->setEnabled(true);
}
void OptionsDialog::disableApplyButton()
{
ui->applyButton->setEnabled(false);
}
void OptionsDialog::enableSaveButtons()
{
/* prevent enabling of the save buttons when data modified, if there is an invalid proxy address present */
if(fProxyIpValid)
setSaveButtonState(true);
}
void OptionsDialog::disableSaveButtons()
{
setSaveButtonState(false);
}
void OptionsDialog::setSaveButtonState(bool fState)
{
ui->applyButton->setEnabled(fState);
ui->okButton->setEnabled(fState);
}
void OptionsDialog::on_resetButton_clicked()
{
if(model)
{
// confirmation dialog
QMessageBox::StandardButton btnRetVal = QMessageBox::question(this, tr("Confirm options reset"),
tr("Some settings may require a client restart to take effect.") + "<br><br>" + tr("Do you want to proceed?"),
QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel);
if(btnRetVal == QMessageBox::Cancel)
return;
disableApplyButton();
/* disable restart warning messages display */
fRestartWarningDisplayed_Lang = fRestartWarningDisplayed_Proxy = true;
/* reset all options and save the default values (QSettings) */
model->Reset();
mapper->toFirst();
mapper->submit();
/* re-enable restart warning messages display */
fRestartWarningDisplayed_Lang = fRestartWarningDisplayed_Proxy = false;
}
}
void OptionsDialog::on_okButton_clicked()
{
mapper->submit();
accept();
}
void OptionsDialog::on_cancelButton_clicked()
{
reject();
}
void OptionsDialog::on_applyButton_clicked()
{
mapper->submit();
disableApplyButton();
}
void OptionsDialog::showRestartWarning_Proxy()
{
if(!fRestartWarningDisplayed_Proxy)
{
QMessageBox::warning(this, tr("Warning"), tr("This setting will take effect after restarting Confessioncoin."), QMessageBox::Ok);
fRestartWarningDisplayed_Proxy = true;
}
}
void OptionsDialog::showRestartWarning_Lang()
{
if(!fRestartWarningDisplayed_Lang)
{
QMessageBox::warning(this, tr("Warning"), tr("This setting will take effect after restarting Confessioncoin."), QMessageBox::Ok);
fRestartWarningDisplayed_Lang = true;
}
}
void OptionsDialog::updateDisplayUnit()
{
if(model)
{
/* Update transactionFee with the current unit */
ui->transactionFee->setDisplayUnit(model->getDisplayUnit());
}
}
void OptionsDialog::handleProxyIpValid(QValidatedLineEdit *object, bool fState)
{
// this is used in a check before re-enabling the save buttons
fProxyIpValid = fState;
if(fProxyIpValid)
{
enableSaveButtons();
ui->statusLabel->clear();
}
else
{
disableSaveButtons();
object->setValid(fProxyIpValid);
ui->statusLabel->setStyleSheet("QLabel { color: red; }");
ui->statusLabel->setText(tr("The supplied proxy address is invalid."));
}
}
bool OptionsDialog::eventFilter(QObject *object, QEvent *event)
{
if(event->type() == QEvent::FocusOut)
{
if(object == ui->proxyIp)
{
CService addr;
/* Check proxyIp for a valid IPv4/IPv6 address and emit the proxyIpValid signal */
emit proxyIpValid(ui->proxyIp, LookupNumeric(ui->proxyIp->text().toStdString().c_str(), addr));
}
}
return QDialog::eventFilter(object, event);
}
| {
"content_hash": "d6e5e8fcbfb08fae6b891e059b9ceba3",
"timestamp": "",
"source": "github",
"line_count": 282,
"max_line_length": 198,
"avg_line_length": 32.09219858156028,
"alnum_prop": 0.6700552486187845,
"repo_name": "ConfessionCoin/confessioncoin",
"id": "64db19e21f54e5351014085159763af82e610492",
"size": "9050",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/qt/optionsdialog.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "92384"
},
{
"name": "C++",
"bytes": "2546131"
},
{
"name": "CSS",
"bytes": "1127"
},
{
"name": "Objective-C++",
"bytes": "5864"
},
{
"name": "Python",
"bytes": "69749"
},
{
"name": "Shell",
"bytes": "9702"
},
{
"name": "TypeScript",
"bytes": "5385074"
}
],
"symlink_target": ""
} |
MySQL ORM for Node
| {
"content_hash": "4fed4ac351e273c7b5bc3772080b981b",
"timestamp": "",
"source": "github",
"line_count": 1,
"max_line_length": 18,
"avg_line_length": 19,
"alnum_prop": 0.7894736842105263,
"repo_name": "hirokiosame/Abstract",
"id": "0d6177c42b490926a046cf7755afd956e09eb5df",
"size": "30",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "38172"
}
],
"symlink_target": ""
} |
namespace ui {
enum class DomCode;
class KeyEvent;
// Supported hook types.
enum class PlatformKeyboardHookTypes { kModifier, kMedia };
// Interface for Ozone implementations of KeyboardHook.
class COMPONENT_EXPORT(OZONE_BASE) PlatformKeyboardHook {
public:
using KeyEventCallback = base::RepeatingCallback<void(KeyEvent* event)>;
PlatformKeyboardHook();
PlatformKeyboardHook(const PlatformKeyboardHook&) = delete;
PlatformKeyboardHook& operator=(const PlatformKeyboardHook&) = delete;
virtual ~PlatformKeyboardHook();
// KeyboardHook:
virtual bool IsKeyLocked(DomCode dom_code) const = 0;
};
} // namespace ui
#endif // UI_OZONE_PUBLIC_PLATFORM_KEYBOARD_HOOK_H_
| {
"content_hash": "9c0c95880f3d35b6635f6145561e73ed",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 74,
"avg_line_length": 28.583333333333332,
"alnum_prop": 0.7696793002915452,
"repo_name": "nwjs/chromium.src",
"id": "5cbf8da4f83384271b6a3848e16e70718dd4a43f",
"size": "994",
"binary": false,
"copies": "6",
"ref": "refs/heads/nw70",
"path": "ui/ozone/public/platform_keyboard_hook.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
package com.ronglian.sdk.xtao.exception;
/**
* <p>
* Copyright: All Rights Reserved
* </p>
* <p>
* Company: 北京荣之联科技股份有限公司 http://www.ronglian.com
* </p>
* <p>
* Description:
* </p>
* <p>
* Author:Eric Shi/史丙利
* </p>
*/
public class HttpException extends XTaoException {
private static final long serialVersionUID = 5816216491033129947L;
public HttpException() {
}
public HttpException(String message) {
super(message);
}
public HttpException(Throwable cause) {
super(cause);
}
public HttpException(String message, Throwable cause) {
super(message, cause);
}
}
| {
"content_hash": "4cafa3fb9f409ed4d4936e7b6499670d",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 67,
"avg_line_length": 16.52777777777778,
"alnum_prop": 0.6789915966386555,
"repo_name": "shibingli/xtao_sdk",
"id": "72432be8fb7034113d7f7314826c117b702e37b1",
"size": "939",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/ronglian/sdk/xtao/exception/HttpException.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "111641"
}
],
"symlink_target": ""
} |
JAVA="java"
if [ "$JAVA_HOME" != "" ] ; then
JAVA="$JAVA_HOME/bin/java"
fi
$JAVA -Djava.util.logging.config.file=./logging.properties -jar triana-app-@version@.jar $*
| {
"content_hash": "6535ea0bf9add2eed18fe95c1c1ed8fe",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 91,
"avg_line_length": 19.444444444444443,
"alnum_prop": 0.64,
"repo_name": "CSCSI/Triana",
"id": "37177855de8f37d3bce4f9e5c7cef3501f8f4b0a",
"size": "188",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "triana-app/bin/triana.sh",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "35699"
},
{
"name": "CSS",
"bytes": "13201"
},
{
"name": "Java",
"bytes": "10215563"
},
{
"name": "JavaScript",
"bytes": "10926"
},
{
"name": "Shell",
"bytes": "1610"
}
],
"symlink_target": ""
} |
package org.apache.drill.test.framework;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.lang.reflect.Field;
import java.net.Inet4Address;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.drill.test.framework.TestCaseModeler.DataSource;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.log4j.Logger;
/**
* Collection of utilities supporting the drill test framework.
*
*
*/
public class Utils {
private static final Logger LOG = Logger.getLogger(Utils.class);
private static final String DRILL_TEST_CONFIG = "drillTestConfig";
private static final Map<Integer, String> sqlTypes;
private static final Map<Integer, String> sqlNullabilities;
private static final Map<String, String> drillTestProperties;
private static final String CWD = System.getProperty("user.dir");
private static final ConnectionPool connectionPool;
static {
// setup sql types
final Map<Integer, String> map = Maps.newHashMap();
final Field[] fields = Types.class.getDeclaredFields();
for (Field field : fields) {
try {
map.put((Integer) field.get(Types.class), field.getName());
} catch (IllegalAccessException e) {
throw new RuntimeException("Error while initializing sql types.", e);
}
}
sqlTypes = ImmutableMap.copyOf(map);
// setup sql nullabilities
final Map<Integer, String> nullabilityMap = Maps.newHashMap();
final Field[] nullableFields = ResultSetMetaData.class.getDeclaredFields();
for (Field nullableField : nullableFields) {
try {
nullabilityMap.put((Integer) nullableField.get(ResultSetMetaData.class), nullableField.getName());
} catch (IllegalAccessException e) {
throw new RuntimeException("Error while initializing sql nullabilities.", e);
}
}
sqlNullabilities = ImmutableMap.copyOf(nullabilityMap);
// read configuration file
final Map<String, String> drillProperties = Maps.newHashMap();
final File overrideFile = new File(System.getProperty("user.home") + "/." + DRILL_TEST_CONFIG);
final ResourceBundle bundle;
if (overrideFile.exists() && !overrideFile.isDirectory()) {
try {
bundle = new PropertyResourceBundle(new FileInputStream(overrideFile));
} catch (IOException e) {
throw new RuntimeException("Error reading configuration file in root directory.", e);
}
} else {
bundle = ResourceBundle.getBundle(DRILL_TEST_CONFIG);
}
for (final String key : bundle.keySet()) {
drillProperties.put(key.trim(), bundle.getString(key).trim());
}
drillTestProperties = ImmutableMap.copyOf(drillProperties);
// connection pool
connectionPool = new ConnectionPool();
}
public static ConnectionPool getConnectionPool() {
return connectionPool;
}
/**
* Constructs an iteration of test case definitions from various test data
* sources, obtained from the mvn command line option. See README.md for more
* details.
*
* @return an iteration of object arrays that defines the set of tests to be
* executed.
* @throws Exception
*/
public static List<DrillTestCase> getDrillTestCases() throws IOException {
String[] testDefSources = null;
try {
testDefSources = TestDriver.OPTIONS.sources.split(",");
} catch (Exception e) {
testDefSources = new String[] { "" }; //Look at the default location for test definition files
}
String[] testGroups = null;
try {
testGroups = TestDriver.OPTIONS.groups.split(",");
} catch (Exception e) {
LOG.info("Test groups not specified. Will run all collected tests.");
}
List<DrillTestCase> drillTestCases = new ArrayList<>();
for (String testDefSource : testDefSources) {
testDefSource = Utils.getAbsolutePath(testDefSource, "DRILL_TEST_DATA_DIR");
File testDefSourceFile = new File(testDefSource);
List<File> testDefFiles = searchFiles(testDefSourceFile, ".*.json");
for (File testDefFile : testDefFiles) {
// try {
TestCaseModeler modeler;
try {
modeler = getTestCaseModeler(testDefFile.getAbsolutePath());
} catch (JsonParseException e) {
LOG.warn("Caught exception parsing " + testDefFile + ". This test will not be executed.", e);
continue;
}
List<String> categories = modeler.categories;
boolean foundTests = false;
for (String testGroup : testGroups) {
if (categories != null && !categories.contains(testGroup)) {
continue;
} else {
foundTests = true;
break;
}
}
if (!foundTests) {continue;}
String queryFileExtension = modeler.matrices.get(0).inputFile;
String expectedFileExtension = modeler.matrices.get(0).expectedFile;
boolean skipSuite = false;
if (modeler.dependencies != null) {
for (String dependency : modeler.dependencies) {
if (TestDriver.OPTIONS.excludeDependenciesAsList().contains(dependency)) {
skipSuite = true;
}
}
}
if (skipSuite) {continue;}
List<File> testQueryFiles = searchFiles(testDefFile.getParentFile(),
queryFileExtension);
for (File testQueryFile : testQueryFiles) {
String expectedFileName = getExpectedFile(testQueryFile.getAbsolutePath(),
queryFileExtension, expectedFileExtension);
drillTestCases.add(new DrillTestCase(modeler, testQueryFile.getAbsolutePath(), expectedFileName));
}
}
}
if (drillTestCases.size() == 0) {
LOG.warn("Warning: No test cases have been collected.");
}
return drillTestCases;
}
private static List<File> searchFiles(File root, String regex) {
List<File> list = new ArrayList<File>();
Pattern pattern = Pattern.compile(regex + "$");
Matcher matcher = null;
if (root.isFile()) {
matcher = pattern.matcher(root.getName());
if (matcher.find()) {
list.add(root);
return list;
}
} else {
for (File file : root.listFiles()) {
if (!file.getName().equals("datasources")) {
list.addAll(searchFiles(file, regex));
}
}
}
return list;
}
private static TestCaseModeler getTestCaseModeler(String testDefFile)
throws IOException {
byte[] jsonData = Files.readAllBytes(Paths.get(testDefFile));
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.readValue(new String(jsonData), TestCaseModeler.class);
}
private static String getExpectedFile(String queryFile, String queryFileExt,
String expectedFileExt) {
int idx = queryFile.indexOf(queryFileExt.substring(2));
return queryFile.substring(0, idx).concat(expectedFileExt.substring(2));
}
/**
* Computes difference between two dates
*
* @param date1
* newer date
* @param date2
* older date
* @param unit
* one of "second", "minute", "hour" and "day"
* @return difference in time in accordance to the unit specified
*/
public static int getDateDiff(Date date1, Date date2, String unit) {
int diff = (int) (date1.getTime() - date2.getTime()) / 1000;
if (unit.equals("second")) {
return diff;
}
diff /= 60;
if (unit.equals("minute")) {
return diff;
}
diff /= 60;
if (unit.equals("hour")) {
return diff;
}
diff /= 24;
if (unit.equals("day")) {
return diff;
}
return 0;
}
/**
* Returns the map containing all properties in the drill test properties
* file.
*
* @return map containing all properties in the drill test properties file.
*/
public static Map<String, String> getDrillTestProperties() {
return drillTestProperties;
}
/**
* Constructs resolved path for a file. If the file starts with "/", it is
* assumed to already be an absolute path.
*
* @param filename
* name of file for which absolute path is being constructed.
* @param propertyKey
* name of property to resolve absolute path from.
* @return absolute path for a file.
*/
public static String getAbsolutePath(String filename, String propertyKey) {
if (filename.startsWith("/")) {
return filename;
}
return drillTestProperties.get(propertyKey) + "/" + filename;
}
/**
* Reads a query file and returns an array of queries.
*
* @param queryFileName
* name of file containing queries
* @return array of queries
* @throws IOException
*/
public static String[] getSqlStatements(String queryFileName)
throws IOException {
StringBuilder builder = new StringBuilder();
BufferedReader reader = new BufferedReader(new FileReader(new File(
queryFileName)));
String line = null;
while ((line = reader.readLine()) != null) {
builder.append(line + "\n");
}
reader.close();
String[] statements = builder.toString().trim().split(";");
for(int i=0; i<statements.length; i++) {
statements[i]=statements[i].trim();
/*while (statement.endsWith(";")) {
statement = statement.substring(0, statement.length() - 1);
}*/
}
return statements;
}
// this function should only be used while the sql resultset is still valid,
// i.e. the connection related to the resultset is still valid (not closed)
public static String getSqlResult(ResultSet resultSet) throws SQLException {
StringBuffer stringBuffer = new StringBuffer();
List columnLabels = new ArrayList<String>();
try {
int columnCount = resultSet.getMetaData().getColumnCount();
for (int i = 1; i <= columnCount; i++) {
columnLabels.add(resultSet.getMetaData().getColumnLabel(i));
}
List<Integer> types = Lists.newArrayList();
for (int i = 1; i <= columnCount; i++) {
types.add(resultSet.getMetaData().getColumnType(i));
}
LOG.debug("Result set data types:");
LOG.debug(Utils.getTypesInStrings(types));
stringBuffer.append(new ColumnList(types, columnLabels).toString() + "\n");
while (resultSet.next()) {
List<Object> values = Lists.newArrayList();
for (int i = 1; i <= columnCount; i++) {
try {
if (resultSet.getObject(i) == null) {
values.add(null);
continue;
}
if (resultSet.getMetaData().getColumnType(i) == Types.NVARCHAR) {
values.add(new String(resultSet.getBytes(i), "UTF-16"));
} else {
values.add(new String(resultSet.getBytes(i), "UTF-8"));
}
} catch (Exception e) {
if (resultSet.getMetaData().getColumnType(i) == Types.DATE) {
values.add(resultSet.getDate(i));
} else {
values.add(resultSet.getObject(i));
}
}
}
stringBuffer.append(new ColumnList(types, values).toString() + "\n");
}
} catch (IllegalArgumentException | IllegalAccessException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} finally {
if (resultSet != null) {
resultSet.close();
}
}
return stringBuffer.toString();
}
/**
* Turns a list of types in numerical values into one in strings with semantic
* content.
*
* @param typesInInteger
* list of types in numerical values.
* @return
* @throws IllegalArgumentException
* @throws IllegalAccessException
*/
public static List<String> getTypesInStrings(List<Integer> typesInInteger)
throws IllegalArgumentException, IllegalAccessException {
final List<String> typesInStrings = Lists.newArrayList();
for (final Integer type : typesInInteger) {
typesInStrings.add(sqlTypes.get(type));
}
return typesInStrings;
}
/**
* Turns a list of nullabilities in numerical values into one in strings with semantic
* content.
*
* @param nullabilitiesInInteger
* list of types in numerical values.
* @return
* @throws IllegalArgumentException
* @throws IllegalAccessException
*/
public static List<String> getNullabilitiesInStrings(List<Integer> nullabilitiesInInteger)
throws IllegalArgumentException, IllegalAccessException {
final List<String> nullabilitiesInStrings = Lists.newArrayList();
for (final Integer nullability : nullabilitiesInInteger) {
nullabilitiesInStrings.add(sqlNullabilities.get(nullability));
}
return nullabilitiesInStrings;
}
/**
* Saves content of existing drill storage plugins.
*
* @param ipAddress
* IP address of node to update storage plugin for
* @param pluginType
* type of plugin; e.g.: "dfs", "cp"
* @return content of the specified plugin
* @throws Exception
*/
public static String getExistingDrillStoragePlugin(String ipAddress,
String pluginType) throws IOException {
StringBuilder builder = new StringBuilder();
builder.append("http://" + ipAddress + ":8047/storage/" + pluginType);
HttpUriRequest request = new HttpGet(builder.toString() + ".json");
DefaultHttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(request);
return getHttpResponseAsString(response);
}
/**
* Updates storage plugin for drill
*
* @param filename
* name of file containing drill storage plugin
* @param ipAddress
* IP address of node to update storage plugin for
* @param pluginType
* type of plugin; e.g.: "dfs", "cp"
* @return true if operation is successful
*/
public static boolean updateDrillStoragePlugin(String filename,
String ipAddress, String pluginType, String fsMode) throws IOException {
String content = getFileContent(filename);
content = content.replace("localhost", Inet4Address.getLocalHost()
.getHostAddress());
if (fsMode.equals(TestDriver.LOCALFS)) {
content = content.replace("maprfs:", "file:");
content = content.replaceAll("location\"\\s*:\\s*\"", "location\":\"" + System.getProperty("user.home"));
}
return postDrillStoragePlugin(content, ipAddress, pluginType);
}
/**
* Posts/updates drill storage plugin content
*
* @param content
* string containing drill storage plugin
* @param ipAddress
* IP address of node to update storage plugin for
* @param pluginType
* type of plugin; e.g.: "dfs", "cp"
* @return true if operation is successful
* @throws Exception
*/
public static boolean postDrillStoragePlugin(String content,
String ipAddress, String pluginType) throws IOException {
StringBuilder builder = new StringBuilder();
builder.append("http://" + ipAddress + ":8047/storage/" + pluginType);
HttpPost post = new HttpPost(builder.toString() + ".json");
post.setHeader("Content-Type", "application/json");
post.setEntity(new StringEntity(content));
DefaultHttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(post);
return isResponseSuccessful(response);
}
private static String getFileContent(String filename) throws IOException {
String path = new File(filename).getAbsolutePath();
byte[] encoded = Files.readAllBytes(Paths.get(path));
return new String(encoded, "UTF-8");
}
private static String getHttpResponseAsString(HttpResponse response) throws IOException {
Reader reader = new BufferedReader(new InputStreamReader(response
.getEntity().getContent(), "UTF-8"));
StringBuilder builder = new StringBuilder();
char[] buffer = new char[1024];
int l = 0;
while (l >= 0) {
builder.append(buffer, 0, l);
l = reader.read(buffer);
}
return builder.toString();
}
private static boolean isResponseSuccessful(HttpResponse response) throws IOException {
return getHttpResponseAsString(response).toLowerCase().contains(
"\"result\" : \"success\"");
}
public static String generateOutputFileName(String inputFileName,
String testId, boolean isPlan) throws IOException {
String drillOutputDirName = TestDriver.drillOutputDirName;
if (drillOutputDirName == null) {
drillOutputDirName = "/tmp";
}
File drillOutputDirDir = new File(drillOutputDirName);
if (!drillOutputDirDir.exists()) {
if (!drillOutputDirDir.mkdir()) {
LOG.debug("Cannot create directory " + drillOutputDirName
+ ". Using /tmp for drill output");
drillOutputDirName = "/tmp";
}
}
int index = inputFileName.lastIndexOf('/');
String queryName = inputFileName.substring(index + 1);
queryName = queryName.split("\\.")[0];
String outputFileName = drillOutputDirName + "/" + testId + "_" + queryName;
if (isPlan) {
outputFileName += ".plan";
} else {
outputFileName += ".output_"
+ new Date().toString().replace(' ', '_');
}
return outputFileName;
}
public static void deleteFile(String filename) {
try {
Path path = FileSystems.getDefault().getPath(filename);
Files.delete(path);
} catch (IOException e) {
e.printStackTrace();
}
}
public static int getNumberOfClusterNodes() {
if (drillTestProperties.containsKey("NUMBER_OF_CLUSTER_NODES")) {
return Integer.parseInt(drillTestProperties.get("NUMBER_OF_CLUSTER_NODES"));
}
return 0;
}
public static int getNumberOfDrillbits(Connection connection) {
String query = "select count(*) from sys.drillbits";
int numberOfDrillbits = 0;
try {
ResultSet resultSet = execSQL(query, connection);
resultSet.next();
numberOfDrillbits = resultSet.getInt(1);
} catch (SQLException e) {
e.printStackTrace();
}
return numberOfDrillbits;
}
public static CmdConsOut execCmd(String cmd){
CmdConsOut cmdConsOut = new CmdConsOut();
cmdConsOut.cmd = cmd;
int exitCode = -1;
StringBuffer stringBuffer = new StringBuffer();
try{
Process p = Runtime.getRuntime().exec(cmd);
// InputStreamReader isr = new InputStreamReader(p.getInputStream());
InputStreamReader isr = new InputStreamReader(p.getErrorStream());
BufferedReader br = new BufferedReader(isr);
String line=null;
while ((line = br.readLine()) != null) {
stringBuffer.append(line + "\n");
}
br.close();
exitCode = p.waitFor();
} catch (Exception e) {
e.printStackTrace();
} finally {
cmdConsOut.exitCode = exitCode;
cmdConsOut.consoleOut = stringBuffer.toString();
}
if (cmdConsOut.exitCode == 0) {
LOG.debug("Command " + cmd + " successful.\n" + cmdConsOut.consoleOut);
} else {
LOG.debug("Command " + cmd + " failed.\n" + cmdConsOut.consoleOut);
}
return cmdConsOut;
}
public static ResultSet execSQL(String sql, Connection connection) throws SQLException {
try {
Statement statement = connection.createStatement();
return statement.executeQuery(sql);
} catch (SQLException e) {
e.printStackTrace();
try {
connection.close();
} catch (SQLException e1) {
e1.printStackTrace();
}
throw e;
}
}
}
| {
"content_hash": "a700d7930c09ed1c2a3a193738f0959e",
"timestamp": "",
"source": "github",
"line_count": 591,
"max_line_length": 111,
"avg_line_length": 34.363790186125215,
"alnum_prop": 0.6662071003003595,
"repo_name": "vmarkman/drill-test-framework",
"id": "8a4e9dfcf86dc1f86eb9970d795ca64f53a4fb9c",
"size": "21111",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "framework/src/main/java/org/apache/drill/test/framework/Utils.java",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "E",
"bytes": "4826729"
},
{
"name": "Eiffel",
"bytes": "18165010"
},
{
"name": "Java",
"bytes": "98955"
},
{
"name": "OpenEdge ABL",
"bytes": "1590703"
},
{
"name": "PLSQL",
"bytes": "24316"
},
{
"name": "PLpgSQL",
"bytes": "5858"
},
{
"name": "Python",
"bytes": "937"
},
{
"name": "SQLPL",
"bytes": "230"
},
{
"name": "Shell",
"bytes": "35137"
}
],
"symlink_target": ""
} |
package org.acra;
import android.content.Context;
import static org.acra.ReportField.*;
/**
* Responsible for collating those constants shared among the ACRA components.
* <p/>
*
* @author William Ferguson
* @since 4.3.0
*/
public final class ACRAConstants {
public static final String REPORTFILE_EXTENSION = ".stacktrace";
/**
* Suffix to be added to report files when they have been approved by the
* user in NOTIFICATION mode
*/
static final String APPROVED_SUFFIX = "-approved";
/**
* This key is used to store the silent state of a report sent by
* handleSilentException().
*/
static final String SILENT_SUFFIX = "-" + IS_SILENT;
/**
* This is the number of previously stored reports that we send in
* {@link SendWorker#checkAndSendReports(android.content.Context, boolean)}.
* The number of reports is limited to avoid ANR on application start.
*/
static final int MAX_SEND_REPORTS = 5;
/**
* Used in the intent starting CrashReportDialog to provide the name of the
* latest generated report file in order to be able to associate the user
* comment.
*/
protected static final String EXTRA_REPORT_FILE_NAME = "REPORT_FILE_NAME";
/**
* Set this extra to true to force the deletion of reports by the
* {@link CrashReportDialog} activity.
*/
protected static final String EXTRA_FORCE_CANCEL = "FORCE_CANCEL";
/**
* This is the identifier (value = 666) use for the status bar notification
* issued when crashes occur.
*/
static final int NOTIF_CRASH_ID = 666;
/**
* Number of milliseconds to wait after displaying a toast.
*/
static final int TOAST_WAIT_DURATION = 3000;
/**
* A special String value to allow the usage of a pseudo-null default value
* in annotation parameters.
*/
public static final String NULL_VALUE = "ACRA-NULL-STRING";
public static final boolean DEFAULT_FORCE_CLOSE_DIALOG_AFTER_TOAST = false;
public static final int DEFAULT_MAX_NUMBER_OF_REQUEST_RETRIES = 3;
public static final int DEFAULT_SOCKET_TIMEOUT = 5000;
public static final int DEFAULT_CONNECTION_TIMEOUT = 3000;
public static final boolean DEFAULT_DELETE_UNAPPROVED_REPORTS_ON_APPLICATION_START = true;
public static final boolean DEFAULT_DELETE_OLD_UNSENT_REPORTS_ON_APPLICATION_START = true;
public static final int DEFAULT_DROPBOX_COLLECTION_MINUTES = 5;
public static final boolean DEFAULT_INCLUDE_DROPBOX_SYSTEM_TAGS = false;
public static final int DEFAULT_SHARED_PREFERENCES_MODE = Context.MODE_PRIVATE;
public static final int DEFAULT_NOTIFICATION_ICON = android.R.drawable.stat_notify_error;
public static final int DEFAULT_DIALOG_ICON = android.R.drawable.ic_dialog_alert;
public static final int DEFAULT_DIALOG_POSITIVE_BUTTON_TEXT = android.R.string.ok;
public static final int DEFAULT_DIALOG_NEGATIVE_BUTTON_TEXT = android.R.string.cancel;
public static final int DEFAULT_RES_VALUE = 0;
public static final String DEFAULT_STRING_VALUE = "";
public static final int DEFAULT_LOGCAT_LINES = 100;
public static final int DEFAULT_BUFFER_SIZE_IN_BYTES = 8192;
public static final boolean DEFAULT_LOGCAT_FILTER_BY_PID = false;
public static final boolean DEFAULT_SEND_REPORTS_IN_DEV_MODE = true;
public static final String DEFAULT_APPLICATION_LOGFILE = DEFAULT_STRING_VALUE;
public static final int DEFAULT_APPLICATION_LOGFILE_LINES = DEFAULT_LOGCAT_LINES;
public static final String DEFAULT_GOOGLE_FORM_URL_FORMAT = "https://docs.google.com/spreadsheet/formResponse?formkey=%s&ifq";
public static final boolean DEFAULT_DISABLE_SSL_CERT_VALIDATION = false;
/**
* Default list of {@link ReportField}s to be sent in email reports. You can
* set your own list with
* {@link org.acra.annotation.ReportsCrashes#customReportContent()}.
*
* @see org.acra.annotation.ReportsCrashes#mailTo()
*/
public final static ReportField[] DEFAULT_MAIL_REPORT_FIELDS = { USER_COMMENT, ANDROID_VERSION, APP_VERSION_NAME,
BRAND, PHONE_MODEL, CUSTOM_DATA, STACK_TRACE };
/**
* Default list of {@link ReportField}s to be sent in reports. You can set
* your own list with
* {@link org.acra.annotation.ReportsCrashes#customReportContent()}.
*/
public static final ReportField[] DEFAULT_REPORT_FIELDS = { REPORT_ID, APP_VERSION_CODE, APP_VERSION_NAME,
PACKAGE_NAME, FILE_PATH, PHONE_MODEL, BRAND, PRODUCT, ANDROID_VERSION, BUILD, TOTAL_MEM_SIZE,
AVAILABLE_MEM_SIZE, BUILD_CONFIG, CUSTOM_DATA, IS_SILENT, STACK_TRACE, INITIAL_CONFIGURATION, CRASH_CONFIGURATION,
DISPLAY, USER_COMMENT, USER_EMAIL, USER_APP_START_DATE, USER_CRASH_DATE, DUMPSYS_MEMINFO, LOGCAT,
INSTALLATION_ID, DEVICE_FEATURES, ENVIRONMENT, SHARED_PREFERENCES, SETTINGS_SYSTEM, SETTINGS_SECURE,
SETTINGS_GLOBAL };
}
| {
"content_hash": "f6880b3979518177ec1a74a6c3cafb4b",
"timestamp": "",
"source": "github",
"line_count": 129,
"max_line_length": 130,
"avg_line_length": 39.83720930232558,
"alnum_prop": 0.6861257053901537,
"repo_name": "rekire/acra",
"id": "ae4c62d3a075678ec01c1b207a892674aefc2cb1",
"size": "5758",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "src/main/java/org/acra/ACRAConstants.java",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
namespace ANNA {
Neuron::Neuron() : weights(nullptr)
{
}
Neuron::Neuron(int numInput) : numInput(numInput)
{
// how to protect from numInput = 0
this->weights = new double[numInput];
for (int i = 0; i < numInput; i++) {
this->weights[i] = (rand() % 1001 - 500) / 1000.0; // randow values
}
}
Neuron::Neuron(const Neuron & neuron)
{
this->numInput = neuron.getNumInput();
this->weights = new double[this->numInput];
this->importWeights(neuron);
}
Neuron& Neuron::operator=(const Neuron& neuron)
{
this->numInput = neuron.getNumInput();
delete[] this->weights;
this->weights = new double[this->numInput];
this->importWeights(neuron);
return *this;
}
Neuron::~Neuron()
{
delete[] this->weights;
}
void Neuron::init(int numInput)
{
// how to protect from numInput = 0
this->numInput = numInput;
delete[] this->weights;
this->weights = new double[numInput];
for (int i = 0; i < numInput; i++) {
this->weights[i] = (rand() % 1001 - 500) / 1000.0; // randow values
}
}
double Neuron::computeOutput(double* input, ActivationFunc activFunc)
{
this->output = activFunc(this->computeInputSum(input));
return this->output;
}
int Neuron::getNumInput() const
{
return this->numInput;
}
double Neuron::getOutput() const
{
return this->output;
}
double* Neuron::getWeights() const
{
return this->weights;
}
double Neuron::getWeight(int weightNo) const
{
return this->weights[weightNo];
}
void Neuron::setWeight(int weightNo, double newWeight)
{
this->weights[weightNo] = newWeight;
}
void Neuron::importWeights(const Neuron& neuron)
{
for (int i = 0; i < this->numInput; i++) {
this->weights[i] = neuron.getWeight(i);
}
}
double Neuron::computeInputSum(double* input)
{
double sum = 0.0;
for (int i = 0; i < this->numInput; i++) {
sum += weights[i] * input[i];
}
return sum;
}
}
| {
"content_hash": "577531624b99456519a7c7a213d1f5c2",
"timestamp": "",
"source": "github",
"line_count": 94,
"max_line_length": 80,
"avg_line_length": 22.03191489361702,
"alnum_prop": 0.5895702559150169,
"repo_name": "elideveloper/ANNA",
"id": "bc5d0dcba9046c4dad164e0c47336272d3ff5487",
"size": "2114",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Neuron.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "255"
},
{
"name": "C++",
"bytes": "36300"
},
{
"name": "QMake",
"bytes": "268"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "f5e987a2f5dcf29d3e8cb32c633ee529",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "dcc7afbbd35aa53d2607f8607cffa47cac9a4d20",
"size": "173",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Orchidaceae/Pentisea/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
require 'spec_helper'
describe Spree::Taxon do
before do
stock_location = create(:stock_location, backorderable_default: false)
@product_with_stock = create(:product)
@product_out_of_stock = create(:product)
stock_location.stock_items.where(:variant_id => @product_with_stock.master.id).first.adjust_count_on_hand(10)
stock_location.stock_items.where(:variant_id => @product_out_of_stock.master.id).first.adjust_count_on_hand(0)
@taxonomy = create(:taxonomy)
@root_taxon = @taxonomy.root
@parent_taxon = create(:taxon, :name => 'Parent', :taxonomy_id => @taxonomy.id, :parent => @root_taxon)
@child_taxon = create(:taxon, :name =>'Child 1', :taxonomy_id => @taxonomy.id, :parent => @parent_taxon)
@parent_taxon.reload # Need to reload for descendents to show up
@product_with_stock.taxons << @parent_taxon
@product_with_stock.taxons << @child_taxon
@product_out_of_stock.taxons << @parent_taxon
@product_out_of_stock.taxons << @child_taxon
end
context "with show_zero_stock_products = FALSE" do
before do
Spree::Config[:show_zero_stock_products] = false
end
it "includes a product with available stock" do
@parent_taxon.active_products.should include @product_with_stock
end
it "excludes a product without available stock" do
@parent_taxon.active_products.should_not include @product_out_of_stock
end
end
context "with show_zero_stock_products = TRUE" do
before do
Spree::Config[:show_zero_stock_products] = true
end
it "includes both products with and without stock" do
@parent_taxon.active_products.should include @product_with_stock
@parent_taxon.active_products.should include @product_out_of_stock
end
end
end
| {
"content_hash": "fed66dd7746446437207c8e0c5fcd3c1",
"timestamp": "",
"source": "github",
"line_count": 52,
"max_line_length": 114,
"avg_line_length": 34.07692307692308,
"alnum_prop": 0.6930022573363431,
"repo_name": "swrobel/spree_zero_stock_products",
"id": "f7618cfda8d4775c0e2064cfabe8c70c99914ada",
"size": "1772",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "spec/models/spree/taxon/taxon_spec.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "10322"
}
],
"symlink_target": ""
} |
package main
import (
"context"
"fmt"
"log"
"os"
"strings"
cepubsub "github.com/cloudevents/sdk-go/protocol/pubsub/v2"
pscontext "github.com/cloudevents/sdk-go/protocol/pubsub/v2/context"
cloudevents "github.com/cloudevents/sdk-go/v2"
"github.com/kelseyhightower/envconfig"
)
/*
To setup:
gcloud pubsub topics create demo_cloudevents
gcloud pubsub subscriptions create foo --topic=demo_cloudevents
To test:
gcloud pubsub topics publish demo_cloudevents --message='{"Hello": "world"}'
To fix a bad message:
gcloud pubsub subscriptions pull --auto-ack foo
*/
type envConfig struct {
ProjectID string `envconfig:"GOOGLE_CLOUD_PROJECT"`
SubscriptionIDs string `envconfig:"PUBSUB_SUBSCRIPTIONS" default:"foo" required:"true"`
}
type Example struct {
Sequence int `json:"id"`
Message string `json:"message"`
}
func receive(ctx context.Context, event cloudevents.Event) error {
fmt.Printf("Event Context: %+v\n", event.Context)
fmt.Printf("Protocol Context: %+v\n", pscontext.ProtocolContextFrom(ctx))
data := &Example{}
if err := event.DataAs(data); err != nil {
fmt.Printf("Got Data Error: %s\n", err.Error())
}
fmt.Printf("Data: %+v\n", data)
fmt.Printf("----------------------------\n")
return nil
}
func main() {
ctx := context.Background()
var env envConfig
if err := envconfig.Process("", &env); err != nil {
log.Printf("[ERROR] Failed to process env var: %s", err)
os.Exit(1)
}
var opts []cepubsub.Option
opts = append(opts, cepubsub.WithProjectID(env.ProjectID))
for _, subscription := range strings.Split(env.SubscriptionIDs, ",") {
opts = append(opts, cepubsub.WithSubscriptionID(subscription))
}
t, err := cepubsub.New(context.Background(), opts...)
if err != nil {
log.Fatalf("failed to create pubsub transport, %s", err.Error())
}
c, err := cloudevents.NewClient(t)
if err != nil {
log.Fatalf("failed to create client, %s", err.Error())
}
log.Println("Created client, listening...")
if err := c.StartReceiver(ctx, receive); err != nil {
log.Fatalf("failed to start pubsub receiver, %s", err.Error())
}
}
| {
"content_hash": "2649c852ed9dcf6c34cece0e56bdd181",
"timestamp": "",
"source": "github",
"line_count": 83,
"max_line_length": 88,
"avg_line_length": 25.120481927710845,
"alnum_prop": 0.690167865707434,
"repo_name": "cloudevents/sdk-go",
"id": "abfb86ddc2487ddf201c7978368614e8953dbf6d",
"size": "2167",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "samples/pubsub/multireceiver/main.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "3954"
},
{
"name": "Gnuplot",
"bytes": "9243"
},
{
"name": "Go",
"bytes": "1037371"
},
{
"name": "Shell",
"bytes": "9976"
}
],
"symlink_target": ""
} |
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef H_Nekocoin_SCRIPT
#define H_Nekocoin_SCRIPT
#include <string>
#include <vector>
#include <boost/foreach.hpp>
#include <boost/variant.hpp>
#include "keystore.h"
#include "bignum.h"
class CTransaction;
/** Signature hash types/flags */
enum
{
SIGHASH_ALL = 1,
SIGHASH_NONE = 2,
SIGHASH_SINGLE = 3,
SIGHASH_ANYONECANPAY = 0x80,
};
enum txnouttype
{
TX_NONSTANDARD,
// 'standard' transaction types:
TX_PUBKEY,
TX_PUBKEYHASH,
TX_SCRIPTHASH,
TX_MULTISIG,
};
class CNoDestination {
public:
friend bool operator==(const CNoDestination &a, const CNoDestination &b) { return true; }
friend bool operator<(const CNoDestination &a, const CNoDestination &b) { return true; }
};
/** A txout script template with a specific destination. It is either:
* * CNoDestination: no destination set
* * CKeyID: TX_PUBKEYHASH destination
* * CScriptID: TX_SCRIPTHASH destination
* A CTxDestination is the internal data type encoded in a CNekocoinAddress
*/
typedef boost::variant<CNoDestination, CKeyID, CScriptID> CTxDestination;
const char* GetTxnOutputType(txnouttype t);
/** Script opcodes */
enum opcodetype
{
// push value
OP_0 = 0x00,
OP_FALSE = OP_0,
OP_PUSHDATA1 = 0x4c,
OP_PUSHDATA2 = 0x4d,
OP_PUSHDATA4 = 0x4e,
OP_1NEGATE = 0x4f,
OP_RESERVED = 0x50,
OP_1 = 0x51,
OP_TRUE=OP_1,
OP_2 = 0x52,
OP_3 = 0x53,
OP_4 = 0x54,
OP_5 = 0x55,
OP_6 = 0x56,
OP_7 = 0x57,
OP_8 = 0x58,
OP_9 = 0x59,
OP_10 = 0x5a,
OP_11 = 0x5b,
OP_12 = 0x5c,
OP_13 = 0x5d,
OP_14 = 0x5e,
OP_15 = 0x5f,
OP_16 = 0x60,
// control
OP_NOP = 0x61,
OP_VER = 0x62,
OP_IF = 0x63,
OP_NOTIF = 0x64,
OP_VERIF = 0x65,
OP_VERNOTIF = 0x66,
OP_ELSE = 0x67,
OP_ENDIF = 0x68,
OP_VERIFY = 0x69,
OP_RETURN = 0x6a,
// stack ops
OP_TOALTSTACK = 0x6b,
OP_FROMALTSTACK = 0x6c,
OP_2DROP = 0x6d,
OP_2DUP = 0x6e,
OP_3DUP = 0x6f,
OP_2OVER = 0x70,
OP_2ROT = 0x71,
OP_2SWAP = 0x72,
OP_IFDUP = 0x73,
OP_DEPTH = 0x74,
OP_DROP = 0x75,
OP_DUP = 0x76,
OP_NIP = 0x77,
OP_OVER = 0x78,
OP_PICK = 0x79,
OP_ROLL = 0x7a,
OP_ROT = 0x7b,
OP_SWAP = 0x7c,
OP_TUCK = 0x7d,
// splice ops
OP_CAT = 0x7e,
OP_SUBSTR = 0x7f,
OP_LEFT = 0x80,
OP_RIGHT = 0x81,
OP_SIZE = 0x82,
// bit logic
OP_INVERT = 0x83,
OP_AND = 0x84,
OP_OR = 0x85,
OP_XOR = 0x86,
OP_EQUAL = 0x87,
OP_EQUALVERIFY = 0x88,
OP_RESERVED1 = 0x89,
OP_RESERVED2 = 0x8a,
// numeric
OP_1ADD = 0x8b,
OP_1SUB = 0x8c,
OP_2MUL = 0x8d,
OP_2DIV = 0x8e,
OP_NEGATE = 0x8f,
OP_ABS = 0x90,
OP_NOT = 0x91,
OP_0NOTEQUAL = 0x92,
OP_ADD = 0x93,
OP_SUB = 0x94,
OP_MUL = 0x95,
OP_DIV = 0x96,
OP_MOD = 0x97,
OP_LSHIFT = 0x98,
OP_RSHIFT = 0x99,
OP_BOOLAND = 0x9a,
OP_BOOLOR = 0x9b,
OP_NUMEQUAL = 0x9c,
OP_NUMEQUALVERIFY = 0x9d,
OP_NUMNOTEQUAL = 0x9e,
OP_LESSTHAN = 0x9f,
OP_GREATERTHAN = 0xa0,
OP_LESSTHANOREQUAL = 0xa1,
OP_GREATERTHANOREQUAL = 0xa2,
OP_MIN = 0xa3,
OP_MAX = 0xa4,
OP_WITHIN = 0xa5,
// crypto
OP_RIPEMD160 = 0xa6,
OP_SHA1 = 0xa7,
OP_SHA256 = 0xa8,
OP_HASH160 = 0xa9,
OP_HASH256 = 0xaa,
OP_CODESEPARATOR = 0xab,
OP_CHECKSIG = 0xac,
OP_CHECKSIGVERIFY = 0xad,
OP_CHECKMULTISIG = 0xae,
OP_CHECKMULTISIGVERIFY = 0xaf,
// expansion
OP_NOP1 = 0xb0,
OP_NOP2 = 0xb1,
OP_NOP3 = 0xb2,
OP_NOP4 = 0xb3,
OP_NOP5 = 0xb4,
OP_NOP6 = 0xb5,
OP_NOP7 = 0xb6,
OP_NOP8 = 0xb7,
OP_NOP9 = 0xb8,
OP_NOP10 = 0xb9,
// template matching params
OP_SMALLINTEGER = 0xfa,
OP_PUBKEYS = 0xfb,
OP_PUBKEYHASH = 0xfd,
OP_PUBKEY = 0xfe,
OP_INVALIDOPCODE = 0xff,
};
const char* GetOpName(opcodetype opcode);
inline std::string ValueString(const std::vector<unsigned char>& vch)
{
if (vch.size() <= 4)
return strprintf("%d", CBigNum(vch).getint());
else
return HexStr(vch);
}
inline std::string StackString(const std::vector<std::vector<unsigned char> >& vStack)
{
std::string str;
BOOST_FOREACH(const std::vector<unsigned char>& vch, vStack)
{
if (!str.empty())
str += " ";
str += ValueString(vch);
}
return str;
}
/** Serialized script, used inside transaction inputs and outputs */
class CScript : public std::vector<unsigned char>
{
protected:
CScript& push_int64(int64 n)
{
if (n == -1 || (n >= 1 && n <= 16))
{
push_back(n + (OP_1 - 1));
}
else
{
CBigNum bn(n);
*this << bn.getvch();
}
return *this;
}
CScript& push_uint64(uint64 n)
{
if (n >= 1 && n <= 16)
{
push_back(n + (OP_1 - 1));
}
else
{
CBigNum bn(n);
*this << bn.getvch();
}
return *this;
}
public:
CScript() { }
CScript(const CScript& b) : std::vector<unsigned char>(b.begin(), b.end()) { }
CScript(const_iterator pbegin, const_iterator pend) : std::vector<unsigned char>(pbegin, pend) { }
#ifndef _MSC_VER
CScript(const unsigned char* pbegin, const unsigned char* pend) : std::vector<unsigned char>(pbegin, pend) { }
#endif
CScript& operator+=(const CScript& b)
{
insert(end(), b.begin(), b.end());
return *this;
}
friend CScript operator+(const CScript& a, const CScript& b)
{
CScript ret = a;
ret += b;
return ret;
}
//explicit CScript(char b) is not portable. Use 'signed char' or 'unsigned char'.
explicit CScript(signed char b) { operator<<(b); }
explicit CScript(short b) { operator<<(b); }
explicit CScript(int b) { operator<<(b); }
explicit CScript(long b) { operator<<(b); }
explicit CScript(int64 b) { operator<<(b); }
explicit CScript(unsigned char b) { operator<<(b); }
explicit CScript(unsigned int b) { operator<<(b); }
explicit CScript(unsigned short b) { operator<<(b); }
explicit CScript(unsigned long b) { operator<<(b); }
explicit CScript(uint64 b) { operator<<(b); }
explicit CScript(opcodetype b) { operator<<(b); }
explicit CScript(const uint256& b) { operator<<(b); }
explicit CScript(const CBigNum& b) { operator<<(b); }
explicit CScript(const std::vector<unsigned char>& b) { operator<<(b); }
//CScript& operator<<(char b) is not portable. Use 'signed char' or 'unsigned char'.
CScript& operator<<(signed char b) { return push_int64(b); }
CScript& operator<<(short b) { return push_int64(b); }
CScript& operator<<(int b) { return push_int64(b); }
CScript& operator<<(long b) { return push_int64(b); }
CScript& operator<<(int64 b) { return push_int64(b); }
CScript& operator<<(unsigned char b) { return push_uint64(b); }
CScript& operator<<(unsigned int b) { return push_uint64(b); }
CScript& operator<<(unsigned short b) { return push_uint64(b); }
CScript& operator<<(unsigned long b) { return push_uint64(b); }
CScript& operator<<(uint64 b) { return push_uint64(b); }
CScript& operator<<(opcodetype opcode)
{
if (opcode < 0 || opcode > 0xff)
throw std::runtime_error("CScript::operator<<() : invalid opcode");
insert(end(), (unsigned char)opcode);
return *this;
}
CScript& operator<<(const uint160& b)
{
insert(end(), sizeof(b));
insert(end(), (unsigned char*)&b, (unsigned char*)&b + sizeof(b));
return *this;
}
CScript& operator<<(const uint256& b)
{
insert(end(), sizeof(b));
insert(end(), (unsigned char*)&b, (unsigned char*)&b + sizeof(b));
return *this;
}
CScript& operator<<(const CPubKey& key)
{
std::vector<unsigned char> vchKey = key.Raw();
return (*this) << vchKey;
}
CScript& operator<<(const CBigNum& b)
{
*this << b.getvch();
return *this;
}
CScript& operator<<(const std::vector<unsigned char>& b)
{
if (b.size() < OP_PUSHDATA1)
{
insert(end(), (unsigned char)b.size());
}
else if (b.size() <= 0xff)
{
insert(end(), OP_PUSHDATA1);
insert(end(), (unsigned char)b.size());
}
else if (b.size() <= 0xffff)
{
insert(end(), OP_PUSHDATA2);
unsigned short nSize = b.size();
insert(end(), (unsigned char*)&nSize, (unsigned char*)&nSize + sizeof(nSize));
}
else
{
insert(end(), OP_PUSHDATA4);
unsigned int nSize = b.size();
insert(end(), (unsigned char*)&nSize, (unsigned char*)&nSize + sizeof(nSize));
}
insert(end(), b.begin(), b.end());
return *this;
}
CScript& operator<<(const CScript& b)
{
// I'm not sure if this should push the script or concatenate scripts.
// If there's ever a use for pushing a script onto a script, delete this member fn
assert(!"Warning: Pushing a CScript onto a CScript with << is probably not intended, use + to concatenate!");
return *this;
}
bool GetOp(iterator& pc, opcodetype& opcodeRet, std::vector<unsigned char>& vchRet)
{
// Wrapper so it can be called with either iterator or const_iterator
const_iterator pc2 = pc;
bool fRet = GetOp2(pc2, opcodeRet, &vchRet);
pc = begin() + (pc2 - begin());
return fRet;
}
bool GetOp(iterator& pc, opcodetype& opcodeRet)
{
const_iterator pc2 = pc;
bool fRet = GetOp2(pc2, opcodeRet, NULL);
pc = begin() + (pc2 - begin());
return fRet;
}
bool GetOp(const_iterator& pc, opcodetype& opcodeRet, std::vector<unsigned char>& vchRet) const
{
return GetOp2(pc, opcodeRet, &vchRet);
}
bool GetOp(const_iterator& pc, opcodetype& opcodeRet) const
{
return GetOp2(pc, opcodeRet, NULL);
}
bool GetOp2(const_iterator& pc, opcodetype& opcodeRet, std::vector<unsigned char>* pvchRet) const
{
opcodeRet = OP_INVALIDOPCODE;
if (pvchRet)
pvchRet->clear();
if (pc >= end())
return false;
// Read instruction
if (end() - pc < 1)
return false;
unsigned int opcode = *pc++;
// Immediate operand
if (opcode <= OP_PUSHDATA4)
{
unsigned int nSize;
if (opcode < OP_PUSHDATA1)
{
nSize = opcode;
}
else if (opcode == OP_PUSHDATA1)
{
if (end() - pc < 1)
return false;
nSize = *pc++;
}
else if (opcode == OP_PUSHDATA2)
{
if (end() - pc < 2)
return false;
nSize = 0;
memcpy(&nSize, &pc[0], 2);
pc += 2;
}
else if (opcode == OP_PUSHDATA4)
{
if (end() - pc < 4)
return false;
memcpy(&nSize, &pc[0], 4);
pc += 4;
}
if (end() - pc < 0 || (unsigned int)(end() - pc) < nSize)
return false;
if (pvchRet)
pvchRet->assign(pc, pc + nSize);
pc += nSize;
}
opcodeRet = (opcodetype)opcode;
return true;
}
// Encode/decode small integers:
static int DecodeOP_N(opcodetype opcode)
{
if (opcode == OP_0)
return 0;
assert(opcode >= OP_1 && opcode <= OP_16);
return (int)opcode - (int)(OP_1 - 1);
}
static opcodetype EncodeOP_N(int n)
{
assert(n >= 0 && n <= 16);
if (n == 0)
return OP_0;
return (opcodetype)(OP_1+n-1);
}
int FindAndDelete(const CScript& b)
{
int nFound = 0;
if (b.empty())
return nFound;
iterator pc = begin();
opcodetype opcode;
do
{
while (end() - pc >= (long)b.size() && memcmp(&pc[0], &b[0], b.size()) == 0)
{
erase(pc, pc + b.size());
++nFound;
}
}
while (GetOp(pc, opcode));
return nFound;
}
int Find(opcodetype op) const
{
int nFound = 0;
opcodetype opcode;
for (const_iterator pc = begin(); pc != end() && GetOp(pc, opcode);)
if (opcode == op)
++nFound;
return nFound;
}
// Pre-version-0.6, Nekocoin always counted CHECKMULTISIGs
// as 20 sigops. With pay-to-script-hash, that changed:
// CHECKMULTISIGs serialized in scriptSigs are
// counted more accurately, assuming they are of the form
// ... OP_N CHECKMULTISIG ...
unsigned int GetSigOpCount(bool fAccurate) const;
// Accurately count sigOps, including sigOps in
// pay-to-script-hash transactions:
unsigned int GetSigOpCount(const CScript& scriptSig) const;
bool IsPayToScriptHash() const;
// Called by CTransaction::IsStandard
bool IsPushOnly() const
{
const_iterator pc = begin();
while (pc < end())
{
opcodetype opcode;
if (!GetOp(pc, opcode))
return false;
if (opcode > OP_16)
return false;
}
return true;
}
void SetDestination(const CTxDestination& address);
void SetMultisig(int nRequired, const std::vector<CKey>& keys);
void PrintHex() const
{
printf("CScript(%s)\n", HexStr(begin(), end(), true).c_str());
}
std::string ToString() const
{
std::string str;
opcodetype opcode;
std::vector<unsigned char> vch;
const_iterator pc = begin();
while (pc < end())
{
if (!str.empty())
str += " ";
if (!GetOp(pc, opcode, vch))
{
str += "[error]";
return str;
}
if (0 <= opcode && opcode <= OP_PUSHDATA4)
str += ValueString(vch);
else
str += GetOpName(opcode);
}
return str;
}
void print() const
{
printf("%s\n", ToString().c_str());
}
CScriptID GetID() const
{
return CScriptID(Hash160(*this));
}
};
bool EvalScript(std::vector<std::vector<unsigned char> >& stack, const CScript& script, const CTransaction& txTo, unsigned int nIn, int nHashType);
bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, std::vector<std::vector<unsigned char> >& vSolutionsRet);
int ScriptSigArgsExpected(txnouttype t, const std::vector<std::vector<unsigned char> >& vSolutions);
bool IsStandard(const CScript& scriptPubKey);
bool IsMine(const CKeyStore& keystore, const CScript& scriptPubKey);
bool IsMine(const CKeyStore& keystore, const CTxDestination &dest);
bool ExtractDestination(const CScript& scriptPubKey, CTxDestination& addressRet);
bool ExtractDestinations(const CScript& scriptPubKey, txnouttype& typeRet, std::vector<CTxDestination>& addressRet, int& nRequiredRet);
bool SignSignature(const CKeyStore& keystore, const CScript& fromPubKey, CTransaction& txTo, unsigned int nIn, int nHashType=SIGHASH_ALL);
bool SignSignature(const CKeyStore& keystore, const CTransaction& txFrom, CTransaction& txTo, unsigned int nIn, int nHashType=SIGHASH_ALL);
bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn,
bool fValidatePayToScriptHash, int nHashType);
bool VerifySignature(const CTransaction& txFrom, const CTransaction& txTo, unsigned int nIn, bool fValidatePayToScriptHash, int nHashType);
// Given two sets of signatures for scriptPubKey, possibly with OP_0 placeholders,
// combine them intelligently and return the result.
CScript CombineSignatures(CScript scriptPubKey, const CTransaction& txTo, unsigned int nIn, const CScript& scriptSig1, const CScript& scriptSig2);
#endif
| {
"content_hash": "5ef0b07768d2eb9704a443f942eba3ab",
"timestamp": "",
"source": "github",
"line_count": 604,
"max_line_length": 147,
"avg_line_length": 27.539735099337747,
"alnum_prop": 0.5616207767223759,
"repo_name": "nekocoin/nekocoin",
"id": "9ca8b4364755e7491ebd48d888495030d87eb009",
"size": "16634",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/script.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "42620"
},
{
"name": "C++",
"bytes": "1512361"
},
{
"name": "Objective-C",
"bytes": "2451"
},
{
"name": "Prolog",
"bytes": "11363"
},
{
"name": "Python",
"bytes": "63076"
},
{
"name": "Ruby",
"bytes": "5315"
},
{
"name": "Shell",
"bytes": "1414"
},
{
"name": "TypeScript",
"bytes": "3759873"
}
],
"symlink_target": ""
} |
#include <stdio.h>
#include <string.h> /* for strncat() & memcpy() */
#include <stdlib.h> /* for exit() */
#include <zmq.h> /* for ZeroMQ functions */
#include <arpa/inet.h> /* for ntohl() */
#include "config.h"
#include "broker.h"
#include "request.h"
#include "response.h"
#include "packedobjectsd.h"
#ifdef DEBUG_MODE
#define dbg(fmtstr, args...) \
(printf("libpackedobjectsd" ":%s: " fmtstr "\n", __func__, ##args))
#else
#define dbg(dummy...)
#endif
#ifdef QUIET_MODE
#define alert(dummy...)
#else
#define alert(fmtstr, args...) \
(fprintf(stderr, "libpackedobjectsd" ":%s: " fmtstr "\n", __func__, ##args))
#endif
int getBrokerInfo(packedobjectsdObject *pod_obj)
{
int rc;
int64_t more;
size_t more_size = sizeof(more);
int portin;
int portout;
int processid;
int address_size;
int request_size;
int response_size;
void *context;
void *requester;
char *endpoint;
char *request_pdu;
char *response_pdu;
char *nodetype;
char broker_hostname[MAX_ADDRESS_SIZE];
xmlDocPtr response_doc = NULL;
address_size = strlen(pod_obj->server_address) + sizeof (int) + 7; /* 7 bytes for 'tcp://' and ':' */
endpoint = malloc(address_size + 1);
sprintf(endpoint, "tcp://%s:%d", pod_obj->server_address, pod_obj->server_port);
nodetype = which_node(pod_obj->node_type);
dbg("Connecting %s to the server at %s", nodetype, endpoint);
/* Initialise the zeromq context and socket address */
if((context = zmq_init (1)) == NULL) {
alert("Failed to initialize zeromq context");
}
/* Create socket to connect to look up server*/
if((requester = zmq_socket (context, ZMQ_REQ)) == NULL){
alert("Failed to create zeromq socket: %s", zmq_strerror (errno));
return -1;
}
if((rc = zmq_connect (requester, endpoint)) == -1){
alert("Failed to create zeromq connection: %s", zmq_strerror (errno));
return -1;
}
if((request_pdu = encodeRequestDoc(pod_obj->uid_str, pod_obj->schema_hash, nodetype, &request_size)) == NULL) {
return -1;
}
if((rc = sendMessagePDU(requester, request_pdu, request_size, 0)) == -1) {
alert("Failed to send request structure to server: %s", zmq_strerror (errno));
return -1;
}
// receive node id
if((response_pdu = receiveMessagePDU(requester, &response_size)) == NULL){
alert("The received message is NULL\n");
return -1;
}
// convert received node id to host order bytes
pod_obj->unique_id = ntohl(*(unsigned long *)response_pdu);
dbg("The node_id assigned is %lu", pod_obj->unique_id);
if((rc = zmq_getsockopt(requester, ZMQ_RCVMORE, &more, &more_size)) == -1) {
alert("Failed to get socket option");
}
// receive broker details
if(more) {
if((response_pdu = receiveMessagePDU(requester, &response_size)) == NULL){
alert("The received message is NULL\n");
return -1;
}
if((response_doc = decodeResponseDoc(response_pdu)) == NULL) {
return -1;
}
if((processResponseDoc(response_doc, broker_hostname, &portin, &portout, &processid)) == -1) {
return -1;
}
if (pod_obj->node_type == PUBLISHER || pod_obj->node_type == PUBSUB) {
if((pod_obj->publisher_endpoint = malloc(MAX_PDU_SIZE)) == NULL){
alert("Failed to allocate memory for publisher endpoint");
return -1;
}
sprintf(pod_obj->publisher_endpoint, "tcp://%s:%d", broker_hostname, portin);
dbg("broker endpoint for publisher %s", pod_obj->publisher_endpoint);
}
if (pod_obj->node_type == SUBSCRIBER || pod_obj->node_type == PUBSUB) {
if((pod_obj->subscriber_endpoint = malloc(MAX_PDU_SIZE)) == NULL){
alert("Failed to allocate memory for subscriber endpoint");
return -1;
}
sprintf(pod_obj->subscriber_endpoint, "tcp://%s:%d", broker_hostname, portout);
dbg("broker endpoint for subscriber %s", pod_obj->subscriber_endpoint);
}
if (pod_obj->node_type == SEARCHER || pod_obj->node_type == RESPONDER || pod_obj->node_type == SEARES) {
if((pod_obj->publisher_endpoint = malloc(MAX_PDU_SIZE)) == NULL){
alert("Failed to allocate memory for publisher endpoint");
return -1;
}
sprintf(pod_obj->publisher_endpoint, "tcp://%s:%d", broker_hostname, portin);
dbg("broker endpoint for publisher %s", pod_obj->publisher_endpoint);
if((pod_obj->subscriber_endpoint = malloc(MAX_PDU_SIZE)) == NULL){
alert("Failed to allocate memory for subscriber endpoint");
return -1;
}
sprintf(pod_obj->subscriber_endpoint, "tcp://%s:%d", broker_hostname, portout);
dbg("broker endpoint for subscriber %s", pod_obj->subscriber_endpoint);
}
}
/* Freeing up zeromq context, socket and pointers */
free(endpoint);
free(response_pdu);
zmq_close(requester);
zmq_term(context);
return 0;
}
/* End of broker.c */
| {
"content_hash": "dc1bee5c3134865c0a8e4aba74971b91",
"timestamp": "",
"source": "github",
"line_count": 157,
"max_line_length": 113,
"avg_line_length": 30.738853503184714,
"alnum_prop": 0.6380024865312889,
"repo_name": "jnbagale/packedobjectsd",
"id": "cfab294fbb3792908b6abb799b24118c2ffbac45",
"size": "4826",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/broker.c",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "89885"
},
{
"name": "C++",
"bytes": "889"
},
{
"name": "Shell",
"bytes": "412"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using Microsoft.Data.SqlClient;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using AutoFixture;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Moq;
using NUnit.Framework;
using SFA.DAS.CommitmentsV2.Application.Commands.ProcessFullyApprovedCohort;
using SFA.DAS.CommitmentsV2.Data;
using SFA.DAS.CommitmentsV2.Messages.Events;
using SFA.DAS.CommitmentsV2.Models;
using SFA.DAS.CommitmentsV2.TestHelpers;
using SFA.DAS.CommitmentsV2.Types;
using SFA.DAS.EAS.Account.Api.Client;
using SFA.DAS.EAS.Account.Api.Types;
using SFA.DAS.NServiceBus.Services;
namespace SFA.DAS.CommitmentsV2.UnitTests.Application.Commands
{
[TestFixture]
[Parallelizable(ParallelScope.None)]
public class ProcessFullyApprovedCohortCommandHandlerTests
{
[TestCase(ApprenticeshipEmployerType.NonLevy)]
[TestCase(ApprenticeshipEmployerType.Levy)]
public void Handle_WhenHandlingCommand_ThenShouldProcessFullyApprovedCohort(ApprenticeshipEmployerType apprenticeshipEmployerType)
{
var f = new ProcessFullyApprovedCohortCommandFixture();
f.SetApprenticeshipEmployerType(apprenticeshipEmployerType)
.Handle();
f.Db.Verify(d => d.ExecuteSqlCommandAsync(
"EXEC ProcessFullyApprovedCohort @cohortId, @accountId, @apprenticeshipEmployerType",
It.Is<SqlParameter>(p => p.ParameterName == "cohortId" && p.Value.Equals(f.Command.CohortId)),
It.Is<SqlParameter>(p => p.ParameterName == "accountId" && p.Value.Equals(f.Command.AccountId)),
It.Is<SqlParameter>(p => p.ParameterName == "apprenticeshipEmployerType" && p.Value.Equals(apprenticeshipEmployerType))),
Times.Once);
}
[TestCase(ApprenticeshipEmployerType.NonLevy, false)]
[TestCase(ApprenticeshipEmployerType.NonLevy, true)]
[TestCase(ApprenticeshipEmployerType.Levy, false)]
[TestCase(ApprenticeshipEmployerType.Levy, true)]
public void Handle_WhenHandlingCommand_ThenShouldPublishEvents(ApprenticeshipEmployerType apprenticeshipEmployerType, bool isFundedByTransfer)
{
var f = new ProcessFullyApprovedCohortCommandFixture();
f.SetApprenticeshipEmployerType(apprenticeshipEmployerType)
.SetApprovedApprenticeships(isFundedByTransfer)
.Handle();
f.Apprenticeships.ForEach(
a => f.EventPublisher.Verify(
p => p.Publish(It.Is<ApprenticeshipCreatedEvent>(
e => f.IsValid(apprenticeshipEmployerType, a, e))),
Times.Once));
}
[Test]
public void Handle_WhenHandlingCommand_WithChangeOfParty_ThenShouldPublishApprenticeshipWithChangeOfPartyCreatedEvents()
{
var f = new ProcessFullyApprovedCohortCommandFixture();
f.SetChangeOfPartyRequest(true)
.SetApprenticeshipEmployerType(ApprenticeshipEmployerType.NonLevy)
.SetApprovedApprenticeships(false)
.Handle();
f.Apprenticeships.ForEach(
a => f.EventPublisher.Verify(
p => p.Publish(It.Is<ApprenticeshipWithChangeOfPartyCreatedEvent>(
e => f.IsValidChangeOfPartyEvent(a, e))),
Times.Once));
}
[Test]
public void Handle_WhenHandlingCommand_WithChangeOfParty_ThenShouldAddContinuationOfIdToApprenticeCreatedEvents()
{
var f = new ProcessFullyApprovedCohortCommandFixture();
f.SetChangeOfPartyRequest(true)
.SetApprenticeshipEmployerType(ApprenticeshipEmployerType.NonLevy)
.SetApprovedApprenticeshipAsContinuation()
.Handle();
f.Apprenticeships.ForEach(
a => f.EventPublisher.Verify(
p => p.Publish(It.Is<ApprenticeshipCreatedEvent>(
e => e.ContinuationOfId == f.PreviousApprenticeshipId)),
Times.Once));
}
}
public class ProcessFullyApprovedCohortCommandFixture
{
public IFixture AutoFixture { get; set; }
public ProcessFullyApprovedCohortCommand Command { get; set; }
public Mock<IAccountApiClient> AccountApiClient { get; set; }
public Mock<ProviderCommitmentsDbContext> Db { get; set; }
public Mock<IEventPublisher> EventPublisher { get; set; }
public List<Apprenticeship> Apprenticeships { get; set; }
public IRequestHandler<ProcessFullyApprovedCohortCommand> Handler { get; set; }
public long PreviousApprenticeshipId { get; set; }
public ProcessFullyApprovedCohortCommandFixture()
{
AutoFixture = new Fixture();
Command = AutoFixture.Create<ProcessFullyApprovedCohortCommand>();
Command.SetValue(x => x.ChangeOfPartyRequestId, default(long?));
AccountApiClient = new Mock<IAccountApiClient>();
Db = new Mock<ProviderCommitmentsDbContext>(new DbContextOptionsBuilder<ProviderCommitmentsDbContext>().UseInMemoryDatabase(Guid.NewGuid().ToString()).Options) { CallBase = true };
EventPublisher = new Mock<IEventPublisher>();
Apprenticeships = new List<Apprenticeship>();
Handler = new ProcessFullyApprovedCohortCommandHandler(AccountApiClient.Object, new Lazy<ProviderCommitmentsDbContext>(() => Db.Object), EventPublisher.Object, Mock.Of<ILogger<ProcessFullyApprovedCohortCommandHandler>>());
AutoFixture.Behaviors.Add(new OmitOnRecursionBehavior());
Db.Setup(d => d.ExecuteSqlCommandAsync(It.IsAny<string>(), It.IsAny<object[]>())).Returns(Task.CompletedTask);
EventPublisher.Setup(p => p.Publish(It.IsAny<object>())).Returns(Task.CompletedTask);
PreviousApprenticeshipId = AutoFixture.Create<long>();
}
public Task Handle()
{
return Handler.Handle(Command, CancellationToken.None);
}
public ProcessFullyApprovedCohortCommandFixture SetApprenticeshipEmployerType(ApprenticeshipEmployerType apprenticeshipEmployerType)
{
AccountApiClient.Setup(c => c.GetAccount(Command.AccountId))
.ReturnsAsync(new AccountDetailViewModel
{
ApprenticeshipEmployerType = apprenticeshipEmployerType.ToString()
});
return this;
}
public ProcessFullyApprovedCohortCommandFixture SetChangeOfPartyRequest(bool isChangeOfParty)
{
Command.SetValue(x => x.ChangeOfPartyRequestId, isChangeOfParty ? 123 : default(long?));
return this;
}
public ProcessFullyApprovedCohortCommandFixture SetApprovedApprenticeships(bool isFundedByTransfer)
{
var provider = new Provider {Name = "Test Provider"};
var account = new Account(1, "", "", "", DateTime.UtcNow);
var accountLegalEntity = new AccountLegalEntity(account, 1, 1, "", "", "Test Employer", OrganisationType.Charities, "", DateTime.UtcNow);
AutoFixture.Inject(account);
var cohortBuilder = AutoFixture.Build<Cohort>()
.Without(c => c.Apprenticeships)
.With(c => c.AccountLegalEntity, accountLegalEntity)
.With(c => c.Provider, provider)
.With(x => x.IsDeleted, false);
if (!isFundedByTransfer)
{
cohortBuilder.Without(c => c.TransferSenderId).Without(c => c.TransferApprovalActionedOn);
}
var apprenticeshipBuilder = AutoFixture.Build<Apprenticeship>()
.Without(a => a.DataLockStatus)
.Without(a => a.EpaOrg)
.Without(a => a.ApprenticeshipUpdate)
.Without(a => a.Continuation)
.Without(s => s.ApprenticeshipConfirmationStatus)
.Without(a => a.PreviousApprenticeship);
var cohort1 = cohortBuilder.With(c => c.Id, Command.CohortId).Create();
var cohort2 = cohortBuilder.Create();
var apprenticeship1 = apprenticeshipBuilder.With(a => a.Cohort, cohort1).Create();
var apprenticeship2 = apprenticeshipBuilder.With(a => a.Cohort, cohort1).Create();
var apprenticeship3 = apprenticeshipBuilder.With(a => a.Cohort, cohort2).Create();
var apprenticeships1 = new[] { apprenticeship1, apprenticeship2 };
var apprenticeships2 = new[] { apprenticeship1, apprenticeship2, apprenticeship3 };
Apprenticeships.AddRange(apprenticeships1);
Db.Object.AccountLegalEntities.Add(accountLegalEntity);
Db.Object.Providers.Add(provider);
Db.Object.Apprenticeships.AddRange(apprenticeships2);
Db.Object.SaveChanges();
return this;
}
public ProcessFullyApprovedCohortCommandFixture SetApprovedApprenticeshipAsContinuation()
{
var provider = new Provider { Name = "Test Provider" };
var account = new Account(1, "", "", "", DateTime.UtcNow);
var accountLegalEntity = new AccountLegalEntity(account, 1, 1, "", "", "Test Employer", OrganisationType.Charities, "", DateTime.UtcNow);
AutoFixture.Inject(account);
var cohortBuilder = AutoFixture.Build<Cohort>()
.Without(c => c.Apprenticeships)
.With(c => c.AccountLegalEntity, accountLegalEntity)
.With(c => c.Provider, provider)
.With(x => x.IsDeleted, false)
.Without(c => c.TransferSenderId).Without(c => c.TransferApprovalActionedOn);
var apprenticeshipBuilder = AutoFixture.Build<Apprenticeship>()
.Without(a => a.DataLockStatus)
.Without(a => a.EpaOrg)
.Without(a => a.ApprenticeshipUpdate)
.Without(a => a.Continuation)
.Without(a => a.PreviousApprenticeship);
var cohort = cohortBuilder.With(c => c.Id, Command.CohortId).Create();
var apprenticeshipNew = apprenticeshipBuilder
.With(a => a.Cohort, cohort)
.With(a => a.ContinuationOfId, PreviousApprenticeshipId)
.Without(s => s.ApprenticeshipConfirmationStatus)
.Create();
var apprenticeships = new[] { apprenticeshipNew };
Db.Object.AccountLegalEntities.Add(accountLegalEntity);
Db.Object.Providers.Add(provider);
Db.Object.Apprenticeships.AddRange(apprenticeships);
Db.Object.SaveChanges();
return this;
}
public bool IsValid(ApprenticeshipEmployerType apprenticeshipEmployerType, Apprenticeship apprenticeship, ApprenticeshipCreatedEvent apprenticeshipCreatedEvent)
{
var isValid = apprenticeshipCreatedEvent.ApprenticeshipId == apprenticeship.Id &&
apprenticeshipCreatedEvent.CreatedOn.Date == DateTime.UtcNow.Date &&
apprenticeshipCreatedEvent.AgreedOn == apprenticeship.Cohort.EmployerAndProviderApprovedOn &&
apprenticeshipCreatedEvent.AccountId == apprenticeship.Cohort.EmployerAccountId &&
apprenticeshipCreatedEvent.AccountLegalEntityPublicHashedId == apprenticeship.Cohort.AccountLegalEntity.PublicHashedId &&
apprenticeshipCreatedEvent.LegalEntityName == apprenticeship.Cohort.AccountLegalEntity.Name &&
apprenticeshipCreatedEvent.ProviderId == apprenticeship.Cohort.Provider.UkPrn &&
apprenticeshipCreatedEvent.TransferSenderId == apprenticeship.Cohort.TransferSenderId &&
apprenticeshipCreatedEvent.ApprenticeshipEmployerTypeOnApproval == apprenticeshipEmployerType &&
apprenticeshipCreatedEvent.Uln == apprenticeship.Uln &&
apprenticeshipCreatedEvent.TrainingType == apprenticeship.ProgrammeType.Value &&
apprenticeshipCreatedEvent.TrainingCode == apprenticeship.CourseCode &&
apprenticeshipCreatedEvent.DeliveryModel == apprenticeship.DeliveryModel &&
apprenticeshipCreatedEvent.StartDate == apprenticeship.StartDate.Value &&
apprenticeshipCreatedEvent.EndDate == apprenticeship.EndDate.Value &&
apprenticeshipCreatedEvent.PriceEpisodes.Count() == apprenticeship.PriceHistory.Count &&
apprenticeshipCreatedEvent.DateOfBirth == apprenticeship.DateOfBirth;
for (var i = 0; i < apprenticeship.PriceHistory.Count; i++)
{
var priceHistory = apprenticeship.PriceHistory.ElementAt(i);
var priceEpisode = apprenticeshipCreatedEvent.PriceEpisodes.ElementAtOrDefault(i);
isValid = isValid &&
priceEpisode?.FromDate == priceHistory.FromDate &
priceEpisode?.ToDate == priceHistory.ToDate &
priceEpisode?.Cost == priceHistory.Cost;
}
return isValid;
}
public bool IsValidChangeOfPartyEvent(Apprenticeship apprenticeship, ApprenticeshipWithChangeOfPartyCreatedEvent changeOfPartyCreatedEvent)
{
return apprenticeship.Id == changeOfPartyCreatedEvent.ApprenticeshipId
&& Command.ChangeOfPartyRequestId == changeOfPartyCreatedEvent.ChangeOfPartyRequestId;
}
}
} | {
"content_hash": "4b250049b547665892f69401724808b1",
"timestamp": "",
"source": "github",
"line_count": 276,
"max_line_length": 234,
"avg_line_length": 50.45652173913044,
"alnum_prop": 0.6419646704006894,
"repo_name": "SkillsFundingAgency/das-commitments",
"id": "9f0f0c6ae8d463d084f6567ae6fd81e3f0304d51",
"size": "13926",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/CommitmentsV2/SFA.DAS.CommitmentsV2.UnitTests/Application/Commands/ProcessFullyApprovedCohortCommandHandlerTests.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "167"
},
{
"name": "C#",
"bytes": "4259078"
},
{
"name": "CSS",
"bytes": "330874"
},
{
"name": "F#",
"bytes": "20884"
},
{
"name": "HTML",
"bytes": "37546"
},
{
"name": "JavaScript",
"bytes": "30001"
},
{
"name": "PLpgSQL",
"bytes": "477"
},
{
"name": "PowerShell",
"bytes": "7972"
},
{
"name": "TSQL",
"bytes": "99241"
}
],
"symlink_target": ""
} |
package org.drools.guvnor.server.util;
import java.io.StringReader;
import org.drools.builder.DecisionTableConfiguration;
import org.drools.builder.DecisionTableInputType;
import org.drools.builder.KnowledgeBuilderFactory;
import org.drools.builder.ResourceConfiguration;
import org.drools.builder.ResourceType;
import org.drools.guvnor.client.common.AssetFormats;
import org.drools.guvnor.client.rpc.AnalysisReport;
import org.drools.guvnor.server.contenthandler.ContentHandler;
import org.drools.guvnor.server.contenthandler.ContentManager;
import org.drools.guvnor.server.contenthandler.IRuleAsset;
import org.drools.io.ResourceFactory;
import org.drools.repository.AssetItem;
import org.drools.repository.AssetItemIterator;
import org.drools.repository.PackageItem;
import org.drools.verifier.Verifier;
import org.drools.verifier.VerifierError;
import org.drools.verifier.builder.ScopesAgendaFilter;
import org.drools.verifier.data.VerifierReport;
public class VerifierRunner {
private Verifier verifier;
private PackageItem packageItem;
public VerifierRunner(Verifier verifier) {
this.verifier = verifier;
}
public AnalysisReport verify(PackageItem packageItem,
ScopesAgendaFilter scopesAgendaFilter) {
this.packageItem = packageItem;
addHeaderToVerifier();
addToVerifier( packageItem.listAssetsByFormat( new String[]{AssetFormats.DSL} ),
ResourceType.DSL );
// TODO: Model JARS
addToVerifier( packageItem.listAssetsByFormat( new String[]{AssetFormats.DRL_MODEL} ),
ResourceType.DRL );
addToVerifier( packageItem.listAssetsByFormat( new String[]{AssetFormats.FUNCTION} ),
ResourceType.DRL );
addToVerifier( packageItem.listAssetsByFormat( new String[]{AssetFormats.DSL_TEMPLATE_RULE} ),
ResourceType.DSLR );
addToVerifier( packageItem.listAssetsByFormat( new String[]{AssetFormats.DECISION_SPREADSHEET_XLS} ),
ResourceType.DTABLE );
addGuidedDecisionTablesToVerifier();
addDRLRulesToVerifier();
addToVerifier( packageItem.listAssetsByFormat( new String[]{AssetFormats.BUSINESS_RULE} ),
ResourceType.BRL );
fireAnalysis( scopesAgendaFilter );
VerifierReport report = verifier.getResult();
return VerifierReportCreator.doReport( report );
}
private void fireAnalysis(ScopesAgendaFilter scopesAgendaFilter) throws RuntimeException {
verifier.fireAnalysis( scopesAgendaFilter );
if ( verifier.hasErrors() ) {
StringBuilder message = new StringBuilder( "Verifier Errors:\n" );
for ( VerifierError verifierError : verifier.getErrors() ) {
message.append( "\t" );
message.append( verifierError.getMessage() );
message.append( "\n" );
}
throw new RuntimeException( message.toString() );
}
}
private void addHeaderToVerifier() {
StringBuilder header = new StringBuilder();
header.append( "package " + packageItem.getName() + "\n" );
header.append( DroolsHeader.getDroolsHeader( packageItem ) + "\n" );
verifier.addResourcesToVerify( ResourceFactory.newReaderResource( new StringReader( header.toString() ) ),
ResourceType.DRL );
}
private void addToVerifier(AssetItemIterator assets,
ResourceType resourceType) {
while ( assets.hasNext() ) {
AssetItem asset = assets.next();
if ( !asset.isArchived() && !asset.getDisabled() ) {
if ( resourceType == ResourceType.DTABLE ) {
DecisionTableConfiguration dtableconfiguration = KnowledgeBuilderFactory.newDecisionTableConfiguration();
dtableconfiguration.setInputType( DecisionTableInputType.XLS );
verifier.addResourcesToVerify( ResourceFactory.newByteArrayResource( asset.getBinaryContentAsBytes() ),
resourceType,
(ResourceConfiguration) dtableconfiguration );
} else {
verifier.addResourcesToVerify( ResourceFactory.newReaderResource( new StringReader( asset.getContent() ) ),
resourceType );
}
}
}
}
private void addGuidedDecisionTablesToVerifier() {
AssetItemIterator rules = packageItem.listAssetsByFormat( AssetFormats.DECISION_TABLE_GUIDED );
while ( rules.hasNext() ) {
AssetItem rule = rules.next();
ContentHandler contentHandler = ContentManager.getHandler( rule.getFormat() );
if ( contentHandler.isRuleAsset() ) {
IRuleAsset ruleAsset = (IRuleAsset) contentHandler;
String drl = ruleAsset.getRawDRL( rule );
verifier.addResourcesToVerify( ResourceFactory.newReaderResource( new StringReader( drl ) ),
ResourceType.DRL );
}
}
}
private void addDRLRulesToVerifier() {
AssetItemIterator rules = packageItem.listAssetsByFormat( AssetFormats.DRL );
while ( rules.hasNext() ) {
AssetItem rule = rules.next();
ContentHandler contentHandler = ContentManager.getHandler( rule.getFormat() );
if ( contentHandler.isRuleAsset() ) {
IRuleAsset ruleAsset = (IRuleAsset) contentHandler;
String drl = ruleAsset.getRawDRL( rule );
verifier.addResourcesToVerify( ResourceFactory.newReaderResource( new StringReader( drl ) ),
ResourceType.DRL );
}
}
}
}
| {
"content_hash": "67eab65b692f67300706623f1ef7c4b7",
"timestamp": "",
"source": "github",
"line_count": 152,
"max_line_length": 127,
"avg_line_length": 39.30921052631579,
"alnum_prop": 0.6348117154811715,
"repo_name": "Rikkola/guvnor",
"id": "0a72c527471d710d8f7d664e5625c1fdc3a3ac8d",
"size": "6568",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "guvnor-webapp/src/main/java/org/drools/guvnor/server/util/VerifierRunner.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ActionScript",
"bytes": "408232"
},
{
"name": "Java",
"bytes": "6321729"
},
{
"name": "JavaScript",
"bytes": "1200370"
},
{
"name": "Shell",
"bytes": "4740"
}
],
"symlink_target": ""
} |
#include "setup.h"
#ifdef HAVE_SYS_SOCKET_H
#include <sys/socket.h>
#endif
#ifdef HAVE_SYS_IOCTL_H
#include <sys/ioctl.h>
#endif
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef HAVE_FCNTL_H
#include <fcntl.h>
#endif
#if (defined(HAVE_IOCTL_FIONBIO) && defined(NETWARE))
#include <sys/filio.h>
#endif
#ifdef __VMS
#include <in.h>
#include <inet.h>
#endif
#include "nonblock.h"
/*
* curlx_nonblock() set the given socket to either blocking or non-blocking
* mode based on the 'nonblock' boolean argument. This function is highly
* portable.
*/
int curlx_nonblock(curl_socket_t sockfd, /* operate on this */
int nonblock /* TRUE or FALSE */)
{
#if defined(USE_BLOCKING_SOCKETS)
return 0; /* returns success */
#elif defined(HAVE_FCNTL_O_NONBLOCK)
/* most recent unix versions */
int flags;
flags = fcntl(sockfd, F_GETFL, 0);
if(nonblock)
return fcntl(sockfd, F_SETFL, flags | O_NONBLOCK);
else
return fcntl(sockfd, F_SETFL, flags & (~O_NONBLOCK));
#elif defined(HAVE_IOCTL_FIONBIO)
/* older unix versions */
int flags = nonblock ? 1 : 0;
return ioctl(sockfd, FIONBIO, &flags);
#elif defined(HAVE_IOCTLSOCKET_FIONBIO)
/* Windows */
unsigned long flags = nonblock ? 1UL : 0UL;
return ioctlsocket(sockfd, FIONBIO, &flags);
#elif defined(HAVE_IOCTLSOCKET_CAMEL_FIONBIO)
/* Amiga */
long flags = nonblock ? 1L : 0L;
return IoctlSocket(sockfd, FIONBIO, flags);
#elif defined(HAVE_SETSOCKOPT_SO_NONBLOCK)
/* BeOS */
long b = nonblock ? 1L : 0L;
return setsockopt(sockfd, SOL_SOCKET, SO_NONBLOCK, &b, sizeof(b));
#else
# error "no non-blocking method was found/used/set"
#endif
}
| {
"content_hash": "c0003e4d2431f9b5e668d8b149202f9f",
"timestamp": "",
"source": "github",
"line_count": 77,
"max_line_length": 75,
"avg_line_length": 21.649350649350648,
"alnum_prop": 0.6784643071385723,
"repo_name": "bearlin/tool_restful_client_connector",
"id": "529ce8bcab69f85495f99f4431aa5595eb86b01f",
"size": "2691",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "Tools/ThirdParty/curl/libcurl/Implementation/Linux_x64/curl/nonblock.c",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "7242998"
},
{
"name": "C++",
"bytes": "2275584"
},
{
"name": "Shell",
"bytes": "299"
}
],
"symlink_target": ""
} |
SPHINXOPTS =
SPHINXBUILD = sphinx-build
PAPER =
BUILDDIR = ../ecdocs
#BUILDDIR = _build
# Internal variables.
PAPEROPT_a4 = -D latex_paper_size=a4
PAPEROPT_letter = -D latex_paper_size=letter
ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
# the i18n builder cannot share the environment and doctrees with the others
I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext
help:
@echo "Please use \`make <target>' where <target> is one of"
@echo " html to make standalone HTML files"
@echo " dirhtml to make HTML files named index.html in directories"
@echo " singlehtml to make a single large HTML file"
@echo " pickle to make pickle files"
@echo " json to make JSON files"
@echo " htmlhelp to make HTML files and a HTML help project"
@echo " qthelp to make HTML files and a qthelp project"
@echo " devhelp to make HTML files and a Devhelp project"
@echo " epub to make an epub"
@echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
@echo " latexpdf to make LaTeX files and run them through pdflatex"
@echo " text to make text files"
@echo " man to make manual pages"
@echo " texinfo to make Texinfo files"
@echo " info to make Texinfo files and run them through makeinfo"
@echo " gettext to make PO message catalogs"
@echo " changes to make an overview of all changed/added/deprecated items"
@echo " linkcheck to check all external links for integrity"
@echo " doctest to run all doctests embedded in the documentation (if enabled)"
clean:
-rm -rf $(BUILDDIR)/*
html:
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
dirhtml:
$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
singlehtml:
$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
@echo
@echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
pickle:
$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
@echo
@echo "Build finished; now you can process the pickle files."
json:
$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
@echo
@echo "Build finished; now you can process the JSON files."
htmlhelp:
$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
@echo
@echo "Build finished; now you can run HTML Help Workshop with the" \
".hhp project file in $(BUILDDIR)/htmlhelp."
qthelp:
$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
@echo
@echo "Build finished; now you can run "qcollectiongenerator" with the" \
".qhcp project file in $(BUILDDIR)/qthelp, like this:"
@echo "# qcollectiongenerator $(BUILDDIR)/qthelp/Estrangement.qhcp"
@echo "To view the help file:"
@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/Estrangement.qhc"
devhelp:
$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
@echo
@echo "Build finished."
@echo "To view the help file:"
@echo "# mkdir -p $$HOME/.local/share/devhelp/Estrangement"
@echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/Estrangement"
@echo "# devhelp"
epub:
$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
@echo
@echo "Build finished. The epub file is in $(BUILDDIR)/epub."
latex:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo
@echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
@echo "Run \`make' in that directory to run these through (pdf)latex" \
"(use \`make latexpdf' here to do that automatically)."
latexpdf:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through pdflatex..."
$(MAKE) -C $(BUILDDIR)/latex all-pdf
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
text:
$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
@echo
@echo "Build finished. The text files are in $(BUILDDIR)/text."
man:
$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
@echo
@echo "Build finished. The manual pages are in $(BUILDDIR)/man."
texinfo:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo
@echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
@echo "Run \`make' in that directory to run these through makeinfo" \
"(use \`make info' here to do that automatically)."
info:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo "Running Texinfo files through makeinfo..."
make -C $(BUILDDIR)/texinfo info
@echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
gettext:
$(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
@echo
@echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
changes:
$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
@echo
@echo "The overview file is in $(BUILDDIR)/changes."
linkcheck:
$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
@echo
@echo "Link check complete; look for any errors in the above output " \
"or in $(BUILDDIR)/linkcheck/output.txt."
doctest:
$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
@echo "Testing of doctests in the sources finished, look at the " \
"results in $(BUILDDIR)/doctest/output.txt."
| {
"content_hash": "d03455c6bad2b7eda56398c54ccf36d5",
"timestamp": "",
"source": "github",
"line_count": 150,
"max_line_length": 141,
"avg_line_length": 36.82,
"alnum_prop": 0.70161144305631,
"repo_name": "kawadia/estrangement",
"id": "05e1ef657dedb14df35e76d1fc07fa94d3f51de9",
"size": "5615",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/Makefile",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Python",
"bytes": "146272"
},
{
"name": "Shell",
"bytes": "503"
}
],
"symlink_target": ""
} |
<?php
/**
* Created by PhpStorm.
* User: Nicolas Canfrere
* Date: 28/09/2014
* Time: 15:16
*/
/*
____________________
__ / ______ \
{ \ ___/___ / } \
{ / / # } |
{/ ô ô ; __} |
/ \__} / \ /\
<=(_ __<==/ | /\___\ | \
(_ _( | | | | | / #
(_ (_ | | | | | |
(__< |mm_|mm_| |mm_|mm_|
*/
namespace ZPB\AdminBundle\Controller\Parrainage;
use Symfony\Component\HttpFoundation\Request;
use ZPB\AdminBundle\Controller\BaseController;
use ZPB\AdminBundle\Entity\AnimalCategory;
use ZPB\AdminBundle\Form\Type\AnimalCategoryType;
class CategoryController extends BaseController
{
public function listAction()
{
$entities = $this->getRepo('ZPBAdminBundle:AnimalCategory')->findAll(); //->findBy([], ['name'=> 'ASC']);
return $this->render('ZPBAdminBundle:Parrainage/Category:list.html.twig', ['entities'=>$entities]);
}
public function createAction(Request $request)
{
$entity = new AnimalCategory();
$form = $this->createForm(new AnimalCategoryType(), $entity);
$form->handleRequest($request);
if($form->isValid()){
$this->getManager()->persist($entity);
$this->getManager()->flush();
$this->setSuccess('Nouvelle catégorie bien enregistrée');
return $this->redirect($this->generateUrl('zpb_admin_sponsor_animals_categories_list'));
}
return $this->render('ZPBAdminBundle:Parrainage/Category:create.html.twig', ['form'=>$form->createView()]);
}
public function updateAction($id, Request $request)
{
$entity = $this->getRepo('ZPBAdminBundle:AnimalCategory')->find($id);
if(!$entity){
throw $this->createNotFoundException();
}
$form = $this->createForm(new AnimalCategoryType(), $entity);
$form->handleRequest($request);
if($form->isValid()){
$this->getManager()->persist($entity);
$this->getManager()->flush();
$this->setSuccess('Catégorie bien modifiée');
return $this->redirect($this->generateUrl('zpb_admin_sponsor_animals_categories_list'));
}
return $this->render('ZPBAdminBundle:Parrainage/Category:update.html.twig', ['form'=>$form->createView()]);
}
public function deleteAction($id, Request $request)
{
if(!$this->validateToken($request->query->get('_token'), 'delete_category')){
throw $this->createAccessDeniedException();
}
if(null == $entity = $this->getRepo('ZPBAdminBundle:AnimalCategory')->find($id)){
throw $this->createNotFoundException();
}
$animals = $entity->getAnimals();
if(count($animals) < 1){
$this->getManager()->remove($entity);
$this->getManager()->flush();
$this->setSuccess('Catégorie bien supprimée');
return $this->redirect($this->generateUrl('zpb_admin_sponsor_animals_categories_list'));
}
$categories = $this->getRepo('ZPBAdminBundle:AnimalCategory')->findAll();
return $this->render('ZPBAdminBundle:Parrainage/Category:cant_delete.html.twig', ['category'=>$entity, 'animals'=>$animals, 'categories'=>$categories]);
}
}
| {
"content_hash": "2fc7d2b0813e3033b4fad92bece1772e",
"timestamp": "",
"source": "github",
"line_count": 89,
"max_line_length": 160,
"avg_line_length": 37.62921348314607,
"alnum_prop": 0.5652433562257391,
"repo_name": "Grosloup/multisite3",
"id": "2a867773cab40ad9711a035495f2fd8d83a1aec2",
"size": "3357",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/ZPB/AdminBundle/Controller/Parrainage/CategoryController.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "177199"
},
{
"name": "JavaScript",
"bytes": "201999"
},
{
"name": "PHP",
"bytes": "998539"
},
{
"name": "Pascal",
"bytes": "5012"
},
{
"name": "Perl",
"bytes": "41853"
},
{
"name": "Puppet",
"bytes": "1056679"
},
{
"name": "Ruby",
"bytes": "2461593"
},
{
"name": "Shell",
"bytes": "82364"
},
{
"name": "VimL",
"bytes": "10301"
}
],
"symlink_target": ""
} |
using namespace std;
using namespace QuantLib;
boost::shared_ptr<YieldTermStructure>
flatRate(const Date& today,
const boost::shared_ptr<Quote>& forward,
const DayCounter& dc) {
return boost::shared_ptr<YieldTermStructure>(
new FlatForward(today, Handle<Quote>(forward), dc));
}
int main() {
const Size maturity = 2;
DayCounter dc = Actual365Fixed();
const Date today = Date::todaysDate();
const Real upperBarrier = 1.02;
const Real lowerBarrier = 0.86;
Settings::instance().evaluationDate() = today;
Handle<Quote> spot(boost::shared_ptr<Quote>(new SimpleQuote(1.)));
boost::shared_ptr<SimpleQuote> qRate(new SimpleQuote(0.0));
Handle<YieldTermStructure> qTS(flatRate(today, qRate, dc));
boost::shared_ptr<SimpleQuote> rRate(new SimpleQuote(0.05));
Handle<YieldTermStructure> rTS(flatRate(today, rRate, dc));
boost::shared_ptr<SimpleQuote> sRate(new SimpleQuote(0.0));
Handle<YieldTermStructure> sTS(flatRate(today, sRate, dc));
Handle<BlackVolTermStructure> vTS(boost::shared_ptr<BlackVolTermStructure>(new BlackConstantVol(today, NullCalendar(), 0.15, dc)));
const boost::shared_ptr<GeneralizedBlackScholesProcess> underlyingProcess(
new GeneralizedBlackScholesProcess(spot, qTS, sTS, vTS));
const Period monitorPeriod = Period(1, Weeks);
Schedule schedule(today, today + Period(maturity, Years),
monitorPeriod, TARGET(),
Following, Following,
DateGeneration::Forward, false);
std::vector<Time> times(schedule.size());
std::transform(schedule.begin(), schedule.end(), times.begin(),
boost::bind(&Actual365Fixed::yearFraction,
dc, today, boost::placeholders::_1, Date(), Date()));
TimeGrid grid(times.begin(), times.end());
std::vector<Real> redemption(times.size());
for (Size i=0; i < redemption.size(); ++i) {
redemption[i] = 1. + 0.16 * times[i];
}
typedef PseudoRandom::rsg_type rsg_type;
typedef MultiPathGenerator<rsg_type>::sample_type sample_type;
BigNatural seed = 42;
rsg_type rsg = PseudoRandom::make_sequence_generator(grid.size()-1, seed);
MultiPathGenerator<rsg_type> generator(underlyingProcess, grid, rsg, false);
GeneralStatistics stat;
Real antitheticPayoff=0;
const Size nrTrails = 3000;
for (Size i=0; i < nrTrails; ++i) {
const bool antithetic = (i%2)==0 ? false : true;
sample_type path = antithetic ? generator.antithetic()
: generator.next();
Real payoff=0;
for (Size j=1; j < times.size(); ++j) {
if (path.value[0][j] > upperBarrier * spot->value()) {
payoff = redemption[j] * rTS->discount(times[j]);
break;
}
else if (path.value[0][j] < lowerBarrier * spot->value())
{
payoff = path.value[0][j] * rTS->discount(times[j]);
break;
}
else if (j == times.size() - 1) {
payoff = redemption[j] * rTS->discount(times[j]);
}
}
if (antithetic){
stat.add(0.5*(antitheticPayoff + payoff));
}
else {
antitheticPayoff = payoff;
}
}
const Real calculated = stat.mean();
const Real error = stat.errorEstimate();
cout << "Calculated: " << calculated << "\nError esi.: " << error << endl;
return 0;
} | {
"content_hash": "be251fad7c540b30a8e725ba6a9d39e5",
"timestamp": "",
"source": "github",
"line_count": 101,
"max_line_length": 135,
"avg_line_length": 35.00990099009901,
"alnum_prop": 0.5995475113122172,
"repo_name": "ChinaQuants/qlengine",
"id": "3e85dc6a4aaa633b5b5c5bb9f02b4e7c99faf79c",
"size": "3584",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "QuantLib-Ext/examples/AutoCallable/AutoCallable.cpp",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Batchfile",
"bytes": "3311"
},
{
"name": "C++",
"bytes": "116227"
},
{
"name": "CMake",
"bytes": "12372"
},
{
"name": "M4",
"bytes": "12639"
},
{
"name": "Makefile",
"bytes": "5728"
},
{
"name": "Shell",
"bytes": "730918"
}
],
"symlink_target": ""
} |
package org.apache.geode.redis.internal.commands.executor.pubsub;
import org.junit.ClassRule;
import org.apache.geode.NativeRedisTestRule;
public class SubscriptionsNativeRedisAcceptanceTest extends AbstractSubscriptionsIntegrationTest {
@ClassRule
public static NativeRedisTestRule redis = new NativeRedisTestRule();
@Override
public int getPort() {
return redis.getPort();
}
}
| {
"content_hash": "89d4af61cbec83fcf219a03f0c88e2f7",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 98,
"avg_line_length": 22.22222222222222,
"alnum_prop": 0.7975,
"repo_name": "masaki-yamakawa/geode",
"id": "cf865263e084f4a8e369ba91df3f93e1d85927c2",
"size": "1189",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "geode-for-redis/src/acceptanceTest/java/org/apache/geode/redis/internal/commands/executor/pubsub/SubscriptionsNativeRedisAcceptanceTest.java",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "104031"
},
{
"name": "Dockerfile",
"bytes": "15935"
},
{
"name": "Go",
"bytes": "40709"
},
{
"name": "Groovy",
"bytes": "36499"
},
{
"name": "HTML",
"bytes": "4053180"
},
{
"name": "Java",
"bytes": "36217142"
},
{
"name": "JavaScript",
"bytes": "1780821"
},
{
"name": "Python",
"bytes": "29801"
},
{
"name": "Ruby",
"bytes": "1801"
},
{
"name": "SCSS",
"bytes": "2677"
},
{
"name": "Shell",
"bytes": "286170"
}
],
"symlink_target": ""
} |
// QtArg include.
#include <QtArg/Arg>
#include <QtArg/CmdLine>
// Qt include.
#include <QtCore/QString>
#include <QtCore/QStringList>
// unit test helper.
#include <test/helper/helper.hpp>
UNIT_TEST_START
//
// test_complex_1
//
UNIT_START( test_complex_1 )
QStringList arguments;
arguments << QLatin1String( "test" )
<< QLatin1String( "-a" ) << QLatin1String( "1" )
<< QLatin1String( "--bb" ) << QLatin1String( "2" )
<< QLatin1String( "--cc" ) << QLatin1String( "3" )
<< QLatin1String( "-d" ) << QLatin1String( "4" )
<< QLatin1String( "-e" ) << QLatin1String( "-f" )
<< QLatin1String( "-g" )
<< QLatin1String( "-i" ) << QLatin1String( "5" );
QtArgCmdLine cmd( arguments );
QtArg a( QLatin1Char( 'a' ), QString(), QString(), false, true );
QtArg b( QLatin1String( "bb" ), QString(), false, true );
QtArg c( QLatin1String( "cc" ), QString(), false, true );
QtArg d( QLatin1Char( 'd' ), QString(), QString(), false, true );
QtArg e( QLatin1Char( 'e' ), QString(), QString(), false, false );
QtArg f( QLatin1Char( 'f' ), QString(), QString(), false, false );
QtArg g( QLatin1Char( 'g' ), QString(), QString(), false, false );
QtArg i( QLatin1Char( 'i' ), QString(), QString(), false, true );
cmd.addArg( a );
cmd.addArg( b );
cmd.addArg( c );
cmd.addArg( d );
cmd.addArg( e );
cmd.addArg( f );
cmd.addArg( g );
cmd.addArg( i );
cmd.parse();
CHECK_CONDITION( a.value().toString() == QLatin1String( "1" ) )
CHECK_CONDITION( b.value().toString() == QLatin1String( "2" ) )
CHECK_CONDITION( c.value().toString() == QLatin1String( "3" ) )
CHECK_CONDITION( d.value().toString() == QLatin1String( "4" ) )
CHECK_CONDITION( e.value().toBool() == true )
CHECK_CONDITION( f.value().toBool() == true )
CHECK_CONDITION( g.value().toBool() == true )
CHECK_CONDITION( i.value().toString() == QLatin1String( "5" ) )
UNIT_FINISH( test_complex_1 )
//
// test_complex_2
//
UNIT_START( test_complex_2 )
QStringList arguments;
arguments << QLatin1String( "test" )
<< QLatin1String( "-a" ) << QLatin1String( "1" )
<< QLatin1String( "--bb" ) << QLatin1String( "2" )
<< QLatin1String( "--cc=3" )
<< QLatin1String( "-d4" )
<< QLatin1String( "-ef" )
<< QLatin1String( "-gi5" );
QtArgCmdLine cmd( arguments );
QtArg a( QLatin1Char( 'a' ), QString(), QString(), false, true );
QtArg b( QLatin1String( "bb" ), QString(), false, true );
QtArg c( QLatin1String( "cc" ), QString(), false, true );
QtArg d( QLatin1Char( 'd' ), QString(), QString(), false, true );
QtArg e( QLatin1Char( 'e' ), QString(), QString(), false, false );
QtArg f( QLatin1Char( 'f' ), QString(), QString(), false, false );
QtArg g( QLatin1Char( 'g' ), QString(), QString(), false, false );
QtArg i( QLatin1Char( 'i' ), QString(), QString(), false, true );
cmd.addArg( a );
cmd.addArg( b );
cmd.addArg( c );
cmd.addArg( d );
cmd.addArg( e );
cmd.addArg( f );
cmd.addArg( g );
cmd.addArg( i );
cmd.parse();
CHECK_CONDITION( a.value().toString() == QLatin1String( "1" ) )
CHECK_CONDITION( b.value().toString() == QLatin1String( "2" ) )
CHECK_CONDITION( c.value().toString() == QLatin1String( "3" ) )
CHECK_CONDITION( d.value().toString() == QLatin1String( "4" ) )
CHECK_CONDITION( e.value().toBool() == true )
CHECK_CONDITION( f.value().toBool() == true )
CHECK_CONDITION( g.value().toBool() == true )
CHECK_CONDITION( i.value().toString() == QLatin1String( "5" ) )
UNIT_FINISH( test_complex_2 )
//
// test_complex_3
//
UNIT_START( test_complex_3 )
QStringList arguments;
arguments << QLatin1String( "test" )
<< QLatin1String( "-a" ) << QLatin1String( "1" )
<< QLatin1String( "--bb" ) << QLatin1String( "2" )
<< QLatin1String( "--cc=3" ) << QLatin1String( "-d4" )
<< QLatin1String( "-efgi" ) << QLatin1String( "5" );
QtArgCmdLine cmd( arguments );
QtArg a( QLatin1Char( 'a' ), QString(), QString(), false, true );
QtArg b( QLatin1String( "bb" ), QString(), false, true );
QtArg c( QLatin1String( "cc" ), QString(), false, true );
QtArg d( QLatin1Char( 'd' ), QString(), QString(), false, true );
QtArg e( QLatin1Char( 'e' ), QString(), QString(), false, false );
QtArg f( QLatin1Char( 'f' ), QString(), QString(), false, false );
QtArg g( QLatin1Char( 'g' ), QString(), QString(), false, false );
QtArg i( QLatin1Char( 'i' ), QString(), QString(), false, true );
cmd.addArg( a );
cmd.addArg( b );
cmd.addArg( c );
cmd.addArg( d );
cmd.addArg( e );
cmd.addArg( f );
cmd.addArg( g );
cmd.addArg( i );
cmd.parse();
CHECK_CONDITION( a.value().toString() == QLatin1String( "1" ) )
CHECK_CONDITION( b.value().toString() == QLatin1String( "2" ) )
CHECK_CONDITION( c.value().toString() == QLatin1String( "3" ) )
CHECK_CONDITION( d.value().toString() == QLatin1String( "4" ) )
CHECK_CONDITION( e.value().toBool() == true )
CHECK_CONDITION( f.value().toBool() == true )
CHECK_CONDITION( g.value().toBool() == true )
CHECK_CONDITION( i.value().toString() == QLatin1String( "5" ) )
UNIT_FINISH( test_complex_3 )
//
// test_complex_4
//
UNIT_START( test_complex_4 )
QStringList arguments;
arguments << QLatin1String( "test" )
<< QLatin1String( "-a" ) << QLatin1String( "1" )
<< QLatin1String( "-b=2" )
<< QLatin1String( "-c3" )
<< QLatin1String( "-d" ) << QLatin1String( "4" );
QtArgCmdLine cmd( arguments );
QtArg a( QLatin1Char( 'a' ), QString(), QString(), false, true );
QtArg b( QLatin1Char( 'b' ), QString(), QString(), false, true );
QtArg c( QLatin1Char( 'c' ), QString(), QString(), false, true );
QtArg d( QLatin1Char( 'd' ), QString(), QString(), false, true );
cmd.addArg( a );
cmd.addArg( b );
cmd.addArg( c );
cmd.addArg( d );
cmd.parse();
CHECK_CONDITION( a.value().toString() == QLatin1String( "1" ) )
CHECK_CONDITION( b.value().toString() == QLatin1String( "2" ) )
CHECK_CONDITION( c.value().toString() == QLatin1String( "3" ) )
CHECK_CONDITION( d.value().toString() == QLatin1String( "4" ) )
UNIT_FINISH( test_complex_4 )
//
// test_complex_5
//
UNIT_START( test_complex_5 )
QStringList arguments;
arguments << QLatin1String( "test" )
<< QLatin1String( "--a1" ) << QLatin1String( "1" )
<< QLatin1String( "--b2=2" )
<< QLatin1String( "--c3=3" )
<< QLatin1String( "--d4" ) << QLatin1String( "4" );
QtArgCmdLine cmd( arguments );
QtArg a( QLatin1String( "a1" ), QString(), false, true );
QtArg b( QLatin1String( "b2" ), QString(), false, true );
QtArg c( QLatin1String( "c3" ), QString(), false, true );
QtArg d( QLatin1String( "d4" ), QString(), false, true );
cmd.addArg( a );
cmd.addArg( b );
cmd.addArg( c );
cmd.addArg( d );
cmd.parse();
CHECK_CONDITION( a.value().toString() == QLatin1String( "1" ) )
CHECK_CONDITION( b.value().toString() == QLatin1String( "2" ) )
CHECK_CONDITION( c.value().toString() == QLatin1String( "3" ) )
CHECK_CONDITION( d.value().toString() == QLatin1String( "4" ) )
UNIT_FINISH( test_complex_5 )
UNIT_TEST_FINISH
| {
"content_hash": "0e15577172cb620269a2499269a3eebd",
"timestamp": "",
"source": "github",
"line_count": 232,
"max_line_length": 68,
"avg_line_length": 31.025862068965516,
"alnum_prop": 0.5926646290636288,
"repo_name": "markusmarx/qtargparser",
"id": "bbd5343ad83c80ee4de2d2829da5bf547a78d790",
"size": "8381",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "test/complex/main.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "178371"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<workingSetManager>
<workingSet aggregate="true" factoryID="org.eclipse.ui.internal.WorkingSetFactory" id="1488265270341_0" label="Window Working Set" name="Aggregate for window 1488265270339"/>
</workingSetManager> | {
"content_hash": "43f85bf18cc74df57a9bf554e5b1a340",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 174,
"avg_line_length": 63.5,
"alnum_prop": 0.7834645669291339,
"repo_name": "bg1bgst333/Sample",
"id": "e270a2694d2e465f3524c7eac7c76b9baa49d88a",
"size": "254",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "android/WebViewClient/onPageFinished/src/WebViewClient/.metadata/.plugins/org.eclipse.ui.workbench/workingsets.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP.NET",
"bytes": "306893"
},
{
"name": "C",
"bytes": "1135468"
},
{
"name": "C#",
"bytes": "1243665"
},
{
"name": "C++",
"bytes": "4221060"
},
{
"name": "CMake",
"bytes": "147011"
},
{
"name": "CSS",
"bytes": "92700"
},
{
"name": "D",
"bytes": "504"
},
{
"name": "Go",
"bytes": "714"
},
{
"name": "HTML",
"bytes": "22314"
},
{
"name": "Java",
"bytes": "6233694"
},
{
"name": "JavaScript",
"bytes": "9675"
},
{
"name": "Kotlin",
"bytes": "252"
},
{
"name": "Makefile",
"bytes": "34822"
},
{
"name": "PHP",
"bytes": "12476"
},
{
"name": "Perl",
"bytes": "86739"
},
{
"name": "Python",
"bytes": "6272"
},
{
"name": "Raku",
"bytes": "160"
},
{
"name": "Roff",
"bytes": "1054"
},
{
"name": "Ruby",
"bytes": "747"
},
{
"name": "Rust",
"bytes": "209"
},
{
"name": "Shell",
"bytes": "186"
}
],
"symlink_target": ""
} |
var TagList = React.createClass({
render: function() {
var that = this;
var createTag = function(item, index) {
return (
<li>
<div className='tag'>
<span className='name'>{item.name}</span>
<span className='remove' onClick={that.props.removeTag.bind(that, item)}>x</span>
</div>
</li>
);
};
return <ul>{this.props.tags.map(createTag)}</ul>;
}
});
var TagInput = React.createClass({
getInitialState: function() {
return {
tags: this.props.tags
};
},
onKeyDown: function(e) {
if ((e.keyCode == 13)) {
this.addTag();
}
},
addTag: function(e) {
var nameDOM = React.findDOMNode(this.refs.name);
var name = nameDOM.value.trim();
if (!name)
return;
if (this.state.tags.map(function(e) { return e.name; }).indexOf(name) >= 0) {
alert("duplicated");
return;
}
nameDOM.value = "";
var nextItems = this.state.tags.concat([{name: name}]);
this.setState({tags: nextItems});
},
removeTag: function(tag) {
var index = this.state.tags.indexOf(tag);
if (index < 0)
return;
this.state.tags.splice(index, 1)
var nextItems = this.state.tags;
this.setState({tags: nextItems});
},
getTags: function() {
var tags = this.state.tags.map(function(e) { return e.name; });
return tags;
},
getTagsSerialize: function() {
var tags = this.state.tags.map(function(e) { return e.name; }).join(',');
return tags;
},
render: function() {
return (
<div className="tag-list">
<TagList tags={this.state.tags} removeTag={this.removeTag}/>
<div>
<input ref="name" className="tag-input" placeholder="+" onKeyDown={this.onKeyDown} />
<button type="button" className="btn btn-primary" onClick={this.addTag}>Add Tags</button>
</div>
</div>
);
},
});
var tagInput = React.render(<TagInput tags={[{name: 'tag1'},{name: 'tag2'},{name: 'tag3'}]} />, document.getElementById('example')); | {
"content_hash": "b5797bf33265dd9da433676972f677fb",
"timestamp": "",
"source": "github",
"line_count": 74,
"max_line_length": 132,
"avg_line_length": 31.87837837837838,
"alnum_prop": 0.5023314963967783,
"repo_name": "ffbli666/tagInput",
"id": "c63f9a6fbc7223cc176d81cacc43f03848ba96e6",
"size": "2359",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/react/tagInput.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1024"
},
{
"name": "HTML",
"bytes": "6978"
},
{
"name": "JavaScript",
"bytes": "498939"
}
],
"symlink_target": ""
} |
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Gallery'
db.create_table('gallery_gallery', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('name', self.gf('django.db.models.fields.CharField')(max_length=100)),
('slug', self.gf('django.db.models.fields.SlugField')(unique=True, max_length=50, db_index=True)),
('description', self.gf('django.db.models.fields.TextField')(null=True, blank=True)),
('parent_gallery', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['gallery.Gallery'], null=True, blank=True)),
('published', self.gf('django.db.models.fields.BooleanField')(default=False)),
('order', self.gf('django.db.models.fields.PositiveSmallIntegerField')(null=True, blank=True)),
('date_created', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, blank=True)),
('date_modified', self.gf('django.db.models.fields.DateTimeField')(auto_now=True, blank=True)),
))
db.send_create_signal('gallery', ['Gallery'])
# Adding model 'Picture'
db.create_table('gallery_picture', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('name', self.gf('django.db.models.fields.CharField')(max_length=100)),
('slug', self.gf('django.db.models.fields.SlugField')(unique=True, max_length=50, db_index=True)),
('original', self.gf('django.db.models.fields.files.ImageField')(max_length=100)),
('viewable', self.gf('django.db.models.fields.files.ImageField')(max_length=100)),
('thumbnail', self.gf('django.db.models.fields.files.ImageField')(max_length=100)),
('description', self.gf('django.db.models.fields.TextField')(null=True, blank=True)),
('gallery', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['gallery.Gallery'])),
('order', self.gf('django.db.models.fields.PositiveSmallIntegerField')(null=True, blank=True)),
('date_created', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, blank=True)),
('date_modified', self.gf('django.db.models.fields.DateTimeField')(auto_now=True, blank=True)),
))
db.send_create_signal('gallery', ['Picture'])
def backwards(self, orm):
# Deleting model 'Gallery'
db.delete_table('gallery_gallery')
# Deleting model 'Picture'
db.delete_table('gallery_picture')
models = {
'gallery.gallery': {
'Meta': {'ordering': "('order',)", 'object_name': 'Gallery'},
'date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'date_modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'order': ('django.db.models.fields.PositiveSmallIntegerField', [], {'null': 'True', 'blank': 'True'}),
'parent_gallery': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['gallery.Gallery']", 'null': 'True', 'blank': 'True'}),
'published': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '50', 'db_index': 'True'})
},
'gallery.picture': {
'Meta': {'ordering': "('order',)", 'object_name': 'Picture'},
'date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'date_modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'gallery': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['gallery.Gallery']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'order': ('django.db.models.fields.PositiveSmallIntegerField', [], {'null': 'True', 'blank': 'True'}),
'original': ('django.db.models.fields.files.ImageField', [], {'max_length': '100'}),
'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '50', 'db_index': 'True'}),
'thumbnail': ('django.db.models.fields.files.ImageField', [], {'max_length': '100'}),
'viewable': ('django.db.models.fields.files.ImageField', [], {'max_length': '100'})
}
}
complete_apps = ['gallery']
| {
"content_hash": "f984713ac76383c417148e49daa532de",
"timestamp": "",
"source": "github",
"line_count": 79,
"max_line_length": 148,
"avg_line_length": 64.73417721518987,
"alnum_prop": 0.5913179507235041,
"repo_name": "varikin/dali",
"id": "f5f7273990ac30ff9df526218684caf54a365f51",
"size": "5132",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "dali/gallery/migrations/0001_initial.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "JavaScript",
"bytes": "18209"
},
{
"name": "Python",
"bytes": "61378"
}
],
"symlink_target": ""
} |
package org.marat.workflow.demo.model;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class ProductBundle extends Product {
private static final long serialVersionUID = 5906465427616631321L;
private final List<Product> childProducts = new ArrayList<>();
public ProductBundle(final String productId) {
super(productId);
}
public ProductBundle addChildProduct(final Product product) {
childProducts.add(product);
return this;
}
public List<Product> getChildProducts() {
return Collections.unmodifiableList(childProducts);
}
}
| {
"content_hash": "8d46c95a43baafdc00657e1133b58bf4",
"timestamp": "",
"source": "github",
"line_count": 27,
"max_line_length": 67,
"avg_line_length": 21.85185185185185,
"alnum_prop": 0.7796610169491526,
"repo_name": "mratzer/workflow",
"id": "b67c8102bda83cae7c569ff62f02ddb2ccb3a82b",
"size": "1186",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "workflow-demo/src/main/java/org/marat/workflow/demo/model/ProductBundle.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "126430"
}
],
"symlink_target": ""
} |
{% load field_form %}
{{ form.non_field_errors }}
{% for field in form %}
{% if field.is_hidden %}
{{ field }}
{% else %}
<div class="form-field">
{% if field.errors %}
<div class="form-field-error">{{ field.errors }}</div>
{% endif %}
{% if field.field.widget|is_checkbox %}
<span class="form-checkbox">{{ field }} {{ field.label_tag }}</span>
{% else %}
<span class="form-input{% if field.errors %} input-error{% endif %}">{{ field.label_tag }} {{ field }}</span>
{% endif %}
{% if field.help_text %}
<div class="form-field-help">{{ field.help_text }}</div>
{% endif %}
</div>
{% endif %}
{% endfor %} | {
"content_hash": "0ff860b187ce065a21f431bbd350e0ca",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 122,
"avg_line_length": 36.38095238095238,
"alnum_prop": 0.4698952879581152,
"repo_name": "codefisher/djangopress",
"id": "219861d6a09d57dac8e7c26349ea1de5acefd2c1",
"size": "764",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "djangopress/core/templates/core/form.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "37234"
},
{
"name": "HTML",
"bytes": "66474"
},
{
"name": "JavaScript",
"bytes": "14582"
},
{
"name": "Python",
"bytes": "345188"
},
{
"name": "Shell",
"bytes": "813"
}
],
"symlink_target": ""
} |
using System.Xml.Serialization;
using Genesis.Net.Common;
namespace Genesis.Net.Entities.Requests.Query
{
[XmlRoot("retrieval_request_request", Namespace = "SingleRetrievalRequest")]
public class SingleRetrievalRequest : Request
{
public override string ApiPath
{
get
{
return "retrieval_requests";
}
}
[XmlElement(ElementName="arn")]
public string Arn { get; set; }
[XmlElement(ElementName="original_transaction_unique_id")]
public string OriginalTransactionUniqueId { get; set; }
public SingleRetrievalRequest()
{
}
}
} | {
"content_hash": "7bc3e31de6e44a7aeecad77ace9f47c2",
"timestamp": "",
"source": "github",
"line_count": 27,
"max_line_length": 80,
"avg_line_length": 24.925925925925927,
"alnum_prop": 0.6062407132243685,
"repo_name": "GenesisGateway/genesis_dotnet",
"id": "9fc8f105088637f7b94fd8825e265613bc05f7e6",
"size": "673",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Genesis.NET/Entities/Requests/Query/SingleRetrievalRequest.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "319"
},
{
"name": "C#",
"bytes": "3296563"
}
],
"symlink_target": ""
} |
module OpenProject::Revisions::Git
module Config
module GitoliteNotifications
extend self
def gitolite_notify_global_prefix
get_setting(:gitolite_notify_global_prefix)
end
def gitolite_notify_global_sender_address
get_setting(:gitolite_notify_global_sender_address)
end
def gitolite_notify_global_include
get_setting(:gitolite_notify_global_include)
end
def gitolite_notify_global_exclude
get_setting(:gitolite_notify_global_exclude)
end
end
end
end
| {
"content_hash": "8bb756ec7789073cdd2f64ed7ccaa7b5",
"timestamp": "",
"source": "github",
"line_count": 27,
"max_line_length": 59,
"avg_line_length": 20.59259259259259,
"alnum_prop": 0.6780575539568345,
"repo_name": "gwdg/openproject-revisions_git",
"id": "a5cc4f4101ca875a06bcbfb6999c249eebbf0959",
"size": "556",
"binary": false,
"copies": "2",
"ref": "refs/heads/dev",
"path": "lib/open_project/revisions/git/config/gitolite_notifications.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2753"
},
{
"name": "HTML",
"bytes": "62828"
},
{
"name": "Python",
"bytes": "145717"
},
{
"name": "Ruby",
"bytes": "209726"
}
],
"symlink_target": ""
} |
(function (app) {
'use strict';
app.provider('RSrcPixelDensity', RSrcPixelDensityProvider);
function RSrcPixelDensityProvider () {
// This lives in a separate provider so that it can be disabled / configured at app startup.
var pixelDensity =
(window.matchMedia(
'only screen and (-webkit-min-device-pixel-ratio: 3), ' + // Safari & iOS Safari & older android browser
'only screen and (min-resolution: 3dppx), ' + // Standard - Chrome, Firefox, Chrome for Android
'only screen and (min-resolution: 288dpi)' // IE 9-11, Opera Mini
).matches) ? 3 :
(window.matchMedia(
'only screen and (-webkit-min-device-pixel-ratio: 1.5), ' +
'only screen and (min-resolution: 1.5dppx), ' +
'only screen and (min-resolution: 144dpi)'
).matches) ? 2 :
1;
this.provideCustom = function RSrcCustomPixelDensity (customPixelDensity) {
if (typeof customPixelDensity === 'number') {
pixelDensity = customPixelDensity;
}
else if (typeof customPixelDensity === 'function') {
pixelDensity = customPixelDensity();
}
else {
throw new Error('RSrcPixelDensity.provideCustom must be passed either a pixel density as a number or a' +
' function to calculate it.');
}
};
this.$get = function RSrcPixelDensityFactory () {
return pixelDensity;
};
}
})(angular.module('ng-responsive-image.pixel-density', [
])); | {
"content_hash": "d020b8aa8d36527e17d3c0b53d136ff8",
"timestamp": "",
"source": "github",
"line_count": 49,
"max_line_length": 113,
"avg_line_length": 30.20408163265306,
"alnum_prop": 0.6297297297297297,
"repo_name": "nightswapping/ng-responsive-image",
"id": "07153e4826cfd90f21ba5dd35471cff1f00f7c31",
"size": "1480",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/pixel_density.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "33659"
}
],
"symlink_target": ""
} |
{% extends "base.html" %}
{% block head %}
{{ super() }}
<script src="{{ url_for('static',filename='bootstrap-datetimepicker.min.js') }}" charset="UTF-8"></script>
<link href="{{ url_for('static',filename='bootstrap-datetimepicker.min.css') }}" rel="stylesheet">
<script src="{{ url_for('static',filename='bootstrap-datetimepicker.zh-CN.js') }}" charset="UTF-8"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#base_exp_li').removeClass('active');
$('#base_need_li').removeClass('active');
$('#base_more_li').removeClass('active');
$('#base_plan_li').removeClass('active');
$('#base_worklog_li').removeClass('active');
$(".form_datetime").datetimepicker({
format: 'yyyy-mm-dd',
minView: 2,
autoclose: true,
todayHighlight: true,
todayBtn: true,
language: 'zh-CN'
});
var todos;
$.getJSON($SCRIPT_ROOT + '/_get_overview_info', {}, function (data) {
$('#all_projects').text(data['all_projects']);
$('#on_projects').text(data['on_projects']);
$('#all_applications').text(data['all_applications']);
$('#on_applications').text(data['on_applications']);
$('#all_needs').text(data['all_needs']);
$('#on_needs').text(data['on_needs']);
$('#all_tasks').text(data['all_tasks']);
$('#on_tasks').text(data['on_tasks']);
});
function refresh() {
$.getJSON($SCRIPT_ROOT + '/_get_task_info', {}, function (data) {
$('#todo_task_nums').text(data['todo_task_nums']);
$('#done_task_nums').text(data['done_task_nums']);
todos = data.todo_task_list;
var dones = data.done_task_list;
var todotable = "";
var d = new Date();
var vYear = d.getFullYear();
var vMon = d.getMonth() + 1;
var vDay = d.getDate();
var clientDate = vYear + '-' + (vMon < 10 ? "0" + vMon : vMon) + '-' + (vDay < 10 ? "0" + vDay : vDay);
for (var loop in todos) {
var trStyle = '';
//if(todos[loop]['plan_finish_time']>clientDate){
// trStyle='class="text-info"';
//}else if(todos[loop]['plan_finish_time']==clientDate){
// trStyle='class="text-warning"';
//}else{
// trStyle='class="text-danger"';
//}
todotable = todotable +
"<tr id='" + todos[loop]['id'] + "' " + trStyle + ">" +
"<td><input type='checkbox' data-toggle='modal' data-target='#myModal' data='" + loop + "'></td>" +
"<td>" + todos[loop]['stage_name'] + " " + todos[loop]['task_name'] + " " + todos[loop]['task_detail'] + "</td>" +
"<td>" + todos[loop]['plan_start_time'] + " ~ " + todos[loop]['plan_finish_time'] + "</td>" +
"<td>" + todos[loop]['status'] + "</td>" +
"<td>" + parseInt(todos[loop]['processing_progress'] * 100) + "%</td>" +
"<td>" + todos[loop]['comment'] + "</td>" +
"</tr>"
}
$('#todo_task_list').html(todotable)
var donetable = "";
for (var loop in dones) {
donetable = donetable +
"<tr id='" + dones[loop]['id'] + "'>" +
"<td><input type='checkbox' disabled='true' ></td>" +
"<td><del>" + dones[loop]['stage_name'] + " " + dones[loop]['task_name'] + " " + dones[loop]['task_detail'] + "</del></td>" +
"<td><del>" + dones[loop]['plan_start_time'] + " ~ " + dones[loop]['plan_finish_time'] + "</del></td>" +
"<td><del>" + dones[loop]['status'] + "</del></td>" +
"<td><del>" + dones[loop]['processing_progress'] * 100 + "%</del></td>" +
"<td><del>" + dones[loop]['comment'] + "</del></td>" +
"</tr>"
}
$('#done_task_list').html(donetable)
});
}
refresh();
$('#myModal').on('shown.bs.modal', function (event) {
var checkbox = $(event.relatedTarget);
var loop = checkbox.attr('data');
var modal = $(this);
var status = todos[loop]['status'];
$("#modalStatusSelect").val(status);
$("#start_date_selector").val(todos[loop]['real_start_time']);
$("#finish_date_selector").val(todos[loop]['real_finish_time']);
modal.find('#taskProgess').val(parseInt(todos[loop]['processing_progress'] * 100));
modal.find('#taskID').val(todos[loop]['id']);
modal.find('#taskComment').val(todos[loop]['comment']);
modal.find('#modalTitle').text(todos[loop]['stage_name'] + " " + todos[loop]['task_name'] + " " + todos[loop]['task_detail'])
});
$('#submitButton').on('click', function () {
var statusSelect = $("#modalStatusSelect");
var finishDate = $('#finish_date_selector');
var startDate = $('#start_date_selector');
var taskProgress = $('#taskProgess');
var taskComment = $('#taskComment');
var taskID = $('#taskID');
if ((statusSelect.val() == '已完成') && (finishDate.val().length < 3)) {
finishDate.addClass('alert-danger');
return
}
if ((statusSelect.val() == '已完成') && (taskProgress.val() != 100)) {
taskProgress.addClass('alert-danger');
return
}
if ((statusSelect.val() == '未开始') && (startDate.val().length > 3)) {
startDate.addClass('alert-danger');
return
}
$.post($SCRIPT_ROOT + "/_update_task", JSON.stringify({
id: taskID.val(),
status: statusSelect.val(),
progress: taskProgress.val(),
startdate: startDate.val(),
finishdate: finishDate.val(),
comment: taskComment.val()
}), function (data) {
if (data == 'ok') {
$('#myModal').modal('hide');
refresh();
}
});
});
$('#done_div').on('click', function () {
if ($('#done_task_nums').text() > 0) {
var done_task_list = $('#done_task_list');
if (done_task_list.hasClass('hidden')) {
done_task_list.removeClass('hidden');
} else {
done_task_list.addClass('hidden');
}
}
});
$('#myModal').on('hidden.bs.modal', function (event) {
$("input:checkbox").attr("checked", false);
});
function getActivity(lines) {
$.post($SCRIPT_ROOT + "/_get_activity", JSON.stringify({limits: lines}), function (data) {
var str = "";
for (var o in data.result) {
str = str + "<li class='list-group-item small'>" + data.result[o] + "</li>";
}
$('#activity_div').html(str);
});
}
getActivity(5);
$('#show_more_activity').on('click', function () {
if ($(this).hasClass('glyphicon-chevron-down')) {
$(this).removeClass('glyphicon-chevron-down');
getActivity(20);
$(this).addClass('glyphicon-chevron-up');
} else {
$(this).removeClass('glyphicon-chevron-up');
getActivity(5);
$(this).addClass('glyphicon-chevron-down');
}
});
$('#shareSubmitButton').on('click', function () {
var title = $.trim($('#shareTitle').val());
var summary = $.trim($('#shareSummary').val());
var url = $.trim($('#shareUrl').val());
if(!title){
showMessage('标题不能为空!','danger','shareMsgDiv');
$('#shareTitleInput').addClass('has-error');
return;
}
if(!summary){
showMessage('简介不能为空!','danger','shareMsgDiv');
$('#sharesummaryinput').addClass('has-error');
return;
}
$.post($SCRIPT_ROOT + '/_quick_add_share',
JSON.stringify({
title: title,
summary: summary,
url: url
}), function (data) {
if (data == 'ok') {
$('#shareModal').modal('hide');
$('#shareTitleInput').removeClass('has-error');
$('#sharesummaryinput').removeClass('has-error');
}
getExperience(12);
});
});
$('#show_share').click(function () {
location.href = '{{ url_for('experience') }}'
});
function getExperience(lines) {
$.post($SCRIPT_ROOT + "/_get_experience", JSON.stringify({limits: lines}), function (data) {
$('#share_content').html('');
for (var o in data.result) {
var str = '<div class="row"><div class="col-sm-8 small pull-left">';
if (data.result[o]['type'] == 1) {
str = str + '<span class="glyphicon glyphicon-option-vertical" aria-hidden="true"></span>';
} else {
str = str + '<span class="glyphicon glyphicon-grain" aria-hidden="true"></span>';
}
str = str + ' <a href="' + data.result[o]['url'] + '" target="_blank">' + data.result[o]['title'] + '</a> </div>';
str = str + '<div class="col-sm-4 small pull-right"><em>- ' + data.result[o]['user'] + ' ' + data.result[o]['modify_time'];
str = str + '</em></div><div class="col-sm-4 small pull-right"></div></div>'
$('#share_content').append(str);
}
});
}
getExperience(12);
})
</script>
{% endblock %}
{% block page_content %}
<div class="well well-sm">
<div class="row">
<div class="col-md-1"><strong>概览</strong></div>
<div class="col-md-2">项目 <code id="all_projects">-</code>/<code id="on_projects">-</code></div>
<div class="col-md-2">系统 <code id="all_applications">-</code>/<code id="on_applications">-</code></div>
<div class="col-md-2">需求 <code id="all_needs">-</code>/<code id="on_needs">-</code></div>
<div class="col-md-2">任务 <code id="all_tasks">-</code>/<code id="on_tasks">-</code></div>
</div>
</div>
<div class="panel panel-default small">
<div class="panel-heading"><h5>今日待办 <span class="badge" id="todo_task_nums">0</span></h5></div>
<table class="table" id="todo_task_list">
</table>
<div class="panel-footer" id="done_div"><strong id="done_task_nums">0</strong> 个已完成任务</div>
<table class="table hidden" id="done_task_list">
</table>
</div>
<div class="row">
<div class="col-md-6">
<div class="panel panel-default">
<div class="panel-heading">
<div class="row">
<div class="col-sm-2"><strong>活动</strong></div>
<div class="col-sm-10 text-right small"><span class="glyphicon glyphicon-chevron-down"
aria-hidden="true" id="show_more_activity"></span>
</div>
</div>
</div>
<div class="panel-body" id="activity_content">
<ul class='list-group' id="activity_div">
</ul>
</div>
</div>
</div>
<div class="col-md-6">
<div class="panel panel-default">
<div class="panel-heading">
<div class="row">
<div class="col-sm-2"><strong>分享</strong></div>
<div class="col-sm-10 text-right small">
<span class="glyphicon glyphicon-plus" aria-hidden="true" data-toggle='modal'
data-target='#shareModal'></span>
<span class="glyphicon glyphicon-new-window" aria-hidden="true" id="show_share"></span>
</div>
</div>
</div>
<div class="panel-body pre-scrollable" style="height: 241px;overflow-y: auto" id="share_content"></div>
</div>
</div>
</div>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
aria-hidden="true">×</span></button>
<h4 class="modal-title" id="modalTitle">任务进展</h4>
</div>
<div class="modal-body">
<form class="form-horizontal small">
<div class="form-group">
<label class="col-sm-2 control-label">任务状态</label>
<div class="col-sm-3">
<select class="form-control" id="modalStatusSelect">
{% for foo in task_status_choices %}
<option value="{{ foo[1] }}">{{ foo[1] }}</option>
{% endfor %}
</select>
</div>
<label class="col-sm-2 control-label">执行进度</label>
<div class="col-sm-3">
<input type="number" class="form-control" id="taskProgess" placeholder="%">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">开始时间</label>
<div class="col-sm-3">
<input type="text" size="16" readonly class="form_datetime form-control"
id="start_date_selector">
</div>
<label class="col-sm-2 control-label">结束时间</label>
<div class="col-sm-3">
<input type="text" size="16" readonly class="form_datetime form-control"
id="finish_date_selector">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">备注</label>
<div class="col-sm-8">
<textarea class="form-control" rows="2" id="taskComment"></textarea>
</div>
</div>
<input type="hidden" id="taskID" value="-1">
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
<button type="button" class="btn btn-primary" id="submitButton">提交</button>
</div>
</div>
</div>
</div>
<div class="modal fade" id="shareModal" tabindex="-1" role="dialog" aria-labelledby="shareModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
aria-hidden="true">×</span></button>
<h4 class="modal-title" id="shareModalTitle">快速分享</h4>
</div>
<div class="modal-body">
<div id="shareMsgDiv"></div>
<form class="form-horizontal small">
<div class="form-group">
<label class="col-sm-2 control-label">标题</label>
<div class="col-sm-9" id="shareTitleInput"><input type="text" class="form-control" id="shareTitle"
placeholder="必填"></div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">简介</label>
<div class="col-sm-9" id="shareSummaryInput">
<textarea class="form-control" rows="2" id="shareSummary" placeholder="必填"></textarea>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">链接</label>
<div class="col-sm-9" id="shareUrlInput"><input type="text" class="form-control" id="shareUrl"
placeholder="如:www.zhihu.com"></div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
<button type="button" class="btn btn-primary" id="shareSubmitButton">提交</button>
</div>
</div>
</div>
</div>
{% endblock %} | {
"content_hash": "71df75fbd177d712493dc90976726574",
"timestamp": "",
"source": "github",
"line_count": 363,
"max_line_length": 157,
"avg_line_length": 53.019283746556475,
"alnum_prop": 0.4162942949184246,
"repo_name": "frontc/Effect_PM",
"id": "09bebc3e82c3bf7988df9e0521d95ffb77cc4d98",
"size": "19426",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "pm/templates/index.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "110371"
},
{
"name": "JavaScript",
"bytes": "813"
},
{
"name": "Python",
"bytes": "77683"
}
],
"symlink_target": ""
} |
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Message.outgoing'
db.add_column('django_mailbox_message', 'outgoing',
self.gf('django.db.models.fields.BooleanField')(default=False),
keep_default=False)
def backwards(self, orm):
# Deleting field 'Message.outgoing'
db.delete_column('django_mailbox_message', 'outgoing')
models = {
'django_mailbox.mailbox': {
'Meta': {'object_name': 'Mailbox'},
'active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'uri': ('django.db.models.fields.CharField', [], {'default': 'None', 'max_length': '255', 'null': 'True', 'blank': 'True'})
},
'django_mailbox.message': {
'Meta': {'object_name': 'Message'},
'body': ('django.db.models.fields.TextField', [], {}),
'from_address': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'mailbox': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'messages'", 'to': "orm['django_mailbox.Mailbox']"}),
'message_id': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'outgoing': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'received': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'subject': ('django.db.models.fields.CharField', [], {'max_length': '255'})
}
}
complete_apps = ['django_mailbox']
| {
"content_hash": "2a47e30a04cf05c00a4052a29ec95ea4",
"timestamp": "",
"source": "github",
"line_count": 42,
"max_line_length": 145,
"avg_line_length": 46.88095238095238,
"alnum_prop": 0.5647536820721178,
"repo_name": "ad-m/django-mailbox",
"id": "245c43bb7e673d8cd464ff98440eac3f0b9383c3",
"size": "1969",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "django_mailbox/south_migrations/0004_auto__add_field_message_outgoing.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "145934"
}
],
"symlink_target": ""
} |
import * as React from 'react';
import * as moment from 'moment';
import { Layout } from '../layout';
import { UserState, UserProfile } from '../../redux/userState';
import {
getProfileInfo,
UserCallDetails
} from '../../redux/remoteData/asyncActionCreator';
interface Props {
readonly currentUser?: UserState;
}
interface State {
loadedProfile: boolean;
profile?: UserProfile;
}
const fakePhotoUrl = '/img/example-activist.jpg';
const fakeUserProfile = {
name: 'Example Activist',
sub: '',
exp: 0,
picture: fakePhotoUrl,
callDetails: {
weeklyStreak: 10,
stats: {
unavailable: 20,
contact: 203,
voicemail: 140
},
firstCallTime: 1494383929,
calls: [
{
date: 'Monday, Jun 18, 2018',
issues: [
{
count: 3,
issue_name: 'Support Sanctions to Check Trump\'s ZTE Deal'
},
{
count: 2,
issue_name: 'Protect Our Elections from Foreign Interference'
}
]
},
{
date: 'Sunday, Jun 10, 2018',
issues: [
{
count: 2,
issue_name: 'Protect Clean Air Car Emissions Standards'
},
{
count: 2,
issue_name:
'Urge Your State Reps to Pass Net Neutrality Protections'
}
]
}
]
}
} as UserProfile;
class ProfilePage extends React.Component<Props, State> {
constructor(props: Props) {
super(props);
this.state = { loadedProfile: false };
}
componentDidMount() {
getProfileInfo()
.then(profile => {
this.setState({ profile: profile, loadedProfile: true });
})
.catch(error => {
// console.log('error getting profile', error);
});
}
totalCalls(callDetails: UserCallDetails): number {
return (
callDetails.stats.contact +
callDetails.stats.unavailable +
callDetails.stats.voicemail
);
}
callLine(callDetails?: UserCallDetails): String {
if (callDetails === undefined || this.totalCalls(callDetails) === 0) {
return 'Make your first call today!';
}
let calls = this.totalCalls(callDetails) + ' Calls';
if (callDetails.weeklyStreak > 0) {
calls = calls + ' ⋆ ' + callDetails.weeklyStreak + ' Week Streak';
}
return calls;
}
firstCallTime(callDetails?: UserCallDetails): String {
if (callDetails && callDetails.firstCallTime > 0) {
const firstCall = moment.unix(callDetails.firstCallTime);
return 'Making Calls Since ' + firstCall.format('MMMM YYYY');
}
return '';
}
moreCalls(callDetails?: UserCallDetails): String {
if (callDetails && callDetails.calls.length === 0) {
return 'No calls made in the last 30 days';
}
return 'And calls from more than 30 days ago...';
}
profileContent(profile: UserProfile, fake: boolean) {
return (
<section className={`profile ${fake && 'preview'}`}>
<div className="profile-header">
<img src={profile.picture} />
<h1>{profile.name}</h1>
<h2>{this.callLine(profile.callDetails)}</h2>
<p>{this.firstCallTime(profile.callDetails)}</p>
</div>
{/* <ul className="profile-awards clearfix">
<li>🏅5 Calls Supporter</li>
<li>🏅Midterm Challenge</li>
</ul> */}
<div className="profile-history">
{profile.callDetails &&
profile.callDetails.calls.map((day, index) => {
return (
<span key={index}>
<div className="profile-history-day">
<h4>{day.date}</h4>
{day.issues.map((issue, issueIndex) => {
return (
<div className="profile-history-item" key={issueIndex}>
<img src="/img/5calls-stars-white.png" />
<p>
<strong>{issue.count} calls</strong> for{' '}
{issue.issue_name}
</p>
</div>
);
})}
</div>
<hr />
</span>
);
})}
<p>{this.moreCalls(profile.callDetails)}</p>
</div>
</section>
);
}
pageContent() {
if (this.props.currentUser && this.props.currentUser.profile) {
if (!this.state.profile) {
return (
<section className="loading">
<h2>Loading your profile info...</h2>
<p>This'll be just a moment</p>
</section>
);
} else {
return this.profileContent(this.state.profile, false);
}
} else {
// not logged in state
return (
<span>
<section className="loading">
<h2>Log in to see your call history 📊</h2>
<p>Your current call total will be saved</p>
</section>
{this.profileContent(fakeUserProfile, true)}
</span>
);
}
}
render() {
return <Layout>{this.pageContent()}</Layout>;
}
}
export default ProfilePage;
| {
"content_hash": "cd17f56d1f09f5e1347073764633be26",
"timestamp": "",
"source": "github",
"line_count": 195,
"max_line_length": 79,
"avg_line_length": 26.646153846153847,
"alnum_prop": 0.5277136258660509,
"repo_name": "5calls/5calls",
"id": "ce64eb8f46ed249ba5c78e4ed42d15e7bbd806c0",
"size": "5207",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/components/profile/ProfilePage.tsx",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "42508"
},
{
"name": "Go",
"bytes": "2644"
},
{
"name": "HTML",
"bytes": "25266"
},
{
"name": "JavaScript",
"bytes": "57667"
},
{
"name": "Makefile",
"bytes": "444"
},
{
"name": "SCSS",
"bytes": "45391"
},
{
"name": "TypeScript",
"bytes": "271665"
}
],
"symlink_target": ""
} |
from .empirical_distribution import ECDF, monotone_fn_inverter, StepFunction
from .edgeworth import ExpandedNormal
from .discrete import genpoisson_p, zipoisson, zigenpoisson, zinegbin
| {
"content_hash": "0d3bf203da454f647bd752a74923eb2e",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 76,
"avg_line_length": 61.666666666666664,
"alnum_prop": 0.8432432432432433,
"repo_name": "ChadFulton/statsmodels",
"id": "2941b495554102f72fbef5dfc0dd4f049d1d8f56",
"size": "185",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "statsmodels/distributions/__init__.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "AGS Script",
"bytes": "457842"
},
{
"name": "Assembly",
"bytes": "10035"
},
{
"name": "Batchfile",
"bytes": "3469"
},
{
"name": "C",
"bytes": "381"
},
{
"name": "HTML",
"bytes": "148470"
},
{
"name": "MATLAB",
"bytes": "2609"
},
{
"name": "Python",
"bytes": "11749760"
},
{
"name": "R",
"bytes": "90986"
},
{
"name": "Rebol",
"bytes": "123"
},
{
"name": "Shell",
"bytes": "8181"
},
{
"name": "Smarty",
"bytes": "1014"
},
{
"name": "Stata",
"bytes": "65045"
}
],
"symlink_target": ""
} |
(function(scope) {
var gui = require('nw.gui'),
clipboard = gui.Clipboard.get(),
totalProgress = 0,
currentMessage = '',
maximizeOnce = false;
var win = gui.Window.get();
/**
Exports
*/
scope.splashInfo = {};
scope.splashInfo.maximize = true;
scope.splashInfo.logging = false;
scope.splashInfo.set = function(info, progress, to) {
if (totalProgress == undefined) totalProgress = 0;
var setInfoInvoker = function() {
doSetInfo(info, progress)
};
if ( to && to > 0 ) {
setTimeout(setInfoInvoker, to);
} else {
setInfoInvoker(info, progress);
}
};
// \
var doSetInfo = function(info, progress) {
currentMessage = info;
totalProgress += progress;
totalProgress = Math.min(totalProgress, 100);
scope.splashInfo.logging && console.log("SPLASH: {progress: '" + totalProgress + "', message:'" + currentMessage + "'}");
clipboard.set("SPLASH: {progress: '" + totalProgress + "', message:'" + currentMessage + "'}", 'text');
if ( totalProgress >= 100 && !maximizeOnce ) {
maximizeOnce = true;
if ( scope.splashInfo.maximize ) win.maximize();
win.show();
}
}
})(window);
| {
"content_hash": "933cd2637aa5e7be3eda0cbdf36d4488",
"timestamp": "",
"source": "github",
"line_count": 41,
"max_line_length": 129,
"avg_line_length": 32.31707317073171,
"alnum_prop": 0.5486792452830188,
"repo_name": "the86freak/Splashscreen-Clipboard",
"id": "5106dc342ef01ce3188ff2d28b32968b45412c33",
"size": "1325",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "JS/splashInfo.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "480"
},
{
"name": "C++",
"bytes": "26669"
},
{
"name": "JavaScript",
"bytes": "1325"
}
],
"symlink_target": ""
} |
#pragma once
#include "ParticleDemo.h"
#define GLM_FORCE_CXX98
#include <glm/glm.hpp>
namespace Annulus
{
class Particle;
class ParticleSpring;
}
namespace Demos
{
class ParticleSpringDemo : public ParticleDemo
{
public:
/**
* Constructor.
* @param renderWindow A reference to the RenderWindow for which this demo is created.
* @param world A reference to the world for which this demo is created.
*/
ParticleSpringDemo(sf::RenderWindow& renderWindow, Annulus::ParticleWorld& world);
/**
* Destructor.
*/
~ParticleSpringDemo();
/**
* Initialize this demo.
*/
virtual void Initialize() override;
/**
* The Update method for this demo.
* @param nanoseconds The amount of time over which the Update is called.
*/
virtual void Update(std::chrono::nanoseconds nanoseconds) override;
/**
* Draw the demo.
*/
virtual void Draw() override;
private:
/**
* Particle in demo.
*/
Annulus::Particle* mParticle1;
/**
* Particle in demo.
*/
Annulus::Particle* mParticle2;
/**
* The spring force generator between the two particles.
*/
Annulus::ParticleSpring* mSpring;
/**
* Circle representing a particle.
*/
sf::CircleShape* mCircle1;
/**
* Circle representing a particle.
*/
sf::CircleShape* mCircle2;
/**
* The length of the spring in the rest state.
*/
const static std::float_t sSpringRestLength;
/**
* The spring constant for the spring.
*/
const static std::float_t sSpringConstant;
/**
* The initial position of the particle.
*/
const static glm::vec2 sParticlePosition1;
/**
* The initial position of the particle.
*/
const static glm::vec2 sParticlePosition2;
};
} | {
"content_hash": "2dbebd294b1c5885fb7267b1f008dce4",
"timestamp": "",
"source": "github",
"line_count": 80,
"max_line_length": 87,
"avg_line_length": 21.1125,
"alnum_prop": 0.6802841918294849,
"repo_name": "Siddhant628/Annulus-Physics-Engine",
"id": "e5c3b986272c3e14ba5d821ee1c79f4e8d6faae3",
"size": "1689",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Annulus/source/Testbed/ParticleSpringDemo.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C++",
"bytes": "153192"
}
],
"symlink_target": ""
} |
package com.amazonaws.services.datapipeline.model;
import java.io.Serializable;
import javax.annotation.Generated;
/**
* <p>
* Contains the output of QueryObjects.
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/QueryObjects" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class QueryObjectsResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {
/**
* <p>
* The identifiers that match the query selectors.
* </p>
*/
private com.amazonaws.internal.SdkInternalList<String> ids;
/**
* <p>
* The starting point for the next page of results. To view the next page of results, call <code>QueryObjects</code>
* again with this marker value. If the value is null, there are no more results.
* </p>
*/
private String marker;
/**
* <p>
* Indicates whether there are more results that can be obtained by a subsequent call.
* </p>
*/
private Boolean hasMoreResults;
/**
* <p>
* The identifiers that match the query selectors.
* </p>
*
* @return The identifiers that match the query selectors.
*/
public java.util.List<String> getIds() {
if (ids == null) {
ids = new com.amazonaws.internal.SdkInternalList<String>();
}
return ids;
}
/**
* <p>
* The identifiers that match the query selectors.
* </p>
*
* @param ids
* The identifiers that match the query selectors.
*/
public void setIds(java.util.Collection<String> ids) {
if (ids == null) {
this.ids = null;
return;
}
this.ids = new com.amazonaws.internal.SdkInternalList<String>(ids);
}
/**
* <p>
* The identifiers that match the query selectors.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if any). Use
* {@link #setIds(java.util.Collection)} or {@link #withIds(java.util.Collection)} if you want to override the
* existing values.
* </p>
*
* @param ids
* The identifiers that match the query selectors.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public QueryObjectsResult withIds(String... ids) {
if (this.ids == null) {
setIds(new com.amazonaws.internal.SdkInternalList<String>(ids.length));
}
for (String ele : ids) {
this.ids.add(ele);
}
return this;
}
/**
* <p>
* The identifiers that match the query selectors.
* </p>
*
* @param ids
* The identifiers that match the query selectors.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public QueryObjectsResult withIds(java.util.Collection<String> ids) {
setIds(ids);
return this;
}
/**
* <p>
* The starting point for the next page of results. To view the next page of results, call <code>QueryObjects</code>
* again with this marker value. If the value is null, there are no more results.
* </p>
*
* @param marker
* The starting point for the next page of results. To view the next page of results, call
* <code>QueryObjects</code> again with this marker value. If the value is null, there are no more results.
*/
public void setMarker(String marker) {
this.marker = marker;
}
/**
* <p>
* The starting point for the next page of results. To view the next page of results, call <code>QueryObjects</code>
* again with this marker value. If the value is null, there are no more results.
* </p>
*
* @return The starting point for the next page of results. To view the next page of results, call
* <code>QueryObjects</code> again with this marker value. If the value is null, there are no more results.
*/
public String getMarker() {
return this.marker;
}
/**
* <p>
* The starting point for the next page of results. To view the next page of results, call <code>QueryObjects</code>
* again with this marker value. If the value is null, there are no more results.
* </p>
*
* @param marker
* The starting point for the next page of results. To view the next page of results, call
* <code>QueryObjects</code> again with this marker value. If the value is null, there are no more results.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public QueryObjectsResult withMarker(String marker) {
setMarker(marker);
return this;
}
/**
* <p>
* Indicates whether there are more results that can be obtained by a subsequent call.
* </p>
*
* @param hasMoreResults
* Indicates whether there are more results that can be obtained by a subsequent call.
*/
public void setHasMoreResults(Boolean hasMoreResults) {
this.hasMoreResults = hasMoreResults;
}
/**
* <p>
* Indicates whether there are more results that can be obtained by a subsequent call.
* </p>
*
* @return Indicates whether there are more results that can be obtained by a subsequent call.
*/
public Boolean getHasMoreResults() {
return this.hasMoreResults;
}
/**
* <p>
* Indicates whether there are more results that can be obtained by a subsequent call.
* </p>
*
* @param hasMoreResults
* Indicates whether there are more results that can be obtained by a subsequent call.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public QueryObjectsResult withHasMoreResults(Boolean hasMoreResults) {
setHasMoreResults(hasMoreResults);
return this;
}
/**
* <p>
* Indicates whether there are more results that can be obtained by a subsequent call.
* </p>
*
* @return Indicates whether there are more results that can be obtained by a subsequent call.
*/
public Boolean isHasMoreResults() {
return this.hasMoreResults;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getIds() != null)
sb.append("Ids: ").append(getIds()).append(",");
if (getMarker() != null)
sb.append("Marker: ").append(getMarker()).append(",");
if (getHasMoreResults() != null)
sb.append("HasMoreResults: ").append(getHasMoreResults());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof QueryObjectsResult == false)
return false;
QueryObjectsResult other = (QueryObjectsResult) obj;
if (other.getIds() == null ^ this.getIds() == null)
return false;
if (other.getIds() != null && other.getIds().equals(this.getIds()) == false)
return false;
if (other.getMarker() == null ^ this.getMarker() == null)
return false;
if (other.getMarker() != null && other.getMarker().equals(this.getMarker()) == false)
return false;
if (other.getHasMoreResults() == null ^ this.getHasMoreResults() == null)
return false;
if (other.getHasMoreResults() != null && other.getHasMoreResults().equals(this.getHasMoreResults()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getIds() == null) ? 0 : getIds().hashCode());
hashCode = prime * hashCode + ((getMarker() == null) ? 0 : getMarker().hashCode());
hashCode = prime * hashCode + ((getHasMoreResults() == null) ? 0 : getHasMoreResults().hashCode());
return hashCode;
}
@Override
public QueryObjectsResult clone() {
try {
return (QueryObjectsResult) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
}
| {
"content_hash": "2ac54fd6283bfa1b499604d1e284220f",
"timestamp": "",
"source": "github",
"line_count": 276,
"max_line_length": 145,
"avg_line_length": 32.52536231884058,
"alnum_prop": 0.6062158850395455,
"repo_name": "aws/aws-sdk-java",
"id": "9c97c416d33acb56c9fa7e81443b93a5fc82cd6f",
"size": "9557",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "aws-java-sdk-datapipeline/src/main/java/com/amazonaws/services/datapipeline/model/QueryObjectsResult.java",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
"""
Inject README.rst to __init__.py and cli.py
README.rst has to have a section "CLI" followed by "Python interface".
The section "CLI" has to be underlined by "-".
"""
from __future__ import print_function
import re
def stripout_docstring(file, keep_title):
pre_lines = []
post_lines = []
for line in file:
pre_lines.append(line)
if re.match('^r?["\']{3}$', line):
is_in_title = True
for line in file:
if re.match('^["\']{3}$', line):
post_lines.append(line)
break
if keep_title and is_in_title:
pre_lines.append(line)
if line.strip() == '':
is_in_title = False
break
post_lines.extend(file)
return pre_lines, post_lines
def inject_rst(path, rst, keep_title=False):
with open(path) as file:
pre_lines, post_lines = stripout_docstring(file, keep_title)
rst_str = ''.join(rst)
if keep_title:
rst_str = rst_str.strip() + '\n'
with open(path, 'w') as file:
file.writelines(pre_lines)
file.write(rst_str)
file.writelines(post_lines)
def inject_readme(readme, init_py, cli_py):
init_rst = []
cli_rst = []
with open(readme) as file:
for line in file:
if line.rstrip() == 'CLI':
next_line = next(file)
if not re.match('^-+$', next_line):
raise RuntimeError('Unrecognized line after CLI: {}'
.format(next_line))
for line in file:
if line.rstrip() == 'Python interface':
break
cli_rst.append(line)
init_rst.append(line)
inject_rst(init_py, init_rst)
inject_rst(cli_py, cli_rst, keep_title=True)
def make_parser(doc=__doc__):
import argparse
parser = argparse.ArgumentParser(
formatter_class=type('FormatterClass',
(argparse.RawDescriptionHelpFormatter,
argparse.ArgumentDefaultsHelpFormatter),
{}),
description=doc)
parser.add_argument('readme', nargs='?', default='README.rst')
parser.add_argument('--init-py', default='src/dictsdiff/__init__.py')
parser.add_argument('--cli-py', default='src/dictsdiff/cli.py')
return parser
def main(args=None):
parser = make_parser()
ns = parser.parse_args(args)
inject_readme(**vars(ns))
if __name__ == '__main__':
main()
| {
"content_hash": "8775d96b284381ba9176470613e56598",
"timestamp": "",
"source": "github",
"line_count": 88,
"max_line_length": 73,
"avg_line_length": 29.556818181818183,
"alnum_prop": 0.5290272971933871,
"repo_name": "tkf/dictsdiff",
"id": "c163dbddeb4f393912c7a39480df83db0f91907e",
"size": "2625",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "misc/inject_readme.py",
"mode": "33261",
"license": "bsd-2-clause",
"language": [
{
"name": "Makefile",
"bytes": "719"
},
{
"name": "Python",
"bytes": "30861"
}
],
"symlink_target": ""
} |
var WordNet=require('node-wordnet')
var word;
module.exports = function(options) {
return function(socket, next) {
//console.log("%s connected.", socket.user);
socket
.on('message', function(message) {
if (/^\/dic\s.*$/.test(message)) {
word=message.slice(5).trim();
var wordnet = new WordNet()
wordnet.lookup(word, function(results) {
results.forEach(function(result) {
if (word==result.lemma)
socket.emit('message', {u: "Dictionary", m: '<p>'+result.lemma.bold()+' ('+result.pos+')</p><p>'+result.gloss+'</p><p>Synonyms: '+result.synonyms+'</p>', dictionary: true});
});
});
}
});
next();
};
}; | {
"content_hash": "0ca1925d5d884a98de6376c3704ca8af",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 178,
"avg_line_length": 28.375,
"alnum_prop": 0.5756240822320118,
"repo_name": "Flameborn/ding.ga",
"id": "a0b161026aaa0ffd69edbea5e5ced0908d833445",
"size": "681",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ding-dic/index.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "4632"
},
{
"name": "JavaScript",
"bytes": "16256"
}
],
"symlink_target": ""
} |
package com.emajliramokade
package services
package impl
import api.model.ImageSave.Zahtjev
import hr.ngs.patterns.ISerialization
class GoImageSaver(
val serialization: ISerialization[String])
extends abstracts.RemoteImageSaver
with RemotingDispatch[Zahtjev] {
val method = "PUT"
def serviceUrlFactory(t: Zahtjev) =
s"http://emajliramokade.com:10080/Kada/${ t.getKadaID }/Slike"
}
| {
"content_hash": "7ddf0c3385e8f086bbe154c734462233",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 66,
"avg_line_length": 22.72222222222222,
"alnum_prop": 0.7603911980440098,
"repo_name": "element-doo/ekade",
"id": "ba700fb3f8e2eb487880e88aa55210dfd732ed7a",
"size": "409",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "code/scala/Services/src/main/scala/com/emajliramokade/services/impl/GoImageSaver.scala",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ASP",
"bytes": "98"
},
{
"name": "C",
"bytes": "25705"
},
{
"name": "C#",
"bytes": "17967"
},
{
"name": "C++",
"bytes": "15638"
},
{
"name": "CSS",
"bytes": "740408"
},
{
"name": "Clojure",
"bytes": "5023"
},
{
"name": "CoffeeScript",
"bytes": "9248"
},
{
"name": "Common Lisp",
"bytes": "6895"
},
{
"name": "Go",
"bytes": "539925"
},
{
"name": "Haskell",
"bytes": "8556"
},
{
"name": "Java",
"bytes": "279851"
},
{
"name": "JavaScript",
"bytes": "744735"
},
{
"name": "Objective-C",
"bytes": "10198"
},
{
"name": "PHP",
"bytes": "926811"
},
{
"name": "Python",
"bytes": "6837"
},
{
"name": "Rust",
"bytes": "31817"
},
{
"name": "Scala",
"bytes": "55803"
},
{
"name": "Shell",
"bytes": "5315"
}
],
"symlink_target": ""
} |
// PlantUML Studio
// Copyright 2013 Matthew Hamilton - matthamilton@live.com
// Copyright 2010 Omar Al Zabir - http://omaralzabir.com/ (original author)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System.Windows.Controls;
namespace PlantUmlStudio.View
{
/// <summary>
/// Interaction logic for StatusBar.xaml
/// </summary>
public partial class StatusBar : UserControl
{
public StatusBar()
{
InitializeComponent();
}
}
}
| {
"content_hash": "67c740feffe244bfec896f7d5156d50c",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 76,
"avg_line_length": 31.451612903225808,
"alnum_prop": 0.7220512820512821,
"repo_name": "mthamil/PlantUMLStudio",
"id": "b90112136fda5400396b9bfc2aa1ca17677eac5a",
"size": "977",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "PlantUmlStudio/View/StatusBar.xaml.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "782187"
},
{
"name": "HTML",
"bytes": "54771"
}
],
"symlink_target": ""
} |
json_file '/tmp/kitchen/data/created.json' do
data node['data_file_test']['data']
owner 'nobody'
group 'nogroup'
mode '01666'
end
file '/tmp/kitchen/data/mangled-existing.txt' do
content 'this should not be here'
action :nothing
end
json_file '/tmp/kitchen/data/existing.json' do
data modified: true
action :create_if_missing
notifies :create, 'file[/tmp/kitchen/data/mangled-existing.txt]'
end
json_file '/tmp/kitchen/data/delete-me.json' do
action :delete
end
| {
"content_hash": "31ceba8d980ed1cb616c78956bc44e2a",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 66,
"avg_line_length": 25.428571428571427,
"alnum_prop": 0.6573033707865169,
"repo_name": "3ofcoins/chef-cookbook-data_file",
"id": "32ce2c233eeeb07529a2aee84662a7601b521cf3",
"size": "534",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/cookbooks/data_file_test/recipes/actions_and_properties.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "6088"
},
{
"name": "Shell",
"bytes": "188"
}
],
"symlink_target": ""
} |
"use strict";
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var util = require("../util");
var AudioNode = require("./AudioNode");
var IIRFilterNodeDSP = require("./dsp/IIRFilterNode");
var IIRFilterNode = function (_AudioNode) {
_inherits(IIRFilterNode, _AudioNode);
/**
* @param {AudioContext} context
* @param {object} opts
* @param {Float32Array} opts.feedforward
* @param {Float32Array} opts.feedback
*/
function IIRFilterNode(context, opts) {
_classCallCheck(this, IIRFilterNode);
opts = opts || /* istanbul ignore next */{};
var feedforward = util.defaults(opts.feedforward, [0]);
var feedback = util.defaults(opts.feedback, [1]);
var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(IIRFilterNode).call(this, context, {
inputs: [1],
outputs: [1],
channelCount: 2,
channelCountMode: "max"
}));
_this._feedforward = feedforward;
_this._feedback = feedback;
_this.dspInit();
_this.dspUpdateKernel(1);
return _this;
}
/**
* @param {Float32Array} frequencyHz
* @param {Float32Array} magResponse
* @param {Float32Array} phaseResponse
*/
/* istanbul ignore next */
_createClass(IIRFilterNode, [{
key: "getFrequencyResponse",
value: function getFrequencyResponse() {
throw new TypeError("NOT YET IMPLEMENTED");
}
/**
* @return {Float32Array}
*/
}, {
key: "getFeedforward",
value: function getFeedforward() {
return this._feedforward;
}
/**
* @return {Float32Array}
*/
}, {
key: "getFeedback",
value: function getFeedback() {
return this._feedback;
}
/**
* @param {number} numberOfChannels
*/
}, {
key: "channelDidUpdate",
value: function channelDidUpdate(numberOfChannels) {
this.dspUpdateKernel(numberOfChannels);
this.outputs[0].setNumberOfChannels(numberOfChannels);
}
}]);
return IIRFilterNode;
}(AudioNode);
Object.assign(IIRFilterNode.prototype, IIRFilterNodeDSP);
module.exports = IIRFilterNode; | {
"content_hash": "b82fa1d6a3b5e64fd889f4e8608c3de7",
"timestamp": "",
"source": "github",
"line_count": 99,
"max_line_length": 564,
"avg_line_length": 35.303030303030305,
"alnum_prop": 0.6804005722460658,
"repo_name": "g200kg/LiveBeats",
"id": "2f545386e49f012b7ee75355f2b455f692c38b2d",
"size": "3495",
"binary": false,
"copies": "1",
"ref": "refs/heads/gh-pages",
"path": "node_modules/web-audio-engine/lib/impl/IIRFilterNode.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "188184"
},
{
"name": "JavaScript",
"bytes": "112365"
}
],
"symlink_target": ""
} |
"""
A Python Statsd implementation with some datadog special sauce.
"""
# set up logging before importing any other components
from config import initialize_logging # noqa
initialize_logging('dogstatsd')
from utils.proxy import set_no_proxy_settings # noqa
set_no_proxy_settings()
# stdlib
import logging
import optparse
import os
import select
import signal
import socket
import sys
import threading
from time import sleep, time
from urllib import urlencode
import zlib
# For pickle & PID files, see issue 293
os.umask(022)
# 3rd party
import requests
import simplejson as json
# project
from aggregator import get_formatter, MetricsBucketAggregator
from checks.check_status import DogstatsdStatus
from checks.metric_types import MetricTypes
from config import get_config, get_version
from daemon import AgentSupervisor, Daemon
from util import chunks, get_uuid, plural
from utils.hostname import get_hostname
from utils.pidfile import PidFile
from utils.net import inet_pton
from utils.net import IPV6_V6ONLY, IPPROTO_IPV6
# urllib3 logs a bunch of stuff at the info level
requests_log = logging.getLogger("requests.packages.urllib3")
requests_log.setLevel(logging.WARN)
requests_log.propagate = True
log = logging.getLogger('dogstatsd')
PID_NAME = "dogstatsd"
PID_DIR = None
# Dogstatsd constants in seconds
DOGSTATSD_FLUSH_INTERVAL = 10
DOGSTATSD_AGGREGATOR_BUCKET_SIZE = 10
WATCHDOG_TIMEOUT = 120
UDP_SOCKET_TIMEOUT = 5
# Since we call flush more often than the metrics aggregation interval, we should
# log a bunch of flushes in a row every so often.
FLUSH_LOGGING_PERIOD = 70
FLUSH_LOGGING_INITIAL = 10
FLUSH_LOGGING_COUNT = 5
EVENT_CHUNK_SIZE = 50
COMPRESS_THRESHOLD = 1024
def add_serialization_status_metric(status, hostname):
"""
Add a metric to track the number of metric serializations,
tagged by their status.
"""
interval = 10.0
value = 1
return {
'tags': ["status:{0}".format(status)],
'metric': 'datadog.dogstatsd.serialization_status',
'interval': interval,
'device_name': None,
'host': hostname,
'points': [(time(), value / interval)],
'type': MetricTypes.RATE,
}
def unicode_metrics(metrics):
for i, metric in enumerate(metrics):
for key, value in metric.items():
if isinstance(value, basestring):
metric[key] = unicode(value, errors='replace')
elif isinstance(value, tuple) or isinstance(value, list):
value_list = list(value)
for j, value_element in enumerate(value_list):
if isinstance(value_element, basestring):
value_list[j] = unicode(value_element, errors='replace')
metric[key] = tuple(value_list)
metrics[i] = metric
return metrics
def serialize_metrics(metrics, hostname):
try:
metrics.append(add_serialization_status_metric("success", hostname))
serialized = json.dumps({"series": metrics})
except UnicodeDecodeError as e:
log.exception("Unable to serialize payload. Trying to replace bad characters. %s", e)
metrics.append(add_serialization_status_metric("failure", hostname))
try:
log.error(metrics)
serialized = json.dumps({"series": unicode_metrics(metrics)})
except Exception as e:
log.exception("Unable to serialize payload. Giving up. %s", e)
serialized = json.dumps({"series": [add_serialization_status_metric("permanent_failure", hostname)]})
if len(serialized) > COMPRESS_THRESHOLD:
headers = {'Content-Type': 'application/json',
'Content-Encoding': 'deflate'}
serialized = zlib.compress(serialized)
else:
headers = {'Content-Type': 'application/json'}
return serialized, headers
def serialize_event(event):
return json.dumps(event)
def mapto_v6(addr):
"""
Map an IPv4 address to an IPv6 one.
If the address is already an IPv6 one, just return it.
Return None if the IP address is not valid.
"""
try:
inet_pton(socket.AF_INET, addr)
return '::ffff:{}'.format(addr)
except socket.error:
try:
inet_pton(socket.AF_INET6, addr)
return addr
except socket.error:
log.debug('%s is not a valid IP address.', addr)
return None
def get_socket_address(host, port, ipv4_only=False):
"""
Gather informations to open the server socket.
Try to resolve the name giving precedence to IPv4 for retro compatibility
but still mapping the host to an IPv6 address, fallback to IPv6.
"""
try:
info = socket.getaddrinfo(host, port, socket.AF_INET, socket.SOCK_DGRAM)
except socket.gaierror as e:
try:
if not ipv4_only:
info = socket.getaddrinfo(host, port, socket.AF_INET6, socket.SOCK_DGRAM)
elif host == 'localhost':
log.warning("Warning localhost seems undefined in your host file, using 127.0.0.1 instead")
info = socket.getaddrinfo('127.0.0.1', port, socket.AF_INET, socket.SOCK_DGRAM)
else:
log.error('Error processing host %s and port %s: %s', host, port, e)
return None
except socket.gaierror as e:
log.error('Error processing host %s and port %s: %s', host, port, e)
return None
# we get the first item of the list and map the address for IPv4 hosts
sockaddr = info[0][-1]
if info[0][0] == socket.AF_INET and not ipv4_only:
mapped_host = mapto_v6(sockaddr[0])
sockaddr = (mapped_host, sockaddr[1], 0, 0)
return sockaddr
class Reporter(threading.Thread):
"""
The reporter periodically sends the aggregated metrics to the
server.
"""
def __init__(self, interval, metrics_aggregator, api_host, api_key=None,
use_watchdog=False, event_chunk_size=None):
threading.Thread.__init__(self)
self.interval = int(interval)
self.finished = threading.Event()
self.metrics_aggregator = metrics_aggregator
self.flush_count = 0
self.log_count = 0
self.hostname = get_hostname()
self.watchdog = None
if use_watchdog:
from util import Watchdog
self.watchdog = Watchdog(WATCHDOG_TIMEOUT)
self.api_key = api_key
self.api_host = api_host
self.event_chunk_size = event_chunk_size or EVENT_CHUNK_SIZE
def stop(self):
log.info("Stopping reporter")
self.finished.set()
def run(self):
log.info("Reporting to %s every %ss" % (self.api_host, self.interval))
log.debug("Watchdog enabled: %s" % bool(self.watchdog))
# Persist a start-up message.
DogstatsdStatus().persist()
while not self.finished.isSet(): # Use camel case isSet for 2.4 support.
self.finished.wait(self.interval)
self.metrics_aggregator.send_packet_count('datadog.dogstatsd.packet.count')
self.flush()
if self.watchdog:
self.watchdog.reset()
# Clean up the status messages.
log.debug("Stopped reporter")
DogstatsdStatus.remove_latest_status()
def flush(self):
try:
self.flush_count += 1
self.log_count += 1
packets_per_second = self.metrics_aggregator.packets_per_second(self.interval)
packet_count = self.metrics_aggregator.total_count
metrics = self.metrics_aggregator.flush()
count = len(metrics)
if self.flush_count % FLUSH_LOGGING_PERIOD == 0:
self.log_count = 0
if count:
self.submit(metrics)
events = self.metrics_aggregator.flush_events()
event_count = len(events)
if event_count:
self.submit_events(events)
service_checks = self.metrics_aggregator.flush_service_checks()
service_check_count = len(service_checks)
if service_check_count:
self.submit_service_checks(service_checks)
should_log = self.flush_count <= FLUSH_LOGGING_INITIAL or self.log_count <= FLUSH_LOGGING_COUNT
log_func = log.info
if not should_log:
log_func = log.debug
log_func("Flush #%s: flushed %s metric%s, %s event%s, and %s service check run%s" % (self.flush_count, count, plural(count), event_count, plural(event_count), service_check_count, plural(service_check_count)))
if self.flush_count == FLUSH_LOGGING_INITIAL:
log.info("First flushes done, %s flushes will be logged every %s flushes." % (FLUSH_LOGGING_COUNT, FLUSH_LOGGING_PERIOD))
# Persist a status message.
packet_count = self.metrics_aggregator.total_count
DogstatsdStatus(
flush_count=self.flush_count,
packet_count=packet_count,
packets_per_second=packets_per_second,
metric_count=count,
event_count=event_count,
service_check_count=service_check_count,
).persist()
except Exception:
if self.finished.isSet():
log.debug("Couldn't flush metrics, but that's expected as we're stopping")
else:
log.exception("Error flushing metrics")
def submit(self, metrics):
body, headers = serialize_metrics(metrics, self.hostname)
params = {}
if self.api_key:
params['api_key'] = self.api_key
url = '%s/api/v1/series?%s' % (self.api_host, urlencode(params))
self.submit_http(url, body, headers)
def submit_events(self, events):
headers = {'Content-Type':'application/json'}
event_chunk_size = self.event_chunk_size
for chunk in chunks(events, event_chunk_size):
payload = {
'apiKey': self.api_key,
'events': {
'api': chunk
},
'uuid': get_uuid(),
'internalHostname': get_hostname()
}
params = {}
if self.api_key:
params['api_key'] = self.api_key
url = '%s/intake?%s' % (self.api_host, urlencode(params))
self.submit_http(url, json.dumps(payload), headers)
def submit_http(self, url, data, headers):
headers["DD-Dogstatsd-Version"] = get_version()
log.debug("Posting payload to %s" % url)
try:
start_time = time()
r = requests.post(url, data=data, timeout=5, headers=headers)
r.raise_for_status()
if r.status_code >= 200 and r.status_code < 205:
log.debug("Payload accepted")
status = r.status_code
duration = round((time() - start_time) * 1000.0, 4)
log.debug("%s POST %s (%sms)" % (status, url, duration))
except Exception:
log.exception("Unable to post payload.")
try:
log.error("Received status code: {0}".format(r.status_code))
except Exception:
pass
def submit_service_checks(self, service_checks):
headers = {'Content-Type':'application/json'}
params = {}
if self.api_key:
params['api_key'] = self.api_key
url = '{0}/api/v1/check_run?{1}'.format(self.api_host, urlencode(params))
self.submit_http(url, json.dumps(service_checks), headers)
class Server(object):
"""
A statsd udp server.
"""
def __init__(self, metrics_aggregator, host, port, forward_to_host=None, forward_to_port=None):
self.sockaddr = None
self.socket = None
self.metrics_aggregator = metrics_aggregator
self.host = host
self.port = port
self.buffer_size = 1024 * 8
self.running = False
self.should_forward = forward_to_host is not None
self.forward_udp_sock = None
# In case we want to forward every packet received to another statsd server
if self.should_forward:
if forward_to_port is None:
forward_to_port = 8125
log.info("External statsd forwarding enabled. All packets received will be forwarded to %s:%s" % (forward_to_host, forward_to_port))
try:
self.forward_udp_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.forward_udp_sock.connect((forward_to_host, forward_to_port))
except Exception:
log.exception("Error while setting up connection to external statsd server")
def start(self):
"""
Run the server.
"""
ipv4_only = False
try:
# Bind to the UDP socket in IPv4 and IPv6 compatibility mode
self.socket = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
# Configure the socket so that it accepts connections from both
# IPv4 and IPv6 networks in a portable manner.
self.socket.setsockopt(IPPROTO_IPV6, IPV6_V6ONLY, 0)
except Exception:
log.info('unable to create IPv6 socket, falling back to IPv4.')
self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
ipv4_only = True
self.socket.setblocking(0)
#let's get the sockaddr
self.sockaddr = get_socket_address(self.host, int(self.port), ipv4_only=ipv4_only)
try:
self.socket.bind(self.sockaddr)
except TypeError:
log.error('Unable to start Dogstatsd server loop, exiting...')
return
log.info('Listening on socket address: %s', str(self.sockaddr))
# Inline variables for quick look-up.
buffer_size = self.buffer_size
aggregator_submit = self.metrics_aggregator.submit_packets
sock = [self.socket]
socket_recv = self.socket.recv
select_select = select.select
select_error = select.error
timeout = UDP_SOCKET_TIMEOUT
should_forward = self.should_forward
forward_udp_sock = self.forward_udp_sock
# Run our select loop.
self.running = True
message = None
while self.running:
try:
ready = select_select(sock, [], [], timeout)
if ready[0]:
message = socket_recv(buffer_size)
aggregator_submit(message)
if should_forward:
forward_udp_sock.send(message)
except select_error as se:
# Ignore interrupted system calls from sigterm.
errno = se[0]
if errno != 4:
raise
except (KeyboardInterrupt, SystemExit):
break
except Exception:
log.exception('Error receiving datagram `%s`', message)
def stop(self):
self.running = False
class Dogstatsd(Daemon):
""" This class is the dogstatsd daemon. """
def __init__(self, pid_file, server, reporter, autorestart):
Daemon.__init__(self, pid_file, autorestart=autorestart)
self.server = server
self.reporter = reporter
def _handle_sigterm(self, signum, frame):
log.debug("Caught sigterm. Stopping run loop.")
self.server.stop()
def run(self):
# Gracefully exit on sigterm.
signal.signal(signal.SIGTERM, self._handle_sigterm)
# Handle Keyboard Interrupt
signal.signal(signal.SIGINT, self._handle_sigterm)
# Start the reporting thread before accepting data
self.reporter.start()
try:
try:
self.server.start()
except Exception as e:
log.exception(
'Error starting dogstatsd server on %s', self.server.sockaddr)
raise e
finally:
# The server will block until it's done. Once we're here, shutdown
# the reporting thread.
self.reporter.stop()
self.reporter.join()
log.info("Dogstatsd is stopped")
# Restart if asked to restart
if self.autorestart:
sys.exit(AgentSupervisor.RESTART_EXIT_STATUS)
@classmethod
def info(self):
logging.getLogger().setLevel(logging.ERROR)
return DogstatsdStatus.print_latest_status()
def init(config_path=None, use_watchdog=False, use_forwarder=False, args=None):
"""Configure the server and the reporting thread.
"""
c = get_config(parse_args=False, cfg_path=config_path)
if (not c['use_dogstatsd'] and
(args and args[0] in ['start', 'restart'] or not args)):
log.info("Dogstatsd is disabled. Exiting")
# We're exiting purposefully, so exit with zero (supervisor's expected
# code). HACK: Sleep a little bit so supervisor thinks we've started cleanly
# and thus can exit cleanly.
sleep(4)
sys.exit(0)
port = c['dogstatsd_port']
interval = DOGSTATSD_FLUSH_INTERVAL
api_key = c['api_key']
aggregator_interval = DOGSTATSD_AGGREGATOR_BUCKET_SIZE
non_local_traffic = c['non_local_traffic']
forward_to_host = c.get('statsd_forward_host')
forward_to_port = c.get('statsd_forward_port')
event_chunk_size = c.get('event_chunk_size')
recent_point_threshold = c.get('recent_point_threshold', None)
server_host = c['bind_host']
target = c['dd_url']
if use_forwarder:
target = c['dogstatsd_target']
hostname = get_hostname(c)
# Create the aggregator (which is the point of communication between the
# server and reporting threads.
assert 0 < interval
aggregator = MetricsBucketAggregator(
hostname,
aggregator_interval,
recent_point_threshold=recent_point_threshold,
formatter=get_formatter(c),
histogram_aggregates=c.get('histogram_aggregates'),
histogram_percentiles=c.get('histogram_percentiles'),
utf8_decoding=c['utf8_decoding']
)
# Start the reporting thread.
reporter = Reporter(interval, aggregator, target, api_key, use_watchdog, event_chunk_size)
# NOTICE: when `non_local_traffic` is passed we need to bind to any interface on the box. The forwarder uses
# Tornado which takes care of sockets creation (more than one socket can be used at once depending on the
# network settings), so it's enough to just pass an empty string '' to the library.
# In Dogstatsd we use a single, fullstack socket, so passing '' as the address doesn't work and we default to
# '0.0.0.0'. If someone needs to bind Dogstatsd to the IPv6 '::', they need to turn off `non_local_traffic` and
# use the '::' meta address as `bind_host`.
if non_local_traffic:
server_host = '0.0.0.0'
server = Server(aggregator, server_host, port, forward_to_host=forward_to_host, forward_to_port=forward_to_port)
return reporter, server, c
def main(config_path=None):
""" The main entry point for the unix version of dogstatsd. """
# Deprecation notice
from utils.deprecations import deprecate_old_command_line_tools
deprecate_old_command_line_tools()
COMMANDS_START_DOGSTATSD = [
'start',
'stop',
'restart',
'status'
]
parser = optparse.OptionParser("%prog [start|stop|restart|status]")
parser.add_option('-u', '--use-local-forwarder', action='store_true',
dest="use_forwarder", default=False)
opts, args = parser.parse_args()
if not args or args[0] in COMMANDS_START_DOGSTATSD:
reporter, server, cnf = init(config_path, use_watchdog=True, use_forwarder=opts.use_forwarder, args=args)
daemon = Dogstatsd(PidFile(PID_NAME, PID_DIR).get_path(), server, reporter,
cnf.get('autorestart', False))
# If no args were passed in, run the server in the foreground.
if not args:
daemon.start(foreground=True)
return 0
# Otherwise, we're process the deamon command.
else:
command = args[0]
if command == 'start':
daemon.start()
elif command == 'stop':
daemon.stop()
elif command == 'restart':
daemon.restart()
elif command == 'status':
daemon.status()
elif command == 'info':
return Dogstatsd.info()
else:
sys.stderr.write("Unknown command: %s\n\n" % command)
parser.print_help()
return 1
return 0
if __name__ == '__main__':
sys.exit(main())
| {
"content_hash": "9e3b51e515d17579b86d47d9aed424a6",
"timestamp": "",
"source": "github",
"line_count": 588,
"max_line_length": 221,
"avg_line_length": 35.326530612244895,
"alnum_prop": 0.6089928750240708,
"repo_name": "Wattpad/dd-agent",
"id": "bc00647e31eab2a0007cbe9ccce5dcd19371d3a4",
"size": "20921",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "dogstatsd.py",
"mode": "33261",
"license": "bsd-3-clause",
"language": [
{
"name": "ApacheConf",
"bytes": "2753"
},
{
"name": "Go",
"bytes": "2389"
},
{
"name": "HTML",
"bytes": "8536"
},
{
"name": "Nginx",
"bytes": "3908"
},
{
"name": "PowerShell",
"bytes": "2665"
},
{
"name": "Python",
"bytes": "2490407"
},
{
"name": "Ruby",
"bytes": "86890"
},
{
"name": "Shell",
"bytes": "76283"
},
{
"name": "XSLT",
"bytes": "2222"
}
],
"symlink_target": ""
} |
<?php
namespace humhub\modules\admin\models;
use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use humhub\modules\user\models\User;
/**
* Description of UserSearch
*
* @author luke
*/
class UserApprovalSearch extends User
{
public function attributes()
{
// add related fields to searchable attributes
return array_merge(parent::attributes(), ['profile.firstname', 'profile.lastname', 'group.name', 'group.id']);
}
public function rules()
{
return [
[['id', 'group.id'], 'integer'],
[['username', 'email', 'created_at', 'profile.firstname', 'profile.lastname'], 'safe'],
];
}
/**
* @inheritdoc
*/
public function scenarios()
{
// bypass scenarios() implementation in the parent class
return Model::scenarios();
}
/**
* Creates data provider instance with search query applied
*
* @param array $params
*
* @return ActiveDataProvider
*/
public function search($params = [])
{
$query = User::find()->joinWith(['profile', 'groups']);
$dataProvider = new ActiveDataProvider([
'query' => $query,
'pagination' => ['pageSize' => 50],
]);
$dataProvider->setSort([
'attributes' => [
'username',
'email',
'super_admin',
'profile.firstname',
'profile.lastname',
'created_at',
]
]);
$this->load($params);
if (!$this->validate()) {
$query->where('0=1');
return $dataProvider;
}
/**
* Limit Groups
*/
$groups = $this->getGroups();
$groupIds = [];
foreach ($groups as $group) {
$groupIds[] = $group->id;
}
$query->andWhere(['IN', 'group.id', $groupIds]);
$query->andWhere(['status' => User::STATUS_NEED_APPROVAL]);
$query->andFilterWhere(['id' => $this->id]);
$query->andFilterWhere(['like', 'id', $this->id]);
$query->andFilterWhere(['like', 'username', $this->username]);
$query->andFilterWhere(['like', 'email', $this->email]);
$query->andFilterWhere(['like', 'profile.firstname', $this->getAttribute('profile.firstname')]);
$query->andFilterWhere(['like', 'profile.lastname', $this->getAttribute('profile.lastname')]);
return $dataProvider;
}
public static function getUserApprovalCount()
{
return User::find()->where(['status' => User::STATUS_NEED_APPROVAL])->count();
}
/**
* Get approval groups
*/
public function getGroups()
{
if (Yii::$app->user->isAdmin()) {
return \humhub\modules\user\models\Group::find()->all();
} else {
return Yii::$app->user->getIdentity()->managerGroups;
}
}
} | {
"content_hash": "e7f969f89bb043a0af6731862f2a5956",
"timestamp": "",
"source": "github",
"line_count": 114,
"max_line_length": 118,
"avg_line_length": 25.894736842105264,
"alnum_prop": 0.5274390243902439,
"repo_name": "LeonidLyalin/vova",
"id": "af77139d4953c92468fba245c8725092feb65be7",
"size": "3090",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "common/humhub/protected/humhub/modules/admin/models/UserApprovalSearch.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ApacheConf",
"bytes": "227"
},
{
"name": "Batchfile",
"bytes": "3096"
},
{
"name": "CSS",
"bytes": "824207"
},
{
"name": "HTML",
"bytes": "25309"
},
{
"name": "JavaScript",
"bytes": "1284304"
},
{
"name": "PHP",
"bytes": "8757729"
},
{
"name": "Ruby",
"bytes": "375"
},
{
"name": "Shell",
"bytes": "3256"
}
],
"symlink_target": ""
} |
from telemetry.page import page_test
from telemetry.timeline.model import TimelineModel
from telemetry.timeline import tracing_config
from telemetry.util import statistics
from telemetry.value import scalar
class V8GCTimes(page_test.PageTest):
_TIME_OUT_IN_SECONDS = 60
_CATEGORIES = ['blink.console',
'renderer.scheduler',
'v8',
'webkit.console']
_RENDERER_MAIN_THREAD = 'CrRendererMain'
_IDLE_TASK_PARENT = 'SingleThreadIdleTaskRunner::RunTask'
def __init__(self):
super(V8GCTimes, self).__init__()
def WillNavigateToPage(self, page, tab):
config = tracing_config.TracingConfig()
for category in self._CATEGORIES:
config.tracing_category_filter.AddIncludedCategory(category)
config.enable_chrome_trace = True
tab.browser.platform.tracing_controller.StartTracing(
config, self._TIME_OUT_IN_SECONDS)
def ValidateAndMeasurePage(self, page, tab, results):
trace_data = tab.browser.platform.tracing_controller.StopTracing()
timeline_model = TimelineModel(trace_data)
renderer_process = timeline_model.GetRendererProcessFromTabId(tab.id)
self._AddV8MetricsToResults(renderer_process, results)
def DidRunPage(self, platform):
if platform.tracing_controller.is_tracing_running:
platform.tracing_controller.StopTracing()
def _AddV8MetricsToResults(self, process, results):
if process is None:
return
for thread in process.threads.values():
if thread.name != self._RENDERER_MAIN_THREAD:
continue
self._AddV8EventStatsToResults(thread, results)
self._AddCpuTimeStatsToResults(thread, results)
def _AddV8EventStatsToResults(self, thread, results):
v8_event_stats = [
V8EventStat('V8.GCIncrementalMarking',
'v8_gc_incremental_marking',
'incremental marking steps'),
V8EventStat('V8.GCScavenger',
'v8_gc_scavenger',
'scavenges'),
V8EventStat('V8.GCCompactor',
'v8_gc_mark_compactor',
'mark-sweep-compactor'),
V8EventStat('V8.GCFinalizeMC',
'v8_gc_finalize_incremental',
'finalization of incremental marking'),
V8EventStat('V8.GCFinalizeMCReduceMemory',
'v8_gc_finalize_incremental_reduce_memory',
'finalization of incremental marking with memory reducer')]
# Find all V8 GC events in the trace.
for event in thread.IterAllSlices():
event_stat = _FindV8EventStatForEvent(v8_event_stats, event.name)
if not event_stat:
continue
event_stat.thread_duration += event.thread_duration
event_stat.max_thread_duration = max(event_stat.max_thread_duration,
event.thread_duration)
event_stat.count += 1
parent_idle_task = _ParentIdleTask(event)
if parent_idle_task:
allotted_idle_time = parent_idle_task.args['allotted_time_ms']
idle_task_wall_overrun = 0
if event.duration > allotted_idle_time:
idle_task_wall_overrun = event.duration - allotted_idle_time
# Don't count time over the deadline as being inside idle time.
# Since the deadline should be relative to wall clock we compare
# allotted_time_ms with wall duration instead of thread duration, and
# then assume the thread duration was inside idle for the same
# percentage of time.
inside_idle = event.thread_duration * statistics.DivideIfPossibleOrZero(
event.duration - idle_task_wall_overrun, event.duration)
event_stat.thread_duration_inside_idle += inside_idle
event_stat.idle_task_overrun_duration += idle_task_wall_overrun
for v8_event_stat in v8_event_stats:
results.AddValue(scalar.ScalarValue(
results.current_page, v8_event_stat.result_name, 'ms',
v8_event_stat.thread_duration,
description=('Total thread duration spent in %s' %
v8_event_stat.result_description)))
results.AddValue(scalar.ScalarValue(
results.current_page, '%s_max' % v8_event_stat.result_name, 'ms',
v8_event_stat.max_thread_duration,
description=('Max thread duration spent in %s' %
v8_event_stat.result_description)))
results.AddValue(scalar.ScalarValue(
results.current_page, '%s_count' % v8_event_stat.result_name, 'count',
v8_event_stat.count,
description=('Number of %s' %
v8_event_stat.result_description)))
average_thread_duration = statistics.DivideIfPossibleOrZero(
v8_event_stat.thread_duration, v8_event_stat.count)
results.AddValue(scalar.ScalarValue(
results.current_page, '%s_average' % v8_event_stat.result_name, 'ms',
average_thread_duration,
description=('Average thread duration spent in %s' %
v8_event_stat.result_description)))
results.AddValue(scalar.ScalarValue(results.current_page,
'%s_outside_idle' % v8_event_stat.result_name, 'ms',
v8_event_stat.thread_duration_outside_idle,
description=(
'Total thread duration spent in %s outside of idle tasks' %
v8_event_stat.result_description)))
results.AddValue(scalar.ScalarValue(results.current_page,
'%s_idle_deadline_overrun' % v8_event_stat.result_name, 'ms',
v8_event_stat.idle_task_overrun_duration,
description=('Total idle task deadline overrun for %s idle tasks'
% v8_event_stat.result_description)))
results.AddValue(scalar.ScalarValue(results.current_page,
'%s_percentage_idle' % v8_event_stat.result_name, 'idle%',
v8_event_stat.percentage_thread_duration_during_idle,
description=('Percentage of %s spent in idle time' %
v8_event_stat.result_description)))
# Add total metrics.
gc_total = sum(x.thread_duration for x in v8_event_stats)
gc_total_outside_idle = sum(
x.thread_duration_outside_idle for x in v8_event_stats)
gc_total_idle_deadline_overrun = sum(
x.idle_task_overrun_duration for x in v8_event_stats)
gc_total_percentage_idle = statistics.DivideIfPossibleOrZero(
100 * (gc_total - gc_total_outside_idle), gc_total)
results.AddValue(scalar.ScalarValue(results.current_page,
'v8_gc_total', 'ms', gc_total,
description='Total thread duration of all garbage collection events'))
results.AddValue(scalar.ScalarValue(results.current_page,
'v8_gc_total_outside_idle', 'ms', gc_total_outside_idle,
description=(
'Total thread duration of all garbage collection events outside of '
'idle tasks')))
results.AddValue(scalar.ScalarValue(results.current_page,
'v8_gc_total_idle_deadline_overrun', 'ms',
gc_total_idle_deadline_overrun,
description=(
'Total idle task deadline overrun for all idle tasks garbage '
'collection events')))
results.AddValue(scalar.ScalarValue(results.current_page,
'v8_gc_total_percentage_idle', 'idle%', gc_total_percentage_idle,
description=(
'Percentage of the thread duration of all garbage collection '
'events spent inside of idle tasks')))
def _AddCpuTimeStatsToResults(self, thread, results):
if thread.toplevel_slices:
start_time = min(s.start for s in thread.toplevel_slices)
end_time = max(s.end for s in thread.toplevel_slices)
duration = end_time - start_time
cpu_time = sum(s.thread_duration for s in thread.toplevel_slices)
else:
duration = cpu_time = 0
results.AddValue(scalar.ScalarValue(
results.current_page, 'duration', 'ms', duration))
results.AddValue(scalar.ScalarValue(
results.current_page, 'cpu_time', 'ms', cpu_time))
def _FindV8EventStatForEvent(v8_event_stats_list, event_name):
for v8_event_stat in v8_event_stats_list:
if v8_event_stat.src_event_name == event_name:
return v8_event_stat
return None
def _ParentIdleTask(event):
parent = event.parent_slice
while parent:
# pylint: disable=protected-access
if parent.name == V8GCTimes._IDLE_TASK_PARENT:
return parent
parent = parent.parent_slice
return None
class V8EventStat(object):
def __init__(self, src_event_name, result_name, result_description):
self.src_event_name = src_event_name
self.result_name = result_name
self.result_description = result_description
self.thread_duration = 0.0
self.thread_duration_inside_idle = 0.0
self.idle_task_overrun_duration = 0.0
self.max_thread_duration = 0.0
self.count = 0
@property
def thread_duration_outside_idle(self):
return self.thread_duration - self.thread_duration_inside_idle
@property
def percentage_thread_duration_during_idle(self):
return statistics.DivideIfPossibleOrZero(
100 * self.thread_duration_inside_idle, self.thread_duration)
| {
"content_hash": "80ab82413537e7fb56b793f8b64505fe",
"timestamp": "",
"source": "github",
"line_count": 214,
"max_line_length": 80,
"avg_line_length": 42.77570093457944,
"alnum_prop": 0.6597116014856893,
"repo_name": "XiaosongWei/chromium-crosswalk",
"id": "90543f223d4d83c229a9ea404eb4ece24451d6ac",
"size": "9317",
"binary": false,
"copies": "7",
"ref": "refs/heads/master",
"path": "tools/perf/measurements/v8_gc_times.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
package com.hp.autonomy.searchcomponents.idol.answer.requests;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
@SuppressWarnings("unused")
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type", defaultImpl = ConversationRequestImpl.class)
@JsonSubTypes(@JsonSubTypes.Type(ConversationRequestImpl.class))
public interface ConversationRequestMixin {
}
| {
"content_hash": "a97f9c7c8b8d05947dccc5cefd10a092",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 141,
"avg_line_length": 38,
"alnum_prop": 0.8289473684210527,
"repo_name": "hpe-idol/haven-search-components",
"id": "5ed63fdc009d852c3b761b5f654957f04adda5dd",
"size": "627",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "idol/src/main/java/com/hp/autonomy/searchcomponents/idol/answer/requests/ConversationRequestMixin.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "924451"
},
{
"name": "Shell",
"bytes": "223"
}
],
"symlink_target": ""
} |
package com.cloudbees.lxd.client.api;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import javax.annotation.Generated;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.Map;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"id",
"class",
"created_at",
"updated_at",
"status",
"status_code",
"resources",
"metadata",
"may_cancel",
"err"
})
public class Operation implements Serializable {
@JsonProperty("id")
private String id;
@JsonProperty("class")
private String clazz;
@JsonProperty("created_at")
private Date createdAt;
@JsonProperty("updated_at")
private Date updatedAt;
@JsonProperty("status")
private String status;
@JsonProperty("status_code")
private StatusCode statusCode;
@JsonProperty("resources")
private Map<String, List<String>> resources;
@JsonProperty("metadata")
private Map<String, Object> metadata;
@JsonProperty("may_cancel")
private String mayCancel;
@JsonProperty("err")
private String err;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getClazz() {
return clazz;
}
public void setClazz(String clazz) {
this.clazz = clazz;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public Date getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public StatusCode getStatusCode() {
return statusCode;
}
public void setStatusCode(StatusCode statusCode) {
this.statusCode = statusCode;
}
public Map<String, List<String>> getResources() {
return resources;
}
public void setResources(Map<String, List<String>> resources) {
this.resources = resources;
}
public Map<String, Object> getMetadata() {
return metadata;
}
public void setMetadata(Map<String, Object> metadata) {
this.metadata = metadata;
}
public String getMayCancel() {
return mayCancel;
}
public void setMayCancel(String mayCancel) {
this.mayCancel = mayCancel;
}
public String getErr() {
return err;
}
public void setErr(String err) {
this.err = err;
}
@Override
public String toString() {
return "Operation{" +
"id='" + id + '\'' +
", clazz='" + clazz + '\'' +
", createdAt='" + createdAt + '\'' +
", updatedAt='" + updatedAt + '\'' +
", status='" + status + '\'' +
", statusCode=" + statusCode +
", resources=" + resources +
", metadata='" + metadata + '\'' +
", mayCancel='" + mayCancel + '\'' +
", err='" + err + '\'' +
'}';
}
}
| {
"content_hash": "eac374f440a990060c5be241ac716dfd",
"timestamp": "",
"source": "github",
"line_count": 154,
"max_line_length": 67,
"avg_line_length": 21.441558441558442,
"alnum_prop": 0.5896426408237432,
"repo_name": "cloudbees-oss/lxd-client",
"id": "b9c9082436a60cfb4427d5b620eff9fb9e834995",
"size": "4443",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/cloudbees/lxd/client/api/Operation.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Go",
"bytes": "15990"
},
{
"name": "Java",
"bytes": "207899"
},
{
"name": "Makefile",
"bytes": "3864"
},
{
"name": "Shell",
"bytes": "976"
}
],
"symlink_target": ""
} |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.azurestackhci.fluent.models;
import com.azure.core.annotation.Immutable;
import com.azure.resourcemanager.azurestackhci.models.Operation;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
/**
* A list of REST API operations supported by an Azure Resource Provider. It contains an URL link to get the next set of
* results.
*/
@Immutable
public final class OperationListResultInner {
/*
* List of operations supported by the resource provider
*/
@JsonProperty(value = "value", access = JsonProperty.Access.WRITE_ONLY)
private List<Operation> value;
/*
* URL to get the next set of operation list results (if there are any).
*/
@JsonProperty(value = "nextLink", access = JsonProperty.Access.WRITE_ONLY)
private String nextLink;
/**
* Get the value property: List of operations supported by the resource provider.
*
* @return the value value.
*/
public List<Operation> value() {
return this.value;
}
/**
* Get the nextLink property: URL to get the next set of operation list results (if there are any).
*
* @return the nextLink value.
*/
public String nextLink() {
return this.nextLink;
}
/**
* Validates the instance.
*
* @throws IllegalArgumentException thrown if the instance is not valid.
*/
public void validate() {
if (value() != null) {
value().forEach(e -> e.validate());
}
}
}
| {
"content_hash": "0235e931cb43d262fa943f02a11e588a",
"timestamp": "",
"source": "github",
"line_count": 58,
"max_line_length": 120,
"avg_line_length": 29.20689655172414,
"alnum_prop": 0.666469893742621,
"repo_name": "Azure/azure-sdk-for-java",
"id": "cd70af853a48e276d5b9e11cd1cc8dac28597f27",
"size": "1694",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "sdk/azurestackhci/azure-resourcemanager-azurestackhci/src/main/java/com/azure/resourcemanager/azurestackhci/fluent/models/OperationListResultInner.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "8762"
},
{
"name": "Bicep",
"bytes": "15055"
},
{
"name": "CSS",
"bytes": "7676"
},
{
"name": "Dockerfile",
"bytes": "2028"
},
{
"name": "Groovy",
"bytes": "3237482"
},
{
"name": "HTML",
"bytes": "42090"
},
{
"name": "Java",
"bytes": "432409546"
},
{
"name": "JavaScript",
"bytes": "36557"
},
{
"name": "Jupyter Notebook",
"bytes": "95868"
},
{
"name": "PowerShell",
"bytes": "737517"
},
{
"name": "Python",
"bytes": "240542"
},
{
"name": "Scala",
"bytes": "1143898"
},
{
"name": "Shell",
"bytes": "18488"
},
{
"name": "XSLT",
"bytes": "755"
}
],
"symlink_target": ""
} |
package org.cocos2dx.lib;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import android.opengl.GLSurfaceView;
import org.cocos2dx.lib.Cocos2dxHelper;
public class Cocos2dxRenderer implements GLSurfaceView.Renderer {
// ===========================================================
// Constants
// ===========================================================
private final static long NANOSECONDSPERSECOND = 1000000000L;
private final static long NANOSECONDSPERMICROSECOND = 1000000;
private static long sAnimationInterval = (long) (1.0 / 60 * Cocos2dxRenderer.NANOSECONDSPERSECOND);
// ===========================================================
// Fields
// ===========================================================
private long mLastTickInNanoSeconds;
private int mScreenWidth;
private int mScreenHeight;
private boolean mNativeInitCompleted = false;
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
public static void setAnimationInterval(final double pAnimationInterval) {
Cocos2dxRenderer.sAnimationInterval = (long) (pAnimationInterval * Cocos2dxRenderer.NANOSECONDSPERSECOND);
}
public void setScreenWidthAndHeight(final int pSurfaceWidth, final int pSurfaceHeight) {
this.mScreenWidth = pSurfaceWidth;
this.mScreenHeight = pSurfaceHeight;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public void onSurfaceCreated(final GL10 pGL10, final EGLConfig pEGLConfig) {
Cocos2dxRenderer.nativeInit(this.mScreenWidth, this.mScreenHeight);
this.mLastTickInNanoSeconds = System.nanoTime();
mNativeInitCompleted = true;
}
@Override
public void onSurfaceChanged(final GL10 pGL10, final int pWidth, final int pHeight) {
Cocos2dxRenderer.nativeOnSurfaceChanged(pWidth, pHeight);
}
@Override
public void onDrawFrame(final GL10 gl) {
/*
* No need to use algorithm in default(60 FPS) situation,
* since onDrawFrame() was called by system 60 times per second by default.
*/
if (sAnimationInterval <= 1.0 / 60 * Cocos2dxRenderer.NANOSECONDSPERSECOND) {
Cocos2dxRenderer.nativeRender();
} else {
final long now = System.nanoTime();
final long interval = now - this.mLastTickInNanoSeconds;
if (interval < Cocos2dxRenderer.sAnimationInterval) {
try {
Thread.sleep((Cocos2dxRenderer.sAnimationInterval - interval) / Cocos2dxRenderer.NANOSECONDSPERMICROSECOND);
} catch (final Exception e) {
}
}
/*
* Render time MUST be counted in, or the FPS will slower than appointed.
*/
this.mLastTickInNanoSeconds = System.nanoTime();
Cocos2dxRenderer.nativeRender();
}
}
// ===========================================================
// Methods
// ===========================================================
private static native void nativeTouchesBegin(final int pID, final float pX, final float pY);
private static native void nativeTouchesEnd(final int pID, final float pX, final float pY);
private static native void nativeTouchesMove(final int[] pIDs, final float[] pXs, final float[] pYs);
private static native void nativeTouchesCancel(final int[] pIDs, final float[] pXs, final float[] pYs);
private static native boolean nativeKeyDown(final int pKeyCode);
private static native void nativeRender();
private static native void nativeInit(final int pWidth, final int pHeight);
private static native void nativeOnSurfaceChanged(final int pWidth, final int pHeight);
private static native void nativeOnPause();
private static native void nativeOnResume();
public void handleActionDown(final int pID, final float pX, final float pY) {
Cocos2dxRenderer.nativeTouchesBegin(pID, pX, pY);
}
public void handleActionUp(final int pID, final float pX, final float pY) {
Cocos2dxRenderer.nativeTouchesEnd(pID, pX, pY);
}
public void handleActionCancel(final int[] pIDs, final float[] pXs, final float[] pYs) {
Cocos2dxRenderer.nativeTouchesCancel(pIDs, pXs, pYs);
}
public void handleActionMove(final int[] pIDs, final float[] pXs, final float[] pYs) {
Cocos2dxRenderer.nativeTouchesMove(pIDs, pXs, pYs);
}
public void handleKeyDown(final int pKeyCode) {
Cocos2dxRenderer.nativeKeyDown(pKeyCode);
}
public void handleOnPause() {
// onPause may be invoked before onSurfaceCreated
// and engine will be initialized correctly after
// onSurfaceCreated is invoked, can not invoke any
// native methed before onSurfaceCreated is invoked
if (! mNativeInitCompleted)
return;
Cocos2dxHelper.onEnterBackground();
Cocos2dxRenderer.nativeOnPause();
}
public void handleOnResume() {
Cocos2dxHelper.onEnterForeground();
Cocos2dxRenderer.nativeOnResume();
}
private static native void nativeInsertText(final String pText);
private static native void nativeDeleteBackward();
private static native String nativeGetContentText();
public void handleInsertText(final String pText) {
Cocos2dxRenderer.nativeInsertText(pText);
}
public void handleDeleteBackward() {
Cocos2dxRenderer.nativeDeleteBackward();
}
public String getContentText() {
return Cocos2dxRenderer.nativeGetContentText();
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| {
"content_hash": "d86a13b89d2e436a044396a9734e3160",
"timestamp": "",
"source": "github",
"line_count": 159,
"max_line_length": 113,
"avg_line_length": 35.503144654088054,
"alnum_prop": 0.6481842338352525,
"repo_name": "stevetranby/cocos2dx-shader-cookbook",
"id": "360307ba182dd43b4de1b613fa5bb4c4dab33090",
"size": "6889",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "cocos2d/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxRenderer.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "2395"
},
{
"name": "C",
"bytes": "1199428"
},
{
"name": "C#",
"bytes": "29241"
},
{
"name": "C++",
"bytes": "6719550"
},
{
"name": "CMake",
"bytes": "18713"
},
{
"name": "GLSL",
"bytes": "36141"
},
{
"name": "Java",
"bytes": "536212"
},
{
"name": "JavaScript",
"bytes": "6893"
},
{
"name": "Makefile",
"bytes": "20365"
},
{
"name": "Objective-C",
"bytes": "908043"
},
{
"name": "Objective-C++",
"bytes": "269072"
},
{
"name": "PowerShell",
"bytes": "18747"
},
{
"name": "Python",
"bytes": "75075"
},
{
"name": "Shell",
"bytes": "23088"
}
],
"symlink_target": ""
} |
class QtTrajectoryAnalysis : public QDialog
{
Q_OBJECT
public:
QtTrajectoryAnalysis(QWidget *parent = 0, Qt::WFlags flags = 0);
~QtTrajectoryAnalysis();
bool loadImage(std::string);
void setFolder(QString);
void setBatchInfo(QStringList&);
private:
Ui::QtTrajectoryAnalysisClass ui;
ServiceDLL* serviceDll;
extractThread *m_extractThread;
updateThread *m_updateThread;
analyzeThread *m_analyzeThread;
std::string outputFolder; //Êä³öÎļþ¼Ð
std::string videoName;//Îļþ¼ÐÃû×Ö
bool isClicked;
QIcon iconRun;
QIcon iconStop;
QGraphicsScene imgScene;
QGraphicsScene dstScene;
///ÅúÁ¿´¦Àí
WaitingProgressBar waitingDlg;
QStringList fileList;
QString folder;
bool isBatch;
int batchCnt;
AI_TrajectoryAnalysis AI_ta;
AI_TrajectoryAnalysis AI_da;
private:
bool init();
void destroy();
void setImage(cv::Mat&, QGraphicsScene*, QGraphicsView*);
void setRun();
void setStop();
void batchFiles();
void continueBatch();
std::string getFileName(const QString&, QString, QString&);
QImage const copy_mat_to_qimage(cv::Mat const &mat, QImage::Format format);
QImage const mat_to_qimage_cpy(cv::Mat &mat, int qimage_format);
private slots:
void on_pBtn_Run_clicked();
void on_pBtn_OutputFolder_clicked();
void on_pBtn_Check_clicked();
void on_pBtn_Analysis_clicked();
void on_pBtn_quit_clicked();
void updateProcessBar(int);
void getThreadEnd(cv::Mat*);
void getThreadStop();
void getThreadFail();
void getFrameImg(cv::Mat*);
void AnalyzeThreadEnd(cv::Mat*);
void AnalyzeThreadFail();
void closeWaitDlg();
void batchDone();
};
Q_DECLARE_METATYPE(cv::Mat);
#endif // QTTRAJECTORYANALYSIS_H
| {
"content_hash": "23c31c12948fab70367a80f65b2b1858",
"timestamp": "",
"source": "github",
"line_count": 71,
"max_line_length": 76,
"avg_line_length": 23.014084507042252,
"alnum_prop": 0.7466340269277846,
"repo_name": "billhhh/Maskedman_cloud",
"id": "27a5aba405fd4baf5817b06f9de7e8ad18b16c7a",
"size": "2028",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "2【借鉴 代码】/1【轨迹分析】servcie_trajectory_analysis/QtTrajectoryAnalysis/QtTrajectoryAnalysis/qttrajectoryanalysis.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "5819"
},
{
"name": "C++",
"bytes": "18895318"
},
{
"name": "JavaScript",
"bytes": "8900"
}
],
"symlink_target": ""
} |
using NMF.Collections.Generic;
using NMF.Collections.ObjectModel;
using NMF.Expressions;
using NMF.Expressions.Linq;
using NMF.Models;
using NMF.Models.Collections;
using NMF.Models.Expressions;
using NMF.Serialization;
using NMF.Utilities;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
namespace LL.MDE.Components.Qvt.Metamodel.EMOF
{
/// <summary>
/// The default implementation of the Tag class
/// </summary>
[XmlIdentifierAttribute("name")]
[XmlNamespaceAttribute("http://www.omg.org/spec/QVT/20140401/EMOF")]
[XmlNamespacePrefixAttribute("emof")]
[DebuggerDisplayAttribute("Tag {Name}")]
public class Tag : Element, ITag, IModelElement
{
/// <summary>
/// The backing field for the Name property
/// </summary>
private string _name;
/// <summary>
/// The backing field for the Value property
/// </summary>
private string _value;
/// <summary>
/// The backing field for the Element property
/// </summary>
private ObservableAssociationSet<IElement> _element;
private static NMF.Models.Meta.IClass _classInstance;
public Tag()
{
this._element = new ObservableAssociationSet<IElement>();
this._element.CollectionChanging += this.ElementCollectionChanging;
this._element.CollectionChanged += this.ElementCollectionChanged;
}
/// <summary>
/// The name property
/// </summary>
[XmlElementNameAttribute("name")]
[IdAttribute()]
[XmlAttributeAttribute(true)]
public virtual string Name
{
get
{
return this._name;
}
set
{
if ((this._name != value))
{
this.OnNameChanging(EventArgs.Empty);
this.OnPropertyChanging("Name");
string old = this._name;
this._name = value;
ValueChangedEventArgs e = new ValueChangedEventArgs(old, value);
this.OnNameChanged(e);
this.OnPropertyChanged("Name", e);
}
}
}
/// <summary>
/// The value property
/// </summary>
[XmlElementNameAttribute("value")]
[XmlAttributeAttribute(true)]
public virtual string Value
{
get
{
return this._value;
}
set
{
if ((this._value != value))
{
this.OnValueChanging(EventArgs.Empty);
this.OnPropertyChanging("Value");
string old = this._value;
this._value = value;
ValueChangedEventArgs e = new ValueChangedEventArgs(old, value);
this.OnValueChanged(e);
this.OnPropertyChanged("Value", e);
}
}
}
/// <summary>
/// The element property
/// </summary>
[DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Content)]
[XmlElementNameAttribute("element")]
[XmlAttributeAttribute(true)]
[ConstantAttribute()]
public virtual ISetExpression<IElement> Element
{
get
{
return this._element;
}
}
/// <summary>
/// Gets the referenced model elements of this model element
/// </summary>
public override IEnumerableExpression<IModelElement> ReferencedElements
{
get
{
return base.ReferencedElements.Concat(new TagReferencedElementsCollection(this));
}
}
/// <summary>
/// Gets a value indicating whether the current model element can be identified by an attribute value
/// </summary>
public override bool IsIdentified
{
get
{
return true;
}
}
/// <summary>
/// Gets fired before the Name property changes its value
/// </summary>
public event EventHandler NameChanging;
/// <summary>
/// Gets fired when the Name property changed its value
/// </summary>
public event EventHandler<ValueChangedEventArgs> NameChanged;
/// <summary>
/// Gets fired before the Value property changes its value
/// </summary>
public event EventHandler ValueChanging;
/// <summary>
/// Gets fired when the Value property changed its value
/// </summary>
public event EventHandler<ValueChangedEventArgs> ValueChanged;
/// <summary>
/// Raises the NameChanging event
/// </summary>
/// <param name="eventArgs">The event data</param>
protected virtual void OnNameChanging(EventArgs eventArgs)
{
EventHandler handler = this.NameChanging;
if ((handler != null))
{
handler.Invoke(this, eventArgs);
}
}
/// <summary>
/// Raises the NameChanged event
/// </summary>
/// <param name="eventArgs">The event data</param>
protected virtual void OnNameChanged(ValueChangedEventArgs eventArgs)
{
EventHandler<ValueChangedEventArgs> handler = this.NameChanged;
if ((handler != null))
{
handler.Invoke(this, eventArgs);
}
}
/// <summary>
/// Raises the ValueChanging event
/// </summary>
/// <param name="eventArgs">The event data</param>
protected virtual void OnValueChanging(EventArgs eventArgs)
{
EventHandler handler = this.ValueChanging;
if ((handler != null))
{
handler.Invoke(this, eventArgs);
}
}
/// <summary>
/// Raises the ValueChanged event
/// </summary>
/// <param name="eventArgs">The event data</param>
protected virtual void OnValueChanged(ValueChangedEventArgs eventArgs)
{
EventHandler<ValueChangedEventArgs> handler = this.ValueChanged;
if ((handler != null))
{
handler.Invoke(this, eventArgs);
}
}
/// <summary>
/// Forwards CollectionChanging notifications for the Element property to the parent model element
/// </summary>
/// <param name="sender">The collection that raised the change</param>
/// <param name="e">The original event data</param>
private void ElementCollectionChanging(object sender, NMF.Collections.ObjectModel.NotifyCollectionChangingEventArgs e)
{
this.OnCollectionChanging("Element", e);
}
/// <summary>
/// Forwards CollectionChanged notifications for the Element property to the parent model element
/// </summary>
/// <param name="sender">The collection that raised the change</param>
/// <param name="e">The original event data</param>
private void ElementCollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
this.OnCollectionChanged("Element", e);
}
/// <summary>
/// Resolves the given attribute name
/// </summary>
/// <returns>The attribute value or null if it could not be found</returns>
/// <param name="attribute">The requested attribute name</param>
/// <param name="index">The index of this attribute</param>
protected override object GetAttributeValue(string attribute, int index)
{
if ((attribute == "NAME"))
{
return this.Name;
}
if ((attribute == "VALUE"))
{
return this.Value;
}
return base.GetAttributeValue(attribute, index);
}
/// <summary>
/// Gets the Model element collection for the given feature
/// </summary>
/// <returns>A non-generic list of elements</returns>
/// <param name="feature">The requested feature</param>
protected override System.Collections.IList GetCollectionForFeature(string feature)
{
if ((feature == "ELEMENT"))
{
return this._element;
}
return base.GetCollectionForFeature(feature);
}
/// <summary>
/// Sets a value to the given feature
/// </summary>
/// <param name="feature">The requested feature</param>
/// <param name="value">The value that should be set to that feature</param>
protected override void SetFeature(string feature, object value)
{
if ((feature == "NAME"))
{
this.Name = ((string)(value));
return;
}
if ((feature == "VALUE"))
{
this.Value = ((string)(value));
return;
}
base.SetFeature(feature, value);
}
/// <summary>
/// Gets the Class for this model element
/// </summary>
public override NMF.Models.Meta.IClass GetClass()
{
throw new NotSupportedException();
}
/// <summary>
/// Gets the identifier string for this model element
/// </summary>
/// <returns>The identifier string</returns>
public override string ToIdentifierString()
{
if ((this.Name == null))
{
return null;
}
return this.Name.ToString();
}
/// <summary>
/// The collection class to to represent the children of the Tag class
/// </summary>
public class TagReferencedElementsCollection : ReferenceCollection, ICollectionExpression<IModelElement>, ICollection<IModelElement>
{
private Tag _parent;
/// <summary>
/// Creates a new instance
/// </summary>
public TagReferencedElementsCollection(Tag parent)
{
this._parent = parent;
}
/// <summary>
/// Gets the amount of elements contained in this collection
/// </summary>
public override int Count
{
get
{
int count = 0;
count = (count + this._parent.Element.Count);
return count;
}
}
protected override void AttachCore()
{
this._parent.Element.AsNotifiable().CollectionChanged += this.PropagateCollectionChanges;
}
protected override void DetachCore()
{
this._parent.Element.AsNotifiable().CollectionChanged -= this.PropagateCollectionChanges;
}
/// <summary>
/// Adds the given element to the collection
/// </summary>
/// <param name="item">The item to add</param>
public override void Add(IModelElement item)
{
IElement elementCasted = item.As<IElement>();
if ((elementCasted != null))
{
this._parent.Element.Add(elementCasted);
}
}
/// <summary>
/// Clears the collection and resets all references that implement it.
/// </summary>
public override void Clear()
{
this._parent.Element.Clear();
}
/// <summary>
/// Gets a value indicating whether the given element is contained in the collection
/// </summary>
/// <returns>True, if it is contained, otherwise False</returns>
/// <param name="item">The item that should be looked out for</param>
public override bool Contains(IModelElement item)
{
if (this._parent.Element.Contains(item))
{
return true;
}
return false;
}
/// <summary>
/// Copies the contents of the collection to the given array starting from the given array index
/// </summary>
/// <param name="array">The array in which the elements should be copied</param>
/// <param name="arrayIndex">The starting index</param>
public override void CopyTo(IModelElement[] array, int arrayIndex)
{
IEnumerator<IModelElement> elementEnumerator = this._parent.Element.GetEnumerator();
try
{
for (
; elementEnumerator.MoveNext();
)
{
array[arrayIndex] = elementEnumerator.Current;
arrayIndex = (arrayIndex + 1);
}
}
finally
{
elementEnumerator.Dispose();
}
}
/// <summary>
/// Removes the given item from the collection
/// </summary>
/// <returns>True, if the item was removed, otherwise False</returns>
/// <param name="item">The item that should be removed</param>
public override bool Remove(IModelElement item)
{
IElement elementItem = item.As<IElement>();
if (((elementItem != null)
&& this._parent.Element.Remove(elementItem)))
{
return true;
}
return false;
}
/// <summary>
/// Gets an enumerator that enumerates the collection
/// </summary>
/// <returns>A generic enumerator</returns>
public override IEnumerator<IModelElement> GetEnumerator()
{
return Enumerable.Empty<IModelElement>().Concat(this._parent.Element).GetEnumerator();
}
}
/// <summary>
/// Represents a proxy to represent an incremental access to the name property
/// </summary>
private sealed class NameProxy : ModelPropertyChange<ITag, string>
{
/// <summary>
/// Creates a new observable property access proxy
/// </summary>
/// <param name="modelElement">The model instance element for which to create the property access proxy</param>
public NameProxy(ITag modelElement) :
base(modelElement)
{
}
/// <summary>
/// Gets or sets the value of this expression
/// </summary>
public override string Value
{
get
{
return this.ModelElement.Name;
}
set
{
this.ModelElement.Name = value;
}
}
/// <summary>
/// Registers an event handler to subscribe specifically on the changed event for this property
/// </summary>
/// <param name="handler">The handler that should be subscribed to the property change event</param>
protected override void RegisterChangeEventHandler(System.EventHandler<NMF.Expressions.ValueChangedEventArgs> handler)
{
this.ModelElement.NameChanged += handler;
}
/// <summary>
/// Registers an event handler to subscribe specifically on the changed event for this property
/// </summary>
/// <param name="handler">The handler that should be unsubscribed from the property change event</param>
protected override void UnregisterChangeEventHandler(System.EventHandler<NMF.Expressions.ValueChangedEventArgs> handler)
{
this.ModelElement.NameChanged -= handler;
}
}
/// <summary>
/// Represents a proxy to represent an incremental access to the value property
/// </summary>
private sealed class ValueProxy : ModelPropertyChange<ITag, string>
{
/// <summary>
/// Creates a new observable property access proxy
/// </summary>
/// <param name="modelElement">The model instance element for which to create the property access proxy</param>
public ValueProxy(ITag modelElement) :
base(modelElement)
{
}
/// <summary>
/// Gets or sets the value of this expression
/// </summary>
public override string Value
{
get
{
return this.ModelElement.Value;
}
set
{
this.ModelElement.Value = value;
}
}
/// <summary>
/// Registers an event handler to subscribe specifically on the changed event for this property
/// </summary>
/// <param name="handler">The handler that should be subscribed to the property change event</param>
protected override void RegisterChangeEventHandler(System.EventHandler<NMF.Expressions.ValueChangedEventArgs> handler)
{
this.ModelElement.ValueChanged += handler;
}
/// <summary>
/// Registers an event handler to subscribe specifically on the changed event for this property
/// </summary>
/// <param name="handler">The handler that should be unsubscribed from the property change event</param>
protected override void UnregisterChangeEventHandler(System.EventHandler<NMF.Expressions.ValueChangedEventArgs> handler)
{
this.ModelElement.ValueChanged -= handler;
}
}
}
}
| {
"content_hash": "b06fe5a54ae0611fae007489349e3940",
"timestamp": "",
"source": "github",
"line_count": 535,
"max_line_length": 140,
"avg_line_length": 35.566355140186914,
"alnum_prop": 0.5162392264031953,
"repo_name": "LieberLieber/QvtCodeGenerator",
"id": "01407f99a9d894a123f70ba4b71553052e40fafb",
"size": "19425",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "QvtEnginePerformance/LL.MDE.Components.Qvt.Metamodel/Generated/EMOF/Tag.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "5649534"
},
{
"name": "Smalltalk",
"bytes": "14824"
}
],
"symlink_target": ""
} |
package net.lag.kestrel
import java.io._
import java.net.Socket
import scala.collection.Map
import scala.collection.mutable
class TestClient(host: String, port: Int) {
var socket: Socket = null
var out: OutputStream = null
var in: DataInputStream = null
connect
def connect = {
socket = new Socket(host, port)
out = socket.getOutputStream
in = new DataInputStream(socket.getInputStream)
}
def disconnect = {
socket.close
}
private def readline = {
// this isn't meant to be efficient, just simple.
val out = new StringBuilder
var done = false
while (!done) {
val ch: Int = in.read
if ((ch < 0) || (ch == 10)) {
done = true
} else if (ch != 13) {
out += ch.toChar
}
}
out.toString
}
def set(key: String, value: String): String = {
out.write(("set " + key + " 0 0 " + value.length + "\r\n" + value + "\r\n").getBytes)
readline
}
def set(key: String, value: String, expiry: Int) = {
out.write(("set " + key + " 0 " + expiry + " " + value.length + "\r\n" + value + "\r\n").getBytes)
readline
}
def get(key: String): String = {
out.write(("get " + key + "\r\n").getBytes)
val line = readline
if (line == "END") {
return ""
}
// VALUE <name> <flags> <length>
val len = line.split(" ")(3).toInt
val buffer = new Array[Byte](len)
in.readFully(buffer)
readline
readline // "END"
new String(buffer)
}
def add(key: String, value: String) = {
out.write(("add " + key + " 0 0 " + value.length + "\r\n" + value + "\r\n").getBytes)
readline
}
def stats: Map[String, String] = {
out.write("stats\r\n".getBytes)
var done = false
val map = new mutable.HashMap[String, String]
while (!done) {
val line = readline
if (line startsWith "STAT") {
val args = line.split(" ")
map(args(1)) = args(2)
} else if (line == "END") {
done = true
}
}
map
}
}
| {
"content_hash": "484ebae167ffb13a7d4bac8e05775ec0",
"timestamp": "",
"source": "github",
"line_count": 90,
"max_line_length": 102,
"avg_line_length": 22.31111111111111,
"alnum_prop": 0.5592629482071713,
"repo_name": "al3x/kestrel",
"id": "a608d0495b9c1e896210cdc0406955164a3296f4",
"size": "3148",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/test/scala/net/lag/kestrel/TestClient.scala",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
from __future__ import unicode_literals, division, absolute_import
from builtins import * # pylint: disable=unused-import, redefined-builtin
import logging
import os
from flexget import plugin
from flexget.event import event
log = logging.getLogger('proxy')
PROTOCOLS = ['http', 'https', 'ftp']
class Proxy(object):
"""Adds a proxy to the requests session."""
schema = {
'oneOf': [
{'type': 'string', 'format': 'url'},
{
'type': 'object',
'properties': dict((prot, {'type': 'string', 'format': 'url'}) for prot in PROTOCOLS),
'additionalProperties': False
}
]
}
@plugin.priority(255)
def on_task_start(self, task, config):
if not config:
# If no configuration is provided, see if there are any proxy env variables
proxies = {}
for prot in PROTOCOLS:
if os.environ.get(prot + '_proxy'):
proxies[prot] = os.environ[prot + '_proxy']
if not proxies:
# If there were no environment variables set, do nothing
return
elif isinstance(config, dict):
proxies = config
else:
# Map all protocols to the configured proxy
proxies = dict((prot, config) for prot in PROTOCOLS)
log.verbose('Setting proxy to %s' % proxies)
task.requests.proxies = proxies
@event('plugin.register')
def register_plugin():
plugin.register(Proxy, 'proxy', builtin=True, api_ver=2)
| {
"content_hash": "08da1de2a97f19aa48fccb20f7fe14a7",
"timestamp": "",
"source": "github",
"line_count": 51,
"max_line_length": 102,
"avg_line_length": 30.80392156862745,
"alnum_prop": 0.573520050922979,
"repo_name": "oxc/Flexget",
"id": "3c9612a3bf74d7a5528b15d7b5360e8e1f72c8f1",
"size": "1571",
"binary": false,
"copies": "4",
"ref": "refs/heads/develop",
"path": "flexget/plugins/operate/proxy.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "9267"
},
{
"name": "HTML",
"bytes": "49610"
},
{
"name": "JavaScript",
"bytes": "239825"
},
{
"name": "Python",
"bytes": "2749010"
},
{
"name": "SRecode Template",
"bytes": "3"
}
],
"symlink_target": ""
} |
<?php
/*
Unsafe sample
input : execute a ls command using the function system, and put the last result in $tainted
sanitize : regular expression accepts everything
construction : use of sprintf via a %s with simple quote
*/
/*Copyright 2015 Bertrand STIVALET
Permission is hereby granted, without written agreement or royalty fee, to
use, copy, modify, and distribute this software and its documentation for
any purpose, provided that the above copyright notice and the following
three paragraphs appear in all copies of this software.
IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT,
INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE
BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT
LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO
OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
MODIFICATIONS.*/
$tainted = system('ls', $retval);
$re = "/^.*$/";
if(preg_match($re, $tainted) == 1){
$tainted = $tainted;
}
else{
$tainted = "";
}
//flaw
$var = http_redirect(sprintf("'%s'", $tainted));
?> | {
"content_hash": "2933be206112720c2c0b3cc6dcfa1610",
"timestamp": "",
"source": "github",
"line_count": 61,
"max_line_length": 91,
"avg_line_length": 21.901639344262296,
"alnum_prop": 0.750748502994012,
"repo_name": "stivalet/PHP-Vulnerability-test-suite",
"id": "4eaec0b9b414115572d3ad539f4dee8c8f2c62c7",
"size": "1336",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "URF/CWE_601/unsafe/CWE_601__system__func_preg_match-no_filtering__http_redirect_url-sprintf_%s_simple_quote.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "64184004"
}
],
"symlink_target": ""
} |
using UnityEngine;
using System.Collections.Generic;
namespace AmplifyShaderEditor
{
public struct Constants
{
public readonly static string UndoMoveNodesId = "Moving Nodes";
public readonly static string UndoRegisterFullGrapId = "Register Graph";
public readonly static string UndoAddNodeToCommentaryId = "Add node to Commentary";
public readonly static string UndoRemoveNodeFromCommentaryId = "Remove node from Commentary";
public readonly static string UndoCreateNodeId = "Create Object";
public readonly static string UndoDeleteNodeId = "Destroy Object";
public readonly static string UndoDeleteConnectionId = "Destroy Connection";
public readonly static string UndoCreateConnectionId = "Create Connection";
public readonly static float MenuDragSpeed = -0.5f;
public readonly static string DefaultCustomInspector = "ASEMaterialInspector";
public readonly static string ReferenceTypeStr = "Type";
public readonly static string AvailableReferenceStr = "Reference";
public readonly static string InstancePostfixStr = " (Instance) ";
public readonly static string HelpURL = "http://amplify.pt/";
public readonly static string ASEMenuName = "Amplify Shader";
public readonly static string UnityShaderVariables = "UnityShaderVariables.cginc";
public readonly static string UnityCgLibFuncs = "UnityCG.cginc";
public readonly static string UnityStandardUtilsLibFuncs = "UnityStandardUtils.cginc";
public readonly static string UnityPBSLightingLib = "UnityPBSLighting.cginc";
public static readonly string ATSharedLibGUID = "ba242738c4be3324aa88d126f7cc19f9";
public readonly static Color InfiniteLoopColor = Color.red;
public readonly static Color DefaultCategoryColor = new Color( 0.1f, 0.35f, 0.44f, 1.0f );
public readonly static Color NodeBodyColor = new Color( 1f, 1f, 1f, 1.0f );
public readonly static Color ModeTextColor = new Color( 1f, 1f, 1f, 0.25f );
public readonly static Color ModeIconColor = new Color( 1f, 1f, 1f, 0.75f );
public readonly static Color PortTextColor = new Color( 1f, 1f, 1f, 0.5f );
public readonly static Color BoxSelectionColor = new Color( 1f, 1f, 1f, 0.5f );
public readonly static Color NodeSelectedColor = new Color( 0.5f, 0.5f, 1f, 1f );
public readonly static Color NodeDefaultColor = new Color( 1f, 1f, 1f, 1f );
public readonly static Color NodeConnectedColor = new Color( 1.0f, 1f, 0.0f, 1f );
public readonly static Color NodeErrorColor = new Color( 1f, 0.5f, 0.5f, 1f );
public readonly static string NoSpecifiedCategoryStr = "<None>";
public readonly static int MINIMIZE_WINDOW_LOCK_SIZE = 750;
public readonly static int FoldoutMouseId = 0; // Left Mouse Button
public readonly static float SNAP_SQR_DIST = 200f;
public readonly static int INVALID_NODE_ID = -1;
public readonly static float WIRE_WIDTH = 7f;
public readonly static float WIRE_CONTROL_POINT_DIST = 0.7f;
public readonly static float WIRE_CONTROL_POINT_DIST_INV = 1.7f;
public readonly static float IconsLeftRightMargin = 5f;
public readonly static float PropertyPickerWidth = 16f;
public readonly static float PropertyPickerHeight = 16f;
public readonly static float PreviewExpanderWidth = 16f;
public readonly static float PreviewExpanderHeight = 16f;
public readonly static float TextFieldFontSize = 11f;
public readonly static float DefaultFontSize = 15f;
public readonly static float DefaultTitleFontSize = 13f;
public readonly static float PropertiesTitleFontSize = 11f;
public readonly static float MessageFontSize = 40f;
public readonly static float SelectedObjectFontSize = 30f;
public readonly static float PORT_X_ADJUST = 10;
public readonly static float PORT_INITIAL_X = 10;
public readonly static float PORT_INITIAL_Y = 40;
public readonly static float INPUT_PORT_DELTA_Y = 5;
public readonly static float PORT_TO_LABEL_SPACE_X = 5;
public readonly static float NODE_HEADER_HEIGHT = 32;
public readonly static float NODE_HEADER_EXTRA_HEIGHT = 5;
public readonly static float NODE_HEADER_LEFTRIGHT_MARGIN = 10;
public readonly static float MULTIPLE_SELECION_BOX_ALPHA = 0.5f;
public readonly static float RMB_CLICK_DELTA_TIME = 0.1f;
public readonly static float RMB_SCREEN_DIST = 10f;
public readonly static float CAMERA_MAX_ZOOM = 2f;
public readonly static float CAMERA_MIN_ZOOM = 1f;
public readonly static float CAMERA_ZOOM_SPEED = 0.1f;
public readonly static float ALT_CAMERA_ZOOM_SPEED = -0.05f;
public readonly static object INVALID_VALUE = null;
public readonly static float HORIZONTAL_TANGENT_SIZE = 100f;
public readonly static float OUTSIDE_WIRE_MARGIN = 5f;
public readonly static string CodeWrapper = "({0})";
public readonly static string UnpackNormal = "UnpackNormal( {0} )";
public readonly static string UnpackNormalScale = "UnpackNormal( {0} , {1} )";
public readonly static string NodesDumpFormat = "{0}:,{1},{2}\n";
public readonly static string LocalVarIdentation = "\t\t\t";
public readonly static string SimpleLocalValueDec = LocalVarIdentation + "{0} {1};\n";
public readonly static string LocalValueDecWithoutIdent = "{0} {1} = {2};";
public readonly static string LocalValueDec = LocalVarIdentation + LocalValueDecWithoutIdent + '\n';
public readonly static string LocalValueDef = LocalVarIdentation + "{0} = {1};\n";
public readonly static string CastHelper = "({0}).{1}";
public readonly static string PropertyLocalVarDec = "{0} {1} = {0}({2});";
public readonly static string UniformDec = "uniform {0} {1};";
public readonly static string PropertyValueLabel = "Value( {0} )";
public readonly static string ConstantsValueLabel = "Const( {0} )";
public readonly static string PropertyFloatFormatLabel = "0.###";
public readonly static string PropertyBigFloatFormatLabel = "0.###e+0";
public readonly static string PropertyIntFormatLabel = "0";
public readonly static string PropertyBigIntFormatLabel = "0e+0";
public readonly static string PropertyVectorFormatLabel = "0.##";
public readonly static string PropertyBigVectorFormatLabel = "0.##e+0";
public readonly static string PropertyMatrixFormatLabel = "0.#";
public readonly static string PropertyBigMatrixFormatLabel = "0.#e+0";
public readonly static string NoPropertiesLabel = "No assigned properties";
public readonly static string ValueLabel = "Value";
public readonly static string DefaultValueLabel = "Default Value";
public readonly static string MaterialValueLabel = "Material Value";
public readonly static string InputVarStr = "i";//"input";
public readonly static string OutputVarStr = "o";//"output";
public readonly static string CustomLightOutputVarStr = "s";
public readonly static string CustomLightStructStr = "Custom";
public readonly static string VertexShaderOutputStr = "o";
public readonly static string VertexShaderInputStr = "v";//"vertexData";
public readonly static string VertexDataFunc = "vertexDataFunc";
public readonly static string VirtualCoordNameStr = "vcoord";
public readonly static string VertexVecNameStr = "vertexVec";
public readonly static string VertexVecDecStr = "float3 " + VertexVecNameStr;
public readonly static string VertexVecVertStr = VertexShaderOutputStr + "." + VertexVecNameStr;
public readonly static string NormalVecNameStr = "normalVec";
public readonly static string NormalVecDecStr = "float3 " + NormalVecNameStr;
public readonly static string NormalVecFragStr = InputVarStr + "." + NormalVecNameStr;
public readonly static string NormalVecVertStr = VertexShaderOutputStr + "." + NormalVecNameStr;
public readonly static string IncidentVecNameStr = "incidentVec";
public readonly static string IncidentVecDecStr = "float3 " + IncidentVecNameStr;
public readonly static string IncidentVecDefStr = VertexShaderOutputStr + "." + IncidentVecNameStr + " = normalize( " + VertexVecNameStr + " - _WorldSpaceCameraPos.xyz)";
public readonly static string IncidentVecFragStr = InputVarStr + "." + IncidentVecNameStr;
public readonly static string IncidentVecVertStr = VertexShaderOutputStr + "." + IncidentVecNameStr;
public readonly static string WorldNormalLocalDecStr = "WorldNormalVector( " + Constants.InputVarStr + " , {0}( 0,0,1 ))";
public readonly static string VFaceVariable = "ASEVFace";
public readonly static string VFaceInput = "fixed ASEVFace : VFACE";
public readonly static string NoStringValue = "None";
public readonly static string EmptyPortValue = " ";
public readonly static string[] OverallInvalidChars = { "\r", "\n", "\\", " ", ".", ">", ",", "<", "\'", "\"", ";", ":", "[", "{", "]", "}", "=", "+", "`", "~", "/", "?", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "-" };
public readonly static string[] ShaderInvalidChars = { "\r", "\n", "\\", "\'", "\"", };
public readonly static string[] WikiInvalidChars = { "#","<",">", "[", "]", "|", "{", "}", "%", "+", "?", "\\", "/", ",", ";", "." };
public readonly static Dictionary<string, string> ReplacementStringValues = new Dictionary<string, string>() { { " == ", "Equals" },
{ " > ", "Greater" },
{ " >= ", "GreaterOrEqual" },
{ " < ", "Less" },
{ " <= ", "LessOrEqual" }};
public readonly static string InternalData = "INTERNAL_DATA";
public readonly static string NoMaterialStr = "None";
public readonly static string OptionalParametersSep = " ";
public readonly static string NodeUndoId = "NODE_UNDO_ID";
public readonly static string NodeCreateUndoId = "NODE_CREATE_UNDO_ID";
public readonly static string NodeDestroyUndoId = "NODE_DESTROY_UNDO_ID";
// Custom node tags
//[InPortBegin:Id:Type:Name:InPortEnd]
public readonly static string CNIP = "#IP";
public readonly static float FLOAT_DRAW_HEIGHT_FIELD_SIZE = 16f;
public readonly static float FLOAT_DRAW_WIDTH_FIELD_SIZE = 45f;
public readonly static float FLOAT_WIDTH_SPACING = 3f;
public readonly static Color LockedPortColor = new Color( 0.3f, 0.3f, 0.3f, 0.5f );
public readonly static int[] AvailableUVChannels = { 0, 1, 2, 3 };
public readonly static string[] AvailableUVChannelsStr = { "0", "1", "2", "3" };
public readonly static string AvailableUVChannelLabel = "UV Channel";
public readonly static int[] AvailableUVSizes = { 2, 3, 4 };
public readonly static string[] AvailableUVSizesStr = { "Float 2", "Float 3", "Float 4"};
public readonly static string AvailableUVSizesLabel = "Coord Size";
public readonly static int[] AvailableUVSets = { 0, 1, 2, 3 };
public readonly static string[] AvailableUVSetsStr = { "1", "2", "3", "4" };
public readonly static string AvailableUVSetsLabel = "UV Set";
public readonly static string LineSeparator = "________________________________";
public readonly static Vector2 CopyPasteDeltaPos = new Vector2( 40, 40 );
public readonly static string[] VectorSuffixes = { ".x", ".y", ".z", ".w" };
public readonly static string[] ColorSuffixes = { ".r", ".g", ".b", ".a" };
public const string InternalDataLabelStr = "Internal Data";
public const string AttributesLaberStr = "Attributes";
public const string ParameterLabelStr = "Parameters";
public static readonly string[] ReferenceArrayLabels = {"Object", "Reference" };
}
}
| {
"content_hash": "5e90cb17211ce15d9c48edfa6f2a9724",
"timestamp": "",
"source": "github",
"line_count": 236,
"max_line_length": 229,
"avg_line_length": 48.26271186440678,
"alnum_prop": 0.7201931518876207,
"repo_name": "bi3mer/SeniorProject",
"id": "877b0c9a4d0ce3fe6019ca9f2d2359aa86f0a3ab",
"size": "11503",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Assets/AmplifyShaderEditor/Plugins/Editor/Constants.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "5530081"
},
{
"name": "C++",
"bytes": "946"
},
{
"name": "GLSL",
"bytes": "21345"
},
{
"name": "HLSL",
"bytes": "204971"
},
{
"name": "Mask",
"bytes": "33634"
},
{
"name": "Objective-C",
"bytes": "446"
},
{
"name": "Objective-C++",
"bytes": "5963"
},
{
"name": "ShaderLab",
"bytes": "611878"
},
{
"name": "Smalltalk",
"bytes": "106"
}
],
"symlink_target": ""
} |
<?php
add_action( 'admin_init', 'nextgenthemes_init_edd_updaters', 0 );
add_action( 'admin_init', 'nextgenthemes_activation_notices' );
add_action( 'admin_init', 'nextgenthemes_register_settings' );
add_action( 'admin_menu', 'nextgenthemes_menus' );
function nextgenthemes_admin_install_search_url( $search_term ) {
$path = "plugin-install.php?s={$search_term}&tab=search&type=term";
if ( is_multisite() ) {
return network_admin_url( $path );
} else {
return admin_url( $path );
}
}
function nextgenthemes_ads_page() { ?>
<style>
body {
background: hsl(210, 13%, 16%);
}
#wpcontent {
padding: 0;
}
#wpbody-content {
/* padding-bottom: 2rem; */
}
#wpfooter {
display: none;
}
#nextgenthemes-ads {
padding: 1.7rem;
column-width: 40rem;
column-gap: 1.7rem;
}
@media only screen and (max-device-width: 400px) {
#nextgenthemes-ads {
padding-left: 0;
padding-right: 0;
}
}
#nextgenthemes-ads,
#nextgenthemes-ads * {
box-sizing: border-box;
}
#nextgenthemes-ads::after {
content: "";
display: table;
clear: both;
}
#nextgenthemes-ads {
color: white;
}
#nextgenthemes-ads h1,
#nextgenthemes-ads h2,
#nextgenthemes-ads h3 {
color: inherit;
margin-left: 2rem;
margin-right: 1.7rem;
}
#nextgenthemes-ads h1 {
line-height: 1;
}
#nextgenthemes-ads img {
width: 100%;
height: auto;
}
#nextgenthemes-ads > a {
text-decoration: none;
position: relative;
display: inline-block;
width: 100%;
background-color: hsl(210, 13%, 13%);
border: 1px solid hsl(207, 48%, 30%);
transition: box-shadow .3s, background-color .3s, border-color .3s;
color: #eee;
font-size: 1.05rem;
margin-bottom: 2rem;
line-height: 1.4;
}
#nextgenthemes-ads > a:hover {
background-color: hsl(210, 13%, 10%);
box-shadow: 0 0 10px hsla(207, 48%, 50%, 1);
border-color: hsl(207, 48%, 40%);
}
#nextgenthemes-ads p {
margin-left: 2rem;
margin-right: 1.7rem;
font-size: 1.2rem;
}
#nextgenthemes-ads ul {
list-style: square;
margin-left: 2.5rem;
margin-right: .7rem;
}
#nextgenthemes-ads > a > span {
position: absolute;
padding: .6rem 1rem;
right: 0px;
bottom: 0px;
font-size: 2rem;
color: white;
background-color: hsl(207, 48%, 30%);
border-top-left-radius: 3px;
//transform: rotate(3deg);
}
#nextgenthemes-ads figure {
margin: 1rem;
}
</style>
<?php $img_dir = plugin_dir_url( __FILE__ ) . 'product-images/'; ?>
<div id="nextgenthemes-ads">
<?php if ( ! defined( 'ARVE_PRO_VERSION' ) ) : ?>
<a href="https://nextgenthemes.com/plugins/arve-pro/">
<figure><img src="<?php echo $img_dir; ?>arve.svg" alt"ARVE"></figure>
<?php nextgenthemes_feature_list_html( ARVE_PATH . 'readme/html/20-description-features-pro.html' ); ?>
<span>Paid</span>
</a>
<?php endif; ?>
<?php if ( ! defined( 'ARVE_AMP_VERSION' ) ) : ?>
<a href="https://nextgenthemes.com/plugins/arve-accelerated-mobile-pages-addon/">
<figure><img src="<?php echo $img_dir; ?>arve.svg" alt"ARVE"></figure>
<?php nextgenthemes_feature_list_html( ARVE_PATH . 'readme/html/25-description-features-amp.html' ); ?>
<span>Paid</span>
</a>
<?php endif; ?>
<?php if ( ! is_plugin_active( 'regenerate-thumbnails-reminder/regenerate-thumbnails-reminder.php' ) ) : ?>
<a href="<?php echo nextgenthemes_admin_install_search_url( 'Regenerate+Thumbnails+Reminder' ); ?>">
<h1>Regenerate Thumbnails Reminder</h1>
<p>Get a reminder when you change your thumbnail sizes to regenerate them. Note Thumbnails sizes change automatically if you swtich themes.</p>
<span>Free</span>
</a>
<?php endif; ?>
</div>
<?php
}
function nextgenthemes_feature_list_html( $filepath ) {
echo strip_tags( file_get_contents( $filepath ), '<ul></ul><li></li><h3></h3>' );
}
function nextgenthemes_activation_notices() {
$products = nextgenthemes_get_products();
foreach ( $products as $key => $value ) {
if( $value['active'] && ! $value['valid_key'] ) {
$msg = sprintf(
__( 'Hi there, thanks for your purchase. One last step, please activate your %s <a href="%s">here now</a>.', ARVE_SLUG ),
$value['name'],
get_admin_url() . 'admin.php?page=nextgenthemes-licenses'
);
new ARVE_Admin_Notice_Factory( $key . '-activation-notice', "<p>$msg</p>", false );
}
}
}
function nextgenthemes_get_products() {
$products = array(
'arve_pro' => array(
'name' => 'ARVE Pro',
'id' => 1253,
'type' => 'plugin',
'author' => 'Nicolas Jonas',
'url' => 'https://nextgenthemes.com/plugins/arve-pro/',
),
'arve_amp' => array(
'name' => 'ARVE AMP',
'id' => 16941,
'type' => 'plugin',
'author' => 'Nicolas Jonas',
'url' => 'https://nextgenthemes.com/plugins/arve-amp/',
),
'arve_random_video' => array(
'name' => 'ARVE Random Video',
'id' => 31933,
'type' => 'plugin',
'author' => 'Nicolas Jonas',
'url' => 'https://nextgenthemes.com/plugins/arve-random-video/',
)
);
$products = apply_filters( 'nextgenthemes_products', $products );
foreach ( $products as $key => $value ) {
$products[ $key ]['slug'] = $key;
$products[ $key ]['installed'] = false;
$products[ $key ]['active'] = false;
$products[ $key ]['valid_key'] = nextgenthemes_has_valid_key( $key );
$version_define = strtoupper( $key ) . '_VERSION';
$file_define = strtoupper( $key ) . '_FILE';
if( defined( $version_define ) ) {
$products[ $key ]['version'] = constant( $version_define );
}
if( defined( $file_define ) ) {
$products[ $key ]['file'] = constant( $file_define );
}
$version_define = "\\nextgenthemes\\$key\\VERSION";
$file_define = "\\nextgenthemes\\$key\\FILE";
if( defined( $version_define ) ) {
$products[ $key ]['version'] = constant( $version_define );
}
if( defined( $file_define ) ) {
$products[ $key ]['file'] = constant( $file_define );
}
if ( 'plugin' === $value['type'] ) {
$file_slug = str_replace( '_', '-', $key );
$products[ $key ]['installed'] = nextgenthemes_is_plugin_installed( "$file_slug/$file_slug.php" );
$products[ $key ]['active'] = is_plugin_active( "$file_slug/$file_slug.php" );
}
}
return $products;
}
function nextgenthemes_is_plugin_installed( $plugin_basename ) {
$plugins = get_plugins();
if( array_key_exists( $plugin_basename, $plugins ) ) {
return true;
} else {
return false;
}
}
/**
* Register the administration menu for this plugin into the WordPress Dashboard menu.
*
* @since 1.0.0
*/
function nextgenthemes_menus() {
$plugin_screen_hook_suffix = add_options_page(
__( 'ARVE Licenses', ARVE_SLUG ),
__( 'ARVE Licenses', ARVE_SLUG ),
'manage_options',
'nextgenthemes-licenses',
'nextgenthemes_licenses_page'
);
}
function nextgenthemes_register_settings() {
add_settings_section(
'keys', # id,
__( 'Licenses', ARVE_SLUG ), # title,
'__return_empty_string', # callback,
'nextgenthemes-licenses' # page
);
foreach ( nextgenthemes_get_products() as $product_slug => $product ) :
$option_basename = "nextgenthemes_{$product_slug}_key";
$option_keyname = $option_basename . '[key]';
add_settings_field(
$option_keyname, # id,
$product['name'], # title,
'nextgenthemes_key_callback', # callback,
'nextgenthemes-licenses', # page,
'keys', # section
array( # args
'product' => $product,
'label_for' => $option_keyname,
'option_basename' => $option_basename,
'attr' => array(
'type' => 'text',
'id' => $option_keyname,
'name' => $option_keyname,
'class' => 'arve-license-input',
'value' => nextgenthemes_get_defined_key( $product_slug ) ? __( 'is defined (wp-config.php?)', ARVE_SLUG ) : nextgenthemes_get_key( $product_slug, 'option_only' ),
)
)
);
register_setting(
'nextgenthemes', # option_group
$option_basename, # option_name
'nextgenthemes_validate_license' # validation callback
);
endforeach;
}
function nextgenthemes_key_callback( $args ) {
echo '<p>';
printf( '<input%s>', arve_attr( array(
'type' => 'hidden',
'id' => $args['option_basename'] . '[product]',
'name' => $args['option_basename'] . '[product]',
'value' => $args['product']['slug'],
) ) );
printf(
'<input%s%s>',
arve_attr( $args['attr'] ),
nextgenthemes_get_defined_key( $args['product']['slug'] ) ? ' disabled' : ''
);
$defined_key = nextgenthemes_get_defined_key( $args['product']['slug'] );
$key = nextgenthemes_get_key( $args['product']['slug'] );
if( $defined_key || ! empty( $key ) ) {
submit_button( __('Activate License', ARVE_SLUG ), 'primary', $args['option_basename'] . '[activate_key]', false );
submit_button( __('Deactivate License', ARVE_SLUG ), 'secondary', $args['option_basename'] . '[deactivate_key]', false );
submit_button( __('Check License', ARVE_SLUG ), 'secondary', $args['option_basename'] . '[check_key]', false );
}
echo '</p>';
echo '<p>';
echo __( 'License Status: ', ARVE_SLUG ) . nextgenthemes_get_key_status( $args['product']['slug'] );
echo '</p>';
if( $args['product']['installed'] && ! $args['product']['active'] ) {
printf( '<strong>%s</strong>', __( 'Plugin is installed but not activated', ARVE_SLUG ) );
} elseif( ! $args['product']['active'] ) {
printf(
'<a%s>%s</a>',
arve_attr( array(
'href' => $args['product']['url'],
'class' => 'button button-primary',
) ),
__( 'Not installed, check it out', ARVE_SLUG )
);
}
}
function nextgenthemes_validate_license( $input ) {
if( ! is_array( $input ) ) {
return sanitize_text_field( $input );
}
$product = $input['product'];
if ( $defined_key = nextgenthemes_get_defined_key( $product ) ) {
$option_key = $key = $defined_key;
} else {
$key = sanitize_text_field( $input['key'] );
$option_key = nextgenthemes_get_key( $product );
}
if( ( $key != $option_key ) || isset( $input['activate_key'] ) ) {
nextgenthemes_api_update_key_status( $product, $key, 'activate' );
} elseif ( isset( $input['deactivate_key'] ) ) {
nextgenthemes_api_update_key_status( $product, $key, 'deactivate' );
} elseif ( isset( $input['check_key'] ) ) {
nextgenthemes_api_update_key_status( $product, $key, 'check' );
}
return $key;
}
function nextgenthemes_get_key( $product, $option_only = false ) {
if( ! $option_only && $defined_key = nextgenthemes_get_defined_key( $product ) ) {
return $defined_key;
}
return get_option( "nextgenthemes_{$product}_key" );
}
function nextgenthemes_get_key_status( $product ) {
return get_option( "nextgenthemes_{$product}_key_status" );
}
function nextgenthemes_update_key_status( $product, $key ) {
update_option( "nextgenthemes_{$product}_key_status", $key );
}
function nextgenthemes_has_valid_key( $product ) {
return ( 'valid' === nextgenthemes_get_key_status( $product ) ) ? true : false;
}
function nextgenthemes_api_update_key_status( $product, $key, $action ) {
$products = nextgenthemes_get_products();
$key_status = nextgenthemes_api_action( $products[ $product ]['id'], $key, $action );
nextgenthemes_update_key_status( $product, $key_status );
}
function nextgenthemes_get_defined_key( $slug ) {
$constant_name = str_replace( '-', '_', strtoupper( $slug . '_KEY' ) );
if( defined( $constant_name ) && constant( $constant_name ) ) {
return constant( $constant_name );
} else {
return false;
}
}
function nextgenthemes_licenses_page() {
?>
<div class="wrap">
<h2><?php esc_html_e( get_admin_page_title() ); ?></h2>
<form method="post" action="options.php">
<?php do_settings_sections( 'nextgenthemes-licenses' ); ?>
<?php settings_fields( 'nextgenthemes' ); ?>
<?php submit_button( __( 'Save Changes' ), 'primary', 'submit', false ); ?>
</form>
</div>
<?php
}
function nextgenthemes_init_edd_updaters() {
$products = nextgenthemes_get_products();
foreach ( $products as $product ) {
if ( 'plugin' == $product['type'] && ! empty( $product['file'] ) ) {
nextgenthemes_init_plugin_updater( $product );
} elseif ( 'theme' == $product['type'] ) {
nextgenthemes_init_theme_updater( $product );
}
}
}
function nextgenthemes_init_plugin_updater( $product ) {
// setup the updater
new Nextgenthemes_Plugin_Updater(
apply_filters( 'nextgenthemes_api_url', 'https://nextgenthemes.com' ),
$product['file'],
array(
'version' => $product['version'],
'license' => nextgenthemes_get_key( $product['slug'] ),
#'item_name' => $product['name'],
'item_id' => $product['id'],
'author' => $product['author']
)
);
}
function nextgenthemes_init_theme_updater( $product ) {
new EDD_Theme_Updater(
array(
'remote_api_url' => 'https://nextgenthemes.com',
'version' => $product['version'],
'license' => nextgenthemes_get_key( $product['slug'] ),
'item_id' => $product['name'],
'author' => $product['id'],
'theme_slug' => $product['slug'],
'download_id' => $product['download_id'], // Optional, used for generating a license renewal link
#'renew_url' => $product['renew_link'], // Optional, allows for a custom license renewal link
),
array(
'theme-license' => __( 'Theme License', ARVE_SLUG ),
'enter-key' => __( 'Enter your theme license key.', ARVE_SLUG ),
'license-key' => __( 'License Key', ARVE_SLUG ),
'license-action' => __( 'License Action', ARVE_SLUG ),
'deactivate-license' => __( 'Deactivate License', ARVE_SLUG ),
'activate-license' => __( 'Activate License', ARVE_SLUG ),
'status-unknown' => __( 'License status is unknown.', ARVE_SLUG ),
'renew' => __( 'Renew?', ARVE_SLUG ),
'unlimited' => __( 'unlimited', ARVE_SLUG ),
'license-key-is-active' => __( 'License key is active.', ARVE_SLUG ),
'expires%s' => __( 'Expires %s.', ARVE_SLUG ),
'expires-never' => __( 'Lifetime License.', ARVE_SLUG ),
'%1$s/%2$-sites' => __( 'You have %1$s / %2$s sites activated.', ARVE_SLUG ),
'license-key-expired-%s' => __( 'License key expired %s.', ARVE_SLUG ),
'license-key-expired' => __( 'License key has expired.', ARVE_SLUG ),
'license-keys-do-not-match' => __( 'License keys do not match.', ARVE_SLUG ),
'license-is-inactive' => __( 'License is inactive.', ARVE_SLUG ),
'license-key-is-disabled' => __( 'License key is disabled.', ARVE_SLUG ),
'site-is-inactive' => __( 'Site is inactive.', ARVE_SLUG ),
'license-status-unknown' => __( 'License status is unknown.', ARVE_SLUG ),
'update-notice' => __( "Updating this theme will lose any customizations you have made. 'Cancel' to stop, 'OK' to update.", ARVE_SLUG ),
'update-available' => __('<strong>%1$s %2$s</strong> is available. <a href="%3$s" class="thickbox" title="%4s">Check out what\'s new</a> or <a href="%5$s"%6$s>update now</a>.', ARVE_SLUG ),
)
);
}
function nextgenthemes_api_action( $item_id, $key, $action ) {
if ( ! in_array( $action, array( 'activate', 'deactivate', 'check' ) ) ) {
wp_die( 'invalid action' );
}
// data to send in our API request
$api_params = array(
'edd_action' => $action . '_license',
'license' => sanitize_text_field( $key ),
'item_id' => $item_id,
'url' => home_url()
);
// Call the custom API.
$response = wp_remote_post(
'https://nextgenthemes.com',
array( 'timeout' => 15, 'sslverify' => true, 'body' => $api_params )
);
// make sure the response came back okay
if ( is_wp_error( $response ) || 200 !== wp_remote_retrieve_response_code( $response ) ) {
if ( is_wp_error( $response ) ) {
$message = $response->get_error_message();
} else {
$message = __( 'An error occurred, please try again.', ARVE_SLUG );
}
} else {
$license_data = json_decode( wp_remote_retrieve_body( $response ) );
if ( false === $license_data->success ) {
switch( $license_data->error ) {
case 'expired' :
$message = sprintf(
__( 'Your license key expired on %s.' ),
date_i18n( get_option( 'date_format' ), strtotime( $license_data->expires, current_time( 'timestamp' ) ) )
);
break;
case 'revoked' :
$message = __( 'Your license key has been disabled.', ARVE_SLUG );
break;
case 'missing' :
$message = __( 'Invalid license.', ARVE_SLUG );
break;
case 'invalid' :
case 'site_inactive' :
$message = __( 'Your license is not active for this URL.', ARVE_SLUG );
break;
case 'item_name_mismatch' :
$message = sprintf( __( 'This appears to be an invalid license key for %s.' ), ARVE_SLUG );
break;
case 'no_activations_left':
$message = __( 'Your license key has reached its activation limit.', ARVE_SLUG );
break;
default :
$message = __( 'An error occurred, please try again.', ARVE_SLUG );
break;
}
}
}
if ( empty( $message ) ) {
if ( empty( $license_data->license ) ) {
$textarea_dump = arve_textarea_dump( $response );
$message = sprintf(
__( 'Error. Please report the following:<br> %s', ARVE_SLUG ),
$textarea_dump
);
} else {
$message = $license_data->license;
}
}
return $message;
}
function arve_dump( $var ) {
ob_start();
var_dump( $var );
return ob_get_clean();
}
function arve_textarea_dump( $var ) {
return sprintf( '<textarea style="width: 100%; height: 70vh;">%s</textarea>', esc_textarea( arve_dump( $var ) ) );
}
| {
"content_hash": "567242efed40396dce3e8cca61c29010",
"timestamp": "",
"source": "github",
"line_count": 610,
"max_line_length": 201,
"avg_line_length": 28.977049180327867,
"alnum_prop": 0.5979293957909029,
"repo_name": "sifonsecac/capitalino-errante",
"id": "75941cce08e083f0cae12a9487afb992be561b84",
"size": "17676",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "wp-content/plugins/advanced-responsive-video-embedder/admin/functions-licensing.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "3458117"
},
{
"name": "HTML",
"bytes": "42443"
},
{
"name": "Hack",
"bytes": "915"
},
{
"name": "JavaScript",
"bytes": "5543630"
},
{
"name": "PHP",
"bytes": "22604660"
},
{
"name": "Ruby",
"bytes": "3054"
},
{
"name": "Shell",
"bytes": "8030"
},
{
"name": "Smarty",
"bytes": "33"
},
{
"name": "XSLT",
"bytes": "4267"
}
],
"symlink_target": ""
} |
Use TDD to build your NginX config files feature by feature, or write regression tests to help you refactor your config-monsters.
## Installation
You'll need Ruby and bundler.
Add this line to a Gemfile in your project folder:
gem 'rspec-nginx'
And then execute:
$ bundle
Or install it yourself as:
$ gem install rspec-nginx
## Usage
require 'rspec/nginx'
describe 'simple-vhost-with-www-redirect' do
describe 'nginx.conf', :type => :nginx_config do
it { should have_valid_syntax }
end
end
## Contributing
1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request
| {
"content_hash": "45d4f339f77503423c8eebd6b93b0499",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 129,
"avg_line_length": 20.710526315789473,
"alnum_prop": 0.6963151207115629,
"repo_name": "andyt/rspec-nginx",
"id": "ebe1352f5d0ccdfd2b068ca620401cc2aeeed252",
"size": "803",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "9425"
}
],
"symlink_target": ""
} |
@interface CoreDataManager : NSObject
+ (void)setCoreDataManagedObjectContext:(NSManagedObjectContext*)context;
+ (NSArray*)getAllEntityRecords:(NSString*)entityForName;
+ (void)removeCoreDataEntityRows:(NSString*)entityForName;
@end
| {
"content_hash": "f601cf47b80a964ecdacdd318ec01575",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 73,
"avg_line_length": 33.714285714285715,
"alnum_prop": 0.826271186440678,
"repo_name": "FlipFlopWeekly/zorios",
"id": "e18f8e7a4577dfb7da8b3d0d5cb04f3f659fc04a",
"size": "411",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Zorios/Manager/CoreDataManager.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "979"
},
{
"name": "Objective-C",
"bytes": "90575"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>SECLDAPConnector</groupId>
<artifactId>SECLDAPConnector</artifactId>
<version>develop</version>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.runmyprocess</groupId>
<artifactId>json</artifactId>
<version>1.6.4</version>
</dependency>
<dependency>
<groupId>com.runmyprocess.sec</groupId>
<artifactId>rmp-sec-sdk</artifactId>
<version>develop</version>
</dependency>
<dependency>
<groupId>net.sf.michael-o.dirctxsrc</groupId>
<artifactId>dircontextsource</artifactId>
<version>0.10</version>
</dependency>
<dependency>
<groupId>net.ericaro</groupId>
<artifactId>neoevents</artifactId>
<version>1.0.1</version>
</dependency>
<dependency>
<groupId>com.unboundid</groupId>
<artifactId>unboundid-ldapsdk</artifactId>
<version>1.1.3</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
<encoding>utf8</encoding>
</configuration>
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<archive>
<manifest>
<mainClass>com.runmyprocess.sec.LDAPHandler</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
<executions>
<execution>
<id>make-assembly</id> <!-- this is used for inheritance merges -->
<phase>package</phase> <!-- bind to the packaging phase -->
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project> | {
"content_hash": "2d0c50271fe338f70ab32e6049818de4",
"timestamp": "",
"source": "github",
"line_count": 81,
"max_line_length": 108,
"avg_line_length": 36.358024691358025,
"alnum_prop": 0.4977928692699491,
"repo_name": "runmyprocess/sec-ldap",
"id": "15d5c9b0956492e6521483127df41a193f03e8fa",
"size": "2945",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "pom.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "12122"
}
],
"symlink_target": ""
} |
<html>
<head>
<title>Ragebot</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-2.2.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
</head>
<body>
{{! Top navbar }}
<nav class="navbar navbar-default navbar-fixed-top">
<div class="container">
<div class="navbar-header hidden-xs">
<a class="navbar-brand" href="#">Ragebot</a>
</div>
<form class="navbar-form navbar-right" role="search">
<div class="form-group">
<input type="text" class="form-control" placeholder="Search" id="filter">
</div>
</form>
</div>
</nav>
{{! Content }}
<div class="container" style="margin-bottom: 50px; margin-top: 70px">
<div class="row">
<div class="col-md-4">
<div class="panel panel-default">
<div class="panel-heading" style="overflow: hidden;">
<span id="current" style="white-space: nowrap;"></span>
</div>
<div class="panel-body text-center">
<button type="button" class="btn btn-default btn-lg hide" id="resume" data-toggle="tooltip" data-placement="top" title="Resume"><span class="glyphicon glyphicon-play" aria-hidden="true"></span></button>
<button type="button" class="btn btn-default btn-lg" id="pause" data-toggle="tooltip" data-placement="top" title="Pause"><span class="glyphicon glyphicon-pause" aria-hidden="true"></span></button>
<button type="button" class="btn btn-default btn-lg" id="next" data-toggle="tooltip" data-placement="top" title="Next"><span class="glyphicon glyphicon-forward" aria-hidden="true"></span></button>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading">
Music queue
</div>
<div class="panel-body">
<ul class="list-group" id="queueList">
</ul>
</div>
</div>
</div>
<div class="col-md-8">
<ul class="list-group" id="musicList">
{{ #musiclist }}
<li class="list-group-item" id="{{ index }}">
<span class="musicName">{{ name }}</span>
<div class="btn-group pull-right">
<a href="#" class="btn btn-default btn-sm playBtn" data-toggle="tooltip" data-placement="top" title="Play this song"><span class="glyphicon glyphicon-play" aria-hidden="true"></span></a>
<a href="#" class="btn btn-default btn-sm queueBtn" data-toggle="tooltip" data-placement="top" title="Add to queue"><span class="glyphicon glyphicon-music" aria-hidden="true"></span></a>
</div>
</li>
{{ /musiclist }}
</ul>
</div>
</div>
</div>
{{! Bottom navbar }}
<nav class="navbar navbar-default navbar-fixed-bottom navbar-header hidden-xs">
<div class="container">
<ul class="nav navbar-nav">
<li><a href="http://www.rage-inside.fr">Rage-Inside.fr</a></li>
<li><a href="http://forums.rage-inside.fr">Forums</a></li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li><a href="#" role="button" id="refresh"><span class="glyphicon glyphicon-refresh" aria-hidden="true"></span> Refresh music list</a></li>
</ul>
</div>
</nav>
<script>
$(function() {
var socket = io();
(function init() {
$('[data-toggle="tooltip"]').tooltip({"container": "body"});
$("#filter").on("keyup", filterList);
$("#refresh").on("click", refreshList);
$("a.playBtn").on("click", playMusic);
$("a.queueBtn").on("click", queueMusic);
$("#next").on("click", next);
$("#resume").on("click", resume);
$("#pause").on("click", pause);
socket.on('current', function(musicId) {
$("#current").text(getSongById(musicId));
$("ul#musicList li.active").removeClass("active");
$("ul#musicList li#" + musicId).addClass("active");
});
socket.on('resumed', function() {
$("#pause .span").removeClass('hide');
$("#resume").addClass('hide');
});
socket.on('playing', function() {
$("#pause").removeClass('hide');
$("#resume").addClass('hide');
});
socket.on('paused', function() {
$("#pause").addClass('hide');
$("#resume").removeClass('hide');
});
socket.on('queueUpdate', function(musicQueue) {
buildQueue(musicQueue);
});
})();
function next() {
sendBotCommand("/next");
}
function resume() {
sendBotCommand("/resume");
}
function pause() {
sendBotCommand("/pause");
}
function playMusic(event) {
var id = $(event.currentTarget).parents("li")[0].id;
socket.emit('playById', id);
}
function queueMusic(event) {
var id = $(event.currentTarget).parents("li")[0].id;
socket.emit('queueById', id);
}
function filterList() {
$('li').removeClass('hide');;
$('li').filter(listCheck).addClass('hide');
}
function listCheck(index, value) {
if ($(value).text().toLowerCase().indexOf($("#filter").val().toLowerCase()) == -1) {
return true;
}
}
function refreshList() {
$.post("/refresh").then(function(data) {
if (data === "ok") {
location.reload(true);
}
});
}
function buildQueue(queue) {
$("#queueList").empty();
if (queue.length === 0) {
$("#queueList").append("<p>Empty</p>");
}
var count = 1;
queue.forEach(function(musicId) {
var queueItem = '<li class="list-group-item">' +
'<span class="musicName">' + count + ' - ' + getSongById(musicId) + '</span> ' +
// '<a href="#" class="btn btn-default btn-sm removeBtn pull-right" data-toggle="tooltip" data-placement="top" title="Remove from queue (not working)"><span class="glyphicon glyphicon-remove" aria-hidden="true"></span></a> ' +
'</li>';
$("#queueList").append(queueItem);
count++;
});
}
function sendBotCommand(command) {
socket.emit('botCmd', command);
}
function getSongById(id) {
return $("ul#musicList li#" + id + " span.musicName").text();
}
});
</script>
</body>
</html> | {
"content_hash": "1176e7edaf37d674f275d7d435f3d8b1",
"timestamp": "",
"source": "github",
"line_count": 186,
"max_line_length": 231,
"avg_line_length": 33.596774193548384,
"alnum_prop": 0.6106577052328372,
"repo_name": "Rage-inside/discord-Ragebot",
"id": "ecfa6a267ccefdad6993f4866c413fc807f9d7b9",
"size": "6249",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "bot/www/html/index.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "6249"
},
{
"name": "JavaScript",
"bytes": "70876"
},
{
"name": "Shell",
"bytes": "328"
}
],
"symlink_target": ""
} |
<Type Name="IComponentDeserializer" FullName="Urho.Resources.IComponentDeserializer">
<TypeSignature Language="C#" Value="public interface IComponentDeserializer" />
<TypeSignature Language="ILAsm" Value=".class public interface auto ansi abstract IComponentDeserializer" />
<AssemblyInfo>
<AssemblyName>Urho</AssemblyName>
<AssemblyVersion>1.0.0.0</AssemblyVersion>
</AssemblyInfo>
<Interfaces />
<Docs>
<summary>Interface that provides a serialization API to retrieve state during a load operation.</summary>
<remarks>To be added.</remarks>
</Docs>
<Members>
<Member MemberName="Deserialize<T>">
<MemberSignature Language="C#" Value="public T Deserialize<T> (string key);" />
<MemberSignature Language="ILAsm" Value=".method public hidebysig newslot virtual instance !!T Deserialize<T>(string key) cil managed" />
<MemberType>Method</MemberType>
<AssemblyInfo>
<AssemblyVersion>1.0.0.0</AssemblyVersion>
</AssemblyInfo>
<ReturnValue>
<ReturnType>T</ReturnType>
</ReturnValue>
<TypeParameters>
<TypeParameter Name="T" />
</TypeParameters>
<Parameters>
<Parameter Name="key" Type="System.String" />
</Parameters>
<Docs>
<typeparam name="T">To be added.</typeparam>
<param name="key">The key to retrieve from storage.</param>
<summary>Retrieves an object with the given key and with the given type.</summary>
<returns>To be added.</returns>
<remarks>The valid types for T are string, Vector2, Vector3, Vector4, IntRect, Quaternion, Colors, floats, ints, unsigned ints, bools and doubles.</remarks>
</Docs>
</Member>
</Members>
</Type>
| {
"content_hash": "36e376b66f7d7c9fb17713e1a1c8512c",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 164,
"avg_line_length": 44.717948717948715,
"alnum_prop": 0.6806192660550459,
"repo_name": "florin-chelaru/urho",
"id": "fbacabc4ec86ca0fc0cf1c8bfa5a79f123672741",
"size": "1744",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Docs/Urho.Resources/IComponentDeserializer.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "1504000"
},
{
"name": "C#",
"bytes": "3618775"
},
{
"name": "C++",
"bytes": "982541"
},
{
"name": "CSS",
"bytes": "3736"
},
{
"name": "F#",
"bytes": "14158"
},
{
"name": "GLSL",
"bytes": "156108"
},
{
"name": "HLSL",
"bytes": "181070"
},
{
"name": "HTML",
"bytes": "7034"
},
{
"name": "Java",
"bytes": "131204"
},
{
"name": "Makefile",
"bytes": "4311"
},
{
"name": "Objective-C",
"bytes": "8426"
},
{
"name": "Perl",
"bytes": "9691"
}
],
"symlink_target": ""
} |
layout: page
title: Pearl Inc. Party
date: 2016-05-24
author: Joe Aguilar
tags: weekly links, java
status: published
summary: Phasellus mattis ante at tortor facilisis tristique. Praesent.
banner: images/banner/wedding.jpg
booking:
startDate: 05/23/2016
endDate: 05/28/2016
ctyhocn: YTOSOHX
groupCode: PIP
published: true
---
Morbi mattis, felis eu mollis consequat, ex dolor viverra nisl, sed dignissim lectus erat vel felis. Donec fringilla odio eu orci vestibulum, in ultricies libero congue. Morbi eu fermentum nisi. Aenean condimentum dolor vitae neque lobortis, interdum molestie ex commodo. Aenean nunc dolor, ultricies commodo magna nec, blandit sagittis purus. Aliquam erat volutpat. Integer placerat eros vitae posuere porttitor.
* Pellentesque sed leo euismod, rhoncus nulla ac, euismod tortor
* Aenean nec lorem pulvinar, vestibulum diam in, interdum augue.
Fusce eleifend lectus nec urna sodales tristique. Duis eleifend, odio commodo fringilla vehicula, velit justo sollicitudin nisi, vitae auctor augue augue et velit. Phasellus ut varius libero. In hac habitasse platea dictumst. Phasellus sit amet pharetra nulla. Mauris ullamcorper velit at turpis consequat lobortis. Suspendisse pretium enim quis feugiat fermentum. Ut et ultrices sapien, vitae tristique justo. Vestibulum tincidunt a est ac vehicula. Cras consectetur in quam ut euismod. Mauris facilisis felis placerat ultrices consectetur. Donec viverra libero mauris.
Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla eget pellentesque neque, ac vehicula nisi. Quisque id tincidunt nulla, quis tristique tellus. Integer non eros semper, fringilla mi a, dignissim mauris. Fusce semper arcu sit amet nisi tempus luctus. Mauris a risus a mauris mattis dignissim dapibus sed felis. Suspendisse mollis lorem ipsum, ac fermentum mauris lobortis semper. Cras convallis ut lorem malesuada consectetur. Pellentesque id sagittis ante, sed euismod dui. Fusce id nibh mollis, tempus odio quis, vehicula leo. Ut eget scelerisque quam. Aliquam vitae libero at eros tempus mattis. Ut mollis a orci vel euismod.
| {
"content_hash": "873afeb3a148d8adbb7c8323e19fad84",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 669,
"avg_line_length": 96.4090909090909,
"alnum_prop": 0.8123526638378123,
"repo_name": "KlishGroup/prose-pogs",
"id": "eeb234181c70094b234b84db3c74500045dcb672",
"size": "2125",
"binary": false,
"copies": "1",
"ref": "refs/heads/gh-pages",
"path": "pogs/Y/YTOSOHX/PIP/index.md",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
<div class="container graphs-page">
<h1>Graphs with D3</h1>
<button ng-click="graphsCtrl.generateData()">Generate new data</button>
<div class="row">
<div class="col-md-12">
<ajst-todo-graph
todos="graphsCtrl.todos">
</ajst-todo-graph>
</div>
</div>
</div>
| {
"content_hash": "bb29bff17706409cf680b229163d58b8",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 73,
"avg_line_length": 19.8,
"alnum_prop": 0.6060606060606061,
"repo_name": "nycda/angularjs-tutorial",
"id": "1a84ae271f2d86fd8b46b6c7ca26f34f7cd1ca22",
"size": "297",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/app/graphs/graphs.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1346"
},
{
"name": "JavaScript",
"bytes": "43948"
}
],
"symlink_target": ""
} |
// Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// clang-format off
// #import 'chrome://os-settings/chromeos/os_settings.js';
// #import 'chrome://os-settings/strings.m.js';
// #import {Router, Route, routes} from 'chrome://os-settings/chromeos/os_settings.js';
// #import {flush, Polymer} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
// #import {waitBeforeNextRender, waitAfterNextRender, eventToPromise} from 'chrome://test/test_util.js';
// #import {assertTrue, assertEquals, assertFalse, assertNotEquals} from '../../../chai_assert.js';
// #import {createDefaultBluetoothDevice, FakeBluetoothConfig} from 'chrome://test/cr_components/chromeos/bluetooth/fake_bluetooth_config.js';
// #import {setBluetoothConfigForTesting} from 'chrome://resources/cr_components/chromeos/bluetooth/cros_bluetooth_config.js';
// clang-format on
suite('OsBluetoothDeviceDetailPageTest', function() {
/** @type {!FakeBluetoothConfig} */
let bluetoothConfig;
/** @type {!SettingsBluetoothDeviceDetailSubpageElement|undefined} */
let bluetoothDeviceDetailPage;
/** @type {!chromeos.bluetoothConfig.mojom} */
let mojom;
/**
* @type {!chromeos.bluetoothConfig.mojom.SystemPropertiesObserverInterface}
*/
let propertiesObserver;
setup(function() {
mojom = chromeos.bluetoothConfig.mojom;
bluetoothConfig = new FakeBluetoothConfig();
setBluetoothConfigForTesting(bluetoothConfig);
});
function init() {
bluetoothDeviceDetailPage =
document.createElement('os-settings-bluetooth-device-detail-subpage');
document.body.appendChild(bluetoothDeviceDetailPage);
Polymer.dom.flush();
propertiesObserver = {
/**
* SystemPropertiesObserverInterface override
* @param {!chromeos.bluetoothConfig.mojom.BluetoothSystemProperties}
* properties
*/
onPropertiesUpdated(properties) {
bluetoothDeviceDetailPage.systemProperties = properties;
},
};
bluetoothConfig.observeSystemProperties(propertiesObserver);
Polymer.dom.flush();
}
function flushAsync() {
Polymer.dom.flush();
return new Promise((resolve) => setTimeout(resolve));
}
teardown(function() {
bluetoothDeviceDetailPage.remove();
bluetoothDeviceDetailPage = null;
settings.Router.getInstance().resetRouteForTesting();
});
test(
'Error text is not shown after navigating away from page',
async function() {
init();
bluetoothConfig.setBluetoothEnabledState(/*enabled=*/ true);
const windowPopstatePromise =
test_util.eventToPromise('popstate', window);
const getBluetoothConnectDisconnectBtn = () =>
bluetoothDeviceDetailPage.$$('#connectDisconnectBtn');
const getConnectionFailedText = () =>
bluetoothDeviceDetailPage.$$('#connectionFailed');
const id = '12345/6789&';
const device1 = createDefaultBluetoothDevice(
id,
/*publicName=*/ 'BeatsX',
/*connectionState=*/
chromeos.bluetoothConfig.mojom.DeviceConnectionState.kNotConnected,
/*opt_nickname=*/ 'device1',
/*opt_audioCapability=*/
mojom.AudioOutputCapability.kCapableOfAudioOutput,
/*opt_deviceType=*/ mojom.DeviceType.kMouse);
device1.deviceProperties.batteryInfo = {
defaultProperties: {batteryPercentage: 90}
};
bluetoothConfig.appendToPairedDeviceList([device1]);
await flushAsync();
let params = new URLSearchParams();
params.append('id', id);
settings.Router.getInstance().navigateTo(
settings.routes.BLUETOOTH_DEVICE_DETAIL, params);
await flushAsync();
// Try to connect.
getBluetoothConnectDisconnectBtn().click();
await flushAsync();
bluetoothConfig.completeConnect(/*success=*/ false);
await flushAsync();
assertTrue(!!getConnectionFailedText());
params = new URLSearchParams();
params.append('id', id);
settings.Router.getInstance().navigateTo(
settings.routes.BLUETOOTH_DEVICE_DETAIL, params);
await flushAsync();
assertFalse(!!getConnectionFailedText());
});
test('Managed by enterprise icon', async function() {
init();
bluetoothConfig.setBluetoothEnabledState(/*enabled=*/ true);
const getManagedIcon = () => {
return bluetoothDeviceDetailPage.$$('#managedIcon');
};
const navigateToDeviceDetailPage = () => {
const params = new URLSearchParams();
params.append('id', '12345/6789&');
settings.Router.getInstance().navigateTo(
settings.routes.BLUETOOTH_DEVICE_DETAIL, params);
};
const device = createDefaultBluetoothDevice(
/*id=*/ '12345/6789&',
/*publicName=*/ 'BeatsX',
/*connectionState=*/
chromeos.bluetoothConfig.mojom.DeviceConnectionState.kConnected,
/*opt_nickname=*/ 'device1',
/*opt_audioCapability=*/
mojom.AudioOutputCapability.kCapableOfAudioOutput,
/*opt_deviceType=*/ mojom.DeviceType.kMouse,
/*opt_isBlockedByPolicy=*/ true);
bluetoothConfig.appendToPairedDeviceList([device]);
await flushAsync();
navigateToDeviceDetailPage();
await flushAsync();
assertTrue(!!getManagedIcon());
device.deviceProperties.isBlockedByPolicy = false;
bluetoothConfig.updatePairedDevice(device);
await flushAsync();
assertFalse(!!getManagedIcon());
});
test('True Wireless Images shown when expected', async function() {
init();
bluetoothConfig.setBluetoothEnabledState(/*enabled=*/ true);
const getTrueWirelessImages = () =>
bluetoothDeviceDetailPage.$$('#trueWirelessImages');
const navigateToDeviceDetailPage = () => {
const params = new URLSearchParams();
params.append('id', '12345/6789&');
settings.Router.getInstance().navigateTo(
settings.routes.BLUETOOTH_DEVICE_DETAIL, params);
};
const device = createDefaultBluetoothDevice(
/*id=*/ '12345/6789&',
/*publicName=*/ 'BeatsX',
/*connectionState=*/
chromeos.bluetoothConfig.mojom.DeviceConnectionState.kNotConnected,
/*opt_nickname=*/ 'device1',
/*opt_audioCapability=*/
mojom.AudioOutputCapability.kCapableOfAudioOutput,
/*opt_deviceType=*/ mojom.DeviceType.kMouse,
/*opt_isBlockedByPolicy=*/ true);
const fakeUrl = {url: 'fake_image'};
// Emulate missing the right bud image.
device.deviceProperties.imageInfo = {
defaultImageUrl: fakeUrl,
trueWirelessImages: {leftBudImageUrl: fakeUrl, caseImageUrl: fakeUrl}
};
device.deviceProperties.batteryInfo = {
leftBudInfo: {batteryPercentage: 90}
};
bluetoothConfig.appendToPairedDeviceList([device]);
await flushAsync();
navigateToDeviceDetailPage();
// Don't display component unless all images are present.
await flushAsync();
assertFalse(!!getTrueWirelessImages());
device.deviceProperties.imageInfo.trueWirelessImages.rightBudImageUrl =
fakeUrl;
bluetoothConfig.updatePairedDevice(device);
await flushAsync();
assertTrue(!!getTrueWirelessImages());
// If detailed battery info is not available, only show True Wireless
// component if not connected.
device.deviceProperties.batteryInfo = {};
device.deviceProperties.connectionState =
mojom.DeviceConnectionState.kNotConnected;
bluetoothConfig.updatePairedDevice(device);
await flushAsync();
assertTrue(!!getTrueWirelessImages());
device.deviceProperties.connectionState =
mojom.DeviceConnectionState.kConnecting;
bluetoothConfig.updatePairedDevice(device);
await flushAsync();
assertTrue(!!getTrueWirelessImages());
device.deviceProperties.connectionState =
mojom.DeviceConnectionState.kConnected;
bluetoothConfig.updatePairedDevice(device);
await flushAsync();
assertFalse(!!getTrueWirelessImages());
});
test('Show change settings row, and navigate to subpages', async function() {
init();
bluetoothConfig.setBluetoothEnabledState(/*enabled=*/ true);
const getChangeMouseSettings = () =>
bluetoothDeviceDetailPage.$$('#changeMouseSettings');
const getChangeKeyboardSettings = () =>
bluetoothDeviceDetailPage.$$('#changeKeyboardSettings');
const device1 = createDefaultBluetoothDevice(
/*id=*/ '12//345&6789',
/*publicName=*/ 'BeatsX',
/*connectionState=*/
chromeos.bluetoothConfig.mojom.DeviceConnectionState.kConnected,
/*opt_nickname=*/ 'device1',
/*opt_audioCapability=*/
mojom.AudioOutputCapability.kCapableOfAudioOutput,
/*opt_deviceType=*/ mojom.DeviceType.kMouse);
bluetoothConfig.appendToPairedDeviceList([device1]);
await flushAsync();
assertFalse(!!getChangeMouseSettings());
assertFalse(!!getChangeKeyboardSettings());
const params = new URLSearchParams();
params.append('id', '12//345&6789');
settings.Router.getInstance().navigateTo(
settings.routes.BLUETOOTH_DEVICE_DETAIL, params);
await flushAsync();
assertTrue(bluetoothDeviceDetailPage.getIsDeviceConnectedForTest());
assertTrue(!!getChangeMouseSettings());
assertFalse(!!getChangeKeyboardSettings());
assertEquals(
bluetoothDeviceDetailPage.i18n(
'bluetoothDeviceDetailChangeDeviceSettingsMouse'),
getChangeMouseSettings().label);
device1.deviceProperties.connectionState =
mojom.DeviceConnectionState.kNotConnected;
bluetoothConfig.updatePairedDevice(device1);
await flushAsync();
assertFalse(!!getChangeMouseSettings());
device1.deviceProperties.connectionState =
mojom.DeviceConnectionState.kConnected;
bluetoothConfig.updatePairedDevice(device1);
await flushAsync();
assertTrue(!!getChangeMouseSettings());
getChangeMouseSettings().click();
await flushAsync();
assertEquals(
settings.Router.getInstance().getCurrentRoute(),
settings.routes.POINTERS);
// Navigate back to the detail page.
assertNotEquals(
getChangeMouseSettings(),
bluetoothDeviceDetailPage.shadowRoot.activeElement);
let windowPopstatePromise = test_util.eventToPromise('popstate', window);
settings.Router.getInstance().navigateToPreviousRoute();
await windowPopstatePromise;
await waitBeforeNextRender(bluetoothDeviceDetailPage);
assertTrue(bluetoothDeviceDetailPage.getIsDeviceConnectedForTest());
// Check that |#changeMouseSettings| has been focused.
assertEquals(
getChangeMouseSettings(),
bluetoothDeviceDetailPage.shadowRoot.activeElement);
device1.deviceProperties.deviceType = mojom.DeviceType.kKeyboard;
bluetoothConfig.updatePairedDevice(device1);
await flushAsync();
assertFalse(!!getChangeMouseSettings());
assertTrue(!!getChangeKeyboardSettings());
device1.deviceProperties.connectionState =
mojom.DeviceConnectionState.kNotConnected;
bluetoothConfig.updatePairedDevice(device1);
await flushAsync();
assertFalse(!!getChangeKeyboardSettings());
device1.deviceProperties.connectionState =
mojom.DeviceConnectionState.kConnected;
bluetoothConfig.updatePairedDevice(device1);
await flushAsync();
assertTrue(!!getChangeKeyboardSettings());
getChangeKeyboardSettings().click();
await flushAsync();
assertEquals(
settings.Router.getInstance().getCurrentRoute(),
settings.routes.KEYBOARD);
// Navigate back to the detail page.
assertNotEquals(
getChangeKeyboardSettings(),
bluetoothDeviceDetailPage.shadowRoot.activeElement);
windowPopstatePromise = test_util.eventToPromise('popstate', window);
settings.Router.getInstance().navigateToPreviousRoute();
await windowPopstatePromise;
await waitBeforeNextRender(bluetoothDeviceDetailPage);
assertTrue(bluetoothDeviceDetailPage.getIsDeviceConnectedForTest());
// Check that |#changeKeyboardSettings| has been focused.
assertEquals(
getChangeKeyboardSettings(),
bluetoothDeviceDetailPage.shadowRoot.activeElement);
// This is needed or other tests will fail.
// TODO(gordonseto): Figure out how to remove this.
getChangeKeyboardSettings().click();
await flushAsync();
});
test('Device becomes unavailable while viewing page.', async function() {
init();
bluetoothConfig.setBluetoothEnabledState(/*enabled=*/ true);
const windowPopstatePromise = test_util.eventToPromise('popstate', window);
const device1 = createDefaultBluetoothDevice(
/*id=*/ '12345/6789&',
/*publicName=*/ 'BeatsX',
/*connectionState=*/
chromeos.bluetoothConfig.mojom.DeviceConnectionState.kConnected,
/*opt_nickname=*/ 'device1',
/*opt_audioCapability=*/
mojom.AudioOutputCapability.kCapableOfAudioOutput,
/*opt_deviceType=*/ mojom.DeviceType.kMouse);
const device2 = createDefaultBluetoothDevice(
/*id=*/ '987654321',
/*publicName=*/ 'MX 3',
/*connectionState=*/
chromeos.bluetoothConfig.mojom.DeviceConnectionState.kConnected,
/*opt_nickname=*/ 'device2',
/*opt_audioCapability=*/
mojom.AudioOutputCapability.kCapableOfAudioOutput,
/*opt_deviceType=*/ mojom.DeviceType.kMouse);
bluetoothConfig.appendToPairedDeviceList([device1, device2]);
await flushAsync();
const params = new URLSearchParams();
params.append('id', '12345/6789&');
settings.Router.getInstance().navigateTo(
settings.routes.BLUETOOTH_DEVICE_DETAIL, params);
await flushAsync();
assertEquals('device1', bluetoothDeviceDetailPage.parentNode.pageTitle);
bluetoothConfig.removePairedDevice(device1);
await windowPopstatePromise;
});
test('Device UI states test', async function() {
init();
const getBluetoothStatusIcon = () =>
bluetoothDeviceDetailPage.$$('#statusIcon');
const getBluetoothStateText = () =>
bluetoothDeviceDetailPage.$$('#bluetoothStateText');
const getBluetoothForgetBtn = () =>
bluetoothDeviceDetailPage.$$('#forgetBtn');
const getBluetoothStateBtn = () =>
bluetoothDeviceDetailPage.$$('#connectDisconnectBtn');
const getBluetoothDeviceNameLabel = () =>
bluetoothDeviceDetailPage.$$('#bluetoothDeviceNameLabel');
const getBluetoothDeviceBatteryInfo = () =>
bluetoothDeviceDetailPage.$$('#batteryInfo');
const getNonAudioOutputDeviceMessage = () =>
bluetoothDeviceDetailPage.$$('#nonAudioOutputDeviceMessage');
bluetoothConfig.setBluetoothEnabledState(/*enabled=*/ true);
assertTrue(!!getBluetoothStatusIcon());
assertTrue(!!getBluetoothStateText());
assertTrue(!!getBluetoothDeviceNameLabel());
assertFalse(!!getBluetoothForgetBtn());
assertFalse(!!getBluetoothStateBtn());
assertFalse(!!getBluetoothDeviceBatteryInfo());
assertFalse(!!getNonAudioOutputDeviceMessage());
const deviceNickname = 'device1';
const device1 = createDefaultBluetoothDevice(
/*id=*/ '123456789',
/*publicName=*/ 'BeatsX',
/*connectionState=*/
chromeos.bluetoothConfig.mojom.DeviceConnectionState.kConnected,
deviceNickname,
/*opt_udioCapability=*/
mojom.AudioOutputCapability.kCapableOfAudioOutput,
/*opt_deviceType=*/ mojom.DeviceType.kHeadset);
device1.deviceProperties.batteryInfo = {
defaultProperties: {batteryPercentage: 90}
};
bluetoothConfig.appendToPairedDeviceList([device1]);
await flushAsync();
let params = new URLSearchParams();
params.append('id', '123456789');
settings.Router.getInstance().navigateTo(
settings.routes.BLUETOOTH_DEVICE_DETAIL, params);
await flushAsync();
assertTrue(!!getBluetoothForgetBtn());
// Simulate connected state and audio capable.
assertTrue(!!getBluetoothStateBtn());
assertEquals(
bluetoothDeviceDetailPage.i18n('bluetoothDeviceDetailConnected'),
getBluetoothStateText().textContent.trim());
assertTrue(bluetoothDeviceDetailPage.getIsDeviceConnectedForTest());
assertEquals(
deviceNickname, getBluetoothDeviceNameLabel().textContent.trim());
assertEquals(
'os-settings:bluetooth-connected', getBluetoothStatusIcon().icon);
assertTrue(!!getBluetoothDeviceBatteryInfo());
assertFalse(!!getNonAudioOutputDeviceMessage());
// Simulate disconnected state and not audio capable.
device1.deviceProperties.connectionState =
mojom.DeviceConnectionState.kNotConnected;
device1.deviceProperties.audioCapability =
mojom.AudioOutputCapability.kNotCapableOfAudioOutput;
device1.deviceProperties.batteryInfo = {defaultProperties: null};
bluetoothConfig.updatePairedDevice(device1);
await flushAsync();
assertFalse(!!getBluetoothStateBtn());
assertEquals(
bluetoothDeviceDetailPage.i18n('bluetoothDeviceDetailDisconnected'),
getBluetoothStateText().textContent.trim());
assertFalse(bluetoothDeviceDetailPage.getIsDeviceConnectedForTest());
assertEquals(
'os-settings:bluetooth-disabled', getBluetoothStatusIcon().icon);
assertFalse(!!getBluetoothDeviceBatteryInfo());
assertEquals(
getBluetoothForgetBtn().ariaLabel,
bluetoothDeviceDetailPage.i18n(
'bluetoothDeviceDetailForgetA11yLabel', deviceNickname));
assertTrue(!!getNonAudioOutputDeviceMessage());
assertEquals(
bluetoothDeviceDetailPage.i18n(
'bluetoothDeviceDetailHIDMessageDisconnected'),
getNonAudioOutputDeviceMessage().textContent.trim());
// Simulate connected state and not audio capable.
device1.deviceProperties.connectionState =
mojom.DeviceConnectionState.kConnected;
bluetoothConfig.updatePairedDevice(device1);
await flushAsync();
assertTrue(!!getNonAudioOutputDeviceMessage());
assertEquals(
bluetoothDeviceDetailPage.i18n(
'bluetoothDeviceDetailHIDMessageConnected'),
getNonAudioOutputDeviceMessage().textContent.trim());
device1.deviceProperties.audioCapability =
mojom.AudioOutputCapability.kCapableOfAudioOutput;
bluetoothConfig.updatePairedDevice(device1);
// Navigate away from details subpage with while connected and navigate
// back.
const windowPopstatePromise = test_util.eventToPromise('popstate', window);
settings.Router.getInstance().navigateToPreviousRoute();
await windowPopstatePromise;
params = new URLSearchParams();
params.append('id', '123456789');
settings.Router.getInstance().navigateTo(
settings.routes.BLUETOOTH_DEVICE_DETAIL, params);
await flushAsync();
assertTrue(!!getBluetoothStateBtn());
assertEquals(
bluetoothDeviceDetailPage.i18n('bluetoothDeviceDetailConnected'),
getBluetoothStateText().textContent.trim());
});
test(
'Change device dialog is shown after change name button click',
async function() {
init();
bluetoothConfig.setBluetoothEnabledState(/*enabled=*/ true);
const getChangeDeviceNameDialog = () =>
bluetoothDeviceDetailPage.$$('#changeDeviceNameDialog');
const device1 = createDefaultBluetoothDevice(
/*id=*/ '12//345&6789',
/*publicName=*/ 'BeatsX',
/*connectionState=*/
chromeos.bluetoothConfig.mojom.DeviceConnectionState.kConnected,
/*opt_nickname=*/ 'device1',
/*opt_audioCapability=*/
mojom.AudioOutputCapability.kCapableOfAudioOutput,
/*opt_deviceType=*/ mojom.DeviceType.kMouse);
bluetoothConfig.appendToPairedDeviceList([device1]);
await flushAsync();
const params = new URLSearchParams();
params.append('id', '12//345&6789');
settings.Router.getInstance().navigateTo(
settings.routes.BLUETOOTH_DEVICE_DETAIL, params);
await flushAsync();
assertFalse(!!getChangeDeviceNameDialog());
const changeNameBtn = bluetoothDeviceDetailPage.$$('#changeNameBtn');
assertTrue(!!changeNameBtn);
changeNameBtn.click();
await flushAsync();
assertTrue(!!getChangeDeviceNameDialog());
});
test('Landing on page while device is still connecting', async function() {
init();
bluetoothConfig.setBluetoothEnabledState(/*enabled=*/ true);
const getBluetoothConnectDisconnectBtn = () =>
bluetoothDeviceDetailPage.$$('#connectDisconnectBtn');
const getBluetoothStateText = () =>
bluetoothDeviceDetailPage.$$('#bluetoothStateText');
const getConnectionFailedText = () =>
bluetoothDeviceDetailPage.$$('#connectionFailed');
const id = '12//345&6789';
const device1 = createDefaultBluetoothDevice(
/*id=*/ id,
/*publicName=*/ 'BeatsX',
/*connectionState=*/
chromeos.bluetoothConfig.mojom.DeviceConnectionState.kConnecting,
/*opt_nickname=*/ 'device1',
/*opt_audioCapability=*/
mojom.AudioOutputCapability.kCapableOfAudioOutput,
/*opt_deviceType=*/ mojom.DeviceType.kMouse);
bluetoothConfig.appendToPairedDeviceList([device1]);
await flushAsync();
const params = new URLSearchParams();
params.append('id', id);
settings.Router.getInstance().navigateTo(
settings.routes.BLUETOOTH_DEVICE_DETAIL, params);
await flushAsync();
await flushAsync();
assertTrue(!!getBluetoothConnectDisconnectBtn());
assertEquals(
bluetoothDeviceDetailPage.i18n('bluetoothConnecting'),
getBluetoothStateText().textContent.trim());
assertFalse(!!getConnectionFailedText());
assertTrue(getBluetoothConnectDisconnectBtn().disabled);
assertEquals(
bluetoothDeviceDetailPage.i18n('bluetoothConnect'),
getBluetoothConnectDisconnectBtn().textContent.trim());
});
test('Connect/Disconnect/forget states and error message', async function() {
init();
bluetoothConfig.setBluetoothEnabledState(/*enabled=*/ true);
const windowPopstatePromise = test_util.eventToPromise('popstate', window);
const getBluetoothForgetBtn = () =>
bluetoothDeviceDetailPage.$$('#forgetBtn');
const getBluetoothConnectDisconnectBtn = () =>
bluetoothDeviceDetailPage.$$('#connectDisconnectBtn');
const getBluetoothStateText = () =>
bluetoothDeviceDetailPage.$$('#bluetoothStateText');
const getConnectionFailedText = () =>
bluetoothDeviceDetailPage.$$('#connectionFailed');
const assertUIState =
(isShowingConnectionFailed, isConnectDisconnectBtnDisabled,
bluetoothStateText, connectDisconnectBtnText) => {
assertEquals(!!getConnectionFailedText(), isShowingConnectionFailed);
assertEquals(
getBluetoothConnectDisconnectBtn().disabled,
isConnectDisconnectBtnDisabled);
assertEquals(
getBluetoothStateText().textContent.trim(), bluetoothStateText);
assertEquals(
getBluetoothConnectDisconnectBtn().textContent.trim(),
connectDisconnectBtnText);
};
const id = '12345/6789&';
const device1 = createDefaultBluetoothDevice(
id,
/*publicName=*/ 'BeatsX',
/*connectionState=*/
chromeos.bluetoothConfig.mojom.DeviceConnectionState.kNotConnected,
/*opt_nickname=*/ 'device1',
/*opt_audioCapability=*/
mojom.AudioOutputCapability.kCapableOfAudioOutput,
/*opt_deviceType=*/ mojom.DeviceType.kMouse);
device1.deviceProperties.batteryInfo = {
defaultProperties: {batteryPercentage: 90}
};
bluetoothConfig.appendToPairedDeviceList([device1]);
await flushAsync();
const params = new URLSearchParams();
params.append('id', id);
settings.Router.getInstance().navigateTo(
settings.routes.BLUETOOTH_DEVICE_DETAIL, params);
await flushAsync();
assertTrue(!!getBluetoothConnectDisconnectBtn());
// Disconnected without error.
assertUIState(
/*isShowingConnectionFailed=*/ false,
/*isConnectDisconnectBtnDisabled=*/ false,
/*bluetoothStateText=*/
bluetoothDeviceDetailPage.i18n('bluetoothDeviceDetailDisconnected'),
/*connectDisconnectBtnText=*/
bluetoothDeviceDetailPage.i18n('bluetoothConnect'));
// Try to connect.
getBluetoothConnectDisconnectBtn().click();
await flushAsync();
// Connecting.
assertUIState(
/*isShowingConnectionFailed=*/ false,
/*isConnectDisconnectBtnDisabled=*/ true,
/*bluetoothStateText=*/
bluetoothDeviceDetailPage.i18n('bluetoothConnecting'),
/*connectDisconnectBtnText=*/
bluetoothDeviceDetailPage.i18n('bluetoothConnect'));
bluetoothConfig.completeConnect(/*success=*/ false);
// Connection fails.
await flushAsync();
// Disconnected with error.
assertUIState(
/*isShowingConnectionFailed=*/ true,
/*isConnectDisconnectBtnDisabled=*/ false,
/*bluetoothStateText=*/
bluetoothDeviceDetailPage.i18n('bluetoothDeviceDetailDisconnected'),
/*connectDisconnectBtnText=*/
bluetoothDeviceDetailPage.i18n('bluetoothConnect'));
// Change device while connection failed text is shown.
bluetoothConfig.appendToPairedDeviceList([Object.assign({}, device1)]);
await flushAsync();
// Disconnected with error.
assertUIState(
/*isShowingConnectionFailed=*/ true,
/*isConnectDisconnectBtnDisabled=*/ false,
/*bluetoothStateText=*/
bluetoothDeviceDetailPage.i18n('bluetoothDeviceDetailDisconnected'),
/*connectDisconnectBtnText=*/
bluetoothDeviceDetailPage.i18n('bluetoothConnect'));
// Try to connect with success.
getBluetoothConnectDisconnectBtn().click();
await flushAsync();
bluetoothConfig.completeConnect(/*success=*/ true);
// Connection success.
assertUIState(
/*isShowingConnectionFailed=*/ false,
/*isConnectDisconnectBtnDisabled=*/ false,
/*bluetoothStateText=*/
bluetoothDeviceDetailPage.i18n('bluetoothDeviceDetailConnected'),
/*connectDisconnectBtnText=*/
bluetoothDeviceDetailPage.i18n('bluetoothDisconnect'));
// Disconnect device and check that connection error is not shown.
getBluetoothConnectDisconnectBtn().click();
await flushAsync();
bluetoothConfig.completeDisconnect(/*success=*/ true);
await flushAsync();
// Disconnected without error.
assertUIState(
/*isShowingConnectionFailed=*/ false,
/*isConnectDisconnectBtnDisabled=*/ false,
/*bluetoothStateText=*/
bluetoothDeviceDetailPage.i18n('bluetoothDeviceDetailDisconnected'),
/*connectDisconnectBtnText=*/
bluetoothDeviceDetailPage.i18n('bluetoothConnect'));
// Try to connect with error.
getBluetoothConnectDisconnectBtn().click();
await flushAsync();
bluetoothConfig.completeConnect(/*success=*/ false);
await flushAsync();
// Disconnected with error.
assertUIState(
/*isShowingConnectionFailed=*/ true,
/*isConnectDisconnectBtnDisabled=*/ false,
/*bluetoothStateText=*/
bluetoothDeviceDetailPage.i18n('bluetoothDeviceDetailDisconnected'),
/*connectDisconnectBtnText=*/
bluetoothDeviceDetailPage.i18n('bluetoothConnect'));
// Device automatically reconnects without calling connect. This
// can happen if connection failure was because device was turned off
// and is turned on. We expect connection error text to not show when
// disconnected.
device1.deviceProperties.connectionState =
mojom.DeviceConnectionState.kConnected;
bluetoothConfig.updatePairedDevice(device1);
await flushAsync();
// Connection success.
assertUIState(
/*isShowingConnectionFailed=*/ false,
/*isConnectDisconnectBtnDisabled=*/ false,
/*bluetoothStateText=*/
bluetoothDeviceDetailPage.i18n('bluetoothDeviceDetailConnected'),
/*connectDisconnectBtnText=*/
bluetoothDeviceDetailPage.i18n('bluetoothDisconnect'));
// Disconnect device and check that connection error is not shown.
getBluetoothConnectDisconnectBtn().click();
await flushAsync();
bluetoothConfig.completeDisconnect(/*success=*/ true);
await flushAsync();
// Disconnected without error.
assertUIState(
/*isShowingConnectionFailed=*/ false,
/*isConnectDisconnectBtnDisabled=*/ false,
/*bluetoothStateText=*/
bluetoothDeviceDetailPage.i18n('bluetoothDeviceDetailDisconnected'),
/*connectDisconnectBtnText=*/
bluetoothDeviceDetailPage.i18n('bluetoothConnect'));
// Retry connection with success.
getBluetoothConnectDisconnectBtn().click();
await flushAsync();
// Connecting.
assertUIState(
/*isShowingConnectionFailed=*/ false,
/*isConnectDisconnectBtnDisabled=*/ true,
/*bluetoothStateText=*/
bluetoothDeviceDetailPage.i18n('bluetoothConnecting'),
/*connectDisconnectBtnText=*/
bluetoothDeviceDetailPage.i18n('bluetoothConnect'));
bluetoothConfig.completeConnect(/*success=*/ true);
await flushAsync();
// Connection success.
assertUIState(
/*isShowingConnectionFailed=*/ false,
/*isConnectDisconnectBtnDisabled=*/ false,
/*bluetoothStateText=*/
bluetoothDeviceDetailPage.i18n('bluetoothDeviceDetailConnected'),
/*connectDisconnectBtnText=*/
bluetoothDeviceDetailPage.i18n('bluetoothDisconnect'));
// Forget device.
getBluetoothForgetBtn().click();
await flushAsync();
bluetoothConfig.completeForget(/*success=*/ true);
await windowPopstatePromise;
// Device and device Id should be null after navigating backward.
assertFalse(!!bluetoothDeviceDetailPage.getDeviceForTest());
assertFalse(!!bluetoothDeviceDetailPage.getDeviceIdForTest());
});
});
| {
"content_hash": "aaa797685e587002f468e827b976dcf2",
"timestamp": "",
"source": "github",
"line_count": 809,
"max_line_length": 142,
"avg_line_length": 37.49814585908529,
"alnum_prop": 0.697356276371308,
"repo_name": "scheib/chromium",
"id": "c0c61a2bad2df5187082644e41a33ffc5ed21957",
"size": "30336",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "chrome/test/data/webui/settings/chromeos/os_bluetooth_device_detail_subpage_tests.js",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<Schema>
<entity name="branch">
<forEvery entity="employee" value="1000"/>
<forEvery entity="customer" value="1000000"/>
</entity>
<entity name="employee">
</entity>
<entity name="customer">
<forEvery entity="account" value="2.5" />
</entity>
<entity name="account">
<forEvery entity="card" value="2"/>
<forEvery event="transaction" value="4"/>
</entity>
<entity name="card">
</entity>
<event name="transaction">
</event>
</Schema> | {
"content_hash": "eea77f6355c2e4fcf05fe89487e77a4d",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 47,
"avg_line_length": 19.615384615384617,
"alnum_prop": 0.6294117647058823,
"repo_name": "tchico/dgMaster-trunk",
"id": "0fd1f2259bbd20ff1b37179c7324e6b257e11eba",
"size": "510",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src-test/generator/misc/testConfigBig.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "672"
},
{
"name": "Java",
"bytes": "1416753"
}
],
"symlink_target": ""
} |
"use strict";
var path = require('path');
var index_1 = require('../index');
var fs = require('mz/fs');
var theme_1 = require('../theme');
var yargs = require('yargs');
yargs
.usage([
'',
'Usage: highlight [options] [file]',
'',
'Outputs a file or STDIN input with syntax highlighting'
].join('\n'))
.option('theme', {
alias: 't',
nargs: 1,
description: 'Use a theme defined in a JSON file'
})
.option('language', {
alias: 'l',
nargs: 1,
description: 'Set the langugage explicitely. If omitted will try to auto-detect'
})
.version(function () { return require('../../package.json').version; })
.help('help')
.alias('help', 'h')
.alias('version', 'v');
var argv = yargs.argv;
var file = argv._[0];
var codePromise;
if (!file && !process.stdin.isTTY) {
// Input from STDIN
process.stdin.setEncoding('utf8');
var code_1 = '';
process.stdin.on('readable', function () {
var chunk = process.stdin.read();
if (chunk !== null) {
code_1 += chunk;
}
});
codePromise = new Promise(function (resolve) {
process.stdin.on('end', function () {
resolve(code_1);
});
});
}
else if (file) {
// Read file
codePromise = fs.readFile(file, 'utf-8');
}
else {
yargs.showHelp();
process.exit(1);
}
Promise.all([
codePromise,
argv.theme ? fs.readFile(argv.theme, 'utf8') : Promise.resolve()
]).then(function (_a) {
var code = _a[0], theme = _a[1];
var options = {
ignoreIllegals: true,
theme: theme && theme_1.parse(theme)
};
if (file) {
var ext = path.extname(file).substr(1);
if (ext && index_1.supportsLanguage(ext)) {
options.language = ext;
}
}
options.language = argv.language;
process.stdout.write(index_1.highlight(code, options));
}).then(function () {
process.exit(0);
}).catch(function (err) {
console.error(err);
process.exit(1);
});
//# sourceMappingURL=highlight.js.map | {
"content_hash": "54194bc09917768febb05333b623eda4",
"timestamp": "",
"source": "github",
"line_count": 78,
"max_line_length": 84,
"avg_line_length": 26.08974358974359,
"alnum_prop": 0.5690417690417691,
"repo_name": "ghh0000/testTs",
"id": "22438cadd688d8436c042229a7306257b7cf644c",
"size": "2035",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "node_modules/cli-highlight/dist/bin/highlight.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "109359"
},
{
"name": "TypeScript",
"bytes": "44527"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "72d8cbf1049cc1db4c4a1cb67be4a32c",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "e744d927fce53c4ecc6556d6bfad84edcd81e49f",
"size": "179",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Anthemis bushehrica/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
using System;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using Vidyano.Service.Repository;
namespace LearningJapanese.Service
{
public class KanjiActions : RomajiActions<LearningJapaneseEntityModelContainer, Kanji>
{
private static readonly Regex onRegex = new Regex("<tr><td>ON reading\\(s\\)</td><td><b>([^<]+)</b></td></tr>", RegexOptions.Compiled);
private static readonly Regex kunRegex = new Regex("<tr><td>KUN reading\\(s\\)</td><td><b>([^<]+)</b></td></tr>", RegexOptions.Compiled);
private static readonly Regex strokeCountRegex = new Regex("<tr><td>Stroke Count</td><td><b>([^<]+)</b></td></tr>", RegexOptions.Compiled);
private static readonly Regex meaningRegex = new Regex("<tr><td>English meanings</td><td><b>([^<]+)</b></td></tr>", RegexOptions.Compiled);
private static readonly Regex radicalRegex = new Regex("title=\"Index:Chinese radical/([^\"]+)\"", RegexOptions.Compiled);
public override void OnConstruct(PersistentObject obj)
{
base.OnConstruct(obj);
if (obj.IsNew || obj.ObjectId != null)
obj["Radical"].Options = Context.CachedKanji().OrderBy(k => k.Radical).Select(k => k.Radical).Distinct().ToArray();
}
public override void OnConstruct(Query query, PersistentObject parent)
{
base.OnConstruct(query, parent);
if (query.Source == "Custom.RelatedKanji")
query.Actions = new[] { "RefreshQuery", "Filter" };
else
query.DisableActions("BulkEdit", "Delete");
}
public override void OnRefresh(RefreshArgs args)
{
var obj = args.PersistentObject;
var kanji = (string)obj["Character"];
if (!string.IsNullOrEmpty(kanji))
{
if (obj.IsNew && Context.CachedKanji().Any(k => k.Character == kanji))
{
obj.AddNotification("Kanji already exists! [url:" + kanji + "|#!/Learning/Kanji/" + kanji + "]", NotificationType.Notice);
return;
}
try
{
var wc = new WebClient { Encoding = Encoding.UTF8 };
var contents = wc.DownloadString("http://www.csse.monash.edu.au/~jwb/cgi-bin/wwwjdic.cgi?1MMJ" + kanji);
PopulateValue(obj, contents, "On", onRegex);
PopulateValue(obj, contents, "Kun", kunRegex);
PopulateValue(obj, contents, "StrokeCount", strokeCountRegex);
var meaningAttr = PopulateValue(obj, contents, "Meaning", meaningRegex);
meaningAttr.SetValue(((string)meaningAttr).Replace("、", " "));
try
{
wc = new WebClient { Encoding = Encoding.UTF8 };
contents = wc.DownloadString("http://en.wiktionary.org/wiki/" + kanji);
PopulateValue(obj, contents, "Radical", radicalRegex);
}
catch
{
obj.AddNotification("Can't get radical from: http://en.wiktionary.org/wiki/" + kanji, NotificationType.Notice);
}
}
catch (Exception ex)
{
obj.AddNotification(ex.Message, NotificationType.Notice);
}
}
}
protected override Kanji LoadEntity(PersistentObject obj, bool forRefresh = false)
{
Kanji entity;
if (!obj.IsNew)
{
int id;
entity = int.TryParse(obj.ObjectId, out id) ? Context.Kanji.FirstOrDefault(k => k.Id == id) : Context.Kanji.FirstOrDefault(k => k.Character == obj.ObjectId);
if (entity != null && id == 0)
obj.ObjectId = entity.GetKey();
}
else
entity = forRefresh ? CreateNewEntity(obj) : null;
if (entity != null)
{
if (forRefresh)
obj.PopulateObjectValues(entity, Context);
else if (!obj.HasNotification)
obj.AddNotification("[url:WWWJDIC|http://www.csse.monash.edu.au/~jwb/cgi-bin/wwwjdic.cgi?1MMJ" + entity.Character + "] - [url:Wiktionary|http://en.wiktionary.org/wiki/" + entity.Character + "]", NotificationType.OK);
}
return entity;
}
private static PersistentObjectAttribute PopulateValue(PersistentObject obj, string contents, string attrName, Regex regex)
{
var attr = obj[attrName];
var match = regex.Match(contents);
if (match.Success)
attr.SetValue(match.Groups[1].Value.Trim().Replace(" ", "、"));
return attr;
}
}
} | {
"content_hash": "19a3fb7ea2a58591eb5dba42588f3f9e",
"timestamp": "",
"source": "github",
"line_count": 111,
"max_line_length": 236,
"avg_line_length": 44.42342342342342,
"alnum_prop": 0.5428919083350233,
"repo_name": "stevehansen/learningjapanese",
"id": "82d54888ecd5d566ba1677e59a0747b2e13be508",
"size": "4937",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "LearningJapanese/Service/KanjiActions.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "89311"
},
{
"name": "HTML",
"bytes": "5125"
}
],
"symlink_target": ""
} |
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
<div class="x_panel">
<div class="x_title">
<ol class="breadcrumb pull-left">
<li><a ng-click="navigateToPath('/cdns')">CDNs</a></li>
<li><a ng-click="navigateToPath('/cdns/' + cdn.id)">{{cdn.name}}</a></li>
<li><a ng-click="navigateToPath('/cdns/' + cdn.id + '/federations')">Federations</a></li>
<li><a ng-click="navigateToPath('/cdns/' + cdn.id + '/federations/' + federation.id)">{{federation.cname}}</a></li>
<li class="active">Delivery Services</li>
</ol>
<div class="pull-right">
<button class="btn btn-primary" title="Link Delivery Services to Federation" ng-click="selectDeliveryServices()"><i class="fa fa-link"></i></button>
<button class="btn btn-default" title="Refresh" ng-click="refresh()"><i class="fa fa-refresh"></i></button>
</div>
<div class="clearfix"></div>
</div>
<div class="x_content">
<br>
<table id="federationDSTable" class="table responsive-utilities jambo_table">
<thead>
<tr class="headings">
<th>XML ID</th>
<th>Type</th>
<th>CDN</th>
<th></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="ds in ::deliveryServices">
<td>{{::ds.xmlId}}</td>
<td>{{::ds.type}}</td>
<td>{{::ds.cdn}}</td>
<td><button type="button" class="btn btn-link" title="Unlink Delivery Service from Federation" ng-click="confirmRemoveDS(ds)"><i class="fa fa-chain-broken"></i></button></td>
</tr>
</tbody>
</table>
</div>
</div>
| {
"content_hash": "94a877ebaa87ea690dde23948a7f3cac",
"timestamp": "",
"source": "github",
"line_count": 60,
"max_line_length": 190,
"avg_line_length": 41.35,
"alnum_prop": 0.5949214026602176,
"repo_name": "alficles/incubator-trafficcontrol",
"id": "107121386a87cf3e8273a8178abd5a6cf1b81e3a",
"size": "2481",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "traffic_portal/app/src/common/modules/table/cdnFederationDeliveryServices/table.cdnFederationDeliveryServices.tpl.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "21929"
},
{
"name": "CSS",
"bytes": "188991"
},
{
"name": "Go",
"bytes": "1451886"
},
{
"name": "HTML",
"bytes": "731049"
},
{
"name": "Java",
"bytes": "1233059"
},
{
"name": "JavaScript",
"bytes": "1612580"
},
{
"name": "Makefile",
"bytes": "1047"
},
{
"name": "PLSQL",
"bytes": "4308"
},
{
"name": "PLpgSQL",
"bytes": "70798"
},
{
"name": "Perl",
"bytes": "3491771"
},
{
"name": "Perl 6",
"bytes": "25530"
},
{
"name": "Python",
"bytes": "93425"
},
{
"name": "Roff",
"bytes": "4011"
},
{
"name": "Ruby",
"bytes": "4090"
},
{
"name": "SQLPL",
"bytes": "66645"
},
{
"name": "Shell",
"bytes": "166287"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en-us">
{% include head.html %}
<body>
{% include sidebar.html %}
<div class="content container">
{{ content }}
{% include comments.html %}
</div>
{% include analytics.html %}
</body>
</html>
| {
"content_hash": "21532810ec2c71703c8090dc701a0d73",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 35,
"avg_line_length": 14.444444444444445,
"alnum_prop": 0.5423076923076923,
"repo_name": "lkdjiin/xavier",
"id": "c556e365a3b79ca042634f35dd1c0ac7944096fd",
"size": "260",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/_layouts/default.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "14690"
},
{
"name": "HTML",
"bytes": "6286"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Juice.Mobile {
public enum MobileTransition {
None,
Slide,
SlideUp,
SlideDown,
SlideFade,
Pop,
Fade,
Flip,
Turn,
Flow
}
}
| {
"content_hash": "c1b563d1bca46737a0d9841ebbd2a235",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 33,
"avg_line_length": 12.736842105263158,
"alnum_prop": 0.6983471074380165,
"repo_name": "appendto/juiceui",
"id": "ad2ee1df5604a91acf8a92aa287bc0bfe4152a8f",
"size": "244",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Juice/Mobile/Enums/MobileTransition.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "70533"
},
{
"name": "C#",
"bytes": "346737"
},
{
"name": "JavaScript",
"bytes": "1678119"
}
],
"symlink_target": ""
} |
package org.apache.drill.exec.work.metadata;
import static org.apache.drill.exec.store.ischema.InfoSchemaConstants.CATS_COL_CATALOG_NAME;
import static org.apache.drill.exec.store.ischema.InfoSchemaConstants.COLS_COL_COLUMN_NAME;
import static org.apache.drill.exec.store.ischema.InfoSchemaConstants.SCHS_COL_SCHEMA_NAME;
import static org.apache.drill.exec.store.ischema.InfoSchemaConstants.SHRD_COL_TABLE_NAME;
import static org.apache.drill.exec.store.ischema.InfoSchemaConstants.SHRD_COL_TABLE_SCHEMA;
import static org.apache.drill.exec.store.ischema.InfoSchemaConstants.TBLS_COL_TABLE_TYPE;
import static org.apache.drill.exec.store.ischema.InfoSchemaTableType.CATALOGS;
import static org.apache.drill.exec.store.ischema.InfoSchemaTableType.COLUMNS;
import static org.apache.drill.exec.store.ischema.InfoSchemaTableType.SCHEMATA;
import static org.apache.drill.exec.store.ischema.InfoSchemaTableType.TABLES;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import org.apache.calcite.schema.SchemaPlus;
import org.apache.drill.common.FunctionNames;
import org.apache.drill.common.config.DrillConfig;
import org.apache.drill.common.exceptions.ErrorHelper;
import org.apache.drill.exec.ops.ViewExpansionContext;
import org.apache.drill.exec.proto.UserBitShared.DrillPBError;
import org.apache.drill.exec.proto.UserBitShared.DrillPBError.ErrorType;
import org.apache.drill.exec.proto.UserBitShared.UserCredentials;
import org.apache.drill.exec.proto.UserProtos.CatalogMetadata;
import org.apache.drill.exec.proto.UserProtos.ColumnMetadata;
import org.apache.drill.exec.proto.UserProtos.GetCatalogsReq;
import org.apache.drill.exec.proto.UserProtos.GetCatalogsResp;
import org.apache.drill.exec.proto.UserProtos.GetColumnsReq;
import org.apache.drill.exec.proto.UserProtos.GetColumnsResp;
import org.apache.drill.exec.proto.UserProtos.GetSchemasReq;
import org.apache.drill.exec.proto.UserProtos.GetSchemasResp;
import org.apache.drill.exec.proto.UserProtos.GetTablesReq;
import org.apache.drill.exec.proto.UserProtos.GetTablesResp;
import org.apache.drill.exec.proto.UserProtos.LikeFilter;
import org.apache.drill.exec.proto.UserProtos.RequestStatus;
import org.apache.drill.exec.proto.UserProtos.RpcType;
import org.apache.drill.exec.proto.UserProtos.SchemaMetadata;
import org.apache.drill.exec.proto.UserProtos.TableMetadata;
import org.apache.drill.exec.rpc.Response;
import org.apache.drill.exec.rpc.ResponseSender;
import org.apache.drill.exec.rpc.user.UserSession;
import org.apache.drill.exec.server.DrillbitContext;
import org.apache.drill.exec.server.options.OptionValue;
import org.apache.drill.exec.store.SchemaConfig.SchemaConfigInfoProvider;
import org.apache.drill.exec.store.SchemaTreeProvider;
import org.apache.drill.exec.store.ischema.InfoSchemaFilter;
import org.apache.drill.exec.store.ischema.InfoSchemaFilter.ConstantExprNode;
import org.apache.drill.exec.store.ischema.InfoSchemaFilter.ExprNode;
import org.apache.drill.exec.store.ischema.InfoSchemaFilter.FieldExprNode;
import org.apache.drill.exec.store.ischema.InfoSchemaFilter.FunctionExprNode;
import org.apache.drill.exec.store.ischema.InfoSchemaTableType;
import org.apache.drill.exec.store.ischema.Records.Catalog;
import org.apache.drill.exec.store.ischema.Records.Column;
import org.apache.drill.exec.store.ischema.Records.Schema;
import org.apache.drill.exec.store.ischema.Records.Table;
import org.apache.drill.exec.store.pojo.PojoRecordReader;
import org.apache.drill.metastore.MetastoreRegistry;
import org.apache.drill.shaded.guava.com.google.common.base.Preconditions;
import org.apache.drill.shaded.guava.com.google.common.collect.ComparisonChain;
import org.apache.drill.shaded.guava.com.google.common.collect.ImmutableList;
import org.apache.drill.shaded.guava.com.google.common.collect.Ordering;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Contains worker {@link Runnable} classes for providing the metadata and related helper methods.
*/
public class MetadataProvider {
private static final Logger logger = LoggerFactory.getLogger(MetadataProvider.class);
private static final String IN_FUNCTION = "in";
// Is this intended? Function name here is lower case of actual name?
private static final String AND_FUNCTION = FunctionNames.AND.toLowerCase();
private static final String OR_FUNCTION = FunctionNames.OR.toLowerCase();
/**
* @return Runnable that fetches the catalog metadata for given {@link GetCatalogsReq} and sends response at the end.
*/
public static Runnable catalogs(final UserSession session, final DrillbitContext dContext,
final GetCatalogsReq req, final ResponseSender responseSender) {
return new CatalogsProvider(session, dContext, req, responseSender);
}
/**
* @return Runnable that fetches the schema metadata for given {@link GetSchemasReq} and sends response at the end.
*/
public static Runnable schemas(final UserSession session, final DrillbitContext dContext,
final GetSchemasReq req, final ResponseSender responseSender) {
return new SchemasProvider(session, dContext, req, responseSender);
}
/**
* @return Runnable that fetches the table metadata for given {@link GetTablesReq} and sends response at the end.
*/
public static Runnable tables(final UserSession session, final DrillbitContext dContext,
final GetTablesReq req, final ResponseSender responseSender) {
return new TablesProvider(session, dContext, req, responseSender);
}
/**
* @return Runnable that fetches the column metadata for given {@link GetColumnsReq} and sends response at the end.
*/
public static Runnable columns(final UserSession session, final DrillbitContext dContext,
final GetColumnsReq req, final ResponseSender responseSender) {
return new ColumnsProvider(session, dContext, req, responseSender);
}
/**
* Super class for all metadata provider runnable classes.
*/
private abstract static class MetadataRunnable implements Runnable {
protected final UserSession session;
private final ResponseSender responseSender;
private final DrillbitContext dContext;
private MetadataRunnable(final UserSession session, final DrillbitContext dContext,
final ResponseSender responseSender) {
this.session = Preconditions.checkNotNull(session);
this.dContext = Preconditions.checkNotNull(dContext);
this.responseSender = Preconditions.checkNotNull(responseSender);
}
@Override
public void run() {
try(SchemaTreeProvider schemaTreeProvider = new SchemaTreeProvider(dContext)) {
responseSender.send(runInternal(session, schemaTreeProvider));
} catch (final Throwable error) {
logger.error("Unhandled metadata provider error", error);
}
}
/**
* @return A {@link Response} message. Response must be returned in any case.
*/
protected abstract Response runInternal(UserSession session, SchemaTreeProvider schemaProvider);
public DrillConfig getConfig() {
return dContext.getConfig();
}
public MetastoreRegistry getMetastoreRegistry() {
return dContext.getMetastoreRegistry();
}
}
/**
* Runnable that fetches the catalog metadata for given {@link GetCatalogsReq} and sends response at the end.
*/
private static class CatalogsProvider extends MetadataRunnable {
private static final Ordering<CatalogMetadata> CATALOGS_ORDERING = new Ordering<CatalogMetadata>() {
@Override
public int compare(CatalogMetadata left, CatalogMetadata right) {
return Ordering.natural().compare(left.getCatalogName(), right.getCatalogName());
}
};
private final GetCatalogsReq req;
public CatalogsProvider(final UserSession session, final DrillbitContext dContext,
final GetCatalogsReq req, final ResponseSender responseSender) {
super(session, dContext, responseSender);
this.req = Preconditions.checkNotNull(req);
}
@Override
protected Response runInternal(final UserSession session, final SchemaTreeProvider schemaProvider) {
final GetCatalogsResp.Builder respBuilder = GetCatalogsResp.newBuilder();
final InfoSchemaFilter filter = createInfoSchemaFilter(
req.hasCatalogNameFilter() ? req.getCatalogNameFilter() : null, null, null, null, null);
try {
final PojoRecordReader<Catalog> records =
getPojoRecordReader(CATALOGS, filter, getConfig(), schemaProvider, session, getMetastoreRegistry());
List<CatalogMetadata> metadata = new ArrayList<>();
for(Catalog c : records) {
final CatalogMetadata.Builder catBuilder = CatalogMetadata.newBuilder();
catBuilder.setCatalogName(c.CATALOG_NAME);
catBuilder.setDescription(c.CATALOG_DESCRIPTION);
catBuilder.setConnect(c.CATALOG_CONNECT);
metadata.add(catBuilder.build());
}
// Reorder results according to JDBC spec
Collections.sort(metadata, CATALOGS_ORDERING);
respBuilder.addAllCatalogs(metadata);
respBuilder.setStatus(RequestStatus.OK);
} catch (Throwable e) {
respBuilder.setStatus(RequestStatus.FAILED);
respBuilder.setError(createPBError("get catalogs", e));
} finally {
return new Response(RpcType.CATALOGS, respBuilder.build());
}
}
}
private static class SchemasProvider extends MetadataRunnable {
private static final Ordering<SchemaMetadata> SCHEMAS_ORDERING = new Ordering<SchemaMetadata>() {
@Override
public int compare(SchemaMetadata left, SchemaMetadata right) {
return ComparisonChain.start()
.compare(left.getCatalogName(), right.getCatalogName())
.compare(left.getSchemaName(), right.getSchemaName())
.result();
};
};
private final GetSchemasReq req;
private SchemasProvider(final UserSession session, final DrillbitContext dContext,
final GetSchemasReq req, final ResponseSender responseSender) {
super(session, dContext, responseSender);
this.req = Preconditions.checkNotNull(req);
}
@Override
protected Response runInternal(final UserSession session, final SchemaTreeProvider schemaProvider) {
final GetSchemasResp.Builder respBuilder = GetSchemasResp.newBuilder();
final InfoSchemaFilter filter = createInfoSchemaFilter(
req.hasCatalogNameFilter() ? req.getCatalogNameFilter() : null,
req.hasSchemaNameFilter() ? req.getSchemaNameFilter() : null,
null, null, null);
try {
final PojoRecordReader<Schema> records =
getPojoRecordReader(SCHEMATA, filter, getConfig(), schemaProvider, session, getMetastoreRegistry());
List<SchemaMetadata> metadata = new ArrayList<>();
for(Schema s : records) {
final SchemaMetadata.Builder schemaBuilder = SchemaMetadata.newBuilder();
schemaBuilder.setCatalogName(s.CATALOG_NAME);
schemaBuilder.setSchemaName(s.SCHEMA_NAME);
schemaBuilder.setOwner(s.SCHEMA_OWNER);
schemaBuilder.setType(s.TYPE);
schemaBuilder.setMutable(s.IS_MUTABLE);
metadata.add(schemaBuilder.build());
}
// Reorder results according to JDBC spec
Collections.sort(metadata, SCHEMAS_ORDERING);
respBuilder.addAllSchemas(metadata);
respBuilder.setStatus(RequestStatus.OK);
} catch (Throwable e) {
respBuilder.setStatus(RequestStatus.FAILED);
respBuilder.setError(createPBError("get schemas", e));
} finally {
return new Response(RpcType.SCHEMAS, respBuilder.build());
}
}
}
private static class TablesProvider extends MetadataRunnable {
private static final Ordering<TableMetadata> TABLES_ORDERING = new Ordering<TableMetadata>() {
@Override
public int compare(TableMetadata left, TableMetadata right) {
return ComparisonChain.start()
.compare(left.getType(), right.getType())
.compare(left.getCatalogName(), right.getCatalogName())
.compare(left.getSchemaName(), right.getSchemaName())
.compare(left.getTableName(), right.getTableName())
.result();
}
};
private final GetTablesReq req;
private TablesProvider(final UserSession session, final DrillbitContext dContext,
final GetTablesReq req, final ResponseSender responseSender) {
super(session, dContext, responseSender);
this.req = Preconditions.checkNotNull(req);
}
@Override
protected Response runInternal(final UserSession session, final SchemaTreeProvider schemaProvider) {
final GetTablesResp.Builder respBuilder = GetTablesResp.newBuilder();
final InfoSchemaFilter filter = createInfoSchemaFilter(
req.hasCatalogNameFilter() ? req.getCatalogNameFilter() : null,
req.hasSchemaNameFilter() ? req.getSchemaNameFilter() : null,
req.hasTableNameFilter() ? req.getTableNameFilter() : null,
req.getTableTypeFilterCount() != 0 ? req.getTableTypeFilterList() : null,
null);
try {
final PojoRecordReader<Table> records =
getPojoRecordReader(TABLES, filter, getConfig(), schemaProvider, session, getMetastoreRegistry());
List<TableMetadata> metadata = new ArrayList<>();
for(Table t : records) {
final TableMetadata.Builder tableBuilder = TableMetadata.newBuilder();
tableBuilder.setCatalogName(t.TABLE_CATALOG);
tableBuilder.setSchemaName(t.TABLE_SCHEMA);
tableBuilder.setTableName(t.TABLE_NAME);
tableBuilder.setType(t.TABLE_TYPE);
metadata.add(tableBuilder.build());
}
// Reorder results according to JDBC/ODBC spec
Collections.sort(metadata, TABLES_ORDERING);
respBuilder.addAllTables(metadata);
respBuilder.setStatus(RequestStatus.OK);
} catch (Throwable e) {
respBuilder.setStatus(RequestStatus.FAILED);
respBuilder.setError(createPBError("get tables", e));
} finally {
return new Response(RpcType.TABLES, respBuilder.build());
}
}
}
private static class ColumnsProvider extends MetadataRunnable {
private static final Ordering<ColumnMetadata> COLUMNS_ORDERING = new Ordering<ColumnMetadata>() {
@Override
public int compare(ColumnMetadata left, ColumnMetadata right) {
return ComparisonChain.start()
.compare(left.getCatalogName(), right.getCatalogName())
.compare(left.getSchemaName(), right.getSchemaName())
.compare(left.getTableName(), right.getTableName())
.compare(left.getOrdinalPosition(), right.getOrdinalPosition())
.result();
}
};
private final GetColumnsReq req;
private ColumnsProvider(final UserSession session, final DrillbitContext dContext,
final GetColumnsReq req, final ResponseSender responseSender) {
super(session, dContext, responseSender);
this.req = Preconditions.checkNotNull(req);
}
@Override
protected Response runInternal(final UserSession session, final SchemaTreeProvider schemaProvider) {
final GetColumnsResp.Builder respBuilder = GetColumnsResp.newBuilder();
final InfoSchemaFilter filter = createInfoSchemaFilter(
req.hasCatalogNameFilter() ? req.getCatalogNameFilter() : null,
req.hasSchemaNameFilter() ? req.getSchemaNameFilter() : null,
req.hasTableNameFilter() ? req.getTableNameFilter() : null,
null, req.hasColumnNameFilter() ? req.getColumnNameFilter() : null
);
try {
final PojoRecordReader<Column> records =
getPojoRecordReader(COLUMNS, filter, getConfig(), schemaProvider, session, getMetastoreRegistry());
List<ColumnMetadata> metadata = new ArrayList<>();
for(Column c : records) {
final ColumnMetadata.Builder columnBuilder = ColumnMetadata.newBuilder();
columnBuilder.setCatalogName(c.TABLE_CATALOG);
columnBuilder.setSchemaName(c.TABLE_SCHEMA);
columnBuilder.setTableName(c.TABLE_NAME);
columnBuilder.setColumnName(c.COLUMN_NAME);
columnBuilder.setOrdinalPosition(c.ORDINAL_POSITION);
if (c.COLUMN_DEFAULT != null) {
columnBuilder.setDefaultValue(c.COLUMN_DEFAULT);
}
if ("YES".equalsIgnoreCase(c.IS_NULLABLE)) {
columnBuilder.setIsNullable(true);
} else {
columnBuilder.setIsNullable(false);
}
columnBuilder.setDataType(c.DATA_TYPE);
if (c.CHARACTER_MAXIMUM_LENGTH != null) {
columnBuilder.setCharMaxLength(c.CHARACTER_MAXIMUM_LENGTH);
}
if (c.CHARACTER_OCTET_LENGTH != null) {
columnBuilder.setCharOctetLength(c.CHARACTER_OCTET_LENGTH);
}
if (c.NUMERIC_SCALE != null) {
columnBuilder.setNumericScale(c.NUMERIC_SCALE);
}
if (c.NUMERIC_PRECISION != null) {
columnBuilder.setNumericPrecision(c.NUMERIC_PRECISION);
}
if (c.NUMERIC_PRECISION_RADIX != null) {
columnBuilder.setNumericPrecisionRadix(c.NUMERIC_PRECISION_RADIX);
}
if (c.DATETIME_PRECISION != null) {
columnBuilder.setDateTimePrecision(c.DATETIME_PRECISION);
}
if (c.INTERVAL_TYPE != null) {
columnBuilder.setIntervalType(c.INTERVAL_TYPE);
}
if (c.INTERVAL_PRECISION != null) {
columnBuilder.setIntervalPrecision(c.INTERVAL_PRECISION);
}
if (c.COLUMN_SIZE != null) {
columnBuilder.setColumnSize(c.COLUMN_SIZE);
}
metadata.add(columnBuilder.build());
}
// Reorder results according to JDBC/ODBC spec
Collections.sort(metadata, COLUMNS_ORDERING);
respBuilder.addAllColumns(metadata);
respBuilder.setStatus(RequestStatus.OK);
} catch (Throwable e) {
respBuilder.setStatus(RequestStatus.FAILED);
respBuilder.setError(createPBError("get columns", e));
} finally {
return new Response(RpcType.COLUMNS, respBuilder.build());
}
}
}
/**
* Helper method to create a {@link InfoSchemaFilter} that combines the given filters with an AND.
*
* @param catalogNameFilter Optional filter on <code>catalog name</code>
* @param schemaNameFilter Optional filter on <code>schema name</code>
* @param tableNameFilter Optional filter on <code>table name</code>
* @param tableTypeFilter Optional filter on <code>table type</code>
* @param columnNameFilter Optional filter on <code>column name</code>
* @return information schema filter
*/
private static InfoSchemaFilter createInfoSchemaFilter(LikeFilter catalogNameFilter,
LikeFilter schemaNameFilter,
LikeFilter tableNameFilter,
List<String> tableTypeFilter,
LikeFilter columnNameFilter) {
FunctionExprNode exprNode = createLikeFunctionExprNode(CATS_COL_CATALOG_NAME, catalogNameFilter);
// schema names are case insensitive in Drill and stored in lower case
// convert like filter condition elements to lower case
if (schemaNameFilter != null) {
LikeFilter.Builder builder = LikeFilter.newBuilder();
if (schemaNameFilter.hasPattern()) {
builder.setPattern(schemaNameFilter.getPattern().toLowerCase());
}
if (schemaNameFilter.hasEscape()) {
builder.setEscape(schemaNameFilter.getEscape().toLowerCase());
}
schemaNameFilter = builder.build();
}
exprNode = combineFunctions(AND_FUNCTION,
exprNode,
combineFunctions(OR_FUNCTION,
createLikeFunctionExprNode(SHRD_COL_TABLE_SCHEMA, schemaNameFilter),
createLikeFunctionExprNode(SCHS_COL_SCHEMA_NAME, schemaNameFilter)
)
);
exprNode = combineFunctions(AND_FUNCTION,
exprNode,
createLikeFunctionExprNode(SHRD_COL_TABLE_NAME, tableNameFilter)
);
exprNode = combineFunctions(AND_FUNCTION,
exprNode,
createInFunctionExprNode(TBLS_COL_TABLE_TYPE, tableTypeFilter)
);
exprNode = combineFunctions(AND_FUNCTION,
exprNode,
createLikeFunctionExprNode(COLS_COL_COLUMN_NAME, columnNameFilter)
);
return exprNode != null ? new InfoSchemaFilter(exprNode) : null;
}
/**
* Helper method to create {@link FunctionExprNode} from {@link LikeFilter}.
* @param fieldName Name of the filed on which the like expression is applied.
* @param likeFilter
* @return {@link FunctionExprNode} for given arguments. Null if the <code>likeFilter</code> is null.
*/
private static FunctionExprNode createLikeFunctionExprNode(String fieldName, LikeFilter likeFilter) {
if (likeFilter == null) {
return null;
}
return new FunctionExprNode(FunctionNames.LIKE,
likeFilter.hasEscape() ?
ImmutableList.of(
new FieldExprNode(fieldName),
new ConstantExprNode(likeFilter.getPattern()),
new ConstantExprNode(likeFilter.getEscape())) :
ImmutableList.of(
new FieldExprNode(fieldName),
new ConstantExprNode(likeFilter.getPattern()))
);
}
/**
* Helper method to create {@link FunctionExprNode} from {@code List<String>}.
* @param fieldName Name of the filed on which the like expression is applied.
* @param valuesFilter a list of values
* @return {@link FunctionExprNode} for given arguments. Null if the <code>valuesFilter</code> is null.
*/
private static FunctionExprNode createInFunctionExprNode(String fieldName, List<String> valuesFilter) {
if (valuesFilter == null) {
return null;
}
ImmutableList.Builder<ExprNode> nodes = ImmutableList.builder();
nodes.add(new FieldExprNode(fieldName));
for(String type: valuesFilter) {
nodes.add(new ConstantExprNode(type));
}
return new FunctionExprNode(IN_FUNCTION, nodes.build());
}
/**
* Helper method to combine two {@link FunctionExprNode}s with a given <code>functionName</code>. If one of them is
* null, other one is returned as it is.
*/
private static FunctionExprNode combineFunctions(final String functionName,
final FunctionExprNode func1, final FunctionExprNode func2) {
if (func1 == null) {
return func2;
}
if (func2 == null) {
return func1;
}
return new FunctionExprNode(functionName, ImmutableList.<ExprNode>of(func1, func2));
}
/**
* Helper method to create a {@link PojoRecordReader} for given arguments.
* @param tableType
* @param filter
* @param provider
* @param userSession
* @return
*/
private static <S> PojoRecordReader<S> getPojoRecordReader(final InfoSchemaTableType tableType, final InfoSchemaFilter filter, final DrillConfig config,
final SchemaTreeProvider provider, final UserSession userSession, final MetastoreRegistry metastoreRegistry) {
final SchemaPlus rootSchema =
provider.createRootSchema(userSession.getCredentials().getUserName(), newSchemaConfigInfoProvider(config, userSession, provider));
return tableType.getRecordReader(rootSchema, filter, userSession.getOptions(), metastoreRegistry);
}
/**
* Helper method to create a {@link SchemaConfigInfoProvider} instance for metadata purposes.
* @param session
* @param schemaTreeProvider
* @return
*/
private static SchemaConfigInfoProvider newSchemaConfigInfoProvider(final DrillConfig config, final UserSession session, final SchemaTreeProvider schemaTreeProvider) {
return new SchemaConfigInfoProvider() {
private final ViewExpansionContext viewExpansionContext = new ViewExpansionContext(config, this);
@Override
public ViewExpansionContext getViewExpansionContext() {
return viewExpansionContext;
}
@Override
public SchemaPlus getRootSchema(String userName) {
return schemaTreeProvider.createRootSchema(userName, this);
}
@Override
public OptionValue getOption(String optionKey) {
return session.getOptions().getOption(optionKey);
}
@Override
public String getQueryUserName() {
return session.getCredentials().getUserName();
}
@Override public UserCredentials getQueryUserCredentials() {
return session.getCredentials();
}
};
}
/**
* Helper method to create {@link DrillPBError} for client response message.
* @param failedFunction Brief description of the failed function.
* @param ex Exception thrown
* @return
*/
static DrillPBError createPBError(final String failedFunction, final Throwable ex) {
final String errorId = UUID.randomUUID().toString();
logger.error("Failed to {}. ErrorId: {}", failedFunction, errorId, ex);
final DrillPBError.Builder builder = DrillPBError.newBuilder();
builder.setErrorType(ErrorType.SYSTEM); // Metadata requests shouldn't cause any user errors
builder.setErrorId(errorId);
if (ex.getMessage() != null) {
builder.setMessage(ex.getMessage());
}
builder.setException(ErrorHelper.getWrapper(ex));
return builder.build();
}
}
| {
"content_hash": "fc70ff7f6eed428ca520a9b05c34f0fc",
"timestamp": "",
"source": "github",
"line_count": 618,
"max_line_length": 169,
"avg_line_length": 41.34789644012945,
"alnum_prop": 0.7099362110124056,
"repo_name": "apache/drill",
"id": "2d2dd9058961e356f635260fe18082907a493f66",
"size": "26354",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "exec/java-exec/src/main/java/org/apache/drill/exec/work/metadata/MetadataProvider.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "22729"
},
{
"name": "Batchfile",
"bytes": "7541"
},
{
"name": "C",
"bytes": "31425"
},
{
"name": "C++",
"bytes": "595697"
},
{
"name": "CMake",
"bytes": "25162"
},
{
"name": "CSS",
"bytes": "2057"
},
{
"name": "Dockerfile",
"bytes": "9523"
},
{
"name": "FreeMarker",
"bytes": "209313"
},
{
"name": "HCL",
"bytes": "842"
},
{
"name": "HTML",
"bytes": "1398"
},
{
"name": "Java",
"bytes": "34664876"
},
{
"name": "JavaScript",
"bytes": "83256"
},
{
"name": "Shell",
"bytes": "122072"
}
],
"symlink_target": ""
} |
"""firstproject URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url, include
from django.contrib import admin
from django.contrib.auth import views
from firstapp.forms import LoginForm
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'',include('firstapp.urls')),
url(r'login/$', views.login, {
'template_name':'login.html',
'authentication_form':LoginForm
}, name="login"),
url(r'logout/$', views.logout,{
'next_page':'/login'
}),
]
| {
"content_hash": "479c8afc1b1a5106eebe7d31f155dc2b",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 79,
"avg_line_length": 34.40625,
"alnum_prop": 0.6757493188010899,
"repo_name": "CSUChico-CINS465/CINS465-Spring2017-Lecture-Examples",
"id": "3737ea3f51ffd2ffd390aef95ace7d64032fc97e",
"size": "1101",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "firstDjango/firstproject/firstproject/urls.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Dockerfile",
"bytes": "1176"
},
{
"name": "HTML",
"bytes": "75319"
},
{
"name": "JavaScript",
"bytes": "15083"
},
{
"name": "Python",
"bytes": "21984"
},
{
"name": "Shell",
"bytes": "3282"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>disel: Not compatible 👼</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.13.1 / disel - 2.2</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
disel
<small>
2.2
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-10-04 03:59:34 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-10-04 03:59:34 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-threads base
base-unix base
conf-findutils 1 Virtual package relying on findutils
conf-gmp 4 Virtual package relying on a GMP lib system installation
coq 8.13.1 Formal proof management system
num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.13.1 The OCaml compiler (virtual package)
ocaml-base-compiler 4.13.1 Official release 4.13.1
ocaml-config 2 OCaml Switch Configuration
ocaml-options-vanilla 1 Ensure that OCaml is compiled with no special options enabled
ocamlfind 1.9.5 A library manager for OCaml
zarith 1.12 Implements arithmetic and logical operations over arbitrary-precision integers
# opam file:
opam-version: "2.0"
maintainer: "palmskog@gmail.com"
homepage: "https://github.com/DistributedComponents/disel"
dev-repo: "git+https://github.com/DistributedComponents/disel.git"
bug-reports: "https://github.com/DistributedComponents/disel/issues"
license: "BSD-2-Clause"
synopsis: "Core framework files for Disel, a separation-style logic for compositional verification of distributed systems in Coq"
description: """
Disel is a framework for implementation and compositional verification of
distributed systems and their clients in Coq. In Disel, users implement
distributed systems using a domain specific language shallowly embedded in Coq
which provides both high-level programming constructs as well as low-level
communication primitives. Components of composite systems are specified in Disel
as protocols, which capture system-specific logic and disentangle system definitions
from implementation details.
"""
build: [make "-j%{jobs}%" "-C" "Core"]
install: [make "-C" "Core" "install"]
depends: [
"ocaml"
"coq" {>= "8.7" & < "8.13~"}
"coq-mathcomp-ssreflect" {>= "1.9.0" & < "1.12~"}
"coq-fcsl-pcm" {< "1.3.0"}
]
tags: [
"category:Computer Science/Concurrent Systems and Protocols/Theory of concurrent systems"
"keyword:program verification"
"keyword:separation logic"
"keyword:distributed algorithms"
"logpath:DiSeL"
"date:2020-07-26"
]
authors: [
"Ilya Sergey"
"James R. Wilcox"
]
url {
src: "https://github.com/DistributedComponents/disel/archive/v2.2.tar.gz"
checksum: "sha512=52ede64ded6f54ec60220095d5315a1862a4eae067cdeeb418c5902167b2b8387a8e0de076811493808a55988b1753c1cf1c1c33e146d1279461fe056d4817a7"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install 🏜️</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-disel.2.2 coq.8.13.1</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.13.1).
The following dependencies couldn't be met:
- coq-disel -> coq < 8.13~ -> ocaml < 4.12
base of this switch (use `--unlock-base' to force)
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-disel.2.2</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| {
"content_hash": "e0a41cd8504c73c461f5457107f31e70",
"timestamp": "",
"source": "github",
"line_count": 181,
"max_line_length": 159,
"avg_line_length": 43.35911602209945,
"alnum_prop": 0.5726299694189603,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "21328a5d4c827d040bdcf1d198890631b3309d58",
"size": "7873",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.13.1-2.0.10/released/8.13.1/disel/2.2.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
using System;
using Content.Shared.GameObjects.Components.Weapons.Ranged.Barrels;
using Content.Shared.GameObjects.EntitySystems;
using Robust.Server.GameObjects;
using Robust.Server.GameObjects.EntitySystems;
using Robust.Shared.GameObjects;
using Robust.Shared.GameObjects.EntitySystemMessages;
using Robust.Shared.GameObjects.Systems;
using Robust.Shared.Interfaces.GameObjects;
using Robust.Shared.Interfaces.Timing;
using Robust.Shared.IoC;
using Robust.Shared.Localization;
using Robust.Shared.Log;
using Robust.Shared.Map;
using Robust.Shared.Maths;
using Robust.Shared.Serialization;
using Robust.Shared.Utility;
namespace Content.Server.GameObjects.Components.Weapon.Ranged.Ammunition
{
/// <summary>
/// Allows this entity to be loaded into a ranged weapon (if the caliber matches)
/// Generally used for bullets but can be used for other things like bananas
/// </summary>
[RegisterComponent]
public class AmmoComponent : Component, IExamine
{
[Dependency] private readonly IGameTiming _gameTiming = default!;
public override string Name => "Ammo";
public BallisticCaliber Caliber => _caliber;
private BallisticCaliber _caliber;
public bool Spent
{
get
{
if (_ammoIsProjectile)
{
return false;
}
return _spent;
}
}
private bool _spent;
/// <summary>
/// Used for anything without a case that fires itself
/// </summary>
private bool _ammoIsProjectile;
/// <summary>
/// Used for something that is deleted when the projectile is retrieved
/// </summary>
public bool Caseless => _caseless;
private bool _caseless;
// Rather than managing bullet / case state seemed easier to just have 2 toggles
// ammoIsProjectile being for a beanbag for example and caseless being for ClRifle rounds
/// <summary>
/// For shotguns where they might shoot multiple entities
/// </summary>
public int ProjectilesFired => _projectilesFired;
private int _projectilesFired;
private string _projectileId;
// How far apart each entity is if multiple are shot
public float EvenSpreadAngle => _evenSpreadAngle;
private float _evenSpreadAngle;
/// <summary>
/// How fast the shot entities travel
/// </summary>
public float Velocity => _velocity;
private float _velocity;
private string _muzzleFlashSprite;
public string SoundCollectionEject => _soundCollectionEject;
private string _soundCollectionEject;
public override void ExposeData(ObjectSerializer serializer)
{
base.ExposeData(serializer);
// For shotty of whatever as well
serializer.DataField(ref _projectileId, "projectile", null);
serializer.DataField(ref _caliber, "caliber", BallisticCaliber.Unspecified);
serializer.DataField(ref _projectilesFired, "projectilesFired", 1);
// Used for shotty to determine overall pellet spread
serializer.DataField(ref _evenSpreadAngle, "ammoSpread", 0);
serializer.DataField(ref _velocity, "ammoVelocity", 20.0f);
serializer.DataField(ref _ammoIsProjectile, "isProjectile", false);
serializer.DataField(ref _caseless, "caseless", false);
// Being both caseless and shooting yourself doesn't make sense
DebugTools.Assert(!(_ammoIsProjectile && _caseless));
serializer.DataField(ref _muzzleFlashSprite, "muzzleFlash", "Objects/Weapons/Guns/Projectiles/bullet_muzzle.png");
serializer.DataField(ref _soundCollectionEject, "soundCollectionEject", "CasingEject");
if (_projectilesFired < 1)
{
Logger.Error("Ammo can't have less than 1 projectile");
}
if (_evenSpreadAngle > 0 && _projectilesFired == 1)
{
Logger.Error("Can't have an even spread if only 1 projectile is fired");
throw new InvalidOperationException();
}
}
public IEntity TakeBullet(EntityCoordinates spawnAt)
{
if (_ammoIsProjectile)
{
return Owner;
}
if (_spent)
{
return null;
}
_spent = true;
if (Owner.TryGetComponent(out AppearanceComponent appearanceComponent))
{
appearanceComponent.SetData(AmmoVisuals.Spent, true);
}
var entity = Owner.EntityManager.SpawnEntity(_projectileId, spawnAt);
DebugTools.AssertNotNull(entity);
return entity;
}
public void MuzzleFlash(IEntity entity, Angle angle)
{
if (_muzzleFlashSprite == null)
{
return;
}
var time = _gameTiming.CurTime;
var deathTime = time + TimeSpan.FromMilliseconds(200);
// Offset the sprite so it actually looks like it's coming from the gun
var offset = angle.ToVec().Normalized / 2;
var message = new EffectSystemMessage
{
EffectSprite = _muzzleFlashSprite,
Born = time,
DeathTime = deathTime,
AttachedEntityUid = entity.Uid,
AttachedOffset = offset,
//Rotated from east facing
Rotation = (float) angle.Theta,
Color = Vector4.Multiply(new Vector4(255, 255, 255, 255), 1.0f),
ColorDelta = new Vector4(0, 0, 0, -1500f),
Shaded = false
};
EntitySystem.Get<EffectSystem>().CreateParticle(message);
}
public void Examine(FormattedMessage message, bool inDetailsRange)
{
var text = Loc.GetString("It's [color=white]{0}[/color] ammo.", Caliber);
message.AddMarkup(text);
}
}
public enum BallisticCaliber
{
Unspecified = 0,
A357, // Placeholder?
ClRifle,
SRifle,
Pistol,
A35, // Placeholder?
LRifle,
Magnum,
AntiMaterial,
Shotgun,
Cap,
Rocket,
Dart, // Placeholder
Grenade,
Energy,
}
}
| {
"content_hash": "eada65249c4f4b906925c0fc4c4f2a34",
"timestamp": "",
"source": "github",
"line_count": 186,
"max_line_length": 126,
"avg_line_length": 34.94086021505376,
"alnum_prop": 0.5967071857208801,
"repo_name": "space-wizards/space-station-14-content",
"id": "2550aed3fca57e85c01d98a8158c2b1539c7206f",
"size": "6501",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Content.Server/GameObjects/Components/Weapon/Ranged/Ammunition/AmmoComponent.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "344"
},
{
"name": "C#",
"bytes": "582784"
},
{
"name": "Python",
"bytes": "13736"
},
{
"name": "Shell",
"bytes": "429"
}
],
"symlink_target": ""
} |
package cl.io.gateway;
import cl.io.gateway.plugin.IGatewayPluginBootstrap;
public class InternalPlugin extends InternalElement<IGatewayPluginBootstrap> {
private final String description;
private final Class<?> pluginType;
public InternalPlugin(String description, Class<?> pluginType, String contextId,
Class<IGatewayPluginBootstrap> serviceClass, String gatewayId) {
super(contextId, serviceClass, gatewayId);
this.description = description;
this.pluginType = pluginType;
}
public String getDescription() {
return description;
}
public Class<?> getPluginType() {
return pluginType;
}
}
| {
"content_hash": "36bb5ffdca0f88a3562fc1967a566abc",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 84,
"avg_line_length": 26.192307692307693,
"alnum_prop": 0.7048458149779736,
"repo_name": "egacl/gatewayio",
"id": "bc1010bc8c0fa5e2fa723099aa2716431696e83c",
"size": "1303",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "GatewayProjects/Gateway/src/main/java/cl/io/gateway/InternalPlugin.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "127"
},
{
"name": "Java",
"bytes": "328998"
}
],
"symlink_target": ""
} |
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
| {
"content_hash": "89b9675dc8ba00f94ac873d492c097c2",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 73,
"avg_line_length": 13.958333333333334,
"alnum_prop": 0.7104477611940299,
"repo_name": "Donsig/SSHAdmin",
"id": "ae0cd9c5765b5078ccf00c7b7a23b652f724270b",
"size": "520",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "SSHAdmin/ViewController.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "65965"
},
{
"name": "Objective-C",
"bytes": "70143"
}
],
"symlink_target": ""
} |
page '/*.xml', layout: false
page '/*.json', layout: false
page '/*.txt', layout: false
# With alternative layout
# page "/path/to/file.html", layout: :otherlayout
# Proxy pages (http://middlemanapp.com/basics/dynamic-pages/)
# proxy "/this-page-has-no-template.html", "/template-file.html", locals: {
# which_fake_page: "Rendering a fake page with a local variable" }
# General configuration
activate :relative_assets
set :relative_links, true
# Reload the browser automatically whenever files change
configure :development do
activate :livereload
end
###
# Helpers
###
# Methods defined in the helpers block are available in templates
# helpers do
# def some_helper
# "Helping"
# end
# end
# Build-specific configuration
configure :build do
# Skip clean node_modules
set :skip_build_clean do |path|
path =~ /\/node_modules\//
end
# Minify CSS on build
# activate :minify_css
# Minify Javascript on build
# activate :minify_javascript
end
after_configuration do
Opal.paths.each do |path|
sprockets.append_path path
end
end
after_build do |builder|
builder.thor.inside(config[:build_dir]) do |arg|
builder.thor.run 'npm install'
end
end
| {
"content_hash": "eee7764eb828caff513b14adf63a5d83",
"timestamp": "",
"source": "github",
"line_count": 56,
"max_line_length": 75,
"avg_line_length": 21.303571428571427,
"alnum_prop": 0.7099748533109808,
"repo_name": "raccy/electricman",
"id": "ef3b285d4ae74397c555f1ffafe10156097ff430",
"size": "1293",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "config.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1104"
},
{
"name": "CoffeeScript",
"bytes": "50"
},
{
"name": "HTML",
"bytes": "890"
},
{
"name": "Opal",
"bytes": "1393"
},
{
"name": "Ruby",
"bytes": "5950"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
Index Fungorum
#### Published in
null
#### Original name
Erinella subtilissima Pat.
### Remarks
null | {
"content_hash": "54d1f6a0b2865f0205766f62c47d4b1d",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 26,
"avg_line_length": 10.076923076923077,
"alnum_prop": 0.7099236641221374,
"repo_name": "mdoering/backbone",
"id": "79f0fbbc374d86178fe00b50150b5a4fbaab84bf",
"size": "181",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Fungi/Ascomycota/Leotiomycetes/Helotiales/Hyaloscyphaceae/Erinella/Erinella subtilissima/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
class FilePositionStop : public DataExtractor {
public:
FilePositionStop(DataExtractor *next, ConcreteTableColumn *prototype, TriggerCondition *condition, int levelUp);
protected:
virtual TableColumn* handleExtraction(AbstractTree &tree);
private:
int levelUp;
};
#endif //FILEPOSITIONSTOP_H | {
"content_hash": "6ce85cb3f794f9932947214dc3c681ba",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 116,
"avg_line_length": 19.4375,
"alnum_prop": 0.7717041800643086,
"repo_name": "petrufm/mcc",
"id": "628f2fb6bb17f1acd757dcc41c02a97398cb828c",
"size": "457",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "mcc/src/FilePositionStop.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "375"
},
{
"name": "C++",
"bytes": "366571"
}
],
"symlink_target": ""
} |
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^login/$', views.login23, name='login'),
url(r'^comeback/$', views.comeback, name='comeback'),
url(r'^profiles/$', views.profiles, name='profiles'),
url(r'^status/$', views.status, name='status'),
]
| {
"content_hash": "7b67872e4ce2a7d46feea60d0b0ca575",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 57,
"avg_line_length": 29.2,
"alnum_prop": 0.6438356164383562,
"repo_name": "jiivan/genoomy",
"id": "277e4a526afa2bfd1434c8224df8ca0d7f4db8a6",
"size": "338",
"binary": false,
"copies": "1",
"ref": "refs/heads/dev_deploy",
"path": "genoome/twentythree/urls.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "51082"
},
{
"name": "HTML",
"bytes": "47982"
},
{
"name": "JavaScript",
"bytes": "31061"
},
{
"name": "Python",
"bytes": "138292"
},
{
"name": "Shell",
"bytes": "5962"
}
],
"symlink_target": ""
} |
package org.apache.ode.store.hib;
import org.apache.ode.bpel.iapi.ProcessState;
import org.apache.ode.store.ProcessConfDAO;
import org.apache.ode.utils.stl.CollectionsX;
import org.apache.ode.utils.stl.UnaryFunction;
import javax.xml.namespace.QName;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
/**
* @author mriou <mriou at apache dot org>
* @hibernate.class table="STORE_PROCESS"
*/
public class ProcessConfDaoImpl extends HibObj implements ProcessConfDAO {
private DeploymentUnitDaoImpl _du;
private Map<String,String> _properties = new HashMap<String,String>();
/** Simple name of the process. */
private String _processId;
/** Process type. */
private String _type;
/** Process version. */
private long _version;
/** Process state.*/
private String _state;
/**
* @hibernate.many-to-one foreign-key="none"
* @hibernate.column name="DU"
*/
public DeploymentUnitDaoImpl getDeploymentUnit() {
return _du;
}
public void setDeploymentUnit(DeploymentUnitDaoImpl du) {
_du = du;
}
/**
* @hibernate.map table="STORE_PROCESS_PROP" role="properties_"
* @hibernate.collection-key column="propId" foreign-key="none"
* @hibernate.collection-index column="name" type="string"
* @hibernate.collection-element column="data" type="materialized_clob"
*/
public Map<String,String> getProperties_() {
return _properties;
}
public void setProperties_(Map<String,String> properties) {
_properties = properties;
}
/**
*
* @hibernate.id generator-class="assigned"
* @hibernate.column
* name="PID"
* not-null="true"
*/
public String getPID_() {
return _processId;
}
public void setPID_(String processId) {
_processId = processId;
}
/**
* The type of the process (BPEL process definition name).
* @hibernate.property
* column="TYPE"
*/
public String getType_() {
return _type;
}
public void setType_(String type) {
_type = type;
}
/**
* The process version.
* @hibernate.property
* column="version"
*/
public long getVersion() {
return _version;
}
public void setVersion(long version) {
_version = version;
}
/**
* The process state.
* @hibernate.property
* column="STATE"
*/
public String getState_() {
return _state;
}
public void setState_(String state) {
_state = state;
}
public QName getPID() {
return QName.valueOf(getPID_());
}
public void setPID(QName pid) {
setPID_(pid.toString());
}
public void setState(ProcessState state) {
setState_(state.toString());
}
public void setProperty(QName name, String content) {
_properties.put(name.toString(),content);
}
public void delete() {
super.delete();
}
public QName getType() {
return QName.valueOf(getType_());
}
public void setType(QName type) {
setType_(type.toString());
}
public ProcessState getState() {
return ProcessState.valueOf(getState_());
}
public String getProperty(QName name) {
return _properties.get(name.toString());
}
public Collection<QName> getPropertyNames() {
return CollectionsX.transform(new ArrayList<QName>(), _properties.keySet(),new UnaryFunction<String,QName>() {
public QName apply(String x) {
return QName.valueOf(x);
}
});
}
}
| {
"content_hash": "bf20b5313f14b029182dceaa9ace3c90",
"timestamp": "",
"source": "github",
"line_count": 167,
"max_line_length": 118,
"avg_line_length": 22.17365269461078,
"alnum_prop": 0.6065352416959222,
"repo_name": "apache/ode",
"id": "a44506167826c96c33a056446f3d38e56cdb475f",
"size": "4511",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "bpel-store/src/main/java/org/apache/ode/store/hib/ProcessConfDaoImpl.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "6359"
},
{
"name": "CSS",
"bytes": "35867"
},
{
"name": "Groovy",
"bytes": "4205"
},
{
"name": "HTML",
"bytes": "41741"
},
{
"name": "Java",
"bytes": "5649254"
},
{
"name": "JavaScript",
"bytes": "248611"
},
{
"name": "Ruby",
"bytes": "107187"
},
{
"name": "Shell",
"bytes": "11659"
},
{
"name": "TSQL",
"bytes": "10000"
},
{
"name": "XSLT",
"bytes": "6703"
}
],
"symlink_target": ""
} |
<?php
/*
Safe sample
input : use proc_open to read /tmp/tainted.txt
sanitize : use of ternary condition
construction : concatenation with simple quote
*/
/*Copyright 2015 Bertrand STIVALET
Permission is hereby granted, without written agreement or royalty fee, to
use, copy, modify, and distribute this software and its documentation for
any purpose, provided that the above copyright notice and the following
three paragraphs appear in all copies of this software.
IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT,
INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE
BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT
LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO
OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
MODIFICATIONS.*/
$descriptorspec = array(
0 => array("pipe", "r"),
1 => array("pipe", "w"),
2 => array("file", "/tmp/error-output.txt", "a")
);
$cwd = '/tmp';
$process = proc_open('more /tmp/tainted.txt', $descriptorspec, $pipes, $cwd, NULL);
if (is_resource($process)) {
fclose($pipes[0]);
$tainted = stream_get_contents($pipes[1]);
fclose($pipes[1]);
$return_value = proc_close($process);
}
$tainted = $tainted == 'safe1' ? 'safe1' : 'safe2';
$query = "SELECT * FROM COURSE c WHERE c.id IN (SELECT idcourse FROM REGISTRATION WHERE idstudent='". $tainted . "')";
$conn = mysql_connect('localhost', 'mysql_user', 'mysql_password'); // Connection to the database (address, user, password)
mysql_select_db('dbname') ;
echo "query : ". $query ."<br /><br />" ;
$res = mysql_query($query); //execution
while($data =mysql_fetch_array($res)){
print_r($data) ;
echo "<br />" ;
}
mysql_close($conn);
?> | {
"content_hash": "e1aee42c77e716b74516bd2e363b8c18",
"timestamp": "",
"source": "github",
"line_count": 75,
"max_line_length": 123,
"avg_line_length": 26.226666666666667,
"alnum_prop": 0.7112353838332486,
"repo_name": "stivalet/PHP-Vulnerability-test-suite",
"id": "1d039f225a159b81866d4987fd89b18c168bec01",
"size": "1967",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Injection/CWE_89/safe/CWE_89__proc_open__ternary_white_list__multiple_select-concatenation_simple_quote.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "64184004"
}
],
"symlink_target": ""
} |
import { Injectable, Inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { map } from 'rxjs/operators';
import { Category } from '../models';
@Injectable()
export class CategoryService {
private readonly module = 'categories';
constructor (@Inject('CONFIG') private config,
private http: HttpClient) {
}
index (request: { page_index: string, page_size: string, project_id: string }): Observable<Category[]> {
const uri = `${this.config.api}/${this.module}`;
return this.http.get<Category[]>(uri, { params: request }).pipe(
map(response => response)
);
}
}
| {
"content_hash": "f0776993a51954e4965913fcf6e3680d",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 106,
"avg_line_length": 29.869565217391305,
"alnum_prop": 0.6564774381368268,
"repo_name": "AidenChen/ApiHanger",
"id": "07aaaa2f87a6127c227f57c1302472e20c6430f4",
"size": "687",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/app/services/category.service.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "3888"
},
{
"name": "HTML",
"bytes": "11815"
},
{
"name": "JavaScript",
"bytes": "1645"
},
{
"name": "TypeScript",
"bytes": "39878"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "a1fd26fe16caae47a898f96a1c608e89",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "ec7a98aa82f46c394e9eea1e5937091276fcf55d",
"size": "176",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Gentianales/Apocynaceae/Cabucala/Cabucala humbertii/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<?php
namespace Kunstmaan\SeoBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Kunstmaan\AdminBundle\Entity\AbstractEntity;
use Kunstmaan\SeoBundle\Form\RobotsType;
/**
* Robots.txt data.
*
* @ORM\Entity
* @ORM\Table(name="kuma_robots")
*/
class Robots extends AbstractEntity
{
/**
* @var string
*
* @ORM\Column(name="robots_txt", type="text", nullable=true)
*/
protected $robotsTxt;
/**
* Return string representation of entity.
*
* @return string
*/
public function __toString()
{
return 'Robots';
}
/**
* @return string
*/
public function getRobotsTxt()
{
return $this->robotsTxt;
}
/**
* @param string $robotsTxt
*/
public function setRobotsTxt($robotsTxt)
{
$this->robotsTxt = $robotsTxt;
}
/**
* @return string
*/
public function getDefaultAdminType()
{
return RobotsType::class;
}
}
| {
"content_hash": "814acb4efed55fcae8e7ba077f42f85e",
"timestamp": "",
"source": "github",
"line_count": 57,
"max_line_length": 65,
"avg_line_length": 17.157894736842106,
"alnum_prop": 0.5777096114519428,
"repo_name": "hgabka/KunstmaanBundlesCMS",
"id": "8f27df3c2bb7b5a818b5b0297dd63cc48ec7dd4f",
"size": "978",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Kunstmaan/SeoBundle/Entity/Robots.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "46244"
},
{
"name": "CSS",
"bytes": "468600"
},
{
"name": "Gherkin",
"bytes": "22178"
},
{
"name": "HTML",
"bytes": "934141"
},
{
"name": "Hack",
"bytes": "20"
},
{
"name": "JavaScript",
"bytes": "4087160"
},
{
"name": "PHP",
"bytes": "2946789"
},
{
"name": "Ruby",
"bytes": "2363"
},
{
"name": "Shell",
"bytes": "235"
}
],
"symlink_target": ""
} |
package org.apache.sentry.provider.db.log.entity;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import org.apache.sentry.provider.db.log.util.Constants;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.node.ContainerNode;
import org.junit.Test;
public class TestDbAuditMetadataLogEntity {
@Test
public void testToJsonFormatLog() throws Throwable {
DBAuditMetadataLogEntity amle = new DBAuditMetadataLogEntity("serviceName", "userName",
"impersonator", "ipAddress", "operation", "eventTime", "operationText", "allowed",
"objectType", "component", "databaseName", "tableName", "columnName", "resourcePath");
String jsonAuditLog = amle.toJsonFormatLog();
ContainerNode rootNode = AuditMetadataLogEntity.parse(jsonAuditLog);
assertEntryEquals(rootNode, Constants.LOG_FIELD_SERVICE_NAME, "serviceName");
assertEntryEquals(rootNode, Constants.LOG_FIELD_USER_NAME, "userName");
assertEntryEquals(rootNode, Constants.LOG_FIELD_IMPERSONATOR,
"impersonator");
assertEntryEquals(rootNode, Constants.LOG_FIELD_IP_ADDRESS, "ipAddress");
assertEntryEquals(rootNode, Constants.LOG_FIELD_OPERATION, "operation");
assertEntryEquals(rootNode, Constants.LOG_FIELD_EVENT_TIME, "eventTime");
assertEntryEquals(rootNode, Constants.LOG_FIELD_OPERATION_TEXT,
"operationText");
assertEntryEquals(rootNode, Constants.LOG_FIELD_ALLOWED, "allowed");
assertEntryEquals(rootNode, Constants.LOG_FIELD_DATABASE_NAME,
"databaseName");
assertEntryEquals(rootNode, Constants.LOG_FIELD_TABLE_NAME, "tableName");
assertEntryEquals(rootNode, Constants.LOG_FIELD_COLUMN_NAME, "columnName");
assertEntryEquals(rootNode, Constants.LOG_FIELD_RESOURCE_PATH,
"resourcePath");
assertEntryEquals(rootNode, Constants.LOG_FIELD_OBJECT_TYPE, "objectType");
}
void assertEntryEquals(ContainerNode rootNode, String key, String value) {
JsonNode node = assertNodeContains(rootNode, key);
assertEquals(value, node.getTextValue());
}
private JsonNode assertNodeContains(ContainerNode rootNode, String key) {
JsonNode node = rootNode.get(key);
if (node == null) {
fail("No entry of name \"" + key + "\" found in " + rootNode.toString());
}
return node;
}
}
| {
"content_hash": "a01041398eec489509639062536cc767",
"timestamp": "",
"source": "github",
"line_count": 53,
"max_line_length": 94,
"avg_line_length": 43.75471698113208,
"alnum_prop": 0.7425614489003881,
"repo_name": "apache/incubator-sentry",
"id": "3d336af94111db806e2305f7a3deea3d8878bb36",
"size": "3125",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "sentry-provider/sentry-provider-db/src/test/java/org/apache/sentry/provider/db/log/entity/TestDbAuditMetadataLogEntity.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "4846"
},
{
"name": "HTML",
"bytes": "5005"
},
{
"name": "Java",
"bytes": "3922648"
},
{
"name": "JavaScript",
"bytes": "22225"
},
{
"name": "PLpgSQL",
"bytes": "410"
},
{
"name": "Python",
"bytes": "11367"
},
{
"name": "SQLPL",
"bytes": "30"
},
{
"name": "Shell",
"bytes": "27225"
},
{
"name": "Thrift",
"bytes": "27270"
},
{
"name": "XSLT",
"bytes": "25595"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "f4e4e41bbf773b07151d8cb6b8887589",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "5f2d14f975f57854909ad43171a0a97ca62880f0",
"size": "230",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Fabales/Fabaceae/Ramirezella/Ramirezella strobiliophora/Ramirezella strobiliophora pubescens/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
from tools.modified.androguard.core import androconf
from PySide import QtCore
from tools.modified.androguard.misc import *
import os.path
import traceback
class FileLoadingThread(QtCore.QThread):
def __init__(self, session, parent=None):
QtCore.QThread.__init__(self, parent)
self.session = session
self.file_path = None
self.incoming_file = ()
def load(self, file_path):
self.file_path = file_path
if file_path.endswith(".ag"):
self.incoming_file = (file_path, 'SESSION')
else:
file_type = androconf.is_android(file_path)
self.incoming_file = (file_path, file_type)
self.start(QtCore.QThread.LowestPriority)
def run(self):
if self.incoming_file:
try:
file_path, file_type = self.incoming_file
if file_type in ["APK", "DEX", "DEY"]:
ret = self.session.add(file_path,
open(file_path, 'r').read())
self.emit(QtCore.SIGNAL("loadedFile(bool)"), ret)
elif file_type == "SESSION" :
self.session.load(file_path)
self.emit(QtCore.SIGNAL("loadedFile(bool)"), True)
except Exception as e:
androconf.debug(e)
androconf.debug(traceback.format_exc())
self.emit(QtCore.SIGNAL("loadedFile(bool)"), False)
self.incoming_file = []
else:
self.emit(QtCore.SIGNAL("loadedFile(bool)"), False)
| {
"content_hash": "14b40cc27a095e4f267307ef8fb8aaec",
"timestamp": "",
"source": "github",
"line_count": 45,
"max_line_length": 71,
"avg_line_length": 35.022222222222226,
"alnum_prop": 0.5545685279187818,
"repo_name": "CreatorB/hackerdroid",
"id": "3d562765c557ef4ddfad7f9baaa859e28a9e1624",
"size": "1576",
"binary": false,
"copies": "7",
"ref": "refs/heads/master",
"path": "AndroBugs_Framework/tools/modified/androguard/gui/fileloading.py",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "27553317"
},
{
"name": "Shell",
"bytes": "546"
}
],
"symlink_target": ""
} |
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <getopt.h>
#include "globals.h"
#include "proc.h"
static const char* const kOptLongAppName = "app";
static const char* const kOptLongLibPath = "lib";
static const char* const kOptLongModulePath = "module";
static const char* const kOptLongClassName = "class";
static const char kOptAppName = 'a';
static const char kOptLibPath = 'l';
static const char kOptModulePath = 'm';
static const char kOptClassName = 'c';
void PrintUsage()
{
const char *usage = \
"Usage: ./launcher\n"
" --app [-a] APPNAME (The package name (or keyword) of the target app)\n"
" --lib [-l] LIBPATH (The absolute path name of ProbeDroid core library)\n"
" --module [-m] MODULEPATH (The absolute path name of your instrumentation package)\n"
" --class [-c] CLASSNAME (The fullly qualified main class name of your instrumentation package)\n"
"\n"
"Example:\n"
"./launcher"
" --app com.google.android.app.maps"
" --lib /data/local/tmp/libprobedroid.so"
" --module /data/local/tmp/Instument.apk"
" --class org.zsshen.instument.Main\n"
"\n"
"./launcher"
" -a com.google.android.app.maps"
" -l /data/local/tmp/libprobedroid.so"
" -m /data/local/tmp/Instument.apk"
" -c org.zsshen.instument.Main\n";
std::cerr << usage;
}
int main(int32_t argc, char** argv)
{
// Acquire the command line arguments.
struct option opts[] = {
{kOptLongAppName, required_argument, 0, kOptAppName},
{kOptLongLibPath, required_argument, 0, kOptLibPath},
{kOptLongModulePath, required_argument, 0, kOptModulePath},
{kOptLongClassName, required_argument, 0, kOptClassName},
};
char sz_order[kBlahSizeTiny];
memset(sz_order, 0, sizeof(char) * kBlahSizeTiny);
sprintf(sz_order, "%c:%c:%c:%c:", kOptAppName, kOptLibPath,
kOptModulePath, kOptClassName);
int opt, idx_opt;
char *app_name = nullptr, *lib_path = nullptr, *module_path = nullptr,
*class_name = nullptr;
while ((opt = getopt_long(argc, argv, sz_order, opts, &idx_opt)) != -1) {
switch (opt) {
case kOptAppName:
app_name = optarg;
break;
case kOptLibPath:
lib_path = optarg;
break;
case kOptModulePath:
module_path = optarg;
break;
case kOptClassName:
class_name = optarg;
break;
default:
PrintUsage();
return EXIT_FAILURE;
}
}
if (!app_name || !lib_path || !module_path || !class_name) {
PrintUsage();
return EXIT_FAILURE;
}
// Start to launcher the designated shared object.
proc::EggHunter hunter;
hunter.Hunt(app_name, lib_path, module_path, class_name);
return EXIT_SUCCESS;
} | {
"content_hash": "de909cd1aa9a7b30f2736b6f1c3a5864",
"timestamp": "",
"source": "github",
"line_count": 96,
"max_line_length": 109,
"avg_line_length": 31.302083333333332,
"alnum_prop": 0.5870216306156406,
"repo_name": "ZSShen/ProbeDroid",
"id": "35ad205f00ab7dec76cc90feb0e2342e4390d1e3",
"size": "4206",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "launcher/jni/launcher.cc",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "25743"
},
{
"name": "C",
"bytes": "79718"
},
{
"name": "C++",
"bytes": "185350"
},
{
"name": "Java",
"bytes": "42386"
},
{
"name": "Makefile",
"bytes": "2751"
},
{
"name": "Python",
"bytes": "4602"
}
],
"symlink_target": ""
} |
layout: page
title: PL Theory Readings
permalink: /pl-readings/
---
* [Programming Bottom-Up](http://www.paulgraham.com/progbot.html) [1993] by Paul Graham
* [The Why of Y](https://www.dreamsongs.com/Files/WhyOfY.pdf) [2001] by Richard P. Gabriel
* [Destroy All Ifs](http://degoes.net/articles/destroy-all-ifs) [2016] by John A. De Goes
* [Lisp: It's Not About Macros, It's About Read](http://jlongster.com/Lisp--It-s-Not-About-Macros,-It-s-About-Read) [2012] by James Long
* [A Coming Revolution in Metaprogramming](http://notes.willcrichton.net/the-coming-age-of-the-polyglot-programmer/) [2016] by Will Crichton
* [Rust: The New LLVM](http://notes.willcrichton.net/rust-the-new-llvm/) [2016] by Will Crichton
* [On the Cruelty of Really Teaching Computing Science](https://www.cs.utexas.edu/users/EWD/transcriptions/EWD10xx/EWD1036.html) [1988] by Edsger W. Dijkstra
* [Types](https://gist.github.com/garybernhardt/122909856b570c5c457a6cd674795a9c) [2016] by Gary Bernhardt
* [Raw Markdown (GitHub)](https://gist.githubusercontent.com/garybernhardt/122909856b570c5c457a6cd674795a9c/raw/843c05aa304c9c090dd63309a61edb9f9cbf108d/types.markdown)
* [Cached Article (in case the above links die)](/pl-types) | {
"content_hash": "497b114faf49d4e36a5682194fe46577",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 172,
"avg_line_length": 80.93333333333334,
"alnum_prop": 0.7602965403624382,
"repo_name": "gragas/gragas.github.io",
"id": "6fee851c3e00d6ac40cee063930af6de3fdb9334",
"size": "1218",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "pl-readings.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "11698"
},
{
"name": "HTML",
"bytes": "5030"
},
{
"name": "Ruby",
"bytes": "3163"
}
],
"symlink_target": ""
} |
#!/bin/bash
# Copyright 2014 The Kubernetes Authors All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# The golang package that we are building.
readonly KUBE_GO_PACKAGE=k8s.io/kubernetes
readonly KUBE_GOPATH="${KUBE_OUTPUT}/go"
# Load contrib target functions
if [ -n "${KUBERNETES_CONTRIB:-}" ]; then
for contrib in "${KUBERNETES_CONTRIB}"; do
source "${KUBE_ROOT}/contrib/${contrib}/target.sh"
done
fi
# The set of server targets that we are only building for Linux
kube::golang::server_targets() {
local targets=(
cmd/kube-proxy
cmd/kube-apiserver
cmd/kube-controller-manager
cmd/kubelet
cmd/kubemark
cmd/hyperkube
cmd/linkcheck
plugin/cmd/kube-scheduler
)
if [ -n "${KUBERNETES_CONTRIB:-}" ]; then
for contrib in "${KUBERNETES_CONTRIB}"; do
targets+=($(eval "kube::contrib::${contrib}::server_targets"))
done
fi
echo "${targets[@]}"
}
readonly KUBE_SERVER_TARGETS=($(kube::golang::server_targets))
readonly KUBE_SERVER_BINARIES=("${KUBE_SERVER_TARGETS[@]##*/}")
# The server platform we are building on.
readonly KUBE_SERVER_PLATFORMS=(
linux/amd64
linux/arm
)
# The set of client targets that we are building for all platforms
readonly KUBE_CLIENT_TARGETS=(
cmd/kubectl
)
readonly KUBE_CLIENT_BINARIES=("${KUBE_CLIENT_TARGETS[@]##*/}")
readonly KUBE_CLIENT_BINARIES_WIN=("${KUBE_CLIENT_BINARIES[@]/%/.exe}")
# The set of test targets that we are building for all platforms
kube::golang::test_targets() {
local targets=(
cmd/integration
cmd/gendocs
cmd/genkubedocs
cmd/genman
cmd/mungedocs
cmd/genbashcomp
cmd/genconversion
cmd/gendeepcopy
cmd/genswaggertypedocs
examples/k8petstore/web-server/src
github.com/onsi/ginkgo/ginkgo
test/e2e/e2e.test
)
if [ -n "${KUBERNETES_CONTRIB:-}" ]; then
for contrib in "${KUBERNETES_CONTRIB}"; do
targets+=($(eval "kube::contrib::${contrib}::test_targets"))
done
fi
echo "${targets[@]}"
}
readonly KUBE_TEST_TARGETS=($(kube::golang::test_targets))
readonly KUBE_TEST_BINARIES=("${KUBE_TEST_TARGETS[@]##*/}")
readonly KUBE_TEST_BINARIES_WIN=("${KUBE_TEST_BINARIES[@]/%/.exe}")
readonly KUBE_TEST_PORTABLE=(
test/images/network-tester/rc.json
test/images/network-tester/service.json
test/kubemark
hack/e2e.go
hack/e2e-internal
hack/get-build.sh
hack/ginkgo-e2e.sh
hack/lib
)
# If we update this we need to also update the set of golang compilers we build
# in 'build/build-image/Dockerfile'
readonly KUBE_CLIENT_PLATFORMS=(
linux/amd64
linux/386
linux/arm
darwin/amd64
darwin/386
windows/amd64
)
# Gigabytes desired for parallel platform builds. 11 is fairly
# arbitrary, but is a reasonable splitting point for 2015
# laptops-versus-not.
#
# If you are using boot2docker, the following seems to work (note
# that 12000 rounds to 11G):
# boot2docker down
# VBoxManage modifyvm boot2docker-vm --memory 12000
# boot2docker up
readonly KUBE_PARALLEL_BUILD_MEMORY=11
readonly KUBE_ALL_TARGETS=(
"${KUBE_SERVER_TARGETS[@]}"
"${KUBE_CLIENT_TARGETS[@]}"
"${KUBE_TEST_TARGETS[@]}"
)
readonly KUBE_ALL_BINARIES=("${KUBE_ALL_TARGETS[@]##*/}")
readonly KUBE_STATIC_LIBRARIES=(
kube-apiserver
kube-controller-manager
kube-scheduler
kube-proxy
kubectl
)
kube::golang::is_statically_linked_library() {
local e
for e in "${KUBE_STATIC_LIBRARIES[@]}"; do [[ "$1" == *"/$e" ]] && return 0; done;
# Allow individual overrides--e.g., so that you can get a static build of
# kubectl for inclusion in a container.
if [ -n "${KUBE_STATIC_OVERRIDES:+x}" ]; then
for e in "${KUBE_STATIC_OVERRIDES[@]}"; do [[ "$1" == *"/$e" ]] && return 0; done;
fi
return 1;
}
# kube::binaries_from_targets take a list of build targets and return the
# full go package to be built
kube::golang::binaries_from_targets() {
local target
for target; do
# If the target starts with what looks like a domain name, assume it has a
# fully-qualified package name rather than one that needs the Kubernetes
# package prepended.
if [[ "${target}" =~ ^([[:alnum:]]+".")+[[:alnum:]]+"/" ]]; then
echo "${target}"
else
echo "${KUBE_GO_PACKAGE}/${target}"
fi
done
}
# Asks golang what it thinks the host platform is. The go tool chain does some
# slightly different things when the target platform matches the host platform.
kube::golang::host_platform() {
echo "$(go env GOHOSTOS)/$(go env GOHOSTARCH)"
}
kube::golang::current_platform() {
local os="${GOOS-}"
if [[ -z $os ]]; then
os=$(go env GOHOSTOS)
fi
local arch="${GOARCH-}"
if [[ -z $arch ]]; then
arch=$(go env GOHOSTARCH)
fi
echo "$os/$arch"
}
# Takes the the platform name ($1) and sets the appropriate golang env variables
# for that platform.
kube::golang::set_platform_envs() {
[[ -n ${1-} ]] || {
kube::log::error_exit "!!! Internal error. No platform set in kube::golang::set_platform_envs"
}
export GOOS=${platform%/*}
export GOARCH=${platform##*/}
}
kube::golang::unset_platform_envs() {
unset GOOS
unset GOARCH
}
# Create the GOPATH tree under $KUBE_OUTPUT
kube::golang::create_gopath_tree() {
local go_pkg_dir="${KUBE_GOPATH}/src/${KUBE_GO_PACKAGE}"
local go_pkg_basedir=$(dirname "${go_pkg_dir}")
mkdir -p "${go_pkg_basedir}"
rm -f "${go_pkg_dir}"
# TODO: This symlink should be relative.
ln -s "${KUBE_ROOT}" "${go_pkg_dir}"
}
# kube::golang::setup_env will check that the `go` commands is available in
# ${PATH}. If not running on Travis, it will also check that the Go version is
# good enough for the Kubernetes build.
#
# Input Vars:
# KUBE_EXTRA_GOPATH - If set, this is included in created GOPATH
# KUBE_NO_GODEPS - If set, we don't add 'Godeps/_workspace' to GOPATH
#
# Output Vars:
# export GOPATH - A modified GOPATH to our created tree along with extra
# stuff.
# export GOBIN - This is actively unset if already set as we want binaries
# placed in a predictable place.
kube::golang::setup_env() {
kube::golang::create_gopath_tree
if [[ -z "$(which go)" ]]; then
kube::log::usage_from_stdin <<EOF
Can't find 'go' in PATH, please fix and retry.
See http://golang.org/doc/install for installation instructions.
EOF
exit 2
fi
# Travis continuous build uses a head go release that doesn't report
# a version number, so we skip this check on Travis. It's unnecessary
# there anyway.
if [[ "${TRAVIS:-}" != "true" ]]; then
local go_version
go_version=($(go version))
if [[ "${go_version[2]}" < "go1.4" ]]; then
kube::log::usage_from_stdin <<EOF
Detected go version: ${go_version[*]}.
Kubernetes requires go version 1.4 or greater.
Please install Go version 1.4 or later.
EOF
exit 2
fi
fi
GOPATH=${KUBE_GOPATH}
# Append KUBE_EXTRA_GOPATH to the GOPATH if it is defined.
if [[ -n ${KUBE_EXTRA_GOPATH:-} ]]; then
GOPATH="${GOPATH}:${KUBE_EXTRA_GOPATH}"
fi
# Append the tree maintained by `godep` to the GOPATH unless KUBE_NO_GODEPS
# is defined.
if [[ -z ${KUBE_NO_GODEPS:-} ]]; then
GOPATH="${GOPATH}:${KUBE_ROOT}/Godeps/_workspace"
fi
export GOPATH
# Unset GOBIN in case it already exists in the current session.
unset GOBIN
}
# This will take binaries from $GOPATH/bin and copy them to the appropriate
# place in ${KUBE_OUTPUT_BINDIR}
#
# Ideally this wouldn't be necessary and we could just set GOBIN to
# KUBE_OUTPUT_BINDIR but that won't work in the face of cross compilation. 'go
# install' will place binaries that match the host platform directly in $GOBIN
# while placing cross compiled binaries into `platform_arch` subdirs. This
# complicates pretty much everything else we do around packaging and such.
kube::golang::place_bins() {
local host_platform
host_platform=$(kube::golang::host_platform)
kube::log::status "Placing binaries"
local platform
for platform in "${KUBE_CLIENT_PLATFORMS[@]}"; do
# The substitution on platform_src below will replace all slashes with
# underscores. It'll transform darwin/amd64 -> darwin_amd64.
local platform_src="/${platform//\//_}"
if [[ $platform == $host_platform ]]; then
platform_src=""
fi
local gopaths=("${KUBE_GOPATH}")
# If targets were built inside Godeps, then we need to sync from there too.
if [[ -z ${KUBE_NO_GODEPS:-} ]]; then
gopaths+=("${KUBE_ROOT}/Godeps/_workspace")
fi
local gopath
for gopath in "${gopaths[@]}"; do
local full_binpath_src="${gopath}/bin${platform_src}"
if [[ -d "${full_binpath_src}" ]]; then
mkdir -p "${KUBE_OUTPUT_BINPATH}/${platform}"
find "${full_binpath_src}" -maxdepth 1 -type f -exec \
rsync -pt {} "${KUBE_OUTPUT_BINPATH}/${platform}" \;
fi
done
done
}
kube::golang::fallback_if_stdlib_not_installable() {
local go_root_dir=$(go env GOROOT);
local go_host_os=$(go env GOHOSTOS);
local go_host_arch=$(go env GOHOSTARCH);
local cgo_pkg_dir=${go_root_dir}/pkg/${go_host_os}_${go_host_arch}_cgo;
if [ -e ${cgo_pkg_dir} ]; then
return 0;
fi
if [ -w ${go_root_dir}/pkg ]; then
return 0;
fi
kube::log::status "+++ Warning: stdlib pkg with cgo flag not found.";
kube::log::status "+++ Warning: stdlib pkg cannot be rebuilt since ${go_root_dir}/pkg is not writable by `whoami`";
kube::log::status "+++ Warning: Make ${go_root_dir}/pkg writable for `whoami` for a one-time stdlib install, Or"
kube::log::status "+++ Warning: Rebuild stdlib using the command 'CGO_ENABLED=0 go install -a -installsuffix cgo std'";
kube::log::status "+++ Falling back to go build, which is slower";
use_go_build=true
}
# Try and replicate the native binary placement of go install without
# calling go install.
kube::golang::output_filename_for_binary() {
local binary=$1
local platform=$2
local output_path="${KUBE_GOPATH}/bin"
if [[ $platform != $host_platform ]]; then
output_path="${output_path}/${platform//\//_}"
fi
local bin=$(basename "${binary}")
if [[ ${GOOS} == "windows" ]]; then
bin="${bin}.exe"
fi
echo "${output_path}/${bin}"
}
kube::golang::build_binaries_for_platform() {
local platform=$1
local use_go_build=${2-}
local -a statics=()
local -a nonstatics=()
local -a tests=()
for binary in "${binaries[@]}"; do
if [[ "${binary}" =~ ".test"$ ]]; then
tests+=($binary)
elif kube::golang::is_statically_linked_library "${binary}"; then
statics+=($binary)
else
nonstatics+=($binary)
fi
done
if [[ "${#statics[@]}" != 0 ]]; then
kube::golang::fallback_if_stdlib_not_installable;
fi
if [[ -n ${use_go_build:-} ]]; then
kube::log::progress " "
for binary in "${statics[@]:+${statics[@]}}"; do
local outfile=$(kube::golang::output_filename_for_binary "${binary}" "${platform}")
CGO_ENABLED=0 go build -o "${outfile}" \
"${goflags[@]:+${goflags[@]}}" \
-ldflags "${goldflags}" \
"${binary}"
kube::log::progress "*"
done
for binary in "${nonstatics[@]:+${nonstatics[@]}}"; do
local outfile=$(kube::golang::output_filename_for_binary "${binary}" "${platform}")
go build -o "${outfile}" \
"${goflags[@]:+${goflags[@]}}" \
-ldflags "${goldflags}" \
"${binary}"
kube::log::progress "*"
done
kube::log::progress "\n"
else
# Use go install.
if [[ "${#nonstatics[@]}" != 0 ]]; then
go install "${goflags[@]:+${goflags[@]}}" \
-ldflags "${goldflags}" \
"${nonstatics[@]:+${nonstatics[@]}}"
fi
if [[ "${#statics[@]}" != 0 ]]; then
CGO_ENABLED=0 go install -installsuffix cgo "${goflags[@]:+${goflags[@]}}" \
-ldflags "${goldflags}" \
"${statics[@]:+${statics[@]}}"
fi
fi
for test in "${tests[@]:+${tests[@]}}"; do
local outfile=$(kube::golang::output_filename_for_binary "${test}" \
"${platform}")
# Go 1.4 added -o to control where the binary is saved, but Go 1.3 doesn't
# have this flag. Whenever we deprecate go 1.3, update to use -o instead of
# changing into the output directory.
mkdir -p "$(dirname ${outfile})"
pushd "$(dirname ${outfile})" >/dev/null
go test -c \
"${goflags[@]:+${goflags[@]}}" \
-ldflags "${goldflags}" \
"$(dirname ${test})"
popd >/dev/null
done
}
# Return approximate physical memory available in gigabytes.
kube::golang::get_physmem() {
local mem
# Linux kernel version >=3.14, in kb
if mem=$(grep MemAvailable /proc/meminfo | awk '{ print $2 }'); then
echo $(( ${mem} / 1048576 ))
return
fi
# Linux, in kb
if mem=$(grep MemTotal /proc/meminfo | awk '{ print $2 }'); then
echo $(( ${mem} / 1048576 ))
return
fi
# OS X, in bytes. Note that get_physmem, as used, should only ever
# run in a Linux container (because it's only used in the multiple
# platform case, which is a Dockerized build), but this is provided
# for completeness.
if mem=$(sysctl -n hw.memsize 2>/dev/null); then
echo $(( ${mem} / 1073741824 ))
return
fi
# If we can't infer it, just give up and assume a low memory system
echo 1
}
# Build binaries targets specified
#
# Input:
# $@ - targets and go flags. If no targets are set then all binaries targets
# are built.
# KUBE_BUILD_PLATFORMS - Incoming variable of targets to build for. If unset
# then just the host architecture is built.
kube::golang::build_binaries() {
# Create a sub-shell so that we don't pollute the outer environment
(
# Check for `go` binary and set ${GOPATH}.
kube::golang::setup_env
local host_platform
host_platform=$(kube::golang::host_platform)
# Use eval to preserve embedded quoted strings.
local goflags goldflags
eval "goflags=(${KUBE_GOFLAGS:-})"
goldflags="${KUBE_GOLDFLAGS:-} $(kube::version::ldflags)"
local use_go_build
local -a targets=()
local arg
for arg; do
if [[ "${arg}" == "--use_go_build" ]]; then
use_go_build=true
elif [[ "${arg}" == -* ]]; then
# Assume arguments starting with a dash are flags to pass to go.
goflags+=("${arg}")
else
targets+=("${arg}")
fi
done
if [[ ${#targets[@]} -eq 0 ]]; then
targets=("${KUBE_ALL_TARGETS[@]}")
fi
local -a platforms=("${KUBE_BUILD_PLATFORMS[@]:+${KUBE_BUILD_PLATFORMS[@]}}")
if [[ ${#platforms[@]} -eq 0 ]]; then
platforms=("${host_platform}")
fi
local binaries
binaries=($(kube::golang::binaries_from_targets "${targets[@]}"))
local parallel=false
if [[ ${#platforms[@]} -gt 1 ]]; then
local gigs
gigs=$(kube::golang::get_physmem)
if [[ ${gigs} -ge ${KUBE_PARALLEL_BUILD_MEMORY} ]]; then
kube::log::status "Multiple platforms requested and available ${gigs}G >= threshold ${KUBE_PARALLEL_BUILD_MEMORY}G, building platforms in parallel"
parallel=true
else
kube::log::status "Multiple platforms requested, but available ${gigs}G < threshold ${KUBE_PARALLEL_BUILD_MEMORY}G, building platforms in serial"
parallel=false
fi
fi
if [[ "${parallel}" == "true" ]]; then
kube::log::status "Building go targets for ${platforms[@]} in parallel (output will appear in a burst when complete):" "${targets[@]}"
local platform
for platform in "${platforms[@]}"; do (
kube::golang::set_platform_envs "${platform}"
kube::log::status "${platform}: go build started"
kube::golang::build_binaries_for_platform ${platform} ${use_go_build:-}
kube::log::status "${platform}: go build finished"
) &> "/tmp//${platform//\//_}.build" &
done
local fails=0
for job in $(jobs -p); do
wait ${job} || let "fails+=1"
done
for platform in "${platforms[@]}"; do
cat "/tmp//${platform//\//_}.build"
done
exit ${fails}
else
for platform in "${platforms[@]}"; do
kube::log::status "Building go targets for ${platform}:" "${targets[@]}"
kube::golang::set_platform_envs "${platform}"
kube::golang::build_binaries_for_platform ${platform} ${use_go_build:-}
done
fi
)
}
| {
"content_hash": "870f6f57ad0ac98c69377ad8e8c2eec6",
"timestamp": "",
"source": "github",
"line_count": 541,
"max_line_length": 155,
"avg_line_length": 30.91866913123845,
"alnum_prop": 0.6367549470915287,
"repo_name": "Defensative/kubernetes",
"id": "bf881caf3800bf42378b44b0c5b58a42a766b54a",
"size": "16727",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "hack/lib/golang.sh",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "Go",
"bytes": "18946159"
},
{
"name": "HTML",
"bytes": "1193991"
},
{
"name": "Makefile",
"bytes": "46385"
},
{
"name": "Nginx",
"bytes": "1013"
},
{
"name": "Python",
"bytes": "68276"
},
{
"name": "SaltStack",
"bytes": "44811"
},
{
"name": "Shell",
"bytes": "1183500"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/TradeMaximizer-1.3a.iml" filepath="$PROJECT_DIR$/TradeMaximizer-1.3a.iml" />
</modules>
</component>
</project>
| {
"content_hash": "c1cbe2095c43cdcc2ee9d893f4ac4d51",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 120,
"avg_line_length": 31.11111111111111,
"alnum_prop": 0.6678571428571428,
"repo_name": "DrFriendless/TradeMaximizerOz",
"id": "f0224a8c194af54559a482388ec24e1ead5e3917",
"size": "280",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": ".idea/modules.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "40888175"
},
{
"name": "Java",
"bytes": "153442"
},
{
"name": "Shell",
"bytes": "38"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.