task_url
stringlengths 30
116
| task_name
stringlengths 2
86
| task_description
stringlengths 0
14.4k
| language_url
stringlengths 2
53
| language_name
stringlengths 1
52
| code
stringlengths 0
61.9k
|
---|---|---|---|---|---|
http://rosettacode.org/wiki/SEDOLs
|
SEDOLs
|
Task
For each number list of 6-digit SEDOLs, calculate and append the checksum digit.
That is, given this input:
710889
B0YBKJ
406566
B0YBLH
228276
B0YBKL
557910
B0YBKR
585284
B0YBKT
B00030
Produce this output:
7108899
B0YBKJ7
4065663
B0YBLH2
2282765
B0YBKL9
5579107
B0YBKR5
5852842
B0YBKT7
B000300
Extra credit
Check each input is correctly formed, especially with respect to valid characters allowed in a SEDOL string.
Related tasks
Luhn test
ISIN
|
#Rust
|
Rust
|
fn sedol(input: &str) -> Option<String> {
let weights = vec![1, 3, 1, 7, 3, 9, 1];
let valid_chars = "0123456789BCDFGHJKLMNPQRSTVWXYZ";
if input.len() != 6 {
return None;
}
// could be done by regex if needed
for c in input.chars() {
if !valid_chars.contains(c) {
return None;
}
}
let mut result: u32 = input
.chars()
.map(|c| {
if c.is_digit(10) {
c as u32 - 48
} else {
c as u32 - 55
}
})
.zip(weights)
.map(|(cnum, w)| w * cnum)
.collect::<Vec<u32>>()
.iter()
.sum();
result = (10 - result % 10) % 10;
Some(input.to_owned() + &result.to_string())
}
fn main() {
let inputs = vec![
"710889", "B0YBKJ", "406566", "B0YBLH", "228276", "B0YBKL", "557910", "B0YBKR", "585284",
"B0YBKT", "B00030",
];
for input in inputs {
println!("{} SEDOL: {:?}", &input, sedol(&input).unwrap());
}
}
|
http://rosettacode.org/wiki/SEDOLs
|
SEDOLs
|
Task
For each number list of 6-digit SEDOLs, calculate and append the checksum digit.
That is, given this input:
710889
B0YBKJ
406566
B0YBLH
228276
B0YBKL
557910
B0YBKR
585284
B0YBKT
B00030
Produce this output:
7108899
B0YBKJ7
4065663
B0YBLH2
2282765
B0YBKL9
5579107
B0YBKR5
5852842
B0YBKT7
B000300
Extra credit
Check each input is correctly formed, especially with respect to valid characters allowed in a SEDOL string.
Related tasks
Luhn test
ISIN
|
#Scala
|
Scala
|
class SEDOL(s: String) {
require(s.size == 6 || s.size == 7, "SEDOL length must be 6 or 7 characters")
require(s.size == 6 || s(6).asDigit == chksum, "Incorrect SEDOL checksum")
require(s forall (c => !("aeiou" contains c.toLower)), "Vowels not allowed in SEDOL")
def chksum = 10 - ((s zip List(1, 3, 1, 7, 3, 9) map { case (c, w) => c.asDigit * w } sum) % 10)
override def toString = s.take(6) + chksum
}
|
http://rosettacode.org/wiki/Sequence_of_non-squares
|
Sequence of non-squares
|
Task
Show that the following remarkable formula gives the sequence of non-square natural numbers:
n + floor(1/2 + sqrt(n))
Print out the values for n in the range 1 to 22
Show that no squares occur for n less than one million
This is sequence A000037 in the OEIS database.
|
#XLISP
|
XLISP
|
(defun non-square (n)
(+ n (floor (+ 0.5 (sqrt n)))))
(defun range (x y)
(if (< x y)
(cons x (range (+ x 1) y))))
(defun squarep (x)
(= x (expt (floor (sqrt x)) 2)))
(defun count-squares (x y)
(define squares 0)
(if (squarep (non-square x))
(define squares (+ squares 1)))
(if (= x y)
squares
(count-squares (+ x 1) y)))
(print (mapcar non-square (range 1 23)))
(print `(number of squares for values less than 1000000 = ,(count-squares 1 1000000)))
|
http://rosettacode.org/wiki/Set
|
Set
|
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
A set is a collection of elements, without duplicates and without order.
Task
Show each of these set operations:
Set creation
Test m ∈ S -- "m is an element in set S"
A ∪ B -- union; a set of all elements either in set A or in set B.
A ∩ B -- intersection; a set of all elements in both set A and set B.
A ∖ B -- difference; a set of all elements in set A, except those in set B.
A ⊆ B -- subset; true if every element in set A is also in set B.
A = B -- equality; true if every element of set A is in set B and vice versa.
As an option, show some other set operations.
(If A ⊆ B, but A ≠ B, then A is called a true or proper subset of B, written A ⊂ B or A ⊊ B.)
As another option, show how to modify a mutable set.
One might implement a set using an associative array (with set elements as array keys and some dummy value as the values).
One might also implement a set with a binary search tree, or with a hash table, or with an ordered array of binary bits (operated on with bit-wise binary operators).
The basic test, m ∈ S, is O(n) with a sequential list of elements, O(log n) with a balanced binary search tree, or (O(1) average-case, O(n) worst case) with a hash table.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
|
#Python
|
Python
|
>>> s1, s2 = {1, 2, 3, 4}, {3, 4, 5, 6}
>>> s1 | s2 # Union
{1, 2, 3, 4, 5, 6}
>>> s1 & s2 # Intersection
{3, 4}
>>> s1 - s2 # Difference
{1, 2}
>>> s1 < s1 # True subset
False
>>> {3, 1} < s1 # True subset
True
>>> s1 <= s1 # Subset
True
>>> {3, 1} <= s1 # Subset
True
>>> {3, 2, 4, 1} == s1 # Equality
True
>>> s1 == s2 # Equality
False
>>> 2 in s1 # Membership
True
>>> 10 not in s1 # Non-membership
True
>>> {1, 2, 3, 4, 5} > s1 # True superset
True
>>> {1, 2, 3, 4} > s1 # True superset
False
>>> {1, 2, 3, 4} >= s1 # Superset
True
>>> s1 ^ s2 # Symmetric difference
{1, 2, 5, 6}
>>> len(s1) # Cardinality
4
>>> s1.add(99) # Mutability
>>> s1
{99, 1, 2, 3, 4}
>>> s1.discard(99) # Mutability
>>> s1
{1, 2, 3, 4}
>>> s1 |= s2 # Mutability
>>> s1
{1, 2, 3, 4, 5, 6}
>>> s1 -= s2 # Mutability
>>> s1
{1, 2}
>>> s1 ^= s2 # Mutability
>>> s1
{1, 2, 3, 4, 5, 6}
>>>
|
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
|
Sieve of Eratosthenes
|
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer.
Task
Implement the Sieve of Eratosthenes algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found.
That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes.
If there's an easy way to add such a wheel based optimization, implement it as an alternative version.
Note
It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task.
Related tasks
Emirp primes
count in factors
prime decomposition
factors of an integer
extensible prime generator
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
|
#Furor
|
Furor
|
tick sto startingtick
#g 100000 sto MAX
@MAX mem !maximize sto primeNumbers
one count
@primeNumbers 0 2 [^]
2 @MAX külső: {||
@count {|
{}§külső {} []@primeNumbers !/ else{<}§külső
|} // @count vége
@primeNumbers @count++ {} [^]
|} // @MAX vége
@primeNumbers free
."Time : " tick @startingtick - print ." tick\n"
."Prímek száma = " @count printnl
end
{ „MAX” } { „startingtick” } { „primeNumbers” } { „count” }
|
http://rosettacode.org/wiki/SEDOLs
|
SEDOLs
|
Task
For each number list of 6-digit SEDOLs, calculate and append the checksum digit.
That is, given this input:
710889
B0YBKJ
406566
B0YBLH
228276
B0YBKL
557910
B0YBKR
585284
B0YBKT
B00030
Produce this output:
7108899
B0YBKJ7
4065663
B0YBLH2
2282765
B0YBKL9
5579107
B0YBKR5
5852842
B0YBKT7
B000300
Extra credit
Check each input is correctly formed, especially with respect to valid characters allowed in a SEDOL string.
Related tasks
Luhn test
ISIN
|
#Seed7
|
Seed7
|
$ include "seed7_05.s7i";
const func char: sedolCheckDigit (in string: sedol) is func
result
var char: checkDigit is ' ';
local
const array integer: weight is [] (1, 3, 1, 7, 3, 9);
var char: ch is ' ';
var integer: index is 0;
var integer: item is 0;
var integer: sum is 0;
begin
for ch key index range sedol do
case ch of
when {'0' .. '9'}:
item := ord(ch) - ord('0');
when {'A' .. 'Z'} - {'A', 'E', 'I', 'O', 'U'}:
item := ord(ch) - ord('A') + 10;
otherwise:
raise RANGE_ERROR;
end case;
sum +:= item * weight[index];
end for;
checkDigit := chr(-sum mod 10 + ord('0'));
end func;
const proc: main is func
local
var string: sedol is "";
begin
for sedol range [] ("710889", "B0YBKJ", "406566", "B0YBLH", "228276", "B0YBKL",
"557910", "B0YBKR", "585284", "B0YBKT", "B00030") do
writeln(sedol <& sedolCheckDigit(sedol));
end for;
end func;
|
http://rosettacode.org/wiki/Sequence_of_non-squares
|
Sequence of non-squares
|
Task
Show that the following remarkable formula gives the sequence of non-square natural numbers:
n + floor(1/2 + sqrt(n))
Print out the values for n in the range 1 to 22
Show that no squares occur for n less than one million
This is sequence A000037 in the OEIS database.
|
#XPL0
|
XPL0
|
include c:\cxpl\codes; \intrinsic 'code' declarations
func real Floor(X); \Truncate X toward - infinity
real X;
return float(fix(X-0.5));
func PerfectSq(N); \Return 'true' if N is a perfect square
int N;
return sqrt(N)*sqrt(N) = N;
int N, M, M0;
[for N:= 1 to 22 do
[IntOut(0, fix(float(N) + Floor(0.5 + sqrt(float(N))))); ChOut(0,^ )];
CrLf(0);
M0:= 1;
for N:= 1 to 999_999 do
[M:= fix(float(N) + Floor(0.5 + sqrt(float(N))));
if PerfectSq(M) then [IntOut(0, M); Crlf(0)]; \error: have square
if M#M0+1 and not PerfectSq(M0+1) then \error: not sequential
[IntOut(0, M); Crlf(0)];
M0:= M;
];
]
|
http://rosettacode.org/wiki/Sequence_of_non-squares
|
Sequence of non-squares
|
Task
Show that the following remarkable formula gives the sequence of non-square natural numbers:
n + floor(1/2 + sqrt(n))
Print out the values for n in the range 1 to 22
Show that no squares occur for n less than one million
This is sequence A000037 in the OEIS database.
|
#Yabasic
|
Yabasic
|
// Display first 22 values
print "The first 22 numbers generated by the sequence are : "
for i = 1 to 22
print nonSquare(i), " ";
next i
print
// Check for squares up to one million
found = false
for i = 1 to 1e6
j = sqrt(nonSquare(i))
if j = int(j) then
found = true
print i, " square numbers found" //print "Found square: ", i
break
end if
next i
if not found print "No squares found"
end
sub nonSquare (n)
return n + int(0.5 + sqrt(n))
end sub
|
http://rosettacode.org/wiki/Set
|
Set
|
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
A set is a collection of elements, without duplicates and without order.
Task
Show each of these set operations:
Set creation
Test m ∈ S -- "m is an element in set S"
A ∪ B -- union; a set of all elements either in set A or in set B.
A ∩ B -- intersection; a set of all elements in both set A and set B.
A ∖ B -- difference; a set of all elements in set A, except those in set B.
A ⊆ B -- subset; true if every element in set A is also in set B.
A = B -- equality; true if every element of set A is in set B and vice versa.
As an option, show some other set operations.
(If A ⊆ B, but A ≠ B, then A is called a true or proper subset of B, written A ⊂ B or A ⊊ B.)
As another option, show how to modify a mutable set.
One might implement a set using an associative array (with set elements as array keys and some dummy value as the values).
One might also implement a set with a binary search tree, or with a hash table, or with an ordered array of binary bits (operated on with bit-wise binary operators).
The basic test, m ∈ S, is O(n) with a sequential list of elements, O(log n) with a balanced binary search tree, or (O(1) average-case, O(n) worst case) with a hash table.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
|
#Quackery
|
Quackery
|
[ [] $ "" rot
sort$ witheach
[ tuck != if
[ dup dip
[ nested join ] ] ]
drop ] is -duplicates ( { --> { )
[ [] $ "" rot
sort$ witheach
[ tuck = if
[ nested join
$ "" ] ]
drop -duplicates ] is duplicates ( { --> { )
[ [] $ "" rot
sort$ witheach
[ tuck != iff
[ dup dip [ nested join ] ]
else
[ dip [ -1 pluck ]
over != if
[ nested join $ "" ] ] ]
drop ] is --duplicates ( { --> { )
[ [] swap
[ trim
dup $ "" = if
[ $ '"set{" without "}set"'
message put bail ]
nextword
dup $ "}set" != while
nested rot join swap
again ]
drop swap
-duplicates
' [ ' ] swap nested join
swap dip [ nested join ] ] builds set{ ( [ $ --> [ $ )
[ -duplicates
say "{ "
witheach [ echo$ sp ]
say "}" ] is echoset ( { --> { )
[ join duplicates ] is intersection ( { { --> { )
[ join -duplicates ] is union ( { { --> { )
[ join --duplicates ] is symmdiff ( { { --> { )
[ over intersection symmdiff ] is difference ( { { --> { )
[ over intersection = ] is subset ( { { --> b )
[ dip nested subset ] is element ( $ { --> b )
[ 2dup = iff
[ 2drop false ]
else subset ] is propersubset ( { { --> b )
( ------------------------------ demo ------------------------------ )
set{ apple peach pear melon
apricot banana orange }set is fruits ( --> { )
set{ red orange green blue
purple apricot peach }set is colours ( --> { )
fruits dup echoset say " are fruits" cr
colours dup echoset say " are colours" cr
2dup intersection echoset say " are both fruits and colours" cr
2dup union echoset say " are fruits or colours" cr
2dup symmdiff echoset say " are fruits or colours but not both" cr
difference echoset say " are fruits that are not colours" cr
set{ red green blue }set dup echoset say " are"
colours subset not if [ say " not" ] say " all colours" cr
say "fruits and colours are" fruits colours = not if [ say " not" ]
say " exactly the same" cr
$ "orange" dup echo$ say " is"
fruits element not if [ say " not" ] say " a fruit" cr
set{ orange }set dup echoset say " is"
fruits propersubset dup if [ say " not" ] say " the only fruit"
not if [ say " or not a fruit" ] cr
|
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
|
Sieve of Eratosthenes
|
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer.
Task
Implement the Sieve of Eratosthenes algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found.
That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes.
If there's an easy way to add such a wheel based optimization, implement it as an alternative version.
Note
It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task.
Related tasks
Emirp primes
count in factors
prime decomposition
factors of an integer
extensible prime generator
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
|
#FutureBasic
|
FutureBasic
|
window 1, @"Sieve of Eratosthenes", (0,0,720,300)
begin globals
dynamic gPrimes(1) as Boolean
end globals
local fn SieveOfEratosthenes( n as long )
long i, j
for i = 2 to n
for j = i * i to n step i
gPrimes(j) = _true
next
if gPrimes(i) = 0 then print i,
next i
kill gPrimes
end fn
fn SieveOfEratosthenes( 100 )
HandleEvents
|
http://rosettacode.org/wiki/SEDOLs
|
SEDOLs
|
Task
For each number list of 6-digit SEDOLs, calculate and append the checksum digit.
That is, given this input:
710889
B0YBKJ
406566
B0YBLH
228276
B0YBKL
557910
B0YBKR
585284
B0YBKT
B00030
Produce this output:
7108899
B0YBKJ7
4065663
B0YBLH2
2282765
B0YBKL9
5579107
B0YBKR5
5852842
B0YBKT7
B000300
Extra credit
Check each input is correctly formed, especially with respect to valid characters allowed in a SEDOL string.
Related tasks
Luhn test
ISIN
|
#Sidef
|
Sidef
|
func sedol(s) {
die 'No vowels allowed' if (s ~~ /[AEIOU]/);
die 'Invalid format' if (s !~ /^[0-9B-DF-HJ-NP-TV-Z]{6}$/);
const base36 = ((@(0..9) + @('A'..'Z')) ~Z @(0..35) -> flatten.to_h);
const weights = [1, 3, 1, 7, 3, 9];
var vs = [base36{ s.chars... }];
var checksum = (vs ~Z* weights -> sum);
var check_digit = ((10 - checksum%10) % 10);
return (s + check_digit);
}
%w(
710889
B0YBKJ
406566
B0YBLH
228276
B0YBKL
557910
B0YBKR
585284
B0YBKT
B00030
).each { |s|
say sedol(s);
}
|
http://rosettacode.org/wiki/Sequence_of_non-squares
|
Sequence of non-squares
|
Task
Show that the following remarkable formula gives the sequence of non-square natural numbers:
n + floor(1/2 + sqrt(n))
Print out the values for n in the range 1 to 22
Show that no squares occur for n less than one million
This is sequence A000037 in the OEIS database.
|
#zkl
|
zkl
|
fcn seq(n){n + (0.5+n.toFloat().sqrt()).floor()}
[1..22].apply(seq).toString(*).println();
fcn isSquare(n){n.toFloat().sqrt().modf()[1]==0.0}
isSquare(25) //-->True
isSquare(26) //-->False
[2..0d1_000_000].filter(fcn(n){isSquare(seq(n))}).println();
|
http://rosettacode.org/wiki/Set
|
Set
|
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
A set is a collection of elements, without duplicates and without order.
Task
Show each of these set operations:
Set creation
Test m ∈ S -- "m is an element in set S"
A ∪ B -- union; a set of all elements either in set A or in set B.
A ∩ B -- intersection; a set of all elements in both set A and set B.
A ∖ B -- difference; a set of all elements in set A, except those in set B.
A ⊆ B -- subset; true if every element in set A is also in set B.
A = B -- equality; true if every element of set A is in set B and vice versa.
As an option, show some other set operations.
(If A ⊆ B, but A ≠ B, then A is called a true or proper subset of B, written A ⊂ B or A ⊊ B.)
As another option, show how to modify a mutable set.
One might implement a set using an associative array (with set elements as array keys and some dummy value as the values).
One might also implement a set with a binary search tree, or with a hash table, or with an ordered array of binary bits (operated on with bit-wise binary operators).
The basic test, m ∈ S, is O(n) with a sequential list of elements, O(log n) with a balanced binary search tree, or (O(1) average-case, O(n) worst case) with a hash table.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
|
#Racket
|
Racket
|
#lang racket
(define A (set 1 2 3 4))
(define B (set 3 4 5 6))
(define C (set 4 5))
(set-union A B) ; gives (set 1 2 3 4 5 6)
(set-intersect A B) ; gives (set 3 4)
(set-subtract A B) ; gives (set 1 2)
(set=? A B) ; gives #f
(subset? C A) ; gives #f
(subset? C B) ; gives #t
|
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
|
Sieve of Eratosthenes
|
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer.
Task
Implement the Sieve of Eratosthenes algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found.
That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes.
If there's an easy way to add such a wheel based optimization, implement it as an alternative version.
Note
It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task.
Related tasks
Emirp primes
count in factors
prime decomposition
factors of an integer
extensible prime generator
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
|
#F.C5.8Drmul.C3.A6
|
Fōrmulæ
|
Eratosthenes := function(n)
local a, i, j;
a := ListWithIdenticalEntries(n, true);
if n < 2 then
return [];
else
for i in [2 .. n] do
if a[i] then
j := i*i;
if j > n then
return Filtered([2 .. n], i -> a[i]);
else
while j <= n do
a[j] := false;
j := j + i;
od;
fi;
fi;
od;
fi;
end;
Eratosthenes(100);
[ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97 ]
|
http://rosettacode.org/wiki/SEDOLs
|
SEDOLs
|
Task
For each number list of 6-digit SEDOLs, calculate and append the checksum digit.
That is, given this input:
710889
B0YBKJ
406566
B0YBLH
228276
B0YBKL
557910
B0YBKR
585284
B0YBKT
B00030
Produce this output:
7108899
B0YBKJ7
4065663
B0YBLH2
2282765
B0YBKL9
5579107
B0YBKR5
5852842
B0YBKT7
B000300
Extra credit
Check each input is correctly formed, especially with respect to valid characters allowed in a SEDOL string.
Related tasks
Luhn test
ISIN
|
#Smalltalk
|
Smalltalk
|
String extend [
includesAnyOf: aSet [
aSet do: [ :e | (self includes: e) ifTrue: [ ^true ] ].
^false
]
].
|
http://rosettacode.org/wiki/SEDOLs
|
SEDOLs
|
Task
For each number list of 6-digit SEDOLs, calculate and append the checksum digit.
That is, given this input:
710889
B0YBKJ
406566
B0YBLH
228276
B0YBKL
557910
B0YBKR
585284
B0YBKT
B00030
Produce this output:
7108899
B0YBKJ7
4065663
B0YBLH2
2282765
B0YBKL9
5579107
B0YBKR5
5852842
B0YBKT7
B000300
Extra credit
Check each input is correctly formed, especially with respect to valid characters allowed in a SEDOL string.
Related tasks
Luhn test
ISIN
|
#SQL_PL
|
SQL PL
|
--#SET TERMINATOR @
SET SERVEROUTPUT ON@
CREATE OR REPLACE FUNCTION CHECK_SEDOL (
IN TEXT VARCHAR(6)
) RETURNS VARCHAR(7)
BEGIN
DECLARE TYPE SEDOL AS CHAR(1) ARRAY [6];
--declare text varchar(6) default 'B12345';
DECLARE WEIGHT SEDOL;
DECLARE I SMALLINT;
DECLARE SENTENCE VARCHAR(256);
DECLARE CHAR_AT CHAR(1);
DECLARE OUTPUT CHAR(1);
DECLARE SUM SMALLINT;
DECLARE CHECK SMALLINT;
DECLARE INVALID_CHAR CONDITION FOR SQLSTATE '22004' ;
DECLARE STMT STATEMENT;
-- Converts all to upper.
SET TEXT = UPPER (TEXT);
-- CALL DBMS_OUTPUT.PUT_LINE(TEXT);
-- Checks the characters.
SET I = 1;
WHILE (I <= 6) DO
SET CHAR_AT = SUBSTR(TEXT, I, 1);
-- CALL DBMS_OUTPUT.PUT_LINE('Char ' || CHAR_AT);
SET SENTENCE = 'SET ? = (SELECT SEDOL FROM (SELECT ''' || CHAR_AT
|| ''' SEDOL FROM SYSIBM.SYSDUMMY1) WHERE SEDOL IN (''B'',''C'',''D'',''F'',''G'',''H'',''J'','
|| '''K'',''L'',''M'',''N'',''P'',''Q'',''R'',''S'',''T'',''V'',''W'',''X'',''Y'',''Z'',''0'','
|| '''1'',''2'',''3'',''4'',''5'',''6'',''7'',''8'',''9''))';
PREPARE STMT FROM SENTENCE;
EXECUTE STMT INTO OUTPUT;
IF (OUTPUT IS NULL) THEN
SIGNAL INVALID_CHAR;
END IF;
SET I = I + 1;
END WHILE;
-- Assigns weight
SET WEIGHT[1] = '1';
SET WEIGHT[2] = '3';
SET WEIGHT[3] = '1';
SET WEIGHT[4] = '7';
SET WEIGHT[5] = '3';
SET WEIGHT[6] = '9';
-- Process the SEDOL.
SET SUM = 0;
SET I = 1;
WHILE (I <= 6) DO
SET CHAR_AT = SUBSTR(TEXT, I, 1);
IF (ASCII(CHAR_AT) > 65) THEN
SET SUM = SUM + WEIGHT[I] * (ASCII(CHAR_AT) - 64 + 9);
ELSE
SET SUM = SUM + WEIGHT[I] * CHAR_AT;
END IF;
SET I = I + 1;
END WHILE;
SET CHECK = MOD((10 - MOD(SUM, 10)), 10);
CALL DBMS_OUTPUT.PUT_LINE(CHECK);
RETURN TEXT || CHECK;
END @
|
http://rosettacode.org/wiki/Set
|
Set
|
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
A set is a collection of elements, without duplicates and without order.
Task
Show each of these set operations:
Set creation
Test m ∈ S -- "m is an element in set S"
A ∪ B -- union; a set of all elements either in set A or in set B.
A ∩ B -- intersection; a set of all elements in both set A and set B.
A ∖ B -- difference; a set of all elements in set A, except those in set B.
A ⊆ B -- subset; true if every element in set A is also in set B.
A = B -- equality; true if every element of set A is in set B and vice versa.
As an option, show some other set operations.
(If A ⊆ B, but A ≠ B, then A is called a true or proper subset of B, written A ⊂ B or A ⊊ B.)
As another option, show how to modify a mutable set.
One might implement a set using an associative array (with set elements as array keys and some dummy value as the values).
One might also implement a set with a binary search tree, or with a hash table, or with an ordered array of binary bits (operated on with bit-wise binary operators).
The basic test, m ∈ S, is O(n) with a sequential list of elements, O(log n) with a balanced binary search tree, or (O(1) average-case, O(n) worst case) with a hash table.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
|
#Raku
|
Raku
|
use Test;
my $a = set <a b c>;
my $b = set <b c d>;
my $c = set <a b c d e>;
ok 'c' ∈ $a, "c is an element in set A";
nok 'd' ∈ $a, "d is not an element in set A";
is-deeply $a ∪ $b, set(<a b c d>), "union; a set of all elements either in set A or in set B";
is-deeply $a ∩ $b, set(<b c>), "intersection; a set of all elements in both set A and set B";
is $a (-) $b, set(<a>), "difference; a set of all elements in set A, except those in set B";
ok $a ⊆ $c, "subset; true if every element in set A is also in set B";
nok $c ⊆ $a, "subset; false if every element in set A is not also in set B";
ok $a ⊂ $c, "strict subset; true if every element in set A is also in set B";
nok $a ⊂ $a, "strict subset; false for equal sets";
ok $a === set(<a b c>), "equality; true if every element of set A is in set B and vice-versa";
nok $a === $b, "equality; false for differing sets";
|
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
|
Sieve of Eratosthenes
|
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer.
Task
Implement the Sieve of Eratosthenes algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found.
That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes.
If there's an easy way to add such a wheel based optimization, implement it as an alternative version.
Note
It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task.
Related tasks
Emirp primes
count in factors
prime decomposition
factors of an integer
extensible prime generator
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
|
#GAP
|
GAP
|
Eratosthenes := function(n)
local a, i, j;
a := ListWithIdenticalEntries(n, true);
if n < 2 then
return [];
else
for i in [2 .. n] do
if a[i] then
j := i*i;
if j > n then
return Filtered([2 .. n], i -> a[i]);
else
while j <= n do
a[j] := false;
j := j + i;
od;
fi;
fi;
od;
fi;
end;
Eratosthenes(100);
[ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97 ]
|
http://rosettacode.org/wiki/SEDOLs
|
SEDOLs
|
Task
For each number list of 6-digit SEDOLs, calculate and append the checksum digit.
That is, given this input:
710889
B0YBKJ
406566
B0YBLH
228276
B0YBKL
557910
B0YBKR
585284
B0YBKT
B00030
Produce this output:
7108899
B0YBKJ7
4065663
B0YBLH2
2282765
B0YBKL9
5579107
B0YBKR5
5852842
B0YBKT7
B000300
Extra credit
Check each input is correctly formed, especially with respect to valid characters allowed in a SEDOL string.
Related tasks
Luhn test
ISIN
|
#Standard_ML
|
Standard ML
|
fun char2value c =
if List.exists (fn x => x = c) (explode "AEIOU") then raise Fail "no vowels"
else if Char.isDigit c then ord c - ord #"0"
else if Char.isUpper c then ord c - ord #"A" + 10
else raise Match
val sedolweight = [1,3,1,7,3,9]
fun checksum sedol = let
val tmp = ListPair.foldlEq (fn (ch, weight, sum) => sum + char2value ch * weight)
0 (explode sedol, sedolweight)
in
Int.toString ((10 - (tmp mod 10)) mod 10)
end
app (fn sedol => print (sedol ^ checksum sedol ^ "\n"))
[ "710889",
"B0YBKJ",
"406566",
"B0YBLH",
"228276",
"B0YBKL",
"557910",
"B0YBKR",
"585284",
"B0YBKT" ];
|
http://rosettacode.org/wiki/SEDOLs
|
SEDOLs
|
Task
For each number list of 6-digit SEDOLs, calculate and append the checksum digit.
That is, given this input:
710889
B0YBKJ
406566
B0YBLH
228276
B0YBKL
557910
B0YBKR
585284
B0YBKT
B00030
Produce this output:
7108899
B0YBKJ7
4065663
B0YBLH2
2282765
B0YBKL9
5579107
B0YBKR5
5852842
B0YBKT7
B000300
Extra credit
Check each input is correctly formed, especially with respect to valid characters allowed in a SEDOL string.
Related tasks
Luhn test
ISIN
|
#Tcl
|
Tcl
|
namespace eval sedol {
variable chars {0 1 2 3 4 5 6 7 8 9 "" B C D "" F G H "" J K L M N "" P Q R S T "" V W X Y Z}
variable weight {1 3 1 7 3 9 1}
proc checksum {alnum6} {
variable chars
variable weight
set sum 0
set col 0
foreach char [split [string toupper [string range $alnum6 0 5]] ""] {
if {[set idx [lsearch -exact $chars $char]] == -1} {
error "invalid character: $char"
}
incr sum [expr {$idx * [lindex $weight $col]}]
incr col
}
return [expr {(10 - ($sum % 10)) % 10}]
}
proc valid {alnum7} {
expr {[checksum [string range $alnum7 0 5]] == [string index $alnum7 6]}
}
}
proc assert {condition {message "Assertion failed!"}} {
if { ! [uplevel 1 [list expr $condition]]} {
return -code error $message
}
}
set codes {710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT}
set answers {7108899 B0YBKJ7 4065663 B0YBLH2 2282765 B0YBKL9 5579107 B0YBKR5 5852842 B0YBKT7}
foreach code $codes answer $answers {
set sedol "${code}[sedol::checksum $code]"
assert {$sedol eq $answer} "assertion failed: $sedol ne $answer"
puts $sedol
}
|
http://rosettacode.org/wiki/Set
|
Set
|
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
A set is a collection of elements, without duplicates and without order.
Task
Show each of these set operations:
Set creation
Test m ∈ S -- "m is an element in set S"
A ∪ B -- union; a set of all elements either in set A or in set B.
A ∩ B -- intersection; a set of all elements in both set A and set B.
A ∖ B -- difference; a set of all elements in set A, except those in set B.
A ⊆ B -- subset; true if every element in set A is also in set B.
A = B -- equality; true if every element of set A is in set B and vice versa.
As an option, show some other set operations.
(If A ⊆ B, but A ≠ B, then A is called a true or proper subset of B, written A ⊂ B or A ⊊ B.)
As another option, show how to modify a mutable set.
One might implement a set using an associative array (with set elements as array keys and some dummy value as the values).
One might also implement a set with a binary search tree, or with a hash table, or with an ordered array of binary bits (operated on with bit-wise binary operators).
The basic test, m ∈ S, is O(n) with a sequential list of elements, O(log n) with a balanced binary search tree, or (O(1) average-case, O(n) worst case) with a hash table.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
|
#REXX
|
REXX
|
/*REXX program demonstrates some common SET functions. */
truth.0= 'false'; truth.1= "true" /*two common names for a truth table. */
set.= /*the order of sets isn't important. */
call setAdd 'prime',2 3 2 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
call setSay 'prime' /*a small set of some prime numbers. */
call setAdd 'emirp',97 97 89 83 79 73 71 67 61 59 53 47 43 41 37 31 29 23 19 17 13 11 7 5 3 2
call setSay 'emirp' /*a small set of backward primes. */
call setAdd 'happy',1 7 10 13 19 23 28 31 32 44 49 68 70 79 82 86 91 100 94 97 97 97 97 97
call setSay 'happy' /*a small set of some happy numbers. */
do j=11 to 100 by 10 /*see if PRIME contains some numbers. */
call setHas 'prime', j
say ' prime contains' j":" truth.result
end /*j*/
call setUnion 'prime','happy','eweion'; call setSay 'eweion' /* (sic). */
call setCommon 'prime','happy','common'; call setSay 'common'
call setDiff 'prime','happy','diff' ; call setSay 'diff'; _=left('', 12)
call setSubset 'prime','happy' ; say _ 'prime is a subset of happy:' truth.result
call setEqual 'prime','emirp' ; say _ 'prime is equal to emirp:' truth.result
exit /*stick a fork in it, we're done.*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
setHas: procedure expose set.; arg _ .,! .; return wordpos(!, set._)\==0
setAdd: return set$('add' , arg(1), arg(2))
setDiff: return set$('diff' , arg(1), arg(2), arg(3))
setSay: return set$('say' , arg(1), arg(2))
setUnion: return set$('union' , arg(1), arg(2), arg(3))
setCommon: return set$('common' , arg(1), arg(2), arg(3))
setEqual: return set$('equal' , arg(1), arg(2))
setSubset: return set$('subSet' , arg(1), arg(2))
/*──────────────────────────────────────────────────────────────────────────────────────*/
set$: procedure expose set.; arg $,_1,_2,_3; set_=set._1; t=_3; s=t; !=1
if $=='SAY' then do; say "[set."_1']= 'set._1; return set._1; end
if $=='UNION' then do
call set$ 'add', _3, set._1
call set$ 'add', _3, set._2
return set._3
end
add=$=='ADD'; common=$=='COMMON'; diff=$=='DIFF'; eq=$=='EQUAL'; subset=$=='SUBSET'
if common | diff | eq | subset then s=_2
if add then do; set_=_2; t=_1; s=_1; end
do j=1 for words(set_); _=word(set_, j); has=wordpos(_, set.s)\==0
if (add & \has) |,
(common & has) |,
(diff & \has) then set.t=space(set.t _)
if (eq | subset) & \has then return 0
end /*j*/
if subset then return 1
if eq then if arg()>3 then return 1
else return set$('equal', _2, _1, 1)
return set.t
|
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
|
Sieve of Eratosthenes
|
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer.
Task
Implement the Sieve of Eratosthenes algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found.
That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes.
If there's an easy way to add such a wheel based optimization, implement it as an alternative version.
Note
It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task.
Related tasks
Emirp primes
count in factors
prime decomposition
factors of an integer
extensible prime generator
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
|
#GLBasic
|
GLBasic
|
// Sieve of Eratosthenes (find primes)
// GLBasic implementation
GLOBAL n%, k%, limit%, flags%[]
limit = 100 // search primes up to this number
DIM flags[limit+1] // GLBasic arrays start at 0
FOR n = 2 TO SQR(limit)
IF flags[n] = 0
FOR k = n*n TO limit STEP n
flags[k] = 1
NEXT
ENDIF
NEXT
// Display the primes
FOR n = 2 TO limit
IF flags[n] = 0 THEN STDOUT n + ", "
NEXT
KEYWAIT
|
http://rosettacode.org/wiki/SEDOLs
|
SEDOLs
|
Task
For each number list of 6-digit SEDOLs, calculate and append the checksum digit.
That is, given this input:
710889
B0YBKJ
406566
B0YBLH
228276
B0YBKL
557910
B0YBKR
585284
B0YBKT
B00030
Produce this output:
7108899
B0YBKJ7
4065663
B0YBLH2
2282765
B0YBKL9
5579107
B0YBKR5
5852842
B0YBKT7
B000300
Extra credit
Check each input is correctly formed, especially with respect to valid characters allowed in a SEDOL string.
Related tasks
Luhn test
ISIN
|
#Transact-SQL
|
Transact-SQL
|
CREATE FUNCTION [dbo].[fn_CheckSEDOL]
( @SEDOL varchar(50) )
RETURNS varchar(7)
AS
BEGIN
declare @true bit = 1,
@false bit = 0,
@isSEDOL bit,
@sedol_weights varchar(6) ='131739',
@sedol_len int = LEN(@SEDOL),
@sum int = 0
if ((@sedol_len = 6))
begin
select @SEDOL = UPPER(@SEDOL)
Declare @vowels varchar(5) = 'AEIOU',
@letters varchar(21) = 'BCDFGHJKLMNPQRSTVWXYZ',
@i int=1,
@isStillGood bit = @true,
@char char = '',
@weighting int =0
select @isSEDOL = @false
while ((@i < 7) and (@isStillGood = @true))
begin
select @char = SUBSTRING(@SEDOL,@i,1),
@weighting = CONVERT (INT,SUBSTRING(@sedol_weights, @i, 1))
if (CHARINDEX(@char, @vowels) > 0) -- no vowels please
begin
select @isStillGood=@false
end
else
begin
if (ISNUMERIC(@char) = @true) -- is a number
begin
select @sum = @sum + (ASCII(@char) - 48) * @weighting
end
else if (CHARINDEX(@char, @letters) = 0) -- test for the rest of the alphabet
begin
select @isStillGood=@false
end
else
begin
select @sum = @sum + (ASCII(@char) - 55) * @weighting
end
end
select @i = @i +1
end -- of while loop
if (@isStillGood = @true)
begin
declare @checksum int = (10 - (@sum%10))%10
select @SEDOL = @SEDOL + CONVERT(CHAR,@checksum)
end
end
else
begin
select @SEDOL = ''
end
-- Return the result of the function
RETURN @SEDOL
END
|
http://rosettacode.org/wiki/Set
|
Set
|
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
A set is a collection of elements, without duplicates and without order.
Task
Show each of these set operations:
Set creation
Test m ∈ S -- "m is an element in set S"
A ∪ B -- union; a set of all elements either in set A or in set B.
A ∩ B -- intersection; a set of all elements in both set A and set B.
A ∖ B -- difference; a set of all elements in set A, except those in set B.
A ⊆ B -- subset; true if every element in set A is also in set B.
A = B -- equality; true if every element of set A is in set B and vice versa.
As an option, show some other set operations.
(If A ⊆ B, but A ≠ B, then A is called a true or proper subset of B, written A ⊂ B or A ⊊ B.)
As another option, show how to modify a mutable set.
One might implement a set using an associative array (with set elements as array keys and some dummy value as the values).
One might also implement a set with a binary search tree, or with a hash table, or with an ordered array of binary bits (operated on with bit-wise binary operators).
The basic test, m ∈ S, is O(n) with a sequential list of elements, O(log n) with a balanced binary search tree, or (O(1) average-case, O(n) worst case) with a hash table.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
|
#Ring
|
Ring
|
# Project : Set
arr = ["apple", "banana", "cherry", "date", "elderberry", "fig", "grape"]
for n = 1 to 25
add(arr,"")
next
seta = "1010101"
see "Set A: " + arrset(arr,seta) + nl
setb = "0111110"
see "Set B: " + arrset(arr,setb) + nl
elementm = "0000010"
see "Element M: " + arrset(arr,elementm) + nl
temp = arrsetinsec(elementm,seta)
if len(temp) > 0
see "M is an element of set A" + nl
else
see "M is not an element of set A" + nl
ok
temp = arrsetinsec(elementm,setb)
if len(temp) > 0
see "M is an element of set B" + nl
else
see "M is not an element of set B" + nl
ok
see "The union of A and B is: "
see arrsetunion(seta,setb) + nl
see "The intersection of A and B is: "
see arrsetinsec(seta,setb) + nl
see "The difference of A and B is: "
see arrsetnot(seta,setb) + nl
flag = arrsetsub(seta,setb)
if flag = 1
see "Set A is a subset of set B" + nl
else
see "Set A is not a subset of set B" + nl
ok
if seta = setb
see "Set A is equal to set B" + nl
else
see "Set A is not equal to set B" + nl
ok
func arrset(arr,set)
o = ""
for i = 1 to 7
if set[i] = "1"
o = o + arr[i] + ", "
ok
next
return left(o,len(o)-2)
func arrsetunion(seta,setb)
o = ""
union = list(len(seta))
for n = 1 to len(seta)
if seta[n] = "1" or setb[n] = "1"
union[n] = "1"
else
union[n] = "0"
ok
next
for i = 1 to len(union)
if union[i] = "1"
o = o + arr[i] + ", "
ok
next
return o
func arrsetinsec(setc,setd)
o = ""
union = list(len(setc))
for n = 1 to len(setc)
if setc[n] = "1" and setd[n] = "1"
union[n] = "1"
else
union[n] = "0"
ok
next
for i = 1 to len(union)
if union[i] = "1"
o = o + arr[i] + ", "
ok
next
return o
func arrsetnot(seta,setb)
o = ""
union = list(len(seta))
for n = 1 to len(seta)
if seta[n] = "1" and setb[n] = "0"
union[n] = "1"
else
union[n] = "0"
ok
next
for i = 1 to len(union)
if union[i] = "1"
o = o + arr[i] + ", "
ok
next
return o
func arrsetsub(setc,setd)
flag = 1
for n = 1 to len(setc)
if setc[n] = "1" and setd[n] = "0"
flag = 0
ok
next
return flag
|
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
|
Sieve of Eratosthenes
|
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer.
Task
Implement the Sieve of Eratosthenes algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found.
That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes.
If there's an easy way to add such a wheel based optimization, implement it as an alternative version.
Note
It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task.
Related tasks
Emirp primes
count in factors
prime decomposition
factors of an integer
extensible prime generator
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
|
#Go
|
Go
|
package main
import "fmt"
func main() {
const limit = 201 // means sieve numbers < 201
// sieve
c := make([]bool, limit) // c for composite. false means prime candidate
c[1] = true // 1 not considered prime
p := 2
for {
// first allowed optimization: outer loop only goes to sqrt(limit)
p2 := p * p
if p2 >= limit {
break
}
// second allowed optimization: inner loop starts at sqr(p)
for i := p2; i < limit; i += p {
c[i] = true // it's a composite
}
// scan to get next prime for outer loop
for {
p++
if !c[p] {
break
}
}
}
// sieve complete. now print a representation.
for n := 1; n < limit; n++ {
if c[n] {
fmt.Print(" .")
} else {
fmt.Printf("%3d", n)
}
if n%20 == 0 {
fmt.Println("")
}
}
}
|
http://rosettacode.org/wiki/SEDOLs
|
SEDOLs
|
Task
For each number list of 6-digit SEDOLs, calculate and append the checksum digit.
That is, given this input:
710889
B0YBKJ
406566
B0YBLH
228276
B0YBKL
557910
B0YBKR
585284
B0YBKT
B00030
Produce this output:
7108899
B0YBKJ7
4065663
B0YBLH2
2282765
B0YBKL9
5579107
B0YBKR5
5852842
B0YBKT7
B000300
Extra credit
Check each input is correctly formed, especially with respect to valid characters allowed in a SEDOL string.
Related tasks
Luhn test
ISIN
|
#TUSCRIPT
|
TUSCRIPT
|
$$ MODE TUSCRIPT
check="1'3'1'7'3'9"
values="123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
value=STRINGS (values,":<%:")
BUILD r_TABLE/or illegal=":A:E:I:O:U:"
LOOP input="710889'B0YBKJ'406566'B0YBLH'228276'B0YBKL'557910'B0YBKR'585284'B0YBKT'BOYAKT'B00030",sum=""
IF (input.ma.illegal) THEN
PRINT/ERROR input, " illegal"
CYCLE
ENDIF
strings=STRINGS (input,":<%:")
LOOP d,nr=strings
c=SELECT (check,#d)
IF (nr!='digits') nr=FILTER_INDEX (value,":{nr}:",-)
x=nr*c, sum=APPEND(sum,x)
ENDLOOP
endsum=SUM(sum), checksum=10-(endsum%10)
IF (checksum==10) checksum=0
PRINT input, " checkdigit: ", checksum
ENDLOOP
|
http://rosettacode.org/wiki/SEDOLs
|
SEDOLs
|
Task
For each number list of 6-digit SEDOLs, calculate and append the checksum digit.
That is, given this input:
710889
B0YBKJ
406566
B0YBLH
228276
B0YBKL
557910
B0YBKR
585284
B0YBKT
B00030
Produce this output:
7108899
B0YBKJ7
4065663
B0YBLH2
2282765
B0YBKL9
5579107
B0YBKR5
5852842
B0YBKT7
B000300
Extra credit
Check each input is correctly formed, especially with respect to valid characters allowed in a SEDOL string.
Related tasks
Luhn test
ISIN
|
#Ursala
|
Ursala
|
#import std
#import nat
alphabet = digits-- ~=`A-~r letters
weights = <1,3,1,7,3,9>
charval = -:@rlXS num alphabet
iprod = sum:-0+ product*p/weights+ charval*
checksum = difference/10+ remainder\10+ iprod
|
http://rosettacode.org/wiki/Set
|
Set
|
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
A set is a collection of elements, without duplicates and without order.
Task
Show each of these set operations:
Set creation
Test m ∈ S -- "m is an element in set S"
A ∪ B -- union; a set of all elements either in set A or in set B.
A ∩ B -- intersection; a set of all elements in both set A and set B.
A ∖ B -- difference; a set of all elements in set A, except those in set B.
A ⊆ B -- subset; true if every element in set A is also in set B.
A = B -- equality; true if every element of set A is in set B and vice versa.
As an option, show some other set operations.
(If A ⊆ B, but A ≠ B, then A is called a true or proper subset of B, written A ⊂ B or A ⊊ B.)
As another option, show how to modify a mutable set.
One might implement a set using an associative array (with set elements as array keys and some dummy value as the values).
One might also implement a set with a binary search tree, or with a hash table, or with an ordered array of binary bits (operated on with bit-wise binary operators).
The basic test, m ∈ S, is O(n) with a sequential list of elements, O(log n) with a balanced binary search tree, or (O(1) average-case, O(n) worst case) with a hash table.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
|
#Ruby
|
Ruby
|
>> require 'set'
=> true
>> s1, s2 = Set[1, 2, 3, 4], [3, 4, 5, 6].to_set # different ways of creating a set
=> [#<Set: {1, 2, 3, 4}>, #<Set: {5, 6, 3, 4}>]
>> s1 | s2 # Union
=> #<Set: {5, 6, 1, 2, 3, 4}>
>> s1 & s2 # Intersection
=> #<Set: {3, 4}>
>> s1 - s2 # Difference
=> #<Set: {1, 2}>
>> s1.proper_subset?(s1) # Proper subset
=> false
>> Set[3, 1].proper_subset?(s1) # Proper subset
=> true
>> s1.subset?(s1) # Subset
=> true
>> Set[3, 1].subset?(s1) # Subset
=> true
>> Set[3, 2, 4, 1] == s1 # Equality
=> true
>> s1 == s2 # Equality
=> false
>> s1.include?(2) # Membership
=> true
>> Set[1, 2, 3, 4, 5].proper_superset?(s1) # Proper superset
=> true
>> Set[1, 2, 3, 4].proper_superset?(s1) # Proper superset
=> false
>> Set[1, 2, 3, 4].superset?(s1) # Superset
=> true
>> s1 ^ s2 # Symmetric difference
=> #<Set: {5, 6, 1, 2}>
>> s1.size # Cardinality
=> 4
>> s1 << 99 # Mutability (or s1.add(99) )
=> #<Set: {99, 1, 2, 3, 4}>
>> s1.delete(99) # Mutability
=> #<Set: {1, 2, 3, 4}>
>> s1.merge(s2) # Mutability
=> #<Set: {5, 6, 1, 2, 3, 4}>
>> s1.subtract(s2) # Mutability
=> #<Set: {1, 2}>
>>
|
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
|
Sieve of Eratosthenes
|
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer.
Task
Implement the Sieve of Eratosthenes algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found.
That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes.
If there's an easy way to add such a wheel based optimization, implement it as an alternative version.
Note
It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task.
Related tasks
Emirp primes
count in factors
prime decomposition
factors of an integer
extensible prime generator
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
|
#Groovy
|
Groovy
|
def sievePrimes = { bound ->
def isPrime = new BitSet(bound)
isPrime[0..1] = false
isPrime[2..bound] = true
(2..(Math.sqrt(bound))).each { pc ->
if (isPrime[pc]) {
((pc**2)..bound).step(pc) { isPrime[it] = false }
}
}
(0..bound).findAll { isPrime[it] }
}
|
http://rosettacode.org/wiki/SEDOLs
|
SEDOLs
|
Task
For each number list of 6-digit SEDOLs, calculate and append the checksum digit.
That is, given this input:
710889
B0YBKJ
406566
B0YBLH
228276
B0YBKL
557910
B0YBKR
585284
B0YBKT
B00030
Produce this output:
7108899
B0YBKJ7
4065663
B0YBLH2
2282765
B0YBKL9
5579107
B0YBKR5
5852842
B0YBKT7
B000300
Extra credit
Check each input is correctly formed, especially with respect to valid characters allowed in a SEDOL string.
Related tasks
Luhn test
ISIN
|
#VBA
|
VBA
|
Function getSedolCheckDigit(Input1)
Dim mult(6) As Integer
mult(1) = 1: mult(2) = 3: mult(3) = 1
mult(4) = 7: mult(5) = 3: mult(6) = 9
If Len(Input1) <> 6 Then
getSedolCheckDigit = "Six chars only please"
Exit Function
End If
Input1 = UCase(Input1)
Total = 0
For i = 1 To 6
s1 = Mid(Input1, i, 1)
If (s1 = "A") Or (s1 = "E") Or (s1 = "I") Or (s1 = "O") Or (s1 = "U") Then
getSedolCheckDigit = "No vowels"
Exit Function
End If
If (Asc(s1) >= 48) And (Asc(s1) <= 57) Then
Total = Total + Val(s1) * mult(i)
Else
Total = Total + (Asc(s1) - 55) * mult(i)
End If
Next i
getSedolCheckDigit = Input1 + CStr((10 - (Total Mod 10)) Mod 10)
End Function
|
http://rosettacode.org/wiki/Set
|
Set
|
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
A set is a collection of elements, without duplicates and without order.
Task
Show each of these set operations:
Set creation
Test m ∈ S -- "m is an element in set S"
A ∪ B -- union; a set of all elements either in set A or in set B.
A ∩ B -- intersection; a set of all elements in both set A and set B.
A ∖ B -- difference; a set of all elements in set A, except those in set B.
A ⊆ B -- subset; true if every element in set A is also in set B.
A = B -- equality; true if every element of set A is in set B and vice versa.
As an option, show some other set operations.
(If A ⊆ B, but A ≠ B, then A is called a true or proper subset of B, written A ⊂ B or A ⊊ B.)
As another option, show how to modify a mutable set.
One might implement a set using an associative array (with set elements as array keys and some dummy value as the values).
One might also implement a set with a binary search tree, or with a hash table, or with an ordered array of binary bits (operated on with bit-wise binary operators).
The basic test, m ∈ S, is O(n) with a sequential list of elements, O(log n) with a balanced binary search tree, or (O(1) average-case, O(n) worst case) with a hash table.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
|
#Run_BASIC
|
Run BASIC
|
A$ = "apple cherry elderberry grape"
B$ = "banana cherry date elderberry fig"
C$ = "apple cherry elderberry grape orange"
D$ = "apple cherry elderberry grape"
E$ = "apple cherry elderberry"
M$ = "banana"
print "A = ";A$
print "B = ";B$
print "C = ";C$
print "D = ";D$
print "E = ";E$
print "M = ";M$
if instr(A$,M$) = 0 then a$ = "not "
print "M is ";a$; "an element of Set A"
a$ = ""
if instr(B$,M$) = 0 then a$ = "not "
print "M is ";a$; "an element of Set B"
un$ = A$ + " "
for i = 1 to 5
if instr(un$,word$(B$,i)) = 0 then un$ = un$ + word$(B$,i) + " "
next i
print "union(A,B) = ";un$
for i = 1 to 5
if instr(A$,word$(B$,i)) <> 0 then ins$ = ins$ + word$(B$,i) + " "
next i
print "Intersection(A,B) = ";ins$
for i = 1 to 5
if instr(B$,word$(A$,i)) = 0 then dif$ = dif$ + word$(A$,i) + " "
next i
print "Difference(A,B) = ";dif$
a = subs(A$,B$,"AB")
a = subs(A$,C$,"AC")
a = subs(A$,D$,"AD")
a = subs(A$,E$,"AE")
a = eqs(A$,B$,"AB")
a = eqs(A$,C$,"AC")
a = eqs(A$,D$,"AD")
a = eqs(A$,E$,"AE")
end
function subs(a$,b$,sets$)
for i = 1 to 5
if instr(b$,word$(a$,i)) <> 0 then subs = subs + 1
next i
if subs = 4 then
print left$(sets$,1);" is a subset of ";right$(sets$,1)
else
print left$(sets$,1);" is not a subset of ";right$(sets$,1)
end if
end function
function eqs(a$,b$,sets$)
for i = 1 to 5
if word$(a$,i) <> "" then a = a + 1
if word$(b$,i) <> "" then b = b + 1
if instr(b$,word$(a$,i)) <> 0 then c = c + 1
next i
if (a = b) and (a = c) then
print left$(sets$,1);" is equal ";right$(sets$,1)
else
print left$(sets$,1);" is not equal ";right$(sets$,1)
end if
end function
|
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
|
Sieve of Eratosthenes
|
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer.
Task
Implement the Sieve of Eratosthenes algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found.
That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes.
If there's an easy way to add such a wheel based optimization, implement it as an alternative version.
Note
It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task.
Related tasks
Emirp primes
count in factors
prime decomposition
factors of an integer
extensible prime generator
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
|
#GW-BASIC
|
GW-BASIC
|
10 INPUT "ENTER NUMBER TO SEARCH TO: ";LIMIT
20 DIM FLAGS(LIMIT)
30 FOR N = 2 TO SQR (LIMIT)
40 IF FLAGS(N) < > 0 GOTO 80
50 FOR K = N * N TO LIMIT STEP N
60 FLAGS(K) = 1
70 NEXT K
80 NEXT N
90 REM DISPLAY THE PRIMES
100 FOR N = 2 TO LIMIT
110 IF FLAGS(N) = 0 THEN PRINT N;", ";
120 NEXT N
|
http://rosettacode.org/wiki/SEDOLs
|
SEDOLs
|
Task
For each number list of 6-digit SEDOLs, calculate and append the checksum digit.
That is, given this input:
710889
B0YBKJ
406566
B0YBLH
228276
B0YBKL
557910
B0YBKR
585284
B0YBKT
B00030
Produce this output:
7108899
B0YBKJ7
4065663
B0YBLH2
2282765
B0YBKL9
5579107
B0YBKR5
5852842
B0YBKT7
B000300
Extra credit
Check each input is correctly formed, especially with respect to valid characters allowed in a SEDOL string.
Related tasks
Luhn test
ISIN
|
#VBScript
|
VBScript
|
arr = Array("710889",_
"B0YBKJ",_
"406566",_
"B0YBLH",_
"228276",_
"B0YBKL",_
"557910",_
"B0YBKR",_
"585284",_
"B0YBKT",_
"12345",_
"A12345",_
"B00030")
For j = 0 To UBound(arr)
WScript.StdOut.Write arr(j) & getSEDOLCheckDigit(arr(j))
WScript.StdOut.WriteLine
Next
Function getSEDOLCheckDigit(str)
If Len(str) <> 6 Then
getSEDOLCheckDigit = " is invalid. Only 6 character strings are allowed."
Exit Function
End If
Set mult = CreateObject("Scripting.Dictionary")
With mult
.Add "1","1" : .Add "2", "3" : .Add "3", "1"
.Add "4","7" : .Add "5", "3" : .Add "6", "9"
End With
total = 0
For i = 1 To 6
s = Mid(str,i,1)
If s = "A" Or s = "E" Or s = "I" Or s = "O" Or s = "U" Then
getSEDOLCheckDigit = " is invalid. Vowels are not allowed."
Exit Function
End If
If Asc(s) >= 48 And Asc(s) <=57 Then
total = total + CInt(s) * CInt(mult.Item(CStr(i)))
Else
total = total + (Asc(s) - 55) * CInt(mult.Item(CStr(i)))
End If
Next
getSEDOLCheckDigit = (10 - total Mod 10) Mod 10
End Function
|
http://rosettacode.org/wiki/SEDOLs
|
SEDOLs
|
Task
For each number list of 6-digit SEDOLs, calculate and append the checksum digit.
That is, given this input:
710889
B0YBKJ
406566
B0YBLH
228276
B0YBKL
557910
B0YBKR
585284
B0YBKT
B00030
Produce this output:
7108899
B0YBKJ7
4065663
B0YBLH2
2282765
B0YBKL9
5579107
B0YBKR5
5852842
B0YBKT7
B000300
Extra credit
Check each input is correctly formed, especially with respect to valid characters allowed in a SEDOL string.
Related tasks
Luhn test
ISIN
|
#Visual_FoxPro
|
Visual FoxPro
|
#DEFINE ALPHABET "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
#DEFINE VOWELS "AEIOU"
#DEFINE VALIDCHARS "0123456789" + ALPHABET
LOCAL cMsg As String, cCode As String
LOCAL ARRAY codes[12]
codes[1] = "710889"
codes[2] = "B0YBKJ"
codes[3] = "406566"
codes[4] = "B0YBLH"
codes[5] = "228276"
codes[6] = "B0YBKL"
codes[7] = "557910"
codes[8] = "B0YBKR"
codes[9] = "585284"
codes[10] = "B0YBKT"
codes[11] = "B00030"
codes[12] = "B0030A"
DIMENSION w[6]
w[1] = 1
w[2] = 3
w[3] = 1
w[4] = 7
w[5] = 3
w[6] = 9
CLEAR
FOR EACH cCode IN codes
cMsg = ""
IF IsValidCode(@cCode, @cMsg) && Parameters passed by reference
cCode = cCode + GetCheckDigit(cCode)
? cCode
ELSE
? cCode, cMsg
ENDIF
ENDFOR
FUNCTION GetCheckDigit(tcCode As String) As String
LOCAL i As Integer, c As String, s As Integer, k As Integer
s = 0
FOR i = 1 TO 6
c = SUBSTR(tcCode, i, 1)
IF ISDIGIT(c)
k = VAL(c)
ELSE
k = 9 + AT(c, ALPHABET)
ENDIF
s = s + k*w[i]
ENDFOR
RETURN TRANSFORM((10 - s%10)%10)
ENDFUNC
FUNCTION IsValidCode(tcCode As String, tcMsg As String) As Boolean
LOCAL n As Integer, c As String, i As Integer
*!* Get rid of any spaces and convert to upper case
tcCode = UPPER(STRTRAN(tcCode, " "))
n = LEN(tcCode)
IF LEN(tcCode) # 6
tcMsg = "Code must be 6 characters."
ELSE
FOR i = 1 TO n
c = SUBSTR(tcCode, i, 1)
IF NOT c $ VALIDCHAR
tcMsg = c + " is not a valid character."
EXIT
ELSE
IF c $ VOWELS
tcMsg = "Vowels are not allowed."
EXIT
ENDIF
ENDIF
ENDFOR
ENDIF
RETURN EMPTY(tcMsg)
ENDFUNC
|
http://rosettacode.org/wiki/Search_in_paragraph%27s_text
|
Search in paragraph's text
|
The goal is to verify the presence of a word or regular expression within several paragraphs of text (structured or not) and to format the output of the relevant paragraphs before putting them on the standard output.
So here, let’s imagine that we are trying to verify the presence of a keyword "SystemError" within what I want to call "the paragraphs" "Traceback (most recent call last):" in the file Traceback.txt
cat Traceback.txt :
2018-06-19 23:19:34,877 ERROR Processes plugin raised an exception.
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/landscape/sysinfo/sysinfo.py", line 99, in run
result = plugin.run()
File "/usr/lib/python3/dist-packages/landscape/sysinfo/processes.py", line 18, in run
for process_info in info.get_all_process_info():
File "/usr/lib/python3/dist-packages/landscape/lib/process.py", line 39, in get_all_process_info
process_info = self.get_process_info(process_id)
File "/usr/lib/python3/dist-packages/landscape/lib/process.py", line 61, in get_process_info
cmd_line = file.readline()
File "/usr/lib/python3.6/encodings/ascii.py", line 26, in decode
return codecs.ascii_decode(input, self.errors)[0]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc5 in position 152: ordinal not in range(128)
2018-06-19 23:19:34,877 ERROR Processes plugin raised an exception.
Traceback (most recent call last):
vmodl.fault.SystemError: (vmodl.fault.SystemError) {
dynamicType = ,
dynamicProperty = (vmodl.DynamicProperty) [],
msg = 'A general system error occurred: Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.',
faultCause = ,
faultMessage = (vmodl.LocalizableMessage) [],
reason = 'Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.'
}
[Tue Jan 21 16:16:19.250245 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] Traceback (most recent call last):
[Tue Jan 21 16:16:19.252221 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] SystemError: unable to access /home/dir
[Tue Jan 21 16:16:19.249067 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] mod_wsgi (pid=6515): Failed to exec Python script file '/home/pi/RaspBerryPiAdhan/www/sysinfo.wsgi'.
[Tue Jan 21 16:16:19.249609 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] mod_wsgi (pid=6515): Exception occurred processing WSGI script '/home/pi/RaspBerryPiAdhan/www/sysinfo.wsgi'.
[Tue Jan 21 17:16:19.250245 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] Traceback (most recent call last):
[Tue Jan 21 17:16:19.250679 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] File "/home/pi/RaspBerryPiAdhan/www/sysinfo.wsgi", line 5, in <module>
[Tue Jan 21 17:16:19.251735 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] from test import app as application
[Tue Jan 21 17:16:19.252221 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] ImportError: cannot import name app
2021-04-23 17:13:14,425 ERROR Network plugin raised an exception.
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/landscape/sysinfo/sysinfo.py", line 99,
in run
result = plugin.run()
File "/usr/lib/python3/dist-packages/landscape/sysinfo/network.py", line 36,
in run
device_info = self._get_device_info()
File "/usr/lib/python3/dist-packages/landscape/lib/network.py", line 163, in
get_active_device_info
speed, duplex = get_network_interface_speed(
File "/usr/lib/python3/dist-packages/landscape/lib/network.py", line 249, in
get_network_interface_speed
res = status_cmd.tostring()
AttributeError: 'array.array' object has no attribute 'tostring'
11/01 18:24:57.726 ERROR| log:0072| post-test sysinfo error: 11/01 18:24:57.727 ERROR| traceback:0013| Traceback (most recent call last): 11/01 18:24:57.728 ERROR| traceback:0013| File "/tmp/sysinfo/autoserv-0tMj3m/common_lib/log.py", line 70, in decorated_func 11/01 18:24:57.729 ERROR| traceback:0013| fn(*args, **dargs) 11/01 18:24:57.730 ERROR| traceback:0013| File "/tmp/sysinfo/autoserv-0tMj3m/bin/base_sysinfo.py", line 286, in log_after_each_test 11/01 18:24:57.731 ERROR| traceback:0013| old_packages = set(self._installed_packages) 11/01 18:24:57.731 ERROR| traceback:0013| TypeError: 'NoneType' object is not iterable
12/01 19:24:57.726 ERROR| log:0072| post-test sysinfo error: 11/01 18:24:57.727 ERROR| traceback:0013| Traceback (most recent call last): 11/01 18:24:57.728 ERROR| traceback:0013| File "/tmp/sysinfo/autoserv-0tMj3m/common_lib/log.py", line 70, in decorated_func 11/01 18:24:57.729 ERROR| traceback:0013| fn(*args, **dargs) 11/01 18:24:57.730 ERROR| traceback:0013| File "/tmp/sysinfo/autoserv-0tMj3m/bin/base_sysinfo.py", line 286, in log_after_each_test 11/01 18:24:57.731 ERROR| traceback:0013| old_packages = set(self._installed_packages) 11/01 18:24:57.731 ERROR| traceback:0013| SystemError: no such file or directory
Traceback (most recent call last):
File "/usr/lib/vmware-vpx/vsan-health/pyMoVsan/VsanClusterPrototypeImpl.py", line 1492, in WaitForUpdateTask
WaitForTask(task)
File "/usr/lib/vmware-vpx/pyJack/pyVim/task.py", line 123, in WaitForTask
raise task.info.error
vmodl.fault.SystemError: (vmodl.fault.SystemError) {
dynamicType = ,
dynamicProperty = (vmodl.DynamicProperty) [],
msg = 'A general system error occurred: Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.',
faultCause = ,
faultMessage = (vmodl.LocalizableMessage) [],
reason = 'Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.'
}
The expected result must be formated with ---------------- for paragraph's separator AND "Traceback (most recent call last):" as the beginning of each relevant's paragraph :
Traceback (most recent call last):
vmodl.fault.SystemError: (vmodl.fault.SystemError) {
dynamicType = ,
dynamicProperty = (vmodl.DynamicProperty) [],
msg = 'A general system error occurred: Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.',
faultCause = ,
faultMessage = (vmodl.LocalizableMessage) [],
reason = 'Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.'
}
----------------
Traceback (most recent call last):
[Tue Jan 21 16:16:19.252221 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] SystemError: unable to access /home/dir
[Tue Jan 21 16:16:19.249067 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] mod_wsgi (pid=6515): Failed to exec Python script file '/home/pi/RaspBerryPiAdhan/www/sysinfo.wsgi'.
[Tue Jan 21 16:16:19.249609 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] mod_wsgi (pid=6515): Exception occurred processing WSGI script '/home/pi/RaspBerryPiAdhan/www/sysinfo.wsgi'.
----------------
Traceback (most recent call last): 11/01 18:24:57.728 ERROR| traceback:0013| File "/tmp/sysinfo/autoserv-0tMj3m/common_lib/log.py", line 70, in decorated_func 11/01 18:24:57.729 ERROR| traceback:0013| fn(*args, **dargs) 11/01 18:24:57.730 ERROR| traceback:0013| File "/tmp/sysinfo/autoserv-0tMj3m/bin/base_sysinfo.py", line 286, in log_after_each_test 11/01 18:24:57.731 ERROR| traceback:0013| old_packages = set(self._installed_packages) 11/01 18:24:57.731 ERROR| traceback:0013| SystemError: no such file or directory
----------------
Traceback (most recent call last):
File "/usr/lib/vmware-vpx/vsan-health/pyMoVsan/VsanClusterPrototypeImpl.py", line 1492, in WaitForUpdateTask
WaitForTask(task)
File "/usr/lib/vmware-vpx/pyJack/pyVim/task.py", line 123, in WaitForTask
raise task.info.error
vmodl.fault.SystemError: (vmodl.fault.SystemError) {
dynamicType = ,
dynamicProperty = (vmodl.DynamicProperty) [],
msg = 'A general system error occurred: Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.',
faultCause = ,
faultMessage = (vmodl.LocalizableMessage) [],
reason = 'Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.'
}
----------------
|
#AWK
|
AWK
|
awk 'BEGIN { RS = "" ; ORS = "\n----------------\n" } /Traceback/ && /SystemError/ { print substr($0,index($0,"Traceback")) }' Traceback.txt
|
http://rosettacode.org/wiki/Set
|
Set
|
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
A set is a collection of elements, without duplicates and without order.
Task
Show each of these set operations:
Set creation
Test m ∈ S -- "m is an element in set S"
A ∪ B -- union; a set of all elements either in set A or in set B.
A ∩ B -- intersection; a set of all elements in both set A and set B.
A ∖ B -- difference; a set of all elements in set A, except those in set B.
A ⊆ B -- subset; true if every element in set A is also in set B.
A = B -- equality; true if every element of set A is in set B and vice versa.
As an option, show some other set operations.
(If A ⊆ B, but A ≠ B, then A is called a true or proper subset of B, written A ⊂ B or A ⊊ B.)
As another option, show how to modify a mutable set.
One might implement a set using an associative array (with set elements as array keys and some dummy value as the values).
One might also implement a set with a binary search tree, or with a hash table, or with an ordered array of binary bits (operated on with bit-wise binary operators).
The basic test, m ∈ S, is O(n) with a sequential list of elements, O(log n) with a balanced binary search tree, or (O(1) average-case, O(n) worst case) with a hash table.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
|
#Rust
|
Rust
|
use std::collections::HashSet;
fn main() {
let a = vec![1, 3, 4].into_iter().collect::<HashSet<i32>>();
let b = vec![3, 5, 6].into_iter().collect::<HashSet<i32>>();
println!("Set A: {:?}", a.iter().collect::<Vec<_>>());
println!("Set B: {:?}", b.iter().collect::<Vec<_>>());
println!("Does A contain 4? {}", a.contains(&4));
println!("Union: {:?}", a.union(&b).collect::<Vec<_>>());
println!("Intersection: {:?}", a.intersection(&b).collect::<Vec<_>>());
println!("Difference: {:?}", a.difference(&b).collect::<Vec<_>>());
println!("Is A a subset of B? {}", a.is_subset(&b));
println!("Is A equal to B? {}", a == b);
}
|
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
|
Sieve of Eratosthenes
|
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer.
Task
Implement the Sieve of Eratosthenes algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found.
That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes.
If there's an easy way to add such a wheel based optimization, implement it as an alternative version.
Note
It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task.
Related tasks
Emirp primes
count in factors
prime decomposition
factors of an integer
extensible prime generator
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
|
#Haskell
|
Haskell
|
{-# LANGUAGE FlexibleContexts #-} -- too lazy to write contexts...
{-# OPTIONS_GHC -O2 #-}
import Control.Monad.ST ( runST, ST )
import Data.Array.Base ( MArray(newArray, unsafeRead, unsafeWrite),
IArray(unsafeAt),
STUArray, unsafeFreezeSTUArray, assocs )
import Data.Time.Clock.POSIX ( getPOSIXTime ) -- for timing...
primesTo :: Int -> [Int] -- generate a list of primes to given limit...
primesTo limit = runST $ do
let lmt = limit - 2-- raw index of limit!
cmpsts <- newArray (2, limit) False -- when indexed is true is composite
cmpstsf <- unsafeFreezeSTUArray cmpsts -- frozen in place!
let getbpndx bp = (bp, bp * bp - 2) -- bp -> bp, raw index of start cull
cullcmpst i = unsafeWrite cmpsts i True -- cull composite by raw ndx
cull4bpndx (bp, si0) = mapM_ cullcmpst [ si0, si0 + bp .. lmt ]
mapM_ cull4bpndx
$ takeWhile ((>=) lmt . snd) -- for bp's <= square root limit
[ getbpndx bp | (bp, False) <- assocs cmpstsf ]
return [ p | (p, False) <- assocs cmpstsf ] -- non-raw ndx is prime
-- testing...
main :: IO ()
main = do
putStrLn $ "The primes up to 100 are " ++ show (primesTo 100)
putStrLn $ "The number of primes up to a million is " ++
show (length $ primesTo 1000000)
let top = 1000000000
start <- getPOSIXTime
let answr = length $ primesTo top
stop <- answr `seq` getPOSIXTime -- force result for timing!
let elpsd = round $ 1e3 * (stop - start) :: Int
putStrLn $ "Found " ++ show answr ++ " to " ++ show top ++
" in " ++ show elpsd ++ " milliseconds."
|
http://rosettacode.org/wiki/SEDOLs
|
SEDOLs
|
Task
For each number list of 6-digit SEDOLs, calculate and append the checksum digit.
That is, given this input:
710889
B0YBKJ
406566
B0YBLH
228276
B0YBKL
557910
B0YBKR
585284
B0YBKT
B00030
Produce this output:
7108899
B0YBKJ7
4065663
B0YBLH2
2282765
B0YBKL9
5579107
B0YBKR5
5852842
B0YBKT7
B000300
Extra credit
Check each input is correctly formed, especially with respect to valid characters allowed in a SEDOL string.
Related tasks
Luhn test
ISIN
|
#Wren
|
Wren
|
import "/str" for Char
import "/fmt" for Conv
var sedol = Fn.new { |s|
if (!(s is String && s.count == 6)) return false
var weights = [1, 3, 1, 7, 3, 9]
var sum = 0
for (i in 0..5) {
var c = s[i]
if (!Char.isUpper(c) && !Char.isDigit(c)) return null
if ("AEIOU".contains(c)) return null
sum = sum + Conv.atoi(c, 36) * weights[i]
}
var cd = (10 - sum%10) % 10
return s + "%(cd)"
}
var tests = [
"710889",
"B0YBKJ",
"406566",
"B0YBLH",
"228276",
"B0YBKL",
"557910",
"B0YBKR",
"585284",
"B0YBKT",
"B00030",
"I23456"
]
for (test in tests) {
var a
var ans = (a = sedol.call(test)) ? a : "not valid"
System.print("%(test) -> %(ans)")
}
|
http://rosettacode.org/wiki/Search_in_paragraph%27s_text
|
Search in paragraph's text
|
The goal is to verify the presence of a word or regular expression within several paragraphs of text (structured or not) and to format the output of the relevant paragraphs before putting them on the standard output.
So here, let’s imagine that we are trying to verify the presence of a keyword "SystemError" within what I want to call "the paragraphs" "Traceback (most recent call last):" in the file Traceback.txt
cat Traceback.txt :
2018-06-19 23:19:34,877 ERROR Processes plugin raised an exception.
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/landscape/sysinfo/sysinfo.py", line 99, in run
result = plugin.run()
File "/usr/lib/python3/dist-packages/landscape/sysinfo/processes.py", line 18, in run
for process_info in info.get_all_process_info():
File "/usr/lib/python3/dist-packages/landscape/lib/process.py", line 39, in get_all_process_info
process_info = self.get_process_info(process_id)
File "/usr/lib/python3/dist-packages/landscape/lib/process.py", line 61, in get_process_info
cmd_line = file.readline()
File "/usr/lib/python3.6/encodings/ascii.py", line 26, in decode
return codecs.ascii_decode(input, self.errors)[0]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc5 in position 152: ordinal not in range(128)
2018-06-19 23:19:34,877 ERROR Processes plugin raised an exception.
Traceback (most recent call last):
vmodl.fault.SystemError: (vmodl.fault.SystemError) {
dynamicType = ,
dynamicProperty = (vmodl.DynamicProperty) [],
msg = 'A general system error occurred: Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.',
faultCause = ,
faultMessage = (vmodl.LocalizableMessage) [],
reason = 'Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.'
}
[Tue Jan 21 16:16:19.250245 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] Traceback (most recent call last):
[Tue Jan 21 16:16:19.252221 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] SystemError: unable to access /home/dir
[Tue Jan 21 16:16:19.249067 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] mod_wsgi (pid=6515): Failed to exec Python script file '/home/pi/RaspBerryPiAdhan/www/sysinfo.wsgi'.
[Tue Jan 21 16:16:19.249609 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] mod_wsgi (pid=6515): Exception occurred processing WSGI script '/home/pi/RaspBerryPiAdhan/www/sysinfo.wsgi'.
[Tue Jan 21 17:16:19.250245 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] Traceback (most recent call last):
[Tue Jan 21 17:16:19.250679 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] File "/home/pi/RaspBerryPiAdhan/www/sysinfo.wsgi", line 5, in <module>
[Tue Jan 21 17:16:19.251735 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] from test import app as application
[Tue Jan 21 17:16:19.252221 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] ImportError: cannot import name app
2021-04-23 17:13:14,425 ERROR Network plugin raised an exception.
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/landscape/sysinfo/sysinfo.py", line 99,
in run
result = plugin.run()
File "/usr/lib/python3/dist-packages/landscape/sysinfo/network.py", line 36,
in run
device_info = self._get_device_info()
File "/usr/lib/python3/dist-packages/landscape/lib/network.py", line 163, in
get_active_device_info
speed, duplex = get_network_interface_speed(
File "/usr/lib/python3/dist-packages/landscape/lib/network.py", line 249, in
get_network_interface_speed
res = status_cmd.tostring()
AttributeError: 'array.array' object has no attribute 'tostring'
11/01 18:24:57.726 ERROR| log:0072| post-test sysinfo error: 11/01 18:24:57.727 ERROR| traceback:0013| Traceback (most recent call last): 11/01 18:24:57.728 ERROR| traceback:0013| File "/tmp/sysinfo/autoserv-0tMj3m/common_lib/log.py", line 70, in decorated_func 11/01 18:24:57.729 ERROR| traceback:0013| fn(*args, **dargs) 11/01 18:24:57.730 ERROR| traceback:0013| File "/tmp/sysinfo/autoserv-0tMj3m/bin/base_sysinfo.py", line 286, in log_after_each_test 11/01 18:24:57.731 ERROR| traceback:0013| old_packages = set(self._installed_packages) 11/01 18:24:57.731 ERROR| traceback:0013| TypeError: 'NoneType' object is not iterable
12/01 19:24:57.726 ERROR| log:0072| post-test sysinfo error: 11/01 18:24:57.727 ERROR| traceback:0013| Traceback (most recent call last): 11/01 18:24:57.728 ERROR| traceback:0013| File "/tmp/sysinfo/autoserv-0tMj3m/common_lib/log.py", line 70, in decorated_func 11/01 18:24:57.729 ERROR| traceback:0013| fn(*args, **dargs) 11/01 18:24:57.730 ERROR| traceback:0013| File "/tmp/sysinfo/autoserv-0tMj3m/bin/base_sysinfo.py", line 286, in log_after_each_test 11/01 18:24:57.731 ERROR| traceback:0013| old_packages = set(self._installed_packages) 11/01 18:24:57.731 ERROR| traceback:0013| SystemError: no such file or directory
Traceback (most recent call last):
File "/usr/lib/vmware-vpx/vsan-health/pyMoVsan/VsanClusterPrototypeImpl.py", line 1492, in WaitForUpdateTask
WaitForTask(task)
File "/usr/lib/vmware-vpx/pyJack/pyVim/task.py", line 123, in WaitForTask
raise task.info.error
vmodl.fault.SystemError: (vmodl.fault.SystemError) {
dynamicType = ,
dynamicProperty = (vmodl.DynamicProperty) [],
msg = 'A general system error occurred: Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.',
faultCause = ,
faultMessage = (vmodl.LocalizableMessage) [],
reason = 'Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.'
}
The expected result must be formated with ---------------- for paragraph's separator AND "Traceback (most recent call last):" as the beginning of each relevant's paragraph :
Traceback (most recent call last):
vmodl.fault.SystemError: (vmodl.fault.SystemError) {
dynamicType = ,
dynamicProperty = (vmodl.DynamicProperty) [],
msg = 'A general system error occurred: Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.',
faultCause = ,
faultMessage = (vmodl.LocalizableMessage) [],
reason = 'Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.'
}
----------------
Traceback (most recent call last):
[Tue Jan 21 16:16:19.252221 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] SystemError: unable to access /home/dir
[Tue Jan 21 16:16:19.249067 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] mod_wsgi (pid=6515): Failed to exec Python script file '/home/pi/RaspBerryPiAdhan/www/sysinfo.wsgi'.
[Tue Jan 21 16:16:19.249609 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] mod_wsgi (pid=6515): Exception occurred processing WSGI script '/home/pi/RaspBerryPiAdhan/www/sysinfo.wsgi'.
----------------
Traceback (most recent call last): 11/01 18:24:57.728 ERROR| traceback:0013| File "/tmp/sysinfo/autoserv-0tMj3m/common_lib/log.py", line 70, in decorated_func 11/01 18:24:57.729 ERROR| traceback:0013| fn(*args, **dargs) 11/01 18:24:57.730 ERROR| traceback:0013| File "/tmp/sysinfo/autoserv-0tMj3m/bin/base_sysinfo.py", line 286, in log_after_each_test 11/01 18:24:57.731 ERROR| traceback:0013| old_packages = set(self._installed_packages) 11/01 18:24:57.731 ERROR| traceback:0013| SystemError: no such file or directory
----------------
Traceback (most recent call last):
File "/usr/lib/vmware-vpx/vsan-health/pyMoVsan/VsanClusterPrototypeImpl.py", line 1492, in WaitForUpdateTask
WaitForTask(task)
File "/usr/lib/vmware-vpx/pyJack/pyVim/task.py", line 123, in WaitForTask
raise task.info.error
vmodl.fault.SystemError: (vmodl.fault.SystemError) {
dynamicType = ,
dynamicProperty = (vmodl.DynamicProperty) [],
msg = 'A general system error occurred: Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.',
faultCause = ,
faultMessage = (vmodl.LocalizableMessage) [],
reason = 'Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.'
}
----------------
|
#J
|
J
|
NB. read file, separate on blank lines
paragraphs=: ((LF,LF)&E. <;.2 ])fread 'traceback.txt'
NB. ignore text preceding 'Traceback (most recent call last)'
cleaned=: {{y}.~{.I.'Traceback (most recent call last)'&E.y}}each paragraphs
NB. limit to paragraphs containing 'SystemError'
searched=: (#~ (1 e.'SystemError'&E.)every) cleaned
NB. add "paragraph 'separator'" and display
echo ;searched ,L:0 '----------------',LF
|
http://rosettacode.org/wiki/Search_in_paragraph%27s_text
|
Search in paragraph's text
|
The goal is to verify the presence of a word or regular expression within several paragraphs of text (structured or not) and to format the output of the relevant paragraphs before putting them on the standard output.
So here, let’s imagine that we are trying to verify the presence of a keyword "SystemError" within what I want to call "the paragraphs" "Traceback (most recent call last):" in the file Traceback.txt
cat Traceback.txt :
2018-06-19 23:19:34,877 ERROR Processes plugin raised an exception.
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/landscape/sysinfo/sysinfo.py", line 99, in run
result = plugin.run()
File "/usr/lib/python3/dist-packages/landscape/sysinfo/processes.py", line 18, in run
for process_info in info.get_all_process_info():
File "/usr/lib/python3/dist-packages/landscape/lib/process.py", line 39, in get_all_process_info
process_info = self.get_process_info(process_id)
File "/usr/lib/python3/dist-packages/landscape/lib/process.py", line 61, in get_process_info
cmd_line = file.readline()
File "/usr/lib/python3.6/encodings/ascii.py", line 26, in decode
return codecs.ascii_decode(input, self.errors)[0]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc5 in position 152: ordinal not in range(128)
2018-06-19 23:19:34,877 ERROR Processes plugin raised an exception.
Traceback (most recent call last):
vmodl.fault.SystemError: (vmodl.fault.SystemError) {
dynamicType = ,
dynamicProperty = (vmodl.DynamicProperty) [],
msg = 'A general system error occurred: Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.',
faultCause = ,
faultMessage = (vmodl.LocalizableMessage) [],
reason = 'Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.'
}
[Tue Jan 21 16:16:19.250245 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] Traceback (most recent call last):
[Tue Jan 21 16:16:19.252221 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] SystemError: unable to access /home/dir
[Tue Jan 21 16:16:19.249067 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] mod_wsgi (pid=6515): Failed to exec Python script file '/home/pi/RaspBerryPiAdhan/www/sysinfo.wsgi'.
[Tue Jan 21 16:16:19.249609 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] mod_wsgi (pid=6515): Exception occurred processing WSGI script '/home/pi/RaspBerryPiAdhan/www/sysinfo.wsgi'.
[Tue Jan 21 17:16:19.250245 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] Traceback (most recent call last):
[Tue Jan 21 17:16:19.250679 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] File "/home/pi/RaspBerryPiAdhan/www/sysinfo.wsgi", line 5, in <module>
[Tue Jan 21 17:16:19.251735 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] from test import app as application
[Tue Jan 21 17:16:19.252221 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] ImportError: cannot import name app
2021-04-23 17:13:14,425 ERROR Network plugin raised an exception.
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/landscape/sysinfo/sysinfo.py", line 99,
in run
result = plugin.run()
File "/usr/lib/python3/dist-packages/landscape/sysinfo/network.py", line 36,
in run
device_info = self._get_device_info()
File "/usr/lib/python3/dist-packages/landscape/lib/network.py", line 163, in
get_active_device_info
speed, duplex = get_network_interface_speed(
File "/usr/lib/python3/dist-packages/landscape/lib/network.py", line 249, in
get_network_interface_speed
res = status_cmd.tostring()
AttributeError: 'array.array' object has no attribute 'tostring'
11/01 18:24:57.726 ERROR| log:0072| post-test sysinfo error: 11/01 18:24:57.727 ERROR| traceback:0013| Traceback (most recent call last): 11/01 18:24:57.728 ERROR| traceback:0013| File "/tmp/sysinfo/autoserv-0tMj3m/common_lib/log.py", line 70, in decorated_func 11/01 18:24:57.729 ERROR| traceback:0013| fn(*args, **dargs) 11/01 18:24:57.730 ERROR| traceback:0013| File "/tmp/sysinfo/autoserv-0tMj3m/bin/base_sysinfo.py", line 286, in log_after_each_test 11/01 18:24:57.731 ERROR| traceback:0013| old_packages = set(self._installed_packages) 11/01 18:24:57.731 ERROR| traceback:0013| TypeError: 'NoneType' object is not iterable
12/01 19:24:57.726 ERROR| log:0072| post-test sysinfo error: 11/01 18:24:57.727 ERROR| traceback:0013| Traceback (most recent call last): 11/01 18:24:57.728 ERROR| traceback:0013| File "/tmp/sysinfo/autoserv-0tMj3m/common_lib/log.py", line 70, in decorated_func 11/01 18:24:57.729 ERROR| traceback:0013| fn(*args, **dargs) 11/01 18:24:57.730 ERROR| traceback:0013| File "/tmp/sysinfo/autoserv-0tMj3m/bin/base_sysinfo.py", line 286, in log_after_each_test 11/01 18:24:57.731 ERROR| traceback:0013| old_packages = set(self._installed_packages) 11/01 18:24:57.731 ERROR| traceback:0013| SystemError: no such file or directory
Traceback (most recent call last):
File "/usr/lib/vmware-vpx/vsan-health/pyMoVsan/VsanClusterPrototypeImpl.py", line 1492, in WaitForUpdateTask
WaitForTask(task)
File "/usr/lib/vmware-vpx/pyJack/pyVim/task.py", line 123, in WaitForTask
raise task.info.error
vmodl.fault.SystemError: (vmodl.fault.SystemError) {
dynamicType = ,
dynamicProperty = (vmodl.DynamicProperty) [],
msg = 'A general system error occurred: Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.',
faultCause = ,
faultMessage = (vmodl.LocalizableMessage) [],
reason = 'Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.'
}
The expected result must be formated with ---------------- for paragraph's separator AND "Traceback (most recent call last):" as the beginning of each relevant's paragraph :
Traceback (most recent call last):
vmodl.fault.SystemError: (vmodl.fault.SystemError) {
dynamicType = ,
dynamicProperty = (vmodl.DynamicProperty) [],
msg = 'A general system error occurred: Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.',
faultCause = ,
faultMessage = (vmodl.LocalizableMessage) [],
reason = 'Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.'
}
----------------
Traceback (most recent call last):
[Tue Jan 21 16:16:19.252221 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] SystemError: unable to access /home/dir
[Tue Jan 21 16:16:19.249067 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] mod_wsgi (pid=6515): Failed to exec Python script file '/home/pi/RaspBerryPiAdhan/www/sysinfo.wsgi'.
[Tue Jan 21 16:16:19.249609 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] mod_wsgi (pid=6515): Exception occurred processing WSGI script '/home/pi/RaspBerryPiAdhan/www/sysinfo.wsgi'.
----------------
Traceback (most recent call last): 11/01 18:24:57.728 ERROR| traceback:0013| File "/tmp/sysinfo/autoserv-0tMj3m/common_lib/log.py", line 70, in decorated_func 11/01 18:24:57.729 ERROR| traceback:0013| fn(*args, **dargs) 11/01 18:24:57.730 ERROR| traceback:0013| File "/tmp/sysinfo/autoserv-0tMj3m/bin/base_sysinfo.py", line 286, in log_after_each_test 11/01 18:24:57.731 ERROR| traceback:0013| old_packages = set(self._installed_packages) 11/01 18:24:57.731 ERROR| traceback:0013| SystemError: no such file or directory
----------------
Traceback (most recent call last):
File "/usr/lib/vmware-vpx/vsan-health/pyMoVsan/VsanClusterPrototypeImpl.py", line 1492, in WaitForUpdateTask
WaitForTask(task)
File "/usr/lib/vmware-vpx/pyJack/pyVim/task.py", line 123, in WaitForTask
raise task.info.error
vmodl.fault.SystemError: (vmodl.fault.SystemError) {
dynamicType = ,
dynamicProperty = (vmodl.DynamicProperty) [],
msg = 'A general system error occurred: Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.',
faultCause = ,
faultMessage = (vmodl.LocalizableMessage) [],
reason = 'Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.'
}
----------------
|
#jq
|
jq
|
def p1: "Traceback (most recent call last):";
def p2: "SystemError";
def sep: "----------------";
split("\n\n")[]
| index(p1) as $ix
| select( $ix and index(p2) )
| .[$ix:], sep
|
http://rosettacode.org/wiki/Search_in_paragraph%27s_text
|
Search in paragraph's text
|
The goal is to verify the presence of a word or regular expression within several paragraphs of text (structured or not) and to format the output of the relevant paragraphs before putting them on the standard output.
So here, let’s imagine that we are trying to verify the presence of a keyword "SystemError" within what I want to call "the paragraphs" "Traceback (most recent call last):" in the file Traceback.txt
cat Traceback.txt :
2018-06-19 23:19:34,877 ERROR Processes plugin raised an exception.
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/landscape/sysinfo/sysinfo.py", line 99, in run
result = plugin.run()
File "/usr/lib/python3/dist-packages/landscape/sysinfo/processes.py", line 18, in run
for process_info in info.get_all_process_info():
File "/usr/lib/python3/dist-packages/landscape/lib/process.py", line 39, in get_all_process_info
process_info = self.get_process_info(process_id)
File "/usr/lib/python3/dist-packages/landscape/lib/process.py", line 61, in get_process_info
cmd_line = file.readline()
File "/usr/lib/python3.6/encodings/ascii.py", line 26, in decode
return codecs.ascii_decode(input, self.errors)[0]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc5 in position 152: ordinal not in range(128)
2018-06-19 23:19:34,877 ERROR Processes plugin raised an exception.
Traceback (most recent call last):
vmodl.fault.SystemError: (vmodl.fault.SystemError) {
dynamicType = ,
dynamicProperty = (vmodl.DynamicProperty) [],
msg = 'A general system error occurred: Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.',
faultCause = ,
faultMessage = (vmodl.LocalizableMessage) [],
reason = 'Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.'
}
[Tue Jan 21 16:16:19.250245 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] Traceback (most recent call last):
[Tue Jan 21 16:16:19.252221 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] SystemError: unable to access /home/dir
[Tue Jan 21 16:16:19.249067 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] mod_wsgi (pid=6515): Failed to exec Python script file '/home/pi/RaspBerryPiAdhan/www/sysinfo.wsgi'.
[Tue Jan 21 16:16:19.249609 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] mod_wsgi (pid=6515): Exception occurred processing WSGI script '/home/pi/RaspBerryPiAdhan/www/sysinfo.wsgi'.
[Tue Jan 21 17:16:19.250245 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] Traceback (most recent call last):
[Tue Jan 21 17:16:19.250679 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] File "/home/pi/RaspBerryPiAdhan/www/sysinfo.wsgi", line 5, in <module>
[Tue Jan 21 17:16:19.251735 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] from test import app as application
[Tue Jan 21 17:16:19.252221 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] ImportError: cannot import name app
2021-04-23 17:13:14,425 ERROR Network plugin raised an exception.
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/landscape/sysinfo/sysinfo.py", line 99,
in run
result = plugin.run()
File "/usr/lib/python3/dist-packages/landscape/sysinfo/network.py", line 36,
in run
device_info = self._get_device_info()
File "/usr/lib/python3/dist-packages/landscape/lib/network.py", line 163, in
get_active_device_info
speed, duplex = get_network_interface_speed(
File "/usr/lib/python3/dist-packages/landscape/lib/network.py", line 249, in
get_network_interface_speed
res = status_cmd.tostring()
AttributeError: 'array.array' object has no attribute 'tostring'
11/01 18:24:57.726 ERROR| log:0072| post-test sysinfo error: 11/01 18:24:57.727 ERROR| traceback:0013| Traceback (most recent call last): 11/01 18:24:57.728 ERROR| traceback:0013| File "/tmp/sysinfo/autoserv-0tMj3m/common_lib/log.py", line 70, in decorated_func 11/01 18:24:57.729 ERROR| traceback:0013| fn(*args, **dargs) 11/01 18:24:57.730 ERROR| traceback:0013| File "/tmp/sysinfo/autoserv-0tMj3m/bin/base_sysinfo.py", line 286, in log_after_each_test 11/01 18:24:57.731 ERROR| traceback:0013| old_packages = set(self._installed_packages) 11/01 18:24:57.731 ERROR| traceback:0013| TypeError: 'NoneType' object is not iterable
12/01 19:24:57.726 ERROR| log:0072| post-test sysinfo error: 11/01 18:24:57.727 ERROR| traceback:0013| Traceback (most recent call last): 11/01 18:24:57.728 ERROR| traceback:0013| File "/tmp/sysinfo/autoserv-0tMj3m/common_lib/log.py", line 70, in decorated_func 11/01 18:24:57.729 ERROR| traceback:0013| fn(*args, **dargs) 11/01 18:24:57.730 ERROR| traceback:0013| File "/tmp/sysinfo/autoserv-0tMj3m/bin/base_sysinfo.py", line 286, in log_after_each_test 11/01 18:24:57.731 ERROR| traceback:0013| old_packages = set(self._installed_packages) 11/01 18:24:57.731 ERROR| traceback:0013| SystemError: no such file or directory
Traceback (most recent call last):
File "/usr/lib/vmware-vpx/vsan-health/pyMoVsan/VsanClusterPrototypeImpl.py", line 1492, in WaitForUpdateTask
WaitForTask(task)
File "/usr/lib/vmware-vpx/pyJack/pyVim/task.py", line 123, in WaitForTask
raise task.info.error
vmodl.fault.SystemError: (vmodl.fault.SystemError) {
dynamicType = ,
dynamicProperty = (vmodl.DynamicProperty) [],
msg = 'A general system error occurred: Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.',
faultCause = ,
faultMessage = (vmodl.LocalizableMessage) [],
reason = 'Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.'
}
The expected result must be formated with ---------------- for paragraph's separator AND "Traceback (most recent call last):" as the beginning of each relevant's paragraph :
Traceback (most recent call last):
vmodl.fault.SystemError: (vmodl.fault.SystemError) {
dynamicType = ,
dynamicProperty = (vmodl.DynamicProperty) [],
msg = 'A general system error occurred: Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.',
faultCause = ,
faultMessage = (vmodl.LocalizableMessage) [],
reason = 'Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.'
}
----------------
Traceback (most recent call last):
[Tue Jan 21 16:16:19.252221 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] SystemError: unable to access /home/dir
[Tue Jan 21 16:16:19.249067 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] mod_wsgi (pid=6515): Failed to exec Python script file '/home/pi/RaspBerryPiAdhan/www/sysinfo.wsgi'.
[Tue Jan 21 16:16:19.249609 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] mod_wsgi (pid=6515): Exception occurred processing WSGI script '/home/pi/RaspBerryPiAdhan/www/sysinfo.wsgi'.
----------------
Traceback (most recent call last): 11/01 18:24:57.728 ERROR| traceback:0013| File "/tmp/sysinfo/autoserv-0tMj3m/common_lib/log.py", line 70, in decorated_func 11/01 18:24:57.729 ERROR| traceback:0013| fn(*args, **dargs) 11/01 18:24:57.730 ERROR| traceback:0013| File "/tmp/sysinfo/autoserv-0tMj3m/bin/base_sysinfo.py", line 286, in log_after_each_test 11/01 18:24:57.731 ERROR| traceback:0013| old_packages = set(self._installed_packages) 11/01 18:24:57.731 ERROR| traceback:0013| SystemError: no such file or directory
----------------
Traceback (most recent call last):
File "/usr/lib/vmware-vpx/vsan-health/pyMoVsan/VsanClusterPrototypeImpl.py", line 1492, in WaitForUpdateTask
WaitForTask(task)
File "/usr/lib/vmware-vpx/pyJack/pyVim/task.py", line 123, in WaitForTask
raise task.info.error
vmodl.fault.SystemError: (vmodl.fault.SystemError) {
dynamicType = ,
dynamicProperty = (vmodl.DynamicProperty) [],
msg = 'A general system error occurred: Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.',
faultCause = ,
faultMessage = (vmodl.LocalizableMessage) [],
reason = 'Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.'
}
----------------
|
#Julia
|
Julia
|
const filename = "traceback.txt"
const pmarker, target = "Traceback (most recent call last):", "SystemError"
foreach(
p -> println(p, p[end] == '\n' ? "" : "\n", "-"^16),
[
p[findfirst(pmarker, p).start:end] for
p in split(read(filename, String), r"\r?\n\r?\n") if
contains(p, pmarker) && contains(p, target)
],
)
|
http://rosettacode.org/wiki/Search_in_paragraph%27s_text
|
Search in paragraph's text
|
The goal is to verify the presence of a word or regular expression within several paragraphs of text (structured or not) and to format the output of the relevant paragraphs before putting them on the standard output.
So here, let’s imagine that we are trying to verify the presence of a keyword "SystemError" within what I want to call "the paragraphs" "Traceback (most recent call last):" in the file Traceback.txt
cat Traceback.txt :
2018-06-19 23:19:34,877 ERROR Processes plugin raised an exception.
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/landscape/sysinfo/sysinfo.py", line 99, in run
result = plugin.run()
File "/usr/lib/python3/dist-packages/landscape/sysinfo/processes.py", line 18, in run
for process_info in info.get_all_process_info():
File "/usr/lib/python3/dist-packages/landscape/lib/process.py", line 39, in get_all_process_info
process_info = self.get_process_info(process_id)
File "/usr/lib/python3/dist-packages/landscape/lib/process.py", line 61, in get_process_info
cmd_line = file.readline()
File "/usr/lib/python3.6/encodings/ascii.py", line 26, in decode
return codecs.ascii_decode(input, self.errors)[0]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc5 in position 152: ordinal not in range(128)
2018-06-19 23:19:34,877 ERROR Processes plugin raised an exception.
Traceback (most recent call last):
vmodl.fault.SystemError: (vmodl.fault.SystemError) {
dynamicType = ,
dynamicProperty = (vmodl.DynamicProperty) [],
msg = 'A general system error occurred: Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.',
faultCause = ,
faultMessage = (vmodl.LocalizableMessage) [],
reason = 'Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.'
}
[Tue Jan 21 16:16:19.250245 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] Traceback (most recent call last):
[Tue Jan 21 16:16:19.252221 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] SystemError: unable to access /home/dir
[Tue Jan 21 16:16:19.249067 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] mod_wsgi (pid=6515): Failed to exec Python script file '/home/pi/RaspBerryPiAdhan/www/sysinfo.wsgi'.
[Tue Jan 21 16:16:19.249609 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] mod_wsgi (pid=6515): Exception occurred processing WSGI script '/home/pi/RaspBerryPiAdhan/www/sysinfo.wsgi'.
[Tue Jan 21 17:16:19.250245 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] Traceback (most recent call last):
[Tue Jan 21 17:16:19.250679 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] File "/home/pi/RaspBerryPiAdhan/www/sysinfo.wsgi", line 5, in <module>
[Tue Jan 21 17:16:19.251735 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] from test import app as application
[Tue Jan 21 17:16:19.252221 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] ImportError: cannot import name app
2021-04-23 17:13:14,425 ERROR Network plugin raised an exception.
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/landscape/sysinfo/sysinfo.py", line 99,
in run
result = plugin.run()
File "/usr/lib/python3/dist-packages/landscape/sysinfo/network.py", line 36,
in run
device_info = self._get_device_info()
File "/usr/lib/python3/dist-packages/landscape/lib/network.py", line 163, in
get_active_device_info
speed, duplex = get_network_interface_speed(
File "/usr/lib/python3/dist-packages/landscape/lib/network.py", line 249, in
get_network_interface_speed
res = status_cmd.tostring()
AttributeError: 'array.array' object has no attribute 'tostring'
11/01 18:24:57.726 ERROR| log:0072| post-test sysinfo error: 11/01 18:24:57.727 ERROR| traceback:0013| Traceback (most recent call last): 11/01 18:24:57.728 ERROR| traceback:0013| File "/tmp/sysinfo/autoserv-0tMj3m/common_lib/log.py", line 70, in decorated_func 11/01 18:24:57.729 ERROR| traceback:0013| fn(*args, **dargs) 11/01 18:24:57.730 ERROR| traceback:0013| File "/tmp/sysinfo/autoserv-0tMj3m/bin/base_sysinfo.py", line 286, in log_after_each_test 11/01 18:24:57.731 ERROR| traceback:0013| old_packages = set(self._installed_packages) 11/01 18:24:57.731 ERROR| traceback:0013| TypeError: 'NoneType' object is not iterable
12/01 19:24:57.726 ERROR| log:0072| post-test sysinfo error: 11/01 18:24:57.727 ERROR| traceback:0013| Traceback (most recent call last): 11/01 18:24:57.728 ERROR| traceback:0013| File "/tmp/sysinfo/autoserv-0tMj3m/common_lib/log.py", line 70, in decorated_func 11/01 18:24:57.729 ERROR| traceback:0013| fn(*args, **dargs) 11/01 18:24:57.730 ERROR| traceback:0013| File "/tmp/sysinfo/autoserv-0tMj3m/bin/base_sysinfo.py", line 286, in log_after_each_test 11/01 18:24:57.731 ERROR| traceback:0013| old_packages = set(self._installed_packages) 11/01 18:24:57.731 ERROR| traceback:0013| SystemError: no such file or directory
Traceback (most recent call last):
File "/usr/lib/vmware-vpx/vsan-health/pyMoVsan/VsanClusterPrototypeImpl.py", line 1492, in WaitForUpdateTask
WaitForTask(task)
File "/usr/lib/vmware-vpx/pyJack/pyVim/task.py", line 123, in WaitForTask
raise task.info.error
vmodl.fault.SystemError: (vmodl.fault.SystemError) {
dynamicType = ,
dynamicProperty = (vmodl.DynamicProperty) [],
msg = 'A general system error occurred: Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.',
faultCause = ,
faultMessage = (vmodl.LocalizableMessage) [],
reason = 'Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.'
}
The expected result must be formated with ---------------- for paragraph's separator AND "Traceback (most recent call last):" as the beginning of each relevant's paragraph :
Traceback (most recent call last):
vmodl.fault.SystemError: (vmodl.fault.SystemError) {
dynamicType = ,
dynamicProperty = (vmodl.DynamicProperty) [],
msg = 'A general system error occurred: Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.',
faultCause = ,
faultMessage = (vmodl.LocalizableMessage) [],
reason = 'Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.'
}
----------------
Traceback (most recent call last):
[Tue Jan 21 16:16:19.252221 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] SystemError: unable to access /home/dir
[Tue Jan 21 16:16:19.249067 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] mod_wsgi (pid=6515): Failed to exec Python script file '/home/pi/RaspBerryPiAdhan/www/sysinfo.wsgi'.
[Tue Jan 21 16:16:19.249609 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] mod_wsgi (pid=6515): Exception occurred processing WSGI script '/home/pi/RaspBerryPiAdhan/www/sysinfo.wsgi'.
----------------
Traceback (most recent call last): 11/01 18:24:57.728 ERROR| traceback:0013| File "/tmp/sysinfo/autoserv-0tMj3m/common_lib/log.py", line 70, in decorated_func 11/01 18:24:57.729 ERROR| traceback:0013| fn(*args, **dargs) 11/01 18:24:57.730 ERROR| traceback:0013| File "/tmp/sysinfo/autoserv-0tMj3m/bin/base_sysinfo.py", line 286, in log_after_each_test 11/01 18:24:57.731 ERROR| traceback:0013| old_packages = set(self._installed_packages) 11/01 18:24:57.731 ERROR| traceback:0013| SystemError: no such file or directory
----------------
Traceback (most recent call last):
File "/usr/lib/vmware-vpx/vsan-health/pyMoVsan/VsanClusterPrototypeImpl.py", line 1492, in WaitForUpdateTask
WaitForTask(task)
File "/usr/lib/vmware-vpx/pyJack/pyVim/task.py", line 123, in WaitForTask
raise task.info.error
vmodl.fault.SystemError: (vmodl.fault.SystemError) {
dynamicType = ,
dynamicProperty = (vmodl.DynamicProperty) [],
msg = 'A general system error occurred: Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.',
faultCause = ,
faultMessage = (vmodl.LocalizableMessage) [],
reason = 'Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.'
}
----------------
|
#Phix
|
Phix
|
with javascript_semantics
--constant text = get_text("Traceback.txt") -- (not js!)
constant text = """
2018-06-19 23:19:34,877 ERROR Processes plugin raised an exception.
<snip>
}""",
paras = split(text,"\n\n"),
tmrcl = "Traceback (most recent call last)"
for i=1 to length(paras) do
string para = paras[i]
integer tdx = match(tmrcl,para)
if tdx then
para = para[tdx..$]
if match("SystemError",para) then
printf(1,"%s\n----------------\n",{para})
end if
end if
end for
|
http://rosettacode.org/wiki/Set
|
Set
|
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
A set is a collection of elements, without duplicates and without order.
Task
Show each of these set operations:
Set creation
Test m ∈ S -- "m is an element in set S"
A ∪ B -- union; a set of all elements either in set A or in set B.
A ∩ B -- intersection; a set of all elements in both set A and set B.
A ∖ B -- difference; a set of all elements in set A, except those in set B.
A ⊆ B -- subset; true if every element in set A is also in set B.
A = B -- equality; true if every element of set A is in set B and vice versa.
As an option, show some other set operations.
(If A ⊆ B, but A ≠ B, then A is called a true or proper subset of B, written A ⊂ B or A ⊊ B.)
As another option, show how to modify a mutable set.
One might implement a set using an associative array (with set elements as array keys and some dummy value as the values).
One might also implement a set with a binary search tree, or with a hash table, or with an ordered array of binary bits (operated on with bit-wise binary operators).
The basic test, m ∈ S, is O(n) with a sequential list of elements, O(log n) with a balanced binary search tree, or (O(1) average-case, O(n) worst case) with a hash table.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
|
#Scala
|
Scala
|
object sets {
val set1 = Set(1,2,3,4,5)
val set2 = Set(3,5,7,9)
println(set1 contains 3)
println(set1 | set2)
println(set1 & set2)
println(set1 diff set2)
println(set1 subsetOf set2)
println(set1 == set2)
}
|
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
|
Sieve of Eratosthenes
|
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer.
Task
Implement the Sieve of Eratosthenes algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found.
That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes.
If there's an easy way to add such a wheel based optimization, implement it as an alternative version.
Note
It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task.
Related tasks
Emirp primes
count in factors
prime decomposition
factors of an integer
extensible prime generator
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
|
#HicEst
|
HicEst
|
REAL :: N=100, sieve(N)
sieve = $ > 1 ! = 0 1 1 1 1 ...
DO i = 1, N^0.5
IF( sieve(i) ) THEN
DO j = i^2, N, i
sieve(j) = 0
ENDDO
ENDIF
ENDDO
DO i = 1, N
IF( sieve(i) ) WRITE() i
ENDDO
|
http://rosettacode.org/wiki/SEDOLs
|
SEDOLs
|
Task
For each number list of 6-digit SEDOLs, calculate and append the checksum digit.
That is, given this input:
710889
B0YBKJ
406566
B0YBLH
228276
B0YBKL
557910
B0YBKR
585284
B0YBKT
B00030
Produce this output:
7108899
B0YBKJ7
4065663
B0YBLH2
2282765
B0YBKL9
5579107
B0YBKR5
5852842
B0YBKT7
B000300
Extra credit
Check each input is correctly formed, especially with respect to valid characters allowed in a SEDOL string.
Related tasks
Luhn test
ISIN
|
#XPL0
|
XPL0
|
string 0; \use zero-terminated strings
func CheckDigit(Str); \Return the check digit for a SEDOL
char Str;
int Sum, I, C, V;
[Sum:= 0;
for I:= 0 to 6-1 do
[C:= Str(I);
case of
C>=^0 & C<=^9: V:= C-^0;
C>=^A & C<=^Z: V:= C-^A+10
other V:= -1;
case I of
1, 4: V:= V*3;
3: V:= V*7;
5: V:= V*9
other [];
Sum:= Sum+V;
];
return rem( (10 - rem(Sum/10)) / 10 ) + ^0;
];
int Sedol, N;
[Sedol:= ["710889",
"B0YBKJ",
"406566",
"B0YBLH",
"228276",
"B0YBKL",
"557910",
"B0YBKR",
"585284",
"B0YBKT",
"B00030"];
for N:= 0 to 11-1 do
[Text(0, Sedol(N));
ChOut(0, CheckDigit(Sedol(N)));
CrLf(0);
];
]
|
http://rosettacode.org/wiki/SEDOLs
|
SEDOLs
|
Task
For each number list of 6-digit SEDOLs, calculate and append the checksum digit.
That is, given this input:
710889
B0YBKJ
406566
B0YBLH
228276
B0YBKL
557910
B0YBKR
585284
B0YBKT
B00030
Produce this output:
7108899
B0YBKJ7
4065663
B0YBLH2
2282765
B0YBKL9
5579107
B0YBKR5
5852842
B0YBKT7
B000300
Extra credit
Check each input is correctly formed, especially with respect to valid characters allowed in a SEDOL string.
Related tasks
Luhn test
ISIN
|
#Yabasic
|
Yabasic
|
data "710889", "B0YBKJ", "406566", "B0YBLH", "228276", "B0YBKL", "557910", "B0YBKR", "585284", "B0YBKT", "B00030", "AB", "B00A03", ""
do
read d$
if d$ = "" break
print sedol$(d$)
loop
sub sedol$(d$)
LOCAL a, i, s, weights$(1)
a = len(d$)
if a < 6 or a > 6 return d$ + ": Error in length"
for i = 1 to 6
if not instr("BCDFGHJKLMNPQRSTVWXYZ0123456789", mid$(d$, i, 1)) return d$ + ": Error in symbol " + mid$(d$, i, 1)
next
a = token("1 3 1 7 3 9", weights$())
FOR i = 1 TO 6
a = ASC(MID$(d$, i, 1)) - 48
s = s + (a + 3 * (a > 9)) * val(weights$(i))
NEXT
return d$ + CHR$(48 + mod(10 - mod(s, 10), 10))
end sub
|
http://rosettacode.org/wiki/Search_in_paragraph%27s_text
|
Search in paragraph's text
|
The goal is to verify the presence of a word or regular expression within several paragraphs of text (structured or not) and to format the output of the relevant paragraphs before putting them on the standard output.
So here, let’s imagine that we are trying to verify the presence of a keyword "SystemError" within what I want to call "the paragraphs" "Traceback (most recent call last):" in the file Traceback.txt
cat Traceback.txt :
2018-06-19 23:19:34,877 ERROR Processes plugin raised an exception.
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/landscape/sysinfo/sysinfo.py", line 99, in run
result = plugin.run()
File "/usr/lib/python3/dist-packages/landscape/sysinfo/processes.py", line 18, in run
for process_info in info.get_all_process_info():
File "/usr/lib/python3/dist-packages/landscape/lib/process.py", line 39, in get_all_process_info
process_info = self.get_process_info(process_id)
File "/usr/lib/python3/dist-packages/landscape/lib/process.py", line 61, in get_process_info
cmd_line = file.readline()
File "/usr/lib/python3.6/encodings/ascii.py", line 26, in decode
return codecs.ascii_decode(input, self.errors)[0]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc5 in position 152: ordinal not in range(128)
2018-06-19 23:19:34,877 ERROR Processes plugin raised an exception.
Traceback (most recent call last):
vmodl.fault.SystemError: (vmodl.fault.SystemError) {
dynamicType = ,
dynamicProperty = (vmodl.DynamicProperty) [],
msg = 'A general system error occurred: Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.',
faultCause = ,
faultMessage = (vmodl.LocalizableMessage) [],
reason = 'Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.'
}
[Tue Jan 21 16:16:19.250245 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] Traceback (most recent call last):
[Tue Jan 21 16:16:19.252221 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] SystemError: unable to access /home/dir
[Tue Jan 21 16:16:19.249067 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] mod_wsgi (pid=6515): Failed to exec Python script file '/home/pi/RaspBerryPiAdhan/www/sysinfo.wsgi'.
[Tue Jan 21 16:16:19.249609 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] mod_wsgi (pid=6515): Exception occurred processing WSGI script '/home/pi/RaspBerryPiAdhan/www/sysinfo.wsgi'.
[Tue Jan 21 17:16:19.250245 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] Traceback (most recent call last):
[Tue Jan 21 17:16:19.250679 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] File "/home/pi/RaspBerryPiAdhan/www/sysinfo.wsgi", line 5, in <module>
[Tue Jan 21 17:16:19.251735 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] from test import app as application
[Tue Jan 21 17:16:19.252221 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] ImportError: cannot import name app
2021-04-23 17:13:14,425 ERROR Network plugin raised an exception.
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/landscape/sysinfo/sysinfo.py", line 99,
in run
result = plugin.run()
File "/usr/lib/python3/dist-packages/landscape/sysinfo/network.py", line 36,
in run
device_info = self._get_device_info()
File "/usr/lib/python3/dist-packages/landscape/lib/network.py", line 163, in
get_active_device_info
speed, duplex = get_network_interface_speed(
File "/usr/lib/python3/dist-packages/landscape/lib/network.py", line 249, in
get_network_interface_speed
res = status_cmd.tostring()
AttributeError: 'array.array' object has no attribute 'tostring'
11/01 18:24:57.726 ERROR| log:0072| post-test sysinfo error: 11/01 18:24:57.727 ERROR| traceback:0013| Traceback (most recent call last): 11/01 18:24:57.728 ERROR| traceback:0013| File "/tmp/sysinfo/autoserv-0tMj3m/common_lib/log.py", line 70, in decorated_func 11/01 18:24:57.729 ERROR| traceback:0013| fn(*args, **dargs) 11/01 18:24:57.730 ERROR| traceback:0013| File "/tmp/sysinfo/autoserv-0tMj3m/bin/base_sysinfo.py", line 286, in log_after_each_test 11/01 18:24:57.731 ERROR| traceback:0013| old_packages = set(self._installed_packages) 11/01 18:24:57.731 ERROR| traceback:0013| TypeError: 'NoneType' object is not iterable
12/01 19:24:57.726 ERROR| log:0072| post-test sysinfo error: 11/01 18:24:57.727 ERROR| traceback:0013| Traceback (most recent call last): 11/01 18:24:57.728 ERROR| traceback:0013| File "/tmp/sysinfo/autoserv-0tMj3m/common_lib/log.py", line 70, in decorated_func 11/01 18:24:57.729 ERROR| traceback:0013| fn(*args, **dargs) 11/01 18:24:57.730 ERROR| traceback:0013| File "/tmp/sysinfo/autoserv-0tMj3m/bin/base_sysinfo.py", line 286, in log_after_each_test 11/01 18:24:57.731 ERROR| traceback:0013| old_packages = set(self._installed_packages) 11/01 18:24:57.731 ERROR| traceback:0013| SystemError: no such file or directory
Traceback (most recent call last):
File "/usr/lib/vmware-vpx/vsan-health/pyMoVsan/VsanClusterPrototypeImpl.py", line 1492, in WaitForUpdateTask
WaitForTask(task)
File "/usr/lib/vmware-vpx/pyJack/pyVim/task.py", line 123, in WaitForTask
raise task.info.error
vmodl.fault.SystemError: (vmodl.fault.SystemError) {
dynamicType = ,
dynamicProperty = (vmodl.DynamicProperty) [],
msg = 'A general system error occurred: Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.',
faultCause = ,
faultMessage = (vmodl.LocalizableMessage) [],
reason = 'Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.'
}
The expected result must be formated with ---------------- for paragraph's separator AND "Traceback (most recent call last):" as the beginning of each relevant's paragraph :
Traceback (most recent call last):
vmodl.fault.SystemError: (vmodl.fault.SystemError) {
dynamicType = ,
dynamicProperty = (vmodl.DynamicProperty) [],
msg = 'A general system error occurred: Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.',
faultCause = ,
faultMessage = (vmodl.LocalizableMessage) [],
reason = 'Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.'
}
----------------
Traceback (most recent call last):
[Tue Jan 21 16:16:19.252221 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] SystemError: unable to access /home/dir
[Tue Jan 21 16:16:19.249067 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] mod_wsgi (pid=6515): Failed to exec Python script file '/home/pi/RaspBerryPiAdhan/www/sysinfo.wsgi'.
[Tue Jan 21 16:16:19.249609 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] mod_wsgi (pid=6515): Exception occurred processing WSGI script '/home/pi/RaspBerryPiAdhan/www/sysinfo.wsgi'.
----------------
Traceback (most recent call last): 11/01 18:24:57.728 ERROR| traceback:0013| File "/tmp/sysinfo/autoserv-0tMj3m/common_lib/log.py", line 70, in decorated_func 11/01 18:24:57.729 ERROR| traceback:0013| fn(*args, **dargs) 11/01 18:24:57.730 ERROR| traceback:0013| File "/tmp/sysinfo/autoserv-0tMj3m/bin/base_sysinfo.py", line 286, in log_after_each_test 11/01 18:24:57.731 ERROR| traceback:0013| old_packages = set(self._installed_packages) 11/01 18:24:57.731 ERROR| traceback:0013| SystemError: no such file or directory
----------------
Traceback (most recent call last):
File "/usr/lib/vmware-vpx/vsan-health/pyMoVsan/VsanClusterPrototypeImpl.py", line 1492, in WaitForUpdateTask
WaitForTask(task)
File "/usr/lib/vmware-vpx/pyJack/pyVim/task.py", line 123, in WaitForTask
raise task.info.error
vmodl.fault.SystemError: (vmodl.fault.SystemError) {
dynamicType = ,
dynamicProperty = (vmodl.DynamicProperty) [],
msg = 'A general system error occurred: Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.',
faultCause = ,
faultMessage = (vmodl.LocalizableMessage) [],
reason = 'Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.'
}
----------------
|
#Python
|
Python
|
with open('Traceback.txt', 'r' ) as f:
rawText = f.read()
paragraphs = rawText.split( "\n\n" )
for p in paragraphs:
if "SystemError" in p:
index = p.find( "Traceback (most recent call last):" )
if -1 != index:
print( p[index:] )
print( "----------------" )
|
http://rosettacode.org/wiki/Search_in_paragraph%27s_text
|
Search in paragraph's text
|
The goal is to verify the presence of a word or regular expression within several paragraphs of text (structured or not) and to format the output of the relevant paragraphs before putting them on the standard output.
So here, let’s imagine that we are trying to verify the presence of a keyword "SystemError" within what I want to call "the paragraphs" "Traceback (most recent call last):" in the file Traceback.txt
cat Traceback.txt :
2018-06-19 23:19:34,877 ERROR Processes plugin raised an exception.
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/landscape/sysinfo/sysinfo.py", line 99, in run
result = plugin.run()
File "/usr/lib/python3/dist-packages/landscape/sysinfo/processes.py", line 18, in run
for process_info in info.get_all_process_info():
File "/usr/lib/python3/dist-packages/landscape/lib/process.py", line 39, in get_all_process_info
process_info = self.get_process_info(process_id)
File "/usr/lib/python3/dist-packages/landscape/lib/process.py", line 61, in get_process_info
cmd_line = file.readline()
File "/usr/lib/python3.6/encodings/ascii.py", line 26, in decode
return codecs.ascii_decode(input, self.errors)[0]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc5 in position 152: ordinal not in range(128)
2018-06-19 23:19:34,877 ERROR Processes plugin raised an exception.
Traceback (most recent call last):
vmodl.fault.SystemError: (vmodl.fault.SystemError) {
dynamicType = ,
dynamicProperty = (vmodl.DynamicProperty) [],
msg = 'A general system error occurred: Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.',
faultCause = ,
faultMessage = (vmodl.LocalizableMessage) [],
reason = 'Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.'
}
[Tue Jan 21 16:16:19.250245 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] Traceback (most recent call last):
[Tue Jan 21 16:16:19.252221 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] SystemError: unable to access /home/dir
[Tue Jan 21 16:16:19.249067 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] mod_wsgi (pid=6515): Failed to exec Python script file '/home/pi/RaspBerryPiAdhan/www/sysinfo.wsgi'.
[Tue Jan 21 16:16:19.249609 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] mod_wsgi (pid=6515): Exception occurred processing WSGI script '/home/pi/RaspBerryPiAdhan/www/sysinfo.wsgi'.
[Tue Jan 21 17:16:19.250245 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] Traceback (most recent call last):
[Tue Jan 21 17:16:19.250679 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] File "/home/pi/RaspBerryPiAdhan/www/sysinfo.wsgi", line 5, in <module>
[Tue Jan 21 17:16:19.251735 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] from test import app as application
[Tue Jan 21 17:16:19.252221 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] ImportError: cannot import name app
2021-04-23 17:13:14,425 ERROR Network plugin raised an exception.
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/landscape/sysinfo/sysinfo.py", line 99,
in run
result = plugin.run()
File "/usr/lib/python3/dist-packages/landscape/sysinfo/network.py", line 36,
in run
device_info = self._get_device_info()
File "/usr/lib/python3/dist-packages/landscape/lib/network.py", line 163, in
get_active_device_info
speed, duplex = get_network_interface_speed(
File "/usr/lib/python3/dist-packages/landscape/lib/network.py", line 249, in
get_network_interface_speed
res = status_cmd.tostring()
AttributeError: 'array.array' object has no attribute 'tostring'
11/01 18:24:57.726 ERROR| log:0072| post-test sysinfo error: 11/01 18:24:57.727 ERROR| traceback:0013| Traceback (most recent call last): 11/01 18:24:57.728 ERROR| traceback:0013| File "/tmp/sysinfo/autoserv-0tMj3m/common_lib/log.py", line 70, in decorated_func 11/01 18:24:57.729 ERROR| traceback:0013| fn(*args, **dargs) 11/01 18:24:57.730 ERROR| traceback:0013| File "/tmp/sysinfo/autoserv-0tMj3m/bin/base_sysinfo.py", line 286, in log_after_each_test 11/01 18:24:57.731 ERROR| traceback:0013| old_packages = set(self._installed_packages) 11/01 18:24:57.731 ERROR| traceback:0013| TypeError: 'NoneType' object is not iterable
12/01 19:24:57.726 ERROR| log:0072| post-test sysinfo error: 11/01 18:24:57.727 ERROR| traceback:0013| Traceback (most recent call last): 11/01 18:24:57.728 ERROR| traceback:0013| File "/tmp/sysinfo/autoserv-0tMj3m/common_lib/log.py", line 70, in decorated_func 11/01 18:24:57.729 ERROR| traceback:0013| fn(*args, **dargs) 11/01 18:24:57.730 ERROR| traceback:0013| File "/tmp/sysinfo/autoserv-0tMj3m/bin/base_sysinfo.py", line 286, in log_after_each_test 11/01 18:24:57.731 ERROR| traceback:0013| old_packages = set(self._installed_packages) 11/01 18:24:57.731 ERROR| traceback:0013| SystemError: no such file or directory
Traceback (most recent call last):
File "/usr/lib/vmware-vpx/vsan-health/pyMoVsan/VsanClusterPrototypeImpl.py", line 1492, in WaitForUpdateTask
WaitForTask(task)
File "/usr/lib/vmware-vpx/pyJack/pyVim/task.py", line 123, in WaitForTask
raise task.info.error
vmodl.fault.SystemError: (vmodl.fault.SystemError) {
dynamicType = ,
dynamicProperty = (vmodl.DynamicProperty) [],
msg = 'A general system error occurred: Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.',
faultCause = ,
faultMessage = (vmodl.LocalizableMessage) [],
reason = 'Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.'
}
The expected result must be formated with ---------------- for paragraph's separator AND "Traceback (most recent call last):" as the beginning of each relevant's paragraph :
Traceback (most recent call last):
vmodl.fault.SystemError: (vmodl.fault.SystemError) {
dynamicType = ,
dynamicProperty = (vmodl.DynamicProperty) [],
msg = 'A general system error occurred: Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.',
faultCause = ,
faultMessage = (vmodl.LocalizableMessage) [],
reason = 'Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.'
}
----------------
Traceback (most recent call last):
[Tue Jan 21 16:16:19.252221 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] SystemError: unable to access /home/dir
[Tue Jan 21 16:16:19.249067 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] mod_wsgi (pid=6515): Failed to exec Python script file '/home/pi/RaspBerryPiAdhan/www/sysinfo.wsgi'.
[Tue Jan 21 16:16:19.249609 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] mod_wsgi (pid=6515): Exception occurred processing WSGI script '/home/pi/RaspBerryPiAdhan/www/sysinfo.wsgi'.
----------------
Traceback (most recent call last): 11/01 18:24:57.728 ERROR| traceback:0013| File "/tmp/sysinfo/autoserv-0tMj3m/common_lib/log.py", line 70, in decorated_func 11/01 18:24:57.729 ERROR| traceback:0013| fn(*args, **dargs) 11/01 18:24:57.730 ERROR| traceback:0013| File "/tmp/sysinfo/autoserv-0tMj3m/bin/base_sysinfo.py", line 286, in log_after_each_test 11/01 18:24:57.731 ERROR| traceback:0013| old_packages = set(self._installed_packages) 11/01 18:24:57.731 ERROR| traceback:0013| SystemError: no such file or directory
----------------
Traceback (most recent call last):
File "/usr/lib/vmware-vpx/vsan-health/pyMoVsan/VsanClusterPrototypeImpl.py", line 1492, in WaitForUpdateTask
WaitForTask(task)
File "/usr/lib/vmware-vpx/pyJack/pyVim/task.py", line 123, in WaitForTask
raise task.info.error
vmodl.fault.SystemError: (vmodl.fault.SystemError) {
dynamicType = ,
dynamicProperty = (vmodl.DynamicProperty) [],
msg = 'A general system error occurred: Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.',
faultCause = ,
faultMessage = (vmodl.LocalizableMessage) [],
reason = 'Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.'
}
----------------
|
#Raku
|
Raku
|
unit sub MAIN ( :$for, :$at = 0 );
put slurp.split( /\n\n+/ ).grep( { .contains: $for } )
.map( { .substr: .index: $at } )
.join: "\n----------------\n"
|
http://rosettacode.org/wiki/Search_in_paragraph%27s_text
|
Search in paragraph's text
|
The goal is to verify the presence of a word or regular expression within several paragraphs of text (structured or not) and to format the output of the relevant paragraphs before putting them on the standard output.
So here, let’s imagine that we are trying to verify the presence of a keyword "SystemError" within what I want to call "the paragraphs" "Traceback (most recent call last):" in the file Traceback.txt
cat Traceback.txt :
2018-06-19 23:19:34,877 ERROR Processes plugin raised an exception.
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/landscape/sysinfo/sysinfo.py", line 99, in run
result = plugin.run()
File "/usr/lib/python3/dist-packages/landscape/sysinfo/processes.py", line 18, in run
for process_info in info.get_all_process_info():
File "/usr/lib/python3/dist-packages/landscape/lib/process.py", line 39, in get_all_process_info
process_info = self.get_process_info(process_id)
File "/usr/lib/python3/dist-packages/landscape/lib/process.py", line 61, in get_process_info
cmd_line = file.readline()
File "/usr/lib/python3.6/encodings/ascii.py", line 26, in decode
return codecs.ascii_decode(input, self.errors)[0]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc5 in position 152: ordinal not in range(128)
2018-06-19 23:19:34,877 ERROR Processes plugin raised an exception.
Traceback (most recent call last):
vmodl.fault.SystemError: (vmodl.fault.SystemError) {
dynamicType = ,
dynamicProperty = (vmodl.DynamicProperty) [],
msg = 'A general system error occurred: Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.',
faultCause = ,
faultMessage = (vmodl.LocalizableMessage) [],
reason = 'Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.'
}
[Tue Jan 21 16:16:19.250245 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] Traceback (most recent call last):
[Tue Jan 21 16:16:19.252221 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] SystemError: unable to access /home/dir
[Tue Jan 21 16:16:19.249067 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] mod_wsgi (pid=6515): Failed to exec Python script file '/home/pi/RaspBerryPiAdhan/www/sysinfo.wsgi'.
[Tue Jan 21 16:16:19.249609 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] mod_wsgi (pid=6515): Exception occurred processing WSGI script '/home/pi/RaspBerryPiAdhan/www/sysinfo.wsgi'.
[Tue Jan 21 17:16:19.250245 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] Traceback (most recent call last):
[Tue Jan 21 17:16:19.250679 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] File "/home/pi/RaspBerryPiAdhan/www/sysinfo.wsgi", line 5, in <module>
[Tue Jan 21 17:16:19.251735 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] from test import app as application
[Tue Jan 21 17:16:19.252221 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] ImportError: cannot import name app
2021-04-23 17:13:14,425 ERROR Network plugin raised an exception.
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/landscape/sysinfo/sysinfo.py", line 99,
in run
result = plugin.run()
File "/usr/lib/python3/dist-packages/landscape/sysinfo/network.py", line 36,
in run
device_info = self._get_device_info()
File "/usr/lib/python3/dist-packages/landscape/lib/network.py", line 163, in
get_active_device_info
speed, duplex = get_network_interface_speed(
File "/usr/lib/python3/dist-packages/landscape/lib/network.py", line 249, in
get_network_interface_speed
res = status_cmd.tostring()
AttributeError: 'array.array' object has no attribute 'tostring'
11/01 18:24:57.726 ERROR| log:0072| post-test sysinfo error: 11/01 18:24:57.727 ERROR| traceback:0013| Traceback (most recent call last): 11/01 18:24:57.728 ERROR| traceback:0013| File "/tmp/sysinfo/autoserv-0tMj3m/common_lib/log.py", line 70, in decorated_func 11/01 18:24:57.729 ERROR| traceback:0013| fn(*args, **dargs) 11/01 18:24:57.730 ERROR| traceback:0013| File "/tmp/sysinfo/autoserv-0tMj3m/bin/base_sysinfo.py", line 286, in log_after_each_test 11/01 18:24:57.731 ERROR| traceback:0013| old_packages = set(self._installed_packages) 11/01 18:24:57.731 ERROR| traceback:0013| TypeError: 'NoneType' object is not iterable
12/01 19:24:57.726 ERROR| log:0072| post-test sysinfo error: 11/01 18:24:57.727 ERROR| traceback:0013| Traceback (most recent call last): 11/01 18:24:57.728 ERROR| traceback:0013| File "/tmp/sysinfo/autoserv-0tMj3m/common_lib/log.py", line 70, in decorated_func 11/01 18:24:57.729 ERROR| traceback:0013| fn(*args, **dargs) 11/01 18:24:57.730 ERROR| traceback:0013| File "/tmp/sysinfo/autoserv-0tMj3m/bin/base_sysinfo.py", line 286, in log_after_each_test 11/01 18:24:57.731 ERROR| traceback:0013| old_packages = set(self._installed_packages) 11/01 18:24:57.731 ERROR| traceback:0013| SystemError: no such file or directory
Traceback (most recent call last):
File "/usr/lib/vmware-vpx/vsan-health/pyMoVsan/VsanClusterPrototypeImpl.py", line 1492, in WaitForUpdateTask
WaitForTask(task)
File "/usr/lib/vmware-vpx/pyJack/pyVim/task.py", line 123, in WaitForTask
raise task.info.error
vmodl.fault.SystemError: (vmodl.fault.SystemError) {
dynamicType = ,
dynamicProperty = (vmodl.DynamicProperty) [],
msg = 'A general system error occurred: Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.',
faultCause = ,
faultMessage = (vmodl.LocalizableMessage) [],
reason = 'Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.'
}
The expected result must be formated with ---------------- for paragraph's separator AND "Traceback (most recent call last):" as the beginning of each relevant's paragraph :
Traceback (most recent call last):
vmodl.fault.SystemError: (vmodl.fault.SystemError) {
dynamicType = ,
dynamicProperty = (vmodl.DynamicProperty) [],
msg = 'A general system error occurred: Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.',
faultCause = ,
faultMessage = (vmodl.LocalizableMessage) [],
reason = 'Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.'
}
----------------
Traceback (most recent call last):
[Tue Jan 21 16:16:19.252221 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] SystemError: unable to access /home/dir
[Tue Jan 21 16:16:19.249067 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] mod_wsgi (pid=6515): Failed to exec Python script file '/home/pi/RaspBerryPiAdhan/www/sysinfo.wsgi'.
[Tue Jan 21 16:16:19.249609 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] mod_wsgi (pid=6515): Exception occurred processing WSGI script '/home/pi/RaspBerryPiAdhan/www/sysinfo.wsgi'.
----------------
Traceback (most recent call last): 11/01 18:24:57.728 ERROR| traceback:0013| File "/tmp/sysinfo/autoserv-0tMj3m/common_lib/log.py", line 70, in decorated_func 11/01 18:24:57.729 ERROR| traceback:0013| fn(*args, **dargs) 11/01 18:24:57.730 ERROR| traceback:0013| File "/tmp/sysinfo/autoserv-0tMj3m/bin/base_sysinfo.py", line 286, in log_after_each_test 11/01 18:24:57.731 ERROR| traceback:0013| old_packages = set(self._installed_packages) 11/01 18:24:57.731 ERROR| traceback:0013| SystemError: no such file or directory
----------------
Traceback (most recent call last):
File "/usr/lib/vmware-vpx/vsan-health/pyMoVsan/VsanClusterPrototypeImpl.py", line 1492, in WaitForUpdateTask
WaitForTask(task)
File "/usr/lib/vmware-vpx/pyJack/pyVim/task.py", line 123, in WaitForTask
raise task.info.error
vmodl.fault.SystemError: (vmodl.fault.SystemError) {
dynamicType = ,
dynamicProperty = (vmodl.DynamicProperty) [],
msg = 'A general system error occurred: Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.',
faultCause = ,
faultMessage = (vmodl.LocalizableMessage) [],
reason = 'Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.'
}
----------------
|
#Wren
|
Wren
|
import "io" for File
import "./pattern" for Pattern
var fileName = "Traceback.txt"
var p1 = Pattern.new("Traceback (most recent call last):")
var p2 = Pattern.new("SystemError")
var sep = "----------------"
File.read(fileName)
.split("\n\n")
.where { |para| p1.isMatch(para) && p2.isMatch(para) }
.each { |para|
var ix = p1.find(para).index
System.print(para[ix..-1])
System.print(sep)
}
|
http://rosettacode.org/wiki/Set
|
Set
|
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
A set is a collection of elements, without duplicates and without order.
Task
Show each of these set operations:
Set creation
Test m ∈ S -- "m is an element in set S"
A ∪ B -- union; a set of all elements either in set A or in set B.
A ∩ B -- intersection; a set of all elements in both set A and set B.
A ∖ B -- difference; a set of all elements in set A, except those in set B.
A ⊆ B -- subset; true if every element in set A is also in set B.
A = B -- equality; true if every element of set A is in set B and vice versa.
As an option, show some other set operations.
(If A ⊆ B, but A ≠ B, then A is called a true or proper subset of B, written A ⊂ B or A ⊊ B.)
As another option, show how to modify a mutable set.
One might implement a set using an associative array (with set elements as array keys and some dummy value as the values).
One might also implement a set with a binary search tree, or with a hash table, or with an ordered array of binary bits (operated on with bit-wise binary operators).
The basic test, m ∈ S, is O(n) with a sequential list of elements, O(log n) with a balanced binary search tree, or (O(1) average-case, O(n) worst case) with a hash table.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
|
#Scheme
|
Scheme
|
(define (element? a lst)
(and (not (null? lst))
(or (eq? a (car lst))
(element? a (cdr lst)))))
; util, not strictly needed
(define (uniq lst)
(if (null? lst) lst
(let ((a (car lst)) (b (cdr lst)))
(if (element? a b)
(uniq b)
(cons a (uniq b))))))
(define (intersection a b)
(cond ((null? a) '())
((null? b) '())
(else
(append (intersection (cdr a) b)
(if (element? (car a) b)
(list (car a))
'())))))
(define (union a b)
(if (null? a) b
(union (cdr a)
(if (element? (car a) b)
b
(cons (car a) b)))))
(define (diff a b) ; a - b
(if (null? a) '()
(if (element? (car a) b)
(diff (cdr a) b)
(cons (car a) (diff (cdr a) b)))))
(define (subset? a b) ; A ⊆ B
(if (null? a) #t
(and (element? (car a) b)
(subset? (cdr a) b))))
(define (set-eq? a b)
(and (subset? a b)
(subset? b a)))
|
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
|
Sieve of Eratosthenes
|
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer.
Task
Implement the Sieve of Eratosthenes algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found.
That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes.
If there's an easy way to add such a wheel based optimization, implement it as an alternative version.
Note
It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task.
Related tasks
Emirp primes
count in factors
prime decomposition
factors of an integer
extensible prime generator
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
|
#Hoon
|
Hoon
|
:: Find primes by the sieve of Eratosthenes
!:
|= end=@ud
=/ index 2
=/ primes `(list @ud)`(gulf 1 end)
|- ^- (list @ud)
?: (gte index (lent primes)) primes
$(index +(index), primes +:(skid primes |=([a=@ud] &((gth a index) =(0 (mod a index))))))
|
http://rosettacode.org/wiki/SEDOLs
|
SEDOLs
|
Task
For each number list of 6-digit SEDOLs, calculate and append the checksum digit.
That is, given this input:
710889
B0YBKJ
406566
B0YBLH
228276
B0YBKL
557910
B0YBKR
585284
B0YBKT
B00030
Produce this output:
7108899
B0YBKJ7
4065663
B0YBLH2
2282765
B0YBKL9
5579107
B0YBKR5
5852842
B0YBKT7
B000300
Extra credit
Check each input is correctly formed, especially with respect to valid characters allowed in a SEDOL string.
Related tasks
Luhn test
ISIN
|
#zkl
|
zkl
|
fcn checksum(text){
( text.len()!=6 or (text..matches("*[AEIOUaeioua-z]*")) ) and
throw(Exception.ValueError("Invalid SEDOL text: "+text));
text + (10 - text.pump(List,'wrap(c){
if("0"<=c<="9") c.toAsc()-0x30;
else c.toAsc()-55;
}).zipWith('*,T(1,3,1,7,3,9)).sum() % 10) % 10;
}
|
http://rosettacode.org/wiki/Set
|
Set
|
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
A set is a collection of elements, without duplicates and without order.
Task
Show each of these set operations:
Set creation
Test m ∈ S -- "m is an element in set S"
A ∪ B -- union; a set of all elements either in set A or in set B.
A ∩ B -- intersection; a set of all elements in both set A and set B.
A ∖ B -- difference; a set of all elements in set A, except those in set B.
A ⊆ B -- subset; true if every element in set A is also in set B.
A = B -- equality; true if every element of set A is in set B and vice versa.
As an option, show some other set operations.
(If A ⊆ B, but A ≠ B, then A is called a true or proper subset of B, written A ⊂ B or A ⊊ B.)
As another option, show how to modify a mutable set.
One might implement a set using an associative array (with set elements as array keys and some dummy value as the values).
One might also implement a set with a binary search tree, or with a hash table, or with an ordered array of binary bits (operated on with bit-wise binary operators).
The basic test, m ∈ S, is O(n) with a sequential list of elements, O(log n) with a balanced binary search tree, or (O(1) average-case, O(n) worst case) with a hash table.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
|
#Seed7
|
Seed7
|
$ include "seed7_05.s7i";
const type: charSet is set of char;
enable_output(charSet);
const proc: main is func
local
const charSet: A is {'A', 'B', 'C', 'D', 'E', 'F'};
var charSet: B is charSet.value;
var char: m is 'A';
begin
B := {'E', 'F', 'G', 'H', 'I', 'K'};
incl(B, 'J'); # Add 'J' to set B
excl(B, 'K'); # Remove 'K' from set B
writeln("A: " <& A);
writeln("B: " <& B);
writeln("m: " <& m);
writeln("m in A -- m is an element in A: " <& m in A);
writeln("A | B -- union: " <& A | B);
writeln("A & B -- intersection: " <& A & B);
writeln("A - B -- difference: " <& A - B);
writeln("A >< B -- symmetric difference: " <& A >< B);
writeln("A <= A -- subset: " <& A <= A);
writeln("A < A -- proper subset: " <& A < A);
writeln("A = B -- equality: " <& A = B);
end func;
|
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
|
Sieve of Eratosthenes
|
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer.
Task
Implement the Sieve of Eratosthenes algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found.
That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes.
If there's an easy way to add such a wheel based optimization, implement it as an alternative version.
Note
It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task.
Related tasks
Emirp primes
count in factors
prime decomposition
factors of an integer
extensible prime generator
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
|
#Icon_and_Unicon
|
Icon and Unicon
|
procedure main()
sieve(100)
end
procedure sieve(n)
local p,i,j
p:=list(n, 1)
every i:=2 to sqrt(n) & j:= i+i to n by i & p[i] == 1
do p[j] := 0
every write(i:=2 to n & p[i] == 1 & i)
end
|
http://rosettacode.org/wiki/Set
|
Set
|
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
A set is a collection of elements, without duplicates and without order.
Task
Show each of these set operations:
Set creation
Test m ∈ S -- "m is an element in set S"
A ∪ B -- union; a set of all elements either in set A or in set B.
A ∩ B -- intersection; a set of all elements in both set A and set B.
A ∖ B -- difference; a set of all elements in set A, except those in set B.
A ⊆ B -- subset; true if every element in set A is also in set B.
A = B -- equality; true if every element of set A is in set B and vice versa.
As an option, show some other set operations.
(If A ⊆ B, but A ≠ B, then A is called a true or proper subset of B, written A ⊂ B or A ⊊ B.)
As another option, show how to modify a mutable set.
One might implement a set using an associative array (with set elements as array keys and some dummy value as the values).
One might also implement a set with a binary search tree, or with a hash table, or with an ordered array of binary bits (operated on with bit-wise binary operators).
The basic test, m ∈ S, is O(n) with a sequential list of elements, O(log n) with a balanced binary search tree, or (O(1) average-case, O(n) worst case) with a hash table.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
|
#SETL
|
SETL
|
A := {1, 2, 3, 4};
B := {3, 4, 5, 6};
C := {4, 5};
-- Union, Intersection, Difference, Subset, Equality
print(A + B); -- {1, 2, 3, 4, 5, 6}
print(A * B); -- {3, 4}
print(A - B); -- {1, 2}
print(C subset B); -- #T
print(C = B); -- #F
|
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
|
Sieve of Eratosthenes
|
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer.
Task
Implement the Sieve of Eratosthenes algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found.
That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes.
If there's an easy way to add such a wheel based optimization, implement it as an alternative version.
Note
It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task.
Related tasks
Emirp primes
count in factors
prime decomposition
factors of an integer
extensible prime generator
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
|
#J
|
J
|
10|13
3
|
http://rosettacode.org/wiki/Set
|
Set
|
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
A set is a collection of elements, without duplicates and without order.
Task
Show each of these set operations:
Set creation
Test m ∈ S -- "m is an element in set S"
A ∪ B -- union; a set of all elements either in set A or in set B.
A ∩ B -- intersection; a set of all elements in both set A and set B.
A ∖ B -- difference; a set of all elements in set A, except those in set B.
A ⊆ B -- subset; true if every element in set A is also in set B.
A = B -- equality; true if every element of set A is in set B and vice versa.
As an option, show some other set operations.
(If A ⊆ B, but A ≠ B, then A is called a true or proper subset of B, written A ⊂ B or A ⊊ B.)
As another option, show how to modify a mutable set.
One might implement a set using an associative array (with set elements as array keys and some dummy value as the values).
One might also implement a set with a binary search tree, or with a hash table, or with an ordered array of binary bits (operated on with bit-wise binary operators).
The basic test, m ∈ S, is O(n) with a sequential list of elements, O(log n) with a balanced binary search tree, or (O(1) average-case, O(n) worst case) with a hash table.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
|
#Sidef
|
Sidef
|
class MySet(*set) {
method init {
var elems = set
set = Hash()
elems.each { |e| self += e }
}
method +(elem) {
set{elem} = elem
self
}
method del(elem) {
set.delete(elem)
}
method has(elem) {
set.has_key(elem)
}
method ∪(MySet that) {
MySet(set.values..., that.values...)
}
method ∩(MySet that) {
MySet(set.keys.grep{ |k| k ∈ that } \
.map { |k| set{k} }...)
}
method ∖(MySet that) {
MySet(set.keys.grep{|k| !(k ∈ that) } \
.map {|k| set{k} }...)
}
method ^(MySet that) {
var d = ((self ∖ that) ∪ (that ∖ self))
MySet(d.values...)
}
method count { set.len }
method ≡(MySet that) {
(self ∖ that -> count.is_zero) && (that ∖ self -> count.is_zero)
}
method values { set.values }
method ⊆(MySet that) {
that.set.keys.each { |k|
k ∈ self || return false
}
return true
}
method to_s {
"Set{" + set.values.map{|e| "#{e}"}.sort.join(', ') + "}"
}
}
class Object {
method ∈(MySet set) {
set.has(self)
}
}
|
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
|
Sieve of Eratosthenes
|
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer.
Task
Implement the Sieve of Eratosthenes algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found.
That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes.
If there's an easy way to add such a wheel based optimization, implement it as an alternative version.
Note
It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task.
Related tasks
Emirp primes
count in factors
prime decomposition
factors of an integer
extensible prime generator
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
|
#Janet
|
Janet
|
(defn primes-before
"Gives all the primes < limit"
[limit]
(assert (int? limit))
# Janet has a buffer type (mutable string) which has easy methods for use as bitset
(def buf-size (math/ceil (/ limit 8)))
(def is-prime (buffer/new-filled buf-size (bnot 0)))
(print "Size" buf-size "is-prime: " is-prime)
(buffer/bit-clear is-prime 0)
(buffer/bit-clear is-prime 1)
(for n 0 (math/ceil (math/sqrt limit))
(if (buffer/bit is-prime n) (loop [i :range-to [(* n n) limit n]]
(buffer/bit-clear is-prime i))))
(def res @[]) # Result: Mutable array
(for i 0 limit
(if (buffer/bit is-prime i)
(array/push res i)))
(def res (array/new limit))
(for i 0 limit
(if (buffer/bit is-prime i)
(array/push res i)))
res)
|
http://rosettacode.org/wiki/Set
|
Set
|
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
A set is a collection of elements, without duplicates and without order.
Task
Show each of these set operations:
Set creation
Test m ∈ S -- "m is an element in set S"
A ∪ B -- union; a set of all elements either in set A or in set B.
A ∩ B -- intersection; a set of all elements in both set A and set B.
A ∖ B -- difference; a set of all elements in set A, except those in set B.
A ⊆ B -- subset; true if every element in set A is also in set B.
A = B -- equality; true if every element of set A is in set B and vice versa.
As an option, show some other set operations.
(If A ⊆ B, but A ≠ B, then A is called a true or proper subset of B, written A ⊂ B or A ⊊ B.)
As another option, show how to modify a mutable set.
One might implement a set using an associative array (with set elements as array keys and some dummy value as the values).
One might also implement a set with a binary search tree, or with a hash table, or with an ordered array of binary bits (operated on with bit-wise binary operators).
The basic test, m ∈ S, is O(n) with a sequential list of elements, O(log n) with a balanced binary search tree, or (O(1) average-case, O(n) worst case) with a hash table.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
|
#Simula
|
Simula
|
SIMSET
BEGIN
! WE DON'T SUBCLASS HEAD BUT USE COMPOSITION FOR CLASS SET ;
CLASS SET;
BEGIN
PROCEDURE ADD(E); REF(ELEMENT) E;
BEGIN
IF NOT ISIN(E, THIS SET) THEN E.CLONE.INTO(H);
END**OF**ADD;
BOOLEAN PROCEDURE EMPTY; EMPTY := H.EMPTY;
REF(LINK) PROCEDURE FIRST; FIRST :- H.FIRST;
REF(HEAD) H;
H :- NEW HEAD;
END**OF**SET;
! WE SUBCLASS LINK FOR THE ELEMENTS CONTAINED IN THE SET ;
LINK CLASS ELEMENT;
VIRTUAL:
PROCEDURE ISEQUAL IS
BOOLEAN PROCEDURE ISEQUAL(OTHER); REF(ELEMENT) OTHER;;
PROCEDURE REPR IS
TEXT PROCEDURE REPR;;
PROCEDURE REPR IS
REF(ELEMENT) PROCEDURE CLONE;;
BEGIN
END**OF**ELEMENT;
REF(SET) PROCEDURE UNION(S1, S2); REF(SET) S1, S2;
BEGIN REF(SET) SU, S;
SU :- NEW SET;
FOR S :- S1, S2 DO
BEGIN
IF NOT S.EMPTY THEN
BEGIN REF(ELEMENT) E;
E :- S.FIRST;
WHILE E =/= NONE DO
BEGIN SU.ADD(E); E :- E.SUC;
END;
END;
END;
UNION :- SU;
END**OF**UNION;
REF(SET) PROCEDURE INTERSECTION(S1, S2); REF(SET) S1, S2;
BEGIN REF(SET) SI;
SI :- NEW SET;
IF NOT S1.EMPTY THEN
BEGIN REF(ELEMENT) E;
E :- S1.FIRST;
WHILE E =/= NONE DO
BEGIN IF ISIN(E, S2) THEN SI.ADD(E); E :- E.SUC;
END;
END;
INTERSECTION :- SI;
END**OF**INTERSECTION;
REF(SET) PROCEDURE MINUS(S1, S2); REF(SET) S1, S2;
BEGIN REF(SET) SM;
SM :- NEW SET;
IF NOT S1.EMPTY THEN
BEGIN REF(ELEMENT) E;
E :- S1.FIRST;
WHILE E =/= NONE DO
BEGIN IF NOT ISIN(E, S2) THEN SM.ADD(E); E :- E.SUC;
END;
END;
MINUS :- SM;
END**OF**MINUS;
BOOLEAN PROCEDURE ISSUBSET(S1, S2); REF(SET) S1, S2;
BEGIN BOOLEAN B;
B := TRUE;
IF NOT S1.EMPTY THEN
BEGIN REF(ELEMENT) E;
E :- S1.FIRST;
WHILE B AND E =/= NONE DO
BEGIN
B := ISIN(E, S2);
E :- E.SUC;
END;
END;
ISSUBSET := B;
END**OF**ISSUBSET;
BOOLEAN PROCEDURE ISEQUAL(S1, S2); REF(SET) S1, S2;
BEGIN
ISEQUAL := ISSUBSET(S1, S2) AND THEN ISSUBSET(S2, S1)
END**OF**ISEQUAL;
BOOLEAN PROCEDURE ISIN(ELE,S); REF(ELEMENT) ELE; REF(SET) S;
BEGIN
REF(ELEMENT) E; BOOLEAN FOUND;
IF NOT S.EMPTY THEN
BEGIN
E :- S.FIRST;
FOUND := E.ISEQUAL(ELE);
WHILE NOT FOUND AND E =/= NONE DO
BEGIN FOUND := E.ISEQUAL(ELE); E :- E.SUC;
END;
END;
ISIN := FOUND
END**OF**ISIN;
PROCEDURE OUTSET(S); REF(SET) S;
BEGIN
REF(ELEMENT) E;
OUTCHAR('{');
IF NOT S.EMPTY THEN
BEGIN
E :- S.FIRST; OUTTEXT(E.REPR);
FOR E :- E.SUC WHILE E =/= NONE DO
BEGIN OUTTEXT(", "); OUTTEXT(E.REPR);
END;
END;
OUTCHAR('}');
END**OF**OUTSET;
COMMENT ============== EXAMPLE USING SETS OF NUMBERS ============== ;
ELEMENT CLASS NUMBER(N); INTEGER N;
BEGIN
BOOLEAN PROCEDURE ISEQUAL(OTHER); REF(ELEMENT) OTHER;
ISEQUAL := N = OTHER QUA NUMBER.N;
TEXT PROCEDURE REPR;
BEGIN TEXT T; INTEGER I;
T :- BLANKS(20); T.PUTINT(N);
T.SETPOS(1);
WHILE T.GETCHAR = ' ' DO;
REPR :- T.SUB(T.POS - 1, T.LENGTH - T.POS + 2);
END;
REF(ELEMENT) PROCEDURE CLONE;
CLONE :- NEW NUMBER(N);
END**OF**NUMBER;
PROCEDURE REPORT(S1, MSG1, S2, MSG2, S3); REF(SET) S1, S2, S3; TEXT MSG1, MSG2;
BEGIN
OUTSET(S1); OUTCHAR(' ');
OUTTEXT(MSG1); OUTCHAR(' ');
OUTSET(S2); OUTCHAR(' ');
OUTTEXT(MSG2); OUTCHAR(' ');
OUTSET(S3);
OUTIMAGE;
END**OF**REPORT;
PROCEDURE REPORTBOOL(S1, MSG1, S2, MSG2, B); REF(SET) S1, S2; TEXT MSG1, MSG2; BOOLEAN B;
BEGIN
OUTSET(S1); OUTCHAR(' ');
OUTTEXT(MSG1); OUTCHAR(' ');
OUTSET(S2); OUTCHAR(' ');
OUTTEXT(MSG2); OUTCHAR(' ');
OUTTEXT(IF B THEN "T" ELSE "F");
OUTIMAGE;
END**OF**REPORTBOOL;
PROCEDURE REPORTNUMBOOL(N1, MSG1, S1, MSG2, B); REF(ELEMENT) N1; REF(SET) S1; TEXT MSG1, MSG2; BOOLEAN B;
BEGIN
OUTTEXT(N1.REPR); OUTCHAR(' ');
OUTTEXT(MSG1); OUTCHAR(' ');
OUTSET(S1); OUTCHAR(' ');
OUTTEXT(MSG2); OUTCHAR(' ');
OUTTEXT(IF B THEN "T" ELSE "F");
OUTIMAGE;
END**OF**REPORTNUMBOOL;
REF(SET) S1, S2, S3, S4, S5;
REF(ELEMENT) E;
INTEGER I;
S1 :- NEW SET; FOR I := 1, 2, 3, 4 DO S1.ADD(NEW NUMBER(I));
S2 :- NEW SET; FOR I := 3, 4, 5, 6 DO S2.ADD(NEW NUMBER(I));
S3 :- NEW SET; FOR I := 3, 1 DO S3.ADD(NEW NUMBER(I));
S4 :- NEW SET; FOR I := 1, 2, 3, 4, 5 DO S4.ADD(NEW NUMBER(I));
S5 :- NEW SET; FOR I := 4, 3, 2, 1 DO S5.ADD(NEW NUMBER(I));
REPORT(S1, "UNION", S2, " = ", UNION(S1, S2));
REPORT(S1, "INTERSECTION", S2, " = ", INTERSECTION(S1, S2));
REPORT(S1, "MINUS", S2, " = ", MINUS(S1, S2));
REPORT(S2, "MINUS", S1, " = ", MINUS(S2, S1));
E :- NEW NUMBER(2);
REPORTNUMBOOL(E, "IN", S1, " = ", ISIN(E, S1));
E :- NEW NUMBER(10);
REPORTNUMBOOL(E, "NOT IN", S1, " = ", NOT ISIN(E, S1));
REPORTBOOL(S1, "IS SUBSET OF", S1, " = ", ISSUBSET(S1, S1));
REPORTBOOL(S3, "IS SUBSET OF", S1, " = ", ISSUBSET(S3, S1));
REPORTBOOL(S4, "IS SUPERSET OF", S1, " = ", ISSUBSET(S1, S4));
REPORTBOOL(S1, "IS EQUAL TO", S2, " = ", ISEQUAL(S1, S2));
REPORTBOOL(S2, "IS EQUAL TO", S2, " = ", ISEQUAL(S2, S2));
REPORTBOOL(S1, "IS EQUAL TO", S5, " = ", ISEQUAL(S1, S5));
END.
|
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
|
Sieve of Eratosthenes
|
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer.
Task
Implement the Sieve of Eratosthenes algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found.
That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes.
If there's an easy way to add such a wheel based optimization, implement it as an alternative version.
Note
It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task.
Related tasks
Emirp primes
count in factors
prime decomposition
factors of an integer
extensible prime generator
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
|
#Java
|
Java
|
import java.util.LinkedList;
public class Sieve{
public static LinkedList<Integer> sieve(int n){
if(n < 2) return new LinkedList<Integer>();
LinkedList<Integer> primes = new LinkedList<Integer>();
LinkedList<Integer> nums = new LinkedList<Integer>();
for(int i = 2;i <= n;i++){ //unoptimized
nums.add(i);
}
while(nums.size() > 0){
int nextPrime = nums.remove();
for(int i = nextPrime * nextPrime;i <= n;i += nextPrime){
nums.removeFirstOccurrence(i);
}
primes.add(nextPrime);
}
return primes;
}
}
|
http://rosettacode.org/wiki/Set
|
Set
|
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
A set is a collection of elements, without duplicates and without order.
Task
Show each of these set operations:
Set creation
Test m ∈ S -- "m is an element in set S"
A ∪ B -- union; a set of all elements either in set A or in set B.
A ∩ B -- intersection; a set of all elements in both set A and set B.
A ∖ B -- difference; a set of all elements in set A, except those in set B.
A ⊆ B -- subset; true if every element in set A is also in set B.
A = B -- equality; true if every element of set A is in set B and vice versa.
As an option, show some other set operations.
(If A ⊆ B, but A ≠ B, then A is called a true or proper subset of B, written A ⊂ B or A ⊊ B.)
As another option, show how to modify a mutable set.
One might implement a set using an associative array (with set elements as array keys and some dummy value as the values).
One might also implement a set with a binary search tree, or with a hash table, or with an ordered array of binary bits (operated on with bit-wise binary operators).
The basic test, m ∈ S, is O(n) with a sequential list of elements, O(log n) with a balanced binary search tree, or (O(1) average-case, O(n) worst case) with a hash table.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
|
#Smalltalk
|
Smalltalk
|
#(1 2 3) asSet union: #(2 3 4) asSet.
"a Set(1 2 3 4)"
#(1 2 3) asSet intersection: #(2 3 4) asSet.
"a Set(2 3)"
#(1 2 3) asSet difference: #(2 3 4) asSet.
"a Set(1)"
#(1 2 3) asSet includesAllOf: #(1 3) asSet.
"true"
#(1 2 3) asSet includesAllOf: #(1 3 4) asSet.
"false"
#(1 2 3) asSet = #(2 1 3) asSet.
"true"
#(1 2 3) asSet = #(1 2 4) asSet.
"false"
|
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
|
Sieve of Eratosthenes
|
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer.
Task
Implement the Sieve of Eratosthenes algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found.
That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes.
If there's an easy way to add such a wheel based optimization, implement it as an alternative version.
Note
It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task.
Related tasks
Emirp primes
count in factors
prime decomposition
factors of an integer
extensible prime generator
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
|
#JavaScript
|
JavaScript
|
function eratosthenes(limit) {
var primes = [];
if (limit >= 2) {
var sqrtlmt = Math.sqrt(limit) - 2;
var nums = new Array(); // start with an empty Array...
for (var i = 2; i <= limit; i++) // and
nums.push(i); // only initialize the Array once...
for (var i = 0; i <= sqrtlmt; i++) {
var p = nums[i]
if (p)
for (var j = p * p - 2; j < nums.length; j += p)
nums[j] = 0;
}
for (var i = 0; i < nums.length; i++) {
var p = nums[i];
if (p)
primes.push(p);
}
}
return primes;
}
var primes = eratosthenes(100);
if (typeof print == "undefined")
print = (typeof WScript != "undefined") ? WScript.Echo : alert;
print(primes);
|
http://rosettacode.org/wiki/Set
|
Set
|
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
A set is a collection of elements, without duplicates and without order.
Task
Show each of these set operations:
Set creation
Test m ∈ S -- "m is an element in set S"
A ∪ B -- union; a set of all elements either in set A or in set B.
A ∩ B -- intersection; a set of all elements in both set A and set B.
A ∖ B -- difference; a set of all elements in set A, except those in set B.
A ⊆ B -- subset; true if every element in set A is also in set B.
A = B -- equality; true if every element of set A is in set B and vice versa.
As an option, show some other set operations.
(If A ⊆ B, but A ≠ B, then A is called a true or proper subset of B, written A ⊂ B or A ⊊ B.)
As another option, show how to modify a mutable set.
One might implement a set using an associative array (with set elements as array keys and some dummy value as the values).
One might also implement a set with a binary search tree, or with a hash table, or with an ordered array of binary bits (operated on with bit-wise binary operators).
The basic test, m ∈ S, is O(n) with a sequential list of elements, O(log n) with a balanced binary search tree, or (O(1) average-case, O(n) worst case) with a hash table.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
|
#SQL
|
SQL
|
-- set of numbers is a table
-- create one set with 3 elements
CREATE TABLE myset1 (element NUMBER);
INSERT INTO myset1 VALUES (1);
INSERT INTO myset1 VALUES (2);
INSERT INTO myset1 VALUES (3);
commit;
-- check if 1 is an element
SELECT 'TRUE' BOOL FROM dual
WHERE 1 IN
(SELECT element FROM myset1);
-- create second set with 3 elements
CREATE TABLE myset2 (element NUMBER);
INSERT INTO myset2 VALUES (1);
INSERT INTO myset2 VALUES (5);
INSERT INTO myset2 VALUES (6);
commit;
-- union sets
SELECT element FROM myset1
UNION
SELECT element FROM myset2;
-- intersection
SELECT element FROM myset1
INTERSECT
SELECT element FROM myset2;
-- difference
SELECT element FROM myset1
minus
SELECT element FROM myset2;
-- subset
-- change myset2 to only have 1 as element
DELETE FROM myset2 WHERE NOT element = 1;
commit;
-- check if myset2 subset of myset1
SELECT 'TRUE' BOOL FROM dual
WHERE 0 = (SELECT COUNT(*) FROM
(SELECT element FROM myset2
minus
SELECT element FROM myset1));
-- equality
-- change myset1 to only have 1 as element
DELETE FROM myset1 WHERE NOT element = 1;
commit;
-- check if myset2 subset of myset1 and
-- check if myset1 subset of myset2 and
SELECT 'TRUE' BOOL FROM dual
WHERE
0 = (SELECT COUNT(*) FROM
(SELECT element FROM myset2
minus
SELECT element FROM myset1)) AND
0 =
(SELECT COUNT(*) FROM
(SELECT element FROM myset1
minus
SELECT element FROM myset2));
|
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
|
Sieve of Eratosthenes
|
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer.
Task
Implement the Sieve of Eratosthenes algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found.
That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes.
If there's an easy way to add such a wheel based optimization, implement it as an alternative version.
Note
It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task.
Related tasks
Emirp primes
count in factors
prime decomposition
factors of an integer
extensible prime generator
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
|
#JOVIAL
|
JOVIAL
|
START
FILE MYOUTPUT ... $ ''Insufficient information to complete this declaration''
PROC SIEVEE $
'' define the sieve data structure ''
ARRAY CANDIDATES 1000 B $
FOR I =0,1,999 $
BEGIN
'' everything is potentially prime until proven otherwise ''
CANDIDATES($I$) = 1$
END
'' Neither 1 nor 0 is prime, so flag them off ''
CANDIDATES($0$) = 0$
CANDIDATES($1$) = 0$
'' start the sieve with the integer 0 ''
FOR I = 0$
BEGIN
IF I GE 1000$
GOTO DONE$
'' advance to the next un-crossed out number. ''
'' this number must be a prime ''
NEXTI. IF I LS 1000 AND Candidates($I$) EQ 0 $
BEGIN
I = I + 1 $
GOTO NEXTI $
END
'' insure against running off the end of the data structure ''
IF I LT 1000 $
BEGIN
'' cross out all multiples of the prime, starting with 2*p. ''
FOR J=2 $
FOR K=0 $
BEGIN
K = J * I $
IF K GT 999 $
GOTO ADV $
CANDIDATES($K$) = 0 $
J = J + 1 $
END
'' advance to the next candidate ''
ADV. I = I + 1 $
END
END
'' all uncrossed-out numbers are prime (and only those numbers) ''
'' print all primes ''
DONE. OPEN OUTPUT MYOUTPUT $
FOR I=0,1,999$
BEGIN
IF CANDIDATES($I$) NQ 0$
BEGIN
OUTPUT MYOUTPUT I $
END
END
TERM$
|
http://rosettacode.org/wiki/Set
|
Set
|
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
A set is a collection of elements, without duplicates and without order.
Task
Show each of these set operations:
Set creation
Test m ∈ S -- "m is an element in set S"
A ∪ B -- union; a set of all elements either in set A or in set B.
A ∩ B -- intersection; a set of all elements in both set A and set B.
A ∖ B -- difference; a set of all elements in set A, except those in set B.
A ⊆ B -- subset; true if every element in set A is also in set B.
A = B -- equality; true if every element of set A is in set B and vice versa.
As an option, show some other set operations.
(If A ⊆ B, but A ≠ B, then A is called a true or proper subset of B, written A ⊂ B or A ⊊ B.)
As another option, show how to modify a mutable set.
One might implement a set using an associative array (with set elements as array keys and some dummy value as the values).
One might also implement a set with a binary search tree, or with a hash table, or with an ordered array of binary bits (operated on with bit-wise binary operators).
The basic test, m ∈ S, is O(n) with a sequential list of elements, O(log n) with a balanced binary search tree, or (O(1) average-case, O(n) worst case) with a hash table.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
|
#Swift
|
Swift
|
var s1 : Set<Int> = [1, 2, 3, 4]
let s2 : Set<Int> = [3, 4, 5, 6]
println(s1.union(s2)) // union; prints "[5, 6, 2, 3, 1, 4]"
println(s1.intersect(s2)) // intersection; prints "[3, 4]"
println(s1.subtract(s2)) // difference; prints "[2, 1]"
println(s1.isSubsetOf(s1)) // subset; prints "true"
println(Set<Int>([3, 1]).isSubsetOf(s1)) // subset; prints "true"
println(s1.isStrictSubsetOf(s1)) // proper subset; prints "false"
println(Set<Int>([3, 1]).isStrictSubsetOf(s1)) // proper subset; prints "true"
println(Set<Int>([3, 2, 4, 1]) == s1) // equality; prints "true"
println(s1 == s2) // equality; prints "false"
println(s1.contains(2)) // membership; prints "true"
println(Set<Int>([1, 2, 3, 4]).isSupersetOf(s1)) // superset; prints "true"
println(Set<Int>([1, 2, 3, 4]).isStrictSupersetOf(s1)) // proper superset; prints "false"
println(Set<Int>([1, 2, 3, 4, 5]).isStrictSupersetOf(s1)) // proper superset; prints "true"
println(s1.exclusiveOr(s2)) // symmetric difference; prints "[5, 6, 2, 1]"
println(s1.count) // cardinality; prints "4"
s1.insert(99) // mutability
println(s1) // prints "[99, 2, 3, 1, 4]"
s1.remove(99) // mutability
println(s1) // prints "[2, 3, 1, 4]"
s1.unionInPlace(s2) // mutability
println(s1) // prints "[5, 6, 2, 3, 1, 4]"
s1.subtractInPlace(s2) // mutability
println(s1) // prints "[2, 1]"
s1.exclusiveOrInPlace(s2) // mutability
println(s1) // prints "[5, 6, 2, 3, 1, 4]"
|
http://rosettacode.org/wiki/Scope_modifiers
|
Scope modifiers
|
Most programming languages offer support for subroutines.
When execution changes between subroutines, different sets of variables and functions ("scopes") are available to the program.
Frequently these sets are defined by the placement of the variable and function declarations ("static scoping" or "lexical scoping").
These sets may also be defined by special modifiers to the variable and function declarations.
Show the different scope modifiers available in your language and briefly explain how they change the scope of their variable or function.
If your language has no scope modifiers, note it.
|
#11l
|
11l
|
V x = ‘From global scope’
F outerfunc()
V x = ‘From scope at outerfunc’
F scoped_local()
V x = ‘scope local’
R ‘scoped_local scope gives x = ’x
print(scoped_local())
F scoped_nonlocal()
R ‘scoped_nonlocal scope gives x = ’@x
print(scoped_nonlocal())
F scoped_global()
R ‘scoped_global scope gives x = ’:x
print(scoped_global())
outerfunc()
|
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
|
Sieve of Eratosthenes
|
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer.
Task
Implement the Sieve of Eratosthenes algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found.
That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes.
If there's an easy way to add such a wheel based optimization, implement it as an alternative version.
Note
It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task.
Related tasks
Emirp primes
count in factors
prime decomposition
factors of an integer
extensible prime generator
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
|
#jq
|
jq
|
# Denoting the input by $n, which is assumed to be a positive integer,
# eratosthenes/0 produces an array of primes less than or equal to $n:
def eratosthenes:
# erase(i) sets .[i*j] to false for integral j > 1
def erase(i):
if .[i] then reduce range(2; (1 + length) / i) as $j (.; .[i * $j] = false)
else .
end;
(. + 1) as $n
| (($n|sqrt) / 2) as $s
| [null, null, range(2; $n)]
| reduce (2, 1 + (2 * range(1; $s))) as $i (.; erase($i))
| map(select(.));
|
http://rosettacode.org/wiki/Set
|
Set
|
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
A set is a collection of elements, without duplicates and without order.
Task
Show each of these set operations:
Set creation
Test m ∈ S -- "m is an element in set S"
A ∪ B -- union; a set of all elements either in set A or in set B.
A ∩ B -- intersection; a set of all elements in both set A and set B.
A ∖ B -- difference; a set of all elements in set A, except those in set B.
A ⊆ B -- subset; true if every element in set A is also in set B.
A = B -- equality; true if every element of set A is in set B and vice versa.
As an option, show some other set operations.
(If A ⊆ B, but A ≠ B, then A is called a true or proper subset of B, written A ⊂ B or A ⊊ B.)
As another option, show how to modify a mutable set.
One might implement a set using an associative array (with set elements as array keys and some dummy value as the values).
One might also implement a set with a binary search tree, or with a hash table, or with an ordered array of binary bits (operated on with bit-wise binary operators).
The basic test, m ∈ S, is O(n) with a sequential list of elements, O(log n) with a balanced binary search tree, or (O(1) average-case, O(n) worst case) with a hash table.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
|
#Tcl
|
Tcl
|
package require struct::set
# Many ways to build sets
set s1 [list 1 2 3 4]
set s2 {3 4 5 6}
struct::set add s3 {2 3 4 3 2}; # $s3 will be proper set...
set item 5
puts "union: [struct::set union $s1 $s2]"
puts "intersection: [struct::set intersect $s1 $s2]"
puts "difference: [struct::set difference $s1 $s2]"
puts "membership predicate: [struct::set contains $s1 $item]"
puts "subset predicate: [struct::set subsetof $s1 $s2]"; # NB: not strict subset test!
puts "equality predicate: [struct::set equal $s1 $s2]"
# Adding an element to a set (note that we pass in the name of the variable holding the set):
struct::set include s3 $item
# Removing an element from a set:
struct::set exclude s3 $item
# Getting the cardinality:
puts "cardinality: [struct::set size $s3]
|
http://rosettacode.org/wiki/Scope_modifiers
|
Scope modifiers
|
Most programming languages offer support for subroutines.
When execution changes between subroutines, different sets of variables and functions ("scopes") are available to the program.
Frequently these sets are defined by the placement of the variable and function declarations ("static scoping" or "lexical scoping").
These sets may also be defined by special modifiers to the variable and function declarations.
Show the different scope modifiers available in your language and briefly explain how they change the scope of their variable or function.
If your language has no scope modifiers, note it.
|
#6502_Assembly
|
6502 Assembly
|
macro LDIR,source,dest,count
;LoaD, Increment, Repeat
lda #<source
sta $00
lda #>source
sta $01
lda #<dest
sta $02
lda #>dest
sta $03
ldx count
ldy #0
\@: ;this is a local label
lda ($00),y ;load a byte from the source address
sta ($02),y ;store in destination address
iny ;increment
dex
bne \@ ;repeat until x=0
endm
|
http://rosettacode.org/wiki/Scope_modifiers
|
Scope modifiers
|
Most programming languages offer support for subroutines.
When execution changes between subroutines, different sets of variables and functions ("scopes") are available to the program.
Frequently these sets are defined by the placement of the variable and function declarations ("static scoping" or "lexical scoping").
These sets may also be defined by special modifiers to the variable and function declarations.
Show the different scope modifiers available in your language and briefly explain how they change the scope of their variable or function.
If your language has no scope modifiers, note it.
|
#Ada
|
Ada
|
package P is
... -- Declarations placed here are publicly visible
private
... -- These declarations are visible only to the children of P
end P;
|
http://rosettacode.org/wiki/Scope_modifiers
|
Scope modifiers
|
Most programming languages offer support for subroutines.
When execution changes between subroutines, different sets of variables and functions ("scopes") are available to the program.
Frequently these sets are defined by the placement of the variable and function declarations ("static scoping" or "lexical scoping").
These sets may also be defined by special modifiers to the variable and function declarations.
Show the different scope modifiers available in your language and briefly explain how they change the scope of their variable or function.
If your language has no scope modifiers, note it.
|
#ALGOL_60
|
ALGOL 60
|
singleton = "global variable"
assume_global()
{
Global ; assume all variables declared in this function are global in scope
Static callcount := 0 ; except this one declared static, initialized once only
MsgBox % singleton ; usefull to initialize a bunch of singletons
callcount++
}
assume_global2()
{
Local var1 ; assume global except for var1 (similar to global scope declaration)
MsgBox % singleton
}
object(member, value = 0, null = 0)
{
Static ; assume all variables in this function to be static
If value ; can be used to simulate objects
_%member% := value
Else If null
_%member% := ""
Return (_%member%)
}
|
http://rosettacode.org/wiki/Secure_temporary_file
|
Secure temporary file
|
Task
Create a temporary file, securely and exclusively (opening it such that there are no possible race conditions).
It's fine assuming local filesystem semantics (NFS or other networking filesystems can have signficantly more complicated semantics for satisfying the "no race conditions" criteria).
The function should automatically resolve name collisions and should only fail in cases where permission is denied, the filesystem is read-only or full, or similar conditions exist (returning an error or raising an exception as appropriate to the language/environment).
|
#Ada
|
Ada
|
with Ada.Text_Io; use Ada.Text_Io;
procedure Temp_File is
Temp : File_Type;
Contents : String(1..80);
Length : Natural;
begin
-- Create a temporary file
Create(File => Temp);
Put_Line(File => Temp, Item => "Hello World");
Reset(File => Temp, Mode => In_File);
Get_Line(File => Temp, Item => Contents, Last => Length);
Put_Line(Contents(1..Length));
end Temp_File;
|
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
|
Sieve of Eratosthenes
|
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer.
Task
Implement the Sieve of Eratosthenes algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found.
That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes.
If there's an easy way to add such a wheel based optimization, implement it as an alternative version.
Note
It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task.
Related tasks
Emirp primes
count in factors
prime decomposition
factors of an integer
extensible prime generator
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
|
#Julia
|
Julia
|
# Returns an array of positive prime numbers less than or equal to lim
function sieve(lim :: Int)
if lim < 2 return [] end
limi :: Int = (lim - 1) ÷ 2 # calculate the required array size
isprime :: Array{Bool} = trues(limi)
llimi :: Int = (isqrt(lim) - 1) ÷ 2 # and calculate maximum root prime index
result :: Array{Int} = [2] #Initial array
for i in 1:limi
if isprime[i]
p = i + i + 1 # 2i + 1
if i <= llimi
for j = (p*p-1)>>>1:p:limi # quick shift/divide in case LLVM doesn't optimize divide by 2 away
isprime[j] = false
end
end
push!(result, p)
end
end
return result
end
|
http://rosettacode.org/wiki/Set
|
Set
|
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
A set is a collection of elements, without duplicates and without order.
Task
Show each of these set operations:
Set creation
Test m ∈ S -- "m is an element in set S"
A ∪ B -- union; a set of all elements either in set A or in set B.
A ∩ B -- intersection; a set of all elements in both set A and set B.
A ∖ B -- difference; a set of all elements in set A, except those in set B.
A ⊆ B -- subset; true if every element in set A is also in set B.
A = B -- equality; true if every element of set A is in set B and vice versa.
As an option, show some other set operations.
(If A ⊆ B, but A ≠ B, then A is called a true or proper subset of B, written A ⊂ B or A ⊊ B.)
As another option, show how to modify a mutable set.
One might implement a set using an associative array (with set elements as array keys and some dummy value as the values).
One might also implement a set with a binary search tree, or with a hash table, or with an ordered array of binary bits (operated on with bit-wise binary operators).
The basic test, m ∈ S, is O(n) with a sequential list of elements, O(log n) with a balanced binary search tree, or (O(1) average-case, O(n) worst case) with a hash table.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
|
#VBA
|
VBA
|
'Implementation of "set" using the built in Collection datatype.
'A collection can hold any object as item. The examples here are only strings.
'A collection stores item, key pairs. With the key you can retrieve the item.
'The keys are hidden and cannot be changed. No duplicate keys are allowed.
'For the "set" implementation item is the same as the key. And keys must
'be a string.
Private Function createSet(t As Variant) As Collection
Dim x As New Collection
For Each elem In t
x.Add elem, elem
Next elem
Set createSet = x
End Function
Private Function isElement(s As Variant, x As Collection) As Boolean
Dim errno As Integer, t As Variant
On Error GoTo err
t = x(s)
isElement = True
Exit Function
err:
isElement = False
End Function
Private Function setUnion(A As Collection, B As Collection) As Collection
Dim x As New Collection
For Each elem In A
x.Add elem, elem
Next elem
For Each elem In B
On Error Resume Next 'Trying to add a duplicate throws an error
x.Add elem, elem
Next elem
Set setUnion = x
End Function
Private Function intersection(A As Collection, B As Collection) As Collection
Dim x As New Collection
For Each elem In A
If isElement(elem, B) Then x.Add elem, elem
Next elem
For Each elem In B
If isElement(elem, A) Then
On Error Resume Next
x.Add elem, elem
End If
Next elem
Set intersection = x
End Function
Private Function difference(A As Collection, B As Collection) As Collection
Dim x As New Collection
For Each elem In A
If Not isElement(elem, B) Then x.Add elem, elem
Next elem
Set difference = x
End Function
Private Function subset(A As Collection, B As Collection) As Boolean
Dim flag As Boolean
flag = True
For Each elem In A
If Not isElement(elem, B) Then
flag = False
Exit For
End If
Next elem
subset = flag
End Function
Private Function equality(A As Collection, B As Collection) As Boolean
Dim flag As Boolean
flag = True
If A.Count = B.Count Then
For Each elem In A
If Not isElement(elem, B) Then
flag = False
Exit For
End If
Next elem
Else
flag = False
End If
equality = flag
End Function
Private Function properSubset(A As Collection, B As Collection) As Boolean
Dim flag As Boolean
flag = True
If A.Count < B.Count Then
For Each elem In A
If Not isElement(elem, B) Then
flag = False
Exit For
End If
Next elem
Else
flag = False
End If
properSubset = flag
End Function
Public Sub main()
'Set creation
Dim s As Variant
Dim A As Collection, B As Collection, C As Collection
s = [{"Apple","Banana","Pear","Pineapple"}]
Set A = createSet(s) 'Fills the collection A with the elements of s
'Test m ? S -- "m is an element in set S"
Debug.Print isElement("Apple", A) 'returns True
Debug.Print isElement("Fruit", A) 'returns False
'A ? B -- union; a set of all elements either in set A or in set B.
s = [{"Fruit","Banana","Pear","Orange"}]
Set B = createSet(s)
Set C = setUnion(A, B)
'A n B -- intersection; a set of all elements in both set A and set B.
Set C = intersection(A, B)
'A \ B -- difference; a set of all elements in set A, except those in set B.
Set C = difference(A, B)
'A ? B -- subset; true if every element in set A is also in set B.
Debug.Print subset(A, B)
'A = B -- equality; true if every element of set A is in set B and vice versa.
Debug.Print equality(A, B)
'Proper subset
Debug.Print properSubset(A, B)
'Modify -remove an element by key
A.Remove "Apple"
'Modify -remove the first element in the collection/set
A.Remove 1
'Add "10" to A
A.Add "10", "10"
End Sub
|
http://rosettacode.org/wiki/Scope_modifiers
|
Scope modifiers
|
Most programming languages offer support for subroutines.
When execution changes between subroutines, different sets of variables and functions ("scopes") are available to the program.
Frequently these sets are defined by the placement of the variable and function declarations ("static scoping" or "lexical scoping").
These sets may also be defined by special modifiers to the variable and function declarations.
Show the different scope modifiers available in your language and briefly explain how they change the scope of their variable or function.
If your language has no scope modifiers, note it.
|
#ALGOL_68
|
ALGOL 68
|
singleton = "global variable"
assume_global()
{
Global ; assume all variables declared in this function are global in scope
Static callcount := 0 ; except this one declared static, initialized once only
MsgBox % singleton ; usefull to initialize a bunch of singletons
callcount++
}
assume_global2()
{
Local var1 ; assume global except for var1 (similar to global scope declaration)
MsgBox % singleton
}
object(member, value = 0, null = 0)
{
Static ; assume all variables in this function to be static
If value ; can be used to simulate objects
_%member% := value
Else If null
_%member% := ""
Return (_%member%)
}
|
http://rosettacode.org/wiki/Scope_modifiers
|
Scope modifiers
|
Most programming languages offer support for subroutines.
When execution changes between subroutines, different sets of variables and functions ("scopes") are available to the program.
Frequently these sets are defined by the placement of the variable and function declarations ("static scoping" or "lexical scoping").
These sets may also be defined by special modifiers to the variable and function declarations.
Show the different scope modifiers available in your language and briefly explain how they change the scope of their variable or function.
If your language has no scope modifiers, note it.
|
#ALGOL_W
|
ALGOL W
|
singleton = "global variable"
assume_global()
{
Global ; assume all variables declared in this function are global in scope
Static callcount := 0 ; except this one declared static, initialized once only
MsgBox % singleton ; usefull to initialize a bunch of singletons
callcount++
}
assume_global2()
{
Local var1 ; assume global except for var1 (similar to global scope declaration)
MsgBox % singleton
}
object(member, value = 0, null = 0)
{
Static ; assume all variables in this function to be static
If value ; can be used to simulate objects
_%member% := value
Else If null
_%member% := ""
Return (_%member%)
}
|
http://rosettacode.org/wiki/Secure_temporary_file
|
Secure temporary file
|
Task
Create a temporary file, securely and exclusively (opening it such that there are no possible race conditions).
It's fine assuming local filesystem semantics (NFS or other networking filesystems can have signficantly more complicated semantics for satisfying the "no race conditions" criteria).
The function should automatically resolve name collisions and should only fail in cases where permission is denied, the filesystem is read-only or full, or similar conditions exist (returning an error or raising an exception as appropriate to the language/environment).
|
#BBC_BASIC
|
BBC BASIC
|
file% = FNopentempfile
IF file% = 0 ERROR 100, "Failed to open temp file"
PRINT #file%, "Hello world!"
PTR#file% = 0
INPUT #file%, message$
CLOSE #file%
PRINT message$
END
DEF FNopentempfile
LOCAL pname%, hfile%, chan%
OPEN_EXISTING = 3
FILE_FLAG_DELETE_ON_CLOSE = &4000000
GENERIC_READ = &80000000
GENERIC_WRITE = &40000000
INVALID_HANDLE_VALUE = -1
DIM pname% LOCAL 260
FOR chan% = 5 TO 12
IF @hfile%(chan%) = 0 EXIT FOR
NEXT
IF chan% > 12 THEN = 0
SYS "GetTempFileName", @tmp$, "BBC", 0, pname%
SYS "CreateFile", $$pname%, GENERIC_READ OR GENERIC_WRITE, 0, 0, \
\ OPEN_EXISTING, FILE_FLAG_DELETE_ON_CLOSE, 0 TO hfile%
IF hfile% = INVALID_HANDLE_VALUE THEN = 0
@hfile%(chan%) = hfile%
= chan%
|
http://rosettacode.org/wiki/Secure_temporary_file
|
Secure temporary file
|
Task
Create a temporary file, securely and exclusively (opening it such that there are no possible race conditions).
It's fine assuming local filesystem semantics (NFS or other networking filesystems can have signficantly more complicated semantics for satisfying the "no race conditions" criteria).
The function should automatically resolve name collisions and should only fail in cases where permission is denied, the filesystem is read-only or full, or similar conditions exist (returning an error or raising an exception as appropriate to the language/environment).
|
#C
|
C
|
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
FILE *fh = tmpfile(); /* file is automatically deleted when program exits */
/* do stuff with stream "fh" */
fclose(fh);
/* The C standard library also has a tmpnam() function to create a file
for you to open later. But you should not use it because someone else might
be able to open the file from the time it is created by this function to the
time you open it. */
return 0;
}
|
http://rosettacode.org/wiki/Secure_temporary_file
|
Secure temporary file
|
Task
Create a temporary file, securely and exclusively (opening it such that there are no possible race conditions).
It's fine assuming local filesystem semantics (NFS or other networking filesystems can have signficantly more complicated semantics for satisfying the "no race conditions" criteria).
The function should automatically resolve name collisions and should only fail in cases where permission is denied, the filesystem is read-only or full, or similar conditions exist (returning an error or raising an exception as appropriate to the language/environment).
|
#C.23
|
C#
|
using System;
using System.IO;
Console.WriteLine(Path.GetTempFileName());
|
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
|
Sieve of Eratosthenes
|
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer.
Task
Implement the Sieve of Eratosthenes algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found.
That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes.
If there's an easy way to add such a wheel based optimization, implement it as an alternative version.
Note
It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task.
Related tasks
Emirp primes
count in factors
prime decomposition
factors of an integer
extensible prime generator
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
|
#Klingphix
|
Klingphix
|
include ..\Utilitys.tlhy
%limit %i
1000 !limit
( 1 $limit ) sequence
( 2 $limit sqrt int ) [ !i $i get [ ( 2 $limit 1 - $i / int ) [ $i * false swap set ] for ] if ] for
( 1 $limit false ) remove
pstack
"Press ENTER to end " input
|
http://rosettacode.org/wiki/Set
|
Set
|
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
A set is a collection of elements, without duplicates and without order.
Task
Show each of these set operations:
Set creation
Test m ∈ S -- "m is an element in set S"
A ∪ B -- union; a set of all elements either in set A or in set B.
A ∩ B -- intersection; a set of all elements in both set A and set B.
A ∖ B -- difference; a set of all elements in set A, except those in set B.
A ⊆ B -- subset; true if every element in set A is also in set B.
A = B -- equality; true if every element of set A is in set B and vice versa.
As an option, show some other set operations.
(If A ⊆ B, but A ≠ B, then A is called a true or proper subset of B, written A ⊂ B or A ⊊ B.)
As another option, show how to modify a mutable set.
One might implement a set using an associative array (with set elements as array keys and some dummy value as the values).
One might also implement a set with a binary search tree, or with a hash table, or with an ordered array of binary bits (operated on with bit-wise binary operators).
The basic test, m ∈ S, is O(n) with a sequential list of elements, O(log n) with a balanced binary search tree, or (O(1) average-case, O(n) worst case) with a hash table.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
|
#Wren
|
Wren
|
import "/set" for Set
var fruits = Set.new(["apple", "pear", "orange", "banana"])
System.print("fruits : %(fruits)")
var fruits2 = Set.new(["melon", "orange", "lemon", "gooseberry"])
System.print("fruits2 : %(fruits2)\n")
System.print("fruits contains 'banana' : %(fruits.contains("banana"))")
System.print("fruits2 contains 'elderberry' : %(fruits2.contains("elderberry"))\n")
System.print("Union : %(fruits.union(fruits2))")
System.print("Intersection : %(fruits.intersect(fruits2))")
System.print("Difference : %(fruits.except(fruits2))\n")
System.print("fruits2 is a subset of fruits : %(fruits2.subsetOf(fruits))\n")
var fruits3 = fruits.copy()
System.print("fruits3 : %(fruits3)\n")
System.print("fruits2 and fruits are equal : %(fruits2 == fruits)")
System.print("fruits3 and fruits are equal : %(fruits3 == fruits)\n")
var fruits4 = Set.new(["apple", "orange"])
System.print("fruits4 : %(fruits4)\n")
System.print("fruits3 is a proper subset of fruits : %(fruits3.properSubsetOf(fruits))")
System.print("fruits4 is a proper subset of fruits : %(fruits4.properSubsetOf(fruits))\n")
var fruits5 = Set.new(["cherry", "blueberry", "raspberry"])
System.print("fruits5 : %(fruits5)\n")
fruits5.add("guava")
System.print("fruits5 + 'guava' : %(fruits5)")
fruits5.remove("cherry")
System.print("fruits5 - 'cherry' : %(fruits5)")
|
http://rosettacode.org/wiki/Scope_modifiers
|
Scope modifiers
|
Most programming languages offer support for subroutines.
When execution changes between subroutines, different sets of variables and functions ("scopes") are available to the program.
Frequently these sets are defined by the placement of the variable and function declarations ("static scoping" or "lexical scoping").
These sets may also be defined by special modifiers to the variable and function declarations.
Show the different scope modifiers available in your language and briefly explain how they change the scope of their variable or function.
If your language has no scope modifiers, note it.
|
#AutoHotkey
|
AutoHotkey
|
singleton = "global variable"
assume_global()
{
Global ; assume all variables declared in this function are global in scope
Static callcount := 0 ; except this one declared static, initialized once only
MsgBox % singleton ; usefull to initialize a bunch of singletons
callcount++
}
assume_global2()
{
Local var1 ; assume global except for var1 (similar to global scope declaration)
MsgBox % singleton
}
object(member, value = 0, null = 0)
{
Static ; assume all variables in this function to be static
If value ; can be used to simulate objects
_%member% := value
Else If null
_%member% := ""
Return (_%member%)
}
|
http://rosettacode.org/wiki/Scope_modifiers
|
Scope modifiers
|
Most programming languages offer support for subroutines.
When execution changes between subroutines, different sets of variables and functions ("scopes") are available to the program.
Frequently these sets are defined by the placement of the variable and function declarations ("static scoping" or "lexical scoping").
These sets may also be defined by special modifiers to the variable and function declarations.
Show the different scope modifiers available in your language and briefly explain how they change the scope of their variable or function.
If your language has no scope modifiers, note it.
|
#Axe
|
Axe
|
10 X = 1
20 DEF FN F(X) = X
30 DEF FN G(N) = X
40 PRINT FN F(2)
50 PRINT FN G(3)
|
http://rosettacode.org/wiki/Secure_temporary_file
|
Secure temporary file
|
Task
Create a temporary file, securely and exclusively (opening it such that there are no possible race conditions).
It's fine assuming local filesystem semantics (NFS or other networking filesystems can have signficantly more complicated semantics for satisfying the "no race conditions" criteria).
The function should automatically resolve name collisions and should only fail in cases where permission is denied, the filesystem is read-only or full, or similar conditions exist (returning an error or raising an exception as appropriate to the language/environment).
|
#Clojure
|
Clojure
|
(let [temp-file (java.io.File/createTempFile "pre" ".suff")]
; insert logic here that would use temp-file
(.delete temp-file))
|
http://rosettacode.org/wiki/Secure_temporary_file
|
Secure temporary file
|
Task
Create a temporary file, securely and exclusively (opening it such that there are no possible race conditions).
It's fine assuming local filesystem semantics (NFS or other networking filesystems can have signficantly more complicated semantics for satisfying the "no race conditions" criteria).
The function should automatically resolve name collisions and should only fail in cases where permission is denied, the filesystem is read-only or full, or similar conditions exist (returning an error or raising an exception as appropriate to the language/environment).
|
#D
|
D
|
module tempfile ;
import tango.io.TempFile, tango.io.Stdout ;
void main(char[][] args) {
// create a temporary file that will be deleted automatically when out of scope
auto tempTransient = new TempFile(TempFile.Transient) ;
Stdout(tempTransient.path()).newline ;
// create a temporary file, still persist after the TempFile object has been destroyed
auto tempPermanent = new TempFile(TempFile.Permanent) ;
Stdout(tempPermanent.path()).newline ;
// both can only be accessed by the current user (the program?).
}
|
http://rosettacode.org/wiki/Secure_temporary_file
|
Secure temporary file
|
Task
Create a temporary file, securely and exclusively (opening it such that there are no possible race conditions).
It's fine assuming local filesystem semantics (NFS or other networking filesystems can have signficantly more complicated semantics for satisfying the "no race conditions" criteria).
The function should automatically resolve name collisions and should only fail in cases where permission is denied, the filesystem is read-only or full, or similar conditions exist (returning an error or raising an exception as appropriate to the language/environment).
|
#Delphi
|
Delphi
|
program Secure_temporary_file;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
System.IOUtils;
var
FileName, buf: string;
begin
FileName := TPath.GetTempFileName;
with TFile.Open(FileName, TFileMode.fmCreate, TFileAccess.faReadWrite,
Tfileshare.fsNone) do
begin
buf := 'This is a exclusive temp file';
Write(buf[1], buf.Length * sizeof(char));
Free;
end;
writeln(FileName);
Readln;
end.
|
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
|
Sieve of Eratosthenes
|
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer.
Task
Implement the Sieve of Eratosthenes algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found.
That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes.
If there's an easy way to add such a wheel based optimization, implement it as an alternative version.
Note
It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task.
Related tasks
Emirp primes
count in factors
prime decomposition
factors of an integer
extensible prime generator
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
|
#Kotlin
|
Kotlin
|
import kotlin.math.sqrt
fun sieve(max: Int): List<Int> {
val xs = (2..max).toMutableList()
val limit = sqrt(max.toDouble()).toInt()
for (x in 2..limit) xs -= x * x..max step x
return xs
}
fun main(args: Array<String>) {
println(sieve(100))
}
|
http://rosettacode.org/wiki/Set
|
Set
|
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
A set is a collection of elements, without duplicates and without order.
Task
Show each of these set operations:
Set creation
Test m ∈ S -- "m is an element in set S"
A ∪ B -- union; a set of all elements either in set A or in set B.
A ∩ B -- intersection; a set of all elements in both set A and set B.
A ∖ B -- difference; a set of all elements in set A, except those in set B.
A ⊆ B -- subset; true if every element in set A is also in set B.
A = B -- equality; true if every element of set A is in set B and vice versa.
As an option, show some other set operations.
(If A ⊆ B, but A ≠ B, then A is called a true or proper subset of B, written A ⊂ B or A ⊊ B.)
As another option, show how to modify a mutable set.
One might implement a set using an associative array (with set elements as array keys and some dummy value as the values).
One might also implement a set with a binary search tree, or with a hash table, or with an ordered array of binary bits (operated on with bit-wise binary operators).
The basic test, m ∈ S, is O(n) with a sequential list of elements, O(log n) with a balanced binary search tree, or (O(1) average-case, O(n) worst case) with a hash table.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
|
#zkl
|
zkl
|
var [const] unique = Utils.Helpers.listUnique;
class Set {
fcn init { var [const] set = (vm.arglist.copy() : unique(_)) }
fcn holds(x) { set.holds(x) }
fcn union(setB) { self(set.xplode(),setB.set.xplode()) }
fcn intersection(setB){ sb:=setB.set;
C:=self(); sc:=C.set;
foreach x in (set){ if (sb.holds(x)) sc.append(x) }
C
}
fcn diff(setB){ C:=self(); C.set.extend(set);
setB.set.pump(Void,C.set.remove);
C
}
fcn isSubset(setB){ sb:=setB.set;
set.pump(Void,'wrap(x){
if (not sb.holds(x)) return(Void.Stop,False); True
})
}
fcn __opEQ(setB) { ((set.len() == setB.set.len()) and self.isSubset(setB)) }
}
|
http://rosettacode.org/wiki/Scope_modifiers
|
Scope modifiers
|
Most programming languages offer support for subroutines.
When execution changes between subroutines, different sets of variables and functions ("scopes") are available to the program.
Frequently these sets are defined by the placement of the variable and function declarations ("static scoping" or "lexical scoping").
These sets may also be defined by special modifiers to the variable and function declarations.
Show the different scope modifiers available in your language and briefly explain how they change the scope of their variable or function.
If your language has no scope modifiers, note it.
|
#BASIC
|
BASIC
|
10 X = 1
20 DEF FN F(X) = X
30 DEF FN G(N) = X
40 PRINT FN F(2)
50 PRINT FN G(3)
|
http://rosettacode.org/wiki/Scope_modifiers
|
Scope modifiers
|
Most programming languages offer support for subroutines.
When execution changes between subroutines, different sets of variables and functions ("scopes") are available to the program.
Frequently these sets are defined by the placement of the variable and function declarations ("static scoping" or "lexical scoping").
These sets may also be defined by special modifiers to the variable and function declarations.
Show the different scope modifiers available in your language and briefly explain how they change the scope of their variable or function.
If your language has no scope modifiers, note it.
|
#bc
|
bc
|
define g(a) {
auto b
b = 3
"Inside g: a = "; a
"Inside g: b = "; b
"Inside g: c = "; c
"Inside g: d = "; d
a = 3; b = 3; c = 3; d = 3
}
define f(a) {
auto b, c
b = 2; c = 2
"Inside f (before call): a = "; a
"Inside f (before call): b = "; b
"Inside f (before call): c = "; c
"Inside f (before call): d = "; d
x = g(2) /* Assignment prevents output of the return value */
"Inside f (after call): a = "; a
"Inside f (after call): b = "; b
"Inside f (after call): c = "; c
"Inside f (after call): d = "; d
a = 2; b = 2; c = 2; d = 2
}
a = 1; b = 1; c = 1; d = 1
"Global scope (before call): a = "; a
"Global scope (before call): b = "; b
"Global scope (before call): c = "; c
"Global scope (before call): d = "; d
x = f(1)
"Global scope (before call): a = "; a
"Global scope (before call): b = "; b
"Global scope (before call): c = "; c
"Global scope (before call): d = "; d
|
http://rosettacode.org/wiki/Secure_temporary_file
|
Secure temporary file
|
Task
Create a temporary file, securely and exclusively (opening it such that there are no possible race conditions).
It's fine assuming local filesystem semantics (NFS or other networking filesystems can have signficantly more complicated semantics for satisfying the "no race conditions" criteria).
The function should automatically resolve name collisions and should only fail in cases where permission is denied, the filesystem is read-only or full, or similar conditions exist (returning an error or raising an exception as appropriate to the language/environment).
|
#Emacs_Lisp
|
Emacs Lisp
|
(make-temp-file "prefix")
;; => "/tmp/prefix25452LPe"
|
http://rosettacode.org/wiki/Secure_temporary_file
|
Secure temporary file
|
Task
Create a temporary file, securely and exclusively (opening it such that there are no possible race conditions).
It's fine assuming local filesystem semantics (NFS or other networking filesystems can have signficantly more complicated semantics for satisfying the "no race conditions" criteria).
The function should automatically resolve name collisions and should only fail in cases where permission is denied, the filesystem is read-only or full, or similar conditions exist (returning an error or raising an exception as appropriate to the language/environment).
|
#Fortran
|
Fortran
|
OPEN (F,STATUS = 'SCRATCH') !Temporary disc storage.
|
http://rosettacode.org/wiki/Secure_temporary_file
|
Secure temporary file
|
Task
Create a temporary file, securely and exclusively (opening it such that there are no possible race conditions).
It's fine assuming local filesystem semantics (NFS or other networking filesystems can have signficantly more complicated semantics for satisfying the "no race conditions" criteria).
The function should automatically resolve name collisions and should only fail in cases where permission is denied, the filesystem is read-only or full, or similar conditions exist (returning an error or raising an exception as appropriate to the language/environment).
|
#Go
|
Go
|
package main
import (
"fmt"
"io/ioutil"
"log"
"os"
)
func main() {
f, err := ioutil.TempFile("", "foo")
if err != nil {
log.Fatal(err)
}
defer f.Close()
// We need to make sure we remove the file
// once it is no longer needed.
defer os.Remove(f.Name())
// … use the file via 'f' …
fmt.Fprintln(f, "Using temporary file:", f.Name())
f.Seek(0, 0)
d, err := ioutil.ReadAll(f)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Wrote and read: %s\n", d)
// The defer statements above will close and remove the
// temporary file here (or on any return of this function).
}
|
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
|
Sieve of Eratosthenes
|
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer.
Task
Implement the Sieve of Eratosthenes algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found.
That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes.
If there's an easy way to add such a wheel based optimization, implement it as an alternative version.
Note
It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task.
Related tasks
Emirp primes
count in factors
prime decomposition
factors of an integer
extensible prime generator
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
|
#Lambdatalk
|
Lambdatalk
|
{def sieve
{def sieve.rec2
{lambda {:a :n :i :k}
{if {< :k :n}
then {sieve.rec2 {A.set! :k 0 :a} :n :i {+ :k :i}}
else :a}}}
{def sieve.rec1
{lambda {:a :n :i}
{if {< :i {sqrt :n}}
then {sieve.rec1 {if {= {A.get :i :a} 1}
then {sieve.rec2 :a :n :i {* :i :i}}
else :a}
:n {+ :i 1}}
else :a}}}
{def sieve.disp
{lambda {:s}
{S.replace \s by space in
{S.map {{lambda {:a :i} {if {= {A.get :i :a} 1} then :i else}} :s}
{S.serie 2 {- {A.length :s} 1}}} }}}
{lambda {:n}
{sieve.disp
{sieve.rec1 {A.new {S.map {lambda {_} 1} {S.serie 1 :n}}}
:n 2}}}}
-> sieve
{sieve 100}
-> 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
|
http://rosettacode.org/wiki/Scope_modifiers
|
Scope modifiers
|
Most programming languages offer support for subroutines.
When execution changes between subroutines, different sets of variables and functions ("scopes") are available to the program.
Frequently these sets are defined by the placement of the variable and function declarations ("static scoping" or "lexical scoping").
These sets may also be defined by special modifiers to the variable and function declarations.
Show the different scope modifiers available in your language and briefly explain how they change the scope of their variable or function.
If your language has no scope modifiers, note it.
|
#Bracmat
|
Bracmat
|
67:?x {x has global scope}
& 77:?y { y has global scope }
& ( double
=
. !y+!y { y refers to the variable declared in myFunc, which
shadows the global variable with the same name }
)
& ( myFunc
= y,z { y and z have dynamic scope. z is never used. }
. !arg:?y { arg is dynamically scoped }
& double$
& !x+!y
)
|
http://rosettacode.org/wiki/Scope_modifiers
|
Scope modifiers
|
Most programming languages offer support for subroutines.
When execution changes between subroutines, different sets of variables and functions ("scopes") are available to the program.
Frequently these sets are defined by the placement of the variable and function declarations ("static scoping" or "lexical scoping").
These sets may also be defined by special modifiers to the variable and function declarations.
Show the different scope modifiers available in your language and briefly explain how they change the scope of their variable or function.
If your language has no scope modifiers, note it.
|
#C
|
C
|
int a; // a is global
static int p; // p is "locale" and can be seen only from file1.c
extern float v; // a global declared somewhere else
// a "global" function
int code(int arg)
{
int myp; // 1) this can be seen only from inside code
// 2) In recursive code this variable will be in a
// different stack frame (like a closure)
static int myc; // 3) still a variable that can be seen only from
// inside code, but its value will be kept
// among different code calls
// 4) In recursive code this variable will be the
// same in every stack frame - a significant scoping difference
}
// a "local" function; can be seen only inside file1.c
static void code2(void)
{
v = v * 1.02; // update global v
// ...
}
|
http://rosettacode.org/wiki/Scope_modifiers
|
Scope modifiers
|
Most programming languages offer support for subroutines.
When execution changes between subroutines, different sets of variables and functions ("scopes") are available to the program.
Frequently these sets are defined by the placement of the variable and function declarations ("static scoping" or "lexical scoping").
These sets may also be defined by special modifiers to the variable and function declarations.
Show the different scope modifiers available in your language and briefly explain how they change the scope of their variable or function.
If your language has no scope modifiers, note it.
|
#C.23
|
C#
|
public //visible to anything.
protected //visible to current class and to derived classes.
internal //visible to anything inside the same assembly (.dll/.exe).
protected internal //visible to anything inside the same assembly and also to derived classes outside the assembly.
private //visible only to the current class.
//C# 7.2 adds:
private protected //visible to current class and to derived classes inside the same assembly.
// | | subclass | other class || subclass | other class
//Modifier | class | in same assembly | in same assembly || outside assembly | outside assembly
//-------------------------------------------------------------------------------------------------------
//public | Yes | Yes | Yes || Yes | Yes
//protected internal | Yes | Yes | Yes || Yes | No
//protected | Yes | Yes | No || Yes | No
//internal | Yes | Yes | Yes || No | No
//private | Yes | No | No || No | No
// C# 7.2:
//private protected | Yes | Yes | No || No | No
|
http://rosettacode.org/wiki/Secure_temporary_file
|
Secure temporary file
|
Task
Create a temporary file, securely and exclusively (opening it such that there are no possible race conditions).
It's fine assuming local filesystem semantics (NFS or other networking filesystems can have signficantly more complicated semantics for satisfying the "no race conditions" criteria).
The function should automatically resolve name collisions and should only fail in cases where permission is denied, the filesystem is read-only or full, or similar conditions exist (returning an error or raising an exception as appropriate to the language/environment).
|
#Groovy
|
Groovy
|
def file = File.createTempFile( "xxx", ".txt" )
// There is no requirement in the instructions to delete the file.
//file.deleteOnExit()
println file
|
http://rosettacode.org/wiki/Secure_temporary_file
|
Secure temporary file
|
Task
Create a temporary file, securely and exclusively (opening it such that there are no possible race conditions).
It's fine assuming local filesystem semantics (NFS or other networking filesystems can have signficantly more complicated semantics for satisfying the "no race conditions" criteria).
The function should automatically resolve name collisions and should only fail in cases where permission is denied, the filesystem is read-only or full, or similar conditions exist (returning an error or raising an exception as appropriate to the language/environment).
|
#Haskell
|
Haskell
|
import System.IO
main = do (pathOfTempFile, h) <- openTempFile "." "prefix.suffix" -- first argument is path to directory where you want to put it
-- do stuff with it here; "h" is the Handle to the opened file
return ()
|
http://rosettacode.org/wiki/Secure_temporary_file
|
Secure temporary file
|
Task
Create a temporary file, securely and exclusively (opening it such that there are no possible race conditions).
It's fine assuming local filesystem semantics (NFS or other networking filesystems can have signficantly more complicated semantics for satisfying the "no race conditions" criteria).
The function should automatically resolve name collisions and should only fail in cases where permission is denied, the filesystem is read-only or full, or similar conditions exist (returning an error or raising an exception as appropriate to the language/environment).
|
#HicEst
|
HicEst
|
! The "scratch" option opens a file exclusively for the current process.
! A scratch file is automatically deleted upon process termination.
OPEN( FIle='TemporaryAndExclusive', SCRatch, IOStat=ErrNr)
WRITE(FIle='TemporaryAndExclusive') "something"
WRITE(FIle='TemporaryAndExclusive', CLoSe=1) ! explicit "close" deletes file
! Without "scratch" access can be controlled by "denyread", "denywrite", "denyreadwrite" options.
OPEN( FIle='DenyForOthers', DenyREAdWRIte, IOStat=ErrNr)
WRITE(FIle='DenyForOthers') "something"
WRITE(FIle='DenyForOthers', DELETE=1)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.