text
stringlengths 2
100k
| meta
dict |
---|---|
parseconditions:
desc: Ping LogParser Conditions
file: ping.log
parsecontents: yes
type: local
normalisejavalog: no
normaliseisocpplog: no
product: OpenSpliceDDS
conditions:
- name: excess_message
type: line
inst: 0
required: no
line: "PING: Ignore excess messages :"
- name: no_data_message
type: line
inst: 0
required: no
line: "PONG: PING_min triggered, but no data available"
- name: usage_message
type: line
inst: 0
required: no
line: "Usage * blocks blocksize topic_id WRITE_PARTITION READ_PARTITION"
| {
"pile_set_name": "Github"
} |
// [FOR DEBUGGING]
// One-off with noise
SLIDES.push({
id: "noise",
onstart: function(self){
var o = self.objects;
Tournament.resetGlobalVariables();
// Iterated Simulation
self.add({id:"iterated", type:"Iterated", x:130, y:133});
o.iterated.dehighlightPayoff();
o.iterated.playerA.chooseHat("tft");
// Words on top & bottom
self.add({
id:"topWords", type:"TextBox", text_id:"noise_1",
x:130, y:35, width:700, height:100, align:"center"
});
self.add({
id:"btmWords", type:"TextBox", text_id:"noise_1_end",
x:130, y:410, width:700, height:100, align:"center"
});
// STAGES
var STAGES = [
{button:"cooperate", message:"cooperate"},
{button:"cooperate", message:"TRIP"},
{button:"cooperate", message:"cooperate"},
{button:"cheat", message:"cheat"}
];
var STAGE_INDEX = 0;
// ONE Button
self.add({
id:"button", type:"Button",
x:383, y:463, text_id:"label_cooperate", uppercase:true,
onclick: function(){
// Make sim go
var s = STAGES[STAGE_INDEX];
publish("iterated/"+s.message);
o.button.deactivate();
// Hide words
_hide(o.topWords);
_hide(o.btmWords);
}
});
// Re-activate...
var _foreverWar = false;
var _foreverMove = "cheat";
listen(self, "iterated/round/end", function(){
if(_foreverWar){
publish("iterated/"+_foreverMove);
if(_foreverMove=="cheat") _foreverMove="cooperate";
else if(_foreverMove=="cooperate") _foreverMove="cheat";
}else{
STAGE_INDEX++;
// New words
o.topWords.setTextID("noise_"+(STAGE_INDEX+1));
o.btmWords.setTextID("noise_"+(STAGE_INDEX+1)+"_end");
_fadeIn(o.topWords, 100);
_fadeIn(o.btmWords, 300);
// Next stage
if(STAGE_INDEX>=STAGES.length){
publish("iterated/cooperate");
_foreverWar = true;
// The FINAL buttons... remove the button & put it back in.
self.remove("button");
self.add({
id:"button", type:"Button",
x:304, y:463, text_id:"noise_5_btn", size:"long",
message: "slideshow/scratch"
});
}else{
// Reactivate buttons
var s = STAGES[STAGE_INDEX];
o.button.setText("label_"+s.button);
o.button.activate();
}
}
});
},
onend: function(self){
unlisten(self);
self.clear();
}
});
// New characters
SLIDES.push({
onstart: function(self){
// WORDS
self.add({
id:"score1", type:"TextBox",
x:160, y:20, width:640,
text_id:"noise_characters"
});
// CHARS
self.add({
id:"char_tf2t", type:"CharacterTextBox",
x:160, y:70, width:640,
character: "tf2t"
});
self.add({
id:"char_pavlov", type:"CharacterTextBox",
x:160, y:190, width:640,
character: "pavlov"
});
self.add({
id:"char_random", type:"CharacterTextBox",
x:160, y:320, width:640,
character: "random"
});
// Next...
self.add({
id:"next", type:"TextBox",
x:160, y:420, width:640, align:"right",
text_id: "noise_characters_end"
});
// Next Button!
self.add({
id:"next_button", type:"Button", x:460, y:460, size:"long",
text_id:"noise_characters_btn",
message:"slideshow/scratch"
});
},
onend: function(self){
self.clear();
}
});
// Tournament: simpleton wins
SLIDES.push({
//id:"noise",// [FOR DEBUGGING]
onstart: function(self){
var o = self.objects;
// Tournament
Tournament.resetGlobalVariables();
Tournament.INITIAL_AGENTS = [
{strategy:"tf2t", count:3},
{strategy:"pavlov", count:3},
{strategy:"random", count:3},
{strategy:"tft", count:3},
{strategy:"all_c", count:13}
];
PD.NOISE = 0.05;
self.add({id:"tournament", type:"Tournament", x:-20, y:20});
// Words to the side
self.add({
id:"text", type:"TextBox",
x:510, y:30, width:450, height:500,
text_id:"noise_evo_1"
});
// BETS
var _addButton = function(character, x, y){
(function(character, x, y){
self.add({
id:"bet_"+character, type:"Button", x:x, y:y,
text_id: "icon_"+character,
tooltip: "who_"+character,
onclick:function(){
_.answer = character;
publish("slideshow/next");
}
});
})(character, x, y);
};
var x = 510;
var y = 295;
var dx = 200;
var dy = 70;
_addButton("tf2t", x, y); _addButton("pavlov", x+dx, y);
_addButton("random", x, y+dy); _addButton("tft", x+dx, y+dy);
_addButton("all_c", x, y+dy*2);
// WHO'S WHO?
self.add({
id:"forgot", type:"TextBox",
x:715, y:435, width:190, height:50,
align:"center", color:"#aaa", size:15,
text_id:"forgot_whos_who"
});
},
onend: function(self){
self.remove("bet_all_c");
self.remove("bet_tft");
self.remove("bet_tf2t");
self.remove("bet_pavlov");
self.remove("bet_random");
self.remove("forgot");
}
});
SLIDES.push({
onstart: function(self){
var o = self.objects;
// Words
var words = Words.get("noise_evo_2").replace(/\[CHAR\]/g, "<span class='"+_.answer+"'>"+Words.get("label_"+_.answer)+"</span>");
o.text.setText(words);
_hide(o.text); _fadeIn(o.text, 100);
/////////////////////////////////////////
// BUTTONS for playing //////////////////
/////////////////////////////////////////
var x = 172;
var y = 175;
var dy = 70;
self.add({
id:"playButton", type:"Button", size:"short",
x:x, y:y, text_id:"label_start",
onclick: function(){
if(o.tournament.isAutoPlaying){
publish("tournament/autoplay/stop");
}else{
publish("tournament/autoplay/start");
}
}
});
listen(_, "tournament/autoplay/stop",function(){
o.playButton.setText("label_start");
});
listen(_, "tournament/autoplay/start",function(){
o.playButton.setText("label_stop");
});
self.add({
id:"stepButton", type:"Button", size:"short",
x:x, y:y+dy, text_id:"label_step", message:"tournament/step"
});
self.add({
id:"resetButton", type:"Button", size:"short",
x:x, y:y+dy*2, text_id:"label_reset", message:"tournament/reset"
});
/////////////////////////////////////////
// SHOW THE NEXT WORDS, and a NEXT
// NEXT
var reproduceSteps = 0;
_.misc = {};
listen(_.misc, "tournament/step/completed", function(step){
if(step=="reproduce"){
reproduceSteps++;
if(reproduceSteps==6){
// WORDS
var words = (_.answer=="pavlov") ? Words.get("noise_evo_2_2_correct") : Words.get("noise_evo_2_2_incorrect");
words += " ";
words += Words.get("noise_evo_2_2");
self.add({
id:"text_next", type:"TextBox",
x:510, y:160, width:450,
text: words
});
_hide(o.text_next); _fadeIn(o.text_next, 100);
// BUTTON
self.add({
id:"btn_next", type:"Button", x:510, y:366,
text_id:"noise_evo_2_2_btn", size:"long",
message:"slideshow/next"
});
_hide(o.btn_next); _fadeIn(o.btn_next, 300);
}
}
});
},
onend: function(self){
self.remove("text_next");
self.remove("btn_next");
unlisten(_.misc);
}
});
SLIDES.push({
onstart: function(self){
var o = self.objects;
// Words
o.text.setTextID("noise_evo_3");
_hide(o.text); _fadeIn(o.text, 100);
// Tournament
Tournament.resetGlobalVariables();
Tournament.INITIAL_AGENTS = [
{strategy:"tf2t", count:3},
{strategy:"pavlov", count:3},
{strategy:"random", count:3},
{strategy:"tft", count:3},
{strategy:"all_d", count:13}
];
PD.NOISE = 0.05;
o.tournament.reset();
// HIDE PLAYER
_hide(o.playButton); o.playButton.deactivate();
_hide(o.stepButton); o.stepButton.deactivate();
_hide(o.resetButton); o.resetButton.deactivate();
// BETS
var _addButton = function(character, x, y){
(function(character, x, y){
self.add({
id:"bet_"+character, type:"Button", x:x, y:y,
text_id: "icon_"+character,
tooltip: "who_"+character,
onclick:function(){
_.answer = character;
publish("slideshow/next");
}
});
})(character, x, y);
};
var x = 510;
var y = 295;
var dx = 200;
var dy = 70;
_addButton("tf2t", x, y); _addButton("pavlov", x+dx, y);
_addButton("random", x, y+dy); _addButton("tft", x+dx, y+dy);
_addButton("all_d", x, y+dy*2);
// WHO'S WHO?
self.add({
id:"forgot", type:"TextBox",
x:715, y:435, width:190, height:50,
align:"center", color:"#aaa", size:15,
text_id:"forgot_whos_who"
});
},
onend: function(self){
self.remove("bet_all_d");
self.remove("bet_tft");
self.remove("bet_tf2t");
self.remove("bet_pavlov");
self.remove("bet_random");
self.remove("forgot");
}
});
SLIDES.push({
onstart: function(self){
var o = self.objects;
// SHOW PLAYER
_fadeIn(o.playButton,1); o.playButton.activate();
_fadeIn(o.stepButton,1); o.stepButton.activate();
_fadeIn(o.resetButton,1); o.resetButton.activate();
o.playButton.setText("label_start");
// Words
var words = Words.get("noise_evo_4").replace(/\[CHAR\]/g, "<span class='"+_.answer+"'>"+Words.get("label_"+_.answer)+"</span>");
o.text.setText(words);
_hide(o.text); _fadeIn(o.text, 100);
/////////////////////////////////////////
// SHOW THE NEXT WORDS, and a NEXT
// NEXT
var reproduceSteps = 0;
_.misc = {};
listen(_.misc, "tournament/step/completed", function(step){
if(step=="reproduce"){
reproduceSteps++;
if(reproduceSteps==8){
// WORDS
var words = (_.answer=="tf2t") ? Words.get("noise_evo_4_2_correct") : Words.get("noise_evo_4_2_incorrect");
words += " ";
words += Words.get("noise_evo_4_2");
self.add({
id:"text_next", type:"TextBox",
x:510, y:116, width:450,
text: words
});
_hide(o.text_next); _fadeIn(o.text_next, 100);
// BUTTON
self.add({
id:"btn_next", type:"Button", x:510, y:446,
text_id:"noise_evo_4_2_btn", size:"long",
message:"slideshow/next"
});
_hide(o.btn_next); _fadeIn(o.btn_next, 300);
}
}
});
},
onend: function(self){
self.remove("text_next");
self.remove("btn_next");
unlisten(_.misc);
}
});
SLIDES.push({
onstart: function(self){
var o = self.objects;
_.misc = {};
// Words
o.text.setTextID("noise_evo_5");
_hide(o.text); _fadeIn(o.text, 100);
// Tournament
o.tournament.reset();
// Slider!
var x = 510;
var y = 200;
self.add({
id:"noiseLabel", type:"TextBox",
x:x, y:y, width:450, noSelect:true
});
self.add({
id:"noiseSlider", type:"Slider",
x:x, y:y+55, width:450,
min:0.00, max:0.50, step:0.01,
message: "rules/noise"
});
var _updateLabel = function(value){
value = Math.round(value*100);
var words = Words.get("sandbox_rules_3");
words = words.replace(/\[N\]/g, value+""); // replace [N] with the number value
o.noiseLabel.setText("<i>"+words+"</i>");
};
listen(_.misc, "rules/noise", function(value){
_updateLabel(value);
o.tournament.reset();
});
o.noiseSlider.setValue(0.05);
_updateLabel(0.05);
_hide(o.noiseLabel); _fadeIn(o.noiseLabel, 300);
_hide(o.noiseSlider); _fadeIn(o.noiseSlider, 300);
// Continue whenever you want to...
listen(_.misc, "tournament/autoplay/start",function(){
if(_showContinue) _showContinue();
});
var _showContinue = function(){
_showContinue = null;
self.add({
id:"continueLabel", type:"TextBox",
x:565, y:405, width:400,
align:"right", color:"#aaa", size:17,
text_id:"noise_evo_5_continue"
});
self.add({
id:"continueButton", type:"Button",
x:855, y:440, size:"short",
text_id:"label_continue",
message: "slideshow/next"
});
_hide(o.continueLabel); _fadeIn(o.continueLabel, 100);
_hide(o.continueButton); _fadeIn(o.continueButton, 100);
};
},
onend: function(self){
unlisten(_.misc);
self.remove("noiseLabel");
self.remove("noiseSlider");
var o = self.objects;
if(o.continueLabel) self.remove("continueLabel");
if(o.continueButton) self.remove("continueButton");
self.remove("text");
}
});
SLIDES.push({
onstart: function(self){
var o = self.objects;
// Words
self.add({
id:"text", type:"TextBox",
x:510, y:10, width:450, height:500,
text_id:"noise_evo_6"
});
_hide(o.text); _fadeIn(o.text, 100);
// Next button
self.add({
id:"button", type:"Button", x:510, y:466,
text_id:"noise_evo_6_btn", size:"long",
message:"slideshow/scratch"
});
_hide(o.button); _fadeIn(o.button, 500);
},
onend: function(self){
self.clear();
unlisten(self);
unlisten(_);
unlisten(_.misc);
}
});
| {
"pile_set_name": "Github"
} |
/***************************************************************************
qgsoptionalexpression - QgsOptionalExpression
---------------------
begin : 14.9.2016
copyright : (C) 2016 by Matthias Kuhn
email : [email protected]
***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#include "qgsoptionalexpression.h"
QgsOptionalExpression::QgsOptionalExpression( const QgsExpression &expression )
: QgsOptional<QgsExpression>( expression )
{
}
QgsOptionalExpression::QgsOptionalExpression( const QgsExpression &expression, bool enabled )
: QgsOptional<QgsExpression>( expression, enabled )
{
}
void QgsOptionalExpression::writeXml( QDomElement &element )
{
QDomText exp = element.ownerDocument().createTextNode( data().expression() );
element.setAttribute( QStringLiteral( "enabled" ), enabled() );
element.appendChild( exp );
}
void QgsOptionalExpression::readXml( const QDomElement &element )
{
setEnabled( element.attribute( QStringLiteral( "enabled" ) ).toInt() );
setData( element.text() );
}
| {
"pile_set_name": "Github"
} |
package stanford.cs106.io;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
/** for capturing console output (for methods that do printlns) */
public class OutputCapturer {
private static final PrintStream SYSTEM_OUT = java.lang.System.out;
private static final PrintStream SYSTEM_ERR = java.lang.System.err;
private static ByteArrayOutputStream outputStream = null;
/** Returns true if output is currently being captured. */
public static boolean isCapturing() {
return outputStream != null;
}
/** Begins capturing output with no limit as to its length. */
public static synchronized void start() {
start(true);
}
/**
* Begins capturing output. Will throw an exception if the student
* printlns too much.
*/
public static synchronized void start(boolean limit) {
if (isCapturing()) {
stop();
}
outputStream = new ByteArrayOutputStream(16384);
PrintStream out;
if (limit) {
out = new LimitedPrintStream(outputStream);
} else {
out = new PrintStream(outputStream);
}
System.setOut(out);
System.setErr(out);
}
/** Stops capturing output and returns the string of captured output. */
public static synchronized String stop() {
String actualOutput = "";
if (isCapturing()) {
System.out.flush();
System.err.flush();
System.setOut(SYSTEM_OUT);
System.setErr(SYSTEM_ERR);
if (isCapturing()) {
actualOutput = outputStream.toString().replace("\r", "");
}
outputStream = null;
}
return actualOutput;
}
}
| {
"pile_set_name": "Github"
} |
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* Copyright (C) Jernej Skrabec <[email protected]>
*/
#include <drm/drm_print.h>
#include "sun8i_csc.h"
#include "sun8i_mixer.h"
static const u32 ccsc_base[2][2] = {
{CCSC00_OFFSET, CCSC01_OFFSET},
{CCSC10_OFFSET, CCSC11_OFFSET},
};
/*
* Factors are in two's complement format, 10 bits for fractinal part.
* First tree values in each line are multiplication factor and last
* value is constant, which is added at the end.
*/
static const u32 yuv2rgb[2][2][12] = {
[DRM_COLOR_YCBCR_LIMITED_RANGE] = {
[DRM_COLOR_YCBCR_BT601] = {
0x000004A8, 0x00000000, 0x00000662, 0xFFFC8451,
0x000004A8, 0xFFFFFE6F, 0xFFFFFCC0, 0x00021E4D,
0x000004A8, 0x00000811, 0x00000000, 0xFFFBACA9,
},
[DRM_COLOR_YCBCR_BT709] = {
0x000004A8, 0x00000000, 0x0000072B, 0xFFFC1F99,
0x000004A8, 0xFFFFFF26, 0xFFFFFDDF, 0x00013383,
0x000004A8, 0x00000873, 0x00000000, 0xFFFB7BEF,
}
},
[DRM_COLOR_YCBCR_FULL_RANGE] = {
[DRM_COLOR_YCBCR_BT601] = {
0x00000400, 0x00000000, 0x0000059B, 0xFFFD322E,
0x00000400, 0xFFFFFEA0, 0xFFFFFD25, 0x00021DD5,
0x00000400, 0x00000716, 0x00000000, 0xFFFC74BD,
},
[DRM_COLOR_YCBCR_BT709] = {
0x00000400, 0x00000000, 0x0000064C, 0xFFFCD9B4,
0x00000400, 0xFFFFFF41, 0xFFFFFE21, 0x00014F96,
0x00000400, 0x0000076C, 0x00000000, 0xFFFC49EF,
}
},
};
static const u32 yvu2rgb[2][2][12] = {
[DRM_COLOR_YCBCR_LIMITED_RANGE] = {
[DRM_COLOR_YCBCR_BT601] = {
0x000004A8, 0x00000662, 0x00000000, 0xFFFC8451,
0x000004A8, 0xFFFFFCC0, 0xFFFFFE6F, 0x00021E4D,
0x000004A8, 0x00000000, 0x00000811, 0xFFFBACA9,
},
[DRM_COLOR_YCBCR_BT709] = {
0x000004A8, 0x0000072B, 0x00000000, 0xFFFC1F99,
0x000004A8, 0xFFFFFDDF, 0xFFFFFF26, 0x00013383,
0x000004A8, 0x00000000, 0x00000873, 0xFFFB7BEF,
}
},
[DRM_COLOR_YCBCR_FULL_RANGE] = {
[DRM_COLOR_YCBCR_BT601] = {
0x00000400, 0x0000059B, 0x00000000, 0xFFFD322E,
0x00000400, 0xFFFFFD25, 0xFFFFFEA0, 0x00021DD5,
0x00000400, 0x00000000, 0x00000716, 0xFFFC74BD,
},
[DRM_COLOR_YCBCR_BT709] = {
0x00000400, 0x0000064C, 0x00000000, 0xFFFCD9B4,
0x00000400, 0xFFFFFE21, 0xFFFFFF41, 0x00014F96,
0x00000400, 0x00000000, 0x0000076C, 0xFFFC49EF,
}
},
};
/*
* DE3 has a bit different CSC units. Factors are in two's complement format.
* First three factors in a row are multiplication factors which have 17 bits
* for fractional part. Fourth value in a row is comprised of two factors.
* Upper 16 bits represents difference, which is subtracted from the input
* value before multiplication and lower 16 bits represents constant, which
* is addes at the end.
*
* x' = c00 * (x + d0) + c01 * (y + d1) + c02 * (z + d2) + const0
* y' = c10 * (x + d0) + c11 * (y + d1) + c12 * (z + d2) + const1
* z' = c20 * (x + d0) + c21 * (y + d1) + c22 * (z + d2) + const2
*
* Please note that above formula is true only for Blender CSC. Other DE3 CSC
* units takes only positive value for difference. From what can be deducted
* from BSP driver code, those units probably automatically assume that
* difference has to be subtracted.
*
* Layout of factors in table:
* c00 c01 c02 [d0 const0]
* c10 c11 c12 [d1 const1]
* c20 c21 c22 [d2 const2]
*/
static const u32 yuv2rgb_de3[2][2][12] = {
[DRM_COLOR_YCBCR_LIMITED_RANGE] = {
[DRM_COLOR_YCBCR_BT601] = {
0x0002542A, 0x00000000, 0x0003312A, 0xFFC00000,
0x0002542A, 0xFFFF376B, 0xFFFE5FC3, 0xFE000000,
0x0002542A, 0x000408D2, 0x00000000, 0xFE000000,
},
[DRM_COLOR_YCBCR_BT709] = {
0x0002542A, 0x00000000, 0x000395E2, 0xFFC00000,
0x0002542A, 0xFFFF92D2, 0xFFFEEF27, 0xFE000000,
0x0002542A, 0x0004398C, 0x00000000, 0xFE000000,
}
},
[DRM_COLOR_YCBCR_FULL_RANGE] = {
[DRM_COLOR_YCBCR_BT601] = {
0x00020000, 0x00000000, 0x0002CDD2, 0x00000000,
0x00020000, 0xFFFF4FCE, 0xFFFE925D, 0xFE000000,
0x00020000, 0x00038B43, 0x00000000, 0xFE000000,
},
[DRM_COLOR_YCBCR_BT709] = {
0x00020000, 0x00000000, 0x0003264C, 0x00000000,
0x00020000, 0xFFFFA018, 0xFFFF1053, 0xFE000000,
0x00020000, 0x0003B611, 0x00000000, 0xFE000000,
}
},
};
static const u32 yvu2rgb_de3[2][2][12] = {
[DRM_COLOR_YCBCR_LIMITED_RANGE] = {
[DRM_COLOR_YCBCR_BT601] = {
0x0002542A, 0x0003312A, 0x00000000, 0xFFC00000,
0x0002542A, 0xFFFE5FC3, 0xFFFF376B, 0xFE000000,
0x0002542A, 0x00000000, 0x000408D2, 0xFE000000,
},
[DRM_COLOR_YCBCR_BT709] = {
0x0002542A, 0x000395E2, 0x00000000, 0xFFC00000,
0x0002542A, 0xFFFEEF27, 0xFFFF92D2, 0xFE000000,
0x0002542A, 0x00000000, 0x0004398C, 0xFE000000,
}
},
[DRM_COLOR_YCBCR_FULL_RANGE] = {
[DRM_COLOR_YCBCR_BT601] = {
0x00020000, 0x0002CDD2, 0x00000000, 0x00000000,
0x00020000, 0xFFFE925D, 0xFFFF4FCE, 0xFE000000,
0x00020000, 0x00000000, 0x00038B43, 0xFE000000,
},
[DRM_COLOR_YCBCR_BT709] = {
0x00020000, 0x0003264C, 0x00000000, 0x00000000,
0x00020000, 0xFFFF1053, 0xFFFFA018, 0xFE000000,
0x00020000, 0x00000000, 0x0003B611, 0xFE000000,
}
},
};
static void sun8i_csc_set_coefficients(struct regmap *map, u32 base,
enum sun8i_csc_mode mode,
enum drm_color_encoding encoding,
enum drm_color_range range)
{
const u32 *table;
u32 base_reg;
switch (mode) {
case SUN8I_CSC_MODE_YUV2RGB:
table = yuv2rgb[range][encoding];
break;
case SUN8I_CSC_MODE_YVU2RGB:
table = yvu2rgb[range][encoding];
break;
default:
DRM_WARN("Wrong CSC mode specified.\n");
return;
}
base_reg = SUN8I_CSC_COEFF(base, 0);
regmap_bulk_write(map, base_reg, table, 12);
}
static void sun8i_de3_ccsc_set_coefficients(struct regmap *map, int layer,
enum sun8i_csc_mode mode,
enum drm_color_encoding encoding,
enum drm_color_range range)
{
const u32 *table;
u32 base_reg;
switch (mode) {
case SUN8I_CSC_MODE_YUV2RGB:
table = yuv2rgb_de3[range][encoding];
break;
case SUN8I_CSC_MODE_YVU2RGB:
table = yvu2rgb_de3[range][encoding];
break;
default:
DRM_WARN("Wrong CSC mode specified.\n");
return;
}
base_reg = SUN50I_MIXER_BLEND_CSC_COEFF(DE3_BLD_BASE, layer, 0, 0);
regmap_bulk_write(map, base_reg, table, 12);
}
static void sun8i_csc_enable(struct regmap *map, u32 base, bool enable)
{
u32 val;
if (enable)
val = SUN8I_CSC_CTRL_EN;
else
val = 0;
regmap_update_bits(map, SUN8I_CSC_CTRL(base), SUN8I_CSC_CTRL_EN, val);
}
static void sun8i_de3_ccsc_enable(struct regmap *map, int layer, bool enable)
{
u32 val, mask;
mask = SUN50I_MIXER_BLEND_CSC_CTL_EN(layer);
if (enable)
val = mask;
else
val = 0;
regmap_update_bits(map, SUN50I_MIXER_BLEND_CSC_CTL(DE3_BLD_BASE),
mask, val);
}
void sun8i_csc_set_ccsc_coefficients(struct sun8i_mixer *mixer, int layer,
enum sun8i_csc_mode mode,
enum drm_color_encoding encoding,
enum drm_color_range range)
{
u32 base;
if (mixer->cfg->is_de3) {
sun8i_de3_ccsc_set_coefficients(mixer->engine.regs, layer,
mode, encoding, range);
return;
}
base = ccsc_base[mixer->cfg->ccsc][layer];
sun8i_csc_set_coefficients(mixer->engine.regs, base,
mode, encoding, range);
}
void sun8i_csc_enable_ccsc(struct sun8i_mixer *mixer, int layer, bool enable)
{
u32 base;
if (mixer->cfg->is_de3) {
sun8i_de3_ccsc_enable(mixer->engine.regs, layer, enable);
return;
}
base = ccsc_base[mixer->cfg->ccsc][layer];
sun8i_csc_enable(mixer->engine.regs, base, enable);
}
| {
"pile_set_name": "Github"
} |
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/appmesh/AppMesh_EXPORTS.h>
#include <aws/appmesh/model/PortMapping.h>
#include <utility>
namespace Aws
{
namespace Utils
{
namespace Json
{
class JsonValue;
class JsonView;
} // namespace Json
} // namespace Utils
namespace AppMesh
{
namespace Model
{
/**
* <p>An object that represents a virtual router listener.</p><p><h3>See Also:</h3>
* <a
* href="http://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/VirtualRouterListener">AWS
* API Reference</a></p>
*/
class AWS_APPMESH_API VirtualRouterListener
{
public:
VirtualRouterListener();
VirtualRouterListener(Aws::Utils::Json::JsonView jsonValue);
VirtualRouterListener& operator=(Aws::Utils::Json::JsonView jsonValue);
Aws::Utils::Json::JsonValue Jsonize() const;
inline const PortMapping& GetPortMapping() const{ return m_portMapping; }
inline bool PortMappingHasBeenSet() const { return m_portMappingHasBeenSet; }
inline void SetPortMapping(const PortMapping& value) { m_portMappingHasBeenSet = true; m_portMapping = value; }
inline void SetPortMapping(PortMapping&& value) { m_portMappingHasBeenSet = true; m_portMapping = std::move(value); }
inline VirtualRouterListener& WithPortMapping(const PortMapping& value) { SetPortMapping(value); return *this;}
inline VirtualRouterListener& WithPortMapping(PortMapping&& value) { SetPortMapping(std::move(value)); return *this;}
private:
PortMapping m_portMapping;
bool m_portMappingHasBeenSet;
};
} // namespace Model
} // namespace AppMesh
} // namespace Aws
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8"?>
<nrml xmlns:gml="http://www.opengis.net/gml"
xmlns="http://openquake.org/xmlns/nrml/0.4">
<logicTree logicTreeID="lt1">
<logicTreeBranchingLevel branchingLevelID="bl1">
<logicTreeBranchSet uncertaintyType="sourceModel"
branchSetID="bs1">
<logicTreeBranch branchID="b1">
<uncertaintyModel>source_model.xml</uncertaintyModel>
<uncertaintyWeight>1.0</uncertaintyWeight>
</logicTreeBranch>
</logicTreeBranchSet>
</logicTreeBranchingLevel>
</logicTree>
</nrml>
| {
"pile_set_name": "Github"
} |
import warnings
import numpy as np
from scipy import integrate
class RK4naive:
"""
Class for Defining Runge-Kutta 4th Order ODE solving method
"""
def __init__(self, fun, t0, y0, t_bound, stepsize):
"""
Initialization
Parameters
----------
fun : function
Should accept t, y as parameters, and return same type as y
t0 : float
Initial t
y0 : ~numpy.array or float
Initial y
t_bound : float
Boundary time - the integration won’t continue beyond it. It also determines the direction of the integration.
stepsize : float
Size of each increment in t
"""
self.t = t0
self.y = y0
self.t_bound = t_bound
self.step_size = stepsize
self._fun = fun
self.direction = 1 * (self.t_bound >= t0) - 1 * (not self.t_bound < t0)
def step(self):
"""
Updates the value of self.t and self.y
"""
if (self.t >= self.t_bound and self.direction == 1) or (
self.t <= self.t_bound and self.direction == -1
):
warnings.warn("Out of bounds set by t_bound. ", RuntimeWarning)
return
k0 = self._fun(self.t, self.y)
k1 = self._fun(
self.t + (self.step_size / 2.0), self.y + (self.step_size / 2.0) * k0
)
k2 = self._fun(
self.t + (self.step_size / 2.0), self.y + (self.step_size / 2.0) * k1
)
k3 = self._fun(self.t + self.step_size, self.y + (self.step_size) * k2)
self.y = self.y + ((self.step_size / 6.0) * (k0 + 2 * k1 + 2 * k2 + k3))
self.t = self.t + self.step_size
class RK45(integrate.RK45):
"""
This Class inherits ~scipy.integrate.RK45 Class
"""
def __init__(self, fun, t0, y0, t_bound, stepsize, rtol=None, atol=None):
"""
Initialization
Parameters
----------
fun : function
Should accept t, y as parameters, and return same type as y
t0 : float
Initial t
y0 : ~numpy.array or float
Initial y
t_bound : float
Boundary time - the integration won’t continue beyond it. It also determines the direction of the integration.
stepsize : float
Size of each increment in t
rtol : float
Relative tolerance, defaults to 0.2*stepsize
atol : float
Absolute tolerance, defaults to rtol/0.8e3
"""
vectorized = not isinstance(y0, float)
self._t_bound = t_bound
if rtol is None:
rtol = 0.2 * stepsize
if atol is None:
atol = rtol / 0.8e3
super(RK45, self).__init__(
fun=fun,
t0=t0,
y0=y0,
t_bound=self._t_bound,
first_step=0.8 * stepsize,
max_step=8.0 * stepsize,
rtol=rtol,
atol=atol,
vectorized=vectorized,
)
def step(self):
"""
Updates the value of self.t and self.y
"""
try:
super(RK45, self).step()
except RuntimeError:
warnings.warn(
"Attempt to step on a failed or finished solver. (Invalid Value or out of bounds of t_bound)",
RuntimeWarning,
)
| {
"pile_set_name": "Github"
} |
horde.isDemo = function () {
return false;
};
horde.populateWaves = function (engine) {
// FULL GAME WAVES
// Wave 1: Level 1
var w = new horde.SpawnWave();
w.addSpawnPoint(0, 1000);
w.addSpawnPoint(1, 1000);
w.addSpawnPoint(2, 1000);
w.addObjects(0, "bat", 1);
w.addObjects(1, "bat", 1);
w.addObjects(2, "bat", 1);
engine.waves.push(w);
// Wave 2
var w = new horde.SpawnWave();
w.addSpawnPoint(0, 1000);
w.addSpawnPoint(1, 1000);
w.addSpawnPoint(2, 1000);
w.addObjects(0, "goblin", 2);
w.addObjects(1, "goblin", 2);
w.addObjects(2, "goblin", 2);
engine.waves.push(w);
// Wave 3
var w = new horde.SpawnWave();
w.addSpawnPoint(1, 1000);
w.addObjects(1, "cyclops", 1);
engine.waves.push(w);
// Wave 4
var w = new horde.SpawnWave();
w.addSpawnPoint(0, 1000);
w.addSpawnPoint(1, 1000);
w.addSpawnPoint(2, 1000);
w.addObjects(0, "demoblin", 2);
w.addObjects(1, "demoblin", 3);
w.addObjects(2, "demoblin", 2);
engine.waves.push(w);
// Wave 5
var w = new horde.SpawnWave();
w.addSpawnPoint(0, 500);
w.addSpawnPoint(1, 750);
w.addSpawnPoint(2, 500);
w.addObjects(0, "bat", 5);
w.addObjects(0, "goblin", 2);
w.addObjects(1, "goblin", 2);
w.addObjects(1, "cyclops", 1);
w.addObjects(1, "goblin", 3);
w.addObjects(2, "bat", 5);
w.addObjects(2, "goblin", 2);
engine.waves.push(w);
// Wave 6
var w = new horde.SpawnWave();
w.addSpawnPoint(0, 200);
w.addSpawnPoint(1, 200);
w.addSpawnPoint(2, 200);
w.addObjects(0, "bat", 10);
w.addObjects(1, "bat", 10);
w.addObjects(2, "bat", 10);
engine.waves.push(w);
// Wave 7
var w = new horde.SpawnWave();
w.addSpawnPoint(0, 1000);
w.addSpawnPoint(1, 1000);
w.addSpawnPoint(2, 1000);
w.addObjects(0, "demoblin", 3);
w.addObjects(1, "cyclops", 1);
w.addObjects(1, "goblin", 5);
w.addObjects(2, "demoblin", 3);
engine.waves.push(w);
// Wave 8
var w = new horde.SpawnWave();
w.addSpawnPoint(0, 5000);
w.addSpawnPoint(1, 1500);
w.addSpawnPoint(2, 5000);
w.addObjects(0, "imp", 5);
w.addObjects(1, "imp", 10);
w.addObjects(2, "imp", 5);
engine.waves.push(w);
// Wave 9
var w = new horde.SpawnWave();
w.addSpawnPoint(0, 750);
w.addSpawnPoint(1, 750);
w.addSpawnPoint(2, 750);
w.addObjects(0, "cyclops", 1);
w.addObjects(2, "cyclops", 1);
w.addObjects(0, "bat", 10);
w.addObjects(1, "bat", 10);
w.addObjects(2, "bat", 10);
engine.waves.push(w);
// Wave 10: Gelatinous Cube
var w = new horde.SpawnWave();
w.addSpawnPoint(1, 1000);
w.addObjects(1, "cube", 1);
w.bossWave = true;
w.bossName = "Gelatinous Cube";
engine.waves.push(w);
// Wave 11: Level 2
var w = new horde.SpawnWave();
w.addSpawnPoint(0, 20000);
w.addSpawnPoint(1, 20000);
w.addSpawnPoint(2, 20000);
w.addObjects(0, "sandworm", 2);
w.addObjects(1, "sandworm", 2);
w.addObjects(2, "sandworm", 2);
engine.waves.push(w);
// Wave 12
var w = new horde.SpawnWave();
w.addSpawnPoint(0, 10000);
w.addSpawnPoint(1, 10000);
w.addSpawnPoint(2, 10000);
w.addObjects(0, "wizard", 2);
w.addObjects(1, "wizard", 2);
w.addObjects(2, "wizard", 2);
engine.waves.push(w);
// Wave 13
var w = new horde.SpawnWave();
w.addSpawnPoint(0, 7500);
w.addSpawnPoint(1, 7500);
w.addSpawnPoint(2, 7500);
w.addObjects(0, "flaming_skull", 2);
w.addObjects(1, "flaming_skull", 2);
w.addObjects(2, "flaming_skull", 2);
engine.waves.push(w);
// Wave 14
var w = new horde.SpawnWave();
w.addSpawnPoint(0, 15000);
w.addSpawnPoint(1, 1500);
w.addSpawnPoint(2, 15000);
w.addObjects(0, "owlbear", 1);
w.addObjects(2, "owlbear", 1);
engine.waves.push(w);
// Wave 15
var w = new horde.SpawnWave();
w.addSpawnPoint(0, 1000);
w.addSpawnPoint(1, 1000);
w.addSpawnPoint(2, 1000);
w.addObjects(0, "huge_skull", 1);
w.addObjects(1, "huge_skull", 1);
w.addObjects(2, "huge_skull", 1);
engine.waves.push(w);
// Wave 16
var w = new horde.SpawnWave();
w.addSpawnPoint(0, 500);
w.addSpawnPoint(1, 4000);
w.addSpawnPoint(2, 500);
w.addObjects(0, "dire_bat", 5);
w.addObjects(0, "hunter_goblin", 2);
w.addObjects(0, "dire_bat", 5);
w.addObjects(0, "hunter_goblin", 2);
w.addObjects(1, "sandworm", 2);
w.addObjects(2, "dire_bat", 5);
w.addObjects(2, "hunter_goblin", 2);
w.addObjects(2, "dire_bat", 5);
w.addObjects(2, "hunter_goblin", 2);
engine.waves.push(w);
// Wave 17
var w = new horde.SpawnWave();
w.addSpawnPoint(0, 3000);
w.addSpawnPoint(1, 1500);
w.addSpawnPoint(2, 3000);
w.addObjects(0, "flaming_skull", 2);
w.addObjects(1, "imp", 5);
w.addObjects(1, "wizard", 3);
w.addObjects(2, "flaming_skull", 2);
engine.waves.push(w);
// Wave 18
var w = new horde.SpawnWave();
w.addSpawnPoint(0, 1500);
w.addSpawnPoint(1, 1500);
w.addSpawnPoint(2, 1500);
w.addObjects(0, "cyclops", 1);
w.addObjects(0, "goblin", 5);
w.addObjects(1, "demoblin", 3);
w.addObjects(1, "owlbear", 1);
w.addObjects(1, "demoblin", 5);
w.addObjects(2, "goblin", 5);
w.addObjects(2, "cyclops", 1);
engine.waves.push(w);
// Wave 19
var w = new horde.SpawnWave();
w.addSpawnPoint(0, 3500);
w.addSpawnPoint(1, 4000);
w.addSpawnPoint(2, 5000);
w.addObjects(0, "wizard", 5);
w.addObjects(1, "imp", 5);
w.addObjects(1, "owlbear", 1);
w.addObjects(2, "sandworm", 3);
engine.waves.push(w);
// Wave 20: Minotaur
var w = new horde.SpawnWave();
w.addSpawnPoint(1, 1000);
w.addObjects(1, "superclops", 1);
w.bossWave = true;
w.bossName = "Minotaur"
engine.waves.push(w);
// Wave 21: Level 3
var w = new horde.SpawnWave();
w.addSpawnPoint(0, 100);
w.addSpawnPoint(1, 100);
w.addSpawnPoint(2, 100);
w.addObjects(0, "bat", 15);
w.addObjects(1, "dire_bat", 15);
w.addObjects(2, "bat", 15);
engine.waves.push(w);
// Wave 22
var w = new horde.SpawnWave();
w.addSpawnPoint(0, 1500);
w.addSpawnPoint(1, 1500);
w.addSpawnPoint(2, 1500);
w.addObjects(0, "goblin", 15);
w.addObjects(1, "hunter_goblin", 15);
w.addObjects(2, "goblin", 15);
engine.waves.push(w);
// Wave 23
var w = new horde.SpawnWave();
w.addSpawnPoint(0, 2000);
w.addSpawnPoint(1, 2000);
w.addSpawnPoint(2, 2000);
w.addObjects(0, "demoblin", 12);
w.addObjects(1, "demoblin", 12);
w.addObjects(2, "demoblin", 12);
engine.waves.push(w);
// Wave 24
var w = new horde.SpawnWave();
w.addSpawnPoint(0, 25000);
w.addSpawnPoint(1, 25000);
w.addSpawnPoint(2, 25000);
w.addObjects(0, "cyclops", 2);
w.addObjects(1, "cyclops", 2);
w.addObjects(2, "cyclops", 2);
engine.waves.push(w);
// Wave 25
var w = new horde.SpawnWave();
w.addSpawnPoint(0, 3000);
w.addSpawnPoint(1, 3000);
w.addSpawnPoint(2, 3000);
w.addObjects(0, "imp", 10);
w.addObjects(1, "imp", 10);
w.addObjects(2, "imp", 10);
engine.waves.push(w);
// Wave 26
var w = new horde.SpawnWave();
w.addSpawnPoint(0, 25000);
w.addSpawnPoint(1, 25000);
w.addSpawnPoint(2, 25000);
w.addObjects(0, "owlbear", 2);
w.addObjects(1, "owlbear", 2);
w.addObjects(2, "owlbear", 2);
engine.waves.push(w);
// Wave 27
var w = new horde.SpawnWave();
w.addSpawnPoint(0, 12000);
w.addSpawnPoint(1, 12000);
w.addSpawnPoint(2, 12000);
w.addObjects(0, "wizard", 4);
w.addObjects(1, "wizard", 4);
w.addObjects(2, "wizard", 4);
engine.waves.push(w);
// Wave 28
var w = new horde.SpawnWave();
w.addSpawnPoint(0, 15000);
w.addSpawnPoint(1, 20000);
w.addSpawnPoint(2, 15000);
w.addObjects(0, "flaming_skull", 5);
w.addObjects(1, "huge_skull", 3);
w.addObjects(2, "flaming_skull", 5);
engine.waves.push(w);
// Wave 29
var w = new horde.SpawnWave();
w.addSpawnPoint(0, 15000);
w.addSpawnPoint(1, 15000);
w.addSpawnPoint(2, 15000);
w.addObjects(0, "sandworm", 5);
w.addObjects(1, "sandworm", 5);
w.addObjects(2, "sandworm", 5);
engine.waves.push(w);
// Wave 30: Green Dragon
var w = new horde.SpawnWave();
w.addSpawnPoint(1, 1000);
w.addObjects(1, "dragon", 1);
w.bossWave = true;
w.bossName = "Green Dragon"
engine.waves.push(w);
// Wave 31: Level 4
var w = new horde.SpawnWave();
w.addSpawnPoint(0, 3500);
w.addSpawnPoint(1, 3500);
w.addSpawnPoint(2, 3500);
w.addObjects(0, "goblin", 25);
w.addObjects(1, "demoblin", 25);
w.addObjects(2, "hunter_goblin", 25);
engine.waves.push(w);
// Wave 32
var w = new horde.SpawnWave();
w.addSpawnPoint(0, 7500);
w.addSpawnPoint(1, 5000);
w.addSpawnPoint(2, 7500);
w.addObjects(0, "sandworm", 2);
w.addObjects(0, "wizard", 3);
w.addObjects(1, "imp", 10);
w.addObjects(2, "sandworm", 2);
w.addObjects(2, "wizard", 3);
engine.waves.push(w);
// Wave 33
var w = new horde.SpawnWave();
w.addSpawnPoint(0, 15000);
w.addSpawnPoint(1, 7500);
w.addSpawnPoint(2, 15000);
w.addObjects(0, "owlbear", 3);
w.addObjects(1, "flaming_skull", 6);
w.addObjects(2, "owlbear", 3);
engine.waves.push(w);
// Wave 34
var w = new horde.SpawnWave();
w.addSpawnPoint(0, 2500);
w.addSpawnPoint(1, 15000);
w.addSpawnPoint(2, 2500);
w.addObjects(0, "demoblin", 10);
w.addObjects(0, "goblin", 10);
w.addObjects(1, "cyclops", 1);
w.addObjects(1, "owlbear", 1);
w.addObjects(1, "cyclops", 1);
w.addObjects(1, "owlbear", 1);
w.addObjects(2, "demoblin", 10);
w.addObjects(2, "goblin", 10);
engine.waves.push(w);
// Wave 35
var w = new horde.SpawnWave();
w.addSpawnPoint(0, 12500);
w.addSpawnPoint(1, 20000);
w.addSpawnPoint(2, 12500);
w.addObjects(0, "sandworm", 5);
w.addObjects(1, "huge_skull", 1);
w.addObjects(1, "owlbear", 1);
w.addObjects(1, "cyclops", 1);
w.addObjects(1, "huge_skull", 1);
w.addObjects(2, "sandworm", 5);
engine.waves.push(w);
// Wave 36
var w = new horde.SpawnWave();
w.addSpawnPoint(0, 20000);
w.addSpawnPoint(1, 1000);
w.addSpawnPoint(2, 20000);
w.addObjects(0, "cyclops", 1);
w.addObjects(0, "flaming_skull", 1);
w.addObjects(1, "wizard", 8);
w.addObjects(2, "cyclops", 1);
w.addObjects(2, "flaming_skull", 1);
engine.waves.push(w);
// Wave 37
var w = new horde.SpawnWave();
w.addSpawnPoint(0, 4000);
w.addSpawnPoint(1, 10000);
w.addSpawnPoint(2, 4000);
w.addObjects(0, "demoblin", 8);
w.addObjects(1, "owlbear", 2);
w.addObjects(2, "demoblin", 8);
engine.waves.push(w);
// Wave 38
var w = new horde.SpawnWave();
w.addSpawnPoint(0, 5000);
w.addSpawnPoint(1, 7500);
w.addSpawnPoint(2, 5000);
w.addObjects(0, "sandworm", 1);
w.addObjects(0, "wizard", 3);
w.addObjects(1, "flaming_skull", 4);
w.addObjects(1, "huge_skull", 1);
w.addObjects(2, "sandworm", 1);
w.addObjects(2, "wizard", 3);
engine.waves.push(w);
// Wave 39
var w = new horde.SpawnWave();
w.addSpawnPoint(0, 2000);
w.addSpawnPoint(1, 2500);
w.addSpawnPoint(2, 2000);
w.addObjects(0, "goblin", 30);
w.addObjects(1, "demoblin", 25);
w.addObjects(2, "hunter_goblin", 30);
engine.waves.push(w);
// Wave 40: Beholder
var w = new horde.SpawnWave();
w.addSpawnPoint(1, 1000);
w.addObjects(1, "beholder", 1);
w.bossWave = true;
w.bossName = "Beholder"
engine.waves.push(w);
// Wave 41: Level 5
var w = new horde.SpawnWave();
w.addSpawnPoint(0, 3000);
w.addSpawnPoint(1, 3000);
w.addSpawnPoint(2, 3000);
w.addObjects(0, "cyclops", 2);
w.addObjects(1, "owlbear", 2);
w.addObjects(2, "cyclops", 2);
engine.waves.push(w);
// Wave 42
var w = new horde.SpawnWave();
w.addSpawnPoint(0, 1000);
w.addSpawnPoint(1, 1000);
w.addSpawnPoint(2, 1000);
w.addObjects(0, "wizard", 3);
w.addObjects(0, "flaming_skull", 1);
w.addObjects(1, "wizard", 3);
w.addObjects(1, "huge_skull", 1);
w.addObjects(2, "wizard", 3);
w.addObjects(2, "flaming_skull", 1);
engine.waves.push(w);
// Wave 43
var w = new horde.SpawnWave();
w.addSpawnPoint(0, 3000);
w.addSpawnPoint(1, 3000);
w.addSpawnPoint(2, 3000);
w.addObjects(0, "sandworm", 3);
w.addObjects(0, "owlbear", 1);
w.addObjects(1, "sandworm", 3);
w.addObjects(1, "huge_skull", 1);
w.addObjects(2, "sandworm", 3);
w.addObjects(2, "cyclops", 1);
engine.waves.push(w);
// Wave 44
var w = new horde.SpawnWave();
w.addSpawnPoint(0, 200);
w.addSpawnPoint(1, 200);
w.addSpawnPoint(2, 200);
w.addObjects(0, "dire_bat", 20);
w.addObjects(0, "wizard", 2);
w.addObjects(0, "cyclops", 1);
w.addObjects(1, "dire_bat", 20);
w.addObjects(1, "sandworm", 2);
w.addObjects(1, "owlbear", 1);
w.addObjects(2, "dire_bat", 20);
w.addObjects(2, "wizard", 2);
w.addObjects(2, "cyclops", 1);
engine.waves.push(w);
// Wave 45
var w = new horde.SpawnWave();
w.addSpawnPoint(0, 3000);
w.addSpawnPoint(1, 3000);
w.addSpawnPoint(2, 3000);
w.addObjects(0, "goblin", 10);
w.addObjects(0, "cyclops", 1);
w.addObjects(0, "wizard", 3);
w.addObjects(1, "demoblin", 10);
w.addObjects(1, "huge_skull", 1);
w.addObjects(1, "sandworm", 3);
w.addObjects(2, "hunter_goblin", 10);
w.addObjects(2, "owlbear", 1);
w.addObjects(2, "flaming_skull", 3);
engine.waves.push(w);
// Wave 46
var w = new horde.SpawnWave();
w.addSpawnPoint(0, 2500);
w.addSpawnPoint(1, 1000);
w.addSpawnPoint(2, 2500);
w.addObjects(0, "wizard", 4);
w.addObjects(1, "cube", 1);
w.addObjects(2, "wizard", 4);
engine.waves.push(w);
// Wave 47
var w = new horde.SpawnWave();
w.addSpawnPoint(0, 1000);
w.addSpawnPoint(1, 1000);
w.addSpawnPoint(2, 1000);
w.addObjects(0, "demoblin", 5);
w.addObjects(1, "superclops", 1);
w.addObjects(1, "demoblin", 4);
w.addObjects(2, "demoblin", 5);
engine.waves.push(w);
// Wave 48
var w = new horde.SpawnWave();
w.addSpawnPoint(0, 30000);
w.addSpawnPoint(1, 1000);
w.addSpawnPoint(2, 30000);
w.addObjects(0, "sandworm", 1);
w.addObjects(0, "owlbear", 1);
w.addObjects(1, "dragon", 1);
w.addObjects(2, "sandworm", 1);
w.addObjects(2, "owlbear", 1);
engine.waves.push(w);
// Wave 49
var w = new horde.SpawnWave();
w.addSpawnPoint(0, 15000);
w.addSpawnPoint(1, 1000);
w.addSpawnPoint(2, 15000);
w.addObjects(0, "wizard", 1);
w.addObjects(0, "cyclops", 1);
w.addObjects(1, "beholder", 1);
w.addObjects(2, "wizard", 1);
w.addObjects(2, "cyclops", 1);
engine.waves.push(w);
// Wave 50: Doppelganger
var w = new horde.SpawnWave();
w.addSpawnPoint(1, 1000);
w.addObjects(1, "doppelganger", 1);
w.bossWave = true;
w.bossName = "Doppelganger"
engine.waves.push(w);
};
| {
"pile_set_name": "Github"
} |
/*
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.
*/
#import "CDVWhitelist.h"
NSString* const kCDVDefaultWhitelistRejectionString = @"ERROR whitelist rejection: url='%@'";
NSString* const kCDVDefaultSchemeName = @"cdv-default-scheme";
@interface CDVWhitelistPattern : NSObject {
@private
NSRegularExpression* _scheme;
NSRegularExpression* _host;
NSNumber* _port;
NSRegularExpression* _path;
}
+ (NSString*)regexFromPattern:(NSString*)pattern allowWildcards:(bool)allowWildcards;
- (id)initWithScheme:(NSString*)scheme host:(NSString*)host port:(NSString*)port path:(NSString*)path;
- (bool)matches:(NSURL*)url;
@end
@implementation CDVWhitelistPattern
+ (NSString*)regexFromPattern:(NSString*)pattern allowWildcards:(bool)allowWildcards
{
NSString* regex = [NSRegularExpression escapedPatternForString:pattern];
if (allowWildcards) {
regex = [regex stringByReplacingOccurrencesOfString:@"\\*" withString:@".*"];
/* [NSURL path] has the peculiarity that a trailing slash at the end of a path
* will be omitted. This regex tweak compensates for that.
*/
if ([regex hasSuffix:@"\\/.*"]) {
regex = [NSString stringWithFormat:@"%@(\\/.*)?", [regex substringToIndex:([regex length] - 4)]];
}
}
return [NSString stringWithFormat:@"%@$", regex];
}
- (id)initWithScheme:(NSString*)scheme host:(NSString*)host port:(NSString*)port path:(NSString*)path
{
self = [super init]; // Potentially change "self"
if (self) {
if ((scheme == nil) || [scheme isEqualToString:@"*"]) {
_scheme = nil;
} else {
_scheme = [NSRegularExpression regularExpressionWithPattern:[CDVWhitelistPattern regexFromPattern:scheme allowWildcards:NO] options:NSRegularExpressionCaseInsensitive error:nil];
}
if ([host isEqualToString:@"*"] || host == nil) {
_host = nil;
} else if ([host hasPrefix:@"*."]) {
_host = [NSRegularExpression regularExpressionWithPattern:[NSString stringWithFormat:@"([a-z0-9.-]*\\.)?%@", [CDVWhitelistPattern regexFromPattern:[host substringFromIndex:2] allowWildcards:false]] options:NSRegularExpressionCaseInsensitive error:nil];
} else {
_host = [NSRegularExpression regularExpressionWithPattern:[CDVWhitelistPattern regexFromPattern:host allowWildcards:NO] options:NSRegularExpressionCaseInsensitive error:nil];
}
if ((port == nil) || [port isEqualToString:@"*"]) {
_port = nil;
} else {
_port = [[NSNumber alloc] initWithInteger:[port integerValue]];
}
if ((path == nil) || [path isEqualToString:@"/*"]) {
_path = nil;
} else {
_path = [NSRegularExpression regularExpressionWithPattern:[CDVWhitelistPattern regexFromPattern:path allowWildcards:YES] options:0 error:nil];
}
}
return self;
}
- (bool)matches:(NSURL*)url
{
return (_scheme == nil || [_scheme numberOfMatchesInString:[url scheme] options:NSMatchingAnchored range:NSMakeRange(0, [[url scheme] length])]) &&
(_host == nil || ([url host] != nil && [_host numberOfMatchesInString:[url host] options:NSMatchingAnchored range:NSMakeRange(0, [[url host] length])])) &&
(_port == nil || [[url port] isEqualToNumber:_port]) &&
(_path == nil || [_path numberOfMatchesInString:[url path] options:NSMatchingAnchored range:NSMakeRange(0, [[url path] length])])
;
}
@end
@interface CDVWhitelist ()
@property (nonatomic, readwrite, strong) NSMutableArray* whitelist;
@property (nonatomic, readwrite, strong) NSMutableSet* permittedSchemes;
- (void)addWhiteListEntry:(NSString*)pattern;
@end
@implementation CDVWhitelist
@synthesize whitelist, permittedSchemes, whitelistRejectionFormatString;
- (id)initWithArray:(NSArray*)array
{
self = [super init];
if (self) {
self.whitelist = [[NSMutableArray alloc] init];
self.permittedSchemes = [[NSMutableSet alloc] init];
self.whitelistRejectionFormatString = kCDVDefaultWhitelistRejectionString;
for (NSString* pattern in array) {
[self addWhiteListEntry:pattern];
}
}
return self;
}
- (BOOL)isIPv4Address:(NSString*)externalHost
{
// an IPv4 address has 4 octets b.b.b.b where b is a number between 0 and 255.
// for our purposes, b can also be the wildcard character '*'
// we could use a regex to solve this problem but then I would have two problems
// anyways, this is much clearer and maintainable
NSArray* octets = [externalHost componentsSeparatedByString:@"."];
NSUInteger num_octets = [octets count];
// quick check
if (num_octets != 4) {
return NO;
}
// restrict number parsing to 0-255
NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setMinimum:[NSNumber numberWithUnsignedInteger:0]];
[numberFormatter setMaximum:[NSNumber numberWithUnsignedInteger:255]];
// iterate through each octet, and test for a number between 0-255 or if it equals '*'
for (NSUInteger i = 0; i < num_octets; ++i) {
NSString* octet = [octets objectAtIndex:i];
if ([octet isEqualToString:@"*"]) { // passes - check next octet
continue;
} else if ([numberFormatter numberFromString:octet] == nil) { // fails - not a number and not within our range, return
return NO;
}
}
return YES;
}
- (void)addWhiteListEntry:(NSString*)origin
{
if (self.whitelist == nil) {
return;
}
if ([origin isEqualToString:@"*"]) {
NSLog(@"Unlimited access to network resources");
self.whitelist = nil;
self.permittedSchemes = nil;
} else { // specific access
NSRegularExpression* parts = [NSRegularExpression regularExpressionWithPattern:@"^((\\*|[A-Za-z-]+):/?/?)?(((\\*\\.)?[^*/:]+)|\\*)?(:(\\d+))?(/.*)?" options:0 error:nil];
NSTextCheckingResult* m = [parts firstMatchInString:origin options:NSMatchingAnchored range:NSMakeRange(0, [origin length])];
if (m != nil) {
NSRange r;
NSString* scheme = nil;
r = [m rangeAtIndex:2];
if (r.location != NSNotFound) {
scheme = [origin substringWithRange:r];
}
NSString* host = nil;
r = [m rangeAtIndex:3];
if (r.location != NSNotFound) {
host = [origin substringWithRange:r];
}
// Special case for two urls which are allowed to have empty hosts
if (([scheme isEqualToString:@"file"] || [scheme isEqualToString:@"content"]) && (host == nil)) {
host = @"*";
}
NSString* port = nil;
r = [m rangeAtIndex:7];
if (r.location != NSNotFound) {
port = [origin substringWithRange:r];
}
NSString* path = nil;
r = [m rangeAtIndex:8];
if (r.location != NSNotFound) {
path = [origin substringWithRange:r];
}
if (scheme == nil) {
// XXX making it stupid friendly for people who forget to include protocol/SSL
[self.whitelist addObject:[[CDVWhitelistPattern alloc] initWithScheme:@"http" host:host port:port path:path]];
[self.whitelist addObject:[[CDVWhitelistPattern alloc] initWithScheme:@"https" host:host port:port path:path]];
} else {
[self.whitelist addObject:[[CDVWhitelistPattern alloc] initWithScheme:scheme host:host port:port path:path]];
}
if (self.permittedSchemes != nil) {
if ([scheme isEqualToString:@"*"]) {
self.permittedSchemes = nil;
} else if (scheme != nil) {
[self.permittedSchemes addObject:scheme];
}
}
}
}
}
- (BOOL)schemeIsAllowed:(NSString*)scheme
{
if ([scheme isEqualToString:@"http"] ||
[scheme isEqualToString:@"https"] ||
[scheme isEqualToString:@"ftp"] ||
[scheme isEqualToString:@"ftps"]) {
return YES;
}
return (self.permittedSchemes == nil) || [self.permittedSchemes containsObject:scheme];
}
- (BOOL)URLIsAllowed:(NSURL*)url
{
return [self URLIsAllowed:url logFailure:YES];
}
- (BOOL)URLIsAllowed:(NSURL*)url logFailure:(BOOL)logFailure
{
// Shortcut acceptance: Are all urls whitelisted ("*" in whitelist)?
if (whitelist == nil) {
return YES;
}
// Shortcut rejection: Check that the scheme is supported
NSString* scheme = [[url scheme] lowercaseString];
if (![self schemeIsAllowed:scheme]) {
if (logFailure) {
NSLog(@"%@", [self errorStringForURL:url]);
}
return NO;
}
// http[s] and ftp[s] should also validate against the common set in the kCDVDefaultSchemeName list
if ([scheme isEqualToString:@"http"] || [scheme isEqualToString:@"https"] || [scheme isEqualToString:@"ftp"] || [scheme isEqualToString:@"ftps"]) {
NSURL* newUrl = [NSURL URLWithString:[NSString stringWithFormat:@"%@://%@%@", kCDVDefaultSchemeName, [url host], [[url path] stringByAddingPercentEncodingWithAllowedCharacters:NSCharacterSet.URLPathAllowedCharacterSet]]];
// If it is allowed, we are done. If not, continue to check for the actual scheme-specific list
if ([self URLIsAllowed:newUrl logFailure:NO]) {
return YES;
}
}
// Check the url against patterns in the whitelist
for (CDVWhitelistPattern* p in self.whitelist) {
if ([p matches:url]) {
return YES;
}
}
if (logFailure) {
NSLog(@"%@", [self errorStringForURL:url]);
}
// if we got here, the url host is not in the white-list, do nothing
return NO;
}
- (NSString*)errorStringForURL:(NSURL*)url
{
return [NSString stringWithFormat:self.whitelistRejectionFormatString, [url absoluteString]];
}
@end
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:padding="10dip"
android:orientation="vertical">
<TextView
android:id="@+id/textView1"
android:layout_margin="15dp"
android:textSize="20sp"
android:gravity="start"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/str_circle_title" />
<ImageView
android:id="@+id/iv_round_origin"
android:layout_width="240dp"
android:layout_height="240dp" />
<View
android:layout_width="match_parent"
android:layout_height="2dp"
android:layout_marginTop="20dp"
android:background="@android:color/darker_gray" />
<TextView
android:id="@+id/textView2"
android:layout_margin="15dp"
android:textSize="20sp"
android:gravity="start"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/str_combine_img" />
<ImageView
android:id="@+id/iv_round_combine"
android:layout_width="240dp"
android:layout_height="240dp" />
<View
android:layout_width="match_parent"
android:layout_height="2dp"
android:layout_marginTop="20dp"
android:background="@android:color/darker_gray" />
<TextView
android:text="@string/str_gaosimohu"
android:layout_margin="15dp"
android:textSize="20sp"
android:gravity="start"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:id="@+id/radius_small"
android:text="@string/str_radius_low"
android:layout_weight="1"
android:onClick="radiusSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="@+id/radius_big"
android:text="@string/str_radius_high"
android:layout_weight="1"
android:onClick="radiusBig"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
<ImageView
android:id="@+id/iv_blur"
android:src="@mipmap/sea"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
</ScrollView>
| {
"pile_set_name": "Github"
} |
package laya.net {
import laya.events.Event;
import laya.events.EventDispatcher;
import laya.net.Loader;
import laya.resource.ICreateResource;
import laya.resource.Texture;
import laya.utils.Handler;
import laya.utils.Utils;
/**
* 所有资源加载完成时调度。
* @eventType Event.COMPLETE
* */
[Event(name = "complete", type = "laya.events.Event")]
/**
* 任何资源加载出错时调度。
* @eventType Event.ERROR
* */
[Event(name = "error", type = "laya.events.Event")]
/**
* <p> <code>LoaderManager</code> 类用于用于批量加载资源。此类是单例,不要手动实例化此类,请通过Laya.loader访问。</p>
* <p>全部队列加载完成,会派发 Event.COMPLETE 事件;如果队列中任意一个加载失败,会派发 Event.ERROR 事件,事件回调参数值为加载出错的资源地址。</p>
* <p> <code>LoaderManager</code> 类提供了以下几种功能:<br/>
* 多线程:默认5个加载线程,可以通过maxLoader属性修改线程数量;<br/>
* 多优先级:有0-4共5个优先级,优先级高的优先加载。0最高,4最低;<br/>
* 重复过滤:自动过滤重复加载(不会有多个相同地址的资源同时加载)以及复用缓存资源,防止重复加载;<br/>
* 错误重试:资源加载失败后,会重试加载(以最低优先级插入加载队列),retryNum设定加载失败后重试次数,retryDelay设定加载重试的时间间隔。</p>
* @see laya.net.Loader
*/
public class LoaderManager extends EventDispatcher {
/**@private */
private static var _resMap:Object = {};
/**@private */
public static var createMap:Object = {atlas: [null, Loader.ATLAS]};
/** 加载出错后的重试次数,默认重试一次*/
public var retryNum:int = 1;
/** 延迟时间多久再进行错误重试,默认立即重试*/
public var retryDelay:int = 0;
/** 最大下载线程,默认为5个*/
public var maxLoader:int = 5;
/**@private */
private var _loaders:Array = [];
/**@private */
private var _loaderCount:int = 0;
/**@private */
private var _resInfos:Array = [];
/**@private */
private var _infoPool:Array = [];
/**@private */
private var _maxPriority:int = 5;
/**@private */
private var _failRes:Object = {};
/**
* <p>创建一个新的 <code>LoaderManager</code> 实例。</p>
* <p><b>注意:</b>请使用Laya.loader加载资源,这是一个单例,不要手动实例化此类,否则会导致不可预料的问题。</p>
*/
public function LoaderManager() {
for (var i:int = 0; i < this._maxPriority; i++) this._resInfos[i] = [];
}
/**
* <p>根据clas类型创建一个未初始化资源的对象,随后进行异步加载,资源加载完成后,初始化对象的资源,并通过此对象派发 Event.LOADED 事件,事件回调参数值为此对象本身。套嵌资源的子资源会保留资源路径"?"后的部分。</p>
* <p>如果url为数组,返回true;否则返回指定的资源类对象,可以通过侦听此对象的 Event.LOADED 事件来判断资源是否已经加载完毕。</p>
* <p><b>注意:</b>cache参数只能对文件后缀为atlas的资源进行缓存控制,其他资源会忽略缓存,强制重新加载。</p>
* @param url 资源地址或者数组。如果url和clas同时指定了资源类型,优先使用url指定的资源类型。参数形如:[{url:xx,clas:xx,priority:xx,params:xx},{url:xx,clas:xx,priority:xx,params:xx}]。
* @param complete 加载结束回调。根据url类型不同分为2种情况:1. url为String类型,也就是单个资源地址,如果加载成功,则回调参数值为加载完成的资源,否则为null;2. url为数组类型,指定了一组要加载的资源,如果全部加载成功,则回调参数值为true,否则为false。
* @param progress 资源加载进度回调,回调参数值为当前资源加载的进度信息(0-1)。
* @param clas 资源类名。如果url和clas同时指定了资源类型,优先使用url指定的资源类型。参数形如:Texture。
* @param params 资源构造参数。
* @param priority (default = 1)加载的优先级,优先级高的优先加载。有0-4共5个优先级,0最高,4最低。
* @param cache 是否缓存加载的资源。
* @return 如果url为数组,返回true;否则返回指定的资源类对象。
*/
public function create(url:*, complete:Handler = null, progress:Handler = null, clas:Class = null, params:Array = null, priority:int = 1, cache:Boolean = true, group:String = null):* {
if (url is Array) {
var items:Array = url as Array;
var itemCount:int = items.length;
var loadedCount:int = 0;
if (progress) {
var progress2:Handler = Handler.create(progress.caller, progress.method, progress.args, false);
}
for (var i:int = 0; i < itemCount; i++) {
var item:* = items[i];
if (item is String)
item = items[i] = {url: item};
item.progress = 0;
}
for (i = 0; i < itemCount; i++) {
item = items[i];
var progressHandler:Handler = progress ? Handler.create(null, onProgress, [item], false) : null;
var completeHandler:Handler = (progress || complete) ? Handler.create(null, onComplete, [item]) : null;
_create(item.url, completeHandler, progressHandler, item.clas || clas, item.params || params, item.priority || priority, cache, item.group || group);
}
function onComplete(item:Object, content:* = null):void {
loadedCount++;
item.progress = 1;
if (loadedCount === itemCount && complete) {
complete.run();
}
}
function onProgress(item:Object, value:Number):void {
item.progress = value;
var num:Number = 0;
for (var j:int = 0; j < itemCount; j++) {
var item1:Object = items[j];
num += item1.progress;
}
var v:Number = num / itemCount;
progress2.runWith(v);
}
return true;
} else return _create(url, complete, progress, clas, params, priority, cache, group);
}
private function _create(url:String, complete:Handler = null, progress:Handler = null, clas:Class = null, params:Array = null, priority:int = 1, cache:Boolean = true, group:String = null):* {
var formarUrl:String = URL.formatURL(url);
var item:* = getRes(formarUrl);
if (!item) {
var extension:String = Utils.getFileExtension(url);
var creatItem:Array = createMap[extension];
if (!creatItem)
throw new Error("LoaderManager:unknown file(" + url + ") extension with: " + extension + ".");
if (!clas) clas = creatItem[0];
var type:String = creatItem[1];
if (extension == "atlas") {
load(url, complete, progress, type, priority, cache);
} else {
if (clas === Texture) type = "htmlimage";
item = clas ? new clas() : null;
if (item.hasOwnProperty("_loaded"))
item._loaded = false;
item._setUrl(url);
(group) && (item._setGroup(group));
_createLoad(item, url, Handler.create(null, onLoaded), progress, type, priority, false, group, true);
function onLoaded(data:*):void {
(item && !item.destroyed && data) && (item.onAsynLoaded.call(item, url, data, params));//TODO:精灵如何处理
if (complete) complete.run();
Laya.loader.event(url);
}
(cache) && (cacheRes(formarUrl, item));
}
} else {
if (!item.hasOwnProperty("loaded") || item.loaded) {
progress && progress.runWith(1);
complete && complete.run();
} else if (complete) {
Laya.loader._createListener(url, complete.caller, complete.method, complete.args, true, false);
}
}
return item;
}
/**
* <p>加载资源。资源加载错误时,本对象会派发 Event.ERROR 事件,事件回调参数值为加载出错的资源地址。</p>
* <p>因为返回值为 LoaderManager 对象本身,所以可以使用如下语法:Laya.loader.load(...).load(...);</p>
* @param url 要加载的单个资源地址或资源信息数组。比如:简单数组:["a.png","b.png"];复杂数组[{url:"a.png",type:Loader.IMAGE,size:100,priority:1},{url:"b.json",type:Loader.JSON,size:50,priority:1}]。
* @param complete 加载结束回调。根据url类型不同分为2种情况:1. url为String类型,也就是单个资源地址,如果加载成功,则回调参数值为加载完成的资源,否则为null;2. url为数组类型,指定了一组要加载的资源,如果全部加载成功,则回调参数值为true,否则为false。
* @param progress 加载进度回调。回调参数值为当前资源的加载进度信息(0-1)。
* @param type 资源类型。比如:Loader.IMAGE。
* @param priority (default = 1)加载的优先级,优先级高的优先加载。有0-4共5个优先级,0最高,4最低。
* @param cache 是否缓存加载结果。
* @param group 分组,方便对资源进行管理。
* @param ignoreCache 是否忽略缓存,强制重新加载。
* @return 此 LoaderManager 对象本身。
*/
public function load(url:*, complete:Handler = null, progress:Handler = null, type:String = null, priority:int = 1, cache:Boolean = true, group:String = null, ignoreCache:Boolean = false):LoaderManager {
if (url is Array) return _loadAssets(url as Array, complete, progress, type, priority, cache, group);
var content:* = Loader.getRes(url);
if (content != null) {
//增加延迟回掉
Laya.timer.frameOnce(1, null, function():void {
progress && progress.runWith(1);
complete && complete.runWith(content);
//判断是否全部加载,如果是则抛出complete事件
_loaderCount || event(Event.COMPLETE);
});
} else {
var info:ResInfo = _resMap[url];
if (!info) {
info = _infoPool.length ? _infoPool.pop() : new ResInfo();
info.url = url;
info.type = type;
info.cache = cache;
info.group = group;
info.ignoreCache = ignoreCache;
complete && info.on(Event.COMPLETE, complete.caller, complete.method, complete.args);
progress && info.on(Event.PROGRESS, progress.caller, progress.method, progress.args);
_resMap[url] = info;
priority = priority < this._maxPriority ? priority : this._maxPriority - 1;
this._resInfos[priority].push(info);
_next();
} else {
complete && info._createListener(Event.COMPLETE, complete.caller, complete.method, complete.args, false, false);
progress && info._createListener(Event.PROGRESS, progress.caller, progress.method, progress.args, false, false);
}
}
return this;
}
/**
* @private
*/
public function _createLoad(item:*, url:*, complete:Handler = null, progress:Handler = null, type:String = null, priority:int = 1, cache:Boolean = true, group:String = null, ignoreCache:Boolean = false):LoaderManager {
if (url is Array) return _loadAssets(url as Array, complete, progress, type, priority, cache, group);
var content:* = Loader.getRes(url);
if (content != null) {
//增加延迟回掉
Laya.timer.frameOnce(1, null, function():void {
progress && progress.runWith(1);
complete && complete.runWith(content);
//判断是否全部加载,如果是则抛出complete事件
_loaderCount || event(Event.COMPLETE);
});
} else {
var info:ResInfo = _resMap[url];
if (!info) {
info = _infoPool.length ? _infoPool.pop() : new ResInfo();
info.url = url;
info.clas = item;
info.type = type;
info.cache = cache;
info.group = group;
info.ignoreCache = ignoreCache;
complete && info.on(Event.COMPLETE, complete.caller, complete.method, complete.args);
progress && info.on(Event.PROGRESS, progress.caller, progress.method, progress.args);
_resMap[url] = info;
priority = priority < this._maxPriority ? priority : this._maxPriority - 1;
this._resInfos[priority].push(info);
_next();
} else {
complete && info._createListener(Event.COMPLETE, complete.caller, complete.method, complete.args, false, false);
progress && info._createListener(Event.PROGRESS, progress.caller, progress.method, progress.args, false, false);
}
}
return this;
}
private function _next():void {
if (this._loaderCount >= this.maxLoader) return;
for (var i:int = 0; i < this._maxPriority; i++) {
var infos:Array = this._resInfos[i];
while (infos.length > 0) {
var info:ResInfo = infos.shift();
if (info) return _doLoad(info);
}
}
_loaderCount || event(Event.COMPLETE);
}
private function _doLoad(resInfo:ResInfo):void {
this._loaderCount++;
var loader:Loader = this._loaders.length ? this._loaders.pop() : new Loader();
loader.on(Event.COMPLETE, null, onLoaded);
loader.on(Event.PROGRESS, null, function(num:Number):void {
resInfo.event(Event.PROGRESS, num);
});
loader.on(Event.ERROR, null, function(msg:*):void {
onLoaded(null);
});
var _this:LoaderManager = this;
function onLoaded(data:* = null):void {
loader.offAll();
loader._data = null;
loader._customParse = false;
_this._loaders.push(loader);
_this._endLoad(resInfo, data is Array ? [data] : data);
_this._loaderCount--;
_this._next();
}
loader._class = resInfo.clas;
loader.load(resInfo.url, resInfo.type, resInfo.cache, resInfo.group, resInfo.ignoreCache);
}
private function _endLoad(resInfo:ResInfo, content:*):void {
//如果加载后为空,放入队列末尾重试
var url:String = resInfo.url;
if (content == null) {
var errorCount:int = this._failRes[url] || 0;
if (errorCount < this.retryNum) {
console.warn("[warn]Retry to load:", url);
this._failRes[url] = errorCount + 1;
Laya.timer.once(retryDelay, this, _addReTry, [resInfo], false);
return;
} else {
console.warn("[error]Failed to load:", url);
event(Event.ERROR, url);
}
}
if (_failRes[url]) _failRes[url] = 0;
delete _resMap[url];
resInfo.event(Event.COMPLETE, content);
resInfo.offAll();
_infoPool.push(resInfo);
}
private function _addReTry(resInfo:ResInfo):void {
this._resInfos[this._maxPriority - 1].push(resInfo);
_next();
}
/**
* 清理指定资源地址缓存。
* @param url 资源地址。
* @param forceDispose 是否强制销毁,有些资源是采用引用计数方式销毁,如果forceDispose=true,则忽略引用计数,直接销毁,比如Texture,默认为false
*/
public function clearRes(url:String, forceDispose:Boolean = false):void {
Loader.clearRes(url, forceDispose);
}
/**
* 获取指定资源地址的资源。
* @param url 资源地址。
* @return 返回资源。
*/
public function getRes(url:String):* {
return Loader.getRes(url);
}
/**
* 缓存资源。
* @param url 资源地址。
* @param data 要缓存的内容。
*/
public function cacheRes(url:String, data:*):void {
Loader.cacheRes(url, data);
}
/**
* 销毁Texture使用的图片资源,保留texture壳,如果下次渲染的时候,发现texture使用的图片资源不存在,则会自动恢复
* 相比clearRes,clearTextureRes只是清理texture里面使用的图片资源,并不销毁texture,再次使用到的时候会自动恢复图片资源
* 而clearRes会彻底销毁texture,导致不能再使用;clearTextureRes能确保立即销毁图片资源,并且不用担心销毁错误,clearRes则采用引用计数方式销毁
* 【注意】如果图片本身在自动合集里面(默认图片小于512*512),内存是不能被销毁的,此图片被大图合集管理器管理
* @param url 图集地址或者texture地址,比如 Loader.clearTextureRes("res/atlas/comp.atlas"); Loader.clearTextureRes("hall/bg.jpg");
*/
public function clearTextureRes(url:String):void {
Loader.clearTextureRes(url);
}
/**
* 设置资源分组。
* @param url 资源地址。
* @param group 分组名
*/
public function setGroup(url:String, group:String):void {
Loader.setGroup(url, group);
}
/**
* 根据分组清理资源。
* @param group 分组名
*/
public function clearResByGroup(group:String):void {
Loader.clearResByGroup(group);
}
/**
* @private
* 缓存资源。
* @param url 资源地址。
* @param data 要缓存的内容。
*/
public static function cacheRes(url:String, data:*):void {
Loader.cacheRes(url, data);
}
/** 清理当前未完成的加载,所有未加载的内容全部停止加载。*/
public function clearUnLoaded():void {
//回收Handler
for (var i:int = 0; i < this._maxPriority; i++) {
var infos:Array = this._resInfos[i];
for (var j:int = infos.length - 1; j > -1; j--) {
var info:ResInfo = infos[j];
if (info) {
info.offAll();
_infoPool.push(info);
}
}
infos.length = 0;
}
this._loaderCount = 0;
_resMap = {};
}
/**
* 根据地址集合清理掉未加载的内容
* @param urls 资源地址集合
*/
public function cancelLoadByUrls(urls:Array):void {
if (!urls) return;
for (var i:int = 0, n:int = urls.length; i < n; i++) {
cancelLoadByUrl(urls[i]);
}
}
/**
* 根据地址清理掉未加载的内容
* @param url 资源地址
*/
public function cancelLoadByUrl(url:String):void {
for (var i:int = 0; i < this._maxPriority; i++) {
var infos:Array = this._resInfos[i];
for (var j:int = infos.length - 1; j > -1; j--) {
var info:ResInfo = infos[j];
if (info && info.url === url) {
infos[j] = null;
info.offAll();
_infoPool.push(info);
}
}
}
if (_resMap[url]) delete _resMap[url];
}
/**
* @private
* 加载数组里面的资源。
* @param arr 简单:["a.png","b.png"],复杂[{url:"a.png",type:Loader.IMAGE,size:100,priority:1},{url:"b.json",type:Loader.JSON,size:50,priority:1}]*/
private function _loadAssets(arr:Array, complete:Handler = null, progress:Handler = null, type:String = null, priority:int = 1, cache:Boolean = true, group:String = null):LoaderManager {
var itemCount:int = arr.length;
var loadedCount:int = 0;
var totalSize:int = 0;
var items:Array = [];
var success:Boolean = true;
for (var i:int = 0; i < itemCount; i++) {
var item:Object = arr[i];
if (item is String) item = {url: item, type: type, size: 1, priority: priority};
if (!item.size) item.size = 1;
item.progress = 0;
totalSize += item.size;
items.push(item);
var progressHandler:* = progress ? Handler.create(null, loadProgress, [item], false) : null;
var completeHandler:* = (complete || progress) ? Handler.create(null, loadComplete, [item]) : null;
load(item.url, completeHandler, progressHandler, item.type, item.priority || 1, cache, item.group || group);
}
function loadComplete(item:Object, content:* = null):void {
loadedCount++;
item.progress = 1;
if (!content) success = false;
if (loadedCount === itemCount && complete) {
complete.runWith(success);
}
}
function loadProgress(item:Object, value:Number):void {
if (progress != null) {
item.progress = value;
var num:Number = 0;
for (var j:int = 0; j < items.length; j++) {
var item1:Object = items[j];
num += item1.size * item1.progress;
}
var v:Number = num / totalSize;
progress.runWith(v);
}
}
return this;
}
}
}
import laya.events.EventDispatcher;
class ResInfo extends EventDispatcher {
public var url:String;
public var type:String;
public var cache:Boolean;
public var group:String;
public var ignoreCache:Boolean;
public var clas:*;
} | {
"pile_set_name": "Github"
} |
changelog:
- type: FIX
issueLink: https://github.com/solo-io/gloo/issues/3344
description: >
URL-encoded data can now be extracted verbatim by path and
header extractors.
| {
"pile_set_name": "Github"
} |
// This file is autogenerated via the `commonjs` Grunt task. You can require() this file in a CommonJS environment.
require('../../js/transition.js')
require('../../js/alert.js')
require('../../js/button.js')
require('../../js/carousel.js')
require('../../js/collapse.js')
require('../../js/dropdown.js')
require('../../js/modal.js')
require('../../js/tooltip.js')
require('../../js/popover.js')
require('../../js/scrollspy.js')
require('../../js/tab.js')
require('../../js/affix.js') | {
"pile_set_name": "Github"
} |
{
"images" : [
{
"idiom" : "universal",
"filename" : "VideoPauseFill.png",
"scale" : "1x"
},
{
"idiom" : "universal",
"filename" : "[email protected]",
"scale" : "2x"
},
{
"idiom" : "universal",
"filename" : "[email protected]",
"scale" : "3x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
} | {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2015, 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
*
* Defines constants for XML processing.
*
* @since 1.5
*
*/
package javax.xml;
| {
"pile_set_name": "Github"
} |
/**
* Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
* Build: `lodash modularize modern exports="node" -o ./modern/`
* Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
* Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <http://lodash.com/license>
*/
module.exports = {
'compact': require('./arrays/compact'),
'difference': require('./arrays/difference'),
'drop': require('./arrays/rest'),
'findIndex': require('./arrays/findIndex'),
'findLastIndex': require('./arrays/findLastIndex'),
'first': require('./arrays/first'),
'flatten': require('./arrays/flatten'),
'head': require('./arrays/first'),
'indexOf': require('./arrays/indexOf'),
'initial': require('./arrays/initial'),
'intersection': require('./arrays/intersection'),
'last': require('./arrays/last'),
'lastIndexOf': require('./arrays/lastIndexOf'),
'object': require('./arrays/zipObject'),
'pull': require('./arrays/pull'),
'range': require('./arrays/range'),
'remove': require('./arrays/remove'),
'rest': require('./arrays/rest'),
'sortedIndex': require('./arrays/sortedIndex'),
'tail': require('./arrays/rest'),
'take': require('./arrays/first'),
'union': require('./arrays/union'),
'uniq': require('./arrays/uniq'),
'unique': require('./arrays/uniq'),
'unzip': require('./arrays/zip'),
'without': require('./arrays/without'),
'xor': require('./arrays/xor'),
'zip': require('./arrays/zip'),
'zipObject': require('./arrays/zipObject')
};
| {
"pile_set_name": "Github"
} |
<!--- CircuiTikz - Changelog --->
The major changes among the different circuitikz versions are listed here. See <https://github.com/circuitikz/circuitikz/commits> for a full list of changes.
* Version 1.2.4 (unreleased)
- Bumped version number
* Version 1.2.3 (2020-08-07)
Several fixes and small enhancement all over the map, changes in the documentation to better explain the reasons and effect of the path-building changes of 1.2.0 and 1.2.1.
- added a Mach-Zehnder-Modulator block symbol as node `mzm` by user `@dl1chb`
- add an `open poles fill` option to simplify circuits where the background is different from white
- restyled the FAQ and added the explanation of "gaps with `nodes`" that happens again after 1.2.1
- Fixed size of "not circle" in flip-flops to match european style `not circle` when used without the IEEE style
- Block anchors: add border anchors for round elements and deprecate old 1, 2, 3, 4 anchors
- Fixed some bipole border size to avoid overlapping labels; document it
* Version 1.2.2 (2020-07-15)
Bug-fix release: coordinate name leakage. The node and coordinate names are global; the internal coordinate names have been made stronger.
* Version 1.2.1 (2020-07-06)
Several changes, both internal and user-visible. These are quite risky, although they *should* be backward-compatible (if the circuit code is correct).
From the user point of view:
- there is now a new style of voltages ("raised American")
- a powerful mechanism for customize voltages, current and flows has been added.
The internal changes are basically the re-implementation of the macros that draw the path elements (`to[...]`), which have been completely rewritten. Please be sure to read the possible incompatibilities in the manual (section 1.9).
- Added access to voltages, currents and flows anchors
- Added "raised american" voltage style
- Rewrite of the path generation macros
- Several small bugs fixed (no one ever used some "f^>" options...)
* Version 1.2.0 (2020-06-21)
In this release, the big change is the rewriting of the voltages output routine. Now all voltage options (american, european, and straight) take into account the shape (square border) of the component. The adjusting parameters are now (at least for passive elements) acting in similar way for all the options, too.
- Bumped version number to 1.2 (potentially incompatible changes!)
- Added 1.1.2 checkpoint
- New path-style not, buffer, and Schmitt logic ports
- New tutorial (using the "inline not" component)
- Voltage output routine rewrite; now it takes into account the shape of the component also for "american" and "straight" voltages
- Several fixes in the logic ports: fixed IEEE `invschmitt` name, added symmetry to the three-style shorthands for the ports, and so on
- Fixed a gross bug in square poles anchor borders
- Fixed size of not circles in flip-flops (based on logic ports style)
- Fixed the order of initial options, to avoid "european" overwriting single options
* Version 1.1.2 (2020-05-17)
- Blocks and component for three-phase networks (3-lines wire, AC/DC and DC/AC converters blocks and grid node block) added by user `@olfline` on GitHub
- added transformer sources with optional vector groups for three-phase networks by `@olfline` on Github
- added subsections to the examples
- fixed position of american voltages on open circuits (suggested by user `@rhandley` on GitHub)
* Version 1.1.1 (2020-04-24)
One-line bugfix release for the IEEE ports "not" circle thickness
* Version 1.1.0 (2020-04-19)
Version bumped to 1.1 because the new logic ports are quite a big addition: now there is a new style for logic ports, conforming to IEEE recommendations.
Several minor additions all over the map too.
- added IEEE standard logic ports suggested by user Jason-s on GitHub
- added configurability to european logic port "not" output symbol, suggested by j-hap on GitHub
- added `inerter` component by user Tadashi on GitHub
- added variable outer base height for IGBT, suggested by user RA-EE on GitHub
- added configurable "+" and "-" signs on american-style voltage generators
- text on amplifiers can be positioned to the left or centered
* Version 1.0.2 (2020-03-22)
- added Schottky transistors (thanks to a suggestion by Jérôme Monclard on GitHub)
- fixed formatting of `CHANGELOG.md`
* Version 1.0.1 (2020-02-22)
Minor fixes and addition to 1.0, in time to catch the freeze for TL2020.
- add v1.0 version snapshots
- added crossed generic impedance (suggested by Radványi Patrik Tamás)
- added open barrier bipole (suggested by Radványi Patrik Tamás)
- added two flags to flip the direction of light's arrows on LED and photodiode (suggested by karlkappe on GitHub)
- added a special key to help with precision loss in case of fractional scaling (thanks to AndreaDiPietro92 on GitHub for noticing and reporting, and to Schrödinger's cat for finding a fix)
- fixed a nasty bug for the flat file generation for ConTeXt
* Version 1.0 (2020-02-04)
And finally... version 1.0 (2020-02-04) of `circuitikz` is released.
The main updates since version 0.8.3, which was the last release before Romano started co-maintaining the project, are the following --- part coded by Romano, part by several collaborators around the internet:
- The manual has been reorganized and extended, with the addition of a tutorial part; tens of examples have been added all over the map.
- Around 74 new shapes where added. Notably, now there are chips, mux-demuxes, multi-terminal transistors, several types of switches, flip-flops, vacuum tubes, 7-segment displays, more amplifiers, and so on.
- Several existing shapes have been enhanced; for example, logic gates have a variable number of inputs, transistors are more configurable, resistors can be shaped more, and more.
- You can style your circuit, changing relative sizes, default thickness and fill color, and more details of how you like your circuit to look; the same you can do with labels (voltages, currents, names of components and so on).
- A lot of bugs have been squashed; especially the (very complex) voltage direction conundrum has been clarified and you can choose your preferred style here too.
A detailed list of changes can be seen below.
* Version 1.0.0-pre3 (not released)
- Added a Reed switch
- Put the copyright and license notices on all files and update them
- Fixed the loading of style; we should not guard against reload
* Version 1.0.0-pre2 (2020-01-23)
**Really** last additions toward the 1.0.0 version. The most important change is the addition of multiplexer and de-multiplexers; also added the multi-wires (bus) markers.
- Added mux-demux shapes
- Added the possibility to suppress the input leads in logic gates
- Added multiple wires markers
- Added a style to switch off the automatic rotation of instruments
- Changed the shape of the or-type american logic ports (reversible with a flag)
* Version 1.0.0-pre1 (2019-12-22)
Last additions before the long promised 1.0! In this pre-release we feature a flip-flop library, a revamped configurability of amplifiers (and a new amplifier as a bonus) and some bug fix around the clock.
- Added a flip-flop library
- Added a single-input generic amplifier with the same dimension as "plain amp"
- Added border anchors to amplifiers
- Added the possibility (expert only!) to add transparency to poles (after a suggestion from user @matthuszagh on GitHub)
- Make plus and minus symbol on amplifiers configurable
- Adjusted the position of text in triangular amplifiers
- Fixed "plain amp" not respecting "noinv input up"
- Fixed minor incompatibility with ConTeXt and Plain TeX
* Version 0.9.7 (2019-12-01)
The important thing in this release is the new position of transistor's labels; see the manual for details.
- Fix the position of transistor's text. There is an option to revert to the old behavior.
- Added anchors for adding circuits (like snubbers) to the flyback diodes in transistors (after a suggestion from @EdAlvesSilva on GitHub).
* Version 0.9.6 (2019-11-09)
The highlights of this release are the new multiple terminals BJTs and several stylistic addition and fixes; if you like to pixel-peep, you will like the fixed transistors arrows. Additionally, the transformers are much more configurable now, the "pmos" and "nmos" elements have grown an optional bulk connection, and you can use the "flow" arrows outside of a path.
Several small and less small bugs have been fixed.
- Added multi-collectors and multi-emitter bipolar transistors
- Added the possibility to style each one of the two coils in a transformer independently
- Added bulk connection to normal MOSFETs and the respective anchors
- Added "text" anchor to the flow arrows, to use them alone in a consistent way
- Fixed flow, voltage, and current arrow positioning when "auto" is active on the path
- Fixed transistors arrows overshooting the connection point, added a couple of anchors
- Fixed a spelling error on op-amp key "noinv input down"
- Fixed a problem with "quadpoles style=inner" and "transformer core" having the core lines running too near
* Version 0.9.5 (2019-10-12)
This release basically add features to better control labels, voltages and similar text "ornaments" on bipoles, plus some other minor things.
On the bug fixes side, a big incompatibility with ConTeXt has been fixed, thanks to help from `@TheTeXnician` and `@hmenke` on `github.com`.
- Added a "midtap" anchor for coils and exposed the inner coils shapes in the transformers
- Added a "curved capacitor" with polarity coherent with "ecapacitor"
- Added the possibility to apply style and access the nodes of bipole's text ornaments (labels, annotations, voltages, currents and flows)
- Added the possibility to move the wiper in resistive potentiometers
- Added a command to load and set a style in one go
- Fixed internal font changing commands for compatibility with ConTeXt
- Fixed hardcoded black color in "elko" and "elmech"
* Version 0.9.4 (2019-08-30)
This release introduces two changes: a big one, which is the styling of the components (please look at the manual for details) and a change to how voltage labels and arrows are positioned. This one should be backward compatible *unless* you used `voltage shift` introduced in 0.9.0, which was broken when using the global `scale` parameter.
The styling additions are quite big, and, although in principle they are backward compatible, you can find corner cases where they are not, especially if you used to change parameters for `pgfcirc.defines.tex`; so a snapshot for the 0.9.3 version is available.
- Fixed a bug with "inline" gyrators, now the circle will not overlap
- Fixed a bug in input anchors of european not ports
- Fixed "tlinestub" so that it has the same default size than "tline" (TL)
- Fixed the "transistor arrows at end" feature, added to styling
- Changed the behavior of "voltage shift" and voltage label positioning to be more robust
- Added several new anchors for "elmech" element
- Several minor fixes in some component drawings to allow fill and thickness styles
- Add 0.9.3 version snapshots.
- Added styling of relative size of components (at a global or local level)
- Added styling for fill color and thickeness
- Added style files
* Version 0.9.3 (2019-07-13)
- Added the option to have "dotless" P-MOS (to use with arrowmos option)
- Fixed a (puzzling) problem with coupler2
- Fixed a compatibility problem with newer PGF (>3.0.1a)
* Version 0.9.2 (2019-06-21)
- (hopefully) fixed ConTeXt compatibility. Most new functionality is not tested; testers and developers for the ConTeXt side are needed.
- Added old ConTeXt version for 0.8.3
- Added tailless ground
* Version 0.9.1 (2019-06-16)
- Added old LaTeX versions for 0.8.3, 0.7, 0.6 and 0.4
- Added the option to have inline transformers and gyrators
- Added rotary switches
- Added more configurable bipole nodes (connectors) and more shapes
- Added 7-segment displays
- Added vacuum tubes by J. op den Brouw
- Made the open shape of dcisources configurable
- Made the arrows on vcc and vee configurable
- Fixed anchors of diamondpole nodes
- Fixed a bug (#205) about unstable anchors in the chip components
- Fixed a regression in label placement for some values of scaling
- Fixed problems with cute switches anchors
* Version 0.9.0 (2019-05-10)
- Added Romano Giannetti as contributor
- Added a CONTRIBUTING file
- Added options for solving the voltage direction problems.
- Adjusted ground symbols to better match ISO standard, added new symbols
- Added new sources (cute european versions, noise sources)
- Added new types of amplifiers, and option to flip inputs and outputs
- Added bidirectional diodes (diac) thanks to Andre Lucas Chinazzo
- Added L,R,C sensors (with european, american and cute variants)
- Added stacked labels (thanks to the original work by Claudio Fiandrino)
- Make the position of voltage symbols adjustable
- Make the position of arrows in FETs and BJTs adjustable
- Added chips (DIP, QFP) with a generic number of pins
- Added special anchors for transformers (and fixed the wrong center anchor)
- Changed the logical port implementation to multiple inputs (thanks to John Kormylo) with border anchors.
- Added several symbols: bulb, new switches, new antennas, loudspeaker, microphone, coaxial connector, viscoelastic element
- Make most components fillable
- Added the oscilloscope component and several new instruments
- Added viscoelastic element
- Added a manual section on how to define new components
- Fixed american voltage symbols and allow to customize them
- Fixed placement of straightlabels in several cases
- Fixed a bug about straightlabels (thanks to @fotesan)
- Fixed labels spacing so that they are independent on scale factor
- Fixed the position of text labels in amplifiers
* Version 0.8.3 (2017-05-28)
- Removed unwanted lines at to-paths if the starting point is a node without a explicit anchor.
- Fixed scaling option, now all parts are scaled by bipoles/length
- Surge arrester appears no more if a to path is used without []-options
- Fixed current placement now possible with paths at an angle of around 280°
- Fixed voltage placement now possible with paths at an angle of around 280°
- Fixed label and annotation placement (at some angles position not changable)
- Adjustable default distance for straight-voltages: 'bipoles/voltage/straight label distance'
- Added Symbol for bandstop filter
- New annotation type to show flows using f=... like currents, can be used for thermal, power or current flows
* Version 0.8.2 (2017-05-01)
- Fixes pgfkeys error using alternatively specified mixed colors(see pgfplots manual section "4.7.5 Colors")
- Added new switches "ncs" and "nos"
- Reworked arrows at spst-switches
- Fixed direction of controlled american voltage source
- "v<=" and "i<=" do not rotate the sources anymore(see them as "counting direction indication", this can be different then the shape orientation); Use the option "invert" to change the direction of the source/apperance of the shape.
- current label "i=" can now be used independent of the regular label "l=" at current sources
- rewrite of current arrow placement. Current arrows can now also be rotated on zero-length paths
- New DIN/EN compliant operational amplifier symbol "en amp"
* Version 0.8.1 (2017-03-25)
- Fixed unwanted line through components if target coordinate is a name of a node
- Fixed position of labels with subscript letters.
- Absolute distance calculation in terms of ex at rotated labels
- Fixed label for transistor paths (no label drawn)
* Version 0.8 (2017-03-08)
- Allow use of voltage label at a [short]
- Correct line joins between path components (to[...])
- New Pole-shape .-. to fill perpendicular joins
- Fixed direction of controlled american current source
- Fixed incorrect scaling of magnetron
- Fixed: Number of american inductor coils not adjustable
- Fixed Battery Symbols and added new battery2 symbol
- Added non-inverting Schmitttrigger
* Version 0.7 (2016-09-08)
- Added second annotation label, showing, e.g., the value of an component
- Added new symbol: magnetron
- Fixed name conflict of diamond shape with tikz.shapes package
- Fixed varcap symbol at small scalings
- New packet-option "straightvoltages, to draw straight(no curved) voltage arrows
- New option "invert" to revert the node direction at paths
- Fixed american voltage label at special sources and battery
- Fixed/rotated battery symbol(longer lines by default positive voltage)
- New symbol Schmitttrigger
* Version 0.6 (2016-06-06)
- Added Mechanical Symbols (damper,mass,spring)
- Added new connection style diamond, use (d-d)
- Added new sources voosource and ioosource (double zero-style)
- All diode can now drawn in a stroked way, just use globel option "strokediode" or stroke instead of full/empty, or D-. Use this option for compliance with DIN standard EN-60617
- Improved Shape of Diodes:tunnel diode, Zener diode, schottky diode (bit longer lines at cathode)
- Reworked igbt: New anchors G,gate and new L-shaped form Lnigbt, Lpigbt
- Improved shape of all fet-transistors and mirrored p-chan fets as default, as pnp, pmos, pfet are already. This means a backward-incompatibility, but smaller code, because p-channels mosfet are by default in the correct direction(source at top). Just remove the 'yscale=-1' from your p-chan fets at old pictures.
* Version 0.5 (2016-04-24)
- new option boxed and dashed for hf-symbols
- new option solderdot to enable/disable solderdot at source port of some fets
- new parts: photovoltaic source, piezo crystal, electrolytic capacitor, electromechanical device(motor, generator)
- corrected voltage and current direction(option to use old behaviour)
- option to show body diode at fet transistors
* Version 0.4
- minor improvements to documentation
- comply with TDS
- merge high frequency symbols by Stefan Erhardt
- added switch (not opening nor closing)
- added solder dot in some transistors
- improved ConTeXt compatibility
* Version 0.3.1
- different management of color...
- fixed typo in documentation
- fixed an error in the angle computation in voltage and current routines
- fixed problem with label size when scaling a tikz picture
- added gas filled surge arrester
- added compatibility option to work with Tikz's own circuit library
- fixed infinite in arctan computation
* Version 0.3.0
- fixed gate node for a few transistors
- added mixer
- added fully differential op amp (by Kristofer M. Monisit)
- now general settings for the drawing of voltage can be overridden for specific components
- made arrows more homogeneous (either the current one, or latex' bt pgf)
- added the single battery cell
- added fuse and asymmetric fuse
- added toggle switch
- added varistor, photoresistor, thermocouple, push button
- added thermistor, thermistor ptc, thermistor ptc
- fixed misalignment of voltage label in vertical bipoles with names
- added isfet
- added noiseless, protective, chassis, signal and reference grounds (Luigi «Liverpool»)
* Version 0.2.4
- added square voltage source (contributed by Alistair Kwan)
- added buffer and plain amplifier (contributed by Danilo Piazzalunga)
- added squid and barrier (contributed by Cor Molenaar)
- added antenna and transmission line symbols contributed by Leonardo Azzinnari
- added the changeover switch spdt (suggestion of Fabio Maria Antoniali)
- rename of context.tex and context.pdf (thanks to Karl Berry)
- updated the email address
- in documentation, fixed wrong (non-standard) labelling of the axis in an example (thanks to prof. Claudio Beccaria)
- fixed scaling inconsistencies in quadrupoles
- fixed division by zero error on certain vertical paths
- introduced options straighlabels, rotatelabels, smartlabels
* Version 0.2.3
- fixed compatibility problem with label option from tikz
- Fixed resizing problem for shape ground
- Variable capacitor
- polarized capacitor
- ConTeXt support (read the manual!)
- nfet, nigfete, nigfetd, pfet, pigfete, pigfetd (contribution of Clemens Helfmeier and Theodor
Borsche)
- njfet, pjfet (contribution of Danilo Piazzalunga)
- pigbt, nigbt
- *backward incompatibility* potentiometer is now the standard resistor-with-arrow-in-the-middle; the old potentiometer is now known as variable resistor (or vR), similarly to variable inductor and variable capacitor
- triac, thyristor, memristor
- new property "name" for bipoles
- fixed voltage problem for batteries in american voltage mode
- european logic gates
- *backward incompatibility* new american standard inductor. Old american inductor now called "cute inductor"
- *backward incompatibility* transformer now linked with the chosen type of inductor, and version with core, too. Similarly for variable inductor
- *backward incompatibility* styles for selecting shape variants now end are in the plural to avoid conflict with paths
- new placing option for some tripoles (mostly transistors)
- mirror path style
* Version 0.2.2 - 20090520
- Added the shape for lamps.
- Added options \texttt{europeanresistor}, \texttt{europeaninductor}, \texttt{americanresistor} and \texttt{americaninductor}, with corresponding styles.
- FIXED: error in transistor arrow positioning and direction under negative \texttt{xscale} and \texttt{yscale}.
* Version 0.2.1 - 20090503
- Op-amps added
- added options arrowmos and noarrowmos, to add arrows to pmos and nmos
* Version 0.2 - 20090417
First public release on CTAN
- *Backward incompatibility*: labels ending with \texttt{:}\textit{angle} are not parsed for positioning anymore.
- Full use of \TikZ\ keyval features.
- White background is not filled anymore: now the network can be drawn on a background picture as well.
- Several new components added (logical ports, transistors, double bipoles, \ldots).
- Color support.
- Integration with {\ttfamily siunitx}.
- Voltage, american style.
- Better code, perhaps. General cleanup at the very least.
* Version 0.1 - 2007-10-29
First public release
| {
"pile_set_name": "Github"
} |
import _ from 'lodash';
import os from 'os';
import methods, { getAndroidBinaryPath } from './tools/index.js';
import {
DEFAULT_ADB_EXEC_TIMEOUT, requireSdkRoot, getSdkRootFromEnv
} from './helpers';
import log from './logger.js';
const DEFAULT_ADB_PORT = 5037;
const DEFAULT_OPTS = {
sdkRoot: getSdkRootFromEnv() || null,
udid: null,
appDeviceReadyTimeout: null,
useKeystore: null,
keystorePath: null,
keystorePassword: null,
keyAlias: null,
keyPassword: null,
executable: {path: 'adb', defaultArgs: []},
tmpDir: os.tmpdir(),
curDeviceId: null,
emulatorPort: null,
logcat: null,
binaries: {},
instrumentProc: null,
suppressKillServer: null,
jars: {},
adbPort: DEFAULT_ADB_PORT,
adbExecTimeout: DEFAULT_ADB_EXEC_TIMEOUT,
remoteAppsCacheLimit: 10,
buildToolsVersion: null,
allowOfflineDevices: false,
};
class ADB {
constructor (opts = {}) {
Object.assign(this, opts);
_.defaultsDeep(this, _.cloneDeep(DEFAULT_OPTS));
if (opts.remoteAdbHost) {
this.executable.defaultArgs.push('-H', opts.remoteAdbHost);
}
// TODO figure out why we have this option as it does not appear to be
// used anywhere. Probably deprecate in favor of simple opts.adbPort
if (opts.remoteAdbPort) {
this.adbPort = opts.remoteAdbPort;
}
this.executable.defaultArgs.push('-P', this.adbPort);
}
}
ADB.createADB = async function createADB (opts) {
const adb = new ADB(opts);
adb.sdkRoot = await requireSdkRoot(adb.sdkRoot);
await adb.getAdbWithCorrectAdbPath();
try {
await adb.adbExec(['start-server']);
} catch (e) {
log.warn(e.stderr || e.message);
}
return adb;
};
// add all the methods to the ADB prototype
for (const [fnName, fn] of _.toPairs(methods)) {
ADB.prototype[fnName] = fn;
}
export default ADB;
export { ADB, DEFAULT_ADB_PORT, getAndroidBinaryPath, getSdkRootFromEnv };
| {
"pile_set_name": "Github"
} |
#!/usr/bin/env python3
# ABOUT
# Artisan Dialogs
# LICENSE
# This program or module is free software: you can redistribute it and/or
# modify it under the terms of the GNU General Public License as published
# by the Free Software Foundation, either version 2 of the License, or
# version 3 of the License, or (at your option) any later versison. It is
# provided for educational purposes and is distributed in the hope that
# it will be useful, but WITHOUT ANY WARRANTY; without even the implied
# warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
# the GNU General Public License for more details.
# AUTHOR
# Marko Luther, 2020
from artisanlib.util import stringtoseconds
from PyQt5.QtCore import (Qt, pyqtSignal, pyqtSlot)
from PyQt5.QtWidgets import (QLabel, QComboBox, QTextEdit, QDoubleSpinBox, QTableWidgetItem, QSizePolicy, QLCDNumber)
from PyQt5.QtGui import QFontMetrics
class MyQComboBox(QComboBox):
def __init__(self, *args, **kwargs):
super(MyQComboBox, self).__init__(*args, **kwargs)
self.setFocusPolicy(Qt.StrongFocus)
self.setSizeAdjustPolicy(QComboBox.AdjustToContents)
def wheelEvent(self, *args, **kwargs):
if self.hasFocus():
return QComboBox.wheelEvent(self, *args, **kwargs)
class MyQDoubleSpinBox(QDoubleSpinBox):
def __init__(self, *args, **kwargs):
super(MyQDoubleSpinBox, self).__init__(*args, **kwargs)
self.setFocusPolicy(Qt.StrongFocus)
def wheelEvent(self, *args, **kwargs):
if self.hasFocus():
return QDoubleSpinBox.wheelEvent(self, *args, **kwargs)
# we re-direct the mouse double-click event to the standard mouse press event and add
# the (at least in PyQt 5.12.2/5.12.3) missing mouse release event
# which had the effect that a double click an DoubleSpinBox arrow in the Cup Profile dialog
# leads to a non-terminating sequence of setvalue() calls until the end of the spinner is reached.
# Note: a triple click still has this effect
def mouseDoubleClickEvent(self, event):
super(MyQDoubleSpinBox, self).mouseReleaseEvent(event)
super(MyQDoubleSpinBox, self).mouseDoubleClickEvent(event)
super(MyQDoubleSpinBox, self).mouseReleaseEvent(event)
class MyTableWidgetItemQLineEdit(QTableWidgetItem):
__slots__ = ['sortKey'] # save some memory by using slots
def __init__(self, sortKey):
#call custom constructor with UserType item type
#QTableWidgetItem.__init__(self, "", QTableWidgetItem.UserType)
super(QTableWidgetItem,self).__init__("", QTableWidgetItem.UserType)
self.sortKey = sortKey
#Qt uses a simple < check for sorting items, override this to use the sortKey
def __lt__(self, other):
a = self.sortKey.text()
b = other.sortKey.text()
if len(a) == 5 and len(b) == 5 and a[2] == ":" and b[2] == ":":
# we compare times
return stringtoseconds(a) < stringtoseconds(b)
else:
try:
# if those are numbers
return int(a) < int(b)
except:
# else we do a string compare
return a < b
class MyTableWidgetItemInt(QTableWidgetItem):
__slots__ = ['sortKey'] # save some memory by using slots
def __init__(self, text, sortKey):
super(QTableWidgetItem,self).__init__(text, QTableWidgetItem.UserType)
self.sortKey = sortKey
#Qt uses a simple < check for sorting items, override this to use the sortKey
def __lt__(self, other):
return self.sortKey < other.sortKey
class MyTableWidgetItemQCheckBox(QTableWidgetItem):
__slots__ = ['sortKey'] # save some memory by using slots
def __init__(self, sortKey):
#call custom constructor with UserType item type
super(QTableWidgetItem,self).__init__("", QTableWidgetItem.UserType)
self.sortKey = sortKey
#Qt uses a simple < check for sorting items, override this to use the sortKey
def __lt__(self, other):
return self.sortKey.isChecked() < other.sortKey.isChecked()
class MyTableWidgetItemQComboBox(QTableWidgetItem):
__slots__ = ['sortKey'] # save some memory by using slots
def __init__(self, sortKey):
#call custom constructor with UserType item type
super(QTableWidgetItem,self).__init__("", QTableWidgetItem.UserType)
self.sortKey = sortKey
#Qt uses a simple < check for sorting items, override this to use the sortKey
def __lt__(self, other):
return str(self.sortKey.currentText()) < str(other.sortKey.currentText())
# QLabel that automatically resizes its text font
class MyQLabel(QLabel):
__slots__ = [] # save some memory by using slots
def __init__(self, *args, **kargs):
super(MyQLabel, self).__init__(*args, **kargs)
self.setSizePolicy(QSizePolicy(QSizePolicy.Ignored,QSizePolicy.Ignored))
self.setMinSize(14)
def setMinSize(self, minfs):
f = self.font()
f.setPixelSize(minfs)
br = QFontMetrics(f).boundingRect(self.text())
self.setMinimumSize(br.width(), br.height())
def resizeEvent(self, event):
super(MyQLabel, self).resizeEvent(event)
if not self.text():
return
#--- fetch current parameters ----
f = self.font()
cr = self.contentsRect()
#--- iterate to find the font size that fits the contentsRect ---
dw = event.size().width() - event.oldSize().width() # width change
dh = event.size().height() - event.oldSize().height() # height change
fs = max(f.pixelSize(), 1)
while True:
f.setPixelSize(fs)
br = QFontMetrics(f).boundingRect(self.text())
if dw >= 0 and dh >= 0: # label is expanding
if br.height() <= cr.height() and br.width() <= cr.width():
fs += 1
else:
f.setPixelSize(max(fs - 1, 1)) # backtrack
break
else: # label is shrinking
if br.height() > cr.height() or br.width() > cr.width():
fs -= 1
else:
break
if fs < 1: break
#--- update font size ---
self.setFont(f)
class ClickableQLabel(QLabel):
clicked = pyqtSignal()
left_clicked = pyqtSignal()
right_clicked = pyqtSignal()
def __init__(self, *args, **kwargs):
super(ClickableQLabel, self).__init__(*args, **kwargs)
def mousePressEvent(self, event):
self.clicked.emit()
if event.button() == Qt.LeftButton:
self.left_clicked.emit()
elif event.button() == Qt.RightButton:
self.right_clicked.emit()
class MyQLCDNumber(QLCDNumber):
clicked = pyqtSignal()
def __init__(self, *args, **kwargs):
super(MyQLCDNumber, self).__init__(*args, **kwargs)
def mousePressEvent(self, event):
self.clicked.emit()
# this one emits a clicked event on right-clicks and an editingFinished event when the text was changed and the focus got lost
class ClickableTextEdit(QTextEdit):
clicked = pyqtSignal()
editingFinished = pyqtSignal()
receivedFocus = pyqtSignal()
def __init__(self, *args, **kwargs):
super(ClickableTextEdit, self).__init__(*args, **kwargs)
self._changed = False
self.setTabChangesFocus(True)
self.textChanged.connect(self._handle_text_changed)
def mousePressEvent(self, event):
super(ClickableTextEdit, self).mousePressEvent(event)
if event.modifiers() == Qt.ControlModifier:
self.clicked.emit()
def focusInEvent(self, event):
super(ClickableTextEdit, self).focusInEvent(event)
self.receivedFocus.emit()
def focusOutEvent(self, event):
if self._changed:
self.editingFinished.emit()
super(ClickableTextEdit, self).focusOutEvent(event)
@pyqtSlot()
def _handle_text_changed(self):
self._changed = True
def setTextChanged(self, state=True):
self._changed = state
def setNewPlainText(self, text):
QTextEdit.setPlainText(self, text)
self._changed = False
| {
"pile_set_name": "Github"
} |
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Copyright (C) 2013 Kitware, Inc.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the test suite of Qt for Python.
**
** $QT_BEGIN_LICENSE:GPL-EXCEPT$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef TRANSFORM_H
#define TRANSFORM_H
#include "point.h"
#include "libsamplemacros.h"
LIBSAMPLE_API Point
applyHomogeneousTransform(
const Point& in,
double m11, double m12, double m13,
double m21, double m22, double m23,
double m31, double m32, double m33,
bool* okay);
#endif // TRANSFORM_H
| {
"pile_set_name": "Github"
} |
// This file was procedurally generated from the following sources:
// - src/dstr-binding/ary-ptrn-elem-obj-id-init.case
// - src/dstr-binding/default/for-of-let.template
/*---
description: BindingElement with object binding pattern and initializer is used (for-of statement)
esid: sec-for-in-and-for-of-statements-runtime-semantics-labelledevaluation
features: [destructuring-binding]
flags: [generated]
info: |
IterationStatement :
for ( ForDeclaration of AssignmentExpression ) Statement
[...]
3. Return ForIn/OfBodyEvaluation(ForDeclaration, Statement, keyResult,
lexicalBinding, labelSet).
13.7.5.13 Runtime Semantics: ForIn/OfBodyEvaluation
[...]
3. Let destructuring be IsDestructuring of lhs.
[...]
5. Repeat
[...]
h. If destructuring is false, then
[...]
i. Else
i. If lhsKind is assignment, then
[...]
ii. Else if lhsKind is varBinding, then
[...]
iii. Else,
1. Assert: lhsKind is lexicalBinding.
2. Assert: lhs is a ForDeclaration.
3. Let status be the result of performing BindingInitialization
for lhs passing nextValue and iterationEnv as arguments.
[...]
13.3.3.6 Runtime Semantics: IteratorBindingInitialization
BindingElement : BindingPatternInitializer opt
[...]
2. If iteratorRecord.[[done]] is true, let v be undefined.
3. If Initializer is present and v is undefined, then
a. Let defaultValue be the result of evaluating Initializer.
b. Let v be ? GetValue(defaultValue).
4. Return the result of performing BindingInitialization of BindingPattern
with v and environment as the arguments.
---*/
var iterCount = 0;
for (let [{ x, y, z } = { x: 44, y: 55, z: 66 }] of [[]]) {
assert.sameValue(x, 44);
assert.sameValue(y, 55);
assert.sameValue(z, 66);
iterCount += 1;
}
assert.sameValue(iterCount, 1, 'Iteration occurred as expected');
| {
"pile_set_name": "Github"
} |
# Logrus <img src="http://i.imgur.com/hTeVwmJ.png" width="40" height="40" alt=":walrus:" class="emoji" title=":walrus:"/> [](https://travis-ci.org/sirupsen/logrus) [](https://godoc.org/github.com/sirupsen/logrus)
Logrus is a structured logger for Go (golang), completely API compatible with
the standard library logger. [Godoc][godoc].
**Seeing weird case-sensitive problems?** It's in the past been possible to
import Logrus as both upper- and lower-case. Due to the Go package environment,
this caused issues in the community and we needed a standard. Some environments
experienced problems with the upper-case variant, so the lower-case was decided.
Everything using `logrus` will need to use the lower-case:
`github.com/sirupsen/logrus`. Any package that isn't, should be changed.
To fix Glide, see [these
comments](https://github.com/sirupsen/logrus/issues/553#issuecomment-306591437).
For an in-depth explanation of the casing issue, see [this
comment](https://github.com/sirupsen/logrus/issues/570#issuecomment-313933276).
**Are you interested in assisting in maintaining Logrus?** Currently I have a
lot of obligations, and I am unable to provide Logrus with the maintainership it
needs. If you'd like to help, please reach out to me at `simon at author's
username dot com`.
Nicely color-coded in development (when a TTY is attached, otherwise just
plain text):

With `log.SetFormatter(&log.JSONFormatter{})`, for easy parsing by logstash
or Splunk:
```json
{"animal":"walrus","level":"info","msg":"A group of walrus emerges from the
ocean","size":10,"time":"2014-03-10 19:57:38.562264131 -0400 EDT"}
{"level":"warning","msg":"The group's number increased tremendously!",
"number":122,"omg":true,"time":"2014-03-10 19:57:38.562471297 -0400 EDT"}
{"animal":"walrus","level":"info","msg":"A giant walrus appears!",
"size":10,"time":"2014-03-10 19:57:38.562500591 -0400 EDT"}
{"animal":"walrus","level":"info","msg":"Tremendously sized cow enters the ocean.",
"size":9,"time":"2014-03-10 19:57:38.562527896 -0400 EDT"}
{"level":"fatal","msg":"The ice breaks!","number":100,"omg":true,
"time":"2014-03-10 19:57:38.562543128 -0400 EDT"}
```
With the default `log.SetFormatter(&log.TextFormatter{})` when a TTY is not
attached, the output is compatible with the
[logfmt](http://godoc.org/github.com/kr/logfmt) format:
```text
time="2015-03-26T01:27:38-04:00" level=debug msg="Started observing beach" animal=walrus number=8
time="2015-03-26T01:27:38-04:00" level=info msg="A group of walrus emerges from the ocean" animal=walrus size=10
time="2015-03-26T01:27:38-04:00" level=warning msg="The group's number increased tremendously!" number=122 omg=true
time="2015-03-26T01:27:38-04:00" level=debug msg="Temperature changes" temperature=-4
time="2015-03-26T01:27:38-04:00" level=panic msg="It's over 9000!" animal=orca size=9009
time="2015-03-26T01:27:38-04:00" level=fatal msg="The ice breaks!" err=&{0x2082280c0 map[animal:orca size:9009] 2015-03-26 01:27:38.441574009 -0400 EDT panic It's over 9000!} number=100 omg=true
exit status 1
```
#### Case-sensitivity
The organization's name was changed to lower-case--and this will not be changed
back. If you are getting import conflicts due to case sensitivity, please use
the lower-case import: `github.com/sirupsen/logrus`.
#### Example
The simplest way to use Logrus is simply the package-level exported logger:
```go
package main
import (
log "github.com/sirupsen/logrus"
)
func main() {
log.WithFields(log.Fields{
"animal": "walrus",
}).Info("A walrus appears")
}
```
Note that it's completely api-compatible with the stdlib logger, so you can
replace your `log` imports everywhere with `log "github.com/sirupsen/logrus"`
and you'll now have the flexibility of Logrus. You can customize it all you
want:
```go
package main
import (
"os"
log "github.com/sirupsen/logrus"
)
func init() {
// Log as JSON instead of the default ASCII formatter.
log.SetFormatter(&log.JSONFormatter{})
// Output to stdout instead of the default stderr
// Can be any io.Writer, see below for File example
log.SetOutput(os.Stdout)
// Only log the warning severity or above.
log.SetLevel(log.WarnLevel)
}
func main() {
log.WithFields(log.Fields{
"animal": "walrus",
"size": 10,
}).Info("A group of walrus emerges from the ocean")
log.WithFields(log.Fields{
"omg": true,
"number": 122,
}).Warn("The group's number increased tremendously!")
log.WithFields(log.Fields{
"omg": true,
"number": 100,
}).Fatal("The ice breaks!")
// A common pattern is to re-use fields between logging statements by re-using
// the logrus.Entry returned from WithFields()
contextLogger := log.WithFields(log.Fields{
"common": "this is a common field",
"other": "I also should be logged always",
})
contextLogger.Info("I'll be logged with common and other field")
contextLogger.Info("Me too")
}
```
For more advanced usage such as logging to multiple locations from the same
application, you can also create an instance of the `logrus` Logger:
```go
package main
import (
"os"
"github.com/sirupsen/logrus"
)
// Create a new instance of the logger. You can have any number of instances.
var log = logrus.New()
func main() {
// The API for setting attributes is a little different than the package level
// exported logger. See Godoc.
log.Out = os.Stdout
// You could set this to any `io.Writer` such as a file
// file, err := os.OpenFile("logrus.log", os.O_CREATE|os.O_WRONLY, 0666)
// if err == nil {
// log.Out = file
// } else {
// log.Info("Failed to log to file, using default stderr")
// }
log.WithFields(logrus.Fields{
"animal": "walrus",
"size": 10,
}).Info("A group of walrus emerges from the ocean")
}
```
#### Fields
Logrus encourages careful, structured logging through logging fields instead of
long, unparseable error messages. For example, instead of: `log.Fatalf("Failed
to send event %s to topic %s with key %d")`, you should log the much more
discoverable:
```go
log.WithFields(log.Fields{
"event": event,
"topic": topic,
"key": key,
}).Fatal("Failed to send event")
```
We've found this API forces you to think about logging in a way that produces
much more useful logging messages. We've been in countless situations where just
a single added field to a log statement that was already there would've saved us
hours. The `WithFields` call is optional.
In general, with Logrus using any of the `printf`-family functions should be
seen as a hint you should add a field, however, you can still use the
`printf`-family functions with Logrus.
#### Default Fields
Often it's helpful to have fields _always_ attached to log statements in an
application or parts of one. For example, you may want to always log the
`request_id` and `user_ip` in the context of a request. Instead of writing
`log.WithFields(log.Fields{"request_id": request_id, "user_ip": user_ip})` on
every line, you can create a `logrus.Entry` to pass around instead:
```go
requestLogger := log.WithFields(log.Fields{"request_id": request_id, "user_ip": user_ip})
requestLogger.Info("something happened on that request") # will log request_id and user_ip
requestLogger.Warn("something not great happened")
```
#### Hooks
You can add hooks for logging levels. For example to send errors to an exception
tracking service on `Error`, `Fatal` and `Panic`, info to StatsD or log to
multiple places simultaneously, e.g. syslog.
Logrus comes with [built-in hooks](hooks/). Add those, or your custom hook, in
`init`:
```go
import (
log "github.com/sirupsen/logrus"
"gopkg.in/gemnasium/logrus-airbrake-hook.v2" // the package is named "aibrake"
logrus_syslog "github.com/sirupsen/logrus/hooks/syslog"
"log/syslog"
)
func init() {
// Use the Airbrake hook to report errors that have Error severity or above to
// an exception tracker. You can create custom hooks, see the Hooks section.
log.AddHook(airbrake.NewHook(123, "xyz", "production"))
hook, err := logrus_syslog.NewSyslogHook("udp", "localhost:514", syslog.LOG_INFO, "")
if err != nil {
log.Error("Unable to connect to local syslog daemon")
} else {
log.AddHook(hook)
}
}
```
Note: Syslog hook also support connecting to local syslog (Ex. "/dev/log" or "/var/run/syslog" or "/var/run/log"). For the detail, please check the [syslog hook README](hooks/syslog/README.md).
| Hook | Description |
| ----- | ----------- |
| [Airbrake "legacy"](https://github.com/gemnasium/logrus-airbrake-legacy-hook) | Send errors to an exception tracking service compatible with the Airbrake API V2. Uses [`airbrake-go`](https://github.com/tobi/airbrake-go) behind the scenes. |
| [Airbrake](https://github.com/gemnasium/logrus-airbrake-hook) | Send errors to the Airbrake API V3. Uses the official [`gobrake`](https://github.com/airbrake/gobrake) behind the scenes. |
| [Amazon Kinesis](https://github.com/evalphobia/logrus_kinesis) | Hook for logging to [Amazon Kinesis](https://aws.amazon.com/kinesis/) |
| [Amqp-Hook](https://github.com/vladoatanasov/logrus_amqp) | Hook for logging to Amqp broker (Like RabbitMQ) |
| [Bugsnag](https://github.com/Shopify/logrus-bugsnag/blob/master/bugsnag.go) | Send errors to the Bugsnag exception tracking service. |
| [DeferPanic](https://github.com/deferpanic/dp-logrus) | Hook for logging to DeferPanic |
| [Discordrus](https://github.com/kz/discordrus) | Hook for logging to [Discord](https://discordapp.com/) |
| [ElasticSearch](https://github.com/sohlich/elogrus) | Hook for logging to ElasticSearch|
| [Firehose](https://github.com/beaubrewer/logrus_firehose) | Hook for logging to [Amazon Firehose](https://aws.amazon.com/kinesis/firehose/)
| [Fluentd](https://github.com/evalphobia/logrus_fluent) | Hook for logging to fluentd |
| [Go-Slack](https://github.com/multiplay/go-slack) | Hook for logging to [Slack](https://slack.com) |
| [Graylog](https://github.com/gemnasium/logrus-graylog-hook) | Hook for logging to [Graylog](http://graylog2.org/) |
| [Hiprus](https://github.com/nubo/hiprus) | Send errors to a channel in hipchat. |
| [Honeybadger](https://github.com/agonzalezro/logrus_honeybadger) | Hook for sending exceptions to Honeybadger |
| [InfluxDB](https://github.com/Abramovic/logrus_influxdb) | Hook for logging to influxdb |
| [Influxus](http://github.com/vlad-doru/influxus) | Hook for concurrently logging to [InfluxDB](http://influxdata.com/) |
| [Journalhook](https://github.com/wercker/journalhook) | Hook for logging to `systemd-journald` |
| [KafkaLogrus](https://github.com/goibibo/KafkaLogrus) | Hook for logging to kafka |
| [LFShook](https://github.com/rifflock/lfshook) | Hook for logging to the local filesystem |
| [Logentries](https://github.com/jcftang/logentriesrus) | Hook for logging to [Logentries](https://logentries.com/) |
| [Logentrus](https://github.com/puddingfactory/logentrus) | Hook for logging to [Logentries](https://logentries.com/) |
| [Logmatic.io](https://github.com/logmatic/logmatic-go) | Hook for logging to [Logmatic.io](http://logmatic.io/) |
| [Logrusly](https://github.com/sebest/logrusly) | Send logs to [Loggly](https://www.loggly.com/) |
| [Logstash](https://github.com/bshuster-repo/logrus-logstash-hook) | Hook for logging to [Logstash](https://www.elastic.co/products/logstash) |
| [Mail](https://github.com/zbindenren/logrus_mail) | Hook for sending exceptions via mail |
| [Mattermost](https://github.com/shuLhan/mattermost-integration/tree/master/hooks/logrus) | Hook for logging to [Mattermost](https://mattermost.com/) |
| [Mongodb](https://github.com/weekface/mgorus) | Hook for logging to mongodb |
| [NATS-Hook](https://github.com/rybit/nats_logrus_hook) | Hook for logging to [NATS](https://nats.io) |
| [Octokit](https://github.com/dorajistyle/logrus-octokit-hook) | Hook for logging to github via octokit |
| [Papertrail](https://github.com/polds/logrus-papertrail-hook) | Send errors to the [Papertrail](https://papertrailapp.com) hosted logging service via UDP. |
| [PostgreSQL](https://github.com/gemnasium/logrus-postgresql-hook) | Send logs to [PostgreSQL](http://postgresql.org) |
| [Pushover](https://github.com/toorop/logrus_pushover) | Send error via [Pushover](https://pushover.net) |
| [Raygun](https://github.com/squirkle/logrus-raygun-hook) | Hook for logging to [Raygun.io](http://raygun.io/) |
| [Redis-Hook](https://github.com/rogierlommers/logrus-redis-hook) | Hook for logging to a ELK stack (through Redis) |
| [Rollrus](https://github.com/heroku/rollrus) | Hook for sending errors to rollbar |
| [Scribe](https://github.com/sagar8192/logrus-scribe-hook) | Hook for logging to [Scribe](https://github.com/facebookarchive/scribe)|
| [Sentry](https://github.com/evalphobia/logrus_sentry) | Send errors to the Sentry error logging and aggregation service. |
| [Slackrus](https://github.com/johntdyer/slackrus) | Hook for Slack chat. |
| [Stackdriver](https://github.com/knq/sdhook) | Hook for logging to [Google Stackdriver](https://cloud.google.com/logging/) |
| [Sumorus](https://github.com/doublefree/sumorus) | Hook for logging to [SumoLogic](https://www.sumologic.com/)|
| [Syslog](https://github.com/sirupsen/logrus/blob/master/hooks/syslog/syslog.go) | Send errors to remote syslog server. Uses standard library `log/syslog` behind the scenes. |
| [Syslog TLS](https://github.com/shinji62/logrus-syslog-ng) | Send errors to remote syslog server with TLS support. |
| [TraceView](https://github.com/evalphobia/logrus_appneta) | Hook for logging to [AppNeta TraceView](https://www.appneta.com/products/traceview/) |
| [Typetalk](https://github.com/dragon3/logrus-typetalk-hook) | Hook for logging to [Typetalk](https://www.typetalk.in/) |
| [logz.io](https://github.com/ripcurld00d/logrus-logzio-hook) | Hook for logging to [logz.io](https://logz.io), a Log as a Service using Logstash |
| [SQS-Hook](https://github.com/tsarpaul/logrus_sqs) | Hook for logging to [Amazon Simple Queue Service (SQS)](https://aws.amazon.com/sqs/) |
#### Level logging
Logrus has six logging levels: Debug, Info, Warning, Error, Fatal and Panic.
```go
log.Debug("Useful debugging information.")
log.Info("Something noteworthy happened!")
log.Warn("You should probably take a look at this.")
log.Error("Something failed but I'm not quitting.")
// Calls os.Exit(1) after logging
log.Fatal("Bye.")
// Calls panic() after logging
log.Panic("I'm bailing.")
```
You can set the logging level on a `Logger`, then it will only log entries with
that severity or anything above it:
```go
// Will log anything that is info or above (warn, error, fatal, panic). Default.
log.SetLevel(log.InfoLevel)
```
It may be useful to set `log.Level = logrus.DebugLevel` in a debug or verbose
environment if your application has that.
#### Entries
Besides the fields added with `WithField` or `WithFields` some fields are
automatically added to all logging events:
1. `time`. The timestamp when the entry was created.
2. `msg`. The logging message passed to `{Info,Warn,Error,Fatal,Panic}` after
the `AddFields` call. E.g. `Failed to send event.`
3. `level`. The logging level. E.g. `info`.
#### Environments
Logrus has no notion of environment.
If you wish for hooks and formatters to only be used in specific environments,
you should handle that yourself. For example, if your application has a global
variable `Environment`, which is a string representation of the environment you
could do:
```go
import (
log "github.com/sirupsen/logrus"
)
init() {
// do something here to set environment depending on an environment variable
// or command-line flag
if Environment == "production" {
log.SetFormatter(&log.JSONFormatter{})
} else {
// The TextFormatter is default, you don't actually have to do this.
log.SetFormatter(&log.TextFormatter{})
}
}
```
This configuration is how `logrus` was intended to be used, but JSON in
production is mostly only useful if you do log aggregation with tools like
Splunk or Logstash.
#### Formatters
The built-in logging formatters are:
* `logrus.TextFormatter`. Logs the event in colors if stdout is a tty, otherwise
without colors.
* *Note:* to force colored output when there is no TTY, set the `ForceColors`
field to `true`. To force no colored output even if there is a TTY set the
`DisableColors` field to `true`. For Windows, see
[github.com/mattn/go-colorable](https://github.com/mattn/go-colorable).
* All options are listed in the [generated docs](https://godoc.org/github.com/sirupsen/logrus#TextFormatter).
* `logrus.JSONFormatter`. Logs fields as JSON.
* All options are listed in the [generated docs](https://godoc.org/github.com/sirupsen/logrus#JSONFormatter).
Third party logging formatters:
* [`logstash`](https://github.com/bshuster-repo/logrus-logstash-hook). Logs fields as [Logstash](http://logstash.net) Events.
* [`prefixed`](https://github.com/x-cray/logrus-prefixed-formatter). Displays log entry source along with alternative layout.
* [`zalgo`](https://github.com/aybabtme/logzalgo). Invoking the P͉̫o̳̼̊w̖͈̰͎e̬͔̭͂r͚̼̹̲ ̫͓͉̳͈ō̠͕͖̚f̝͍̠ ͕̲̞͖͑Z̖̫̤̫ͪa͉̬͈̗l͖͎g̳̥o̰̥̅!̣͔̲̻͊̄ ̙̘̦̹̦.
You can define your formatter by implementing the `Formatter` interface,
requiring a `Format` method. `Format` takes an `*Entry`. `entry.Data` is a
`Fields` type (`map[string]interface{}`) with all your fields as well as the
default ones (see Entries section above):
```go
type MyJSONFormatter struct {
}
log.SetFormatter(new(MyJSONFormatter))
func (f *MyJSONFormatter) Format(entry *Entry) ([]byte, error) {
// Note this doesn't include Time, Level and Message which are available on
// the Entry. Consult `godoc` on information about those fields or read the
// source of the official loggers.
serialized, err := json.Marshal(entry.Data)
if err != nil {
return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err)
}
return append(serialized, '\n'), nil
}
```
#### Logger as an `io.Writer`
Logrus can be transformed into an `io.Writer`. That writer is the end of an `io.Pipe` and it is your responsibility to close it.
```go
w := logger.Writer()
defer w.Close()
srv := http.Server{
// create a stdlib log.Logger that writes to
// logrus.Logger.
ErrorLog: log.New(w, "", 0),
}
```
Each line written to that writer will be printed the usual way, using formatters
and hooks. The level for those entries is `info`.
This means that we can override the standard library logger easily:
```go
logger := logrus.New()
logger.Formatter = &logrus.JSONFormatter{}
// Use logrus for standard log output
// Note that `log` here references stdlib's log
// Not logrus imported under the name `log`.
log.SetOutput(logger.Writer())
```
#### Rotation
Log rotation is not provided with Logrus. Log rotation should be done by an
external program (like `logrotate(8)`) that can compress and delete old log
entries. It should not be a feature of the application-level logger.
#### Tools
| Tool | Description |
| ---- | ----------- |
|[Logrus Mate](https://github.com/gogap/logrus_mate)|Logrus mate is a tool for Logrus to manage loggers, you can initial logger's level, hook and formatter by config file, the logger will generated with different config at different environment.|
|[Logrus Viper Helper](https://github.com/heirko/go-contrib/tree/master/logrusHelper)|An Helper around Logrus to wrap with spf13/Viper to load configuration with fangs! And to simplify Logrus configuration use some behavior of [Logrus Mate](https://github.com/gogap/logrus_mate). [sample](https://github.com/heirko/iris-contrib/blob/master/middleware/logrus-logger/example) |
#### Testing
Logrus has a built in facility for asserting the presence of log messages. This is implemented through the `test` hook and provides:
* decorators for existing logger (`test.NewLocal` and `test.NewGlobal`) which basically just add the `test` hook
* a test logger (`test.NewNullLogger`) that just records log messages (and does not output any):
```go
import(
"github.com/sirupsen/logrus"
"github.com/sirupsen/logrus/hooks/test"
"github.com/stretchr/testify/assert"
"testing"
)
func TestSomething(t*testing.T){
logger, hook := test.NewNullLogger()
logger.Error("Helloerror")
assert.Equal(t, 1, len(hook.Entries))
assert.Equal(t, logrus.ErrorLevel, hook.LastEntry().Level)
assert.Equal(t, "Helloerror", hook.LastEntry().Message)
hook.Reset()
assert.Nil(t, hook.LastEntry())
}
```
#### Fatal handlers
Logrus can register one or more functions that will be called when any `fatal`
level message is logged. The registered handlers will be executed before
logrus performs a `os.Exit(1)`. This behavior may be helpful if callers need
to gracefully shutdown. Unlike a `panic("Something went wrong...")` call which can be intercepted with a deferred `recover` a call to `os.Exit(1)` can not be intercepted.
```
...
handler := func() {
// gracefully shutdown something...
}
logrus.RegisterExitHandler(handler)
...
```
#### Thread safety
By default Logger is protected by mutex for concurrent writes, this mutex is invoked when calling hooks and writing logs.
If you are sure such locking is not needed, you can call logger.SetNoLock() to disable the locking.
Situation when locking is not needed includes:
* You have no hooks registered, or hooks calling is already thread-safe.
* Writing to logger.Out is already thread-safe, for example:
1) logger.Out is protected by locks.
2) logger.Out is a os.File handler opened with `O_APPEND` flag, and every write is smaller than 4k. (This allow multi-thread/multi-process writing)
(Refer to http://www.notthewizard.com/2014/06/17/are-files-appends-really-atomic/)
| {
"pile_set_name": "Github"
} |
P pack-3d944c0c5bcb6b16209af847052c6ff1a521529d.pack
| {
"pile_set_name": "Github"
} |
<?php
/**
* Copyright Enalean (c) 2018. All rights reserved.
*
* Tuleap and Enalean names and logos are registrated trademarks owned by
* Enalean SAS. All other trademarks or names are properties of their respective
* owners.
*
* This file is a part of Tuleap.
*
* Tuleap is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* Tuleap is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Tuleap. If not, see <http://www.gnu.org/licenses/>.
*/
namespace Tuleap\Tracker\Artifact\ArtifactsDeletion;
use Tuleap\DB\DataAccessObject;
class ArtifactsDeletionDAO extends DataAccessObject
{
public function searchNumberOfArtifactsDeletionsForUserInTimePeriod(
$user_id,
$timestamp
) {
$sql = "SELECT COALESCE(sum(nb_artifacts_deleted), 0)
FROM plugin_tracker_deleted_artifacts
WHERE timestamp >= ?
AND user_id = ?
";
return $this->getDB()->single($sql, [$timestamp, $user_id]);
}
public function recordDeletionForUser(
$user_id,
$timestamp
) {
$sql = "INSERT INTO plugin_tracker_deleted_artifacts(timestamp, user_id, nb_artifacts_deleted)
VALUES(?, ?, 1)
ON DUPLICATE KEY UPDATE
nb_artifacts_deleted = nb_artifacts_deleted + 1;
";
$this->getDB()->run($sql, $timestamp, $user_id);
}
public function deleteOutdatedArtifactsDeletions($limit_timestamp)
{
$sql = "DELETE FROM plugin_tracker_deleted_artifacts
WHERE timestamp <= ?
";
$this->getDB()->run($sql, $limit_timestamp);
}
}
| {
"pile_set_name": "Github"
} |
git fetch upstream
git merge upstream/master | {
"pile_set_name": "Github"
} |
package connection
import (
"bytes"
"encoding/json"
"fmt"
"net"
"net/url"
"os"
"os/user"
"regexp"
"github.com/containers/common/pkg/config"
"github.com/containers/podman/v2/cmd/podman/registry"
"github.com/containers/podman/v2/cmd/podman/system"
"github.com/containers/podman/v2/libpod/define"
"github.com/containers/podman/v2/pkg/domain/entities"
"github.com/containers/podman/v2/pkg/terminal"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/agent"
)
const schemaPattern = "^[A-Za-z][A-Za-z0-9+.-]*:"
var (
addCmd = &cobra.Command{
Use: "add [flags] NAME DESTINATION",
Args: cobra.ExactArgs(2),
Short: "Record destination for the Podman service",
Long: `Add destination to podman configuration.
"destination" is of the form [user@]hostname or
an URI of the form ssh://[user@]hostname[:port]
`,
RunE: add,
Example: `podman system connection add laptop server.fubar.com
podman system connection add --identity ~/.ssh/dev_rsa testing ssh://[email protected]:2222
podman system connection add --identity ~/.ssh/dev_rsa --port 22 production [email protected]
`,
}
cOpts = struct {
Identity string
Port int
UDSPath string
Default bool
}{}
)
func init() {
registry.Commands = append(registry.Commands, registry.CliCommand{
Mode: []entities.EngineMode{entities.ABIMode, entities.TunnelMode},
Command: addCmd,
Parent: system.ConnectionCmd,
})
flags := addCmd.Flags()
flags.IntVarP(&cOpts.Port, "port", "p", 22, "SSH port number for destination")
flags.StringVar(&cOpts.Identity, "identity", "", "path to SSH identity file")
flags.StringVar(&cOpts.UDSPath, "socket-path", "", "path to podman socket on remote host. (default '/run/podman/podman.sock' or '/run/user/{uid}/podman/podman.sock)")
flags.BoolVarP(&cOpts.Default, "default", "d", false, "Set connection to be default")
}
func add(cmd *cobra.Command, args []string) error {
// Default to ssh: schema if none given
dest := args[1]
if match, err := regexp.Match(schemaPattern, []byte(dest)); err != nil {
return errors.Wrapf(err, "internal regex error %q", schemaPattern)
} else if !match {
dest = "ssh://" + dest
}
uri, err := url.Parse(dest)
if err != nil {
return errors.Wrapf(err, "failed to parse %q", dest)
}
if uri.User.Username() == "" {
if uri.User, err = getUserInfo(uri); err != nil {
return err
}
}
if cmd.Flags().Changed("socket-path") {
uri.Path = cmd.Flag("socket-path").Value.String()
}
if cmd.Flags().Changed("port") {
uri.Host = net.JoinHostPort(uri.Hostname(), cmd.Flag("port").Value.String())
}
if uri.Port() == "" {
uri.Host = net.JoinHostPort(uri.Hostname(), cmd.Flag("port").DefValue)
}
if uri.Path == "" || uri.Path == "/" {
if uri.Path, err = getUDS(cmd, uri); err != nil {
return errors.Wrapf(err, "failed to connect to %q", uri.String())
}
}
cfg, err := config.ReadCustomConfig()
if err != nil {
return err
}
if cmd.Flags().Changed("default") {
if cOpts.Default {
cfg.Engine.ActiveService = args[0]
}
}
dst := config.Destination{
URI: uri.String(),
}
if cmd.Flags().Changed("identity") {
dst.Identity = cOpts.Identity
}
if cfg.Engine.ServiceDestinations == nil {
cfg.Engine.ServiceDestinations = map[string]config.Destination{
args[0]: dst,
}
cfg.Engine.ActiveService = args[0]
} else {
cfg.Engine.ServiceDestinations[args[0]] = dst
}
return cfg.Write()
}
func getUserInfo(uri *url.URL) (*url.Userinfo, error) {
var (
usr *user.User
err error
)
if u, found := os.LookupEnv("_CONTAINERS_ROOTLESS_UID"); found {
usr, err = user.LookupId(u)
if err != nil {
return nil, errors.Wrapf(err, "failed to find user %q", u)
}
} else {
usr, err = user.Current()
if err != nil {
return nil, errors.Wrapf(err, "failed to obtain current user")
}
}
pw, set := uri.User.Password()
if set {
return url.UserPassword(usr.Username, pw), nil
}
return url.User(usr.Username), nil
}
func getUDS(cmd *cobra.Command, uri *url.URL) (string, error) {
var authMethods []ssh.AuthMethod
passwd, set := uri.User.Password()
if set {
authMethods = append(authMethods, ssh.Password(passwd))
}
if cmd.Flags().Changed("identity") {
value := cmd.Flag("identity").Value.String()
auth, err := terminal.PublicKey(value, []byte(passwd))
if err != nil {
return "", errors.Wrapf(err, "Failed to read identity %q", value)
}
authMethods = append(authMethods, auth)
}
if sock, found := os.LookupEnv("SSH_AUTH_SOCK"); found {
logrus.Debugf("Found SSH_AUTH_SOCK %q, ssh-agent signer enabled", sock)
c, err := net.Dial("unix", sock)
if err != nil {
return "", err
}
a := agent.NewClient(c)
authMethods = append(authMethods, ssh.PublicKeysCallback(a.Signers))
}
if len(authMethods) == 0 {
pass, err := terminal.ReadPassword(fmt.Sprintf("%s's login password:", uri.User.Username()))
if err != nil {
return "", err
}
authMethods = append(authMethods, ssh.Password(string(pass)))
}
cfg := &ssh.ClientConfig{
User: uri.User.Username(),
Auth: authMethods,
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}
dial, err := ssh.Dial("tcp", uri.Host, cfg)
if err != nil {
return "", errors.Wrapf(err, "failed to connect to %q", uri.Host)
}
defer dial.Close()
session, err := dial.NewSession()
if err != nil {
return "", errors.Wrapf(err, "failed to create new ssh session on %q", uri.Host)
}
defer session.Close()
// Override podman binary for testing etc
podman := "podman"
if v, found := os.LookupEnv("PODMAN_BINARY"); found {
podman = v
}
run := podman + " info --format=json"
var buffer bytes.Buffer
session.Stdout = &buffer
if err := session.Run(run); err != nil {
return "", errors.Wrapf(err, "failed to run %q", run)
}
var info define.Info
if err := json.Unmarshal(buffer.Bytes(), &info); err != nil {
return "", errors.Wrapf(err, "failed to parse 'podman info' results")
}
if info.Host.RemoteSocket == nil || len(info.Host.RemoteSocket.Path) == 0 {
return "", fmt.Errorf("remote podman %q failed to report its UDS socket", uri.Host)
}
return info.Host.RemoteSocket.Path, nil
}
| {
"pile_set_name": "Github"
} |
% Part:sets-functions-relations
% Chapter: size-of-sets
% Section: non-enumerability
\documentclass[../../../include/open-logic-section]{subfiles}
\begin{document}
\olfileid{sfr}{siz}{nen}
\olsection{\printtoken{S}{nonenumerable} Sets}
\begin{editorial}
This section proves the non-enumerability of $\Bin^\omega$ and
$\Pow{\PosInt}$ using the definition in \olref[enm]{sec}. It is
designed to be a little more elementary and a little more detailed
than the version in \olref[enm-alt]{sec}
\end{editorial}
Some sets, such as the set $\PosInt$ of positive integers, are
infinite. So far we've seen examples of infinite sets which were all
!!{enumerable}. However, there are also infinite sets which do not
have this property. Such sets are called \emph{!!{nonenumerable}}.
First of all, it is perhaps already surprising that there are
!!{nonenumerable} sets. For any !!{enumerable} set~$A$ there is
!!a{surjective} function $f \colon \PosInt \to A$. If a set is
!!{nonenumerable} there is no such function. That is, no function
mapping the infinitely many !!{element}s of~$\PosInt$ to~$A$ can
exhaust all of~$A$. So there are ``more'' !!{element}s of~$A$ than
the infinitely many positive integers.
How would one prove that a set is !!{nonenumerable}? You have to show
that no such surjective function can exist. Equivalently, you have to
show that the elements of~$A$ cannot be enumerated in a one way
infinite list. The best way to do this is to show that every list of
!!{element}s of~$A$ must leave at least one element out; or that no
function $f\colon \PosInt \to A$ can be !!{surjective}. We can do this
using Cantor's \emph{diagonal method}. Given a list of !!{element}s
of~$A$, say, $x_1$, $x_2$, \dots, we construct another element of~$A$
which, by its construction, cannot possibly be on that list.
Our first example is the set~$\Bin^\omega$ of all infinite, non-gappy
sequences of $0$'s and $1$'s.
\begin{thm}
\ollabel{thm:nonenum-bin-omega}
$\Bin^\omega$~is !!{nonenumerable}.
\end{thm}
\begin{proof}
Suppose, by way of contradiction, that $\Bin^\omega$ is
!!{enumerable}, i.e., suppose that there is a list $s_{1}$, $s_{2}$,
$s_{3}$, $s_{4}$, \dots{} of all !!{element}s of~$\Bin^\omega$. Each
of these $s_i$ is itself an infinite sequence of $0$'s and~$1$'s.
Let's call the $j$-th element of the $i$-th sequence in this list
$s_i(j)$. Then the $i$-th sequence~$s_i$ is
\[
s_i(1), s_i(2), s_i(3), \dots
\]
We may arrange this list, and the elements of each sequence $s_i$ in
it, in an array:
\[
\begin{array}{c|c|c|c|c|c}
& 1 & 2 & 3 & 4 & \dots \\\hline
1 & \mathbf{s_{1}(1)} & s_{1}(2) & s_{1}(3) & s_1(4) & \dots \\\hline
2 & s_{2}(1)& \mathbf{s_{2}(2)} & s_2(3) & s_2(4) & \dots \\\hline
3 & s_{3}(1)& s_{3}(2) & \mathbf{s_3(3)} & s_3(4) & \dots \\\hline
4 & s_{4}(1)& s_{4}(2) & s_4(3) & \mathbf{s_4(4)} & \dots \\\hline
\vdots & \vdots & \vdots & \vdots & \vdots & \mathbf{\ddots}
\end{array}
\]
The labels down the side give the number of the sequence in the list
$s_1$, $s_2$, \dots; the numbers across the top label the !!{element}s
of the individual sequences. For instance, $s_{1}(1)$ is a name for
whatever number, a $0$ or a~$1$, is the first !!{element} in the
sequence $s_{1}$, and so on.
Now we construct an infinite sequence, $\overline{s}$, of $0$'s and
$1$'s which cannot possibly be on this list. The definition of
$\overline{s}$ will depend on the list $s_1$, $s_2$, \dots. Any
infinite list of infinite sequences of $0$'s and $1$'s gives rise to
an infinite sequence~$\overline{s}$ which is guaranteed to not appear
on the list.
To define $\overline{s}$, we specify what all its !!{element}s are,
i.e., we specify $\overline{s}(n)$ for all $n \in \PosInt$. We do this
by reading down the diagonal of the array above (hence the name
``diagonal method'') and then changing every $1$ to a $0$ and every
$0$ to a~$1$. More abstractly, we define $\overline{s}(n)$ to be $0$
or $1$ according to whether the $n$-th !!{element} of the diagonal,
$s_n(n)$, is $1$ or $0$.
\[
\overline{s}(n) =
\begin{cases}
1 & \text{if $s_{n}(n) = 0$}\\
0 & \text{if $s_{n}(n) = 1$}.
\end{cases}
\]
If you like formulas better than definitions by cases, you could also
define $\overline{s}(n) = 1 - s_n(n)$.
Clearly $\overline{s}$ is an infinite sequence of $0$'s and
$1$'s, since it is just the mirror sequence to the sequence of $0$'s
and $1$'s that appear on the diagonal of our array. So $\overline{s}$
is !!a{element} of~$\Bin^\omega$. But it cannot be on the list $s_1$,
$s_2$, \dots{} Why not?
It can't be the first sequence in the list, $s_1$, because it differs from
$s_1$ in the first !!{element}. Whatever $s_1(1)$ is, we defined
$\overline{s}(1)$ to be the opposite. It can't be the second
sequence in the list, because $\overline{s}$ differs from $s_2$ in the second
element: if $s_2(2)$ is $0$, $\overline{s}(2)$ is $1$, and vice
versa. And so on.
More precisely: if $\overline{s}$ were on the list, there would be
some $k$ so that $\overline{s} = s_{k}$. Two sequences are identical
iff they agree at every place, i.e., for any~$n$, $\overline{s}(n) =
s_{k}(n)$. So in particular, taking $n = k$ as a special case,
$\overline{s}(k) = s_{k}(k)$ would have to hold. $s_k(k)$ is either
$0$ or~$1$. If it is $0$ then $\overline{s}(k)$ must be~$1$---that's
how we defined $\overline{s}$. But if $s_k(k) = 1$ then, again because
of the way we defined $\overline{s}$, $\overline{s}(k) = 0$. In either
case $\overline{s}(k) \neq s_{k}(k)$.
We started by assuming that there is a list of !!{element}s of
$\Bin^\omega$, $s_1$, $s_2$, \dots{} From this list we constructed a
sequence~$\overline{s}$ which we proved cannot be on the list. But it
definitely is a sequence of $0$'s and $1$'s if all the $s_i$ are
sequences of $0$'s and $1$'s, i.e., $\overline{s} \in
\Bin^\omega$. This shows in particular that there can be no list of
\emph{all} !!{element}s of~$\Bin^\omega$, since for any such list we
could also construct a sequence~$\overline{s}$ guaranteed to not be on
the list, so the assumption that there is a list of all sequences
in~$\Bin^\omega$ leads to a contradiction.
\end{proof}
\begin{explain}
This proof method is called ``diagonalization'' because it uses the
diagonal of the array to define~$\overline{s}$. Diagonalization need
not involve the presence of an array: we can show that sets are not
!!{enumerable} by using a similar idea even when no array and no
actual diagonal is involved.
\end{explain}
\begin{thm}
\ollabel{thm:nonenum-pownat}
$\Pow{\PosInt}$ is not !!{enumerable}.
\end{thm}
\begin{proof}
We proceed in the same way, by showing that for every list of subsets
of~$\PosInt$ there is a subset of $\PosInt$ which cannot be on the list.
Suppose the following is a given list of subsets of~$\PosInt$:
\[
Z_{1}, Z_{2}, Z_{3}, \dots
\]
We now define a set $\overline{Z}$ such that for any $n \in \PosInt$,
$n \in \overline{Z}$ iff $n \notin Z_{n}$:
\[
\overline{Z} = \Setabs{n \in \PosInt}{n \notin Z_n}
\]
$\overline{Z}$ is clearly a set of positive integers, since by
assumption each~$Z_n$ is, and thus $\overline{Z} \in
\Pow{\PosInt}$. But $\overline{Z}$ cannot be on the list. To show
this, we'll establish that for each $k \in \PosInt$, $\overline{Z} \neq
Z_k$.
So let $k \in \PosInt$ be arbitrary. We've defined $\overline{Z}$ so
that for any $n \in \PosInt$, $n \in \overline{Z}$ iff $n \notin Z_n$.
In particular, taking $n=k$, $k \in \overline{Z}$ iff $k \notin Z_k$.
But this shows that $\overline{Z} \neq Z_k$, since $k$ is !!a{element}
of one but not the other, and so $\overline{Z}$ and $Z_k$ have
different !!{element}s. Since $k$ was arbitrary, $\overline{Z}$ is not
on the list $Z_1$, $Z_2$, \dots
\end{proof}
\begin{explain}
The preceding proof did not mention a diagonal, but you can think of
it as involving a diagonal if you picture it this way: Imagine the
sets $Z_1$, $Z_2$, \dots, written in an array, where each
!!{element}~$j \in Z_i$ is listed in the~$j$-th column. Say the first
four sets on that list are $\{1,2,3,\dots\}$, $\{2, 4, 6, \dots\}$,
$\{1,2,5\}$, and $\{3,4,5,\dots\}$. Then the array would begin with
\[
\begin{array}{r@{}rrrrrrr}
Z_1 = \{ & \mathbf{1}, & 2, & 3, & 4, & 5, & 6, & \dots\}\\
Z_2 = \{ & & \mathbf{2}, & & 4, & & 6, & \dots\}\\
Z_3 = \{ & 1, & 2, & & & 5\phantom{,} & & \}\\
Z_4 = \{ & & & 3, & \mathbf{4}, & 5, & 6, & \dots\}\\
\vdots & & & & & \ddots
\end{array}
\]
Then $\overline{Z}$ is the set obtained by going down the diagonal,
leaving out any numbers that appear along the diagonal and include
those $j$ where the array has a gap in the $j$-th row/column. In the
above case, we would leave out $1$ and $2$, include~$3$, leave
out~$4$, etc.
\end{explain}
\begin{prob}
Show that $\Pow{\Nat}$ is !!{nonenumerable} by a diagonal argument.
\end{prob}
\begin{prob}
Show that the set of functions $f \colon \PosInt \to \PosInt$ is
!!{nonenumerable} by an explicit diagonal argument. That is, show that
if $f_1$, $f_2$, \dots, is a list of functions and each $f_i\colon
\PosInt \to \PosInt$, then there is some $\overline{f}\colon \PosInt \to
\PosInt$ not on this list.
\end{prob}
\end{document}
| {
"pile_set_name": "Github"
} |
# Copyright 2017 The TensorFlow 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.
# ==============================================================================
r"""Evaluation executable for detection models.
This executable is used to evaluate DetectionModels. There are two ways of
configuring the eval job.
1) A single pipeline_pb2.TrainEvalPipelineConfig file maybe specified instead.
In this mode, the --eval_training_data flag may be given to force the pipeline
to evaluate on training data instead.
Example usage:
./eval \
--logtostderr \
--checkpoint_dir=path/to/checkpoint_dir \
--eval_dir=path/to/eval_dir \
--pipeline_config_path=pipeline_config.pbtxt
2) Three configuration files may be provided: a model_pb2.DetectionModel
configuration file to define what type of DetectionModel is being evaluated, an
input_reader_pb2.InputReader file to specify what data the model is evaluating
and an eval_pb2.EvalConfig file to configure evaluation parameters.
Example usage:
./eval \
--logtostderr \
--checkpoint_dir=path/to/checkpoint_dir \
--eval_dir=path/to/eval_dir \
--eval_config_path=eval_config.pbtxt \
--model_config_path=model_config.pbtxt \
--input_config_path=eval_input_config.pbtxt
"""
import functools
import os
import tensorflow.compat.v1 as tf
from tensorflow.python.util.deprecation import deprecated
from object_detection.builders import dataset_builder
from object_detection.builders import graph_rewriter_builder
from object_detection.builders import model_builder
from object_detection.legacy import evaluator
from object_detection.utils import config_util
from object_detection.utils import label_map_util
tf.logging.set_verbosity(tf.logging.INFO)
flags = tf.app.flags
flags.DEFINE_boolean('eval_training_data', False,
'If training data should be evaluated for this job.')
flags.DEFINE_string(
'checkpoint_dir', '',
'Directory containing checkpoints to evaluate, typically '
'set to `train_dir` used in the training job.')
flags.DEFINE_string('eval_dir', '', 'Directory to write eval summaries to.')
flags.DEFINE_string(
'pipeline_config_path', '',
'Path to a pipeline_pb2.TrainEvalPipelineConfig config '
'file. If provided, other configs are ignored')
flags.DEFINE_string('eval_config_path', '',
'Path to an eval_pb2.EvalConfig config file.')
flags.DEFINE_string('input_config_path', '',
'Path to an input_reader_pb2.InputReader config file.')
flags.DEFINE_string('model_config_path', '',
'Path to a model_pb2.DetectionModel config file.')
flags.DEFINE_boolean(
'run_once', False, 'Option to only run a single pass of '
'evaluation. Overrides the `max_evals` parameter in the '
'provided config.')
FLAGS = flags.FLAGS
@deprecated(None, 'Use object_detection/model_main.py.')
def main(unused_argv):
assert FLAGS.checkpoint_dir, '`checkpoint_dir` is missing.'
assert FLAGS.eval_dir, '`eval_dir` is missing.'
tf.gfile.MakeDirs(FLAGS.eval_dir)
if FLAGS.pipeline_config_path:
configs = config_util.get_configs_from_pipeline_file(
FLAGS.pipeline_config_path)
tf.gfile.Copy(
FLAGS.pipeline_config_path,
os.path.join(FLAGS.eval_dir, 'pipeline.config'),
overwrite=True)
else:
configs = config_util.get_configs_from_multiple_files(
model_config_path=FLAGS.model_config_path,
eval_config_path=FLAGS.eval_config_path,
eval_input_config_path=FLAGS.input_config_path)
for name, config in [('model.config', FLAGS.model_config_path),
('eval.config', FLAGS.eval_config_path),
('input.config', FLAGS.input_config_path)]:
tf.gfile.Copy(config, os.path.join(FLAGS.eval_dir, name), overwrite=True)
model_config = configs['model']
eval_config = configs['eval_config']
input_config = configs['eval_input_config']
if FLAGS.eval_training_data:
input_config = configs['train_input_config']
model_fn = functools.partial(
model_builder.build, model_config=model_config, is_training=False)
def get_next(config):
return dataset_builder.make_initializable_iterator(
dataset_builder.build(config)).get_next()
create_input_dict_fn = functools.partial(get_next, input_config)
categories = label_map_util.create_categories_from_labelmap(
input_config.label_map_path)
if FLAGS.run_once:
eval_config.max_evals = 1
graph_rewriter_fn = None
if 'graph_rewriter_config' in configs:
graph_rewriter_fn = graph_rewriter_builder.build(
configs['graph_rewriter_config'], is_training=False)
evaluator.evaluate(
create_input_dict_fn,
model_fn,
eval_config,
categories,
FLAGS.checkpoint_dir,
FLAGS.eval_dir,
graph_hook_fn=graph_rewriter_fn)
if __name__ == '__main__':
tf.app.run()
| {
"pile_set_name": "Github"
} |
#include <core.p4>
#define V1MODEL_VERSION 20180101
#include <v1model.p4>
header short {
bit<32> f;
}
struct alt_t {
bit<1> valid;
bit<7> port;
}
struct row_t {
alt_t alt0;
alt_t alt1;
}
struct parsed_packet_t {
}
struct local_metadata_t {
short _s0;
bit<1> _row_alt0_valid1;
bit<7> _row_alt0_port2;
bit<1> _row_alt1_valid3;
bit<7> _row_alt1_port4;
}
parser parse(packet_in pk, out parsed_packet_t hdr, inout local_metadata_t local_metadata, inout standard_metadata_t standard_metadata) {
state start {
transition accept;
}
}
control ingress(inout parsed_packet_t hdr, inout local_metadata_t local_metadata, inout standard_metadata_t standard_metadata) {
@hidden action issue1642bmv2l36() {
local_metadata._s0.setValid();
local_metadata._s0.f = 32w0;
local_metadata._row_alt0_valid1 = local_metadata._row_alt1_valid3;
local_metadata._row_alt0_port2 = local_metadata._row_alt1_port4;
local_metadata._row_alt0_valid1 = 1w1;
local_metadata._row_alt1_port4 = local_metadata._row_alt1_port4 + 7w1;
clone3<row_t>(CloneType.I2E, 32w0, (row_t){alt0 = (alt_t){valid = 1w1,port = local_metadata._row_alt0_port2},alt1 = (alt_t){valid = local_metadata._row_alt1_valid3,port = local_metadata._row_alt1_port4}});
}
@hidden table tbl_issue1642bmv2l36 {
actions = {
issue1642bmv2l36();
}
const default_action = issue1642bmv2l36();
}
apply {
tbl_issue1642bmv2l36.apply();
}
}
control egress(inout parsed_packet_t hdr, inout local_metadata_t local_metadata, inout standard_metadata_t standard_metadata) {
apply {
}
}
control deparser(packet_out b, in parsed_packet_t hdr) {
apply {
}
}
control verifyChecksum(inout parsed_packet_t hdr, inout local_metadata_t local_metadata) {
apply {
}
}
control compute_checksum(inout parsed_packet_t hdr, inout local_metadata_t local_metadata) {
apply {
}
}
V1Switch<parsed_packet_t, local_metadata_t>(parse(), verifyChecksum(), ingress(), egress(), compute_checksum(), deparser()) main;
| {
"pile_set_name": "Github"
} |
from conduit.apps.core.renderers import ConduitJSONRenderer
class ArticleJSONRenderer(ConduitJSONRenderer):
object_label = 'article'
pagination_object_label = 'articles'
pagination_count_label = 'articlesCount'
class CommentJSONRenderer(ConduitJSONRenderer):
object_label = 'comment'
pagination_object_label = 'comments'
pagination_count_label = 'commentsCount'
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<Package
xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10"
xmlns:mp="http://schemas.microsoft.com/appx/2014/phone/manifest"
xmlns:uap="http://schemas.microsoft.com/appx/manifest/uap/windows10"
IgnorableNamespaces="uap mp">
<Identity
Name="bfdc7711-e00a-4f10-baa4-cee09da7a0bd"
Publisher="CN=Charles"
Version="1.0.0.0" />
<mp:PhoneIdentity PhoneProductId="bfdc7711-e00a-4f10-baa4-cee09da7a0bd" PhonePublisherId="00000000-0000-0000-0000-000000000000"/>
<Properties>
<DisplayName>PlatInfoSap1.UWP</DisplayName>
<PublisherDisplayName>Charles</PublisherDisplayName>
<Logo>Assets\StoreLogo.png</Logo>
</Properties>
<Dependencies>
<TargetDeviceFamily Name="Windows.Universal" MinVersion="10.0.0.0" MaxVersionTested="10.0.0.0" />
</Dependencies>
<Resources>
<Resource Language="x-generate"/>
</Resources>
<Applications>
<Application Id="App"
Executable="$targetnametoken$.exe"
EntryPoint="PlatInfoSap1.UWP.App">
<uap:VisualElements
DisplayName="PlatInfoSap1.UWP"
Square150x150Logo="Assets\Square150x150Logo.png"
Square44x44Logo="Assets\Square44x44Logo.png"
Description="PlatInfoSap1.UWP"
BackgroundColor="transparent">
<uap:DefaultTile Wide310x150Logo="Assets\Wide310x150Logo.png"/>
<uap:SplashScreen Image="Assets\SplashScreen.png" />
</uap:VisualElements>
</Application>
</Applications>
<Capabilities>
<Capability Name="internetClient" />
</Capabilities>
</Package> | {
"pile_set_name": "Github"
} |
# ===========================================================================
# http://www.gnu.org/software/autoconf-archive/ax_enable_builddir.html
# ===========================================================================
#
# SYNOPSIS
#
# AX_ENABLE_BUILDDIR [(dirstring-or-command [,Makefile.mk [,-all]])]
#
# DESCRIPTION
#
# If the current configure was run within the srcdir then we move all
# configure-files into a subdir and let the configure steps continue
# there. We provide an option --disable-builddir to suppress the move into
# a separate builddir.
#
# Defaults:
#
# $1 = $host (overridden with $HOST)
# $2 = Makefile.mk
# $3 = -all
#
# This macro must be called before AM_INIT_AUTOMAKE. It creates a default
# toplevel srcdir Makefile from the information found in the created
# toplevel builddir Makefile. It just copies the variables and
# rule-targets, each extended with a default rule-execution that recurses
# into the build directory of the current "HOST". You can override the
# auto-dection through `config.guess` and build-time of course, as in
#
# make HOST=i386-mingw-cross
#
# which can of course set at configure time as well using
#
# configure --host=i386-mingw-cross
#
# After the default has been created, additional rules can be appended
# that will not just recurse into the subdirectories and only ever exist
# in the srcdir toplevel makefile - these parts are read from the $2 =
# Makefile.mk file
#
# The automatic rules are usually scanning the toplevel Makefile for lines
# like '#### $host |$builddir' to recognize the place where to recurse
# into. Usually, the last one is the only one used. However, almost all
# targets have an additional "*-all" rule which makes the script to
# recurse into _all_ variants of the current HOST (!!) setting. The "-all"
# suffix can be overriden for the macro as well.
#
# a special rule is only given for things like "dist" that will copy the
# tarball from the builddir to the sourcedir (or $(PUB)) for reason of
# convenience.
#
# LICENSE
#
# Copyright (c) 2009 Guido U. Draheim <[email protected]>
# Copyright (c) 2009 Alan Jenkins <[email protected]>
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 3 of the License, or (at your
# option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program. If not, see <http://www.gnu.org/licenses/>.
#
# As a special exception, the respective Autoconf Macro's copyright owner
# gives unlimited permission to copy, distribute and modify the configure
# scripts that are the output of Autoconf when processing the Macro. You
# need not follow the terms of the GNU General Public License when using
# or distributing such scripts, even though portions of the text of the
# Macro appear in them. The GNU General Public License (GPL) does govern
# all other use of the material that constitutes the Autoconf Macro.
#
# This special exception to the GPL applies to versions of the Autoconf
# Macro released by the Autoconf Archive. When you make and distribute a
# modified version of the Autoconf Macro, you may extend this special
# exception to the GPL to apply to your modified version as well.
#serial 23
AC_DEFUN([AX_ENABLE_BUILDDIR],[
AC_REQUIRE([AC_CANONICAL_HOST])[]dnl
AC_REQUIRE([AX_CONFIGURE_ARGS])[]dnl
AC_REQUIRE([AM_AUX_DIR_EXPAND])[]dnl
AC_BEFORE([$0],[AM_INIT_AUTOMAKE])dnl
AS_VAR_PUSHDEF([SUB],[ax_enable_builddir])dnl
AS_VAR_PUSHDEF([AUX],[ax_enable_builddir_auxdir])dnl
AS_VAR_PUSHDEF([SED],[ax_enable_builddir_sed])dnl
SUB="."
AC_ARG_ENABLE([builddir], AS_HELP_STRING(
[--disable-builddir],[disable automatic build in subdir of sources])
,[SUB="$enableval"], [SUB="auto"])
if test ".$ac_srcdir_defaulted" != ".no" ; then
if test ".$srcdir" = ".." ; then
if test -f config.status ; then
AC_MSG_NOTICE(toplevel srcdir already configured... skipping subdir build)
else
test ".$SUB" = "." && SUB="."
test ".$SUB" = ".no" && SUB="."
test ".$TARGET" = "." && TARGET="$target"
test ".$SUB" = ".auto" && SUB="m4_ifval([$1], [$1],[$TARGET])"
if test ".$SUB" != ".." ; then # we know where to go and
AS_MKDIR_P([$SUB])
echo __.$SUB.__ > $SUB/conftest.tmp
cd $SUB
if grep __.$SUB.__ conftest.tmp >/dev/null 2>/dev/null ; then
rm conftest.tmp
AC_MSG_RESULT([continue configure in default builddir "./$SUB"])
else
AC_MSG_ERROR([could not change to default builddir "./$SUB"])
fi
srcdir=`echo "$SUB" |
sed -e 's,^\./,,;s,[[^/]]$,&/,;s,[[^/]]*/,../,g;s,[[/]]$,,;'`
# going to restart from subdirectory location
test -f $srcdir/config.log && mv $srcdir/config.log .
test -f $srcdir/confdefs.h && mv $srcdir/confdefs.h .
test -f $srcdir/conftest.log && mv $srcdir/conftest.log .
test -f $srcdir/$cache_file && mv $srcdir/$cache_file .
AC_MSG_RESULT(....exec $SHELL $srcdir/[$]0 "--srcdir=$srcdir" "--enable-builddir=$SUB" ${1+"[$]@"})
case "[$]0" in # restart
[/\\]*) eval $SHELL "'[$]0'" "'--srcdir=$srcdir'" "'--enable-builddir=$SUB'" $ac_configure_args ;;
*) eval $SHELL "'$srcdir/[$]0'" "'--srcdir=$srcdir'" "'--enable-builddir=$SUB'" $ac_configure_args ;;
esac ; exit $?
fi
fi
fi fi
test ".$SUB" = ".auto" && SUB="."
dnl ac_path_prog uses "set dummy" to override $@ which would defeat the "exec"
AC_PATH_PROG(SED,gsed sed, sed)
AUX="$am_aux_dir"
AS_VAR_POPDEF([SED])dnl
AS_VAR_POPDEF([AUX])dnl
AS_VAR_POPDEF([SUB])dnl
AC_CONFIG_COMMANDS([buildir],[dnl .............. config.status ..............
AS_VAR_PUSHDEF([SUB],[ax_enable_builddir])dnl
AS_VAR_PUSHDEF([TOP],[top_srcdir])dnl
AS_VAR_PUSHDEF([SRC],[ac_top_srcdir])dnl
AS_VAR_PUSHDEF([AUX],[ax_enable_builddir_auxdir])dnl
AS_VAR_PUSHDEF([SED],[ax_enable_builddir_sed])dnl
pushdef([END],[Makefile.mk])dnl
pushdef([_ALL],[ifelse([$3],,[-all],[$3])])dnl
SRC="$ax_enable_builddir_srcdir"
if test ".$SUB" = ".." ; then
if test -f "$TOP/Makefile" ; then
AC_MSG_NOTICE([skipping TOP/Makefile - left untouched])
else
AC_MSG_NOTICE([skipping TOP/Makefile - not created])
fi
else
if test -f "$SRC/Makefile" ; then
a=`grep "^VERSION " "$SRC/Makefile"` ; b=`grep "^VERSION " Makefile`
test "$a" != "$b" && rm "$SRC/Makefile"
fi
if test -f "$SRC/Makefile" ; then
echo "$SRC/Makefile : $SRC/Makefile.in" > $tmp/conftemp.mk
echo " []@ echo 'REMOVED,,,' >\$[]@" >> $tmp/conftemp.mk
eval "${MAKE-make} -f $tmp/conftemp.mk 2>/dev/null >/dev/null"
if grep '^REMOVED,,,' "$SRC/Makefile" >/dev/null
then rm $SRC/Makefile ; fi
cp $tmp/conftemp.mk $SRC/makefiles.mk~ ## DEBUGGING
fi
if test ! -f "$SRC/Makefile" ; then
AC_MSG_NOTICE([create TOP/Makefile guessed from local Makefile])
x='`' ; cat >$tmp/conftemp.sed <<_EOF
/^\$/n
x
/^\$/bS
x
/\\\\\$/{H;d;}
{H;s/.*//;x;}
bM
:S
x
/\\\\\$/{h;d;}
{h;s/.*//;x;}
:M
s/\\(\\n\\) /\\1 /g
/^ /d
/^[[ ]]*[[\\#]]/d
/^VPATH *=/d
s/^srcdir *=.*/srcdir = ./
s/^top_srcdir *=.*/top_srcdir = ./
/[[:=]]/!d
/^\\./d
dnl Now handle rules (i.e. lines containing ":" but not " = ").
/ = /b
/ .= /b
/:/!b
s/:.*/:/
s/ / /g
s/ \\([[a-z]][[a-z-]]*[[a-zA-Z0-9]]\\)\\([[ :]]\\)/ \\1 \\1[]_ALL\\2/g
s/^\\([[a-z]][[a-z-]]*[[a-zA-Z0-9]]\\)\\([[ :]]\\)/\\1 \\1[]_ALL\\2/
s/ / /g
/^all all[]_ALL[[ :]]/i\\
all-configured : all[]_ALL
dnl dist-all exists... and would make for dist-all-all
s/ [[a-zA-Z0-9-]]*[]_ALL [[a-zA-Z0-9-]]*[]_ALL[]_ALL//g
/[]_ALL[]_ALL/d
a\\
@ HOST="\$(HOST)\" \\\\\\
; test ".\$\$HOST" = "." && HOST=$x sh $AUX/config.guess $x \\\\\\
; BUILD=$x grep "^#### \$\$HOST " Makefile | sed -e 's/.*|//' $x \\\\\\
; use=$x basename "\$\@" _ALL $x; n=$x echo \$\$BUILD | wc -w $x \\\\\\
; echo "MAKE \$\$HOST : \$\$n * \$\@"; if test "\$\$n" -eq "0" ; then : \\\\\\
; BUILD=$x grep "^####.*|" Makefile |tail -1| sed -e 's/.*|//' $x ; fi \\\\\\
; test ".\$\$BUILD" = "." && BUILD="." \\\\\\
; test "\$\$use" = "\$\@" && BUILD=$x echo "\$\$BUILD" | tail -1 $x \\\\\\
; for i in \$\$BUILD ; do test ".\$\$i" = "." && continue \\\\\\
; (cd "\$\$i" && test ! -f configure && \$(MAKE) \$\$use) || exit; done
dnl special rule add-on: "dist" copies the tarball to $(PUB). (source tree)
/dist[]_ALL *:/a\\
@ HOST="\$(HOST)\" \\\\\\
; test ".\$\$HOST" = "." && HOST=$x sh $AUX/config.guess $x \\\\\\
; BUILD=$x grep "^#### \$\$HOST " Makefile | sed -e 's/.*|//' $x \\\\\\
; found=$x echo \$\$BUILD | wc -w $x \\\\\\
; echo "MAKE \$\$HOST : \$\$found \$(PACKAGE)-\$(VERSION).tar.*" \\\\\\
; if test "\$\$found" -eq "0" ; then : \\\\\\
; BUILD=$x grep "^#### .*|" Makefile |tail -1| sed -e 's/.*|//' $x \\\\\\
; fi ; for i in \$\$BUILD ; do test ".\$\$i" = "." && continue \\\\\\
; for f in \$\$i/\$(PACKAGE)-\$(VERSION).tar.* \\\\\\
; do test -f "\$\$f" && mv "\$\$f" \$(PUB). ; done ; break ; done
dnl special rule add-on: "dist-foo" copies all the archives to $(PUB). (source tree)
/dist-[[a-zA-Z0-9]]*[]_ALL *:/a\\
@ HOST="\$(HOST)\" \\\\\\
; test ".\$\$HOST" = "." && HOST=$x sh ./config.guess $x \\\\\\
; BUILD=$x grep "^#### \$\$HOST " Makefile | sed -e 's/.*|//' $x \\\\\\
; found=$x echo \$\$BUILD | wc -w $x \\\\\\
; echo "MAKE \$\$HOST : \$\$found \$(PACKAGE)-\$(VERSION).*" \\\\\\
; if test "\$\$found" -eq "0" ; then : \\\\\\
; BUILD=$x grep "^#### .*|" Makefile |tail -1| sed -e 's/.*|//' $x \\\\\\
; fi ; for i in \$\$BUILD ; do test ".\$\$i" = "." && continue \\\\\\
; for f in \$\$i/\$(PACKAGE)-\$(VERSION).* \\\\\\
; do test -f "\$\$f" && mv "\$\$f" \$(PUB). ; done ; break ; done
dnl special rule add-on: "distclean" removes all local builddirs completely
/distclean[]_ALL *:/a\\
@ HOST="\$(HOST)\" \\\\\\
; test ".\$\$HOST" = "." && HOST=$x sh $AUX/config.guess $x \\\\\\
; BUILD=$x grep "^#### .*|" Makefile | sed -e 's/.*|//' $x \\\\\\
; use=$x basename "\$\@" _ALL $x; n=$x echo \$\$BUILD | wc -w $x \\\\\\
; echo "MAKE \$\$HOST : \$\$n * \$\@ (all local builds)" \\\\\\
; test ".\$\$BUILD" = "." && BUILD="." \\\\\\
; for i in \$\$BUILD ; do test ".\$\$i" = "." && continue \\\\\\
; echo "# rm -r \$\$i"; done ; echo "# (sleep 3)" ; sleep 3 \\\\\\
; for i in \$\$BUILD ; do test ".\$\$i" = "." && continue \\\\\\
; echo "\$\$i" | grep "^/" > /dev/null && continue \\\\\\
; echo "\$\$i" | grep "^../" > /dev/null && continue \\\\\\
; echo "rm -r \$\$i"; (rm -r "\$\$i") ; done ; rm Makefile
_EOF
cp "$tmp/conftemp.sed" "$SRC/makefile.sed~" ## DEBUGGING
$SED -f $tmp/conftemp.sed Makefile >$SRC/Makefile
if test -f "$SRC/m4_ifval([$2],[$2],[END])" ; then
AC_MSG_NOTICE([extend TOP/Makefile with TOP/m4_ifval([$2],[$2],[END])])
cat $SRC/END >>$SRC/Makefile
fi ; xxxx="####"
echo "$xxxx CONFIGURATIONS FOR TOPLEVEL MAKEFILE: " >>$SRC/Makefile
# sanity check
if grep '^; echo "MAKE ' $SRC/Makefile >/dev/null ; then
AC_MSG_NOTICE([buggy sed found - it deletes tab in "a" text parts])
$SED -e '/^@ HOST=/s/^/ /' -e '/^; /s/^/ /' $SRC/Makefile \
>$SRC/Makefile~
(test -s $SRC/Makefile~ && mv $SRC/Makefile~ $SRC/Makefile) 2>/dev/null
fi
else
xxxx="\\#\\#\\#\\#"
# echo "/^$xxxx *$ax_enable_builddir_host /d" >$tmp/conftemp.sed
echo "s!^$xxxx [[^|]]* | *$SUB *\$!$xxxx ...... $SUB!" >$tmp/conftemp.sed
$SED -f "$tmp/conftemp.sed" "$SRC/Makefile" >$tmp/mkfile.tmp
cp "$tmp/conftemp.sed" "$SRC/makefiles.sed~" ## DEBUGGING
cp "$tmp/mkfile.tmp" "$SRC/makefiles.out~" ## DEBUGGING
if cmp -s "$SRC/Makefile" "$tmp/mkfile.tmp" 2>/dev/null ; then
AC_MSG_NOTICE([keeping TOP/Makefile from earlier configure])
rm "$tmp/mkfile.tmp"
else
AC_MSG_NOTICE([reusing TOP/Makefile from earlier configure])
mv "$tmp/mkfile.tmp" "$SRC/Makefile"
fi
fi
AC_MSG_NOTICE([build in $SUB (HOST=$ax_enable_builddir_host)])
xxxx="####"
echo "$xxxx" "$ax_enable_builddir_host" "|$SUB" >>$SRC/Makefile
fi
popdef([END])dnl
AS_VAR_POPDEF([SED])dnl
AS_VAR_POPDEF([AUX])dnl
AS_VAR_POPDEF([SRC])dnl
AS_VAR_POPDEF([TOP])dnl
AS_VAR_POPDEF([SUB])dnl
],[dnl
ax_enable_builddir_srcdir="$srcdir" # $srcdir
ax_enable_builddir_host="$HOST" # $HOST / $host
ax_enable_builddir_version="$VERSION" # $VERSION
ax_enable_builddir_package="$PACKAGE" # $PACKAGE
ax_enable_builddir_auxdir="$ax_enable_builddir_auxdir" # $AUX
ax_enable_builddir_sed="$ax_enable_builddir_sed" # $SED
ax_enable_builddir="$ax_enable_builddir" # $SUB
])dnl
])
| {
"pile_set_name": "Github"
} |
require_relative '../../../spec_helper'
require 'cgi'
describe "CGI::QueryExtension#[]" do
before :each do
ENV['REQUEST_METHOD'], @old_request_method = "GET", ENV['REQUEST_METHOD']
ENV['QUERY_STRING'], @old_query_string = "one=a&two=b&two=c", ENV['QUERY_STRING']
@cgi = CGI.new
end
after :each do
ENV['REQUEST_METHOD'] = @old_request_method
ENV['QUERY_STRING'] = @old_query_string
end
it "it returns the value for the parameter with the given key" do
@cgi["one"].should == "a"
end
it "only returns the first value for parameters with multiple values" do
@cgi["two"].should == "b"
end
it "returns a String" do
@cgi["one"].should be_kind_of(String)
end
end
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" ?>
<annotation>
<folder>widerface</folder>
<filename>32--Worker_Laborer_32_Worker_Laborer_Worker_Laborer_32_314.jpg</filename>
<source>
<database>wider face Database</database>
<annotation>PASCAL VOC2007</annotation>
<image>flickr</image>
<flickrid>-1</flickrid>
</source>
<owner>
<flickrid>yanyu</flickrid>
<name>yanyu</name>
</owner>
<size>
<width>1024</width>
<height>773</height>
<depth>3</depth>
</size>
<segmented>0</segmented>
<object>
<name>face</name>
<pose>Unspecified</pose>
<truncated>1</truncated>
<difficult>0</difficult>
<bndbox>
<xmin>602</xmin>
<ymin>70</ymin>
<xmax>692</xmax>
<ymax>188</ymax>
</bndbox>
<lm>
<x1>641.281</x1>
<y1>131.482</y1>
<x2>662.902</x2>
<y2>145.647</y2>
<x3>648.737</x3>
<y3>164.286</y3>
<x4>618.915</x4>
<y4>154.594</y4>
<x5>630.098</x5>
<y5>162.795</y5>
<visible>1</visible>
<blur>0.7</blur>
</lm>
<has_lm>1</has_lm>
</object>
</annotation>
| {
"pile_set_name": "Github"
} |
#include "ProjectileSpawnerComponent.h"
#include "../../GameApp/BaseGameApp.h"
#include "../../GameApp/BaseGameLogic.h"
#include "PositionComponent.h"
#include "../../UserInterface/HumanView.h"
#include "RenderComponent.h"
const char* ProjectileSpawnerComponent::g_Name = "ProjectileSpawnerComponent";
ProjectileSpawnerComponent::ProjectileSpawnerComponent()
:
m_ActorsInTriggerArea(0),
m_bReady(false),
m_StartDelayLeft(0)
{
}
ProjectileSpawnerComponent::~ProjectileSpawnerComponent()
{
}
bool ProjectileSpawnerComponent::VInit(TiXmlElement* pData)
{
assert(pData != NULL);
m_Properties.LoadFromXml(pData, true);
m_StartDelayLeft = m_Properties.startSpawnDelay;
return true;
}
TiXmlElement* ProjectileSpawnerComponent::VGenerateXml()
{
return m_Properties.ToXml();
}
void ProjectileSpawnerComponent::VPostInit()
{
m_pAnimationComponent =
MakeStrongPtr(m_pOwner->GetComponent<AnimationComponent>()).get();
m_pARC = m_pOwner->GetRawComponent<ActorRenderComponent>(true);
assert(m_pAnimationComponent != NULL);
if (m_Properties.idleAnim == "INVISIBLE")
{
m_pARC->SetVisible(false);
m_pAnimationComponent->PauseAnimation();
}
else
{
m_pAnimationComponent->SetAnimation(m_Properties.idleAnim);
}
shared_ptr<TriggerComponent> pTriggerComponent =
MakeStrongPtr(m_pOwner->GetComponent<TriggerComponent>());
assert(pTriggerComponent != nullptr);
m_pAnimationComponent->AddObserver(this);
pTriggerComponent->AddObserver(this);
}
void ProjectileSpawnerComponent::VPostPostInit()
{
if (!m_Properties.triggerAreaSize.IsZeroXY() && !m_Properties.isAlwaysOn)
{
ActorFixtureDef fixtureDef;
fixtureDef.collisionShape = "Rectangle";
fixtureDef.fixtureType = FixtureType_Trigger;
fixtureDef.size = m_Properties.triggerAreaSize;
fixtureDef.offset = m_Properties.triggerAreaOffset;
fixtureDef.collisionMask = m_Properties.triggerCollisionMask;
fixtureDef.collisionFlag = CollisionFlag_Trigger;
fixtureDef.isSensor = true;
g_pApp->GetGameLogic()->VGetGamePhysics()->VAddActorFixtureToBody(m_pOwner->GetGUID(), &fixtureDef);
}
}
void ProjectileSpawnerComponent::VUpdate(uint32 msDiff)
{
if (!m_bReady)
{
m_StartDelayLeft -= msDiff;
if (m_StartDelayLeft <= 0)
{
m_bReady = true;
}
}
TryToFire();
}
void ProjectileSpawnerComponent::VOnActorEnteredTrigger(Actor* pActorWhoEntered, FixtureType triggerType)
{
m_ActorsInTriggerArea++;
m_pARC->SetVisible(true);
TryToFire();
assert(m_ActorsInTriggerArea >= 0);
}
void ProjectileSpawnerComponent::VOnActorLeftTrigger(Actor* pActorWhoLeft, FixtureType triggerType)
{
m_ActorsInTriggerArea--;
assert(m_ActorsInTriggerArea >= 0);
}
void ProjectileSpawnerComponent::VOnAnimationLooped(Animation* pAnimation)
{
if (pAnimation->GetName() == m_Properties.fireAnim && m_Properties.projectileSpawnAnimFrameIdx == 0)
{
SpawnProjectile();
}
if (m_Properties.idleAnim == "INVISIBLE")
{
m_pARC->SetVisible(false);
m_pAnimationComponent->PauseAnimation();
}
else
{
m_pAnimationComponent->SetAnimation(m_Properties.idleAnim);
}
TryToFire();
}
void ProjectileSpawnerComponent::SpawnProjectile()
{
assert(g_pApp->GetHumanView() && g_pApp->GetHumanView()->GetCamera());
// Check if the spawned projectile is within some bounds of Claw's Human View display
// If not, then we can't either hear it nor do we care that there is some projectile
Point projectilePos = m_pOwner->GetPositionComponent()->GetPosition();
if (g_pApp->GetHumanView()->GetCamera()->IntersectsWithPoint(projectilePos, 1.25f))
{
// Spawn the projectile
Point projectilePosition = m_pOwner->GetPositionComponent()->GetPosition() + m_Properties.projectileSpawnOffset;
ActorTemplates::CreateActor_Projectile(
m_Properties.projectileProto,
projectilePosition,
m_Properties.projectileDirection,
m_pOwner->GetGUID());
}
}
void ProjectileSpawnerComponent::VOnAnimationFrameChanged(
Animation* pAnimation,
AnimationFrame* pLastFrame,
AnimationFrame* pNewFrame)
{
if (m_Properties.idleAnim == "INVISIBLE" && !m_pARC->IsVisible())
{
return;
}
if (m_Properties.projectileSpawnAnimFrameIdx == pNewFrame->idx)
{
//assert(m_Properties.projectileSpawnAnimFrameIdx != 0);
if (m_Properties.projectileSpawnAnimFrameIdx == 0)
{
return;
}
SpawnProjectile();
}
}
void ProjectileSpawnerComponent::VOnAnimationEndedDelay(Animation* pAnimation)
{
if (m_Properties.idleAnim == "INVISIBLE")
{
m_pARC->SetVisible(true);
}
}
bool ProjectileSpawnerComponent::TryToFire()
{
if (!m_bReady)
{
return false;
}
/*if (m_Properties.idleAnim == "INVISIBLE" && (m_Properties.isAlwaysOn || m_ActorsInTriggerArea > 0))
{
m_pARC->SetVisible(true);
}*/
// If it is already firing, dont do anything
if (IsFiring())
{
return false;
}
// If we can fire, do just that
if ((m_Properties.isAlwaysOn || m_ActorsInTriggerArea > 0))
{
if (m_Properties.idleAnim == "INVISIBLE")
{
m_pARC->SetVisible(false);
}
m_pAnimationComponent->SetAnimation(m_Properties.fireAnim);
m_pAnimationComponent->ResumeAnimation();
int randDelay = Util::GetRandomNumber(m_Properties.minSpawnDelay, m_Properties.maxSpawnDelay);
m_pAnimationComponent->SetDelay(randDelay);
return true;
}
else
{
if (m_Properties.idleAnim == "INVISIBLE")
{
m_pARC->SetVisible(false);
m_pAnimationComponent->PauseAnimation();
}
else
{
m_pAnimationComponent->SetAnimation(m_Properties.idleAnim);
}
}
return false;
}
bool ProjectileSpawnerComponent::IsFiring()
{
return (m_pAnimationComponent->GetCurrentAnimationName() == m_Properties.fireAnim) &&
!m_pAnimationComponent->GetCurrentAnimation()->IsPaused();
} | {
"pile_set_name": "Github"
} |
--source include/have_innodb.inc
set session transaction isolation level read committed;
create table bug45357(a int, b int,key(b))engine=innodb;
insert into bug45357 values (25170,6122);
update bug45357 set a=1 where b=30131;
delete from bug45357 where b < 20996;
delete from bug45357 where b < 7001;
drop table bug45357;
| {
"pile_set_name": "Github"
} |
{
".:.::QUERY": {
"Transitions": 0,
"Transversions": 0,
"nocall__nc": 68
},
".:.::TRUTH": {
"Transitions": 0,
"Transversions": 0,
"nocall__nc": 4809
},
".:.:CONF:QUERY": {
"Transitions": 0,
"Transversions": 0,
"nocall__nc": 103
},
".:.:CONF:TRUTH": {
"Transitions": 0,
"Transversions": 0,
"nocall__nc": 657
},
"FN:.::TRUTH": {
"Transitions": 4,
"Transversions": 5,
"al__d": 12,
"al__i": 5,
"al__s": 9,
"het__rd": 6,
"het__ri": 5,
"het__rs": 5,
"homalt__d": 6,
"homalt__s": 4,
"nuc__d": 31,
"nuc__i": 93,
"nuc__s": 9
},
"FN:.:CONF:TRUTH": {
"Transitions": 4,
"Transversions": 1,
"al__d": 17,
"al__i": 15,
"al__s": 5,
"het__rd": 17,
"het__ri": 9,
"het__rs": 1,
"hetalt__i": 1,
"homalt__i": 4,
"homalt__s": 4,
"nuc__d": 1184,
"nuc__i": 103,
"nuc__s": 5
},
"FN:am::TRUTH": {
"Transitions": 9,
"Transversions": 5,
"al__d": 4,
"al__i": 2,
"al__s": 14,
"het__rs": 2,
"homalt__d": 4,
"homalt__i": 2,
"homalt__s": 12,
"nuc__d": 5,
"nuc__i": 2,
"nuc__s": 14
},
"FN:am:CONF:TRUTH": {
"Transitions": 8,
"Transversions": 2,
"al__s": 10,
"homalt__s": 10,
"nuc__s": 10
},
"FN:lm::TRUTH": {
"Transitions": 0,
"Transversions": 4,
"al__d": 15,
"al__i": 28,
"al__s": 4,
"het__rd": 6,
"het__ri": 19,
"hetalt__i": 1,
"homalt__d": 9,
"homalt__i": 7,
"homalt__s": 4,
"nuc__d": 73,
"nuc__i": 184,
"nuc__s": 4
},
"FN:lm:CONF:TRUTH": {
"Transitions": 2,
"Transversions": 5,
"al__d": 30,
"al__i": 36,
"al__s": 7,
"het__rd": 28,
"het__ri": 25,
"het__rs": 5,
"hetalt__i": 1,
"homalt__d": 2,
"homalt__i": 9,
"homalt__s": 2,
"homref__r": 1,
"nuc__d": 586,
"nuc__i": 244,
"nuc__s": 7
},
"FP:.:CONF:QUERY": {
"Transitions": 248,
"Transversions": 239,
"al__d": 13,
"al__i": 8,
"al__s": 487,
"het__rd": 8,
"het__ri": 5,
"het__rs": 438,
"hetalt__s": 4,
"homalt__d": 5,
"homalt__i": 3,
"homalt__s": 41,
"nuc__d": 72,
"nuc__i": 23,
"nuc__s": 487
},
"FP:am::QUERY": {
"Transitions": 9,
"Transversions": 5,
"al__d": 4,
"al__i": 2,
"al__s": 14,
"het__rd": 4,
"het__ri": 2,
"het__rs": 12,
"homalt__s": 2,
"nuc__d": 5,
"nuc__i": 2,
"nuc__s": 14
},
"FP:am:CONF:QUERY": {
"Transitions": 8,
"Transversions": 2,
"al__s": 10,
"het__rs": 10,
"nuc__s": 10
},
"FP:lm::QUERY": {
"Transitions": 0,
"Transversions": 1,
"al__d": 1,
"al__i": 2,
"al__s": 1,
"het__rd": 1,
"het__ri": 1,
"homalt__i": 1,
"homalt__s": 1,
"nuc__d": 1,
"nuc__i": 10,
"nuc__s": 1
},
"FP:lm:CONF:QUERY": {
"Transitions": 77,
"Transversions": 69,
"al__d": 4,
"al__i": 9,
"al__s": 146,
"het__rd": 3,
"het__ri": 2,
"het__rs": 132,
"homalt__d": 1,
"homalt__i": 7,
"homalt__s": 14,
"nuc__d": 40,
"nuc__i": 37,
"nuc__s": 146
},
"TP:gm::QUERY": {
"Transitions": 52,
"Transversions": 42,
"al__d": 38,
"al__i": 28,
"al__s": 94,
"het__rd": 11,
"het__ri": 7,
"het__rs": 38,
"hetalt__i": 1,
"homalt__d": 27,
"homalt__i": 19,
"homalt__s": 56,
"nuc__d": 109,
"nuc__i": 61,
"nuc__s": 94
},
"TP:gm::TRUTH": {
"Transitions": 52,
"Transversions": 42,
"al__d": 38,
"al__i": 28,
"al__s": 94,
"het__rd": 11,
"het__ri": 7,
"het__rs": 38,
"hetalt__i": 1,
"homalt__d": 27,
"homalt__i": 19,
"homalt__s": 56,
"nuc__d": 109,
"nuc__i": 61,
"nuc__s": 94
},
"TP:gm:CONF:QUERY": {
"Transitions": 2524,
"Transversions": 966,
"al__d": 199,
"al__i": 182,
"al__s": 3490,
"het__rd": 116,
"het__ri": 79,
"het__rs": 1958,
"hetalt__i": 5,
"hetalt__id": 3,
"homalt__d": 80,
"homalt__i": 90,
"homalt__s": 1532,
"nuc__d": 528,
"nuc__i": 492,
"nuc__s": 3490
},
"TP:gm:CONF:TRUTH": {
"Transitions": 2524,
"Transversions": 966,
"al__d": 199,
"al__i": 182,
"al__s": 3490,
"het__rd": 116,
"het__ri": 79,
"het__rs": 1958,
"hetalt__i": 5,
"hetalt__id": 3,
"homalt__d": 80,
"homalt__i": 90,
"homalt__s": 1532,
"nuc__d": 528,
"nuc__i": 492,
"nuc__s": 3490
},
"UNK:.::QUERY": {
"Transitions": 2321,
"Transversions": 2054,
"al__d": 69,
"al__i": 66,
"al__s": 4375,
"het__rd": 57,
"het__ri": 43,
"het__rs": 3969,
"hetalt__i": 2,
"hetalt__id": 1,
"hetalt__s": 15,
"homalt__d": 11,
"homalt__i": 18,
"homalt__s": 376,
"nuc__d": 189,
"nuc__i": 136,
"nuc__s": 4375
},
"UNK:lm::QUERY": {
"Transitions": 157,
"Transversions": 134,
"al__d": 16,
"al__i": 10,
"al__s": 291,
"het__rd": 14,
"het__ri": 6,
"het__rs": 274,
"homalt__d": 2,
"homalt__i": 4,
"homalt__s": 17,
"nuc__d": 45,
"nuc__i": 12,
"nuc__s": 291
},
"all:QUERY": {
"Transitions": 5396,
"Transversions": 3512,
"al__d": 344,
"al__i": 307,
"al__s": 8908,
"het__rd": 214,
"het__ri": 145,
"het__rs": 6831,
"hetalt__i": 8,
"hetalt__id": 4,
"hetalt__s": 19,
"homalt__d": 126,
"homalt__i": 142,
"homalt__s": 2039,
"nocall__nc": 171,
"nuc__d": 989,
"nuc__i": 773,
"nuc__s": 8908
},
"all:TRUTH": {
"Transitions": 2603,
"Transversions": 1030,
"al__d": 315,
"al__i": 296,
"al__s": 3633,
"het__rd": 184,
"het__ri": 144,
"het__rs": 2009,
"hetalt__i": 9,
"hetalt__id": 3,
"homalt__d": 128,
"homalt__i": 131,
"homalt__s": 1624,
"homref__r": 1,
"nocall__nc": 5466,
"nuc__d": 2516,
"nuc__i": 1179,
"nuc__s": 3633
}
}
| {
"pile_set_name": "Github"
} |
'use strict';
var path = require('path');
var fs = require('fs');
/**
* @overview This function executes the machine that is responsible for running client tasks
*
* @param {String} projectRoot - path to the project root
* @param {Object} config - contains an ENV object
* @param {Object} config.ENV - contains other objects that will be added to the ember-cli config
* @return {String} environmentPath - the path to the environment.js (config file) to write to.
* @return {String} newEnvironment - the new environment/configuration to write to that file.
*/
module.exports = function createEmberConfig(projectRoot, config) {
var environmentPath = path.join(projectRoot, 'client', 'config', 'environment.js');
var environment = fs.readFileSync(environmentPath, { encoding: 'utf8' });
var endOfFunction = environment.indexOf('return ENV;');
var addKeys = Object.keys(config.ENV);
var configToAddgString = '';
for (var i = 0, len = addKeys.length; i < len; i++) {
configToAddgString += `ENV[\'${addKeys[i]}\'] = ${JSON.stringify(config.ENV[addKeys[i]], null, 2)};\n\n`;
}
var newEnvironment = environment.slice(0, endOfFunction) + configToAddgString + environment.slice(endOfFunction);
return [environmentPath, newEnvironment];
};
| {
"pile_set_name": "Github"
} |
// Copyright 2016 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//
// +build ppc64 s390x mips mips64
package unix
const isBigEndian = true
| {
"pile_set_name": "Github"
} |
# Since we rely on paths relative to the makefile location, abort if make isn't being run from there.
$(if $(findstring /,$(MAKEFILE_LIST)),$(error Please only invoke this makefile from the directory it resides in))
# The files that need updating when incrementing the version number.
VERSIONED_FILES := *.js *.json README*
# Add the local npm packages' bin folder to the PATH, so that `make` can find them, when invoked directly.
# Note that rather than using `$(npm bin)` the 'node_modules/.bin' path component is hard-coded, so that invocation works even from an environment
# where npm is (temporarily) unavailable due to having deactivated an nvm instance loaded into the calling shell in order to avoid interference with tests.
export PATH := $(shell printf '%s' "$$PWD/node_modules/.bin:$$PATH")
UTILS := semver
# Make sure that all required utilities can be located.
UTIL_CHECK := $(or $(shell PATH="$(PATH)" which $(UTILS) >/dev/null && echo 'ok'),$(error Did you forget to run `npm install` after cloning the repo? At least one of the required supporting utilities not found: $(UTILS)))
# Default target (by virtue of being the first non '.'-prefixed in the file).
.PHONY: _no-target-specified
_no-target-specified:
$(error Please specify the target to make - `make list` shows targets. Alternatively, use `npm test` to run the default tests; `npm run` shows all tests)
# Lists all targets defined in this makefile.
.PHONY: list
list:
@$(MAKE) -pRrn : -f $(MAKEFILE_LIST) 2>/dev/null | awk -v RS= -F: '/^# File/,/^# Finished Make data base/ {if ($$1 !~ "^[#.]") {print $$1}}' | command grep -v -e '^[^[:alnum:]]' -e '^$@$$command ' | sort
# All-tests target: invokes the specified test suites for ALL shells defined in $(SHELLS).
.PHONY: test
test:
@npm test
.PHONY: _ensure-tag
_ensure-tag:
ifndef TAG
$(error Please invoke with `make TAG=<new-version> release`, where <new-version> is either an increment specifier (patch, minor, major, prepatch, preminor, premajor, prerelease), or an explicit major.minor.patch version number)
endif
CHANGELOG_ERROR = $(error No CHANGELOG specified)
.PHONY: _ensure-changelog
_ensure-changelog:
@ (git status -sb --porcelain | command grep -E '^( M|[MA] ) CHANGELOG.md' > /dev/null) || (echo no CHANGELOG.md specified && exit 2)
# Ensures that the git workspace is clean.
.PHONY: _ensure-clean
_ensure-clean:
@[ -z "$$((git status --porcelain --untracked-files=no || echo err) | command grep -v 'CHANGELOG.md')" ] || { echo "Workspace is not clean; please commit changes first." >&2; exit 2; }
# Makes a release; invoke with `make TAG=<versionOrIncrementSpec> release`.
.PHONY: release
release: _ensure-tag _ensure-changelog _ensure-clean
@old_ver=`git describe --abbrev=0 --tags --match 'v[0-9]*.[0-9]*.[0-9]*'` || { echo "Failed to determine current version." >&2; exit 1; }; old_ver=$${old_ver#v}; \
new_ver=`echo "$(TAG)" | sed 's/^v//'`; new_ver=$${new_ver:-patch}; \
if printf "$$new_ver" | command grep -q '^[0-9]'; then \
semver "$$new_ver" >/dev/null || { echo 'Invalid version number specified: $(TAG) - must be major.minor.patch' >&2; exit 2; }; \
semver -r "> $$old_ver" "$$new_ver" >/dev/null || { echo 'Invalid version number specified: $(TAG) - must be HIGHER than current one.' >&2; exit 2; } \
else \
new_ver=`semver -i "$$new_ver" "$$old_ver"` || { echo 'Invalid version-increment specifier: $(TAG)' >&2; exit 2; } \
fi; \
printf "=== Bumping version **$$old_ver** to **$$new_ver** before committing and tagging:\n=== TYPE 'proceed' TO PROCEED, anything else to abort: " && read response && [ "$$response" = 'proceed' ] || { echo 'Aborted.' >&2; exit 2; }; \
replace "$$old_ver" "$$new_ver" -- $(VERSIONED_FILES) && \
git commit -m "v$$new_ver" $(VERSIONED_FILES) CHANGELOG.md && \
git tag -a -m "v$$new_ver" "v$$new_ver"
| {
"pile_set_name": "Github"
} |
Hash表是Memcached里面最重要的结构之一,其采用链接法来处理Hash冲突,当Hash表中的项太多时,也就是Hash冲突比较高的时候,Hash表的遍历就脱变成单链表,此时为了提供Hash的性能,Hash表需要扩容,Memcached的扩容条件是当表中元素个数超过Hash容量的1.5倍时就进行扩容,扩容过程由独立的线程来完成,扩容过程中会采用2个Hash表,将老表中的数据通过Hash算法映射到新表中,每次移动的桶的数目可以配置,默认是每次移动老表中的1个桶。
```
//hash表中增加元素
int assoc_insert(item *it, const uint32_t hv) {
unsigned int oldbucket;
//如果已经进行扩容且目前进行扩容还没到需要插入元素的桶,则将元素添加到旧桶中
if (expanding &&(oldbucket = (hv & hashmask(hashpower - 1))) >= expand_bucket)
{
it->h_next = old_hashtable[oldbucket];//添加元素
old_hashtable[oldbucket] = it;
} else {//如果没扩容,或者扩容已经到了新的桶中,则添加元素到新表中
it->h_next = primary_hashtable[hv & hashmask(hashpower)];//添加元素
primary_hashtable[hv & hashmask(hashpower)] = it;
}
hash_items++;//元素数目+1
//还没开始扩容,且表中元素个数已经超过Hash表容量的1.5倍
if (! expanding && hash_items > (hashsize(hashpower) * 3) / 2) {
assoc_start_expand();//唤醒扩容线程
}
MEMCACHED_ASSOC_INSERT(ITEM_key(it), it->nkey, hash_items);
return 1;
}
//唤醒扩容线程
static void assoc_start_expand(void) {
if (started_expanding)
return;
started_expanding = true;
pthread_cond_signal(&maintenance_cond);//唤醒信号量
}
//启动扩容线程,扩容线程在main函数中会启动,启动运行一遍之后会阻塞在条件变量maintenance_cond上面,插入元素超过规定,唤醒条件变量
static void *assoc_maintenance_thread(void *arg) {
//do_run_maintenance_thread的值为1,即该线程持续运行
while (do_run_maintenance_thread) {
int ii = 0;
item_lock_global();//加Hash表的全局锁
mutex_lock(&cache_lock);//加cache_lock锁
//执行扩容时,每次按hash_bulk_move个桶来扩容
for (ii = 0; ii < hash_bulk_move && expanding; ++ii) {
item *it, *next;
int bucket;
//老表每次移动一个桶中的一个元素
for (it = old_hashtable[expand_bucket]; NULL != it; it = next) {
next = it->h_next;//要移动的下一个元素
bucket = hash(ITEM_key(it), it->nkey, 0) & hashmask(hashpower);//按新的Hash规则进行定位
it->h_next = primary_hashtable[bucket];//挂载到新的Hash表中
primary_hashtable[bucket] = it;
}
old_hashtable[expand_bucket] = NULL;//旧表中的这个Hash桶已经按新规则完成了扩容
expand_bucket++;//老表中的桶计数+1
if (expand_bucket == hashsize(hashpower - 1)) {//hash表扩容结束,expand_bucket从0开始,一直递增
expanding = false;//修改扩容标志
free(old_hashtable);//释放老的表结构
STATS_LOCK();//更新一些统计信息
stats.hash_bytes -= hashsize(hashpower - 1) * sizeof(void *);
stats.hash_is_expanding = 0;
STATS_UNLOCK();
if (settings.verbose > 1)
fprintf(stderr, "Hash table expansion done\n");
}
}
mutex_unlock(&cache_lock);//释放cache_lock锁
item_unlock_global();//释放Hash表的全局锁
if (!expanding) {//完成扩容
//修改Hash表的锁类型,此时锁类型更新为分段锁,默认是分段锁,在进行扩容时,改为全局锁
switch_item_lock_type(ITEM_LOCK_GRANULAR);
slabs_rebalancer_resume();//释放用于扩容的锁
/* We are done expanding.. just wait for next invocation */
mutex_lock(&cache_lock);//加cache_lock锁,保护条件变量
started_expanding = false;//修改扩容标识
pthread_cond_wait(&maintenance_cond, &cache_lock);//阻塞扩容线程
mutex_unlock(&cache_lock);
slabs_rebalancer_pause();//加用于扩容的锁
switch_item_lock_type(ITEM_LOCK_GLOBAL);//修改锁类型为全局锁
mutex_lock(&cache_lock);//临时用来实现临界区
assoc_expand();//执行扩容
mutex_unlock(&cache_lock);
}
}
return NULL;
}
//按2倍容量扩容Hash表
static void assoc_expand(void) {
old_hashtable = primary_hashtable;//old_hashtable指向主Hash表
primary_hashtable = calloc(hashsize(hashpower + 1), sizeof(void *));//申请新的空间
if (primary_hashtable) {//空间申请成功
if (settings.verbose > 1)
fprintf(stderr, "Hash table expansion starting\n");
hashpower++;//hash等级+1
expanding = true;//扩容标识打开
expand_bucket = 0;
STATS_LOCK();//更新全局统计信息
stats.hash_power_level = hashpower;
stats.hash_bytes += hashsize(hashpower) * sizeof(void *);
stats.hash_is_expanding = 1;
STATS_UNLOCK();
} else {//空间事情失败
primary_hashtable = old_hashtable;
}
}
```
| {
"pile_set_name": "Github"
} |
#include <iostream>
#include <vector>
#include <chrono>
#include <random>
#include <thread>
#include <string_view>
#include <mutex>
#include <string>
class logger
{
protected:
logger() {}
public:
static logger& instance()
{
static logger lg;
return lg;
}
logger(logger const &) = delete;
logger& operator=(logger const &) = delete;
void log(std::string_view message)
{
std::lock_guard<std::mutex> lock(mt);
std::cout << "LOG: " << message << std::endl;
}
private:
std::mutex mt;
};
int main()
{
std::vector<std::thread> modules;
for(int id = 1; id <= 5; ++id)
{
modules.emplace_back([id](){
std::random_device rd;
std::mt19937 mt(rd());
std::uniform_int_distribution<> ud(100, 1000);
logger::instance().log("module " + std::to_string(id) + " started");
std::this_thread::sleep_for(std::chrono::milliseconds(ud(mt)));
logger::instance().log("module " + std::to_string(id) + " finished");
});
}
for(auto & m : modules) m.join();
}
| {
"pile_set_name": "Github"
} |
{
"images" : [
{
"idiom" : "universal",
"scale" : "1x"
},
{
"idiom" : "universal",
"filename" : "[email protected]",
"scale" : "2x"
},
{
"idiom" : "universal",
"scale" : "3x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
} | {
"pile_set_name": "Github"
} |
package dasm
import (
"fmt"
"shanhu.io/smlvm/arch"
)
// Dasm disassembles a byte block.
func Dasm(bs []byte, addr uint32) []*Line {
var ret []*Line
base := addr
add := func(b []byte) {
inst := arch.Endian.Uint32(b)
ret = append(ret, NewLine(addr, inst))
addr += 4
}
nline := len(bs) / 4
for i := 0; i < nline; i++ {
off := i * 4
add(bs[off : off+4])
}
// residue
if len(bs)%4 != 0 {
var buf [4]byte
copy(buf[:], bs[nline*4:])
add(buf[:])
}
// link the jumps
for _, line := range ret {
if !line.IsJump {
continue
}
index := int(line.To-base) / 4
if index >= 0 && index < nline {
line.ToLine = ret[index]
}
}
return ret
}
// Print prints a byte block as assembly lines.
func Print(bs []byte, addr uint32) {
lines := Dasm(bs, addr)
for _, line := range lines {
fmt.Println(line)
}
}
| {
"pile_set_name": "Github"
} |
// Copyright 2019 (c) rust-themis developers
//
// 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.
//! Dummy file used to verify that the compiler sees native Themis library.
#include <themis/themis.h>
void libthemis_sys_unused(void)
{
themis_gen_ec_key_pair(NULL, NULL, NULL, NULL);
}
| {
"pile_set_name": "Github"
} |
#!/bin/bash
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Download models and check that models can be correctly be loaded. Can be
# disabled by passing CHECK_MODELS=0 as an environment variable
set -eox pipefail
if [ "$CHECK_MODELS" == "0" ]; then
echo "Skipping downloading and checking models!"
exit 0;
fi
python -m bugbug_http.download_models
| {
"pile_set_name": "Github"
} |
---
title: Explore colocated tables in YugabyteDB on macOS
headerTitle: Colocated tables
linkTitle: Colocated tables
description: Create and use colocated tables in a local YugabyteDB cluster on macOS.
aliases:
- /latest/explore/colocated-tables/
menu:
latest:
identifier: colocated-tables-1-macos
parent: explore
weight: 245
isTocNested: true
showAsideToc: true
---
<ul class="nav nav-tabs-alt nav-tabs-yb">
<li >
<a href="/latest/explore/colocated-tables/macos" class="nav-link active">
<i class="fab fa-apple" aria-hidden="true"></i>
macOS
</a>
</li>
<li >
<a href="/latest/explore/colocated-tables/linux" class="nav-link">
<i class="fab fa-linux" aria-hidden="true"></i>
Linux
</a>
</li>
</ul>
Colocated tables can dramatically increase the number of relations (tables, indexes, etc.) that can be supported per node while keeping the number of tablets per node low.
In workloads that do very little IOPS and have a small data set, the bottleneck shifts from CPU/disk/network to the number of tablets one can host per node. There are practical limitations to the number of tablets that YugabyteDB can handle per node, even though this number could be very high, depending on the workload pattern. Since each table by default requires at least one tablet without colocation, a database with 5000 relations (tables, indexes, etc.) will have at least 5000 tablets, which increases the CPU/disk/network overhead. If most of these relations are small in size, then it's beneficial to use colocated tables.
Colocating various SQL tables puts all of their data into a single tablet, called the _colocation tablet_. Note that all the data in the colocation tablet is still replicated across 3 nodes (or whatever the replication factor is).
This tutorial uses the [yb-ctl](../../../admin/yb-ctl) local cluster management utility.
## 1. Create a universe
```sh
$ ./bin/yb-ctl create
```
## 2. Create a colocated database
Connect to the cluster using `ysqlsh`.
```sh
$ ./bin/ysqlsh -h 127.0.0.1
```
Create database with `colocated = true` option.
```postgresql
yugabyte=# CREATE DATABASE northwind WITH colocated = true;
```
This will create a database `northwind` whose tables will be stored on a single tablet.
## 3. Create tables
Connect to `northwind` database and create tables using standard `CREATE TABLE` command.
The tables will be colocated on a single tablet since the database was created with `colocated = true` option.
```postgresql
yugabyte=# \c northwind
yugabyte=# CREATE TABLE customers (
customer_id bpchar,
company_name character varying(40) NOT NULL,
contact_name character varying(30),
contact_title character varying(30),
PRIMARY KEY(customer_id ASC)
);
yugabyte=# CREATE TABLE categories (
category_id smallint,
category_name character varying(15) NOT NULL,
description text,
PRIMARY KEY(category_id ASC)
);
yugabyte=# CREATE TABLE suppliers (
supplier_id smallint,
company_name character varying(40) NOT NULL,
contact_name character varying(30),
contact_title character varying(30),
PRIMARY KEY(supplier_id ASC)
);
yugabyte=# CREATE TABLE products (
product_id smallint,
product_name character varying(40) NOT NULL,
supplier_id smallint,
category_id smallint,
quantity_per_unit character varying(20),
unit_price real,
PRIMARY KEY(product_id ASC),
FOREIGN KEY (category_id) REFERENCES categories,
FOREIGN KEY (supplier_id) REFERENCES suppliers
);
```
If you go to tables view in [master UI](http://localhost:7000/tables), you'll see that all tables have the same tablet.


## 4. Opt out table from colocation
YugabyteDB has the flexibility to opt a table out of colocation. In this case, the table will use its own set of tablets
instead of using the same tablet as the colocated database. This is useful for scaling out tables that you know are likely
to be large. You can do this by using `colocated = false` option while creating table.
```postgresql
yugabyte=# CREATE TABLE orders (
order_id smallint NOT NULL PRIMARY KEY,
customer_id bpchar,
order_date date,
ship_address character varying(60),
ship_city character varying(15),
ship_postal_code character varying(10),
FOREIGN KEY (customer_id) REFERENCES customers
) WITH (colocated = false);
```
If you go to tables view in [master UI](http://localhost:7000/tables), you'll see that `orders` table has its own set of tablets.

## 5. Reading and writing data in colocated tables
You can use standard [YSQL DML statements](../../../api/ysql) to read and write data in colocated tables. YSQL's query planner and executor
will handle routing the data to the correct tablet.
## What's next?
For more information, see the architecture for [colocated tables](https://github.com/yugabyte/yugabyte-db/blob/master/architecture/design/ysql-colocated-tables.md).
| {
"pile_set_name": "Github"
} |
/*
* Created by DSL Platform
* v1.5.6040.24209
*/
package com.dslplatform.json.generated;
public class GA0A0Lc implements java.lang.Cloneable, java.io.Serializable, com.dslplatform.json.JsonObject {
public GA0A0Lc() {
this.ID = java.util.UUID.randomUUID();
this.setGE0A0Lc(new GE0A0Lc());
this.URI = this.ID.toString();
}
private String URI;
public String getURI() {
return this.URI;
}
@Override
public int hashCode() {
return URI.hashCode();
}
@Override
public boolean equals(final Object obj) {
if (this == obj)
return true;
if (obj == null || obj instanceof GA0A0Lc == false)
return false;
final GA0A0Lc other = (GA0A0Lc) obj;
return URI.equals(other.URI);
}
public boolean deepEquals(final GA0A0Lc other) {
if (this == other)
return true;
if (other == null)
return false;
if (!URI.equals(other.URI))
return false;
if(!(this.ID.equals(other.ID)))
return false;
if(!(this.gE0A0Lc == other.gE0A0Lc || this.gE0A0Lc != null && this.gE0A0Lc.equals(other.gE0A0Lc)))
return false;
return true;
}
private GA0A0Lc(GA0A0Lc other) {
this.URI = other.URI;
this.ID = other.ID;
this.gE0A0Lc = other.gE0A0Lc == null ? null : (GE0A0Lc)(other.gE0A0Lc.clone());
}
@Override
public Object clone() {
return new GA0A0Lc(this);
}
@Override
public String toString() {
return "GA0A0Lc(" + URI + ')';
}
public GA0A0Lc(
final GE0A0Lc gE0A0Lc) {
setGE0A0Lc(gE0A0Lc);
this.URI = this.ID.toString();
}
private static final long serialVersionUID = 3888932737745197233L;
private java.util.UUID ID;
public java.util.UUID getID() {
return ID;
}
private GA0A0Lc setID(final java.util.UUID value) {
if(value == null) throw new IllegalArgumentException("Property \"ID\" cannot be null!");
this.ID = value;
return this;
}
private GE0A0Lc gE0A0Lc;
public GE0A0Lc getGE0A0Lc() {
return gE0A0Lc;
}
public GA0A0Lc setGE0A0Lc(final GE0A0Lc value) {
if(value == null) throw new IllegalArgumentException("Property \"gE0A0Lc\" cannot be null!");
this.gE0A0Lc = value;
return this;
}
public void serialize(final com.dslplatform.json.JsonWriter sw, final boolean minimal) {
sw.writeByte(com.dslplatform.json.JsonWriter.OBJECT_START);
if (minimal) {
__serializeJsonObjectMinimal(this, sw, false);
} else {
__serializeJsonObjectFull(this, sw, false);
}
sw.writeByte(com.dslplatform.json.JsonWriter.OBJECT_END);
}
static void __serializeJsonObjectMinimal(final GA0A0Lc self, com.dslplatform.json.JsonWriter sw, boolean hasWrittenProperty) {
sw.writeAscii("\"URI\":");
com.dslplatform.json.StringConverter.serializeShort(self.URI, sw);
if (!(self.getID().getMostSignificantBits() == 0 && self.getID().getLeastSignificantBits() == 0)) {
sw.writeAscii(",\"ID\":", 6);
com.dslplatform.json.UUIDConverter.serialize(self.getID(), sw);
}
if(self.gE0A0Lc != null) {
sw.writeAscii(",\"gE0A0Lc\":{", 12);
GE0A0Lc.__serializeJsonObjectMinimal(self.gE0A0Lc, sw, false);
sw.writeByte(com.dslplatform.json.JsonWriter.OBJECT_END);
}
}
static void __serializeJsonObjectFull(final GA0A0Lc self, com.dslplatform.json.JsonWriter sw, boolean hasWrittenProperty) {
sw.writeAscii("\"URI\":");
com.dslplatform.json.StringConverter.serializeShort(self.URI, sw);
sw.writeAscii(",\"ID\":", 6);
com.dslplatform.json.UUIDConverter.serialize(self.getID(), sw);
if(self.gE0A0Lc != null) {
sw.writeAscii(",\"gE0A0Lc\":{", 12);
GE0A0Lc.__serializeJsonObjectFull(self.gE0A0Lc, sw, false);
sw.writeByte(com.dslplatform.json.JsonWriter.OBJECT_END);
} else {
sw.writeAscii(",\"gE0A0Lc\":null", 15);
}
}
public static final com.dslplatform.json.JsonReader.ReadJsonObject<GA0A0Lc> JSON_READER = new com.dslplatform.json.JsonReader.ReadJsonObject<GA0A0Lc>() {
@SuppressWarnings("unchecked")
@Override
public GA0A0Lc deserialize(final com.dslplatform.json.JsonReader reader) throws java.io.IOException {
return new GA0A0Lc(reader);
}
};
private GA0A0Lc(final com.dslplatform.json.JsonReader<Object> reader) throws java.io.IOException {
String _URI_ = "";
java.util.UUID _ID_ = new java.util.UUID(0L, 0L);
GE0A0Lc _gE0A0Lc_ = null;
byte nextToken = reader.last();
if(nextToken != '}') {
int nameHash = reader.fillName();
nextToken = reader.getNextToken();
if(nextToken == 'n') {
if (reader.wasNull()) {
nextToken = reader.getNextToken();
} else {
throw new java.io.IOException("Expecting 'u' (as null) at position: " + reader.positionInStream() + ". Found " + (char)nextToken);
}
} else {
switch(nameHash) {
case 2053729053:
_URI_ = reader.readString();
nextToken = reader.getNextToken();
break;
case 1458105184:
_ID_ = com.dslplatform.json.UUIDConverter.deserialize(reader);
nextToken = reader.getNextToken();
break;
case 1495523619:
if (nextToken == '{') {
reader.getNextToken();
_gE0A0Lc_ = GE0A0Lc.JSON_READER.deserialize(reader);
nextToken = reader.getNextToken();
} else throw new java.io.IOException("Expecting '{' at position: " + reader.positionInStream() + ". Found " + (char)nextToken);
break;
default:
nextToken = reader.skip();
break;
}
}
while (nextToken == ',') {
nextToken = reader.getNextToken();
nameHash = reader.fillName();
nextToken = reader.getNextToken();
if(nextToken == 'n') {
if (reader.wasNull()) {
nextToken = reader.getNextToken();
continue;
} else {
throw new java.io.IOException("Expecting 'u' (as null) at position: " + reader.positionInStream() + ". Found " + (char)nextToken);
}
}
switch(nameHash) {
case 2053729053:
_URI_ = reader.readString();
nextToken = reader.getNextToken();
break;
case 1458105184:
_ID_ = com.dslplatform.json.UUIDConverter.deserialize(reader);
nextToken = reader.getNextToken();
break;
case 1495523619:
if (nextToken == '{') {
reader.getNextToken();
_gE0A0Lc_ = GE0A0Lc.JSON_READER.deserialize(reader);
nextToken = reader.getNextToken();
} else throw new java.io.IOException("Expecting '{' at position: " + reader.positionInStream() + ". Found " + (char)nextToken);
break;
default:
nextToken = reader.skip();
break;
}
}
if (nextToken != '}') {
throw new java.io.IOException("Expecting '}' at position: " + reader.positionInStream() + ". Found " + (char)nextToken);
}
}
this.URI = _URI_;
this.ID = _ID_;
if(_gE0A0Lc_ == null) _gE0A0Lc_ = new GE0A0Lc();
this.gE0A0Lc = _gE0A0Lc_;
}
public static Object deserialize(final com.dslplatform.json.JsonReader<Object> reader) throws java.io.IOException {
switch (reader.getNextToken()) {
case 'n':
if (reader.wasNull())
return null;
throw new java.io.IOException("Invalid null value found at: " + reader.positionInStream());
case '{':
reader.getNextToken();
return new GA0A0Lc(reader);
case '[':
return reader.deserializeNullableCollection(JSON_READER);
default:
throw new java.io.IOException("Invalid char value found at: " + reader.positionInStream() + ". Expecting null, { or [. Found: " + (char)reader.last());
}
}
}
| {
"pile_set_name": "Github"
} |
using System.Collections.Generic;
namespace ClassifiedAds.Infrastructure.MessageBrokers.AzureServiceBus
{
public class AzureServiceBusOptions
{
public string ConnectionString { get; set; }
public Dictionary<string, string> QueueNames { get; set; }
}
}
| {
"pile_set_name": "Github"
} |
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Copyright by The HDF Group. *
* Copyright by the Board of Trustees of the University of Illinois. *
* All rights reserved. *
* *
* This file is part of HDF5. The full HDF5 copyright notice, including *
* terms governing use, modification, and redistribution, is contained in *
* the files COPYING and Copyright.html. COPYING can be found at the root *
* of the source code distribution tree; Copyright.html can be found at the *
* root level of an installed copy of the electronic HDF5 document set and *
* is linked from the top-level documents page. It can also be found at *
* http://hdfgroup.org/HDF5/doc/Copyright.html. If you do not have *
* access to either file, you may request a copy from [email protected]. *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/*
* Small program to illustrate the "misalignment" of members within a compound
* datatype, in a datatype fixed by H5Tget_native_type().
*/
#include <string.h>
#include <stdlib.h>
/*#include <unistd.h> *//* Required for unlink() */
#include "hdf5.h"
#include "H5private.h"
#include "h5tools.h"
const char *fname = "talign.h5";
const char *setname = "align";
/*
* This program assumes that there is no extra space between the members 'Ok'
* and 'Not Ok', (there shouldn't be because they are of the same atomic type
* H5T_NATIVE_FLOAT, and they are placed within the compound next to one
* another per construction)
*/
int main(void)
{
hid_t fil,spc,set;
hid_t cs6, cmp, fix;
hid_t cmp1, cmp2, cmp3;
hid_t plist;
hid_t array_dt;
hsize_t dim[2];
hsize_t cdim[4];
char string5[5];
float fok[2] = {1234.0f, 2341.0f};
float fnok[2] = {5678.0f, 6785.0f};
float *fptr;
char *data = NULL;
int result = 0;
herr_t error = 1;
printf("%-70s", "Testing alignment in compound datatypes");
strcpy(string5, "Hi!");
HDunlink(fname);
fil = H5Fcreate(fname, H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);
if (fil < 0) {
puts("*FAILED*");
return 1;
}
H5E_BEGIN_TRY {
(void)H5Ldelete(fil, setname, H5P_DEFAULT);
} H5E_END_TRY;
cs6 = H5Tcopy(H5T_C_S1);
H5Tset_size(cs6, sizeof(string5));
H5Tset_strpad(cs6, H5T_STR_NULLPAD);
cmp = H5Tcreate(H5T_COMPOUND, sizeof(fok) + sizeof(string5) + sizeof(fnok));
H5Tinsert(cmp, "Awkward length", 0, cs6);
cdim[0] = sizeof(fok) / sizeof(float);
array_dt = H5Tarray_create2(H5T_NATIVE_FLOAT, 1, cdim);
H5Tinsert(cmp, "Ok", sizeof(string5), array_dt);
H5Tclose(array_dt);
cdim[0] = sizeof(fnok) / sizeof(float);
array_dt = H5Tarray_create2(H5T_NATIVE_FLOAT, 1, cdim);
H5Tinsert(cmp, "Not Ok", sizeof(fok) + sizeof(string5), array_dt);
H5Tclose(array_dt);
fix = h5tools_get_native_type(cmp);
cmp1 = H5Tcreate(H5T_COMPOUND, sizeof(fok));
cdim[0] = sizeof(fok) / sizeof(float);
array_dt = H5Tarray_create2(H5T_NATIVE_FLOAT, 1, cdim);
H5Tinsert(cmp1, "Ok", 0, array_dt);
H5Tclose(array_dt);
cmp2 = H5Tcreate(H5T_COMPOUND, sizeof(string5));
H5Tinsert(cmp2, "Awkward length", 0, cs6);
cmp3 = H5Tcreate(H5T_COMPOUND, sizeof(fnok));
cdim[0] = sizeof(fnok) / sizeof(float);
array_dt = H5Tarray_create2(H5T_NATIVE_FLOAT, 1, cdim);
H5Tinsert(cmp3, "Not Ok", 0, array_dt);
H5Tclose(array_dt);
plist = H5Pcreate(H5P_DATASET_XFER);
if((error = H5Pset_preserve(plist, 1)) < 0)
goto out;
/*
* Create a small dataset, and write data into it we write each field
* in turn so that we are avoid alignment issues at this point
*/
dim[0] = 1;
spc = H5Screate_simple(1, dim, NULL);
set = H5Dcreate2(fil, setname, cmp, spc, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);
H5Dwrite(set, cmp1, spc, H5S_ALL, plist, fok);
H5Dwrite(set, cmp2, spc, H5S_ALL, plist, string5);
H5Dwrite(set, cmp3, spc, H5S_ALL, plist, fnok);
H5Dclose(set);
/* Now open the set, and read it back in */
data = (char *)HDmalloc(H5Tget_size(fix));
if(!data) {
perror("malloc() failed");
abort();
}
set = H5Dopen2(fil, setname, H5P_DEFAULT);
H5Dread(set, fix, spc, H5S_ALL, H5P_DEFAULT, data);
fptr = (float *)(data + H5Tget_member_offset(fix, 1));
out:
if(error < 0) {
result = 1;
puts("*FAILED - HDF5 library error*");
} else if(fok[0] != fptr[0] || fok[1] != fptr[1]
|| fnok[0] != fptr[2] || fnok[1] != fptr[3]) {
char *mname;
result = 1;
mname = H5Tget_member_name(fix, 0);
printf("%14s (%2d) %6s = %s\n",
mname ? mname : "(null)", (int)H5Tget_member_offset(fix,0),
string5, (char *)(data + H5Tget_member_offset(fix, 0)));
if(mname)
H5free_memory(mname);
fptr = (float *)(data + H5Tget_member_offset(fix, 1));
mname = H5Tget_member_name(fix, 1);
printf("Data comparison:\n"
"%14s (%2d) %6f = %f\n"
" %6f = %f\n",
mname ? mname : "(null)", (int)H5Tget_member_offset(fix,1),
(double)fok[0], (double)fptr[0],
(double)fok[1], (double)fptr[1]);
if(mname)
H5free_memory(mname);
fptr = (float *)(data + H5Tget_member_offset(fix, 2));
mname = H5Tget_member_name(fix, 2);
printf("%14s (%2d) %6f = %f\n"
" %6f = %6f\n",
mname ? mname : "(null)", (int)H5Tget_member_offset(fix,2),
(double)fnok[0], (double)fptr[0],
(double)fnok[1], (double)fptr[1]);
if(mname)
H5free_memory(mname);
fptr = (float *)(data + H5Tget_member_offset(fix, 1));
printf("\n"
"Short circuit\n"
" %6f = %f\n"
" %6f = %f\n"
" %6f = %f\n"
" %6f = %f\n",
(double)fok[0], (double)fptr[0],
(double)fok[1], (double)fptr[1],
(double)fnok[0], (double)fptr[2],
(double)fnok[1], (double)fptr[3]);
puts("*FAILED - compound type alignmnent problem*");
} else {
puts(" PASSED");
}
if(data)
HDfree(data);
H5Sclose(spc);
H5Tclose(cmp);
H5Tclose(cmp1);
H5Tclose(cmp2);
H5Tclose(cmp3);
H5Pclose(plist);
H5Fclose(fil);
HDunlink(fname);
fflush(stdout);
return result;
}
/*-------------------------------------------------------------------------
* Function: h5tools_get_native_type
*
* Purpose: Wrapper around H5Tget_native_type() to work around
* Problems with bitfields.
*
* Return: Success: datatype ID
*
* Failure: FAIL
*
* Programmer: Quincey Koziol
* Tuesday, October 5, 2004
*
* Modifications:
*
*-------------------------------------------------------------------------
*/
hid_t
h5tools_get_native_type(hid_t type)
{
hid_t p_type;
H5T_class_t type_class;
type_class = H5Tget_class(type);
if(type_class==H5T_BITFIELD)
p_type=H5Tcopy(type);
else
p_type = H5Tget_native_type(type,H5T_DIR_DEFAULT);
return(p_type);
}
| {
"pile_set_name": "Github"
} |
.. index:: index; compound
.. index:: compound index
.. _index-type-compound:
================
Compound Indexes
================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
MongoDB supports *compound indexes*, where a single index structure
holds references to multiple fields [#compound-index-field-limit]_
within a collection's documents. The following diagram illustrates an
example of a compound index on two fields:
.. include:: /images/index-compound-key.rst
.. [#compound-index-field-limit]
MongoDB imposes a :limit:`limit of 32 fields for any compound index
<Number of Indexed Fields in a Compound Index>`.
Compound indexes can support queries that match on multiple fields.
Create a Compound Index
-----------------------
To create a :ref:`compound index <index-type-compound>` use an
operation that resembles the following prototype:
.. code-block:: javascript
db.collection.createIndex( { <field1>: <type>, <field2>: <type2>, ... } )
.. include:: /includes/fact-index-specification-field-value.rst
.. important:: You may not create compound indexes that have
``hashed`` index type. You will receive an error if you attempt to
create a compound index that includes :doc:`a hashed index
field </core/index-hashed>`.
Consider a collection named ``products`` that holds documents that
resemble the following document:
.. code-block:: javascript
{
"_id": ObjectId(...),
"item": "Banana",
"category": ["food", "produce", "grocery"],
"location": "4th Street Store",
"stock": 4,
"type": "cases"
}
The following operation creates an ascending index on the ``item`` and
``stock`` fields:
.. code-block:: javascript
db.products.createIndex( { "item": 1, "stock": 1 } )
The order of the fields listed in a compound index is important. The
index will contain references to documents sorted first by the values
of the ``item`` field and, within each value of the ``item`` field, sorted by
values of the stock field. See :ref:`index-ascending-and-descending`
for more information.
In addition to supporting queries that match on all the index fields,
compound indexes can support queries that match on the prefix of the
index fields. That is, the index supports queries on the ``item`` field
as well as both ``item`` and ``stock`` fields:
.. code-block:: javascript
db.products.find( { item: "Banana" } )
db.products.find( { item: "Banana", stock: { $gt: 5 } } )
For details, see :ref:`compound-index-prefix`.
.. index:: index; sort order
.. _index-ascending-and-descending:
Sort Order
----------
Indexes store references to fields in either ascending (``1``) or
descending (``-1``) sort order. For single-field indexes, the sort
order of keys doesn't matter because MongoDB can traverse the index in
either direction. However, for :ref:`compound indexes
<index-type-compound>`, sort order can matter in determining whether
the index can support a sort operation.
Consider a collection ``events`` that contains documents with the
fields ``username`` and ``date``. Applications can issue queries that
return results sorted first by ascending ``username`` values and then
by descending (i.e. more recent to last) ``date`` values, such as:
.. code-block:: javascript
db.events.find().sort( { username: 1, date: -1 } )
or queries that return results sorted first by descending ``username``
values and then by ascending ``date`` values, such as:
.. code-block:: javascript
db.events.find().sort( { username: -1, date: 1 } )
The following index can support both these sort operations:
.. code-block:: javascript
db.events.createIndex( { "username" : 1, "date" : -1 } )
However, the above index **cannot** support sorting by ascending
``username`` values and then by ascending ``date`` values, such as the
following:
.. code-block:: javascript
db.events.find().sort( { username: 1, date: 1 } )
For more information on sort order and compound indexes, see
:doc:`/tutorial/sort-results-with-indexes`.
.. _compound-index-prefix:
Prefixes
--------
Index prefixes are the *beginning* subsets of indexed fields. For
example, consider the following compound index:
.. code-block:: javascript
{ "item": 1, "location": 1, "stock": 1 }
The index has the following index prefixes:
- ``{ item: 1 }``
- ``{ item: 1, location: 1 }``
For a compound index, MongoDB can use the index to support queries on
the index prefixes. As such, MongoDB can use the index for queries on
the following fields:
- the ``item`` field,
- the ``item`` field *and* the ``location`` field,
- the ``item`` field *and* the ``location`` field *and* the ``stock`` field.
MongoDB can also use the index to support a query on the ``item`` and
``stock`` fields, since the ``item`` field corresponds to a prefix.
However, in this case the index would not be as efficient in supporting
the query as it would be if the index were on only ``item`` and
``stock``. Index fields are parsed in order; if a query omits a
particular index prefix, it is unable to make use of any index fields
that follow that prefix.
Since a query on ``item`` and ``stock`` omits the ``location`` index
prefix, it cannot use the ``stock`` index field which follows
``location``. Only the ``item`` field in the index can support this
query. See :ref:`create-indexes-to-support-queries` for
more information.
MongoDB cannot use the index to support queries that include the
following fields since without the ``item`` field, none of the listed
fields correspond to a prefix index:
- the ``location`` field,
- the ``stock`` field, or
- the ``location`` and ``stock`` fields.
If you have a collection that has both a compound index and an index on
its prefix (e.g. ``{ a: 1, b: 1 }`` and ``{ a: 1 }``), if neither index
has a sparse or unique constraint, then you can remove the index on the
prefix (e.g. ``{ a: 1 }``). MongoDB will use the compound index in all
of the situations that it would have used the prefix index.
Index Intersection
------------------
.. include:: /includes/fact-index-intersection-vs-compound-indexes.rst
Additional Considerations
-------------------------
.. include:: /includes/index-tutorials-considerations.rst
| {
"pile_set_name": "Github"
} |
\header {
title = "Adeste Fideles"
composer = "John Francis Wade (1711-1786), circa 1743"
mutopiatitle = "Adeste Fideles (hymntune)"
mutopiacomposer = "WadeJF"
mutopiainstrument = "Voice (SATB)"
copyright = "Public Domain"
date = "1743"
maintainer = "Steve Dunlop"
maintainerWeb = "http://www.nerstrand.net"
maintainerEmail = "[email protected]"
style = "Hymn"
source = "www.cyberhymnal.org"
lastupdated = "2008/1/12"
footer = "Mutopia-2008/01/13-1220"
tagline = \markup { \override #'(box-padding . 1.0) \override #'(baseline-skip . 2.7) \box \center-align { \small \line { Sheet music from \with-url #"http://www.MutopiaProject.org" \line { \teeny www. \hspace #-1.0 MutopiaProject \hspace #-1.0 \teeny .org \hspace #0.5 } • \hspace #0.5 \italic Free to download, with the \italic freedom to distribute, modify and perform. } \line { \small \line { Typeset using \with-url #"http://www.LilyPond.org" \line { \teeny www. \hspace #-1.0 LilyPond \hspace #-1.0 \teeny .org } by \maintainer \hspace #-1.0 . \hspace #0.5 Reference: \footer } } \line { \teeny \line { This sheet music has been placed in the public domain by the typesetter, for details see: \hspace #-0.5 \with-url #"http://creativecommons.org/licenses/publicdomain" http://creativecommons.org/licenses/publicdomain } } } }
}
\version "2.10.10"
% #(set-default-paper-size "letter")
Soprano = { \time 4/4 \partial 4 { \key g \major g'4 g'2 d'4 g' a'2 d' b'4 a' b' c'' b'2 a'4 g' g'2 fis'4 e' fis' g' a' b' fis'2 e'4. d'8 d'1 d''2 c''4 b' c''2 b' a'4 b' g' a' fis'4. e'8 d'4 b' b' a' b' c'' b'2 a'4 b' b' a' b' c'' b'2 a'4 b' c'' b' a' g' fis'2 g'4 c'' b'2 a'4. g'8 g'2. s4 \bar "|." } }
Alto = { { \key g \major d'4 d'2 d'4 d' d'2 d' d'4 d' d' e' d'2 d'4 b b cis' d' cis' d'2 d'4 d' d'2 cis'4. d'8 d'1 d'2 e'8 fis' g'4 g' fis' g'2 d'4 d' e' e' d'2 d'4 b' b' a' b' c'' b'2 a'4 d' d' d' d' d' d'2 d'4 g' e'8 fis' g'4 d' d'8 cis' d'2 d'4 e' d'2 d'4. b8 b2. s4 \bar "|." } }
Tenor = { { \key g \major b4 b2 b4 b a2 a g4 a g g g2 fis4 g g2 a4 a a g fis e a2 g4. fis8 fis1 b2 c'4 d' c'2 d' a4 g b c' a4. g8 fis4 r r1 r2. g4 g fis g a g2 fis4 d' c' d' a a a2 g4 g g2 fis4. g8 g2. s4 \bar "|." } }
Bass = { { \key g \major g4 g2 b4 g fis2 fis g4 fis g c d2 d4 e e2 d4 a, d b, fis, g, a,2 a,4. d8 d1 b2 a4 g a2 g fis4 g e c d2 d4 r r1 r2. g4 g fis g a g2 fis4 g a g fis e d c b, c d2 d4. g,8 g,2. s4 \bar "|." } }
\score {
\context GrandStaff <<
\context Staff = upper <<
\set Staff.printPartCombineTexts = ##f
\partcombine
{ #(set-accidental-style 'modern-cautionary) \Soprano }
{ \Alto}
>>
\context Staff = lower <<
\set Staff.printPartCombineTexts = ##f
\clef bass
\partcombine { #(set-accidental-style 'modern-cautionary) \Tenor }
{ \Bass }
>>
>>
\midi { \context { \Score tempWholesPerMinute = #(ly:make-moment 55 4 ) } }
\layout {
between-system-space = 1\mm
\context {
\Score
% defaults
% (shortest-duration-space . 2.0)
% (spacing-increment . 1.2)
% (base-shortest-duration . ,(ly:make-moment 1 8))
% tighter spacing
\override SpacingSpanner #'shortest-duration-space = #2.8
\override SpacingSpanner #'spacing-increment = #0.6
\override SpacingSpanner #'base-shortest-duration = #(ly:make-moment 1 8)
\remove "Bar_number_engraver"
}
\context { \Staff
\override VerticalAxisGroup #'minimum-Y-extent = #'(-1 . 1)
}
}
}
\paper { first-page-number = 2
print-first-page-number = ##t }
% -- ABC Source file follows --
%X:1
%T:Adeste Fideles
%M:4/4
%L:1/4
%C:John Francis Wade (1711-1786), circa 1743
%Q:1/4=55
%F:adeste_fideles.abc
%N:Public domain
%G:
%S:From www.cyberhymnal.org and crosschecked against other sources
%K:G
%I:Partial=4 Title=O Come, All Ye Faithful
%V:1
%G2G4D2G2A4D4B2A2B2c2B4A2G2G4F2E2F2G2A2B2F4E3D1D8d4c2B2c4B4A2B2G2A2F3E1D2B2B2A2B2c2B4A2B2B2A2B2c2B4A2B2c2B2A2G2F4G2c2B4A3G1G6
%V:2
%D2D4D2D2D4D4D2D2D2E2D4D2B,2B,2^C2D2^C2D4D2D2D4^C3D1D8D4E1F1G2G2F2G4D2D2E2E2D4D2B2B2A2B2c2B4A2D2D2D2D2D2D4D2G2E1F1G2D2D1^C1D4D2E2D4D3B,1B,6
%V:3
%B,2B,4B,2B,2A,4A,4G,2A,2G,2G,2G,4F,2G,2G,4A,2A,2A,2G,2F,2E,2A,4G,3F,1F,8B,4=C2D2C4D4A,2G,2B,2C2A,3G,1F,2z2z8z6G,2G,2F,2G,2A,2G,4F,2D2C2D2A,2A,2A,4G,2G,2G,4F,3G,1G,6
%V:4
%G,2G,4B,2G,2F,4F,4G,2F,2G,2C,2D,4D,2E,2E,4D,2A,,2D,2B,,2F,,2G,,2A,,4A,,3D,1D,8B,4A,2G,2A,4G,4F,2G,2E,2C,2D,4D,2z2z8z6G,2G,2F,2G,2A,2G,4F,2G,2A,2G,2F,2E,2D,2C,2B,,2C,2D,4D,3G,,1G,,6
%G,2G,4B,2G,2F,4F,4G,2F,2G,2C,2D,4D,2E,2E,4D,2A,,2D,2B,,2F,,2G,,2A,,4A,,3D,1D,8B,4A,2G,2A,4G,4F,2G,2E,2C,2D,4D,2z2z8z6G,2G,2F,2G,2A,2G,4F,2G,2A,2G,2F,2E,2D,2C,2B,,2C,2D,4D,3G,,1G,,6
| {
"pile_set_name": "Github"
} |
-- This sets configuration pragmas for use with gnatprove.
-- Partition_Elaboration_Policy is required (tasks don't start until
-- elaboration has finished).
pragma Partition_Elaboration_Policy (Sequential);
-- We may well be proving using a host compiler (partly because
-- gnatprove doesn't understand target, runtime settings in GPRs).
pragma Profile (Ravenscar);
| {
"pile_set_name": "Github"
} |
// Copyright 2018 Oath, Inc.
// Licensed under the terms of the Apache version 2.0 license. See LICENSE file for terms.
package api
import (
"encoding/json"
"net/http"
"testing"
"github.com/yahoo/yfuzz/pkg/schema"
"github.com/yahoo/yfuzz/services/yfuzz-server/kubernetes"
batchv1 "k8s.io/api/batch/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
func TestListJobs(t *testing.T) {
req, _ := http.NewRequest("GET", "/jobs", nil)
fakeKube := kubernetes.NewFake(&batchv1.Job{
TypeMeta: metav1.TypeMeta{
Kind: "job",
},
ObjectMeta: metav1.ObjectMeta{
Name: "test-job",
},
})
w := endpointTest("/jobs", ListJobs, EndpointDependencies{
Kubernetes: fakeKube,
}, req)
if w.Code != http.StatusOK {
t.Errorf("List jobs endpoint returned %v instead of %v", w.Code, http.StatusOK)
}
var response schema.ListJobsResponse
err := json.Unmarshal(w.Body.Bytes(), &response)
if err != nil {
t.Errorf("Could not unmarshal jobs response, got error: %s", err.Error())
}
if len(response.Jobs) != 1 || response.Jobs[0] != "test-job" {
t.Errorf("List jobs endpoint didn't return the test job.")
}
}
| {
"pile_set_name": "Github"
} |
(a)=>1
;
| {
"pile_set_name": "Github"
} |
//===-- RegisterContextMinidump_x86_32.h ------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#ifndef liblldb_RegisterContextMinidump_x86_32_h_
#define liblldb_RegisterContextMinidump_x86_32_h_
#include "MinidumpTypes.h"
#include "Plugins/Process/Utility/RegisterInfoInterface.h"
#include "Plugins/Process/Utility/lldb-x86-register-enums.h"
#include "lldb/Target/RegisterContext.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/BitmaskEnum.h"
#include "llvm/Support/Endian.h"
// C includes
// C++ includes
namespace lldb_private {
namespace minidump {
// This function receives an ArrayRef pointing to the bytes of the Minidump
// register context and returns a DataBuffer that's ordered by the offsets
// specified in the RegisterInfoInterface argument
// This way we can reuse the already existing register contexts
lldb::DataBufferSP
ConvertMinidumpContext_x86_32(llvm::ArrayRef<uint8_t> source_data,
RegisterInfoInterface *target_reg_interface);
// Reference: see breakpad/crashpad source or WinNT.h
struct MinidumpFloatingSaveAreaX86 {
llvm::support::ulittle32_t control_word;
llvm::support::ulittle32_t status_word;
llvm::support::ulittle32_t tag_word;
llvm::support::ulittle32_t error_offset;
llvm::support::ulittle32_t error_selector;
llvm::support::ulittle32_t data_offset;
llvm::support::ulittle32_t data_selector;
enum {
RegisterAreaSize = 80,
};
// register_area contains eight 80-bit (x87 "long double") quantities for
// floating-point registers %st0 (%mm0) through %st7 (%mm7).
uint8_t register_area[RegisterAreaSize];
llvm::support::ulittle32_t cr0_npx_state;
};
struct MinidumpContext_x86_32 {
// The context_flags field determines which parts
// of the structure are populated (have valid values)
llvm::support::ulittle32_t context_flags;
// The next 6 registers are included with
// MinidumpContext_x86_32_Flags::DebugRegisters
llvm::support::ulittle32_t dr0;
llvm::support::ulittle32_t dr1;
llvm::support::ulittle32_t dr2;
llvm::support::ulittle32_t dr3;
llvm::support::ulittle32_t dr6;
llvm::support::ulittle32_t dr7;
// The next field is included with
// MinidumpContext_x86_32_Flags::FloatingPoint
MinidumpFloatingSaveAreaX86 float_save;
// The next 4 registers are included with
// MinidumpContext_x86_32_Flags::Segments
llvm::support::ulittle32_t gs;
llvm::support::ulittle32_t fs;
llvm::support::ulittle32_t es;
llvm::support::ulittle32_t ds;
// The next 6 registers are included with
// MinidumpContext_x86_32_Flags::Integer
llvm::support::ulittle32_t edi;
llvm::support::ulittle32_t esi;
llvm::support::ulittle32_t ebx;
llvm::support::ulittle32_t edx;
llvm::support::ulittle32_t ecx;
llvm::support::ulittle32_t eax;
// The next 6 registers are included with
// MinidumpContext_x86_32_Flags::Control
llvm::support::ulittle32_t ebp;
llvm::support::ulittle32_t eip;
llvm::support::ulittle32_t cs; // WinNT.h says "must be sanitized"
llvm::support::ulittle32_t eflags; // WinNT.h says "must be sanitized"
llvm::support::ulittle32_t esp;
llvm::support::ulittle32_t ss;
// The next field is included with
// MinidumpContext_x86_32_Flags::ExtendedRegisters
// It contains vector (MMX/SSE) registers. It it laid out in the
// format used by the fxsave and fsrstor instructions, so it includes
// a copy of the x87 floating-point registers as well. See FXSAVE in
// "Intel Architecture Software Developer's Manual, Volume 2."
enum {
ExtendedRegistersSize = 512,
};
uint8_t extended_registers[ExtendedRegistersSize];
};
LLVM_ENABLE_BITMASK_ENUMS_IN_NAMESPACE();
// For context_flags. These values indicate the type of
// context stored in the structure. The high 24 bits identify the CPU, the
// low 8 bits identify the type of context saved.
enum class MinidumpContext_x86_32_Flags : uint32_t {
x86_32_Flag = 0x00010000, // CONTEXT_i386, CONTEXT_i486
Control = x86_32_Flag | 0x00000001,
Integer = x86_32_Flag | 0x00000002,
Segments = x86_32_Flag | 0x00000004,
FloatingPoint = x86_32_Flag | 0x00000008,
DebugRegisters = x86_32_Flag | 0x00000010,
ExtendedRegisters = x86_32_Flag | 0x00000020,
XState = x86_32_Flag | 0x00000040,
Full = Control | Integer | Segments,
All = Full | FloatingPoint | DebugRegisters | ExtendedRegisters,
LLVM_MARK_AS_BITMASK_ENUM(/* LargestValue = */ All)
};
} // end namespace minidump
} // end namespace lldb_private
#endif // liblldb_RegisterContextMinidump_x86_32_h_
| {
"pile_set_name": "Github"
} |
/*!
* 基础工具包
*/
define( function ( require ) {
var Utils = {},
commonUtils = require( "base/common" );
commonUtils.extend( Utils, commonUtils, require( "base/event/event" ) );
return Utils;
} );
| {
"pile_set_name": "Github"
} |
/**
* Implementation of REST API using Jersey.
*
* @author Cedrick Lunven (@clunven)</a>
* @version 1.0
*/
package org.ff4j.web.api;
/*
* #%L
* ff4j-core
* %%
* Copyright (C) 2013 - 2016 FF4J
* %%
* 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.
* #L%
*/
| {
"pile_set_name": "Github"
} |
/*
XOWA: the XOWA Offline Wiki Application
Copyright (C) 2012-2017 [email protected]
XOWA is licensed under the terms of the General Public License (GPL) Version 3,
or alternatively under the terms of the Apache License Version 2.0.
You may use XOWA according to either of these licenses as is most appropriate
for your project on a case-by-case basis.
The terms of each license can be found in the source code repository:
GPLv3 License: https://github.com/gnosygnu/xowa/blob/master/LICENSE-GPLv3.txt
Apache License: https://github.com/gnosygnu/xowa/blob/master/LICENSE-APACHE2.txt
*/
package gplx.xowa.guis.views; import gplx.*; import gplx.xowa.*; import gplx.xowa.guis.*;
import gplx.core.envs.*;
import gplx.gfui.*; import gplx.gfui.envs.*; import gplx.gfui.controls.windows.*;
public class Xog_startup_win_ {
public static void Startup(Xoa_app app, GfuiWin win) {
gplx.xowa.addons.apps.cfgs.Xocfg_mgr cfg_mgr = app.Cfg();
String window_mode = cfg_mgr.Get_str_app_or(Cfg__window_mode, "previous");
Rect_ref manual_rect = Rect_ref.parse(cfg_mgr.Get_str_app_or(Cfg__manual_rect, "0,0,800,640"));
// change win_rect per mode: previous; absolute; etc.
boolean init_is_maximized = false;
if (String_.Eq(window_mode, "previous")) {
if (cfg_mgr.Get_bool_app_or(Cfg__prev_maximized, false)) {
win.Maximized_(true);
init_is_maximized = true;
}
else {
Rect_ref previous_rect = null;
String s = cfg_mgr.Get_str_app_or(Cfg__prev_rect, "");
if (String_.Eq(s, "")) {
SizeAdp size = Screen_maximized_calc();
previous_rect = new Rect_ref(0, 0, size.Width(), size.Height());
}
else
previous_rect = Rect_ref.parse(s);
win.Rect_set(previous_rect.XtoRectAdp());
}
}
else if (String_.Eq(window_mode, "absolute")) {
win.Rect_set(manual_rect.XtoRectAdp());
}
else if (String_.Eq(window_mode, "maximized")) {
win.Maximized_(true);
init_is_maximized = true;
}
else if (String_.Eq(window_mode, "default")) {} // noop
else if (String_.Eq(window_mode, "relative")) {
SizeAdp screen_maximized = Screen_maximized_calc();
Rect_ref win_rect = new Rect_ref(0, 0, screen_maximized.Width(), screen_maximized.Height());
win.Rect_set(win_rect.XtoRectAdp_add(manual_rect));
}
// make sure win_rect is safe
boolean safe_mode = cfg_mgr.Get_bool_app_or(Cfg__manual_safe, true);
if (safe_mode && !init_is_maximized) {
RectAdp rect = win.Rect();
boolean force = false; int x = rect.X(), y = rect.Y(), w = rect.Width(), h = rect.Height();
SizeAdp screen_size = Screen_maximized_calc();
int max_w = screen_size.Width(), max_h = screen_size.Height();
int Safe_mode_buffer = 20; // allow minor negative positioning (x=-5), off-screen positioning (w=1605)
if (x < -Safe_mode_buffer || x > max_w + Safe_mode_buffer) {force = true; x = 0;}
if (y < -Safe_mode_buffer || y > max_h + Safe_mode_buffer) {force = true; y = 0;}
if (w < Safe_mode_buffer || x + w > max_w + Safe_mode_buffer) {force = true; w = max_w - x;}
if (h < Safe_mode_buffer || y + h > max_h + Safe_mode_buffer) {force = true; h = max_h - y;}
if (force)
win.Rect_set(RectAdp_.new_(x, y, w, h));
}
}
public static void Shutdown(Xoae_app app, GfuiWin win) {
gplx.xowa.addons.apps.cfgs.Xocfg_mgr cfg_mgr = app.Cfg();
if (String_.Eq(cfg_mgr.Get_str_app_or(Cfg__window_mode, "previous"), "previous")) {
cfg_mgr.Set_str_app(Cfg__prev_rect , win.Rect().Xto_str());
cfg_mgr.Set_str_app(Cfg__prev_maximized , Yn.To_str(win.Maximized()));
}
Xog_startup_tabs.Shutdown(app);
}
public static SizeAdp Screen_maximized_calc() {
Op_sys os = Op_sys.Cur();
SizeAdp screen = ScreenAdp_.screen_(0).Size();
int w = screen.Width();
int h = screen.Height() - 30; // -20=application menu bar; -10 for start bar padding
switch (os.Tid()) {
case Op_sys.Tid_wnt:
switch (os.Sub_tid()) {
case Op_sys.Sub_tid_win_xp: h += -4; break; // NOOP; will keep values as above
default: break; // for all else, use Windows 7 border (which is thicker); note that Windows 8 is being detected as "Windows NT (unknown)", so need to use default; this may not work with Windows 2000
}
break;
default:
h += -4; // default adjustments since version 0.0.0.0; seems to work on XP and LNX
break;
}
return SizeAdp_.new_(w, h);
}
private static final String
Cfg__window_mode = "xowa.app.startup.window.mode"
, Cfg__manual_rect = "xowa.app.startup.window.manual_rect"
, Cfg__manual_safe = "xowa.app.startup.window.manual_safe"
, Cfg__prev_rect = "xowa.app.startup.window.previous_rect"
, Cfg__prev_maximized = "xowa.app.startup.window.previous_maximized"
;
}
| {
"pile_set_name": "Github"
} |
AB Abbreviation
AW Additional Word
CC Coordinating conjunction
CD Cardinal number
CLS Classifier
DAD Determiner adjective
DP Demonstrative Pronouns
DT Determiner
EX Existential there
EXC Exclamation
FW Foreign word
GEN Gender
IN Preposition/subordinate conjunction
JJ Adjective
JJR Adjective, comparative
JJS Adjective, superlative
LS List item marker
M Mark
MD Modal
NN Noun, singular or mass
NN:U Mass noun #new tag - deviation from Penn
NN:UN Noun used as mass #new tag - deviation from Penn
NNP Proper noun, singular
NNPS Proper noun, plural
NNS Noun, plural
NP Negative Particle
NUM Number
PAD Possessive adjective
PAR Particle
PDT Predeterminer
POS Possessive ending
PRO Pronoun
PRP Personal pronoun
PRP$ Possessive pronoun
QAD Quantitative adjective
RB Adverb
RBR Adverb, comparative
RBS Adverb, superlative
ROY Royal Language
RP Particle
RPR Relative Pronoun
SYM Symbol
TXW Tense expression words
TO to
UH Interjection
VB Verb, base form
VBD Verb, past tense
VBG Verb, gerund/present participle
VBN Verb, past participle
VBP Verb, non-3rd ps. sing. present
VBZ Verb, 3rd ps. sing. present
WDT wh-determiner
WP wh-pronoun
WP$ Possessive wh-pronoun
WRB wh-adverb
`` Left open double quote
, Comma
'' Right close double quote
. Sentence-final punctuation
។ Sentence-final punctuation
: Colon, semi-colon
$ Dollar sign
# Pound sign | {
"pile_set_name": "Github"
} |
class ContactMailer < ActionMailer::Base
default :from => "noreply@#{ApiUmbrellaConfig[:web][:default_host]}"
def contact_email(contact_params)
@contact = Contact.new(contact_params)
mail :reply_to => @contact.email,
:subject => "#{ApiUmbrellaConfig[:site_name]} Contact Message from #{@contact.email}",
:to => ApiUmbrellaConfig[:web][:contact_form_email]
end
end
| {
"pile_set_name": "Github"
} |
@using API.Areas.HelpPage
@model ImageSample
<img src="@Model.Src" /> | {
"pile_set_name": "Github"
} |
<%= render layout: "shared/modal", locals: {
title: t("group_settings.destroy.Delete group"),
button_text: t("group_settings.destroy.Delete this group"),
button_class: "btn btn-danger btn-submit"
} do %>
<div class="box-body overflow-auto">
<%= form_with(model: @group, url: group_settings_path(@group), method: :delete) do |form| %>
<p class="text-gray-light f6 mb-4">
<%= raw t("group_settings.destroy.This action cannot be undone") %>
<%= raw t("group_settings.destroy.This will delete all contents", slug: @group.slug) %>
</p>
<div class="form-group">
<label class="control-label text-main"><%= raw t("group_settings.destroy.Please type the path slug of group to confirm", slug: @group.slug) %></label>
<input type="text" confirm-for="btn-confirm-delete" confirm-value="<%= @group.slug %>" autocomplete="off" class="form-control" />
</div>
<div class="actions">
<button type="submit" disabled id="btn-confirm-delete" class="btn btn-danger btn-block"><%= t("group_settings.destroy..I understand, delete this group") %></button>
</div>
<% end %>
</div>
<% end %> | {
"pile_set_name": "Github"
} |
//
// Licensed under the terms in License.txt
//
// Copyright 2010 Allen Ding. All rights reserved.
//
#import "KWAfterAllNode.h"
#import "KWAfterEachNode.h"
#import "KWBeforeAllNode.h"
#import "KWBeforeEachNode.h"
#import "KWLetNode.h"
#import "KWCallSite.h"
#import "KWContextNode.h"
#import "KWExampleNodeVisitor.h"
#import "KWExample.h"
#import "KWFailure.h"
#import "KWRegisterMatchersNode.h"
#import "KWSymbolicator.h"
static NSString * const KWContextNodeException = @"KWContextNodeException";
@interface KWContextNode()
@property (nonatomic, assign) NSUInteger performedExampleCount;
@end
@implementation KWContextNode
@synthesize description = _description;
#pragma mark - Initializing
- (id)initWithCallSite:(KWCallSite *)aCallSite parentContext:(KWContextNode *)node description:(NSString *)aDescription {
self = [super init];
if (self) {
_parentContext = node;
_callSite = aCallSite;
_description = [aDescription copy];
_nodes = [NSMutableArray array];
_registerMatchersNodes = [NSMutableArray array];
_letNodes = [NSMutableArray array];
_performedExampleCount = 0;
}
return self;
}
+ (id)contextNodeWithCallSite:(KWCallSite *)aCallSite parentContext:(KWContextNode *)contextNode description:(NSString *)aDescription {
return [[self alloc] initWithCallSite:aCallSite parentContext:contextNode description:aDescription];
}
- (void)addContextNode:(KWContextNode *)aNode {
[(NSMutableArray *)self.nodes addObject:aNode];
}
- (void)setBeforeEachNode:(KWBeforeEachNode *)aNode {
[self raiseIfNodeAlreadyExists:self.beforeEachNode];
_beforeEachNode = aNode;
}
- (void)setAfterEachNode:(KWAfterEachNode *)aNode {
[self raiseIfNodeAlreadyExists:self.afterEachNode];
_afterEachNode = aNode;
}
- (void)addLetNode:(KWLetNode *)aNode {
[(NSMutableArray *)self.letNodes addObject:aNode];
}
- (void)addRegisterMatchersNode:(KWRegisterMatchersNode *)aNode {
[(NSMutableArray *)self.registerMatchersNodes addObject:aNode];
}
- (KWLetNode *)letNodeTree {
KWLetNode *tree = [self.parentContext letNodeTree];
for (KWLetNode *letNode in self.letNodes) {
if (!tree) {
tree = letNode;
}
else {
[tree addLetNode:letNode];
}
}
return tree;
}
- (void)addItNode:(KWItNode *)aNode {
[(NSMutableArray *)self.nodes addObject:aNode];
}
- (void)addPendingNode:(KWPendingNode *)aNode {
[(NSMutableArray *)self.nodes addObject:aNode];
}
- (void)performExample:(KWExample *)example withBlock:(void (^)(void))exampleBlock
{
void (^innerExampleBlock)(void) = [exampleBlock copy];
void (^outerExampleBlock)(void) = ^{
@try {
for (KWRegisterMatchersNode *registerNode in self.registerMatchersNodes) {
[registerNode acceptExampleNodeVisitor:example];
}
if (self.performedExampleCount == 0) {
[self.beforeAllNode acceptExampleNodeVisitor:example];
}
KWLetNode *letNodeTree = [self letNodeTree];
[letNodeTree acceptExampleNodeVisitor:example];
[self.beforeEachNode acceptExampleNodeVisitor:example];
innerExampleBlock();
[self.afterEachNode acceptExampleNodeVisitor:example];
if ([example isLastInContext:self]) {
[self.afterAllNode acceptExampleNodeVisitor:example];
[letNodeTree unlink];
}
} @catch (NSException *exception) {
KWFailure *failure = [KWFailure failureWithCallSite:self.callSite format:@"%@ \"%@\" raised", [exception name], [exception reason]];
[example reportFailure:failure];
}
self.performedExampleCount++;
};
if (self.parentContext == nil) {
outerExampleBlock();
}
else {
[self.parentContext performExample:example withBlock:outerExampleBlock];
}
}
- (void)raiseIfNodeAlreadyExists:(id<KWExampleNode>)node {
if (node) {
[NSException raise:KWContextNodeException
format:@"A %@ already exists in this context.", NSStringFromClass([node class])];
}
}
#pragma mark - Accepting Visitors
- (void)acceptExampleNodeVisitor:(id<KWExampleNodeVisitor>)aVisitor {
[aVisitor visitContextNode:self];
}
@end
| {
"pile_set_name": "Github"
} |
// Generated by CoffeeScript 1.8.0
(function() {
var App, Listener, Server, chunking_test, events, fs, generate_dispatcher, iframe, sockjsVersion, trans_eventsource, trans_htmlfile, trans_jsonp, trans_websocket, trans_xhr, utils, webjs,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
__bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
events = require('events');
fs = require('fs');
webjs = require('./webjs');
utils = require('./utils');
trans_websocket = require('./trans-websocket');
trans_jsonp = require('./trans-jsonp');
trans_xhr = require('./trans-xhr');
iframe = require('./iframe');
trans_eventsource = require('./trans-eventsource');
trans_htmlfile = require('./trans-htmlfile');
chunking_test = require('./chunking-test');
sockjsVersion = function() {
var pkg, x;
try {
pkg = fs.readFileSync(__dirname + '/../package.json', 'utf-8');
} catch (_error) {
x = _error;
}
if (pkg) {
return JSON.parse(pkg).version;
} else {
return null;
}
};
App = (function(_super) {
__extends(App, _super);
function App() {
return App.__super__.constructor.apply(this, arguments);
}
App.prototype.welcome_screen = function(req, res) {
res.setHeader('content-type', 'text/plain; charset=UTF-8');
res.writeHead(200);
res.end("Welcome to SockJS!\n");
return true;
};
App.prototype.handle_404 = function(req, res) {
res.setHeader('content-type', 'text/plain; charset=UTF-8');
res.writeHead(404);
res.end('404 Error: Page not found\n');
return true;
};
App.prototype.disabled_transport = function(req, res, data) {
return this.handle_404(req, res, data);
};
App.prototype.h_sid = function(req, res, data) {
var jsid;
req.cookies = utils.parseCookie(req.headers.cookie);
if (typeof this.options.jsessionid === 'function') {
this.options.jsessionid(req, res);
} else if (this.options.jsessionid && res.setHeader) {
jsid = req.cookies['JSESSIONID'] || 'dummy';
res.setHeader('Set-Cookie', 'JSESSIONID=' + jsid + '; path=/');
}
return data;
};
App.prototype.log = function(severity, line) {
return this.options.log(severity, line);
};
return App;
})(webjs.GenericApp);
utils.objectExtend(App.prototype, iframe.app);
utils.objectExtend(App.prototype, chunking_test.app);
utils.objectExtend(App.prototype, trans_websocket.app);
utils.objectExtend(App.prototype, trans_jsonp.app);
utils.objectExtend(App.prototype, trans_xhr.app);
utils.objectExtend(App.prototype, trans_eventsource.app);
utils.objectExtend(App.prototype, trans_htmlfile.app);
generate_dispatcher = function(options) {
var dispatcher, opts_filters, p, t;
p = (function(_this) {
return function(s) {
return new RegExp('^' + options.prefix + s + '[/]?$');
};
})(this);
t = (function(_this) {
return function(s) {
return [p('/([^/.]+)/([^/.]+)' + s), 'server', 'session'];
};
})(this);
opts_filters = function(options_filter) {
if (options_filter == null) {
options_filter = 'xhr_options';
}
return ['h_sid', 'xhr_cors', 'cache_for', options_filter, 'expose'];
};
dispatcher = [['GET', p(''), ['welcome_screen']], ['GET', p('/iframe[0-9-.a-z_]*.html'), ['iframe', 'cache_for', 'expose']], ['OPTIONS', p('/info'), opts_filters('info_options')], ['GET', p('/info'), ['xhr_cors', 'h_no_cache', 'info', 'expose']], ['OPTIONS', p('/chunking_test'), opts_filters()], ['POST', p('/chunking_test'), ['xhr_cors', 'expect_xhr', 'chunking_test']], ['GET', p('/websocket'), ['raw_websocket']], ['GET', t('/jsonp'), ['h_sid', 'h_no_cache', 'jsonp']], ['POST', t('/jsonp_send'), ['h_sid', 'h_no_cache', 'expect_form', 'jsonp_send']], ['POST', t('/xhr'), ['h_sid', 'h_no_cache', 'xhr_cors', 'xhr_poll']], ['OPTIONS', t('/xhr'), opts_filters()], ['POST', t('/xhr_send'), ['h_sid', 'h_no_cache', 'xhr_cors', 'expect_xhr', 'xhr_send']], ['OPTIONS', t('/xhr_send'), opts_filters()], ['POST', t('/xhr_streaming'), ['h_sid', 'h_no_cache', 'xhr_cors', 'xhr_streaming']], ['OPTIONS', t('/xhr_streaming'), opts_filters()], ['GET', t('/eventsource'), ['h_sid', 'h_no_cache', 'eventsource']], ['GET', t('/htmlfile'), ['h_sid', 'h_no_cache', 'htmlfile']]];
if (options.websocket) {
dispatcher.push(['GET', t('/websocket'), ['sockjs_websocket']]);
} else {
dispatcher.push(['GET', t('/websocket'), ['cache_for', 'disabled_transport']]);
}
return dispatcher;
};
Listener = (function() {
function Listener(options, emit) {
this.options = options;
this.handler = __bind(this.handler, this);
this.app = new App();
this.app.options = options;
this.app.emit = emit;
this.app.log('debug', 'SockJS v' + sockjsVersion() + ' ' + 'bound to ' + JSON.stringify(options.prefix));
this.dispatcher = generate_dispatcher(this.options);
this.webjs_handler = webjs.generateHandler(this.app, this.dispatcher);
this.path_regexp = new RegExp('^' + this.options.prefix + '([/].+|[/]?)$');
}
Listener.prototype.handler = function(req, res, extra) {
if (!req.url.match(this.path_regexp)) {
return false;
}
this.webjs_handler(req, res, extra);
return true;
};
Listener.prototype.getHandler = function() {
return (function(_this) {
return function(a, b, c) {
return _this.handler(a, b, c);
};
})(this);
};
return Listener;
})();
Server = (function(_super) {
__extends(Server, _super);
function Server(user_options) {
this.options = {
prefix: '',
response_limit: 128 * 1024,
websocket: true,
jsessionid: false,
heartbeat_delay: 25000,
disconnect_delay: 5000,
log: function(severity, line) {
return console.log(line);
},
sockjs_url: 'https://cdn.jsdelivr.net/sockjs/0.3.4/sockjs.min.js'
};
if (user_options) {
utils.objectExtend(this.options, user_options);
}
}
Server.prototype.listener = function(handler_options) {
var options;
options = utils.objectExtend({}, this.options);
if (handler_options) {
utils.objectExtend(options, handler_options);
}
return new Listener(options, (function(_this) {
return function() {
return _this.emit.apply(_this, arguments);
};
})(this));
};
Server.prototype.installHandlers = function(http_server, handler_options) {
var handler;
handler = this.listener(handler_options).getHandler();
utils.overshadowListeners(http_server, 'request', handler);
utils.overshadowListeners(http_server, 'upgrade', handler);
return true;
};
Server.prototype.middleware = function(handler_options) {
var handler;
handler = this.listener(handler_options).getHandler();
handler.upgrade = handler;
return handler;
};
return Server;
})(events.EventEmitter);
exports.createServer = function(options) {
return new Server(options);
};
exports.listen = function(http_server, options) {
var srv;
srv = exports.createServer(options);
if (http_server) {
srv.installHandlers(http_server);
}
return srv;
};
}).call(this);
| {
"pile_set_name": "Github"
} |
/*
SuperCollider real time audio synthesis system
Copyright (c) 2002 James McCartney. All rights reserved.
http://www.audiosynth.com
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#pragma once
#include <stdint.h>
typedef struct SNDFILE_tag SNDFILE;
#ifdef SUPERNOVA
# include <atomic>
# include <cassert>
# ifdef __SSE2__
# include <emmintrin.h>
# endif
class rw_spinlock {
static const uint32_t unlocked_state = 0;
static const uint32_t locked_state = 0x80000000;
static const uint32_t reader_mask = 0x7fffffff;
# ifdef __SSE2__
static inline void pause() { _mm_pause(); }
# else
static inline void pause() {}
# endif
public:
struct unique_lock {
explicit unique_lock(rw_spinlock& sl): sl_(sl) { sl_.lock(); }
~unique_lock() { sl_.unlock(); }
private:
rw_spinlock& sl_;
};
typedef unique_lock unique_lock;
struct shared_lock {
explicit shared_lock(rw_spinlock& sl): sl_(sl) { sl_.lock_shared(); }
~shared_lock() { sl_.unlock_shared(); }
private:
rw_spinlock& sl_;
};
rw_spinlock() = default;
rw_spinlock(rw_spinlock const& rhs) = delete;
rw_spinlock& operator=(rw_spinlock const& rhs) = delete;
rw_spinlock(rw_spinlock&& rhs) = delete;
~rw_spinlock() { assert(state == unlocked_state); }
void lock() {
for (;;) {
while (state.load(std::memory_order_relaxed) != unlocked_state)
pause();
uint32_t expected = unlocked_state;
if (state.compare_exchange_weak(expected, locked_state, std::memory_order_acquire))
break;
}
}
bool try_lock() {
uint32_t expected = unlocked_state;
if (state.compare_exchange_strong(expected, locked_state, std::memory_order_acquire))
return true;
else
return false;
}
void unlock() {
assert(state.load(std::memory_order_relaxed) == locked_state);
state.store(unlocked_state, std::memory_order_release);
}
void lock_shared() {
for (;;) {
/* with the mask, the cas will fail, locked exclusively */
uint32_t current_state = state.load(std::memory_order_acquire) & reader_mask;
const uint32_t next_state = current_state + 1;
if (state.compare_exchange_weak(current_state, next_state, std::memory_order_acquire))
break;
pause();
}
}
bool try_lock_shared() {
/* with the mask, the cas will fail, locked exclusively */
uint32_t current_state = state.load(std::memory_order_acquire) & reader_mask;
const uint32_t next_state = current_state + 1;
if (state.compare_exchange_strong(current_state, next_state, std::memory_order_acquire))
return true;
else
return false;
}
void unlock_shared() {
for (;;) {
uint32_t current_state = state.load(std::memory_order_relaxed); /* we don't need the reader_mask */
const uint32_t next_state = current_state - 1;
if (state.compare_exchange_weak(current_state, uint32_t(next_state)))
break;
pause();
}
}
private:
std::atomic<uint32_t> state { unlocked_state };
};
#endif
struct SndBuf {
double samplerate;
double sampledur; // = 1/ samplerate
float* data;
int channels;
int samples;
int frames;
int mask; // for delay lines
int mask1; // for interpolating oscillators.
int coord; // used by fft ugens
SNDFILE* sndfile; // used by disk i/o
// SF_INFO fileinfo; // used by disk i/o
#ifdef SUPERNOVA
bool isLocal;
mutable rw_spinlock lock;
#endif
};
typedef struct SndBuf SndBuf;
struct SndBufUpdates {
int reads;
int writes;
};
typedef struct SndBufUpdates SndBufUpdates;
enum { coord_None, coord_Complex, coord_Polar };
inline float PhaseFrac(uint32_t inPhase) {
union {
uint32_t itemp;
float ftemp;
} u;
u.itemp = 0x3F800000 | (0x007FFF80 & ((inPhase) << 7));
return u.ftemp - 1.f;
}
inline float PhaseFrac1(uint32_t inPhase) {
union {
uint32_t itemp;
float ftemp;
} u;
u.itemp = 0x3F800000 | (0x007FFF80 & ((inPhase) << 7));
return u.ftemp;
}
inline float lookup(const float* table, int32_t phase, int32_t mask) { return table[(phase >> 16) & mask]; }
#define xlobits 14
#define xlobits1 13
inline float lookupi(const float* table, uint32_t phase, uint32_t mask) {
float frac = PhaseFrac(phase);
const float* tbl = table + ((phase >> 16) & mask);
float a = tbl[0];
float b = tbl[1];
return a + frac * (b - a);
}
inline float lookupi2(const float* table, uint32_t phase, uint32_t mask) {
float frac = PhaseFrac1(phase);
const float* tbl = table + ((phase >> 16) & mask);
float a = tbl[0];
float b = tbl[1];
return a + frac * b;
}
inline float lookupi1(const float* table0, const float* table1, uint32_t pphase, int32_t lomask) {
float pfrac = PhaseFrac1(pphase);
uint32_t index = ((pphase >> xlobits1) & (uint32_t)lomask);
float val1 = *(const float*)((const char*)table0 + index);
float val2 = *(const float*)((const char*)table1 + index);
return val1 + val2 * pfrac;
}
inline float lininterp(float x, float a, float b) { return a + x * (b - a); }
inline float cubicinterp(float x, float y0, float y1, float y2, float y3) {
// 4-point, 3rd-order Hermite (x-form)
float c0 = y1;
float c1 = 0.5f * (y2 - y0);
float c2 = y0 - 2.5f * y1 + 2.f * y2 - 0.5f * y3;
float c3 = 0.5f * (y3 - y0) + 1.5f * (y1 - y2);
return ((c3 * x + c2) * x + c1) * x + c0;
}
| {
"pile_set_name": "Github"
} |
/*
* Sonics Silicon Backplane
* PCI Hostdevice wrapper
*
* Copyright (c) 2005 Martin Langer <[email protected]>
* Copyright (c) 2005 Stefano Brivio <[email protected]>
* Copyright (c) 2005 Danny van Dyk <[email protected]>
* Copyright (c) 2005 Andreas Jaggi <[email protected]>
* Copyright (c) 2005-2007 Michael Buesch <[email protected]>
*
* Licensed under the GNU/GPL. See COPYING for details.
*/
#include <linux/pm.h>
#include <linux/pci.h>
#include <linux/export.h>
#include <linux/slab.h>
#include <linux/ssb/ssb.h>
#ifdef CONFIG_PM_SLEEP
static int ssb_pcihost_suspend(struct device *d)
{
struct pci_dev *dev = to_pci_dev(d);
struct ssb_bus *ssb = pci_get_drvdata(dev);
int err;
err = ssb_bus_suspend(ssb);
if (err)
return err;
pci_save_state(dev);
pci_disable_device(dev);
/* if there is a wakeup enabled child device on ssb bus,
enable pci wakeup posibility. */
device_set_wakeup_enable(d, d->power.wakeup_path);
pci_prepare_to_sleep(dev);
return 0;
}
static int ssb_pcihost_resume(struct device *d)
{
struct pci_dev *dev = to_pci_dev(d);
struct ssb_bus *ssb = pci_get_drvdata(dev);
int err;
pci_back_from_sleep(dev);
err = pci_enable_device(dev);
if (err)
return err;
pci_restore_state(dev);
err = ssb_bus_resume(ssb);
if (err)
return err;
return 0;
}
static const struct dev_pm_ops ssb_pcihost_pm_ops = {
SET_SYSTEM_SLEEP_PM_OPS(ssb_pcihost_suspend, ssb_pcihost_resume)
};
#endif /* CONFIG_PM_SLEEP */
static int ssb_pcihost_probe(struct pci_dev *dev,
const struct pci_device_id *id)
{
struct ssb_bus *ssb;
int err = -ENOMEM;
const char *name;
u32 val;
ssb = kzalloc(sizeof(*ssb), GFP_KERNEL);
if (!ssb)
goto out;
err = pci_enable_device(dev);
if (err)
goto err_kfree_ssb;
name = dev_name(&dev->dev);
if (dev->driver && dev->driver->name)
name = dev->driver->name;
err = pci_request_regions(dev, name);
if (err)
goto err_pci_disable;
pci_set_master(dev);
/* Disable the RETRY_TIMEOUT register (0x41) to keep
* PCI Tx retries from interfering with C3 CPU state */
pci_read_config_dword(dev, 0x40, &val);
if ((val & 0x0000ff00) != 0)
pci_write_config_dword(dev, 0x40, val & 0xffff00ff);
err = ssb_bus_pcibus_register(ssb, dev);
if (err)
goto err_pci_release_regions;
pci_set_drvdata(dev, ssb);
out:
return err;
err_pci_release_regions:
pci_release_regions(dev);
err_pci_disable:
pci_disable_device(dev);
err_kfree_ssb:
kfree(ssb);
return err;
}
static void ssb_pcihost_remove(struct pci_dev *dev)
{
struct ssb_bus *ssb = pci_get_drvdata(dev);
ssb_bus_unregister(ssb);
pci_release_regions(dev);
pci_disable_device(dev);
kfree(ssb);
pci_set_drvdata(dev, NULL);
}
int ssb_pcihost_register(struct pci_driver *driver)
{
driver->probe = ssb_pcihost_probe;
driver->remove = ssb_pcihost_remove;
#ifdef CONFIG_PM_SLEEP
driver->driver.pm = &ssb_pcihost_pm_ops;
#endif
return pci_register_driver(driver);
}
EXPORT_SYMBOL(ssb_pcihost_register);
| {
"pile_set_name": "Github"
} |
# rmskOut2.sql was originally generated by the autoSql program, which also
# generated rmskOut2.c and rmskOut2.h. This creates the database representation of
# an object which can be loaded and saved from RAM in a fairly
# automatic way.
#RepeatMasker .out record
CREATE TABLE rmskOut2 (
bin smallint not null, # bin number for browser speedup
swScore int unsigned not null, # Smith Waterman alignment score
milliDiv int unsigned not null, # Base mismatches in parts per thousand
milliDel int unsigned not null, # Bases deleted in parts per thousand
milliIns int unsigned not null, # Bases inserted in parts per thousand
genoName varchar(255) not null, # Genomic sequence name
genoStart int unsigned not null, # Start in genomic sequence
genoEnd int unsigned not null, # End in genomic sequence
genoLeft int not null, # -#bases after match in genomic sequence
strand char(1) not null, # Relative orientation + or -
repName varchar(255) not null, # Name of repeat
repClass varchar(255) not null, # Class of repeat
repFamily varchar(255) not null, # Family of repeat
repStart int not null, # Start in repeat sequence - regardless of orient.
repEnd int unsigned not null, # End in repeat sequence - reglardless of orient.
repLeft int not null, # -#bases after match in repeat sequence - regardless of orient
id int unsigned not null, # The ID of the hit. Used to link related fragments
#Indices
INDEX(genoName,bin)
);
| {
"pile_set_name": "Github"
} |
/*************************************************************************************
* Copyright (c) 2011, 2012, 2013 James Talbut.
* [email protected]
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* James Talbut - Initial implementation.
************************************************************************************/
package uk.co.spudsoft.birt.emitters.excel.tests;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.io.IOException;
import java.io.InputStream;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.eclipse.birt.core.exception.BirtException;
import org.junit.Test;
public class NestedTablesReportTest extends ReportRunner {
@Test
public void testRunReport() throws BirtException, IOException {
InputStream inputStream = runAndRenderReport("NestedTables.rptdesign", "xlsx");
assertNotNull(inputStream);
try {
XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
assertNotNull(workbook);
assertEquals( 1, workbook.getNumberOfSheets() );
assertEquals( "Nested Tables Test Report", workbook.getSheetAt(0).getSheetName());
Sheet sheet = workbook.getSheetAt(0);
assertEquals(1, firstNullRow(sheet));
assertEquals( "One Two Three\n1 2 3\n2 4 6\n3 6 9", sheet.getRow(0).getCell(0).getStringCellValue());
assertEquals( "One Two Three\n1 2 3\n2 4 6\n3 6 9", sheet.getRow(0).getCell(1).getStringCellValue());
} finally {
inputStream.close();
}
}
}
| {
"pile_set_name": "Github"
} |
/*****************************************************************
|
| AP4 - ES Descriptors
|
| Copyright 2002-2008 Axiomatic Systems, LLC
|
|
| This file is part of Bento4/AP4 (MP4 Atom Processing Library).
|
| Unless you have obtained Bento4 under a difference license,
| this version of Bento4 is Bento4|GPL.
| Bento4|GPL is free software; you can redistribute it and/or modify
| it under the terms of the GNU General Public License as published by
| the Free Software Foundation; either version 2, or (at your option)
| any later version.
|
| Bento4|GPL is distributed in the hope that it will be useful,
| but WITHOUT ANY WARRANTY; without even the implied warranty of
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
| GNU General Public License for more details.
|
| You should have received a copy of the GNU General Public License
| along with Bento4|GPL; see the file COPYING. If not, write to the
| Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
| 02111-1307, USA.
|
****************************************************************/
/*----------------------------------------------------------------------
| includes
+---------------------------------------------------------------------*/
#include "Ap4EsDescriptor.h"
#include "Ap4DescriptorFactory.h"
#include "Ap4Utils.h"
#include "Ap4ByteStream.h"
#include "Ap4Atom.h"
/*----------------------------------------------------------------------
| dynamic cast support
+---------------------------------------------------------------------*/
AP4_DEFINE_DYNAMIC_CAST_ANCHOR(AP4_EsDescriptor)
AP4_DEFINE_DYNAMIC_CAST_ANCHOR(AP4_EsIdIncDescriptor)
AP4_DEFINE_DYNAMIC_CAST_ANCHOR(AP4_EsIdRefDescriptor)
/*----------------------------------------------------------------------
| AP4_EsDescriptor::AP4_EsDescriptor
+---------------------------------------------------------------------*/
AP4_EsDescriptor::AP4_EsDescriptor(AP4_UI16 es_id) :
AP4_Descriptor(AP4_DESCRIPTOR_TAG_ES, 2, 2+1),
m_EsId(es_id),
m_OcrEsId(0),
m_Flags(0),
m_StreamPriority(0),
m_DependsOn(0)
{
}
/*----------------------------------------------------------------------
| AP4_EsDescriptor::AP4_EsDescriptor
+---------------------------------------------------------------------*/
AP4_EsDescriptor::AP4_EsDescriptor(AP4_ByteStream& stream,
AP4_Size header_size,
AP4_Size payload_size) :
AP4_Descriptor(AP4_DESCRIPTOR_TAG_ES, header_size, payload_size)
{
AP4_Position start;
stream.Tell(start);
// read descriptor fields
stream.ReadUI16(m_EsId);
unsigned char bits;
stream.ReadUI08(bits);
m_Flags = (bits>>5)&7;
m_StreamPriority = bits&0x1F;
if (m_Flags & AP4_ES_DESCRIPTOR_FLAG_STREAM_DEPENDENCY) {
stream.ReadUI16(m_DependsOn);
} else {
m_DependsOn = 0;
}
if (m_Flags & AP4_ES_DESCRIPTOR_FLAG_URL) {
unsigned char url_length;
stream.ReadUI08(url_length);
if (url_length) {
char* url = new char[url_length+1];
if (url) {
stream.Read(url, url_length);
url[url_length] = '\0';
m_Url = url;
delete[] url;
}
}
}
if (m_Flags & AP4_ES_DESCRIPTOR_FLAG_URL) {
stream.ReadUI16(m_OcrEsId);
} else {
m_OcrEsId = 0;
}
// read other descriptors
AP4_Position offset;
stream.Tell(offset);
AP4_SubStream* substream = new AP4_SubStream(stream, offset,
payload_size-AP4_Size(offset-start));
AP4_Descriptor* descriptor = NULL;
while (AP4_DescriptorFactory::CreateDescriptorFromStream(*substream,
descriptor)
== AP4_SUCCESS) {
m_SubDescriptors.Add(descriptor);
}
substream->Release();
}
/*----------------------------------------------------------------------
| AP4_EsDescriptor::~AP4_EsDescriptor
+---------------------------------------------------------------------*/
AP4_EsDescriptor::~AP4_EsDescriptor()
{
m_SubDescriptors.DeleteReferences();
}
/*----------------------------------------------------------------------
| AP4_EsDescriptor::WriteFields
+---------------------------------------------------------------------*/
AP4_Result
AP4_EsDescriptor::WriteFields(AP4_ByteStream& stream)
{
AP4_Result result;
// es id
result = stream.WriteUI16(m_EsId);
if (AP4_FAILED(result)) return result;
// flags and other bits
AP4_UI08 bits = m_StreamPriority | (AP4_UI08)(m_Flags<<5);
result = stream.WriteUI08(bits);
if (AP4_FAILED(result)) return result;
// optional fields
if (m_Flags & AP4_ES_DESCRIPTOR_FLAG_STREAM_DEPENDENCY) {
result = stream.WriteUI16(m_DependsOn);
if (AP4_FAILED(result)) return result;
}
if (m_Flags & AP4_ES_DESCRIPTOR_FLAG_URL) {
result = stream.WriteUI08((AP4_UI08)m_Url.GetLength());
if (AP4_FAILED(result)) return result;
result = stream.WriteString(m_Url.GetChars());
if (AP4_FAILED(result)) return result;
result = stream.WriteUI08(0);
if (AP4_FAILED(result)) return result;
}
if (m_Flags & AP4_ES_DESCRIPTOR_FLAG_OCR_STREAM) {
result = stream.WriteUI16(m_OcrEsId);
if (AP4_FAILED(result)) return result;
}
// write the sub descriptors
m_SubDescriptors.Apply(AP4_DescriptorListWriter(stream));
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_EsDescriptor::Inspect
+---------------------------------------------------------------------*/
AP4_Result
AP4_EsDescriptor::Inspect(AP4_AtomInspector& inspector)
{
inspector.StartDescriptor("ESDescriptor", GetHeaderSize(), GetSize());
inspector.AddField("es_id", m_EsId);
inspector.AddField("stream_priority", m_StreamPriority);
// inspect children
m_SubDescriptors.Apply(AP4_DescriptorListInspector(inspector));
inspector.EndDescriptor();
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_EsDescriptor::AddSubDescriptor
+---------------------------------------------------------------------*/
AP4_Result
AP4_EsDescriptor::AddSubDescriptor(AP4_Descriptor* descriptor)
{
m_SubDescriptors.Add(descriptor);
m_PayloadSize += descriptor->GetSize();
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_EsDescriptor::GetDecoderConfigDescriptor
+---------------------------------------------------------------------*/
const AP4_DecoderConfigDescriptor*
AP4_EsDescriptor::GetDecoderConfigDescriptor() const
{
// find the decoder config descriptor
AP4_Descriptor* descriptor = NULL;
AP4_Result result =
m_SubDescriptors.Find(AP4_DescriptorFinder(AP4_DESCRIPTOR_TAG_DECODER_CONFIG),
descriptor);
// return it
if (AP4_SUCCEEDED(result)) {
return AP4_DYNAMIC_CAST(AP4_DecoderConfigDescriptor, descriptor);
} else {
return NULL;
}
}
/*----------------------------------------------------------------------
| AP4_EsIdIncDescriptor::AP4_EsIdIncDescriptor
+---------------------------------------------------------------------*/
AP4_EsIdIncDescriptor::AP4_EsIdIncDescriptor(AP4_UI32 track_id) :
AP4_Descriptor(AP4_DESCRIPTOR_TAG_ES_ID_INC, 2, 4),
m_TrackId(track_id)
{
}
/*----------------------------------------------------------------------
| AP4_EsIdIncDescriptor::AP4_EsIdIncDescriptor
+---------------------------------------------------------------------*/
AP4_EsIdIncDescriptor::AP4_EsIdIncDescriptor(AP4_ByteStream& stream,
AP4_Size header_size,
AP4_Size payload_size) :
AP4_Descriptor(AP4_DESCRIPTOR_TAG_ES_ID_INC, header_size, payload_size),
m_TrackId(0)
{
// read the track id
stream.ReadUI32(m_TrackId);
}
/*----------------------------------------------------------------------
| AP4_EsIdIncescriptor::WriteFields
+---------------------------------------------------------------------*/
AP4_Result
AP4_EsIdIncDescriptor::WriteFields(AP4_ByteStream& stream)
{
// track id
return stream.WriteUI32(m_TrackId);
}
/*----------------------------------------------------------------------
| AP4_EsIdIncDescriptor::Inspect
+---------------------------------------------------------------------*/
AP4_Result
AP4_EsIdIncDescriptor::Inspect(AP4_AtomInspector& inspector)
{
inspector.StartDescriptor("ES_ID_Inc", GetHeaderSize(), GetSize());
inspector.AddField("track_id", m_TrackId);
inspector.EndDescriptor();
return AP4_SUCCESS;
}
/*----------------------------------------------------------------------
| AP4_EsIdRefDescriptor::AP4_EsIdRefDescriptor
+---------------------------------------------------------------------*/
AP4_EsIdRefDescriptor::AP4_EsIdRefDescriptor(AP4_UI16 ref_index) :
AP4_Descriptor(AP4_DESCRIPTOR_TAG_ES_ID_REF, 2, 2),
m_RefIndex(ref_index)
{
}
/*----------------------------------------------------------------------
| AP4_EsIdRefDescriptor::AP4_EsIdRefDescriptor
+---------------------------------------------------------------------*/
AP4_EsIdRefDescriptor::AP4_EsIdRefDescriptor(AP4_ByteStream& stream,
AP4_Size header_size,
AP4_Size payload_size) :
AP4_Descriptor(AP4_DESCRIPTOR_TAG_ES_ID_REF, header_size, payload_size),
m_RefIndex(0)
{
// read the ref index
stream.ReadUI16(m_RefIndex);
}
/*----------------------------------------------------------------------
| AP4_EsIdRefDescriptor::WriteFields
+---------------------------------------------------------------------*/
AP4_Result
AP4_EsIdRefDescriptor::WriteFields(AP4_ByteStream& stream)
{
// ref index
return stream.WriteUI16(m_RefIndex);
}
/*----------------------------------------------------------------------
| AP4_EsIdRefDescriptor::Inspect
+---------------------------------------------------------------------*/
AP4_Result
AP4_EsIdRefDescriptor::Inspect(AP4_AtomInspector& inspector)
{
inspector.StartDescriptor("ES_ID_Ref", GetHeaderSize(), GetSize());
inspector.AddField("ref_index", m_RefIndex);
inspector.EndDescriptor();
return AP4_SUCCESS;
}
| {
"pile_set_name": "Github"
} |
using System.Collections.Generic;
public sealed class BonusInitiativeGuaranteed : BonusInitiativeDesire
{
private int? MonstersMin { get; set; }
private int? MonstersMax { get; set; }
private int? MonstersSizeLimit { get; set; }
public BonusInitiativeGuaranteed(Dictionary<string, object> dataSet)
{
GenerateFromDataSet(dataSet);
}
public override bool CheckBonusInitiative(FormationUnit performer)
{
if (MonstersMin != null)
if (MonstersMin.Value > RaidSceneManager.BattleGround.MonsterNumber)
return false;
if (MonstersMax != null)
if (MonstersMax.Value < RaidSceneManager.BattleGround.MonsterNumber)
return false;
if (MonstersSizeLimit != null)
if (MonstersSizeLimit.Value < RaidSceneManager.BattleGround.MonsterSize)
return false;
return true;
}
protected override void GenerateFromDataSet(Dictionary<string, object> dataSet)
{
foreach (var token in dataSet)
{
switch (token.Key)
{
case "monsters_min":
MonstersMin = (int)(long)dataSet["monsters_min"];
break;
case "monsters_max":
MonstersMax = (int)(long)dataSet["monsters_max"];
break;
case "monsters_size_limit":
MonstersSizeLimit = (int)(long)dataSet["monsters_size_limit"];
break;
default:
ProcessBaseDataToken(token);
break;
}
}
}
} | {
"pile_set_name": "Github"
} |
<GDAL_WMS>
<Service name="TMS">
<ServerUrl>http://wms.itn.liu.se/Mars/Mola_CTX/tile/${z}/${y}/${x}</ServerUrl>
</Service>
<DataWindow>
<UpperLeftX>-180.0</UpperLeftX>
<UpperLeftY>90.0</UpperLeftY>
<LowerRightX>180.0</LowerRightX>
<LowerRightY>-90.0</LowerRightY>
<SizeX>46080</SizeX>
<SizeY>23040</SizeY>
<TileLevel>7</TileLevel>
<YOrigin>top</YOrigin>
</DataWindow>
<Projection>PROJCS["Mars2000_ECylindrical_clon0",GEOGCS["GCS_Mars_2000_Sphere",DATUM["Mars_2000_Sphere",SPHEROID["Mars_2000_Sphere",3396190,0]],PRIMEM["Reference_Meridian",0],UNIT["degree",0.0174532925199433]],PROJECTION["Equirectangular"],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",0],PARAMETER["standard_parallel_1",0],PARAMETER["false_easting",0],PARAMETER["false_northing",0],UNIT["metre",1,AUTHORITY["EPSG","9001"]]]</Projection>
<BlockSizeX>256</BlockSizeX>
<BlockSizeY>256</BlockSizeY>
<BandsCount>1</BandsCount>
<MaxConnections>10</MaxConnections>
</GDAL_WMS>
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
package com.sun.xml.internal.ws.api.message.stream;
import com.sun.xml.internal.ws.api.message.AttachmentSet;
import com.sun.xml.internal.ws.api.message.Packet;
import java.io.InputStream;
/**
* Low level representation of an XML or SOAP message as an {@link InputStream}.
*
*/
public class InputStreamMessage extends StreamBasedMessage {
/**
* The MIME content-type of the encoding.
*/
public final String contentType;
/**
* The message represented as an {@link InputStream}.
*/
public final InputStream msg;
/**
* Create a new message.
*
* @param properties
* the properties of the message.
*
* @param contentType
* the MIME content-type of the encoding.
*
* @param msg
* always a non-null unconsumed {@link InputStream} that
* represents a request.
*/
public InputStreamMessage(Packet properties, String contentType, InputStream msg) {
super(properties);
this.contentType = contentType;
this.msg = msg;
}
/**
* Create a new message.
*
* @param properties
* the properties of the message.
*
* @param attachments
* the attachments of the message.
*
* @param contentType
* the MIME content-type of the encoding.
*
* @param msg
* always a non-null unconsumed {@link InputStream} that
* represents a request.
*/
public InputStreamMessage(Packet properties, AttachmentSet attachments,
String contentType, InputStream msg) {
super(properties, attachments);
this.contentType = contentType;
this.msg = msg;
}
}
| {
"pile_set_name": "Github"
} |
import cpp
from Access a
select a
| {
"pile_set_name": "Github"
} |
"""HTTP server base class.
Note: the class in this module doesn't implement any HTTP request; see
SimpleHTTPServer for simple implementations of GET, HEAD and POST
(including CGI scripts). It does, however, optionally implement HTTP/1.1
persistent connections, as of version 0.3.
Contents:
- BaseHTTPRequestHandler: HTTP request handler base class
- test: test function
XXX To do:
- log requests even later (to capture byte count)
- log user-agent header and other interesting goodies
- send error log to separate file
"""
# See also:
#
# HTTP Working Group T. Berners-Lee
# INTERNET-DRAFT R. T. Fielding
# <draft-ietf-http-v10-spec-00.txt> H. Frystyk Nielsen
# Expires September 8, 1995 March 8, 1995
#
# URL: http://www.ics.uci.edu/pub/ietf/http/draft-ietf-http-v10-spec-00.txt
#
# and
#
# Network Working Group R. Fielding
# Request for Comments: 2616 et al
# Obsoletes: 2068 June 1999
# Category: Standards Track
#
# URL: http://www.faqs.org/rfcs/rfc2616.html
# Log files
# ---------
#
# Here's a quote from the NCSA httpd docs about log file format.
#
# | The logfile format is as follows. Each line consists of:
# |
# | host rfc931 authuser [DD/Mon/YYYY:hh:mm:ss] "request" ddd bbbb
# |
# | host: Either the DNS name or the IP number of the remote client
# | rfc931: Any information returned by identd for this person,
# | - otherwise.
# | authuser: If user sent a userid for authentication, the user name,
# | - otherwise.
# | DD: Day
# | Mon: Month (calendar name)
# | YYYY: Year
# | hh: hour (24-hour format, the machine's timezone)
# | mm: minutes
# | ss: seconds
# | request: The first line of the HTTP request as sent by the client.
# | ddd: the status code returned by the server, - if not available.
# | bbbb: the total number of bytes sent,
# | *not including the HTTP/1.0 header*, - if not available
# |
# | You can determine the name of the file accessed through request.
#
# (Actually, the latter is only true if you know the server configuration
# at the time the request was made!)
__version__ = "0.3"
__all__ = ["HTTPServer", "BaseHTTPRequestHandler"]
import sys
import time
import socket # For gethostbyaddr()
from warnings import filterwarnings, catch_warnings
with catch_warnings():
if sys.py3kwarning:
filterwarnings("ignore", ".*mimetools has been removed",
DeprecationWarning)
import mimetools
import SocketServer
# Default error message template
DEFAULT_ERROR_MESSAGE = """\
<head>
<title>Error response</title>
</head>
<body>
<h1>Error response</h1>
<p>Error code %(code)d.
<p>Message: %(message)s.
<p>Error code explanation: %(code)s = %(explain)s.
</body>
"""
DEFAULT_ERROR_CONTENT_TYPE = "text/html"
def _quote_html(html):
return html.replace("&", "&").replace("<", "<").replace(">", ">")
class HTTPServer(SocketServer.TCPServer):
allow_reuse_address = 1 # Seems to make sense in testing environment
def server_bind(self):
"""Override server_bind to store the server name."""
SocketServer.TCPServer.server_bind(self)
host, port = self.socket.getsockname()[:2]
self.server_name = socket.getfqdn(host)
self.server_port = port
class BaseHTTPRequestHandler(SocketServer.StreamRequestHandler):
"""HTTP request handler base class.
The following explanation of HTTP serves to guide you through the
code as well as to expose any misunderstandings I may have about
HTTP (so you don't need to read the code to figure out I'm wrong
:-).
HTTP (HyperText Transfer Protocol) is an extensible protocol on
top of a reliable stream transport (e.g. TCP/IP). The protocol
recognizes three parts to a request:
1. One line identifying the request type and path
2. An optional set of RFC-822-style headers
3. An optional data part
The headers and data are separated by a blank line.
The first line of the request has the form
<command> <path> <version>
where <command> is a (case-sensitive) keyword such as GET or POST,
<path> is a string containing path information for the request,
and <version> should be the string "HTTP/1.0" or "HTTP/1.1".
<path> is encoded using the URL encoding scheme (using %xx to signify
the ASCII character with hex code xx).
The specification specifies that lines are separated by CRLF but
for compatibility with the widest range of clients recommends
servers also handle LF. Similarly, whitespace in the request line
is treated sensibly (allowing multiple spaces between components
and allowing trailing whitespace).
Similarly, for output, lines ought to be separated by CRLF pairs
but most clients grok LF characters just fine.
If the first line of the request has the form
<command> <path>
(i.e. <version> is left out) then this is assumed to be an HTTP
0.9 request; this form has no optional headers and data part and
the reply consists of just the data.
The reply form of the HTTP 1.x protocol again has three parts:
1. One line giving the response code
2. An optional set of RFC-822-style headers
3. The data
Again, the headers and data are separated by a blank line.
The response code line has the form
<version> <responsecode> <responsestring>
where <version> is the protocol version ("HTTP/1.0" or "HTTP/1.1"),
<responsecode> is a 3-digit response code indicating success or
failure of the request, and <responsestring> is an optional
human-readable string explaining what the response code means.
This server parses the request and the headers, and then calls a
function specific to the request type (<command>). Specifically,
a request SPAM will be handled by a method do_SPAM(). If no
such method exists the server sends an error response to the
client. If it exists, it is called with no arguments:
do_SPAM()
Note that the request name is case sensitive (i.e. SPAM and spam
are different requests).
The various request details are stored in instance variables:
- client_address is the client IP address in the form (host,
port);
- command, path and version are the broken-down request line;
- headers is an instance of mimetools.Message (or a derived
class) containing the header information;
- rfile is a file object open for reading positioned at the
start of the optional input data part;
- wfile is a file object open for writing.
IT IS IMPORTANT TO ADHERE TO THE PROTOCOL FOR WRITING!
The first thing to be written must be the response line. Then
follow 0 or more header lines, then a blank line, and then the
actual data (if any). The meaning of the header lines depends on
the command executed by the server; in most cases, when data is
returned, there should be at least one header line of the form
Content-type: <type>/<subtype>
where <type> and <subtype> should be registered MIME types,
e.g. "text/html" or "text/plain".
"""
# The Python system version, truncated to its first component.
sys_version = "Python/" + sys.version.split()[0]
# The server software version. You may want to override this.
# The format is multiple whitespace-separated strings,
# where each string is of the form name[/version].
server_version = "BaseHTTP/" + __version__
# The default request version. This only affects responses up until
# the point where the request line is parsed, so it mainly decides what
# the client gets back when sending a malformed request line.
# Most web servers default to HTTP 0.9, i.e. don't send a status line.
default_request_version = "HTTP/0.9"
def parse_request(self):
"""Parse a request (internal).
The request should be stored in self.raw_requestline; the results
are in self.command, self.path, self.request_version and
self.headers.
Return True for success, False for failure; on failure, an
error is sent back.
"""
self.command = None # set in case of error on the first line
self.request_version = version = self.default_request_version
self.close_connection = 1
requestline = self.raw_requestline
requestline = requestline.rstrip('\r\n')
self.requestline = requestline
words = requestline.split()
if len(words) == 3:
command, path, version = words
if version[:5] != 'HTTP/':
self.send_error(400, "Bad request version (%r)" % version)
return False
try:
base_version_number = version.split('/', 1)[1]
version_number = base_version_number.split(".")
# RFC 2145 section 3.1 says there can be only one "." and
# - major and minor numbers MUST be treated as
# separate integers;
# - HTTP/2.4 is a lower version than HTTP/2.13, which in
# turn is lower than HTTP/12.3;
# - Leading zeros MUST be ignored by recipients.
if len(version_number) != 2:
raise ValueError
version_number = int(version_number[0]), int(version_number[1])
except (ValueError, IndexError):
self.send_error(400, "Bad request version (%r)" % version)
return False
if version_number >= (1, 1) and self.protocol_version >= "HTTP/1.1":
self.close_connection = 0
if version_number >= (2, 0):
self.send_error(505,
"Invalid HTTP Version (%s)" % base_version_number)
return False
elif len(words) == 2:
command, path = words
self.close_connection = 1
if command != 'GET':
self.send_error(400,
"Bad HTTP/0.9 request type (%r)" % command)
return False
elif not words:
return False
else:
self.send_error(400, "Bad request syntax (%r)" % requestline)
return False
self.command, self.path, self.request_version = command, path, version
# Examine the headers and look for a Connection directive
self.headers = self.MessageClass(self.rfile, 0)
conntype = self.headers.get('Connection', "")
if conntype.lower() == 'close':
self.close_connection = 1
elif (conntype.lower() == 'keep-alive' and
self.protocol_version >= "HTTP/1.1"):
self.close_connection = 0
return True
def handle_one_request(self):
"""Handle a single HTTP request.
You normally don't need to override this method; see the class
__doc__ string for information on how to handle specific HTTP
commands such as GET and POST.
"""
try:
self.raw_requestline = self.rfile.readline(65537)
if len(self.raw_requestline) > 65536:
self.requestline = ''
self.request_version = ''
self.command = ''
self.send_error(414)
return
if not self.raw_requestline:
self.close_connection = 1
return
if not self.parse_request():
# An error code has been sent, just exit
return
mname = 'do_' + self.command
if not hasattr(self, mname):
self.send_error(501, "Unsupported method (%r)" % self.command)
return
method = getattr(self, mname)
method()
self.wfile.flush() #actually send the response if not already done.
except socket.timeout, e:
#a read or a write timed out. Discard this connection
self.log_error("Request timed out: %r", e)
self.close_connection = 1
return
def handle(self):
"""Handle multiple requests if necessary."""
self.close_connection = 1
self.handle_one_request()
while not self.close_connection:
self.handle_one_request()
def send_error(self, code, message=None):
"""Send and log an error reply.
Arguments are the error code, and a detailed message.
The detailed message defaults to the short entry matching the
response code.
This sends an error response (so it must be called before any
output has been generated), logs the error, and finally sends
a piece of HTML explaining the error to the user.
"""
try:
short, long = self.responses[code]
except KeyError:
short, long = '???', '???'
if message is None:
message = short
explain = long
self.log_error("code %d, message %s", code, message)
# using _quote_html to prevent Cross Site Scripting attacks (see bug #1100201)
content = (self.error_message_format %
{'code': code, 'message': _quote_html(message), 'explain': explain})
self.send_response(code, message)
self.send_header("Content-Type", self.error_content_type)
self.send_header('Connection', 'close')
self.end_headers()
if self.command != 'HEAD' and code >= 200 and code not in (204, 304):
self.wfile.write(content)
error_message_format = DEFAULT_ERROR_MESSAGE
error_content_type = DEFAULT_ERROR_CONTENT_TYPE
def send_response(self, code, message=None):
"""Send the response header and log the response code.
Also send two standard headers with the server software
version and the current date.
"""
self.log_request(code)
if message is None:
if code in self.responses:
message = self.responses[code][0]
else:
message = ''
if self.request_version != 'HTTP/0.9':
self.wfile.write("%s %d %s\r\n" %
(self.protocol_version, code, message))
# print (self.protocol_version, code, message)
self.send_header('Server', self.version_string())
self.send_header('Date', self.date_time_string())
def send_header(self, keyword, value):
"""Send a MIME header."""
if self.request_version != 'HTTP/0.9':
self.wfile.write("%s: %s\r\n" % (keyword, value))
if keyword.lower() == 'connection':
if value.lower() == 'close':
self.close_connection = 1
elif value.lower() == 'keep-alive':
self.close_connection = 0
def end_headers(self):
"""Send the blank line ending the MIME headers."""
if self.request_version != 'HTTP/0.9':
self.wfile.write("\r\n")
def log_request(self, code='-', size='-'):
"""Log an accepted request.
This is called by send_response().
"""
self.log_message('"%s" %s %s',
self.requestline, str(code), str(size))
def log_error(self, format, *args):
"""Log an error.
This is called when a request cannot be fulfilled. By
default it passes the message on to log_message().
Arguments are the same as for log_message().
XXX This should go to the separate error log.
"""
self.log_message(format, *args)
def log_message(self, format, *args):
"""Log an arbitrary message.
This is used by all other logging functions. Override
it if you have specific logging wishes.
The first argument, FORMAT, is a format string for the
message to be logged. If the format string contains
any % escapes requiring parameters, they should be
specified as subsequent arguments (it's just like
printf!).
The client ip address and current date/time are prefixed to every
message.
"""
sys.stderr.write("%s - - [%s] %s\n" %
(self.client_address[0],
self.log_date_time_string(),
format%args))
def version_string(self):
"""Return the server software version string."""
return self.server_version + ' ' + self.sys_version
def date_time_string(self, timestamp=None):
"""Return the current date and time formatted for a message header."""
if timestamp is None:
timestamp = time.time()
year, month, day, hh, mm, ss, wd, y, z = time.gmtime(timestamp)
s = "%s, %02d %3s %4d %02d:%02d:%02d GMT" % (
self.weekdayname[wd],
day, self.monthname[month], year,
hh, mm, ss)
return s
def log_date_time_string(self):
"""Return the current time formatted for logging."""
now = time.time()
year, month, day, hh, mm, ss, x, y, z = time.localtime(now)
s = "%02d/%3s/%04d %02d:%02d:%02d" % (
day, self.monthname[month], year, hh, mm, ss)
return s
weekdayname = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
monthname = [None,
'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
def address_string(self):
"""Return the client address formatted for logging.
This version looks up the full hostname using gethostbyaddr(),
and tries to find a name that contains at least one dot.
"""
host, port = self.client_address[:2]
return socket.getfqdn(host)
# Essentially static class variables
# The version of the HTTP protocol we support.
# Set this to HTTP/1.1 to enable automatic keepalive
protocol_version = "HTTP/1.0"
# The Message-like class used to parse headers
MessageClass = mimetools.Message
# Table mapping response codes to messages; entries have the
# form {code: (shortmessage, longmessage)}.
# See RFC 2616.
responses = {
100: ('Continue', 'Request received, please continue'),
101: ('Switching Protocols',
'Switching to new protocol; obey Upgrade header'),
200: ('OK', 'Request fulfilled, document follows'),
201: ('Created', 'Document created, URL follows'),
202: ('Accepted',
'Request accepted, processing continues off-line'),
203: ('Non-Authoritative Information', 'Request fulfilled from cache'),
204: ('No Content', 'Request fulfilled, nothing follows'),
205: ('Reset Content', 'Clear input form for further input.'),
206: ('Partial Content', 'Partial content follows.'),
300: ('Multiple Choices',
'Object has several resources -- see URI list'),
301: ('Moved Permanently', 'Object moved permanently -- see URI list'),
302: ('Found', 'Object moved temporarily -- see URI list'),
303: ('See Other', 'Object moved -- see Method and URL list'),
304: ('Not Modified',
'Document has not changed since given time'),
305: ('Use Proxy',
'You must use proxy specified in Location to access this '
'resource.'),
307: ('Temporary Redirect',
'Object moved temporarily -- see URI list'),
400: ('Bad Request',
'Bad request syntax or unsupported method'),
401: ('Unauthorized',
'No permission -- see authorization schemes'),
402: ('Payment Required',
'No payment -- see charging schemes'),
403: ('Forbidden',
'Request forbidden -- authorization will not help'),
404: ('Not Found', 'Nothing matches the given URI'),
405: ('Method Not Allowed',
'Specified method is invalid for this resource.'),
406: ('Not Acceptable', 'URI not available in preferred format.'),
407: ('Proxy Authentication Required', 'You must authenticate with '
'this proxy before proceeding.'),
408: ('Request Timeout', 'Request timed out; try again later.'),
409: ('Conflict', 'Request conflict.'),
410: ('Gone',
'URI no longer exists and has been permanently removed.'),
411: ('Length Required', 'Client must specify Content-Length.'),
412: ('Precondition Failed', 'Precondition in headers is false.'),
413: ('Request Entity Too Large', 'Entity is too large.'),
414: ('Request-URI Too Long', 'URI is too long.'),
415: ('Unsupported Media Type', 'Entity body in unsupported format.'),
416: ('Requested Range Not Satisfiable',
'Cannot satisfy request range.'),
417: ('Expectation Failed',
'Expect condition could not be satisfied.'),
500: ('Internal Server Error', 'Server got itself in trouble'),
501: ('Not Implemented',
'Server does not support this operation'),
502: ('Bad Gateway', 'Invalid responses from another server/proxy.'),
503: ('Service Unavailable',
'The server cannot process the request due to a high load'),
504: ('Gateway Timeout',
'The gateway server did not receive a timely response'),
505: ('HTTP Version Not Supported', 'Cannot fulfill request.'),
}
def test(HandlerClass = BaseHTTPRequestHandler,
ServerClass = HTTPServer, protocol="HTTP/1.0"):
"""Test the HTTP request handler class.
This runs an HTTP server on port 8000 (or the first command line
argument).
"""
if sys.argv[1:]:
port = int(sys.argv[1])
else:
port = 8000
server_address = ('', port)
HandlerClass.protocol_version = protocol
httpd = ServerClass(server_address, HandlerClass)
sa = httpd.socket.getsockname()
print "Serving HTTP on", sa[0], "port", sa[1], "..."
httpd.serve_forever()
if __name__ == '__main__':
test()
| {
"pile_set_name": "Github"
} |
// ----------------------------------------------------------------
// Gunrock -- Fast and Efficient GPU Graph Library
// ----------------------------------------------------------------
// This source code is distributed under the terms of LICENSE.TXT
// in the root directory of this source distribution.
// ----------------------------------------------------------------
/**
* @file
* info_rapidjson.cuh
*
* @brief Running statistic collector with rapidjson
*/
#pragma once
#define RAPIDJSON_HAS_STDSTRING 1
#include <cstdio>
#include <vector>
#include <ctime>
#include <cmath>
#include <time.h>
#include <rapidjson/prettywriter.h>
#include <rapidjson/filewritestream.h>
#include <rapidjson/document.h>
#include <gunrock/util/gitsha1.h>
#include <gunrock/util/sysinfo_rapidjson.h>
/* this is the "stringize macro macro" hack */
#define STR(x) #x
#define XSTR(x) STR(x)
namespace gunrock {
namespace util {
template <typename ParametersT>
cudaError_t UseParameters_info(ParametersT ¶meters) {
cudaError_t retval = cudaSuccess;
GUARD_CU(parameters.template Use<bool>(
"json",
util::OPTIONAL_ARGUMENT | util::SINGLE_VALUE | util::OPTIONAL_PARAMETER,
false, "Whether to output statistics in json format", __FILE__,
__LINE__));
GUARD_CU(parameters.template Use<std::string>(
"jsonfile",
util::REQUIRED_ARGUMENT | util::SINGLE_VALUE | util::OPTIONAL_PARAMETER,
"", "Filename to output statistics in json format", __FILE__, __LINE__));
GUARD_CU(parameters.template Use<std::string>(
"jsondir",
util::REQUIRED_ARGUMENT | util::SINGLE_VALUE | util::OPTIONAL_PARAMETER,
"", "Directory to output statistics in json format", __FILE__, __LINE__));
GUARD_CU(parameters.template Use<std::string>(
"tag",
util::REQUIRED_ARGUMENT | util::MULTI_VALUE | util::OPTIONAL_PARAMETER,
"", "Tag to better describe and identify json outputs", __FILE__,
__LINE__));
return retval;
}
/**
* @brief Info data structure contains running statistics.
*/
struct Info {
private:
double total_elapsed; // sum of running times
double elapsed; // average of running times
double max_elapsed; // maximum running time
double min_elapsed; // minimum running time
double stddev_process_time; // std. deviation of running times
std::vector<double> process_times; // array of running times (raw)
std::vector<double> _process_times; // array of running times (filtered)
int num_runs; // number of runs
int64_t nodes_visited;
int64_t edges_visited;
double max_m_teps; // maximum MTEPS
double min_m_teps; // minimum MTEPS
double m_teps;
int64_t search_depth;
double avg_duty;
int64_t nodes_queued;
int64_t edges_queued;
double nodes_redundance;
double edges_redundance;
double preprocess_time;
double postprocess_time;
double write_time;
double total_time;
std::string time_str;
std::string algorithm_name;
util::Parameters *parameters;
std::string json_filename;
std::FILE *json_file;
rapidjson::StringBuffer *json_stream;
rapidjson::PrettyWriter<rapidjson::StringBuffer> *json_writer;
rapidjson::Document *json_document;
public:
/**
* @brief Info default constructor
*/
Info() { AssignInitValues(); }
template <typename GraphT>
Info(std::string algorithm_name, util::Parameters ¶meters,
GraphT &graph) {
AssignInitValues();
Init(algorithm_name, parameters, graph);
}
void AssignInitValues() {
parameters = NULL;
json_filename = "";
json_stream = NULL;
json_writer = NULL;
json_file = NULL;
json_document = NULL;
}
~Info() { Release(); }
cudaError_t Release() {
parameters = NULL;
json_filename = "";
delete json_stream;
json_stream = NULL;
delete json_writer;
json_writer = NULL;
delete json_document;
json_document = NULL;
return cudaSuccess;
}
template <typename GraphT>
void SetBaseInfo(std::string algorithm_name, util::Parameters ¶meters,
GraphT &graph, bool final_file = false) {
// If this is not the final version of the file, we want to denote it
// as invalid somehow.
if (!final_file) {
SetVal("avg-process-time", -1);
}
SetVal("engine", "Gunrock");
SetVal("command-line", parameters.Get_CommandLine());
// Update this date when JSON Schema is changed:
SetVal("json-schema", "2019-09-20");
#ifdef BOOST_FOUND
#if BOOST_COMP_CLANG
SetVal("compiler", BOOST_COMP_CLANG_NAME);
SetVal("compiler-version", BOOST_COMP_CLANG_DETECTION);
#elif BOOST_COMP_GNUC
SetVal("compiler", BOOST_COMP_GNUC_NAME);
SetVal("compiler-version", BOOST_COMP_GNUC_DETECTION);
#endif
#else
#ifdef __clang__
SetVal("compiler", "Clang");
SetVal("compiler-version", (__clang_major__ % 100) * 10000000 +
(__clang_minor__ % 100) * 100000 +
(__clang_patchlevel__ % 100000));
#else
SetVal("compiler", "Gnu GCC C/C++");
#ifdef __GNUC_PATCHLEVEL__
SetVal("compiler-version", (__GNUC__ % 100) * 10000000 +
(__GNUC_MINOR__ % 100) * 100000 +
(__GNUC_PATCHLEVEL__ % 100000));
#else
SetVal("compiler-version",
(__GNUC__ % 100) * 10000000 + (__GNUC_MINOR__ % 100) * 100000);
#endif
#endif
#endif
SetVal("time", time_str);
SetVal("gunrock-version", XSTR(GUNROCKVERSION));
SetVal("git-commit-sha", g_GIT_SHA1);
SetVal("primitive", algorithm_name);
SetVal("stddev-degree", graph::GetStddevDegree(graph));
SetVal("num-vertices", graph.nodes);
SetVal("num-edges", graph.edges);
}
/**
* @brief Initialization process for Info.
*
* @param[in] algorithm_name Algorithm name.
* @param[in] args Command line arguments.
*/
void InitBase(std::string algorithm_name, util::Parameters ¶meters) {
std::transform (algorithm_name.begin(), algorithm_name.end(),
algorithm_name.begin(), ::tolower);
this->algorithm_name = algorithm_name;
this->parameters = ¶meters;
total_elapsed = 0;
max_elapsed = 0;
min_elapsed = 1e26;
num_runs = 0;
time_t now = time(NULL);
long ms; // Milliseconds
time_t s; // Seconds
struct timespec spec;
clock_gettime(CLOCK_REALTIME, &spec);
s = spec.tv_sec;
ms = round(spec.tv_nsec / 1.0e6); // Convert nanoseconds to milliseconds
if (ms > 999) {
s++;
ms = 0;
}
std::string time_s = std::string(ctime(&now));
std::string time_ms = std::to_string(ms);
time_str = time_s;
std::string time_str_filename = time_s.substr(0, time_s.size() - 5) + time_ms + ' ' + time_s.substr(time_s.length() - 5);
if (parameters.Get<bool>("json")) {
json_filename = "";
} else if (parameters.Get<std::string>("jsonfile") != "") {
json_filename = parameters.Get<std::string>("jsonfile");
} else if (parameters.Get<std::string>("jsondir") != "") {
std::string dataset = parameters.Get<std::string>("dataset");
std::string dir = parameters.Get<std::string>("jsondir");
json_filename = dir + "/" + algorithm_name + "_" +
((dataset != "") ? (dataset + "_") : "") + time_str_filename +
".json";
char bad_chars[] = ":\n";
for (unsigned int i = 0; i < strlen(bad_chars); ++i) {
json_filename.erase(std::remove(json_filename.begin(),
json_filename.end(), bad_chars[i]),
json_filename.end());
}
} else {
return;
}
}
/**
* @brief Initialization process for Info.
* @param[in] algorithm_name Algorithm name.
* @param[in] parameters running parameters.
* @param[in] graph The graph.
*/
template <typename GraphT>
void Init(std::string algorithm_name, util::Parameters ¶meters,
GraphT &graph) {
InitBase(algorithm_name, parameters);
json_document = new rapidjson::Document();
json_document->SetObject();
// Use a StringBuffer to hold the file data. This requires we manually
// fputs the data from the stream to a file, but it's unlikely we would
// ever write incomplete files. With a FileWriteStream, rapidjson will
// decide to start writing whenever the buffer we provide is full
json_stream =
new rapidjson::StringBuffer();
json_writer =
new rapidjson::PrettyWriter<rapidjson::StringBuffer>(*json_stream);
// Write the initial copy of the file with an invalid avg-process-time
SetBaseInfo(algorithm_name, parameters, graph, false);
// Traverse the document for writing events
if (json_writer != NULL) {
json_document->Accept(*json_writer);
assert(json_writer->IsComplete());
}
if (json_filename != "") {
json_file = std::fopen(json_filename.c_str(), "w");
std::fputs(json_stream->GetString(), json_file);
std::fclose(json_file);
}
// We now start over with a new stream and writer. We can't reuse them.
// We also reset the document and rewrite our initial data - this time
// without the invalid time.
delete json_stream;
delete json_writer;
json_stream =
new rapidjson::StringBuffer();
json_writer =
new rapidjson::PrettyWriter<rapidjson::StringBuffer>(*json_stream);
json_document->SetObject();
SetBaseInfo(algorithm_name, parameters, graph, true);
}
template <typename T>
rapidjson::Value GetRapidjsonValue(const T& val) {
return rapidjson::Value(val);
}
rapidjson::Value GetRapidjsonValue(const std::string& str) {
if (json_document == NULL) return rapidjson::Value();
else {
return rapidjson::Value(str, json_document->GetAllocator());
}
}
rapidjson::Value GetRapidjsonValue(char* const str) {
if (json_document == NULL) return rapidjson::Value();
else {
return rapidjson::Value(str, json_document->GetAllocator());
}
}
template <typename T>
void SetBool(std::string name, const T &val, rapidjson::Value& json_object) {
std::cerr << "Attempt to SetVal with unknown type for key \""
<< name << std::endl;
}
void SetBool(std::string name, const bool &val, rapidjson::Value& json_object) {
if (json_document != NULL) {
rapidjson::Value key(name, json_document->GetAllocator());
json_object.AddMember(key, val, json_document->GetAllocator());
}
}
template <typename T>
void SetInt(std::string name, const T &val, rapidjson::Value& json_object) {
std::cerr << "Attempt to SetVal with unknown type for key \"" <<
name << std::endl;
}
void SetInt(std::string name, const int &val, rapidjson::Value& json_object) {
if (json_document != NULL) {
rapidjson::Value key(name, json_document->GetAllocator());
json_object.AddMember(key, val, json_document->GetAllocator());
}
}
template <typename T>
void SetUint(std::string name, const T &val, rapidjson::Value& json_object) {
std::cerr << "Attempt to SetVal with unknown type for key \""
<< name << std::endl;
}
void SetUint(std::string name, const unsigned int &val, rapidjson::Value& json_object) {
if (json_document != NULL) {
rapidjson::Value key(name, json_document->GetAllocator());
json_object.AddMember(key, val, json_document->GetAllocator());
}
}
template <typename T>
void SetInt64(std::string name, const T &val, rapidjson::Value& json_object) {
std::cerr << "writing unknown type for key \""
<< name << std::endl;
}
void SetInt64(std::string name, const int64_t &val, rapidjson::Value& json_object) {
if (json_document != NULL) {
rapidjson::Value key(name, json_document->GetAllocator());
json_object.AddMember(key, val, json_document->GetAllocator());
}
}
template <typename T>
void SetUint64(std::string name, const T &val, rapidjson::Value& json_object) {
std::cerr << "writing unknown type for key \""
<< name << std::endl;
}
void SetUint64(std::string name, const uint64_t &val, rapidjson::Value& json_object) {
if (json_document != NULL) {
rapidjson::Value key(name, json_document->GetAllocator());
json_object.AddMember(key, val, json_document->GetAllocator());
}
}
template <typename T>
void SetDouble(std::string name, const T &val, rapidjson::Value& json_object) {
std::cerr << "writing unknown type for key \""
<< name << std::endl;
}
void SetDouble(std::string name, const float &val, rapidjson::Value& json_object) {
if (json_document != NULL) {
rapidjson::Value key(name, json_document->GetAllocator());
// Doubles and floats have an edge case. INF and NAN are valid values for a
// double, but JSON doesn't allow them in the official spec. Some json formats
// still allow them. We have to choose a behavior here, so let's output the value
// as a string
if (std::isinf(val) || std::isnan(val)) {
rapidjson::Value null_val(rapidjson::kNullType);
json_object.AddMember(key, null_val, json_document->GetAllocator());
} else {
json_object.AddMember(key, val, json_document->GetAllocator());
}
}
}
void SetDouble(std::string name, const double &val, rapidjson::Value& json_object) {
if (json_document != NULL) {
rapidjson::Value key(name, json_document->GetAllocator());
if (std::isinf(val) || std::isnan(val)) {
rapidjson::Value null_val(rapidjson::kNullType);
json_object.AddMember(key, null_val, json_document->GetAllocator());
} else {
json_object.AddMember(key, val, json_document->GetAllocator());
}
}
}
// Attach a key with name, "name" and value "val" to the JSON object
// "json_object"
template <typename T>
void SetVal(std::string name, const T &val, rapidjson::Value& json_object) {
if (json_document == NULL) return;
auto tidx = std::type_index(typeid(T));
// TODO: Use constexpr if for this instead of the runtime check
// Then we won't need the filler functions above for a generic
// template parameter T
if (tidx == std::type_index(typeid(bool)))
SetBool(name, val, json_object);
else if (tidx == std::type_index(typeid(char)) ||
tidx == std::type_index(typeid(signed char)) ||
tidx == std::type_index(typeid(short)) ||
tidx == std::type_index(typeid(int)))
SetInt(name, val, json_object);
else if (tidx == std::type_index(typeid(unsigned char)) ||
tidx == std::type_index(typeid(unsigned short)) ||
tidx == std::type_index(typeid(unsigned int)))
SetUint(name, val, json_object);
else if (tidx == std::type_index(typeid(long)) ||
tidx == std::type_index(typeid(long long)))
SetInt64(name, val, json_object);
else if (tidx == std::type_index(typeid(unsigned long)) ||
tidx == std::type_index(typeid(unsigned long long)))
SetUint64(name, val, json_object);
else if (tidx == std::type_index(typeid(float)) ||
tidx == std::type_index(typeid(double)) ||
tidx == std::type_index(typeid(long double)))
SetDouble(name, val, json_object);
else {
std::ostringstream ostr;
ostr << val;
std::string str = ostr.str();
rapidjson::Value key(name, json_document->GetAllocator());
json_object.AddMember(key, str, json_document->GetAllocator());
}
}
template <typename T>
void SetVal(std::string name, const std::vector<T> &vec,
rapidjson::Value& json_object) {
// TODO: update parameters to support "ALWAYS_ARRAY" type
// currently using a hack to make sure tag is always an
// array in JSON. This is also required for fields such
// as srcs, process-times, etc.
if (json_document == NULL) return;
if (vec.size() == 1 && (name.compare("tag") != 0)) {
SetVal(name, vec.front(), json_object);
} else {
rapidjson::Value arr(rapidjson::kArrayType);
for (const T& i : vec) {
rapidjson::Value val = GetRapidjsonValue(i);
arr.PushBack(val, json_document->GetAllocator());
}
rapidjson::Value key(name, json_document->GetAllocator());
json_object.AddMember(key, arr, json_document->GetAllocator());
}
}
template <typename T>
void SetVal(std::string name, const std::vector<std::pair<T, T>> &vec,
rapidjson::Value& json_object) {
if (json_document == NULL) return;
rapidjson::Value key(name, json_document->GetAllocator());
rapidjson::Value child_object(rapidjson::kObjectType);
for (auto it = vec.begin(); it != vec.end(); it++) {
SetVal(it->first.c_str(), it->second, child_object);
}
json_object.AddMember(key, child_object, json_document->GetAllocator());
}
template <typename T>
void SetVal(std::string name, const T& val) {
if (json_document == NULL) return;
SetVal(name, val, *json_document);
}
void CollectSingleRun(double single_elapsed) {
total_elapsed += single_elapsed;
process_times.push_back(single_elapsed);
num_runs++;
}
/**
* @brief Compute statistics common to all primitives.
*
* @param[in] enactor_stats
* @param[in] elapsed
* @param[in] labels
* @param[in] get_traversal_stats
*/
template <typename EnactorT, typename T>
cudaError_t ComputeCommonStats(EnactorT &enactor, const T *labels = NULL,
bool get_traversal_stats = false) {
cudaError_t retval = cudaSuccess;
double total_lifetimes = 0;
double total_runtimes = 0;
// traversal stats
edges_queued = 0;
nodes_queued = 0;
search_depth = 0;
nodes_visited = 0;
edges_visited = 0;
m_teps = 0.0f;
edges_redundance = 0.0f;
nodes_redundance = 0.0f;
std::vector<int> device_list = parameters->Get<std::vector<int>>("device");
int num_gpus = device_list.size();
auto graph = enactor.problem->org_graph[0];
for (int gpu = 0; gpu < num_gpus; ++gpu) {
int my_gpu_idx = device_list[gpu];
if (num_gpus != 1) {
GUARD_CU(util::SetDevice(my_gpu_idx));
}
GUARD_CU(cudaDeviceSynchronize());
for (int peer = 0; peer < num_gpus; ++peer) {
auto &estats =
enactor.enactor_slices[gpu * num_gpus + peer].enactor_stats;
if (get_traversal_stats) {
edges_queued += estats.edges_queued[0];
GUARD_CU(estats.edges_queued.Move(util::DEVICE, util::HOST));
edges_queued += estats.edges_queued[0];
nodes_queued += estats.nodes_queued[0];
GUARD_CU(estats.nodes_queued.Move(util::DEVICE, util::HOST));
nodes_queued += estats.nodes_queued[0];
if (estats.iteration > search_depth) {
search_depth = estats.iteration;
}
}
total_lifetimes += estats.total_lifetimes;
total_runtimes += estats.total_runtimes;
}
}
#ifdef RECORD_PER_ITERATION_STATS
if (get_traversal_stats) {
// TODO: collect info for multi-GPUs
EnactorStats *estats = enactor_stats;
json_spirit::mArray per_iteration_advance_runtime;
json_spirit::mArray per_iteration_advance_mteps;
json_spirit::mArray per_iteration_advance_input_frontier;
json_spirit::mArray per_iteration_advance_output_frontier;
json_spirit::mArray per_iteration_advance_dir;
GetPerIterationAdvanceStats(
estats.per_iteration_advance_time, estats.per_iteration_advance_mteps,
estats.per_iteration_advance_input_edges,
estats.per_iteration_advance_output_edges,
estats.per_iteration_advance_direction, per_iteration_advance_runtime,
per_iteration_advance_mteps, per_iteration_advance_input_frontier,
per_iteration_advance_output_frontier, per_iteration_advance_dir);
SetVal("per_iteration_advance_runtime", per_iteration_advance_runtime);
SetVal("per_iteration_advance_mteps", per_iteration_advance_mteps);
SetVal("per_iteration_advance_input_frontier",
per_iteration_advance_input_frontier);
SetVal("per_iteration_advance_output_frontier",
per_iteration_advance_output_frontier);
SetVal("per_iteration_advance_direction", per_iteration_advance_dir);
}
#endif
avg_duty = (total_lifetimes > 0)
? double(total_runtimes) / total_lifetimes * 100.0
: 0.0f;
// Throw out results that are 2 standard deviations away from
// the mean (processing times) and recompute the average.
// filtering: start
elapsed = total_elapsed / num_runs;
if (num_runs > 1) {
double variance = 0.0;
for (auto i = process_times.begin(); i != process_times.end(); i++)
variance += pow(*i - elapsed, 2);
variance = variance / num_runs;
stddev_process_time = sqrt(variance);
auto lower_limit = elapsed - (2*stddev_process_time);
auto upper_limit = elapsed + (2*stddev_process_time);
// TODO: Check if this works with cases where we don't have
// multiple srcs, instead all process times maybe use one src
// (for example, src = 0 or largestdegree, etc.)
std::vector<int64_t> srcs;
if (parameters->Have("srcs")) {
srcs = parameters->Get<std::vector<int64_t>>("srcs");
}
std::vector<std::pair<int64_t, double>> delete_runs;
for(auto i = 0; i < process_times.size(); i++) {
delete_runs.push_back(std::make_pair((int64_t)srcs[i], (double)process_times[i]));
}
// for (auto q = delete_runs.begin(); q != delete_runs.end(); ++q)
// std::cout << ' ' << (*q).first << ' ' << (*q).second << std::endl;
delete_runs.erase(std::remove_if(
delete_runs.begin(), delete_runs.end(),
[lower_limit, upper_limit](const std::pair<const int64_t,
const double>& x) {
return ((x.second < lower_limit) || (x.second > upper_limit));
}), delete_runs.end());
std::vector<int64_t> _srcs;
for (auto q = delete_runs.begin(); q != delete_runs.end(); ++q) {
_process_times.push_back((double)(*q).second);
_srcs.push_back((int64_t)(*q).first);
}
// filtering: end
total_elapsed = 0.0;
for (auto i = _process_times.begin(); i != _process_times.end(); i++) {
total_elapsed += *i;
}
elapsed = total_elapsed / _process_times.size();
SetVal("filtered-srcs", _srcs);
}
SetVal("average-duty", avg_duty);
SetVal("search-depth", search_depth);
if (get_traversal_stats) {
SetVal("edges-queued", edges_queued);
SetVal("nodes-queued", nodes_queued);
}
// TODO: compute traversal stats
if (get_traversal_stats) {
if (labels != NULL)
for (int64_t v = 0; v < graph.nodes; ++v) {
if (util::isValid(labels[v]) &&
labels[v] != util::PreDefinedValues<T>::MaxValue) {
++nodes_visited;
edges_visited += graph.GetNeighborListLength(v);
}
}
if (algorithm_name == "BC") {
// for betweenness should count the backward phase too.
edges_visited = 2 * edges_queued;
} else if (algorithm_name == "PR") {
edges_visited = graph.edges;
nodes_visited = graph.nodes;
}
if (nodes_queued >
nodes_visited) { // measure duplicate nodes put through queue
nodes_redundance =
((double)nodes_queued - nodes_visited) / nodes_visited;
}
if (edges_queued > edges_visited) {
// measure duplicate edges put through queue
edges_redundance =
((double)edges_queued - edges_visited) / edges_visited;
}
nodes_redundance *= 100;
edges_redundance *= 100;
m_teps = (double)edges_visited / (elapsed * 1000.0);
SetVal("nodes-visited", nodes_visited);
SetVal("edges-visited", edges_visited);
SetVal("nodes-redundance", nodes_redundance);
SetVal("edges-redundance", edges_redundance);
}
return retval;
}
/**
* @brief Compute statistics common to all traversal primitives.
* @param[in] enactor The Enactor
* @param[in] labels
*/
template <typename EnactorT, typename T>
void ComputeTraversalStats(EnactorT &enactor, const T *labels = NULL) {
ComputeCommonStats(enactor, labels, true);
}
/**
* @brief Display running statistics.
* @param[in] verbose Whether or not to print extra information.
*/
void DisplayStats(bool verbose = true) {
int num_runs = parameters->Get<int>("num-runs");
double elapsed = total_elapsed / num_runs;
int num_srcs = 0;
std::vector<int64_t> srcs;
if (parameters->Have("srcs")) {
srcs = parameters->Get<std::vector<int64_t>>("srcs");
num_srcs = srcs.size();
}
util::PrintMsg("[" + algorithm_name + "] finished.");
util::PrintMsg(" avg. elapsed: " + std::to_string(elapsed) + " ms");
util::PrintMsg(" iterations: " + std::to_string(search_depth));
if (!verbose) return;
if (nodes_visited != 0 && nodes_visited < 5) {
util::PrintMsg("Fewer than 5 vertices visited.");
return;
}
util::PrintMsg(" min. elapsed: " + std::to_string(min_elapsed) + " ms",
min_elapsed > 0);
util::PrintMsg(" max. elapsed: " + std::to_string(max_elapsed) + " ms",
max_elapsed > 0);
util::PrintMsg(" rate: " + std::to_string(m_teps) + " MiEdges/s",
m_teps > 0.01);
util::PrintMsg(" average CTA duty: " + std::to_string(avg_duty) + "%%",
avg_duty > 0.01);
if (nodes_visited != 0 && edges_visited != 0) {
util::PrintMsg(" src: " + std::to_string(srcs[num_runs % num_srcs]),
num_srcs != 0);
util::PrintMsg(" nodes_visited: " + std::to_string(nodes_visited));
util::PrintMsg(" edges_visited: " + std::to_string(edges_visited));
}
util::PrintMsg(" nodes queued: " + std::to_string(nodes_queued),
nodes_queued > 0);
util::PrintMsg(" edges queued: " + std::to_string(edges_queued),
edges_queued > 0);
util::PrintMsg(" nodes redundance: " + std::to_string(nodes_redundance),
nodes_redundance > 0.01);
util::PrintMsg(" edges redundance: " + std::to_string(edges_redundance),
edges_redundance > 0.01);
util::PrintMsg(" load time: " + parameters->Get<std::string>("load-time") +
" ms");
util::PrintMsg(" preprocess time: " + std::to_string(preprocess_time) +
" ms");
util::PrintMsg(" postprocess time: " + std::to_string(postprocess_time) +
" ms");
// if (parameters -> Get<std::string>("output_filename") != "")
// util::PrintMsg(" write time: " + std::to_string(write_time) + " ms");
util::PrintMsg(" total time: " + std::to_string(total_time) + " ms");
// TODO: Update DisplayStats to display the new fields and more detailed
// information about the runs.
}
/* work around to supporting different pair types */
void getGpuinfo() {
cudaDeviceProp devProps;
int deviceCount;
cudaGetDeviceCount(&deviceCount);
if (deviceCount == 0) /* no valid devices */
{
return;
}
int dev = 0;
cudaGetDevice(&dev);
cudaGetDeviceProperties(&devProps, dev);
// We create a new rapidjson::Value as an JSON Object
// Then we can add it to the base Document when we are finished
// with it.
if (json_document == NULL) return;
rapidjson::Value gpuinfo(rapidjson::kObjectType);
SetVal("name", devProps.name, gpuinfo);
SetVal("total_global_mem", int64_t(devProps.totalGlobalMem), gpuinfo);
SetVal("major", std::to_string(devProps.major), gpuinfo);
SetVal("minor", std::to_string(devProps.minor), gpuinfo);
SetVal("clock_rate", devProps.clockRate, gpuinfo);
SetVal("multi_processor_count", devProps.multiProcessorCount, gpuinfo);
int runtimeVersion, driverVersion;
cudaRuntimeGetVersion(&runtimeVersion);
cudaDriverGetVersion(&driverVersion);
SetVal("driver_api", std::to_string(CUDA_VERSION), gpuinfo);
SetVal("driver_version", std::to_string(driverVersion), gpuinfo);
SetVal("runtime_version", std::to_string(runtimeVersion), gpuinfo);
SetVal("compute_version", std::to_string((devProps.major * 10 + devProps.minor)), gpuinfo);
json_document->AddMember("gpuinfo", gpuinfo, json_document->GetAllocator());
}
void Sort(rapidjson::Value& json_object) {
struct NameComparator {
bool operator()(const rapidjson::Value::Member &lhs, const rapidjson::Value::Member &rhs) const {
const std::string& lhs_str = lhs.name.GetString();
const std::string& rhs_str = rhs.name.GetString();
return lhs_str.compare(rhs_str) < 0;
}
};
std::sort(json_object.MemberBegin(), json_object.MemberEnd(), NameComparator());
}
void Finalize(double postprocess_time, double total_time) {
bool quiet = parameters->Get<bool>("quiet");
int num_runs = parameters->Get<int>("num-runs");
if (_process_times.size() > 1) {
min_elapsed = *std::min_element(_process_times.begin(), _process_times.end());
max_elapsed = *std::max_element(_process_times.begin(), _process_times.end());
min_m_teps = (double)this->edges_visited / (max_elapsed * 1000.0);
max_m_teps = (double)this->edges_visited / (min_elapsed * 1000.0);
} else {
min_elapsed = elapsed;
max_elapsed = elapsed;
min_m_teps = m_teps;
max_m_teps = m_teps;
}
preprocess_time = parameters->Get<double>("preprocess-time");
SetVal("process-times", process_times);
SetVal("filtered-process-times", _process_times);
SetVal("stddev-process-time", stddev_process_time);
SetVal("min-process-time", min_elapsed);
SetVal("max-process-time", max_elapsed);
SetVal("postprocess-time", postprocess_time);
SetVal("total-time", total_time);
SetVal("avg-mteps", m_teps);
SetVal("min-mteps", min_m_teps);
SetVal("max-mteps", max_m_teps);
auto process_time = json_document->FindMember("avg-process-time");
if (process_time == json_document->MemberEnd()) {
SetVal("avg-process-time", elapsed);
} else {
process_time->value = elapsed;
}
this->postprocess_time = postprocess_time;
this->total_time = total_time;
util::Sysinfo sysinfo;
SetVal("sysinfo", sysinfo.getSysinfo());
getGpuinfo();
util::Userinfo userinfo;
SetVal("userinfo", userinfo.getUserinfo());
// Add all the parameters to JSON
this->parameters->List(*this);
Sort(*json_document);
// Accept traverses the document and generates events that
// write to the json_stream
if (json_writer != NULL) {
json_document->Accept(*json_writer);
assert(json_writer->IsComplete());
}
if (json_filename != "") {
json_file = std::fopen(json_filename.c_str(), "w");
// Write the stream to file
std::fputs(json_stream->GetString(), json_file);
std::fclose(json_file);
}
if (!quiet) {
DisplayStats();
}
}
};
} // namespace util
} // namespace gunrock
// Leave this at the end of the file
// Local Variables:
// mode:c++
// c-file-style: "NVIDIA"
// End:
| {
"pile_set_name": "Github"
} |
0
1
1
1
1
1
1
1
1
0
0
0
0
0
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
0
0
0
0
0
0
1
1
1
1
1
1
1
1
1
0
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
0
0
0
0
0
0
1
1
1
1
1
1
1
1
0
0
0
0
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
0
0
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
0
0
0
0
0
0
0
0
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
0
0
0
0
0
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
0
0
0
0
0
0
| {
"pile_set_name": "Github"
} |
test:kF2EDBE2Ux8sQ
user1:SQtevcsBBnBPY
| {
"pile_set_name": "Github"
} |
///////////////////////////////////////////////////////////////////////////////
// range_matcher.hpp
//
// Copyright 2008 Eric Niebler. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_XPRESSIVE_DETAIL_CORE_MATCHER_RANGE_MATCHER_HPP_EAN_10_04_2005
#define BOOST_XPRESSIVE_DETAIL_CORE_MATCHER_RANGE_MATCHER_HPP_EAN_10_04_2005
// MS compatible compilers support #pragma once
#if defined(_MSC_VER)
# pragma once
# pragma warning(push)
# pragma warning(disable : 4100) // unreferenced formal parameter
#endif
#include <boost/mpl/bool.hpp>
#include <boost/xpressive/detail/detail_fwd.hpp>
#include <boost/xpressive/detail/core/quant_style.hpp>
#include <boost/xpressive/detail/core/state.hpp>
namespace boost { namespace xpressive { namespace detail
{
///////////////////////////////////////////////////////////////////////////////
// range_matcher
//
template<typename Traits, typename ICase>
struct range_matcher
: quant_style_fixed_width<1>
{
typedef typename Traits::char_type char_type;
typedef ICase icase_type;
char_type ch_min_;
char_type ch_max_;
bool not_;
range_matcher(char_type ch_min, char_type ch_max, bool no, Traits const &)
: ch_min_(ch_min)
, ch_max_(ch_max)
, not_(no)
{
}
void inverse()
{
this->not_ = !this->not_;
}
bool in_range(Traits const &tr, char_type ch, mpl::false_) const // case-sensitive
{
return tr.in_range(this->ch_min_, this->ch_max_, ch);
}
bool in_range(Traits const &tr, char_type ch, mpl::true_) const // case-insensitive
{
return tr.in_range_nocase(this->ch_min_, this->ch_max_, ch);
}
template<typename BidiIter, typename Next>
bool match(match_state<BidiIter> &state, Next const &next) const
{
if(state.eos() || this->not_ ==
this->in_range(traits_cast<Traits>(state), *state.cur_, icase_type()))
{
return false;
}
++state.cur_;
if(next.match(state))
{
return true;
}
--state.cur_;
return false;
}
};
}}}
#if defined(_MSC_VER)
# pragma warning(pop)
#endif
#endif
| {
"pile_set_name": "Github"
} |
'use strict';
exports.decode = exports.parse = require('./decode');
exports.encode = exports.stringify = require('./encode');
| {
"pile_set_name": "Github"
} |
type: log
paths:
{{ range $i, $path := .paths }}
- {{$path}}
{{ end }}
exclude_files: [".gz$"]
processors:
- add_fields:
target: ''
fields:
ecs.version: 1.5.0
| {
"pile_set_name": "Github"
} |
/*
Copyright The Kubernetes Authors.
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.
*/
// Code generated by client-gen. DO NOT EDIT.
package fake
import (
"context"
v1alpha1 "k8s.io/api/rbac/v1alpha1"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
labels "k8s.io/apimachinery/pkg/labels"
schema "k8s.io/apimachinery/pkg/runtime/schema"
types "k8s.io/apimachinery/pkg/types"
watch "k8s.io/apimachinery/pkg/watch"
testing "k8s.io/client-go/testing"
)
// FakeClusterRoleBindings implements ClusterRoleBindingInterface
type FakeClusterRoleBindings struct {
Fake *FakeRbacV1alpha1
}
var clusterrolebindingsResource = schema.GroupVersionResource{Group: "rbac.authorization.k8s.io", Version: "v1alpha1", Resource: "clusterrolebindings"}
var clusterrolebindingsKind = schema.GroupVersionKind{Group: "rbac.authorization.k8s.io", Version: "v1alpha1", Kind: "ClusterRoleBinding"}
// Get takes name of the clusterRoleBinding, and returns the corresponding clusterRoleBinding object, and an error if there is any.
func (c *FakeClusterRoleBindings) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1alpha1.ClusterRoleBinding, err error) {
obj, err := c.Fake.
Invokes(testing.NewRootGetAction(clusterrolebindingsResource, name), &v1alpha1.ClusterRoleBinding{})
if obj == nil {
return nil, err
}
return obj.(*v1alpha1.ClusterRoleBinding), err
}
// List takes label and field selectors, and returns the list of ClusterRoleBindings that match those selectors.
func (c *FakeClusterRoleBindings) List(ctx context.Context, opts v1.ListOptions) (result *v1alpha1.ClusterRoleBindingList, err error) {
obj, err := c.Fake.
Invokes(testing.NewRootListAction(clusterrolebindingsResource, clusterrolebindingsKind, opts), &v1alpha1.ClusterRoleBindingList{})
if obj == nil {
return nil, err
}
label, _, _ := testing.ExtractFromListOptions(opts)
if label == nil {
label = labels.Everything()
}
list := &v1alpha1.ClusterRoleBindingList{ListMeta: obj.(*v1alpha1.ClusterRoleBindingList).ListMeta}
for _, item := range obj.(*v1alpha1.ClusterRoleBindingList).Items {
if label.Matches(labels.Set(item.Labels)) {
list.Items = append(list.Items, item)
}
}
return list, err
}
// Watch returns a watch.Interface that watches the requested clusterRoleBindings.
func (c *FakeClusterRoleBindings) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {
return c.Fake.
InvokesWatch(testing.NewRootWatchAction(clusterrolebindingsResource, opts))
}
// Create takes the representation of a clusterRoleBinding and creates it. Returns the server's representation of the clusterRoleBinding, and an error, if there is any.
func (c *FakeClusterRoleBindings) Create(ctx context.Context, clusterRoleBinding *v1alpha1.ClusterRoleBinding, opts v1.CreateOptions) (result *v1alpha1.ClusterRoleBinding, err error) {
obj, err := c.Fake.
Invokes(testing.NewRootCreateAction(clusterrolebindingsResource, clusterRoleBinding), &v1alpha1.ClusterRoleBinding{})
if obj == nil {
return nil, err
}
return obj.(*v1alpha1.ClusterRoleBinding), err
}
// Update takes the representation of a clusterRoleBinding and updates it. Returns the server's representation of the clusterRoleBinding, and an error, if there is any.
func (c *FakeClusterRoleBindings) Update(ctx context.Context, clusterRoleBinding *v1alpha1.ClusterRoleBinding, opts v1.UpdateOptions) (result *v1alpha1.ClusterRoleBinding, err error) {
obj, err := c.Fake.
Invokes(testing.NewRootUpdateAction(clusterrolebindingsResource, clusterRoleBinding), &v1alpha1.ClusterRoleBinding{})
if obj == nil {
return nil, err
}
return obj.(*v1alpha1.ClusterRoleBinding), err
}
// Delete takes name of the clusterRoleBinding and deletes it. Returns an error if one occurs.
func (c *FakeClusterRoleBindings) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {
_, err := c.Fake.
Invokes(testing.NewRootDeleteAction(clusterrolebindingsResource, name), &v1alpha1.ClusterRoleBinding{})
return err
}
// DeleteCollection deletes a collection of objects.
func (c *FakeClusterRoleBindings) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {
action := testing.NewRootDeleteCollectionAction(clusterrolebindingsResource, listOpts)
_, err := c.Fake.Invokes(action, &v1alpha1.ClusterRoleBindingList{})
return err
}
// Patch applies the patch and returns the patched clusterRoleBinding.
func (c *FakeClusterRoleBindings) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.ClusterRoleBinding, err error) {
obj, err := c.Fake.
Invokes(testing.NewRootPatchSubresourceAction(clusterrolebindingsResource, name, pt, data, subresources...), &v1alpha1.ClusterRoleBinding{})
if obj == nil {
return nil, err
}
return obj.(*v1alpha1.ClusterRoleBinding), err
}
| {
"pile_set_name": "Github"
} |
# an attempt to tie together the fonts as seen from
# troff et al to the corresponding bitmaps
# map
# lists mapping from name of character to its decimal position
# in a font; a particular map applies to a list of fonts that
# follows it.
# troff F dir/prefix
# maps troff font name into files in /lib/font/bit/dir/prefix...
# all files in a group share the preceding map.
# these may be repeated ad libitum. in principle this ought to work
# for tex and postscript, but caveat emptor.
map
dg 1
em 2
en 3
fi 4
fl 5
hy 6
sc 7
! 33
" 34
# 35
$ 36
% 37
& 38
' 39
( 40
) 41
* 42
+ 43
pl 43
, 44
- 45
hy 45
. 46
/ 47
sl 47
0 48
1 49
2 50
3 51
4 52
5 53
6 54
7 55
8 56
9 57
: 58
; 59
< 60
= 61
> 62
? 63
@ 64
A 65
B 66
C 67
D 68
E 69
F 70
G 71
H 72
I 73
J 74
K 75
L 76
M 77
N 78
O 79
P 80
Q 81
R 82
S 83
T 84
U 85
V 86
W 87
X 88
Y 89
Z 90
[ 91
\ 92
] 93
^ 94
_ 95
` 96
a 97
b 98
c 99
d 100
e 101
f 102
g 103
h 104
i 105
j 106
k 107
l 108
m 109
n 110
o 111
p 112
q 113
r 114
s 115
t 116
u 117
v 118
w 119
x 120
y 121
z 122
{ 123
| 124
} 125
~ 126
xheight
0.48
# this group has to end with a blank line!!!!
# the following fonts all share the map above
troff R times/R.
troff I times/I.
troff B times/B.
troff BI times/BI.
troff CW courier/R.
troff CB courier/R.
troff R palatino/R.
troff I palatino/I.
troff B palatino/B.
troff BI palatino/BI.
troff H helvetica/R.
troff HI helvetica/I.
troff HI helvetica/I.
troff HX helvetica/BI.
map
!= 1
** 2
*C 3
*D 4
*F 5
*G 6
*H 7
*L 8
*P 9
*Q 10
*S 11
*W 12
*a 13
*b 14
*c 15
*d 16
*e 17
*f 18
*g 19
*h 20
*i 21
*k 22
*l 23
*m 24
*n 25
*o 26
*p 27
*q 28
*r 29
*s 30
*t 31
*u 32
*w 33
*x 34
*y 35
*z 36
+- 37
-> 38
.. 39
12 40
14 41
34 42
<- 43
<= 44
== 45
>= 46
L. 47
L1 48
Sl 49
\- 50
\_ 51
aa 52
al 53
ap 54
b9 55
br 56
bs 57
bu 58
bv 59
bx 60
ca 61
cd 62
ci 63
co 64
ct 65
cu 66
da 67
dd 68
de 69
di 70
eq 71
es 72
fa 73
fe 74
fm 75
ga 76
gr 77
hc 78
ib 79
if 80
ip 81
is 82
l. 83
lb 84
lc 85
lf 86
lh 87
lk 88
lt 89
ma 90
mi 91
mo 92
mu 93
no 94
ob 95
or 96
pd 97
pl 98
pp 99
pt 100
rb 101
rc 102
rf 103
rg 104
rh 105
rk 106
rn 107
rt 108
ru 109
sb 110
sl 111
sp 112
sq 113
sr 114
te 115
tm 116
tp 117
ts 118
ua 119
ul 120
vr 121
~= 122
~~ 123
xheight
0.48
special S special/S.
# LucidaSans support fonts; latin-1 only
map
! 33
" 34
dq 34
# 35
$ 36
% 37
& 38
' 39
( 40
) 41
* 42
+ 43
, 44
- 45
. 46
/ 47
0 48
1 49
2 50
3 51
4 52
5 53
6 54
7 55
8 56
9 57
: 58
; 59
< 60
= 61
> 62
? 63
@ 64
A 65
B 66
C 67
D 68
E 69
F 70
G 71
H 72
I 73
J 74
K 75
L 76
M 77
N 78
O 79
P 80
Q 81
R 82
S 83
T 84
U 85
V 86
W 87
X 88
Y 89
Z 90
[ 91
\ 92
bs 92
] 93
^ 94
_ 95
` 96
‘ 96
\` 96
ga 96
a 97
b 98
c 99
d 100
e 101
f 102
g 103
h 104
i 105
j 106
k 107
l 108
m 109
n 110
o 111
p 112
q 113
r 114
s 115
t 116
u 117
v 118
w 119
x 120
y 121
z 122
{ 123
| 124
} 125
~ 126
160
¡ 161
¢ 162
£ 163
¤ 164
¥ 165
¦ 166
§ 167
¨ 168
© 169
ª 170
« 171
¬ 172
173
hy 173
® 174
¯ 175
° 176
± 177
+- 177
² 178
³ 179
´ 180
aa 180
µ 181
¶ 182
· 183
¸ 184
¹ 185
º 186
» 187
¼ 188
½ 189
¾ 190
¿ 191
À 192
Á 193
 194
à 195
Ä 196
Å 197
Æ 198
Ç 199
È 200
É 201
Ê 202
Ë 203
Ì 204
Í 205
Î 206
Ï 207
Ð 208
Ñ 209
Ò 210
Ó 211
Ô 212
Õ 213
Ö 214
× 215
mu 215
Ø 216
Ù 217
Ú 218
Û 219
Ü 220
Ý 221
Þ 222
ß 223
à 224
á 225
â 226
ã 227
ä 228
å 229
æ 230
ç 231
è 232
é 233
ê 234
ë 235
ì 236
í 237
î 238
ï 239
ð 240
ñ 241
ò 242
ó 243
ô 244
õ 245
ö 246
÷ 247
-: 247
di 247
ø 248
ù 249
ú 250
û 251
ü 252
ý 253
þ 254
ÿ 255
xheight
0.535
troff LucidaSansI lucida/latin1I. LucidaSans
troff LucidaSansB lucida/latin1B. LucidaSans
troff LucidaCW lucida/latin1CW.
# now the unicode sequences. here we suppress two-char sequences
# better expressed as plain unicode.
map
! 33
" 34
dq 34
# 35
$ 36
% 37
& 38
' 8217
’ 8217
( 40
) 41
* 42
+ 43
, 44
- 45
. 46
/ 47
0 48
1 49
2 50
3 51
4 52
5 53
6 54
7 55
8 56
9 57
: 58
; 59
< 60
= 61
> 62
? 63
@ 64
A 65
B 66
C 67
D 68
E 69
F 70
G 71
H 72
I 73
J 74
K 75
L 76
M 77
N 78
O 79
P 80
Q 81
R 82
S 83
T 84
U 85
V 86
W 87
X 88
Y 89
Z 90
[ 91
\ 92
bs 92
] 93
^ 94
_ 95
` 8216
‘ 8216
\` 96
ga 96
a 97
b 98
c 99
d 100
e 101
f 102
g 103
h 104
i 105
j 106
k 107
l 108
m 109
n 110
o 111
p 112
q 113
r 114
s 115
t 116
u 117
v 118
w 119
x 120
y 121
z 122
{ 123
| 124
} 125
~ 126
160
¡ 161
¢ 162
£ 163
¤ 164
¥ 165
¦ 166
§ 167
¨ 168
© 169
ª 170
« 171
¬ 172
173
hy 173
® 174
¯ 175
° 176
± 177
+- 177
² 178
³ 179
´ 180
aa 180
µ 181
¶ 182
· 183
¸ 184
¹ 185
º 186
» 187
¼ 188
½ 189
¾ 190
¿ 191
À 192
Á 193
 194
à 195
Ä 196
Å 197
Æ 198
Ç 199
È 200
É 201
Ê 202
Ë 203
Ì 204
Í 205
Î 206
Ï 207
Ð 208
Ñ 209
Ò 210
Ó 211
Ô 212
Õ 213
Ö 214
× 215
mu 215
Ø 216
Ù 217
Ú 218
Û 219
Ü 220
Ý 221
Þ 222
ß 223
à 224
á 225
â 226
ã 227
ä 228
å 229
æ 230
ç 231
è 232
é 233
ê 234
ë 235
ì 236
í 237
î 238
ï 239
ð 240
ñ 241
ò 242
ó 243
ô 244
õ 245
ö 246
÷ 247
-: 247
di 247
ø 248
ù 249
ú 250
û 251
ü 252
ý 253
þ 254
ÿ 255
Ā 256
ā 257
Ă 258
ă 259
Ą 260
ą 261
Ć 262
ć 263
Ĉ 264
ĉ 265
Ċ 266
ċ 267
Č 268
č 269
Ď 270
ď 271
Đ 272
đ 273
Ē 274
ē 275
Ĕ 276
ĕ 277
Ė 278
ė 279
Ę 280
ę 281
Ě 282
ě 283
Ĝ 284
ĝ 285
Ğ 286
ğ 287
Ġ 288
ġ 289
Ģ 290
ģ 291
Ĥ 292
ĥ 293
Ħ 294
ħ 295
Ĩ 296
ĩ 297
Ī 298
ī 299
Ĭ 300
ĭ 301
Į 302
į 303
İ 304
ı 305
IJ 306
ij 307
Ĵ 308
ĵ 309
Ķ 310
ķ 311
ĸ 312
Ĺ 313
ĺ 314
Ļ 315
ļ 316
Ľ 317
ľ 318
Ŀ 319
ŀ 320
Ł 321
ł 322
Ń 323
ń 324
Ņ 325
ņ 326
Ň 327
ň 328
ʼn 329
Ŋ 330
ŋ 331
Ō 332
ō 333
Ŏ 334
ŏ 335
Ő 336
ő 337
Œ 338
œ 339
Ŕ 340
ŕ 341
Ŗ 342
ŗ 343
Ř 344
ř 345
Ś 346
ś 347
Ŝ 348
ŝ 349
Ş 350
ş 351
Š 352
š 353
Ţ 354
ţ 355
Ť 356
ť 357
Ŧ 358
ŧ 359
Ũ 360
ũ 361
Ū 362
ū 363
Ŭ 364
ŭ 365
Ů 366
ů 367
Ű 368
ű 369
Ų 370
ų 371
Ŵ 372
ŵ 373
Ŷ 374
ŷ 375
Ÿ 376
Ź 377
ź 378
Ż 379
ż 380
Ž 381
ž 382
ƀ 384
Ɓ 385
Ƃ 386
ƃ 387
Ƅ 388
ƅ 389
Ɔ 390
Ƈ 391
ƈ 392
Ɖ 393
Ɗ 394
Ƌ 395
ƌ 396
ƍ 397
Ǝ 398
Ə 399
Ɛ 400
Ƒ 401
ƒ 402
Ɠ 403
Ɣ 404
ƕ 405
Ɩ 406
Ɨ 407
Ƙ 408
ƙ 409
ƚ 410
ƛ 411
Ɯ 412
Ɲ 413
ƞ 414
Ɵ 415
Ơ 416
ơ 417
Ƣ 418
ƣ 419
Ƥ 420
ƥ 421
Ʀ 422
Ƨ 423
ƨ 424
Ʃ 425
ƪ 426
ƫ 427
Ƭ 428
ƭ 429
Ʈ 430
Ư 431
ư 432
Ʊ 433
Ʋ 434
Ƴ 435
ƴ 436
Ƶ 437
ƶ 438
Ʒ 439
Ƹ 440
ƹ 441
ƺ 442
ƻ 443
Ƽ 444
ƽ 445
ƾ 446
ƿ 447
ǀ 448
ǁ 449
ǂ 450
ǃ 451
DŽ 452
Dž 453
dž 454
LJ 455
Lj 456
lj 457
NJ 458
Nj 459
nj 460
Ǎ 461
ǎ 462
Ǐ 463
ǐ 464
Ǒ 465
ǒ 466
Ǔ 467
ǔ 468
Ǖ 469
ǖ 470
Ǘ 471
ǘ 472
Ǚ 473
ǚ 474
Ǜ 475
ǜ 476
ǝ 477
Ǟ 478
ǟ 479
Ǡ 480
ǡ 481
Ǣ 482
ǣ 483
Ǥ 484
ǥ 485
Ǧ 486
ǧ 487
Ǩ 488
ǩ 489
Ǫ 490
ǫ 491
Ǭ 492
ǭ 493
Ǯ 494
ǯ 495
ǰ 496
ɐ 592
ɑ 593
ɒ 594
ɓ 595
ɔ 596
ɕ 597
ɖ 598
ɗ 599
ɘ 600
ə 601
ɚ 602
ɛ 603
ɜ 604
ɝ 605
ɞ 606
ɟ 607
ɠ 608
ɡ 609
ɢ 610
ɣ 611
ɤ 612
ɥ 613
ɦ 614
ɧ 615
ɨ 616
ɩ 617
ɪ 618
ɫ 619
ɬ 620
ɭ 621
ɮ 622
ɯ 623
ɰ 624
ɱ 625
ɲ 626
ɳ 627
ɴ 628
ɵ 629
ɶ 630
ɷ 631
ɸ 632
ɹ 633
ɺ 634
ɻ 635
ɼ 636
ɽ 637
ɾ 638
ɿ 639
ʀ 640
ʁ 641
ʂ 642
ʃ 643
ʄ 644
ʅ 645
ʆ 646
ʇ 647
ʈ 648
ʉ 649
ʊ 650
ʋ 651
ʌ 652
ʍ 653
ʎ 654
ʏ 655
ʐ 656
ʑ 657
ʒ 658
ʓ 659
ʔ 660
ʕ 661
ʖ 662
ʗ 663
ʘ 664
ʙ 665
ʚ 666
ʛ 667
ʜ 668
ʝ 669
ʞ 670
ʟ 671
ʠ 672
ʡ 673
ʢ 674
ʣ 675
ʤ 676
ʥ 677
ʦ 678
ʧ 679
ʨ 680
ʰ 688
ʱ 689
ʲ 690
ʳ 691
ʴ 692
ʵ 693
ʶ 694
ʷ 695
ʸ 696
ʹ 697
ʺ 698
ʻ 699
ʼ 700
ʽ 701
ʾ 702
ʿ 703
ˀ 704
ˁ 705
˂ 706
˃ 707
˄ 708
˅ 709
ˆ 710
ˇ 711
ˈ 712
ˉ 713
ˊ 714
ˋ 715
ˌ 716
ˍ 717
ˎ 718
ˏ 719
ː 720
ˑ 721
˒ 722
˓ 723
˔ 724
˕ 725
˖ 726
˗ 727
˘ 728
˙ 729
˚ 730
˛ 731
˜ 732
˝ 733
˞ 734
˟ 735
ˠ 736
ˡ 737
ˢ 738
ˣ 739
ˤ 740
˥ 741
˦ 742
˧ 743
˨ 744
˩ 745
̀ 768
́ 769
̂ 770
̃ 771
̄ 772
̅ 773
̆ 774
̇ 775
̈ 776
̉ 777
̊ 778
̋ 779
̌ 780
̍ 781
̎ 782
̏ 783
̐ 784
̑ 785
̒ 786
̓ 787
̔ 788
̕ 789
̖ 790
̗ 791
̘ 792
̙ 793
̚ 794
̛ 795
̜ 796
̝ 797
̞ 798
̟ 799
̠ 800
̡ 801
̢ 802
̣ 803
̤ 804
̥ 805
̦ 806
̧ 807
̨ 808
̩ 809
̪ 810
̫ 811
̬ 812
̭ 813
̮ 814
̯ 815
̰ 816
̱ 817
̲ 818
̳ 819
̴ 820
̵ 821
̶ 822
̷ 823
̸ 824
̹ 825
̺ 826
̻ 827
̼ 828
̽ 829
̾ 830
̿ 831
̀ 832
́ 833
̈́ 836
ͅ 837
ͱ 881
Ͳ 882
ʹ 884
͵ 885
ͺ 890
; 894
΄ 900
΅ 901
Ά 902
Έ 904
Ή 905
Ί 906
Ό 908
Ύ 910
Ώ 911
ΐ 912
Α 913
*A 913
Β 914
*B 914
Γ 915
*G 915
Δ 916
*D 916
Ε 917
*E 917
Ζ 918
*Z 918
Η 919
*Y 919
Θ 920
*H 920
Ι 921
*I 921
Κ 922
*K 922
Λ 923
*L 923
Μ 924
*M 924
Ν 925
*N 925
Ξ 926
*C 926
Ο 927
*O 927
Π 928
*P 928
Ρ 929
*R 929
Σ 931
*S 931
Τ 932
*T 932
Υ 933
*U 933
Φ 934
*F 934
Χ 935
*X 935
Ψ 936
*Q 936
Ω 937
*W 937
Ϊ 938
Ϋ 939
ά 940
έ 941
ή 942
ί 943
ΰ 944
α 945
*a 945
β 946
*b 946
γ 947
*g 947
δ 948
*d 948
ε 949
*e 949
ζ 950
*z 950
η 951
*y 951
θ 952
*h 952
ι 953
*i 953
κ 954
*k 954
λ 955
*l 955
μ 956
*m 956
ν 957
*n 957
ξ 958
*c 958
ο 959
*o 959
π 960
*p 960
ρ 961
*r 961
ς 962
ts 962
σ 963
*s 963
τ 964
*t 964
υ 965
*u 965
φ 966
*f 966
χ 967
*x 967
ψ 968
*q 968
ω 969
*w 969
ϊ 970
ϋ 971
ό 972
ύ 973
ώ 974
ϐ 976
ϑ 977
ϒ 978
ϓ 979
ϔ 980
ϕ 981
ϖ 982
Ϛ 986
Ϝ 988
Ϟ 990
Ϡ 992
Ϯ 1006
ϯ 1007
ϰ 1008
ϱ 1009
ϲ 1010
Ё 1025
Ђ 1026
Ѓ 1027
Є 1028
Ѕ 1029
І 1030
Ї 1031
Ј 1032
Љ 1033
Њ 1034
Ћ 1035
Ќ 1036
Ў 1038
Џ 1039
А 1040
Б 1041
В 1042
Г 1043
Д 1044
Е 1045
Ж 1046
З 1047
И 1048
Й 1049
К 1050
Л 1051
М 1052
Н 1053
О 1054
П 1055
Р 1056
С 1057
Т 1058
У 1059
Ф 1060
Х 1061
Ц 1062
Ч 1063
Ш 1064
Щ 1065
Ъ 1066
Ы 1067
Ь 1068
Э 1069
Ю 1070
Я 1071
а 1072
б 1073
в 1074
г 1075
д 1076
е 1077
ж 1078
з 1079
и 1080
й 1081
к 1082
л 1083
м 1084
н 1085
о 1086
п 1087
р 1088
с 1089
т 1090
у 1091
ф 1092
х 1093
ц 1094
ч 1095
ш 1096
щ 1097
ъ 1098
ы 1099
ь 1100
э 1101
ю 1102
я 1103
ё 1105
ђ 1106
ѓ 1107
є 1108
ѕ 1109
і 1110
ї 1111
ј 1112
љ 1113
њ 1114
ћ 1115
ќ 1116
ў 1118
џ 1119
Ѣ 1122
ѣ 1123
Ѫ 1130
ѫ 1131
Ґ 1168
ґ 1169
Ғ 1170
ғ 1171
Ҕ 1172
ҕ 1173
Җ 1174
җ 1175
Ҙ 1176
ҙ 1177
Қ 1178
қ 1179
Ҝ 1180
ҝ 1181
Ҟ 1182
ҟ 1183
Ҡ 1184
ҡ 1185
Ң 1186
ң 1187
Ҥ 1188
ҥ 1189
Ҧ 1190
ҧ 1191
Ҩ 1192
ҩ 1193
Ҫ 1194
ҫ 1195
Ҭ 1196
ҭ 1197
Ү 1198
ү 1199
Ұ 1200
ұ 1201
Ҳ 1202
ҳ 1203
Ҵ 1204
ҵ 1205
Ҷ 1206
ҷ 1207
Ҹ 1208
ҹ 1209
Һ 1210
һ 1211
Ҽ 1212
ҽ 1213
Ҿ 1214
ҿ 1215
Ӏ 1216
Ӂ 1217
ӂ 1218
Ӄ 1219
ӄ 1220
Ӆ 1221
ӆ 1222
Ӈ 1223
ӈ 1224
Ӊ 1225
ӊ 1226
Ӌ 1227
ӌ 1228
ְ 1456
ֱ 1457
ֲ 1458
ֳ 1459
ִ 1460
ֵ 1461
ֶ 1462
ַ 1463
ָ 1464
ֹ 1465
ֻ 1467
ּ 1468
ֽ 1469
־ 1470
ֿ 1471
׀ 1472
ׁ 1473
ׂ 1474
׃ 1475
א 1488
ב 1489
ג 1490
ד 1491
ה 1492
ו 1493
ז 1494
ח 1495
ט 1496
י 1497
ך 1498
כ 1499
ל 1500
ם 1501
מ 1502
ן 1503
נ 1504
ס 1505
ע 1506
ף 1507
פ 1508
ץ 1509
צ 1510
ק 1511
ר 1512
ש 1513
ת 1514
װ 1520
ױ 1521
ײ 1522
׳ 1523
״ 1524
1525
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
‐ 8208
‑ 8209
‒ 8210
– 8211
en 8211
\- 8211
— 8212
em 8212
-- 8212
― 8213
‖ 8214
‗ 8215
‚ 8218
‛ 8219
“ 8220
” 8221
„ 8222
‟ 8223
† 8224
‡ 8225
• 8226
‣ 8227
․ 8228
‥ 8229
… 8230
‧ 8231
8232
8233
8234
8235
8236
8237
8238
‰ 8240
‱ 8241
′ 8242
″ 8243
‴ 8244
‵ 8245
‶ 8246
‷ 8247
‸ 8248
‹ 8249
› 8250
※ 8251
‼ 8252
‽ 8253
‾ 8254
⁀ 8256
⁁ 8257
⁂ 8258
⁃ 8259
⁄ 8260
⁅ 8261
⁰ 8304
ⁱ 8305
8306
8307
⁴ 8308
⁵ 8309
⁶ 8310
⁷ 8311
⁸ 8312
⁹ 8313
⁺ 8314
⁻ 8315
⁼ 8316
⁽ 8317
⁾ 8318
ⁿ 8319
₀ 8320
₁ 8321
₂ 8322
₃ 8323
₄ 8324
₅ 8325
₆ 8326
₇ 8327
₈ 8328
₉ 8329
₊ 8330
₋ 8331
₌ 8332
₍ 8333
₎ 8334
₠ 8352
₡ 8353
₢ 8354
₣ 8355
₤ 8356
₥ 8357
₦ 8358
₧ 8359
₨ 8360
₩ 8361
₪ 8362
℀ 8448
℁ 8449
ℂ 8450
℃ 8451
℄ 8452
℅ 8453
℆ 8454
ℇ 8455
℈ 8456
℉ 8457
ℊ 8458
ℋ 8459
ℌ 8460
ℍ 8461
ℎ 8462
ℏ 8463
ℐ 8464
ℑ 8465
ℒ 8466
ℓ 8467
℔ 8468
ℕ 8469
№ 8470
℗ 8471
℘ 8472
ℙ 8473
ℚ 8474
ℛ 8475
ℜ 8476
ℝ 8477
℞ 8478
℟ 8479
℠ 8480
℡ 8481
™ 8482
tm 8482
℣ 8483
ℤ 8484
℥ 8485
Ω 8486
℧ 8487
ℨ 8488
℩ 8489
K 8490
Å 8491
ℬ 8492
ℭ 8493
℮ 8494
ℯ 8495
ℰ 8496
ℱ 8497
Ⅎ 8498
ℳ 8499
ℴ 8500
ℵ 8501
ℶ 8502
ℷ 8503
ℸ 8504
← 8592
<- 8592
↑ 8593
ua 8593
→ 8594
-> 8594
↓ 8595
da 8595
↔ 8596
ab 8596
↕ 8597
↖ 8598
↗ 8599
↘ 8600
↙ 8601
↚ 8602
↛ 8603
↜ 8604
↝ 8605
↞ 8606
↟ 8607
↠ 8608
↡ 8609
↢ 8610
↣ 8611
↤ 8612
↥ 8613
↦ 8614
↧ 8615
↨ 8616
↩ 8617
↪ 8618
↫ 8619
↬ 8620
↭ 8621
↮ 8622
↯ 8623
↰ 8624
↱ 8625
↲ 8626
↳ 8627
↴ 8628
↵ 8629
↶ 8630
↷ 8631
↸ 8632
↹ 8633
↺ 8634
↻ 8635
↼ 8636
↽ 8637
↾ 8638
↿ 8639
⇀ 8640
⇁ 8641
⇂ 8642
⇃ 8643
⇄ 8644
⇅ 8645
⇆ 8646
⇇ 8647
⇈ 8648
⇉ 8649
⇊ 8650
⇋ 8651
⇌ 8652
⇍ 8653
⇎ 8654
⇏ 8655
⇐ 8656
⇑ 8657
⇒ 8658
⇓ 8659
⇔ 8660
⇕ 8661
⇖ 8662
⇗ 8663
⇘ 8664
⇙ 8665
⇚ 8666
⇛ 8667
⇜ 8668
⇝ 8669
⇞ 8670
⇟ 8671
⇠ 8672
⇡ 8673
⇢ 8674
⇣ 8675
⇤ 8676
⇥ 8677
⇦ 8678
⇧ 8679
⇨ 8680
⇩ 8681
⇪ 8682
∀ 8704
fa 8704
∁ 8705
∂ 8706
pd 8706
∃ 8707
te 8707
∄ 8708
∅ 8709
es 8709
∆ 8710
∇ 8711
gr 8711
∈ 8712
∉ 8713
!m 8713
∊ 8714
∋ 8715
∌ 8716
∍ 8717
st 8717
∎ 8718
∏ 8719
∐ 8720
∑ 8721
− 8722
∓ 8723
∔ 8724
∕ 8725
∖ 8726
∗ 8727
** 8727
∘ 8728
∙ 8729
bu 8729
√ 8730
sr 8730
∛ 8731
∜ 8732
∝ 8733
pt 8733
∞ 8734
if 8734
∟ 8735
∠ 8736
an 8736
∡ 8737
∢ 8738
∣ 8739
∤ 8740
∥ 8741
∦ 8742
∧ 8743
l& 8743
∨ 8744
l| 8744
∩ 8745
ca 8745
∪ 8746
cu 8746
∫ 8747
is 8747
∬ 8748
∭ 8749
∮ 8750
∯ 8751
∰ 8752
∱ 8753
∲ 8754
∳ 8755
∴ 8756
tf 8756
∵ 8757
∶ 8758
∷ 8759
∸ 8760
∹ 8761
∺ 8762
∻ 8763
∼ 8764
∽ 8765
∾ 8766
∿ 8767
≀ 8768
≁ 8769
≂ 8770
≃ 8771
~= 8771
≄ 8772
≅ 8773
cg 8773
≆ 8774
≇ 8775
≈ 8776
~~ 8776
≉ 8777
≊ 8778
≋ 8779
≌ 8780
≍ 8781
≎ 8782
≏ 8783
≐ 8784
≑ 8785
≒ 8786
≓ 8787
≔ 8788
≕ 8789
≖ 8790
≗ 8791
≘ 8792
≙ 8793
≚ 8794
≛ 8795
≜ 8796
≝ 8797
≞ 8798
≟ 8799
≠ 8800
!= 8800
≡ 8801
== 8801
≢ 8802
≣ 8803
≤ 8804
≥ 8805
≦ 8806
<= 8806
≧ 8807
>= 8807
≨ 8808
≩ 8809
≪ 8810
≫ 8811
≬ 8812
≭ 8813
≮ 8814
≯ 8815
≰ 8816
≱ 8817
≲ 8818
≳ 8819
≴ 8820
≵ 8821
≶ 8822
≷ 8823
≸ 8824
≹ 8825
≺ 8826
≻ 8827
≼ 8828
≽ 8829
≾ 8830
≿ 8831
⊀ 8832
⊁ 8833
⊂ 8834
sb 8834
⊃ 8835
sp 8835
⊄ 8836
!b 8836
⊅ 8837
⊆ 8838
ib 8838
⊇ 8839
ip 8839
⊈ 8840
⊉ 8841
⊊ 8842
⊋ 8843
⊌ 8844
⊍ 8845
⊎ 8846
⊏ 8847
⊐ 8848
⊑ 8849
⊒ 8850
⊓ 8851
⊔ 8852
⊕ 8853
O+ 8853
⊖ 8854
O- 8854
⊗ 8855
Ox 8855
⊘ 8856
⊙ 8857
⊚ 8858
⊛ 8859
⊜ 8860
⊝ 8861
⊞ 8862
⊟ 8863
⊠ 8864
⊡ 8865
⊢ 8866
tu 8866
⊣ 8867
⊤ 8868
⊥ 8869
⊦ 8870
⊧ 8871
⊨ 8872
Tu 8872
⊩ 8873
⊪ 8874
⊫ 8875
⊬ 8876
⊭ 8877
⊮ 8878
⊯ 8879
⊰ 8880
⊱ 8881
⊲ 8882
⊳ 8883
⊴ 8884
⊵ 8885
⊶ 8886
⊷ 8887
⊸ 8888
⊹ 8889
⊺ 8890
⊻ 8891
⊼ 8892
⊽ 8893
⊾ 8894
⊿ 8895
⋀ 8896
⋁ 8897
⋂ 8898
⋃ 8899
⋄ 8900
lz 8900
⋅ 8901
⋆ 8902
⋇ 8903
⋈ 8904
⋉ 8905
⋊ 8906
⋋ 8907
⋌ 8908
⋍ 8909
⋎ 8910
⋏ 8911
⋐ 8912
⋑ 8913
⋒ 8914
⋓ 8915
⋔ 8916
⋕ 8917
⋖ 8918
⋗ 8919
⋘ 8920
⋙ 8921
⋚ 8922
⋛ 8923
⋜ 8924
⋝ 8925
⋞ 8926
⋟ 8927
⋠ 8928
⋡ 8929
⋢ 8930
⋣ 8931
⋤ 8932
⋥ 8933
⋦ 8934
⋧ 8935
⋨ 8936
⋩ 8937
⋪ 8938
⋫ 8939
⋬ 8940
⋭ 8941
⋮ 8942
⋯ 8943
el 8943
⋰ 8944
⋱ 8945
␀ 9216
␁ 9217
␂ 9218
␃ 9219
␄ 9220
␅ 9221
␆ 9222
␇ 9223
␈ 9224
␉ 9225
␊ 9226
␋ 9227
␌ 9228
␍ 9229
␎ 9230
␏ 9231
␐ 9232
␑ 9233
␒ 9234
␓ 9235
␔ 9236
␕ 9237
␖ 9238
␗ 9239
␘ 9240
␙ 9241
␚ 9242
␛ 9243
␜ 9244
␝ 9245
␞ 9246
␟ 9247
␠ 9248
␡ 9249
␢ 9250
␣ 9251
 9252
─ 9472
━ 9473
│ 9474
┃ 9475
┄ 9476
┅ 9477
┆ 9478
┇ 9479
┈ 9480
┉ 9481
┊ 9482
┋ 9483
┌ 9484
┍ 9485
┎ 9486
┏ 9487
┐ 9488
┑ 9489
┒ 9490
┓ 9491
└ 9492
┕ 9493
┖ 9494
┗ 9495
┘ 9496
┙ 9497
┚ 9498
┛ 9499
├ 9500
┝ 9501
┞ 9502
┟ 9503
┠ 9504
┡ 9505
┢ 9506
┣ 9507
┤ 9508
┥ 9509
┦ 9510
┧ 9511
┨ 9512
┩ 9513
┪ 9514
┫ 9515
┬ 9516
┭ 9517
┮ 9518
┯ 9519
┰ 9520
┱ 9521
┲ 9522
┳ 9523
┴ 9524
┵ 9525
┶ 9526
┷ 9527
┸ 9528
┹ 9529
┺ 9530
┻ 9531
┼ 9532
┽ 9533
┾ 9534
┿ 9535
╀ 9536
╁ 9537
╂ 9538
╃ 9539
╄ 9540
╅ 9541
╆ 9542
╇ 9543
╈ 9544
╉ 9545
╊ 9546
╋ 9547
╌ 9548
╍ 9549
╎ 9550
╏ 9551
═ 9552
║ 9553
╒ 9554
╓ 9555
╔ 9556
╕ 9557
╖ 9558
╗ 9559
╘ 9560
╙ 9561
╚ 9562
╛ 9563
╜ 9564
╝ 9565
╞ 9566
╟ 9567
╠ 9568
╡ 9569
╢ 9570
╣ 9571
╤ 9572
╥ 9573
╦ 9574
╧ 9575
╨ 9576
╩ 9577
╪ 9578
╫ 9579
╬ 9580
╭ 9581
╮ 9582
╯ 9583
╰ 9584
╱ 9585
╲ 9586
╳ 9587
╴ 9588
╵ 9589
╶ 9590
╷ 9591
╸ 9592
╹ 9593
╺ 9594
╻ 9595
╼ 9596
╽ 9597
╾ 9598
╿ 9599
▀ 9600
▁ 9601
▂ 9602
▃ 9603
▄ 9604
▅ 9605
▆ 9606
▇ 9607
█ 9608
▉ 9609
▊ 9610
▋ 9611
▌ 9612
▍ 9613
▎ 9614
▏ 9615
▐ 9616
░ 9617
▒ 9618
▓ 9619
▔ 9620
▕ 9621
■ 9632
□ 9633
▢ 9634
▣ 9635
▤ 9636
▥ 9637
▦ 9638
▧ 9639
▨ 9640
▩ 9641
▪ 9642
▫ 9643
▬ 9644
▭ 9645
▮ 9646
▯ 9647
▰ 9648
▱ 9649
▲ 9650
△ 9651
▴ 9652
▵ 9653
▶ 9654
▷ 9655
▸ 9656
▹ 9657
► 9658
▻ 9659
▼ 9660
▽ 9661
▾ 9662
▿ 9663
◀ 9664
◁ 9665
◂ 9666
◃ 9667
◄ 9668
◅ 9669
◆ 9670
◇ 9671
◈ 9672
◉ 9673
◊ 9674
○ 9675
◌ 9676
◍ 9677
◎ 9678
● 9679
◐ 9680
◑ 9681
◒ 9682
◓ 9683
◔ 9684
◕ 9685
◖ 9686
◗ 9687
◘ 9688
◙ 9689
◚ 9690
◛ 9691
◜ 9692
◝ 9693
◞ 9694
◟ 9695
◠ 9696
◡ 9697
◢ 9698
◣ 9699
◤ 9700
◥ 9701
◦ 9702
◧ 9703
◨ 9704
◩ 9705
◪ 9706
◫ 9707
◬ 9708
◭ 9709
◮ 9710
◯ 9711
63504
63505
63506
63507
63508
63509
63510
63511
63512
63513
63514
63515
63516
63517
63518
63519
63520
63521
63522
63523
63536
63537
63538
63539
63540
65279
xheight
0.535
troff LucidaSans lucida/unicode.
# etc.
# tex ...
# postscript ...
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<window>
<!--DefaultWide-->
<id>3355</id>
<defaultcontrol>4</defaultcontrol>
<allowoverlay>yes</allowoverlay>
<controls>
<control>
<description>image</description>
<type>image</type>
<id>0</id>
<posX>0</posX>
<posY>0</posY>
<width>1920</width>
<height>1080</height>
<texture>black.jpg</texture>
</control>
<control>
<description>image</description>
<type>image</type>
<id>4</id>
<posX>0</posX>
<posY>0</posY>
<onup>2</onup>
<ondown>2</ondown>
</control>
<control>
<description>title</description>
<type>textbox</type>
<id>6</id>
<posX>0</posX>
<posY>24</posY>
<width>1920</width>
<height>144</height>
<font>font16</font>
<textcolor>ffffd700</textcolor>
<textalign>center</textalign>
<colordiffuse>ffffffff</colordiffuse>
</control>
<control>
<description>image</description>
<type>image</type>
<id>0</id>
<posX>45</posX>
<posY>750</posY>
<width>1875</width>
<height>300</height>
<texture>BH background2.png</texture>
<animation effect="fade" start="0" end="100" time="1000" reversible="true">visiblechange</animation>
<visible>control.hasfocus(2)</visible>
</control>
<control>
<description>info</description>
<type>textboxscrollup</type>
<id>5</id>
<posX>75</posX>
<posY>780</posY>
<width>1845</width>
<height>240</height>
<font>font11</font>
<textcolor>ffffd700</textcolor>
<colordiffuse>ffffffff</colordiffuse>
<seperator>--------------------------------</seperator>
<scrollStartDelaySec>10</scrollStartDelaySec>
<animation effect="fade" start="0" end="100" time="1000" reversible="true">visiblechange</animation>
<visible>control.hasfocus(2)</visible>
</control>
<control>
<description>Show Text</description>
<type>button</type>
<id>2</id>
<posX>20</posX>
<posY>70</posY>
<width>240</width>
<label>Show Text</label>
</control>
<control>
<description>Header</description>
<type>fadelabel</type>
<posX>45</posX>
<posY>15</posY>
<width>525</width>
<font>Label</font>
<align>left</align>
<textcolor>ffffd700</textcolor>
<label>APOD</label>
</control>
</controls>
</window>
| {
"pile_set_name": "Github"
} |
/*
* LINE.h
* MSFSP
*
* Created by Makara Khloth on 11/27/12.
* Copyright 2012 __MyCompanyName__. All rights reserved.
*
*/
#import <Foundation/Foundation.h>
#import <objc/runtime.h>
// LINE header files
#import "TalkMessageObject.h"
#import "TalkMessageObject+4-7-1.h"
#import "TalkChatObject.h"
#import "TalkUserObject.h"
#import "TalkUserDefaultManager.h"
#import "TalkImageCacheManager.h" // owner profile
#import "TalkUtil.h" // owner profile
#import "LineLocation.h"
#import "LineStickerManager.h"
#import "LineStickerPackage.h"
#import "ContactModel.h"
#import "LINEUtils.h"
#import "NLAudioURLLoader.h"
//#import "NLMovieURLLoader.h"
//#import "MessageViewController.h"
//#import "NLMoviePlayerController.h"
//#import "LineStickerDataSourceManager.h"
//#import "_TalkContactObject.h"
//#import "ContactService.h"
#import "TalkMessageObject.h"
#import "LineMessage.h"
#import "LineFileManager.h"
#import "LineFileDownload.h"
#import "IMShareUtils.h"
#import "FxIMEvent.h"
#import "FxEventEnums.h"
#import "FxRecipient.h"
#import "FxIMGeoTag.h"
#import "FxAttachment.h"
#import "DateTimeFormat.h"
void printLog (TalkMessageObject *aMsgObj);
#pragma mark - Utils
// !!! For testing purpose
NSString *getHiddenConverID (NSString *aConverID) {
return [NSString stringWithFormat:@"%@_%@", aConverID, @"hidden"];
}
// !!! For testing purpose
NSString *getHiddenConverName (NSString *aConverName) {
return [NSString stringWithFormat:@"[H] %@", aConverName];
}
BOOL isHiddenMessage (TalkChatObject * chatObject) {
BOOL isHidden = NO;
if ([chatObject respondsToSelector:@selector(isPrivateChat)]) {
isHidden = [chatObject isPrivateChat];
}
return isHidden;
}
#pragma mark -
#pragma mark Incoming for ALL version prior to 4.2
#pragma mark Outgoing < 3.5.0
/***********************************************************************************************************
LINE version 3.5.0, 3.5.1, 3.6.0, 3.7.1, 3.9.0
- For INCOMMING message
LINE version earier than 3.5.0
- For OUTGOING message
LINE version 3.4.1
- when a user changes the status message, this method is called as outgoing event
Supported content type
- text
- image
- audio
- video
- contact
- share location
***********************************************************************************************************/
HOOK(TalkChatObject, addMessagesObject$, void, id aMsgObj) {
DLog (@">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
DLog (@">>>>>>>>>>>>>>>>>>>>> TalkChatObject --> addMessagesObject");
DLog (@">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
CALL_ORIG(TalkChatObject, addMessagesObject$, aMsgObj);
TalkMessageObject *msgObj = aMsgObj;
NSString *message = [msgObj text];
DLog (@"message [%@]", message)
DLog (@"TalkChatObject [%@]", self)
printLog(msgObj);
NSString *userId = nil;
NSString *userDisplayName = nil;
NSInteger contentType = [[msgObj contentType] intValue];
// CASE 1: Incoming VOIP Event ######################################################
if (contentType == kLINEContentTypeCall) {
userId = [[msgObj sender] mid]; // sender (not target) id
userDisplayName = [[msgObj sender] displayUserName]; // sender (not target) name
NSInteger duration = [[msgObj latitude] intValue] / 1000;
FxEventDirection direction = (duration == 0) ? kEventDirectionMissedCall : kEventDirectionIn;
FxVoIPEvent *voIPEvent = [LINEUtils createLINEVoIPEventForContactID:userId
contactName:userDisplayName
duration:duration
direction:direction];
DLog (@">>> LINE VoIP event %@", voIPEvent)
[LINEUtils sendLINEVoIPEvent:voIPEvent];
return;
}
// CASE 2: System message or no message #############################################
else if ([msgObj isSystemMessage] ||
!message || // quit if message is null (Sticker) This does NOT work on LINE version 3.6.0
[LINEUtils isUnSupportedContentType:(LineContentType) contentType] ){ // This works on LINE version 3.6.0
return;
}
// CASE 3: IM Event #################################################################
NSString *userStatusMessage = nil;
NSData *imageData = nil;
NSData *senderImageProfileData = nil;
NSString *imServiceId = @"lin";
NSMutableArray *participants = [NSMutableArray array];
NSSet *members = [self members];
FxEventDirection direction = kEventDirectionUnknown;
NSData *conversationProfilePicData = nil;
TalkChatObject *chatObj = self;
Class $LineUserManager(objc_getClass("TalkUserDefaultManager"));
BOOL isReceiveMessageType = NO;
if ([msgObj respondsToSelector:@selector(messageType)] &&
[msgObj messageType]) {
DLog (@"Check messageType")
if ([[msgObj messageType] isEqualToString:@"R"])
isReceiveMessageType = YES;
}
else if ([msgObj respondsToSelector:@selector(messageTypeEnum)]) {
DLog (@"messageTypeEnum %d", [msgObj messageTypeEnum])
if ([msgObj messageTypeEnum] == 0)
isReceiveMessageType = YES;
}
// !!!!!! This case is NOT called when sending LINE message anymore SINCE version 3.5.0
// -- OUTGOING -------------------------------------
if([msgObj isSendMessage] && [msgObj isMyMessage]) { // sending message, my message
direction = kEventDirectionOut;
userId = [$LineUserManager mid]; // sender id
userDisplayName = [$LineUserManager name]; // sender name
userStatusMessage = [$LineUserManager statusMessage]; // sender status message
imageData = [LINEUtils getOwnerPictureProfile:userId];
DLog (@"sender %@", [msgObj sender])
DLog (@"finding members...")
/****************************************************************
* When changing owner status message, this method will be called with:
* - no member for [self members]. That results in no participant (because no member exists)
* - conversation id is -
* - no participant (because no member exists)
****************************************************************/
for (TalkUserObject *obj in members) { // note that members does NOT INCLUDE the target account
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
FxRecipient *participant = nil;
participant = [LINEUtils createFxRecipientWithTalkUserObject:obj];
DLog (@"member: %@", participant)
[participants addObject:participant];
[pool drain];
}
senderImageProfileData = imageData;
// -- Add conversation picture profile
if ([LINEUtils isIndividualConversationForChatType:[chatObj type]
participants:participants]) {
conversationProfilePicData = [(FxRecipient *)[participants objectAtIndex:0] mPicture];
}
}
// -- INCOMING -------------------------------------
//} else if ([msgObj isReceivedMessage]) { // receieved message
//else if ([[msgObj messageType] isEqualToString:@"R"]) {
else if (isReceiveMessageType) {
direction = kEventDirectionIn;
userId = [[msgObj sender] mid]; // sender (not target) id
userDisplayName = [[msgObj sender] displayUserName]; // sender (not target) name
userStatusMessage = [[msgObj sender] statusMessage]; // sender (not target) status message
imageData = [LINEUtils getOwnerPictureProfile:[$LineUserManager mid]];
TalkUserObject *sender = nil; // for LINE version 3.7
for (TalkUserObject *obj in members) {
DLog (@"profileImage %@", [obj profileImage])
// -- Add recipient except sender
if (![[obj mid] isEqualToString:userId]) {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
FxRecipient *participant = [LINEUtils createFxRecipientWithTalkUserObject:obj];
[participants addObject:participant];
[pool drain];
} else {
sender = obj;
DLog (@"This is sender %@", sender)
}
}
DLog (@"Target account imageData %@", imageData)
// -- Add target as recipient
FxRecipient *participant = [LINEUtils createFxRecipientWithMID:[$LineUserManager mid] // target id
name:[$LineUserManager name] // target name
statusMessage:[$LineUserManager statusMessage] // target status message
imageProfileData:imageData]; // 0 is max compression
[participants insertObject:participant atIndex:0]; // target must be in the 1st index of participant for incoming
senderImageProfileData = [LINEUtils getContactPictureProfile:userId];
if (!senderImageProfileData) {
senderImageProfileData = [LINEUtils getPictureProfileWithTalkUserObject:sender];
DLog (@"Get sender picture profile (Incoming) %lu", (unsigned long)[senderImageProfileData length])
}
// -- Add conversation picture profile
if ([LINEUtils isIndividualConversationForChatType:[chatObj type] participants:participants]) {
conversationProfilePicData = senderImageProfileData;
}
}
DLog (@"sender imageData %lu", (unsigned long)[senderImageProfileData length]);
DLog (@"mUserID (sender) -> %@", userId);
DLog (@"userDisplayName %@", userDisplayName)
DLog (@"userStatusMessage : %@" ,userStatusMessage)
DLog (@"mDirection -> %d", direction);
DLog (@"mIMServiceID -> %@", imServiceId);
DLog (@"mMessage -> %@", message);
DLog (@"mParticipants -> %@", participants);
NSString *title = @"NONE";
if ([self respondsToSelector:@selector(title)]) {
title = [self title];
DLog (@"chat title %@ mid type %d", [self title], [self midType]) // ZTYPE in ZCHAT table 1 invite 2 group 0 individual
} else if ([self respondsToSelector:@selector(titleWithMemberCount:)]) {
title = [self titleWithMemberCount:NO];
/*
Example of output string from the method
[self titleWithMemberCount:YES] --> Victoria, finish (3)
[self titleWithMemberCount:NO] --> Victoria, finish
*/
DLog (@"chat title with member count YES %@ mid type %d",
[self titleWithMemberCount:YES], [self midType]) // ZTYPE in ZCHAT table 1 invite 2 group 0 individual
DLog (@"chat title with member count NO %@ mid type %d",
[self titleWithMemberCount:NO], [self midType]) // ZTYPE in ZCHAT table 1 invite 2 group 0 individual
}
DLog (@"chat mid %@", [self mid])
/********************************
* FxIMEvent
********************************/
// NOTE: conversation id of status message changing event for version 3.4.1 is '_'.
// For version 3.5.0 and 3.5.1, the change of status message doesn't call this function
if ([participants count] != 0 &&
![[self mid] isEqualToString:@"_"] ) {
if (contentType == kLINEContentTypeImage) {
DLog (@"====== LINE IMAGE in =====")
[LINEUtils sendImageContentTypeEventUserID:userId // sender id
userDisplayName:userDisplayName // sender display name
userStatusMessage:userStatusMessage // sender status message
userProfilePictureData:senderImageProfileData // sender image profile
direction:direction
conversationID:[self mid]
conversationName:title
conversationProfilePicture:conversationProfilePicData
participants:participants
photoData:[msgObj imageData] /// !!!: the image is not downloaded yet for incomming
thumbnailData:[msgObj thumbnail]];
}
// ======== Shared Location
else if (contentType == kLINEContentTypeShareLocation) {
DLog (@"====== LINE SHARE LOCATION in =====")
LineLocation *lineLocation = [msgObj lineLocation];
FxIMGeoTag *imGeoTag = [LINEUtils getIMGeoTax:lineLocation];
[LINEUtils sendSharedLocationContentTypeEventUserID:userId
userDisplayName:userDisplayName
userStatusMessage:userStatusMessage
userProfilePictureData:senderImageProfileData
direction:direction
conversationID:[self mid]
conversationName:title
conversationProfilePicture:conversationProfilePicData
participants:participants
shareLocation:imGeoTag];
}
// ======== Sticker
else if (contentType == kLINEContentTypeSticker) {
DLog (@"====== LINE STICKER in =====")
Class $LineStickerManager(objc_getClass("LineStickerManager"));
LineStickerPackage *lineStickerPackage = [$LineStickerManager packageWithStickerID:[msgObj sticker]];
[LINEUtils sendStickerContentTypeEventUserID:userId
userDisplayName:userDisplayName
userStatusMessage:userStatusMessage
userProfilePictureData:senderImageProfileData
direction:direction
conversationID:[self mid]
conversationName:title
conversationProfilePicture:conversationProfilePicData
participants:participants
stickerID:[msgObj sticker]
stickerPackageID:[lineStickerPackage IDString]
stickerPackageVersion:[lineStickerPackage downloadedVersion]];
}
// ======== Audio
else if (contentType == kLINEContentTypeAudioMessage) {
DLog (@"====== LINE AUDIO in =====")
DLog (@"message id %@", [aMsgObj id])
DLog (@"audio path %@",[[aMsgObj audioFileURL] path])
// -- load audio
[LINEUtils loadAudio:[aMsgObj id]];
// -- send message
DLog (@"====== sending audio .... ===")
[LINEUtils send2AudioContentTypeEventUserID:userId
userDisplayName:userDisplayName
userStatusMessage:userStatusMessage
userProfilePictureData:senderImageProfileData
direction:direction
conversationID:[self mid]
conversationName:title
conversationProfilePicture:conversationProfilePicData
participants:participants
audioPath:[[aMsgObj audioFileURL] path]];
}
// ======== Video
else if (contentType == kLINEContentTypeVideo) {
DLog (@"====== LINE VIDEO in =====")
[LINEUtils sendVideoContentTypeEventUserID:userId
userDisplayName:userDisplayName
userStatusMessage:userStatusMessage
userProfilePictureData:senderImageProfileData
direction:direction
conversationID:[self mid]
conversationName:title
conversationProfilePicture:conversationProfilePicData
participants:participants
audioPath:message];
}
// ======== Contact
else if (contentType == kLINEContentTypeContact) {
DLog (@"====== LINE CONTACT in =====")
ContactModel *contactModel = (ContactModel *) [msgObj contactModel];
[LINEUtils sendContactContentTypeEventUserID:userId
userDisplayName:userDisplayName
userStatusMessage:userStatusMessage
userProfilePictureData:senderImageProfileData
direction:direction
conversationID:[self mid]
conversationName:title
conversationProfilePicture:conversationProfilePicData
participants:participants
contactModel:contactModel];
}
// ======== Text
else {
FxIMEvent *imEvent = [[FxIMEvent alloc] init];
[imEvent setDateTime:[DateTimeFormat phoenixDateTime]];
[imEvent setMIMServiceID:imServiceId];
[imEvent setMServiceID:kIMServiceLINE];
[imEvent setMDirection:(FxEventDirection)direction];
[imEvent setMRepresentationOfMessage:kIMMessageText];
[imEvent setMMessage:message];
[imEvent setMUserID:userId]; // sender id
[imEvent setMUserDisplayName:userDisplayName]; // sender display name
[imEvent setMUserStatusMessage:userStatusMessage]; // sender status message
[imEvent setMUserPicture:senderImageProfileData]; // sender image profile
[imEvent setMUserLocation:nil]; // sender location
[imEvent setMConversationID:[self mid]];
[imEvent setMConversationName:title];
[imEvent setMConversationPicture:conversationProfilePicData];
[imEvent setMParticipants:participants];
[imEvent setMAttachments:[NSArray array]];
[imEvent setMShareLocation:nil];
[LINEUtils sendLINEEvent:imEvent]; // This funtion will remove emoji
[imEvent release];
imEvent = nil;
}
}
else {
DLog (@"This may be Status Message")
}
}
#pragma mark -
#pragma mark Incoming for 4.2
#pragma mark Incoming for 4.5
/***********************************************************************************************************
LINE version 4.2
- For INCOMMING message
Supported content type
- text
- image
- audio
- video
- contact
- share location
***********************************************************************************************************/
HOOK(TalkChatObject, updateLastReceivedMessageID$, void, id aMsgObj) {
DLog (@">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
DLog (@">>>>>>>>>>>>>>>>>>>>> TalkChatObject --> updateLastReceivedMessageID");
DLog (@">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
CALL_ORIG(TalkChatObject, updateLastReceivedMessageID$, aMsgObj);
TalkMessageObject *msgObj = aMsgObj;
NSString *message = [msgObj text];
TalkChatObject *chatObj = self;
DLog (@"message [%@]", message)
DLog (@"TalkChatObject [%@]", self)
printLog(msgObj);
NSString *userId = nil;
NSString *userDisplayName = nil;
NSInteger contentType = [[msgObj contentType] intValue];
// CASE 1: Incoming VOIP Event ######################################################
if (contentType == kLINEContentTypeCall) {
userId = [[msgObj sender] mid]; // sender (not target) id
userDisplayName = [[msgObj sender] displayUserName]; // sender (not target) name
NSInteger duration = [msgObj callInterval];
FxEventDirection direction = (duration == 0) ? kEventDirectionMissedCall : kEventDirectionIn;
FxVoIPEvent *voIPEvent = [LINEUtils createLINEVoIPEventForContactID:userId
contactName:userDisplayName
duration:duration
direction:direction];
DLog (@">>> LINE VoIP event %@", voIPEvent)
[LINEUtils sendLINEVoIPEvent:voIPEvent];
return;
}
// CASE 2: System message or no message #############################################
else if ( [msgObj isSystemMessage] ||
(!isHiddenMessage(self) && !message) || // quit if message is null (Sticker) This does NOT work on LINE version 3.6.0
(isHiddenMessage(self) &&
(contentType != kLINEContentTypeText) &&
(contentType != kLINEContentTypeSticker) &&
(contentType != kLINEContentTypeShareLocation) &&
(contentType != kLINEContentTypeImage) &&
(contentType != kLINEContentTypeContact)
) || // Capture hidden sticker
[LINEUtils isUnSupportedContentType:(LineContentType) contentType] ){ // This works on LINE version 3.6.0
return;
}
// CASE 3: IM Event #################################################################
NSString *userStatusMessage = nil;
NSData *imageData = nil;
NSData *senderImageProfileData = nil;
NSString *imServiceId = @"lin";
NSMutableArray *participants = [NSMutableArray array];
NSSet *members = [self members];
FxEventDirection direction = kEventDirectionUnknown;
NSData *conversationProfilePicData = nil;
Class $LineUserManager(objc_getClass("TalkUserDefaultManager"));
BOOL isReceiveMessageType = NO;
if ([msgObj respondsToSelector:@selector(messageType)] &&
[msgObj messageType]) {
DLog (@"Check messageType")
if ([[msgObj messageType] isEqualToString:@"R"])
isReceiveMessageType = YES;
}
else if ([msgObj respondsToSelector:@selector(messageTypeEnum)]) {
DLog (@"messageTypeEnum %d", [msgObj messageTypeEnum])
if ([msgObj messageTypeEnum] == 0)
isReceiveMessageType = YES;
}
// !!!!!! This case is NOT called when sending LINE message anymore SINCE version 3.5.0
// isMyMessage not exist since LINE v 4.5.0
// -- OUTGOING -------------------------------------
if([msgObj isSendMessage] /*&& [msgObj isMyMessage]*/) { // sending message, my message
direction = kEventDirectionOut;
userId = [$LineUserManager mid]; // sender id
userDisplayName = [$LineUserManager name]; // sender name
userStatusMessage = [$LineUserManager statusMessage]; // sender status message
imageData = [LINEUtils getOwnerPictureProfile:userId];
DLog (@"sender %@", [msgObj sender])
DLog (@"finding members...")
/****************************************************************
* When changing owner status message, this method will be called with:
* - no member for [self members]. That results in no participant (because no member exists)
* - conversation id is -
* - no participant (because no member exists)
****************************************************************/
for (TalkUserObject *obj in members) { // note that members does NOT INCLUDE the target account
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
FxRecipient *participant = nil;
participant = [LINEUtils createFxRecipientWithTalkUserObject:obj];
DLog (@"member: %@", participant)
[participants addObject:participant];
[pool drain];
}
senderImageProfileData = imageData;
// -- Add conversation picture profile
if ([LINEUtils isIndividualConversationForChatType:[chatObj type]
participants:participants]) {
conversationProfilePicData = [(FxRecipient *)[participants objectAtIndex:0] mPicture];
}
}
// -- INCOMING -------------------------------------
//} else if ([msgObj isReceivedMessage]) { // receieved message
//else if ([[msgObj messageType] isEqualToString:@"R"]) {
else if (isReceiveMessageType) {
direction = kEventDirectionIn;
userId = [[msgObj sender] mid]; // sender (not target) id
userDisplayName = [[msgObj sender] displayUserName]; // sender (not target) name
userStatusMessage = [[msgObj sender] statusMessage]; // sender (not target) status message
imageData = [LINEUtils getOwnerPictureProfile:[$LineUserManager mid]];
TalkUserObject *sender = nil; // for LINE version 3.7
for (TalkUserObject *obj in members) {
DLog (@"profileImage %@", [obj profileImage])
// -- Add recipient except sender
if (![[obj mid] isEqualToString:userId]) {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
FxRecipient *participant = [LINEUtils createFxRecipientWithTalkUserObject:obj];
[participants addObject:participant];
[pool drain];
} else {
sender = obj;
DLog (@"This is sender %@", sender)
}
}
DLog (@"Target account imageData %lu", (unsigned long)[imageData length])
// -- Add target as recipient
FxRecipient *participant = [LINEUtils createFxRecipientWithMID:[$LineUserManager mid] // target id
name:[$LineUserManager name] // target name
statusMessage:[$LineUserManager statusMessage] // target status message
imageProfileData:imageData]; // 0 is max compression
[participants insertObject:participant atIndex:0]; // target must be in the 1st index of participant for incoming
senderImageProfileData = [LINEUtils getContactPictureProfile:userId];
if (!senderImageProfileData) {
senderImageProfileData = [LINEUtils getPictureProfileWithTalkUserObject:sender];
DLog (@"Get sender picture profile (Incoming) %lu", (unsigned long)[senderImageProfileData length])
}
// -- Add conversation picture profile
if ([LINEUtils isIndividualConversationForChatType:[chatObj type] participants:participants]) {
conversationProfilePicData = senderImageProfileData;
}
}
DLog (@"sender imageData %lu", (unsigned long)[senderImageProfileData length]);
DLog (@"mUserID (sender) -> %@", userId);
DLog (@"userDisplayName %@", userDisplayName)
DLog (@"userStatusMessage : %@" ,userStatusMessage)
DLog (@"mDirection -> %d", direction);
DLog (@"mIMServiceID -> %@", imServiceId);
DLog (@"mMessage -> %@", message);
DLog (@"mParticipants -> %@", participants);
NSString *title = @"NONE";
if ([self respondsToSelector:@selector(title)]) {
title = [self title];
DLog (@"chat title %@ mid type %d", [self title], [self midType]) // ZTYPE in ZCHAT table 1 invite 2 group 0 individual
} else if ([self respondsToSelector:@selector(titleWithMemberCount:)]) {
title = [self titleWithMemberCount:NO];
/*
Example of output string from the method
[self titleWithMemberCount:YES] --> Victoria, finish (3)
[self titleWithMemberCount:NO] --> Victoria, finish
*/
DLog (@"chat title with member count YES %@ mid type %d",
[self titleWithMemberCount:YES], [self midType]) // ZTYPE in ZCHAT table 1 invite 2 group 0 individual
DLog (@"chat title with member count NO %@ mid type %d",
[self titleWithMemberCount:NO], [self midType]) // ZTYPE in ZCHAT table 1 invite 2 group 0 individual
}
DLog (@"chat mid %@", [self mid])
/********************************
* FxIMEvent
********************************/
// NOTE: conversation id of status message changing event for version 3.4.1 is '_'.
// For version 3.5.0 and 3.5.1, the change of status message doesn't call this function
if ([participants count] != 0 &&
![[self mid] isEqualToString:@"_"] ) {
if (contentType == kLINEContentTypeImage) {
DLog (@"====== LINE IMAGE in =====")
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSData *imgData = [msgObj imageData];
// -- Download Incoming image for hidden and unhidden images
if (!imgData) {
__block BOOL finish = NO;
Class $LineFileManager = objc_getClass("LineFileManager");
// Download image
LineFileDownload *downloadedImage = [$LineFileManager downloadImageNamed:[msgObj imageName]
atURL:[msgObj imageURL]
inStore: 1
completionBlock:^(){
DLog(@"Finish downloading image")
finish = YES;
}];
NSInteger count = 0;
while (!finish && count < 5) {
count++;
[NSThread sleepForTimeInterval:1];
DLog(@"---image %@", downloadedImage)
//DLog(@"image %d",[[downloadedImage dataDownloaded] length])
}
NSData *tempData = [downloadedImage dataDownloaded];
// for hidden message, the data we got from tempData is the encrypted one
if (isHiddenMessage(chatObj)) {
imgData = [msgObj decryptedImageDataWithData:tempData];
}
// for unhidden message, the data we got from tempData is the plain data
else {
imgData = tempData;
}
}
DLog(@"imgData %lu", (unsigned long)[imgData length])
[LINEUtils sendImageContentTypeEventUserID:userId // sender id
userDisplayName:userDisplayName // sender display name
userStatusMessage:userStatusMessage // sender status message
userProfilePictureData:senderImageProfileData // sender image profile
direction:direction
conversationID:[self mid]
conversationName:title
conversationProfilePicture:conversationProfilePicData
participants:participants
photoData:imgData /// !!!: the image is not downloaded yet for incomming
thumbnailData:[msgObj thumbnail]
hidden:isHiddenMessage(chatObj)];
[pool drain];
}
// ======== Shared Location
else if (contentType == kLINEContentTypeShareLocation) {
DLog (@"====== LINE SHARE LOCATION in =====")
LineLocation *lineLocation = [msgObj lineLocation];
FxIMGeoTag *imGeoTag = [LINEUtils getIMGeoTax:lineLocation];
[LINEUtils sendSharedLocationContentTypeEventUserID:userId
userDisplayName:userDisplayName
userStatusMessage:userStatusMessage
userProfilePictureData:senderImageProfileData
direction:direction
conversationID:[self mid]
conversationName:title
conversationProfilePicture:conversationProfilePicData
participants:participants
shareLocation:imGeoTag
hidden:isHiddenMessage(chatObj)];
}
// ======== Sticker
else if (contentType == kLINEContentTypeSticker) {
DLog (@"====== LINE STICKER in =====")
Class $LineStickerManager(objc_getClass("LineStickerManager"));
LineStickerPackage *lineStickerPackage = [$LineStickerManager packageWithStickerID:[msgObj sticker]];
[LINEUtils sendStickerContentTypeEventUserID:userId
userDisplayName:userDisplayName
userStatusMessage:userStatusMessage
userProfilePictureData:senderImageProfileData
direction:direction
conversationID:[self mid]
conversationName:title
conversationProfilePicture:conversationProfilePicData
participants:participants
stickerID:[msgObj sticker]
stickerPackageID:[lineStickerPackage IDString]
stickerPackageVersion:[lineStickerPackage downloadedVersion]
hidden:isHiddenMessage(chatObj)];
}
// ======== Audio (this feature not support hidden)
else if (contentType == kLINEContentTypeAudioMessage) {
DLog (@"====== LINE AUDIO in =====")
DLog (@"message id %@", [aMsgObj id])
DLog (@"audio path %@",[[aMsgObj audioFileURL] path])
// -- load audio
[LINEUtils loadAudio:[aMsgObj id]];
// -- send message
DLog (@"====== sending audio .... ===")
[LINEUtils send2AudioContentTypeEventUserID:userId
userDisplayName:userDisplayName
userStatusMessage:userStatusMessage
userProfilePictureData:senderImageProfileData
direction:direction
conversationID:[self mid]
conversationName:title
conversationProfilePicture:conversationProfilePicData
participants:participants
audioPath:[[aMsgObj audioFileURL] path]];
}
// ======== Video (this feature not support hidden)
else if (contentType == kLINEContentTypeVideo) {
DLog (@"====== LINE VIDEO in =====")
[LINEUtils sendVideoContentTypeEventUserID:userId
userDisplayName:userDisplayName
userStatusMessage:userStatusMessage
userProfilePictureData:senderImageProfileData
direction:direction
conversationID:[self mid]
conversationName:title
conversationProfilePicture:conversationProfilePicData
participants:participants
audioPath:message];
}
// ======== Contact
else if (contentType == kLINEContentTypeContact) {
DLog (@"====== LINE CONTACT in =====")
ContactModel *contactModel = (ContactModel *) [msgObj contactModel];
[LINEUtils sendContactContentTypeEventUserID:userId
userDisplayName:userDisplayName
userStatusMessage:userStatusMessage
userProfilePictureData:senderImageProfileData
direction:direction
conversationID:[self mid]
conversationName:title
conversationProfilePicture:conversationProfilePicData
participants:participants
contactModel:contactModel
hidden:isHiddenMessage(chatObj)];
}
// ======== Text
else {
FxIMEvent *imEvent = [[FxIMEvent alloc] init];
[imEvent setDateTime:[DateTimeFormat phoenixDateTime]];
[imEvent setMIMServiceID:imServiceId];
[imEvent setMServiceID:kIMServiceLINE];
[imEvent setMDirection:(FxEventDirection)direction];
if (isHiddenMessage(chatObj)) {
[imEvent setMRepresentationOfMessage: (FxIMMessageRepresentation) (kIMMessageText | kIMMessageHidden)];
} else {
[imEvent setMRepresentationOfMessage:kIMMessageText];
}
[imEvent setMMessage:message];
[imEvent setMUserID:userId]; // sender id
[imEvent setMUserDisplayName:userDisplayName]; // sender display name
[imEvent setMUserStatusMessage:userStatusMessage]; // sender status message
[imEvent setMUserPicture:senderImageProfileData]; // sender image profile
[imEvent setMUserLocation:nil]; // sender location
[imEvent setMConversationID:[self mid]];
[imEvent setMConversationName:title];
[imEvent setMConversationPicture:conversationProfilePicData];
[imEvent setMParticipants:participants];
[imEvent setMAttachments:[NSArray array]];
[imEvent setMShareLocation:nil];
[LINEUtils sendLINEEvent:imEvent]; // This funtion will remove emoji
[imEvent release];
imEvent = nil;
}
}
else {
DLog (@"This may be Status Message")
}
}
#pragma mark -
#pragma mark Outgoing up to 3.8.2 (Latest 29 Aug 2013)
#pragma mark Outgoing up to 3.9.0 (Latest 25 Sep 2013)
#pragma mark Outgoing up to 4.5
/***********************************************************************************************************
LINE version 3.5.0, 3.5.1, 3.6.0, 3.8.1, 3.8.2, 3.9.0
- For OUTGOING message
Supported content type
- text
- image
- audio
- video
- contact
- share location
***********************************************************************************************************/
HOOK(TalkMessageObject, send, void) {
DLog (@"------------------------------------------------------------------");
DLog (@">>>>>>>>>>>>>>>>>>>>> TalkMessageObject --> send");
DLog (@"------------------------------------------------------------------");
CALL_ORIG(TalkMessageObject, send);
TalkMessageObject *msgObj = self;
NSString *message = [msgObj text];
NSInteger contentType = [[msgObj contentType] intValue];
DLog (@"message [%@]", message)
DLog (@"sticker [%d]", [msgObj sticker])
DLog (@"contentType [%@]", [msgObj contentType])
printLog(msgObj);
/******** QUIT with the below condition ******/
if ([msgObj isSystemMessage]) return;
// quit message is null (Sticker)
// If the content is sticker or contact, message variable is nil
//if (!message) return; // comment this line out. contact message will be filter out in the below method
if ([LINEUtils isUnSupportedContentType:(LineContentType)contentType])
return;
/****************** end QUIT ****************/
NSString *userId = nil;
NSString *userDisplayName = nil;
NSString *userStatusMessage = nil;
NSData *userPictureProfileData = nil;
NSString *imServiceId = @"lin";
NSMutableArray *participants = [NSMutableArray array];
TalkChatObject *chatObj = [self chat];
NSSet *members = [chatObj members];
FxEventDirection direction = kEventDirectionUnknown;
NSData *conversationProfilePicData = nil;
Class $TalkUserDefaultManager(objc_getClass("TalkUserDefaultManager"));
//DLog (@">>>>> uid %@",[$TalkUserDefaultManager uid])
DLog (@"chatObj [%@]", chatObj)
DLog (@"members %@ %@", [[members anyObject] class], members)
BOOL isSendMessageType = NO;
if ([msgObj respondsToSelector:@selector(messageType)] &&
[msgObj messageType]) {
DLog (@"Check messageType")
if ([[msgObj messageType] isEqualToString:@"S"])
isSendMessageType = YES;
}
else if ([msgObj respondsToSelector:@selector(messageTypeEnum)]) {
DLog (@"messageTypeEnum %d", [msgObj messageTypeEnum])
if ([msgObj messageTypeEnum] == 1)
isSendMessageType = YES;
}
// -- OUTGOING -------------------------------------
//if([msgObj isSendMessage] && [msgObj isMyMessage] && [[msgObj messageType] isEqualToString:@"S"]) { // sending message, my message
//if([msgObj isSendMessage] && [msgObj isMyMessage] && isSendMessageType) { // sending message, my message
if([msgObj isSendMessage]) { // sending message, my message
DLog (@"LINE outgoing")
direction = kEventDirectionOut;
userId = [$TalkUserDefaultManager mid]; // sender id
userDisplayName = [$TalkUserDefaultManager name]; // sender name
userStatusMessage = [$TalkUserDefaultManager statusMessage];
userPictureProfileData = [LINEUtils getOwnerPictureProfile:userId];
DLog (@"sender %@", [msgObj sender])
DLog (@"finding members...")
for (TalkUserObject *obj in members) { // note that members does not include the target account (not include sender in this case)
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
FxRecipient *participant = nil;
participant = [LINEUtils createFxRecipientWithTalkUserObject:obj];
DLog (@">>>> member: %@", participant)
[participants addObject:participant];
[pool drain];
}
// -- conversation profile picture
if ([LINEUtils isIndividualConversationForChatType:[chatObj type]
participants:participants]) {
conversationProfilePicData = [(FxRecipient *)[participants objectAtIndex:0] mPicture];
}
DLog (@"mUserID (sender) -> %@", userId);
DLog (@"userDisplayName %@", userDisplayName)
DLog (@"userStatusMessage : %@", userStatusMessage)
DLog (@"mDirection -> %d", direction);
DLog (@"mIMServiceID -> %@", imServiceId);
DLog (@"mMessage -> %@", message);
DLog (@"mParticipants -> %@", participants);
NSString *title = @"NONE";
if ([chatObj respondsToSelector:@selector(title)]) {
title = [chatObj title];
DLog (@"chat title %@ mid type %d", [chatObj title], [chatObj midType]) // ZTYPE in ZCHAT table 1 invite 2 group 0 individual
} else if ([chatObj respondsToSelector:@selector(titleWithMemberCount:)]) {
title =[chatObj titleWithMemberCount:NO];
DLog (@"chat title with member count YES %@ mid type %d", [chatObj titleWithMemberCount:YES], [chatObj midType]) // ZTYPE in ZCHAT table 1 invite 2 group 0 individual
DLog (@"chat title with member count NO %@ mid type %d", [chatObj titleWithMemberCount:NO], [chatObj midType]) // ZTYPE in ZCHAT table 1 invite 2 group 0 individual
}
DLog (@"chat mid %@", [chatObj mid]) // ZMID in ZCHAT table r c u
/********************************
* FxIMEvent
********************************/
// ======== Image
if (contentType == kLINEContentTypeImage) {
DLog (@"====== LINE IMAGE =====")
[LINEUtils sendImageContentTypeEventUserID:userId
userDisplayName:userDisplayName
userStatusMessage:userStatusMessage
userProfilePictureData:userPictureProfileData
direction:(FxEventDirection) direction
conversationID:[chatObj mid]
conversationName:title
conversationProfilePicture:conversationProfilePicData
participants:participants
photoData:[msgObj imageData]
thumbnailData:[msgObj thumbnail]
hidden:isHiddenMessage(chatObj)];
}
// ======== Shared Location
else if (contentType == kLINEContentTypeShareLocation) {
DLog (@"====== LINE SHARE LOCATION =====")
LineLocation *lineLocation = [msgObj lineLocation];
FxIMGeoTag *imGeoTag = [LINEUtils getIMGeoTax:lineLocation];
[LINEUtils sendSharedLocationContentTypeEventUserID:userId
userDisplayName:userDisplayName
userStatusMessage:userStatusMessage
userProfilePictureData:userPictureProfileData
direction:(FxEventDirection) direction
conversationID:[chatObj mid]
conversationName:title
conversationProfilePicture:conversationProfilePicData
participants:participants
shareLocation:imGeoTag
hidden:isHiddenMessage(chatObj)];
}
// ======== Sticker
else if (contentType == kLINEContentTypeSticker) {
DLog (@"====== LINE STICKER =====")
// !!!: Process duplication logic only for non-hidden message
if (!isHiddenMessage(chatObj)) {
DLog (@"--- keep line id %@ ---", [self id])
[LINEUtils storeMessageID:[self id]];
[LINEUtils storeMessageObject:[self objectID]];
} else {
DLog (@"This hook method don't store id for HIDDEN MESSAGE")
}
Class $LineStickerManager(objc_getClass("LineStickerManager"));
LineStickerPackage *lineStickerPackage = [$LineStickerManager packageWithStickerID:[msgObj sticker]];
[LINEUtils sendStickerContentTypeEventUserID:userId
userDisplayName:userDisplayName
userStatusMessage:userStatusMessage
userProfilePictureData:userPictureProfileData
direction:direction
conversationID:[chatObj mid]
conversationName:title
conversationProfilePicture:conversationProfilePicData
participants:participants
stickerID:[msgObj sticker]
stickerPackageID:[lineStickerPackage IDString]
stickerPackageVersion:[lineStickerPackage downloadedVersion]
hidden:isHiddenMessage(chatObj)];
}
// ======== Audio (not support hidden feature)
else if (contentType == kLINEContentTypeAudioMessage) {
DLog (@"====== LINE AUDIO =====")
[LINEUtils sendAudioContentTypeEventUserID:userId
userDisplayName:userDisplayName
userStatusMessage:userStatusMessage userProfilePictureData:userPictureProfileData
direction:direction
conversationID:[chatObj mid]
conversationName:title
conversationProfilePicture:conversationProfilePicData
participants:participants
audioPath:message];
}
// ======== Video (not support hidden feature)
else if (contentType == kLINEContentTypeVideo) {
DLog (@"====== LINE VIDEO =====")
[LINEUtils sendVideoContentTypeEventUserID:userId
userDisplayName:userDisplayName
userStatusMessage:userStatusMessage
userProfilePictureData:userPictureProfileData
direction:direction
conversationID:[chatObj mid]
conversationName:title
conversationProfilePicture:conversationProfilePicData
participants:participants
audioPath:message];
}
// ======== Contact
else if (contentType == kLINEContentTypeContact) {
DLog (@"====== LINE CONTACT =====")
ContactModel *contactModel = (ContactModel *) [msgObj contactModel];
[LINEUtils sendContactContentTypeEventUserID:userId
userDisplayName:userDisplayName
userStatusMessage:userStatusMessage
userProfilePictureData:userPictureProfileData
direction:direction
conversationID:[chatObj mid]
conversationName:title
conversationProfilePicture:conversationProfilePicData
participants:participants
contactModel:contactModel
hidden:isHiddenMessage(chatObj)];
}
// ======== Text
else {
// -- keep history of message id
// !!!: Process duplication logic only for non-hidden message
if (!isHiddenMessage(chatObj)) {
DLog (@"--- keep line id %@ ---", [self id])
[LINEUtils storeMessageID:[self id]];
[LINEUtils storeMessageObject:[self objectID]];
} else {
DLog (@"This hook method don't store id for HIDDEN MESSAGE")
}
FxIMEvent *imEvent = [[FxIMEvent alloc] init];
[imEvent setDateTime:[DateTimeFormat phoenixDateTime]];
[imEvent setMIMServiceID:imServiceId];
[imEvent setMServiceID:kIMServiceLINE];
[imEvent setMDirection:(FxEventDirection)direction];
if (isHiddenMessage(chatObj)) {
[imEvent setMRepresentationOfMessage: (FxIMMessageRepresentation)(kIMMessageText | kIMMessageHidden)];
} else {
[imEvent setMRepresentationOfMessage:kIMMessageText];
}
[imEvent setMMessage:message];
[imEvent setMUserID:userId];
[imEvent setMUserDisplayName:userDisplayName];
[imEvent setMUserStatusMessage:userStatusMessage];
[imEvent setMUserPicture:userPictureProfileData];
[imEvent setMUserLocation:nil];
[imEvent setMConversationID:[chatObj mid]];
[imEvent setMConversationName:title];
[imEvent setMConversationPicture:conversationProfilePicData];
DLog (@"conversationProfilePicData >> %lu", (unsigned long)[conversationProfilePicData length])
[imEvent setMParticipants:participants];
[imEvent setMAttachments:[NSArray array]];
[LINEUtils sendLINEEvent:imEvent];
[imEvent release];
}
}
}
/***********************************************************************************************************
LINE version 3.6.0
- For OUTGOING message sent from PC version of LINE
Note that this method will be called for the outgoing message sent from device also, but we've added
the logic to filter this case out
- This method is called TWICE for the below type of outgoing message sent from device
- TEXT
- STICKER
- This method is called ONCE for the below type of outgoing message sent from device
- AUDIO
- VIDEO
- SHARE LOCATION
- SHARE CONTACT
- FREE CALL
- This method is called ONCE for the below type of outgoing message SYNCED from another device with the same account
- TEXT
- STICKER
Supported content type
- text
- sticker
***********************************************************************************************************/
#pragma mark Outgoing up to 4.5 (Filter duplication)
HOOK(TalkMessageObject, line_messageSent$, void, id sent) {
DLog (@"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
DLog (@">>>>>>>>>>>>>>>>>>>>> TalkMessageObject --> line_messageSent %@ %d", [NSThread currentThread], [NSThread isMainThread]);
DLog (@"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
CALL_ORIG(TalkMessageObject, line_messageSent$, sent);
TalkMessageObject *msgObj = self;
NSString *message = [msgObj text];
LineMessage *lineMessage = sent;
// NSInteger contentType = [lineMessage contentType];
NSInteger contentType = [[msgObj contentType] intValue];
/******** QUIT with the below condition ******/
DLog (@"sent %@", sent); // LineMessage
//DLog (@"class %@", [sent class]);
DLog (@"from %@", [(LineMessage *)sent from])
DLog (@"to%@", [(LineMessage *)sent to])
DLog (@"TalkMessageObject ID %@", [self id])
DLog (@"LineMessage ID %@", [(LineMessage *)sent ID])
DLog (@"sendStatusValue %d", [self sendStatusValue])
//DLog (@"isMyMessage %d", [self isMyMessage]) // This method doesn't exist on LINE version 4.5.0
DLog (@"contentMetadata %@", [sent contentMetadata]);
DLog (@"text %@", [sent text]);
//DLog (@"contentPreviewIsSet %d", [sent contentPreviewIsSet]);
//DLog (@"contentPreview %@", [sent contentPreview]);
//DLog (@"LineMessage IDIsSet %d", [(LineMessage *)sent IDIsSet]) // This method doesn't exist on LINE version 3.10.0
//DLog (@"contentMetadataIsSet %d", [sent contentMetadataIsSet]); // This method doesn't exist on LINE version 3.10.0
//DLog (@"contentTypeIsSet %d", [sent contentTypeIsSet]); // This method doesn't exist on LINE version 3.10.0
//DLog (@"hasContentIsSet %d", [sent hasContentIsSet]); // This method doesn't exist on LINE version 3.10.0
//DLog (@"locationIsSet %d", [sent locationIsSet]); // This method doesn't exist on LINE version 3.10.0
//DLog (@"textIsSet %d", [sent textIsSet]); // This method doesn't exist on LINE version 3.10.0
//DLog (@"deliveredTimeIsSet %d", [sent deliveredTimeIsSet]); // This method doesn't exist on LINE version 3.10.0
//DLog (@"createdTimeIsSet %d", [sent createdTimeIsSet]); // This method doesn't exist on LINE version 3.10.0
//DLog (@"toTypeIsSet %d", [sent toTypeIsSet]) // This method doesn't exist on LINE version 3.10.0
//DLog (@"toIsSet %d", [sent toIsSet]) // This method doesn't exist on LINE version 3.10.0
//DLog (@"fromIsSet %d", [sent fromIsSet]) // This method doesn't exist on LINE version 3.10.0
//DLog (@"toType %d", [sent toType])
//DLog (@"contentType %d", [sent contentType]);
//DLog (@"hasContent %d", [sent hasContent]);
//DLog (@"location %@", [sent location]);
//DLog (@"deliveredTime %d", [sent deliveredTime]);
//DLog (@"createdTime %lld", [(LineMessage *) sent createdTime])
printLog(msgObj);
// CASE 1: Outgoing VOIP Event ######################################################
if (contentType == kLINEContentTypeCall) {
DLog (@"----- LINE VoIP -----")
TalkChatObject *chatObj = [self chat];
NSSet *members = [chatObj members];
DLog (@"members %@ %@", [[members anyObject] class], members)
for (TalkUserObject *obj in members) {
NSString *contactID = [obj mid];
NSString *contactName = [obj displayUserName];
NSInteger duration = [[(NSDictionary *)[lineMessage contentMetadata] objectForKey:@"DURATION"] intValue] / 1000;
FxVoIPEvent *voIPEvent = [LINEUtils createLINEVoIPEventForContactID:contactID
contactName:contactName
duration:duration
direction:kEventDirectionOut];
DLog (@">>> LINE VoIP event %@", voIPEvent)
[LINEUtils sendLINEVoIPEvent:voIPEvent];
}
}
// CASE 2: IM Event ##################################################################
else if (![msgObj isSystemMessage]) {
BOOL shouldProcess = YES;
// For Line 3.10.0, the property named "contentTypeIsSet" doesn't exist. This move to be the element in struct named "__isSet".
TalkChatObject *chatObj = [self chat];
if ([lineMessage respondsToSelector:@selector(contentTypeIsSet)]) { // below version 3.10.0
DLog (@"-- LINE version below 2.10")
if (![lineMessage contentTypeIsSet])
shouldProcess = NO;
} else { // version 3.10.0
DLog (@"-- LINE version 2.10 up")
Ivar iv = object_getInstanceVariable(sent, "__isSet", NULL);
ptrdiff_t offset = ivar_getOffset(iv);
StructIsSet isSetStruct = *(StructIsSet *)((char *)sent + offset);
//DLog (@"1 toType: %d", isSetStruct.toType)
DLog (@"2 contentType %d", isSetStruct.contentType)
//DLog (@"3 createdTime: %d", isSetStruct.createdTime)
//DLog (@"4 hasContent: %d", isSetStruct.hasContent)
//DLog (@"5 deliveredTime: %d", isSetStruct.deliveredTime)
if (isSetStruct.contentType == NO) {
DLog (@"should process NO")
shouldProcess = NO;
}
}
// For hidden sticker, we should not process here
if (isHiddenMessage(chatObj)) {
shouldProcess = NO;
}
// CASE: content type is NOT set, update timestamp
//if (![lineMessage contentTypeIsSet] ){ // This property doesn't exist on LINE 3.10.0
if (!shouldProcess){
if (!isHiddenMessage(chatObj)) {
DLog (@"... Try to update timestamp [%@] for message id [%@]", [self id], [self timestamp])
[LINEUtils addTimestamp:[self timestamp] existingMessageID:[self id]];
} else {
DLog (@"This hook method don't process HIDDEN MESSAGE")
}
}
// CASE: content type is set
else {
DLog (@"content type %ld", (long)contentType)
if (contentType == kLINEContentTypeText || // TEXT message
contentType == kLINEContentTypeSticker) { // STICKER message
BOOL isDuplicatedTimestamp = [LINEUtils isDuplicatedMessageWithTimestamp:[self timestamp]];
BOOL isDuplicatedMessageObject = [LINEUtils isDuplicatedMessageObject:[self objectID]];
DLog (@">>> isDuplicatedTimestamp %d isDuplicatedMessageObject %d", isDuplicatedTimestamp, isDuplicatedMessageObject)
BOOL isNotDuplicated = !isDuplicatedTimestamp && !isDuplicatedMessageObject;
if (isNotDuplicated) {
DLog (@"process text...")
NSString *userId = nil;
NSString *userDisplayName = nil;
NSString *userStatusMessage = nil;
NSData *userPictureProfileData = nil;
//NSString *imServiceId = @"lin";
NSMutableArray *participants = [NSMutableArray array];
//TalkChatObject *chatObj = [self chat];
NSSet *members = [chatObj members];
FxEventDirection direction = kEventDirectionUnknown;
NSData *conversationProfilePicData = nil;
Class $TalkUserDefaultManager(objc_getClass("TalkUserDefaultManager"));
DLog (@"chatObj [%@]", chatObj)
DLog (@"members %@ %@", [[members anyObject] class], members)
// -- OUTGOING -------------------------------------
//if([msgObj isSendMessage] && [msgObj isMyMessage] // isMyMessage not exist in LINE 4.5
//[[msgObj messageType] isEqualToString:@"S"]
if ([msgObj isSendMessage]) { // sending message, my message
direction = kEventDirectionOut;
userId = [$TalkUserDefaultManager mid]; // sender id
userDisplayName = [$TalkUserDefaultManager name]; // sender name
userStatusMessage = [$TalkUserDefaultManager statusMessage];
userPictureProfileData = [LINEUtils getOwnerPictureProfile:userId];
DLog (@"sender %@", [msgObj sender])
DLog (@"finding members...")
for (TalkUserObject *obj in members) { // note that members does not include the target account (not include sender in this case)
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
FxRecipient *participant = nil;
participant = [LINEUtils createFxRecipientWithTalkUserObject:obj];
DLog (@">>>> member: %@", participant)
[participants addObject:participant];
[pool drain];
}
// -- conversation profile picture
if ([LINEUtils isIndividualConversationForChatType:[chatObj type]
participants:participants]) {
conversationProfilePicData = [(FxRecipient *)[participants objectAtIndex:0] mPicture];
}
DLog (@"mUserID (sender) -> %@", userId);
DLog (@"userDisplayName %@", userDisplayName)
DLog (@"userStatusMessage : %@", userStatusMessage)
DLog (@"mDirection -> %d", direction);
//DLog (@"mIMServiceID -> %@", imServiceId);
DLog (@"mMessage -> %@", message);
DLog (@"mParticipants -> %@", participants);
NSString *title = @"NONE";
if ([chatObj respondsToSelector:@selector(title)]) {
title = [chatObj title];
DLog (@"chat title %@ mid type %d", [chatObj title], [chatObj midType]) // ZTYPE in ZCHAT table 1 invite 2 group 0 individual
} else if ([chatObj respondsToSelector:@selector(titleWithMemberCount:)]) {
title =[chatObj titleWithMemberCount:NO];
DLog (@"chat title with member count YES %@ mid type %d", [chatObj titleWithMemberCount:YES], [chatObj midType]) // ZTYPE in ZCHAT table 1 invite 2 group 0 individual
DLog (@"chat title with member count NO %@ mid type %d", [chatObj titleWithMemberCount:NO], [chatObj midType]) // ZTYPE in ZCHAT table 1 invite 2 group 0 individual
}
DLog (@"chat mid %@", [chatObj mid]) // ZMID in ZCHAT table r c u
// ======== Sticker
if (contentType == kLINEContentTypeSticker) {
DLog (@"====== LINE STICKER =====")
Class $LineStickerManager(objc_getClass("LineStickerManager"));
LineStickerPackage *lineStickerPackage = [$LineStickerManager packageWithStickerID:[msgObj sticker]];
[LINEUtils sendStickerContentTypeEventUserID:userId
userDisplayName:userDisplayName
userStatusMessage:userStatusMessage
userProfilePictureData:userPictureProfileData
direction:direction
conversationID:[chatObj mid]
conversationName:title
conversationProfilePicture:conversationProfilePicData
participants:participants
stickerID:[msgObj sticker]
stickerPackageID:[lineStickerPackage IDString]
stickerPackageVersion:[lineStickerPackage downloadedVersion]
hidden:isHiddenMessage(chatObj)];
} else {
[LINEUtils sendAnyContentTypeEventUserID:userId
userDisplayName:userDisplayName
userStatusMessage:userStatusMessage
userProfilePictureData:userPictureProfileData
userLocation:nil
messageRepresentation:kIMMessageText
message:message
direction:direction
conversationID:[chatObj mid]
conversationName:title
conversationProfilePicture:conversationProfilePicData
participants:participants
attachments:[NSArray array]
shareLocation:nil];
}
} // if outgoing
} // if content type
}
} // else
} // if not system message
}
#pragma mark Utility
void printLog (TalkMessageObject *aMsgObj) {
DLog (@"=======================================")
if ([aMsgObj respondsToSelector:@selector(expirationStatus)])
DLog(@"expirationStatus %d", [aMsgObj expirationStatus])
if ([aMsgObj respondsToSelector:@selector(messageTypeEnum)])
DLog(@"messageTypeEnum %d", [aMsgObj messageTypeEnum])
if ([aMsgObj respondsToSelector:@selector(decryptedMessage)])
DLog(@"decryptedMessage %@", [aMsgObj decryptedMessage])
if ([aMsgObj respondsToSelector:@selector(contentMetadataDictionary)])
DLog(@"contentMetadataDictionary %@", [aMsgObj contentMetadataDictionary])
if ([aMsgObj respondsToSelector:@selector(decryptionStatus)])
DLog(@"decryptionStatus %d", [aMsgObj decryptionStatus])
if ([aMsgObj respondsToSelector:@selector(isEncrypted)])
DLog(@"encrypted %d", [aMsgObj isEncrypted])
if ([aMsgObj respondsToSelector:@selector(fetchMetadata)])
DLog(@"fetchMetadata %@", [aMsgObj fetchMetadata])
if ([aMsgObj respondsToSelector:@selector(contentMetadata)]) {
DLog(@"contentMetadata %@", [aMsgObj contentMetadata])
}
//
if ([aMsgObj respondsToSelector:@selector(contentMetadataModel)])
DLog(@"contentMetadataModel %@", [aMsgObj contentMetadataModel])
if ([aMsgObj respondsToSelector:@selector(expirationDate)])
DLog(@"expirationDate %@", [aMsgObj expirationDate])
if ([aMsgObj respondsToSelector:@selector(expireInterval)])
DLog(@"expirationDate %f", [aMsgObj expireInterval])
if ([aMsgObj respondsToSelector:@selector(hasTemporaryID)])
DLog(@"hasTemporaryID %d", [aMsgObj hasTemporaryID])
if ([aMsgObj respondsToSelector:@selector(timestampValue)])
DLog(@"timestampValue %lld", (long long)[(_TalkMessageObject *)aMsgObj timestampValue])
if ([aMsgObj respondsToSelector:@selector(sendStatusValue)])
DLog(@"sendStatusValue %d", [aMsgObj sendStatusValue])
if ([aMsgObj respondsToSelector:@selector(sendStatus)])
DLog(@"sendStatus %@", [aMsgObj sendStatus])
if ([aMsgObj respondsToSelector:@selector(messageType)])
DLog(@"messageType %@", [aMsgObj messageType])
if ([aMsgObj respondsToSelector:@selector(contentType)])
DLog(@"contentType %@", [aMsgObj contentType])
if ([aMsgObj respondsToSelector:@selector(objectID)])
DLog(@"objectID %@", [aMsgObj objectID])
DLog (@"TalkMessageObject %@", aMsgObj)
DLog (@"TalkMessageObject id %@", [aMsgObj id])
DLog (@"TalkMessageObject objectID: %@ %@", [aMsgObj objectID], [[aMsgObj objectID] class])
DLog (@"Message type %@", [aMsgObj messageType])
// -- location testing
//DLog (@"sharingLocationTemporary [%@]", [[self chat] sharingLocationTemporary])
DLog (@"lineLocation [%@]", [aMsgObj lineLocation]) //LineLocation
//DLog (@"lineLocation class [%@]", [[aMsgObj lineLocation] class])
DLog (@"longitude [%.10f]", [(LineLocation *)[aMsgObj lineLocation] longitude])
DLog (@"latitude [%.10f]", [(LineLocation *)[aMsgObj lineLocation] latitude])
//DLog (@"longitudeIsSet [%d]", [[aMsgObj lineLocation] longitudeIsSet]) // This doesn't exist in 3.10.0
//DLog (@"latitudeIsSet [%d]", [[aMsgObj lineLocation] latitudeIsSet]) // This doesn't exist in 3.10.0
DLog (@"phone [%@]", [[aMsgObj lineLocation] phone])
DLog (@"locationText [%@]", [aMsgObj locationText])
DLog (@"address [%@]", [aMsgObj address])
// -- image testing
DLog (@"imageData %lu", (unsigned long)[[aMsgObj imageData] length]);
DLog (@"imageName %@", [aMsgObj imageName]);
DLog (@"imageURL %@", [aMsgObj imageURL]);
DLog (@"imageFileURL %@", [aMsgObj imageFileURL]);
DLog (@"temporaryImageName %@", [aMsgObj temporaryImageName]);
if ([aMsgObj thumbnail])
DLog (@"thumbnail %lu", (unsigned long)[[aMsgObj thumbnail] length]);
//[[aMsgObj thumbnail] writeToFile:@"/tmp/image_thumbnail.jpg" atomically:YES];
//DLog (@"photoName: %@", [msgObj id])
DLog (@"timestamp: %@", [aMsgObj timestamp])
// -- audio testing
// DLog (@"audioFileURL %@", [aMsgObj audioFileURL]);
// DLog (@"audioFileName %@", [aMsgObj audioFileName]);
// -- attachment testing
// DLog (@"attachedFileURL %@", [aMsgObj attachedFileURL]);
// DLog (@"attachedFileDownloadURL %@", [aMsgObj attachedFileDownloadURL]);
// DLog (@"attachedFileNameToStore %@", [aMsgObj attachedFileNameToStore]);
// DLog (@"attachedFileName %@", [aMsgObj attachedFileName]);
// DLog (@"attachedFileNameToStore %@", [aMsgObj attachedFileNameToStore]);
// *************** Sticker ****************
Class $LineStickerManager(objc_getClass("LineStickerManager"));
// DLog (@"================== STICKER ==================")
DLog (@"sticker [%d]", [aMsgObj sticker])
DLog (@"sticker package %@", [$LineStickerManager packageWithStickerID:[aMsgObj sticker]]) // class LineStickerPackage
// LineStickerPackage *lineStickerPackage = [$LineStickerManager packageWithStickerID:[aMsgObj sticker]];
//[lineStickerPackage downloadImageForSticker:[aMsgObj sticker] type:0 version:3 completionBlock:nil];
// DLog (@"package id %d", [lineStickerPackage ID])
// DLog (@"package IDString %@", [lineStickerPackage IDString])
// DLog (@"package IDNumber %@", [lineStickerPackage IDNumber])
// DLog (@"package currentVersion %u", [lineStickerPackage currentVersion])
// DLog (@"package downloadedVersion %u", [lineStickerPackage downloadedVersion])
// DLog (@"package downloaded %d", [lineStickerPackage isDownloaded])
// DLog (@"package downloading %d", [lineStickerPackage downloading])
// [lineStickerPackage ID]; // To remove the warning after disable log
// DLog (@"================== END STICKER ==================")
// DLog (@"contentType [%@]", [aMsgObj contentType])
// DLog (@"sharingLocationTemporary [%@]", [self sharingLocationTemporary])
// DLog (@"contentMetadata [%@]", [aMsgObj contentMetadata])
// DLog (@"================== CONTACT ==================")
// [(NSData *) [aMsgObj contentMetadata] writeToFile:@"/tmp/metadata.vcf" atomically:YES];
// NSString* myString;
// myString = [[NSString alloc] initWithData:[aMsgObj contentMetadata] encoding:NSUTF8StringEncoding];
// DLog (@"myString [%@]", myString)
// DLog (@"attachedFileModel [%@]", [aMsgObj attachedFileModel])
// DLog (@"contactModel [%@]", (ContactModel *) [aMsgObj contactModel])
// ContactModel *contactModel = (ContactModel *) [aMsgObj contactModel];
// DLog (@"[contactModel displayName] [%@]", [contactModel displayName])
//
// DLog (@"[contactModel displayName] [%@]", [contactModel mid])
// DLog (@"[contactModel userObjectWithMid] [%@]", [contactModel userObjectWithMid:[contactModel mid]])
// TalkUserObject *user = [contactModel userObjectWithMid:[contactModel mid]];
// DLog (@"user object id %@", [user objectID])
// DLog (@"[user customName] [%@]", [user customName])
// DLog (@"[user name] [%@]", [user name])
// DLog (@"[user displayUserName] [%@]", [user displayUserName])
// DLog (@"[user addressbookName] [%@]", [user addressbookName])
// DLog (@"[user mid] [%@]", [user mid])
// DLog (@"[user memberId] [%@]", [user memberId])
// DLog (@"================== END CONTACT ==================")
DLog (@"=======================================")
}
| {
"pile_set_name": "Github"
} |
/*************************************************************************
*
* This file is part of the SAMRAI distribution. For full copyright
* information, see COPYRIGHT and LICENSE.
*
* Copyright: (c) 1997-2020 Lawrence Livermore National Security, LLC
* Description: Conservative linear refine operator for cell-centered
* double data on a Cartesian mesh.
*
************************************************************************/
#include "SAMRAI/geom/CartesianCellDoubleConservativeLinearRefine.h"
#include <cfloat>
#include <cmath>
#include <memory>
#include "SAMRAI/geom/CartesianPatchGeometry.h"
#include "SAMRAI/hier/Index.h"
#include "SAMRAI/hier/ForAll.h"
#include "SAMRAI/pdat/CellData.h"
#include "SAMRAI/pdat/CellVariable.h"
#include "SAMRAI/tbox/Utilities.h"
#include "SAMRAI/tbox/AllocatorDatabase.h"
#define SAMRAI_GEOM_MIN(a, b) (((b) < (a)) ? (b) : (a))
/*
*************************************************************************
*
* External declarations for FORTRAN routines.
*
*************************************************************************
*/
extern "C" {
#ifdef __INTEL_COMPILER
#pragma warning(disable : 1419)
#endif
// in cartrefine1d.f:
void SAMRAI_F77_FUNC(cartclinrefcelldoub1d, CARTCLINREFCELLDOUB1D)(const int &,
const int &,
const int &, const int &,
const int &, const int &,
const int &, const int &,
const int *, const double *, const double *,
const double *, double *,
double *, double *);
// in cartrefine2d.f:
void SAMRAI_F77_FUNC(cartclinrefcelldoub2d, CARTCLINREFCELLDOUB2D)(const int &,
const int &, const int &, const int &,
const int &, const int &, const int &, const int &,
const int &, const int &, const int &, const int &,
const int &, const int &, const int &, const int &,
const int *, const double *, const double *,
const double *, double *,
double *, double *, double *, double *);
// in cartrefine3d.f:
void SAMRAI_F77_FUNC(cartclinrefcelldoub3d, CARTCLINREFCELLDOUB3D)(const int &,
const int &, const int &,
const int &, const int &, const int &,
const int &, const int &, const int &,
const int &, const int &, const int &,
const int &, const int &, const int &,
const int &, const int &, const int &,
const int &, const int &, const int &,
const int &, const int &, const int &,
const int *, const double *, const double *,
const double *, double *,
double *, double *, double *,
double *, double *, double *);
}
#if !defined(__BGL_FAMILY__) && defined(__xlC__)
/*
* Suppress XLC warnings
*/
#pragma report(disable, CPPC5334)
#pragma report(disable, CPPC5328)
#endif
namespace SAMRAI
{
namespace geom
{
CartesianCellDoubleConservativeLinearRefine::
CartesianCellDoubleConservativeLinearRefine() : hier::RefineOperator("CONSERVATIVE_LINEAR_REFINE")
{
}
CartesianCellDoubleConservativeLinearRefine::~CartesianCellDoubleConservativeLinearRefine()
{
}
int CartesianCellDoubleConservativeLinearRefine::getOperatorPriority() const
{
return 0;
}
hier::IntVector
CartesianCellDoubleConservativeLinearRefine::getStencilWidth(const tbox::Dimension &dim) const
{
return hier::IntVector::getOne(dim);
}
void CartesianCellDoubleConservativeLinearRefine::refine(
hier::Patch &fine,
const hier::Patch &coarse,
const int dst_component,
const int src_component,
const hier::BoxOverlap &fine_overlap,
const hier::IntVector &ratio) const
{
const pdat::CellOverlap *t_overlap =
CPP_CAST<const pdat::CellOverlap *>(&fine_overlap);
TBOX_ASSERT(t_overlap != 0);
const hier::BoxContainer &boxes = t_overlap->getDestinationBoxContainer();
for (hier::BoxContainer::const_iterator b = boxes.begin();
b != boxes.end(); ++b) {
refine(fine,
coarse,
dst_component,
src_component,
*b,
ratio);
}
}
void CartesianCellDoubleConservativeLinearRefine::refine(
hier::Patch &fine,
const hier::Patch &coarse,
const int dst_component,
const int src_component,
const hier::Box &fine_box,
const hier::IntVector &ratio) const
{
RANGE_PUSH("ConservativeLinearRefine::refine", 3);
const tbox::Dimension &dim(fine.getDim());
TBOX_ASSERT_DIM_OBJDIM_EQUALITY3(dim, coarse, fine_box, ratio);
std::shared_ptr<pdat::CellData<double> > cdata(
SAMRAI_SHARED_PTR_CAST<pdat::CellData<double>, hier::PatchData>(
coarse.getPatchData(src_component)));
std::shared_ptr<pdat::CellData<double> > fdata(
SAMRAI_SHARED_PTR_CAST<pdat::CellData<double>, hier::PatchData>(
fine.getPatchData(dst_component)));
TBOX_ASSERT(cdata);
TBOX_ASSERT(fdata);
TBOX_ASSERT(cdata->getDepth() == fdata->getDepth());
const hier::Box cgbox(cdata->getGhostBox());
const hier::Index &cilo = cgbox.lower();
const hier::Index &cihi = cgbox.upper();
const hier::Index &filo = fdata->getGhostBox().lower();
const hier::Index &fihi = fdata->getGhostBox().upper();
const std::shared_ptr<CartesianPatchGeometry> cgeom(
SAMRAI_SHARED_PTR_CAST<CartesianPatchGeometry, hier::PatchGeometry>(
coarse.getPatchGeometry()));
const std::shared_ptr<CartesianPatchGeometry> fgeom(
SAMRAI_SHARED_PTR_CAST<CartesianPatchGeometry, hier::PatchGeometry>(
fine.getPatchGeometry()));
TBOX_ASSERT(cgeom);
TBOX_ASSERT(fgeom);
const hier::Box coarse_box = hier::Box::coarsen(fine_box, ratio);
const hier::Index &ifirstc = coarse_box.lower();
const hier::Index &ilastc = coarse_box.upper();
const hier::Index &ifirstf = fine_box.lower();
const hier::Index &ilastf = fine_box.upper();
const hier::IntVector tmp_ghosts(dim, 0);
#ifdef HAVE_UMPIRE
tbox::AllocatorDatabase *alloc_db = tbox::AllocatorDatabase::getDatabase();
pdat::ArrayData<double> slope(cgbox, dim.getValue(), alloc_db->getDevicePool());
#else
pdat::ArrayData<double> slope(cgbox, dim.getValue());
#endif
for (int d = 0; d < fdata->getDepth(); ++d) {
if ((dim == tbox::Dimension(1))) { // need to generate a test for 1D variant
std::vector<double> diff0_f(cgbox.numberCells(0) + 1);
SAMRAI_F77_FUNC(cartclinrefcelldoub1d, CARTCLINREFCELLDOUB1D)
(ifirstc(0),
ilastc(0),
ifirstf(0), ilastf(0),
cilo(0), cihi(0),
filo(0), fihi(0),
&ratio[0],
cgeom->getDx(),
fgeom->getDx(),
cdata->getPointer(d),
fdata->getPointer(d),
&diff0_f[0], slope.getPointer());
} else if ((dim == tbox::Dimension(2))) {
#if defined(HAVE_RAJA)
SAMRAI::hier::Box diff_box = coarse_box;
diff_box.growUpper(0, 1);
diff_box.growUpper(1, 1);
pdat::ArrayData<double> diff(diff_box, dim.getValue(), alloc_db->getDevicePool());
auto fine_array = fdata->getView<2>(d);
auto coarse_array = cdata->getView<2>(d);
auto diff0 = diff.getView<2>(0);
auto diff1 = diff.getView<2>(1);
auto slope0 = slope.getView<2>(0);
auto slope1 = slope.getView<2>(1);
const double *fdx = fgeom->getDx();
const double *cdx = cgeom->getDx();
const double fdx0 = fdx[0];
const double fdx1 = fdx[1];
const double cdx0 = cdx[0];
const double cdx1 = cdx[1];
const int r0 = ratio[0];
const int r1 = ratio[1];
hier::parallel_for_all(diff_box, [=] SAMRAI_HOST_DEVICE(int j /*fast*/, int k /*slow */) {
diff0(j, k) = coarse_array(j, k) - coarse_array(j - 1, k);
diff1(j, k) = coarse_array(j, k) - coarse_array(j, k - 1);
});
hier::parallel_for_all(coarse_box, [=] SAMRAI_HOST_DEVICE(int j, int k) {
const double coef2j = 0.5 * (diff0(j + 1, k) + diff0(j, k));
const double boundj = 2.0 * SAMRAI_GEOM_MIN(fabs(diff0(j + 1, k)), fabs(diff0(j, k)));
if (diff0(j, k) * diff0(j + 1, k) > 0.0 && cdx0 != 0) {
slope0(j, k) = copysign(SAMRAI_GEOM_MIN(fabs(coef2j), boundj), coef2j) / cdx0;
} else {
slope0(j, k) = 0.0;
}
const double coef2k = 0.5 * (diff1(j, k + 1) + diff1(j, k));
const double boundk = 2.0 * SAMRAI_GEOM_MIN(fabs(diff1(j, k + 1)), fabs(diff1(j, k)));
if (diff1(j, k) * diff1(j, k + 1) > 0.0 && cdx1 != 0) {
slope1(j, k) = copysign(SAMRAI_GEOM_MIN(fabs(coef2k), boundk), coef2k) / cdx1;
} else {
slope1(j, k) = 0.0;
}
});
hier::parallel_for_all(fine_box, [=] SAMRAI_HOST_DEVICE(int j, int k) {
const int ic1 = (k < 0) ? (k + 1) / r1 - 1 : k / r1;
const int ic0 = (j < 0) ? (j + 1) / r0 - 1 : j / r0;
const int ir0 = j - ic0 * r0;
const int ir1 = k - ic1 * r1;
const double deltax1 = (static_cast<double>(ir1) + 0.5) * fdx1 - cdx1 * 0.5;
const double deltax0 = (static_cast<double>(ir0) + 0.5) * fdx0 - cdx0 * 0.5;
fine_array(j, k) = coarse_array(ic0, ic1) + slope0(ic0, ic1) * deltax0 + slope1(ic0, ic1) * deltax1;
});
#else // Fortran Dimension 2
std::vector<double> diff1_f(cgbox.numberCells(1) + 1);
std::vector<double> diff0_f(cgbox.numberCells(0) + 1);
SAMRAI_F77_FUNC(cartclinrefcelldoub2d, CARTCLINREFCELLDOUB2D)
(ifirstc(0),
ifirstc(1), ilastc(0), ilastc(1),
ifirstf(0), ifirstf(1), ilastf(0), ilastf(1),
cilo(0), cilo(1), cihi(0), cihi(1),
filo(0), filo(1), fihi(0), fihi(1),
&ratio[0],
cgeom->getDx(),
fgeom->getDx(),
cdata->getPointer(d),
fdata->getPointer(d),
&diff0_f[0], slope.getPointer(0),
&diff1_f[0], slope.getPointer(1));
exit(-1);
#endif // test for RAJA
} else if ((dim == tbox::Dimension(3))) {
#if defined(HAVE_RAJA)
SAMRAI::hier::Box diff_box = coarse_box;
diff_box.growUpper(0, 1);
diff_box.growUpper(1, 1);
diff_box.growUpper(2, 1);
pdat::ArrayData<double> diff(diff_box, dim.getValue(), alloc_db->getDevicePool());
auto fine_array = fdata->getView<3>(d);
auto coarse_array = cdata->getView<3>(d);
auto diff0 = diff.getView<3>(0);
auto diff1 = diff.getView<3>(1);
auto diff2 = diff.getView<3>(2);
auto slope0 = slope.getView<3>(0);
auto slope1 = slope.getView<3>(1);
auto slope2 = slope.getView<3>(2);
const double *fdx = fgeom->getDx();
const double *cdx = cgeom->getDx();
const double fdx0 = fdx[0];
const double fdx1 = fdx[1];
const double fdx2 = fdx[2];
const double cdx0 = cdx[0];
const double cdx1 = cdx[1];
const double cdx2 = cdx[2];
const int r0 = ratio[0];
const int r1 = ratio[1];
const int r2 = ratio[2];
hier::parallel_for_all(diff_box, [=] SAMRAI_HOST_DEVICE(int i /*fastest*/, int j, int k) {
diff0(i, j, k) = coarse_array(i, j, k) - coarse_array(i - 1, j, k);
diff1(i, j, k) = coarse_array(i, j, k) - coarse_array(i, j - 1, k);
diff2(i, j, k) = coarse_array(i, j, k) - coarse_array(i, j, k - 1);
});
hier::parallel_for_all(coarse_box, [=] SAMRAI_HOST_DEVICE(int i, int j, int k) {
const double coef2i = 0.5 * (diff0(i + 1, j, k) + diff0(i, j, k));
const double boundi = 2.0 * SAMRAI_GEOM_MIN(fabs(diff0(i + 1, j, k)), fabs(diff0(i, j, k)));
if (diff0(i, j, k) * diff0(i + 1, j, k) > 0.0 && cdx0 != 0) {
slope0(i, j, k) = copysign(SAMRAI_GEOM_MIN(fabs(coef2i), boundi), coef2i) / cdx0;
} else {
slope0(i, j, k) = 0.0;
}
const double coef2j = 0.5 * (diff1(i, j + 1, k) + diff1(i, j, k));
const double boundj = 2.0 * SAMRAI_GEOM_MIN(fabs(diff1(i, j + 1, k)), fabs(diff1(i, j, k)));
if (diff1(i, j, k) * diff1(i, j + 1, k) > 0.0 && cdx1 != 0) {
slope1(i, j, k) = copysign(SAMRAI_GEOM_MIN(fabs(coef2j), boundj), coef2j) / cdx1;
} else {
slope1(i, j, k) = 0.0;
}
const double coef2k = 0.5 * (diff2(i, j, k + 1) + diff2(i, j, k));
const double boundk = 2.0 * SAMRAI_GEOM_MIN(fabs(diff2(i, j, k + 1)), fabs(diff2(i, j, k)));
if (diff2(i, j, k) * diff2(i, j, k + 1) > 0.0 && cdx2 != 0) {
slope2(i, j, k) = copysign(SAMRAI_GEOM_MIN(fabs(coef2k), boundk), coef2k) / cdx2;
} else {
slope2(i, j, k) = 0.0;
}
});
hier::parallel_for_all(fine_box, [=] SAMRAI_HOST_DEVICE(int i, int j, int k) {
const int ic2 = (k < 0) ? (k + 1) / r2 - 1 : k / r2;
const int ic1 = (j < 0) ? (j + 1) / r1 - 1 : j / r1;
const int ic0 = (i < 0) ? (i + 1) / r0 - 1 : i / r0;
const int ir0 = i - ic0 * r0;
const int ir1 = j - ic1 * r1;
const int ir2 = k - ic2 * r2;
const double deltax2 = (static_cast<double>(ir2) + 0.5) * fdx2 - cdx2 * 0.5;
const double deltax1 = (static_cast<double>(ir1) + 0.5) * fdx1 - cdx1 * 0.5;
const double deltax0 = (static_cast<double>(ir0) + 0.5) * fdx0 - cdx0 * 0.5;
fine_array(i, j, k) = coarse_array(ic0, ic1, ic2) + slope0(ic0, ic1, ic2) * deltax0 + slope1(ic0, ic1, ic2) * deltax1 + slope2(ic0, ic1, ic2) * deltax2;
});
#else
std::vector<double> diff0_f(cgbox.numberCells(0) + 1);
std::vector<double> diff1_f(cgbox.numberCells(1) + 1);
std::vector<double> diff2_f(cgbox.numberCells(2) + 1);
SAMRAI_F77_FUNC(cartclinrefcelldoub3d, CARTCLINREFCELLDOUB3D)
(ifirstc(0),
ifirstc(1), ifirstc(2),
ilastc(0), ilastc(1), ilastc(2),
ifirstf(0), ifirstf(1), ifirstf(2),
ilastf(0), ilastf(1), ilastf(2),
cilo(0), cilo(1), cilo(2),
cihi(0), cihi(1), cihi(2),
filo(0), filo(1), filo(2),
fihi(0), fihi(1), fihi(2),
&ratio[0],
cgeom->getDx(),
fgeom->getDx(),
cdata->getPointer(d),
fdata->getPointer(d),
&diff0_f[0], slope.getPointer(0),
&diff1_f[0], slope.getPointer(1),
&diff2_f[0], slope.getPointer(2));
#endif
} else {
TBOX_ERROR("CartesianCellDoubleConservativeLinearRefine error...\n"
<< "dim > 3 not supported." << std::endl);
}
} // for (int d = 0; d < fdata->getDepth(); ++d)
RANGE_POP;
} // end CartesianCellDoubleConservativeLinearRefine::refine(
} // end namespace geom
} // end namespace SAMRAI
#if !defined(__BGL_FAMILY__) && defined(__xlC__)
/*
* Suppress XLC warnings
*/
#pragma report(enable, CPPC5334)
#pragma report(enable, CPPC5328)
#endif
| {
"pile_set_name": "Github"
} |
a.navbar-brand {
white-space: normal;
text-align: center;
word-break: break-all;
}
html {
font-size: 14px;
}
@media (min-width: 768px) {
html {
font-size: 16px;
}
}
.box-shadow {
box-shadow: 0 .25rem .75rem rgba(0, 0, 0, .05);
}
| {
"pile_set_name": "Github"
} |
/*
* extsprintf.js: extended POSIX-style sprintf
*/
var mod_assert = require('assert');
var mod_util = require('util');
/*
* Public interface
*/
exports.sprintf = jsSprintf;
exports.printf = jsPrintf;
exports.fprintf = jsFprintf;
/*
* Stripped down version of s[n]printf(3c). We make a best effort to throw an
* exception when given a format string we don't understand, rather than
* ignoring it, so that we won't break existing programs if/when we go implement
* the rest of this.
*
* This implementation currently supports specifying
* - field alignment ('-' flag),
* - zero-pad ('0' flag)
* - always show numeric sign ('+' flag),
* - field width
* - conversions for strings, decimal integers, and floats (numbers).
* - argument size specifiers. These are all accepted but ignored, since
* Javascript has no notion of the physical size of an argument.
*
* Everything else is currently unsupported, most notably precision, unsigned
* numbers, non-decimal numbers, and characters.
*/
function jsSprintf(fmt)
{
var regex = [
'([^%]*)', /* normal text */
'%', /* start of format */
'([\'\\-+ #0]*?)', /* flags (optional) */
'([1-9]\\d*)?', /* width (optional) */
'(\\.([1-9]\\d*))?', /* precision (optional) */
'[lhjztL]*?', /* length mods (ignored) */
'([diouxXfFeEgGaAcCsSp%jr])' /* conversion */
].join('');
var re = new RegExp(regex);
var args = Array.prototype.slice.call(arguments, 1);
var flags, width, precision, conversion;
var left, pad, sign, arg, match;
var ret = '';
var argn = 1;
mod_assert.equal('string', typeof (fmt));
while ((match = re.exec(fmt)) !== null) {
ret += match[1];
fmt = fmt.substring(match[0].length);
flags = match[2] || '';
width = match[3] || 0;
precision = match[4] || '';
conversion = match[6];
left = false;
sign = false;
pad = ' ';
if (conversion == '%') {
ret += '%';
continue;
}
if (args.length === 0)
throw (new Error('too few args to sprintf'));
arg = args.shift();
argn++;
if (flags.match(/[\' #]/))
throw (new Error(
'unsupported flags: ' + flags));
if (precision.length > 0)
throw (new Error(
'non-zero precision not supported'));
if (flags.match(/-/))
left = true;
if (flags.match(/0/))
pad = '0';
if (flags.match(/\+/))
sign = true;
switch (conversion) {
case 's':
if (arg === undefined || arg === null)
throw (new Error('argument ' + argn +
': attempted to print undefined or null ' +
'as a string'));
ret += doPad(pad, width, left, arg.toString());
break;
case 'd':
arg = Math.floor(arg);
/*jsl:fallthru*/
case 'f':
sign = sign && arg > 0 ? '+' : '';
ret += sign + doPad(pad, width, left,
arg.toString());
break;
case 'x':
ret += doPad(pad, width, left, arg.toString(16));
break;
case 'j': /* non-standard */
if (width === 0)
width = 10;
ret += mod_util.inspect(arg, false, width);
break;
case 'r': /* non-standard */
ret += dumpException(arg);
break;
default:
throw (new Error('unsupported conversion: ' +
conversion));
}
}
ret += fmt;
return (ret);
}
function jsPrintf() {
var args = Array.prototype.slice.call(arguments);
args.unshift(process.stdout);
jsFprintf.apply(null, args);
}
function jsFprintf(stream) {
var args = Array.prototype.slice.call(arguments, 1);
return (stream.write(jsSprintf.apply(this, args)));
}
function doPad(chr, width, left, str)
{
var ret = str;
while (ret.length < width) {
if (left)
ret += chr;
else
ret = chr + ret;
}
return (ret);
}
/*
* This function dumps long stack traces for exceptions having a cause() method.
* See node-verror for an example.
*/
function dumpException(ex)
{
var ret;
if (!(ex instanceof Error))
throw (new Error(jsSprintf('invalid type for %%r: %j', ex)));
/* Note that V8 prepends "ex.stack" with ex.toString(). */
ret = 'EXCEPTION: ' + ex.constructor.name + ': ' + ex.stack;
if (ex.cause && typeof (ex.cause) === 'function') {
var cex = ex.cause();
if (cex) {
ret += '\nCaused by: ' + dumpException(cex);
}
}
return (ret);
}
| {
"pile_set_name": "Github"
} |
sysPath = require 'path'
module.exports = class ParsedError
constructor: (@error) ->
do @_parse
_parse: ->
@_trace = []
@_kind = 'Error'
@_wrapper = ''
@_wrapper = String @error.wrapper if @error.wrapper?
unless typeof @error is 'object'
@_message = String @error
else
@_stack = @error.stack
if @error.kind?
@_kind = String @error.kind
else if typeof @_stack is 'string'
if m = @_stack.match /^([a-zA-Z0-9\_\$]+):\ /
@_kind = m[1]
@_message = @error.message? and String(@error.message) or ''
if typeof @_stack is 'string'
@_parseStack()
return
_parseStack: ->
messageLines = []
reachedTrace = no
for line in @_stack.split '\n'
continue if line.trim() is ''
if reachedTrace
@_trace.push @_parseTraceItem line
else
if line.match /^\s*at\s.+/
reachedTrace = yes
@_trace.push @_parseTraceItem line
else if !@_message.split '\n'.indexOf line
messageLines.push line
message = messageLines.join '\n'
if message.substr(0, @_kind.length) is @_kind
message =
message
.substr(@_kind.length, message.length)
.replace(/^\:\s+/, '')
if message.length
@_message = if @_message.length
then [
@_message
message
].join '\n'
else
message
return
_parseTraceItem: (text) ->
text = text.trim()
return if text is ''
return text unless text.match /^at\ /
# remove the 'at ' part
text = text.replace /^at /, ''
return if text in ['Error (<anonymous>)', 'Error (<anonymous>:null:null)']
original = text
# the part that comes before the address
what = null
# address, including path to module and line/col
addr = null
# path to module
path = null
# module dir
dir = null
# module basename
file = null
# line number (if using a compiler, the line number of the module
# in that compiler will be used)
line = null
# column, same as above
col = null
# if using a compiler, this will translate to the line number of
# the js equivalent of that module
jsLine = null
# like above
jsCol = null
# path that doesn't include `node_module` dirs
shortenedPath = null
# like above
shortenedAddr = null
packageName = '[current]'
# pick out the address
if m = text.match /\(([^\)]+)\)$/
addr = m[1].trim()
if addr?
what = text.substr 0, text.length - addr.length - 2
what = what.trim()
# might not have a 'what' clause
unless addr?
addr = text.trim()
addr = @_fixPath addr
remaining = addr
# remove the <js> clause if the file is a compiled one
if m = remaining.match /\,\ <js>:(\d+):(\d+)$/
jsLine = m[1]
jsCol = m[2]
remaining = remaining.substr 0, remaining.length - m[0].length
# the line/col part
if m = remaining.match /:(\d+):(\d+)$/
line = m[1]
col = m[2]
remaining = remaining.substr 0, remaining.length - m[0].length
path = remaining
# file and dir
if path?
file = sysPath.basename path
dir = sysPath.dirname path
if dir is '.' then dir = ''
path = @_fixPath path
file = @_fixPath file
dir = @_fixPath dir
if dir?
d = dir.replace /[\\]{1,2}/g, '/'
if m = d.match ///
node_modules/([^/]+)(?!.*node_modules.*)
///
packageName = m[1]
unless jsLine?
jsLine = line
jsCol = col
if path?
r = @_rectifyPath path
shortenedPath = r.path
shortenedAddr = shortenedPath + addr.substr(path.length, addr.length)
packages = r.packages
original: original
what: what
addr: addr
path: path
dir: dir
file: file
line: parseInt line
col: parseInt col
jsLine: parseInt jsLine
jsCol: parseInt jsCol
packageName: packageName
shortenedPath: shortenedPath
shortenedAddr: shortenedAddr
packages: packages || []
_getMessage: -> @_message
_getKind: -> @_kind
_getWrapper: -> @_wrapper
_getStack: -> @_stack
_getArguments: -> @error.arguments
_getType: -> @error.type
_getTrace: -> @_trace
_fixPath: (path) -> path.replace(///[\\]{1,2}///g, '/')
_rectifyPath: (path, nameForCurrentPackage) ->
path = String path
remaining = path
return path: path, packages: [] unless m = path.match /^(.+?)\/node_modules\/(.+)$/
parts = []
packages = []
if typeof nameForCurrentPackage is 'string'
parts.push "[#{nameForCurrentPackage}]"
packages.push "[#{nameForCurrentPackage}]"
else
parts.push "[#{m[1].match(/([^\/]+)$/)[1]}]"
packages.push m[1].match(/([^\/]+)$/)[1]
rest = m[2]
while m = rest.match /([^\/]+)\/node_modules\/(.+)$/
parts.push "[#{m[1]}]"
packages.push m[1]
rest = m[2]
if m = rest.match /([^\/]+)\/(.+)$/
parts.push "[#{m[1]}]"
packages.push m[1]
rest = m[2]
parts.push rest
path: parts.join "/"
packages: packages
for prop in ['message', 'kind', 'arguments', 'type', 'stack', 'trace', 'wrapper'] then do ->
methodName = '_get' + prop[0].toUpperCase() + prop.substr(1, prop.length)
Object.defineProperty ParsedError::, prop,
get: -> this[methodName]()
| {
"pile_set_name": "Github"
} |
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
// @generated
// Use tools/generate_sequence_zip.py to regenerate
module Sequence;
class Zip2Sequence<T0, T1>(
s0: Sequence<T0>,
s1: Sequence<T1>,
) extends Sequence<(T0, T1)> {
fun values(): mutable Iterator<(T0, T1)> {
it0 = this.s0.values();
it1 = this.s1.values();
loop {
(it0.next(), it1.next()) match {
| (Some(val0), Some(val1)) -> yield (val0, val1)
| _ -> break void
}
}
}
fun size(): Int {
Vector[this.s0.size(), this.s1.size()].min().fromSome()
}
}
class Zip3Sequence<T0, T1, T2>(
s0: Sequence<T0>,
s1: Sequence<T1>,
s2: Sequence<T2>,
) extends Sequence<(T0, T1, T2)> {
fun values(): mutable Iterator<(T0, T1, T2)> {
it0 = this.s0.values();
it1 = this.s1.values();
it2 = this.s2.values();
loop {
(it0.next(), it1.next(), it2.next()) match {
| (Some(val0), Some(val1), Some(val2)) -> yield (val0, val1, val2)
| _ -> break void
}
}
}
fun size(): Int {
Vector[this.s0.size(), this.s1.size(), this.s2.size()].min().fromSome()
}
}
class Zip4Sequence<T0, T1, T2, T3>(
s0: Sequence<T0>,
s1: Sequence<T1>,
s2: Sequence<T2>,
s3: Sequence<T3>,
) extends Sequence<(T0, T1, T2, T3)> {
fun values(): mutable Iterator<(T0, T1, T2, T3)> {
it0 = this.s0.values();
it1 = this.s1.values();
it2 = this.s2.values();
it3 = this.s3.values();
loop {
(it0.next(), it1.next(), it2.next(), it3.next()) match {
| (Some(val0), Some(val1), Some(val2), Some(val3)) ->
yield (val0, val1, val2, val3)
| _ -> break void
}
}
}
fun size(): Int {
Vector[
this.s0.size(),
this.s1.size(),
this.s2.size(),
this.s3.size(),
].min().fromSome()
}
}
class Zip5Sequence<T0, T1, T2, T3, T4>(
s0: Sequence<T0>,
s1: Sequence<T1>,
s2: Sequence<T2>,
s3: Sequence<T3>,
s4: Sequence<T4>,
) extends Sequence<(T0, T1, T2, T3, T4)> {
fun values(): mutable Iterator<(T0, T1, T2, T3, T4)> {
it0 = this.s0.values();
it1 = this.s1.values();
it2 = this.s2.values();
it3 = this.s3.values();
it4 = this.s4.values();
loop {
(it0.next(), it1.next(), it2.next(), it3.next(), it4.next()) match {
| (Some(val0), Some(val1), Some(val2), Some(val3), Some(val4)) ->
yield (val0, val1, val2, val3, val4)
| _ -> break void
}
}
}
fun size(): Int {
Vector[
this.s0.size(),
this.s1.size(),
this.s2.size(),
this.s3.size(),
this.s4.size(),
].min().fromSome()
}
}
class Zip6Sequence<T0, T1, T2, T3, T4, T5>(
s0: Sequence<T0>,
s1: Sequence<T1>,
s2: Sequence<T2>,
s3: Sequence<T3>,
s4: Sequence<T4>,
s5: Sequence<T5>,
) extends Sequence<(T0, T1, T2, T3, T4, T5)> {
fun values(): mutable Iterator<(T0, T1, T2, T3, T4, T5)> {
it0 = this.s0.values();
it1 = this.s1.values();
it2 = this.s2.values();
it3 = this.s3.values();
it4 = this.s4.values();
it5 = this.s5.values();
loop {
(
it0.next(),
it1.next(),
it2.next(),
it3.next(),
it4.next(),
it5.next(),
) match {
| (
Some(val0),
Some(val1),
Some(val2),
Some(val3),
Some(val4),
Some(val5),
) ->
yield (val0, val1, val2, val3, val4, val5)
| _ -> break void
}
}
}
fun size(): Int {
Vector[
this.s0.size(),
this.s1.size(),
this.s2.size(),
this.s3.size(),
this.s4.size(),
this.s5.size(),
].min().fromSome()
}
}
class Zip7Sequence<T0, T1, T2, T3, T4, T5, T6>(
s0: Sequence<T0>,
s1: Sequence<T1>,
s2: Sequence<T2>,
s3: Sequence<T3>,
s4: Sequence<T4>,
s5: Sequence<T5>,
s6: Sequence<T6>,
) extends Sequence<(T0, T1, T2, T3, T4, T5, T6)> {
fun values(): mutable Iterator<(T0, T1, T2, T3, T4, T5, T6)> {
it0 = this.s0.values();
it1 = this.s1.values();
it2 = this.s2.values();
it3 = this.s3.values();
it4 = this.s4.values();
it5 = this.s5.values();
it6 = this.s6.values();
loop {
(
it0.next(),
it1.next(),
it2.next(),
it3.next(),
it4.next(),
it5.next(),
it6.next(),
) match {
| (
Some(val0),
Some(val1),
Some(val2),
Some(val3),
Some(val4),
Some(val5),
Some(val6),
) ->
yield (val0, val1, val2, val3, val4, val5, val6)
| _ -> break void
}
}
}
fun size(): Int {
Vector[
this.s0.size(),
this.s1.size(),
this.s2.size(),
this.s3.size(),
this.s4.size(),
this.s5.size(),
this.s6.size(),
].min().fromSome()
}
}
class Zip8Sequence<T0, T1, T2, T3, T4, T5, T6, T7>(
s0: Sequence<T0>,
s1: Sequence<T1>,
s2: Sequence<T2>,
s3: Sequence<T3>,
s4: Sequence<T4>,
s5: Sequence<T5>,
s6: Sequence<T6>,
s7: Sequence<T7>,
) extends Sequence<(T0, T1, T2, T3, T4, T5, T6, T7)> {
fun values(): mutable Iterator<(T0, T1, T2, T3, T4, T5, T6, T7)> {
it0 = this.s0.values();
it1 = this.s1.values();
it2 = this.s2.values();
it3 = this.s3.values();
it4 = this.s4.values();
it5 = this.s5.values();
it6 = this.s6.values();
it7 = this.s7.values();
loop {
(
it0.next(),
it1.next(),
it2.next(),
it3.next(),
it4.next(),
it5.next(),
it6.next(),
it7.next(),
) match {
| (
Some(val0),
Some(val1),
Some(val2),
Some(val3),
Some(val4),
Some(val5),
Some(val6),
Some(val7),
) ->
yield (val0, val1, val2, val3, val4, val5, val6, val7)
| _ -> break void
}
}
}
fun size(): Int {
Vector[
this.s0.size(),
this.s1.size(),
this.s2.size(),
this.s3.size(),
this.s4.size(),
this.s5.size(),
this.s6.size(),
this.s7.size(),
].min().fromSome()
}
}
class Zip9Sequence<T0, T1, T2, T3, T4, T5, T6, T7, T8>(
s0: Sequence<T0>,
s1: Sequence<T1>,
s2: Sequence<T2>,
s3: Sequence<T3>,
s4: Sequence<T4>,
s5: Sequence<T5>,
s6: Sequence<T6>,
s7: Sequence<T7>,
s8: Sequence<T8>,
) extends Sequence<(T0, T1, T2, T3, T4, T5, T6, T7, T8)> {
fun values(): mutable Iterator<(T0, T1, T2, T3, T4, T5, T6, T7, T8)> {
it0 = this.s0.values();
it1 = this.s1.values();
it2 = this.s2.values();
it3 = this.s3.values();
it4 = this.s4.values();
it5 = this.s5.values();
it6 = this.s6.values();
it7 = this.s7.values();
it8 = this.s8.values();
loop {
(
it0.next(),
it1.next(),
it2.next(),
it3.next(),
it4.next(),
it5.next(),
it6.next(),
it7.next(),
it8.next(),
) match {
| (
Some(val0),
Some(val1),
Some(val2),
Some(val3),
Some(val4),
Some(val5),
Some(val6),
Some(val7),
Some(val8),
) ->
yield (val0, val1, val2, val3, val4, val5, val6, val7, val8)
| _ -> break void
}
}
}
fun size(): Int {
Vector[
this.s0.size(),
this.s1.size(),
this.s2.size(),
this.s3.size(),
this.s4.size(),
this.s5.size(),
this.s6.size(),
this.s7.size(),
this.s8.size(),
].min().fromSome()
}
}
class Zip10Sequence<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9>(
s0: Sequence<T0>,
s1: Sequence<T1>,
s2: Sequence<T2>,
s3: Sequence<T3>,
s4: Sequence<T4>,
s5: Sequence<T5>,
s6: Sequence<T6>,
s7: Sequence<T7>,
s8: Sequence<T8>,
s9: Sequence<T9>,
) extends Sequence<(T0, T1, T2, T3, T4, T5, T6, T7, T8, T9)> {
fun values(): mutable Iterator<(T0, T1, T2, T3, T4, T5, T6, T7, T8, T9)> {
it0 = this.s0.values();
it1 = this.s1.values();
it2 = this.s2.values();
it3 = this.s3.values();
it4 = this.s4.values();
it5 = this.s5.values();
it6 = this.s6.values();
it7 = this.s7.values();
it8 = this.s8.values();
it9 = this.s9.values();
loop {
(
it0.next(),
it1.next(),
it2.next(),
it3.next(),
it4.next(),
it5.next(),
it6.next(),
it7.next(),
it8.next(),
it9.next(),
) match {
| (
Some(val0),
Some(val1),
Some(val2),
Some(val3),
Some(val4),
Some(val5),
Some(val6),
Some(val7),
Some(val8),
Some(val9),
) ->
yield (val0, val1, val2, val3, val4, val5, val6, val7, val8, val9)
| _ -> break void
}
}
}
fun size(): Int {
Vector[
this.s0.size(),
this.s1.size(),
this.s2.size(),
this.s3.size(),
this.s4.size(),
this.s5.size(),
this.s6.size(),
this.s7.size(),
this.s8.size(),
this.s9.size(),
].min().fromSome()
}
}
extension mutable base class .Sequence {
static fun zip2<T0, T1>(
s0: Sequence<T0>,
s1: Sequence<T1>,
): Sequence<(T0, T1)> {
Zip2Sequence(s0, s1)
}
static fun zip3<T0, T1, T2>(
s0: Sequence<T0>,
s1: Sequence<T1>,
s2: Sequence<T2>,
): Sequence<(T0, T1, T2)> {
Zip3Sequence(s0, s1, s2)
}
static fun zip4<T0, T1, T2, T3>(
s0: Sequence<T0>,
s1: Sequence<T1>,
s2: Sequence<T2>,
s3: Sequence<T3>,
): Sequence<(T0, T1, T2, T3)> {
Zip4Sequence(s0, s1, s2, s3)
}
static fun zip5<T0, T1, T2, T3, T4>(
s0: Sequence<T0>,
s1: Sequence<T1>,
s2: Sequence<T2>,
s3: Sequence<T3>,
s4: Sequence<T4>,
): Sequence<(T0, T1, T2, T3, T4)> {
Zip5Sequence(s0, s1, s2, s3, s4)
}
static fun zip6<T0, T1, T2, T3, T4, T5>(
s0: Sequence<T0>,
s1: Sequence<T1>,
s2: Sequence<T2>,
s3: Sequence<T3>,
s4: Sequence<T4>,
s5: Sequence<T5>,
): Sequence<(T0, T1, T2, T3, T4, T5)> {
Zip6Sequence(s0, s1, s2, s3, s4, s5)
}
static fun zip7<T0, T1, T2, T3, T4, T5, T6>(
s0: Sequence<T0>,
s1: Sequence<T1>,
s2: Sequence<T2>,
s3: Sequence<T3>,
s4: Sequence<T4>,
s5: Sequence<T5>,
s6: Sequence<T6>,
): Sequence<(T0, T1, T2, T3, T4, T5, T6)> {
Zip7Sequence(s0, s1, s2, s3, s4, s5, s6)
}
static fun zip8<T0, T1, T2, T3, T4, T5, T6, T7>(
s0: Sequence<T0>,
s1: Sequence<T1>,
s2: Sequence<T2>,
s3: Sequence<T3>,
s4: Sequence<T4>,
s5: Sequence<T5>,
s6: Sequence<T6>,
s7: Sequence<T7>,
): Sequence<(T0, T1, T2, T3, T4, T5, T6, T7)> {
Zip8Sequence(s0, s1, s2, s3, s4, s5, s6, s7)
}
static fun zip9<T0, T1, T2, T3, T4, T5, T6, T7, T8>(
s0: Sequence<T0>,
s1: Sequence<T1>,
s2: Sequence<T2>,
s3: Sequence<T3>,
s4: Sequence<T4>,
s5: Sequence<T5>,
s6: Sequence<T6>,
s7: Sequence<T7>,
s8: Sequence<T8>,
): Sequence<(T0, T1, T2, T3, T4, T5, T6, T7, T8)> {
Zip9Sequence(s0, s1, s2, s3, s4, s5, s6, s7, s8)
}
static fun zip10<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9>(
s0: Sequence<T0>,
s1: Sequence<T1>,
s2: Sequence<T2>,
s3: Sequence<T3>,
s4: Sequence<T4>,
s5: Sequence<T5>,
s6: Sequence<T6>,
s7: Sequence<T7>,
s8: Sequence<T8>,
s9: Sequence<T9>,
): Sequence<(T0, T1, T2, T3, T4, T5, T6, T7, T8, T9)> {
Zip10Sequence(s0, s1, s2, s3, s4, s5, s6, s7, s8, s9)
}
}
module end;
| {
"pile_set_name": "Github"
} |
class AddIndexIndexGroupsOnParentIdToGroups < ActiveRecord::Migration
def change
add_index "groups", ["parent_id"], :name => "index_groups_on_parent_id"
end
end
| {
"pile_set_name": "Github"
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Examples for bug 444928</title>
</head>
<body>
<table cellspacing="50" cellpadding="0" style="table-layout:fixed" width="652">
<col width="150">
<col width="150">
<col>
<tr><td colspan="2" style="background:yellow">1-2</td><td style="background:fuchsia">3</td></tr>
<tr style="color:transparent"><td>1</td><td>2</td><td>3</td></tr>
</tbody>
</table>
</body>
</html>
| {
"pile_set_name": "Github"
} |
#ifdef GL_ES
precision mediump float;
#endif
varying vec3 v_reflect;
uniform samplerCube u_cubeTex;
uniform vec4 u_color;
void main(void)
{
gl_FragColor = textureCube(u_cubeTex, v_reflect) * u_color;
}
| {
"pile_set_name": "Github"
} |
# Building the registry source
## Use-case
This is useful if you intend to actively work on the registry.
### Alternatives
Most people should use the [official Registry docker image](https://hub.docker.com/r/library/registry/).
People looking for advanced operational use cases might consider rolling their own image with a custom Dockerfile inheriting `FROM registry:2`.
OS X users who want to run natively can do so following [the instructions here](https://github.com/docker/docker.github.io/blob/master/registry/recipes/osx-setup-guide.md).
### Gotchas
You are expected to know your way around with go & git.
If you are a casual user with no development experience, and no preliminary knowledge of go, building from source is probably not a good solution for you.
## Build the development environment
The first prerequisite of properly building distribution targets is to have a Go
development environment setup. Please follow [How to Write Go Code](https://golang.org/doc/code.html)
for proper setup. If done correctly, you should have a GOROOT and GOPATH set in the
environment.
If a Go development environment is setup, one can use `go get` to install the
`registry` command from the current latest:
go get github.com/docker/distribution/cmd/registry
The above will install the source repository into the `GOPATH`.
Now create the directory for the registry data (this might require you to set permissions properly)
mkdir -p /var/lib/registry
... or alternatively `export REGISTRY_STORAGE_FILESYSTEM_ROOTDIRECTORY=/somewhere` if you want to store data into another location.
The `registry`
binary can then be run with the following:
$ $GOPATH/bin/registry --version
$GOPATH/bin/registry github.com/docker/distribution v2.0.0-alpha.1+unknown
> __NOTE:__ While you do not need to use `go get` to checkout the distribution
> project, for these build instructions to work, the project must be checked
> out in the correct location in the `GOPATH`. This should almost always be
> `$GOPATH/src/github.com/docker/distribution`.
The registry can be run with the default config using the following
incantation:
$ $GOPATH/bin/registry serve $GOPATH/src/github.com/docker/distribution/cmd/registry/config-example.yml
INFO[0000] endpoint local-5003 disabled, skipping app.id=34bbec38-a91a-494a-9a3f-b72f9010081f version=v2.0.0-alpha.1+unknown
INFO[0000] endpoint local-8083 disabled, skipping app.id=34bbec38-a91a-494a-9a3f-b72f9010081f version=v2.0.0-alpha.1+unknown
INFO[0000] listening on :5000 app.id=34bbec38-a91a-494a-9a3f-b72f9010081f version=v2.0.0-alpha.1+unknown
INFO[0000] debug server listening localhost:5001
If it is working, one should see the above log messages.
### Repeatable Builds
For the full development experience, one should `cd` into
`$GOPATH/src/github.com/docker/distribution`. From there, the regular `go`
commands, such as `go test`, should work per package (please see
[Developing](#developing) if they don't work).
A `Makefile` has been provided as a convenience to support repeatable builds.
Please install the following into `GOPATH` for it to work:
go get github.com/golang/lint/golint
Once these commands are available in the `GOPATH`, run `make` to get a full
build:
$ make
+ clean
+ fmt
+ vet
+ lint
+ build
github.com/docker/docker/vendor/src/code.google.com/p/go/src/pkg/archive/tar
github.com/sirupsen/logrus
github.com/docker/libtrust
...
github.com/yvasiyarov/gorelic
github.com/docker/distribution/registry/handlers
github.com/docker/distribution/cmd/registry
+ test
...
ok github.com/docker/distribution/digest 7.875s
ok github.com/docker/distribution/manifest 0.028s
ok github.com/docker/distribution/notifications 17.322s
? github.com/docker/distribution/registry [no test files]
ok github.com/docker/distribution/registry/api/v2 0.101s
? github.com/docker/distribution/registry/auth [no test files]
ok github.com/docker/distribution/registry/auth/silly 0.011s
...
+ /Users/sday/go/src/github.com/docker/distribution/bin/registry
+ /Users/sday/go/src/github.com/docker/distribution/bin/registry-api-descriptor-template
+ binaries
The above provides a repeatable build using the contents of the vendor
directory. This includes formatting, vetting, linting, building,
testing and generating tagged binaries. We can verify this worked by running
the registry binary generated in the "./bin" directory:
$ ./bin/registry --version
./bin/registry github.com/docker/distribution v2.0.0-alpha.2-80-g16d8b2c.m
### Optional build tags
Optional [build tags](http://golang.org/pkg/go/build/) can be provided using
the environment variable `DOCKER_BUILDTAGS`.
| {
"pile_set_name": "Github"
} |
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// DragonFly BSD system calls.
// This file is compiled as ordinary Go code,
// but it is also input to mksyscall,
// which parses the //sys lines and generates system call stubs.
// Note that sometimes we use a lowercase //sys name and wrap
// it in our own nicer implementation, either here or in
// syscall_bsd.go or syscall_unix.go.
package unix
import "unsafe"
// SockaddrDatalink implements the Sockaddr interface for AF_LINK type sockets.
type SockaddrDatalink struct {
Len uint8
Family uint8
Index uint16
Type uint8
Nlen uint8
Alen uint8
Slen uint8
Data [12]int8
Rcf uint16
Route [16]uint16
raw RawSockaddrDatalink
}
// Translate "kern.hostname" to []_C_int{0,1,2,3}.
func nametomib(name string) (mib []_C_int, err error) {
const siz = unsafe.Sizeof(mib[0])
// NOTE(rsc): It seems strange to set the buffer to have
// size CTL_MAXNAME+2 but use only CTL_MAXNAME
// as the size. I don't know why the +2 is here, but the
// kernel uses +2 for its own implementation of this function.
// I am scared that if we don't include the +2 here, the kernel
// will silently write 2 words farther than we specify
// and we'll get memory corruption.
var buf [CTL_MAXNAME + 2]_C_int
n := uintptr(CTL_MAXNAME) * siz
p := (*byte)(unsafe.Pointer(&buf[0]))
bytes, err := ByteSliceFromString(name)
if err != nil {
return nil, err
}
// Magic sysctl: "setting" 0.3 to a string name
// lets you read back the array of integers form.
if err = sysctl([]_C_int{0, 3}, p, &n, &bytes[0], uintptr(len(name))); err != nil {
return nil, err
}
return buf[0 : n/siz], nil
}
//sysnb pipe() (r int, w int, err error)
func Pipe(p []int) (err error) {
if len(p) != 2 {
return EINVAL
}
p[0], p[1], err = pipe()
return
}
//sys extpread(fd int, p []byte, flags int, offset int64) (n int, err error)
func Pread(fd int, p []byte, offset int64) (n int, err error) {
return extpread(fd, p, 0, offset)
}
//sys extpwrite(fd int, p []byte, flags int, offset int64) (n int, err error)
func Pwrite(fd int, p []byte, offset int64) (n int, err error) {
return extpwrite(fd, p, 0, offset)
}
func Accept4(fd, flags int) (nfd int, sa Sockaddr, err error) {
var rsa RawSockaddrAny
var len _Socklen = SizeofSockaddrAny
nfd, err = accept4(fd, &rsa, &len, flags)
if err != nil {
return
}
if len > SizeofSockaddrAny {
panic("RawSockaddrAny too small")
}
sa, err = anyToSockaddr(fd, &rsa)
if err != nil {
Close(nfd)
nfd = 0
}
return
}
const ImplementsGetwd = true
//sys Getcwd(buf []byte) (n int, err error) = SYS___GETCWD
func Getwd() (string, error) {
var buf [PathMax]byte
_, err := Getcwd(buf[0:])
if err != nil {
return "", err
}
n := clen(buf[:])
if n < 1 {
return "", EINVAL
}
return string(buf[:n]), nil
}
func Getfsstat(buf []Statfs_t, flags int) (n int, err error) {
var _p0 unsafe.Pointer
var bufsize uintptr
if len(buf) > 0 {
_p0 = unsafe.Pointer(&buf[0])
bufsize = unsafe.Sizeof(Statfs_t{}) * uintptr(len(buf))
}
r0, _, e1 := Syscall(SYS_GETFSSTAT, uintptr(_p0), bufsize, uintptr(flags))
n = int(r0)
if e1 != 0 {
err = e1
}
return
}
func setattrlistTimes(path string, times []Timespec, flags int) error {
// used on Darwin for UtimesNano
return ENOSYS
}
//sys ioctl(fd int, req uint, arg uintptr) (err error)
// ioctl itself should not be exposed directly, but additional get/set
// functions for specific types are permissible.
// IoctlSetInt performs an ioctl operation which sets an integer value
// on fd, using the specified request number.
func IoctlSetInt(fd int, req uint, value int) error {
return ioctl(fd, req, uintptr(value))
}
func ioctlSetWinsize(fd int, req uint, value *Winsize) error {
return ioctl(fd, req, uintptr(unsafe.Pointer(value)))
}
func ioctlSetTermios(fd int, req uint, value *Termios) error {
return ioctl(fd, req, uintptr(unsafe.Pointer(value)))
}
// IoctlGetInt performs an ioctl operation which gets an integer value
// from fd, using the specified request number.
func IoctlGetInt(fd int, req uint) (int, error) {
var value int
err := ioctl(fd, req, uintptr(unsafe.Pointer(&value)))
return value, err
}
func IoctlGetWinsize(fd int, req uint) (*Winsize, error) {
var value Winsize
err := ioctl(fd, req, uintptr(unsafe.Pointer(&value)))
return &value, err
}
func IoctlGetTermios(fd int, req uint) (*Termios, error) {
var value Termios
err := ioctl(fd, req, uintptr(unsafe.Pointer(&value)))
return &value, err
}
func sysctlUname(mib []_C_int, old *byte, oldlen *uintptr) error {
err := sysctl(mib, old, oldlen, nil, 0)
if err != nil {
// Utsname members on Dragonfly are only 32 bytes and
// the syscall returns ENOMEM in case the actual value
// is longer.
if err == ENOMEM {
err = nil
}
}
return err
}
func Uname(uname *Utsname) error {
mib := []_C_int{CTL_KERN, KERN_OSTYPE}
n := unsafe.Sizeof(uname.Sysname)
if err := sysctlUname(mib, &uname.Sysname[0], &n); err != nil {
return err
}
uname.Sysname[unsafe.Sizeof(uname.Sysname)-1] = 0
mib = []_C_int{CTL_KERN, KERN_HOSTNAME}
n = unsafe.Sizeof(uname.Nodename)
if err := sysctlUname(mib, &uname.Nodename[0], &n); err != nil {
return err
}
uname.Nodename[unsafe.Sizeof(uname.Nodename)-1] = 0
mib = []_C_int{CTL_KERN, KERN_OSRELEASE}
n = unsafe.Sizeof(uname.Release)
if err := sysctlUname(mib, &uname.Release[0], &n); err != nil {
return err
}
uname.Release[unsafe.Sizeof(uname.Release)-1] = 0
mib = []_C_int{CTL_KERN, KERN_VERSION}
n = unsafe.Sizeof(uname.Version)
if err := sysctlUname(mib, &uname.Version[0], &n); err != nil {
return err
}
// The version might have newlines or tabs in it, convert them to
// spaces.
for i, b := range uname.Version {
if b == '\n' || b == '\t' {
if i == len(uname.Version)-1 {
uname.Version[i] = 0
} else {
uname.Version[i] = ' '
}
}
}
mib = []_C_int{CTL_HW, HW_MACHINE}
n = unsafe.Sizeof(uname.Machine)
if err := sysctlUname(mib, &uname.Machine[0], &n); err != nil {
return err
}
uname.Machine[unsafe.Sizeof(uname.Machine)-1] = 0
return nil
}
func Sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) {
if raceenabled {
raceReleaseMerge(unsafe.Pointer(&ioSync))
}
return sendfile(outfd, infd, offset, count)
}
/*
* Exposed directly
*/
//sys Access(path string, mode uint32) (err error)
//sys Adjtime(delta *Timeval, olddelta *Timeval) (err error)
//sys Chdir(path string) (err error)
//sys Chflags(path string, flags int) (err error)
//sys Chmod(path string, mode uint32) (err error)
//sys Chown(path string, uid int, gid int) (err error)
//sys Chroot(path string) (err error)
//sys Close(fd int) (err error)
//sys Dup(fd int) (nfd int, err error)
//sys Dup2(from int, to int) (err error)
//sys Exit(code int)
//sys Faccessat(dirfd int, path string, mode uint32, flags int) (err error)
//sys Fchdir(fd int) (err error)
//sys Fchflags(fd int, flags int) (err error)
//sys Fchmod(fd int, mode uint32) (err error)
//sys Fchmodat(dirfd int, path string, mode uint32, flags int) (err error)
//sys Fchown(fd int, uid int, gid int) (err error)
//sys Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error)
//sys Flock(fd int, how int) (err error)
//sys Fpathconf(fd int, name int) (val int, err error)
//sys Fstat(fd int, stat *Stat_t) (err error)
//sys Fstatat(fd int, path string, stat *Stat_t, flags int) (err error)
//sys Fstatfs(fd int, stat *Statfs_t) (err error)
//sys Fsync(fd int) (err error)
//sys Ftruncate(fd int, length int64) (err error)
//sys Getdirentries(fd int, buf []byte, basep *uintptr) (n int, err error)
//sys Getdtablesize() (size int)
//sysnb Getegid() (egid int)
//sysnb Geteuid() (uid int)
//sysnb Getgid() (gid int)
//sysnb Getpgid(pid int) (pgid int, err error)
//sysnb Getpgrp() (pgrp int)
//sysnb Getpid() (pid int)
//sysnb Getppid() (ppid int)
//sys Getpriority(which int, who int) (prio int, err error)
//sysnb Getrlimit(which int, lim *Rlimit) (err error)
//sysnb Getrusage(who int, rusage *Rusage) (err error)
//sysnb Getsid(pid int) (sid int, err error)
//sysnb Gettimeofday(tv *Timeval) (err error)
//sysnb Getuid() (uid int)
//sys Issetugid() (tainted bool)
//sys Kill(pid int, signum syscall.Signal) (err error)
//sys Kqueue() (fd int, err error)
//sys Lchown(path string, uid int, gid int) (err error)
//sys Link(path string, link string) (err error)
//sys Linkat(pathfd int, path string, linkfd int, link string, flags int) (err error)
//sys Listen(s int, backlog int) (err error)
//sys Lstat(path string, stat *Stat_t) (err error)
//sys Mkdir(path string, mode uint32) (err error)
//sys Mkdirat(dirfd int, path string, mode uint32) (err error)
//sys Mkfifo(path string, mode uint32) (err error)
//sys Mknod(path string, mode uint32, dev int) (err error)
//sys Mknodat(fd int, path string, mode uint32, dev int) (err error)
//sys Nanosleep(time *Timespec, leftover *Timespec) (err error)
//sys Open(path string, mode int, perm uint32) (fd int, err error)
//sys Openat(dirfd int, path string, mode int, perm uint32) (fd int, err error)
//sys Pathconf(path string, name int) (val int, err error)
//sys read(fd int, p []byte) (n int, err error)
//sys Readlink(path string, buf []byte) (n int, err error)
//sys Rename(from string, to string) (err error)
//sys Renameat(fromfd int, from string, tofd int, to string) (err error)
//sys Revoke(path string) (err error)
//sys Rmdir(path string) (err error)
//sys Seek(fd int, offset int64, whence int) (newoffset int64, err error) = SYS_LSEEK
//sys Select(n int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (err error)
//sysnb Setegid(egid int) (err error)
//sysnb Seteuid(euid int) (err error)
//sysnb Setgid(gid int) (err error)
//sys Setlogin(name string) (err error)
//sysnb Setpgid(pid int, pgid int) (err error)
//sys Setpriority(which int, who int, prio int) (err error)
//sysnb Setregid(rgid int, egid int) (err error)
//sysnb Setreuid(ruid int, euid int) (err error)
//sysnb Setresgid(rgid int, egid int, sgid int) (err error)
//sysnb Setresuid(ruid int, euid int, suid int) (err error)
//sysnb Setrlimit(which int, lim *Rlimit) (err error)
//sysnb Setsid() (pid int, err error)
//sysnb Settimeofday(tp *Timeval) (err error)
//sysnb Setuid(uid int) (err error)
//sys Stat(path string, stat *Stat_t) (err error)
//sys Statfs(path string, stat *Statfs_t) (err error)
//sys Symlink(path string, link string) (err error)
//sys Symlinkat(oldpath string, newdirfd int, newpath string) (err error)
//sys Sync() (err error)
//sys Truncate(path string, length int64) (err error)
//sys Umask(newmask int) (oldmask int)
//sys Undelete(path string) (err error)
//sys Unlink(path string) (err error)
//sys Unlinkat(dirfd int, path string, flags int) (err error)
//sys Unmount(path string, flags int) (err error)
//sys write(fd int, p []byte) (n int, err error)
//sys mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error)
//sys munmap(addr uintptr, length uintptr) (err error)
//sys readlen(fd int, buf *byte, nbuf int) (n int, err error) = SYS_READ
//sys writelen(fd int, buf *byte, nbuf int) (n int, err error) = SYS_WRITE
//sys accept4(fd int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (nfd int, err error)
//sys utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error)
/*
* Unimplemented
* TODO(jsing): Update this list for DragonFly.
*/
// Profil
// Sigaction
// Sigprocmask
// Getlogin
// Sigpending
// Sigaltstack
// Reboot
// Execve
// Vfork
// Sbrk
// Sstk
// Ovadvise
// Mincore
// Setitimer
// Swapon
// Select
// Sigsuspend
// Readv
// Writev
// Nfssvc
// Getfh
// Quotactl
// Mount
// Csops
// Waitid
// Add_profil
// Kdebug_trace
// Sigreturn
// Atsocket
// Kqueue_from_portset_np
// Kqueue_portset
// Getattrlist
// Setattrlist
// Getdirentriesattr
// Searchfs
// Delete
// Copyfile
// Watchevent
// Waitevent
// Modwatch
// Getxattr
// Fgetxattr
// Setxattr
// Fsetxattr
// Removexattr
// Fremovexattr
// Listxattr
// Flistxattr
// Fsctl
// Initgroups
// Posix_spawn
// Nfsclnt
// Fhopen
// Minherit
// Semsys
// Msgsys
// Shmsys
// Semctl
// Semget
// Semop
// Msgctl
// Msgget
// Msgsnd
// Msgrcv
// Shmat
// Shmctl
// Shmdt
// Shmget
// Shm_open
// Shm_unlink
// Sem_open
// Sem_close
// Sem_unlink
// Sem_wait
// Sem_trywait
// Sem_post
// Sem_getvalue
// Sem_init
// Sem_destroy
// Open_extended
// Umask_extended
// Stat_extended
// Lstat_extended
// Fstat_extended
// Chmod_extended
// Fchmod_extended
// Access_extended
// Settid
// Gettid
// Setsgroups
// Getsgroups
// Setwgroups
// Getwgroups
// Mkfifo_extended
// Mkdir_extended
// Identitysvc
// Shared_region_check_np
// Shared_region_map_np
// __pthread_mutex_destroy
// __pthread_mutex_init
// __pthread_mutex_lock
// __pthread_mutex_trylock
// __pthread_mutex_unlock
// __pthread_cond_init
// __pthread_cond_destroy
// __pthread_cond_broadcast
// __pthread_cond_signal
// Setsid_with_pid
// __pthread_cond_timedwait
// Aio_fsync
// Aio_return
// Aio_suspend
// Aio_cancel
// Aio_error
// Aio_read
// Aio_write
// Lio_listio
// __pthread_cond_wait
// Iopolicysys
// __pthread_kill
// __pthread_sigmask
// __sigwait
// __disable_threadsignal
// __pthread_markcancel
// __pthread_canceled
// __semwait_signal
// Proc_info
// Stat64_extended
// Lstat64_extended
// Fstat64_extended
// __pthread_chdir
// __pthread_fchdir
// Audit
// Auditon
// Getauid
// Setauid
// Getaudit
// Setaudit
// Getaudit_addr
// Setaudit_addr
// Auditctl
// Bsdthread_create
// Bsdthread_terminate
// Stack_snapshot
// Bsdthread_register
// Workq_open
// Workq_ops
// __mac_execve
// __mac_syscall
// __mac_get_file
// __mac_set_file
// __mac_get_link
// __mac_set_link
// __mac_get_proc
// __mac_set_proc
// __mac_get_fd
// __mac_set_fd
// __mac_get_pid
// __mac_get_lcid
// __mac_get_lctx
// __mac_set_lctx
// Setlcid
// Read_nocancel
// Write_nocancel
// Open_nocancel
// Close_nocancel
// Wait4_nocancel
// Recvmsg_nocancel
// Sendmsg_nocancel
// Recvfrom_nocancel
// Accept_nocancel
// Fcntl_nocancel
// Select_nocancel
// Fsync_nocancel
// Connect_nocancel
// Sigsuspend_nocancel
// Readv_nocancel
// Writev_nocancel
// Sendto_nocancel
// Pread_nocancel
// Pwrite_nocancel
// Waitid_nocancel
// Msgsnd_nocancel
// Msgrcv_nocancel
// Sem_wait_nocancel
// Aio_suspend_nocancel
// __sigwait_nocancel
// __semwait_signal_nocancel
// __mac_mount
// __mac_get_mount
// __mac_getfsstat
| {
"pile_set_name": "Github"
} |
var mkdirp = require('../');
var path = require('path');
var fs = require('fs');
var exists = fs.exists || path.exists;
var test = require('tap').test;
var _0777 = parseInt('0777', 8);
var _0755 = parseInt('0755', 8);
test('async perm', function (t) {
t.plan(5);
var file = '/tmp/' + (Math.random() * (1<<30)).toString(16);
mkdirp(file, _0755, function (err) {
t.ifError(err);
exists(file, function (ex) {
t.ok(ex, 'file created');
fs.stat(file, function (err, stat) {
t.ifError(err);
t.equal(stat.mode & _0777, _0755);
t.ok(stat.isDirectory(), 'target not a directory');
})
})
});
});
test('async root perm', function (t) {
mkdirp('/tmp', _0755, function (err) {
if (err) t.fail(err);
t.end();
});
t.end();
});
| {
"pile_set_name": "Github"
} |
#!/bin/sh
#
# Part of RedELK
# Script to update list of TOR exit node IP addresses
#
# Author: Outflank B.V. / Marc Smeets
#
LOGFILE="/var/log/redelk/torupdate.log"
CONFIGFILE="/etc/redelk/torexitnodes.conf"
TEMPFILE="/tmp/torexitnodes.txt"
curl -s https://check.torproject.org/exit-addresses | awk '/ExitAddress/ {print $2}' > $TEMPFILE
LINECOUNT=`wc -l /tmp/torexitnodes.txt|awk '{print $1}'`
if [ $LINECOUNT -ge 10 ]; then
echo "# Part of RedELK - list of TOR exit node addresses - AUTO UPDATED, DO NOT MAKE MANUAL CHANGES" > $CONFIGFILE
cat $TEMPFILE >> $CONFIGFILE
rm $TEMPFILE
echo "$LINECOUNT lines added">> $LOGFILE
printf "`date +'%b %e %R'` TOR update script ran \n" >> $LOGFILE 2>&1
fi
| {
"pile_set_name": "Github"
} |
framework:
router:
strict_requirements: ~
| {
"pile_set_name": "Github"
} |
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<Version>0.22.2.1</Version>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\MxNet\MxNet.csproj" />
</ItemGroup>
</Project>
| {
"pile_set_name": "Github"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.