content stringlengths 4 1.04M | lang stringclasses 358
values | score int64 0 5 | repo_name stringlengths 5 114 | repo_path stringlengths 4 229 | repo_licenses listlengths 1 8 |
|---|---|---|---|---|---|
// Copyright (c) 2021 Bluespec, Inc. All Rights Reserved
package Test_AXI4_to_LDST;
// ================================================================
// Standalone unit tester for AXI4_Deburster.bsv
// ================================================================
// Bluespec library imports
import FIFOF :: *;
import Connectable :: *;
import Vector :: *;
import StmtFSM :: *;
// ----------------
// BSV additional libs
import Cur_Cycle :: *;
import Semi_FIFOF :: *;
// ================================================================
// Local imports
import AXI4_Types :: *;
import AXI4_to_LDST :: *;
// ================================================================
Integer verbosity = 0;
// ================================================================
// Synthesized instance of module
typedef 16 Wd_Id;
typedef 64 Wd_Addr;
typedef 512 Wd_AXI_Data;
typedef 0 Wd_User;
typedef 64 Wd_LDST_Data;
typedef AXI4_to_LDST_IFC #(Wd_Id,
Wd_Addr,
Wd_AXI_Data,
Wd_User,
Wd_LDST_Data) AXI4_to_LDST_1_IFC;
(* synthesize *)
module mkAXI4_to_LDST_1 (AXI4_to_LDST_1_IFC);
let m <- mkAXI4_to_LDST;
return m;
endmodule
// ================================================================
(* synthesize *)
module mkTest_AXI4_to_LDST (Empty);
// The DUT
AXI4_to_LDST_1_IFC dut <- mkAXI4_to_LDST_1;
// Transactor representing master
AXI4_Master_Xactor_IFC #(Wd_Id, Wd_Addr, Wd_AXI_Data, Wd_User)
axi4_M_xactor <- mkAXI4_Master_Xactor;
mkConnection (axi4_M_xactor.axi_side, dut.axi4_S);
// This bool controls whether we issue the next AXI request only
// after the prev one has responded, or whether we pipeline them.
Reg #(Bool) rg_one_at_a_time <- mkReg (True);
Reg #(Bool) rg_prev_done <- mkReg (True);
function Stmt fa_set_one_at_a_time (Bool b);
return seq
delay (32); // To allow quiescence
action
rg_one_at_a_time <= b;
$display ("================================================================");
if (b)
$display ("%0d: INFO: Setting Mode to: one-at-a-time", cur_cycle);
else
$display ("%0d: INFO: Setting Mode to: pipelined, cur_cycle", cur_cycle);
endaction
endseq;
endfunction
// ================================================================
// Templates for AXI structs (we modify these slightly in tests)
AXI4_Wr_Addr #(Wd_Id, Wd_Addr, Wd_User)
wr_addr_0 = AXI4_Wr_Addr {awid: 0,
awaddr: 'h_8000_0000,
awlen: (1 - 1),
awsize: axsize_8,
awburst: axburst_incr,
awlock: 0,
awcache: 0,
awprot: 0,
awqos: 0,
awregion: 0,
awuser: 0};
AXI4_Rd_Addr #(Wd_Id, Wd_Addr, Wd_User)
rd_addr_0 = AXI4_Rd_Addr {arid: 0,
araddr: 'h_8000_0000,
arlen: (1 - 1),
arsize: axsize_8,
arburst: axburst_incr,
arlock: 0,
arcache: 0,
arprot: 0,
arqos: 0,
arregion: 0,
aruser: 0};
// 'values' is a vector of bytes [0, 1, 2, ...]
function Bit #(8) fn_for_vector_gen (Integer i);
return fromInteger (i);
endfunction
Vector #(TDiv #(Wd_AXI_Data, 8), Bit #(8)) values = genWith (fn_for_vector_gen);
AXI4_Wr_Data #(Wd_AXI_Data, Wd_User)
wr_data_0 = AXI4_Wr_Data {wdata: pack (values),
wstrb: '1,
wlast: True,
wuser: 0};
function Action fa_show_axi_data (Bit #(Wd_AXI_Data) axi_data);
action
Vector #(TDiv #(Wd_AXI_Data, Wd_LDST_Data),
Bit #(Wd_LDST_Data)) v_slices = unpack (axi_data);
Integer slices_per_axi_data_I = valueOf (TDiv #(Wd_AXI_Data, Wd_LDST_Data));
for (Integer row = 0; row < 2; row = row + 1) begin
$write (" ");
for (Integer col = 0; col < 4; col = col + 1)
$write (" %016h", v_slices [row * 4 + (3 - col)]); // little-endian
$display ("");
end
endaction
endfunction
// ================================================================
// The following rules handle the LD/ST requests emerging from
// the AXI4_to_LDST transformer, returning synthetic responses.
// ----------------
// Store request handler
rule rl_st_handler;
match { .sizecode, .addr, .data } = dut.st_reqs.first;
dut.st_reqs.deq;
$write ("%0d: %m.rl_st_handler:", cur_cycle);
case (sizecode)
2'b00: $write (" SB");
2'b01: $write (" SH");
2'b10: $write (" SW");
2'b11: $write (" SD");
endcase
$display (" addr %0h data %16h", addr, data);
Bool aligned = ( (sizecode == ldst_b)
|| ((sizecode == ldst_h) && (addr [0] == 1'b0))
|| ((sizecode == ldst_w) && (addr [1:0] == 2'b00))
|| ((sizecode == ldst_d) && (addr [2:0] == 3'b000)));
if (! aligned) begin
$display ("%0d: ERROR: %m.rl_st_handler", cur_cycle);
$display (" MISALIGNED sizecode %0h addr %0h data %0h", sizecode, addr, data);
end
dut.st_rsps.enq (! aligned);
endrule
// ----------------
// Load request handler
rule rl_ld_handler;
match { .sizecode, .addr } = dut.ld_reqs.first;
dut.ld_reqs.deq;
Bool aligned = ( (sizecode == ldst_b)
|| ((sizecode == ldst_h) && (addr [0] == 1'b0))
|| ((sizecode == ldst_w) && (addr [1:0] == 2'b00))
|| ((sizecode == ldst_d) && (addr [2:0] == 3'b000)));
let shift_amt = ((addr & 'h3F) << 3);
Bit #(Wd_LDST_Data) rdata = truncate (pack (values) >> shift_amt);
case (sizecode)
2'b00: rdata = (rdata & 'h_FF);
2'b01: rdata = (rdata & 'h_FFFF);
2'b10: rdata = (rdata & 'h_FFFF_FFFF);
endcase
$write ("%0d: %m.rl_ld_handler:", cur_cycle);
case (sizecode)
2'b00: begin $write (" LB"); rdata = (rdata & 'h_FF); end
2'b01: begin $write (" LH"); rdata = (rdata & 'h_FFFF); end
2'b10: begin $write (" LW"); rdata = (rdata & 'h_FFFF_FFFF); end
2'b11: begin $write (" LD"); end
endcase
$write (" addr %0h", addr);
$display (" => data %0h", rdata);
if (! aligned) begin
$display ("%0d: ERROR: %m.rl_ld_handler", cur_cycle);
$display (" MISALIGNED sizecode %0h addr %0h", sizecode, addr);
end
dut.ld_rsps.enq (tuple2 ((! aligned), rdata));
endrule
// ================================================================
// The following rules handle the final AXI responses
// ----------------
// AXI Wr_Resp sink
rule rl_axi_wr_RSP;
let wr_resp = axi4_M_xactor.o_wr_resp.first;
axi4_M_xactor.o_wr_resp.deq;
rg_prev_done <= True;
$display ("%0d: %m.rl_axi_wr_RSP: ", cur_cycle, fshow (wr_resp));
if (wr_resp.bid == '1) begin
$display (" Sentinel wr_resp (bid == '1); exit");
$finish (0);
end
endrule
// ----------------
// AXI Rd_Data sink
rule rl_axi_rd_RSP;
let rd_data = axi4_M_xactor.o_rd_data.first;
axi4_M_xactor.o_rd_data.deq;
rg_prev_done <= True;
$display ("%0d: %m.rl_axi_rd_RSP: ", cur_cycle);
$display (" rid %0h resp %0h rlast %0h ruser %0h",
rd_data.rid, rd_data.rresp, rd_data.rlast, rd_data.ruser);
fa_show_axi_data (rd_data.rdata);
if (rd_data.rid == '1) begin
$display (" Sentinel rd_data (rid == '1); exit");
$finish (0);
end
endrule
// ================================================================
// Stimulus (AXI4 requests and responses)
// ----------------
function Action fa_wr_REQ (AXI4_Wr_Addr #(Wd_Id, Wd_Addr, Wd_User) wr_addr,
AXI4_Wr_Data #(Wd_AXI_Data, Wd_User) wr_data,
Bit #(16) id,
Bit #(64) addr,
AXI4_Size axsize);
action
await ((! rg_one_at_a_time) || rg_prev_done);
wr_addr.awid = id;
wr_addr.awaddr = addr;
wr_addr.awsize = axsize;
axi4_M_xactor.i_wr_addr.enq (wr_addr);
axi4_M_xactor.i_wr_data.enq (wr_data);
if (rg_one_at_a_time)
rg_prev_done <= False;
$display ("================");
$display ("%0d: %m.fa_wr_REQ: id %0h addr %0h sizecode %0h (0x%0h bytes) strb %016h",
cur_cycle,
id, addr,
axsize, fv_AXI4_Size_to_num_bytes (axsize),
wr_data.wstrb);
fa_show_axi_data (wr_data.wdata);
endaction
endfunction
// ----------------
function Action fa_rd_REQ (AXI4_Rd_Addr #(Wd_Id, Wd_Addr, Wd_User) rd_addr,
Bit #(16) id,
Bit #(64) addr,
AXI4_Size axsize);
action
await ((! rg_one_at_a_time) || rg_prev_done);
rd_addr.arid = id;
rd_addr.araddr = addr;
rd_addr.arsize = axsize;
axi4_M_xactor.i_rd_addr.enq (rd_addr);
if (rg_one_at_a_time)
rg_prev_done <= False;
$display ("================");
$display ("%0d: %m.fa_rd_REQ: id %0h addr %0h sizecode %0h (0x%0h bytes)",
cur_cycle,
id, addr,
axsize, fv_AXI4_Size_to_num_bytes (axsize));
endaction
endfunction
// ----------------
// Stimulus tests
function Stmt test_illegal_wr_req (Bit #(16) id);
return seq
// ----------------
// - num beats > 1
// - wlast is True on first beat
// - AWSIZE wider than axi data bus (when axi data bus < widest allowed)
action
let wr_addr1 = wr_addr_0;
wr_addr1.awlen = 2;
let wr_data1 = wr_data_0;
wr_data1.wlast = True;
Integer num_bytes_axi_data = (valueOf (Wd_AXI_Data) / 8);
let axsize = axsize_32;
if (valueOf (Wd_AXI_Data) < 1024)
axsize = fv_num_bytes_to_AXI4_Size (fromInteger (num_bytes_axi_data * 2));
fa_wr_REQ (wr_addr1, wr_data1, id, 'h_ffff_ffff, axsize);
endaction
// Send 2 more wr_data since awlen = 2
axi4_M_xactor.i_wr_data.enq (wr_data_0);
axi4_M_xactor.i_wr_data.enq (wr_data_0);
endseq;
endfunction
function Stmt test_illegal_rd_req (Bit #(16) id);
return seq
// ----------------
// - num beats > 1
// - AWSIZE wider than axi data bus (when axi data bus < widest allowed)
action
let rd_addr1 = rd_addr_0;
rd_addr1.arlen = 2;
Integer num_bytes_axi_data = (valueOf (Wd_AXI_Data) / 8);
let axsize = axsize_32;
if (valueOf (Wd_AXI_Data) < 1024)
axsize = fv_num_bytes_to_AXI4_Size (fromInteger (num_bytes_axi_data * 2));
fa_rd_REQ (rd_addr1, id, 'h_ffff_ffff, axsize);
endaction
endseq;
endfunction
function Stmt test_writes (Bool mode, Bit #(16) id0);
return seq
fa_set_one_at_a_time (mode); // True: one-at-a-time, False: Pipelined
test_illegal_wr_req (id0 + 1);
// Addr at non-zero bytelane, varying sizes
fa_wr_REQ (wr_addr_0, wr_data_0, id0 + 2, 'h_8000_0025, axsize_8);
fa_wr_REQ (wr_addr_0, wr_data_0, id0 + 3, 'h_8000_0025, axsize_16);
fa_wr_REQ (wr_addr_0, wr_data_0, id0 + 4, 'h_8000_0025, axsize_32);
fa_wr_REQ (wr_addr_0, wr_data_0, id0 + 5, 'h_8000_0025, axsize_64);
// Full data: aligned addr, size 64
fa_wr_REQ (wr_addr_0, wr_data_0, id0 + 'h10, 'h_4000_0000, axsize_64);
// Addr at non-zero bytelane, rest of size-window
fa_wr_REQ (wr_addr_0, wr_data_0, id0 + 'h20, 'h_0001_0009, axsize_8);
// Addr at non-zero bytelane, rest of size-window, reduced by wstrb
action
let wr_data1 = wr_data_0;
wr_data1.wstrb = 'h_0000_0000_0000_7E00;
fa_wr_REQ (wr_addr_0, wr_data1, id0 + 'h21, 'h_0001_0009, axsize_8);
endaction
endseq;
endfunction
function Stmt test_reads (Bool mode, Bit #(16) id0);
return seq
fa_set_one_at_a_time (mode); // True: one-at-a-time, False: Pipelined
test_illegal_rd_req (id0 + 1);
// Addr at non-zero bytelane, varying sizes
fa_rd_REQ (rd_addr_0, id0 + 2, 'h_8000_0025, axsize_8);
fa_rd_REQ (rd_addr_0, id0 + 3, 'h_8000_0025, axsize_16);
fa_rd_REQ (rd_addr_0, id0 + 4, 'h_8000_0025, axsize_32);
fa_rd_REQ (rd_addr_0, id0 + 5, 'h_8000_0025, axsize_64);
// Full data: aligned addr, size 64
fa_rd_REQ (rd_addr_0, id0 + 'h10, 'h_4000_0000, axsize_64);
// Addr at non-zero bytelane, rest of size-window
fa_rd_REQ (rd_addr_0, id0 + 'h20, 'h_0001_0009, axsize_8);
endseq;
endfunction
// ----------------
// Stimulus FSM
// Set 'if (True/False)' below to do/skip tests.
FSM fsm_reqs <- mkFSM
(seq
test_writes (True, 'h1000); // one-at-a-time
test_writes (False, 'h2000); // pipelined
test_reads (True, 'h3000); // one-at-a-time
test_reads (False, 'h4000); // pipelined
delay (1024); // Drain all pipelines
// ----------------
// Sentinel (last) test signalled by arid/awid = '1
// only one of the follwing is needed
// fa_wr_REQ (wr_addr_0, wr_data_0, '1, 'h_ffff_ffff, axsize_8);
fa_rd_REQ (rd_addr_0, '1, 'h_ffff_ffff, axsize_8);
endseq);
// ----------------
// Start the FSM
Reg #(Bool) rg_fsm_started <- mkReg (False);
rule rl_start (! rg_fsm_started);
fsm_reqs.start;
rg_fsm_started <= True;
endrule
endmodule
// ================================================================
endpackage
| Bluespec | 5 | darius-bluespec/Flute | src_Testbench/Fabrics/AXI4/Unit_Test/Test_AXI4_to_LDST.bsv | [
"Apache-2.0"
] |
*----------------------------------------------------------------------------------------------------------------------*
* auxiliary settings and defintions *
*----------------------------------------------------------------------------------------------------------------------*
* initialise logfile settings - this allows to write status messages to the logfile
file logfile / '' / ;
put logfile ;
* get yourself a short listing file
option limrow = 0 ; # number of rows (equations) reported in lst file
option limcol = 0 ; # number of columns reported in lst file
option solprint = off ; # solver's solution output printed
option savepoint = 0 ; # creates a result gdx file after every solve
* this is done manually in this code to have the database name in the gdx file name and to save the file in a sub-folder
option ITERLIM = 1e8 ; # iteration limit
option RESLIM = 1e6 ; # resource limit (in seconds; 1e6 is approximately 11 days)
* solver comments for QCP and PATH:
* - GUROBI, CPLEX and MINOS are fast
* - CONOPT is slower, but (in non-linear problems) usually more helpful to identify the feasibility problems
* general comment: sometimes, first using one solver and then another (using the previous solution as starting point)
* helps even if the previous run did not solve to optimality
option LP = CPLEX ;
option NLP = CONOPT ;
option MCP = PATH ;
*option solveopt=clear ;# remove results of previous runs in memory
option solveopt=merge ; # keep results of previous runs in memory
$SETENV GdxCompress 1 # reduces the size of the gdx export file
%calibration%$ONTEXT
$ONLISTING
option limrow = 1e6 ; # number of rows (equations) reported in lst file
option limcol = 1e6 ; # number of columns reported in lst file
option solprint = on ; # solver's solution output printed
$ONTEXT
$OFFTEXT
| GAMS | 3 | shaohuizhang/message_ix | message_ix/model/MESSAGE/auxiliary_settings.gms | [
"Apache-2.0",
"CC-BY-4.0"
] |
.syntax--markup {
&.syntax--bold {
font-weight: bold;
}
&.syntax--italic {
font-style: italic;
}
&.syntax--heading {
color: @blue;
}
&.syntax--link {
color: @cyan;
}
&.syntax--deleted {
color: @red;
}
&.syntax--changed {
color: @yellow;
}
&.syntax--inserted {
color: @cyan;
}
}
| Less | 4 | davidbertsch/atom | packages/solarized-light-syntax/styles/syntax/markup.less | [
"MIT"
] |
interface I {
function f(a:Int):Void;
}
class C implements I {
public function f() {} // missing `a` argument
}
| Haxe | 2 | jonasmalacofilho/haxe | tests/misc/projects/Issue3417/Main.hx | [
"MIT"
] |
DEPS=$(./seq 10 | sed 's/$/.n1/')
redo-ifchange $DEPS
| Stata | 2 | BlameJohnny/redo | t/950-curse/default.n0.do | [
"Apache-2.0"
] |
FORMAT: 1A
# Machines API
# Group Machines
# Machines collection [/machines/{id}]
+ Parameters
+ id: 1 (number)
## Get Machines [GET]
+ Request (application/json)
+ Parameters
+ id: 2 (number)
+ Response 200 (application/json; charset=utf-8)
+ Schema
true
| API Blueprint | 3 | tomoyamachi/dredd | packages/dredd/test/fixtures/json-schema-draft-7-boolean.apib | [
"MIT"
] |
const channel = new MessageChannel();
channel.port2.onmessage = (e) => {
channel.port2.postMessage(e.data === "2");
channel.port2.close();
};
self.postMessage("1", [channel.port1]);
self.onmessage = (e) => {
const port1 = e.ports[0];
port1.postMessage(e.data === "3");
port1.close();
};
| TypeScript | 3 | petamoriken/deno | cli/tests/testdata/workers/message_port.ts | [
"MIT"
] |
// A simple example
import QtQuick 2.7
import QtQuick.Controls 2.3
Rectangle {
color: "red"
anchors.fill: parent
Text {
text: "WEEEEEEEEEE"
font.pixelSize: 50
color: "white"
anchors.centerIn: parent
RotationAnimator on rotation {
running: true
loops: Animation.Infinite
from: 0
to: 360
duration: 1500
}
}
}
| QML | 3 | mathpurpose/ace_ | demo/kitchen-sink/docs/qml.qml | [
"BSD-3-Clause"
] |
export default Worker;
| JavaScript | 0 | 1shenxi/webpack | test/configCases/worker/custom-worker/node_modules/web-worker.js | [
"MIT"
] |
{
metadata: {
namespace: "input_type_names",
export: "CORE_EXPORT",
},
data: [
"button",
"checkbox",
"color",
"date",
"datetime",
"datetime-local",
"email",
"file",
"hidden",
"image",
"month",
"number",
"password",
"radio",
"range",
"reset",
"search",
"submit",
"tel",
"text",
"time",
"url",
"week",
],
}
| JSON5 | 3 | zealoussnow/chromium | third_party/blink/renderer/core/html/forms/input_type_names.json5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] |
.//====================================================================
.//
.// File: $RCSfile: extract_function_bodies.arc,v $
.// Version: $Revision: 1.11 $
.// Modified: $Date: 2013/01/10 23:21:16 $
.//
.// Copyright 2003-2014 Mentor Graphics Corporation All rights reserved.
.//
.//====================================================================
.//
.include "arc/get_names.inc"
.include "arc/als_sql.inc"
.//
.select many fncs from instances of S_SYNC where (selected.DT_ID != 0)
.for each fnc in fncs
.invoke FILE_WRITE( "sql/${fnc.Name}.oal", "$t2tick{fnc.Action_Semantics}" )
.end for
.//
.assign num_util_funcs = 0;
.for each fnc in fncs
.if ("${fnc.Descrip:ParserUtilityFunction}" == "TRUE")
.if ( num_util_funcs == 0 )
-- BP 6.1D content: synch_service syschar: 3
.invoke x = output_datatype_definitions()
${x.body}
.end if
.print "Saving ${fnc.name}"
.assign num_util_funcs = num_util_funcs + 1
.//
.invoke x = output_function_sql( fnc, "ParserValidateFunction: TRUE\nParserUtilityFunction: TRUE\n" )
${x.body}\
.end if
.end for
.//
.invoke lang_name = get_lang_name()
.assign tstfile = "sql/${lang_name.result}_utilities.sql"
.emit to file "${tstfile}"
| Arc | 4 | FMAY-Software/bridgepoint | src/org.xtuml.bp.als/arc/extract_function_bodies.arc | [
"Apache-2.0"
] |
<VirtualHost *>
ServerName dekimobile
ErrorLog /var/log/apache2/error-dekimobile.log
CustomLog /var/log/apache2/access-dekimobile.log common
DocumentRoot "/var/www/dekiwiki/dekimobile"
RewriteEngine On
RewriteCond %{REQUEST_URI} ^/$
RewriteRule ^/$ /index.php?title= [L,QSA,NE]
RewriteCond %{REQUEST_URI} !^/(@api|assets|/deki)/
RewriteCond %{REQUEST_URI} !^/([a-zA-Z0-9]+).php
RewriteCond %{REQUEST_URI} !^/error/(.*)\.var$
RewriteCond %{REQUEST_URI} !^/favicon\.ico$
RewriteCond %{REQUEST_URI} !^/robots\.txt$
RewriteRule ^/(.*)$ /page.php?title=$1 [L,QSA,NE]
# deki-api uses encoded slashes in query parameters so AllowEncodedSlashes must be On
AllowEncodedSlashes On
# FIXME:
# Some php flags we need. These are only needed until all
# the short php open tags are changed to long in the source code.
php_flag short_open_tag on
# Allow short open tags and turn off E_NOTICE messages
php_value error_reporting "E_ALL & ~E_NOTICE"
# Setting php memory parameters
# php_value memory_limit "128M"
# php_value post_max_size "64M"
# php_value upload_max_filesize "64M"
# mod_proxy rules
ProxyPass /@api http://localhost:8081 retry=1
ProxyPassReverse /@api http://localhost:8081
SetEnv force-proxy-request-1.0 1
SetEnv proxy-nokeepalive 1
<Proxy *>
AddDefaultCharset off
Order deny,allow
Deny from all
Allow from all
</Proxy>
</VirtualHost>
<Directory "/var/www/dekiwiki">
# Possible values for the Options directive are "None", "All",
# or any combination of:
# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
#
# Note that "MultiViews" must be named *explicitly* --- "Options All"
# doesn't give it to you.
#
# The Options directive is both complicated and important. Please see
# http://httpd.apache.org/docs-2.2/mod/core.html#options
# for more information.
Options None
# AllowOverride controls what directives may be placed in .htaccess files.
# It can be "All", "None", or any combination of the keywords:
# Options FileInfo AuthConfig Limit
AllowOverride All
# Controls who can get stuff from this server.
Order allow,deny
Allow from all
</Directory>
| ApacheConf | 4 | ChrisHagan/metl2011 | ThumbService/ThumbService/lib/MindTouch_Core_10.0.1_Source/src/tools/dekimobile/app/dekimobile.vhost | [
"Apache-2.0"
] |
-- @shouldWarnWith UnusedExplicitImport
module Main where
import Prelude (Unit, unit, pure)
import Effect (Effect)
import Lib (type (~>), natId)
main :: Effect Unit
main = natId (pure unit)
| PureScript | 4 | andys8/purescript | tests/purs/warning/UnusedExplicitImportTypeOp.purs | [
"BSD-3-Clause"
] |
globals [
notes
notes_allowed
]
extensions [
sound
array
]
turtles-own [
turtle_tone ;; the tone that the turtle represents
other_tone ;; the tone that the collapsing turtle represents
speed
do_something ;; whether this turtle should play a sound
id
]
to setup
clear-all
setup-notes
end
to setup-notes
set notes array:from-list ["C" "C#" "D" "D#" "E" "F" "F#" "G" "G#" "A" "A#" "B"]
set-default-shape turtles "music notes 2"
let i 0 ;; the note that the turtle represents
let agent_id 0 ;; the id of the agent
crt number_of_notes [
set speed (random-float 0.5) + 0.5
set shape "music notes 2"
set color blue
set size 2
set do_something true
setxy random-xcor random-ycor
set heading random 360
set id agent_id
set agent_id (agent_id + 1)
set label array:item notes i
ifelse (i = 11) [ set i 0 ] [ set i (i + 1) ]
]
end
to go
ask turtles [
if count turtles-here > 1 [
collapse
set heading random 360
]
fd speed
]
tick
end
to collapse
;; only play chords, so only play if the
let other_agent turtles-here
let num_notes array:from-list []
;; 0 = C, 1 = C#, 2 = D, 3 = D#, 4 = E, 5 = F, 6 = F#, 7 = G, 8 = G#, 9 = A, 10 = A#, 11 = B, 12 = C
ifelse only_chords
[ set num_notes array:from-list [0 4 7 12 16 19 24] ] ; only the notes in a chord
[ set num_notes array:from-list [0 2 4 5 7 9 11 12 16] ] ; all the tones in a toonladder
;; if sadness = 100, there is a 100% change that all the notes that can be sad will be sad.
if sadness >= 20 [
ifelse only_chords [ array:set num_notes 1 3 ]
[ array:set num_notes 2 3 ]
] if sadness >= 40 [
ifelse only_chords [ set num_notes array:from-list [0 3 7 10 12 16 19 24] ]
[ array:set num_notes 8 15 ]
] if sadness >= 60 [
if only_chords [ array:set num_notes 5 15 ]
] if sadness >= 80 [
ifelse only_chords [ array:set num_notes 7 22 ]
[ array:set num_notes 6 10]
]
ifelse one_note_at_a_time
[ sound:stop-music
sound:start-note instrument tone + (array:item num_notes (random (array:length num_notes))) 64 ]
[ sound:play-note instrument tone + (array:item num_notes (random (array:length num_notes))) 64 random-float 1 ]
end
to kill_sounds
sound:stop-music
end
to test_sound
;;foreach [60 64 67 69 70 69 67 64] [
;; sound:start-note instrument ? 65
;; wait 0.3
;; sound:stop-note instrument ?
;;]
sound:play-note instrument 63 64 1
sound:play-note instrument 67 64 1
end
@#$#@#$#@
GRAPHICS-WINDOW
271
10
944
574
25
20
13.0
1
15
1
1
1
0
1
1
1
-25
25
-20
20
0
0
1
ticks
BUTTON
9
10
127
61
NIL
setup
NIL
1
T
OBSERVER
NIL
O
NIL
NIL
BUTTON
141
10
258
61
NIL
go
T
1
T
OBSERVER
NIL
NIL
NIL
NIL
INPUTBOX
10
124
257
184
number_of_notes
20
1
0
Number
SWITCH
10
388
253
421
one_note_at_a_time
one_note_at_a_time
1
1
-1000
CHOOSER
11
188
257
233
instrument
instrument
"Trumpet" "Banjo" "Jazz Electric Guitar" "Nylon String Guitar" "Acoustic Bass" "Steel Drums" "Violin" "Tuba" "Bird Tweet" "Acoustic Grand Piano" "Clavi"
9
BUTTON
141
73
258
106
all sounds off
kill_sounds
NIL
1
T
OBSERVER
NIL
NIL
NIL
NIL
BUTTON
10
72
127
105
test sound
test_sound
NIL
1
T
OBSERVER
NIL
NIL
NIL
NIL
SLIDER
11
312
256
345
tone
tone
0
100
54
1
1
NIL
HORIZONTAL
SWITCH
9
428
252
461
only_chords
only_chords
1
1
-1000
SLIDER
10
273
256
306
sadness
sadness
0
100
100
1
1
NIL
HORIZONTAL
@#$#@#$#@
WHAT IS IT?
-----------
This section could give a general understanding of what the model is trying to show or explain.
HOW IT WORKS
------------
This section could explain what rules the agents use to create the overall behavior of the model.
HOW TO USE IT
-------------
This section could explain how to use the model, including a description of each of the items in the interface tab.
THINGS TO NOTICE
----------------
This section could give some ideas of things for the user to notice while running the model.
THINGS TO TRY
-------------
This section could give some ideas of things for the user to try to do (move sliders, switches, etc.) with the model.
EXTENDING THE MODEL
-------------------
This section could give some ideas of things to add or change in the procedures tab to make the model more complicated, detailed, accurate, etc.
NETLOGO FEATURES
----------------
This section could point out any especially interesting or unusual features of NetLogo that the model makes use of, particularly in the Procedures tab. It might also point out places where workarounds were needed because of missing features.
RELATED MODELS
--------------
This section could give the names of models in the NetLogo Models Library or elsewhere which are of related interest.
CREDITS AND REFERENCES
----------------------
This section could contain a reference to the model's URL on the web if it has one, as well as any other necessary credits or references.
@#$#@#$#@
default
true
0
Polygon -7500403 true true 150 5 40 250 150 205 260 250
airplane
true
0
Polygon -7500403 true true 150 0 135 15 120 60 120 105 15 165 15 195 120 180 135 240 105 270 120 285 150 270 180 285 210 270 165 240 180 180 285 195 285 165 180 105 180 60 165 15
arrow
true
0
Polygon -7500403 true true 150 0 0 150 105 150 105 293 195 293 195 150 300 150
box
false
0
Polygon -7500403 true true 150 285 285 225 285 75 150 135
Polygon -7500403 true true 150 135 15 75 150 15 285 75
Polygon -7500403 true true 15 75 15 225 150 285 150 135
Line -16777216 false 150 285 150 135
Line -16777216 false 150 135 15 75
Line -16777216 false 150 135 285 75
bug
true
0
Circle -7500403 true true 96 182 108
Circle -7500403 true true 110 127 80
Circle -7500403 true true 110 75 80
Line -7500403 true 150 100 80 30
Line -7500403 true 150 100 220 30
butterfly
true
0
Polygon -7500403 true true 150 165 209 199 225 225 225 255 195 270 165 255 150 240
Polygon -7500403 true true 150 165 89 198 75 225 75 255 105 270 135 255 150 240
Polygon -7500403 true true 139 148 100 105 55 90 25 90 10 105 10 135 25 180 40 195 85 194 139 163
Polygon -7500403 true true 162 150 200 105 245 90 275 90 290 105 290 135 275 180 260 195 215 195 162 165
Polygon -16777216 true false 150 255 135 225 120 150 135 120 150 105 165 120 180 150 165 225
Circle -16777216 true false 135 90 30
Line -16777216 false 150 105 195 60
Line -16777216 false 150 105 105 60
car
false
0
Polygon -7500403 true true 300 180 279 164 261 144 240 135 226 132 213 106 203 84 185 63 159 50 135 50 75 60 0 150 0 165 0 225 300 225 300 180
Circle -16777216 true false 180 180 90
Circle -16777216 true false 30 180 90
Polygon -16777216 true false 162 80 132 78 134 135 209 135 194 105 189 96 180 89
Circle -7500403 true true 47 195 58
Circle -7500403 true true 195 195 58
circle
false
0
Circle -7500403 true true 0 0 300
circle 2
false
0
Circle -7500403 true true 0 0 300
Circle -16777216 true false 30 30 240
cow
false
0
Polygon -7500403 true true 200 193 197 249 179 249 177 196 166 187 140 189 93 191 78 179 72 211 49 209 48 181 37 149 25 120 25 89 45 72 103 84 179 75 198 76 252 64 272 81 293 103 285 121 255 121 242 118 224 167
Polygon -7500403 true true 73 210 86 251 62 249 48 208
Polygon -7500403 true true 25 114 16 195 9 204 23 213 25 200 39 123
cylinder
false
0
Circle -7500403 true true 0 0 300
dot
false
0
Circle -7500403 true true 90 90 120
face happy
false
0
Circle -7500403 true true 8 8 285
Circle -16777216 true false 60 75 60
Circle -16777216 true false 180 75 60
Polygon -16777216 true false 150 255 90 239 62 213 47 191 67 179 90 203 109 218 150 225 192 218 210 203 227 181 251 194 236 217 212 240
face neutral
false
0
Circle -7500403 true true 8 7 285
Circle -16777216 true false 60 75 60
Circle -16777216 true false 180 75 60
Rectangle -16777216 true false 60 195 240 225
face sad
false
0
Circle -7500403 true true 8 8 285
Circle -16777216 true false 60 75 60
Circle -16777216 true false 180 75 60
Polygon -16777216 true false 150 168 90 184 62 210 47 232 67 244 90 220 109 205 150 198 192 205 210 220 227 242 251 229 236 206 212 183
fish
false
0
Polygon -1 true false 44 131 21 87 15 86 0 120 15 150 0 180 13 214 20 212 45 166
Polygon -1 true false 135 195 119 235 95 218 76 210 46 204 60 165
Polygon -1 true false 75 45 83 77 71 103 86 114 166 78 135 60
Polygon -7500403 true true 30 136 151 77 226 81 280 119 292 146 292 160 287 170 270 195 195 210 151 212 30 166
Circle -16777216 true false 215 106 30
flag
false
0
Rectangle -7500403 true true 60 15 75 300
Polygon -7500403 true true 90 150 270 90 90 30
Line -7500403 true 75 135 90 135
Line -7500403 true 75 45 90 45
flower
false
0
Polygon -10899396 true false 135 120 165 165 180 210 180 240 150 300 165 300 195 240 195 195 165 135
Circle -7500403 true true 85 132 38
Circle -7500403 true true 130 147 38
Circle -7500403 true true 192 85 38
Circle -7500403 true true 85 40 38
Circle -7500403 true true 177 40 38
Circle -7500403 true true 177 132 38
Circle -7500403 true true 70 85 38
Circle -7500403 true true 130 25 38
Circle -7500403 true true 96 51 108
Circle -16777216 true false 113 68 74
Polygon -10899396 true false 189 233 219 188 249 173 279 188 234 218
Polygon -10899396 true false 180 255 150 210 105 210 75 240 135 240
house
false
0
Rectangle -7500403 true true 45 120 255 285
Rectangle -16777216 true false 120 210 180 285
Polygon -7500403 true true 15 120 150 15 285 120
Line -16777216 false 30 120 270 120
leaf
false
0
Polygon -7500403 true true 150 210 135 195 120 210 60 210 30 195 60 180 60 165 15 135 30 120 15 105 40 104 45 90 60 90 90 105 105 120 120 120 105 60 120 60 135 30 150 15 165 30 180 60 195 60 180 120 195 120 210 105 240 90 255 90 263 104 285 105 270 120 285 135 240 165 240 180 270 195 240 210 180 210 165 195
Polygon -7500403 true true 135 195 135 240 120 255 105 255 105 285 135 285 165 240 165 195
line
true
0
Line -7500403 true 150 0 150 300
line half
true
0
Line -7500403 true 150 0 150 150
music notes 1
false
0
Polygon -7500403 true true 75 210 96 212 118 218 131 229 135 238 135 243 131 251 118 261 96 268 75 270 55 268 33 262 19 251 15 242 15 238 19 229 33 218 54 212
Rectangle -7500403 true true 120 90 135 255
Polygon -7500403 true true 225 165 246 167 268 173 281 184 285 193 285 198 281 206 268 216 246 223 225 225 205 223 183 217 169 206 165 197 165 193 169 184 183 173 204 167
Polygon -7500403 true true 120 60 120 105 285 45 285 0
Rectangle -7500403 true true 270 15 285 195
music notes 2
false
0
Polygon -7500403 true true 135 195 156 197 178 203 191 214 195 223 195 228 191 236 178 246 156 253 135 255 115 253 93 247 79 236 75 227 75 223 79 214 93 203 114 197
Rectangle -7500403 true true 180 30 195 225
music notes 3
false
0
Polygon -7500403 true true 135 195 156 197 178 203 191 214 195 223 195 228 191 236 178 246 156 253 135 255 115 253 93 247 79 236 75 227 75 223 79 214 93 203 114 197
Rectangle -7500403 true true 180 30 195 225
Polygon -7500403 true true 194 66 210 80 242 93 271 94 293 84 301 68 269 69 238 60 213 46 197 34 193 30
pentagon
false
0
Polygon -7500403 true true 150 15 15 120 60 285 240 285 285 120
person
false
0
Circle -7500403 true true 110 5 80
Polygon -7500403 true true 105 90 120 195 90 285 105 300 135 300 150 225 165 300 195 300 210 285 180 195 195 90
Rectangle -7500403 true true 127 79 172 94
Polygon -7500403 true true 195 90 240 150 225 180 165 105
Polygon -7500403 true true 105 90 60 150 75 180 135 105
plant
false
0
Rectangle -7500403 true true 135 90 165 300
Polygon -7500403 true true 135 255 90 210 45 195 75 255 135 285
Polygon -7500403 true true 165 255 210 210 255 195 225 255 165 285
Polygon -7500403 true true 135 180 90 135 45 120 75 180 135 210
Polygon -7500403 true true 165 180 165 210 225 180 255 120 210 135
Polygon -7500403 true true 135 105 90 60 45 45 75 105 135 135
Polygon -7500403 true true 165 105 165 135 225 105 255 45 210 60
Polygon -7500403 true true 135 90 120 45 150 15 180 45 165 90
square
false
0
Rectangle -7500403 true true 30 30 270 270
square 2
false
0
Rectangle -7500403 true true 30 30 270 270
Rectangle -16777216 true false 60 60 240 240
star
false
0
Polygon -7500403 true true 151 1 185 108 298 108 207 175 242 282 151 216 59 282 94 175 3 108 116 108
target
false
0
Circle -7500403 true true 0 0 300
Circle -16777216 true false 30 30 240
Circle -7500403 true true 60 60 180
Circle -16777216 true false 90 90 120
Circle -7500403 true true 120 120 60
tree
false
0
Circle -7500403 true true 118 3 94
Rectangle -6459832 true false 120 195 180 300
Circle -7500403 true true 65 21 108
Circle -7500403 true true 116 41 127
Circle -7500403 true true 45 90 120
Circle -7500403 true true 104 74 152
triangle
false
0
Polygon -7500403 true true 150 30 15 255 285 255
triangle 2
false
0
Polygon -7500403 true true 150 30 15 255 285 255
Polygon -16777216 true false 151 99 225 223 75 224
truck
false
0
Rectangle -7500403 true true 4 45 195 187
Polygon -7500403 true true 296 193 296 150 259 134 244 104 208 104 207 194
Rectangle -1 true false 195 60 195 105
Polygon -16777216 true false 238 112 252 141 219 141 218 112
Circle -16777216 true false 234 174 42
Rectangle -7500403 true true 181 185 214 194
Circle -16777216 true false 144 174 42
Circle -16777216 true false 24 174 42
Circle -7500403 false true 24 174 42
Circle -7500403 false true 144 174 42
Circle -7500403 false true 234 174 42
turtle
true
0
Polygon -10899396 true false 215 204 240 233 246 254 228 266 215 252 193 210
Polygon -10899396 true false 195 90 225 75 245 75 260 89 269 108 261 124 240 105 225 105 210 105
Polygon -10899396 true false 105 90 75 75 55 75 40 89 31 108 39 124 60 105 75 105 90 105
Polygon -10899396 true false 132 85 134 64 107 51 108 17 150 2 192 18 192 52 169 65 172 87
Polygon -10899396 true false 85 204 60 233 54 254 72 266 85 252 107 210
Polygon -7500403 true true 119 75 179 75 209 101 224 135 220 225 175 261 128 261 81 224 74 135 88 99
wheel
false
0
Circle -7500403 true true 3 3 294
Circle -16777216 true false 30 30 240
Line -7500403 true 150 285 150 15
Line -7500403 true 15 150 285 150
Circle -7500403 true true 120 120 60
Line -7500403 true 216 40 79 269
Line -7500403 true 40 84 269 221
Line -7500403 true 40 216 269 79
Line -7500403 true 84 40 221 269
x
false
0
Polygon -7500403 true true 270 75 225 30 30 225 75 270
Polygon -7500403 true true 30 75 75 30 270 225 225 270
@#$#@#$#@
NetLogo 4.1RC5
@#$#@#$#@
@#$#@#$#@
@#$#@#$#@
@#$#@#$#@
@#$#@#$#@
default
0.0
-0.2 0 0.0 1.0
0.0 1 1.0 0.0
0.2 0 0.0 1.0
link direction
true
0
Line -7500403 true 150 150 90 180
Line -7500403 true 150 150 210 180
@#$#@#$#@
0
@#$#@#$#@
| NetLogo | 5 | ajnavarro/language-dataset | data/github.com/marcvanzee/music-generator/3499f7177daf7df4dd1b234d345f8f48f2ec4ea5/notes.nlogo | [
"MIT"
] |
#include "caffe2/core/context_gpu.h"
#include "caffe2/operators/im2col_op.h"
namespace caffe2 {
REGISTER_CUDA_OPERATOR(Im2Col, Im2ColOp<float, CUDAContext>);
REGISTER_CUDA_OPERATOR(Col2Im, Col2ImOp<float, CUDAContext>);
} // namespace caffe2
| C++ | 3 | Hacky-DH/pytorch | caffe2/operators/im2col_op_gpu.cc | [
"Intel"
] |
# Check the handling of timestamps on output files.
# Check that a command which overwrites one of its inputs before its output is
# only run once. This happens for the 'LLVMBuild.cmake' part of the LLVM
# generator step, for example.
#
# RUN: rm -rf %t.build
# RUN: mkdir -p %t.build
# RUN: cp %s %t.build/build.ninja
# RUN: touch %t.build/input
# RUN: %{llbuild} ninja build --chdir %t.build &> %t1.out
# RUN: %{FileCheck} --check-prefix CHECK-FIRST --input-file %t1.out %s
# CHECK-FIRST: [1/{{.*}}] GENERATOR
#
# RUN: %{llbuild} ninja build --chdir %t.build &> %t2.out
# RUN: %{FileCheck} --check-prefix CHECK-SECOND --input-file %t2.out %s
# CHECK-SECOND-NOT: GENERATOR
# We use `touch -r ...` here to ensure a timestamp on the input which is strictly
# older than the output.
rule GENERATOR
command = date >> input && touch -r / input && date >> output
description = GENERATOR
build output: GENERATOR input
| Ninja | 5 | trombonehero/swift-llbuild | tests/Ninja/Build/output-timestamps.ninja | [
"Apache-2.0"
] |
/*
* Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/*
* DES low level APIs are deprecated for public use, but still ok for internal
* use.
*/
#include "internal/deprecated.h"
#include "e_os.h"
#include "des_local.h"
#include <assert.h>
/*
* The input and output are loaded in multiples of 8 bits. What this means is
* that if you hame numbits=12 and length=2 the first 12 bits will be
* retrieved from the first byte and half the second. The second 12 bits
* will come from the 3rd and half the 4th byte.
*/
/*
* Until Aug 1 2003 this function did not correctly implement CFB-r, so it
* will not be compatible with any encryption prior to that date. Ben.
*/
void DES_cfb_encrypt(const unsigned char *in, unsigned char *out, int numbits,
long length, DES_key_schedule *schedule,
DES_cblock *ivec, int enc)
{
register DES_LONG d0, d1, v0, v1;
register unsigned long l = length;
register int num = numbits / 8, n = (numbits + 7) / 8, i, rem =
numbits % 8;
DES_LONG ti[2];
unsigned char *iv;
#ifndef L_ENDIAN
unsigned char ovec[16];
#else
unsigned int sh[4];
unsigned char *ovec = (unsigned char *)sh;
/* I kind of count that compiler optimizes away this assertion, */
assert(sizeof(sh[0]) == 4); /* as this holds true for all, */
/* but 16-bit platforms... */
#endif
if (numbits <= 0 || numbits > 64)
return;
iv = &(*ivec)[0];
c2l(iv, v0);
c2l(iv, v1);
if (enc) {
while (l >= (unsigned long)n) {
l -= n;
ti[0] = v0;
ti[1] = v1;
DES_encrypt1((DES_LONG *)ti, schedule, DES_ENCRYPT);
c2ln(in, d0, d1, n);
in += n;
d0 ^= ti[0];
d1 ^= ti[1];
l2cn(d0, d1, out, n);
out += n;
/*
* 30-08-94 - eay - changed because l>>32 and l<<32 are bad under
* gcc :-(
*/
if (numbits == 32) {
v0 = v1;
v1 = d0;
} else if (numbits == 64) {
v0 = d0;
v1 = d1;
} else {
#ifndef L_ENDIAN
iv = &ovec[0];
l2c(v0, iv);
l2c(v1, iv);
l2c(d0, iv);
l2c(d1, iv);
#else
sh[0] = v0, sh[1] = v1, sh[2] = d0, sh[3] = d1;
#endif
if (rem == 0)
memmove(ovec, ovec + num, 8);
else
for (i = 0; i < 8; ++i)
ovec[i] = ovec[i + num] << rem |
ovec[i + num + 1] >> (8 - rem);
#ifdef L_ENDIAN
v0 = sh[0], v1 = sh[1];
#else
iv = &ovec[0];
c2l(iv, v0);
c2l(iv, v1);
#endif
}
}
} else {
while (l >= (unsigned long)n) {
l -= n;
ti[0] = v0;
ti[1] = v1;
DES_encrypt1((DES_LONG *)ti, schedule, DES_ENCRYPT);
c2ln(in, d0, d1, n);
in += n;
/*
* 30-08-94 - eay - changed because l>>32 and l<<32 are bad under
* gcc :-(
*/
if (numbits == 32) {
v0 = v1;
v1 = d0;
} else if (numbits == 64) {
v0 = d0;
v1 = d1;
} else {
#ifndef L_ENDIAN
iv = &ovec[0];
l2c(v0, iv);
l2c(v1, iv);
l2c(d0, iv);
l2c(d1, iv);
#else
sh[0] = v0, sh[1] = v1, sh[2] = d0, sh[3] = d1;
#endif
if (rem == 0)
memmove(ovec, ovec + num, 8);
else
for (i = 0; i < 8; ++i)
ovec[i] = ovec[i + num] << rem |
ovec[i + num + 1] >> (8 - rem);
#ifdef L_ENDIAN
v0 = sh[0], v1 = sh[1];
#else
iv = &ovec[0];
c2l(iv, v0);
c2l(iv, v1);
#endif
}
d0 ^= ti[0];
d1 ^= ti[1];
l2cn(d0, d1, out, n);
out += n;
}
}
iv = &(*ivec)[0];
l2c(v0, iv);
l2c(v1, iv);
v0 = v1 = d0 = d1 = ti[0] = ti[1] = 0;
}
| C | 3 | pmesnier/openssl | crypto/des/cfb_enc.c | [
"Apache-2.0"
] |
Rebol [
title: "Needs module test 3"
name: test-needs-url
needs: https://github.com/Oldes/Rebol3/raw/master/src/tests/units/files/test-needs-url-value.reb
]
export test-needs-url-result: (42 = test-needs-url-value)
| Rebol | 3 | 0branch/r3 | src/tests/units/files/test-needs-url.reb | [
"Apache-2.0"
] |
// build-pass
#![crate_type = "lib"]
#![allow(unconditional_panic)]
struct S(u8);
pub fn ice() {
S([][0]);
}
| Rust | 1 | Eric-Arellano/rust | src/test/ui/issues/issue-53275.rs | [
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] |
--TEST--
Bug #71127 (Define in auto_prepend_file is overwrite)
--INI--
opcache.enable=1
opcache.enable_cli=1
opcache.optimization_level=0x7FFFBFFF
--EXTENSIONS--
opcache
--FILE--
<?php
$file = __DIR__ . "/bug71127.inc";
file_put_contents($file, "<?php define('FOO', 'bad'); echo FOO;?>");
define("FOO", "okey");
include($file);
?>
--CLEAN--
<?php
@unlink(__DIR__ . "/bug71127.inc");
?>
--EXPECTF--
Warning: Constant FOO already defined in %sbug71127.inc on line %d
okey
| PHP | 3 | NathanFreeman/php-src | ext/opcache/tests/bug71127.phpt | [
"PHP-3.01"
] |
/*
* Copyright (C) 2012 Michael Niedermayer (michaelni@gmx.at)
*
* This file is part of libswresample
*
* libswresample is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* libswresample is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with libswresample; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "libavutil/x86/cpu.h"
#include "libswresample/swresample_internal.h"
#define D(type, simd) \
mix_1_1_func_type ff_mix_1_1_a_## type ## _ ## simd;\
mix_2_1_func_type ff_mix_2_1_a_## type ## _ ## simd;
D(float, sse)
D(float, avx)
D(int16, mmx)
D(int16, sse2)
av_cold int swri_rematrix_init_x86(struct SwrContext *s){
#if HAVE_X86ASM
int mm_flags = av_get_cpu_flags();
int nb_in = s->used_ch_count;
int nb_out = s->out.ch_count;
int num = nb_in * nb_out;
int i,j;
s->mix_1_1_simd = NULL;
s->mix_2_1_simd = NULL;
if (s->midbuf.fmt == AV_SAMPLE_FMT_S16P){
if(EXTERNAL_MMX(mm_flags)) {
s->mix_1_1_simd = ff_mix_1_1_a_int16_mmx;
s->mix_2_1_simd = ff_mix_2_1_a_int16_mmx;
}
if(EXTERNAL_SSE2(mm_flags)) {
s->mix_1_1_simd = ff_mix_1_1_a_int16_sse2;
s->mix_2_1_simd = ff_mix_2_1_a_int16_sse2;
}
s->native_simd_matrix = av_mallocz_array(num, 2 * sizeof(int16_t));
s->native_simd_one = av_mallocz(2 * sizeof(int16_t));
if (!s->native_simd_matrix || !s->native_simd_one)
return AVERROR(ENOMEM);
for(i=0; i<nb_out; i++){
int sh = 0;
for(j=0; j<nb_in; j++)
sh = FFMAX(sh, FFABS(((int*)s->native_matrix)[i * nb_in + j]));
sh = FFMAX(av_log2(sh) - 14, 0);
for(j=0; j<nb_in; j++) {
((int16_t*)s->native_simd_matrix)[2*(i * nb_in + j)+1] = 15 - sh;
((int16_t*)s->native_simd_matrix)[2*(i * nb_in + j)] =
((((int*)s->native_matrix)[i * nb_in + j]) + (1<<sh>>1)) >> sh;
}
}
((int16_t*)s->native_simd_one)[1] = 14;
((int16_t*)s->native_simd_one)[0] = 16384;
} else if(s->midbuf.fmt == AV_SAMPLE_FMT_FLTP){
if(EXTERNAL_SSE(mm_flags)) {
s->mix_1_1_simd = ff_mix_1_1_a_float_sse;
s->mix_2_1_simd = ff_mix_2_1_a_float_sse;
}
if(EXTERNAL_AVX_FAST(mm_flags)) {
s->mix_1_1_simd = ff_mix_1_1_a_float_avx;
s->mix_2_1_simd = ff_mix_2_1_a_float_avx;
}
s->native_simd_matrix = av_mallocz_array(num, sizeof(float));
s->native_simd_one = av_mallocz(sizeof(float));
if (!s->native_simd_matrix || !s->native_simd_one)
return AVERROR(ENOMEM);
memcpy(s->native_simd_matrix, s->native_matrix, num * sizeof(float));
memcpy(s->native_simd_one, s->native_one, sizeof(float));
}
#endif
return 0;
}
| C | 4 | attenuation/srs | trunk/3rdparty/ffmpeg-4-fit/libswresample/x86/rematrix_init.c | [
"MIT"
] |
exec("swigtest.start", -1);
NULL = SWIG_ptr(0);
p = new_Pop(NULL);
p = new_Pop(NULL, %T);
checkequal(Pop_hip(p, %T), 701, "Pop_hip(%T)");
checkequal(Pop_hip(p, NULL), 702, "Pop_hip(NULL)");
checkequal(Pop_hop(p, %T), 801, "Pop_hop(%T)");
checkequal(Pop_hop(p, NULL), 805, "Pop_hop(NULL)");
checkequal(Pop_pop(p, %T), 901, "Pop_pop(%T)");
checkequal(Pop_pop(p, NULL), 904, "Pop_pop(NULL)");
checkequal(Pop_pop(p), 905, "Pop_pop()");
checkequal(Pop_bop(p, NULL), 1001, "Pop_bop(NULL)");
checkequal(Pop_bip(p, NULL), 2002, "Pop_bip(%T)");
checkequal(muzak(%T), 3001, "muzak(%T)");
checkequal(muzak(NULL), 3002, "muzak(%T)");
exec("swigtest.quit", -1);
| Scilab | 2 | kyletanyag/LL-Smartcard | cacreader/swig-4.0.2/Examples/test-suite/scilab/overload_complicated_runme.sci | [
"BSD-3-Clause"
] |
// revisions: rust2015 rust2018
//[rust2018] edition:2018
trait WithType<T> {}
trait WithRegion<'a> { }
struct Foo<T> {
t: T
}
impl<T> Foo<T>
where
T: WithRegion<'_>
//[rust2015,rust2018]~^ ERROR `'_` cannot be used here
{ }
fn main() {}
| Rust | 4 | Eric-Arellano/rust | src/test/ui/underscore-lifetime/where-clause-inherent-impl-underscore.rs | [
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] |
export const message = "Hello Chunk";
| JavaScript | 0 | 1shenxi/webpack | test/statsCases/output-module/chunk.js | [
"MIT"
] |
/* Copyright 2019 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.
==============================================================================*/
#ifndef TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_RPC_EAGER_GRPC_EAGER_SERVICE_H_
#define TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_RPC_EAGER_GRPC_EAGER_SERVICE_H_
#include "tensorflow/core/protobuf/eager_service.grpc.pb.h"
#include "tensorflow/stream_executor/platform/port.h"
#ifndef PLATFORM_GOOGLE
namespace tensorflow {
namespace eager {
namespace grpc {
// Google internal gRPC generates services under namespace "grpc", but
// opensource version does not add any additional namespaces.
// We currently use proto_library BUILD rule with cc_grpc_version and
// has_services arguments. This rule is deprecated but we can't cleanly migrate
// to cc_grpc_library rule yet. The internal version takes service_namespace
// argument, which would have solved the namespace issue, but the external one
// does not.
//
// Creating aliases here to make sure we can access services under namespace
// "tensorflow::grpc" both in google internal and open-source.
using ::tensorflow::eager::EagerService;
} // namespace grpc
} // namespace eager
} // namespace tensorflow
#endif // PLATFORM_GOOGLE
#endif // TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_RPC_EAGER_GRPC_EAGER_SERVICE_H_
| C | 4 | abhaikollara/tensorflow | tensorflow/core/distributed_runtime/rpc/eager/grpc_eager_service.h | [
"Apache-2.0"
] |
POST /two_chunks_mult_zero_end HTTP/1.1\r\n
Transfer-Encoding: chunked\r\n
\r\n
5\r\n
hello\r\n
6\r\n
world\r\n
000\r\n
\r\n
GET /second HTTP/1.1\r\n
\r\n | HTTP | 1 | ashishmjn/gunicorn | tests/requests/valid/023.http | [
"MIT"
] |
for $i in //Illustration
return string-join(($i/ancestor::PAGE/@number, $i/@HPOS, $i/@VPOS, $i/@WIDTH, $i/@HEIGHT), ',') | XQuery | 3 | ithaka/grobid | grobid-core/src/main/resources/xq/figure-coords-pdfalto.xq | [
"Apache-2.0"
] |
/*
* This software is Copyright (c) 2016 Denis Burykin
* [denis_burykin yahoo com], [denis-burykin2014 yandex ru]
* and it is hereby released to the general public under the following terms:
* Redistribution and use in source and binary forms, with or without
* modification, are permitted.
*
*/
// Extra stage suggested if BRAM is used.
localparam EXTRA_REGISTER_STAGE = 1;
localparam OP_STATE_READY = 0,
OP_STATE_START = 1,
OP_STATE_EXTRA_STAGE = 2,
OP_STATE_NEXT_CHAR = 3,
OP_STATE_NEXT_WORD = 4,
OP_STATE_DONE = 5;
| SystemVerilog | 2 | bourbon-hunter/OSCPRepo | Tools/JohnTheRipper-bleeding-jumbo/src/ztex/fpga-descrypt/pkt_comm/word_gen.vh | [
"MIT"
] |
[a|b]{} | CSS | 0 | kitsonk/swc | css/parser/tests/fixture/esbuild/misc/TdBn3uBF54mw96CCUwpgew/input.css | [
"Apache-2.0",
"MIT"
] |
'reach 0.1';
export const main =
Reach.App(
{},
[ Participant('A', { getX: Fun([], UInt) }) ],
(A) => {
A.only(() => {
const x = declassify(interact.getX());
const y = declassify(interact.getX()); });
A.publish(x, y);
commit();
A.publish()
.timeout(x + y, () => {
A.publish();
commit();
exit(); });
commit();
exit();
});
| RenderScript | 3 | chikeabuah/reach-lang | hs/t/y/timeout_calc.rsh | [
"Apache-2.0"
] |
/*
* Copyright (c) 2020, Oracle and/or its affiliates. All rights reserved.
* Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl.
*/
function ret(a) { return a; }
function dub(a) { return a * 2; }
function inc(a) { return a + 1; }
function dec(a) { return a - 1; }
function call(f, v) { return f(v); }
function main() {
println(ret(42));
println(dub(21));
println(inc(41));
println(dec(43));
println(call(ret, 42));
println(call(dub, 21));
println(call(inc, 41));
println(call(dec, 43));
}
| Slash | 4 | guillermomolina/simplelanguage | language/tests/Call.sl | [
"UPL-1.0"
] |
/*
* Copyright (c) 2020 Intel Corporation
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
!ifndef LOG_NSH_
!define LOG_NSH_
!include "FileFunc.nsh"
!insertmacro GetTime
Var log
Var path
!macro OpenLog
GetFullPathName $path "."
${GetTime} "" "L" $0 $1 $2 $3 $4 $5 $6
IntCmp $4 9 0 0 +2
StrCpy $4 "0$4"
!ifdef INSTALL
StrCpy $R0 "install"
!else
StrCpy $R0 "uninstall"
!endif
StrCpy $log "haxm_$R0-$2$1$0_$4$5.log"
; The log file is created in the current folder rather than $TEMP directly
; because:
; 1. Can be easily found by silent_install.bat
; 2. Convert Unicode to ANSI format to save disk space while copying it
LogEx::Init true "$log"
!macroend
!define OpenLog `!insertmacro OpenLog`
!macro Log string
LogEx::Write '${string}'
!macroend
!define Log `!insertmacro Log`
!macro CloseLog
LogEx::Close
ExecWait 'cmd.exe /c type "$path\$log" > "$TEMP\$log"' $0
IfSilent +2 0
Delete "$path\$log"
!macroend
!define CloseLog `!insertmacro CloseLog`
!endif # LOG_NSH_
| NSIS | 4 | ryoon/haxm | Installer/Log.nsh | [
"BSD-3-Clause"
] |
a: int
def main() -> void begin
a = 5 + var
end
| Cycript | 0 | matheuspb/cython | examples/undeclared_variable.cy | [
"MIT"
] |
21,21
24,3A
3D,3D
40,5A
5F,5F
61,7A
7E,7E
| Component Pascal | 0 | janosch-x/character_set | lib/character_set/predefined_sets/url_path.cps | [
"MIT"
] |
{:deps {clojupyter/clojupyter {:mvn/version "0.3.2"}}}
| edn | 1 | siddhantk232/nixpkgs | pkgs/applications/editors/jupyter-kernels/clojupyter/deps.edn | [
"MIT"
] |
/**************************************************************************************************
* *
* This file is part of BLASFEO. *
* *
* BLASFEO -- BLAS For Embedded Optimization. *
* Copyright (C) 2019 by Gianluca Frison. *
* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. *
* All rights reserved. *
* *
* The 2-Clause BSD License *
* *
* Redistribution and use in source and binary forms, with or without *
* modification, are permitted provided that the following conditions are met: *
* *
* 1. Redistributions of source code must retain the above copyright notice, this *
* list of conditions and the following disclaimer. *
* 2. Redistributions in binary form must reproduce the above copyright notice, *
* this list of conditions and the following disclaimer in the documentation *
* and/or other materials provided with the distribution. *
* *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND *
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED *
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE *
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR *
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES *
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; *
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND *
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT *
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS *
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *
* *
* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de *
* *
**************************************************************************************************/
/*
* ----------- Naming conventions
*
* (precision)(data)
*
* 1) d(double)
* s(single)
*
* 2) ge(general)
* tr(triangular)
* vec(vector)
* row(row)
* col(column)
* dia(diagonal)
*
* 3) se(set)
* cp(copy)
* sc(scale)
* ad(add)
* tr(transpose)
* in(insert)
* ex(extract)
* pe(premute)
* sw(swap)
*
* f(factorization)
*
* lqf(LQ factorization)
* qrf (factorization)
* trf (LU factorization using partial pivoting with row interchanges.)
*
* 4) _l(lower) / _u(upper)
* _lib8 (hp implementation, 8 rows kernel)
* _lib4 (hp implementation, 4 rows kernel)
* _lib0 (hp interface with reference implentation)
* _lib (reference implementation)
* _libref (reference implementation with dedicated namespace)
*
* 5) _sp(sparse)
* _exp(exponential format)
*/
| C | 3 | shoes22/openpilot | third_party/acados/include/blasfeo/include/blasfeo_naming.h | [
"MIT"
] |
'use strict';
const chalk = require('chalk');
const Table = require('cli-table');
function percentChange(prev, current, prevSem, currentSem) {
const [mean, sd] = calculateMeanAndSdOfRatioFromDeltaMethod(
prev,
current,
prevSem,
currentSem
);
const pctChange = +(mean * 100).toFixed(1);
const ci95 = +(100 * 1.96 * sd).toFixed(1);
const ciInfo = ci95 > 0 ? ` +- ${ci95} %` : '';
const text = `${pctChange > 0 ? '+' : ''}${pctChange} %${ciInfo}`;
if (pctChange + ci95 < 0) {
return chalk.green(text);
} else if (pctChange - ci95 > 0) {
return chalk.red(text);
} else {
// Statistically insignificant.
return text;
}
}
function calculateMeanAndSdOfRatioFromDeltaMethod(
meanControl,
meanTest,
semControl,
semTest
) {
const mean =
(meanTest - meanControl) / meanControl -
(Math.pow(semControl, 2) * meanTest) / Math.pow(meanControl, 3);
const variance =
Math.pow(semTest / meanControl, 2) +
Math.pow(semControl * meanTest, 2) / Math.pow(meanControl, 4);
return [mean, Math.sqrt(variance)];
}
function addBenchmarkResults(table, localResults, remoteMasterResults) {
const benchmarks = Object.keys(
(localResults && localResults.benchmarks) ||
(remoteMasterResults && remoteMasterResults.benchmarks)
);
benchmarks.forEach(benchmark => {
const rowHeader = [chalk.white.bold(benchmark)];
if (remoteMasterResults) {
rowHeader.push(chalk.white.bold('Time'));
}
if (localResults) {
rowHeader.push(chalk.white.bold('Time'));
}
if (localResults && remoteMasterResults) {
rowHeader.push(chalk.white.bold('Diff'));
}
table.push(rowHeader);
const measurements =
(localResults && localResults.benchmarks[benchmark].averages) ||
(remoteMasterResults &&
remoteMasterResults.benchmarks[benchmark].averages);
measurements.forEach((measurement, i) => {
const row = [chalk.gray(measurement.entry)];
let remoteMean;
let remoteSem;
if (remoteMasterResults) {
remoteMean = remoteMasterResults.benchmarks[benchmark].averages[i].mean;
remoteSem = remoteMasterResults.benchmarks[benchmark].averages[i].sem;
// https://en.wikipedia.org/wiki/1.96 gives a 99% confidence interval.
const ci95 = remoteSem * 1.96;
row.push(
chalk.white(+remoteMean.toFixed(2) + ' ms +- ' + ci95.toFixed(2))
);
}
let localMean;
let localSem;
if (localResults) {
localMean = localResults.benchmarks[benchmark].averages[i].mean;
localSem = localResults.benchmarks[benchmark].averages[i].sem;
const ci95 = localSem * 1.96;
row.push(
chalk.white(+localMean.toFixed(2) + ' ms +- ' + ci95.toFixed(2))
);
}
if (localResults && remoteMasterResults) {
row.push(percentChange(remoteMean, localMean, remoteSem, localSem));
}
table.push(row);
});
});
}
function printResults(localResults, remoteMasterResults) {
const head = [''];
if (remoteMasterResults) {
head.push(chalk.yellow.bold('Remote (Merge Base)'));
}
if (localResults) {
head.push(chalk.green.bold('Local (Current Branch)'));
}
if (localResults && remoteMasterResults) {
head.push('');
}
const table = new Table({head});
addBenchmarkResults(table, localResults, remoteMasterResults);
console.log(table.toString());
}
module.exports = printResults;
| JavaScript | 4 | vegYY/react | scripts/bench/stats.js | [
"MIT"
] |
# flake8: noqa
import torch
from torch.testing._internal.common_utils import TEST_NUMPY
if TEST_NUMPY:
import numpy as np
# From the docs, there are quite a few ways to create a tensor:
# https://pytorch.org/docs/stable/tensors.html
# torch.tensor()
torch.tensor([[0.1, 1.2], [2.2, 3.1], [4.9, 5.2]])
torch.tensor([0, 1])
torch.tensor([[0.11111, 0.222222, 0.3333333]],
dtype=torch.float64,
device=torch.device('cuda:0'))
torch.tensor(3.14159)
# torch.sparse_coo_tensor
i = torch.tensor([[0, 1, 1],
[2, 0, 2]])
v = torch.tensor([3, 4, 5], dtype=torch.float32)
torch.sparse_coo_tensor(i, v, [2, 4])
torch.sparse_coo_tensor(i, v)
torch.sparse_coo_tensor(i, v, [2, 4],
dtype=torch.float64,
device=torch.device('cuda:0'))
torch.sparse_coo_tensor(torch.empty([1, 0]), [], [1])
torch.sparse_coo_tensor(torch.empty([1, 0]),
torch.empty([0, 2]), [1, 2])
# torch.as_tensor
a = [1, 2, 3]
torch.as_tensor(a)
torch.as_tensor(a, device=torch.device('cuda'))
# torch.as_strided
x = torch.randn(3, 3)
torch.as_strided(x, (2, 2), (1, 2))
torch.as_strided(x, (2, 2), (1, 2), 1)
# torch.from_numpy
if TEST_NUMPY:
torch.from_numpy(np.array([1, 2, 3]))
# torch.zeros/zeros_like
torch.zeros(2, 3)
torch.zeros((2, 3))
torch.zeros([2, 3])
torch.zeros(5)
torch.zeros_like(torch.empty(2, 3))
# torch.ones/ones_like
torch.ones(2, 3)
torch.ones((2, 3))
torch.ones([2, 3])
torch.ones(5)
torch.ones_like(torch.empty(2, 3))
# torch.arange
torch.arange(5)
torch.arange(1, 4)
torch.arange(1, 2.5, 0.5)
# torch.range
torch.range(1, 4)
torch.range(1, 4, 0.5)
# torch.linspace
torch.linspace(3, 10, steps=5)
torch.linspace(-10, 10, steps=5)
torch.linspace(start=-10, end=10, steps=5)
torch.linspace(start=-10, end=10, steps=1)
# torch.logspace
torch.logspace(start=-10, end=10, steps=5)
torch.logspace(start=0.1, end=1.0, steps=5)
torch.logspace(start=0.1, end=1.0, steps=1)
torch.logspace(start=2, end=2, steps=1, base=2)
# torch.eye
torch.eye(3)
# torch.empty/empty_like/empty_strided
torch.empty(2, 3)
torch.empty((2, 3))
torch.empty([2, 3])
torch.empty_like(torch.empty(2, 3), dtype=torch.int64)
torch.empty_strided((2, 3), (1, 2))
# torch.full/full_like
torch.full((2, 3), 3.141592)
torch.full_like(torch.full((2, 3), 3.141592), 2.71828)
# torch.quantize_per_tensor
torch.quantize_per_tensor(torch.tensor([-1.0, 0.0, 1.0, 2.0]), 0.1, 10, torch.quint8)
# torch.quantize_per_channel
x = torch.tensor([[-1.0, 0.0], [1.0, 2.0]])
quant = torch.quantize_per_channel(x, torch.tensor([0.1, 0.01]), torch.tensor([10, 0]), 0, torch.quint8)
# torch.dequantize
torch.dequantize(x)
# torch.complex
real = torch.tensor([1, 2], dtype=torch.float32)
imag = torch.tensor([3, 4], dtype=torch.float32)
torch.complex(real, imag)
# torch.polar
abs = torch.tensor([1, 2], dtype=torch.float64)
pi = torch.acos(torch.zeros(1)).item() * 2
angle = torch.tensor([pi / 2, 5 * pi / 4], dtype=torch.float64)
torch.polar(abs, angle)
# torch.heaviside
inp = torch.tensor([-1.5, 0, 2.0])
values = torch.tensor([0.5])
torch.heaviside(inp, values)
| Python | 4 | Hacky-DH/pytorch | test/typing/pass/creation_ops.py | [
"Intel"
] |
<div class="section">
<h2>Child of @Host() Component</h2>
<p>Flower emoji: {{flower.emoji}}</p>
</div>
| HTML | 2 | coreyscherbing/angular | aio/content/examples/resolution-modifiers/src/app/host-child/host-child.component.html | [
"MIT"
] |
i 00001 00 042 0000 00 022 0000
i 00002 00 27 00026 00 010 2000
i 00003 00 022 0000 00 012 2003
i 00004 00 27 00026 00 010 2007
i 00005 00 022 2004 00 012 2001
i 00006 00 27 00026 14 24 77720
i 00007 13 24 00060 17 24 02011
i 00010 00 010 2001 00 22 00000
i 00011 13 35 00012 00 010 0000
i 00012 00 000 2010 00 023 0000
i 00013 00 043 0013 17 012 0000
i 00014 00 27 00026 00 010 2010
i 00015 00 036 0077 00 043 0013
i 00016 00 011 2002 17 015 0000
i 00017 13 25 77777 14 37 00011
i 00020 00 010 0000 00 023 2000
i 00021 00 012 2000 00 27 00026
i 00022 16 24 01001 00 042 0016
i 00023 00 023 2000 00 031 0000
i 00024 00 012 2005 00 27 00026
i 00025 06 33 12345 00 22 00000
i 00026 02 33 76543 00 22 00000
d 02000 7777 7777 7777 7777
d 02001 0000 0000 0000 0001
d 02002 0000 0000 0000 0007
d 02003 0000 0000 0000 0060
d 02004 7777 7777 7777 7750
d 02005 0010 0000 0000 0000
d 02006 5252 5252 5252 5252
d 02007 2525 2525 2525 2525
| Octave | 1 | besm6/mesm6 | test/acx_anx/acx_anx.oct | [
"MIT"
] |
2016-03-25 04:07:51 - fs0ciety (~whoami@c27-253-43-52.thoms4.vic.optusnet.com.au) has joined #enigma-bbs
2016-03-25 04:07:51 Topic for #enigma-bbs is "ENiGMA½ BBS @ https://github.com/NuSkooler/enigma-bbs/ ~ xibalba.l33t.codes:44510"
2016-03-25 04:07:51 Topic set by NuSkooler (~NuSkooler@68.69.167.121) on Sun, 06 Dec 2015 09:15:55
2016-03-25 04:07:51 Channel #enigma-bbs: 6 nicks (2 ops, 0 voices, 4 normals)
2016-03-25 04:07:52 Channel created on Mon, 30 Nov 2015 09:57:52
2016-03-25 04:08:50 fs0ciety hi guys was looking at your bbs framework, i used to run an oblivion/2 and remoteaccess site back in the early 90s. anyway was wondering how easy would it to implement your bbs software imposed onto a html5 page rather ssh or telnet
2016-03-25 04:09:00 fs0ciety how easy or difficult would it be?
2016-03-25 04:12:15 nolageek There's something like ftelnet which is a telnet client that you can embed in a web page.
2016-03-25 04:13:57 fs0ciety nolageek, cheers - i wanted to essentially create a personal website but instead of using a minimalist static page gen or bloaty cms - i thought how about use a bbs framework :)
2016-03-25 04:16:01 nolageek well, the nature of BBSs is the dialing in .. you could have a web front end to the message areas, etc... but then you may as well just use a form.
2016-03-25 04:16:11 nolageek forum
2016-03-25 04:17:30 fs0ciety true, but i enjoy the asthetic of bbs's.. and essentially being nostalgic with the use of lightbars - i guess i could write something from scratch in nodejs - but this seems more fun. More so it will be a bunch punch of pages with some text regarding certain topics and then using the file section of the bbs for projects for people to download
2016-03-25 04:17:36 fs0ciety just a personal project site really
2016-03-25 04:18:26 nolageek If you want a website with the look of old text-based BBSes you could use the bootstrap.386 theme
2016-03-25 04:19:15 nolageek and there were (are?) some wordpress themes that use command line interfaces.
2016-03-25 04:22:56 nolageek synchronet has a decent web interface as well - https://electronicchicken.com/ for an example of the newest version that's still in development.
2016-03-25 04:24:25 fs0ciety checking it out
2016-03-25 04:24:40 fs0ciety i nearly discovered the commandline like templates you were talking about, but the creator removed his website
2016-03-25 04:30:47 nolageek pm2 lists main.js as errored
2016-03-25 04:35:45 nolageek reran 'npm install ' and I'm back up. :)
2016-03-25 05:05:34 nolageek Mercyful: does Obv/xrm compile on debian?
2016-03-25 05:06:19 Mercyful it will, it's not ready to run yet as it's still in early phases..
2016-03-25 05:07:02 nolageek yeah, I was just checking it out. gettng sqlite3 errors when compiling.
2016-03-25 05:07:25 nolageek ‘sqlite3_close_v2’ was not declared in this scope
2016-03-25 05:08:13 Mercyful ya i haven't done any recent update the linux make files in quite sometime.. but that weeoe for v2, means debian has an "older" versions of sqlite.. that would have to be update to a more recent version,, but nothing to worry about just yet.. ;)
2016-03-25 05:08:30 Mercyful weeoe = error.. hehe
2016-03-25 05:09:02 nolageek hehe
2016-03-25 05:09:51 nolageek what version is it loking for?
2016-03-25 05:13:30 Mercyful hmm from the sqlite3 change log,, at least.. 2012-09-03 (3.7.14) but of course even that is quite old.
2016-03-25 05:14:57 Mercyful the latest is: 2016-03-03 (3.11.1)
2016-03-25 05:17:01 nolageek looks like I've got 3.7.13
2016-03-25 05:17:22 nolageek Hmmm and 2.8 :)
2016-03-25 05:18:07 nolageek I wonder if daydream or enigma are using 2.8
2016-03-25 05:19:48 Mercyful ya, debian needs to update that trash and get into the mid centry on some packages.. hehe
2016-03-25 05:20:59 nolageek guess I could rename them and see what happens. heh
2016-03-25 05:25:54 nolageek ok, removed sqlite 2 and everyhing seems to still be working.
2016-03-25 05:30:44 Mercyful :)
2016-03-25 05:30:55 Mercyful mostl ikely they just call 3..
2016-03-25 05:32:06 nolageek I spoke too soon. But I think it's related to the update I ran. I rebooted and now getting connection issues with enigma again. Hmm.
2016-03-25 05:33:38 Mercyful hopefully he's be back tonight to help out..
2016-03-25 05:34:10 Mercyful i'm buckeling down trying to get the prompts, and login process going.. lots of little things..
2016-03-25 05:38:23 nolageek nevermind I was being stupid, it's working.
2016-03-25 05:40:26 @NuSkooler_ nolageek: Sorry was AFK for a bit - is it working now?
2016-03-25 05:40:46 @NuSkooler_ fs0ciety: You can create a menu bar'd / BBS looking website with just a CMS and some CSS
2016-03-25 05:40:56 @NuSkooler_ I can get you a few example URLs, sec
2016-03-25 05:41:28 @NuSkooler_ http://deadline.aegis-corp.org/
2016-03-25 05:44:23 @NuSkooler_ http://www.masswerk.at/googleBBS/
2016-03-25 05:47:46 nolageek deadline is pretty hot. I've never seem their site before.
2016-03-25 05:47:52 nolageek seen
2016-03-25 05:50:04 @NuSkooler_ Their PCBoard setup is pretty slick too
2016-03-25 05:50:21 @NuSkooler_ the board is pretty much dead, but stays online and it's pretty slick hehe
2016-03-25 05:50:30 nolageek hehe
2016-03-25 05:50:47 @NuSkooler_ Oh and https://jcs.org/notaweblog/2015/04/02/creating_a_bbs_in_2015/
2016-03-25 05:51:26 @NuSkooler_ nolageek: Lemme know what issues you run into - this stuff is likely buggy at this point. I havent' even migrated Xibalba over yet
2016-03-25 05:51:43 @NuSkooler_ I'll do that this weekened and be checking in any bug fixes I come up with hehe
2016-03-25 05:52:07 @NuSkooler_ Working on a official announcement, migration instructions, etc. as well
2016-03-25 05:52:11 @NuSkooler_ and docs docs docs haha
2016-03-25 05:53:23 nolageek No issues really, but I basically just re-installed the whole shebang.
2016-03-25 05:54:24 nolageek one thing I may not have noticed before, but I added more message areas this time around - is there a way to specify the display order of the message areas?
2016-03-25 05:55:41 @NuSkooler_ Hrm... currently they're sorted alphabetically... at least I think I put that in by the 'name'
2016-03-25 05:55:54 nolageek yep.
2016-03-25 05:56:04 @NuSkooler_ Throw a enhancement on github and I'll get to it. should be easy to do
2016-03-25 05:56:38 @NuSkooler_ will put in a 'sort' field or soemthing so you could do like sort: 1 ... sort: 2, etc.
2016-03-25 05:57:08 nolageek Yeah, I wanted all gaming subs together, entertainment, etc... guess you could put them in different groups
2016-03-25 05:58:29 @NuSkooler_ you could, but I think user-defined sort woudl be better
2016-03-25 05:58:53 @NuSkooler_ cuz groups get's complicated when you want to tie together foreign (e.g. AgoraNet) areas and such
2016-03-25 05:59:25 @NuSkooler_ adding the 'sort' key support is probably like a one line change
2016-03-25 05:59:38 @NuSkooler_ lemem find the code, you coudl test it easy (i'll have to wait till i'm home)
2016-03-25 06:00:20 @NuSkooler_ https://github.com/NuSkooler/enigma-bbs/blob/master/core/message_area.js#L100
2016-03-25 06:03:46 nolageek added
2016-03-25 06:04:19 @NuSkooler_ You could try this if you want it now: http://pastebin.com/BP8hjzk7
2016-03-25 06:04:45 @NuSkooler_ I think that's basically what I'd do... but fix the TODO for localeCompare and also do this for conf's
2016-03-25 06:04:51 nolageek what file is that in?
2016-03-25 06:04:54 nolageek oh, duh
2016-03-25 06:05:15 @NuSkooler_ it's untested but I think it should work :D If it fails you can just git checkout core/message_area.js to revert
2016-03-25 06:24:20 @NuSkooler_ Oh just saw above: That sqlite3_close_v2() is actually from newer versions of SQLite
2016-03-25 06:24:52 @NuSkooler_ it's intended to be used when binding via garbage collected languages/etc.; It "attempts" to close, but may not fully deallocate everything until all pending actions are complete
2016-03-25 06:25:05 @NuSkooler_ whereas sqlite3_close() returns "busy" if there is pending stuff
2016-03-25 06:26:17 nolageek and it didn't like the change to the message_area.js
2016-03-25 06:27:36 nolageek oh, I also had to run this after updating my system: nvm use --delete-prefix v4.3.1 --silent
2016-03-25 06:28:18 @NuSkooler_ What did the change do? crash?
2016-03-25 06:28:25 @NuSkooler_ or just not work
2016-03-25 06:28:33 nolageek my message areas weren't listed at all
2016-03-25 06:29:16 nolageek Hmm, trying to think if I restarted after making the change.
2016-03-25 06:29:39 nolageek this is what happens when I'm messing around with this stuff at work.
2016-03-25 06:29:41 nolageek hehe
2016-03-25 06:29:45 @NuSkooler_ could be needed stirng conversion, so: o.area.sort ? o.area.sort.toString() : o.area.name
2016-03-25 06:29:57 @NuSkooler_ yeah know how that goes...always a bazillion things going on hehe
2016-03-25 06:31:04 @NuSkooler_ or even: }), o => { return o.area.sort ? o.area.sort.toString() : o.area.name } );
2016-03-25 06:31:05 @NuSkooler_ to be safe
2016-03-25 06:31:06 @NuSkooler_ hehe
2016-03-25 06:31:20 @NuSkooler_ I'll mess with it tonight either way
2016-03-25 06:38:31 nolageek cool. looking great though.
2016-03-25 06:51:57 @NuSkooler_ Gonna try to smash out other major bugs and todo's that are not tied to big features next
2016-03-25 06:52:15 @NuSkooler_ then prob start on distributed network stuff and/or file base
2016-03-25 06:52:36 @NuSkooler_ unless someone else using this thing asks for something more important
2016-03-25 06:56:12 nolageek hehe
2016-03-25 06:56:31 nolageek I want to start working on some menus.
2016-03-25 06:56:36 nolageek also, how do I add doors?
2016-03-25 07:11:43 @NuSkooler_ nolageek: https://github.com/NuSkooler/enigma-bbs/blob/master/docs/doors.md
2016-03-25 07:12:03 @NuSkooler_ If there are parts there that don't make sense, I'll try and fix them up
2016-03-25 07:12:14 @NuSkooler_ If you're under Linux, I suggest DOSEMU for stuff
2016-03-25 07:21:27 nolageek excellent. thanks!
2016-03-25 07:57:11 @NuSkooler_ lemme know if it's not clear as mud hehehe
2016-03-25 13:59:18 nolageek sup
2016-03-25 14:47:53 @NuSkooler yo
2016-03-25 14:50:54 nolageek yo yo
2016-03-25 14:51:25 nolageek I cannot make up my mind how to re-structure my menus. Way over thinking it.
2016-03-25 14:53:17 nolageek some things are a given for the main menu - message area, doors, chat, email, settings.. but then I get to all of the other things... rumors, last callers, etc..
2016-03-25 15:02:19 @NuSkooler haha
2016-03-25 15:02:57 @NuSkooler I've made sure not to impose any like special menu types in enigma, like you can do them however
2016-03-25 15:03:00 @NuSkooler or at least is the idea
2016-03-25 15:03:01 @NuSkooler hehe
2016-03-25 15:10:44 nolageek I'm completely redoing mine in synchronet since I was never happy with them - they were based on Mystic, which I like. (different menus for main, msg, games, etc...)
2016-03-25 15:10:59 nolageek I dont like boards when they have a big wall of options for a main menu.
2016-03-25 15:11:56 nolageek some are easy - message menu... but things get fuzzy on say, the system info menu.
2016-03-25 15:12:54 nolageek there's a lot that can be considered 'system info' :)
2016-03-25 15:23:00 Mercyful always the fun part :)
2016-03-25 15:25:34 Mercyful writting asynchronous i/o for everything is a handful.. this will either rock when i'm done, or blow chunks.. haha
2016-03-25 15:29:42 Mercyful it's smooth,, just when tricky when you want to query and get a response, you have to make hoops and add timers incase you don't get a response.. heh
2016-03-25 15:29:56 nolageek I'm doing this command shell so that I can basically rename the file and have a directory named the same with the new menu files. Nothing is hardcoded into the scripts like all the others are. Should make it much easier to have multiple themes without re-coding everything. Just need to make sure the menus are arranged well. hehe
2016-03-25 15:30:35 Mercyful sounds like a good idea :)
2016-03-25 15:30:54 nolageek It also keeps track of the user's session activity like the amiga style boards.. --F-P-H etc...
2016-03-25 15:32:11 nolageek also added automessage and rumors mod - didn't like any of the ones available for synchronet.
2016-03-25 15:34:58 Mercyful i hear that.. :)
2016-03-25 15:37:45 Mercyful i'm trying to nail down the login and pre login processes right now, a bit of work getting the terminal detection, ansi detecting going the way it's all setup.. slowly coming togheter.. just so darn tedious casue i have alot of function pointers going and jumping all around. just hope i'm not over doing the normalization hehe
2016-03-25 15:38:53 nolageek I can't imagine how much work it is to write a whole BBS. :) Can't wait to see it.
2016-03-25 15:45:38 @NuSkooler nice
2016-03-25 15:45:40 Mercyful ya, and c++ isn't the most rapid development environment either.. hehe but tx, can't wait to iron this all out. NuSkooler has done an amazing job himself with what he has done in node.js.
2016-03-25 15:45:49 @NuSkooler i still haven't even added ansi detection... i just assume you have it heheh
2016-03-25 15:46:59 @NuSkooler yeah async is def a handful to get a hang of... and can be a pain compared to syncronous code
2016-03-25 15:47:03 Mercyful well ansi detect is just send a lame ESC[6n and get x/y coords response.. of the cursor position.. not much of a detection, but will tell if they client at least has an ANSI capable terminal..
2016-03-25 15:47:05 @NuSkooler but huge benefits
2016-03-25 15:47:34 @NuSkooler i should prob add that at some point... i haven't even bothered to test when terminal is in ascii only though in theory it "should work" (TM)
2016-03-25 15:47:35 @NuSkooler hehe
2016-03-25 15:48:29 Mercyful ya, it's not much to worry about, i mean just about all terms should have color, and ESC sequence support.. hehe
2016-03-25 15:48:46 Mercyful but it's nice to detect and display hehe
2016-03-25 15:49:46 Mercyful ya, even with all the crazy async stuff, virtual classes, and smart pointers.. a conection is still barely taking 0.7 megs of memory which was shocking.. hehe
2016-03-25 15:50:30 Mercyful although i don't have much yet.. but we'll see as it goes along..
2016-03-25 15:52:41 Mercyful my first time doing real async stuff,, other than the rewrite i did to EtherTerm which helped alot too, but that was more direct to one area,, this spawns and handles so much more.. just hope my design isn't too flawed.. hehe
2016-03-25 16:45:40 @NuSkooler the compiler will take away almost all of the overhead of all that stuff and compile code just as if it weren't there... just ends up being less buggy & async code
2016-03-25 16:46:01 @NuSkooler nolageek: I checked in the sorting stuff... i think it should do the trick for you
2016-03-25 22:33:31 Mercyful 22222/8888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888
2016-03-25 22:33:31 Mercyful 8888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888
2016-03-25 22:33:31 Mercyful 88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888
2016-03-25 22:33:31 Mercyful 8888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888
2016-03-26 00:46:27 nolageek 999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999
2016-03-26 00:55:24 Mercyful (~mercyful2@216-80-115-17.c3-0.frg-ubr1.chi-frg.il.cable.rcn.com) has quit (Ping timeout: 276 seconds)
2016-03-26 03:17:44 @NuSkooler lulwut
2016-03-26 03:19:34 @NuSkooler nolageek: Were you able to get doors going?
2016-03-26 03:20:44 nolageek will try today. took a break last night - been up late working on it every night this week.
2016-03-26 03:21:27 nolageek knocking out the rest of these trouble tickets and am going to set it up.
2016-03-26 03:22:39 nolageek how can I force git to do a pull and overwrite any changes I made?
2016-03-26 03:22:59 nolageek it doesn't like that I manually tried to change message_area.js yesturday
2016-03-26 03:27:59 nolageek git reset --hard fixed that. :)
2016-03-26 03:29:30 nolageek ok, pull complete and seeing the same issue as before - no message areas are being displayed.
2016-03-26 03:32:05 nolageek nevermind.
2016-03-26 03:32:08 nolageek :/
2016-03-26 03:32:11 nolageek got it
2016-03-26 03:34:37 @NuSkooler git checkout path/to/file.ext
2016-03-26 03:34:45 @NuSkooler that will give you a clean copy of said file
2016-03-26 03:46:50 nolageek sort works awesome.
2016-03-26 04:20:47 @NuSkooler woot!
2016-03-26 09:53:19 - Mercyful (~mercyful2@216-80-115-17.c3-0.frg-ubr1.chi-frg.il.cable.rcn.com) has joined #enigma-bbs
2016-03-26 10:25:09 Mercyful lol, think my cat was on the keyboard this morning.. :)
2016-03-26 10:52:51 Mercyful (~mercyful2@216-80-115-17.c3-0.frg-ubr1.chi-frg.il.cable.rcn.com) has quit (Quit: Nettalk6 - www.ntalk.de)
2016-03-26 12:59:33 nolageek hehe
2016-03-26 13:43:43 PaddyMac (~patrick@2602:4b:78f5:7200:211:50ff:fef5:592f) has quit (Read error: Connection reset by peer)
2016-03-26 13:44:06 - PaddyMac (~patrick@2602:4b:78f5:7200:211:50ff:fef5:592f) has joined #enigma-bbs
2016-03-26 14:27:57 - Mercyful (~mercyful2@216-80-115-17.c3-0.frg-ubr1.chi-frg.il.cable.rcn.com) has joined #enigma-bbs
2016-03-26 21:48:37 irc: disconnected from server
| IRC log | 1 | 0x4b1dN/2016-dots | misc/weechat/logs/irc.freenode.#enigma-bbs.weechatlog | [
"MIT"
] |
import System.Signal
import System
main : IO ()
main = do
Right () <- collectSignal SigABRT
| Left (Error code) => putStrLn $ "error " ++ (show code)
putStrLn "before"
Right () <- raiseSignal SigABRT
| Left (Error code) => putStrLn $ "got non-zero exit from system call: " ++ (show code)
sleep 1
Just SigABRT <- handleNextCollectedSignal
| Just _ => putStrLn "received the wrong signal."
| Nothing => putStrLn "did not receive expected signal."
putStrLn "after"
Right () <- defaultSignal SigABRT
| Left (Error code) => putStrLn $ "error " ++ (show code)
putStrLn "done."
| Idris | 3 | ska80/idris-jvm | tests/base/system_signal002/HandleSignal.idr | [
"BSD-3-Clause"
] |
module Crystal::System
# Prints directly to stderr without going through an IO.
# This is useful for error messages from components that are required for
# IO to work (fibers, scheduler, event_loop).
def self.print_error(message, *args)
{% if flag?(:unix) %}
LibC.dprintf 2, message, *args
{% elsif flag?(:win32) %}
buffer = StaticArray(UInt8, 512).new(0_u8)
len = LibC.snprintf(buffer, buffer.size, message, *args)
LibC._write 2, buffer, len
{% end %}
end
def self.print_exception(message, ex)
print_error "%s: %s (%s)\n", message, ex.message || "(no message)", ex.class.name
begin
if bt = ex.backtrace?
bt.each do |frame|
print_error " from %s\n", frame
end
else
print_error " (no backtrace)\n"
end
rescue ex
print_error "Error while trying to dump the backtrace: %s (%s)\n", ex.message || "(no message)", ex.class.name
end
end
end
| Crystal | 5 | n00p3/crystal | src/crystal/system/print_error.cr | [
"Apache-2.0"
] |
#include "config.hats"
#include "{$TOP}/avr_prelude/kernel_staload.hats"
staload "{$TOP}/SATS/arduino.sats"
staload UN = "prelude/SATS/unsafe.sats"
#define LED 9
#define DELAY_MS 10.0
typedef analog_w_t = natLt(256)
fun{} int_foreach_clo{n:nat}
(n: int(n), fwork: &natLt(n) -<clo1> void): void =
loop(0, fwork) where {
fun loop{i:nat | i <= n} .<n-i>.
(i: int(i), fwork: &natLt(n) -<clo1> void):void =
if i < n then (fwork(i); loop (i+1, fwork))
}
implement main () = {
fun fadein() = let
var fwork = lam@ (n: analog_w_t) =>
(analogWrite (LED, n); delay_ms(DELAY_MS))
in
int_foreach_clo(256, fwork)
end // end of [fadein]
(* val () = init () *)
val () = pinMode (LED, OUTPUT)
val () = (fix f(): void => (fadein(); f()))()
}
| ATS | 4 | Proclivis/arduino-ats | demo/04_pwm_closure/DATS/main.dats | [
"MIT"
] |
#summary CPIO 5 manual page
== NAME ==
*cpio*
- format of cpio archive files
== DESCRIPTION ==
The
*cpio*
archive format collects any number of files, directories, and other
file system objects (symbolic links, device nodes, etc.) into a single
stream of bytes.
=== General Format===
Each file system object in a
*cpio*
archive comprises a header record with basic numeric metadata
followed by the full pathname of the entry and the file data.
The header record stores a series of integer values that generally
follow the fields in
_struct_ stat.
(See
*stat*(2)
for details.)
The variants differ primarily in how they store those integers
(binary, octal, or hexadecimal).
The header is followed by the pathname of the
entry (the length of the pathname is stored in the header)
and any file data.
The end of the archive is indicated by a special record with
the pathname
"TRAILER!!!".
=== PWB format===
XXX Any documentation of the original PWB/UNIX 1.0 format? XXX
=== Old Binary Format===
The old binary
*cpio*
format stores numbers as 2-byte and 4-byte binary values.
Each entry begins with a header in the following format:
{{{
struct header_old_cpio {
unsigned short c_magic;
unsigned short c_dev;
unsigned short c_ino;
unsigned short c_mode;
unsigned short c_uid;
unsigned short c_gid;
unsigned short c_nlink;
unsigned short c_rdev;
unsigned short c_mtime[2];
unsigned short c_namesize;
unsigned short c_filesize[2];
};
}}}
The
_unsigned_ short
fields here are 16-bit integer values; the
_unsigned_ int
fields are 32-bit integer values.
The fields are as follows
<dl>
<dt>_magic_</dt><dd>
The integer value octal 070707.
This value can be used to determine whether this archive is
written with little-endian or big-endian integers.
</dd><dt>_dev_, _ino_</dt><dd>
The device and inode numbers from the disk.
These are used by programs that read
*cpio*
archives to determine when two entries refer to the same file.
Programs that synthesize
*cpio*
archives should be careful to set these to distinct values for each entry.
</dd><dt>_mode_</dt><dd>
The mode specifies both the regular permissions and the file type.
It consists of several bit fields as follows:
<dl>
<dt>0170000</dt><dd>
This masks the file type bits.
</dd><dt>0140000</dt><dd>
File type value for sockets.
</dd><dt>0120000</dt><dd>
File type value for symbolic links.
For symbolic links, the link body is stored as file data.
</dd><dt>0100000</dt><dd>
File type value for regular files.
</dd><dt>0060000</dt><dd>
File type value for block special devices.
</dd><dt>0040000</dt><dd>
File type value for directories.
</dd><dt>0020000</dt><dd>
File type value for character special devices.
</dd><dt>0010000</dt><dd>
File type value for named pipes or FIFOs.
</dd><dt>0004000</dt><dd>
SUID bit.
</dd><dt>0002000</dt><dd>
SGID bit.
</dd><dt>0001000</dt><dd>
Sticky bit.
On some systems, this modifies the behavior of executables and/or directories.
</dd><dt>0000777</dt><dd>
The lower 9 bits specify read/write/execute permissions
for world, group, and user following standard POSIX conventions.
</dd></dl>
</dd><dt>_uid_, _gid_</dt><dd>
The numeric user id and group id of the owner.
</dd><dt>_nlink_</dt><dd>
The number of links to this file.
Directories always have a value of at least two here.
Note that hardlinked files include file data with every copy in the archive.
</dd><dt>_rdev_</dt><dd>
For block special and character special entries,
this field contains the associated device number.
For all other entry types, it should be set to zero by writers
and ignored by readers.
</dd><dt>_mtime_</dt><dd>
Modification time of the file, indicated as the number
of seconds since the start of the epoch,
00:00:00 UTC January 1, 1970.
The four-byte integer is stored with the most-significant 16 bits first
followed by the least-significant 16 bits.
Each of the two 16 bit values are stored in machine-native byte order.
</dd><dt>_namesize_</dt><dd>
The number of bytes in the pathname that follows the header.
This count includes the trailing NUL byte.
</dd><dt>_filesize_</dt><dd>
The size of the file.
Note that this archive format is limited to
four gigabyte file sizes.
See
_mtime_
above for a description of the storage of four-byte integers.
</dd></dl>
The pathname immediately follows the fixed header.
If the
*namesize*
is odd, an additional NUL byte is added after the pathname.
The file data is then appended, padded with NUL
bytes to an even length.
Hardlinked files are not given special treatment;
the full file contents are included with each copy of the
file.
=== Portable ASCII Format===
Version 2 of the Single UNIX Specification (``SUSv2'')
standardized an ASCII variant that is portable across all
platforms.
It is commonly known as the
"old character"
format or as the
"odc"
format.
It stores the same numeric fields as the old binary format, but
represents them as 6-character or 11-character octal values.
{{{
struct cpio_odc_header {
char c_magic[6];
char c_dev[6];
char c_ino[6];
char c_mode[6];
char c_uid[6];
char c_gid[6];
char c_nlink[6];
char c_rdev[6];
char c_mtime[11];
char c_namesize[6];
char c_filesize[11];
};
}}}
The fields are identical to those in the old binary format.
The name and file body follow the fixed header.
Unlike the old binary format, there is no additional padding
after the pathname or file contents.
If the files being archived are themselves entirely ASCII, then
the resulting archive will be entirely ASCII, except for the
NUL byte that terminates the name field.
=== New ASCII Format===
The "new" ASCII format uses 8-byte hexadecimal fields for
all numbers and separates device numbers into separate fields
for major and minor numbers.
{{{
struct cpio_newc_header {
char c_magic[6];
char c_ino[8];
char c_mode[8];
char c_uid[8];
char c_gid[8];
char c_nlink[8];
char c_mtime[8];
char c_filesize[8];
char c_devmajor[8];
char c_devminor[8];
char c_rdevmajor[8];
char c_rdevminor[8];
char c_namesize[8];
char c_check[8];
};
}}}
Except as specified below, the fields here match those specified
for the old binary format above.
<dl>
<dt>_magic_</dt><dd>
The string
"070701".
</dd><dt>_check_</dt><dd>
This field is always set to zero by writers and ignored by readers.
See the next section for more details.
</dd></dl>
The pathname is followed by NUL bytes so that the total size
of the fixed header plus pathname is a multiple of four.
Likewise, the file data is padded to a multiple of four bytes.
Note that this format supports only 4 gigabyte files (unlike the
older ASCII format, which supports 8 gigabyte files).
In this format, hardlinked files are handled by setting the
filesize to zero for each entry except the last one that
appears in the archive.
=== New CRC Format===
The CRC format is identical to the new ASCII format described
in the previous section except that the magic field is set
to
"070702"
and the
_check_
field is set to the sum of all bytes in the file data.
This sum is computed treating all bytes as unsigned values
and using unsigned arithmetic.
Only the least-significant 32 bits of the sum are stored.
=== HP variants===
The
*cpio*
implementation distributed with HPUX used XXXX but stored
device numbers differently XXX.
=== Other Extensions and Variants===
Sun Solaris uses additional file types to store extended file
data, including ACLs and extended attributes, as special
entries in cpio archives.
XXX Others? XXX
== BUGS ==
The
"CRC"
format is mis-named, as it uses a simple checksum and
not a cyclic redundancy check.
The old binary format is limited to 16 bits for user id,
group id, device, and inode numbers.
It is limited to 4 gigabyte file sizes.
The old ASCII format is limited to 18 bits for
the user id, group id, device, and inode numbers.
It is limited to 8 gigabyte file sizes.
The new ASCII format is limited to 4 gigabyte file sizes.
None of the cpio formats store user or group names,
which are essential when moving files between systems with
dissimilar user or group numbering.
Especially when writing older cpio variants, it may be necessary
to map actual device/inode values to synthesized values that
fit the available fields.
With very large filesystems, this may be necessary even for
the newer formats.
== SEE ALSO ==
*cpio*(1),
*tar*(5)
== STANDARDS ==
The
*cpio*
utility is no longer a part of POSIX or the Single Unix Standard.
It last appeared in
Version 2 of the Single UNIX Specification (``SUSv2'').
It has been supplanted in subsequent standards by
*pax*(1).
The portable ASCII format is currently part of the specification for the
*pax*(1)
utility.
== HISTORY ==
The original cpio utility was written by Dick Haight
while working in AT&T's Unix Support Group.
It appeared in 1977 as part of PWB/UNIX 1.0, the
"Programmer's Work Bench"
derived from
At v6
that was used internally at AT&T.
Both the old binary and old character formats were in use
by 1980, according to the System III source released
by SCO under their
"Ancient Unix"
license.
The character format was adopted as part of
IEEE Std 1003.1-1988 (``POSIX.1'').
XXX when did "newc" appear? Who invented it? When did HP come out with their variant? When did Sun introduce ACLs and extended attributes? XXX
| MediaWiki | 5 | OakCityLabs/ios_system | libarchive/libarchive/doc/wiki/ManPageCpio5.wiki | [
"BSD-3-Clause"
] |
.. _jit_unsupported:
TorchScript Unsupported Pytorch Constructs
============================================
Torch and Tensor Unsupported Attributes
------------------------------------------
TorchScript supports most methods defined on ``torch`` and ``torch.Tensor``, but we do not have full coverage.
Here are specific known ops and categories of ops which have diverging behavior between
Python and TorchScript. If you encounter something else that is not supported please
file a GitHub issue. Deprecated ops are not listed below.
.. automodule:: torch.jit.unsupported_tensor_ops
Functions Not Correctly Bound on Torch
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The following functions will fail if used in TorchScript, either because they
are not bound on `torch` or because Python expects a different schema than
TorchScript.
* :func:`torch.tensordot`
* :func:`torch.nn.init.calculate_gain`
* :func:`torch.nn.init.eye_`
* :func:`torch.nn.init.dirac_`
* :func:`torch.nn.init.kaiming_normal_`
* :func:`torch.nn.init.orthogonal_`
* :func:`torch.nn.init.sparse`
Ops With Divergent Schemas Between Torch & Python
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The following categories of ops have divergent schemas:
Functions which construct tensors from non-tensor inputs do not support the `requires_grad`
argument, except for `torch.tensor`. This covers the following ops:
* :func:`torch.norm`
* :func:`torch.bartlett_window`
* :func:`torch.blackman_window`
* :func:`torch.empty`
* :func:`torch.empty_like`
* :func:`torch.empty_strided`
* :func:`torch.eye`
* :func:`torch.full`
* :func:`torch.full_like`
* :func:`torch.hamming_window`
* :func:`torch.hann_window`
* :func:`torch.linspace`
* :func:`torch.logspace`
* :func:`torch.normal`
* :func:`torch.ones`
* :func:`torch.rand`
* :func:`torch.rand_like`
* :func:`torch.randint_like`
* :func:`torch.randn`
* :func:`torch.randn_like`
* :func:`torch.randperm`
* :func:`torch.tril_indices`
* :func:`torch.triu_indices`
* :func:`torch.vander`
* :func:`torch.zeros`
* :func:`torch.zeros_like`
The following functions require `dtype`, `layout`, `device` as parameters in TorchScript,
but these parameters are optional in Python.
* :func:`torch.randint`
* :func:`torch.sparse_coo_tensor`
* :meth:`~torch.Tensor.to`
PyTorch Unsupported Modules and Classes
------------------------------------------
TorchScript cannot currently compile a number of other commonly used PyTorch
constructs. Below are listed the modules that TorchScript does not support, and
an incomplete list of PyTorch classes that are not supported. For unsupported modules
we suggest using :meth:`torch.jit.trace`.
* :class:`torch.nn.RNN`
* :class:`torch.nn.AdaptiveLogSoftmaxWithLoss`
* :class:`torch.autograd.Function`
* :class:`torch.autograd.enable_grad`
* :class:`torch.Generator`
| reStructuredText | 3 | Hacky-DH/pytorch | docs/source/jit_unsupported.rst | [
"Intel"
] |
'reach 0.1';
export const main = Reach.App(
{}, [], () => {
const _x = 1;
}
);
| RenderScript | 2 | chikeabuah/reach-lang | hs/t/n/Err_Eval_NotPublicIdent.rsh | [
"Apache-2.0"
] |
# Copyright 2016 The OpenSSL Project Authors. All Rights Reserved.
#
# Licensed under the Apache License 2.0 (the "License"). You may not use
# this file except in compliance with the License. You can obtain a copy
# in the file LICENSE in the source distribution or at
# https://www.openssl.org/source/license.html
use strict;
package TLSProxy::CertificateVerify;
use vars '@ISA';
push @ISA, 'TLSProxy::Message';
sub new
{
my $class = shift;
my ($server,
$data,
$records,
$startoffset,
$message_frag_lens) = @_;
my $self = $class->SUPER::new(
$server,
TLSProxy::Message::MT_CERTIFICATE_VERIFY,
$data,
$records,
$startoffset,
$message_frag_lens);
$self->{sigalg} = -1;
$self->{signature} = "";
return $self;
}
sub parse
{
my $self = shift;
my $sigalg = -1;
my $remdata = $self->data;
my $record = ${$self->records}[0];
if (TLSProxy::Proxy->is_tls13()
|| $record->version() == TLSProxy::Record::VERS_TLS_1_2) {
$sigalg = unpack('n', $remdata);
$remdata = substr($remdata, 2);
}
my $siglen = unpack('n', substr($remdata, 0, 2));
my $sig = substr($remdata, 2);
die "Invalid CertificateVerify signature length" if length($sig) != $siglen;
print " SigAlg:".$sigalg."\n";
print " Signature Len:".$siglen."\n";
$self->sigalg($sigalg);
$self->signature($sig);
}
#Reconstruct the on-the-wire message data following changes
sub set_message_contents
{
my $self = shift;
my $data = "";
my $sig = $self->signature();
my $olddata = $self->data();
$data .= pack("n", $self->sigalg()) if ($self->sigalg() != -1);
$data .= pack("n", length($sig));
$data .= $sig;
$self->data($data);
}
#Read/write accessors
sub sigalg
{
my $self = shift;
if (@_) {
$self->{sigalg} = shift;
}
return $self->{sigalg};
}
sub signature
{
my $self = shift;
if (@_) {
$self->{signature} = shift;
}
return $self->{signature};
}
1;
| Perl | 4 | pmesnier/openssl | util/perl/TLSProxy/CertificateVerify.pm | [
"Apache-2.0"
] |
@import Foundation;
#pragma clang assume_nonnull begin
typedef void (^HandlerBlock)(NSString *(^message)(void));
#pragma clang assume_nonnull end
/// Default handler for logging.
extern _Null_unspecified HandlerBlock TheHandlerBlock;
| C | 4 | lwhsu/swift | test/SILGen/Inputs/objc_bridged_block_optionality_diff.h | [
"Apache-2.0"
] |
/*
*
* Copyright 2018 gRPC 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.
*
*/
#include <grpc/support/port_platform.h>
#include "src/core/tsi/alts/crypt/gsec.h"
#include <stdio.h>
#include <string.h>
#include <grpc/support/alloc.h>
static const char vtable_error_msg[] =
"crypter or crypter->vtable has not been initialized properly";
static void maybe_copy_error_msg(const char* src, char** dst) {
if (dst != nullptr && src != nullptr) {
*dst = static_cast<char*>(gpr_malloc(strlen(src) + 1));
memcpy(*dst, src, strlen(src) + 1);
}
}
grpc_status_code gsec_aead_crypter_encrypt(
gsec_aead_crypter* crypter, const uint8_t* nonce, size_t nonce_length,
const uint8_t* aad, size_t aad_length, const uint8_t* plaintext,
size_t plaintext_length, uint8_t* ciphertext_and_tag,
size_t ciphertext_and_tag_length, size_t* bytes_written,
char** error_details) {
if (crypter != nullptr && crypter->vtable != nullptr &&
crypter->vtable->encrypt_iovec != nullptr) {
struct iovec aad_vec = {const_cast<uint8_t*>(aad), aad_length};
struct iovec plaintext_vec = {const_cast<uint8_t*>(plaintext),
plaintext_length};
struct iovec ciphertext_vec = {ciphertext_and_tag,
ciphertext_and_tag_length};
return crypter->vtable->encrypt_iovec(
crypter, nonce, nonce_length, &aad_vec, 1, &plaintext_vec, 1,
ciphertext_vec, bytes_written, error_details);
}
/* An error occurred. */
maybe_copy_error_msg(vtable_error_msg, error_details);
return GRPC_STATUS_INVALID_ARGUMENT;
}
grpc_status_code gsec_aead_crypter_encrypt_iovec(
gsec_aead_crypter* crypter, const uint8_t* nonce, size_t nonce_length,
const struct iovec* aad_vec, size_t aad_vec_length,
const struct iovec* plaintext_vec, size_t plaintext_vec_length,
struct iovec ciphertext_vec, size_t* ciphertext_bytes_written,
char** error_details) {
if (crypter != nullptr && crypter->vtable != nullptr &&
crypter->vtable->encrypt_iovec != nullptr) {
return crypter->vtable->encrypt_iovec(
crypter, nonce, nonce_length, aad_vec, aad_vec_length, plaintext_vec,
plaintext_vec_length, ciphertext_vec, ciphertext_bytes_written,
error_details);
}
/* An error occurred. */
maybe_copy_error_msg(vtable_error_msg, error_details);
return GRPC_STATUS_INVALID_ARGUMENT;
}
grpc_status_code gsec_aead_crypter_decrypt(
gsec_aead_crypter* crypter, const uint8_t* nonce, size_t nonce_length,
const uint8_t* aad, size_t aad_length, const uint8_t* ciphertext_and_tag,
size_t ciphertext_and_tag_length, uint8_t* plaintext,
size_t plaintext_length, size_t* bytes_written, char** error_details) {
if (crypter != nullptr && crypter->vtable != nullptr &&
crypter->vtable->decrypt_iovec != nullptr) {
struct iovec aad_vec = {const_cast<uint8_t*>(aad), aad_length};
struct iovec ciphertext_vec = {const_cast<uint8_t*>(ciphertext_and_tag),
ciphertext_and_tag_length};
struct iovec plaintext_vec = {plaintext, plaintext_length};
return crypter->vtable->decrypt_iovec(
crypter, nonce, nonce_length, &aad_vec, 1, &ciphertext_vec, 1,
plaintext_vec, bytes_written, error_details);
}
/* An error occurred. */
maybe_copy_error_msg(vtable_error_msg, error_details);
return GRPC_STATUS_INVALID_ARGUMENT;
}
grpc_status_code gsec_aead_crypter_decrypt_iovec(
gsec_aead_crypter* crypter, const uint8_t* nonce, size_t nonce_length,
const struct iovec* aad_vec, size_t aad_vec_length,
const struct iovec* ciphertext_vec, size_t ciphertext_vec_length,
struct iovec plaintext_vec, size_t* plaintext_bytes_written,
char** error_details) {
if (crypter != nullptr && crypter->vtable != nullptr &&
crypter->vtable->encrypt_iovec != nullptr) {
return crypter->vtable->decrypt_iovec(
crypter, nonce, nonce_length, aad_vec, aad_vec_length, ciphertext_vec,
ciphertext_vec_length, plaintext_vec, plaintext_bytes_written,
error_details);
}
/* An error occurred. */
maybe_copy_error_msg(vtable_error_msg, error_details);
return GRPC_STATUS_INVALID_ARGUMENT;
}
grpc_status_code gsec_aead_crypter_max_ciphertext_and_tag_length(
const gsec_aead_crypter* crypter, size_t plaintext_length,
size_t* max_ciphertext_and_tag_length_to_return, char** error_details) {
if (crypter != nullptr && crypter->vtable != nullptr &&
crypter->vtable->max_ciphertext_and_tag_length != nullptr) {
return crypter->vtable->max_ciphertext_and_tag_length(
crypter, plaintext_length, max_ciphertext_and_tag_length_to_return,
error_details);
}
/* An error occurred. */
maybe_copy_error_msg(vtable_error_msg, error_details);
return GRPC_STATUS_INVALID_ARGUMENT;
}
grpc_status_code gsec_aead_crypter_max_plaintext_length(
const gsec_aead_crypter* crypter, size_t ciphertext_and_tag_length,
size_t* max_plaintext_length_to_return, char** error_details) {
if (crypter != nullptr && crypter->vtable != nullptr &&
crypter->vtable->max_plaintext_length != nullptr) {
return crypter->vtable->max_plaintext_length(
crypter, ciphertext_and_tag_length, max_plaintext_length_to_return,
error_details);
}
/* An error occurred. */
maybe_copy_error_msg(vtable_error_msg, error_details);
return GRPC_STATUS_INVALID_ARGUMENT;
}
grpc_status_code gsec_aead_crypter_nonce_length(
const gsec_aead_crypter* crypter, size_t* nonce_length_to_return,
char** error_details) {
if (crypter != nullptr && crypter->vtable != nullptr &&
crypter->vtable->nonce_length != nullptr) {
return crypter->vtable->nonce_length(crypter, nonce_length_to_return,
error_details);
}
/* An error occurred. */
maybe_copy_error_msg(vtable_error_msg, error_details);
return GRPC_STATUS_INVALID_ARGUMENT;
}
grpc_status_code gsec_aead_crypter_key_length(const gsec_aead_crypter* crypter,
size_t* key_length_to_return,
char** error_details) {
if (crypter != nullptr && crypter->vtable != nullptr &&
crypter->vtable->key_length != nullptr) {
return crypter->vtable->key_length(crypter, key_length_to_return,
error_details);
}
/* An error occurred */
maybe_copy_error_msg(vtable_error_msg, error_details);
return GRPC_STATUS_INVALID_ARGUMENT;
}
grpc_status_code gsec_aead_crypter_tag_length(const gsec_aead_crypter* crypter,
size_t* tag_length_to_return,
char** error_details) {
if (crypter != nullptr && crypter->vtable != nullptr &&
crypter->vtable->tag_length != nullptr) {
return crypter->vtable->tag_length(crypter, tag_length_to_return,
error_details);
}
/* An error occurred. */
maybe_copy_error_msg(vtable_error_msg, error_details);
return GRPC_STATUS_INVALID_ARGUMENT;
}
void gsec_aead_crypter_destroy(gsec_aead_crypter* crypter) {
if (crypter != nullptr) {
if (crypter->vtable != nullptr && crypter->vtable->destruct != nullptr) {
crypter->vtable->destruct(crypter);
}
gpr_free(crypter);
}
}
| C++ | 5 | warlock135/grpc | src/core/tsi/alts/crypt/gsec.cc | [
"Apache-2.0"
] |
#---------------------------------------------------------------------------
#
# zz60-xc-ovr.m4
#
# Copyright (c) 2013 Daniel Stenberg <daniel@haxx.se>
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#
#---------------------------------------------------------------------------
# serial 1
dnl The funny name of this file is intentional in order to make it
dnl sort alphabetically after any libtool, autoconf or automake
dnl provided .m4 macro file that might get copied into this same
dnl subdirectory. This allows that macro (re)definitions from this
dnl file may override those provided in other files.
dnl Override an autoconf provided macro
dnl -------------------------------------------------
dnl This macro overrides the one provided by autoconf
dnl 2.58 or newer, and provides macro definition for
dnl autoconf 2.57 or older which lack it. This allows
dnl using libtool 2.2 or newer, which requires that
dnl this macro is used in configure.ac, with autoconf
dnl 2.57 or older.
m4_ifdef([AC_CONFIG_MACRO_DIR],
[dnl
m4_undefine([AC_CONFIG_MACRO_DIR])dnl
])
m4_define([AC_CONFIG_MACRO_DIR],[])
dnl XC_OVR_ZZ60
dnl -------------------------------------------------
dnl Placing a call to this macro in configure.ac will
dnl make macros in this file visible to other macros
dnl used for same configure script, overriding those
dnl provided elsewhere.
AC_DEFUN([XC_OVR_ZZ60],
[dnl
AC_BEFORE([$0],[LT_INIT])dnl
AC_BEFORE([$0],[AM_INIT_AUTOMAKE])dnl
AC_BEFORE([$0],[AC_LIBTOOL_WIN32_DLL])dnl
AC_BEFORE([$0],[AC_PROG_LIBTOOL])dnl
dnl
AC_BEFORE([$0],[AC_CONFIG_MACRO_DIR])dnl
AC_BEFORE([$0],[AC_CONFIG_MACRO_DIRS])dnl
])
| M4 | 4 | faizur/curl | m4/zz60-xc-ovr.m4 | [
"curl"
] |
FancySpec describe: DynamicSlotObject with: {
it: "has the correct slots defined" when: {
dso = DynamicSlotObject new
dso tap: @{
name: "Chris"
age: 25
country: "Germany"
}
dso object tap: @{
slots is: ['name, 'age, 'country]
class is: Object
# getters
name is: "Chris"
age is: 25
country is: "Germany"
# setters
name: "Jack"
name is: "Jack"
age: 26
age is: 26
country: "USA"
country is: "USA"
}
}
}
| Fancy | 4 | bakkdoor/fancy | tests/dynamic_slot_object.fy | [
"BSD-3-Clause"
] |
server {
server_name localhost;
root /var/app/www;
location = / {
try_files @site @site;
}
location / {
try_files $uri $uri/ @site;
}
location ~ \.php$ {
return 404;
}
location @site {
fastcgi_pass fpm:9000;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root/index.php;
#uncomment when running via https
#fastcgi_param HTTPS on;
}
error_log /var/log/nginx/error.log;
access_log /var/log/nginx/access.log;
} | ApacheConf | 4 | DjordjeVucinac82/crunchbutton | Nginx/app.vhost | [
"MIT"
] |
#include <torch/csrc/jit/passes/remove_inplace_ops.h>
namespace torch {
namespace jit {
namespace {
static const std::unordered_map<NodeKind, NodeKind> inPlaceToOutOfPlace = {
{aten::add_, aten::add},
{aten::sub_, aten::sub},
{aten::div_, aten::div},
{aten::mul_, aten::mul},
{aten::masked_fill_, aten::masked_fill},
{aten::zero_, aten::zeros_like},
{aten::fill_, aten::full_like}};
// This is a horrible no good awful hack to "fill in" the TensorOptions
// arguments of zeros_like and full_like so that the defaults are filled
// in. Ugh. Would be better to just run the frontend to get the correct
// arity here.
static const std::unordered_map<NodeKind, int> expectedInputCount = {
{aten::zero_, 6},
{aten::fill_, 7}};
bool isInplaceOp(const Node* node) {
return inPlaceToOutOfPlace.count(node->kind()) != 0;
}
// Remove all in-place ops and replace them with out-of-place equivalents.
// e.g.
// %foo = aten::add_(%foo, %n)
// becomes
// %foo.2 = aten::add(%foo, %n)
//
// NOTE: this is NOT SAFE, since it assumes that the LHS is not aliased by
// another value. This is only to avoid breaking ONNX export; when alias
// analysis is done we can emit a warning if someone tries to export.
void RemoveInplaceOps(Block* block) {
auto graph = block->owningGraph();
auto it = block->nodes().begin();
while (it != block->nodes().end()) {
auto node = *it;
++it;
for (auto block : node->blocks()) {
RemoveInplaceOps(block);
}
if (isInplaceOp(node)) {
// create a replacement out of place op
auto newNode = graph->create(inPlaceToOutOfPlace.at(node->kind()));
newNode->insertBefore(node);
newNode->setScope(node->scope());
// copy inputs
for (auto input : node->inputs()) {
newNode->addInput(input);
}
int additionalInputCount = 0;
if (expectedInputCount.find(node->kind()) != expectedInputCount.end()) {
additionalInputCount = expectedInputCount.at(node->kind()) -
static_cast<int>(newNode->inputs().size());
}
for (int i = 0; i < additionalInputCount; ++i) {
auto noneNode = graph->createNone();
noneNode->insertBefore(newNode);
newNode->addInput(noneNode->output());
}
// Create a new output node and replace all uses of self with it
newNode->output()->copyMetadata(node->output());
node->replaceAllUsesWith(newNode);
node->inputs()[0]->replaceAllUsesAfterNodeWith(
newNode, newNode->output());
node->destroy();
}
}
}
} // namespace
// Handles special case of binary inplace ops, where the first input node
// has a lower type precedence than the second input node. When the
// inplace node is converted to a regular op, this information is lost and
// the resulting type is based on type precedence, just like regular ops.
// To avoid this loss of information, we add a cast node before the input
// node with the higher data type precedence, so that both the input types
// are the same.
// An example scenario would be:
// Before:
// graph(%0 : Float),
// %1 : Half):
// # Should result in a Half, but after translation to out-of-place,
// # would become a Float b/c Half+Float -> Float.
// %4 : Float = onnx::Cast[to=1](%1)
// %5 : Float = onnx::Add(%4, %0)
// ...
// After:
// graph(%0 : Float),
// %1 : Half):
// %4 : Half = onnx::Cast[to=10](%0)
// %5 : Half = onnx::Add(%1, %4)
// ...
void ImplicitCastForBinaryInplaceOps(Block* b) {
for (auto it = b->nodes().begin(), end = b->nodes().end(); it != end; ++it) {
for (auto* child_block : it->blocks()) {
ImplicitCastForBinaryInplaceOps(child_block);
}
// Check type if inplace operation is a binary node
if ((it->kind() == aten::add_) || (it->kind() == aten::sub_) ||
(it->kind() == aten::mul_) || (it->kind() == aten::div_)) {
auto originalInputs = it->inputs();
if (originalInputs.at(0) == originalInputs.at(1)) {
continue;
}
TensorTypePtr firstInp_tensor =
originalInputs.at(0)->type()->cast<TensorType>();
TensorTypePtr secondInp_tensor =
originalInputs.at(1)->type()->cast<TensorType>();
if (!(firstInp_tensor) || !(secondInp_tensor) ||
!(firstInp_tensor->scalarType().has_value())) {
continue;
}
auto newInputNode = it->owningGraph()->create(aten::type_as, 1);
newInputNode->insertBefore(*it);
newInputNode->addInput(originalInputs.at(1));
newInputNode->addInput(originalInputs.at(0));
it->replaceInput(1, newInputNode->outputs().at(0));
}
}
}
void RemoveInplaceOps(const std::shared_ptr<Graph>& graph) {
ImplicitCastForBinaryInplaceOps(graph->block());
RemoveInplaceOps(graph->block());
}
} // namespace jit
} // namespace torch
| C++ | 4 | Hacky-DH/pytorch | torch/csrc/jit/passes/remove_inplace_ops.cpp | [
"Intel"
] |
const { uuid } = require(`gatsby-core-utils`)
const { buildSchema, printSchema } = require(`gatsby/graphql`)
const {
wrapSchema,
introspectSchema,
RenameTypes,
} = require(`@graphql-tools/wrap`)
const { linkToExecutor } = require(`@graphql-tools/links`)
const { createHttpLink } = require(`apollo-link-http`)
const { fetchWrapper } = require(`./fetch`)
const { createDataloaderLink } = require(`./batching/dataloader-link`)
const {
NamespaceUnderFieldTransform,
StripNonQueryTransform,
} = require(`./transforms`)
exports.pluginOptionsSchema = ({ Joi }) =>
Joi.object({
url: Joi.string(),
typeName: Joi.string().required(),
fieldName: Joi.string().required(),
headers: Joi.alternatives().try(Joi.object(), Joi.function()),
fetch: Joi.function(),
fetchOptions: Joi.object(),
createLink: Joi.function(),
createSchema: Joi.function(),
batch: Joi.boolean(),
transformSchema: Joi.function(),
}).or(`url`, `createLink`)
exports.createSchemaCustomization = async (
{ actions, createNodeId, cache },
options
) => {
const { addThirdPartySchema } = actions
const {
url,
typeName,
fieldName,
headers = {},
fetch = fetchWrapper,
fetchOptions = {},
createLink,
createSchema,
batch = false,
transformSchema,
} = options
let link
if (createLink) {
link = await createLink(options)
} else {
const options = {
uri: url,
fetch,
fetchOptions,
headers: typeof headers === `function` ? await headers() : headers,
}
link = batch ? createDataloaderLink(options) : createHttpLink(options)
}
let introspectionSchema
if (createSchema) {
introspectionSchema = await createSchema(options)
} else {
const cacheKey = `gatsby-source-graphql-schema-${typeName}-${fieldName}`
let sdl = await cache.get(cacheKey)
if (!sdl) {
introspectionSchema = await introspectSchema(linkToExecutor(link))
sdl = printSchema(introspectionSchema)
} else {
introspectionSchema = buildSchema(sdl)
}
await cache.set(cacheKey, sdl)
}
// This node is created in `sourceNodes`.
const nodeId = createSchemaNodeId({ typeName, createNodeId })
const resolver = (parent, args, context) => {
context.nodeModel.createPageDependency({
path: context.path,
nodeId: nodeId,
})
return {}
}
const defaultTransforms = [
new StripNonQueryTransform(),
new RenameTypes(name => `${typeName}_${name}`),
new NamespaceUnderFieldTransform({
typeName,
fieldName,
resolver,
}),
]
const schema = transformSchema
? transformSchema({
schema: introspectionSchema,
link,
resolver,
defaultTransforms,
options,
})
: wrapSchema({
schema: introspectionSchema,
executor: linkToExecutor(link),
transforms: defaultTransforms,
})
addThirdPartySchema({ schema })
}
exports.sourceNodes = async (
{ actions, createNodeId, createContentDigest },
options
) => {
const { createNode } = actions
const { typeName, fieldName, refetchInterval } = options
const nodeId = createSchemaNodeId({ typeName, createNodeId })
const node = createSchemaNode({
id: nodeId,
typeName,
fieldName,
createContentDigest,
})
createNode(node)
if (process.env.NODE_ENV !== `production`) {
if (refetchInterval) {
const msRefetchInterval = refetchInterval * 1000
const refetcher = () => {
createNode(
createSchemaNode({
id: nodeId,
typeName,
fieldName,
createContentDigest,
})
)
setTimeout(refetcher, msRefetchInterval)
}
setTimeout(refetcher, msRefetchInterval)
}
}
}
function createSchemaNodeId({ typeName, createNodeId }) {
return createNodeId(`gatsby-source-graphql-${typeName}`)
}
function createSchemaNode({ id, typeName, fieldName, createContentDigest }) {
const nodeContent = uuid.v4()
const nodeContentDigest = createContentDigest(nodeContent)
return {
id,
typeName: typeName,
fieldName: fieldName,
parent: null,
children: [],
internal: {
type: `GraphQLSource`,
contentDigest: nodeContentDigest,
ignoreType: true,
},
}
}
| JavaScript | 5 | beingfranklin/gatsby | packages/gatsby-source-graphql/src/gatsby-node.js | [
"MIT"
] |
radius = 0.01;
height = 0.1;
$fn = 50;
difference() {
difference() {
difference() {
union() {
cylinder(center=false, h=height, r=radius);
sphere(radius);
};
translate([0, 0, 0.9*height])
rotate_extrude()
polygon([[0.8*radius, 0], [1.8*radius, -0.577*radius], [1.8*radius, 0.577*radius]]);
}
cylinder(center=false, h=1.1*height, r=0.3*radius);
}
for (i = [1:6]) {
rotate([0, 0, 360/6*i])
translate([-1.1*radius, 0.0, -0.2*height])
cylinder(center=false, h=1.1*height, r=0.2*radius);
}
}
| OpenSCAD | 3 | clazaro/sfepy | doc/preprocessing/screwdriver_handle.scad | [
"BSD-3-Clause"
] |
#![feature(decl_macro)]
#![deny(unused_macros)]
// Most simple case
macro unused { //~ ERROR: unused macro definition
() => {}
}
#[allow(unused_macros)]
mod bar {
// Test that putting the #[deny] close to the macro's definition
// works.
#[deny(unused_macros)]
macro unused { //~ ERROR: unused macro definition
() => {}
}
}
mod boo {
pub(crate) macro unused { //~ ERROR: unused macro definition
() => {}
}
}
fn main() {}
| Rust | 5 | Eric-Arellano/rust | src/test/ui/unused/unused-macro.rs | [
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] |
import { Path } from "graphql/jsutils/Path"
import report from "gatsby-cli/lib/reporter"
import { IActivityArgs } from "gatsby-cli/src/reporter/reporter"
import { IPhantomReporter } from "gatsby-cli/src/reporter/reporter-phantom"
import { IGraphQLSpanTracer } from "../schema/type-definitions"
import { pathToArray } from "./utils"
/**
* Tracks and knows how to get a parent span for a particular
* point in query resolver for a particular query and path
*/
export default class GraphQLSpanTracer implements IGraphQLSpanTracer {
parentActivity: IPhantomReporter
activities: Map<string, IPhantomReporter>
constructor(name: string, activityArgs: IActivityArgs) {
this.parentActivity = report.phantomActivity(
name,
activityArgs
) as IPhantomReporter
this.activities = new Map()
}
getParentActivity(): IPhantomReporter {
return this.parentActivity
}
start(): void {
this.parentActivity.start()
}
end(): void {
this.activities.forEach(activity => {
activity.end()
})
this.parentActivity.end()
}
createResolverActivity(path: Path, name: string): IPhantomReporter {
let prev: Path | undefined = path.prev
while (typeof prev?.key === `number`) {
prev = prev.prev
}
const parentSpan = this.getActivity(prev).span
const activity = report.phantomActivity(`GraphQL Resolver`, {
parentSpan,
tags: {
field: name,
path: pathToArray(path).join(`.`),
},
})
this.setActivity(path, activity)
return activity
}
getActivity(gqlPath: Path | undefined): IPhantomReporter {
const path = pathToArray(gqlPath)
let activity
if (path.length > 0) {
activity = this.activities.get(path.join(`.`))
if (activity) {
return activity
}
}
return this.parentActivity
}
setActivity(gqlPath: Path, activity: IPhantomReporter): void {
const path = pathToArray(gqlPath)
this.activities.set(path.join(`.`), activity)
}
}
| TypeScript | 5 | Pabelnedved/ghostlocoko | packages/gatsby/src/query/graphql-span-tracer.ts | [
"MIT"
] |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Feed Analysis</title>
<style>
body {
width: 100% !important;
-webkit-text-size-adjust: 100%;
-ms-text-size-adjust: 100%;
margin: 0 !important;
padding: 0 !important;
color: #353535;
}
table {
text-align: center;
font-family: monospace;
font-size: 12px;
border-collapse: collapse;
margin-bottom: 48px;
min-width: 720px;
}
table th{
border: 1px solid #f3f3f3;
}
table tr.data:hover {
background: #E7F4FE;
}
.domain {
text-align: left;
}
.domain,
.cell {
border: 1px solid #f3f3f3;
}
.cell {
text-align: right;
min-width: 64px;
}
.cell .delta {
text-align: center;
}
.cell.delta-pos .delta {
color: #ffba00;
}
.cell.delta-neg .delta {
color: #66bb6a;
}
.cell-wrapper {
display: flex;
}
.cell .delta,
.cell .value {
flex: 1;
}
.cell.delta-zero .delta {
visibility: hidden;
}
.cell.delta-zero .value {
color: #353535;
}
.cell.value-zero .value {
color: #f3f3f3;
}
.cell.delta-zero.value-zero .value {
visibility: hidden;
}
</style>
</head>
<body>
<%
def delta_class(value):
if value > 0: return 'delta-pos'
elif value < 0: return 'delta-neg'
else: return 'delta-zero'
def value_class(value):
return 'value-zero' if value == 0 else ''
%>
<%def name="number_cell(row, key)">
<td class="cell ${ value_class(row['base'][key]) } ${ delta_class(row['delta'][key]) }">
<div class="cell-wrapper">
<span class="value">${ row['base'][key] }</span>
<span class="delta">${ '{:+}'.format(row['delta'][key]) }</span>
</div>
</td>
</%def>
<table>
<tr class="header">
<th rowspan="2">domain</th>
<th rowspan="2">total</th>
<th rowspan="2">proxy</th>
<th colspan="${ len(headers['response_status']) }">response_status</th>
<th colspan="${ len(headers['freeze_level']) }">freeze_level</th>
</tr>
<tr class="header">
% for name in headers['response_status']:
<th>${ name }</th>
% endfor
% for name in headers['freeze_level']:
<th>${ name }</th>
% endfor
</tr>
% for row in records:
<tr class="data">
<td class="domain">${ row['domain'] }</td>
${ number_cell(row, 'total') }
${ number_cell(row, 'use_proxy') }
% for name in headers['response_status']:
${ number_cell(row, 'response_status:' + name) }
% endfor
% for name in headers['freeze_level']:
${ number_cell(row, 'freeze_level:' + name) }
% endfor
</tr>
% endfor
</table>
</body>
</html> | Mako | 4 | zuzhi/rssant | rssant/templates/email/feed_analysis.html.mako | [
"BSD-3-Clause"
] |
sleep 1
t app appmode photo
sleep 120
t app button shutter PR
d:\autoexec.ash
REBOOT yes
| AGS Script | 0 | waltersgrey/autoexechack | MegaLapse/2MinInterval/Hero3PlusBlack/autoexec.ash | [
"MIT"
] |
<http://www.w3.org/2013/TurtleTests/s> <http://www.w3.org/2013/TurtleTests/p> 123abc .
| Turtle | 0 | joshrose/audacity | lib-src/lv2/serd/tests/TurtleTests/turtle-syntax-bad-num-03.ttl | [
"CC-BY-3.0"
] |
//===- AccumulatingDiagnosticConsumer.h - Collect Text Diagnostics C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file defines the AccumulatingDiagnosticConsumer class, which collects
// all emitted diagnostics into an externally-owned collection.
//
//===----------------------------------------------------------------------===//
#ifndef SWIFT_ACCUMULATINGDIAGNOSTICCONSUMER_H
#define SWIFT_ACCUMULATINGDIAGNOSTICCONSUMER_H
#include "swift/AST/DiagnosticConsumer.h"
#include "swift/Basic/DiagnosticOptions.h"
#include "swift/Basic/LLVM.h"
#include <string>
#include <sstream>
namespace swift {
/// Diagnostic consumer that simply collects all emitted diagnostics into the provided
/// collection.
class AccumulatingFileDiagnosticConsumer : public DiagnosticConsumer {
std::vector<std::string> &Diagnostics;
public:
AccumulatingFileDiagnosticConsumer(std::vector<std::string> &DiagBuffer)
: Diagnostics(DiagBuffer) {}
private:
void handleDiagnostic(SourceManager &SM,
const DiagnosticInfo &Info) override {
addDiagnostic(SM, Info);
for (auto ChildInfo : Info.ChildDiagnosticInfo) {
addDiagnostic(SM, *ChildInfo);
}
}
// TODO: Support Swift-style diagnostic formatting
void addDiagnostic(SourceManager &SM, const DiagnosticInfo &Info) {
// Determine what kind of diagnostic we're emitting.
llvm::SourceMgr::DiagKind SMKind;
switch (Info.Kind) {
case DiagnosticKind::Error:
SMKind = llvm::SourceMgr::DK_Error;
break;
case DiagnosticKind::Warning:
SMKind = llvm::SourceMgr::DK_Warning;
break;
case DiagnosticKind::Note:
SMKind = llvm::SourceMgr::DK_Note;
break;
case DiagnosticKind::Remark:
SMKind = llvm::SourceMgr::DK_Remark;
break;
}
// Translate ranges.
SmallVector<llvm::SMRange, 2> Ranges;
for (auto R : Info.Ranges)
Ranges.push_back(getRawRange(SM, R));
// Translate fix-its.
SmallVector<llvm::SMFixIt, 2> FixIts;
for (DiagnosticInfo::FixIt F : Info.FixIts)
FixIts.push_back(getRawFixIt(SM, F));
// Actually substitute the diagnostic arguments into the diagnostic text.
llvm::SmallString<256> Text;
{
llvm::raw_svector_ostream Out(Text);
DiagnosticEngine::formatDiagnosticText(Out, Info.FormatString,
Info.FormatArgs);
}
const llvm::SourceMgr &rawSM = SM.getLLVMSourceMgr();
auto Msg = SM.GetMessage(Info.Loc, SMKind, Text, Ranges, FixIts);
std::string result;
llvm::raw_string_ostream os(result);
rawSM.PrintMessage(os, Msg, false);
os.flush();
Diagnostics.push_back(result);
}
};
}
#endif
| C | 5 | gandhi56/swift | include/swift/Frontend/AccumulatingDiagnosticConsumer.h | [
"Apache-2.0"
] |
"""Huawei LTE constants."""
DOMAIN = "huawei_lte"
ATTR_UNIQUE_ID = "unique_id"
CONF_TRACK_WIRED_CLIENTS = "track_wired_clients"
CONF_UNAUTHENTICATED_MODE = "unauthenticated_mode"
DEFAULT_DEVICE_NAME = "LTE"
DEFAULT_NOTIFY_SERVICE_NAME = DOMAIN
DEFAULT_TRACK_WIRED_CLIENTS = True
DEFAULT_UNAUTHENTICATED_MODE = False
UPDATE_SIGNAL = f"{DOMAIN}_update"
CONNECTION_TIMEOUT = 10
NOTIFY_SUPPRESS_TIMEOUT = 30
SERVICE_CLEAR_TRAFFIC_STATISTICS = "clear_traffic_statistics"
SERVICE_REBOOT = "reboot"
SERVICE_RESUME_INTEGRATION = "resume_integration"
SERVICE_SUSPEND_INTEGRATION = "suspend_integration"
ADMIN_SERVICES = {
SERVICE_CLEAR_TRAFFIC_STATISTICS,
SERVICE_REBOOT,
SERVICE_RESUME_INTEGRATION,
SERVICE_SUSPEND_INTEGRATION,
}
KEY_DEVICE_BASIC_INFORMATION = "device_basic_information"
KEY_DEVICE_INFORMATION = "device_information"
KEY_DEVICE_SIGNAL = "device_signal"
KEY_DIALUP_MOBILE_DATASWITCH = "dialup_mobile_dataswitch"
KEY_LAN_HOST_INFO = "lan_host_info"
KEY_MONITORING_CHECK_NOTIFICATIONS = "monitoring_check_notifications"
KEY_MONITORING_MONTH_STATISTICS = "monitoring_month_statistics"
KEY_MONITORING_STATUS = "monitoring_status"
KEY_MONITORING_TRAFFIC_STATISTICS = "monitoring_traffic_statistics"
KEY_NET_CURRENT_PLMN = "net_current_plmn"
KEY_NET_NET_MODE = "net_net_mode"
KEY_SMS_SMS_COUNT = "sms_sms_count"
KEY_WLAN_HOST_LIST = "wlan_host_list"
KEY_WLAN_WIFI_FEATURE_SWITCH = "wlan_wifi_feature_switch"
BINARY_SENSOR_KEYS = {
KEY_MONITORING_CHECK_NOTIFICATIONS,
KEY_MONITORING_STATUS,
KEY_WLAN_WIFI_FEATURE_SWITCH,
}
DEVICE_TRACKER_KEYS = {
KEY_LAN_HOST_INFO,
KEY_WLAN_HOST_LIST,
}
SENSOR_KEYS = {
KEY_DEVICE_INFORMATION,
KEY_DEVICE_SIGNAL,
KEY_MONITORING_CHECK_NOTIFICATIONS,
KEY_MONITORING_MONTH_STATISTICS,
KEY_MONITORING_STATUS,
KEY_MONITORING_TRAFFIC_STATISTICS,
KEY_NET_CURRENT_PLMN,
KEY_NET_NET_MODE,
KEY_SMS_SMS_COUNT,
}
SWITCH_KEYS = {KEY_DIALUP_MOBILE_DATASWITCH}
ALL_KEYS = (
BINARY_SENSOR_KEYS
| DEVICE_TRACKER_KEYS
| SENSOR_KEYS
| SWITCH_KEYS
| {KEY_DEVICE_BASIC_INFORMATION}
)
| Python | 2 | MrDelik/core | homeassistant/components/huawei_lte/const.py | [
"Apache-2.0"
] |
//
// Copyright (c) 2006, Brian Frank and Andy Frank
// Licensed under the Academic Free License version 3.0
//
// History:
// 4 Jan 06 Brian Frank Creation
//
**
** List represents an liner sequence of Objects indexed by an Int.
**
** See [examples]`examples::sys-lists`.
**
@Serializable
rtconst abstract class List<V>
{
//////////////////////////////////////////////////////////////////////////
// Constructor
//////////////////////////////////////////////////////////////////////////
**
** Constructor with of type and initial capacity.
**
static new make(Int capacity) {
return ArrayList<V>(capacity)
}
@NoDoc
static Obj?[] makeObj(Int capacity := 4) {
return ArrayList<Obj?>(capacity)
}
protected new privateMake() {}
const static Obj[] defVal := [,]
//////////////////////////////////////////////////////////////////////////
// Identity
//////////////////////////////////////////////////////////////////////////
**
** Two Lists are equal if they have the same type, the same
** number of items, and all the items at each index return
** true for 'equals'.
**
** Examples:
** [2, 3] == [2, 3] => true
** [2, 3] == [3, 2] => false
** [2, 3] == Num[2, 3] => false
** Str[,] == [,] => false
** Str[,] == Str?[,] => false
**
override Bool equals(Obj? other) {
if (other == null) return false
if (other isnot List) return false
that := other as V[]
//if (this.of != that.of) return false
if (this.size != that.size) return false
for (Int i:=0; i<size; ++i) {
if (this[i] != that[i]) return false
}
return true
}
**
** Return platform dependent hashcode based a hash of the items
** of the list.
**
override Int hash() {
Int hash := 33
each |obj| {
hash = (31*hash) + (obj == null ? 0 : (obj.hash))
}
return hash
}
**
** Get the item Type of this List.
**
** Examples:
** ["hi"].of => Str#
** [[2, 3]].of => Int[]#
**
//abstract Type? of()
//////////////////////////////////////////////////////////////////////////
// Access
//////////////////////////////////////////////////////////////////////////
**
** Return if size == 0. This method is readonly safe.
**
Bool isEmpty() { size == 0 }
**
** The number of items in the list. Getting size is readonly safe,
** setting size throws ReadonlyErr if readonly.
**
** If the size is set greater than the current size then the list is
** automatically grown to be a sparse list with new items defaulting
** to null. However if this is a non-nullable list, then growing a
** list will throw ArgErr.
**
** If the size is set less than the current size then any items with
** indices past the new size are automatically removed. Changing size
** automatically allocates new storage so that capacity exactly matches
** the new size.
**
abstract Int size
@NoDoc
Int sz() { size }
**
** The number of items this list can hold without allocating more memory.
** Capacity is always greater or equal to size. If adding a large
** number of items, it may be more efficient to manually set capacity.
** See the `trim` method to automatically set capacity to size. Throw
** ArgErr if attempting to set capacity less than size. Getting capacity
** is readonly safe, setting capacity throws ReadonlyErr if readonly.
**
abstract Int capacity
**
** Get is used to return the item at the specified the index. A
** negative index may be used to access an index from the end of the
** list. The get method is accessed via the [] shortcut operator. Throw
** IndexErr if index is out of range. This method is readonly safe.
**
@Operator abstract V get(Int index)
**
** Get the item at the specified index, but if index is out of
** range, then return 'def' parameter. A negative index may be
** used according to the same semantics as `get`. This method
** is readonly safe.
**
V? getSafe(Int index, V? defV := null) {
if (index < 0) {
index += size
if (index < 0) return defV
}
if (index >= size) {
return defV
}
return this[index]
}
**
** Return a sub-list based on the specified range. Negative indexes
** may be used to access from the end of the list. This method
** is accessed via the '[]' operator. This method is readonly safe.
** Throw IndexErr if range illegal.
**
** Examples:
** list := [0, 1, 2, 3]
** list[0..2] => [0, 1, 2]
** list[3..3] => [3]
** list[-2..-1] => [2, 3]
** list[0..<2] => [0, 1]
** list[1..-2] => [1, 2]
**
@Operator abstract V[] getRange(Range r)
**
** Return a sub-list based on the specified range
**
virtual List<V> slice(Range r) {
s := r.startIndex(size)
e := r.endIndex(size)
return ListView<V>(this, s, e+1-s)
}
**
** Return if this list contains the specified item.
** Equality is determined by `Obj.equals`. This method is readonly safe.
**
Bool contains(V item) {
findIndex |v,i->Bool| { v == item } != -1
}
**
** Return if this list contains the specified item.
** Equality is determined by '==='. This method is readonly safe.
**
Bool containsSame(V item) {
findIndex |v,i->Bool| { v === item } != -1
}
**
** Return if this list contains every item in the specified list.
** Equality is determined by `Obj.equals`. This method is readonly safe.
**
virtual Bool containsAll(V[] list) {
for (i:=0; i<list.size; ++i) {
obj := list[i]
if (!contains(obj)) {
return false
}
}
return true
}
**
** Return if this list contains any one of the items in the specified list.
** Equality is determined by `Obj.equals`. This method is readonly safe.
**
virtual Bool containsAny(V[] list) {
for (i:=0; i<list.size; ++i) {
obj := list[i]
if (contains(obj)) {
return true
}
}
return false
}
**
** Return the integer index of the specified item using
** the '==' operator (shortcut for equals method) to check
** for equality. Use `indexSame` to find with '===' operator.
** The search starts at the specified offset and returns
** the first match. The offset may be negative to access
** from end of list. Throw IndexErr if offset is out of
** range. If the item is not found return -1. This method
** is readonly safe.
**
Int index(V item, Int offset := 0) {
findIndex( |v,i->Bool| { v == item }, offset)
}
**
** Reverse index lookup. This method works just like `index`
** except that it searches backward from the starting offset.
**
Int indexr(V item, Int offset := -1) {
findrIndex( |v,i->Bool| { v == item }, offset)
}
**
** Return integer index just like `List.index` except
** use '===' same operator instead of the '==' equals operator.
**
Int indexSame(V item, Int offset := 0) {
findIndex( |v,i->Bool| { v === item }, offset)
}
**
** Return the item at index 0, or if empty return null.
** This method is readonly safe.
**
virtual V? first() {
if (size == 0) return null
return this[0]
}
**
** Return the item at index-1, or if empty return null.
** This method is readonly safe.
**
virtual V? last() {
if (size == 0) return null
return this[size-1]
}
**
** Create a shallow duplicate copy of this List. The items
** themselves are not duplicated. This method is readonly safe.
**
abstract List<V> dup()
//////////////////////////////////////////////////////////////////////////
// Modification
//////////////////////////////////////////////////////////////////////////
**
** Set is used to overwrite the item at the specified the index. A
** negative index may be used to access an index from the end of the
** list. The set method is accessed via the []= shortcut operator.
** If you wish to use List as a sparse array and set values greater
** then size, then manually set size larger. Return this. Throw
** IndexErr if index is out of range. Throw ReadonlyErr if readonly.
**
@Operator abstract This set(Int index, V item)
**
** Add the specified item to the end of the list. The item will have
** an index of size. Size is incremented by 1. Return this. Throw
** ReadonlyErr if readonly.
**
@Operator abstract This add(V item)
**
** Call `add` if item is non-null otherwise do nothing. Return this.
**
This addIfNotNull(V? item) {
if (item == null) return this
return add(item)
}
**
** Add all the items in the specified list to the end of this list.
** Size is incremented by list.size. Return this. Throw ReadonlyErr
** if readonly.
**
abstract This addAll(V[] list)
**
** Insert the item at the specified index. A negative index may be
** used to access an index from the end of the list. Size is incremented
** by 1. Return this. Throw IndexErr if index is out of range. Throw
** ReadonlyErr if readonly.
**
abstract This insert(Int index, V item)
**
** Insert all the items in the specified list into this list at the
** specified index. A negative index may be used to access an index
** from the end of the list. Size is incremented by list.size. Return
** this. Throw IndexErr if index is out of range. Throw ReadonlyErr
** if readonly.
**
abstract This insertAll(Int index, V[] list)
**
** Remove the specified value from the list. The value is compared
** using the == operator (shortcut for equals method). Use `removeSame`
** to remove with the === operator. Return the removed value and
** decrement size by 1. If the value is not found, then return null.
** Throw ReadonlyErr if readonly.
**
virtual V? remove(V item) {
index := index(item)
if (index == -1) return null
return removeAt(index)
}
**
** Remove the item just like `remove` except use
** the === operator instead of the == equals operator.
**
virtual V? removeSame(V item) {
index := indexSame(item)
if (index == -1) return null
return removeAt(index)
}
**
** Remove the object at the specified index. A negative index may be
** used to access an index from the end of the list. Size is decremented
** by 1. Return the item removed. Throw IndexErr if index is out of
** range. Throw ReadonlyErr if readonly.
**
abstract V? removeAt(Int index)
**
** Remove a range of indices from this list. Negative indexes
** may be used to access from the end of the list. Throw
** ReadonlyErr if readonly. Throw IndexErr if range illegal.
** Return this (*not* the removed items).
**
abstract This removeRange(Range r)
**
** Remove every item in this list which is found in the 'toRemove' list using
** same semantics as `remove` (compare for equality via the == operator).
** If any value is not found, it is ignored. Return this.
** Throw ReadonlyErr if readonly.
**
virtual This removeAll(V[] list) {
//modify
for (i:=0; i<list.size; ++i) {
obj := list[i]
remove(obj)
}
return this
}
**
** Remove all items from the list and set size to 0. Return this.
** Throw ReadonlyErr if readonly.
**
abstract This clear()
**
** Trim the capacity such that the underlying storage is optimized
** for the current size. Return this. Throw ReadonlyErr if readonly.
**
virtual This trim() {
capacity = size; return this
}
**
** Append a value to the end of the list the given number of times.
** Return this. Throw ReadonlyErr if readonly.
**
** Example:
** Int[,].fill(0, 3) => [0, 0, 0]
**
virtual This fill(V val, Int times) {
esize := size + times
if (esize > capacity) capacity = esize
for (i:=0; i<times; ++i) {
add(val)
}
return this
}
//////////////////////////////////////////////////////////////////////////
// Stack
//////////////////////////////////////////////////////////////////////////
**
** Return the item at index-1, or if empty return null.
** This method has the same semantics as last(). This method
** is readonly safe.
**
V? peek() { last }
**
** Remove the last item and return it, or return null if the list
** is empty. This method as the same semantics as remove(-1), with
** the exception of has an empty list is handled. Throw ReadonlyErr
** if readonly.
**
virtual V? pop() {
if (size == 0) return null
obj := last
removeAt(size-1)
return obj
}
**
** Add the specified item to the end of the list. Return this.
** This method has the same semantics as add(item). Throw ReadonlyErr
** if readonly.
**
This push(V item) { return add(item) }
//////////////////////////////////////////////////////////////////////////
// Iterators
//////////////////////////////////////////////////////////////////////////
**
** Call the specified function for every item in the list starting
** with index 0 and incrementing up to size-1. This method is
** readonly safe.
**
** Example:
** ["a", "b", "c"].each |Str s| { echo(s) }
**
virtual Void each(|V item, Int index| c) {
for (i:=0; i<size; ++i) {
c(get(i), i)
}
}
**
** Reverse each - call the specified function for every item in
** the list starting with index size-1 and decrementing down
** to 0. This method is readonly safe.
**
** Example:
** ["a", "b", "c"].eachr |Str s| { echo(s) }
**
virtual Void eachr(|V item, Int index| c) {
for (i:=size-1; i>=0; --i) {
c(get(i), i)
}
}
**
** Iterate the list usnig the specified range. Negative indexes
** may be used to access from the end of the list. This method is
** readonly safe. Throw IndexErr if range is invalid.
**
virtual Void eachRange(Range r, |V item, Int index| c) {
s := r.startIndex(size)
e := r.endIndex(size)
for (i:=s; i<=e; ++i) {
c(get(i), i)
}
}
**
** Iterate every item in the list starting with index 0 up to
** size-1 until the function returns non-null. If function
** returns non-null, then break the iteration and return the
** resulting object. Return null if the function returns
** null for every item. This method is readonly safe.
**
virtual Obj? eachWhile(|V item, Int index->Obj?| c, Int offset := 0) {
if (offset < 0) offset += size
for (i:=offset; i<size; ++i) {
res := c(get(i), i)
if (res != null) return res
}
return null
}
**
** Reverse `eachWhile`. Iterate every item in the list starting
** with size-1 down to 0. If the function returns non-null, then
** break the iteration and return the resulting object. Return
** null if the function returns null for every item. This method
** is readonly safe.
**
virtual Obj? eachrWhile(|V item, Int index->Obj?| c, Int offset := -1) {
if (offset < 0) offset += size
for (i:=offset; i>=0; --i) {
res := c(get(i), i)
if (res != null) return res
}
return null
}
**
** Return the first item in the list for which c returns true.
** If c returns false for every item, then return null. This
** method is readonly safe.
**
** Example:
** list := [0, 1, 2, 3, 4]
** list.find |Int v->Bool| { return v.toStr == "3" } => 3
** list.find |Int v->Bool| { return v.toStr == "7" } => null
**
V? find(|V item, Int index->Bool| c) {
i := findIndex |v,i->Bool| { c(v,i) }
return i == -1 ? null : get(i)
}
**
** Return the index of the first item in the list for which c returns
** true. If c returns false for every item, then return -1. This
** method is readonly safe.
**
** Example:
** list := [5, 6, 7]
** list.findIndex |Int v->Bool| { return v.toStr == "7" } => 2
** list.findIndex |Int v->Bool| { return v.toStr == "9" } => -1
**
virtual Int findIndex(|V item, Int index->Bool| c, Int offset := 0) {
if (offset < 0) offset += size
for (i:=offset; i<size; ++i) {
obj := this[i]
result := c(obj, i)
if (result) {
return i
}
}
return -1
}
virtual Int findrIndex(|V item, Int index->Bool| c, Int offset := -1) {
if (offset < 0) offset += size
for (i:=offset; i>=0; --i) {
obj := this[i]
result := c(obj, i)
if (result) {
return i
}
}
return -1
}
**
** Return a new list containing the items for which c returns
** true. If c returns false for every item, then return an
** empty list. The inverse of this method is exclude(). This
** method is readonly safe.
**
** Example:
** list := [0, 1, 2, 3, 4]
** list.findAll |Int v->Bool| { return v%2==0 } => [0, 2, 4]
**
V[] findAll(|V item, Int index->Bool| c) {
nlist := List.make(1)
each |obj, i| {
result := c(obj, i)
if (result) {
nlist.add(obj)
}
}
return nlist
}
**
** Return a new list containing the items for which c returns
** false. If c returns true for every item, then return an
** empty list. The inverse of this method is findAll(). This
** method is readonly safe.
**
** Example:
** list := [0, 1, 2, 3, 4]
** list.exclude |Int v->Bool| { return v%2==0 } => [1, 3]
**
V[] exclude(|V item, Int index->Bool| c) {
nlist := List.make(1)
each |obj, i| {
result := c(obj, i)
if (!result) {
nlist.add(obj)
}
}
return nlist
}
**
** Return true if c returns true for any of the items in
** the list. If the list is empty, return false. This method
** is readonly safe.
**
** Example:
** list := ["ant", "bear"]
** list.any |Str v->Bool| { return v.size >= 4 } => true
** list.any |Str v->Bool| { return v.size >= 5 } => false
**
Bool any(|V item, Int index->Bool| c) {
findIndex |v,i->Bool| { c(v,i) } != -1
}
**
** Return true if c returns true for all of the items in
** the list. If the list is empty, return true. This method
** is readonly safe.
**
** Example:
** list := ["ant", "bear"]
** list.all |Str v->Bool| { return v.size >= 3 } => true
** list.all |Str v->Bool| { return v.size >= 4 } => false
**
Bool all(|V item, Int index->Bool| c) {
findIndex |v,i->Bool| { !c(v,i) } == -1
}
**
** Create a new list which is the result of calling c for
** every item in this list. The new list is typed based on
** the return type of c. This method is readonly safe.
**
** Example:
** list := [3, 4, 5]
** list.map |Int v->Int| { return v*2 } => [6, 8, 10]
**
Obj?[] map(|V item, Int index->Obj?| c) {
nlist := List.make(size)
each |obj, i| {
result := c(obj, i)
nlist.add(result)
}
return nlist
}
**
** This is a combination of `map` and `flatten`. Each item in
** this list is mapped to zero or more new items by the given function
** and the results are returned in a single flattened list. Note
** unlike `flatten` only one level of flattening is performed.
** The new list is typed based on the return type of c. This
** method is readonly safe.
**
** Example:
** list := ["a", "b"]
** list.flatMap |v->Str[]| { [v, v.upper] } => ["a", "A", "b", "B"]
**
Obj?[] flatMap(|V item, Int index->Obj?[]| c) {
nlist := List.make(size)
each |obj, i| {
result := c(obj, i)
nlist.addAll(result)
}
return nlist
}
**
** Reduce is used to iterate through every item in the list
** to reduce the list into a single value called the reduction.
** The initial value of the reduction is passed in as the init
** parameter, then passed back to the closure along with each
** item. This method is readonly safe.
**
** Example:
** list := [1, 2, 3]
** list.reduce(0) |Obj r, Int v->Obj| { return (Int)r + v } => 6
**
Obj? reduce(Obj? init, |Obj? reduction, V item, Int index->Obj?| c) {
Obj? reduction := init
each |obj, i| {
reduction = c(reduction, obj, i)
}
return reduction
}
**
** Return the minimum value of the list. If c is provided, then it
** implements the comparator returning -1, 0, or 1. If c is null
** then the <=> operator is used (shortcut for compare method). If
** the list is empty, return null. This method is readonly safe.
**
** Example:
** list := ["albatross", "dog", "horse"]
** list.min => "albatross"
** list.min |Str a, Str b->Int| { return a.size <=> b.size } => "dog"
**
V? min(|V a, V b->Int|? c := null) {
Obj? min
each |obj, i| {
if (i == 0) {
min = obj
return
}
Int result
if (c!=null) result = c(min, obj)
else result = min <=> obj
if (result > 0) {
min = obj
}
}
return min
}
**
** Return the maximum value of the list. If c is provided, then it
** implements the comparator returning -1, 0, or 1. If c is null
** then the <=> operator is used (shortcut for compare method). If
** the list is empty, return null. This method is readonly safe.
**
** Example:
** list := ["albatross", "dog", "horse"]
** list.max => "horse"
** list.max |Str a, Str b->Int| { return a.size <=> b.size } => "albatross"
**
V? max(|V a, V b->Int|? c := null) {
Obj? max
each |obj, i| {
if (i == 0) {
max = obj
return
}
Int result
if (c!=null) result = c(max, obj)
else result = max <=> obj
if (result < 0) {
max = obj
}
}
return max
}
//////////////////////////////////////////////////////////////////////////
// Utils
//////////////////////////////////////////////////////////////////////////
private Void insertSort(Int left, Int right, |V a, V b->Int| cmopFunc) {
self := this
for (i:=left;i < right; i++) {
curVal := self[i+1]
j := i
//shift right
while (j>=left && (cmopFunc(curVal, self[j]) < 0)) {
self[j+1] = self[j]
--j
}
self[j+1] = curVal
}
}
private Void quickSort(Int low, Int high, |V a, V b->Int| cmopFunc) {
if (low == high) return
if(!(low < high)) throw Err("$low >= $high")
//if too small using insert sort
if (high - low < 5) {
insertSort(low, high, cmopFunc)
return
}
self := this
i := low; j := high
//select pivot
pivot := (j+i)/2
min := i
max := j
if (self[i] > self[j]) {
min = j
max = i
}
if (self[pivot] < self[min]) {
pivot = min
}
else if (self[pivot] > self[max]) {
pivot = max
}
pivotVal := self[pivot]
self[pivot] = self[i]
while (i < j) {
while (i<j && cmopFunc(pivotVal, self[j]) <= 0 ) --j
//self[i] is empty
if (i < j) {
self[i] = self[j]
++i
}
while (i<j && cmopFunc(self[i], pivotVal) < 0) ++i
//self[j] is empty
if (i < j) {
self[j] = self[i]
--j
}
}
self[i] = pivotVal
if (low < i-1) {
quickSort(low, i-1, cmopFunc)
}
if (i+1 < high) {
quickSort(j+1, high, cmopFunc)
}
}
**
** Perform an in-place sort on this list. If a method is provided
** it implements the comparator returning -1, 0, or 1. If the
** comparator method is null then sorting is based on the
** value's <=> operator (shortcut for 'compare' method). Return this.
** Throw ReadonlyErr if readonly.
**
** Example:
** s := ["candy", "ate", "he"]
**
** s.sort
** // s now evaluates to [ate, candy, he]
**
** s.sort |Str a, Str b->Int| { return a.size <=> b.size }
** // s now evaluates to ["he", "ate", "candy"]
**
virtual This sort(|V a, V b->Int|? c := null) {
//modify
if (size <= 1) return this
if (c == null) c = |a, b->Int| { a <=> b }
quickSort(0, size-1, c)
return this
}
**
** Reverse sort - perform an in-place reverse sort on this list. If
** a method is provided it implements the comparator returning -1,
** 0, or 1. If the comparator method is null then sorting is based
** on the items <=> operator (shortcut for 'compare' method). Return
** this. Throw ReadonlyErr if readonly.
**
** Example:
** [3, 2, 4, 1].sortr => [4, 3, 2, 1]
**
This sortr(|V a, V b->Int|? c := null) {
sort |a, b| {
if (c == null) return -(a <=> b)
return -c(a, b)
}
}
//return -(insertation point) - 1
private Int bsearch(|V b, Int i->Int| cmopFunc) {
self := this
n := size
if (n == 0) return -1
low := 0
high := n - 1
while (low <= high) {
mid := (low+high) / 2
cond := cmopFunc(self[mid], mid)
if (cond < 0) {
high = mid - 1
} else if (cond > 0) {
low = mid + 1
} else {
return mid
}
}
return -(low+1)
}
**
** Search the list for the index of the specified key using a binary
** search algorithm. The list must be sorted in ascending order according
** to the specified comparator function. If the list contains multiple
** matches for key, no guarantee is made to which one is returned. If
** the comparator is null then then it is assumed to be the '<=>'
** operator (shortcut for the 'compare' method). If the key is not found,
** then return a negative value which is '-(insertation point) - 1'.
**
virtual Int binarySearch(V key, |V a, V b->Int|? c := null) {
return bsearch |b, i| {
if (c == null) return key <=> b
return c(key, b)
}
}
**
** Find an element in the list using a binary search algorithm. The specified
** comparator function returns a negative integer, zero, or a positive integer
** if the desired object is less than, equal to, or greater than specified item.
** The list must be sorted in ascending order according to the specified
** comparator function. If the key is not found, then return a negative value
** which is '-(insertation point) - 1'.
**
virtual Int binaryFind(|V item, Int index->Int| c) {
return bsearch(c)
}
**
** Reverse the order of the items of this list in-place. Return this.
** Throw ReadonlyErr if readonly.
**
** Example:
** [1, 2, 3, 4].reverse => [4, 3, 2, 1]
**
virtual This reverse() {
if (size <= 1) return this
n := size
for (i:=0; i<n; ++i) {
j := n-i-1
if (i >= j) break
a := this[i]
b := this[j]
this[j] = a
this[i] = b
}
return this
}
**
** Swap the items at the two specified indexes. Negative indexes may
** used to access an index from the end of the list. Return this.
** Throw ReadonlyErr if readonly.
**
virtual This swap(Int indexA, Int indexB) {
if (indexA < 0) indexA += size
if (indexB < 0) indexB += size
a := this[indexA]
b := this[indexB]
this[indexB] = a
this[indexA] = b
return this
}
**
** Find the given item, and move it to the given index. All the
** other items are shifted accordingly. Negative indexes may
** used to access an index from the end of the list. If the item is
** null or not found then this is a no op. Return this. Throw
** ReadonlyErr if readonly.
**
** Examples:
** [10, 11, 12].moveTo(11, 0) => [11, 10, 12]
** [10, 11, 12].moveTo(11, -1) => [10, 12, 11]
**
virtual This moveTo(V? item, Int toIndex) {
if (item == null) return this
i := index(item)
if (i == -1) return this
//must deal with before removeAt
if (toIndex < 0) toIndex += size
removeAt(i)
insert(toIndex, item)
return this
}
**
** Return a new list which recursively flattens any list items into
** a one-dimensional result. This method is readonly safe.
**
** Examples:
** [1,2,3].flatten => [1,2,3]
** [[1,2],[3]].flatten => [1,2,3]
** [1,[2,[3]],4].flatten => [1,2,3,4]
**
Obj?[] flatten() {
nlist := List.make(size)
each |item| {
if (item is List) {
f := (item as List)?.flatten
if (f != null) {
nlist.addAll(f)
}
} else {
nlist.add(item)
}
}
return nlist
}
**
** Return a random item from the list. If the list is empty
** return null. This method is readonly safe. Also see
** `Int.random`, `Float.random`, `Range.random`, and `util::Random`.
**
V? random() {
if (size == 0) return null
r := 0..<size
return this[r.random]
}
**
** Shuffle this list's items into a randomized order.
** Return this. Throw ReadonlyErr if readonly.
**
This shuffle() {
//modify
r := 0..<size
each |v, i| {
swap(i, r.random)
}
return this
}
//////////////////////////////////////////////////////////////////////////
// Conversion
//////////////////////////////////////////////////////////////////////////
**
** Return a string representation the list. This method is readonly safe.
**
override Str toStr() {
if (size == 0) return "[,]"
buf := StrBuf()
buf.add("[")
each |item, i| {
if (i != 0) buf.add(", ")
buf.add(item)
}
buf.add("]")
return buf.toStr
}
**
** Return a string by concatenating each item's toStr result
** using the specified separator string. If c is non-null
** then it is used to format each item into a string, otherwise
** Obj.toStr is used. This method is readonly safe.
**
** Example:
** ["a", "b", "c"].join => "abc"
** ["a", "b", "c"].join("-") => "a-b-c"
** ["a", "b", "c"].join("-") |Str s->Str| { return "($s)" } => "(a)-(b)-(c)"
**
Str join(Str separator := "", |V item, Int index->Str|? c := null) {
buf := StrBuf()
each |item, i| {
if (i != 0) buf.add(separator)
if (c != null) {
buf.add(c(item, i))
} else {
buf.add(item)
}
}
return buf.toStr
}
**
** Get this list as a Fantom expression suitable for code generation.
** The individual items must all respond to the 'toCode' method.
**
Str toCode() {
if (size == 0) return "[,]"
buf := StrBuf()
buf.add("[")
each |item, i| {
if (i != 0) buf.add(", ")
buf.add(item->toCode)
}
buf.add("]")
return buf.toStr
}
//////////////////////////////////////////////////////////////////////////
// Readonly
//////////////////////////////////////////////////////////////////////////
**
** Return if this List is readonly. A readonly List is guaranteed to
** be immutable (although its items may be mutable themselves). Any
** attempt to modify a readonly List will result in ReadonlyErr. Use
** `rw` to get a read-write List from a readonly List. Methods
** documented as "readonly safe" may be used safely with a readonly List.
** This method is readonly safe.
**
abstract Bool isRO()
**
** Return if this List is read-write. A read-write List is mutable
** and may be modified. Use `ro` to get a readonly List from a
** read-write List. This method is readonly safe.
**
Bool isRW() { !isRO }
**
** Get a readonly List instance with the same contents as this
** List (although the items may be mutable themselves). If this
** List is already readonly, then return this. Only methods
** documented as "readonly safe" may be used safely with a readonly
** List, all others will throw ReadonlyErr. This method is readonly
** safe. See `Obj.isImmutable` and `Obj.toImmutable` for deep
** immutability.
**
virtual This ro() {
if (isRO) return this
ArrayList<V> nlist := dup
nlist.readOnly = true
return nlist
}
**
** Get a read-write, mutable List instance with the same contents
** as this List. If this List is already read-write, then return this.
** This method is readonly safe.
**
virtual This rw() {
if (isRW) return this
ArrayList<V> nlist := dup
nlist.readOnly = false
return nlist
}
override abstract Bool isImmutable()
override V[] toImmutable() {
if (isImmutable) return this
nlist := ArrayList<V>(size)
each |v| { nlist.add(v?.toImmutable) }
nlist.readOnly = true
nlist.immutable = true
return nlist
}
} | Fantom | 5 | fanx-dev/fanx | library/sys/fan/lang/List.fan | [
"AFL-3.0"
] |
#!/bin/sh
if [ "x${enable_fill}" = "x1" ] ; then
export MALLOC_CONF="junk:false"
fi
| Shell | 2 | Mu-L/jemalloc | test/integration/smallocx.sh | [
"BSD-2-Clause"
] |
// 目的:测试元组使用方法
package TupleTest;
module mkTb();
rule test;
// 元组的基本用法测试 ---------------------------------------------------------------------------------------------------------------
Tuple2#(Bool, Int#(9)) t2 = tuple2(True, -25); // 一个2元组
Tuple8#(int, Bool, Bool, int, UInt#(3), int, bit, Int#(6)) t8 = tuple8(-3, False, False, 19, 1, 7, 'b1, 45); // 一个8元组
Bool v3 = tpl_3(t8); // 获取 t8 的第三个元素(False)
match {.va, .vb} = t2; // 隐式定义了2个变量来承接 t2 的值
$display("va=%d vb=%d v3=%d", va, vb, v3);
// 把一个 Bit#(13) 变量拆成 Bit#(8) (高位)和一个 Bit#(5) ---------------------------------------------------------------------------
Bit#(13) b13 = 'b1011100101100;
Tuple2#(Bit#(8), Bit#(5)) tsplit = split(b13);
match {.b8, .b5} = tsplit;
$display("%b %b", b8, b5);
$finish;
endrule
endmodule
endpackage
| Bluespec | 4 | Xiefengshang/BSV_Tutorial_cn | src/5.TupleTest/TupleTest.bsv | [
"MIT"
] |
<?xml version="1.0" encoding="UTF-8"?>
<!-- ******************************************************************* -->
<!-- -->
<!-- © Copyright IBM Corp. 2010, 2012 -->
<!-- -->
<!-- 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. -->
<!-- -->
<!-- ******************************************************************* -->
<faces-config>
<faces-config-extension>
<namespace-uri>http://www.ibm.com/xsp/coreex</namespace-uri>
<default-prefix>xe</default-prefix>
<designer-extension>
<control-subpackage-name>data</control-subpackage-name>
</designer-extension>
</faces-config-extension>
<!-- move to extlib-data-formlayout.xsp-config -->
<!-- FORM LAYOUT COMPONENTS -->
<component>
<description>Abstract base control for a form layout control, which is an area containing multiple edit boxes or other input controls and a submit button or link used to save the changes.</description>
<display-name>Abstract Form Layout</display-name>
<component-type>com.ibm.xsp.extlib.data.FormLayout</component-type>
<component-class>com.ibm.xsp.extlib.component.data.FormLayout</component-class>
<group-type-ref>com.ibm.xsp.group.core.prop.style</group-type-ref>
<group-type-ref>com.ibm.xsp.group.core.prop.styleClass</group-type-ref>
<property>
<description>Disable the error summary panel, showing the server side errors</description>
<display-name>Disable Error Summary</display-name>
<property-name>disableErrorSummary</property-name>
<property-class>boolean</property-class>
<property-extension>
<designer-extension>
<category>basics</category>
</designer-extension>
</property-extension>
</property>
<property>
<description>Overrides the default text of the error summary</description>
<display-name>Error Summary Text</display-name>
<property-name>errorSummaryText</property-name>
<property-class>java.lang.String</property-class>
<property-extension>
<localizable>true</localizable>
<designer-extension>
<category>basics</category>
</designer-extension>
</property-extension>
</property>
<property>
<description>Defines if the validation errors should be displayed per field</description>
<display-name>Disable Error Field</display-name>
<property-name>disableRowError</property-name>
<property-class>boolean</property-class>
<property-extension>
<designer-extension>
<category>basics</category>
</designer-extension>
</property-extension>
</property>
<property>
<description>Title of the form, to be displayed at the top of the form area.</description>
<display-name>Form Title</display-name>
<property-name>formTitle</property-name>
<property-class>java.lang.String</property-class>
<property-extension>
<localizable>true</localizable>
<designer-extension>
<category>basics</category>
<tags>
not-accessibility-title
</tags>
</designer-extension>
</property-extension>
</property>
<property>
<description>Description of the form to be displayed.</description>
<display-name>Form Description</display-name>
<property-name>formDescription</property-name>
<property-class>java.lang.String</property-class>
<property-extension>
<localizable>true</localizable>
<designer-extension>
<category>basics</category>
<!-- TODO should probably also support a "description" facet
in case the description should have links or be HTML
with bold, UL tags, etc.-->
<tags>
todo
</tags>
</designer-extension>
</property-extension>
</property>
<property>
<description>Defines if a help link should be generated per field</description>
<display-name>Field Help</display-name>
<property-name>fieldHelp</property-name>
<property-class>boolean</property-class>
<property-extension>
<designer-extension>
<category>basics</category>
<!-- TODO this is inherently broken/unimplemented and may have to be removed
and implemented in some different fashion -->
<tags>
todo
</tags>
</designer-extension>
</property-extension>
</property>
<property>
<!-- TODO the description doesn't mention "none", is it a valid option? -->
<!-- # "above", "left" and "none" should not be translated -->
<description>Position of the label relative to the input control or main area. Either the label appears above the input ("above") or at the start of the row containing the input ("left"). The default value is "left". Note, this value is the default for this Form Table control, but the option can be overridden in a Form Layout Row control using the "labelPosition" property on that control.</description>
<display-name>Label Position</display-name>
<property-name>labelPosition</property-name>
<property-class>java.lang.String</property-class>
<property-extension>
<designer-extension>
<category>format</category>
<editor>com.ibm.workplace.designer.property.editors.comboParameterEditor</editor>
<editor-parameter>
above
left
none
</editor-parameter>
<!-- not localizable because it is not translatable text displayed to the end user.-->
<tags>
not-localizable
todo
</tags>
</designer-extension>
</property-extension>
</property>
<property>
<description>Prevents the "*" marks appearing before the required field labels.</description>
<display-name>Disable Required Marks</display-name>
<property-name>disableRequiredMarks</property-name>
<property-class>boolean</property-class>
<property-extension>
<designer-extension>
<category>format</category>
</designer-extension>
</property-extension>
</property>
<property>
<description>Specifies the fieldset legend for nested Form Controls</description>
<display-name>Fieldset Legend</display-name>
<property-name>legend</property-name>
<property-class>java.lang.String</property-class>
<property-extension>
<localizable>true</localizable>
<designer-extension>
<category>accessibility</category>
<tags>
localizable-text
</tags>
</designer-extension>
</property-extension>
</property>
<component-extension>
<component-family>com.ibm.xsp.extlib.data.FormLayout</component-family>
<designer-extension>
</designer-extension>
</component-extension>
</component>
<component>
<description>Displaying a form of input controls with rows containing labels and error fields, an overall title and an area at the bottom for the Save and Cancel actions.</description>
<display-name>Form Table</display-name>
<component-type>com.ibm.xsp.extlib.data.FormTable</component-type>
<component-class>com.ibm.xsp.extlib.component.data.UIFormTable</component-class>
<group-type-ref>com.ibm.xsp.extlib.group.aria_label</group-type-ref>
<property>
<!-- TODO these *Width properties are bad practice - should provide a Style property instead. -->
<description>Width of the column label, expressed in CSS units (e.g. 15% or 150px...).</description>
<display-name>Label Width</display-name>
<property-name>labelWidth</property-name>
<property-class>java.lang.String</property-class>
<property-extension>
<designer-extension>
<category>basics</category>
<!-- note, this allows values like "30px" or "50%", i.e. not an integer -->
<!-- xe:applicationConfiguration.legalLogoHeight has a TODO asking
for a new CSS dimension editor to replace this comboParam -->
<editor>com.ibm.workplace.designer.property.editors.comboParameterEditor</editor>
<editor-parameter>
50%
30px
10em
2cm
auto
inherit
</editor-parameter>
<!-- not localizable because it is a CSS width-->
<tags>
not-localizable
todo
</tags>
</designer-extension>
</property-extension>
</property>
<component-extension>
<base-component-type>com.ibm.xsp.extlib.data.FormLayout</base-component-type>
<component-family>com.ibm.xsp.extlib.data.FormLayout</component-family>
<renderer-type>com.ibm.xsp.extlib.data.OneUIFormTable</renderer-type>
<tag-name>formTable</tag-name>
<designer-extension>
<in-palette>true</in-palette>
<category>Extension Library</category>
<!-- TODO visualization should have the header and footer facets -->
<!-- TODO support putting some formTable rows into a custom control,
currently there's a hack, involving nesting an inner formTable
inside the outer formtable, but from a screen-reader point of view,
that won't work, so need some proper mechanism so it works for accessibility -->
<tags>
todo
</tags>
</designer-extension>
</component-extension>
</component>
<component>
<description>Form layout row control.</description>
<display-name>Form Layout Row</display-name>
<component-type>com.ibm.xsp.extlib.data.FormLayoutRow</component-type>
<component-class>com.ibm.xsp.extlib.component.data.UIFormLayoutRow</component-class>
<group-type-ref>com.ibm.xsp.group.core.prop.style</group-type-ref>
<group-type-ref>com.ibm.xsp.group.core.prop.styleClass</group-type-ref>
<property>
<description>Label to be displayed for the field.</description>
<display-name>Label</display-name>
<property-name>label</property-name>
<property-class>java.lang.String</property-class>
<property-extension>
<localizable>true</localizable>
<designer-extension>
<category>basics</category>
</designer-extension>
</property-extension>
</property>
<property>
<description>Width of the label column, expressed in CSS units (e.g. 15% or 150px...).</description>
<display-name>Label Width</display-name>
<property-name>labelWidth</property-name>
<property-class>java.lang.String</property-class>
<property-extension>
<designer-extension>
<category>basics</category>
<!-- note, this allows values like "30px" or "50%", i.e. not an integer -->
<!-- xe:applicationConfiguration.legalLogoHeight has a TODO asking
for a new CSS dimension editor to replace this comboParam -->
<editor>com.ibm.workplace.designer.property.editors.comboParameterEditor</editor>
<editor-parameter>
50%
30px
10em
2cm
auto
inherit
</editor-parameter>
<!-- not localizable because it is a CSS width-->
<tags>
not-localizable
</tags>
</designer-extension>
</property-extension>
</property>
<property>
<description>Holds the ID of the control used to edit the data. That control should be contained within this Form Layout Row control.</description>
<display-name>For Identifier</display-name>
<property-name>for</property-name>
<property-class>java.lang.String</property-class>
<property-extension>
<designer-extension>
<category>basics</category>
<editor>com.ibm.designer.domino.xsp.idpicker</editor>
</designer-extension>
</property-extension>
</property>
<property>
<description>Holds the help ID for the edited field.</description>
<display-name>Help ID</display-name>
<property-name>helpId</property-name>
<property-class>java.lang.String</property-class>
<property-extension>
<!-- TODO the code doesn't seem to be converting this helpId to a clientId-->
<designer-extension>
<category>basics</category>
<!-- TODO should this use the id-reference editor? -->
<!-- not sure - is it the id to be assigned to an auto-generated control,
or is it a reference to the id of an existing control?
or even is it a facetName? -->
<!-- Think it was attempting to assume that the help link would be within the formRow,
but it may make more sense for there to be a help facet,
as the help goes into a separate column. -->
<!-- TODO should this be allow-run-time-binding>false< ? -->
<!-- TODO description should explain that there is a help facet too -->
<tags>
todo
</tags>
<editor>com.ibm.designer.domino.xsp.idpicker</editor>
</designer-extension>
</property-extension>
</property>
<property>
<!-- # "above", "left", "none", "inherit" should not be translated -->
<description>Position of the label relative to the input control or main area. The label can appear above the input ("above"), or at the start of the row containing the input ("left"), or else the position depends on the Label Position property on the container Form Table control ("inherit"). The default value is "inherit".</description>
<display-name>Label Position</display-name>
<property-name>labelPosition</property-name>
<property-class>java.lang.String</property-class>
<property-extension>
<designer-extension>
<category>format</category>
<editor>com.ibm.workplace.designer.property.editors.comboParameterEditor</editor>
<editor-parameter>
above
left
none
inherit
</editor-parameter>
<!-- not localizable because it is not translatable text displayed to the end user.-->
<!-- TODO description does not explain the "none" option, is it supported?-->
<tags>
not-localizable
todo
</tags>
</designer-extension>
</property-extension>
</property>
<component-extension>
<component-family>com.ibm.xsp.extlib.FormLayout</component-family>
<renderer-type>com.ibm.xsp.extlib.data.FormLayoutRow</renderer-type>
<tag-name>formRow</tag-name>
<designer-extension>
<in-palette>true</in-palette>
<category>Extension Library</category>
<!-- TODO visualization should have the help and label facets -->
<tags>
todo
no-faces-config-renderer
</tags>
</designer-extension>
</component-extension>
</component>
<component>
<description>Form layout column control.</description>
<display-name>Form Layout Column</display-name>
<component-type>com.ibm.xsp.extlib.data.FormLayoutColumn</component-type>
<component-class>com.ibm.xsp.extlib.component.data.UIFormLayoutColumn</component-class>
<group-type-ref>com.ibm.xsp.group.core.prop.style</group-type-ref>
<group-type-ref>com.ibm.xsp.group.core.prop.styleClass</group-type-ref>
<property>
<description>This attribute specifies the number of columns spanned by the current cell. The default value of this attribute is one ("1"). The value zero ("0") means that the cell spans all columns from the current column to the last column of the column group (COLGROUP) in which the cell is defined.</description>
<display-name>Column Span</display-name>
<property-name>colSpan</property-name>
<property-class>int</property-class>
<property-extension>
<designer-extension>
<category>basics</category>
<!-- TODO the description says the default value is 1, but getter has the default value of 0-->
<tags>
todo
</tags>
</designer-extension>
</property-extension>
</property>
<component-extension>
<component-family>com.ibm.xsp.extlib.FormLayout</component-family>
<renderer-type>com.ibm.xsp.extlib.data.FormLayoutColumn</renderer-type>
<tag-name>formColumn</tag-name>
<designer-extension>
<in-palette>true</in-palette>
<category>Extension Library</category>
<tags>
no-faces-config-renderer
</tags>
</designer-extension>
</component-extension>
</component>
<!-- /end move to extlib-data-formlayout.xsp-config -->
</faces-config>
| XPages | 4 | jesse-gallagher/XPagesExtensionLibrary | extlib/lwp/product/runtime/eclipse/plugins/com.ibm.xsp.extlib.controls/src/com/ibm/xsp/extlib/config/raw-extlib-data-formlayout.xsp-config | [
"Apache-2.0"
] |
diff --git opencensus/stats/internal/delta_producer.cc opencensus/stats/internal/delta_producer.cc
index c61b4d9..b3e4ef2 100644
--- opencensus/stats/internal/delta_producer.cc
+++ opencensus/stats/internal/delta_producer.cc
@@ -75,6 +75,20 @@ DeltaProducer* DeltaProducer::Get() {
return global_delta_producer;
}
+void DeltaProducer::Shutdown() {
+ {
+ absl::MutexLock l(&mu_);
+ if (!thread_started_) {
+ return;
+ }
+ thread_started_ = false;
+ }
+ // Join loop thread when shutdown.
+ if (harvester_thread_.joinable()) {
+ harvester_thread_.join();
+ }
+}
+
void DeltaProducer::AddMeasure() {
delta_mu_.Lock();
absl::MutexLock harvester_lock(&harvester_mu_);
@@ -115,7 +129,10 @@ void DeltaProducer::Flush() {
}
DeltaProducer::DeltaProducer()
- : harvester_thread_(&DeltaProducer::RunHarvesterLoop, this) {}
+ : harvester_thread_(&DeltaProducer::RunHarvesterLoop, this) {
+ absl::MutexLock l(&mu_);
+ thread_started_ = true;
+}
void DeltaProducer::SwapDeltas() {
ABSL_ASSERT(last_delta_.delta().empty() && "Last delta was not consumed.");
@@ -131,11 +148,19 @@ void DeltaProducer::RunHarvesterLoop() {
absl::Time next_harvest_time = absl::Now() + harvest_interval_;
while (true) {
const absl::Time now = absl::Now();
- absl::SleepFor(next_harvest_time - now);
+ absl::SleepFor(absl::Seconds(0.1));
// Account for the possibility that the last harvest took longer than
// harvest_interval_ and we are already past next_harvest_time.
- next_harvest_time = std::max(next_harvest_time, now) + harvest_interval_;
- Flush();
+ if (absl::Now() > next_harvest_time) {
+ next_harvest_time = std::max(next_harvest_time, now) + harvest_interval_;
+ Flush();
+ }
+ {
+ absl::MutexLock l(&mu_);
+ if (!thread_started_) {
+ break;
+ }
+ }
}
}
diff --git opencensus/stats/internal/delta_producer.h opencensus/stats/internal/delta_producer.h
index 2cff522..c8e2e95 100644
--- opencensus/stats/internal/delta_producer.h
+++ opencensus/stats/internal/delta_producer.h
@@ -71,6 +71,8 @@ class DeltaProducer final {
// Returns a pointer to the singleton DeltaProducer.
static DeltaProducer* Get();
+ void Shutdown();
+
// Adds a new Measure.
void AddMeasure();
@@ -122,6 +124,9 @@ class DeltaProducer final {
// thread when calling a flush during harvesting.
Delta last_delta_ GUARDED_BY(harvester_mu_);
std::thread harvester_thread_ GUARDED_BY(harvester_mu_);
+
+ mutable absl::Mutex mu_;
+ bool thread_started_ GUARDED_BY(mu_) = false;
};
} // namespace stats
diff --git opencensus/stats/internal/stats_exporter.cc opencensus/stats/internal/stats_exporter.cc
index 43ddbc7..37b4ae1 100644
--- opencensus/stats/internal/stats_exporter.cc
+++ opencensus/stats/internal/stats_exporter.cc
@@ -95,25 +95,52 @@ void StatsExporterImpl::ClearHandlersForTesting() {
}
void StatsExporterImpl::StartExportThread() EXCLUSIVE_LOCKS_REQUIRED(mu_) {
- t_ = std::thread(&StatsExporterImpl::RunWorkerLoop, this);
thread_started_ = true;
+ t_ = std::thread(&StatsExporterImpl::RunWorkerLoop, this);
+}
+
+void StatsExporterImpl::Shutdown() {
+ {
+ absl::MutexLock l(&mu_);
+ if (!thread_started_) {
+ return;
+ }
+ thread_started_ = false;
+ }
+ // Join loop thread when shutdown.
+ if (t_.joinable()) {
+ t_.join();
+ }
}
void StatsExporterImpl::RunWorkerLoop() {
absl::Time next_export_time = GetNextExportTime();
while (true) {
// SleepFor() returns immediately when given a negative duration.
- absl::SleepFor(next_export_time - absl::Now());
+ absl::SleepFor(absl::Seconds(0.1));
// In case the last export took longer than the export interval, we
// calculate the next time from now.
- next_export_time = GetNextExportTime();
- Export();
+ if (absl::Now() > next_export_time) {
+ next_export_time = GetNextExportTime();
+ Export();
+ }
+ {
+ absl::MutexLock l(&mu_);
+ if (!thread_started_) {
+ break;
+ }
+ }
}
}
// StatsExporter
// -------------
+void StatsExporter::Shutdown() {
+ StatsExporterImpl::Get()->Shutdown();
+ StatsExporterImpl::Get()->ClearHandlersForTesting();
+}
+
// static
void StatsExporter::SetInterval(absl::Duration interval) {
StatsExporterImpl::Get()->SetInterval(interval);
diff --git opencensus/stats/internal/stats_exporter_impl.h opencensus/stats/internal/stats_exporter_impl.h
index 11ae3c4..ebe9c4d 100644
--- opencensus/stats/internal/stats_exporter_impl.h
+++ opencensus/stats/internal/stats_exporter_impl.h
@@ -34,6 +34,7 @@ class StatsExporterImpl {
public:
static StatsExporterImpl* Get();
void SetInterval(absl::Duration interval);
+ void Shutdown();
absl::Time GetNextExportTime() const;
void AddView(const ViewDescriptor& view);
void RemoveView(absl::string_view name);
diff --git opencensus/stats/stats_exporter.h opencensus/stats/stats_exporter.h
index 6756858..65e0262 100644
--- opencensus/stats/stats_exporter.h
+++ opencensus/stats/stats_exporter.h
@@ -45,6 +45,8 @@ class StatsExporter final {
// Removes the view with 'name' from the registry, if one is registered.
static void RemoveView(absl::string_view name);
+ static void Shutdown();
+
// StatsExporter::Handler is the interface for push exporters that export
// recorded data for registered views. The exporter should provide a static
// Register() method that takes any arguments needed by the exporter (e.g. a
| Diff | 4 | firebolt55439/ray | thirdparty/patches/opencensus-cpp-shutdown-api.patch | [
"Apache-2.0"
] |
--TEST--
Bug #42107 (sscanf() broken when using %2$s type format parameters)
--FILE--
<?php
var_dump(sscanf('one two', '%1$s %2$s'));
var_dump(sscanf('one two', '%2$s %1$s'));
echo "--\n";
sscanf('one two', '%1$s %2$s', $foo, $bar);
var_dump($foo, $bar);
sscanf('one two', '%2$s %1$s', $foo, $bar);
var_dump($foo, $bar);
echo "--\n";
var_dump(sscanf('one two', '%1$d %2$d'));
var_dump(sscanf('one two', '%1$d'));
echo "Done\n";
?>
--EXPECT--
array(2) {
[0]=>
string(3) "one"
[1]=>
string(3) "two"
}
array(2) {
[0]=>
string(3) "two"
[1]=>
string(3) "one"
}
--
string(3) "one"
string(3) "two"
string(3) "two"
string(3) "one"
--
array(2) {
[0]=>
NULL
[1]=>
NULL
}
array(1) {
[0]=>
NULL
}
Done
| PHP | 3 | thiagooak/php-src | ext/standard/tests/strings/bug42107.phpt | [
"PHP-3.01"
] |
/*
* 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.
*/
package org.apache.spark.sql.streaming.ui
import java.util.{Locale, UUID}
import javax.servlet.http.HttpServletRequest
import scala.xml.Node
import org.mockito.Mockito.{mock, when, RETURNS_SMART_NULLS}
import org.scalatest.BeforeAndAfter
import org.apache.spark.SparkConf
import org.apache.spark.sql.execution.ui.StreamingQueryStatusStore
import org.apache.spark.sql.streaming.StreamingQueryProgress
import org.apache.spark.sql.test.SharedSparkSession
import org.apache.spark.ui.SparkUI
class StreamingQueryPageSuite extends SharedSparkSession with BeforeAndAfter {
test("correctly display streaming query page") {
val id = UUID.randomUUID()
val request = mock(classOf[HttpServletRequest])
val tab = mock(classOf[StreamingQueryTab], RETURNS_SMART_NULLS)
val store = mock(classOf[StreamingQueryStatusStore], RETURNS_SMART_NULLS)
when(tab.appName).thenReturn("testing")
when(tab.headerTabs).thenReturn(Seq.empty)
when(tab.store).thenReturn(store)
val streamQuery = createStreamQueryUIData(id)
when(store.allQueryUIData).thenReturn(Seq(streamQuery))
var html = renderStreamingQueryPage(request, tab)
.toString().toLowerCase(Locale.ROOT)
assert(html.contains("active streaming queries (1)"))
when(streamQuery.summary.isActive).thenReturn(false)
when(streamQuery.summary.exception).thenReturn(None)
html = renderStreamingQueryPage(request, tab)
.toString().toLowerCase(Locale.ROOT)
assert(html.contains("completed streaming queries (1)"))
assert(html.contains("finished"))
when(streamQuery.summary.isActive).thenReturn(false)
when(streamQuery.summary.exception).thenReturn(Option("exception in query"))
html = renderStreamingQueryPage(request, tab)
.toString().toLowerCase(Locale.ROOT)
assert(html.contains("completed streaming queries (1)"))
assert(html.contains("failed"))
assert(html.contains("exception in query"))
}
test("correctly display streaming query statistics page") {
val id = UUID.randomUUID()
val request = mock(classOf[HttpServletRequest])
val tab = mock(classOf[StreamingQueryTab], RETURNS_SMART_NULLS)
val store = mock(classOf[StreamingQueryStatusStore], RETURNS_SMART_NULLS)
when(request.getParameter("id")).thenReturn(id.toString)
when(tab.appName).thenReturn("testing")
when(tab.headerTabs).thenReturn(Seq.empty)
when(tab.store).thenReturn(store)
val ui = mock(classOf[SparkUI])
when(request.getParameter("id")).thenReturn(id.toString)
when(tab.appName).thenReturn("testing")
when(tab.headerTabs).thenReturn(Seq.empty)
when(ui.conf).thenReturn(new SparkConf())
when(tab.parent).thenReturn(ui)
val streamQuery = createStreamQueryUIData(id)
when(store.allQueryUIData).thenReturn(Seq(streamQuery))
val html = renderStreamingQueryStatisticsPage(request, tab)
.toString().toLowerCase(Locale.ROOT)
assert(html.contains("<strong>name: </strong>query<"))
assert(html.contains("""{"x": 1001898000100, "y": 10.0}"""))
assert(html.contains("""{"x": 1001898000100, "y": 12.0}"""))
assert(html.contains("(<strong>3</strong> completed batches)"))
}
private def createStreamQueryUIData(id: UUID): StreamingQueryUIData = {
val progress = mock(classOf[StreamingQueryProgress], RETURNS_SMART_NULLS)
when(progress.timestamp).thenReturn("2001-10-01T01:00:00.100Z")
when(progress.inputRowsPerSecond).thenReturn(10.0)
when(progress.processedRowsPerSecond).thenReturn(12.0)
when(progress.batchId).thenReturn(2)
when(progress.prettyJson).thenReturn("""{"a":1}""")
val summary = mock(classOf[StreamingQueryData], RETURNS_SMART_NULLS)
when(summary.isActive).thenReturn(true)
when(summary.name).thenReturn("query")
when(summary.id).thenReturn(id)
when(summary.runId).thenReturn(id)
when(summary.startTimestamp).thenReturn(1L)
when(summary.exception).thenReturn(None)
val streamQuery = mock(classOf[StreamingQueryUIData], RETURNS_SMART_NULLS)
when(streamQuery.summary).thenReturn(summary)
when(streamQuery.lastProgress).thenReturn(progress)
when(streamQuery.recentProgress).thenReturn(Array(progress))
streamQuery
}
/**
* Render a stage page started with the given conf and return the HTML.
* This also runs a dummy execution page to populate the page with useful content.
*/
private def renderStreamingQueryPage(
request: HttpServletRequest,
tab: StreamingQueryTab): Seq[Node] = {
val page = new StreamingQueryPage(tab)
page.render(request)
}
private def renderStreamingQueryStatisticsPage(
request: HttpServletRequest,
tab: StreamingQueryTab): Seq[Node] = {
val page = new StreamingQueryStatisticsPage(tab)
page.render(request)
}
}
| Scala | 4 | kesavanvt/spark | sql/core/src/test/scala/org/apache/spark/sql/streaming/ui/StreamingQueryPageSuite.scala | [
"BSD-2-Clause",
"Apache-2.0",
"CC0-1.0",
"MIT",
"MIT-0",
"ECL-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] |
diff --git a/cmake/developer_package/vs_version/vs_version.cmake b/cmake/developer_package/vs_version/vs_version.cmake
index 14d4c0e1e..6a44f73b9 100644
--- a/cmake/developer_package/vs_version/vs_version.cmake
+++ b/cmake/developer_package/vs_version/vs_version.cmake
@@ -8,9 +8,9 @@ set(IE_VS_VER_FILEVERSION_STR "${IE_VERSION_MAJOR}.${IE_VERSION_MINOR}.${IE_VERS
set(IE_VS_VER_COMPANY_NAME_STR "Intel Corporation")
set(IE_VS_VER_PRODUCTVERSION_STR "${CI_BUILD_NUMBER}")
-set(IE_VS_VER_PRODUCTNAME_STR "OpenVINO toolkit")
+set(IE_VS_VER_PRODUCTNAME_STR "OpenVINO toolkit (for OpenCV Windows package)")
set(IE_VS_VER_COPYRIGHT_STR "Copyright (C) 2018-2021, Intel Corporation")
-set(IE_VS_VER_COMMENTS_STR "https://docs.openvinotoolkit.org/")
+set(IE_VS_VER_COMMENTS_STR "https://github.com/opencv/opencv/wiki/Intel%27s-Deep-Learning-Inference-Engine-backend")
#
# ie_add_vs_version_file(NAME <name>
| Diff | 3 | xipingyan/opencv | platforms/winpack_dldt/2021.4/20210630-dldt-vs-version.patch | [
"Apache-2.0"
] |
@0xd3a7e843a9c03421;
struct Metadata {
version @0 :UInt32;
timestamp @1 :UInt64;
changeset @2 :UInt32;
uid @3 :UInt32;
user @4 :Text;
}
struct Node {
tags @0 :List(Text);
metadata @1 :Metadata;
}
struct Way {
nodes @0 :List(UInt64);
tags @1 :List(Text);
metadata @2 :Metadata;
}
struct RelationMember {
ref @0 :UInt64;
type @1 :Type;
role @2 :Text;
enum Type {
node @0;
way @1;
relation @2;
}
}
struct Relation {
tags @0 :List(Text);
members @1 :List(RelationMember);
metadata @2 :Metadata;
}
| Cap'n Proto | 3 | DavidKarlas/OSMExpress | python/osmx/messages.capnp | [
"BSD-2-Clause"
] |
$! File: MAKE_PCSI_CURL_KIT_NAME.COM
$!
$! $Id$
$!
$! Calculates the PCSI kit name for use in building an installation kit.
$! PCSI is HP's PolyCenter Software Installation Utility.
$!
$! The results are stored in as logical names so that other procedures
$! can use them.
$!
$! Copyright 2009 - 2020, John Malmberg
$!
$! Permission to use, copy, modify, and/or distribute this software for any
$! purpose with or without fee is hereby granted, provided that the above
$! copyright notice and this permission notice appear in all copies.
$!
$! THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
$! WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
$! MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
$! ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
$! WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
$! ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
$! OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
$!
$! 11-Jun-2009 J. Malmberg
$!
$!========================================================================
$!
$! Save default
$ default_dir = f$environment("DEFAULT")
$!
$! Move to the base directories
$ set def [--]
$!
$! Put things back on error.
$ on warning then goto all_exit
$!
$! The producer is the name or common abbreviation for the entity that is
$! making the kit. It must be set as a logical name before running this
$! procedure.
$!
$! HP documents the producer as the legal owner of the software, but for
$! open source work, it should document who is creating the package for
$! distribution.
$!
$ producer = f$trnlnm("GNV_PCSI_PRODUCER")
$ if producer .eqs. ""
$ then
$ write sys$output "The logical name GNV_PCSI_PRODUCER needs to be defined."
$ write sys$output "This should be set to the common abbreviation or name of"
$ write sys$output "the entity creating this kit. If you are an individual"
$ write sys$output "then use your initials."
$ goto all_exit
$ endif
$ producer_full_name = f$trnlnm("GNV_PCSI_PRODUCER_FULL_NAME")
$ if producer_full_name .eqs. ""
$ then
$ write sys$output "The logical name GNV_PCSI_PRODUCER_FULL_NAME needs to"
$ write sys$output "be defined. This should be set to the full name of"
$ write sys$output "the entity creating this kit. If you are an individual"
$ write sys$output "then use your name."
$ write sys$output "EX: DEFINE GNV_PCSI_PRODUCER_FULL_NAME ""First M. Last"""
$ goto all_exit
$ endif
$!
$ write sys$output "*****"
$ write sys$output "***** Producer = ''producer'"
$ write sys$output "*****"
$!
$!
$! Base is one of 'VMS', 'AXPVMS', 'I64VMS', 'VAXVMS' and indicates what
$! binaries are in the kit. A kit with just 'VMS' can be installed on all
$! architectures.
$!
$ base = "VMS"
$ arch_type = f$getsyi("ARCH_NAME")
$ code = f$extract(0, 1, arch_type)
$ if (code .eqs. "I") then base = "I64VMS"
$ if (code .eqs. "V") then base = "VAXVMS"
$ if (code .eqs. "A") then base = "AXPVMS"
$!
$!
$ product = "curl"
$!
$!
$! We need to get the version from curlver_h. It will have a line like
$! #define LIBCURL_VERSION "7.31.0"
$! or
$! #define LIBCURL_VERSION "7.32.0-20130731".
$!
$! The dash indicates that this is a daily pre-release.
$!
$!
$ open/read/error=version_loop_end vhf [.include.curl]curlver.h
$ version_loop:
$ read vhf line_in
$ if line_in .eqs. "" then goto version_loop
$ if f$locate("#define LIBCURL_VERSION ", line_in) .ne. 0
$ then
$ goto version_loop
$ endif
$ raw_version = f$element(2," ", line_in) - """" - """"
$ version_loop_end:
$ close vhf
$!
$!
$ eco_level = ""
$ if f$search("''default_dir'vms_eco_level.h") .nes. ""
$ then
$ open/read ef 'default_dir'vms_eco_level.h
$ecolevel_loop:
$ read/end=ecolevel_loop_end ef line_in
$ prefix = f$element(0, " ", line_in)
$ if prefix .nes. "#define" then goto ecolevel_loop
$ key = f$element(1, " ", line_in)
$ value = f$element(2, " ", line_in) - """" - """"
$ if key .eqs. "VMS_ECO_LEVEL"
$ then
$ eco_level = "''value'"
$ if eco_level .eqs. "0"
$ then
$ eco_level = ""
$ else
$ eco_level = "E" + eco_level
$ endif
$ goto ecolevel_loop_end
$ endif
$ goto ecolevel_loop
$ecolevel_loop_end:
$ close ef
$ endif
$!
$!
$! This translates to V0732-0 or D0732-0
$! We encode the snapshot date into the version as an ECO since a daily
$! can never have an ECO.
$!
$! version_type = 'V' for a production release, and 'D' for a build from a
$! daiy snapshot of the curl source.
$ majorver = f$element(0, ".", raw_version)
$ minorver = f$element(1, ".", raw_version)
$ raw_update = f$element(2, ".", raw_version)
$ update = f$element(0, "-", raw_update)
$ if update .eqs. "0" then update = ""
$ daily_tag = f$element(1, "-", raw_update)
$ vtype = "V"
$ patch = ""
$ if daily_tag .nes. "-"
$ then
$ vtype = "D"
$ daily_tag_len = f$length(daily_tag)
$ daily_tag = f$extract(4, daily_tag_len - 4, daily_tag)
$ patch = vtype + daily_tag
$ product = product + "_d"
$ else
$ daily_tag = ""
$ if eco_level .nes. "" then patch = eco_level
$ endif
$!
$!
$ version_fao = "!2ZB!2ZB"
$ mmversion = f$fao(version_fao, 'majorver', 'minorver')
$ version = vtype + "''mmversion'"
$ if update .nes. "" .or. patch .nes. ""
$ then
$! The presence of a patch implies an update
$ if update .eqs. "" .and. patch .nes. "" then update = "0"
$ version = version + "-" + update + patch
$ fversion = version
$ else
$ fversion = version
$ version = version + "-"
$ endif
$!
$! Kit type 1 is complete kit, the only type that this procedure will make.
$ kittype = 1
$!
$! Write out a logical name for the resulting base kit name.
$ name = "''producer'-''base'-''product'-''version'-''kittype'"
$ define GNV_PCSI_KITNAME "''name'"
$ fname = "''product'-''fversion'"
$ define GNV_PCSI_FILENAME_BASE "''fname'"
$ write sys$output "*****"
$ write sys$output "***** GNV_PCSI_KITNAME = ''name'."
$ write sys$output "***** GNV_PCSI_FILENAME_BASE = ''fname'."
$ write sys$output "*****"
$!
$all_exit:
$ set def 'default_dir'
$ exit '$status'
| DIGITAL Command Language | 4 | jjatria/curl | packages/vms/make_pcsi_curl_kit_name.com | [
"curl"
] |
import { FormattedMessage, FormattedNumber, useIntl } from 'react-intl'
import Layout from '../components/Layout'
import loadIntlMessages from '../helper/loadIntlMessages'
import { InferGetStaticPropsType } from 'next'
export async function getStaticProps(ctx) {
return {
props: {
intlMessages: await loadIntlMessages(ctx),
},
}
}
type HomePageProps = InferGetStaticPropsType<typeof getStaticProps>
export default function HomePage(props: HomePageProps) {
const intl = useIntl()
return (
<Layout
title={intl.formatMessage({
defaultMessage: 'Home',
description: 'Index Page: document title',
})}
description={intl.formatMessage({
defaultMessage: 'An example app integrating React Intl with Next.js',
description: 'Index Page: Meta Description',
})}
>
<p>
<FormattedMessage
defaultMessage="Hello, World!"
description="Index Page: Content"
/>
</p>
<p>
<FormattedNumber value={1000} />
</p>
</Layout>
)
}
| TypeScript | 4 | blomqma/next.js | examples/with-react-intl/pages/index.tsx | [
"MIT"
] |
/*************************************************************************************
* Copyright (c) 2015, Advanced Micro Devices, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
**************************************************************************************/
__kernel void LRNComputeOutput(const int nthreads, __global T* in, __global T* scale, const T negative_beta, __global T* out) {
int index = get_global_id(0);
int tmp = get_global_size(0);
for(index; index < nthreads; index += tmp)
out[index] = in[index] * pow(scale[index], negative_beta);
}
__kernel void LRNFillScale(const int nthreads, __global T* in, const int num, const int channels, const int height, const int width, const int size, const T alpha_over_size, const T k, __global T* scale) {
int index = get_global_id(0);
int tmp = get_global_size(0);
for(index; index < nthreads; index += tmp) {
// find out the local offset
const int w = index % width;
const int h = (index / width) % height;
const int n = index / width / height;
const int offset = (n * channels * height + h) * width + w;
const int step = height * width;
in = in + offset;
scale = scale + offset;
int head = 0;
const int pre_pad = (size - 1) / 2;
const int post_pad = size - pre_pad - 1;
T accum_scale = 0;
// fill the scale at [n, :, h, w]
// accumulate values
while (head < post_pad && head < channels) {
accum_scale += in[head * step] * in[head * step];
++head;
}
// both add and subtract
while (head < channels) {
accum_scale += in[head * step] * in[head * step];
if (head - size >= 0) {
accum_scale -= in[(head - size) * step]
* in[(head - size) * step];
}
scale[(head - post_pad) * step] = k + accum_scale * alpha_over_size;
++head;
}
// subtract only
while (head < channels + post_pad) {
if (head - size >= 0) {
accum_scale -= in[(head - size) * step]
* in[(head - size) * step];
}
scale[(head - post_pad) * step] = k + accum_scale * alpha_over_size;
++head;
}
}
} | OpenCL | 4 | thisisgopalmandal/opencv | modules/dnn/src/opencl/lrn.cl | [
"BSD-3-Clause"
] |
redo-ifchange "$2"
# On freebsd, 'gzip --rsyncable' fails but returns 0.
# We have to detect lack of --rsyncable some other way.
gzt=$(gzip --rsyncable -c </dev/null 2>/dev/null | wc -c)
if [ "$gzt" -gt 0 ]; then
# when available, --rsyncable makes compressed
# files much more efficient to rsync when they
# change slightly.
gzip --rsyncable -c <$2 >$3
else
gzip -c <$2 >$3
fi
| Stata | 4 | BlameJohnny/redo | docs/cookbook/container/default.gz.do | [
"Apache-2.0"
] |
\data\
ngram 1=9
ngram 2=11
ngram 3=10
\1-grams:
-1.0598761 <unk> 0
0 <s> -0.30103
-1.0598761 </s> 0
-0.8305393 I -0.30103
-0.8305393 like -0.30103
-0.8305393 apple -0.30103
-0.93024224 you -0.30103
-0.93024224 love -0.30103
-0.8305393 coffee -0.30103
\2-grams:
-0.264752 apple </s> 0
-0.53230226 you </s> 0
-0.264752 coffee </s> 0
-0.34788558 <s> I -0.30103
-0.48963785 I like -0.30103
-0.2411913 like apple -0.30103
-0.7358622 <s> you -0.30103
-0.6470869 love you -0.30103
-0.5104463 I love -0.30103
-0.5104463 you love -0.30103
-0.39019543 love coffee -0.30103
\3-grams:
-0.11250631 like apple </s>
-0.18924321 love you </s>
-0.11250631 love coffee </s>
-0.48333442 <s> I like
-0.1040629 I like apple
-0.44046512 I love you
-0.3118567 <s> I love
-0.18418588 <s> you love
-0.3433284 I love coffee
-0.15267509 you love coffee
\end\
| DNS Zone | 3 | texpomru13/espnet | test/test.arpa | [
"Apache-2.0"
] |
#include "arch/barrier.hpp"
thread_barrier_t::thread_barrier_t(int num_workers)
: num_workers_(num_workers), num_waiters_(0) {
guarantee(num_workers > 0);
int res = pthread_mutex_init(&mutex_, nullptr);
guarantee_xerr(res == 0, res, "could not initialize barrier mutex");
res = pthread_cond_init(&cond_, nullptr);
guarantee_xerr(res == 0, res, "could not initialize barrier condition variable");
}
thread_barrier_t::~thread_barrier_t() {
guarantee(num_waiters_ == 0);
int res = pthread_cond_destroy(&cond_);
guarantee_xerr(res == 0, res, "could not destroy barrier condition variable");
res = pthread_mutex_destroy(&mutex_);
guarantee_xerr(res == 0, res, "could not destroy barrier mutex");
}
void thread_barrier_t::wait() {
int res = pthread_mutex_lock(&mutex_);
guarantee_xerr(res == 0, res, "could not acquire barrier mutex");
++num_waiters_;
if (num_waiters_ == num_workers_) {
num_waiters_ = 0;
res = pthread_cond_broadcast(&cond_);
guarantee_xerr(res == 0, res, "barrier could not broadcast to condition variable");
} else {
res = pthread_cond_wait(&cond_, &mutex_);
guarantee_xerr(res == 0, res, "barrier could not wait for condition variable");
}
res = pthread_mutex_unlock(&mutex_);
guarantee_xerr(res == 0, res, "barrier could not unlock mutex");
}
| C++ | 4 | zadcha/rethinkdb | src/arch/barrier.cc | [
"Apache-2.0"
] |
unit aplibud;
(*
* aPLib compression library - the smaller the better :)
*
* VPascal interface to aplib.lib
*
* Copyright (c) 1998-2009 by Joergen Ibsen / Jibz
* All Rights Reserved
*
* http://www.ibsensoftware.com/
*
* -> VPascal by Veit Kannegieser, 23.09.1998
*)
interface
const
aP_pack_continue =1;
aP_pack_break =0;
aPLib_Error =-1; (* indicates error compressing/decompressing *)
(* compression status callback functions *)
{&Saves EBX,ECX,EDX,ESI,EDI}
{$IfDef Win32} {&StdCall+} {$Else} {&Cdecl+} {$EndIf}
type
apack_status =function(const w0,w1,w2:longint;
const cbparam:pointer):longint;
function cb0(const w0,w1,w2:longint; const cbparam:pointer):longint;
function cb1(const w0,w1,w2:longint; const cbparam:pointer):longint;
{&Saves EBX,ESI,EDI}
{&StdCall-}
(* DLL interface functions *)
{&OrgName+} (* aplibu@_aP_pack -> _aP_pack *)
{$IfDef Win32} {&StdCall+} {$Else} {&Cdecl+} {$EndIf}
function _aP_pack(
const source;
const destination;
const length :longint;
const workmem;
const callback :apack_status;
const cbparam:pointer) :longint;
function _aP_workmem_size(
const inputsize :longint) :longint;
function _aP_max_packed_size(
const inputsize :longint) :longint;
function _aP_depack_asm(
const source;
const destination) :longint;
function _aP_depack_asm_fast(
const source;
const destination) :longint;
function _aP_depack_asm_safe(
const source;
const srclen :longint;
const destination;
const dstlen :longint) :longint;
function _aP_crc32(
const source;
const length :longint) :longint;
function _aPsafe_pack(
const source;
const destination;
const length :longint;
const workmem;
const callback :apack_status;
const cbparam:pointer) :longint;
function _aPsafe_check(
const source) :longint;
function _aPsafe_get_orig_size(
const source) :longint;
function _aPsafe_depack(
const source;
const srclen :longint;
const destination;
const dstlen :longint) :longint;
{&Cdecl-}{&StdCall-}{&OrgName-}
implementation
{$IfDef ESC_ABORT}
uses
VpSysLow;
{$EndIf ESC_ABORT}
const
aplib_dll_name={$IfDef OS2 }'aplib.dll'{$EndIf}
{$IfDef Win32}'aplib.dll'{$EndIf}
{$IfDef Linux}'aplib.so' {$EndIf};
function _aP_pack ;external aplib_dll_name {$IfDef Linux}name 'aP_pack' {$EndIf};
function _aP_workmem_size ;external aplib_dll_name {$IfDef Linux}name 'aP_workmem_size' {$EndIf};
function _aP_max_packed_size ;external aplib_dll_name {$IfDef Linux}name 'aP_max_packed_size' {$EndIf};
function _aP_depack_asm ;external aplib_dll_name {$IfDef Linux}name 'aP_depack_asm' {$EndIf};
function _aP_depack_asm_fast ;external aplib_dll_name {$IfDef Linux}name 'aP_depack_asm_fast' {$EndIf};
function _aP_depack_asm_safe ;external aplib_dll_name {$IfDef Linux}name 'aP_depack_asm_safe' {$EndIf};
function _aP_crc32 ;external aplib_dll_name {$IfDef Linux}name 'aP_crc32' {$EndIf};
function _aPsafe_pack ;external aplib_dll_name {$IfDef Linux}name 'aPsafe_pack' {$EndIf};
function _aPsafe_check ;external aplib_dll_name {$IfDef Linux}name 'aPsafe_check' {$EndIf};
function _aPsafe_get_orig_size ;external aplib_dll_name {$IfDef Linux}name 'aPsafe_get_orig_size' {$EndIf};
function _aPsafe_depack ;external aplib_dll_name {$IfDef Linux}name 'aPsafe_depack' {$EndIf};
(* callback samples for _aP_pack *)
function cb0(const w0,w1,w2:longint;
const cbparam:pointer):longint;assembler;{&Frame-}{&Uses None}
asm
mov eax,aP_pack_continue
end;
function cb1(const w0,w1,w2:longint;
const cbparam:pointer):longint;
begin
Write(w1:8,' -> ',w2:8,^m);
cb1:=aP_pack_continue;
{$IfDef ESC_ABORT}
if SysKeyPressed then
if SysReadKey=#27 then
cb1:=aP_pack_break;
{$EndIf ESC_ABORT}
end;
end.
| Pascal | 4 | nehalem501/gendev | tools/files/applib/contrib/vpascal/aplibud.pas | [
"BSD-3-Clause"
] |
"""
"""
interface BaseInterface:
def Add(s as string)
abstract class BaseAbstractClass:
def Add(i as string):
pass
class Consumer(BaseInterface, BaseAbstractClass):
pass
| Boo | 3 | popcatalin81/boo | tests/testcases/warnings/BCW0011-14.boo | [
"BSD-3-Clause"
] |
#! /usr/bin/env hy
(defn greet [thing]
(-> (.format "Hello, {}!" thing)
(print)))
(greet "World")
| Hy | 3 | PushpneetSingh/Hello-world | Hy/hello.hy | [
"MIT"
] |
use v6;
say qq{
Euler Problem 1:
Find the sum of all the multiples of 3 or 5 below 1000.
};
my $euler1 = [+]((1..999).grep({$_%%(3|5)}));
say $euler1;
# 233168
# Shorter.
my $euler2 = (1..999).grep(*%%(3|5)).sum;
say $euler2;
| Perl6 | 5 | Wikunia/hakank | perl6/euler1.p6 | [
"MIT"
] |
package main
import (
"net/http"
"github.com/unrolled/secure" // or "gopkg.in/unrolled/secure.v1"
)
var myHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("hello world"))
})
func main() {
secureMiddleware := secure.New(secure.Options{
AllowedHosts: []string{"example.com", "ssl.example.com"},
HostsProxyHeaders: []string{"X-Forwarded-Host"},
SSLRedirect: true,
SSLHost: "ssl.example.com",
SSLProxyHeaders: map[string]string{"X-Forwarded-Proto": "https"},
STSSeconds: 315360000,
STSIncludeSubdomains: true,
STSPreload: true,
FrameDeny: true,
ContentTypeNosniff: true,
BrowserXssFilter: true,
ContentSecurityPolicy: "script-src $NONCE",
PublicKey: `pin-sha256="base64+primary=="; pin-sha256="base64+backup=="; max-age=5184000; includeSubdomains; report-uri="https://www.example.com/hpkp-report"`,
IsDevelopment: false,
})
app := secureMiddleware.Handler(myHandler)
http.ListenAndServe("127.0.0.1:3000", app)
}
| GAP | 4 | visuo-dev/yaegi | _test/secure.gi | [
"Apache-2.0"
] |
-include ../tools.mk
all: $(TMPDIR)/$(call BIN,bar)
$(call RUN,bar)
$(call REMOVE_DYLIBS,foo)
$(call FAIL,bar)
ifdef IS_MSVC
$(TMPDIR)/$(call BIN,bar): $(call DYLIB,foo)
$(CC) bar.c $(TMPDIR)/foo.dll.lib $(call OUT_EXE,bar)
else
$(TMPDIR)/$(call BIN,bar): $(call DYLIB,foo)
$(CC) bar.c -lfoo -o $(call RUN_BINFILE,bar) -L $(TMPDIR)
endif
$(call DYLIB,foo): foo.rs
$(RUSTC) foo.rs
| Makefile | 3 | Eric-Arellano/rust | src/test/run-make-fulldeps/c-link-to-rust-dylib/Makefile | [
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] |
<mt:Ignore>
# =======================
#
# コンフィグ-ホーム
#
# =======================
</mt:Ignore>
<mt:Ignore>
# -----------------------
# META
# -----------------------
</mt:Ignore>
<mt:Var name="ec_website_name" setvar="ec_meta_title" note="接尾辞を除くtitle要素" />
<mt:IfWebsite>
<mt:If tag="EcWebsiteHomeTitle" note="ホームのtitle要素が指定されていれば">
<mt:EcWebsiteHomeTitle encode_html="1" setvar="ec_meta_title" note="接尾辞を除くtitle要素" />
</mt:If>
<mt:Else>
<mt:If tag="EcBlogHomeTitle" note="ブログのホームのtitle要素が指定されていれば">
<mt:EcBlogHomeTitle encode_html="1" setvar="ec_meta_title" note="接尾辞を除くtitle要素" />
</mt:If>
</mt:IfWebsite>
<mt:Var name="ec_website_description" setvar="ec_meta_description" note="概要" />
<mt:IfWebsite>
<mt:If tag="EcWebsiteHomeDescription" note="ホームの概要が指定されていれば">
<mt:EcWebsiteHomeDescription encode_html="1" setvar="ec_meta_description" note="概要" />
</mt:If>
<mt:Else>
<mt:If tag="EcBlogHomeDescription" note="ブログのホームの概要が指定されていれば">
<mt:EcBlogHomeDescription encode_html="1" setvar="ec_meta_description" note="概要" />
</mt:If>
</mt:IfWebsite>
<mt:Var name="ec_website_url" setvar="ec_meta_permalink" note="完全なURL" />
<mt:Date format_name="iso8601" setvar="ec_meta_publish" note="再構築された時点のタイムスタンプ" />
<mt:Ignore>
# -----------------------
# Others
# -----------------------
</mt:Ignore>
<mt:SetVarBlock name="ec_body_class"" note="body要素のクラス名">home blog-<mt:BlogID /></mt:SetVarBlock>
| MTML | 4 | webbingstudio/mt_theme_echo_bootstrap | dist/themes/echo_bootstrap/templates/config_home.mtml | [
"MIT"
] |
#lang scribble/manual
@title{Acknowledgments}
One curious aspect of free software is that you can appropriate the benefits of other people's work while making it look like your own. No such legerdemain here. Whatever effort I've put into Pollen is dwarfed by the epic accomplishments of the Racket development team. I thank all of them — especially @link["http://www.barzilay.org"]{Eli Barzilay}, @link["https://www.cs.utah.edu/~mflatt/"]{Matthew Flatt}, @link["http://faculty.cs.byu.edu/~jay/home/"]{Jay McCarthy}, @link["https://www.eecs.northwestern.edu/~robby/"]{Robby Findler}, @link["https://www.soic.indiana.edu/faculty-research/directory/profile.html?profile_id=311"]{Sam Tobin-Hochstadt}, and @link["http://www.ccs.neu.edu/home/matthias/"]{Matthias Felleisen} — for making this tremendous tool available, for adding several features I suggested, and for patiently answering my dumb questions over the months.
Thank you to Greg Hendershott for his Markdown parser.
Thank you to Ahmed Fasih, Malcolm Still, Joel Dueck, and other early-stage Pollen users for their patience & suggestions.
The best software tools do more than get the job done. They create an incentive to undertake jobs you wouldn't have attempted before. Racket encouraged me to become a better programmer so I could create Pollen. Likewise, I hope that Pollen encourages you to make things you couldn't before.
MB | Racket | 2 | otherjoel/pollen | pollen/scribblings/acknowledgments.scrbl | [
"MIT"
] |
This is not in the includes dir. | Liquid | 2 | binyamin/eleventy | test/stubs/included.liquid | [
"MIT"
] |
⍝ This version works by computing the sum of the squares in ⍵
⍝ and then finding the square root.
euclidean_norm ← {
(+/⍵ × ⍵) * ÷ 2
}
⍝ As the name suggests, this version computes the dot product
⍝ of ⍵, then finds the square root.
euclidean_norm_dot_product ← {
(⍵ +.× ⍵) * ÷ 2
} | APL | 4 | Mynogs/Algorithm-Implementations | Euclidean_Norm/APL/jcla1/euclidean_norm.apl | [
"MIT"
] |
Origin with(
directory: "coverage-report",
files: fn(file,
case(file,
#r[test/.*\Z], false,
#r[bin/.*\Z], false,
#/\.file_system_test_config.ik\Z/, false,
else, true
)
)
)
| Ioke | 4 | olabini/ioke | ikover_config.ik | [
"ICU",
"MIT"
] |
#!/usr/bin/env perl
#***************************************************************************
# _ _ ____ _
# Project ___| | | | _ \| |
# / __| | | | |_) | |
# | (__| |_| | _ <| |___
# \___|\___/|_| \_\_____|
#
# Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at https://curl.se/docs/copyright.html.
#
# You may opt to use, copy, modify, merge, publish, distribute and/or sell
# copies of the Software, and permit persons to whom the Software is
# furnished to do so, under the terms of the COPYING file.
#
# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
# KIND, either express or implied.
#
###########################################################################
use strict;
use warnings;
use Getopt::Long();
use Pod::Usage();
my $curl = 'curl';
my $shell = 'zsh';
my $help = 0;
Getopt::Long::GetOptions(
'curl=s' => \$curl,
'shell=s' => \$shell,
'help' => \$help,
) or Pod::Usage::pod2usage();
Pod::Usage::pod2usage() if $help;
my $regex = '\s+(?:(-[^\s]+),\s)?(--[^\s]+)\s*(\<.+?\>)?\s+(.*)';
my @opts = parse_main_opts('--help all', $regex);
if ($shell eq 'fish') {
print "# curl fish completion\n\n";
print qq{$_ \n} foreach (@opts);
} elsif ($shell eq 'zsh') {
my $opts_str;
$opts_str .= qq{ $_ \\\n} foreach (@opts);
chomp $opts_str;
my $tmpl = <<"EOS";
#compdef curl
# curl zsh completion
local curcontext="\$curcontext" state state_descr line
typeset -A opt_args
local rc=1
_arguments -C -S \\
$opts_str
'*:URL:_urls' && rc=0
return rc
EOS
print $tmpl;
} else {
die("Unsupported shell: $shell");
}
sub parse_main_opts {
my ($cmd, $regex) = @_;
my @list;
my @lines = call_curl($cmd);
foreach my $line (@lines) {
my ($short, $long, $arg, $desc) = ($line =~ /^$regex/) or next;
my $option = '';
$arg =~ s/\:/\\\:/g if defined $arg;
$desc =~ s/'/'\\''/g if defined $desc;
$desc =~ s/\[/\\\[/g if defined $desc;
$desc =~ s/\]/\\\]/g if defined $desc;
$desc =~ s/\:/\\\:/g if defined $desc;
if ($shell eq 'fish') {
$option .= "complete --command curl";
$option .= " --short-option '" . strip_dash(trim($short)) . "'"
if defined $short;
$option .= " --long-option '" . strip_dash(trim($long)) . "'"
if defined $long;
$option .= " --description '" . strip_dash(trim($desc)) . "'"
if defined $desc;
} elsif ($shell eq 'zsh') {
$option .= '{' . trim($short) . ',' if defined $short;
$option .= trim($long) if defined $long;
$option .= '}' if defined $short;
$option .= '\'[' . trim($desc) . ']\'' if defined $desc;
$option .= ":'$arg'" if defined $arg;
$option .= ':_files'
if defined $arg and ($arg eq '<file>' || $arg eq '<filename>'
|| $arg eq '<dir>');
}
push @list, $option;
}
# Sort longest first, because zsh won't complete an option listed
# after one that's a prefix of it.
@list = sort {
$a =~ /([^=]*)/; my $ma = $1;
$b =~ /([^=]*)/; my $mb = $1;
length($mb) <=> length($ma)
} @list if $shell eq 'zsh';
return @list;
}
sub trim { my $s = shift; $s =~ s/^\s+|\s+$//g; return $s };
sub strip_dash { my $s = shift; $s =~ s/^-+//g; return $s };
sub call_curl {
my ($cmd) = @_;
my $output = `"$curl" $cmd`;
if ($? == -1) {
die "Could not run curl: $!";
} elsif ((my $exit_code = $? >> 8) != 0) {
die "curl returned $exit_code with output:\n$output";
}
return split /\n/, $output;
}
__END__
=head1 NAME
completion.pl - Generates tab-completion files for various shells
=head1 SYNOPSIS
completion.pl [options...]
--curl path to curl executable
--shell zsh/fish
--help prints this help
=cut
| Perl | 4 | Greg-Muchka/curl | scripts/completion.pl | [
"curl"
] |
#(set! null:counter1 (+ null:counter1 1)) | LilyPond | 0 | HolgerPeters/lyp | spec/user_files/null/include.ly | [
"MIT"
] |
discard """
targets: "c cpp js"
"""
block: # bug #14127
template int2uint(T) =
var a = -1
let b = cast[T](a)
doAssert b < 0
let c = b + 1
doAssert c is T
doAssert c == 0
int2uint(int8)
int2uint(int16)
int2uint(int32)
int2uint(int64)
block: # maybe related
template uint2int(T) =
var a = 3
let b = cast[T](a)
doAssert b > 0
let c = b - 1
doAssert c is T
doAssert c == 2
uint2int(uint8)
uint2int(uint16)
uint2int(uint32)
uint2int(uint64)
| Nimrod | 4 | JohnAD/Nim | tests/types/t14127_cast_number.nim | [
"MIT"
] |
:root {
/* Font smoothing */
--font-smoothing: auto;
/* GitHub.com system fonts */
--font-family-monospace: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo,
Courier, monospace;
--font-family-sans: -apple-system, BlinkMacSystemFont, Segoe UI, Helvetica,
Arial, sans-serif, Apple Color Emoji, Segoe UI Emoji, Segoe UI Symbol;
}
| CSS | 4 | GBKstc/react-analysis | packages/react-devtools-shared/src/devtools/views/root.css | [
"MIT"
] |
package com.baeldung.drools.service;
import com.baeldung.drools.model.Product;
import org.junit.Before;
import org.junit.Test;
import static junit.framework.TestCase.assertEquals;
public class ProductServiceIntegrationTest {
private ProductService productService;
@Before
public void setup() {
productService = new ProductService();
}
@Test
public void whenProductTypeElectronic_ThenLabelBarcode() {
Product product = new Product("Microwave", "Electronic");
product = productService.applyLabelToProduct(product);
assertEquals("BarCode", product.getLabel());
}
@Test
public void whenProductTypeBook_ThenLabelIsbn() {
Product product = new Product("AutoBiography", "Book");
product = productService.applyLabelToProduct(product);
assertEquals("ISBN", product.getLabel());
}
}
| Java | 4 | zeesh49/tutorials | drools/src/test/java/com/baeldung/drools/service/ProductServiceIntegrationTest.java | [
"MIT"
] |
//The outfit name that will be created or updated
// with botSetOutfit and that will be passed into
// botCreateBot and botChangeOutfit to set the
// bots' appearance
string outfitName = "Test Outfit";
string outfitName2 = "Test Outfit 2";
key botID;
integer outfit = 0;
default
{
state_entry()
{
//Creates the bot with the given outfit name specified name above
// or if the outfitName is "", the current appearance of the owner
botID = botCreateBot("Test", "Bot", outfitName, llGetPos(), BOT_CREATE_DEFAULT);
}
touch_start(integer n)
{
if (outfit == 0)
{
//Changes what the bot is wearing to the outfit "Test Outfit 2"
botChangeOutfit(botID, outfitName2);
outfit = 1;
}
else
{
//Changes what the bot is wearing back to the outfit "Test Outfit"
botChangeOutfit(botID, outfitName);
outfit = 0;
}
}
} | LSL | 4 | Asterionworld/ether | doc/bot LSL Functions/Examples/bot Change Outfit.lsl | [
"BSD-3-Clause"
] |
/*
* Copyright 2021 Jiří Janoušek <janousek.jiri@gmail.com>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
namespace Nuvola {
public class TiliadoSurvey: GLib.Object {
public const string DEFAULT_URL_TEMPLATE = "https://survey.tiliado.eu/%s/%s/";
public const string INFO_URL = "https://github.com/tiliado/nuvolaplayer/issues/678";
public string? survey_key = null;
private string url_template;
private string survey_id;
public TiliadoSurvey(string? url_template, string survey_id, string? survey_key = null) {
this.url_template = url_template ?? DEFAULT_URL_TEMPLATE;
this.survey_id = survey_id;
this.survey_key = survey_key;
}
public string? get_survey_url() {
if (Drt.String.is_empty(survey_key)) {
return null;
}
string? code = TiliadoSurvey.create_survey_code(survey_key);
return code == null ? null : url_template.printf(survey_id, code);
}
public static string? create_survey_code(string key) {
var s = new StringBuilder.sized(key.length);
unichar c;
for (int i = 0; key.get_next_char(ref i, out c);) {
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')) {
s.append_unichar(c);
}
}
if (s.len == 0) {
return null;
}
return GLib.Checksum.compute_for_string(GLib.ChecksumType.SHA256, s.str.down());
}
}
} // namespace Nuvola
| Vala | 4 | gslav/nuvolaplayer | src/nuvolakit-runner/tiliado/TiliadoSurvey.vala | [
"BSD-2-Clause"
] |
it("should also be here", () => {});
| JavaScript | 1 | 1shenxi/webpack | test/configCases/optimization/runtime-specific-used-exports/c.js | [
"MIT"
] |
within ModelicaByExample.PackageExamples;
package NestedPackages
"An example of how packages can be used to organize things"
package Types
type Rabbits = Real(quantity="Rabbits", min=0);
type Wolves = Real(quantity="Wolves", min=0);
type RabbitReproduction = Real(quantity="Rabbit Reproduction", min=0);
type RabbitFatalities = Real(quantity="Rabbit Fatalities", min=0);
type WolfReproduction = Real(quantity="Wolf Reproduction", min=0);
type WolfFatalities = Real(quantity="Wolf Fatalities", min=0);
end Types;
model LotkaVolterra "Lotka-Volterra with types"
parameter Types.RabbitReproduction alpha=0.1;
parameter Types.RabbitFatalities beta=0.02;
parameter Types.WolfReproduction gamma=0.4;
parameter Types.WolfFatalities delta=0.02;
parameter Types.Rabbits x0=10;
parameter Types.Wolves y0=10;
Types.Rabbits x(start=x0);
Types.Wolves y(start=y0);
equation
der(x) = x*(alpha-beta*y);
der(y) = -y*(gamma-delta*x);
end LotkaVolterra;
end NestedPackages;
| Modelica | 4 | JavascriptID/sourcerer-app | src/test/resources/samples/langs/Modelica/NestedPackages.mo | [
"MIT"
] |
package com.baeldung.reflection;
public abstract class Animal implements Eating {
public static final String CATEGORY = "domestic";
private String name;
public Animal(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
protected abstract String getSound();
}
| Java | 4 | DBatOWL/tutorials | core-java-modules/core-java-11-2/src/main/java/com/baeldung/reflection/Animal.java | [
"MIT"
] |
'reach 0.1';
export const main = Reach.App(() => {
const A = Participant('A', {
params: Object({
x: UInt,
y: UInt,
cx: UInt,
cy: UInt,
}),
show: Fun(true, Null),
});
setOptions({ verifyArithmetic: true });
init();
A.only(() => {
const params = declassify(interact.params);
assume(params.cx > 0);
assume(params.cy > 0);
assume(params.cx <= UInt.max / params.cy);
assume(params.x <= UInt.max);
assume(params.y <= UInt.max);
verifyMuldiv(params.x, params.y, params.cx * params.cy);
});
A.publish(params);
const { x, y, cx, cy } = params;
require(cx > 0);
require(cy > 0);
require(cx <= UInt.max / cy);
require(x <= UInt.max);
require(y <= UInt.max);
verifyMuldiv(x, y, cx * cy);
const j = muldiv(x, y, cx * cy);
require(j <= UInt.max);
A.interact.show(j);
commit();
verifyMuldiv(x, y, cx * cy);
});
| RenderScript | 3 | AwolDes/reach-lang | hs/t/y/verifyMuldiv.rsh | [
"Apache-2.0"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.