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
sequencelengths 1
8
|
---|---|---|---|---|---|
server {
listen 80;
listen [::]:80;
server_name resources.thehack.org.cn;
return 301 https://$host$request_uri;
}
server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name resources.thehack.org.cn;
# ssl settings and certificates
include ssl/ssl.nginxconf;
location / {
root /mnt/mirrors;
}
location /download {
alias /mnt/download;
}
root /mnt/download;
autoindex on;
}
| Nginx | 3 | hackinit/local-nginx | sites-available/resources.nginxconf | [
"MIT"
] |
$highlight_theme = hexo-config("highlight_theme")
if $highlight_theme == "normal"
$highlight-deletion = #fdd
$highlight-addition = #dfd
else
$highlight-deletion = #008000
$highlight-addition = #800000
| Stylus | 3 | lllove0/blog-theme | source/css/_common/components/highlight/diff.styl | [
"MIT"
] |
%http://www.cs.man.ac.uk/~pjj/bnf/c_syntax.bnf
%token int_const char_const float_const id string enumeration_const
%%
translation_unit : external_decl
| translation_unit external_decl
;
external_decl : function_definition
| decl
;
function_definition : decl_specs declarator decl_list compound_stat
| declarator decl_list compound_stat
| decl_specs declarator compound_stat
| declarator compound_stat
;
decl : decl_specs init_declarator_list ';'
| decl_specs ';'
;
decl_list : decl
| decl_list decl
;
decl_specs : storage_class_spec decl_specs
| storage_class_spec
| type_spec decl_specs
| type_spec
| type_qualifier decl_specs
| type_qualifier
;
storage_class_spec : 'auto' | 'register' | 'static' | 'extern' | 'typedef'
;
type_spec : 'void' | 'char' | 'short' | 'int' | 'long' | 'float'
| 'double' | 'signed' | 'unsigned'
| struct_or_union_spec
| enum_spec
| typedef_name
;
type_qualifier : 'const' | 'volatile'
;
struct_or_union_spec : struct_or_union id '{' struct_decl_list '}'
| struct_or_union '{' struct_decl_list '}'
| struct_or_union id
;
struct_or_union : 'struct' | 'union'
;
struct_decl_list : struct_decl
| struct_decl_list struct_decl
;
init_declarator_list : init_declarator
| init_declarator_list ',' init_declarator
;
init_declarator : declarator
| declarator '=' initializer
;
struct_decl : spec_qualifier_list struct_declarator_list ';'
;
spec_qualifier_list : type_spec spec_qualifier_list
| type_spec
| type_qualifier spec_qualifier_list
| type_qualifier
;
struct_declarator_list : struct_declarator
| struct_declarator_list ',' struct_declarator
;
struct_declarator : declarator
| declarator ':' const_exp
| ':' const_exp
;
enum_spec : 'enum' id '{' enumerator_list '}'
| 'enum' '{' enumerator_list '}'
| 'enum' id
;
enumerator_list : enumerator
| enumerator_list ',' enumerator
;
enumerator : id
| id '=' const_exp
;
declarator : pointer direct_declarator
| direct_declarator
;
direct_declarator : id
| '(' declarator ')'
| direct_declarator '[' const_exp ']'
| direct_declarator '[' ']'
| direct_declarator '(' param_type_list ')'
| direct_declarator '(' id_list ')'
| direct_declarator '(' ')'
;
pointer : '*' type_qualifier_list
| '*'
| '*' type_qualifier_list pointer
| '*' pointer
;
type_qualifier_list : type_qualifier
| type_qualifier_list type_qualifier
;
param_type_list : param_list
| param_list ',' '...'
;
param_list : param_decl
| param_list ',' param_decl
;
param_decl : decl_specs declarator
| decl_specs abstract_declarator
| decl_specs
;
id_list : id
| id_list ',' id
;
initializer : assignment_exp
| '{' initializer_list '}'
| '{' initializer_list ',' '}'
;
initializer_list : initializer
| initializer_list ',' initializer
;
type_name : spec_qualifier_list abstract_declarator
| spec_qualifier_list
;
abstract_declarator : pointer
| pointer direct_abstract_declarator
| direct_abstract_declarator
;
direct_abstract_declarator: '(' abstract_declarator ')'
| direct_abstract_declarator '[' const_exp ']'
| '[' const_exp ']'
| direct_abstract_declarator '[' ']'
| '[' ']'
| direct_abstract_declarator '(' param_type_list ')'
| '(' param_type_list ')'
| direct_abstract_declarator '(' ')'
| '(' ')'
;
typedef_name : id
;
stat : labeled_stat
| exp_stat
| compound_stat
| selection_stat
| iteration_stat
| jump_stat
;
labeled_stat : id ':' stat
| 'case' const_exp ':' stat
| 'default' ':' stat
;
exp_stat : exp ';'
| ';'
;
compound_stat : '{' decl_list stat_list '}'
| '{' stat_list '}'
| '{' decl_list '}'
| '{' '}'
;
stat_list : stat
| stat_list stat
;
selection_stat : 'if' '(' exp ')' stat
| 'if' '(' exp ')' stat 'else' stat
| 'switch' '(' exp ')' stat
;
iteration_stat : 'while' '(' exp ')' stat
| 'do' stat 'while' '(' exp ')' ';'
| 'for' '(' exp ';' exp ';' exp ')' stat
| 'for' '(' exp ';' exp ';' ')' stat
| 'for' '(' exp ';' ';' exp ')' stat
| 'for' '(' exp ';' ';' ')' stat
| 'for' '(' ';' exp ';' exp ')' stat
| 'for' '(' ';' exp ';' ')' stat
| 'for' '(' ';' ';' exp ')' stat
| 'for' '(' ';' ';' ')' stat
;
jump_stat : 'goto' id ';'
| 'continue' ';'
| 'break' ';'
| 'return' exp ';'
| 'return' ';'
;
exp : assignment_exp
| exp ',' assignment_exp
;
assignment_exp : conditional_exp
| unary_exp assignment_operator assignment_exp
;
assignment_operator : '=' | '*=' | '/=' | '%=' | '+=' | '-=' | '<<='
| '>>=' | '&=' | '^=' | '|='
;
conditional_exp : logical_or_exp
| logical_or_exp '?' exp ':' conditional_exp
;
const_exp : conditional_exp
;
logical_or_exp : logical_and_exp
| logical_or_exp '||' logical_and_exp
;
logical_and_exp : inclusive_or_exp
| logical_and_exp '&&' inclusive_or_exp
;
inclusive_or_exp : exclusive_or_exp
| inclusive_or_exp '|' exclusive_or_exp
;
exclusive_or_exp : and_exp
| exclusive_or_exp '^' and_exp
;
and_exp : equality_exp
| and_exp '&' equality_exp
;
equality_exp : relational_exp
| equality_exp '==' relational_exp
| equality_exp '!=' relational_exp
;
relational_exp : shift_expression
| relational_exp '<' shift_expression
| relational_exp '>' shift_expression
| relational_exp '<=' shift_expression
| relational_exp '>=' shift_expression
;
shift_expression : additive_exp
| shift_expression '<<' additive_exp
| shift_expression '>>' additive_exp
;
additive_exp : mult_exp
| additive_exp '+' mult_exp
| additive_exp '-' mult_exp
;
mult_exp : cast_exp
| mult_exp '*' cast_exp
| mult_exp '/' cast_exp
| mult_exp '%' cast_exp
;
cast_exp : unary_exp
| '(' type_name ')' cast_exp
;
unary_exp : postfix_exp
| '++' unary_exp
| '--' unary_exp
| unary_operator cast_exp
| 'sizeof' unary_exp
| 'sizeof' '(' type_name ')'
;
unary_operator : '&' | '*' | '+' | '-' | '~' | '!'
;
postfix_exp : primary_exp
| postfix_exp '[' exp ']'
| postfix_exp '(' argument_exp_list ')'
| postfix_exp '(' ')'
| postfix_exp '.' id
| postfix_exp '->' id
| postfix_exp '++'
| postfix_exp '--'
;
primary_exp : id
| const
| string
| '(' exp ')'
;
argument_exp_list : assignment_exp
| argument_exp_list ',' assignment_exp
;
const : int_const
| char_const
| float_const
| enumeration_const
;
| Lex | 4 | StyXman/kgt | examples/c_syntax.lex | [
"BSD-2-Clause"
] |
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Emitter } from 'vs/base/common/event';
import { Disposable, toDisposable } from 'vs/base/common/lifecycle';
import { HeartbeatConstants, IHeartbeatService } from 'vs/platform/terminal/common/terminal';
export class HeartbeatService extends Disposable implements IHeartbeatService {
private readonly _onBeat = this._register(new Emitter<void>());
readonly onBeat = this._onBeat.event;
constructor() {
super();
const interval = setInterval(() => {
this._onBeat.fire();
}, HeartbeatConstants.BeatInterval);
this._register(toDisposable(() => clearInterval(interval)));
}
}
| TypeScript | 4 | sbj42/vscode | src/vs/platform/terminal/node/heartbeatService.ts | [
"MIT"
] |
transformed data {
int N = 5;
int K = 1;
array[5] int<lower=0, upper=1> y = {1, 1, 1, 1, 0};
matrix[5, 1] X = [[1], [1], [1], [1], [1]];
}
parameters {
vector[K] b;
}
model {
y ~ bernoulli_logit(X * b);
}
| Stan | 4 | sthagen/stan-dev-stan | src/test/test-models/good/services/bug_2390_model.stan | [
"CC-BY-3.0",
"BSD-3-Clause"
] |
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns="http://www.w3.org/1999/xhtml">
<xsl:import href="xhr-doc-imported.xsl" />
<xsl:template match="/root">
<xsl:call-template name="works" />
</xsl:template>
</xsl:stylesheet>
| XSLT | 2 | zealoussnow/chromium | third_party/blink/web_tests/fast/xsl/resources/xhr-doc.xsl | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] |
// strings.hb
import stddef;
extern int strcasecmp(char* str1, char* str2);
extern int strncasecmp(char* str1, char* str2, size_t len);
extern char* index(char* src, int ch);
extern char* rindex(char* src, int ch);
| Harbour | 3 | ueki5/cbc | import/strings.hb | [
"Unlicense"
] |
fn main() {
(0..)
.map(
#[target_feature(enable = "")]
//~^ ERROR: attribute should be applied to a function
#[track_caller]
|_| (),
//~^ NOTE: not a function
)
.next();
}
| Rust | 2 | Eric-Arellano/rust | src/test/ui/macros/issue-68060.rs | [
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] |
import std/asyncjs
proc fn1(n: int): Future[int] {.async.} = return n
proc main2() =
proc fn2(n: int): Future[int] {.async.} = return n
proc main3(a: auto) =
proc fn3(n: int): Future[int] {.async.} = return n
proc main4() {.async.} =
proc fn4(n: int): Future[int] {.async.} = return n
discard
| Nimrod | 4 | JohnAD/Nim | tests/js/t17177.nim | [
"MIT"
] |
fn main() {
assert_eq!(1, 2) //~ ERROR: expected `;`
assert_eq!(3, 4) //~ ERROR: expected `;`
println!("hello");
}
| Rust | 2 | mbc-git/rust | src/test/ui/parser/macros-no-semicolon.rs | [
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] |
{
"BABEL_8_BREAKING": true,
"plugins": ["transform-typescript"]
}
| JSON | 3 | fatash89/babel | packages/babel-plugin-transform-typescript/test/fixtures/class/uninitialized-definite/options.json | [
"MIT"
] |
;; Copyright (c) 2011-2014 Robert Virding. 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 HOLDERS 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.
(defmodule chat_ws_handler
(export (init 2) (websocket_handle 3) (websocket_info 3)))
;; Internal state.
(defrecord state (opts ()))
(defun init (req opts)
(chat_server:new_user) ;A new user
`#(cowboy_websocket ,req ,(make-state opts opts)))
;; Callback on received websocket data.
(defun websocket_handle
([`#(text ,data) req st]
(lfe_io:format "ws text: ~p\n" (list data))
(case data
((binary "msg ! " (msg binary))
(chat_server:send_message msg)
`#(ok ,req ,st))
((binary "nick ! " (nick binary))
(chat_server:set_nick nick)
`#(ok ,req ,st))
(_
`#(reply #(text ("status ! received '" ,data "'")) ,req ,st))))
([other req st]
(lfe_io:format "ws other: ~p\n" (list other))
`#(ok ,req ,st)))
;; Callback on message from erlang.
(defun websocket_info
([(= `#(text #(message ,msg)) data) req st]
(lfe_io:format "cs text: ~p\n" (list data))
`#(reply #(text ("output ! " ,msg)) ,req ,st))
([other req st]
(lfe_io:format "cs other: ~p\n" (list other))
`#(ok ,req ,st)))
| LFE | 4 | rvirding/chat_demo | src/chat_ws_handler.lfe | [
"BSD-2-Clause"
] |
spring.rsocket.server.port=7000
server.port=8081
| INI | 0 | DBatOWL/tutorials | spring-5-webflux/src/main/resources/application-server.properties | [
"MIT"
] |
extensions [ gis ; GIS extension for NetLogo, needed if using imported shapefiles
nw ; NW extension for NetLogo, needed to create the network shapes for houses, destinations, etc.
csv ] ; CSV extension for NetLogo, needed to read in the file of which tramstops are connected
globals [ tramstops-dataset ; These are declared here to make it easier to switch between the Random and GM projections
tramlines-dataset
LAs-dataset
Tramstop_Connections
output-filename
run-seed ]
breed [tramstops tramstop] ; Breeds allows the modeller to easily ask some sets of agents to run commands or otherwise take actions
breed [houses house]
breed [places place]
breed [denizens denizen]
breed [ LAs LA ]
turtles-own [LAs-name-t ; These are (in addition to primitive features like size or color) the features that every agent in this model has
LAs-population-t]
tramstops-own [myneighbors
Tramstop_Name]
patches-own [ centroid ; Like turtles-own, these are the features that all patches in this model have (also, primitive patch features like location and color)
LAs-population
LAs-name]
LAs-own [centroid-x] ; These are the features that only the subset of LA agents have. No other turtle will have these.
links-own [Speed ; Like turtles-own and patches-own, links can be assigned model specific features here.
Capacity]
denizens-own [My_Places ; Denizens have the most features as these are the only agents that move around when the model runs.
current-location
current-path
next-location
current-speed
destination
starting-place
travel-timer]
to setup
clear-all ; Always start by clearing everything.
set run-seed new-seed ; Creates a "seed" to use as a unique identifier for the run (also, allows the run to be re-run exactly)
random-seed run-seed ; Initiates this run using the just created seed
set output-filename (word projection "_" Output_File "_" run-seed ) ; Creates an output file to record the model run based on the projection selected, a user input value and the seed created to identify this run
ifelse projection = "Random" ; The model diverges significantly depending on whether you want to use randomly generated or imported features of the model world
[ setup-random ] ; This initiates the procedures to set up a random world, drawing on the various "Random_Generated" switches and sliders.
[ setup-input ] ; This initiates the procedures to set up a world based on imported shapefiles. This too draws on switches and sliders, but not those specific to
setup-trams ; the Random projection models, such as "Random_Generated_Tramstops".
if Garrulous? [ask links [print end1]]
setup-houses-and-places
setup-denizens
check-speed
initial-exports
reset-ticks
end
to setup-random ; The random setup has several steps
resize-world -90 90 -90 90 ; 1- Define the size of the world
set-patch-size 3 ; Patch size interacts with world dimensions to determine the world size.
ask LAs [die] ; 2- LAs are agents (or turtles) that are useful for creating and displaying labels. But first, make sure none are leftover from previous runs.
create-LAs Number_Generated_LAs_Random_Only [ ; According to modeller input on a slider in the interface, the model creates a certain number of "Local Authority" agents
setxy 0 0 ; Those LA agents start at the centre ...
set xcor xcor + random 50 - random 50 ; Move randomly right and left ...
set ycor ycor + random 50 - random 50 ; Move randomly up and down ...
set size 0 ; Set their size to 0 so as to be invisible ...
set label-color yellow ; Set their label color to yellow to increase visibility ...
set LAs-population-t 5 + random Max_Random_Population ; 3- The LA agents set their population as 5 plus a random number up to the maximum set by the modeller (this prevents a 0 population error).
if Label_LAs? [set LAs-name-t (word "LA " who)] ; 4- The LA agents check to see if the modeller has asked them to display their names, and if so they do.
ask patch-here [set LAs-population [LAs-population-t] of LAs-here ; 5- Then the LA agents talks to the patch underneath themselves.
set LAs-name [LAs-name-t] of LAs-here ; The LA agent asks the patch to copy details like population and name from the LA agent to itself.
set pcolor red ; And also asks the patches to set their color to red.
if Garrulous? [print (word pxcor pycor LAs-population LAs-name)]] ; 6- If the model is set to run in Garrulous mode, it prints some descriptive details to the command centre pane in the interface.
ask patches with [pcolor = red] [ ; 7- The model then asks all patches that are colored red
set LAs-population item 0 LAs-population ; To reformat the information they have written in their name and population (this ensures these are recorded properly as strings or numbers
set LAs-name item 0 LAs-name ; rather than lists.
set pcolor red + ((LAs-population - min [LAs-population] of patches with [is-number? LAs-population]) * .1 ) ; The patches then set their color relative to their population to improve visibility.
if pcolor = black [set pcolor pcolor + 5 ] ] ] ; Ask any LA patches that are black to recolor themselves, just for clarity.
repeat 50 [ask patches with [pcolor = black] [if any? neighbors with [pcolor != black] [ ; 8- Then, in 50 separate rounds, black patches check to see if they have any non-black neighbouring patches.
let join-LAs one-of neighbors with [pcolor != black] ; 9- If so, they copy the name, population and colour of one of their non-black neighbours.
set pcolor [pcolor] of join-LAs ; This creates the growth of random "LA-like" zones of color across the world.
set LAs-population [LAs-population] of join-LAs
set LAs-name [LAs-name] of join-LAs] ] ]
end
to setup-input ; The non-random projection also has several steps, many are similar to those in the random set up.
gis:load-coordinate-system (word "Model_Data/" projection ".prj") ; 1- Set the coordinate system or 'projection'. This is optional as long as all of the datasets use the same coordinate system.
set tramstops-dataset gis:load-dataset "Model_Data/GM_Tramstops.shp" ; Load all of your non-random datasets (as many as you need), assigning them to the globals created above.
set tramlines-dataset gis:load-dataset "Model_Data/GM_Tramlines.shp"
set LAs-dataset gis:load-dataset "Model_Data/GM_LAs_R.shp"
gis:set-world-envelope (gis:envelope-union-of (gis:envelope-of tramstops-dataset) ; 2- Set the world envelope to the union of all of the datasets' envelopes. This ensures they line up correctly.
(gis:envelope-of tramlines-dataset)
(gis:envelope-of LAs-dataset))
set Tramstop_Connections (csv:from-file "Model_Data/Tramstop_Connections.csv" "," ) ; Load the .csv file of which tramstops are connected
ask LAs [ die ] ; 3- As with the Random projection, clear any agents that may be around.
gis:set-drawing-color white ; 4- Set the drawing color to white.
gis:draw LAs-dataset 1 ; Draw the polygon data from the shapefile.
let i 1 ; 5- Technical processes of identifing features from the shapefile and loading them into temporary values.
foreach gis:feature-list-of LAs-dataset [ vector-feature ->
let centroid-y gis:location-of gis:centroid-of vector-feature ; The middle of each polygon is identified and added to a list (but not if it lies outside the world as defined).
if not empty? centroid-y ; 6- If the centroid list is not empty,
[ create-LAs 1 ; Then create an LA agent and ...
[ set xcor item 0 centroid-y ; Move it to the right position (right/left)
set ycor item 1 centroid-y ; Move it to the right position (up/down)
set size 0 ; Set their size to 0 so as to be invisible ...
set label-color yellow ; Set their label color to yellow to increase visibility ...
if Label_LAs? [set label gis:property-value vector-feature "name"] ; Set their label color to yellow to increase visibility ...
set LAs-population-t gis:property-value vector-feature "population" ; Set their label to be their name, which is drawn from the imported shapefile ...
set LAs-name-t gis:property-value vector-feature "name" ; And copy that name to turtles-own feature.
ask patch-here [set LAs-population [LAs-population-t] of LAs-here ; 7- Then the LA agents talks to the patch underneath themselves.
set LAs-name [LAs-name-t] of LAs-here ; The LA agent asks the patch to copy details like population and name from the LA agent to itself.
set pcolor red] ] ] ; And also asks the patches to set their color to red.
set i i + 1 ]
gis:apply-coverage LAs-dataset "POPULATION" LAs-population ; 8- Pass the population feature from the LA to the patches within the LA
gis:apply-coverage LAs-dataset "NAME" LAs-name ; Also pass the name feature from LA to patches.
let min-pop min [read-from-string LAs-population ] of patches with [is-string? LAs-population] ; 9- The patches then set their color relative to their population to improve visibility.
ask patches with [is-string? LAs-population] [
set pcolor red + ((read-from-string LAs-population - min-pop) * .1 )
if pcolor = black [set pcolor pcolor + 5 ]] ; Ask any LA patches that are black to recolor themselves, just for clarity.
end
to setup-trams
ask tramstops [ die ] ; Start by ensuring that there are no tramstops already present
set-default-shape tramstops "building store" ; Set the default shape for a tram stop to the building shape that looks most appropriate
ifelse projection = "Random" ; Set up locations for tramstops (and create links between them) based on random generation and user input or uploaded shapefiles
[ nw:generate-preferential-attachment tramstops links Number_Generated_Tramstops_Random_Only 1 [ ; IF RANDOM, create a random preferential attachment network of linked tramstops ...
move-to one-of patches with [pcolor != black] ; and ask them to move to one of the LA areas already created
if Label_Tramstops? [set label (word LAs-name-t who) ] ] ; Check if the modeller has decided to label tramstops, and if so ask them to display their "who" number
repeat 50 [ layout-spring tramstops links 0.2 11 1 ] ] ; Move tramstops around with spring-layout to make the network look better
[gis:set-drawing-color blue ; IF NOT RANDOM, pick up a blue crayon and ...
gis:draw tramlines-dataset 1 ; draw in tramlines according to the tramlines dataset
gis:set-drawing-color cyan ; Pick up a cyan crayon and ...
foreach gis:feature-list-of tramstops-dataset [ vector-feature -> ; look into the tramstop dataset ...
let centroid-stops gis:location-of gis:centroid-of vector-feature ; creating a list of all "centroids" within the bounds of the current NetLogo world, as defined by the current GIS coordinate transformation
if not empty? centroid-stops ; If centroid is not an empty list ...
[ create-tramstops 1 ; create one tramstop per centroid...
[ set xcor item 0 centroid-stops ; Move it to the X coordinate of the centroid
set ycor item 1 centroid-stops ; Move it to the Y coordinate of the centroid
set Tramstop_Name gis:property-value vector-feature "RSTNAM" ; Copy over the name of of the centroid
if Label_Tramstops? [set label gis:property-value vector-feature "RSTNAM" ] ] ] ] ] ; Check if the modeller has decided to label tramstops, and if so ask them to display the name they copied over.
ask tramstops [
set LAs-name-t [LAs-name] of patch-here ; Tramstops copy over the LA-name from the patches on which they find themselves and ..
set LAs-population-t [LAs-population] of patch-here ; the population of the LA.
set color blue ; They change their colour.
set size 3 ; And their size.
if projection != "Random" [foreach Tramstop_Connections ; IF NOT RANDOM, look into the uploaded .csv file and for each row ...
[ [ LinkedStops ] -> ask tramstops with [Tramstop_Name = (item 0 LinkedStops)] ; create a temporary variable copy of that row, then ask tramstops whose names match the first item in the row
[set myneighbors but-first LinkedStops] ] ; to set the "myneighbors" variable to be the rest of the items on the temporary variable list.
foreach myneighbors ; Then, for each item in the "myneighbors" variable...
[ [ next_stop] -> ask tramstops with [Tramstop_Name = next_stop] ; they create a temporary variable and ask the tramstop whose name matches that item to
[create-link-with myself] ] ] ] ; create a link with the original tramstop that is doing the asking
ask tramstops [ set myneighbors link-neighbors ] ; Then, all tramstops reset their "myneighbors" variable to the set of agents with which they are linked.
ask links [set Speed 10 ; Then, all links, which at this point are only between tramstops, set their speed to 10 and ...
set Capacity 100] ; their capacity to 100. Capacity is not a functional variable in the current model code
end
to setup-houses-and-places
ask houses [ die ] ; Start by ensuring that there are no houses already present
set-default-shape houses "house" ; Set the default shape for a house to be house shaped
ask LAs [if is-string? LAs-population-t ; A check to make sure that both random and non-random models have population recorded properly as a number
[set LAs-population-t read-from-string LAs-population-t] ] ; population recorded properly as a number.
if projection = "Random" ; IF RANDOM,
[ask LAs [ifelse Tram_Commute_Only? ; Check to see if the modeller input is set to "houses and places only in LAs with tramstops"
[if any? tramstops with [LAs-name-t = [LAs-name-t] of myself] ; IF SO, LAs with tramstops ...
[hatch-houses 1 + random LAs-population-t ] ] ; hatch at least one house, plus some random number between 0 and their populaton
[hatch-houses 1 + random LAs-population-t ] ] ] ; OTHERWISE, all LAs hatch at least one house, plus some random number between 0 and their populaton.
if projection = "GM_LAs" ; IF NOT RANDOM,
[ask LAs [ifelse Tram_Commute_Only? ; Check to see if the modeller input is set to "houses and places only in LAs with tramstops"
[if any? tramstops with [LAs-name-t = [LAs-name-t] of myself] ; IF SO, LAs with tramstops ...
[hatch-houses ( LAs-population-t / 1000 ) ; Hatch one house per 1000 people
if Garrulous?
[print (word LAs-name-t " has " (LAs-population-t / 1000) " houses.") ] ] ]
[hatch-houses ( LAs-population-t / 1000 ) ; Otherwise, all LAs hatch one house per 1000 people.
if Garrulous?
[print (word LAs-name-t " has " (LAs-population-t / 1000) " houses.") ] ] ] ]
ask houses [ let move-house one-of patches with [LAs-name = [LAs-name-t] of myself] ; Houses then pick a random patch within the same LA
set xcor [pxcor] of move-house ; Then sets its X coordinate to match that of the random patch
set ycor [pycor] of move-house ; Then sets its Y coordinate to match that of the random patch
create-link-with min-one-of tramstops [distance myself] ; Then creates a link to the nearest tramstop,
set color yellow ; Changes its colour
set size 2 ; Sets its size
set label "" ] ; And removes its label (removing a label is the same as setting it to an empty string, written as "").
ask places [ die ] ; Start by ensuring that there are no places already present
set-default-shape places "building institution" ; Set the default shape for a place to be sort of museum-shaped
ask LAs [ifelse Tram_Commute_Only? ; Check to see if the modeller input is set to "houses and places only in LAs with tramstops"
[if any? tramstops with [LAs-name-t = [LAs-name-t] of myself] ; IF SO, LAs with tramstops ...
[let LAs_with_tramstops [LAs-name-t] of tramstops ; create a list of all LAs that have tramstops,
set LAs_with_tramstops remove-duplicates LAs_with_tramstops ; removes any duplicate entries from that list,
hatch-places (Number_Generated_Places / length LAs_with_tramstops ) ] ] ; and hatches places equal to the modeller input divided by the number of LAs with tramstops.
[ hatch-places (Number_Generated_Places / Number_Generated_LAs_Random_Only ) ] ] ; OTHERWISE, all LAs hatches places equal to the modeller input divided by the total number of LAs.
ask places [let move-place one-of patches with [LAs-name = [LAs-name-t] of myself] ; As the houses did before, places pick a random patch within the same LA
set xcor [pxcor] of move-place ; Then sets its X coordinate to match that of the random patch
set ycor [pycor] of move-place ; Then sets its Y coordinate to match that of the random patch
create-link-with min-one-of tramstops [distance myself] ; Then creates a link to the nearest tramstop,
set color orange ; Changes its colour
set size 3 ] ; And its size
ask links [if Speed != 10 [ ; The model then asks all links to check if their speed has already been set to 10
set Speed 1 + random 8 ; If not (should only apply to links between houses and tramstops or places and tramstops
set Capacity 10]] ; And sets capacity (again, still an unused variable).
repeat 10 [ask tramstops [if not any? links with [Speed < 10][ ; Then, the model asks tramstops to check if they have any slow speed links
ask one-of places with [LAs-name-t = [LAs-name-t] of self] [ ; And if not, asks one of the places within their LA to ...
move-to myself ; move to the same patch as the asking tramstop ...
set xcor xcor + random 2 - random 2 ; Shift the X coordinate a bit
set ycor ycor + random 2 - random 2 ; Shift the Y coordinate a bit
ask my-links [die] ; Sever links to other tramstops
create-link-with myself [set Speed (1 + random 9) ; And create an appropriate link with the asking tramstop.
set Capacity 10]]
ask one-of houses with [LAs-name-t = [LAs-name-t] of self] [ ; This same process repeats with houses. These stepsensure
move-to self ; there are no tramstops that are not the "nearest" tramstop to anyone or anything.
set xcor xcor + random 2 - random 2
set ycor ycor + random 2 - random 2
ask my-links [die]
create-link-with myself[set Speed (1 + random 9)
set Capacity 10]]]]]
end
to setup-denizens
ask LAs [ if any? houses with [LAs-name-t = [LAs-name-t] of myself] [ ; The model then asks the LAs that have houses to...
ifelse Reduce_Pop_For_Display? ; Check if the modeller wants to reduce the population for display and...
[hatch-denizens (Max_Random_Population + (LAs-population-t / 1000)) ] ; If so, hatch a significant number of commuters (but not nearly as many as would be hatched if there are high populations
[hatch-denizens LAs-population-t] ] ] ; Otherwise, hatch as many commuters as the population says to
ask denizens [ ; Ask the newly created commuter-agents
move-to one-of houses with [LAs-name-t = [LAs-name-t] of myself] ; to move to one of the houses in their LA
set size 2 ; Set their size
set color green ; Set their colour
create-link-with one-of houses-here ; And create a link to the house on their current location
set current-location one-of houses-here ; And start setting various commuter specific details, like their current-location
set My_Places [] ; some variables are easier to set later if first set to an empty list, written as []
set current-path [] ; -
repeat (5 + random 5 )[let possible-destination one-of places ; Then, they start picking random places they might want to go
if is-list? nw:turtles-on-path-to possible-destination [ ; check to make sure there is a path to get there
set My_Places lput possible-destination My_Places]] ; And if so, start filling up the previously empty list of their places
set My_Places remove-duplicates My_Places ; Double check to be sure there are no duplicates on the list of places to go
if empty? My_Places [die] ; A security check to be sure that no agent can continue to exist if it has not managed to find any places that it can travel to
set destination one-of My_Places ; Select one of their places to go as their destination, or the next place they want to go
set current-path nw:turtles-on-path-to destination ; Record the path to get to their selected destination
repeat 2 [ if not empty? current-path [set current-path but-first current-path] ; Remove the first two stops on the path because these will be themself, followed by the house they are currently located in
set next-location first current-path ; Set the next stop on their path as their short-term goal, which should be the nearest tramstop
face next-location ] ; And face that tramstop
set My_Places fput one-of houses-here My_Places ; Add the house in which they are currently located to their list of places (so they can get home again later)
set starting-place one-of houses-here ; Ask them to record the origen of they next journey
set travel-timer 0 ] ; And ask them to ensure they start counting how long it takes to reach their destination from zero
end
to check-speed
ask denizens [
let who-here [who] of current-location
let who-there [who] of next-location
if link who-here who-there != nobody [set current-speed [Speed] of link who-here who-there]
if link who-there who-here != nobody [set current-speed [Speed] of link who-there who-here]
if Garrulous? [print current-speed]
]
end
to go
ask denizens [ ; The basic "go" process
ifelse distance next-location > (1 * current-speed) ; Commuters check to see if they are more they are less than one timestep away from arriving at their next proximal destination
[fd 1 * current-speed ; If so, they carry on moving forward
set travel-timer travel-timer + 1 ] ; and add one to their travel time
[move-to next-location ; If they are closer than one timestep worth of travel to their next proximal destination, they move directly to it
set travel-timer travel-timer + 1 ; and one to their travel time
ask my-links [die] ; ask their links to the previous proximal destination to die
ifelse length current-path > 1 [set-next-step] ; Check to see if they are at their destination
[when-at-destination]]] ; If not, they go through the processes to head to the next proximal destination
tick ; Or they go through the processes for arriving at their destination
end
to when-at-destination
set current-location next-location ; They copy over their next proximal destination to their current location
set travel-timer travel-timer + 1 ; They add one to their travel time
if Export_Data? ; Check to see if the modeller wants data exports
[file-open (word output-filename ".csv" ) ; If so, they open the appropriate file. The "," enables it to be formatted for .csv
file-print ; Adds their who number, origen, origen LA, destination, destination LA, and travel time .
(word who "," starting-place "," [LAs-name-t] of starting-place ","
destination "," [LAs-name-t] of destination "," travel-timer)
file-close] ; And closes the file - still important.
set starting-place destination ; They copy over their current destination to be the starting-place for the next journey.
set destination one-of My_Places ; Pick a new destination is head to...
set travel-timer 0 ; Reset the counter that tracks time elapsed for travel back to zero
if any? places-here ; Checks to see if they are currently at a Place and...
[create-link-with one-of places-here] ; If so, creates a link with that place.
if any? houses-here ; Checks to see if they are currently at a House and...
[create-link-with one-of houses-here] ; If so, creates a link with that house.
set current-path [] ; Resets the current-path to their new destination back to an empty list
set current-path nw:turtles-on-path-to destination ; Identifies the path to that new destination and fills in the recently reset current-path
set next-location first current-path ; Sets next proximal destination
face next-location ; Turns to face that proximal destination
set current-path but-first current-path ; And removes the proximal destination from the current-path
end
to set-next-step
if any? tramstops-here ; Having arrived at a proximal destination, the commuter-agent checks to see what tramstop is located at its current location
[create-link-with one-of tramstops-here] ; And creates a link with that tramstop
if any? places-here ; Although it should not happen, the the commuter-agent checks to see if there is a place at its current location instead of a tramstop
[create-link-with one-of places-here] ; And if so, creates a link with that place
if any? houses-here ; Although it should not happen, the the commuter-agent checks to see if there is a housee at its current location instead of a tramstop
[create-link-with one-of houses-here] ; And if so, creates a link with that house
set current-location next-location ; copies the recently reached proximal destination over as its current location
set current-path but-first current-path ; And removes the recently reach proximal destination from the path to take to its ultimate destination
set next-location first current-path ; Sets its next proximal destination to be the first step on its path to its ultimate destination
face next-location ; And turns to face that proximal destination
end
to initial-exports
if Export_Data?
[file-open (word output-filename ".csv" ) ; Creates a file named with the output-filename created earlier. Wrapping it in (word ".csv") allows you to set the file type to .csv
file-print (word "Commuter,Origen,Origen_LA,Destination,Destination_LA,Travel_time") ; Set up the headers that should appear in the output file
; file-print (word " , , , , ,") ; Currently not needed - but you could use row (or more like it) to write out any other necessary details from the setup process
file-close] ; Closes the file - necessary to save the input just added and also prepare the file to be opened and written to again in the future
end
@#$#@#$#@
GRAPHICS-WINDOW
294
17
845
569
-1
-1
3.0
1
8
1
1
1
0
0
0
1
-90
90
-90
90
0
0
1
ticks
30.0
BUTTON
5
60
175
93
NIL
setup\n
NIL
1
T
OBSERVER
NIL
NIL
NIL
NIL
1
SWITCH
3
173
176
206
Label_Tramstops?
Label_Tramstops?
1
1
-1000
CHOOSER
5
10
175
55
projection
projection
"GM_LAs" "Random"
0
SLIDER
3
533
290
566
Number_Generated_Tramstops_Random_Only
Number_Generated_Tramstops_Random_Only
3
100
25.0
1
1
NIL
HORIZONTAL
SLIDER
4
571
304
604
Number_Generated_Places
Number_Generated_Places
3
100
17.0
1
1
NIL
HORIZONTAL
SWITCH
2
136
175
169
Garrulous?
Garrulous?
1
1
-1000
BUTTON
21
95
84
128
Go
go
T
1
T
OBSERVER
NIL
NIL
NIL
NIL
1
BUTTON
87
95
166
128
Go Once
go
NIL
1
T
OBSERVER
NIL
NIL
NIL
NIL
1
SLIDER
3
497
290
530
Number_Generated_LAs_Random_Only
Number_Generated_LAs_Random_Only
2
15
5.0
1
1
NIL
HORIZONTAL
INPUTBOX
6
432
158
492
Max_Random_Population
150.0
1
0
Number
SWITCH
3
212
177
245
Label_LAs?
Label_LAs?
1
1
-1000
SWITCH
2
249
179
282
Reduce_Pop_For_Display?
Reduce_Pop_For_Display?
0
1
-1000
SWITCH
3
286
183
319
Tram_Commute_Only?
Tram_Commute_Only?
0
1
-1000
INPUTBOX
2
322
202
382
Output_File
CodeTest
1
0
String
SWITCH
8
389
140
422
Export_Data?
Export_Data?
0
1
-1000
@#$#@#$#@
## WHAT IS IT?
This model is intended to demonstrate three broad concepts, each of which has an associated NetLogo extension:
• importing and exporting files into NetLogo via the CSV extension,
• loading point, line and polygon shapefiles into NetLogo via the GIS extension, and
• building and navigating networks of agents via the NW extension.
To achieve this, the model creates a cross-local authority tram network along with houses, commuters and places for them to travel to. The modeller can choose to create a randomly generated tram network via a few inputs that are only applicable to the random model (number of local authorities, number of tram stops, etc. all are indicated by "_Random_Only" in the name of the input) or can load a real-world tram network using downloaded shape files (in this case, the shape files relate to the Greater Manchester combined authority and Metrolink system).
## HOW IT WORKS
First, the "Projection" must be set to either "Random" or "GM_LAs". The model operation is broadly similar for both, although the set up procedures are different because.
In both cases, the NetLogo world is divided into local authorities, each with a name and resident population, before tram stops are located and linked. If "Projection" is set to:
• "Random" the model setup uses the value of the "Number_Generated_LAs_Random_Only" slider (between 2 and 15 in increments of 1) and built-in NetLogo functions to determine the number and random location of "LAs" agents. The LAs agents are then assigned a random population below the value of "Max_Random_Population" as input by the modeller. The LAs then adjust their colour relative to their population (with a special check to ensure they do not change it to black). The model then asks black patches to observe if any of their neighbours are a non-black colour and, if so, to change their colour to match (choosing randomly between colours if two or more neighbours are not black). The model setup then uses the value of "Number_Generated_Tramstops_Random_Only" slider (between 3 and 100 in increments of 1) to determine the number and initial location of tramstops throughout the entire area. The tramstops are then connected in a preferential attachment network and their position is adjusted by repeating "layout-spring" to improve its appearance.
• "GM_LAs" the model setup draws on .prj, .csv, and .shp files made available by the modeller. These files contain the number, location, shape and name of local authorities (as well as their resident population), and the number, location and names of tramstops as well as how they are linked.
The local authorities will display their names if the modeller input "Label_LAs?" is set to TRUE. The tramstops will display their names if the modeller input "Label_Tramstops?" is set to TRUE. If "Projection" is set to random, the names of LAs and tramstop agents is simply their who number.
After this, the model setup is the same for both projections. Setup continues as the model uses the populations of each local authority and built-in NetLogo functions to create a number of houses within each local authority between 1 and the total population of that local authority). The houses are then located randomly within the local authority. The model then creates commuter agents equal to the population of the local authority, unless "Reduce_Population_for_display?" is set to TRUE. This limits the number of commuters per local authority to the value of "Max_Random_Population" + (the total population of the local authority / 1000). Although "Reduce_Population_for_display?" can be set to TRUE for both the random and non-random projections, it will only have a discernible effect on the non-random projection if "Max_Random_Population" is significantly smaller than the actual population of a given local authority. This switch is intended to improve the setup time, run speed and visual interpretability of non-random projections when the real-world population is problematically high.
However many houses are created, they are then connected to the tram network by creating a link to the nearest tramstop.
The model then uses value of "Number_Generated_Places" (between 3 and 100 in increments of 1) to create and locate places (non-house buildings that commuters can travel to) within the local authorities. The places are then connected to the tram network by creating a link to the nearest tramstop.
The model offers the option to locate houses and places either only within local authorities that have tram stops within their boundaries (by setting "Tram Commute Only?" to TRUE) or within any local authority (by setting "Tram Commute Only?" to FALSE).
The model then assigns commuters a small set of places across the network that they can travel to. The house that each commuter begins at is also added to this list of travel destinations. When the model runs, the commuters select one of their destinations, plots a path to get there via the tram network, and proceeds to move across the network. When they arrive, they choose a new destination and repeat the process.
The model offers the option to allow to export data to a .csv file through the modeller inputs of "Export data?" and "Output_file". If "Export_data?" is set to TRUE, the model creates a .csv named using the input in the "Output_file" field and 6 columns. Whenever a commuter arrives at their destination, they write a line to the .csv file that states their who number, the house or place at which the journey started, the local authority in which the journey started, the house or place at which the journey ended, the local authority in which the journey ended, and the number of time steps elapsed during the journey.
NOTE: The random projection model requires several inputs that the non-random projection model does not (Number_Generated_LAs, Number_Generated_Tramstops, Max_Random_Population).
The non-random projection model draws these same details from the uploaded .shp files. Setting these variables will have no effect on the model if "Projection" is not set to "Random".
There are also options intended to be useful for demonstration and bug-testing purposes. "Reduce_Population_for_Dispaly?" limits the population to a fraction of its total in order to speed up the set up and go processes as well as improve the interpretability of the display. If "Garrulous?" is set to TRUE, the model runs with many outputs written to the command centre in order to improve bug testing. This is unlikely to be interesting for normal operation.
## HOW TO USE IT
Put all files in a sensible folder. This is especially important when running the non-random projection as the model will need to access the shape files and/or .csv files. You may need to rename the files, the folders they are in, or the path to the files as it appears in the code.
When the model is opened, the modeller will need to decide whether to run a random or non-random model. The modeller should set the options for labelling tram stops and/or local authorities, restricting the population for display, restricting the houses and places to LAs with tramstops only, and whether or not an export file should be created (as well as setting the name of that file in the Output_File field).
Random models will require attention to the inputs at the bottom (Max_Random_Populaton, Number_of_Generated_LAs, Number_of_Generated_Tramstops, Number_of_Generated_Places).
Hit set up.
Hit Go once or Go Forever.
## THINGS TO NOTICE
This model is not particularly realistic. It assumes that all commuters travel directly from their houses to their nearest tram stop, travel by tram to the stop nearest their intended destination, then travel directly to that destination before turning around and repeating the process with a new destination (which might be their house).
There is no wait time at tram stops. There is no maximum capacity on the trams. There is no distribution of travel speeds among commuters to account for people that might bike, drive, bus, rollerskate or otherwise travel to the tram stop or people that walk slower than others.
Commuters do not spend any significant time at their destinations. They do not have regular patterns of travel, analogous to a standard commute, but instead randomly pick their destination from among the small set of destinations they have designated as “theirs”.
This is because this model is not intended to replicated an interesting real-wold behaviour with the detail and specificity needed to really say something about that behaviour. Instead, it is meant to demonstrate the processes of importing files, using GIS data, navigating networks, and running experiments. As such, the code is extremely thoroughly commented.
## THINGS TO TRY
A couple of things to try would be to:
• run parameter sweeps on the random model to identify whether there are interesting interactions,
• replace the Greater Manchester shapefiles with analogous files for another tram network, or
• rewrite the output file to include reports from place-agents or tramstop-agents to identify which is the most popular.
## EXTENDING THE MODEL
Reasonable interactions would include:
• Adding bus, bike lane, road, train or other networks,
• Define the destinations that commuters travel to by when they are likely to arrive or how long they spend there,
• Add options to vary the travel speed,
• Introduce actual trams to the tram network so that commuters wait at tram stops or when changing tram lines,
• Other?
## NETLOGO FEATURES
## CREDITS AND REFERENCES
This model use the NetLogo code examples for Travel The Line and GIS extension.
## HOW TO CITE
If you mention this model or the NetLogo software in a publication, we ask that you include the citations below.
For the model itself:
* Kasmire, J. (2020). Tram Commute. UK Data Services and University of Manchester, UK.
Please cite the NetLogo software as:
* Wilensky, U. (1999). NetLogo. http://ccl.northwestern.edu/netlogo/. Center for Connected Learning and Computer-Based Modeling, Northwestern University, Evanston, IL.
## COPYRIGHT AND LICENSE
This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 3.0 License. To view a copy of this license, visit https://creativecommons.org/licenses/by-nc-sa/3.0/ or send a letter to Creative Commons, 559 Nathan Abbott Way, Stanford, California 94305, USA.
Commercial licenses are also available. To inquire about commercial licenses, please contact Uri Wilensky at uri@northwestern.edu.
This model was created as part of the project: CONNECTED MATHEMATICS: MAKING SENSE OF COMPLEX PHENOMENA THROUGH BUILDING OBJECT-BASED PARALLEL MODELS (OBPML). The project gratefully acknowledges the support of the National Science Foundation (Applications of Advanced Technologies Program) -- grant numbers RED #9552950 and REC #9632612.
This model was converted to NetLogo as part of the projects: PARTICIPATORY SIMULATIONS: NETWORK-BASED DESIGN FOR SYSTEMS LEARNING IN CLASSROOMS and/or INTEGRATED SIMULATION AND MODELING ENVIRONMENT. The project gratefully acknowledges the support of the National Science Foundation (REPP & ROLE programs) -- grant numbers REC #9814682 and REC-0126227. Converted from StarLogoT to NetLogo, 2001.
@#$#@#$#@
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
building institution
false
0
Rectangle -7500403 true true 0 60 300 270
Rectangle -16777216 true false 130 196 168 256
Rectangle -16777216 false false 0 255 300 270
Polygon -7500403 true true 0 60 150 15 300 60
Polygon -16777216 false false 0 60 150 15 300 60
Circle -1 true false 135 26 30
Circle -16777216 false false 135 25 30
Rectangle -16777216 false false 0 60 300 75
Rectangle -16777216 false false 218 75 255 90
Rectangle -16777216 false false 218 240 255 255
Rectangle -16777216 false false 224 90 249 240
Rectangle -16777216 false false 45 75 82 90
Rectangle -16777216 false false 45 240 82 255
Rectangle -16777216 false false 51 90 76 240
Rectangle -16777216 false false 90 240 127 255
Rectangle -16777216 false false 90 75 127 90
Rectangle -16777216 false false 96 90 121 240
Rectangle -16777216 false false 179 90 204 240
Rectangle -16777216 false false 173 75 210 90
Rectangle -16777216 false false 173 240 210 255
Rectangle -16777216 false false 269 90 294 240
Rectangle -16777216 false false 263 75 300 90
Rectangle -16777216 false false 263 240 300 255
Rectangle -16777216 false false 0 240 37 255
Rectangle -16777216 false false 6 90 31 240
Rectangle -16777216 false false 0 75 37 90
Line -16777216 false 112 260 184 260
Line -16777216 false 105 265 196 265
building store
false
0
Rectangle -7500403 true true 30 45 45 240
Rectangle -16777216 false false 30 45 45 165
Rectangle -7500403 true true 15 165 285 255
Rectangle -16777216 true false 120 195 180 255
Line -7500403 true 150 195 150 255
Rectangle -16777216 true false 30 180 105 240
Rectangle -16777216 true false 195 180 270 240
Line -16777216 false 0 165 300 165
Polygon -7500403 true true 0 165 45 135 60 90 240 90 255 135 300 165
Rectangle -7500403 true true 0 0 75 45
Rectangle -16777216 false false 0 0 75 45
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
house bungalow
false
0
Rectangle -7500403 true true 210 75 225 255
Rectangle -7500403 true true 90 135 210 255
Rectangle -16777216 true false 165 195 195 255
Line -16777216 false 210 135 210 255
Rectangle -16777216 true false 105 202 135 240
Polygon -7500403 true true 225 150 75 150 150 75
Line -16777216 false 75 150 225 150
Line -16777216 false 195 120 225 150
Polygon -16777216 false false 165 195 150 195 180 165 210 195
Rectangle -16777216 true false 135 105 165 135
house colonial
false
0
Rectangle -7500403 true true 270 75 285 255
Rectangle -7500403 true true 45 135 270 255
Rectangle -16777216 true false 124 195 187 256
Rectangle -16777216 true false 60 195 105 240
Rectangle -16777216 true false 60 150 105 180
Rectangle -16777216 true false 210 150 255 180
Line -16777216 false 270 135 270 255
Polygon -7500403 true true 30 135 285 135 240 90 75 90
Line -16777216 false 30 135 285 135
Line -16777216 false 255 105 285 135
Line -7500403 true 154 195 154 255
Rectangle -16777216 true false 210 195 255 240
Rectangle -16777216 true false 135 150 180 180
house efficiency
false
0
Rectangle -7500403 true true 180 90 195 195
Rectangle -7500403 true true 90 165 210 255
Rectangle -16777216 true false 165 195 195 255
Rectangle -16777216 true false 105 202 135 240
Polygon -7500403 true true 225 165 75 165 150 90
Line -16777216 false 75 165 225 165
house ranch
false
0
Rectangle -7500403 true true 270 120 285 255
Rectangle -7500403 true true 15 180 270 255
Polygon -7500403 true true 0 180 300 180 240 135 60 135 0 180
Rectangle -16777216 true false 120 195 180 255
Line -7500403 true 150 195 150 255
Rectangle -16777216 true false 45 195 105 240
Rectangle -16777216 true false 195 195 255 240
Line -7500403 true 75 195 75 240
Line -7500403 true 225 195 225 240
Line -16777216 false 270 180 270 255
Line -16777216 false 0 180 300 180
house two story
false
0
Polygon -7500403 true true 2 180 227 180 152 150 32 150
Rectangle -7500403 true true 270 75 285 255
Rectangle -7500403 true true 75 135 270 255
Rectangle -16777216 true false 124 195 187 256
Rectangle -16777216 true false 210 195 255 240
Rectangle -16777216 true false 90 150 135 180
Rectangle -16777216 true false 210 150 255 180
Line -16777216 false 270 135 270 255
Rectangle -7500403 true true 15 180 75 255
Polygon -7500403 true true 60 135 285 135 240 90 105 90
Line -16777216 false 75 135 75 180
Rectangle -16777216 true false 30 195 93 240
Line -16777216 false 60 135 285 135
Line -16777216 false 255 105 285 135
Line -16777216 false 0 180 75 180
Line -7500403 true 60 195 60 240
Line -7500403 true 154 195 154 255
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
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
person business
false
0
Rectangle -1 true false 120 90 180 180
Polygon -13345367 true false 135 90 150 105 135 180 150 195 165 180 150 105 165 90
Polygon -7500403 true true 120 90 105 90 60 195 90 210 116 154 120 195 90 285 105 300 135 300 150 225 165 300 195 300 210 285 180 195 183 153 210 210 240 195 195 90 180 90 150 165
Circle -7500403 true true 110 5 80
Rectangle -7500403 true true 127 76 172 91
Line -16777216 false 172 90 161 94
Line -16777216 false 128 90 139 94
Polygon -13345367 true false 195 225 195 300 270 270 270 195
Rectangle -13791810 true false 180 225 195 300
Polygon -14835848 true false 180 226 195 226 270 196 255 196
Polygon -13345367 true false 209 202 209 216 244 202 243 188
Line -16777216 false 180 90 150 165
Line -16777216 false 120 90 150 165
person construction
false
0
Rectangle -7500403 true true 123 76 176 95
Polygon -1 true false 105 90 60 195 90 210 115 162 184 163 210 210 240 195 195 90
Polygon -13345367 true false 180 195 120 195 90 285 105 300 135 300 150 225 165 300 195 300 210 285
Circle -7500403 true true 110 5 80
Line -16777216 false 148 143 150 196
Rectangle -16777216 true false 116 186 182 198
Circle -1 true false 152 143 9
Circle -1 true false 152 166 9
Rectangle -16777216 true false 179 164 183 186
Polygon -955883 true false 180 90 195 90 195 165 195 195 150 195 150 120 180 90
Polygon -955883 true false 120 90 105 90 105 165 105 195 150 195 150 120 120 90
Rectangle -16777216 true false 135 114 150 120
Rectangle -16777216 true false 135 144 150 150
Rectangle -16777216 true false 135 174 150 180
Polygon -955883 true false 105 42 111 16 128 2 149 0 178 6 190 18 192 28 220 29 216 34 201 39 167 35
Polygon -6459832 true false 54 253 54 238 219 73 227 78
Polygon -16777216 true false 15 285 15 255 30 225 45 225 75 255 75 270 45 285
person doctor
false
0
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
Polygon -13345367 true false 135 90 150 105 135 135 150 150 165 135 150 105 165 90
Polygon -7500403 true true 105 90 60 195 90 210 135 105
Polygon -7500403 true true 195 90 240 195 210 210 165 105
Circle -7500403 true true 110 5 80
Rectangle -7500403 true true 127 79 172 94
Polygon -1 true false 105 90 60 195 90 210 114 156 120 195 90 270 210 270 180 195 186 155 210 210 240 195 195 90 165 90 150 150 135 90
Line -16777216 false 150 148 150 270
Line -16777216 false 196 90 151 149
Line -16777216 false 104 90 149 149
Circle -1 true false 180 0 30
Line -16777216 false 180 15 120 15
Line -16777216 false 150 195 165 195
Line -16777216 false 150 240 165 240
Line -16777216 false 150 150 165 150
person farmer
false
0
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
Polygon -1 true false 60 195 90 210 114 154 120 195 180 195 187 157 210 210 240 195 195 90 165 90 150 105 150 150 135 90 105 90
Circle -7500403 true true 110 5 80
Rectangle -7500403 true true 127 79 172 94
Polygon -13345367 true false 120 90 120 180 120 195 90 285 105 300 135 300 150 225 165 300 195 300 210 285 180 195 180 90 172 89 165 135 135 135 127 90
Polygon -6459832 true false 116 4 113 21 71 33 71 40 109 48 117 34 144 27 180 26 188 36 224 23 222 14 178 16 167 0
Line -16777216 false 225 90 270 90
Line -16777216 false 225 15 225 90
Line -16777216 false 270 15 270 90
Line -16777216 false 247 15 247 90
Rectangle -6459832 true false 240 90 255 300
person graduate
false
0
Circle -16777216 false false 39 183 20
Polygon -1 true false 50 203 85 213 118 227 119 207 89 204 52 185
Circle -7500403 true true 110 5 80
Rectangle -7500403 true true 127 79 172 94
Polygon -8630108 true false 90 19 150 37 210 19 195 4 105 4
Polygon -8630108 true false 120 90 105 90 60 195 90 210 120 165 90 285 105 300 195 300 210 285 180 165 210 210 240 195 195 90
Polygon -1184463 true false 135 90 120 90 150 135 180 90 165 90 150 105
Line -2674135 false 195 90 150 135
Line -2674135 false 105 90 150 135
Polygon -1 true false 135 90 150 105 165 90
Circle -1 true false 104 205 20
Circle -1 true false 41 184 20
Circle -16777216 false false 106 206 18
Line -2674135 false 208 22 208 57
person lumberjack
false
0
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
Polygon -2674135 true false 60 196 90 211 114 155 120 196 180 196 187 158 210 211 240 196 195 91 165 91 150 106 150 135 135 91 105 91
Circle -7500403 true true 110 5 80
Rectangle -7500403 true true 127 79 172 94
Polygon -6459832 true false 174 90 181 90 180 195 165 195
Polygon -13345367 true false 180 195 120 195 90 285 105 300 135 300 150 225 165 300 195 300 210 285
Polygon -6459832 true false 126 90 119 90 120 195 135 195
Rectangle -6459832 true false 45 180 255 195
Polygon -16777216 true false 255 165 255 195 240 225 255 240 285 240 300 225 285 195 285 165
Line -16777216 false 135 165 165 165
Line -16777216 false 135 135 165 135
Line -16777216 false 90 135 120 135
Line -16777216 false 105 120 120 120
Line -16777216 false 180 120 195 120
Line -16777216 false 180 135 210 135
Line -16777216 false 90 150 105 165
Line -16777216 false 225 165 210 180
Line -16777216 false 75 165 90 180
Line -16777216 false 210 150 195 165
Line -16777216 false 180 105 210 180
Line -16777216 false 120 105 90 180
Line -16777216 false 150 135 150 165
Polygon -2674135 true false 100 30 104 44 189 24 185 10 173 10 166 1 138 -1 111 3 109 28
person police
false
0
Polygon -1 true false 124 91 150 165 178 91
Polygon -13345367 true false 134 91 149 106 134 181 149 196 164 181 149 106 164 91
Polygon -13345367 true false 180 195 120 195 90 285 105 300 135 300 150 225 165 300 195 300 210 285
Polygon -13345367 true false 120 90 105 90 60 195 90 210 116 158 120 195 180 195 184 158 210 210 240 195 195 90 180 90 165 105 150 165 135 105 120 90
Rectangle -7500403 true true 123 76 176 92
Circle -7500403 true true 110 5 80
Polygon -13345367 true false 150 26 110 41 97 29 137 -1 158 6 185 0 201 6 196 23 204 34 180 33
Line -13345367 false 121 90 194 90
Line -16777216 false 148 143 150 196
Rectangle -16777216 true false 116 186 182 198
Rectangle -16777216 true false 109 183 124 227
Rectangle -16777216 true false 176 183 195 205
Circle -1 true false 152 143 9
Circle -1 true false 152 166 9
Polygon -1184463 true false 172 112 191 112 185 133 179 133
Polygon -1184463 true false 175 6 194 6 189 21 180 21
Line -1184463 false 149 24 197 24
Rectangle -16777216 true false 101 177 122 187
Rectangle -16777216 true false 179 164 183 186
person service
false
0
Polygon -7500403 true true 180 195 120 195 90 285 105 300 135 300 150 225 165 300 195 300 210 285
Polygon -1 true false 120 90 105 90 60 195 90 210 120 150 120 195 180 195 180 150 210 210 240 195 195 90 180 90 165 105 150 165 135 105 120 90
Polygon -1 true false 123 90 149 141 177 90
Rectangle -7500403 true true 123 76 176 92
Circle -7500403 true true 110 5 80
Line -13345367 false 121 90 194 90
Line -16777216 false 148 143 150 196
Rectangle -16777216 true false 116 186 182 198
Circle -1 true false 152 143 9
Circle -1 true false 152 166 9
Rectangle -16777216 true false 179 164 183 186
Polygon -2674135 true false 180 90 195 90 183 160 180 195 150 195 150 135 180 90
Polygon -2674135 true false 120 90 105 90 114 161 120 195 150 195 150 135 120 90
Polygon -2674135 true false 155 91 128 77 128 101
Rectangle -16777216 true false 118 129 141 140
Polygon -2674135 true false 145 91 172 77 172 101
person soldier
false
0
Rectangle -7500403 true true 127 79 172 94
Polygon -10899396 true false 105 90 60 195 90 210 135 105
Polygon -10899396 true false 195 90 240 195 210 210 165 105
Circle -7500403 true true 110 5 80
Polygon -10899396 true false 105 90 120 195 90 285 105 300 135 300 150 225 165 300 195 300 210 285 180 195 195 90
Polygon -6459832 true false 120 90 105 90 180 195 180 165
Line -6459832 false 109 105 139 105
Line -6459832 false 122 125 151 117
Line -6459832 false 137 143 159 134
Line -6459832 false 158 179 181 158
Line -6459832 false 146 160 169 146
Rectangle -6459832 true false 120 193 180 201
Polygon -6459832 true false 122 4 107 16 102 39 105 53 148 34 192 27 189 17 172 2 145 0
Polygon -16777216 true false 183 90 240 15 247 22 193 90
Rectangle -6459832 true false 114 187 128 208
Rectangle -6459832 true false 177 187 191 208
person student
false
0
Polygon -13791810 true false 135 90 150 105 135 165 150 180 165 165 150 105 165 90
Polygon -7500403 true true 195 90 240 195 210 210 165 105
Circle -7500403 true true 110 5 80
Rectangle -7500403 true true 127 79 172 94
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
Polygon -1 true false 100 210 130 225 145 165 85 135 63 189
Polygon -13791810 true false 90 210 120 225 135 165 67 130 53 189
Polygon -1 true false 120 224 131 225 124 210
Line -16777216 false 139 168 126 225
Line -16777216 false 140 167 76 136
Polygon -7500403 true true 105 90 60 195 90 210 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
train passenger car
false
0
Polygon -7500403 true true 15 206 15 150 15 135 30 120 270 120 285 135 285 150 285 206 270 210 30 210
Circle -16777216 true false 240 195 30
Circle -16777216 true false 210 195 30
Circle -16777216 true false 60 195 30
Circle -16777216 true false 30 195 30
Rectangle -16777216 true false 30 140 268 165
Line -7500403 true 60 135 60 165
Line -7500403 true 60 135 60 165
Line -7500403 true 90 135 90 165
Line -7500403 true 120 135 120 165
Line -7500403 true 150 135 150 165
Line -7500403 true 180 135 180 165
Line -7500403 true 210 135 210 165
Line -7500403 true 240 135 240 165
Rectangle -16777216 true false 5 195 19 207
Rectangle -16777216 true false 281 195 295 207
Rectangle -13345367 true false 15 165 285 173
Rectangle -2674135 true false 15 180 285 188
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 6.1.1
@#$#@#$#@
setup
display-cities
display-countries
@#$#@#$#@
@#$#@#$#@
@#$#@#$#@
@#$#@#$#@
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 | hubahuuduwu/abm-workshop | 2020_Training_series_materials/Tram_Commute_Model/TramCommute.nlogo | [
"MIT"
] |
ruleset sample {
meta {
name "Hello World"
description <<
Hello world
>>
author "Phil Windley"
}
// just one rule
rule hello {
select when web pageview
notify("Hello world!", "Just a note to say hello");
}
}
| KRL | 4 | JavascriptID/sourcerer-app | src/test/resources/samples/langs/KRL/helloworld.krl | [
"MIT"
] |
##############################################################################
# PM2
##############################################################################
# Start commands
pm2 start <file> # Start an application
pm2 start <app_id> # Start a stopped application
pm2 start <app_id> ecosystem.config.js # Start an app with the configuration in ecosystem file
pm2 start <file> -i <number_of_instances> # Start an app in cluster mode with n duplicated instances
# Management commands
pm2 ls # List all processes
pm2 save # Save process list to respawn at reboot
pm2 restart <app_id> # Restart an app by ID
pm2 reload <app_id> # Reload an app by ID
pm2 stop <app_id> # Stop an app by ID
pm2 stop all # Stop all running instances
pm2 delete <app_id> # Delete an app by ID
pm2 delete all # Delete all instances
pm2 ecosystem # Generate a sample ecosystem.config.js file
# Monitoring
pm2 show <app_id> # Show a specific app's description
pm2 logs <app_id> --lines=<number_of_lines> # Show the last n lines of logs of an app
pm2 env <app_id> # Show all environment variables of an app
pm2 monit # Monitor all applications' logs, metrics,etc
| Shell | 4 | imdex1009/awesome-cheatsheets | tools/pm2.sh | [
"MIT"
] |
# culture="de-DE"
ConvertFrom-StringData @'
messageDate = Today is
d0 = Sunday (in German)
d1 = Monday (in German)
d2 = Tuesday (in German)
d3 = Wednesday (in German)
d4 = Thursday (in German)
d5 = Friday (in German)
d6 = Saturday (in German)
'@
| PowerShell | 4 | Jellyfrog/PowerShell | test/powershell/Modules/Microsoft.PowerShell.Utility/assets/de-DE/localized.psd1 | [
"MIT"
] |
-- Copyright 2018 Stanford University
--
-- 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.
import "regent"
local c = regentlib.c
fspace BitField
{
bit : bool,
}
-- This example moves the initialization and printing of the region into tasks.
--
-- Tasks that use regions must declare their privileges on the region's fields, which describe
-- how the task will use each field. The clear task just writes to the bit field of the region.
-- Privileges are type checked by the Regent compiler: the task body and any subtasks called by the
-- task can only use the declared privileges.
--
-- Note the ttype of the region includes the types of the index and field spaces.
--
task clear(bit_region : region(ispace(int1d), BitField))
where
writes(bit_region.bit)
do
for b in bit_region do
b.bit = false
end
end
--
-- The printer task reads the bit field of the region.
--
task printer(bit_region : region(ispace(int1d), BitField))
where
reads(bit_region.bit)
do
c.printf("The bits are: ")
var limits = bit_region.bounds
for i = [int](limits.lo), [int](limits.hi) + 1 do
if bit_region[i].bit then
c.printf("1 ")
else
c.printf("0 ")
end
end
c.printf("\n")
end
task main()
var size = 10
var bit_region = region(ispace(int1d, size), BitField)
clear(bit_region)
printer(bit_region)
end
regentlib.start(main)
| Rouge | 5 | elliottslaughter/regent-tutorial | Regions/2.rg | [
"Apache-2.0"
] |
//
// MatOfKeyPoint.m
//
// Created by Giles Payne on 2019/12/27.
//
#import "MatOfKeyPoint.h"
#import "Range.h"
#import "Point2f.h"
#import "KeyPoint.h"
#import "CvType.h"
#import "ArrayUtil.h"
@implementation MatOfKeyPoint
static const int _depth = CV_32F;
static const int _channels = 7;
#ifdef __cplusplus
- (instancetype)initWithNativeMat:(cv::Mat*)nativeMat {
self = [super initWithNativeMat:nativeMat];
if (self && ![self empty] && [self checkVector:_channels depth:_depth] < 0) {
@throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"Incompatible Mat" userInfo:nil];
}
return self;
}
#endif
- (instancetype)initWithMat:(Mat*)mat {
self = [super initWithMat:mat rowRange:[Range all]];
if (self && ![self empty] && [self checkVector:_channels depth:_depth] < 0) {
@throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"Incompatible Mat" userInfo:nil];
}
return self;
}
- (instancetype)initWithArray:(NSArray<KeyPoint*>*)array {
self = [super init];
if (self) {
[self fromArray:array];
}
return self;
}
- (void)alloc:(int)elemNumber {
if (elemNumber>0) {
[super create:elemNumber cols:1 type:[CvType makeType:_depth channels:_channels]];
}
}
- (void)fromArray:(NSArray<KeyPoint*>*)array {
NSMutableArray<NSNumber*>* data = [[NSMutableArray alloc] initWithCapacity:array.count * _channels];
for (int index = 0; index < (int)array.count; index++) {
data[_channels * index] = [NSNumber numberWithFloat:array[index].pt.x];
data[_channels * index + 1] = [NSNumber numberWithFloat:array[index].pt.y];
data[_channels * index + 2] = [NSNumber numberWithFloat:array[index].size];
data[_channels * index + 3] = [NSNumber numberWithFloat:array[index].angle];
data[_channels * index + 4] = [NSNumber numberWithFloat:array[index].response];
data[_channels * index + 5] = [NSNumber numberWithFloat:array[index].octave];
data[_channels * index + 6] = [NSNumber numberWithFloat:array[index].classId];
}
[self alloc:(int)array.count];
[self put:0 col:0 data:data];
}
- (NSArray<KeyPoint*>*)toArray {
int length = [self length] / _channels;
NSMutableArray<KeyPoint*>* ret = createArrayWithSize(length, [KeyPoint new]);
if (length > 0) {
NSMutableArray<NSNumber*>* data = createArrayWithSize([self length], @0.0);
[self get:0 col:0 data:data];
for (int index = 0; index < length; index++) {
ret[index] = [[KeyPoint alloc] initWithX:data[index * _channels].floatValue y:data[index * _channels + 1].floatValue size:data[index * _channels + 2].floatValue angle:data[index * _channels + 3].floatValue response:data[index * _channels + 4].floatValue octave:data[index * _channels + 5].intValue classId:data[index * _channels + 6].intValue];
}
}
return ret;
}
- (int)length {
int num = [self checkVector:_channels depth:_depth];
if (num < 0) {
@throw [NSException exceptionWithName:NSInternalInconsistencyException reason:@"Incompatible Mat" userInfo:nil];
}
return num * _channels;
}
@end
| Objective-C++ | 3 | artun3e/opencv | modules/core/misc/objc/common/MatOfKeyPoint.mm | [
"BSD-3-Clause"
] |
[[howto.hotswapping]]
== Hot Swapping
Spring Boot supports hot swapping.
This section answers questions about how it works.
[[howto.hotswapping.reload-static-content]]
=== Reload Static Content
There are several options for hot reloading.
The recommended approach is to use <<using#using.devtools,`spring-boot-devtools`>>, as it provides additional development-time features, such as support for fast application restarts and LiveReload as well as sensible development-time configuration (such as template caching).
Devtools works by monitoring the classpath for changes.
This means that static resource changes must be "built" for the change to take effect.
By default, this happens automatically in Eclipse when you save your changes.
In IntelliJ IDEA, the Make Project command triggers the necessary build.
Due to the <<using#using.devtools.restart.excluding-resources, default restart exclusions>>, changes to static resources do not trigger a restart of your application.
They do, however, trigger a live reload.
Alternatively, running in an IDE (especially with debugging on) is a good way to do development (all modern IDEs allow reloading of static resources and usually also allow hot-swapping of Java class changes).
Finally, the <<build-tool-plugins#build-tool-plugins, Maven and Gradle plugins>> can be configured (see the `addResources` property) to support running from the command line with reloading of static files directly from source.
You can use that with an external css/js compiler process if you are writing that code with higher-level tools.
[[howto.hotswapping.reload-templates]]
=== Reload Templates without Restarting the Container
Most of the templating technologies supported by Spring Boot include a configuration option to disable caching (described later in this document).
If you use the `spring-boot-devtools` module, these properties are <<using#using.devtools.property-defaults,automatically configured>> for you at development time.
[[howto.hotswapping.reload-templates.freemarker]]
==== FreeMarker Templates
If you use FreeMarker, set `spring.freemarker.cache` to `false`.
See {spring-boot-autoconfigure-module-code}/freemarker/FreeMarkerAutoConfiguration.java[`FreeMarkerAutoConfiguration`] for other FreeMarker customization options.
[[howto.hotswapping.reload-templates.groovy]]
==== Groovy Templates
If you use Groovy templates, set `spring.groovy.template.cache` to `false`.
See {spring-boot-autoconfigure-module-code}/groovy/template/GroovyTemplateAutoConfiguration.java[`GroovyTemplateAutoConfiguration`] for other Groovy customization options.
[[howto.hotswapping.fast-application-restarts]]
=== Fast Application Restarts
The `spring-boot-devtools` module includes support for automatic application restarts.
While not as fast as technologies such as https://www.jrebel.com/products/jrebel[JRebel] it is usually significantly faster than a "`cold start`".
You should probably give it a try before investigating some of the more complex reload options discussed later in this document.
For more details, see the <<using#using.devtools>> section.
[[howto.hotswapping.reload-java-classes-without-restarting]]
=== Reload Java Classes without Restarting the Container
Many modern IDEs (Eclipse, IDEA, and others) support hot swapping of bytecode.
Consequently, if you make a change that does not affect class or method signatures, it should reload cleanly with no side effects.
| AsciiDoc | 4 | Cuiqingqiang/spring-boot | spring-boot-project/spring-boot-docs/src/docs/asciidoc/howto/hotswapping.adoc | [
"Apache-2.0"
] |
--TEST--
Bug #46843 (CP936 euro symbol is not converted properly)
--EXTENSIONS--
mbstring
--FILE--
<?php
var_dump(bin2hex(mb_convert_encoding("\x80", 'UCS-2BE', 'CP936')));
var_dump(bin2hex(mb_convert_encoding("\x20\xac", 'CP936', 'UCS-2BE')));
?>
--EXPECT--
string(4) "20ac"
string(2) "80"
| PHP | 3 | NathanFreeman/php-src | ext/mbstring/tests/bug46843.phpt | [
"PHP-3.01"
] |
;; -*- lexical-binding: t; no-byte-compile: t; -*-
;;; lang/crystal/doctor.el
(unless (executable-find "icr")
(warn! "Couldn't find icr. REPL will not work"))
| Emacs Lisp | 3 | leezu/doom-emacs | modules/lang/crystal/doctor.el | [
"MIT"
] |
Fix rendering in macOS BigSur
See: https://bugreports.qt.io/browse/QTBUG-86513.
Upstream commits (combined in this patch):
- Qt 6.0: 40fb97e97f550b8afd13ecc3a038d9d0c2d82bbb
- Qt 6.0: 3857f104cac127f62e64e55a20613f0ac2e6b843
- Qt 6.1: abee4cdd5925a8513f51784754fca8fa35031732
--- old/qtbase/src/plugins/styles/mac/qmacstyle_mac.mm
+++ new/qtbase/src/plugins/styles/mac/qmacstyle_mac.mm
@@ -3870,6 +3870,7 @@ void QMacStyle::drawControl(ControlElement ce, const QStyleOption *opt, QPainter
const auto cs = d->effectiveAquaSizeConstrain(opt, w);
// Extra hacks to get the proper pressed appreance when not selected or selected and inactive
const bool needsInactiveHack = (!isActive && isSelected);
+ const bool isBigSurOrAbove = QOperatingSystemVersion::current() >= QOperatingSystemVersion::MacOSBigSur;
const auto ct = !needsInactiveHack && (isSelected || tp == QStyleOptionTab::OnlyOneTab) ?
QMacStylePrivate::Button_PushButton :
QMacStylePrivate::Button_PopupButton;
@@ -3878,6 +3879,12 @@ void QMacStyle::drawControl(ControlElement ce, const QStyleOption *opt, QPainter
auto *pb = static_cast<NSButton *>(d->cocoaControl(cw));
auto vOffset = isPopupButton ? 1 : 2;
+ if (isBigSurOrAbove) {
+ // Make it 1, otherwise, offset is very visible compared
+ // to selected tab (which is not a popup button).
+ vOffset = 1;
+ }
+
if (tabDirection == QMacStylePrivate::East)
vOffset -= 1;
const auto outerAdjust = isPopupButton ? 1 : 4;
@@ -3894,9 +3901,22 @@ void QMacStyle::drawControl(ControlElement ce, const QStyleOption *opt, QPainter
frameRect = frameRect.adjusted(-innerAdjust, 0, outerAdjust, 0);
else
frameRect = frameRect.adjusted(-outerAdjust, 0, innerAdjust, 0);
+
+ if (isSelected && isBigSurOrAbove) {
+ // 1 pixed of 'roundness' is still visible on the right
+ // (the left is OK, it's rounded).
+ frameRect = frameRect.adjusted(0, 0, 1, 0);
+ }
+
break;
case QStyleOptionTab::Middle:
frameRect = frameRect.adjusted(-innerAdjust, 0, innerAdjust, 0);
+
+ if (isSelected && isBigSurOrAbove) {
+ // 1 pixel of 'roundness' is still visible on both
+ // sides - left and right.
+ frameRect = frameRect.adjusted(-1, 0, 1, 0);
+ }
break;
case QStyleOptionTab::End:
// Pressed state hack: tweak adjustments in preparation for flip below
@@ -3904,6 +3924,11 @@ void QMacStyle::drawControl(ControlElement ce, const QStyleOption *opt, QPainter
frameRect = frameRect.adjusted(-innerAdjust, 0, outerAdjust, 0);
else
frameRect = frameRect.adjusted(-outerAdjust, 0, innerAdjust, 0);
+
+ if (isSelected && isBigSurOrAbove) {
+ // 1 pixel of 'roundness' is still visible on the left.
+ frameRect = frameRect.adjusted(-1, 0, 0, 0);
+ }
break;
case QStyleOptionTab::OnlyOneTab:
frameRect = frameRect.adjusted(-outerAdjust, 0, outerAdjust, 0);
@@ -3951,7 +3976,10 @@ void QMacStyle::drawControl(ControlElement ce, const QStyleOption *opt, QPainter
NSPopUpArrowPosition oldPosition = NSPopUpArrowAtCenter;
NSPopUpButtonCell *pbCell = nil;
auto rAdjusted = r;
- if (isPopupButton && tp == QStyleOptionTab::OnlyOneTab) {
+ if (isPopupButton && (tp == QStyleOptionTab::OnlyOneTab || isBigSurOrAbove)) {
+ // Note: starting from macOS BigSur NSPopupButton has this
+ // arrow 'button' in a different place and it became
+ // quite visible 'in between' inactive tabs.
pbCell = static_cast<NSPopUpButtonCell *>(pb.cell);
oldPosition = pbCell.arrowPosition;
pbCell.arrowPosition = NSPopUpNoArrow;
@@ -3959,6 +3987,10 @@ void QMacStyle::drawControl(ControlElement ce, const QStyleOption *opt, QPainter
// NSPopUpButton in this state is smaller.
rAdjusted.origin.x -= 3;
rAdjusted.size.width += 6;
+ if (isBigSurOrAbove) {
+ if (tp == QStyleOptionTab::End)
+ rAdjusted.origin.x -= 2;
+ }
}
}
| Diff | 4 | apokalyzr/bitcoin | depends/patches/qt/fix_bigsur_style.patch | [
"MIT"
] |
var $g ptr
var $h i32
func $multiwayfunc ( var %p ptr) ptr {
multiway (dread ptr %p) @labdft {
(dread ptr $g): goto @lab1
(add ptr (dread i32 $g, dread i32 $h)): goto @lab0
(conststr ptr "world"): goto @lab9 }
@lab0
return (dread ptr $g)
@labdft
return (conststr ptr "hello")
@lab9
return (add ptr (conststr ptr "foo", dread i32 $h))
@lab1
return (addrof ptr $h) }
# EXEC: %irbuild Main.mpl
# EXEC: %irbuild Main.irb.mpl
# EXEC: %cmp Main.irb.mpl Main.irb.irb.mpl
| Maple | 3 | harmonyos-mirror/OpenArkCompiler-test | test/testsuite/irbuild_test/I0058-mapleall-irbuild-edge-multiwaystr/Main.mpl | [
"MulanPSL-1.0"
] |
#!/bin/csh
#This script can be used to generate a web page to compare histograms from
#two input root files produced using the EDAnalyzers in RecoEgamma/Examples,
#by running one of:
#
#
#
# "Validation/RecoEgamma/test/PhotonValidator_cfg.py
#
# The default list of histograms (configurable) is based on version VXX-XX-XX
# of Validation/RecoEgamma
#
#Two files are created by this script: validation.C and validation.html.
#validation.C should be run inside root to greate a set of gif images
#which can then be viewed in a web browser using validation.html.
#=============BEGIN CONFIGURATION=================
setenv TYPE Photons
setenv RUNTYPE Central
setenv STARTUP True
setenv CMSSWver1 4_2_0
setenv CMSSWver2 4_2_2
setenv OLDRELEASE 4_2_0
setenv NEWRELEASE 4_2_2
setenv OLDPRERELEASE
setenv NEWPRERELEASE
if ( $STARTUP == True) then
setenv OLDGLOBALTAG START42_V9-v1
setenv NEWGLOBALTAG START42_V11-v1
else
setenv OLDGLOBALTAG MC_42_V9-v1
setenv NEWGLOBALTAG MC_42_V11-v1
endif
#setenv OLDRELEASE ${OLDRELEASE}_${OLDPRERELEASE}
setenv OLDRELEASE ${OLDRELEASE}
#setenv NEWRELEASE ${NEWRELEASE}_${NEWPRERELEASE}
setenv NEWRELEASE ${NEWRELEASE}
#setenv WorkDir1 /afs/cern.ch/user/n/nancy/scratch0/CMSSW/test/CMSSW_${CMSSWver1}/src/Validation/RecoEgamma/test
#setenv WorkDir2 /afs/cern.ch/user/n/nancy/scratch0/CMSSW/test/CMSSW_${CMSSWver2}_${NEWPRERELEASE}/src/Validation/RecoEgamma/test
#setenv WorkDir1 /afs/cern.ch/user/n/nancy/scratch0/CMSSW/test/CMSSW_${CMSSWver1}_${OLDPRERELEASE}/src/Validation/RecoEgamma/test
#setenv WorkDir2 /afs/cern.ch/user/n/nancy/scratch0/CMSSW/test/CMSSW_${CMSSWver2}_${NEWPRERELEASE}/src/Validation/RecoEgamma/test
#setenv WorkDir1 /afs/cern.ch/user/n/nancy/scratch0/CMSSW/test/CMSSW_${CMSSWver1}_${OLDPRERELEASE}/src/Validation/RecoEgamma/test
#setenv WorkDir2 /afs/cern.ch/user/n/nancy/scratch0/CMSSW/test/CMSSW_${CMSSWver2}/src/Validation/RecoEgamma/test
setenv WorkDir1 /afs/cern.ch/user/n/nancy/scratch0/CMSSW/test/CMSSW_${CMSSWver1}/src/Validation/RecoEgamma/test
setenv WorkDir2 /afs/cern.ch/user/n/nancy/scratch0/CMSSW/test/CMSSW_${CMSSWver2}/src/Validation/RecoEgamma/test
#Name of sample (affects output directory name and htmldescription only)
setenv SAMPLE QCD_Pt_80_120STARTUP
#setenv SAMPLE QCD_Pt_20_30STARTUP
if ( $RUNTYPE == Central ) then
setenv HISTOPATHNAME_Efficiencies DQMData/Run\ 1/EgammaV/Run\ summary/PhotonValidator/Efficiencies
setenv HISTOPATHNAME_Photons DQMData/Run\ 1/EgammaV/Run\ summary/PhotonValidator/Photons
setenv HISTOPATHNAME_Conversions DQMData/Run\ 1/EgammaV/Run\ summary/PhotonValidator/ConversionInfo
setenv HISTOPATHNAME_Background DQMData/Run\ 1/EgammaV/Run\ summary/PhotonValidator/Background
endif
if ( $RUNTYPE == Local ) then
setenv HISTOPATHNAME_Efficiencies DQMData/EgammaV/PhotonValidator/Efficiencies
setenv HISTOPATHNAME_Photons DQMData/EgammaV/PhotonValidator/Photons
setenv HISTOPATHNAME_Conversions DQMData/EgammaV/PhotonValidator/ConversionInfo
setenv HISTOPATHNAME_Background DQMData/EgammaV/PhotonValidator/Background
endif
#==============END BASIC CONFIGURATION==================
#Input root trees for the two cases to be compared
if ($SAMPLE == QCD_Pt_20_30STARTUP) then
setenv OLDFILE ${WorkDir1}/PhotonValidationRelVal${OLDRELEASE}_QCD_Pt_20_30.root
setenv NEWFILE ${WorkDir2}/PhotonValidationRelVal${NEWRELEASE}_QCD_Pt_20_30.root
else if ($SAMPLE == QCD_Pt_80_120STARTUP) then
if ( $RUNTYPE == Local ) then
setenv OLDFILE ${WorkDir1}/PhotonValidationRelVal${OLDRELEASE}_QCD_Pt_80_120.root
setenv NEWFILE ${WorkDir2}/PhotonValidationRelVal${NEWRELEASE}_QCD_Pt_80_120.root
else if ( $RUNTYPE == Central ) then
setenv OLDFILE ${WorkDir1}/DQM_V0003_R000000001__RelValQCD_Pt_80_120__CMSSW_${OLDRELEASE}-${OLDGLOBALTAG}__DQM.root
setenv NEWFILE ${WorkDir2}/DQM_V0001_R000000001__RelValQCD_Pt_80_120__CMSSW_${NEWRELEASE}-${NEWGLOBALTAG}__DQM.root
endif
#Location of output. The default will put your output in:
#http://cmsdoc.cern.ch/Physics/egamma/www/validation/
setenv CURRENTDIR $PWD
setenv OUTPATH /afs/cern.ch/cms/Physics/egamma/www/validation
cd $OUTPATH
if (! -d $NEWRELEASE) then
mkdir $NEWRELEASE
endif
setenv OUTPATH $OUTPATH/$NEWRELEASE
cd $OUTPATH
if (! -d ${TYPE}) then
mkdir ${TYPE}
endif
setenv OUTPATH $OUTPATH/${TYPE}
cd $OUTPATH
if (! -d vs${OLDRELEASE}) then
mkdir vs${OLDRELEASE}
endif
setenv OUTPATH $OUTPATH/vs${OLDRELEASE}
setenv OUTDIR $OUTPATH/${SAMPLE}
if (! -d $OUTDIR) then
cd $OUTPATH
mkdir $OUTDIR
cd $OUTDIR
mkdir gifs
endif
cd $OUTDIR
#The list of histograms to be compared for each TYPE can be configured below:
if ( $TYPE == Photons ) then
cat > efficiencyForBkg <<EOF
bkgEffVsEta
bkgEffVsPhi
bkgEffVsEt
deadChVsEtaBkg
deadChVsPhiBkg
deadChVsEtBkg
EOF
cat > scaledhistosForBkg <<EOF
nOfPhotons
scBkgEta
scBkgPhi
scBkgEAll
scBkgEtAll
phoBkgEta
phoBkgPhi
phoBkgEAll
phoBkgEtAll
phoBkgDEta
phoBkgDPhi
isoTrkSolidConeDR04BkgBarrel
isoTrkSolidConeDR04BkgEndcap
nTrkSolidConeDR04BkgBarrel
nTrkSolidConeDR04BkgEndcap
convEtaBkg
convPhiBkg
PoverEtracksBkgAll
PoverEtracksBkgBarrel
PoverEtracksBkgEndcap
mvaOutBkgAll
mvaOutBkgBarrel
mvaOutBkgEndcap
hDPhiTracksAtVtxBkgAll
hDCotTracksBkgAll
EOF
cat > scaledhistosForBkgLogScale <<EOF
hOverEBkgAll
hOverEBkgBarrel
hOverEBkgEndcap
hcalTowerSumEtConeDR04BkgBarrel
hcalTowerSumEtConeDR04BkgEndcap
EoverPtracksBkgAll
EoverPtracksBkgBarrel
EoverPtracksBkgEndcap
r9BkgBarrel
r9BkgEndcap
r1BkgBarrel
r1BkgEndcap
r2BkgBarrel
r2BkgEndcap
sigmaIetaIetaBkgBarrel
sigmaIetaIetaBkgEndcap
ecalRecHitSumEtConeDR04BkgBarrel
ecalRecHitSumEtConeDR04BkgEndcap
EOF
cat > unscaledhistosForBkg <<EOF
pR1VsEtaBkgAll
pR2VsEtaBkgAll
pR1VsEtBkgAll
pR2VsEtBkgAll
pSigmaIetaIetaVsEtaBkgAll
pSigmaIetaIetaVsEtBkgAll
pHOverEVsEtaBkgAll
pHOverEVsEtBkgAll
pEcalRecHitSumEtConeDR04VsEtBkgBarrel
pEcalRecHitSumEtConeDR04VsEtBkgEndcap
pEcalRecHitSumEtConeDR04VsEtaBkgAll
pHcalTowerSumEtConeDR04VsEtBkgBarrel
pHcalTowerSumEtConeDR04VsEtBkgEndcap
pHcalTowerSumEtConeDR04VsEtaBkgAll
pIsoTrkSolidConeDR04VsEtBkgBarrel
pIsoTrkSolidConeDR04VsEtBkgEndcap
pIsoTrkSolidConeDR04VsEtaBkgAll
pnTrkSolidConeDR04VsEtBkgBarrel
pnTrkSolidConeDR04VsEtBkgEndcap
p_nTrkSolidConeDR04VsEtaBkgAll
EOF
cat > 2DhistosForBkg <<EOF
R9VsEtaBkgAll
R9VsEtBkgAll
hOverEVsEtaBkgAll
hOverEVsEtBkgAll
EOF
endif
#=================END CONFIGURATION=====================
if (-e validation.C) rm validation.C
touch validation.C
cat > begin.C <<EOF
{
TFile *file_old = TFile::Open("$OLDFILE");
TFile *file_new = TFile::Open("$NEWFILE");
EOF
cat begin.C >>& validation.C
rm begin.C
setenv N 1
foreach i (`cat efficiencyForBkg`)
cat > temp$N.C <<EOF
TCanvas *c$i = new TCanvas("c$i");
c$i->SetFillColor(10);
//file_old->cd("DQMData/EgammaV/PhotonValidator/Efficiencies");
file_old->cd("$HISTOPATHNAME_Efficiencies");
$i->SetStats(0);
if ( $i==deadChVsEtaBkg || $i==deadChVsPhiBkg || $i==deadChVsEtBkg ) {
$i->GetYaxis()->SetRangeUser(0.,0.2);
}else if ( $i==bkgEffVsEta || $i==bkgEffVsPhi ) {
$i->GetYaxis()->SetRangeUser(0.,0.4);
}else if ( $i==bkgEffVsEt ) {
$i->GetYaxis()->SetRangeUser(0.,1.);
} else {
$i->GetYaxis()->SetRangeUser(0.,1.1);
}
$i->SetLineColor(kPink+8);
$i->SetMarkerColor(kPink+8);
$i->SetMarkerStyle(20);
$i->SetMarkerSize(1);
$i->SetLineWidth(1);
$i->Draw("e1");
//file_new->cd("DQMData/EgammaV/PhotonValidator/Efficiencies");
file_new->cd("$HISTOPATHNAME_Efficiencies");
$i->SetStats(0);
$i->SetMinimum(0.);
$i->SetMaximum(1.1);
$i->SetLineColor(kBlack);
$i->SetMarkerColor(kBlack);
$i->SetMarkerStyle(20);
$i->SetMarkerSize(1);
$i->SetLineWidth(1);
$i->Draw("e1same");
c$i->SaveAs("gifs/$i.gif");
EOF
setenv N `expr $N + 1`
end
foreach i (`cat scaledhistosForBkg`)
cat > temp$N.C <<EOF
TCanvas *c$i = new TCanvas("c$i");
c$i->SetFillColor(10);
//file_new->cd("DQMData/EgammaV/PhotonValidator/Background");
file_new->cd("$HISTOPATHNAME_Background");
Double_t mnew=$i->GetMaximum();
Double_t nnew=$i->GetEntries();
//file_old->cd("DQMData/EgammaV/PhotonValidator/Background");
file_old->cd("$HISTOPATHNAME_Background");
Double_t mold=$i->GetMaximum();
Double_t nold=$i->GetEntries();
$i->SetStats(0);
$i->SetMinimum(0.);
//if ( mnew > mold)
// $i->SetMaximum(mnew+mnew*0.2);
//else
//$i->SetMaximum(mold+mold*0.2);
//$i->SetMaximum(mold+mold*0.2);
$i->SetLineColor(kPink+8);
$i->SetFillColor(kPink+8);
//$i->SetLineWidth(3);
$i->Draw();
//file_new->cd("DQMData/EgammaV/PhotonValidator/Background");
file_new->cd("$HISTOPATHNAME_Background");
Double_t nnew=$i->GetEntries();
$i->SetStats(0);
$i->SetLineColor(kBlack);
$i->SetMarkerColor(kBlack);
$i->SetMarkerStyle(20);
$i->SetMarkerSize(1);
//$i->SetLineWidth(1);
$i->Scale(nold/nnew);
$i->Draw("e1same");
c$i->SaveAs("gifs/$i.gif");
EOF
setenv N `expr $N + 1`
end
foreach i (`cat unscaledhistosForBkg`)
cat > temp$N.C <<EOF
TCanvas *c$i = new TCanvas("c$i");
c$i->SetFillColor(10);
//file_old->cd("DQMData/EgammaV/PhotonValidator/Background");
file_old->cd("$HISTOPATHNAME_Background");
$i->SetStats(0);
if ( $i==pEcalRecHitSumEtConeDR04VsEtaBkgAll || $i==pHcalTowerSumEtConeDR04VsEtaBkgAll ) {
$i->GetYaxis()->SetRangeUser(0.,25.);
} else if ( $i==pEcalRecHitSumEtConeDR04VsEtBkgBarrel || $i==pHcalTowerSumEtConeDR04VsEtBkgBarrel )
{ $i->GetYaxis()->SetRangeUser(0.,30.);
} else if ( $i==p_nTrkSolidConeDR04VsEtaBkgAll || $i==pnTrkSolidConeDR04VsEtBkgBarrel || $i==pnTrkSolidConeDR04VsEtBkgEndcap )
{ $i->GetYaxis()->SetRangeUser(0.,20.);
} else if ( $i==pIsoTrkSolidConeDR04VsEtaBkgAll || $i==pIsoTrkSolidConeDR04VsEtBkgBarrel || $i==pIsoTrkSolidConeDR04VsEtBkgEndcap)
{ $i->GetYaxis()->SetRangeUser(0.,100.);
} else if ( $i==pEcalRecHitSumEtConeDR04VsEtBkgEndcap || $i==pHcalTowerSumEtConeDR04VsEtBkgEndcap )
{$i->GetYaxis()->SetRangeUser(0.,30.);
} else if ( $i==pSigmaIetaIetaVsEtaBkgAll || $i==pSigmaIetaIetaVsEtBkgAll || $i==pHOverEVsEtaBkgAll || $i==pHOverEVsEtBkgAll )
{ $i->GetYaxis()->SetRangeUser(0.,0.1);
} else {
$i->SetMinimum(0.);
$i->SetMaximum(1.);
}
$i->SetLineColor(kPink+8);
$i->SetMarkerColor(kPink+8);
$i->SetMarkerStyle(20);
$i->SetMarkerSize(1);
$i->SetLineWidth(1);
$i->Draw();
//file_new->cd("DQMData/EgammaV/PhotonValidator/Background");
file_new->cd("$HISTOPATHNAME_Background");
$i->SetStats(0);
$i->SetLineColor(kBlack);
$i->SetMarkerColor(kBlack);
$i->SetMarkerStyle(20);
$i->SetMarkerSize(1);
$i->SetLineWidth(1);
$i->Draw("e1same");
c$i->SaveAs("gifs/$i.gif");
EOF
setenv N `expr $N + 1`
end
foreach i (`cat scaledhistosForBkgLogScale`)
cat > temp$N.C <<EOF
TCanvas *c$i = new TCanvas("c$i");
c$i->SetFillColor(10);
c$i->SetLogy(1);
//file_new->cd("DQMData/EgammaV/PhotonValidator/Background");
file_new->cd("$HISTOPATHNAME_Background");
Double_t nnew=$i->GetEntries();
//file_old->cd("DQMData/EgammaV/PhotonValidator/Background");
file_old->cd("$HISTOPATHNAME_Background");
if ( $i==hcalTowerSumEtConeDR04BkgBarrel || $i==hcalTowerSumEtConeDR04BkgEndcap ) {
$i->GetXaxis()->SetRangeUser(0.,10.);
} else if ( $i==hOverEBkgBarrel || $i==hOverEBkgEndcap ) {
$i->GetXaxis()->SetRangeUser(0.,1.);
}
Double_t nold=$i->GetEntries();
$i->SetStats(0);
$i->SetLineColor(kPink+8);
$i->SetFillColor(kPink+8);
$i->Draw();
//file_new->cd("DQMData/EgammaV/PhotonValidator/Background");
file_new->cd("$HISTOPATHNAME_Background");
Double_t nnew=$i->GetEntries();
$i->SetStats(0);
$i->SetLineColor(kBlack);
$i->SetMarkerColor(kBlack);
$i->SetMarkerStyle(20);
$i->SetMarkerSize(1);
$i->Scale(nold/nnew);
$i->Draw("e1same");
c$i->SaveAs("gifs/$i.gif");
EOF
setenv N `expr $N + 1`
end
foreach i (`cat 2DhistosForBkg`)
cat > temp$N.C <<EOF
TCanvas *c$i = new TCanvas("c$i");
c$i->SetFillColor(10);
//file_old->cd("DQMData/EgammaV/PhotonValidator/Background");
file_old->cd("$HISTOPATHNAME_Background");
$i->SetStats(0);
$i->SetMinimum(0.);
$i->SetMarkerColor(kPink+8);
$i->SetMarkerStyle(2);
$i->SetMarkerSize(0.2);
$i->Draw();
//file_new->cd("DQMData/EgammaV/PhotonValidator/Background");
file_new->cd("$HISTOPATHNAME_Background");
$i->SetStats(0);
$i->SetMarkerColor(kBlack);
$i->SetMarkerStyle(2);
$i->SetMarkerSize(0.2);
$i->Draw("same");
c$i->SaveAs("gifs/$i.gif");
EOF
setenv N `expr $N + 1`
end
setenv NTOT `expr $N - 1`
setenv N 1
while ( $N <= $NTOT )
cat temp$N.C >>& validation.C
rm temp$N.C
setenv N `expr $N + 1`
end
cat > end.C <<EOF
}
EOF
cat end.C >>& validation.C
rm end.C
if ( $TYPE == PixelMatchGsfElectron ) then
setenv ANALYZER PixelMatchGsfElectronAnalyzer
setenv CFG read_gsfElectrons
else if ( $TYPE == Photons ) then
setenv ANALYZER PhotonValidator
setenv CFG PhotonValidator_cfg
endif
if (-e validation.html) rm validation.html
if (-e bkgValidationPlotsTemplate.html) rm bkgValidationPlotsTemplate.html
cp ${CURRENTDIR}/bkgValidationPlotsTemplate.html bkgValidationPlotsTemplate.html
touch validation.html
cat > begin.html <<EOF
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>$NEWRELEASE vs $OLDRELEASE $TYPE validation</title>
</head>
<h1>$NEWRELEASE vs $OLDRELEASE $TYPE validation
<br>
$SAMPLE
</h1>
<p>The following plots were made using <a href="http://cmssw.cvs.cern.ch/cgi-bin/cmssw.cgi/CMSSW/Validation/RecoEgamma/src/$ANALYZER.cc">Validation/RecoEgamma/src/$ANALYZER</a>,
using <a href="http://cmssw.cvs.cern.ch/cgi-bin/cmssw.cgi/CMSSW/Validation/RecoEgamma/test/$CFG.py">Validation/RecoEgamma/test/$CFG.py</a>
<p>The script used to make the plots is <a href="validation.C">here</a>.
<br>
In all plots below, $OLDRELEASE is in purple , $NEWRELEASE in black.
<br>
Click on the plots to see them enlarged.
<br>
Responsible: N. Marinelli
<br>
<br>
EOF
cat begin.html >>& validation.html
rm begin.html
cat bkgValidationPlotsTemplate.html >>& validation.html
rm bkgValidationPlotsTemplate.html
rm efficiencyForBkg
rm scaledhistosForBkg
rm scaledhistosForBkgLogScale
rm unscaledhistosForBkg
rm 2DhistosForBkg
#echo "Now paste the following into your terminal window:"
#echo ""
echo "cd $OUTDIR"
#echo " root -b"
#echo ".x validation.C"
#echo ".q"
#echo "cd $CURRENTDIR"
#echo ""
root -b -l -q validation.C
cd $CURRENTDIR
echo "Then you can view your valdation plots here:"
echo "http://cmsdoc.cern.ch/Physics/egamma/www/$OUTPATH/validation.html"
| Tcsh | 4 | ckamtsikis/cmssw | Validation/RecoEgamma/test/bkgValidation.csh | [
"Apache-2.0"
] |
/*
* This config is the same than tester-l3 but repeats itself for every 4 packet
* size starting at $L.
*
* You can grep the output for RESULT and make a nice graph out of this to see
* how your DUT react to different packet sizes.
*
* A launch line would be :
* sudo bin/click -c 0xf -n 4 -- conf/fastclick/tester-l3-loop.click L=60 N=100 S=100000
*/
/*You do not need to change the mac address as we run in promisc, but you need
to set the srcip, gateway ip and dstip correctly */
define($L 60, $N 100, $S 100000);
define($smac 90:e2:ba:c3:79:66)
define($dmac 90:e2:ba:c3:79:68)
define($srcip 192.168.130.4)
define($dstip 192.168.128.14)
define($gatewayip 192.168.130.1)
define($lanport 0000:03:00.0)
define($wanport 0000:01:00.0)
//Explained in loop.click
define($verbose 3)
define($blocking true)
//###################
// TX
//###################
//Create a UDP flow of $N packets
is :: FastUDPFlows(RATE 0, LIMIT $N, LENGTH $L, SRCETH $smac, DSTETH $dmac, SRCIP $srcip, DSTIP $dstip, FLOWS 1, FLOWSIZE $N)
-> MarkMACHeader
//EnsureDPDKBuffer will copy the packet inside a DPDK buffer, so there is no more copies (not even to the NIC) afterwards when we replay the packet many time
-> EnsureDPDKBuffer
-> Strip(14)
-> CheckIPHeader
-> SetIPAddress($gatewayip)
-> uq :: Unqueue()
-> arp_q :: ARPQuerier($srcip, $smac)
-> Queue
//MutliReplayUqueue pulls all packets from its input, and replay them from memory $S amount of time
-> replay :: MultiReplayUnqueue(STOP -1, ACTIVE false, QUICK_CLONE 1)
-> ic0 :: AverageCounter()
-> td0 :: ToDPDKDevice($lanport, BLOCKING $blocking, VERBOSE $verbose)
//Do not replay arp queries...
arp_q[1]
-> td0
//Send a small packet every second to advertise our mac src
td1 :: ToDPDKDevice($wanport, BLOCKING $blocking, VERBOSE $verbose)
//It is good practice to pin any source to let FastClick know what will eat the CPU and allocate FromDPDKDevice threads accordingly. It also help you know what you're doing. Multithreading is everything but magic.
StaticThreadSched(replay 0)
//###################
// RX
//###################
fd0 :: FromDPDKDevice($lanport, PROMISC true, VERBOSE $verbose)
-> arp_c0 :: Classifier(12/0800, 12/0806 20/0001, 12/0806 20/0002, -)
arp_c0[0] -> Print("R0 IP") -> Discard
arp_c0[1] -> Print("R0 ARPQ") ->arp_r0 :: ARPResponder($srcip $smac) -> td0
arp_c0[2] -> Print("R0 ARPR") -> [1]arp_q
arp_c0[3] -> Print("R0 Other") -> Discard
fd1 :: FromDPDKDevice($wanport, PROMISC true, VERBOSE $verbose)
-> arp_c1 :: Classifier(12/0800, 12/0806 20/0001, 12/0806 20/0002, -)
arp_c1[0] -> Print("R1 IP", ACTIVE false) -> oc0 :: AverageCounter() -> Discard
arp_c1[1] -> Print("R1 ARPQ") -> arp_r1 :: ARPResponder($dstip $dmac) -> td1
arp_c1[2] -> Discard
arp_c1[3] -> Print("R1 Other") -> Discard
DriverManager( wait 1s, //First small round to set up ARP etc
write replay.stop 1,
write replay.active true,
wait,
wait 2s,
set LENGTH $L,
label start,
print "Launching test with L=$LENGTH",
write oc0.reset,
write ic0.reset,
write is.length $LENGTH,
write is.reset,
set REP $(mul $(idiv $S $LENGTH) 60),
write replay.stop $REP,
write replay.active true,
write replay.reset,
wait,
wait 10ms, print $(ic0.count), print $(oc0.count),
print $(ic0.link_rate), print $(oc0.link_rate),
set oloss $(div $(sub $(ic0.link_count) $(oc0.link_count)) $(ic0.link_count)),
print "RESULT $LENGTH $(oc0.link_rate) $oloss",
set LENGTH $(add $LENGTH 4),
goto start $(le $LENGTH 1500),
print "All test finished !",
)
| Click | 5 | BorisPis/asplos22-nicmem-fastclick | conf/pktgen/tester-l3-loop.click | [
"BSD-3-Clause-Clear"
] |
\require "c@>=0.2.0" | LilyPond | 0 | HolgerPeters/lyp | spec/package_setups/transitive/b@0.2/package.ly | [
"MIT"
] |
--TEST--
ReflectionExtension::getINIEntries()
--INI--
user_agent=php
--FILE--
<?php
$ext = new ReflectionExtension("standard");
$inis = $ext->getINIEntries();
var_dump($inis["user_agent"]);
?>
--EXPECT--
string(3) "php"
| PHP | 3 | thiagooak/php-src | ext/reflection/tests/015.phpt | [
"PHP-3.01"
] |
#!/usr/bin/env bash
# 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.
# ============================================================================
# Download and build TensorFlow.
set -euxo pipefail
git clone --branch=master --depth=1 https://github.com/tensorflow/tensorflow.git /tensorflow
cd /tensorflow
ln -s $(which ${PYTHON}) /usr/local/bin/python
# Build TensorFlow with support for Intel(R) MKL-DNN
yes "" | ${PYTHON} configure.py && \
bazel build -c opt --config=mkl --cxxopt="-D_GLIBCXX_USE_CXX11_ABI=0" \
tensorflow/tools/pip_package:build_pip_package && \
bazel-bin/tensorflow/tools/pip_package/build_pip_package /tmp/pip && \
pip --no-cache-dir install --upgrade /tmp/pip/tensorflow-*.whl && \
rm -rf /tmp/pip && \
rm -rf /root/.cache
# download and build Horovod
git clone --recursive https://github.com/uber/horovod.git
cd horovod
# export environment
export HOROVOD_WITHOUT_PYTORCH=1
export HOROVOD_WITH_TENSORFLOW=1
python setup.py sdist
pip --no-cache-dir install --upgrade sdist/horovod*.tar.gz && \
rm -rf sdist && \
rm -rf /root/.cache
| Shell | 3 | yage99/tensorflow | tensorflow/tools/dockerfiles/tests/build-mkl-horovod.sh | [
"Apache-2.0"
] |
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { isNonEmptyArray } from 'vs/base/common/arrays';
import { CancellationToken } from 'vs/base/common/cancellation';
import { ICodeEditor } from 'vs/editor/browser/editorBrowser';
import { EditorAction, registerEditorAction, ServicesAccessor } from 'vs/editor/browser/editorExtensions';
import { Range } from 'vs/editor/common/core/range';
import { EditorContextKeys } from 'vs/editor/common/editorContextKeys';
import { ITextModel } from 'vs/editor/common/model';
import { IEditorWorkerService } from 'vs/editor/common/services/editorWorker';
import { ITextModelService } from 'vs/editor/common/services/resolverService';
import { formatDocumentRangesWithSelectedProvider, FormattingMode } from 'vs/editor/contrib/format/browser/format';
import * as nls from 'vs/nls';
import { ContextKeyExpr } from 'vs/platform/contextkey/common/contextkey';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { Progress } from 'vs/platform/progress/common/progress';
import { getOriginalResource } from 'vs/workbench/contrib/scm/browser/dirtydiffDecorator';
import { ISCMService } from 'vs/workbench/contrib/scm/common/scm';
registerEditorAction(class FormatModifiedAction extends EditorAction {
constructor() {
super({
id: 'editor.action.formatChanges',
label: nls.localize('formatChanges', "Format Modified Lines"),
alias: 'Format Modified Lines',
precondition: ContextKeyExpr.and(EditorContextKeys.writable, EditorContextKeys.hasDocumentSelectionFormattingProvider),
});
}
async run(accessor: ServicesAccessor, editor: ICodeEditor): Promise<void> {
const instaService = accessor.get(IInstantiationService);
if (!editor.hasModel()) {
return;
}
const ranges = await instaService.invokeFunction(getModifiedRanges, editor.getModel());
if (isNonEmptyArray(ranges)) {
return instaService.invokeFunction(
formatDocumentRangesWithSelectedProvider, editor, ranges,
FormattingMode.Explicit, Progress.None, CancellationToken.None
);
}
}
});
export async function getModifiedRanges(accessor: ServicesAccessor, modified: ITextModel): Promise<Range[] | undefined | null> {
const scmService = accessor.get(ISCMService);
const workerService = accessor.get(IEditorWorkerService);
const modelService = accessor.get(ITextModelService);
const original = await getOriginalResource(scmService, modified.uri);
if (!original) {
return null; // let undefined signify no changes, null represents no source control (there's probably a better way, but I can't think of one rn)
}
const ranges: Range[] = [];
const ref = await modelService.createModelReference(original);
try {
if (!workerService.canComputeDirtyDiff(original, modified.uri)) {
return undefined;
}
const changes = await workerService.computeDirtyDiff(original, modified.uri, false);
if (!isNonEmptyArray(changes)) {
return undefined;
}
for (const change of changes) {
ranges.push(modified.validateRange(new Range(
change.modifiedStartLineNumber, 1,
change.modifiedEndLineNumber || change.modifiedStartLineNumber /*endLineNumber is 0 when things got deleted*/, Number.MAX_SAFE_INTEGER)
));
}
} finally {
ref.dispose();
}
return ranges;
}
| TypeScript | 5 | EngineLessCC/vscode | src/vs/workbench/contrib/format/browser/formatModified.ts | [
"MIT"
] |
(module
(type $none_=>_none (func))
(memory $0 0)
(export "testFor" (func $unify-local-flags/testFor))
(export "testWhile" (func $unify-local-flags/testFor))
(export "testDo" (func $unify-local-flags/testDo))
(export "memory" (memory $0))
(func $unify-local-flags/testFor
(local $0 i32)
loop $for-loop|2
local.get $0
i32.const 255
i32.and
i32.const 255
i32.lt_u
if
local.get $0
i32.const 1
i32.add
local.set $0
br $for-loop|2
end
end
)
(func $unify-local-flags/testDo
(local $0 i32)
loop $do-loop|1
local.get $0
i32.const 1
i32.add
local.tee $0
i32.const 255
i32.and
i32.const 255
i32.lt_u
br_if $do-loop|1
end
)
)
| WebAssembly | 3 | romdotdog/assemblyscript | tests/compiler/unify-local-flags.optimized.wat | [
"Apache-2.0"
] |
expression
expression, term, factor
0, 1, 36, 37, 38, 39, 28, 29
expression -> expression 38 term | expression 39 term | term
term -> term 36 factor | term 37 factor | factor
factor -> 28 expression 29 | 0 | 1
| Rouge | 3 | vampy/university | compilers/labs/lab4/src/step2/expression.rg | [
"MIT"
] |
/* Copyright 2017-2020 The Verible 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.
*/
%{
/* verilog.lex is a flex-generated lexer for Verilog and SystemVerilog.
*
* Token enumerations come from verilog_token_enum.h,
* (generated from verilog.tab.hh, generated from verilog.y).
*
*/
/**
* Verilog language Standard (2006):
* http://ieeexplore.ieee.org/xpl/mostRecentIssue.jsp?punumber=10779
* System Verilog:
* http://standards.ieee.org/getieee/1800/download/1800-2012.pdf
**/
#define _FLEXLEXER_H_
#include <cstdio>
#include "verilog/parser/verilog_lexer.h"
#include "verilog/parser/verilog_token_enum.h"
/* When testing unstructured sequences of tokens in the unit-tests,
* the start-condition stack may be unbalanced.
* This safeguard just prevents underflow in those cases.
* Only tokens that appear in the default INITIAL state need to call this;
* tokens that are qualified by a start condition should just call
* yy_pop_state(), because they are guaranteed to have a non-empty stack.
*
* This is defined as a macro because the symbols referenced are
* only available in the lexer-actions context.
*/
#define yy_safe_pop_state() if (yy_start_stack_depth > 0) { yy_pop_state(); }
/* Replace the state on the top of the stack with a new one. */
#define yy_set_top_state(state) { yy_pop_state(); yy_push_state(state); }
/* TODO(fangism): Track yylineno with column position. */
%}
%option 8bit
%option c++
%option case-sensitive
%option never-interactive
%option nounistd
%option nounput
%option noyywrap
%option prefix="verilog"
/* to enable stack of initial condition states: */
%option stack
%option yyclass="verilog::VerilogLexer"
/* various lexer states, INITIAL = 0 */
%x TIMESCALE_DIRECTIVE
%x AFTER_DOT
%s UDPTABLE
%s EDGES
%x EDGES_POSSIBLY
%x REAL_SCALE
%x CONSUME_NEXT_SPACES
%x MACRO_CALL_EXPECT_OPEN
%x MACRO_CALL_ARGS
%x MACRO_ARG_IGNORE_LEADING_SPACE
%x MACRO_ARG_UNLEXED
%x ATTRIBUTE_START
%x ATTRIBUTE_MIDDLE
%s COVERGROUP
%s DISCIPLINE
%s PRIMITIVE
%x PP_EXPECT_DEF_ID
%x PP_EXPECT_IF_ID
%x PP_MACRO_FORMALS
%x PP_MACRO_DEFAULT
%x PP_BETWEEN_ID_AND_BODY
%x PP_CONSUME_BODY
%x DEC_BASE
%x BIN_BASE
%x OCT_BASE
%x HEX_BASE
%x ENCRYPTED
%x POST_MACRO_ID
%x IGNORE_REST_OF_LINE
%x IN_EOL_COMMENT
%x LIBRARY_EXPECT_ID
%x LIBRARY_FILEPATHS
/* identifier */
Alpha [a-zA-Z]
RejectChar [\x7F-\xFF]
IdentifierStart {Alpha}|"_"
Letter {IdentifierStart}|"$"
Digit [0-9]
BasicIdentifier {IdentifierStart}({Letter}|{Digit})*
/* treat `id constants like plain identifiers */
MacroIdentifier `{BasicIdentifier}
/* verilog escaped identifiers start with '\', and end with whitespace */
EscapedIdentifier "\\"[^ \t\f\b\n]+
Identifier {BasicIdentifier}
SystemTFIdentifier "$"{BasicIdentifier}
/* LRM: 33.3.1: file_path_spec characters include [.*?/] */
/* Windows might need '\' for path separators. */
/* PathChars [^ ,;\t\r\n] */
/* LeadingPathChars [^ -,;\t\r\n] */
PathChars ({Letter}|{Digit}|[-_.?*/])
LeadingPathChars ({Letter}|{Digit}|[_.?*/])
FilePath {LeadingPathChars}{PathChars}*
/* white space */
LineTerminator \r|\n|\r\n|\0
InputCharacter [^\r\n\0]
InputCharacterNoBackslash [^\\\r\n\0]
Space [ \t\f\b]
/*
* To better track line numbers, LineTerminator is handled separately from Space.
*/
/* Integer literal */
DecimalDigits [0-9]+
HexDigit [0-9a-fA-F]
DecimalIntegerLiteral {DecimalDigits}
HexademicalIntegerLiteral 0(x|X){HexDigit}+
IntegerLiteral {DecimalIntegerLiteral}|{HexademicalIntegerLiteral}
/* allow underscores */
DecNumber [0-9][0-9_]*
OrderOfMagnitude 1[0]*
DecBase \'[sS]?[dD]
BinBase \'[sS]?[bB]
OctBase \'[sS]?[oO]
HexBase \'[sS]?[hH]
AnyBase {DecBase}|{BinBase}|{OctBase}|{HexBase}
XZDigits [xzXZ?]_*
BinDigits [0-1xzXZ_\?]+
OctDigits [0-7xzXZ_\?]+
HexDigits [0-9a-fA-FxzXZ_\?]+
UnbasedNumber \'[01xzXZ]
BadIdentifier {DecNumber}{Identifier}
BadMacroIdentifier `{DecNumber}{BasicIdentifier}
/* Escape sequence */
EscapeSequence "\\"{InputCharacter}
/* String literal */
StringContent ([^\r\n"\\]|{EscapeSequence}|\\{LineTerminator})*
UnterminatedStringLiteral \"{StringContent}
StringLiteral {UnterminatedStringLiteral}\"
/* Preprocessor-evaluated string literal */
EvalStringLiteralContent ([^`]|(`[^"]))*
UnterminatedEvalStringLiteral `\"{EvalStringLiteralContent}
EvalStringLiteral {UnterminatedEvalStringLiteral}`\"
/* attribute lists, treated like comments */
AttributesBegin "(*"
AttributesEnd [*]+")"
/* was TK_PSTAR and TK_STARP */
AttributesContinue [^ \r\n\t\f\b)]
AttributesContent ([^*]|("*"+[^)*]))*
Attributes {AttributesBegin}{AttributesContent}{AttributesEnd}
/* comments */
RestOfLine {InputCharacter}*{LineTerminator}
CommentContent ([^*]|("*"+[^/*]))*
UnterminatedComment "/*"{CommentContent}
TraditionalComment {UnterminatedComment}"*"+"/"
EndOfLineCommentStart "//"
EndOfLineComment {EndOfLineCommentStart}{RestOfLine}
Comment {TraditionalComment}|{EndOfLineComment}
/* line continuation */
LineContinuation "\\"{LineTerminator}
ContinuedLine {InputCharacter}*{LineContinuation}
/* DiscontinuedLine: last character before LineTerminator may not be '\\' */
DiscontinuedLine {InputCharacter}*[^\\\r\n]?{LineTerminator}
/* scientific units */
S [afpnumkKMGT]
/* time units */
TU [munpf]
/* macros */
MacroCallPrefix {MacroIdentifier}{Space}*"("
/* LRM allowing spaces makes it difficult to know without looking up the macro
* whether the open paren starts macro arguments or is a separate set of
* tokens that follow the macro.
*/
TraditionalCommentOrSpace {TraditionalComment}|{Space}
LineTerminatorOrEndOfLineComment {LineTerminator}|{EndOfLineComment}
IgnoreToEndOfLine {TraditionalCommentOrSpace}*{LineTerminatorOrEndOfLineComment}
/* specific pragmas */
PragmaComment "//"{Space}*pragma
PragmaDirective `pragma
Pragma {PragmaComment}|{PragmaDirective}
PragmaProtected {Pragma}{Space}+protect{Space}+begin_protected
PragmaEndProtected {Pragma}{Space}+protect{Space}+end_protected
%%
{Space}+ { UpdateLocation(); return TK_SPACE; }
{LineTerminator} { UpdateLocation(); return TK_NEWLINE; }
/* Internal-use-only tokens to trigger library map (LRM:33) parsing mode. */
`____verible_verilog_library_begin____ { UpdateLocation(); return PD_LIBRARY_SYNTAX_BEGIN; }
`____verible_verilog_library_end____ { UpdateLocation(); return PD_LIBRARY_SYNTAX_END; }
/* Clarification:
* `protected and `endprotected enclose an already encrypted section.
* `protect and `endprotect tell the compiler *to* encrypt a section.
*/
{PragmaProtected}{IgnoreToEndOfLine} {
UpdateLocation();
yy_push_state(ENCRYPTED);
}
`protected{IgnoreToEndOfLine} {
UpdateLocation();
yy_push_state(ENCRYPTED);
}
<ENCRYPTED>{PragmaEndProtected}{IgnoreToEndOfLine} {
yyless(yyleng -1); /* return \n to stream */
UpdateLocation();
yy_pop_state();
}
<ENCRYPTED>`endprotected{IgnoreToEndOfLine} {
yyless(yyleng -1); /* return \n to stream */
UpdateLocation();
yy_pop_state();
}
/* In ENCRYPTED state, ignore all text. */
<ENCRYPTED>{RestOfLine} { UpdateLocation(); /* ignore */ }
{TraditionalComment} {
UpdateLocation();
return TK_COMMENT_BLOCK;
}
/* Explicitly handling EOL comments in state-driven manner prevents the lexer
* from getting stuck in a slow internal loop. In particular, as soon as the
* '\0' character is encountered, break out and pass it onto the parent state
* to handle/reject. See b/129835188. We might need to do this for
* block-style comments as well. */
{EndOfLineCommentStart} {
yy_push_state(IN_EOL_COMMENT);
yymore();
}
<IN_EOL_COMMENT>{
<<EOF>> {
UpdateLocationEOF(); /* return \0 to input stream */
yy_pop_state();
return TK_EOL_COMMENT;
}
{LineContinuation} {
yyless(yyleng-2); /* return \\\n to input stream */
UpdateLocation();
yy_pop_state();
return TK_EOL_COMMENT;
}
{InputCharacterNoBackslash}* {
yymore();
}
"\\" {
yymore();
}
{LineTerminator} {
yyless(yyleng-1); /* return \n to input stream */
UpdateLocation();
yy_pop_state();
return TK_EOL_COMMENT;
}
. {
/* Reject all other characters, defer handling to parent state. */
yyless(yyleng-1); /* return offending character to input stream */
UpdateLocation();
yy_pop_state();
return TK_EOL_COMMENT;
}
}
{UnterminatedComment} { UpdateLocation(); return TK_OTHER; }
/* keywords */
1step { UpdateLocation(); return TK_1step; }
always { UpdateLocation(); return TK_always; }
and { UpdateLocation(); return TK_and; }
assign { UpdateLocation(); return TK_assign; }
begin { UpdateLocation(); return TK_begin; }
buf { UpdateLocation(); return TK_buf; }
bufif0 { UpdateLocation(); return TK_bufif0; }
bufif1 { UpdateLocation(); return TK_bufif1; }
case { UpdateLocation(); return TK_case; }
casex { UpdateLocation(); return TK_casex; }
casez { UpdateLocation(); return TK_casez; }
cmos { UpdateLocation(); return TK_cmos; }
deassign { UpdateLocation(); return TK_deassign; }
default { UpdateLocation(); return TK_default; }
defparam { UpdateLocation(); return TK_defparam; }
disable { UpdateLocation(); return TK_disable; }
edge { UpdateLocation(); yy_push_state(EDGES_POSSIBLY); return TK_edge; }
else { UpdateLocation(); return TK_else; }
end { UpdateLocation(); return TK_end; }
endcase { UpdateLocation(); return TK_endcase; }
endfunction { UpdateLocation(); return TK_endfunction; }
endmodule { UpdateLocation(); return TK_endmodule; }
<PRIMITIVE>endprimitive { UpdateLocation(); yy_safe_pop_state(); return TK_endprimitive; }
endprimitive { UpdateLocation(); return TK_endprimitive; }
endspecify { UpdateLocation(); return TK_endspecify; }
<UDPTABLE>endtable {
UpdateLocation();
yy_pop_state();
return TK_endtable;
}
endtable { UpdateLocation(); return SymbolIdentifier; }
endtask { UpdateLocation(); return TK_endtask; }
event { UpdateLocation(); return TK_event; }
/* The find* functions built-in methods, but not keywords. */
<AFTER_DOT>find {
UpdateLocation();
yy_pop_state();
return TK_find;
}
<AFTER_DOT>find_index {
UpdateLocation();
yy_pop_state();
return TK_find_index;
}
<AFTER_DOT>find_first {
UpdateLocation();
yy_pop_state();
return TK_find_first;
}
<AFTER_DOT>find_first_index {
UpdateLocation();
yy_pop_state();
return TK_find_first_index;
}
<AFTER_DOT>find_last {
UpdateLocation();
yy_pop_state();
return TK_find_last;
}
<AFTER_DOT>find_last_index {
UpdateLocation();
yy_pop_state();
return TK_find_last_index;
}
<AFTER_DOT>sort {
UpdateLocation();
yy_pop_state();
return TK_sort;
}
<AFTER_DOT>rsort {
UpdateLocation();
yy_pop_state();
return TK_rsort;
}
<AFTER_DOT>reverse {
UpdateLocation();
yy_pop_state();
return TK_reverse;
}
<AFTER_DOT>shuffle {
UpdateLocation();
yy_pop_state();
return TK_shuffle;
}
<AFTER_DOT>sum {
UpdateLocation();
yy_pop_state();
return TK_sum;
}
<AFTER_DOT>product {
UpdateLocation();
yy_pop_state();
return TK_product;
}
<AFTER_DOT>and {
UpdateLocation();
yy_pop_state();
return TK_and;
}
<AFTER_DOT>or {
UpdateLocation();
yy_pop_state();
return TK_or;
}
<AFTER_DOT>xor {
UpdateLocation();
yy_pop_state();
return TK_xor;
}
for { UpdateLocation(); return TK_for; }
force { UpdateLocation(); return TK_force; }
forever { UpdateLocation(); return TK_forever; }
fork { UpdateLocation(); return TK_fork; }
function { UpdateLocation(); return TK_function; }
highz0 { UpdateLocation(); return TK_highz0; }
highz1 { UpdateLocation(); return TK_highz1; }
if { UpdateLocation(); return TK_if; }
ifnone { UpdateLocation(); return TK_ifnone; }
initial { UpdateLocation(); return TK_initial; }
inout { UpdateLocation(); return TK_inout; }
input { UpdateLocation(); return TK_input; }
integer { UpdateLocation(); return TK_integer; }
join { UpdateLocation(); return TK_join; }
large { UpdateLocation(); return TK_large; }
macromodule { UpdateLocation(); return TK_macromodule; }
medium { UpdateLocation(); return TK_medium; }
module { UpdateLocation(); return TK_module; }
nand { UpdateLocation(); return TK_nand; }
negedge { UpdateLocation(); return TK_negedge; }
nmos { UpdateLocation(); return TK_nmos; }
nor { UpdateLocation(); return TK_nor; }
not { UpdateLocation(); return TK_not; }
notif0 { UpdateLocation(); return TK_notif0; }
notif1 { UpdateLocation(); return TK_notif1; }
or { UpdateLocation(); return TK_or; }
<COVERGROUP>option { UpdateLocation(); return TK_option; }
option { UpdateLocation(); return SymbolIdentifier; }
output { UpdateLocation(); return TK_output; }
parameter { UpdateLocation(); return TK_parameter; }
pmos { UpdateLocation(); return TK_pmos; }
posedge { UpdateLocation(); return TK_posedge; }
primitive { UpdateLocation(); yy_push_state(PRIMITIVE); return TK_primitive; }
pull0 { UpdateLocation(); return TK_pull0; }
pull1 { UpdateLocation(); return TK_pull1; }
pulldown { UpdateLocation(); return TK_pulldown; }
pullup { UpdateLocation(); return TK_pullup; }
rcmos { UpdateLocation(); return TK_rcmos; }
real { UpdateLocation(); return TK_real; }
realtime { UpdateLocation(); return TK_realtime; }
reg { UpdateLocation(); return TK_reg; }
release { UpdateLocation(); return TK_release; }
repeat { UpdateLocation(); return TK_repeat; }
rnmos { UpdateLocation(); return TK_rnmos; }
rpmos { UpdateLocation(); return TK_rpmos; }
rtran { UpdateLocation(); return TK_rtran; }
rtranif0 { UpdateLocation(); return TK_rtranif0; }
rtranif1 { UpdateLocation(); return TK_rtranif1; }
sample { UpdateLocation(); return TK_sample; }
scalared { UpdateLocation(); return TK_scalared; }
small { UpdateLocation(); return TK_small; }
specify { UpdateLocation(); return TK_specify; }
specparam { UpdateLocation(); return TK_specparam; }
strong0 { UpdateLocation(); return TK_strong0; }
strong1 { UpdateLocation(); return TK_strong1; }
supply0 { UpdateLocation(); return TK_supply0; }
supply1 { UpdateLocation(); return TK_supply1; }
<PRIMITIVE>table { UpdateLocation(); yy_push_state(UDPTABLE); return TK_table; }
table { UpdateLocation(); return SymbolIdentifier; }
task { UpdateLocation(); return TK_task; }
time { UpdateLocation(); return TK_time; }
tran { UpdateLocation(); return TK_tran; }
tranif0 { UpdateLocation(); return TK_tranif0; }
tranif1 { UpdateLocation(); return TK_tranif1; }
tri { UpdateLocation(); return TK_tri; }
tri0 { UpdateLocation(); return TK_tri0; }
tri1 { UpdateLocation(); return TK_tri1; }
triand { UpdateLocation(); return TK_triand; }
trior { UpdateLocation(); return TK_trior; }
trireg { UpdateLocation(); return TK_trireg; }
type_option { UpdateLocation(); return TK_type_option; }
vectored { UpdateLocation(); return TK_vectored; }
wait { UpdateLocation(); return TK_wait; }
wand { UpdateLocation(); return TK_wand; }
weak0 { UpdateLocation(); return TK_weak0; }
weak1 { UpdateLocation(); return TK_weak1; }
while { UpdateLocation(); return TK_while; }
wire { UpdateLocation(); return TK_wire; }
wor { UpdateLocation(); return TK_wor; }
xnor { UpdateLocation(); return TK_xnor; }
xor { UpdateLocation(); return TK_xor; }
/* The 1364-1995 timing checks. */
\$hold { UpdateLocation(); return TK_Shold; }
\$nochange { UpdateLocation(); return TK_Snochange; }
\$period { UpdateLocation(); return TK_Speriod; }
\$recovery { UpdateLocation(); return TK_Srecovery; }
\$setup { UpdateLocation(); return TK_Ssetup; }
\$setuphold { UpdateLocation(); return TK_Ssetuphold; }
\$skew { UpdateLocation(); return TK_Sskew; }
\$width { UpdateLocation(); return TK_Swidth; }
\$attribute { UpdateLocation(); return TKK_attribute; }
bool { UpdateLocation(); return TK_bool; }
automatic { UpdateLocation(); return TK_automatic; }
endgenerate { UpdateLocation(); return TK_endgenerate; }
generate { UpdateLocation(); return TK_generate; }
genvar { UpdateLocation(); return TK_genvar; }
localparam { UpdateLocation(); return TK_localparam; }
noshowcancelled { UpdateLocation(); return TK_noshowcancelled; }
pulsestyle_onevent { UpdateLocation(); return TK_pulsestyle_onevent; }
pulsestyle_ondetect { UpdateLocation(); return TK_pulsestyle_ondetect; }
showcancelled { UpdateLocation(); return TK_showcancelled; }
signed { UpdateLocation(); return TK_signed; }
unsigned { UpdateLocation(); return TK_unsigned; }
/* The new 1364-2001 timing checks. */
\$fullskew { UpdateLocation(); return TK_Sfullskew; }
\$recrem { UpdateLocation(); return TK_Srecrem; }
\$removal { UpdateLocation(); return TK_Sremoval; }
\$timeskew { UpdateLocation(); return TK_Stimeskew; }
cell { UpdateLocation(); return TK_cell; }
config { UpdateLocation(); return TK_config; }
design { UpdateLocation(); return TK_design; }
endconfig { UpdateLocation(); return TK_endconfig; }
incdir {
UpdateLocation();
yy_push_state(LIBRARY_FILEPATHS);
return TK_incdir;
}
include {
UpdateLocation();
yy_push_state(LIBRARY_FILEPATHS);
return TK_include;
}
instance { UpdateLocation(); return TK_instance; }
liblist { UpdateLocation(); return TK_liblist; }
library {
UpdateLocation();
yy_push_state(LIBRARY_EXPECT_ID);
return TK_library;
}
use { UpdateLocation(); return TK_use; }
wone { UpdateLocation(); return TK_wone; }
uwire { UpdateLocation(); return TK_uwire; }
alias { UpdateLocation(); return TK_alias; }
always_comb { UpdateLocation(); return TK_always_comb; }
always_ff { UpdateLocation(); return TK_always_ff; }
always_latch { UpdateLocation(); return TK_always_latch; }
assert { UpdateLocation(); return TK_assert; }
assume { UpdateLocation(); return TK_assume; }
before { UpdateLocation(); return TK_before; }
bind { UpdateLocation(); return TK_bind; }
bins { UpdateLocation(); return TK_bins; }
binsof { UpdateLocation(); return TK_binsof; }
bit { UpdateLocation(); return TK_bit; }
break { UpdateLocation(); return TK_break; }
byte { UpdateLocation(); return TK_byte; }
chandle { UpdateLocation(); return TK_chandle; }
class { UpdateLocation(); return TK_class; }
clocking { UpdateLocation(); return TK_clocking; }
const { UpdateLocation(); return TK_const; }
constraint { UpdateLocation(); return TK_constraint; }
context { UpdateLocation(); return TK_context; }
continue { UpdateLocation(); return TK_continue; }
cover { UpdateLocation(); return TK_cover; }
covergroup {
UpdateLocation();
yy_push_state(COVERGROUP);
return TK_covergroup;
}
coverpoint { UpdateLocation(); return TK_coverpoint; }
cross { UpdateLocation(); return TK_cross; } /* covergroup and Verilog-AMS */
dist { UpdateLocation(); return TK_dist; }
do { UpdateLocation(); return TK_do; }
endclass { UpdateLocation(); return TK_endclass; }
endclocking { UpdateLocation(); return TK_endclocking; }
endgroup {
UpdateLocation();
yy_safe_pop_state();
return TK_endgroup;
}
endinterface { UpdateLocation(); return TK_endinterface; }
endpackage { UpdateLocation(); return TK_endpackage; }
endprogram { UpdateLocation(); return TK_endprogram; }
endproperty { UpdateLocation(); return TK_endproperty; }
endsequence { UpdateLocation(); return TK_endsequence; }
enum { UpdateLocation(); return TK_enum; }
expect { UpdateLocation(); return TK_expect; }
export { UpdateLocation(); return TK_export; }
extends { UpdateLocation(); return TK_extends; }
extern { UpdateLocation(); return TK_extern; }
final { UpdateLocation(); return TK_final; }
first_match { UpdateLocation(); return TK_first_match; }
foreach { UpdateLocation(); return TK_foreach; }
forkjoin { UpdateLocation(); return TK_forkjoin; }
iff { UpdateLocation(); return TK_iff; }
ignore_bins { UpdateLocation(); return TK_ignore_bins; }
illegal_bins { UpdateLocation(); return TK_illegal_bins; }
import { UpdateLocation(); return TK_import; }
inside { UpdateLocation(); return TK_inside; }
int { UpdateLocation(); return TK_int; }
interface { UpdateLocation(); return TK_interface; }
intersect { UpdateLocation(); return TK_intersect; }
join_any { UpdateLocation(); return TK_join_any; }
join_none { UpdateLocation(); return TK_join_none; }
/* yes, "local::" is an actual token according to the LRM. */
local:: { UpdateLocation(); return TK_local_SCOPE; }
local { UpdateLocation(); return TK_local; }
logic { UpdateLocation(); return TK_logic; }
longint { UpdateLocation(); return TK_longint; }
matches { UpdateLocation(); return TK_matches; }
modport { UpdateLocation(); return TK_modport; }
new { UpdateLocation(); return TK_new; }
null { UpdateLocation(); return TK_null; }
package { UpdateLocation(); return TK_package; }
packed { UpdateLocation(); return TK_packed; }
priority { UpdateLocation(); return TK_priority; }
program { UpdateLocation(); return TK_program; }
property { UpdateLocation(); return TK_property; }
protected { UpdateLocation(); return TK_protected; }
pure { UpdateLocation(); return TK_pure; }
rand { UpdateLocation(); return TK_rand; }
randc { UpdateLocation(); return TK_randc; }
randcase { UpdateLocation(); return TK_randcase; }
randomize|std::randomize { UpdateLocation(); return TK_randomize; }
<AFTER_DOT>randomize { UpdateLocation(); yy_pop_state(); return TK_randomize; }
/* randomize is a special function, with its own syntax.
* The spec says [ "std::" ] "randomize" is a randomize_call.
*/
randsequence { UpdateLocation(); return TK_randsequence; }
ref { UpdateLocation(); return TK_ref; }
return { UpdateLocation(); return TK_return; }
\$root { UpdateLocation(); return TK_Sroot; }
sequence { UpdateLocation(); return TK_sequence; }
shortint { UpdateLocation(); return TK_shortint; }
shortreal { UpdateLocation(); return TK_shortreal; }
solve { UpdateLocation(); return TK_solve; }
static { UpdateLocation(); return TK_static; }
string { UpdateLocation(); return TK_string; }
struct { UpdateLocation(); return TK_struct; }
super { UpdateLocation(); return TK_super; }
tagged { UpdateLocation(); return TK_tagged; }
this { UpdateLocation(); return TK_this; }
throughout { UpdateLocation(); return TK_throughout; }
timeprecision { UpdateLocation(); return TK_timeprecision; }
timeunit { UpdateLocation(); return TK_timeunit; }
type { UpdateLocation(); return TK_type; }
typedef { UpdateLocation(); return TK_typedef; }
union { UpdateLocation(); return TK_union; }
<AFTER_DOT>unique { UpdateLocation(); yy_pop_state(); return TK_unique; }
unique { UpdateLocation(); return TK_unique; }
<AFTER_DOT>unique_index {
UpdateLocation();
yy_pop_state();
return TK_unique_index;
}
\$unit { UpdateLocation(); return TK_Sunit; }
var { UpdateLocation(); return TK_var; }
virtual { UpdateLocation(); return TK_virtual; }
void { UpdateLocation(); return TK_void; }
wait_order { UpdateLocation(); return TK_wait_order; }
wildcard { UpdateLocation(); return TK_wildcard; }
<COVERGROUP>with { UpdateLocation(); return TK_with__covergroup; }
with { UpdateLocation(); return TK_with; }
within { UpdateLocation(); return TK_within; }
timeprecision_check { UpdateLocation(); return TK_timeprecision_check; }
timeunit_check { UpdateLocation(); return TK_timeunit_check; }
accept_on { UpdateLocation(); return TK_accept_on; }
checker { UpdateLocation(); return TK_checker; }
endchecker { UpdateLocation(); return TK_endchecker; }
eventually { UpdateLocation(); return TK_eventually; }
global { UpdateLocation(); return TK_global; }
implies { UpdateLocation(); return TK_implies; }
let { UpdateLocation(); return TK_let; }
nexttime { UpdateLocation(); return TK_nexttime; }
reject_on { UpdateLocation(); return TK_reject_on; }
restrict { UpdateLocation(); return TK_restrict; }
s_always { UpdateLocation(); return TK_s_always; }
s_eventually { UpdateLocation(); return TK_s_eventually; }
s_nexttime { UpdateLocation(); return TK_s_nexttime; }
s_until { UpdateLocation(); return TK_s_until; }
s_until_with { UpdateLocation(); return TK_s_until_with; }
strong { UpdateLocation(); return TK_strong; }
sync_accept_on { UpdateLocation(); return TK_sync_accept_on; }
sync_reject_on { UpdateLocation(); return TK_sync_reject_on; }
unique0 { UpdateLocation(); return TK_unique0; }
until { UpdateLocation(); return TK_until; }
until_with { UpdateLocation(); return TK_until_with; }
untyped { UpdateLocation(); return TK_untyped; }
weak { UpdateLocation(); return TK_weak; }
implements { UpdateLocation(); return TK_implements; }
interconnect { UpdateLocation(); return TK_interconnect; }
nettype { UpdateLocation(); return TK_nettype; }
soft { UpdateLocation(); return TK_soft; }
above { UpdateLocation(); return TK_above; } /* Verilog-AMS */
abs { UpdateLocation(); return TK_abs; }
absdelay { UpdateLocation(); return TK_absdelay; }
abstol { UpdateLocation(); return TK_abstol; } /* Verilog-AMS */
access { UpdateLocation(); return TK_access; } /* Verilog-AMS */
acos { UpdateLocation(); return TK_acos; }
acosh { UpdateLocation(); return TK_acosh; }
ac_stim { UpdateLocation(); return TK_ac_stim; }
aliasparam { UpdateLocation(); return TK_aliasparam; }
analog { UpdateLocation(); return TK_analog; } /* Verilog-AMS */
analysis { UpdateLocation(); return TK_analysis; }
asin { UpdateLocation(); return TK_asin; }
asinh { UpdateLocation(); return TK_asinh; }
atan { UpdateLocation(); return TK_atan; }
atan2 { UpdateLocation(); return TK_atan2; }
atanh { UpdateLocation(); return TK_atanh; }
branch { UpdateLocation(); return TK_branch; } /* Verilog-AMS */
ceil { UpdateLocation(); return TK_ceil; }
connect { UpdateLocation(); return TK_connect; } /* Verilog-AMS */
connectmodule { UpdateLocation(); return TK_connectmodule; }
connectrules { UpdateLocation(); return TK_connectrules; }
continuous { UpdateLocation(); return TK_continuous; }
cos { UpdateLocation(); return TK_cos; }
cosh { UpdateLocation(); return TK_cosh; }
ddt { UpdateLocation(); return TK_ddt; }
ddt_nature { UpdateLocation(); return TK_ddt_nature; } /* Verilog-AMS */
ddx { UpdateLocation(); return TK_ddx; }
discipline { /* Verilog-AMS */
UpdateLocation();
yy_push_state(DISCIPLINE);
return TK_discipline;
}
discrete { UpdateLocation(); return TK_discrete; } /* Verilog-AMS */
<DISCIPLINE>domain { UpdateLocation(); return TK_domain; }
domain { UpdateLocation(); return SymbolIdentifier; }
driver_update { UpdateLocation(); return TK_driver_update; }
endconnectrules { UpdateLocation(); return TK_endconnectrules; }
enddiscipline { /* Verilog-AMS */
UpdateLocation();
yy_safe_pop_state();
return TK_enddiscipline;
}
endnature { UpdateLocation(); return TK_endnature; } /* Verilog-AMS */
endparamset { UpdateLocation(); return TK_endparamset; }
exclude { UpdateLocation(); return TK_exclude; } /* Verilog-AMS */
exp { UpdateLocation(); return TK_exp; }
final_step { UpdateLocation(); return TK_final_step; } /* Verilog-AMS */
flicker_noise { UpdateLocation(); return TK_flicker_noise; }
floor { UpdateLocation(); return TK_floor; }
flow { UpdateLocation(); return TK_flow; } /* Verilog-AMS */
from { UpdateLocation(); return TK_from; } /* Verilog-AMS */
ground { UpdateLocation(); return TK_ground; } /* Verilog-AMS */
hypot { UpdateLocation(); return TK_hypot; }
idt { UpdateLocation(); return TK_idt; }
idtmod { UpdateLocation(); return TK_idtmod; }
idt_nature { UpdateLocation(); return TK_idt_nature; } /* Verilog-AMS */
inf { UpdateLocation(); return TK_inf; }
infinite { UpdateLocation(); return TK_infinite; } /* `default_decay_time */
initial_step { UpdateLocation(); return TK_initial_step; } /* Verilog-AMS */
laplace_nd { UpdateLocation(); return TK_laplace_nd; }
laplace_np { UpdateLocation(); return TK_laplace_np; }
laplace_zd { UpdateLocation(); return TK_laplace_zd; }
laplace_zp { UpdateLocation(); return TK_laplace_zp; }
last_crossing { UpdateLocation(); return TK_last_crossing; }
limexp { UpdateLocation(); return TK_limexp; }
ln { UpdateLocation(); return TK_ln; }
log { UpdateLocation(); return TK_log; }
<AFTER_DOT>max { UpdateLocation(); yy_pop_state(); return TK_max; }
merged { UpdateLocation(); return TK_merged; }
<AFTER_DOT>min { UpdateLocation(); yy_pop_state(); return TK_min; }
nature { UpdateLocation(); return TK_nature; } /* Verilog-AMS */
net_resolution { UpdateLocation(); return TK_net_resolution; }
noise_table { UpdateLocation(); return TK_noise_table; }
paramset { UpdateLocation(); return TK_paramset; }
potential { UpdateLocation(); return TK_potential; } /* Verilog-AMS */
pow { UpdateLocation(); return TK_pow; }
resolveto { UpdateLocation(); return TK_resolveto; }
sin { UpdateLocation(); return TK_sin; }
sinh { UpdateLocation(); return TK_sinh; }
slew { UpdateLocation(); return TK_slew; } /* Verilog-AMS */
split { UpdateLocation(); return TK_split; }
sqrt { UpdateLocation(); return TK_sqrt; }
tan { UpdateLocation(); return TK_tan; }
tanh { UpdateLocation(); return TK_tanh; }
timer { UpdateLocation(); return TK_timer; } /* Verilog-AMS */
transition { UpdateLocation(); return TK_transition; }
units { UpdateLocation(); return TK_units; } /* Verilog-AMS */
white_noise { UpdateLocation(); return TK_white_noise; }
wreal { UpdateLocation(); return TK_wreal; }
zi_nd { UpdateLocation(); return TK_zi_nd; }
zi_np { UpdateLocation(); return TK_zi_np; }
zi_zd { UpdateLocation(); return TK_zi_zd; }
zi_zp { UpdateLocation(); return TK_zi_zp; }
/* Operators */
".*" { UpdateLocation(); return TK_DOTSTAR; }
"<<" { UpdateLocation(); return TK_LS; }
"<<<" { UpdateLocation(); return TK_LS; }
">>" { UpdateLocation(); return TK_RS; }
">>>" { UpdateLocation(); return TK_RSS; }
"**" { UpdateLocation(); return TK_POW; }
"<=" { UpdateLocation(); return TK_LE; }
">=" { UpdateLocation(); return TK_GE; }
"=>" { UpdateLocation(); return TK_EG; }
"+=>"|"-=>" {
/*
* Resolve the ambiguity between the += assignment
* operator and +=> polarity edge path operator
*
* +=> should be treated as two separate tokens '+' and
* '=>' (TK_EG), therefore we only consume the first
* character of the matched pattern i.e. either + or -
* and push back the rest of the matches text (=>) in
* the input stream.
*/
yyless(1);
UpdateLocation();
return yytext[0];
}
"|->" { UpdateLocation(); return TK_PIPEARROW; }
"|=>" { UpdateLocation(); return TK_PIPEARROW2; }
"*>" { UpdateLocation(); return TK_SG; }
"==?" { UpdateLocation(); return TK_WILDCARD_EQ; }
"==" { UpdateLocation(); return TK_EQ; }
"!=?" { UpdateLocation(); return TK_WILDCARD_NE; }
"!=" { UpdateLocation(); return TK_NE; }
"===" { UpdateLocation(); return TK_CEQ; }
"!==" { UpdateLocation(); return TK_CNE; }
"||" { UpdateLocation(); return TK_LOR; }
"&&" { UpdateLocation(); return TK_LAND; }
"&&&" { UpdateLocation(); return TK_TAND; }
"~|" { UpdateLocation(); return TK_NOR; }
"~^" { UpdateLocation(); return TK_NXOR; }
"^~" { UpdateLocation(); return TK_NXOR; }
"~&" { UpdateLocation(); return TK_NAND; }
"->>" { UpdateLocation(); return TK_NONBLOCKING_TRIGGER; }
"->" { UpdateLocation(); return _TK_RARROW; }
"<->" { UpdateLocation(); return TK_LOGEQUIV; }
"+:" { UpdateLocation(); return TK_PO_POS; }
"-:" { UpdateLocation(); return TK_PO_NEG; }
"<+" { UpdateLocation(); return TK_CONTRIBUTE; }
"+=" { UpdateLocation(); return TK_PLUS_EQ; }
"-=" { UpdateLocation(); return TK_MINUS_EQ; }
"*=" { UpdateLocation(); return TK_MUL_EQ; }
"/=" { UpdateLocation(); return TK_DIV_EQ; }
"%=" { UpdateLocation(); return TK_MOD_EQ; }
"&=" { UpdateLocation(); return TK_AND_EQ; }
"|=" { UpdateLocation(); return TK_OR_EQ; }
"^=" { UpdateLocation(); return TK_XOR_EQ; }
"<<=" { UpdateLocation(); return TK_LS_EQ; }
">>=" { UpdateLocation(); return TK_RS_EQ; }
"<<<=" { UpdateLocation(); return TK_LS_EQ; }
">>>=" { UpdateLocation(); return TK_RSS_EQ; }
"++" { UpdateLocation(); return TK_INCR; }
"--" {UpdateLocation(); return TK_DECR; }
"'{" { UpdateLocation(); return TK_LP; }
"::" { UpdateLocation(); return TK_SCOPE_RES; }
":=" { UpdateLocation(); return TK_COLON_EQ; }
"://" { yyless(1); UpdateLocation(); return yytext[0]; }
":/*" { yyless(1); UpdateLocation(); return yytext[0]; }
/* Prevent ":/" from consuming the start of a comment. */
":/" { UpdateLocation(); return TK_COLON_DIV; }
"#-#" { UpdateLocation(); return TK_POUNDMINUSPOUND; }
"#=#" { UpdateLocation(); return TK_POUNDEQPOUND; }
"##" { UpdateLocation(); return TK_POUNDPOUND; }
"[*]" { UpdateLocation(); return TK_LBSTARRB; }
"[+]" { UpdateLocation(); return TK_LBPLUSRB; }
"[*" { UpdateLocation(); return TK_LBSTAR; }
"[=" { UpdateLocation(); return TK_LBEQ; }
"[->" { UpdateLocation(); return TK_LBRARROW; }
"@@" { UpdateLocation(); return TK_ATAT; }
/* Watch out for the tricky case of (*). Cannot parse this as "(*"
and ")", but since I know that this is really ( * ), replace it
with "*" and return that. */
/* TODO(fangism): see if this can be simplified without lexer states. */
{AttributesBegin} {
yy_push_state(ATTRIBUTE_START);
yymore();
}
<ATTRIBUTE_START>{Space}+ {
yymore();
}
<ATTRIBUTE_START>{LineTerminator} {
yymore();
}
<ATTRIBUTE_START>")" {
/* This is the (*) case. */
yy_pop_state();
UpdateLocation();
return '*';
}
<ATTRIBUTE_START,ATTRIBUTE_MIDDLE>{AttributesEnd} {
yy_pop_state();
UpdateLocation();
return TK_ATTRIBUTE;
}
<ATTRIBUTE_START>{AttributesContinue} {
yy_set_top_state(ATTRIBUTE_MIDDLE);
yymore();
}
<ATTRIBUTE_MIDDLE>{AttributesContent} { yymore(); }
/* Only enter the EDGES state if the next token is '[', otherwise, rewind. */
<EDGES_POSSIBLY>{
"[" { UpdateLocation(); yy_set_top_state(EDGES); return yytext[0]; }
{Space}+ { UpdateLocation(); return TK_SPACE; }
{LineTerminator} { UpdateLocation(); return TK_NEWLINE; }
{TraditionalComment} {
UpdateLocation();
return TK_COMMENT_BLOCK;
}
{EndOfLineComment} {
yyless(yyleng-1); /* return \n to input stream */
UpdateLocation();
return TK_EOL_COMMENT;
}
. { yyless(0); yy_pop_state(); }
} /* <EDGES_POSSIBLY> */
/* end EDGES state */
<EDGES>"]" { UpdateLocation(); yy_pop_state(); return yytext[0]; }
"." { UpdateLocation(); yy_push_state(AFTER_DOT); return yytext[0]; }
/* single-char tokens */
[}{;:\[\],()'#=@&!?<>%|^~+*/-] { UpdateLocation(); return yytext[0]; }
{StringLiteral} { UpdateLocation(); return TK_StringLiteral; }
{EvalStringLiteral} { UpdateLocation(); return TK_EvalStringLiteral; }
{UnterminatedStringLiteral} {
/* TODO(fangism): Is it worth returning the \n back to the input stream? */
UpdateLocation();
return TK_OTHER;
}
{UnterminatedEvalStringLiteral} {
UpdateLocation();
return TK_OTHER;
}
/* The UDP Table is a unique lexical environment. These are most
tokens that we can expect in a table. */
<UDPTABLE>\(\?0\) { UpdateLocation(); return '_'; }
<UDPTABLE>\(\?1\) { UpdateLocation(); return '+'; }
<UDPTABLE>\(\?[xX]\) { UpdateLocation(); return '%'; }
<UDPTABLE>\(\?\?\) { UpdateLocation(); return '*'; }
<UDPTABLE>\(01\) { UpdateLocation(); return 'r'; }
<UDPTABLE>\(0[xX]\) { UpdateLocation(); return 'Q'; }
<UDPTABLE>\(b[xX]\) { UpdateLocation(); return 'q'; }
<UDPTABLE>\(b0\) { UpdateLocation(); return 'f'; /* b0 is 10|00, but only 10 is meaningful */}
<UDPTABLE>\(b1\) { UpdateLocation(); return 'r'; /* b1 is 11|01, but only 01 is meaningful */}
<UDPTABLE>\(0\?\) { UpdateLocation(); return 'P'; }
<UDPTABLE>\(10\) { UpdateLocation(); return 'f'; }
<UDPTABLE>\(1[xX]\) { UpdateLocation(); return 'M'; }
<UDPTABLE>\(1\?\) { UpdateLocation(); return 'N'; }
<UDPTABLE>\([xX]0\) { UpdateLocation(); return 'F'; }
<UDPTABLE>\([xX]1\) { UpdateLocation(); return 'R'; }
<UDPTABLE>\([xX]\?\) { UpdateLocation(); return 'B'; }
<UDPTABLE>[bB] { UpdateLocation(); return 'b'; }
<UDPTABLE>[lL] { UpdateLocation(); return 'l'; /* IVL extension */ }
<UDPTABLE>[hH] { UpdateLocation(); return 'h'; /* IVL extension */ }
<UDPTABLE>[fF] { UpdateLocation(); return 'f'; }
<UDPTABLE>[rR] { UpdateLocation(); return 'r'; }
<UDPTABLE>[xX] { UpdateLocation(); return 'x'; }
<UDPTABLE>[nN] { UpdateLocation(); return 'n'; }
<UDPTABLE>[pP] { UpdateLocation(); return 'p'; }
<UDPTABLE>[\?\*\-:;] { UpdateLocation(); return yytext[0]; }
<UDPTABLE>[01]+ {
/* Return one digit at a time. */
yyless(1);
UpdateLocation();
return yytext[0];
}
<UDPTABLE>{DecNumber} {
UpdateLocation();
return TK_OTHER; /* Should reject TK_DecNumber inside UDPTABLE */
}
<EDGES>"01" { UpdateLocation(); return TK_edge_descriptor; }
<EDGES>"0x" { UpdateLocation(); return TK_edge_descriptor; }
<EDGES>"0z" { UpdateLocation(); return TK_edge_descriptor; }
<EDGES>"10" { UpdateLocation(); return TK_edge_descriptor; }
<EDGES>"1x" { UpdateLocation(); return TK_edge_descriptor; }
<EDGES>"1z" { UpdateLocation(); return TK_edge_descriptor; }
<EDGES>"x0" { UpdateLocation(); return TK_edge_descriptor; }
<EDGES>"x1" { UpdateLocation(); return TK_edge_descriptor; }
<EDGES>"z0" { UpdateLocation(); return TK_edge_descriptor; }
<EDGES>"z1" { UpdateLocation(); return TK_edge_descriptor; }
<TIMESCALE_DIRECTIVE>{
{TU}?s {
/* timescale unit, like s, ms, us, ns, ps */
UpdateLocation();
return TK_timescale_unit;
}
"/" { UpdateLocation(); return yytext[0]; }
{OrderOfMagnitude} {
UpdateLocation();
return TK_DecNumber;
}
{DecNumber}(\.{DecNumber})?{TU}?s {
UpdateLocation();
return TK_TimeLiteral;
}
{Space}+ { UpdateLocation(); return TK_SPACE; }
{LineTerminator} { UpdateLocation(); return TK_NEWLINE; }
{TraditionalComment} {
UpdateLocation();
return TK_COMMENT_BLOCK;
}
{EndOfLineComment} {
yyless(yyleng-1); /* return \n to input stream */
UpdateLocation();
return TK_EOL_COMMENT;
}
/* any other tokens, return to previous state */
. { yyless(0); yy_pop_state(); }
} /* <TIMESCALE_DIRECTIVE> */
{Identifier} {
UpdateLocation();
/* The original reference lexer looked up identifiers in the symbol table
* to return an enumeral subtype of identifier (param, type, function),
* which implemented essentially a context-sensitive grammar,
* however, for outline generation, we just return a catch-all
* vanilla identifier.
*/
return SymbolIdentifier;
}
{EscapedIdentifier} {
UpdateLocation();
return EscapedIdentifier;
}
/* All other $identifiers: */
{SystemTFIdentifier} { UpdateLocation(); return SystemTFIdentifier; }
{DecBase} {
UpdateLocation();
yy_push_state(DEC_BASE);
return TK_DecBase;
}
<DEC_BASE>{
{DecNumber} {
UpdateLocation();
yy_pop_state();
return TK_DecDigits;
}
{XZDigits} {
UpdateLocation();
yy_pop_state();
return TK_XZDigits;
}
{Space}+ { UpdateLocation(); return TK_SPACE; }
{LineTerminator} { UpdateLocation(); return TK_NEWLINE; }
/* any other tokens, return to previous state */
. { yyless(0); yy_pop_state(); }
}
{BinBase} {
UpdateLocation();
yy_push_state(BIN_BASE);
return TK_BinBase;
}
<BIN_BASE>{
{BinDigits} {
UpdateLocation();
yy_pop_state();
return TK_BinDigits;
}
{Space}+ { UpdateLocation(); return TK_SPACE; }
{LineTerminator} { UpdateLocation(); return TK_NEWLINE; }
/* any other tokens, return to previous state */
. { yyless(0); yy_pop_state(); }
}
{OctBase} {
UpdateLocation();
yy_push_state(OCT_BASE);
return TK_OctBase;
}
<OCT_BASE>{
{OctDigits} {
UpdateLocation();
yy_pop_state();
return TK_OctDigits;
}
{Space}+ { UpdateLocation(); return TK_SPACE; }
{LineTerminator} { UpdateLocation(); return TK_NEWLINE; }
/* any other tokens, return to previous state */
. { yyless(0); yy_pop_state(); }
}
{HexBase} {
UpdateLocation();
yy_push_state(HEX_BASE);
return TK_HexBase;
}
<HEX_BASE>{
{HexDigits} {
UpdateLocation();
yy_pop_state();
return TK_HexDigits;
}
{Space}+ { UpdateLocation(); return TK_SPACE; }
{LineTerminator} { UpdateLocation(); return TK_NEWLINE; }
/* any other tokens, return to previous state */
. { yyless(0); yy_pop_state(); }
}
{UnbasedNumber} { UpdateLocation(); return TK_UnBasedNumber; }
/* Decimal numbers are the usual. But watch out for the UDPTABLE
mode, where there are no decimal numbers. Reject the match if we
are in the UDPTABLE state.
Use of the REJECT macro causes flex to emit code that calls
YY_FATAL_ERROR in an infinite loop, via an internal preprocessor
macro named YY_USES_REJECT. Thus, we don't catch it here, but let
the parser reject it. [b/20249425]
*/
{DecNumber} {
UpdateLocation();
return TK_DecNumber;
}
/* This rule handles scaled time values for SystemVerilog. */
{DecNumber}(\.{DecNumber})?{TU}?s { UpdateLocation(); return TK_TimeLiteral; }
/* There may be contexts where a space is allowed before the unit. */
/* These rules handle the scaled real literals from Verilog-AMS. The
value is a number with a single letter scale factor. If
verilog-ams is not enabled, then reject this rule. If it is
enabled, then collect the scale and use it to scale the value. */
{DecNumber}\.{DecNumber}/{S} {
yy_push_state(REAL_SCALE);
yymore();
}
{DecNumber}/{S} {
yy_push_state(REAL_SCALE);
yymore();
}
<REAL_SCALE>{S} {
UpdateLocation();
yy_pop_state();
return TK_RealTime;
}
{DecNumber}\.{DecNumber}([Ee][+-]?{DecNumber})? {
UpdateLocation();
return TK_RealTime;
}
{DecNumber}[Ee][+-]?{DecNumber} {
UpdateLocation();
return TK_RealTime;
}
<IGNORE_REST_OF_LINE>{RestOfLine} {
yyless(yyleng -1); /* return \n to input stream */
UpdateLocation();
yy_pop_state();
/* ignore */
}
`timescale {
UpdateLocation();
yy_push_state(TIMESCALE_DIRECTIVE);
return DR_timescale;
}
`celldefine { UpdateLocation(); return DR_celldefine; }
`endcelldefine { UpdateLocation(); return DR_endcelldefine; }
`resetall { UpdateLocation(); return DR_resetall; }
`unconnected_drive { UpdateLocation(); return DR_unconnected_drive; }
`nounconnected_drive { UpdateLocation(); return DR_nounconnected_drive; }
/* From 1364-2005 Chapter 19. */
`pragma {
UpdateLocation();
yy_push_state(IGNORE_REST_OF_LINE);
return DR_pragma;
}
/* From 1364-2005 Annex D. */
`default_decay_time { UpdateLocation(); return DR_default_decay_time; }
`default_trireg_strength { UpdateLocation(); return DR_default_trireg_strength; }
`delay_mode_distributed { UpdateLocation(); return DR_delay_mode_distributed; }
`delay_mode_path { UpdateLocation(); return DR_delay_mode_path; }
`delay_mode_unit { UpdateLocation(); return DR_delay_mode_unit; }
`delay_mode_zero { UpdateLocation(); return DR_delay_mode_zero; }
/* From other places, e.g. Verilog-XL. */
`disable_portfaults { UpdateLocation(); return DR_disable_portfaults; }
`enable_portfaults { UpdateLocation(); return DR_enable_portfaults; }
`endprotect { UpdateLocation(); return DR_endprotect; }
`nosuppress_faults { UpdateLocation(); return DR_nosuppress_faults; }
`protect { UpdateLocation(); return DR_protect; }
`suppress_faults { UpdateLocation(); return DR_suppress_faults; }
`uselib {
UpdateLocation();
yy_push_state(IGNORE_REST_OF_LINE);
return DR_uselib;
}
`begin_keywords { UpdateLocation(); return DR_begin_keywords; }
`end_keywords { UpdateLocation(); return DR_end_keywords; }
`default_nettype { UpdateLocation(); return DR_default_nettype; }
/* This lexer is intended for a parser that accepts *un-preprocessed* source. */
`define { UpdateLocation(); yy_push_state(PP_EXPECT_DEF_ID); return PP_define; }
/* TODO(fangism): store definition body token sequences
* to enable preprocessing.
*/
/* In the PP_BETWEEN_ID_AND_BODY state, ignore ignore spaces before
* macro definition body/contents.
*/
<PP_BETWEEN_ID_AND_BODY>{
{Space}+ {
UpdateLocation();
return TK_SPACE;
}
.|{LineTerminator} {
yyless(0); /* return any other character to stream */
UpdateLocation();
yy_set_top_state(PP_CONSUME_BODY);
}
} /* PP_BETWEEN_ID_AND_BODY */
/* In the PP_CONSUME_BODY state, ignore text until end of non-continued line. */
<PP_CONSUME_BODY>{
/* MacroDefinitionBody is effectively: {ContinuedLine}*{DiscontinuedLine} */
{ContinuedLine} {
/* If code abruptly terminates (EOF) after a line continuation,
* just return accumulated text. Fixes b/37984133. */
if (YY_CURRENT_BUFFER->yy_buffer_status == YY_BUFFER_EOF_PENDING) {
yyless(yyleng-1); /* return \n to input stream */
UpdateLocation();
yy_pop_state();
return PP_define_body;
}
yymore();
}
{DiscontinuedLine} {
yyless(yyleng-1); /* return \n to input stream */
UpdateLocation();
yy_pop_state();
/* Return a dummy token so the Location range of the definition (@$) spans
* the (ignored) definition body (in the parser).
*/
return PP_define_body;
}
{InputCharacter}* {
/* This case matches when a line does not end with a continuation or \n. */
yymore();
}
<<EOF>> {
UpdateLocationEOF(); /* return \0 to input stream */
yy_pop_state();
return PP_define_body;
}
}
`else { UpdateLocation(); return PP_else; }
`elsif { UpdateLocation(); yy_push_state(PP_EXPECT_IF_ID); return PP_elsif; }
`endif { UpdateLocation(); return PP_endif; }
`ifdef { UpdateLocation(); yy_push_state(PP_EXPECT_IF_ID); return PP_ifdef; }
`ifndef { UpdateLocation(); yy_push_state(PP_EXPECT_IF_ID); return PP_ifndef; }
`include { UpdateLocation(); return PP_include; }
`undef { UpdateLocation(); yy_push_state(PP_EXPECT_IF_ID); return PP_undef; }
<PP_EXPECT_IF_ID>{
{Space}+ { UpdateLocation(); return TK_SPACE; }
{TraditionalComment} {
UpdateLocation();
return TK_COMMENT_BLOCK;
}
{EndOfLineComment} {
yyless(yyleng-1); /* return \n to input stream */
UpdateLocation();
return TK_EOL_COMMENT;
}
{BasicIdentifier} {
UpdateLocation();
yy_pop_state();
return PP_Identifier;
}
.|{LineTerminator} {
/* Return to previous state and re-lex. */
yyless(0);
yy_pop_state();
UpdateLocation();
}
} /* <PP_EXPECT_IF_ID> */
<PP_EXPECT_DEF_ID>{
{Space}+ { UpdateLocation(); return TK_SPACE; }
{LineTerminator} { UpdateLocation(); return TK_NEWLINE; }
{BasicIdentifier}"(" {
/* When open paren immediately follows the ID, expect formal parameters. */
yyless(yyleng-1); /* return '(' to stream */
UpdateLocation();
yy_set_top_state(PP_MACRO_FORMALS);
return PP_Identifier;
}
{BasicIdentifier} {
UpdateLocation();
/* ignore spaces that may follow */
yy_set_top_state(PP_BETWEEN_ID_AND_BODY);
return PP_Identifier;
}
} /* <PP_EXPECT_DEF_ID> */
<PP_MACRO_FORMALS>{
/* ignores trailing spaces */
{Space}+ { UpdateLocation(); return TK_SPACE; }
{LineTerminator} { UpdateLocation(); return TK_NEWLINE; }
"(" {
++balance_;
UpdateLocation();
return yytext[0];
}
")" {
--balance_;
UpdateLocation();
if (balance_ == 0) {
/* ignore spaces that may follow */
yy_set_top_state(PP_BETWEEN_ID_AND_BODY);
}
return yytext[0];
}
"," { UpdateLocation(); return yytext[0]; }
{BasicIdentifier} {
UpdateLocation();
return PP_Identifier;
}
= {
macro_arg_length_ = 0;
yy_push_state(PP_MACRO_DEFAULT);
yy_push_state(CONSUME_NEXT_SPACES); /* ignore leading space */
UpdateLocation();
/* balance_ == 1 */
return yytext[0];
}
} /* PP_MACRO_FORMALS */
/* The LRM permits empty default parameter value after the =. */
<PP_MACRO_DEFAULT>{
{Space}+ { /* don't know yet if this is a trailing space */ yymore(); }
{LineTerminator} { /* don't know yet if this is a trailing \n */ yymore(); }
[^,(){}" \n\r]+ {
yymore();
macro_arg_length_ = yyleng;
}
"("|"{" {
++balance_;
yymore();
macro_arg_length_ = yyleng;
}
")"|"}" {
if (balance_ == 1) {
/* defer balance_ adjustment to PP_MACRO_FORMALS state */
yyless(macro_arg_length_);
UpdateLocation();
yy_pop_state(); /* back to PP_MACRO_FORMALS, which will ignore spaces */
return PP_default_text;
} else {
--balance_;
yymore();
macro_arg_length_ = yyleng;
}
}
, {
if (balance_ == 1) {
yyless(macro_arg_length_);
UpdateLocation();
yy_pop_state(); /* back to PP_MACRO_FORMALS, which will ignore spaces */
return PP_default_text;
} else {
yymore();
macro_arg_length_ = yyleng;
}
}
{StringLiteral} {
yymore();
macro_arg_length_ = yyleng;
}
/* Do macro default values need {EvalStringLiteral}? */
} /* <PP_MACRO_DEFAULT> */
<MACRO_CALL_EXPECT_OPEN>{
{Space}+ {
UpdateLocation();
return TK_SPACE;
}
"(" {
UpdateLocation();
yy_set_top_state(MACRO_CALL_ARGS);
yy_push_state(MACRO_ARG_IGNORE_LEADING_SPACE);
return yytext[0];
}
}
<MACRO_CALL_ARGS>{
, {
UpdateLocation();
yy_push_state(MACRO_ARG_IGNORE_LEADING_SPACE);
return yytext[0];
}
")"{IgnoreToEndOfLine} {
// let trailing comments spaces be handled by default lexer state
yyless(1);
UpdateLocation();
yy_pop_state();
return MacroCallCloseToEndLine;
}
")" {
UpdateLocation();
yy_pop_state();
return yytext[0];
}
} /* <MACRO_CALL_ARGS> */
<MACRO_ARG_IGNORE_LEADING_SPACE>{
/* Ignore leading space before macro arguments. */
{Space}+ { UpdateLocation(); return TK_SPACE; }
{LineTerminator} { UpdateLocation(); return TK_NEWLINE; }
/* We intentionally defer comment-lexing until macro argument expansion. */
. {
yyless(0);
UpdateLocation();
yy_set_top_state(MACRO_ARG_UNLEXED);
macro_arg_length_ = 0;
}
} /* <MACRO_ARG_IGNORE_LEADING_SPACE> */
<MACRO_ARG_UNLEXED>{
/* Accumulate text until next , or ) (balanced). */
/* At this point, we do not know if this is a trailing space to be removed.
* Keep track of macro_arg_length_ track the position of the last non-space
* character, so that we can pass it to yyless() to backtrack.
*/
{Space}+ { yymore(); }
{LineTerminator} { yymore(); }
{Comment} { macro_arg_length_ = yyleng; yymore(); }
{UnterminatedComment} {
macro_arg_length_ = yyleng;
UpdateLocation();
return TK_OTHER;
}
{StringLiteral} { macro_arg_length_ = yyleng; yymore(); }
{EvalStringLiteral} { macro_arg_length_ = yyleng; yymore(); }
/* [^(){},"]+ { yymore(); } */
{UnterminatedStringLiteral} {
macro_arg_length_ = yyleng;
UpdateLocation();
return TK_OTHER;
}
"{" { macro_arg_length_ = yyleng; yymore(); ++balance_; }
"}" { macro_arg_length_ = yyleng; yymore(); --balance_; }
/* TODO(fangism): check that unlexed text is balanced.
* If it is not, return some error token.
*/
"(" { macro_arg_length_ = yyleng; yymore(); ++balance_; }
")" {
if (balance_ == 0) {
/* Pass this to previous start condition. */
/* Return ')' to input buffer, and rollback to the last non-space
* position in the yytext buffer (before this ')').
*/
yyless(macro_arg_length_);
UpdateLocation();
yy_set_top_state(CONSUME_NEXT_SPACES);
if (yyleng > 0) {
/* Return as an argument only if there was any non-whitespace text. */
return MacroArg;
}
} else {
macro_arg_length_ = yyleng;
yymore();
--balance_;
}
}
, {
if (balance_ == 0) {
/* Pass this to previous start condition. */
/* Return ',' to input buffer, and rollback to the last non-space
* position in the yytext buffer (before this ',').
*/
yyless(macro_arg_length_);
UpdateLocation();
yy_set_top_state(CONSUME_NEXT_SPACES);
if (yyleng > 0) {
/* Return as an argument only if there was any non-whitespace text. */
return MacroArg;
}
} else {
macro_arg_length_ = yyleng;
yymore();
}
}
. {
/* catch-all in this start-condition */
macro_arg_length_ = yyleng;
yymore();
}
} /* <MACRO_ARG_UNLEXED> */
<CONSUME_NEXT_SPACES>{
{Space}+ { UpdateLocation(); return TK_SPACE; }
{LineTerminator} { UpdateLocation(); return TK_NEWLINE; }
. {
/* Defer to previous state on stack. */
yyless(0);
UpdateLocation();
yy_pop_state();
}
} /* <CONSUME_NEXT_SPACES> */
/* To prevent matching other `directives, this pattern must appear last. */
{MacroIdentifier} {
/* If this text runs up to an EOF, handle it here,
* rather than enter other state. Fixes b/37984133. */
if (YY_CURRENT_BUFFER->yy_buffer_status == YY_BUFFER_EOF_PENDING) {
UpdateLocation();
return MacroIdentifier;
}
macro_id_length_ = yyleng; /* save position of macro-id */
yymore();
yy_push_state(POST_MACRO_ID);
}
/* Macro identifiers on their own line are treated as MacroIdItem. */
<POST_MACRO_ID>{
{IgnoreToEndOfLine} {
yyless(macro_id_length_);
UpdateLocation();
yy_pop_state();
return MacroIdItem;
}
{Space}*{AnyBase} {
/* Treat `MACRO '{base}{number} as a constant width. */
yyless(macro_id_length_);
UpdateLocation();
yy_pop_state();
return MacroNumericWidth;
}
/* Macro calls are treated as a special token that can serve as a placeholder
* for statements or expressions. */
{Space}*"(" {
/* Interpret as macro-call.
* Macro calls can be nested, but we don't need a stack of balance_
* because the macro argument text is not lexed here, even if it contains
* more macro calls. Their expansion must be deferred.
*/
balance_ = 0;
yyless(macro_id_length_);
UpdateLocation();
yy_set_top_state(MACRO_CALL_EXPECT_OPEN);
return MacroCallId;
}
. {
/* Treat other macro identifiers like plain identifiers. */
yyless(macro_id_length_);
UpdateLocation();
yy_pop_state();
return MacroIdentifier;
}
} /* <POST_MACRO_ID> */
<AFTER_DOT>{
{Identifier} {
UpdateLocation();
yy_pop_state();
return SymbolIdentifier;
}
{EscapedIdentifier} {
UpdateLocation();
yy_pop_state();
return EscapedIdentifier;
}
{Space}+ { UpdateLocation(); return TK_SPACE; }
{LineTerminator} { UpdateLocation(); return TK_NEWLINE; }
{TraditionalComment} {
UpdateLocation();
return TK_COMMENT_BLOCK;
}
{EndOfLineComment} {
yyless(yyleng-1); /* return \n to input stream */
UpdateLocation();
return TK_EOL_COMMENT;
}
. {
yyless(0);
yy_pop_state();
}
} /* <AFTER_DOT> */
<LIBRARY_EXPECT_ID>{
{Identifier} {
UpdateLocation();
yy_set_top_state(LIBRARY_FILEPATHS);
return SymbolIdentifier;
}
{Space}+ { UpdateLocation(); return TK_SPACE; }
{LineTerminator} { UpdateLocation(); return TK_NEWLINE; }
{TraditionalComment} {
UpdateLocation();
return TK_COMMENT_BLOCK;
}
{EndOfLineComment} {
yyless(yyleng-1); /* return \n to input stream */
UpdateLocation();
return TK_EOL_COMMENT;
}
. {
yyless(0);
yy_pop_state();
}
}
<LIBRARY_FILEPATHS>{
{FilePath} {
UpdateLocation();
return TK_FILEPATH;
}
, { UpdateLocation(); return ','; }
{Space}+ { UpdateLocation(); return TK_SPACE; }
{LineTerminator} { UpdateLocation(); return TK_NEWLINE; }
/* Don't support comments here, because
* slash-star could be interpreted as the start of a path.
*/
. {
yyless(0);
yy_pop_state();
}
}
{RejectChar} { UpdateLocation(); return TK_OTHER; }
`` {
/* Preprocessing token concatenation:
* Even though this should only be legal inside a macro definition,
* we must support the token concatenation operator here so that
* recursive lexing will work.
*/
UpdateLocation(); return PP_TOKEN_CONCAT;
}
` { UpdateLocation(); return TK_OTHER; /* tick should never be alone */ }
/* All other single-character tokens */
. { UpdateLocation(); return yytext[0]; }
{LineContinuation} {
yyless(yyleng-1); /* return \n to input stream */
UpdateLocation();
return TK_LINE_CONT;
}
{BadIdentifier} { UpdateLocation(); return TK_OTHER; }
{BadMacroIdentifier} { UpdateLocation(); return TK_OTHER; }
/* Final catchall. something got lost or mishandled. */
<*>.|\n { UpdateLocation(); return TK_OTHER; }
%%
| Lex | 5 | imphil/verible | verilog/parser/verilog.lex | [
"Apache-2.0"
] |
main() return;
| PAWN | 0 | TheFuseGamer/SampSharp | env/gamemodes/empty.pwn | [
"Apache-2.0"
] |
package jadx.core.clsp;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import jadx.core.dex.instructions.args.ArgType;
/**
* Class node in classpath graph
*/
public class ClspClass {
private final ArgType clsType;
private final int id;
private ArgType[] parents;
private Map<String, ClspMethod> methodsMap = Collections.emptyMap();
private List<ArgType> typeParameters = Collections.emptyList();
public ClspClass(ArgType clsType, int id) {
this.clsType = clsType;
this.id = id;
}
public String getName() {
return clsType.getObject();
}
public ArgType getClsType() {
return clsType;
}
public int getId() {
return id;
}
public ArgType[] getParents() {
return parents;
}
public void setParents(ArgType[] parents) {
this.parents = parents;
}
public Map<String, ClspMethod> getMethodsMap() {
return methodsMap;
}
public List<ClspMethod> getSortedMethodsList() {
List<ClspMethod> list = new ArrayList<>(methodsMap.size());
list.addAll(methodsMap.values());
Collections.sort(list);
return list;
}
public void setMethodsMap(Map<String, ClspMethod> methodsMap) {
this.methodsMap = Objects.requireNonNull(methodsMap);
}
public void setMethods(List<ClspMethod> methods) {
Map<String, ClspMethod> map = new HashMap<>(methods.size());
for (ClspMethod mth : methods) {
map.put(mth.getMethodInfo().getShortId(), mth);
}
setMethodsMap(map);
}
public List<ArgType> getTypeParameters() {
return typeParameters;
}
public void setTypeParameters(List<ArgType> typeParameters) {
this.typeParameters = typeParameters;
}
@Override
public int hashCode() {
return clsType.hashCode();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ClspClass nClass = (ClspClass) o;
return clsType.equals(nClass.clsType);
}
@Override
public String toString() {
return clsType.toString();
}
}
| Java | 4 | mazhidong/jadx | jadx-core/src/main/java/jadx/core/clsp/ClspClass.java | [
"Apache-2.0"
] |
[[import autoload from require "lapis.util"
autoload "models"
]]
| MoonScript | 1 | tommy-mor/lapis | lapis/cmd/templates/models.moon | [
"MIT",
"Unlicense"
] |
BX2_newJ^K8?q
@ | PureBasic | 0 | pchandrasekaran1595/onnx | onnx/backend/test/data/node/test_momentum_multiple/test_data_set_0/output_1.pb | [
"Apache-2.0"
] |
<html><body><div sec:authentication="name"></div></body></html>
| HTML | 1 | Martin-real/spring-boot-2.1.0.RELEASE | spring-boot-project/spring-boot-autoconfigure/src/test/resources/templates/security-dialect.html | [
"Apache-2.0"
] |
#pragma TextEncoding = "UTF-8"
#pragma rtGlobals=3
#pragma ModuleName=SIDAMConfig
#ifndef SIDAMshowProc
#pragma hide = 1
#endif
#include "SIDAM_Utilities_misc"
// Return keys of a table as a list
Function/S SIDAMConfigKeys(String tableName)
Variable refNum
Open/R/Z refNum as SIDAMConfigPath(0)
proceedToTable(refNum, tableName)
String listStr = "", buffer
do
FReadLine refNum, buffer
removeReturn(buffer)
if (!strlen(buffer)) // EOF, empty line
break
elseif (GrepString(buffer, "^\[.*?\]")) // next table
break
endif
removeComment(buffer)
if (strlen(buffer))
listStr += keyFromLine(buffer) + ";"
endif
while (1)
Close refNum
return listStr
End
// Return contents of a table as a key:value; list
Function/S SIDAMConfigItems(String tableName, [int usespecial])
usespecial = ParamIsDefault(usespecial) ? 0 : usespecial
String listsep = SelectString(usespecial, ";", SIDAM_CHAR_ITEMSEP)
String keysep = SelectString(usespecial, ":", SIDAM_CHAR_KEYSEP)
Variable refNum
Open/R/Z refNum as SIDAMConfigPath(0)
proceedToTable(refNum, tableName)
String listStr = "", buffer
do
FReadLine refNum, buffer
removeReturn(buffer)
if (!strlen(buffer)) // EOF, empty line
break
elseif (GrepString(buffer, "^\[.*?\]")) // next table
break
endif
removeComment(buffer)
if (strlen(buffer))
listStr += keyFromLine(buffer) + keysep + stringFromLine(buffer) + listsep
endif
while (1)
Close refNum
return listStr
End
Static Function removeReturn(String &buffer)
buffer = RemoveEnding(RemoveEnding(buffer, num2char(10)), num2char(13))
End
// Return a path to the config file (mode=0) or a folder containing
// the config file (mode=1)
//
// The config file is searched in the following order.
// 1. User Procedures:SIDAM.toml
// 2. User Procedures:SIDAM:SIDAM.toml
// 3. User Procedures:SIDAM:SIDAM.default.toml
Function/S SIDAMConfigPath(int mode)
Variable refNum
String path
path = SpecialDirPath("Igor Pro User Files", 0, 0, 0) \
+ "User Procedures:"
if (isConfigExist(path+SIDAM_FILE_CONFIG))
return path + SelectString(mode, SIDAM_FILE_CONFIG, "")
endif
path = SIDAMPath()
if (isConfigExist(path+SIDAM_FILE_CONFIG))
return path + SelectString(mode, SIDAM_FILE_CONFIG, "")
elseif (isConfigExist(path+SIDAM_FILE_CONFIG_DEFAULT))
return path + SelectString(mode, SIDAM_FILE_CONFIG_DEFAULT, "")
endif
Abort "The config file not found."
End
Static Function isConfigExist(String path)
Variable refNum
Open/R/Z refNum as path
if (V_flag)
return 0
else
Close refNum
return 1
endif
End
// Write configuration as constants
Function SIDAMConfigToProc(Variable refNum)
fprintf refNum, "StrConstant SIDAM_CTAB = \"%s\"\n", SIDAMConfigKeys("[ctab]")
fprintf refNum, "StrConstant SIDAM_CTAB_PATH = \"%s\"\n", SIDAMConfigItems("[ctab]", usespecial=1)
fprintf refNum, "StrConstant SIDAM_LOADER_FUNCTIONS = \"%s\"\n", SIDAMConfigItems("[loader.functions]")
String items = SIDAMConfigItems("[window]")
fprintf refNum, "StrConstant SIDAM_WINDOW_WIDTH = \"%s\"\n", StringByKey("width", items)
fprintf refNum, "StrConstant SIDAM_WINDOW_HEIGHT = \"%s\"\n", StringByKey("height", items)
items = SIDAMConfigItems("[window.format]")
fprintf refNum, "StrConstant SIDAM_WINDOW_FORMAT_XY = \"%s\"\n", StringByKey("xy", items)
fprintf refNum, "StrConstant SIDAM_WINDOW_FORMAT_Z = \"%s\"\n", StringByKey("z", items)
fprintf refNum, "Constant SIDAM_WINDOW_FORMAT_SHOWUNIT = %d\n", NumberByKey("show_units", items)
items = SIDAMConfigItems("[window.colors]")
Wave vw = arrayFromValue(StringByKey("line", items))
fprintf refNum, "Constant SIDAM_WINDOW_LINE_R = %d\n", vw[0]
fprintf refNum, "Constant SIDAM_WINDOW_LINE_G = %d\n", vw[1]
fprintf refNum, "Constant SIDAM_WINDOW_LINE_B = %d\n", vw[2]
Wave vw = arrayFromValue(StringByKey("line2", items))
fprintf refNum, "Constant SIDAM_WINDOW_LINE2_R = %d\n", vw[0]
fprintf refNum, "Constant SIDAM_WINDOW_LINE2_G = %d\n", vw[1]
fprintf refNum, "Constant SIDAM_WINDOW_LINE2_B = %d\n", vw[2]
Wave vw = arrayFromValue(StringByKey("note", items))
fprintf refNum, "Constant SIDAM_WINDOW_NOTE_R = %d\n", vw[0]
fprintf refNum, "Constant SIDAM_WINDOW_NOTE_G = %d\n", vw[1]
fprintf refNum, "Constant SIDAM_WINDOW_NOTE_B = %d\n", vw[2]
items = SIDAMConfigItems("[window.export]")
fprintf refNum, "StrConstant SIDAM_WINDOW_EXPORT_TRANSPARENT = \"%s\"\n", StringByKey("transparent", items)
fprintf refNum, "Constant SIDAM_WINDOW_EXPORT_RESOLUTION = %d\n", NumberByKey("resolution", items)
items = SIDAMConfigItems("[nanonis]")
String nanonis_encoding = StringByKey("text_encoding", items)
if (!strlen(nanonis_encoding))
DefaultTextEncoding
nanonis_encoding = TextEncodingName(V_defaultTextEncoding, 0)
endif
fprintf refNum, "StrConstant SIDAM_NANONIS_TEXTENCODING = \"%s\"\n", nanonis_encoding
fprintf refNum, "StrConstant SIDAM_NANONIS_LENGTHUNIT = \"%s\"\n", StringByKey("length_unit", items)
fprintf refNum, "Constant SIDAM_NANONIS_LENGTHSCALE = %f\n", NumberByKey("length_scale", items)
fprintf refNum, "StrConstant SIDAM_NANONIS_CURRENTUNIT = \"%s\"\n", StringByKey("current_unit", items)
fprintf refNum, "Constant SIDAM_NANONIS_CURRENTSCALE = %f\n", NumberByKey("current_scale", items)
fprintf refNum, "StrConstant SIDAM_NANONIS_VOLTAGEUNIT = \"%s\"\n", StringByKey("voltage_unit", items)
fprintf refNum, "Constant SIDAM_NANONIS_VOLTAGESCALE = %f\n", NumberByKey("voltage_scale", items)
fprintf refNum, "StrConstant SIDAM_NANONIS_CONDUCTANCEUNIT = \"%s\"\n", StringByKey("conductance_unit", items)
fprintf refNum, "Constant SIDAM_NANONIS_CONDUCTANCESCALE = %f\n", NumberByKey("conductance_scale", items)
End
//------------------------------------------------------------------------------
// Concise parser of toml
//
// Functions in this file are supposed to be called with the module
// name like SIDAMConfig#keyFromLine().
// Functions whose name ends with "_" are intended to be used only
// in this file.
//------------------------------------------------------------------------------
Static Function/S keyFromLine(String line)
// For ease of implementation, "=" is not assumed to be included in the key.
return unsurrounding_(StringFromList(0, line, "="))
End
Static Function/S stringFromLine(String line)
// For ease of implementation, "=" is not assumed to be included in the key.
// Multi-lines are not supported.
return unsurrounding_(StringFromList(1, line, "="))
End
Static Function valueFromLine(String line)
// For ease of implementation, "=" is not assumed to be included in the key.
return str2num(StringFromList(1, line, "="))
End
Static Function/WAVE arrayFromValue(String value)
String str = unsurrounding_(value)
if (strsearch(str, "\"", 0) != -1 || strsearch(str, "'", 0) != -1)
Make/T/FREE/N=(ItemsInList(str, ",")) tw = unsurrounding_(StringFromList(p, str, ","))
return tw
else
Make/D/FREE/N=(ItemsInList(str, ",")) vw = str2num(StringFromList(p, str, ","))
return vw
endif
End
// Start from the beginning of the configuration file, and search the table
// specified by the tableName parameter.
Static Function proceedToTable(Variable refNum, String tableName)
String buffer
do
FReadLine refNum, buffer
if (!strlen(buffer)) // EOF
Close refNum
Abort "Error in finding a table ("+tableName+") in the config file."
elseif (!CmpStr(buffer, tableName+"\r"))
return 0
endif
while(1)
End
Static Function removeComment(String &str)
int i = strsearch(str, "#", 0)
str = SelectString(i == -1, str[0, i-1], str)
End
//------------------------------------------------------------------------------
Static Function/S unsurrounding_(String str)
int n = strlen(str)-1
int i0 = strsearch(str, "\"", 0), i1 = strsearch(str, "\"", n, 1)
int j0 = strsearch(str, "'", 0), j1 = strsearch(str, "'", n, 1)
int k0 = strsearch(str, "[", 0), k1 = strsearch(str, "]", n, 1)
int nosurrounding = i0 == -1 && j0 == -1 && k0 == -1
if (nosurrounding)
return removeSpace_(str)
elseif (i0 != -1 && i0 != i1)
return str[i0+1, i1-1]
elseif (j0 != -1 && j0 != j1)
return str[j0+1, j1-1]
elseif (k0 != -1 && k0 != k1)
return str[k0+1, k1-1]
else
Abort "unmatched quotations"
endif
End
Static Function/S removeSpace_(String str)
return ReplaceString(" ", str, "")
End | IGOR Pro | 4 | yuksk/SIDAM | src/SIDAM/func/SIDAM_Config.ipf | [
"MIT"
] |
--TEST--
$GLOBALS resize
--FILE--
<?php
function foo() {
for ($i = 0; $i < 100; $i++) {
$GLOBALS["A". $i] = 1; //trigger resize
}
return "ops";
}
$GLOBALS[foo()] = "ops";
?>
DONE
--EXPECT--
DONE
| PHP | 1 | thiagooak/php-src | Zend/tests/globals_005.phpt | [
"PHP-3.01"
] |
// FIR Sinc filter tests, Perry R. Cook, 10/12
// Stream of rapid impulse responses, designed
// be looked at in wave/spectral display
Impulse imp => FIR f => WvOut w => dac;
w.wavFilename("temp.wav");
1.0 => imp.gain;
4096 => f.order;
4096 :: samp => now;
4096 :: samp => now;
2.0 => f.sinc; 1.0 => imp.next;
4096 :: samp => now;
f.hpHetero(); 1.0 => imp.next;
4096 :: samp => now;
2.0 => f.sinc; 1.0 => imp.next;
f.bpHetero(0.5);
4096 :: samp => now;
8.0 => f.sinc; 1.0 => imp.next;
4096 :: samp => now;
f.hpHetero(); 1.0 => imp.next;
4096 :: samp => now;
8.0 => f.sinc; 1.0 => imp.next;
f.bpHetero(0.5);
4096 :: samp => now;
2.0 => f.sinc; 1.0 => imp.next;
4096 :: samp => now;
2.5 => f.sinc; 1.0 => imp.next;
4096 :: samp => now;
3.0 => f.sinc; 1.0 => imp.next;
4096 :: samp => now;
3.5 => f.sinc; 1.0 => imp.next;
4096 :: samp => now;
7.333 => f.sinc; 1.0 => imp.next;
4096 :: samp => now;
8.0 => f.sinc; 1.0 => imp.next;
4096 :: samp => now;
16.0 => f.sinc; 1.0 => imp.next;
4096 :: samp => now;
32.0 => f.sinc; 1.0 => imp.next;
4096 :: samp => now;
64.0 => f.sinc; 1.0 => imp.next;
4096 :: samp => now;
128.0 => f.sinc; 1.0 => imp.next;
4096 :: samp => now;
w.closeFile();
| ChucK | 3 | ccdarabundit/chugins | FIR/examples/FIRSincImpulseTests.ck | [
"MIT"
] |
#!/usr/bin/env sage
import copy
import collections
import functools
import logging
import operator
import json
import sys
# A point on a curve similar to a target prime curve (same p, a, different b) with small
# prime order n.
AttackPoint = collections.namedtuple("AttackPoint", ["b", "gx", "gy", "n"])
AttackPoint.AsStrDict = lambda self: {"b": str(int(self.b)), "gx": str(int(self.gx)), "gy": str(int(self.gy)), "n": str(int(self.n))}
# Copied from http://www.secg.org/SEC2-Ver-1.0.pdf
P224Parameters = {
"p": 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000001,
"a": 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFE,
"b": 0xB4050A850C04B3ABF54132565044B0B7D7BFD8BA270B39432355FFB4,
"Gx": 0xB70E0CBD6BB4BF7F321390B94A03C1D356C21122343280D6115C1D21,
"Gy": 0xBD376388B5F723FB4C22DFE6CD4375A05A07476444D5819985007E34,
"n": 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF16A2E0B8F03E13DD29455C5C2A3D,
}
P256Parameters = {
"p": 0xFFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF,
"a": 0xFFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC,
"b": 0x5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B,
"Gx": 0x6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296,
"Gy": 0x4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5,
"n": 0xFFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551,
}
class SecureCurve(object):
def __init__(self, params):
self.FF = FiniteField(params["p"])
self.a = self.FF(params["a"])
self.b = self.FF(params["b"])
Gx = self.FF(params["Gx"])
Gy = self.FF(params["Gy"])
assert (Gy**2 == Gx**3 + self.a * Gx + self.b)
self.EC = EllipticCurve(self.FF, [self.a, self.b])
self.G = self.EC.point([Gx, Gy])
self.params = params
# assert (params["n"] == self.G.order())
# logging.debug("Curve parameters OK")
def IsNonRepeatingPrimeFactor(n, p):
return ((n % p == 0) and (n % (p**2) != 0))
def RandomPointWithGivenOrder(EC, r):
for try_ in range(1000):
p = EC.random_point()
h = p * (EC.order() // r)
if not h.is_zero():
assert (h * r).is_zero()
return h
raise Exception("Failed to point point with order %d" % (r))
# Search for an invalid curve point, which the additional constraint
# that is has to be on P256 curve.
#
# Formally, if P256 is defined with (a, b, p) and P224 is defined with (A, B, P).
# We need to find (x, y, B') such that:
#
# (x, y) is on P256:
# (1) y^2 == x^3 + a*x + b (mod p)
#
# (x, y) is on a curve similar to P224: same (A, P), different B.
# (2) y^2 == x^3 + A*x + B' (mod P)
#
# On this curve, the point has small order.
# (3) 0 == (x,y)*q for small q, where * operation is defined over (A, B', P)
#
# Method:
# Randomize B' until the curve size is divided by a small prime,
# get a random small order point on the new curve, get random point
# on P256, and find integer solutions (x, y) that solve both (1) and
# (2) using Chinese Remainder Theorem.
#
# Inspired by https://crypto.stackexchange.com/questions/63964/intersection-of-two-elliptic-curves
#
def FindAttackPoints():
P224 = SecureCurve(P224Parameters)
P256 = SecureCurve(P256Parameters)
p = P256.params["p"]
P = P224.params["p"]
points = []
# Minimize the number of points: search for slightly large primes.
# smaller primes => less on-line work to solve ECDH over small order groups,
# => more offline work to assemble the residues (2 ** #points).
primes = set(prime_range(10000, 30000))
# Product of all points' orders
orders_prod = 1
while orders_prod < P224.params["n"]:
logging.debug("orders_prod = %d" % (orders_prod))
onP256 = P256.EC.random_point()
b = P224.FF.random_element()
EC = EllipticCurve(P224.FF, [P224.a, b])
# Don't change primes set during iteration.
new_primes = copy.copy(primes)
for q in primes:
if IsNonRepeatingPrimeFactor(EC.order(), q):
try:
onNew = RandomPointWithGivenOrder(EC, q)
logging.debug("Small order onNew: (0x%x, 0x%x)" % (onNew.xy()[0], onNew.xy()[1]))
x = crt(int(onP256.xy()[0]), int(onNew.xy()[0]), p, P)
y = crt(int(onP256.xy()[1]), int(onNew.xy()[1]), p, P)
assert(P256.EC.is_on_curve(x, y))
assert(EC.is_on_curve(x, y))
assert(not P224.EC.is_on_curve(x, y))
logging.debug("Lifted: (0x%x, 0x%x)" % (x, y))
points.append(AttackPoint(b, x, y, q))
orders_prod *= q
new_primes.remove(q)
except Exception as e:
logging.warn(e)
pass
primes = copy.copy(new_primes)
return points
# Finds small order points on P224 similar curves.
def main(argv):
logging.basicConfig(level=logging.DEBUG)
set_random_seed(0x12345)
points = FindAttackPoints()
print(json.dumps([p.AsStrDict() for p in points]))
if __name__ == "__main__":
sys.exit(main(sys.argv))
| Sage | 5 | BearerPipelineTest/google-ctf | 2021/quals/crypto-tiramisu/challenge/sage/find_attack_points.sage | [
"Apache-2.0"
] |
\section{asm/gbz80/types.h File Reference}
\label{asm/gbz80/types.h}\index{asm/gbz80/types.h@{asm/gbz80/types.h}}
Types definitions for the gb.
\subsection*{Typedefs}
\begin{CompactItemize}
\item
\label{asm/gbz80/types.h_a2}
\index{INT8@{INT8}!asm/gbz80/types.h@{asm/gbz80/types.h}}\index{asm/gbz80/types.h@{asm/gbz80/types.h}!INT8@{INT8}}
typedef char {\bf INT8}
\begin{CompactList}\small\item\em Signed eight bit.\item\end{CompactList}
\item
\label{asm/gbz80/types.h_a3}
\index{UINT8@{UINT8}!asm/gbz80/types.h@{asm/gbz80/types.h}}\index{asm/gbz80/types.h@{asm/gbz80/types.h}!UINT8@{UINT8}}
typedef unsigned char {\bf UINT8}
\begin{CompactList}\small\item\em Unsigned eight bit.\item\end{CompactList}
\item
\label{asm/gbz80/types.h_a4}
\index{INT16@{INT16}!asm/gbz80/types.h@{asm/gbz80/types.h}}\index{asm/gbz80/types.h@{asm/gbz80/types.h}!INT16@{INT16}}
typedef int {\bf INT16}
\begin{CompactList}\small\item\em Signed sixteen bit.\item\end{CompactList}
\item
\label{asm/gbz80/types.h_a5}
\index{UINT16@{UINT16}!asm/gbz80/types.h@{asm/gbz80/types.h}}\index{asm/gbz80/types.h@{asm/gbz80/types.h}!UINT16@{UINT16}}
typedef unsigned int {\bf UINT16}
\begin{CompactList}\small\item\em Unsigned sixteen bit.\item\end{CompactList}
\item
\label{asm/gbz80/types.h_a6}
\index{INT32@{INT32}!asm/gbz80/types.h@{asm/gbz80/types.h}}\index{asm/gbz80/types.h@{asm/gbz80/types.h}!INT32@{INT32}}
typedef long {\bf INT32}
\begin{CompactList}\small\item\em Signed 32 bit.\item\end{CompactList}
\item
\label{asm/gbz80/types.h_a7}
\index{UINT32@{UINT32}!asm/gbz80/types.h@{asm/gbz80/types.h}}\index{asm/gbz80/types.h@{asm/gbz80/types.h}!UINT32@{UINT32}}
typedef unsigned long {\bf UINT32}
\begin{CompactList}\small\item\em Unsigned 32 bit.\item\end{CompactList}
\item
\label{asm/gbz80/types.h_a8}
\index{size_t@{size\_\-t}!asm/gbz80/types.h@{asm/gbz80/types.h}}\index{asm/gbz80/types.h@{asm/gbz80/types.h}!size_t@{size\_\-t}}
typedef int {\bf size\_\-t}
\item
typedef {\bf UINT16} {\bf clock\_\-t}
\begin{CompactList}\small\item\em Returned from clock.\item\end{CompactList}
\end{CompactItemize}
\vspace{0.4cm}\hrule\vspace{0.2cm}
\subsection*{Detailed Description}
Types definitions for the gb.\vspace{0.4cm}\hrule\vspace{0.2cm}
\subsection*{Typedef Documentation}
\label{asm/gbz80/types.h_a9}
\index{asm/gbz80/types.h@{asm/gbz80/types.h}!clock_t@{clock\_\-t}}
\index{clock_t@{clock\_\-t}!asm/gbz80/types.h@{asm/gbz80/types.h}}
\subsection{\setlength{\rightskip}{0pt plus 5cm}typedef {\bf UINT16} clock\_\-t}
Returned from clock.
\begin{Desc}
\item[{\bf See also: }]\par
{\bf clock}() {\rm (p.~\pageref{time.h_a1})} \end{Desc}
| TeX | 4 | asiekierka/gb-studio | buildTools/win32-ia32/gbdk/doc/libc/latex/asm_gbz80_types.h.tex | [
"MIT"
] |
global function BobMap_InitTempProps
void function BobMap_InitTempProps()
{
PrecacheModel( $"models/vistas/planet_blue_sun.mdl" )
CreatePropDynamic( $"models/vistas/planet_blue_sun.mdl", GetEnt( "skybox_cam_level" ).GetOrigin(), GetEnt( "skybox_cam_level" ).GetAngles() )
} | Squirrel | 3 | GeckoEidechse/NorthstarMods | Northstar.Custom/mod/scripts/vscripts/mp/levels/mp_bob_temp_props.nut | [
"MIT"
] |
# Un mondo più realistico
Nella situazione citata, Pierino riusciva a muoversi quasi senza stancarsi o avere fame. In un mondo più realistico, ci si deve sedere e riposare di tanto in tanto, e anche nutrirsi. Si rende questo mondo più realistico, implementando le seguenti regole:
1. Spostandosi da un luogo all'altro, Pierino perde **energia** e accumula un po' di **fatica**.
2. Pierino può guadagnare più energia mangiando mele.
3. Pierino può recuperare energie riposando sotto l'albero o sull'erba (cioè camminando in una posizione nella tabola di gioco con un un albero o un prato - campo verde)
4. Pierino ha bisogno di trovare e uccidere il lupo
5. Per uccidere il lupo, Pierino deve avere determinati livelli di energia e fatica, altrimenti perde la battaglia.
## Istruzioni
Usare il notebook originale [notebook.ipynb](../notebook.ipynb) come punto di partenza per la propria soluzione.
Modificare la funzione di ricompensa in base alle regole del gioco, eseguire l'algoritmo di reinforcement learning per apprendere la migliore strategia per vincere la partita e confrontare i risultati della passeggiata aleatoria con il proprio algoritmo in termini di numero di partite vinte e perse.
> **Nota**: in questo nuovo mondo, lo stato è più complesso e oltre alla posizione umana include anche la fatica e i livelli di energia. Si può scegliere di rappresentare lo stato come una tupla (Board,energy,fatigue) - (Tavola, Energia, Fatica), o definire una classe per lo stato (si potrebbe anche volerla derivare da `Board`), o anche modificare la classe `Board` originale all'interno di [rlboard.py](../rlboard.py).
Nella propria soluzione, mantenere il codice responsabile della strategia di passeggiata aleatoria e confrontare i risultati del proprio algoritmo con la passeggiata aleatoria alla fine.
> **Nota**: potrebbe essere necessario regolare gli iperparametri per farlo funzionare, in particolare il numero di epoche. Poiché il successo del gioco (lotta contro il lupo) è un evento raro, ci si può aspettare un tempo di allenamento molto più lungo.
## Rubrica
| Criteri | Ottimo | Adeguato | Necessita miglioramento |
| -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
| | Viene presentato un notebook con la definizione delle nuove regole del mondo, l'algoritmo di Q-Learning e alcune spiegazioni testuali. Q-Learning è in grado di migliorare significativamente i risultati rispetto a random walk. | Viene presentato il notebook, viene implementato Q-Learning e migliora i risultati rispetto a random walk, ma non in modo significativo; o il notebook è scarsamente documentato e il codice non è ben strutturato | Vengono fatti alcuni tentativi di ridefinire le regole del mondo, ma l'algoritmo Q-Learning non funziona o la funzione di ricompensa non è completamente definita |
| Markdown | 3 | subramanir2143/ML-For-Beginners | 8-Reinforcement/1-QLearning/translations/assignment.it.md | [
"MIT"
] |
/**
* @param {import('jscodeshift').FileInfo} file
* @param {import('jscodeshift').API} api
*/
export default function transformer(file, api, options) {
const j = api.jscodeshift;
const root = j(file.source);
const printOptions = options.printOptions;
root.findJSXElements('Tabs').forEach(({ node }) => {
let prevScrollButtonValue;
node.openingElement.attributes.forEach((attr) => {
if (attr.name && attr.name.name === 'scrollButtons') {
if (attr.value) {
prevScrollButtonValue = attr.value.value || attr.value.expression?.value;
if (attr.value.value === 'on' || attr.value.expression?.value === 'on') {
delete attr.value;
} else if (attr.value.value === 'desktop' || attr.value.expression?.value === 'desktop') {
delete attr.value;
} else if (attr.value.value === 'off' || attr.value.expression?.value === 'off') {
attr.value = j.jsxExpressionContainer(j.literal(false));
}
}
}
});
if (prevScrollButtonValue === 'on') {
node.openingElement.attributes.push(
j.jsxAttribute(j.jsxIdentifier('allowScrollButtonsMobile')),
);
}
});
return root.toSource(printOptions);
}
| JavaScript | 5 | dany-freeman/material-ui | packages/mui-codemod/src/v5.0.0/tabs-scroll-buttons.js | [
"MIT"
] |
<div class="modal error hidden" id="modal-delete-folder" fid="">
<h2>DELETE</h2>
<p>everything in this folder will be gone <strong>forever</strong>!</p>
<b></b>
<section>
<p class="bold" id="deleting-foldername">A long foldername</p>
</section>
<progress id="deleting-folder" class="progress" value="0" max="100"></progress>
<button class="action l md bold" onclick="confirmDeleteFolder();">yes, delete</button>
<button class="action r sm" onclick="hideActiveModal();">no, wait!</button>
</div>
| Kit | 3 | pws1453/web-client | source/imports/app/docs-modal-delete-folder.kit | [
"MIT"
] |
<template>
<v-container fluid>
<v-switch v-model="switchMe">
<template v-slot:label>
Turn on the progress: <v-progress-circular
:indeterminate="switchMe"
:value="0"
size="24"
class="ml-2"
></v-progress-circular>
</template>
</v-switch>
</v-container>
</template>
<script>
export default {
data () {
return {
switchMe: false,
}
},
}
</script>
| Vue | 3 | mark-gene/vuetify | packages/docs/src/examples/v-switch/slot-label.vue | [
"MIT"
] |
"""Tests for tcp component."""
| Python | 0 | domwillcode/home-assistant | tests/components/tcp/__init__.py | [
"Apache-2.0"
] |
#+TITLE: lang/julia
#+DATE: April 8, 2020
#+SINCE: v1.3
#+STARTUP: inlineimages nofold
* Table of Contents :TOC_3:noexport:
- [[#description][Description]]
- [[#module-flags][Module Flags]]
- [[#plugins][Plugins]]
- [[#prerequisites][Prerequisites]]
- [[#language-server][Language Server]]
- [[#lsp-julia][~lsp-julia~]]
- [[#eglot-jl][~eglot-jl~]]
- [[#features][Features]]
- [[#language-server-1][Language Server]]
- [[#configuration][Configuration]]
- [[#change-the-default-environment-for-the-julia-language-server][Change the default environment for the Julia language server]]
* Description
This module adds support for [[https://julialang.org/][the Julia language]] to Doom Emacs.
+ Syntax highlighting and latex symbols from ~julia-mode~
+ REPL integration from ~julia-repl~
+ Code completion and syntax checking, requires ~:tools lsp~ and ~+lsp~
** Module Flags
+ =+lsp= Enable LSP server support.
** Plugins
+ [[https://github.com/JuliaEditorSupport/julia-emacs/][julia-mode]]
+ [[https://github.com/tpapp/julia-repl][julia-repl]]
+ =+lsp= and =:tools lsp=
+ [[https://github.com/non-jedi/lsp-julia][lsp-julia]]
+ [[https://github.com/emacs-lsp/lsp-mode][lsp]]
+ =+lsp= and =:tools lsp +eglot=
+ [[https://github.com/non-jedi/eglot-jl][eglot-jl]]
+ [[https://github.com/joaotavora/eglot][eglot]]
* Prerequisites
This module requires =julia= and an language server if =+lsp= is enabled.
** Language Server
~+lsp~ requires ~LanguageServer.jl~ and ~SymbolServer.jl~. The =lsp-julia= and
=eglot-jl= packages both come bundled with their own versions of these servers,
which is used by default. If you're happy with that, no further configuration is
necessary.
However, to use your own installation you will need to install then configure
them. To install them, execute these commands in a Julia REPL:
#+BEGIN_SRC julia
using Pkg
Pkg.add("LanguageServer")
Pkg.add("SymbolServer")
#+END_SRC
Then configure =lsp-julia= or =eglot-jl= depending on whether you have enabled
=:tools lsp= or =:tools (lsp +eglot)=, respectively:
*** ~lsp-julia~
To instruct =lsp-julia= not to use the built-in package:
#+BEGIN_SRC elisp
;; ~/.doom.d/config.el
(setq lsp-julia-package-dir nil)
#+END_SRC
To find your installation of ~LanguageServer.jl~, ~eglot-jl~ needs to know the
environment in which it is installed. This is set to v1.0 by default as it is
the current LTS:
#+BEGIN_SRC elisp
(setq lsp-julia-default-environment "~/.julia/environments/v1.0")
#+END_SRC
*** ~eglot-jl~
To find your installation of ~LanguageServer.jl~, ~eglot-jl~ must know the
environment in which it is installed. This is set to v1.0 by default as it is
the current LTS:
#+BEGIN_SRC elisp
;; ~/.doom.d/config.el
(setq eglot-jl-language-server-project "~/.julia/environments/v1.0")
#+END_SRC
But to let ~eglot-jl~ use the environment bundled with it, set it to
~eglot-jl-base~ instead:
#+BEGIN_SRC elisp
;; ~/.doom.d/config.el
(after! eglot-jl
(setq eglot-jl-language-server-project eglot-jl-base))
#+END_SRC
* Features
** Language Server
~+lsp~ adds code completion, syntax checking, formatting and other ~lsp-mode~ or
~eglot~ features. It requires ~LanguageServer.jl~, the installation of which is
described above.
* Configuration
** Change the default environment for the Julia language server
~lsp-julia~ requires a variable be set for the Julia environment. This is set to
v1.0 by default as it is the current LTS.
#+BEGIN_SRC elisp
;; ~/.doom.d/config.el
(setq lsp-julia-default-environment "~/.julia/environments/v1.0")
#+END_SRC
| Org | 4 | leezu/doom-emacs | modules/lang/julia/README.org | [
"MIT"
] |
Strict
Import "bmk_modutil.bmx"
Import "bmk_bank.bmx"
Import "bmk_modinfo.bmx"
Function Zap( path$,stream:TStream )
If Not path Return False
Local name$=StripDir( path )
Local skip=False
If name[..1]="."
skip=True
Else If name.ToLower().EndsWith( ".bak" )
skip=True
EndIf
If skip
stream.WriteLine ""
Return True
EndIf
Local mode=FileMode( path )
Select FileType(path)
Case FILETYPE_NONE
Print "Error zapping file "+path
Return
Case FILETYPE_FILE
Local size=FileSize(path)
stream.WriteLine name
stream.WriteLine mode
stream.WriteLine size
Local from_stream:TStream=ReadStream(path)
CopyBytes from_stream,stream,size
from_stream.Close
Case FILETYPE_DIR
Local dir$[]=LoadDir( path )
Local size=Len( dir )
stream.WriteLine name
stream.WriteLine -mode
stream.WriteLine size
For Local t$=EachIn dir
If Not Zap( path+"/"+t,stream ) Return
Next
End Select
Return True
End Function
Function Unzap( dir$,stream:TStream )
Local name$=stream.ReadLine()
If Not name Return True
Local mode=Int( stream.ReadLine() )
Local size=Int( stream.ReadLine() )
Local path$=dir+"/"+name
If mode<0
mode=-mode
CreateDir path
For Local k=0 Until size
If Not Unzap( path,stream ) Return
Next
Else
DeleteFile path
Local to_stream:TStream=WriteStream(path)
CopyBytes stream,to_stream,size
to_stream.Close
EndIf
SetFileMode path,mode
Return True
End Function
Function ZapMod( name$,stream:TStream )
Local path$=ModuleInterface( name,"release."+cfg_platform+"."+opt_arch )
If FileType(path)<>FILETYPE_FILE
Print "Failed to find module"
Return
EndIf
Local src:TSourceFile=ParseSourceFile( path )
stream.WriteLine "Module: "+name
For Local t$=EachIn src.info
stream.WriteLine t
Next
stream.WriteLine ""
Local bank:TBank=TBank.Create(0)
Local bank_stream:TStream=TBankStream.Create( bank )
If Not Zap( ModulePath(name),bank_stream ) Throw "Failed to publish module"
bank_stream.Close
bank=CompressBank( bank )
bank_stream=TBankStream.Create( bank )
CopyStream bank_stream,stream
bank_stream.Close
End Function
Function UnzapMod( stream:TStream )
Local modinfo:TModInfo=TModInfo.CreateFromStream( stream )
Local path$=ModulePath( modinfo.name )
If Not CreateDir( path,True ) Throw "Unable to create module directory"
DeleteDir path,True
Local bank:TBank=TBank.Create(0)
Local bank_stream:TStream=TBankStream.Create( bank )
CopyStream stream,bank_stream
bank_stream.Close
bank=UncompressBank( bank )
bank_stream=TBankStream.Create( bank )
If Not Unzap( ExtractDir(path),bank_stream )
Print "Failed to Unzap module"
Return
EndIf
bank_stream.Close
?MacOS
Ranlib path
?
Return True
End Function
| BlitzMax | 4 | jabdoa2/blitzmax | src/bmk/bmk_zap.bmx | [
"Zlib"
] |
a { padding: 0 1 0px 1px } | CSS | 1 | mengxy/swc | crates/swc_css_parser/tests/fixture/esbuild/misc/4WSp4-HbKB-f1GLF00sf6A/input.css | [
"Apache-2.0"
] |
'reach 0.1';
const Common = {
get: Fun([], Data({ None: Null, Some: UInt })),
put: Fun([UInt], Null),
};
export const main =
Reach.App(
{ },
[Participant('Alice',
{ ...Common })
],
(Alice) => {
const f = (m) => m.match({
None: 4,
Some: i => i,
});
const i = f(Maybe(UInt).Some(5));
const j = f(Maybe(UInt).None());
Alice.only(() => {
interact.put(i);
interact.put(j);
});
exit();
});
| RenderScript | 4 | chikeabuah/reach-lang | hs/t/n/match_no_closure.rsh | [
"Apache-2.0"
] |
import QtQuick 2.0
import QtQuick.Controls 1.0
import QtQuick.Layouts 1.0
TextArea {
id: logDisplay
readOnly: true
text: torInstance.logMessages.join('\n')
textFormat: TextEdit.PlainText
wrapMode: TextEdit.Wrap
Connections {
target: torInstance.process
onLogMessage: {
logDisplay.append(message)
}
}
}
| QML | 4 | garrettr/ricochet | src/ui/qml/TorLogDisplay.qml | [
"OpenSSL"
] |
---
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r, echo=FALSE, message = FALSE, warnings = FALSE}
library(tidyverse)
#df <- readr::read_rds("2019-02-17_tidy_tuesday_tweets.rds")
df <- rtweet::search_tweets("#tidytuesday", n = 18000, include_rts = FALSE)
clean_df <- df %>%
filter(is_retweet == "FALSE") %>%
filter(!str_detect(tolower(text), "tidyingup")) %>%
select(screen_name, created_at, text, pic = ext_media_url) %>%
unnest(pic) %>%
mutate(text = str_replace_all(text, '#', '`#`')) %>%
group_by(screen_name, text) %>%
mutate(row_n = paste0("pic_", row_number())) %>%
spread(row_n, pic) %>%
filter(!is.na(pic_1)) %>%
arrange(created_at) %>%
filter(!str_detect(text, "The @R4DScommunity welcomes you to week"))
keypost_df <- df %>%
filter(is_retweet == "FALSE") %>%
filter(!str_detect(tolower(text), "tidyingup")) %>%
select(screen_name, created_at, text, pic = ext_media_url) %>%
unnest(pic) %>%
mutate(text = str_replace_all(text, '#', '`#`')) %>%
group_by(screen_name, text) %>%
mutate(row_n = paste0("pic_", row_number())) %>%
spread(row_n, pic) %>%
filter(!is.na(pic_1)) %>%
arrange(created_at) %>%
filter(str_detect(text, "The @R4DScommunity welcomes you to week"))
week_num <- keypost_df %>%
pull(text) %>%
word(7, 7) %>%
as.numeric()
```
```{r, echo=FALSE, results = 'asis'}
cat(paste0("# ", "`#TidyTuesday` Tweets for week ",
week_num,
" \n\n"))
```
The `#TidyTuesday` tweets included here are ones that included at least one image, and are arranged by submission date. Many thanks to the `r nrow(clean_df)`(!) people who submitted!! This page has been autogenerated as of `r Sys.Date()` and we hope you enjoy any random "house-cleaning" tips that accidentally may make their way in!
```{r, echo=FALSE, results='asis'}
cat(paste0(" \n## This Week's Data ", " \n",
keypost_df$text, "\n\n",
case_when(is.na(keypost_df$pic_1) ~ "",
TRUE ~ paste0("\n")),
case_when(is.na(keypost_df$pic_3) ~ "",
TRUE ~ paste0("\n")),
case_when(is.na(keypost_df$pic_4) ~ "",
TRUE ~ paste0("")),
"\n\n",
"*** \n"))
```
<br>
<br>
```{r, echo = FALSE, fig.width=6, fig.height = 4, dpi = 650}
sum_df <- clean_df %>%
mutate(day = lubridate::wday(created_at, label = TRUE)) %>%
group_by(day) %>%
summarize(n = n())
sum_df %>%
ggplot(aes(day, n)) +
#geom_segment(aes(y = 0, x = )) +
geom_segment(aes(y = 0, x = day, xend = day, yend = n), color = ifelse(sum_df$day == "Tue", "blue", "black"), size = 1) +
geom_point(color = ifelse(sum_df$day == "Tue", "blue", "black"), size = 3) +
theme_minimal() +
#theme(axis.title.y = element_text(face = "bold")) +
labs(y = "Number of Tweets\n",
x = "",
caption = "Source: rtweet | By: @thomas_mock",
title = "#TidyTuesday Tweets by Day\n")
```
<br>
<br>
***
```{r, echo=FALSE, results='asis', eval = F}
for(x in length(clean_df)) {
cat(paste0(" \n## Submission by ", clean_df$screen_name ," \n",
clean_df$text, "\n\n ",
case_when(is.na(clean_df$pic_1) ~ "",
TRUE ~ paste0("\n")),
case_when(is.na(clean_df$pic_2) ~ "",
TRUE ~ paste0("\n")),
case_when(is.na(clean_df$pic_3) ~ "",
TRUE ~ paste0("\n")),
case_when(is.na(clean_df$pic_4) ~ "",
TRUE ~ paste0("")),
"\n\n",
"*** \n"))
}
```
```{r, echo = FALSE, results = 'asis'}
for(x in length(clean_df)) {
httr::GET(url = paste0("https://publish.twitter.com/oembed?url=https%3A%2F%2Ftwitter.com%2F",
clean_df$screen_name,
"%2Fstatus%2F",
clean_df$status_id)) %>%
httr::content() %>%
.[["html"]] %>%
cat(paste0(., "\n\n"))
}
```
| RMarkdown | 5 | StephRoark/tidytuesday-1 | community_resources/code_chunks/weekly_collection.rmd | [
"CC0-1.0"
] |
/*
* 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.
*/
// The java codegenerator has a few different codepaths depending
// on how many optionals the struct has; this attempts to exercise
// them.
namespace java thrift.test
struct Opt4 {
1: i32 def1;
2: i32 def2;
3: i32 def3;
4: i32 def4;
}
struct Opt13 {
1: i32 def1;
2: i32 def2;
3: i32 def3;
4: i32 def4;
5: i32 def5;
6: i32 def6;
7: i32 def7;
8: i32 def8;
9: i32 def9;
10: i32 def10;
11: i32 def11;
12: i32 def12;
13: i32 def13;
}
struct Opt30 {
1: i32 def1;
2: i32 def2;
3: i32 def3;
4: i32 def4;
5: i32 def5;
6: i32 def6;
7: i32 def7;
8: i32 def8;
9: i32 def9;
10: i32 def10;
11: i32 def11;
12: i32 def12;
13: i32 def13;
14: i32 def14;
15: i32 def15;
16: i32 def16;
17: i32 def17;
18: i32 def18;
19: i32 def19;
20: i32 def20;
21: i32 def21;
22: i32 def22;
23: i32 def23;
24: i32 def24;
25: i32 def25;
26: i32 def26;
27: i32 def27;
28: i32 def28;
29: i32 def29;
30: i32 def30;
}
struct Opt64 {
1: i32 def1;
2: i32 def2;
3: i32 def3;
4: i32 def4;
5: i32 def5;
6: i32 def6;
7: i32 def7;
8: i32 def8;
9: i32 def9;
10: i32 def10;
11: i32 def11;
12: i32 def12;
13: i32 def13;
14: i32 def14;
15: i32 def15;
16: i32 def16;
17: i32 def17;
18: i32 def18;
19: i32 def19;
20: i32 def20;
21: i32 def21;
22: i32 def22;
23: i32 def23;
24: i32 def24;
25: i32 def25;
26: i32 def26;
27: i32 def27;
28: i32 def28;
29: i32 def29;
30: i32 def30;
31: i32 def31;
32: i32 def32;
33: i32 def33;
34: i32 def34;
35: i32 def35;
36: i32 def36;
37: i32 def37;
38: i32 def38;
39: i32 def39;
40: i32 def40;
41: i32 def41;
42: i32 def42;
43: i32 def43;
44: i32 def44;
45: i32 def45;
46: i32 def46;
47: i32 def47;
48: i32 def48;
49: i32 def49;
50: i32 def50;
51: i32 def51;
52: i32 def52;
53: i32 def53;
54: i32 def54;
55: i32 def55;
56: i32 def56;
57: i32 def57;
58: i32 def58;
59: i32 def59;
60: i32 def60;
61: i32 def61;
62: i32 def62;
63: i32 def63;
64: i32 def64;
}
struct Opt80 {
1: i32 def1;
2: i32 def2;
3: i32 def3;
4: i32 def4;
5: i32 def5;
6: i32 def6;
7: i32 def7;
8: i32 def8;
9: i32 def9;
10: i32 def10;
11: i32 def11;
12: i32 def12;
13: i32 def13;
14: i32 def14;
15: i32 def15;
16: i32 def16;
17: i32 def17;
18: i32 def18;
19: i32 def19;
20: i32 def20;
21: i32 def21;
22: i32 def22;
23: i32 def23;
24: i32 def24;
25: i32 def25;
26: i32 def26;
27: i32 def27;
28: i32 def28;
29: i32 def29;
30: i32 def30;
31: i32 def31;
32: i32 def32;
33: i32 def33;
34: i32 def34;
35: i32 def35;
36: i32 def36;
37: i32 def37;
38: i32 def38;
39: i32 def39;
40: i32 def40;
41: i32 def41;
42: i32 def42;
43: i32 def43;
44: i32 def44;
45: i32 def45;
46: i32 def46;
47: i32 def47;
48: i32 def48;
49: i32 def49;
50: i32 def50;
51: i32 def51;
52: i32 def52;
53: i32 def53;
54: i32 def54;
55: i32 def55;
56: i32 def56;
57: i32 def57;
58: i32 def58;
59: i32 def59;
60: i32 def60;
61: i32 def61;
62: i32 def62;
63: i32 def63;
64: i32 def64;
65: i32 def65;
66: i32 def66;
67: i32 def67;
68: i32 def68;
69: i32 def69;
70: i32 def70;
71: i32 def71;
72: i32 def72;
73: i32 def73;
74: i32 def74;
75: i32 def75;
76: i32 def76;
77: i32 def77;
78: i32 def78;
79: i32 def79;
80: i32 def80;
}
| Thrift | 3 | Jimexist/thrift | test/ManyOptionals.thrift | [
"Apache-2.0"
] |
scriptname _Camp_LightFireFurnScript extends ObjectReference
import CampUtil
import _CampInternal
import Math
bool property is_stone auto
{ Set to TRUE if this lighting furniture is for Strike Stone. }
bool property is_flamespell auto
{ Set to TRUE if this lighting furniture is for Flame Spell. }
Actor property PlayerRef auto
GlobalVariable property _Camp_LastUsedCampfireStage auto
GlobalVariable property _Camp_PerkRank_Firecraft auto
ReferenceAlias property _Camp_PlayerAlias auto
ImpactDataSet property _Camp_SparkIDS auto
Explosion property _Camp_LightWithOilExplosion auto
static property XMarker auto
Sound property MAGCloakFireLP auto
Spell property _Camp_LightFireFXFlamesSpell auto
float old_percentage = 1.0
float total_required_seconds
float remaining_seconds
bool was_hit = false
bool in_use = false
int stone_fx_counter = 0
ObjectReference parent_campfire
ObjectReference spark_marker
int sound_id = 0
float currentX
float currentY
; Skyrim VR
Event OnInit()
if !in_use && GetCompatibilitySystem().isSkyrimVR
currentX = PlayerRef.GetPositionX()
currentY = PlayerRef.GetPositionY()
in_use = true
SetUpLightingCampfire()
AddFireLightingFX()
RegisterForSingleUpdate(1)
endif
endEvent
Event OnActivate(ObjectReference akActionRef)
if !in_use
in_use = true
Game.DisablePlayerControls(true, true, true, false, true, false, false, false)
SetUpLightingCampfire()
int j = 0
while !self.IsFurnitureInUse() && j < 50
j += 1
Utility.Wait(0.1)
endWhile
AddFireLightingFX()
RegisterForSingleUpdate(1)
endif
EndEvent
function SetUpLightingCampfire()
(_Camp_PlayerAlias as _Camp_PlayerHitMonitor).FireLightingReference = self
parent_campfire = GetLastUsedCampfire()
(parent_campfire as CampCampfire).FireLightingReference = self
int modifier_rank
if is_stone
modifier_rank = _Camp_PerkRank_Firecraft.GetValueInt()
elseif is_flamespell
modifier_rank = Math.Floor(PlayerRef.GetAV("Destruction") / 20)
if modifier_rank > 4
modifier_rank = 4
endif
endif
total_required_seconds = (parent_campfire as CampCampfire).base_time_to_light - (modifier_rank * 10)
if total_required_seconds <= 0
total_required_seconds = 1
endif
remaining_seconds = total_required_seconds
CampDebug(0, "Campfire lighting modifier rank " + modifier_rank)
CampDebug(0, "Campfire lighting total seconds " + total_required_seconds)
endFunction
function AddFireLightingFX()
if is_stone
spark_marker = PlayerRef.PlaceAtMe(XMarker)
float[] dist = new float[2]
dist = GetOffsets(PlayerRef, 130.0)
spark_marker.MoveTo(PlayerRef, afXOffset = dist[0], afYOffset = dist[1], afZOffset = 10.0)
elseif is_flamespell
FlameFX()
endif
endFunction
Event OnUpdate()
remaining_seconds -= 1.0
CampDebug(1, "Trying to light campfire, " + remaining_seconds + " secs remaining...")
float percentage = (remaining_seconds / total_required_seconds)
if was_hit
StopLighting()
return
endif
if self.IsFurnitureInUse() || (GetCompatibilitySystem().isSkyrimVR && (PlayerRef.GetPositionX() == currentX && PlayerRef.GetPositionY() == currentY))
if is_stone
stone_fx_counter += 1
StoneFX()
endif
if percentage <= 0.33 && old_percentage > 0.33
if !(parent_campfire as CampCampfire).is_tinder_oil
(parent_campfire as CampCampfire).mySteam.Enable()
endif
RegisterForSingleUpdate(1)
elseif percentage <= 0.0
CampDebug(1, "Campfire lit!")
(parent_campfire as CampCampfire).mySteam.DisableNoWait(true)
if (parent_campfire as CampCampfire).is_tinder_oil
; dramatic pause...
Utility.Wait(1.0)
parent_campfire.PlaceAtMe(_Camp_LightWithOilExplosion)
endif
(parent_campfire as CampCampfire).LightFire()
if is_stone
(parent_campfire as CampCampfire).AdvanceCampingSkill()
elseif is_flamespell
Game.AdvanceSkill("Destruction", 66.0) ; Equivalent to 1x cast of Fireball
endif
if !GetCompatibilitySystem().isSkyrimVR
self.Activate(PlayerRef)
int i = 0
while self.IsFurnitureInUse() && i < 50
Utility.Wait(0.1)
i += 1
endWhile
endif
(parent_campfire as CampCampfire).RegisterForCampfireCallback(0.1)
TakeDown()
else
RegisterForSingleUpdate(1)
endif
else
(parent_campfire as CampCampfire).campfire_stage = 3
_Camp_LastUsedCampfireStage.SetValueInt(3)
TakeDown()
endif
old_percentage = percentage
EndEvent
function PlayerHitEvent(ObjectReference akAggressor, Form akSource, Projectile akProjectile)
was_hit = true
endFunction
function StoneFX()
if stone_fx_counter <= 3
spark_marker.PlayImpactEffect(_Camp_SparkIDS)
endif
if stone_fx_counter >= 5
stone_fx_counter = 0
endif
endFunction
function FlameFX()
sound_id = MAGCloakFireLP.Play(PlayerRef)
Sound.SetInstanceVolume(sound_id, 0.65)
if !GetCompatibilitySystem().isSkyrimVR
PlayerRef.AddSpell(_Camp_LightFireFXFlamesSpell, false)
endif
endFunction
function StopLighting()
if !GetCompatibilitySystem().isSkyrimVR
self.Activate(PlayerRef)
endif
endFunction
function TakeDown()
Game.EnablePlayerControls()
if sound_id != 0
Sound.StopInstance(sound_id)
endif
if spark_marker
spark_marker.Disable()
spark_marker.Delete()
endif
if !GetCompatibilitySystem().isSkyrimVR
PlayerRef.RemoveSpell(_Camp_LightFireFXFlamesSpell)
endif
(_Camp_PlayerAlias as _Camp_PlayerHitMonitor).FireLightingReference = none
(parent_campfire as CampCampfire).FireLightingReference = none
(parent_campfire as CampCampfire).mySteam.DisableNoWait(true)
parent_campfire = none
self.Disable()
self.Delete()
endFunction
float[] function GetOffsets(Actor akSource, Float afDistance = 100.0, float afOffset = 0.0)
Float A = akSource.GetAngleZ() + afOffset
Float YDist = Sin(A)
Float XDist = Cos(A)
XDist *= afDistance
YDist *= afDistance
Float[] Offsets = New Float[2]
Offsets[0] = YDist
Offsets[1] = XDist
Return Offsets
EndFunction | Papyrus | 5 | chesko256/Campfire | Scripts/Source/_Camp_LightFireFurnScript.psc | [
"MIT"
] |
# Copyright 2021 The Google Research 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.
#!/bin/bash
if [[ $# -ne 1 ]]; then
GPUID=0,1,2,3,4,5,6,7
else
GPUID=$1
fi
echo "Run on GPU $GPUID"
# data
PROJECT_ROOT=$(dirname "$(readlink -f "$0")")/..
DATA=convai2/opedata_hard/baseline_model/
#DATA=selfplay_opedata/opedata/full/
#DATA=human_opedata/opedata/full/
DATA_ROOT=$PROJECT_ROOT/data/$DATA
TASK_NAME=air_ope
# output
OUTPUT=$PROJECT_ROOT/outputs/debug/$DATA
#OUTPUT=$PROJECT_ROOT/outputs/debug/random/$DATA
# model
MODEL_TYPE=roberta
MODEL_NAME=roberta-base
CACHEDIR=$PROJECT_ROOT/pretrained_model
#CACHEDIR=$PROJECT_ROOT/pretrained_model/random
FIX_BERT=true
SHARE_BERT=true
# params
LR=1e-5
WEIGHT_DECAY=1e-4
EPOCH=20
SEED=0
ADAM_EPS=1e-6
WARMUP=2000
TRAIN_BATCH=256
MAXLEN=384
# Dice parameter
alphaR=1
alphaC=1
alphaQ=0
regfunC=square
regfunQ=square
[ -e $OUTPUT/script ] || mkdir -p $OUTPUT/script
cp -f $(readlink -f "$0") $OUTPUT/script
rsync -ruzC --exclude-from=$PROJECT_ROOT/.gitignore --exclude 'data' --exclude 'pretrained_model' --exclude 'outputs' --exclude 'transformers' $PROJECT_ROOT/ $OUTPUT/src
CUDA_DEVICE_ORDER=PCI_BUS_ID CUDA_VISIBLE_DEVICES=$GPUID python3 main.py \
$($FIX_BERT && echo '--fix_bert') \
$($SHARE_BERT && echo '--share_bert') \
--alphaR $alphaR \
--alphaC $alphaC \
--alphaQ $alphaQ \
--regfunC $regfunC \
--regfunQ $regfunQ \
--data_dir $DATA_ROOT \
--task_name $TASK_NAME \
--model_name_or_path $MODEL_NAME \
--learning_rate $LR \
--weight_decay $WEIGHT_DECAY \
--adam_epsilon $ADAM_EPS \
--num_train_epochs $EPOCH \
--warmup_steps $WARMUP \
--per_device_train_batch_size $TRAIN_BATCH \
--logging_steps 10 \
--evaluate_during_training \
--save_steps 100000 \
--do_train \
--output_dir $OUTPUT \
--logging_dir $OUTPUT\log \
--cache_dir $CACHEDIR \
--seed $SEED \
--max_seq_length $MAXLEN \
--workers 50 \
--save_embedding \
--overwrite_output_dir
| Shell | 3 | deepneuralmachine/google-research | dialogue_ope/airdialogue_ope/script/debug.sh | [
"Apache-2.0"
] |
#!/usr/bin/env sh
#
# Copyright (c) Microsoft Corporation. All rights reserved.
#
case "$1" in
--inspect*) INSPECT="$1"; shift;;
esac
ROOT="$(dirname "$0")"
"$ROOT/node" ${INSPECT:-} "$ROOT/out/server-main.js" --compatibility=1.63 "$@"
| Shell | 3 | sbj42/vscode | resources/server/bin/server-old.sh | [
"MIT"
] |
# Copyright 1999-2020 Random Person
# Distributed under the terms of the GNU General Public License v2
# @ECLASS: non-gentoo-copyright.eclass
# @MAINTAINER:
# Random Dev <random.dev@gentoo.org>
# @AUTHOR:
# Random Dev <random.dev@gentoo.org>
# @BLURB: Stub eclass.
| Gentoo Eclass | 1 | floppym/pkgcheck | testdata/repos/gentoo/eclass/non-gentoo-copyright.eclass | [
"BSD-3-Clause"
] |
%%{
# RFC 3629 4. Syntax of UTF-8 Byte Sequences
# https://tools.ietf.org/html/rfc3629#section-4
machine rfc3629_utf8;
alphtype int;
utf8_tail = 0x80..0xBF;
utf8_2byte = 0xC2..0xDF utf8_tail;
utf8_3byte = 0xE0 0xA0..0xBF utf8_tail |
0xE1..0xEC utf8_tail utf8_tail |
0xED 0x80..0x9F utf8_tail |
0xEE..0xEF utf8_tail utf8_tail;
utf8_4byte = 0xF0 0x90..0xBF utf8_tail utf8_tail |
0xF1..0xF3 utf8_tail utf8_tail utf8_tail |
0xF4 0x80..0x8F utf8_tail utf8_tail;
utf8_non_ascii = utf8_2byte | utf8_3byte | utf8_4byte;
}%%
| Ragel in Ruby Host | 5 | ylecuyer/mail | lib/mail/parsers/rfc3629_utf8.rl | [
"MIT"
] |
<?Lassoscript
// Last modified 8/31/09 by ECL, Landmann InterActive
/*
Tagdocs;
{Tagname= OutputGallery }
{Description= Outputs a Gallery }
{Author= Eric Landmann }
{AuthorEmail= support@iterate.ws }
{ModifiedBy= }
{ModifiedByEmail= }
{Date= 1/14/09 }
{Usage= OutputGallery }
{ExpectedResults= Outputs the html code containing the entire gallery }
{Dependencies= $GalleryArray must be defined, otherwise you will get a page but with no gallery pictures }
{DevelNotes= This tag is merely a convenience to make it easy for a designer or coder to output a Gallery }
{ChangeNotes= 8/31/09
Integrated into itPage codebase. }
/Tagdocs;
*/
If: !(Lasso_TagExists:'OutputGallery');
Define_Tag:'OutputGallery',
-Description='Outputs the html code containing a Gallery';
Local('Result') = null;
// Check if $DropdownHTML is defined
If: (Var_Defined:'GalleryArray');
#Result = '<!-- START OutputGallery -->\n';
#Result += '<div id="main_image"></div>\n';
#Result += '\t<ul class="gallery_final_unstyled">\n';
Iterate: $GalleryArray, (Local:'i');
Var:'ThisID' = #i->find('id');
Var:'ThisFilename' = #i->find('Filename');
Var:'ThisImageAlt' = #i->find('ImageAlt');
Var:'ThisImageCaption' = #i->find('ImageCaption');
Var:'ThisGalleryText' = #i->find('GalleryGroupText');
If: $svDebug == 'Y';
#Result += ('<p class="debugCT"><strong>OutputGallery</strong>\n');
#Result += ('Response_Filepath = ' (Response_Filepath) '<br>\n');
#Result += ('ThisID = ' ($ThisID) '<br>\n');
#Result += ('ThisFilename = ' ($ThisFilename) '<br>\n');
#Result += ('ThisImageAlt = ' ($ThisImageAlt) '<br>\n');
#Result += ('ThisImageCaption = ' ($ThisImageCaption) '<br>\n');
#Result += ('ThisGalleryText = ' ($ThisGalleryText) '</p>\n');
/If;
// Build the output list item (picture and link) to display
#Result += '\t<li';
// Process the default image being viewed
If: (Response_Filepath) !>> '#';
#Result += ' class="active"';
/If;
#Result += ('><img src="'($svImagesLrgPath)($ThisFilename)'" alt="'($ThisImageAlt)'" title="'($ThisImageCaption)'"></li>\n');
/Iterate;
#Result += ('\t</ul>
<p class="GalleryNavContainer"><a href="#" onclick="$.galleria.prev(); return false;" class="GalleryNav">« previous</a> | <a href="#" onclick="$.galleria.next(); return false;" class="GalleryNav">next »</a></p>\n');
If: (Var:'ThisGalleryText') != '';
// This is a hack to fix the situation where the Gallery Text does not flow with the rest of the page when resized.
// Style sheet should probably be fixed to resolve this.
// #Result += ('\t<div class="GalleryGroupText">' ($ThisGalleryText) '</div>\n');
#Result += ('\t<div class="GalleryContainer">' ($ThisGalleryText) '</div>\n');
/If;
#Result += '<!-- END OutputGallery -->\n';
Return: (Encode_Smart:(#Result));
Else;
// Output a comment that variable is not defined
#Result = '<!-- OutputGallery: GalleryArray is undefined -->\n';
If: $svDebug == 'Y';
#Result += '<strong>OutputGallery: </strong>GalleryArray is undefined<br>\n';
/If;
Return: (Encode_Smart:(#Result));
/If;
/Define_Tag;
Log_Critical: 'Custom Tag Loaded - OutputGallery';
/If;
?>
| Lasso | 4 | subethaedit/SubEthaEd | Documentation/ModeDevelopment/Reference Files/LassoScript-HTML/itpage/LassoStartup/OutputGallery.lasso | [
"MIT"
] |
<html><body>Hello!</body></html> | FreeMarker | 1 | rmartinc/keycloak | testsuite/integration-arquillian/servers/auth-server/services/testsuite-providers/src/main/resources/theme-resources/templates/test.ftl | [
"Apache-2.0"
] |
# This file is distributed under the same license as the Django package.
#
# Translators:
# Henrique Azevedo <pintasart.mail@gmail.com>, 2018
# Jannis Leidel <jannis@leidel.info>, 2011
# jorgecarleitao <jorgecarleitao@gmail.com>, 2014
# Nuno Mariz <nmariz@gmail.com>, 2012-2013,2018
# Raúl Pedro Fernandes Santos, 2014
msgid ""
msgstr ""
"Project-Id-Version: django\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2019-01-16 20:42+0100\n"
"PO-Revision-Date: 2018-12-20 15:27+0000\n"
"Last-Translator: Nuno Mariz <nmariz@gmail.com>\n"
"Language-Team: Portuguese (http://www.transifex.com/django/django/language/"
"pt/)\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Language: pt\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
msgid "Humanize"
msgstr "Humanizar"
#. Translators: Ordinal format for 11 (11th), 12 (12th), and 13 (13th).
msgctxt "ordinal 11, 12, 13"
msgid "{}th"
msgstr "{}.º"
#. Translators: Ordinal format when value ends with 0, e.g. 80th.
msgctxt "ordinal 0"
msgid "{}th"
msgstr "{}.º"
#. Translators: Ordinal format when value ends with 1, e.g. 81st, except 11.
msgctxt "ordinal 1"
msgid "{}st"
msgstr "{}.º"
#. Translators: Ordinal format when value ends with 2, e.g. 82nd, except 12.
msgctxt "ordinal 2"
msgid "{}nd"
msgstr "{}.º"
#. Translators: Ordinal format when value ends with 3, e.g. 83th, except 13.
msgctxt "ordinal 3"
msgid "{}rd"
msgstr "{}.º"
#. Translators: Ordinal format when value ends with 4, e.g. 84th.
msgctxt "ordinal 4"
msgid "{}th"
msgstr "{}.º"
#. Translators: Ordinal format when value ends with 5, e.g. 85th.
msgctxt "ordinal 5"
msgid "{}th"
msgstr "{}.º"
#. Translators: Ordinal format when value ends with 6, e.g. 86th.
msgctxt "ordinal 6"
msgid "{}th"
msgstr "{}.º"
#. Translators: Ordinal format when value ends with 7, e.g. 87th.
msgctxt "ordinal 7"
msgid "{}th"
msgstr "{}.º"
#. Translators: Ordinal format when value ends with 8, e.g. 88th.
msgctxt "ordinal 8"
msgid "{}th"
msgstr "{}.º"
#. Translators: Ordinal format when value ends with 9, e.g. 89th.
msgctxt "ordinal 9"
msgid "{}th"
msgstr "{}.º"
#, python-format
msgid "%(value).1f million"
msgid_plural "%(value).1f million"
msgstr[0] "%(value).1f milhão"
msgstr[1] "%(value).1f milhões"
#, python-format
msgid "%(value)s million"
msgid_plural "%(value)s million"
msgstr[0] "%(value)s milhão"
msgstr[1] "%(value)s milhões"
#, python-format
msgid "%(value).1f billion"
msgid_plural "%(value).1f billion"
msgstr[0] "%(value).1f bilião"
msgstr[1] "%(value).1f biliões"
#, python-format
msgid "%(value)s billion"
msgid_plural "%(value)s billion"
msgstr[0] "%(value)s bilião"
msgstr[1] "%(value)s biliões"
#, python-format
msgid "%(value).1f trillion"
msgid_plural "%(value).1f trillion"
msgstr[0] "%(value).1f trilião"
msgstr[1] "%(value).1f triliões"
#, python-format
msgid "%(value)s trillion"
msgid_plural "%(value)s trillion"
msgstr[0] "%(value)s trilião"
msgstr[1] "%(value)s triliões"
#, python-format
msgid "%(value).1f quadrillion"
msgid_plural "%(value).1f quadrillion"
msgstr[0] "%(value).1f quadrilião"
msgstr[1] "%(value).1f quatriliões"
#, python-format
msgid "%(value)s quadrillion"
msgid_plural "%(value)s quadrillion"
msgstr[0] "%(value)s quadrilião"
msgstr[1] "%(value)s quatriliões"
#, python-format
msgid "%(value).1f quintillion"
msgid_plural "%(value).1f quintillion"
msgstr[0] "%(value).1f quintilião"
msgstr[1] "%(value).1f quintiliões"
#, python-format
msgid "%(value)s quintillion"
msgid_plural "%(value)s quintillion"
msgstr[0] "%(value)s quintilião"
msgstr[1] "%(value)s quintiliões"
#, python-format
msgid "%(value).1f sextillion"
msgid_plural "%(value).1f sextillion"
msgstr[0] "%(value).1f sextilião"
msgstr[1] "%(value).1f sextiliões"
#, python-format
msgid "%(value)s sextillion"
msgid_plural "%(value)s sextillion"
msgstr[0] "%(value)s sextilião"
msgstr[1] "%(value)s sextiliões"
#, python-format
msgid "%(value).1f septillion"
msgid_plural "%(value).1f septillion"
msgstr[0] "%(value).1f septilião"
msgstr[1] "%(value).1f septiliões"
#, python-format
msgid "%(value)s septillion"
msgid_plural "%(value)s septillion"
msgstr[0] "%(value)s septilião"
msgstr[1] "%(value)s septiliões"
#, python-format
msgid "%(value).1f octillion"
msgid_plural "%(value).1f octillion"
msgstr[0] "%(value).1f octilião"
msgstr[1] "%(value).1f octiliões"
#, python-format
msgid "%(value)s octillion"
msgid_plural "%(value)s octillion"
msgstr[0] "%(value)s octilião"
msgstr[1] "%(value)s octiliões"
#, python-format
msgid "%(value).1f nonillion"
msgid_plural "%(value).1f nonillion"
msgstr[0] "%(value).1f nonilião"
msgstr[1] "%(value).1f noniliões"
#, python-format
msgid "%(value)s nonillion"
msgid_plural "%(value)s nonillion"
msgstr[0] "%(value)s nonilião"
msgstr[1] "%(value)s noniliões"
#, python-format
msgid "%(value).1f decillion"
msgid_plural "%(value).1f decillion"
msgstr[0] "%(value).1f decilião"
msgstr[1] "%(value).1f deciliões"
#, python-format
msgid "%(value)s decillion"
msgid_plural "%(value)s decillion"
msgstr[0] "%(value)s decilião"
msgstr[1] "%(value)s deciliões"
#, python-format
msgid "%(value).1f googol"
msgid_plural "%(value).1f googol"
msgstr[0] "%(value).1f googol"
msgstr[1] "%(value).1f googol"
#, python-format
msgid "%(value)s googol"
msgid_plural "%(value)s googol"
msgstr[0] "%(value)s googol"
msgstr[1] "%(value)s googol"
msgid "one"
msgstr "um"
msgid "two"
msgstr "dois"
msgid "three"
msgstr "três"
msgid "four"
msgstr "quatro"
msgid "five"
msgstr "cinco"
msgid "six"
msgstr "seis"
msgid "seven"
msgstr "sete"
msgid "eight"
msgstr "oito"
msgid "nine"
msgstr "nove"
msgid "today"
msgstr "hoje"
msgid "tomorrow"
msgstr "amanhã"
msgid "yesterday"
msgstr "ontem"
#. Translators: delta will contain a string like '2 months' or '1 month, 2
#. weeks'
#, python-format
msgid "%(delta)s ago"
msgstr "%(delta)s atrás"
#. Translators: please keep a non-breaking space (U+00A0) between count
#. and time unit.
#, python-format
msgid "an hour ago"
msgid_plural "%(count)s hours ago"
msgstr[0] "há uma hora atrás"
msgstr[1] "há %(count)s horas atrás"
#. Translators: please keep a non-breaking space (U+00A0) between count
#. and time unit.
#, python-format
msgid "a minute ago"
msgid_plural "%(count)s minutes ago"
msgstr[0] "há um minuto atrás"
msgstr[1] "há %(count)s minutos atrás"
#. Translators: please keep a non-breaking space (U+00A0) between count
#. and time unit.
#, python-format
msgid "a second ago"
msgid_plural "%(count)s seconds ago"
msgstr[0] "há um segundo atrás"
msgstr[1] "há %(count)s segundos atrás"
msgid "now"
msgstr "agora"
#. Translators: please keep a non-breaking space (U+00A0) between count
#. and time unit.
#, python-format
msgid "a second from now"
msgid_plural "%(count)s seconds from now"
msgstr[0] "daqui a um segundo"
msgstr[1] "daqui a %(count)s segundos"
#. Translators: please keep a non-breaking space (U+00A0) between count
#. and time unit.
#, python-format
msgid "a minute from now"
msgid_plural "%(count)s minutes from now"
msgstr[0] "daqui a um minuto"
msgstr[1] "daqui a %(count)s minutos"
#. Translators: please keep a non-breaking space (U+00A0) between count
#. and time unit.
#, python-format
msgid "an hour from now"
msgid_plural "%(count)s hours from now"
msgstr[0] "daqui a uma hora"
msgstr[1] "daqui a %(count)s horas"
#. Translators: delta will contain a string like '2 months' or '1 month, 2
#. weeks'
#, python-format
msgid "%(delta)s from now"
msgstr "%(delta)s a partir de agora"
#. Translators: 'naturaltime-past' strings will be included in '%(delta)s ago'
#, python-format
msgctxt "naturaltime-past"
msgid "%d year"
msgid_plural "%d years"
msgstr[0] "%d ano"
msgstr[1] "%d anos"
#, python-format
msgctxt "naturaltime-past"
msgid "%d month"
msgid_plural "%d months"
msgstr[0] "%d meses"
msgstr[1] "%d meses"
#, python-format
msgctxt "naturaltime-past"
msgid "%d week"
msgid_plural "%d weeks"
msgstr[0] "%d semanas"
msgstr[1] "%d semanas"
#, python-format
msgctxt "naturaltime-past"
msgid "%d day"
msgid_plural "%d days"
msgstr[0] "%d dia"
msgstr[1] "%d dias"
#, python-format
msgctxt "naturaltime-past"
msgid "%d hour"
msgid_plural "%d hours"
msgstr[0] "%d horas"
msgstr[1] "%d horas"
#, python-format
msgctxt "naturaltime-past"
msgid "%d minute"
msgid_plural "%d minutes"
msgstr[0] "%d minuto"
msgstr[1] "%d minutos"
#. Translators: 'naturaltime-future' strings will be included in '%(delta)s
#. from now'
#, python-format
msgctxt "naturaltime-future"
msgid "%d year"
msgid_plural "%d years"
msgstr[0] "%d ano"
msgstr[1] "%d anos"
#, python-format
msgctxt "naturaltime-future"
msgid "%d month"
msgid_plural "%d months"
msgstr[0] "%d mês"
msgstr[1] "%d meses"
#, python-format
msgctxt "naturaltime-future"
msgid "%d week"
msgid_plural "%d weeks"
msgstr[0] "%d semana"
msgstr[1] "%d semanas"
#, python-format
msgctxt "naturaltime-future"
msgid "%d day"
msgid_plural "%d days"
msgstr[0] "%d dia"
msgstr[1] "%d dias"
#, python-format
msgctxt "naturaltime-future"
msgid "%d hour"
msgid_plural "%d hours"
msgstr[0] "%d hora"
msgstr[1] "%d horas"
#, python-format
msgctxt "naturaltime-future"
msgid "%d minute"
msgid_plural "%d minutes"
msgstr[0] "%d minuto"
msgstr[1] "%d minutos"
| Gettext Catalog | 4 | jpmallarino/django | django/contrib/humanize/locale/pt/LC_MESSAGES/django.po | [
"BSD-3-Clause",
"0BSD"
] |
# Copyright 2020 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.
# ==============================================================================
"""Tests for tf_sequence_example_decoder.py."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import numpy as np
import tensorflow.compat.v1 as tf
from object_detection.core import standard_fields as fields
from object_detection.data_decoders import tf_sequence_example_decoder
from object_detection.dataset_tools import seq_example_util
from object_detection.utils import test_case
class TfSequenceExampleDecoderTest(test_case.TestCase):
def _create_label_map(self, path):
label_map_text = """
item {
name: "dog"
id: 1
}
item {
name: "cat"
id: 2
}
item {
name: "panda"
id: 4
}
"""
with tf.gfile.Open(path, 'wb') as f:
f.write(label_map_text)
def _make_random_serialized_jpeg_images(self, num_frames, image_height,
image_width):
def graph_fn():
images = tf.cast(tf.random.uniform(
[num_frames, image_height, image_width, 3],
maxval=256,
dtype=tf.int32), dtype=tf.uint8)
images_list = tf.unstack(images, axis=0)
return [tf.io.encode_jpeg(image) for image in images_list]
encoded_images = self.execute(graph_fn, [])
return encoded_images
def test_decode_sequence_example(self):
num_frames = 4
image_height = 20
image_width = 30
expected_groundtruth_boxes = [
[[0.0, 0.0, 1.0, 1.0], [0.0, 0.0, 0.0, 0.0]],
[[0.2, 0.2, 1.0, 1.0], [0.0, 0.0, 1.0, 1.0]],
[[0.0, 0.0, 1.0, 1.0], [0.1, 0.1, 0.2, 0.2]],
[[0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0]]
]
expected_groundtruth_classes = [
[-1, -1],
[-1, 1],
[1, 2],
[-1, -1]
]
flds = fields.InputDataFields
encoded_images = self._make_random_serialized_jpeg_images(
num_frames, image_height, image_width)
def graph_fn():
label_map_proto_file = os.path.join(self.get_temp_dir(), 'labelmap.pbtxt')
self._create_label_map(label_map_proto_file)
decoder = tf_sequence_example_decoder.TfSequenceExampleDecoder(
label_map_proto_file=label_map_proto_file)
sequence_example_serialized = seq_example_util.make_sequence_example(
dataset_name='video_dataset',
video_id='video',
encoded_images=encoded_images,
image_height=image_height,
image_width=image_width,
image_format='JPEG',
image_source_ids=[str(i) for i in range(num_frames)],
is_annotated=[[1], [1], [1], [1]],
bboxes=[
[[0., 0., 1., 1.]], # Frame 0.
[[0.2, 0.2, 1., 1.],
[0., 0., 1., 1.]], # Frame 1.
[[0., 0., 1., 1.], # Frame 2.
[0.1, 0.1, 0.2, 0.2]],
[[]], # Frame 3.
],
label_strings=[
['fox'], # Frame 0. Fox will be filtered out.
['fox', 'dog'], # Frame 1. Fox will be filtered out.
['dog', 'cat'], # Frame 2.
[], # Frame 3
]).SerializeToString()
example_string_tensor = tf.convert_to_tensor(sequence_example_serialized)
return decoder.decode(example_string_tensor)
tensor_dict_out = self.execute(graph_fn, [])
self.assertAllClose(expected_groundtruth_boxes,
tensor_dict_out[flds.groundtruth_boxes])
self.assertAllEqual(expected_groundtruth_classes,
tensor_dict_out[flds.groundtruth_classes])
def test_decode_sequence_example_context(self):
num_frames = 4
image_height = 20
image_width = 30
expected_groundtruth_boxes = [
[[0.0, 0.0, 1.0, 1.0], [0.0, 0.0, 0.0, 0.0]],
[[0.2, 0.2, 1.0, 1.0], [0.0, 0.0, 1.0, 1.0]],
[[0.0, 0.0, 1.0, 1.0], [0.1, 0.1, 0.2, 0.2]],
[[0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0]]
]
expected_groundtruth_classes = [
[-1, -1],
[-1, 1],
[1, 2],
[-1, -1]
]
expected_context_features = np.array(
[[0.0, 0.1, 0.2], [0.3, 0.4, 0.5]], dtype=np.float32)
flds = fields.InputDataFields
encoded_images = self._make_random_serialized_jpeg_images(
num_frames, image_height, image_width)
def graph_fn():
label_map_proto_file = os.path.join(self.get_temp_dir(), 'labelmap.pbtxt')
self._create_label_map(label_map_proto_file)
decoder = tf_sequence_example_decoder.TfSequenceExampleDecoder(
label_map_proto_file=label_map_proto_file,
load_context_features=True)
sequence_example_serialized = seq_example_util.make_sequence_example(
dataset_name='video_dataset',
video_id='video',
encoded_images=encoded_images,
image_height=image_height,
image_width=image_width,
image_format='JPEG',
image_source_ids=[str(i) for i in range(num_frames)],
is_annotated=[[1], [1], [1], [1]],
bboxes=[
[[0., 0., 1., 1.]], # Frame 0.
[[0.2, 0.2, 1., 1.],
[0., 0., 1., 1.]], # Frame 1.
[[0., 0., 1., 1.], # Frame 2.
[0.1, 0.1, 0.2, 0.2]],
[[]], # Frame 3.
],
label_strings=[
['fox'], # Frame 0. Fox will be filtered out.
['fox', 'dog'], # Frame 1. Fox will be filtered out.
['dog', 'cat'], # Frame 2.
[], # Frame 3
],
context_features=[0.0, 0.1, 0.2, 0.3, 0.4, 0.5],
context_feature_length=[3],
context_features_image_id_list=[b'im_1', b'im_2']
).SerializeToString()
example_string_tensor = tf.convert_to_tensor(sequence_example_serialized)
return decoder.decode(example_string_tensor)
tensor_dict_out = self.execute(graph_fn, [])
self.assertAllClose(expected_groundtruth_boxes,
tensor_dict_out[flds.groundtruth_boxes])
self.assertAllEqual(expected_groundtruth_classes,
tensor_dict_out[flds.groundtruth_classes])
self.assertAllClose(expected_context_features,
tensor_dict_out[flds.context_features])
def test_decode_sequence_example_context_image_id_list(self):
num_frames = 4
image_height = 20
image_width = 30
expected_groundtruth_boxes = [
[[0.0, 0.0, 1.0, 1.0], [0.0, 0.0, 0.0, 0.0]],
[[0.2, 0.2, 1.0, 1.0], [0.0, 0.0, 1.0, 1.0]],
[[0.0, 0.0, 1.0, 1.0], [0.1, 0.1, 0.2, 0.2]],
[[0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0]]
]
expected_groundtruth_classes = [
[-1, -1],
[-1, 1],
[1, 2],
[-1, -1]
]
expected_context_image_ids = [b'im_1', b'im_2']
flds = fields.InputDataFields
encoded_images = self._make_random_serialized_jpeg_images(
num_frames, image_height, image_width)
def graph_fn():
label_map_proto_file = os.path.join(self.get_temp_dir(), 'labelmap.pbtxt')
self._create_label_map(label_map_proto_file)
decoder = tf_sequence_example_decoder.TfSequenceExampleDecoder(
label_map_proto_file=label_map_proto_file,
load_context_image_ids=True)
sequence_example_serialized = seq_example_util.make_sequence_example(
dataset_name='video_dataset',
video_id='video',
encoded_images=encoded_images,
image_height=image_height,
image_width=image_width,
image_format='JPEG',
image_source_ids=[str(i) for i in range(num_frames)],
is_annotated=[[1], [1], [1], [1]],
bboxes=[
[[0., 0., 1., 1.]], # Frame 0.
[[0.2, 0.2, 1., 1.],
[0., 0., 1., 1.]], # Frame 1.
[[0., 0., 1., 1.], # Frame 2.
[0.1, 0.1, 0.2, 0.2]],
[[]], # Frame 3.
],
label_strings=[
['fox'], # Frame 0. Fox will be filtered out.
['fox', 'dog'], # Frame 1. Fox will be filtered out.
['dog', 'cat'], # Frame 2.
[], # Frame 3
],
context_features=[0.0, 0.1, 0.2, 0.3, 0.4, 0.5],
context_feature_length=[3],
context_features_image_id_list=[b'im_1', b'im_2']
).SerializeToString()
example_string_tensor = tf.convert_to_tensor(sequence_example_serialized)
return decoder.decode(example_string_tensor)
tensor_dict_out = self.execute(graph_fn, [])
self.assertAllClose(expected_groundtruth_boxes,
tensor_dict_out[flds.groundtruth_boxes])
self.assertAllEqual(expected_groundtruth_classes,
tensor_dict_out[flds.groundtruth_classes])
self.assertAllEqual(expected_context_image_ids,
tensor_dict_out[flds.context_features_image_id_list])
def test_decode_sequence_example_negative_clip(self):
num_frames = 4
image_height = 20
image_width = 30
expected_groundtruth_boxes = -1 * np.ones((4, 0, 4))
expected_groundtruth_classes = -1 * np.ones((4, 0))
flds = fields.InputDataFields
encoded_images = self._make_random_serialized_jpeg_images(
num_frames, image_height, image_width)
def graph_fn():
sequence_example_serialized = seq_example_util.make_sequence_example(
dataset_name='video_dataset',
video_id='video',
encoded_images=encoded_images,
image_height=image_height,
image_width=image_width,
image_format='JPEG',
image_source_ids=[str(i) for i in range(num_frames)],
bboxes=[
[[]],
[[]],
[[]],
[[]]
],
label_strings=[
[],
[],
[],
[]
]).SerializeToString()
example_string_tensor = tf.convert_to_tensor(sequence_example_serialized)
label_map_proto_file = os.path.join(self.get_temp_dir(), 'labelmap.pbtxt')
self._create_label_map(label_map_proto_file)
decoder = tf_sequence_example_decoder.TfSequenceExampleDecoder(
label_map_proto_file=label_map_proto_file)
return decoder.decode(example_string_tensor)
tensor_dict_out = self.execute(graph_fn, [])
self.assertAllClose(expected_groundtruth_boxes,
tensor_dict_out[flds.groundtruth_boxes])
self.assertAllEqual(expected_groundtruth_classes,
tensor_dict_out[flds.groundtruth_classes])
if __name__ == '__main__':
tf.test.main()
| Python | 5 | akshit-protonn/models | research/object_detection/data_decoders/tf_sequence_example_decoder_test.py | [
"Apache-2.0"
] |
{
outPath: './remote.mp4',
allowRemoteRequests: true,
audioFilePath: './assets/High [NCS Release] - JPB (No Copyright Music)-R8ZRCXy5vhA.m4a',
clips: [
{ layers: [{ type: 'image', path: 'https://picsum.photos/400/400' }] },
{ layers: [{ type: 'image', path: 'https://picsum.photos/200/400' }] },
{ layers: [{ type: 'image', path: 'https://picsum.photos/400/200' }] },
],
} | JSON5 | 2 | aaverty/editly | examples/remote.json5 | [
"MIT"
] |
structure A = struct
signature S = sig
val x : int
end
end
structure B : A.S = struct
val x = 42
end
| UrWeb | 3 | apple314159/urweb | tests/sigInModule.ur | [
"BSD-3-Clause"
] |
source "../tests/includes/init-tests.tcl"
source "../tests/includes/job-utils.tcl"
test "WORKING returns the retry time for the job" {
set qname [randomQueue]
set id [D 0 addjob $qname myjob 5000 replicate 3 retry 123]
assert {[D 0 working $id] == 123}
D 0 ackjob $id
}
test "WORKING can prevent the job to be requeued (without partitions)" {
set qname [randomQueue]
set id [D 0 addjob $qname myjob 5000 replicate 3 retry 3]
set job [D 0 show $id]
assert {$id ne {}}
set myjob [lindex [D 0 getjob from $qname] 0]
assert {[lindex $myjob 0] eq $qname}
assert {[lindex $myjob 1] eq $id}
assert {[lindex $myjob 2] eq "myjob"}
set now [clock seconds]
while {([clock seconds]-$now) < 10} {
assert {[count_job_copies $job queued] == 0}
D 0 working $id
after 1000
}
}
| Tcl | 3 | justincase/disque | tests/cluster/tests/11-waiting-nack.tcl | [
"BSD-3-Clause"
] |
// Copyright 2010-2013 RethinkDB, all rights reserved.
#include "clustering/generic/nonoverlapping_regions.hpp"
bool valid_regions_helper(const std::vector<region_t> ®ionvec,
const std::set<region_t> ®ionset) {
// Disallow empty regions.
if (regionset.find(region_t()) != regionset.end()) {
return false;
}
// Require that the regions join to the universe.
region_t should_be_universe;
region_join_result_t res = region_join(regionvec, &should_be_universe);
if (res != REGION_JOIN_OK || should_be_universe != region_t::universe()) {
return false;
}
return true;
}
bool nonoverlapping_regions_t::set_regions(const std::vector<region_t> ®ions) {
std::set<region_t> regionset(regions.begin(), regions.end());
// Disallow duplicate regions.
if (regionset.size() != regions.size() || !valid_regions_helper(regions, regionset)) {
return false;
}
regions_ = regionset;
return true;
}
bool nonoverlapping_regions_t::valid_for_sharding() const {
std::vector<region_t> regionvec(regions_.begin(), regions_.end());
return valid_regions_helper(regionvec, regions_);
}
// TODO: Ugh, this is O(n)! Oh well.
bool nonoverlapping_regions_t::add_region(const region_t ®ion) {
for (std::set<region_t>::iterator it = regions_.begin();
it != regions_.end();
++it) {
if (region_overlaps(region, *it)) {
return false;
}
}
regions_.insert(region);
return true;
}
| C++ | 4 | zadcha/rethinkdb | src/clustering/generic/nonoverlapping_regions.cc | [
"Apache-2.0"
] |
namespace Ryujinx.HLE.HOS.Services.Ptm.Psm
{
enum ChargerType
{
None,
ChargerOrDock,
UsbC
}
} | C# | 3 | BSoDGamingYT/Ryujinx | Ryujinx.HLE/HOS/Services/Ptm/Psm/Types/ChargerType.cs | [
"MIT"
] |
# Práctica 1 - Parte 1
¿Qué patrón es más fácil de desarrollar (Monolítica vs. Microservicios) y por qué?
- El patrón que podría ser más fácil de aplicar sería el de microservicios ya que la manera en como se organiza el proyecto mediate módulos por separado y que entre ellas tengan una comunicación para realizar las acciones debidas puede ser más accesible al cambio y tengan mayor seguridad en cuestion de los datos que se manejen, también tienen varias ventajas al monolitico dado que si llegara a fallar, toda la aplicación o el proyecto va dejar de funcionar, pero todo va depender de como sea tu aplicación dado que si es grande es mejor usar los microservicios siempre y cuando tengan las personas necesarias para podero realizar, en dado caso que sea más pequeño sería usar un monolítico.
¿En qué consiste el patrón de arquitectura monolítica?
- Consiste en que todos los archivos que se tengan algo funcional a la aplicación , esten organizados en un mismo módulo, donde la comunicación que tienen entre ellos pasa por la memoria y es el uso común que usamos al realizar una aplicación.
¿Cuáles son las principales desventajas de una arquitectura monolítica?
- Que mientras va creciendo la aplicación va ser más díficil administrar tanto la información que vayan adquierendo, como la funcionalidad que necesiten, esto va aprovocar que van a tener que hacer copias iguales en diferentes servidores y todos dependeran de una balanceador de carga que se encarga que siempre la aplicación pueda ejecutar las peticiones de forma eficiente y pueda dividir las peticiones entre las copias.
- otra desventaja es cuando se pida una actualización de código se tendrá que hacer lo mismo en las copias.
- La aplicación deberá ser desarrollada en un solo lenguaje de programación.
- Los componentes que se tengan en una aplicación no se podrán usar en otras aplicaciones dado que fue realizado especificamente para uno en concreto.
¿Qué problemas presenta un monolito al que queremos agregar nueva funcionalidad?
- Va ser más dificil escalar el proyecto ya que se tendrán que hacer replicas del módulo, puesto que se tendrán que poner en otros servidores y los deberán organizar en un load balancer para poder seguir teniendo una eficiencia positiva.
¿Qué sucede si falla una aplicación monolítica?
- Si una cosa falla todo dejará de funcionar, ya que todo esta en un mismo módulo.
¿En qué consiste el patrón de arquitectura basada en microservicios?
- El patrón microservicios organiza el backend mediate componentes distribuidos por separado, puesto que cada uno tendrá una funcionalidad diferente y que entre ellas puedan tengan una comunicación y asi puedan ejecutarse como una sola, cada servicio puede depender por si mismo o por otro, ademas que pueden tener cambios con el paso del tiempo y no vana depender de los otros servicios sin interrumpirse.
¿Qué sucede si aumenta la carga en un servicio de la arquitectura basada en microservicios?
- Se va agregando más funcionalidad a la aplicación sin que interrumpa a los demás servicios que ya tenían.
¿Qué es un ambiente basado en contenedores?
- Es donde cada función del servicio se implementa en un contenedor propio y cada uno ellos se comunican a través de una API, cada uno de ellos podrá usar el lenguaje que necesite, una vez que pase las pruebas correctamente ya lo podrás subir a producción inmediatamente.
Si utilizaramos una arquitectura basada en microservicios, ¿seríamos dependientes a algún lenguaje/tecnología en específico o no?, ¿y por qué?
- No, porque se pueden usar diferentes lenguajes de programación en cada servicio e incluso distintas bases de datos, esto es porque no se guian por la tecnología que estén usando si no por la imformación que entra y sale de la aplicación y así puedan ralizar su tarea.
¿De qué diferentes maneras se pueden comunicar los servicios en una arquitectura basada en microservicios?
- Se comunican mediante los protocolos HTTP, mediante una API donde permite que los servicios se comuniquen entre si, sin importar como estén realizados.
¿Los microservicios pueden ser distribuidos? ¿Por qué?
- si porque se organizan por diferentes servicios donde cada uno tiene una funcionalidad, sin importar las diferentes tecnologíasque tengan..
¿Cuáles son los principales desafios de una arquitectura basada en microservicios?
- Un desafio sería el mantenimiento dado a la cantidad de personas que tengan en cada módulo, si son pocos será dificil poder realizarlo, ya que los microservicios son para proyectos que van en crecimiento constante.
-Se tienen que hacer diferentes pruebas para cada servicio para ver si está funcionando correctamente, durante un tiempo.
- La seguridad y velocidad va depender de la red que se esté usando.
- Obtener y convertir la información, también usará más tiempo en el servidor, ya que tiene que recibir y convertir la información para los diferentes lenguajes que esten usando los servicios
¿Cómo garantizamos la disponibilidad de un servicio en la arquitectura basada en microservicios?
- Realizando las pruebas necesarias para verificar que todo esté en orden | RMarkdown | 3 | jarmarj/DAS_Sistemas | Ene-Jun-2021/monjaras-granados-alicia-montserrat/practica1_SegundoParcial/parte1.rmd | [
"MIT"
] |
fn get_nprocs { m : nat | m > 0 }() : int(m) =
"ext#"
| ATS | 2 | lambdaxymox/polyglot | SATS/nproc.sats | [
"BSD-3-Clause"
] |
a
b
b
/a
/b
/c
a/b
a/b/c
//a
//b
//c
a//b
a//c
b//c
| Max | 0 | yapingxin/libxml2 | v2.9.7/libxml2-2.9.7/test/pattern/simple.pat | [
"MIT"
] |
--TEST--
Unserialize leak in SplObjectStorage
--FILE--
<?php
$payload = 'C:16:"SplObjectStorage":113:{x:i:2;O:8:"stdClass":1:{},a:2:{s:4:"prev";i:2;s:4:"next";O:8:"stdClass":0:{}};r:7;,R:2;s:4:"next";;r:3;};m:a:0:{}}';
try {
var_dump(unserialize($payload));
} catch (Exception $e) {
echo $e->getMessage(), "\n";
}
?>
--EXPECTF--
Notice: SplObjectStorage::unserialize(): Unexpected end of serialized data in %s on line %d
Error at offset 24 of 113 bytes
| PHP | 3 | thiagooak/php-src | ext/standard/tests/serialize/unserialize_leak.phpt | [
"PHP-3.01"
] |
@import url('import1.css');
.testClass {
color: #000;
}
| CSS | 2 | ravitejavalluri/brackets | test/spec/LiveDevelopment-MultiBrowser-test-files/simple1.css | [
"MIT"
] |
package com.baeldung.hibernate;
import com.baeldung.hibernate.pojo.Employee;
import com.baeldung.hibernate.pojo.EntityDescription;
import com.baeldung.hibernate.pojo.Phone;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
public class DynamicMappingIntegrationTest {
private Session session;
private Transaction transaction;
@Before
public void setUp() throws IOException {
session = HibernateUtil.getSessionFactory().openSession();
transaction = session.beginTransaction();
session.createNativeQuery("delete from phone").executeUpdate();
session.createNativeQuery("delete from employee").executeUpdate();
transaction.commit();
transaction = session.beginTransaction();
}
@After
public void tearDown() {
transaction.rollback();
session.close();
}
@Test
public void givenEntity_whenFieldMappedWithFormula_thenFieldIsCalculated() {
Employee employee = new Employee(10_000L, 25);
assertThat(employee.getTaxJavaWay()).isEqualTo(2_500L);
session.save(employee);
session.flush();
session.clear();
employee = session.get(Employee.class, employee.getId());
assertThat(employee.getTax()).isEqualTo(2_500L);
}
@Test
public void givenEntityMappedWithWhere_whenDeletedIsTrue_thenEntityNotFetched() {
Employee employee = new Employee();
session.save(employee);
session.clear();
employee = session.find(Employee.class, employee.getId());
assertThat(employee).isNotNull();
employee.setDeleted(true);
session.flush();
employee = session.find(Employee.class, employee.getId());
assertThat(employee).isNotNull();
session.clear();
employee = session.find(Employee.class, employee.getId());
assertThat(employee).isNull();
}
@Test
public void givenCollectionMappedWithWhere_whenDeletedIsTrue_thenEntityNotFetched() {
Employee employee = new Employee();
Phone phone1 = new Phone("555-45-67");
Phone phone2 = new Phone("555-89-01");
employee.getPhones().add(phone1);
employee.getPhones().add(phone2);
session.save(phone1);
session.save(phone2);
session.save(employee);
session.flush();
session.clear();
employee = session.find(Employee.class, employee.getId());
assertThat(employee.getPhones()).hasSize(2);
employee.getPhones().iterator().next().setDeleted(true);
session.flush();
session.clear();
employee = session.find(Employee.class, employee.getId());
assertThat(employee.getPhones()).hasSize(1);
List<Phone> fullPhoneList = session.createQuery("from Phone").getResultList();
assertThat(fullPhoneList).hasSize(2);
}
@Test
public void givenFilterByIncome_whenIncomeLimitSet_thenFilterIsApplied() throws IOException {
session.save(new Employee(10_000, 25));
session.save(new Employee(12_000, 25));
session.save(new Employee(15_000, 25));
session.flush();
session.clear();
session.enableFilter("incomeLevelFilter")
.setParameter("incomeLimit", 11_000);
List<Employee> employees = session.createQuery("from Employee").getResultList();
assertThat(employees).hasSize(2);
Employee employee = session.get(Employee.class, 1);
assertThat(employee.getGrossIncome()).isEqualTo(10_000);
session.disableFilter("incomeLevelFilter");
employees = session.createQuery("from Employee").getResultList();
assertThat(employees).hasSize(3);
}
@Test
public void givenMappingWithAny_whenDescriptionAddedToEntity_thenDescriptionCanReferAnyEntity() {
Employee employee = new Employee();
Phone phone1 = new Phone("555-45-67");
Phone phone2 = new Phone("555-89-01");
employee.getPhones().add(phone1);
employee.getPhones().add(phone2);
EntityDescription employeeDescription = new EntityDescription("Send to conference next year", employee);
EntityDescription phone1Description = new EntityDescription("Home phone (do not call after 10PM)", phone1);
EntityDescription phone2Description = new EntityDescription("Work phone", phone1);
session.save(phone1);
session.save(phone2);
session.save(employee);
session.save(employeeDescription);
session.save(phone1Description);
session.save(phone2Description);
session.flush();
session.clear();
List<EntityDescription> descriptions = session.createQuery("from EntityDescription").getResultList();
assertThat(Employee.class.isAssignableFrom(descriptions.get(0).getEntity().getClass())).isTrue();
assertThat(Phone.class.isAssignableFrom(descriptions.get(1).getEntity().getClass())).isTrue();
assertThat(Phone.class.isAssignableFrom(descriptions.get(2).getEntity().getClass())).isTrue();
}
}
| Java | 5 | DBatOWL/tutorials | persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/DynamicMappingIntegrationTest.java | [
"MIT"
] |
Definitions
-----------
n: Features
m: Datapoints
K: Clusters
X: m×n dataset
class kMeans
####initialize
Initialize a new k-means clustering object.
Pass the following options, and proceed to clustering.
Options:
* `K` (Integer) *Default: 5*
The number of clusters.
* `maxIterations` (Integer) *Default: 100*
The number of iterations before the algorithm stops.
* `enableConvergenceTest` (Boolean) *Default: true*
Enable convergence test. This test can be computationally intensive, but
might also save many iterations.
* `tolerance` (Float) *Default: 1e-9*
Floating point value for the convergence tolerance.
* `initialize` (Function)
The function used to initialize the centroids.
*Default:* The Forgy method, which chooses K random datapoints, as the
initial centroids. You can also write your own, with the following signature
fn(X, K, m, n), where:
* `X` (2D Array): The set of datapoints. Remember this is passed by reference
and is therefore **mutable**.
* `K` (Integer): The number of centroids to initialize.
* `m` (Integer): The number of datapoints in `X`.
* `n` (Integer): The number of features of each datapoint in `X`.
* `distanceMetric` (Function)
The function used to measure the distance between centroids and points in its
cluster.
**Default** is the sum of the squared error. Other metrics might be
manhattan distance or minkowski distance.
constructor: (options = {}) ->
@K = options.K ? 5
@maxIterations = options.maxIterations ? 100
@enableConvergenceTest = options.enableConvergenceTest ? true
@tolerance = options.tolerance ? 1e-9
@initialize = options.initialize ? kMeans.initializeForgy
@distanceMetric = options.distanceMetric ? @sumSquared
if not (1 <= @K < Infinity)
throw "K must be in the interval [1, Infinity)"
if not (1 <= @maxIterations < Infinity)
throw "maxIterations must be in the interval [1, Infinity)"
####cluster
Initialize clustering over dataset `X`.
`X` should be a m×n matrix of m data rows and n feature columns.
cluster: (@X) ->
@prevCentroids = []
@clusters = []
@currentIteration = 0
[@m, @n] = [@X.length, @X[0].length]
if not @m? or not @n? or @n < 1
throw "Data must be of the format [[x_11, ... , x_1n], ... , [x_m1, ... , x_mn]]"
@centroids = @initialize(@X, @K, @m, @n)
if @centroids.length != @K or @centroids[0].length != @n
throw "`initialize` must return a K×n matrix"
####step
Used when custom logic is interleaved within the clustering process.
See `autoCluster(X)` method below for an example
step: ->
@currentIteration++ < @maxIterations
####autoCluster
Cluster dataset `X` by means of the standard algorithm:
1. Find closest centroid for each datapoint and assign it to the centroids cluster
2. Move the centroid to the mean of its cluster
3. *Optional* Check for convergence, by measuring the distance moved
by the centroid since the last iteration
autoCluster: (X) ->
@cluster X
while @step()
@findClosestCentroids()
@moveCentroids()
break if @hasConverged()
####initializeForgy
The Forgy method uses K random data points as initial centroids. Accessed as
`kMeans.initializeForgy`
*O(K)*
@initializeForgy: (X, K, m, n) ->
X[Math.floor Math.random() * m] for k in [0...K]
####initializeInRange
This initialization places K centroids at random, within the range of the data points.
Accessed as `kMeans.initializeInRange`
*O(n·m+K·n)*
@initializeInRange: (X, K, m, n) ->
min = Infinity for i in [0...n]
max = -Infinity for i in [0...n]
for x in X
for d, i in x
min[i] = Math.min min[i], d
max[i] = Math.max max[i], d
(for k in [0...K]
(for d in [0...n]
Math.random() * (max[d] - min[d]) + min[d]
)
)
####findClosestCentroids
Assign each datapoint to the cluster of its closest centroid.
This is done by adding the datapoint's index to an array of clusters,
where the index of each cluster corrosponds to the index of the centroid for
that cluster.
findClosestCentroids: ->
if @enableConvergenceTest
@prevCentroids = (r.slice(0) for r in @centroids) #Clone optimization
Datapoints will be assigned to clusters to optimize the move step
however, this means that it will be hard to find out which cluster a specific
datapoint belongs to, without probing every element of every cluster
@clusters = ([] for i in [0...@K])
for x, i in @X
cMin = 0
xMin = Infinity
for c, j in @centroids
min = @distanceMetric c, x
if min < xMin
cMin = j
xMin = min
@clusters[cMin].push i
####moveCentroids
Iterate through each cluster and move it's centroid to the mean of all
the datapoints in that cluster.
moveCentroids: ->
for cl, i in @clusters
continue if cl.length < 1 #Avoid division by 0
for j in [0...@n]
sum = 0
for d in cl
sum += @X[d][j]
@centroids[i][j] = sum/(cl.length)
####hasConverged
Check whether any of the elements of the absolute difference between the
previous centroid positions and the current are greater than a set tolerance.
In case they're none are greater, then the algorithm has converged.
hasConverged: ->
return false if not @enableConvergenceTest
for i in [0...@n]
for j in [0...@m]
absDelta = Math.abs @prevCentroids[i][j] - @centroids[i][j]
return true if @tolerance > absDelta
return false
####sumSquared
The default distance metric used by the `findClosestCentroids` step. Takes the
square of the euclidian distances between points. A custom metric can be used by
changing the `options.distanceMetric` when initializing kMeans.
sumSqured: (X, Y) ->
sum = 0
n = X.length
while n--
sum += (Y[n] - X[n]) * (Y[n] - X[n])
sum
Check whether module.exports or exports are present, otherwise attach the class
to the window object.
if module?.exports? or exports?
module.exports = exports = kMeans
else
window.kMeans = kMeans
| Literate CoffeeScript | 5 | Nacalyator/Statistics | node_modules/kmeans-js/src/kMeans.litcoffee | [
"MIT"
] |
IDENTIFICATION DIVISION.
PROGRAM-ID. worker.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 RAND-NUM PIC 9(2).
01 CURRENT-TIME.
05 T-HOURS PIC 99.
05 T-MINS PIC 99.
05 T-SECS PIC 99.
05 T-MS PIC 999.
01 PLAYER-CHOICE PIC X(8).
01 COMPUTER-CHOICE PIC A(10).
01 CHOICE-IND PIC 9.
01 BLAH PIC 99.
01 HTTP-BAD-REQUEST PIC A(3) VALUE '400'.
01 ERROR-NO-INPUT PIC A(24) VALUE 'please provide your pick'.
01 ARG-VALUE PIC S9(9) BINARY.
01 ARG-NAME PIC A(4) VALUE 'pick'.
01 ROCK PIC A(8) VALUE 'rock'.
01 SCISSORS PIC A(8) VALUE 'scissors'.
01 PAPER PIC A(8) VALUE 'paper'.
01 CHOICES.
05 CHOICE PIC A(8) OCCURS 3 TIMES.
01 RESULT PIC X(20) VALUE 'You lose!'.
PROCEDURE DIVISION.
CALL "get_http_form" USING ARG-NAME RETURNING ARG-VALUE.
EVALUATE TRUE
WHEN ARG-VALUE = 1
MOVE 'rock' TO PLAYER-CHOICE
WHEN ARG-VALUE = 2
MOVE 'scissors' TO PLAYER-CHOICE
WHEN ARG-VALUE = 3
MOVE 'paper' TO PLAYER-CHOICE
WHEN OTHER
CALL "set_http_status" USING HTTP-BAD-REQUEST
CALL "set_http_body" USING ERROR-NO-INPUT
STOP RUN
END-EVALUATE
DISPLAY "player: " ARG-VALUE
DISPLAY "player: " PLAYER-CHOICE
MOVE ROCK TO CHOICE(1).
MOVE SCISSORS TO CHOICE(2).
MOVE PAPER TO CHOICE(3).
ACCEPT current-time FROM TIME.
COMPUTE RAND-NUM = FUNCTION RANDOM (T-MS) * 100.
DIVIDE RAND-NUM BY 3 GIVING BLAH REMAINDER CHOICE-IND.
MOVE CHOICE(CHOICE-IND + 1) TO COMPUTER-CHOICE.
CALL "append_http_body" USING "Computer chose "
CALL "append_http_body" USING COMPUTER-CHOICE
CALL "append_http_body" USING "\n"
CALL "append_http_body" USING "Player chose "
CALL "append_http_body" USING PLAYER-CHOICE
CALL "append_http_body" USING "\n"
IF PLAYER-CHOICE = COMPUTER-CHOICE
MOVE 'Tie!' TO RESULT
END-IF.
IF PLAYER-CHOICE = 'rock' AND COMPUTER-CHOICE = 'scissors'
MOVE 'You win!' TO RESULT
END-IF.
IF PLAYER-CHOICE = 'scissors' AND COMPUTER-CHOICE = 'paper'
MOVE 'You win!' TO RESULT
END-IF.
IF PLAYER-CHOICE = 'paper' AND COMPUTER-CHOICE = 'rock'
MOVE 'You win!' TO RESULT
END-IF.
CALL "append_http_body" USING RESULT
CALL "append_http_body" USING "\n"
STOP RUN.
| COBOL | 3 | 6un9-h0-Dan/cobaul | example/hello.cob | [
"MIT"
] |
untyped
global function MenuPrivateMatch_Init
global function InitPrivateMatchMenu
global function HandleLockedCustomMenuItem
global function GetMapImageForMapName
struct
{
var menu
array matchStatusRuis
array MMDevStringElems
array teamSlotBackgrounds
array teamSlotBackgroundsNeutral
var enemyTeamBackgroundPanel
var friendlyTeamBackgroundPanel
var enemyTeamBackground
var friendlyTeamBackground
var enemyPlayersPanel
var friendlyPlayersPanel
var listFriendlies
var listEnemies
var nextMapNameLabel
var nextGameModeLabel
var inviteRoomButton
var inviteFriendsButton
int inboxHeaderIndex
int customizeHeaderIndex
var pilotButton
var titanButton
var boostsButton
var storeButton
var factionButton
var bannerButton
var patchButton
var statsButton
var dpadCommsButton
var playHeader
var customizeHeader
var callsignHeader
var storeHeader
var startMatchButton
var selectMapButton
var selectModeButton
var matchSettingsButton
var callsignCard
var spectatorLabel
var matchSettingsPanel
ComboStruct &lobbyComboStruct
} file
const table<asset> mapImages =
{
mp_forwardbase_kodai = $"loadscreens/mp_forwardbase_kodai_lobby",
mp_grave = $"loadscreens/mp_grave_lobby",
mp_homestead = $"loadscreens/mp_homestead_lobby",
mp_thaw = $"loadscreens/mp_thaw_lobby",
mp_black_water_canal = $"loadscreens/mp_black_water_canal_lobby",
mp_eden = $"loadscreens/mp_eden_lobby",
mp_drydock = $"loadscreens/mp_drydock_lobby",
mp_crashsite3 = $"loadscreens/mp_crashsite3_lobby",
mp_complex3 = $"loadscreens/mp_complex3_lobby",
mp_angel_city = $"loadscreens/mp_angle_city_r2_lobby",
mp_colony02 = $"loadscreens/mp_colony02_lobby",
mp_glitch = $"loadscreens/mp_glitch_lobby",
mp_lf_stacks = $"loadscreens/mp_stacks_lobby",
mp_lf_meadow = $"loadscreens/mp_meadow_lobby",
mp_lf_deck = $"loadscreens/mp_lf_deck_lobby",
mp_lf_traffic = $"loadscreens/mp_lf_traffic_lobby",
mp_coliseum = $"loadscreens/mp_coliseum_lobby",
mp_coliseum_column = $"loadscreens/mp_coliseum_column_lobby",
mp_relic02 = $"loadscreens/mp_relic02_lobby",
mp_wargames = $"loadscreens/mp_wargames_lobby",
mp_rise = $"loadscreens/mp_rise_lobby",
mp_lf_township = $"loadscreens/mp_lf_township_lobby",
mp_lf_uma = $"loadscreens/mp_lf_uma_lobby",
// not really sure if this should be here, whatever
// might be good to make this modular in the future?
sp_training = $"rui/menu/level_select/level_image1",
sp_crashsite = $"rui/menu/level_select/level_image2",
sp_sewers1 = $"rui/menu/level_select/level_image3",
sp_boomtown_start = $"rui/menu/level_select/level_image4",
sp_hub_timeshift = $"rui/menu/level_select/level_image5",
sp_beacon = $"rui/menu/level_select/level_image6",
sp_tday = $"rui/menu/level_select/level_image7",
sp_s2s = $"rui/menu/level_select/level_image8",
sp_skyway_v1 = $"rui/menu/level_select/level_image9",
// mp converted variants
mp_training = $"rui/menu/level_select/level_image1",
mp_crashsite = $"rui/menu/level_select/level_image2",
mp_sewers1 = $"rui/menu/level_select/level_image3",
mp_boomtown_start = $"rui/menu/level_select/level_image4",
mp_hub_timeshift = $"rui/menu/level_select/level_image5",
mp_beacon = $"rui/menu/level_select/level_image6",
mp_tday = $"rui/menu/level_select/level_image7",
mp_s2s = $"rui/menu/level_select/level_image8",
mp_skyway_v1 = $"rui/menu/level_select/level_image9",
}
void function MenuPrivateMatch_Init()
{
PrecacheHUDMaterial( $"ui/menu/common/menu_background_neutral" )
PrecacheHUDMaterial( $"ui/menu/common/menu_background_imc" )
PrecacheHUDMaterial( $"ui/menu/common/menu_background_militia" )
PrecacheHUDMaterial( $"ui/menu/common/menu_background_imc_blur" )
PrecacheHUDMaterial( $"ui/menu/common/menu_background_militia_blur" )
PrecacheHUDMaterial( $"ui/menu/common/menu_background_neutral_blur" )
PrecacheHUDMaterial( $"ui/menu/common/menu_background_blackMarket" )
PrecacheHUDMaterial( $"ui/menu/rank_menus/ranked_FE_background" )
PrecacheHUDMaterial( $"ui/menu/lobby/friendly_slot" )
PrecacheHUDMaterial( $"ui/menu/lobby/friendly_player" )
PrecacheHUDMaterial( $"ui/menu/lobby/enemy_slot" )
PrecacheHUDMaterial( $"ui/menu/lobby/enemy_player" )
PrecacheHUDMaterial( $"ui/menu/lobby/neutral_slot" )
PrecacheHUDMaterial( $"ui/menu/lobby/neutral_player" )
PrecacheHUDMaterial( $"ui/menu/lobby/player_hover" )
PrecacheHUDMaterial( $"ui/menu/main_menu/motd_background" )
PrecacheHUDMaterial( $"ui/menu/main_menu/motd_background_happyhour" )
AddUICallback_OnLevelInit( OnPrivateLobbyLevelInit )
}
asset function GetMapImageForMapName( string mapName )
{
if ( mapName in mapImages )
return mapImages[mapName]
// no way to convert string => asset for dynamic stuff so
// pain
return expect asset ( compilestring( "return $\"loadscreens/" + mapName + "_lobby\"" )() )
}
void function InitPrivateMatchMenu()
{
var menu = GetMenu( "PrivateLobbyMenu" )
file.menu = menu
AddMenuEventHandler( menu, eUIEvent.MENU_OPEN, OnPrivateMatchMenu_Open )
AddMenuEventHandler( menu, eUIEvent.MENU_CLOSE, OnLobbyMenu_Close )
AddMenuEventHandler( menu, eUIEvent.MENU_NAVIGATE_BACK, OnLobbyMenu_NavigateBack )
file.startMatchButton = Hud_GetChild( menu, "StartMatchButton" )
Hud_AddEventHandler( file.startMatchButton, UIE_CLICK, OnStartMatchButton_Activate )
RegisterUIVarChangeCallback( "privatematch_map", Privatematch_map_Changed )
RegisterUIVarChangeCallback( "privatematch_mode", Privatematch_mode_Changed )
RegisterUIVarChangeCallback( "privatematch_starting", Privatematch_starting_Changed )
RegisterUIVarChangeCallback( "gameStartTime", GameStartTime_Changed )
file.matchStatusRuis = GetElementsByClassnameForMenus( "MatchmakingStatusRui", uiGlobal.allMenus )
file.MMDevStringElems = GetElementsByClassnameForMenus( "MMDevStringClass", uiGlobal.allMenus )
file.friendlyPlayersPanel = Hud_GetChild( menu, "MatchFriendliesPanel" )
file.enemyPlayersPanel = Hud_GetChild( menu, "MatchEnemiesPanel" )
file.listFriendlies = Hud_GetChild( file.friendlyPlayersPanel, "ListFriendlies" )
file.listEnemies = Hud_GetChild( file.enemyPlayersPanel, "ListEnemies" )
file.friendlyTeamBackgroundPanel = Hud_GetChild( file.friendlyPlayersPanel, "LobbyFriendlyTeamBackground" )
file.enemyTeamBackgroundPanel = Hud_GetChild( file.enemyPlayersPanel, "LobbyEnemyTeamBackground" )
#if PC_PROG
var panelSize = Hud_GetSize( file.enemyPlayersPanel )
Hud_SetSize( Hud_GetChild( menu, "LobbyChatBox" ), panelSize[0], panelSize[1] )
#endif // #if PC_PROG
file.friendlyTeamBackground = Hud_GetChild( file.friendlyTeamBackgroundPanel, "TeamBackground" )
file.enemyTeamBackground = Hud_GetChild( file.enemyTeamBackgroundPanel, "TeamBackground" )
file.teamSlotBackgrounds = GetElementsByClassnameForMenus( "LobbyTeamSlotBackgroundClass", uiGlobal.allMenus )
file.teamSlotBackgroundsNeutral = GetElementsByClassnameForMenus( "LobbyTeamSlotBackgroundNeutralClass", uiGlobal.allMenus )
file.nextMapNameLabel = Hud_GetChild( menu, "NextMapName" )
file.nextGameModeLabel = Hud_GetChild( menu, "NextGameModeName" )
file.callsignCard = Hud_GetChild( menu, "CallsignCard" )
file.spectatorLabel = Hud_GetChild( menu, "SpectatorLabel" )
file.matchSettingsPanel = Hud_GetChild( menu, "MatchSettings" )
SetupComboButtons( menu, file.startMatchButton, file.listFriendlies )
AddMenuFooterOption( menu, BUTTON_A, "#A_BUTTON_SELECT", "" )
AddMenuFooterOption( menu, BUTTON_B, "#B_BUTTON_BACK", "#BACK" )
AddMenuFooterOption( menu, BUTTON_Y, "#Y_BUTTON_SWITCH_TEAMS", "#SWITCH_TEAMS", PCSwitchTeamsButton_Activate, CanSwitchTeams )
AddMenuFooterOption( menu, BUTTON_X, "#X_BUTTON_MUTE", "#MOUSE2_MUTE", null, CanMute )
AddMenuFooterOption( menu, BUTTON_SHOULDER_RIGHT, "#RB_TRIGGER_TOGGLE_SPECTATE", "#SPECTATE_TEAM", PCToggleSpectateButton_Activate, CanSwitchTeams )
AddMenuVarChangeHandler( "focus", UpdateFooterOptions )
AddMenuVarChangeHandler( "isFullyConnected", UpdateFooterOptions )
AddMenuVarChangeHandler( "isPartyLeader", UpdateFooterOptions )
AddMenuVarChangeHandler( "isPrivateMatch", UpdateFooterOptions )
#if DURANGO_PROG
AddMenuVarChangeHandler( "DURANGO_canInviteFriends", UpdateFooterOptions )
AddMenuVarChangeHandler( "DURANGO_isJoinable", UpdateFooterOptions )
AddMenuVarChangeHandler( "DURANGO_isGameFullyInstalled", UpdateFooterOptions )
#elseif PS4_PROG
AddMenuVarChangeHandler( "PS4_canInviteFriends", UpdateFooterOptions )
#elseif PC_PROG
AddMenuVarChangeHandler( "ORIGIN_isEnabled", UpdateFooterOptions )
AddMenuVarChangeHandler( "ORIGIN_isJoinable", UpdateFooterOptions )
#endif
}
void function OnSelectMapButton_Activate( var button )
{
if ( Hud_IsLocked( button ) )
return
AdvanceMenu( GetMenu( "MapsMenu" ) )
}
void function OnSelectModeButton_Activate( var button )
{
if ( Hud_IsLocked( button ) )
return
AdvanceMenu( GetMenu( "ModesMenu" ) )
}
void function OnSelectMatchSettings_Activate( var button )
{
if ( Hud_IsLocked( button ) )
return
if ( !IsNorthstarServer() )
AdvanceMenu( GetMenu( "MatchSettingsMenu" ) )
else
AdvanceMenu( GetMenu( "CustomMatchSettingsCategoryMenu" ) )
}
void function SetupComboButtons( var menu, var navUpButton, var navDownButton )
{
ComboStruct comboStruct = ComboButtons_Create( menu )
file.lobbyComboStruct = comboStruct
comboStruct.navUpButton = navUpButton
comboStruct.navDownButton = navDownButton
int headerIndex = 0
int buttonIndex = 0
file.playHeader = AddComboButtonHeader( comboStruct, headerIndex, "#MENU_HEADER_PRIVATE_MATCH" )
var selectModeButton = AddComboButton( comboStruct, headerIndex, buttonIndex++, "#MENU_TITLE_SELECT_MODE" )
file.selectModeButton = selectModeButton
Hud_AddEventHandler( selectModeButton, UIE_CLICK, OnSelectModeButton_Activate )
var selectMapButton = AddComboButton( comboStruct, headerIndex, buttonIndex++, "#MENU_TITLE_SELECT_MAP" )
file.selectMapButton = selectMapButton
Hud_AddEventHandler( selectMapButton, UIE_CLICK, OnSelectMapButton_Activate )
file.matchSettingsButton = AddComboButton( comboStruct, headerIndex, buttonIndex++, "#MENU_TITLE_MATCH_SETTINGS" )
Hud_AddEventHandler( file.matchSettingsButton, UIE_CLICK, OnSelectMatchSettings_Activate )
if ( !IsNorthstarServer() )
{
var friendsButton = AddComboButton( comboStruct, headerIndex, buttonIndex++, "#MENU_TITLE_INVITE_FRIENDS" )
file.inviteFriendsButton = friendsButton
Hud_AddEventHandler( friendsButton, UIE_CLICK, InviteFriendsIfAllowed )
}
headerIndex++
buttonIndex = 0
file.customizeHeader = AddComboButtonHeader( comboStruct, headerIndex, "#MENU_HEADER_LOADOUTS" )
file.customizeHeaderIndex = headerIndex
var pilotButton = AddComboButton( comboStruct, headerIndex, buttonIndex++, "#MENU_TITLE_PILOT" )
file.pilotButton = pilotButton
Hud_AddEventHandler( pilotButton, UIE_CLICK, AdvanceMenuEventHandler( GetMenu( "EditPilotLoadoutsMenu" ) ) )
var titanButton = AddComboButton( comboStruct, headerIndex, buttonIndex++, "#MENU_TITLE_TITAN" )
file.titanButton = titanButton
Hud_AddEventHandler( titanButton, UIE_CLICK, AdvanceMenuEventHandler( GetMenu( "EditTitanLoadoutsMenu" ) ) )
file.boostsButton = AddComboButton( comboStruct, headerIndex, buttonIndex++, "#MENU_TITLE_BOOSTS" )
Hud_AddEventHandler( file.boostsButton, UIE_CLICK, AdvanceMenuEventHandler( GetMenu( "BurnCardMenu" ) ) )
file.dpadCommsButton = AddComboButton( comboStruct, headerIndex, buttonIndex++, "#MENU_TITLE_COMMS" )
Hud_AddEventHandler( file.dpadCommsButton, UIE_CLICK, OnDpadCommsButton_Activate )
headerIndex++
buttonIndex = 0
file.callsignHeader = AddComboButtonHeader( comboStruct, headerIndex, "#MENU_HEADER_CALLSIGN" )
file.bannerButton = AddComboButton( comboStruct, headerIndex, buttonIndex++, "#MENU_TITLE_BANNER" )
Hud_AddEventHandler( file.bannerButton, UIE_CLICK, AdvanceMenuEventHandler( GetMenu( "CallsignCardSelectMenu" ) ) )
file.patchButton = AddComboButton( comboStruct, headerIndex, buttonIndex++, "#MENU_TITLE_PATCH" )
Hud_AddEventHandler( file.patchButton, UIE_CLICK, AdvanceMenuEventHandler( GetMenu( "CallsignIconSelectMenu" ) ) )
file.factionButton = AddComboButton( comboStruct, headerIndex, buttonIndex++, "#MENU_TITLE_FACTION" )
Hud_AddEventHandler( file.factionButton, UIE_CLICK, AdvanceMenuEventHandler( GetMenu( "FactionChoiceMenu" ) ) )
file.statsButton = AddComboButton( comboStruct, headerIndex, buttonIndex++, "#MENU_TITLE_STATS" )
Hud_AddEventHandler( file.statsButton, UIE_CLICK, AdvanceMenuEventHandler( GetMenu( "ViewStatsMenu" ) ) )
file.callsignCard = Hud_GetChild( menu, "CallsignCard" )
headerIndex++
buttonIndex = 0
file.storeHeader = AddComboButtonHeader( comboStruct, headerIndex, "#MENU_HEADER_STORE" )
file.storeButton = AddComboButton( comboStruct, headerIndex, buttonIndex++, "#MENU_TITLE_STORE_BROWSE" )
Hud_AddEventHandler( file.storeButton, UIE_CLICK, OnStoreButton_Activate )
var storeNewReleasesButton = AddComboButton( comboStruct, headerIndex, buttonIndex++, "#MENU_TITLE_STORE_NEW_RELEASES" )
Hud_AddEventHandler( storeNewReleasesButton, UIE_CLICK, OnStoreNewReleasesButton_Activate )
var storeBundlesButton = AddComboButton( comboStruct, headerIndex, buttonIndex++, "#MENU_TITLE_STORE_BUNDLES" )
Hud_AddEventHandler( storeBundlesButton, UIE_CLICK, OnStoreBundlesButton_Activate )
headerIndex++
buttonIndex = 0
var settingsHeader = AddComboButtonHeader( comboStruct, headerIndex, "#MENU_HEADER_SETTINGS" )
var controlsButton = AddComboButton( comboStruct, headerIndex, buttonIndex++, "#MENU_TITLE_CONTROLS" )
Hud_AddEventHandler( controlsButton, UIE_CLICK, AdvanceMenuEventHandler( GetMenu( "ControlsMenu" ) ) )
#if CONSOLE_PROG
var avButton = AddComboButton( comboStruct, headerIndex, buttonIndex++, "#AUDIO_VIDEO" )
Hud_AddEventHandler( avButton, UIE_CLICK, AdvanceMenuEventHandler( GetMenu( "AudioVideoMenu" ) ) )
#elseif PC_PROG
var videoButton = AddComboButton( comboStruct, headerIndex, buttonIndex++, "#AUDIO" )
Hud_AddEventHandler( videoButton, UIE_CLICK, AdvanceMenuEventHandler( GetMenu( "AudioMenu" ) ) )
var soundButton = AddComboButton( comboStruct, headerIndex, buttonIndex++, "#VIDEO" )
Hud_AddEventHandler( soundButton, UIE_CLICK, AdvanceMenuEventHandler( GetMenu( "VideoMenu" ) ) )
#endif
var knbButton = AddComboButton( comboStruct, headerIndex, buttonIndex++, "#KNB_MENU_HEADER" )
Hud_AddEventHandler( knbButton, UIE_CLICK, AdvanceMenuEventHandler( GetMenu( "KnowledgeBaseMenu" ) ) )
ComboButtons_Finalize( comboStruct )
}
bool function IsPlayerListFocused()
{
var focusedItem = GetFocus()
// The check for GetScriptID existing isn't ideal, but if the text chat text output element has focus it will script error otherwise
return ( (focusedItem != null) && ("GetScriptID" in focusedItem) && (Hud_GetScriptID( focusedItem ) == "PlayerListButton") )
}
bool function MatchResultsExist()
{
return true // TODO
}
bool function CanSwitchTeams()
{
return ( GetMenuVarBool( "isPrivateMatch" ) && ( level.ui.privatematch_starting != ePrivateMatchStartState.STARTING ) )
}
bool function CanMute()
{
return IsPlayerListFocused()
}
void function OnLobbyMenu_Open()
{
Assert( IsConnected() )
UpdatePrivateMatchButtons()
thread UpdateLobbyUI()
thread LobbyMenuUpdate( GetMenu( "PrivateLobbyMenu" ) )
if ( uiGlobal.activeMenu == GetMenu( "PrivateLobbyMenu" ) )
UI_SetPresentationType( ePresentationType.NO_MODELS )
if ( IsFullyConnected() )
{
entity player = GetUIPlayer()
if ( !IsValid( player ) )
return
while ( player.GetPersistentVarAsInt( "initializedVersion" ) < PERSISTENCE_INIT_VERSION )
{
WaitFrame()
}
UpdateCallsignElement( file.callsignCard )
RefreshCreditsAvailable()
bool emotesAreEnabled = EmotesEnabled()
// "Customize"
{
bool anyNewPilotItems = HasAnyNewPilotItems( player )
bool anyNewTitanItems = HasAnyNewTitanItems( player )
bool anyNewBoosts = HasAnyNewBoosts( player )
bool anyNewCommsIcons = false // emotesAreEnabled ? HasAnyNewDpadCommsIcons( player ) : false
bool anyNewCustomizeHeader = (anyNewPilotItems || anyNewTitanItems || anyNewBoosts || anyNewCommsIcons)
RuiSetBool( Hud_GetRui( file.customizeHeader ), "isNew", anyNewCustomizeHeader )
ComboButton_SetNew( file.pilotButton, anyNewPilotItems )
ComboButton_SetNew( file.titanButton, anyNewTitanItems )
ComboButton_SetNew( file.boostsButton, anyNewBoosts )
ComboButton_SetNew( file.dpadCommsButton, anyNewCommsIcons )
if ( !emotesAreEnabled )
{
Hud_Hide( file.dpadCommsButton )
ComboButtons_ResetColumnFocus( file.lobbyComboStruct )
}
else
{
Hud_Show( file.dpadCommsButton )
}
}
// "Store"
{
bool storeIsNew = DLCStoreShouldBeMarkedAsNew()
RuiSetBool( Hud_GetRui( file.storeHeader ), "isNew", storeIsNew )
ComboButton_SetNew( file.storeButton, storeIsNew )
}
// "Callsign"
{
bool anyNewBanners = HasAnyNewCallsignBanners( player )
bool anyNewPatches = HasAnyNewCallsignPatches( player )
bool anyNewFactions = HasAnyNewFactions( player )
bool anyNewCallsignHeader = (anyNewBanners || anyNewPatches || anyNewFactions)
RuiSetBool( Hud_GetRui( file.callsignHeader ), "isNew", anyNewCallsignHeader )
ComboButton_SetNew( file.bannerButton, anyNewBanners )
ComboButton_SetNew( file.patchButton, anyNewPatches )
ComboButton_SetNew( file.factionButton, anyNewFactions )
}
}
}
void function LobbyMenuUpdate( var menu )
{
EndSignal( uiGlobal.signalDummy, "CleanupInGameMenus" )
while ( GetTopNonDialogMenu() == menu )
{
WaitFrame()
}
}
void function OnLobbyMenu_Close()
{
Signal( uiGlobal.signalDummy, "OnCloseLobbyMenu" )
}
void function OnLobbyMenu_NavigateBack()
{
LeaveDialog()
}
function GameStartTime_Changed()
{
printt( "GameStartTime_Changed", level.ui.gameStartTime )
UpdateGameStartTimeCounter()
}
function UpdateGameStartTimeCounter()
{
if ( level.ui.gameStartTime == null )
{
MatchmakingSetSearchText( "" )
MatchmakingSetCountdownTimer( 0.0 )
HideMatchmakingStatusIcons()
return
}
MatchmakingSetSearchText( "#STARTING_IN_LOBBY" )
MatchmakingSetCountdownTimer( expect float( level.ui.gameStartTime + 0.0 ) )
ShowMatchmakingStatusIcons()
}
function UpdateDebugStatus()
{
EndSignal( uiGlobal.signalDummy, "CleanupInGameMenus" )
OnThreadEnd(
function() : ()
{
foreach ( elem in file.MMDevStringElems )
Hud_Hide( elem )
}
)
foreach ( elem in file.MMDevStringElems )
Hud_Show( elem )
while ( true )
{
local strstr = GetLobbyDevString()
foreach ( elem in file.MMDevStringElems )
Hud_SetText( elem, strstr )
WaitFrameOrUntilLevelLoaded()
}
}
void function SetMapInfo( string mapName )
{
var nextMapImage = Hud_GetChild( file.menu, "NextMapImage" )
asset mapImage = GetMapImageForMapName( mapName )
RuiSetImage( Hud_GetRui( nextMapImage ), "basicImage", mapImage )
Hud_Show( nextMapImage )
Hud_SetText( file.nextMapNameLabel, GetMapDisplayName( mapName ) )
}
void function SetModeInfo( string modeName )
{
var nextModeIcon = Hud_GetChild( file.menu, "NextModeIcon" )
RuiSetImage( Hud_GetRui( nextModeIcon ), "basicImage", GetPlaylistThumbnailImage( modeName ) )
Hud_Show( nextModeIcon )
Hud_SetText( file.nextGameModeLabel, GetGameModeDisplayName( modeName ) )
}
function Privatematch_map_Changed()
{
if ( !IsPrivateMatch() )
return
if ( !IsLobby() )
return
string mapName = PrivateMatch_GetSelectedMap()
SetMapInfo( mapName )
}
function Privatematch_mode_Changed()
{
if ( !IsPrivateMatch() )
return
if ( !IsLobby() )
return
string modeName = PrivateMatch_GetSelectedMode()
SetModeInfo( modeName )
UpdatePrivateMatchButtons()
UpdateMatchSettingsForGamemode()
}
function Privatematch_starting_Changed()
{
if ( !IsPrivateMatch() )
return
if ( !IsLobby() )
return
UpdatePrivateMatchButtons()
UpdateFooterOptions()
}
function UpdatePrivateMatchButtons()
{
var menu = file.menu
if ( level.ui.privatematch_starting == ePrivateMatchStartState.STARTING )
{
RHud_SetText( file.startMatchButton, "#STOP_MATCH" )
Hud_SetLocked( file.selectMapButton, true )
Hud_SetLocked( file.selectModeButton, true )
Hud_SetLocked( file.matchSettingsButton, true )
if ( !IsNorthstarServer() )
Hud_SetLocked( file.inviteFriendsButton, true )
}
else
{
RHud_SetText( file.startMatchButton, "#START_MATCH" )
Hud_SetLocked( file.selectMapButton, false )
Hud_SetLocked( file.selectModeButton, false )
if ( !IsNorthstarServer() )
Hud_SetLocked( file.inviteFriendsButton, false )
string modeName = PrivateMatch_GetSelectedMode()
bool settingsLocked = IsFDMode( modeName )
if ( settingsLocked && uiGlobal.activeMenu == GetMenu( "MatchSettingsMenu" ) )
CloseActiveMenu()
Hud_SetLocked( file.matchSettingsButton, settingsLocked )
}
}
function UpdateLobbyUI()
{
if ( uiGlobal.updatingLobbyUI )
return
uiGlobal.updatingLobbyUI = true
thread UpdateLobby()
thread UpdateDebugStatus()
thread UpdatePlayerInfo()
if ( uiGlobal.EOGOpenInLobby )
EOGOpen()
WaitSignal( uiGlobal.signalDummy, "CleanupInGameMenus" )
uiGlobal.updatingLobbyUI = false
}
function UpdateLobby()
{
EndSignal( uiGlobal.signalDummy, "CleanupInGameMenus" )
var menu = file.menu
WaitFrameOrUntilLevelLoaded()
while ( true )
{
if ( !IsConnected() )
{
WaitFrameOrUntilLevelLoaded()
continue
}
menu.RunAnimationScript( "PrivateMatchLobby" )
// Force the animation scripts (which have zero duration) to complete before anything can cancel them.
ForceUpdateHUDAnimations()
UpdatePrivateMatchButtons()
int gamemodeIdx = expect int( level.ui.privatematch_mode )
int numPlaylistOverrides = GetPlaylistVarOverridesCount()
string playlistOverridesDesc = ""
for ( int varIdx = 0; varIdx < numPlaylistOverrides; ++varIdx )
{
// temp fix for playlistoverrides that aren't handled by private match
string varName = GetPlaylistVarOverrideNameByIndex( varIdx )
if ( varName in MatchSettings_PlaylistVarLabels )
{
float varOrigVal = float( GetCurrentPlaylistGamemodeByIndexVar( gamemodeIdx, varName, false ) )
float varOverrideVal = float( GetCurrentPlaylistGamemodeByIndexVar( gamemodeIdx, varName, true ) )
if ( varOrigVal == varOverrideVal && !IsNorthstarServer() ) // stuff seems to break outside of northstar servers since we dont always use private_match playlist
continue
string label = Localize( MatchSettings_PlaylistVarLabels[varName] ) + ": "
string value = MatchSettings_FormatPlaylistVarValue( varName, varOverrideVal )
playlistOverridesDesc = playlistOverridesDesc + label + "`2" + value + " `0\n"
}
else
{
bool shouldBreak = false
foreach ( string category in GetPrivateMatchSettingCategories( true ) )
{
foreach ( CustomMatchSettingContainer setting in GetPrivateMatchCustomSettingsForCategory( category ) )
{
if ( setting.playlistVar == varName )
{
if ( setting.isEnumSetting )
playlistOverridesDesc += Localize( setting.localizedName ) + ": `2" + Localize( setting.enumNames[ setting.enumValues.find( expect string ( GetCurrentPlaylistVar( varName ) ) ) ] ) + "`0\n"
else
playlistOverridesDesc += Localize( setting.localizedName ) + ": `2" + GetCurrentPlaylistVar( varName ) + "`0\n"
shouldBreak = true
break
}
}
if ( shouldBreak )
break
}
}
}
if ( playlistOverridesDesc.len() )
{
RuiSetString( Hud_GetRui( file.matchSettingsPanel ), "description", playlistOverridesDesc )
Hud_Show( file.matchSettingsPanel )
}
else
{
Hud_Hide( file.matchSettingsPanel )
}
if ( GetUIPlayer() && GetPersistentVar( "privateMatchState" ) == 1 )
Hud_SetVisible( file.spectatorLabel, true )
else
Hud_SetVisible( file.spectatorLabel, false )
WaitFrameOrUntilLevelLoaded()
}
}
void function OnSettingsButton_Activate( var button )
{
if ( level.ui.privatematch_starting == ePrivateMatchStartState.STARTING )
return
AdvanceMenu( GetMenu( "MatchSettingsMenu" ) )
}
void function OnPrivateMatchButton_Activate( var button )
{
ShowPrivateMatchConnectDialog()
ClientCommand( "match_playlist private_match" )
ClientCommand( "StartPrivateMatchSearch" )
}
void function OnStartMatchButton_Activate( var button )
{
if ( AmIPartyLeader() || GetPartySize() == 1 )
ClientCommand( "PrivateMatchLaunch" )
}
function HandleLockedCustomMenuItem( menu, button, tipInfo, hideTip = false )
{
array<var> elements = GetElementsByClassname( menu, "HideWhenLocked" )
var buttonTooltip = Hud_GetChild( menu, "ButtonTooltip" )
var toolTipLabel = Hud_GetChild( buttonTooltip, "Label" )
if ( Hud_IsLocked( button ) && !hideTip )
{
foreach( elem in elements )
Hud_Hide( elem )
local tipArray = clone tipInfo
tipInfo.resize( 6, null )
Hud_SetText( toolTipLabel, tipInfo[0], tipInfo[1], tipInfo[2], tipInfo[3], tipInfo[4], tipInfo[5] )
local buttonPos = button.GetAbsPos()
local buttonHeight = button.GetHeight()
local tooltipHeight = buttonTooltip.GetHeight()
local yOffset = ( tooltipHeight - buttonHeight ) / 2.0
buttonTooltip.SetPos( buttonPos[0] + button.GetWidth() * 0.9, buttonPos[1] - yOffset )
Hud_Show( buttonTooltip )
return true
}
else
{
foreach( elem in elements )
Hud_Show( elem )
Hud_Hide( buttonTooltip )
}
return false
}
void function PrivateMatchSwitchTeams( button )
{
if ( !IsPrivateMatch() )
return
if ( !IsConnected() )
return
if ( uiGlobal.activeMenu != file.menu )
return
EmitUISound( "Menu_GameSummary_ScreenSlideIn" )
ClientCommand( "PrivateMatchSwitchTeams" )
}
void function HideMatchmakingStatusIcons()
{
foreach ( element in file.matchStatusRuis )
RuiSetBool( Hud_GetRui( element ), "iconVisible", false )
}
void function ShowMatchmakingStatusIcons()
{
foreach ( element in file.matchStatusRuis )
RuiSetBool( Hud_GetRui( element ), "iconVisible", true )
}
void function MatchmakingSetSearchText( string searchText, var param1 = "", var param2 = "", var param3 = "", var param4 = "" )
{
foreach ( element in file.matchStatusRuis )
{
RuiSetBool( Hud_GetRui( element ), "statusHasText", searchText != "" )
RuiSetString( Hud_GetRui( element ), "statusText", Localize( searchText, param1, param2, param3, param4 ) )
}
}
void function MatchmakingSetCountdownTimer( float time )
{
foreach ( element in file.matchStatusRuis )
{
RuiSetBool( Hud_GetRui( element ), "timerHasText", time != 0.0 )
RuiSetGameTime( Hud_GetRui( element ), "timerEndTime", time )
}
}
void function OnPrivateLobbyLevelInit()
{
UpdateCallsignElement( file.callsignCard )
RefreshCreditsAvailable()
}
function UpdatePlayerInfo()
{
EndSignal( uiGlobal.signalDummy, "CleanupInGameMenus" )
var menu = file.menu
WaitFrameOrUntilLevelLoaded()
while ( true )
{
RefreshCreditsAvailable()
WaitFrame()
}
}
void function OnPrivateMatchMenu_Open()
{
Lobby_SetFDMode( false )
OnLobbyMenu_Open()
} | Squirrel | 5 | GeckoEidechse/NorthstarMods | Northstar.Client/mod/scripts/vscripts/ui/menu_private_match.nut | [
"MIT"
] |
//This configuration file is to test the icm6error element.
//To run the test with another machine, you can change the source address in InfiniteSource (i.e.3ffe:1ce1:2:0:200::2) to the ip6 machine that you want to send the packet to. Also, change the (IP6ADDR ETHADD) pair of IP6NDSolicitor to your click router machines' setting.
//You can use tcpdump on the other ip6 machine to check if it actually acknolowdges the packet.
//Or you can simply change the last line "ToDevice(eth0)" to "Discard" to run the test on local machine.
//-> ToDevice(eth0);
InfiniteSource( \<00 00 c0 ae 67 ef 00 90 27 e0 23 1f 86 dd
60 00 00 00 00 50 11 01 3f fe 1c e1 00 02 00 00
02 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00
00 00 00 00 12 61 02 7d 00 14 d6 41 55 44 50 20
70 61 63 6b 65 74 21 0a 04 00 00 00 01 00 00 00
01 00 00 00 00 00 00 00 00 80 04 08 00 80 04 08
53 53 00 00 53 53 00 00 05 00 00 00 00 10 00 00
01 00 00 00 54 53 00 00 54 e3 04 08 54 e3 04 08
d8 01 00 00 13 69 13 69>, 1, 5)
-> c::Classifier(12/86dd 54/88,
12/86dd);
c[1] -> Print(Rec-IP6packet, 200)
-> Strip(14)
-> CheckIP6Header(3ffe:1ce1:2:0:200::ffff)
-> Print(before-ICMP6Error, 200)
-> dh:: DecIP6HLIM
-> Print(after-dh-0, 200)
-> Discard;
nds :: IP6NDSolicitor(fe80::2a0:c9ff:fe9c:fd9e, 00:a0:c9:9c:fd:9e);
dh[1]-> ICMP6Error(3ffe:1ce1:2:0:200::1, 3, 0)
-> Print(after-ICMP6Error, 200)
-> [0]nds;
c[0]-> Print(Rec:N.Adv, 200) ->[1]nds;
nds[0] -> Print(send:N.AdvOrIP6, 200)
-> Discard;
| Click | 5 | MacWR/Click-changed-for-ParaGraph | conf/icmp6error.click | [
"Apache-2.0"
] |
/*
* Copyright 2014-2019 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.
*/
/**
* ActionBinding provides IPC API binding for actions to be avalable for other processes.
* The obvious example is the Nuvola Player Controller (nuvolaplayer3ctl) using the actions
* to control playback (e.g. play, pause, skip to the next song, etc.).
*/
public class Nuvola.ActionsBinding: ObjectBinding<ActionsInterface> {
public ActionsBinding(Drt.RpcRouter router, WebWorker web_worker) {
base(router, web_worker, "Nuvola.Actions");
}
protected override void bind_methods() {
bind("add-action", Drt.RpcFlags.PRIVATE|Drt.RpcFlags.WRITABLE,
"Add a new action.",
handle_add_action, {
new Drt.StringParam("group", true, false, null, "Action group"),
new Drt.StringParam("scope", true, false, null, "Action scope, use `win` for window-specific actions (preferred) or `app` for app-specific actions."),
new Drt.StringParam("name", true, false, null, "Action name, should be in `dash-separated-lower-case`, e.g. `toggle-play`."),
new Drt.StringParam("label", false, true, null, "Action label shown in user interface, e.g. `Play`."),
new Drt.StringParam("mnemo_label", false, true, null, "Action label shown in user interface with keyboard navigation using Alt key and letter prefixed with underscore, e.g. Alt+p for `_Play`."),
new Drt.StringParam("icon", false, true, null, "Icon name for action."),
new Drt.StringParam("keybinding", false, true, null, "in-app keyboard shortcut, e.g. `<ctrl>P`."),
new Drt.VariantParam("state", false, true, null, "Action state - `null` for simple actions, `true/false` for toggle actions (on/off).")
});
bind("add-radio-action", Drt.RpcFlags.PRIVATE|Drt.RpcFlags.WRITABLE,
"Add a new action.",
handle_add_radio_action, {
new Drt.StringParam("group", true, false, null, "Action group"),
new Drt.StringParam("scope", true, false, null, "Action scope, use `win` for window-specific actions (preferred) or `app` for app-specific actions."),
new Drt.StringParam("name", true, false, null, "Action name, should be in `dash-separated-lower-case`, e.g. `toggle-play`."),
new Drt.VariantParam("state", true, false, null, "Initial state of the action. Must be one of states specified in the `options` array."),
new Drt.VarArrayParam("options", true, false, null, "Array of options definition in form [`stateId`, `label`, `mnemo_label`, `icon`, `keybinding`]. The `stateId` is unique identifier (Number or String), other parameters are described in `add-action` method."),
});
bind("is-enabled", Drt.RpcFlags.READABLE,
"Returns true if action is enabled.",
handle_is_action_enabled, {
new Drt.StringParam("name", true, false, null, "Action name"),
});
bind("set-enabled", Drt.RpcFlags.PRIVATE|Drt.RpcFlags.WRITABLE,
"Sets whether action is enabled.",
handle_action_set_enabled, {
new Drt.StringParam("name", true, false, null, "Action name"),
new Drt.BoolParam("enabled", true, null, "Enabled state")
});
bind("get-state", Drt.RpcFlags.READABLE,
"Returns state of the action.",
handle_action_get_state, {
new Drt.StringParam("name", true, false, null, "Action name")
});
bind("set-state", Drt.RpcFlags.PRIVATE|Drt.RpcFlags.WRITABLE,
"Set state of the action.",
handle_action_set_state, {
new Drt.StringParam("name", true, false, null, "Action name"),
new Drt.VariantParam("state", false, true, null, "Action state")
});
bind("activate", Drt.RpcFlags.WRITABLE,
"Activates action",
handle_action_activate, {
new Drt.StringParam("name", true, false, null, "Action name"),
new Drt.VariantParam("parameter", false, true, null, "Action parameter"),
});
bind("list-groups", Drt.RpcFlags.READABLE,
"Lists action groups.",
handle_list_groups, null);
bind("list-group-actions", Drt.RpcFlags.READABLE,
"Returns actions of the given group.",
handle_list_group_actions, {
new Drt.StringParam("name", true, false, null, "Group name")
});
}
protected override void object_added(ActionsInterface object) {
object.custom_action_activated.connect(on_custom_action_activated);
}
protected override void object_removed(ActionsInterface object) {
object.custom_action_activated.disconnect(on_custom_action_activated);
}
private void handle_add_action(Drt.RpcRequest request) throws Drt.RpcError {
check_not_empty();
string? group = request.pop_string();
string? scope = request.pop_string();
string? action_name = request.pop_string();
string? label = request.pop_string();
string? mnemo_label = request.pop_string();
string? icon = request.pop_string();
string? keybinding = request.pop_string();
Variant? state = request.pop_variant();
if (state != null && state.get_type_string() == "mv") {
state = null;
}
foreach (ActionsInterface object in objects) {
if (object.add_action(group, scope, action_name, label, mnemo_label, icon, keybinding, state)) {
break;
}
}
request.respond(null);
}
private void handle_add_radio_action(Drt.RpcRequest request) throws Drt.RpcError {
check_not_empty();
string? group = request.pop_string();
string? scope = request.pop_string();
string? action_name = request.pop_string();
Variant? state = request.pop_variant();
VariantIter options_iter = request.pop_variant_array();
string? label = null;
string? mnemo_label = null;
string? icon = null;
string? keybinding = null;
Variant? parameter = null;
Drtgtk.RadioOption[] options = new Drtgtk.RadioOption[options_iter.n_children()];
var i = 0;
Variant? array = null; // "v" (new reference)
while (options_iter.next("v", out array)) {
Variant? value = array.get_child_value(0);
parameter = value.get_variant();
value = null;
array.get_child(1, "v", out value);
label = value.is_of_type(VariantType.STRING) ? value.get_string() : null;
value = null;
array.get_child(2, "v", out value);
mnemo_label = value.is_of_type(VariantType.STRING) ? value.get_string() : null;
value = null;
array.get_child(3, "v", out value);
icon = value.is_of_type(VariantType.STRING) ? value.get_string() : null;
value = null;
array.get_child(4, "v", out value);
keybinding = value.is_of_type(VariantType.STRING) ? value.get_string() : null;
value = null;
options[i++] = new Drtgtk.RadioOption(parameter, label, mnemo_label, icon, keybinding);
}
foreach (ActionsInterface object in objects) {
if (object.add_radio_action(group, scope, action_name, state, options)) {
break;
}
}
request.respond(null);
}
private void handle_is_action_enabled(Drt.RpcRequest request) throws Drt.RpcError {
check_not_empty();
string action_name = request.pop_string();
bool enabled = false;
foreach (ActionsInterface object in objects) {
if (object.is_enabled(action_name, ref enabled)) {
break;
}
}
request.respond(new Variant.boolean(enabled));
}
private void handle_action_set_enabled(Drt.RpcRequest request) throws Drt.RpcError {
check_not_empty();
string? action_name = request.pop_string();
bool enabled = request.pop_bool();
foreach (ActionsInterface object in objects) {
if (object.set_enabled(action_name, enabled)) {
break;
}
}
request.respond(null);
}
private void handle_action_get_state(Drt.RpcRequest request) throws Drt.RpcError {
check_not_empty();
string? action_name = request.pop_string();
Variant? state = null;
foreach (ActionsInterface object in objects) {
if (object.get_state(action_name, ref state)) {
break;
}
}
request.respond(state);
}
private void handle_action_set_state(Drt.RpcRequest request) throws Drt.RpcError {
check_not_empty();
string? action_name = request.pop_string();
Variant? state = request.pop_variant();
foreach (ActionsInterface object in objects) {
if (object.set_state(action_name, state)) {
break;
}
}
request.respond(null);
}
private void handle_action_activate(Drt.RpcRequest request) throws Drt.RpcError {
check_not_empty();
string action_name = request.pop_string();
Variant? parameter = request.pop_variant();
bool handled = false;
foreach (ActionsInterface object in objects) {
if (handled = object.activate(action_name, parameter)) {
break;
}
}
request.respond(new Variant.boolean(handled));
}
private void handle_list_groups(Drt.RpcRequest request) throws Drt.RpcError {
check_not_empty();
var groups_set = new GenericSet<string>(str_hash, str_equal);
foreach (ActionsInterface object in objects) {
List<unowned string> groups_list;
bool done = object.list_groups(out groups_list);
foreach (unowned string group in groups_list) {
groups_set.add(group);
}
if (done) {
break;
}
}
var builder = new VariantBuilder(new VariantType ("as"));
List<unowned string> groups = groups_set.get_values();
foreach (unowned string name in groups) {
builder.add_value(new Variant.string(name));
}
request.respond(builder.end());
}
private void handle_list_group_actions(Drt.RpcRequest request) throws Drt.RpcError {
check_not_empty();
string? group_name = request.pop_string();
var builder = new VariantBuilder(new VariantType("aa{sv}"));
foreach (ActionsInterface object in objects) {
List<Drtgtk.Action> actions_list;
bool done = object.list_group_actions(group_name, out actions_list);
foreach (Drtgtk.Action action in actions_list) {
builder.open(new VariantType("a{sv}"));
builder.add("{sv}", "name", new Variant.string(action.name));
builder.add("{sv}", "label", new Variant.string(action.label ?? ""));
builder.add("{sv}", "enabled", new Variant.boolean(action.enabled));
var radio = action as Drtgtk.RadioAction;
if (radio != null) {
var radio_builder = new VariantBuilder(new VariantType("aa{sv}"));
foreach (Drtgtk.RadioOption option in radio.get_options()) {
radio_builder.open(new VariantType("a{sv}"));
radio_builder.add("{sv}", "param", option.parameter);
radio_builder.add("{sv}", "label", new Variant.string(option.label ?? ""));
radio_builder.close();
}
builder.add("{sv}", "options", radio_builder.end());
}
builder.close();
}
if (done) {
break;
}
}
request.respond(builder.end());
}
private void on_custom_action_activated(string name, Variant? parameter) {
try {
var payload = new Variant("(ssmv)", "ActionActivated", name, parameter);
call_web_worker("Nuvola.actions.emit", ref payload);
} catch (GLib.Error e) {
warning("Communication failed: %s", e.message);
}
}
}
| Vala | 5 | xcffl/nuvolaruntime | src/nuvolakit-runner/components/actions/ActionsBinding.vala | [
"BSD-2-Clause"
] |
# Copyright 1999-2020 Gentoo Authors
# Distributed under the terms of the GNU General Public License v2
EAPI=7
inherit eutils bash-completion-r1
DESCRIPTION="Systems programming language from Mozilla"
HOMEPAGE="https://www.rust-lang.org/"
MY_SRC_URI="https://static.rust-lang.org/dist/rust-nightly"
MY_SRC_SRC_URI="https://static.rust-lang.org/dist/rust-src-nightly.tar.xz"
MY_STDLIB_SRC_URI="https://static.rust-lang.org/dist/rust-std-nightly"
if [[ -v RUST_NIGHTLY_DATE ]]; then
MY_SRC_URI="https://static.rust-lang.org/dist/${RUST_NIGHTLY_DATE}/rust-nightly"
MY_SRC_SRC_URI="https://static.rust-lang.org/dist/${RUST_NIGHTLY_DATE}/rust-src-nightly.tar.xz"
MY_STDLIB_SRC_URI="https://static.rust-lang.org/dist/${RUST_NIGHTLY_DATE}/rust-std-nightly"
fi
ALL_RUSTLIB_TARGETS=(
"wasm32-unknown-unknown"
)
ALL_RUSTLIB_TARGETS=( "${ALL_RUSTLIB_TARGETS[@]/#/rustlib_targets_}" )
LICENSE="|| ( MIT Apache-2.0 ) BSD-1 BSD-2 BSD-4 UoI-NCSA"
SLOT="nightly"
KEYWORDS=""
RESTRICT="network-sandbox"
IUSE="clippy cpu_flags_x86_sse2 doc libressl miri rls rust-analyzer rustfmt source ${ALL_RUSTLIB_TARGETS[*]}"
CDEPEND="
>=app-eselect/eselect-rust-0.3_pre20150425
!dev-lang/rust:0
rustfmt? ( !dev-util/rustfmt )
"
DEPEND="${CDEPEND}
net-misc/wget
"
RDEPEND="${CDEPEND}
sys-libs/zlib
!libressl? ( dev-libs/openssl:0= )
libressl? ( dev-libs/libressl:0= )
net-libs/libssh2
net-misc/curl[ssl]
!dev-util/cargo
"
REQUIRED_USE="x86? ( cpu_flags_x86_sse2 )
rls? ( source )
rust-analyzer? ( source )"
QA_PREBUILT="
opt/${P}/bin/*-${PV}
opt/${P}/lib/*.so
opt/${P}/lib/rustlib/*/lib/*.so
opt/${P}/lib/rustlib/*/lib/*.rlib*
"
src_unpack() {
local postfix
use amd64 && postfix=x86_64-unknown-linux-gnu
use x86 && postfix=i686-unknown-linux-gnu
use arm && postfix=armv7-unknown-linux-gnueabihf
use arm64 && postfix=aarch64-unknown-linux-gnu
wget "${MY_SRC_URI}-${postfix}.tar.xz" || die
unpack ./"rust-nightly-${postfix}.tar.xz"
mv "${WORKDIR}/rust-nightly-${postfix}" "${S}" || die
for arch in ${ALL_RUSTLIB_TARGETS}; do
if use ${arch}; then
target=${arch#"rustlib_targets_"}
elog "Adding ${target}..."
wget "${MY_STDLIB_SRC_URI}-${target}.tar.xz" || die
unpack ./"rust-std-nightly-${target}.tar.xz"
mv "${WORKDIR}/rust-std-nightly-${target}/rust-std-${target}" "${S}/" || die
cat "${WORKDIR}/rust-std-nightly-${target}/components" >> "${S}/components"
fi
done
if use source; then
wget "${MY_SRC_SRC_URI}" || die
unpack ./"rust-src-nightly.tar.xz"
mv "${WORKDIR}/rust-src-nightly/rust-src" "${S}/" || die
cat "${WORKDIR}/rust-src-nightly/components" >> "${S}/components"
fi
}
src_install() {
local std=$(grep 'std' ./components | paste -s -d',')
local components="rustc,cargo,${std}"
use doc && components="${components},rust-docs"
use source && components="${components},rust-src"
use clippy && components="${components},clippy-preview"
use miri && components="${components},miri-preview"
if use rls; then
local analysis=$(grep 'analysis' ./components)
components="${components},rls-preview,${analysis}"
fi
if use rust-analyzer; then
local analysis=$(grep 'analysis' ./components)
components="${components},rust-analyzer-preview,${analysis}"
fi
use rustfmt && components="${components},rustfmt-preview"
elog "installing components: ${components}"
./install.sh \
--components="${components}" \
--disable-verify \
--prefix="${D}/opt/${P}" \
--mandir="${D}/usr/share/${P}/man" \
--disable-ldconfig \
|| die
local rustc=rustc-bin-${PV}
local rustdoc=rustdoc-bin-${PV}
local rustgdb=rust-gdb-bin-${PV}
local rustlldb=rust-lldb-bin-${PV}
mv "${D}/opt/${P}/bin/rustc" "${D}/opt/${P}/bin/${rustc}" || die
mv "${D}/opt/${P}/bin/rustdoc" "${D}/opt/${P}/bin/${rustdoc}" || die
mv "${D}/opt/${P}/bin/rust-gdb" "${D}/opt/${P}/bin/${rustgdb}" || die
mv "${D}/opt/${P}/bin/rust-lldb" "${D}/opt/${P}/bin/${rustlldb}" || die
dosym "../../opt/${P}/bin/${rustc}" "/usr/bin/${rustc}"
dosym "../../opt/${P}/bin/${rustdoc}" "/usr/bin/${rustdoc}"
dosym "../../opt/${P}/bin/${rustgdb}" "/usr/bin/${rustgdb}"
dosym "../../opt/${P}/bin/${rustlldb}" "/usr/bin/${rustlldb}"
local cargo=cargo-bin-${PV}
mv "${D}/opt/${P}/bin/cargo" "${D}/opt/${P}/bin/${cargo}" || die
dosym "../../opt/${P}/bin/${cargo}" "/usr/bin/${cargo}"
if use clippy; then
local clippy_driver=clippy-driver-bin-${PV}
local cargo_clippy=cargo-clippy-bin-${PV}
mv "${D}/opt/${P}/bin/clippy-driver" "${D}/opt/${P}/bin/${clippy_driver}" || die
mv "${D}/opt/${P}/bin/cargo-clippy" "${D}/opt/${P}/bin/${cargo_clippy}" || die
dosym "../../opt/${P}/bin/${clippy_driver}" "/usr/bin/${clippy_driver}"
dosym "../../opt/${P}/bin/${cargo_clippy}" "/usr/bin/${cargo_clippy}"
fi
if use miri; then
local miri=miri-bin-${PV}
local cargo_miri=cargo-miri-bin-${PV}
mv "${D}/opt/${P}/bin/miri" "${D}/opt/${P}/bin/${miri}" || die
mv "${D}/opt/${P}/bin/cargo-miri" "${D}/opt/${P}/bin/${cargo_miri}" || die
dosym "../../opt/${P}/bin/${miri}" "/usr/bin/${miri}"
dosym "../../opt/${P}/bin/${cargo_miri}" "/usr/bin/${cargo_miri}"
fi
if use rls; then
local rls=rls-bin-${PV}
mv "${D}/opt/${P}/bin/rls" "${D}/opt/${P}/bin/${rls}" || die
dosym "../../opt/${P}/bin/${rls}" "/usr/bin/${rls}"
fi
if use rust-analyzer; then
local rust_analyzer=rust-analyzer-bin-${PV}
mv "${D}/opt/${P}/bin/rust-analyzer" "${D}/opt/${P}/bin/${rust_analyzer}" || die
dosym "../../opt/${P}/bin/${rust_analyzer}" "/usr/bin/${rust_analyzer}"
fi
if use rustfmt; then
local rustfmt=rustfmt-bin-${PV}
local cargo_fmt=cargo-fmt-bin-${PV}
mv "${D}/opt/${P}/bin/rustfmt" "${D}/opt/${P}/bin/${rustfmt}" || die
mv "${D}/opt/${P}/bin/cargo-fmt" "${D}/opt/${P}/bin/${cargo_fmt}" || die
dosym "../../opt/${P}/bin/${rustfmt}" "/usr/bin/${rustfmt}"
dosym "../../opt/${P}/bin/${cargo_fmt}" "/usr/bin/${cargo_fmt}"
fi
cat <<-EOF > "${T}"/50${P}
LDPATH="/opt/${P}/lib"
MANPATH="/usr/share/${P}/man"
EOF
doenvd "${T}"/50${P}
cat <<-EOF > "${T}/provider-${P}"
/usr/bin/rustdoc
/usr/bin/rust-gdb
/usr/bin/rust-lldb
EOF
echo /usr/bin/cargo >> "${T}/provider-${P}"
if use clippy; then
echo /usr/bin/clippy-driver >> "${T}/provider-${P}"
echo /usr/bin/cargo-clippy >> "${T}/provider-${P}"
fi
if use miri; then
echo /usr/bin/miri >> "${T}/provider-${P}"
echo /usr/bin/cargo-miri >> "${T}/provider-${P}"
fi
if use rls; then
echo /usr/bin/rls >> "${T}/provider-${P}"
fi
if use rust-analyzer; then
echo /usr/bin/rust-analyzer >> "${T}/provider-${P}"
fi
if use rustfmt; then
echo /usr/bin/rustfmt >> "${T}/provider-${P}"
echo /usr/bin/cargo-fmt >> "${T}/provider-${P}"
fi
dodir /etc/env.d/rust
insinto /etc/env.d/rust
doins "${T}/provider-${P}"
}
pkg_postinst() {
eselect rust update --if-unset
elog "Rust installs a helper script for calling GDB now,"
elog "for your convenience it is installed under /usr/bin/rust-gdb-bin-${PV},"
if has_version app-editors/emacs || has_version app-editors/emacs-vcs; then
elog "install app-emacs/rust-mode to get emacs support for rust."
fi
if has_version app-editors/gvim || has_version app-editors/vim; then
elog "install app-vim/rust-vim to get vim support for rust."
fi
if has_version 'app-shells/zsh'; then
elog "install app-shells/rust-zshcomp to get zsh completion for rust."
fi
}
pkg_postrm() {
eselect rust unset --if-invalid
}
| Gentoo Ebuild | 4 | gentoo/gentoo-rust | dev-lang/rust-bin/rust-bin-9999.ebuild | [
"BSD-3-Clause"
] |
#!/usr/bin/env bash
# Copyright 2014 The Flutter Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
set -ex
readonly SCRIPTS_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
readonly ROOT_DIR="$SCRIPTS_DIR/.."
function is_expected_failure() {
# A test target was specified with the 'build' command.
grep --quiet "is not configured for Running" "$1"
}
log_file="build_log_for_104_complete.txt"
build_command="flutter build bundle"
# Attempt to build 104-complete Shrine app from the Flutter codelabs
git clone https://github.com/material-components/material-components-flutter-codelabs.git
cd material-components-flutter-codelabs/mdc_100_series/
git checkout 104-complete
all_builds_ok=1
echo "$build_command"
$build_command 2>&1 | tee "$log_file"
if [ ${PIPESTATUS[0]} -eq 0 ] || is_expected_failure "$log_file"; then
rm "$log_file"
else
all_builds_ok=0
echo "View https://github.com/flutter/flutter/blob/master/dev/bots/README.md for steps to resolve this failed build test." >> ${log_file}
echo
echo "Log left in $log_file."
echo
fi
# If any build failed, exit with a failure exit status so continuous integration
# tools can react appropriately.
if [ "$all_builds_ok" -eq 1 ]; then
exit 0
else
exit 1
fi
| Shell | 4 | Mayb3Nots/flutter | dev/bots/codelabs_build_test.sh | [
"BSD-3-Clause"
] |
// run-pass
#![allow(dead_code)]
// regression test for issue 4875
// pretty-expanded FIXME #23616
pub struct Foo<T> {
data: T,
}
fn foo<T>(Foo{..}: Foo<T>) {
}
pub fn main() {
}
| Rust | 3 | Eric-Arellano/rust | src/test/ui/issues/issue-4875.rs | [
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] |
{% extends 'tests/_data/fixtures/views/templates/b.volt' %}{% block body %}###{{ super() }}###{% endblock %}
| Volt | 2 | tidytrax/cphalcon | tests/_data/fixtures/views/templates/c.volt | [
"BSD-3-Clause"
] |
module openconfig-transport-line-common {
yang-version "1";
// namespace
namespace "http://openconfig.net/yang/transport-line-common";
prefix "oc-line-com";
// import some basic types
import iana-if-type { prefix ift; }
import openconfig-extensions { prefix oc-ext; }
import openconfig-interfaces { prefix oc-if; }
import openconfig-platform { prefix oc-platform; }
import openconfig-types { prefix oc-types; }
import openconfig-transport-types { prefix oc-opt-types; }
// meta
organization "OpenConfig working group";
contact
"OpenConfig working group
www.openconfig.net";
description
"This module defines common data elements for OpenConfig data
models for optical transport line system elements, such as
amplifiers and ROADMs (wavelength routers).";
oc-ext:openconfig-version "0.3.1";
revision "2017-09-08" {
description
"Correct bug with OSC interfaces";
reference "0.3.1";
}
revision "2017-07-08" {
description
"Add monitor port type and refs to hw ports, ";
reference "0.3.0";
}
revision "2017-03-28" {
description
"Added min/max/avg stats, status for media channels, OCM, APS";
reference "0.2.0";
}
revision "2016-03-31" {
description
"Initial public release";
reference "0.1.0";
}
// extension statements
// feature statements
// identity statements
identity OPTICAL_LINE_PORT_TYPE {
description
"Type definition for optical node port types";
}
identity INGRESS {
base OPTICAL_LINE_PORT_TYPE;
description
"Ingress port, corresponding to a signal entering
a line device such as an amplifier or wavelength
router.";
}
identity EGRESS {
base OPTICAL_LINE_PORT_TYPE;
description
"Egress port, corresponding to a signal exiting
a line device such as an amplifier or wavelength
router.";
}
identity ADD {
base OPTICAL_LINE_PORT_TYPE;
description
"Add port, corresponding to a signal injected
at a wavelength router.";
}
identity DROP {
base OPTICAL_LINE_PORT_TYPE;
description
"Drop port, corresponding to a signal dropped
at a wavelength router.";
}
identity MONITOR {
base OPTICAL_LINE_PORT_TYPE;
description
"Monitor port, corresponding to a signal used by an optical
channel monitor. This is used to represent the connection
that a channel monitor port is connected to. This
connection may be via physical cable and faceplate ports or
internal to the device";
}
// typedef statements
// grouping statements
grouping optical-osc-config {
description
"Configuration data for OSC interfaces";
leaf interface {
type oc-if:base-interface-ref;
description
"Reference to an OSC interface";
}
}
grouping optical-osc-state {
description
"Operational state data for OSC interfaces";
container input-power {
description
"The input optical power of this port in units
of 0.01dBm. If avg/min/max statistics are not supported,
the target is expected to just supply the instant value";
uses oc-types:avg-min-max-instant-stats-precision2-dBm;
}
container output-power {
description
"The output optical power of this port in units
of 0.01dBm. If avg/min/max statistics are not supported,
the target is expected to just supply the instant value";
uses oc-types:avg-min-max-instant-stats-precision2-dBm;
}
container laser-bias-current {
description
"The current applied by the system to the transmit laser to
achieve the output power. The current is expressed in mA
with up to one decimal precision. If avg/min/max statistics
are not supported, the target is expected to just supply
the instant value";
uses oc-types:avg-min-max-instant-stats-precision2-mA;
}
}
grouping optical-osc-top {
description
"Top-level grouping for configuration and operational state
data for optical supervisory channels (OSC) for amplifiers,
WSS/ROADM, nodes, etc.";
container config {
description
"Configuration data for OSCs";
uses optical-osc-config;
}
container state {
config false;
description
"Operational state data for OSCs";
uses optical-osc-config;
uses optical-osc-state;
}
}
grouping transport-line-common-port-config {
description
"Configuration data for optical line ports";
leaf admin-state {
type oc-opt-types:admin-state-type;
description
"Sets the admin state of the optical-port";
}
}
grouping transport-line-common-port-state {
description
"Operational state data describing optical line ports";
leaf optical-port-type {
type identityref {
base OPTICAL_LINE_PORT_TYPE;
}
description
"Indicates the type of transport line port. This is an
informational field that should be made available by the
device (e.g., in the openconfig-platform model).";
}
container input-power {
description
"The total input optical power of this port in units
of 0.01dBm. If avg/min/max statistics are not supported,
just supply the instant value";
uses oc-types:avg-min-max-instant-stats-precision2-dBm;
}
container output-power {
description
"The total output optical power of this port in units
of 0.01dBm. If avg/min/max statistics are not supported,
just supply the instant value";
uses oc-types:avg-min-max-instant-stats-precision2-dBm;
}
}
grouping transport-line-common-port-top {
description
"Top-level grouping ";
container optical-port {
description
"Top-level container ";
container config {
description
"Operational config data for optical line ports";
uses transport-line-common-port-config;
}
container state {
config false;
description
"Operational state data for optical line ports";
uses transport-line-common-port-config;
uses transport-line-common-port-state;
}
}
}
// data definition statements
// uses optical-osc-top;
// augment statements
augment "/oc-platform:components/oc-platform:component" {
description
"Adding optical line port data to platform model";
uses transport-line-common-port-top {
when "/oc-platform:components/oc-platform:component/" +
"oc-platform:state/oc-platform:type = 'PORT'" {
description
"Augment is active when component is of type
PORT";
}
}
}
//TODO:this is placeholder until SONET model is added
//to interfaces model
augment "/oc-if:interfaces/oc-if:interface" {
when "oc-if:config/oc-if:type = 'ift:sonet'" {
description "Additional interface configuration parameters when
the interface type is SONET/SDH";
}
description "Adds additional SONET/SDH-specific data to
osc model";
container sonet {
description
"Data related to SONET/SDH interfaces";
}
}
// rpc statements
// notification statements
}
| YANG | 5 | dorado18/public | release/models/optical-transport/openconfig-transport-line-common.yang | [
"Apache-2.0"
] |
# Parameters
param N := read "network.csv" as "1n" use 1 comment "#";
set Ns := {0..N-1};
set N0 := {1..N-1};
param L := read "network.csv" as "2n" use 1 comment "#";
set Ls := {1..L};
param piTp := read "network.csv" as "3n" use 1 comment "#";
param piTd := read "network.csv" as "4n" use 1 comment "#";
param Sb := read "network.csv" as "5n" use 1 comment "#";
param Vb := read "network.csv" as "6n" use 1 comment "#";
param fromBus[Ls] := read "network.csv" as "<1n> 2n" skip 1 use L comment "#";
param toBus[Ls] := read "network.csv" as "<1n> 3n" skip 1 use L comment "#";
param Yg[Ls] := read "network.csv" as "<1n> 4n" skip 1 use L comment "#";
param Yb[Ls] := read "network.csv" as "<1n> 5n" skip 1 use L comment "#";
param C[Ls] := read "network.csv" as "<1n> 6n" skip 1 use L comment "#";
param V0 := read "network.csv" as "2n" skip 1+L use 1 comment "#";
param Vmin[Ns] := read "network.csv" as "3n" skip 1+L use N comment "#";
param Vmax[Ns] := read "network.csv" as "4n" skip 1+L use N comment "#";
param QPRatio[Ns] := read "network.csv" as "5n" skip 1+L use N comment "#";
param minCurtail := read "accessRequests.dat" as "2n" use 1 comment "#";
param EPS := read "accessRequests.dat" as "3n" use 1 comment "#";
param g[Ns] := read "accessRequests.dat" as "<1n> 2n" skip 1 use N comment "#";
param G[Ns] := read "accessRequests.dat" as "<1n> 3n" skip 1 use N comment "#";
# Circle approximation parameters
param maxCPs:=4;
set cps := {1..maxCPs};
param cpCos[{0..maxCPs}] := <0> 1, <1> 0.923879532511287, <2> 0.707106781186548, <3> 0.382683432365090, <4> 0;
param cpSin[{0..maxCPs}] := <0> 0, <1> 0.382683432365090, <2> 0.707106781186547, <3> 0.923879532511287, <4> 1;
# Variables
var pL[<line> in Ls] >= -C[line]/Sb <= C[line]/Sb;
var qL[<line> in Ls] >= -C[line]/Sb <= C[line]/Sb;
var eL[<n> in Ns] >= -infinity;
var fL[<n> in Ns] >= -infinity;
var r0L >= -infinity;
var q0L >= -infinity;
var zetaL[Ns] >= 0;
var nuL[Ns] >= 0;
var pU[<line> in Ls] >= -C[line]/Sb <= C[line]/Sb;
var qU[<line> in Ls] >= -C[line]/Sb <= C[line]/Sb;
var eU[<n> in Ns] >= -infinity;
var fU[<n> in Ns] >= -infinity;
var r0U >= -infinity;
var q0U >= -infinity;
var zetaU[Ns] >= 0;
var nuU[Ns] >= 0;
var dg[<n> in Ns] >= 0 <= -g[n];
var dG[<n> in Ns] >= 0 <= G[n];
var maxDg >= 0;
var maxDG >= 0;
# Objective
minimize accessRestrictions:
maxDg*piTd + maxDG*piTp
+ sum<n> in Ns: ((zetaL[n]+zetaU[n])*piTd*Sb + (nuL[n]+nuU[n])*piTp*Sb);
subto maxDgDefinition:
forall <n> in Ns:
maxDg >= dg[n]/(if abs(g[n]) >= minCurtail then abs(g[n]) else EPS end);
subto maxDGDefinition:
forall <n> in Ns:
maxDG >= dG[n]/(if abs(G[n]) >= minCurtail then abs(G[n]) else EPS end);
subto SlackVolgateEL:
eL[0] == V0/Vb;
subto SlackVolgateFL:
fL[0] == 0;
subto LinkVoltagePL:
forall <line> in Ls :
pL[line] == V0/Vb * (Yg[line]*(eL[fromBus[line]] - eL[toBus[line]]) - Yb[line]*(fL[fromBus[line]] - fL[toBus[line]])) ;
subto LinkVoltageQL:
forall <line> in Ls :
qL[line] == -V0/Vb * (Yb[line]*(eL[fromBus[line]] - eL[toBus[line]]) + Yg[line]*(fL[fromBus[line]] - fL[toBus[line]])) ;
subto BalanceNodePL:
forall <n> in Ns :
(g[n] + dg[n])/Sb
+ if (n==0) then r0L else 0*r0L end
- sum <line> in Ls : if (fromBus[line] == n) then pL[line] else 0*pL[line] end
+ sum <line> in Ls : if (toBus[line] == n) then pL[line] else 0*pL[line] end
== 0;
subto BalanceNodeQL:
forall <n> in Ns :
(g[n] + dg[n])*QPRatio[n]/Sb
+ if (n==0) then q0L else 0*q0L end
- sum <line> in Ls : if (fromBus[line] == n) then qL[line] else 0*qL[line] end
+ sum <line> in Ls : if (toBus[line] == n) then qL[line] else 0*qL[line] end
== 0;
subto MaxPowerNEQuadrantL:
forall <line,cp> in Ls*cps:
(cpSin[cp]-cpSin[cp-1])*pL[line]+(cpCos[cp-1]-cpCos[cp])*qL[line] <= (C[line]/Sb)*(cpSin[cp-1]*(cpCos[cp-1]-cpCos[cp]) - cpCos[cp-1] * (cpSin[cp-1] - cpSin[cp]));
subto MaxPowerNWQuadrantL:
forall <line,cp> in Ls*cps:
-(cpSin[cp]-cpSin[cp-1])*pL[line]+(cpCos[cp-1]-cpCos[cp])*qL[line] <= (C[line]/Sb)*(cpSin[cp-1]*(cpCos[cp-1]-cpCos[cp]) - cpCos[cp-1] * (cpSin[cp-1] - cpSin[cp]));
subto MaxPowerSEQuadrantL:
forall <line,cp> in Ls*cps:
(cpSin[cp]-cpSin[cp-1])*pL[line]-(cpCos[cp-1]-cpCos[cp])*qL[line] <= (C[line]/Sb)*(cpSin[cp-1]*(cpCos[cp-1]-cpCos[cp]) - cpCos[cp-1] * (cpSin[cp-1] - cpSin[cp]));
subto MaxPowerSWQuadrantL:
forall <line,cp> in Ls*cps:
-(cpSin[cp]-cpSin[cp-1])*pL[line]-(cpCos[cp-1]-cpCos[cp])*qL[line] <= (C[line]/Sb)*(cpSin[cp-1]*(cpCos[cp-1]-cpCos[cp]) - cpCos[cp-1] * (cpSin[cp-1] - cpSin[cp]));
subto MinVoltageL:
forall <n> in Ns :
Vmin[n]-zetaL[n] <= eL[n];
subto NEVoltageBoundL:
forall <n,cp> in Ns*cps:
(cpSin[cp]-cpSin[cp-1])*eL[n]+(cpCos[cp-1]-cpCos[cp])*fL[n] <= (Vmax[n]+nuL[n])*(cpSin[cp]*cpCos[cp-1] - cpCos[cp]*cpSin[cp-1]);
subto SEVoltageBoundL:
forall <n,cp> in Ns*cps:
(cpSin[cp]-cpSin[cp-1])*eL[n]-(cpCos[cp-1]-cpCos[cp])*fL[n] <= (Vmax[n]+nuL[n])*(cpSin[cp]*cpCos[cp-1] - cpCos[cp]*cpSin[cp-1]);
subto SlackVolgateEU:
eU[0] == V0/Vb;
subto SlackVolgateFU:
fU[0] == 0;
subto LinkVoltagePU:
forall <line> in Ls :
pU[line] == V0/Vb * (Yg[line]*(eU[fromBus[line]] - eU[toBus[line]]) - Yb[line]*(fU[fromBus[line]] - fU[toBus[line]])) ;
subto LinkVoltageQU:
forall <line> in Ls :
qU[line] == -V0/Vb * (Yb[line]*(eU[fromBus[line]] - eU[toBus[line]]) + Yg[line]*(fU[fromBus[line]] - fU[toBus[line]])) ;
subto BalanceNodePU:
forall <n> in Ns :
(G[n] - dG[n])/Sb
+ if (n==0) then r0U else 0*r0U end
- sum <line> in Ls : if (fromBus[line] == n) then pU[line] else 0*pU[line] end
+ sum <line> in Ls : if (toBus[line] == n) then pU[line] else 0*pU[line] end
== 0;
subto BalanceNodeQU:
forall <n> in Ns :
(G[n] - dG[n])*QPRatio[n]/Sb
+ if (n==0) then q0U else 0*q0U end
- sum <line> in Ls : if (fromBus[line] == n) then qU[line] else 0*qU[line] end
+ sum <line> in Ls : if (toBus[line] == n) then qU[line] else 0*qU[line] end
== 0;
subto MaxPowerNEQuadrantU:
forall <line,cp> in Ls*cps:
(cpSin[cp]-cpSin[cp-1])*pU[line]+(cpCos[cp-1]-cpCos[cp])*qU[line] <= (C[line]/Sb)*(cpSin[cp-1]*(cpCos[cp-1]-cpCos[cp]) - cpCos[cp-1] * (cpSin[cp-1] - cpSin[cp]));
subto MaxPowerNWQuadrantU:
forall <line,cp> in Ls*cps:
-(cpSin[cp]-cpSin[cp-1])*pU[line]+(cpCos[cp-1]-cpCos[cp])*qU[line] <= (C[line]/Sb)*(cpSin[cp-1]*(cpCos[cp-1]-cpCos[cp]) - cpCos[cp-1] * (cpSin[cp-1] - cpSin[cp]));
subto MaxPowerSEQuadrantU:
forall <line,cp> in Ls*cps:
(cpSin[cp]-cpSin[cp-1])*pU[line]-(cpCos[cp-1]-cpCos[cp])*qU[line] <= (C[line]/Sb)*(cpSin[cp-1]*(cpCos[cp-1]-cpCos[cp]) - cpCos[cp-1] * (cpSin[cp-1] - cpSin[cp]));
subto MaxPowerSWQuadrantU:
forall <line,cp> in Ls*cps:
-(cpSin[cp]-cpSin[cp-1])*pU[line]-(cpCos[cp-1]-cpCos[cp])*qU[line] <= (C[line]/Sb)*(cpSin[cp-1]*(cpCos[cp-1]-cpCos[cp]) - cpCos[cp-1] * (cpSin[cp-1] - cpSin[cp]));
subto MinVoltageU:
forall <n> in Ns :
Vmin[n]-zetaU[n] <= eU[n];
subto NEVoltageBoundU:
forall <n,cp> in Ns*cps:
(cpSin[cp]-cpSin[cp-1])*eU[n]+(cpCos[cp-1]-cpCos[cp])*fU[n] <= (Vmax[n]+nuU[n])*(cpSin[cp]*cpCos[cp-1] - cpCos[cp]*cpSin[cp-1]);
subto SEVoltageBoundU:
forall <n,cp> in Ns*cps:
(cpSin[cp]-cpSin[cp-1])*eU[n]-(cpCos[cp-1]-cpCos[cp])*fU[n] <= (Vmax[n]+nuU[n])*(cpSin[cp]*cpCos[cp-1] - cpCos[cp]*cpSin[cp-1]);
| Zimpl | 4 | sebMathieu/dsima | simulator/models/DSO-linearOpf-accessAgreement.zpl | [
"BSD-3-Clause"
] |
#summary People who contributed to this project
= About =
A successful project requires many people to play many roles. Some members write code or documentation, while others are valuable as testers, submitting patches and suggestions.
==Founders==
|| *Name* ||
|| [https://github.com/alexo Alex Objelean] ||
|| Bogdan Csoregi ||
==Contributors==
The following is a list of developers that have directly contributed to the project.
|| *Name* ||
|| [https://github.com/alf239 Alexey Filippov] ||
|| [https://github.com/dmitrye Dmitry Erman] ||
|| [https://github.com/eivindw Eivind Barstad Waaler] ||
|| [https://github.com/gconaty Garrett Conaty] ||
|| [https://github.com/ivarconr Ivar Conradi Østhus] ||
|| [https://github.com/julienwOL Julien Wajsberg] ||
|| [https://github.com/lltyk lltyk] ||
|| [https://github.com/martin-g Martin Grigorov] ||
|| Matias Mirabelli ||
|| [https://github.com/michael-simons Michael J. Simons] ||
|| [https://github.com/nigelzor Neil Gentleman] ||
|| [https://github.com/olgamelnichuk Olga Melnichuk] ||
|| Ovidiu Hurducas ||
|| [https://github.com/filirom1 Romain Philibert] ||
|| [https://github.com/sebastianco Sebastian Cotarla] ||
|| [https://github.com/blemoine Benoit Lemoine] ||
|| [https://github.com/mwanji Moandji Ezana] ||
Sorry if somebody was missed (can be added anytime) | MediaWiki | 2 | supakiad/wro4j | docs/TheTeam.wiki | [
"Apache-2.0"
] |
apiVersion: release-notes/v2
kind: bug-fix
area: istioctl
releaseNotes:
- |
**Fixed** `istioctl profile diff` and `istioctl profile dump` have unexpected info logs.
| YAML | 1 | rveerama1/istio | releasenotes/notes/34325.yaml | [
"Apache-2.0"
] |
/* Copyright 2021 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_KERNELS_GPU_PRIM_HELPERS_H_
#define TENSORFLOW_CORE_KERNELS_GPU_PRIM_HELPERS_H_
#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM
#define EIGEN_USE_GPU
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/kernels/gpu_prim.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/util/gpu_kernel_helper.h"
#include "tensorflow/stream_executor/stream.h"
namespace tensorflow {
namespace detail {
template <typename T>
__global__ void RangeInitKernel(const T start, const T delta, const T size,
T* out) {
GPU_1D_KERNEL_LOOP(i, size) { out[i] = start + i * delta; }
}
// Initialize out with range start, start + delta, start + 2 * delta, ...
template <typename T>
Status RangeInit(const Eigen::GpuDevice& d, const T start, const T delta,
const T size, T* out) {
if (size == 0) return Status::OK();
GpuLaunchConfig config = GetGpuLaunchConfig(size, d);
return GpuLaunchKernel(RangeInitKernel<T>, config.block_count,
config.thread_per_block, 0, d.stream(), start, delta,
size, out);
}
} // namespace detail
// Computes keys_out = sorted(keys_in), and indices_out = argsort(keys_in).
// If keys_out is not required, it can be set to nullptr.
// If indices_in is nullptr, the range of input indices [0, size) will be used.
template <typename Tkey, typename Tindex>
Status GpuRadixSort(OpKernelContext* context, int size, const Tkey* keys_in,
Tkey* keys_out, // Optional
const Tindex* indices_in, // Optional
Tindex* indices_out, int num_bits = sizeof(Tkey) * 8) {
if (size == 0) return Status::OK();
if (num_bits == 0) {
// Workaround for CUB failing when begin_bit = end_bit = 0 (e.g., when all
// keys are 0, so no sorting is needed).
se::Stream* stream = context->op_device_context()->stream();
if (keys_out) {
// Copy keys_in to keys_out.
size_t num_bytes = size * sizeof(Tkey);
se::DeviceMemoryBase src(const_cast<Tkey*>(keys_in), num_bytes);
se::DeviceMemoryBase dst(keys_out, num_bytes);
if (!stream->ThenMemcpy(&dst, src, num_bytes).ok()) {
return errors::Internal("Failed to copy keys_in to keys_out");
}
}
if (indices_in) {
// Copy indices_in to indices_out.
size_t num_bytes = size * sizeof(Tindex);
se::DeviceMemoryBase src(const_cast<Tindex*>(indices_in), num_bytes);
se::DeviceMemoryBase dst(indices_out, num_bytes);
if (!stream->ThenMemcpy(&dst, src, num_bytes).ok()) {
return errors::Internal("Failed to copy indices_in to indices_out");
}
} else {
// Set output indices to range.
const Eigen::GpuDevice& device =
context->eigen_device<Eigen::GpuDevice>();
TF_RETURN_IF_ERROR(detail::RangeInit(device, Tindex(0), Tindex(1),
Tindex(size), indices_out));
}
return Status::OK();
}
// Allocate temporary inputs/outputs if necessary.
Tensor tmp_indices_in;
if (!indices_in) {
TF_RETURN_IF_ERROR(context->allocate_temp(
DataTypeToEnum<Tindex>::value, TensorShape({size}), &tmp_indices_in));
Tindex* mutable_indices_in = tmp_indices_in.flat<Tindex>().data();
indices_in = mutable_indices_in;
const Eigen::GpuDevice& device = context->eigen_device<Eigen::GpuDevice>();
// Initialize indices_in to the input index range.
TF_RETURN_IF_ERROR(detail::RangeInit(device, Tindex(0), Tindex(1),
Tindex(size), mutable_indices_in));
}
Tensor tmp_keys_out;
if (!keys_out) {
TF_RETURN_IF_ERROR(context->allocate_temp(
DataTypeToEnum<Tkey>::value, TensorShape({size}), &tmp_keys_out));
keys_out = tmp_keys_out.flat<Tkey>().data();
}
// Determine temporary device storage requirements.
Tensor temp_storage;
size_t temp_storage_bytes = 0;
const auto& cu_stream = GetGpuStream(context);
auto err = gpuprim::DeviceRadixSort::SortPairs(
nullptr, temp_storage_bytes, keys_in, keys_out, indices_in, indices_out,
size, /*begin_bit=*/0, /*end_bit=*/num_bits, cu_stream);
if (err != 0) {
return errors::Internal(
"Failed to launch gpuprim::DeviceRadixSort::SortPairs to calculate "
"temp_storage_bytes, status: ",
cudaGetErrorString(err));
}
// Allocate temporary storage.
TF_RETURN_IF_ERROR(context->allocate_temp(
DT_INT8, TensorShape({static_cast<int64_t>(temp_storage_bytes)}),
&temp_storage));
// Sort indices by keys.
err = gpuprim::DeviceRadixSort::SortPairs(
temp_storage.flat<int8>().data(), temp_storage_bytes, keys_in, keys_out,
indices_in, indices_out, size, /*begin_bit=*/0, /*end_bit=*/num_bits,
cu_stream);
if (err != 0) {
return errors::Internal(
"Failed to launch gpuprim::DeviceRadixSort::SortPairs, "
"temp_storage_bytes: ",
temp_storage_bytes, "status: ", cudaGetErrorString(err));
}
return Status::OK();
}
template <typename InputIteratorT, typename OutputIteratorT>
Status GpuInclusivePrefixSum(OpKernelContext* context, int size,
InputIteratorT input, OutputIteratorT output) {
static_assert(
!std::is_same<typename std::remove_reference<decltype(*input)>::type,
bool>::value,
"GpuInclusivePrefixSum does not work correct with booleans, please use "
"TransformInputIterator to explicitly cast to an integer.");
if (size == 0) return Status::OK();
const auto& cu_stream = GetGpuStream(context);
size_t temp_storage_bytes;
auto err = gpuprim::DeviceScan::InclusiveSum(nullptr, temp_storage_bytes,
input, output, size, cu_stream);
if (err != 0) {
return errors::Internal(
"Failed to launch gpuprim::DeviceScan::InclusiveSum to calculate "
"temp_storage_bytes, status: ",
cudaGetErrorString(err));
}
Tensor temp_storage;
TF_RETURN_IF_ERROR(context->allocate_temp(
DT_INT8, TensorShape({static_cast<int64_t>(temp_storage_bytes)}),
&temp_storage));
err = gpuprim::DeviceScan::InclusiveSum(temp_storage.flat<int8>().data(),
temp_storage_bytes, input, output,
size, cu_stream);
if (err != 0) {
return errors::Internal(
"Failed to launch gpuprim::DeviceScan::InclusiveSum, "
"temp_storage_bytes: ",
temp_storage_bytes, ", status: ", cudaGetErrorString(err));
}
return Status::OK();
}
// Note that this behaves deterministically for repeat calls on the same device.
template <typename InputIteratorT, typename OutputIteratorT,
typename OffsetIteratorT, typename ReduceOp, typename T>
Status GpuSegmentedReduce(
OpKernelContext* context, int num_segments, ReduceOp reduce_op,
const T& initial_value,
InputIteratorT input, // [any]
OffsetIteratorT segment_offsets, // [num_segments + 1]
OutputIteratorT output) { // [num_segments]
if (num_segments == 0) return Status::OK();
const auto& cu_stream = GetGpuStream(context);
size_t temp_storage_bytes;
auto err = gpuprim::DeviceSegmentedReduce::Reduce(
nullptr, temp_storage_bytes, input, output, num_segments, segment_offsets,
segment_offsets + 1, reduce_op, initial_value, cu_stream);
if (err != 0) {
return errors::Internal(
"Failed to launch gpuprim::DeviceSegmentedReduce::Reduce to calculate "
"temp_storage_bytes, status: ",
cudaGetErrorString(err));
}
Tensor temp_storage;
TF_RETURN_IF_ERROR(context->allocate_temp(
DT_INT8, TensorShape({static_cast<int64_t>(temp_storage_bytes)}),
&temp_storage));
err = gpuprim::DeviceSegmentedReduce::Reduce(
temp_storage.flat<int8>().data(), temp_storage_bytes, input, output,
num_segments, segment_offsets, segment_offsets + 1, reduce_op,
initial_value, cu_stream);
if (err != 0) {
return errors::Internal(
"Failed to launch gpuprim::DeviceSegmentedReduce::Reduce"
", temp_storage_bytes: ",
temp_storage_bytes, ", status: ", cudaGetErrorString(err));
}
return Status::OK();
}
template <typename InputIteratorT, typename FlagIteratorT,
typename OutputIteratorT, typename NumSelectedT = int>
Status GpuSelectFlagged(OpKernelContext* context, int size,
InputIteratorT input, FlagIteratorT flags,
OutputIteratorT output,
NumSelectedT* out_num_selected = nullptr) {
const auto& cu_stream = GetGpuStream(context);
Tensor out_num_selected_t;
if (!out_num_selected) {
TF_RETURN_IF_ERROR(
context->allocate_temp(DataTypeToEnum<NumSelectedT>::value,
TensorShape({}), &out_num_selected_t));
out_num_selected = out_num_selected_t.scalar<NumSelectedT>().data();
}
size_t temp_storage_bytes;
auto err =
gpuprim::DeviceSelect::Flagged(nullptr, temp_storage_bytes, input, flags,
output, out_num_selected, size, cu_stream);
if (err != 0) {
return errors::Internal(
"Failed to launch gpuprim::DeviceSelect::Flagged to calculate "
"temp_storage_bytes, status: ",
cudaGetErrorString(err));
}
Tensor temp_storage;
TF_RETURN_IF_ERROR(context->allocate_temp(
DT_INT8, TensorShape({static_cast<int64_t>(temp_storage_bytes)}),
&temp_storage));
err = gpuprim::DeviceSelect::Flagged(temp_storage.flat<int8>().data(),
temp_storage_bytes, input, flags, output,
out_num_selected, size, cu_stream);
if (err != 0) {
return errors::Internal(
"Failed to launch gpuprim::DeviceSelect::Flagged, temp_storage_bytes: ",
temp_storage_bytes, ", status: ", cudaGetErrorString(err));
}
return Status::OK();
}
} // namespace tensorflow
#endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM
#endif // TENSORFLOW_CORE_KERNELS_GPU_PRIM_HELPERS_H_
| C | 5 | EricRemmerswaal/tensorflow | tensorflow/core/kernels/gpu_prim_helpers.h | [
"Apache-2.0"
] |
BH1J? | PureBasic | 2 | pchandrasekaran1595/onnx | onnx/backend/test/data/node/test_adam_multiple/test_data_set_0/input_8.pb | [
"Apache-2.0"
] |
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8"/>
<title>Spring Utils Demo</title>
<style type="text/css">
.param{
color:green;
font-style: italic;
}
</style>
</head>
<body>
Parameter set by you: <p th:text="${parameter}" class="param"/>
</body>
</html> | HTML | 3 | zeesh49/tutorials | spring-custom-aop/src/main/resources/templates/other.html | [
"MIT"
] |
#+TITLE: lang/factor
#+DATE: December 3, 2019
#+SINCE: v3.0.0
#+STARTUP: inlineimages
* Table of Contents :TOC_3:noexport:
- [[#description][Description]]
- [[#module-flags][Module Flags]]
- [[#plugins][Plugins]]
- [[#hacks][Hacks]]
- [[#prerequisites][Prerequisites]]
- [[#configuration][Configuration]]
- [[#troubleshooting][Troubleshooting]]
* Description
This module adds support to the [[https://github.com/factor/factor][factor]] programming language and its associated
_fuel_ emacs plugin.
+ If possible, include a brief list of feature highlights here
+ Like code completion, syntax checking or available snippets
+ Include links to packages & external things where possible
** Module Flags
This module provides no flags.
** Plugins
{A list of linked plugins}
** Hacks
{A list of internal modifications to included packages}
* Prerequisites
You must install [[https://github.com/factor/factor][factor]] to use the advanced functionality of this module.
* Configuration
This module requires the installation of factor to be available at
=fuel-factor-root-dir=. Here's an example of how to set it:
#+BEGIN_SRC emacs-lisp
(setq fuel-factor-root-dir "/Applications/factor")
#+END_SRC
* Troubleshooting
Common issues and their solution, or places to look for help.
| Org | 3 | leezu/doom-emacs | modules/lang/factor/README.org | [
"MIT"
] |
/* eslint react/no-danger: 0 */
import React from 'react';
import ReactDOM from 'react-dom';
import _ from 'underscore';
import {Actions, WorkspaceStore, DOMUtils} from 'nylas-exports';
import NylasStore from 'nylas-store';
const TipsBackgroundEl = document.createElement('tutorial-tip-background');
const TipsContainerEl = document.createElement('div');
TipsContainerEl.classList.add('tooltips-container');
document.body.appendChild(TipsContainerEl);
class TipsStoreCls extends NylasStore {
constructor() {
super();
this._tipKeys = [];
}
isTipVisible(key) {
const seen = NylasEnv.config.get('core.tutorial.seen') || [];
return this._tipKeys.find(t => !seen.includes(t)) === key;
}
hasSeenTip(key) {
return (NylasEnv.config.get('core.tutorial.seen') || []).includes(key);
}
// Actions: Since this is a private store just inside this file, we call
// these methods directly for now.
mountedTip = (key) => {
if (!this._tipKeys.includes(key)) {
this._tipKeys.push(key);
}
this.trigger();
}
seenTip = (key) => {
this._tipKeys = this._tipKeys.filter(t => t !== key);
NylasEnv.config.pushAtKeyPath('core.tutorial.seen', key);
this.trigger();
}
unmountedTip = (key) => {
this._tipKeys = this._tipKeys.filter(t => t !== key);
this.trigger();
}
}
const TipsStore = new TipsStoreCls();
class TipPopoverContents extends React.Component {
static propTypes = {
title: React.PropTypes.string,
tipKey: React.PropTypes.string,
instructions: React.PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.element]),
onDismissed: React.PropTypes.func,
}
componentDidMount() {
if (TipsBackgroundEl.parentNode === null) {
document.body.appendChild(TipsBackgroundEl);
}
window.requestAnimationFrame(() => {
TipsBackgroundEl.classList.add('visible');
});
}
componentWillUnmount() {
TipsBackgroundEl.classList.remove('visible');
if (this.props.onDismissed) {
this.props.onDismissed();
}
}
onDone = () => {
TipsStore.seenTip(this.props.tipKey);
Actions.closePopover();
}
render() {
let content = null;
if (typeof this.props.instructions === 'string') {
content = <p dangerouslySetInnerHTML={{__html: this.props.instructions}} />;
} else {
content = <p>{this.props.instructions}</p>
}
return (
<div style={{width: 250, padding: 20, paddingTop: 0}}>
<h2>{this.props.title}</h2>
{content}
<button className="btn" onClick={this.onDone}>Got it!</button>
</div>
);
}
}
export default function HasTutorialTip(ComposedComponent, TipConfig) {
const TipKey = ComposedComponent.displayName;
if (!TipKey) {
throw new Error("To use the HasTutorialTip decorator, your component must have a displayName.");
}
if (TipsStore.hasSeenTip(TipKey)) {
return ComposedComponent;
}
return class extends React.Component {
static displayName = ComposedComponent.displayName;
static containerRequired = ComposedComponent.containerRequired;
static containerStyles = ComposedComponent.containerStyles;
constructor(props) {
super(props);
this._unlisteners = [];
this.state = {visible: false};
}
componentDidMount() {
TipsStore.mountedTip(TipKey);
this._unlisteners = [
TipsStore.listen(this._onTooltipStateChanged),
WorkspaceStore.listen(() => {
this._workspaceTimer = setTimeout(this._onTooltipStateChanged, 0);
}),
]
this._disposables = [
NylasEnv.themes.onDidChangeActiveThemes(() => {
this._themesTimer = setTimeout(this._onRecomputeTooltipPosition, 0);
}),
]
window.addEventListener('resize', this._onRecomputeTooltipPosition);
// unfortunately, we can't render() a container around ComposedComponent
// without modifying the DOM tree and messing with things like flexbox.
// Instead, we leave render() unchanged and attach the bubble and hover
// listeners to the DOM manually.
const el = ReactDOM.findDOMNode(this);
this.tipNode = document.createElement('div');
this.tipNode.classList.add('tutorial-tip');
this.tipAnchor = el.closest('[data-tooltips-anchor]') || document.body;
this.tipAnchor.querySelector('.tooltips-container').appendChild(this.tipNode);
el.addEventListener('mouseover', this._onMouseOver);
this._onTooltipStateChanged();
}
componentDidUpdate() {
if (this.state.visible) {
this._onRecomputeTooltipPosition();
}
}
componentWillUnmount() {
this._unlisteners.forEach((unlisten) => unlisten())
this._disposables.forEach((disposable) => disposable.dispose())
window.removeEventListener('resize', this._onRecomputeTooltipPosition);
this.tipNode.parentNode.removeChild(this.tipNode);
clearTimeout(this._workspaceTimer);
clearTimeout(this._themesTimer);
TipsStore.unmountedTip(TipKey);
}
_containingSheetIsVisible = (el) => {
const sheetEl = el.closest('.sheet') || el.closest('.sheet-toolbar-container');
if (!sheetEl) {
return true;
}
return (sheetEl.dataset.id === WorkspaceStore.topSheet().id);
}
_isVisible = () => {
const el = ReactDOM.findDOMNode(this);
return (
TipsStore.isTipVisible(TipKey) &&
this._containingSheetIsVisible(el) &&
DOMUtils.nodeIsVisible(el)
)
}
_onTooltipStateChanged = () => {
const visible = this._isVisible()
if (this.state.visible !== visible) {
this.setState({visible});
if (visible) {
this.tipNode.classList.add('visible');
this._onRecomputeTooltipPosition();
} else {
this.tipNode.classList.remove('visible');
}
}
}
_onMouseOver = () => {
if (!this.state.visible) {
return;
}
const el = ReactDOM.findDOMNode(this);
el.removeEventListener('mouseover', this._onMouseOver);
const tipRect = this.tipNode.getBoundingClientRect();
const tipFocusCircleRadius = 64;
const rect = ReactDOM.findDOMNode(this).getBoundingClientRect();
const rectCX = Math.round(rect.left + rect.width / 2 - tipFocusCircleRadius);
const rectCY = Math.round(rect.top + rect.height / 2 - tipFocusCircleRadius);
TipsBackgroundEl.style.webkitMaskPosition = `0 0, ${rectCX}px ${rectCY}px`;
Actions.openPopover((
<TipPopoverContents
tipKey={TipKey}
title={TipConfig.title}
instructions={TipConfig.instructions}
onDismissed={() => {
el.addEventListener('mouseover', this._onMouseOver);
}}
/>
), {
originRect: tipRect,
direction: 'down',
fallbackDirection: 'up',
})
}
_onRecomputeTooltipPosition = () => {
const el = ReactDOM.findDOMNode(this);
let settled = 0;
let last = {};
const attempt = () => {
const {left, top} = el.getBoundingClientRect();
const anchorRect = this.tipAnchor.getBoundingClientRect();
this.tipNode.style.left = `${left - anchorRect.left + 5}px`;
this.tipNode.style.top = `${Math.max(top - anchorRect.top + 5, 10)}px`;
if (!_.isEqual(last, {left, top})) {
settled = 0;
last = {left, top};
}
settled += 1;
if (settled < 5) {
window.requestAnimationFrame(attempt);
}
}
attempt();
}
render() {
return (
<ComposedComponent {...this.props} />
);
}
}
}
| JSX | 4 | cnheider/nylas-mail | packages/client-app/src/components/decorators/has-tutorial-tip.jsx | [
"MIT"
] |
Rem
Float is a 32 bit floating point BlitzMax primitive type.
End Rem
Local a:float
a=1
for i=1 to 8
print a
a=a*0.1
next
for i=1 to 8
a=a*10
print a
next
| BlitzMax | 3 | jabdoa2/blitzmax | mod/brl.mod/blitz.mod/doc/float.bmx | [
"Zlib"
] |
:coffeescript
alert "Hello, Coffee!" | Scaml | 0 | maslovalex/scalate | scalate-core/src/test/resources/org/fusesource/scalate/scaml/coffee.scaml | [
"Apache-2.0"
] |
@keyframes why{0%{color:red}100%{color:blue}} | CSS | 3 | Theo-Steiner/svelte | test/css/samples/global-keyframes-with-no-elements/expected.css | [
"MIT"
] |
# this is a GNUPLOT script generating the figure of spi_master_freq_tv.png
set xlabel "Input delay (ns)"
set xrange [0: 125]
set ylabel "Fmax (MHz)"
set yrange [0: 81]
set xtics 12.5 textcolor rgb "black"
set ytics 10 textcolor rgb "black"
set border 3 lc rgb "gray" lw 2
set grid lt -1 lc rgb "gray" lw 2
set samples 10000
set terminal png size 700,500
set output "plot.png"
apb = 12.5
#each line is broken into 10 pieces by the range determined by i
f1(i,x) = (x>= i*apb) && (x < (i+1)*apb) ? 80./(i+1) : 1/0
set style circle radius graph 0.008
#solid and empty circles are draw by the coordinates given in the csv
plot [0:125]\
f1(-1, x) lw 3lc rgb "blue" title "IOMUX",\
for [i=0:9] f1(i, x) with lines lw 3 lc rgb "blue" notitle,\
f1(0, x+25) lw 3 lc rgb "red" title "GPIO",\
for [i=2:11] f1(i, x+25) with lines lw 3 lc rgb "red" notitle, \
"tv.csv" using 1:2 with circles notitle fill solid fc rgb "blue", \
"tv.csv" using 1:4 with circles notitle fc rgb "blue",\
"tv.csv" using 1:3 with circles notitle fill solid fc rgb "red" ,\
"tv.csv" using 1:5 with circles notitle fc rgb "red"
| Gnuplot | 3 | DCNick3/esp-idf | docs/_static/diagrams/spi/spi_master_freq_tv.plt | [
"Apache-2.0"
] |
fileFormatVersion: 2
guid: 3def27a586fdac545a71c421a4593354
timeCreated: 1483528414
licenseType: Pro
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:
| Unity3D Asset | 0 | jiahaodev/xLua | Test/UnitTest/StreamingAssets/luaCallCsReflect.lua.meta | [
"BSD-3-Clause"
] |
.update-package-dependencies-status .loading.inline-block {
vertical-align: text-bottom;
}
| Less | 1 | Embodimentgeniuslm3/BDB11A0E2DE062D2E39E4C5301B2FE5E | packages/update-package-dependencies/styles/update-package-dependencies.less | [
"MIT"
] |
Subsets and Splits