Suggestion: Range as Number type

When defining a type one can specify multiple numbers separated by |.
type TTerminalColors = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15;

Allow to specify number types as ranges, instead of listing each number:
type TTerminalColors = 0..15;
type TRgbColorComponent = 0..255;
type TUInt = 0..4294967295;

Maybe use .. for integers and ... for floats.
interface Math {
  random(): 0...1
}

type RandomDice = 1..6;

const roll: RandomDice = Math.floor(Math.random() * 6);
// Error: -------------------------^ Maybe use Math.ceil()?

This idea can be expanded to characters, e.g. "b" .. "d" would be "b" | "c" | "d". It would be easier to specify character sets.

I think this can be expanded and use syntax like and semantics Haskell ranges.

Syntax
Desugared

type U = (e1..e3)
type U = | e1 | e1+1 | e1+2 | ...e3 |  The union is never if e1 > e3

type U2 = (e1, e2..e3)
type U2 = | e1 | e1+i | e1+2i | ...e3 |, where the increment, i, is e2-e1. If the increment is positive or zero, the union terminates when the next element would be greater than e3; the union is never if e1 > e3. If the increment is negative, the union terminates when the next element would be less than e3; the union is never if e1 < e3.

@panuhorsmalahti What if you specify "bb".."dd"?

@streamich

Maybe use .. for integers and ... for floats.

I really like the idea of generating integral types like this, but I don't see how floating point values could work.

@aluanhaddad Say probability:
type TProbability = 0.0...1.0;

@streamich so that type has a theoretically infinite number of possible inhabitants?

@aluanhaddad actually it would be far from infinite in IEEE floating point. It would have 1,065,353,215 inhabitants by my calculations.

0.0...1.0?  JS uses IEEE double, that's 53 bits of dynamic range.  If that were to be supported, ranges would have to be a first class type, desugaring that to a union would be beyond impractical.

@jcready indeed but, as @fatcerberus points out, realizing it as a union type would be prohibitively expansive.
What I was getting at, in a roundabout manner, was that this would introduce some notion of discrete vs. continuous types into the language.

realizing it as a union type would be prohibitively expansive.

@aluanhaddad Yes, but even specifying an unsigned integer as a union would be very expensive:
type TUInt = 0..4294967295;

This really needs some compelling use cases, because the implementation of unions today is completely unsuited to realizing unions this large. Something that would happen if you wrote something like this
type UInt = 0..4294967295;
var x: UInt = ......;
if (x !== 4) {
  x;
}

would be the instantiation of the union type 0 | 1 | 2 | 3 | 5 | 6 | 7 | ... .

Perhaps it could only work against number literals. Any non-literal number values would have to be explicitly refined with greater/less than comparisons before being considered to inhabit the range. Integer ranges would also require an additional Number.isInteger() check. This should eliminate the need to generate actual union types.

@RyanCavanaugh Subtraction types? 🌞

Negative types, anything but a string:
type NotAString = !string;

@streamich subtraction types are covered by #4183

My use case is: I'd like to type a parameter as 0 or a positive number (it's an array index).

@RoyTinker I definitely think this would be cool but I don't know if that use case helps the argument.
An array is just an object and the ascending indexes are just a convention.
let a = [];
for (let i = 0; i > -10; i -= 1) {
  a[i] = Math.random() * 10;
}

so you ultimately still have to perform the same check
function withItem<T>(items: T[], index: number, f: (x: T) => void) {
  if (items[index]) {
    f(items[index]);
  }
}

It would be quite useful for defining types like second, minute, hour, day, month, etc.

@Frikki those units are on a confined enough interval that it is practical and prohibitively difficult to write them by hand.
type hour =
   | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12
   | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23;

@aluanhaddad But no unsigned int:
type UInt = 0..4294967295;

meh, how about a type like this:
type Factorial<N extends number> = N > 2 ? <N - 1> * N : N;
type F1: Factorial<1>; // 1
type F2: Factorial<2>; // 1 | 2
type F3: Factorial<3>; // 1 | 2 | 6
type FN: Factorial<number>; // 1 | 2 | 6 | ...

Using * operator from @aleksey-bykov comment:
type char = 0..255;
type word = 2 * char;
type int = 2 * word;
type bigint = 2 * int;

@streamich Doubling the bit count does not correspond to multiplication by two, it's more like exponentation with 2 as the the exponent. It's still not correct, though, as you should not raise the upper bound, but the encodable numbers count. All in all, that's not a good definition.

@streamich, a couple of comments:

Using  the termschar, word, etc. could be confusing since folks from other languages might not realize the difference between static definition and runtime behavior.
Your proposed syntax doesn't take the lower bound into account -- what if it is non-zero?
I'd be wary about co-opting the exponentiation operator for use in an ambient/type context, since it's already been added to ES2016.

let's just make the type system turing complete and enjoy the halt problem we hit Ctrl + Shift + B

@aleksey-bykov surely you remember this fine issue 😀

@aluanhaddad

those units [time units] are on a confined enough interval that it is practical and prohibitively difficult to write them by hand.

Now, do that with milliseconds :wink:

Is this issue dead?

@Palid it is tagged with [Needs Proposal] so I doubt that.
As much fun as the discussion has been, most of us have failed to provide compelling real world use cases.
See https://github.com/Microsoft/TypeScript/issues/15480#issuecomment-324152700

Use cases:

You can define precise int types such that subset of  TypeScript can be compiled to WebAssembly or some other target.

Another use case is UInt8Array, Int8Array, Uint16Array, etc.., when you read or write data from those TypeScript could check for errors.

const ab = new ArrayBuffer(1e3);
const uint8 = new UInt8Array(ab);

uint8[0] = 0xFFFFFFFF; // TSError: Number too big!

I've mentioned a few use cases in my OP.

If you implement this, TypeScript community will come up millions of use cases.

I've got a really funny usecase, that actually may be closer to anything else proposed here.
API takes an integer between some range (in my case 5-30) and we need to implement an SDK for that.
Manually writing underneath is tedious (though it can be kinda automated) for 25values, but what about hundreds or thousands?
type X = 5 | 6 | 7 | 8 | 9 | 10 ... | 30

@Palid That's the best and most straightforward case I've seen for this feature.
If a range like 5..30 was defined as syntactic sugar for 5 | 6 | 7 ...  | 30 (or "functions identically") I bet this would be an easy win. Here it would stand for a discrete range of integers.
Perhaps a "continuous range" (as opposed to discrete) could be notated by using a number with a period -- 5.0..30.0.

I was actually considering looking at Typescript to implement typing protection for
https://www.npmjs.com/package/memory-efficient-object
Having range typing would make it easier to spot potential memory overflow at type checking time

Seem like we don't really need union expansion but more like inclusive/exclusive range definition that just compare the range
type TTerminalColors = int & [0,15];
// int && v >= 0 && v <= 15

This would be very useful when controlling motors (using Johnny-Five, for instance), where the speed ranges from 0-255.

Another use case: I am implementing a Canvas-based drawing program using TypeScript and would like to have type checks on opacity (which must be a number between 0.0 and 1.0).

Just thinking... to implement this properly, you’d have to really go all out:

support runtime type guard functions
type narrowing for conditions like x <= 10 and x == 5
support for string | number ranges (since x == 5 is true for x === "5") in addition to number-only ranges
probably even support for a new int type (which would be a subtype of number), and support for int-only ranges

Great idea, but this would be a lot to cover.

Maybe we don't need runtime type guard. Instead we could make compile time guard all the way up
This would need elaborate branch prediction instead
Suppose
function A(color: TTerminalColors):void
{

}

A(15); // OK
var x = 15;
A(x); // OK

function B(value: int) : void
{
    A(value); // ERROR!!!
    if(value >= 0 && value <= 15)
        A(value); // OK, because we check that it is in the range of TTerminalColors
}

function C(value: int) : void
{
    if(value < 0)
        value = 0;
    if(value > 15)
        value = 15;

    A(value); // OK, because is clamped
}

function D(value: TTerminalColors) : void
{
    A(value); // OK, because everywhere we use D() we also need to do the same check
}

My use case:
export const ajax: (config: AjaxOptions) => void;

type Callback = Success | Error;
type Success = (data: any, statusText: string, xhr: XMLHttpRequest) => void;
type Error = (xhr: XMLHttpRequest, statusText: string) => void;

interface AjaxOptions {
  // ...
  statusCode: { [code: number]: Callback | Callback[] },
  // ...
}

It would be nice to be able to restrict the keys in the statusCode option such that at compile-time it can be determined if a status code corresponds to a success or error code:
interface AjaxOptions {
  // ...
  statusCode: {
    200..299: Success,
    400..599: Error
  },
  // ...
}

Another use case would be to type check you database records:

https://github.com/SweetIQ/schemats

Another use case would be type checking Lat/Lon values.

This could be covered by the general validation mechanism of #8665 (not sure why it was closed as a duplicate):
type TTerminalColors (n: number) => Math.floor(n) == n && n >= 0 && n <= 15;
type TRgbColorComponent (n: number) => Math.floor(n) == n && n >= 0 && n <= 255;
type TUInt (n: number) => n >= 0 && n <= 0..4294967295;

Or taken with #4639:
type TTerminalColors (n: uint) => n >= 0 && n <= 15;
type TRgbColorComponent (n: uint) => n >= 0 && n <= 255;

My use case is global coordinates. I want to type out latitude and longitude so they only fall within the specific ranges (0-90 and 0 to 180).

My use case is the implementation of arrays of fixed size where size is a parameter.
For example, I want to define a type for arrays of strings of length 2.
let d: FixedSizeArray<2, string>;
d = [ 'a', 'b' ]; // ok
d = [ 'a' ]; // type error
d = [ 'a', 'b', 'c' ]; // type error
d[0] = 'a1'; // ok
d[1] = 'b1'; // ok
d[2] = 'c1' // type error

With the current version of TS it is possible to define something very close to the "spec" above. The main problem is member access: e.g. d[1] = 'b1'  returns a type error even if it is correct. In order to avoid the error the list of all legal indices must be compiled by hand in the definition of FixedSizeArray, which is boring.
If we had a range operator similar to keyof operator, the following type definition should solve the problem.
type FixedSizeArray<U extends number, T> = {
    [k in range(U)]: T;
} & { length: U };

Where range(N) is a shortcut for range(0,N).
Given numerical literals (naturals) M, N with M < N,
type r = range(M, N);

is equivalent to
type r = M | M+1 | ... | N-1

What might be more general is if we could have the ability to define predicate lambdas and use them as types. Example:
predicate mypredicate = (x) => x > 1 && x < 10
let x: mypredicate = 11 // not ok
let x: mypredicate = 5 // ok

A pro would be low syntax complexity as Lambdas are already available all we need is the ability to use them as types, type checking is typescript specific anyway (keeping in mind the "superset to Javascript" philosophy)
A con is that complexity of the predicate will determine the performance of tooling to provide feedback.
Ensuring a number/character belongs to an arithmetic progressions could be a good common use-case:
// a is the starting element d is the difference between two elements and L is the last element
const belongsToAP = (a, d, L) => {
  return (x) => {
    if(x < a || x > L) return false
    let n = ((x-a)/d) + 1
    if(Number.isInteger(n)) return true
    return false
  }
}

this would allow us to do type checks like:
predicate belongsToMyAP = belongsToAP(1,1, 10)
let x : belongsToMyAP = 5 // ok
let y : belongsToMyAP = 7.2 // not ok

This can be expanded to characters as well.

@Kasahs Something similar to this has already been proposed in #8665.

Throwing my lot in with the "reflecting an API" use-case. A REST endpoint I'm writing a wrapper function for takes an integer in the range 1..1000 as an argument. It generates an error if the number does not satisfy that constraint.

So I'm writing a proposal for numeric ranges and I've run across this issue that I'm not sure how to deal with, so I'm throwing it out there for consideration.
Because the TypeScript compiler is written in TypeScript, it's possible to leverage the properties of the numeric operators to mutate range types.
// Syntax: x..y for an inclusive integer range.

let x: 0..10 = randomNumber(0, 10);
let y = x + 2; // Can deduce that y: 2..12.

This is fine when assigning to a new variable, but what about mutation?
let x: 0..10 = randomNumber(0, 10);
x += 2; // Error: 2..12 is not assignable to type 0..10 (upper bound is out of range).

This error would be techincally correct, but in practice it would be incredibly annoying to deal with. If we want to mutate a variable returned by a function with a range return type, we would always have to add a type assertion.
let x = randomNumber(0, 10) as number; // If randomNumber doesn't return a type assigable to number
// this will be an error, but it would still be annoying to have to sprinkle "as number"
// expressions everywhere.

And if we ignore it, we get the following unsoundness:
function logNumber0To10 (n: 0..10): void {
    console.log(n);
}

let x: 0..10 = randomNumber(0, 10);
x += 2; // Because we're ignoring mutations, x: 0..10, but the runtime value could be 11 or 12,
// which are outside the specified range...
logNumber0To10(x); // ...which means we lose type safety on this call.

A fix for this would be the ability to change the type of a variable after it's declared, so example 2 would just change the type of x to 2..12; but my first instinct is that would introduce too much overhead in the compiler and be confusing to users.
Any thoughts on how to deal with the above?

what about mutation?

Why should mutation be different than any other assignment?

Here is my humble attempt at a proposal. This proposal also requests that other types be added.

Infinity type

Only has the value Infinity

-Infinity type

Only has the value -Infinity

NaN type

Only has the value NaN

double type

All number values in the range [-Number.MAX_VALUE, Number.MAX_VALUE] or, [-1.7976931348623157e+308, 1.7976931348623157e+308]

number is just Infinity|-Infinity|NaN|double
int type

A sub-type of double
All number values x in the range [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER] or [-9007199254740991,<PHONE_NUMBER>740991] and Math.floor(x) === x

So, 3 and 3.0 would values of be an int type

"Finite literal" type

Examples are 1, 3.141, 45
May be sub-types of double or int

The "GtEq" type denoted (>= x)

Where x is a finite literal, Infinity, or -Infinity

The "LtEq" type denoted (<= x)

Where x is a finite literal, Infinity, or -Infinity

The "Gt" type denoted (> x)

Where x is a finite literal, Infinity, or -Infinity

The "Lt" type denoted (< x)

Where x is a finite literal, Infinity, or -Infinity

GtEq type; (>= x)

(>= Infinity) = Infinity
(>= -Infinity) = -Infinity|double|Infinity
Infinity is a sub-type of (>= [finite-literal])
(>= [finite-literal])  is a sub-type of double|Infinity

Gt type; (> x)

(> Infinity) = NaN
(> -Infinity) = double|Infinity
Infinity is a sub-type of (> [finite-literal])
(> [finite-literal])  is a sub-type of double|Infinity

LtEq type; (<= x)

(<= Infinity) = -Infinity|double|Infinity
(<= -Infinity) = -Infinity
-Infinity is a sub-type of (<= [finite-literal])
(<= [finite-literal])  is a sub-type of -Infinity|double

Lt type; (< x)

(< Infinity) = -Infinity|double
(< -Infinity) = NaN
-Infinity is a sub-type of (< [finite-literal])
(< [finite-literal])  is a sub-type of -Infinity|double

Range types
Note that while we can write things like (>= Infinity), the resulting type is not a range type; they're just aliases for other types.
A range type is one of,

(>= [finite-literal])
(> [finite-literal])
(<= [finite-literal])
(< [finite-literal])

Union GtEq/Gt types
When taking the union of two GtEq/Gt types, the type with "more" values is the result,

(>= [finite-literal-A]) | (>= [finite-literal-B]) = ...

If [finite-literal-A] >= [finite-literal-B], then the result is (>= [finite-literal-B])
Else, the result is (>= [finite-literal-A])
e.g. (>= 3) | (>= 5.5) = (>= 3) because (>= 3) is a super-type of (>= 5.5)

(>= [finite-literal-A]) | (> [finite-literal-B]) = ...

If [finite-literal-A] == [finite-literal-B], then the result is (>= [finite-literal-A])
If [finite-literal-A] > [finite-literal-B], then the result is (> [finite-literal-B])
Else, the result is (>= [finite-literal-A])

(> [finite-literal-A]) | (> [finite-literal-B]) = ...

If [finite-literal-A] >= [finite-literal-B], then the result is (> [finite-literal-B])
Else, the result is (> [finite-literal-A])
e.g. (> 3) | (> 5.5) = (> 3) because (> 3) is a super-type of (> 5.5)

Union LtEq/Lt types
When taking the union of two LtEq/Lt types, the type with "more" values is the result,

(<= [finite-literal-A]) | (<= [finite-literal-B]) = ...

If [finite-literal-A] <= [finite-literal-B], then the result is (<= [finite-literal-B])
Else, the result is (<= [finite-literal-A])
e.g. (<= 3) | (<= 5.5) = (<= 5.5) because (<= 5.5) is a super-type of (<= 3)

(<= [finite-literal-A]) | (< [finite-literal-B]) = ...

If [finite-literal-A] == [finite-literal-B], then the result is (<= [finite-literal-A])
If [finite-literal-A] < [finite-literal-B], then the result is (< [finite-literal-B])
Else, the result is (<= [finite-literal-A])

(< [finite-literal-A]) | (< [finite-literal-B]) = ...

If [finite-literal-A] <= [finite-literal-B], then the result is (< [finite-literal-B])
Else, the result is (< [finite-literal-A])
e.g. (< 3) | (< 5.5) = (< 5.5) because (< 5.5) is a super-type of (< 3)

Intersection GtEq/Gt types
When taking the intersection of two GtEq/Gt types, the type with "fewer" values is the result,

(>= [finite-literal-A]) & (>= [finite-literal-B]) = ...

If [finite-literal-A] >= [finite-literal-B], then the result is (>= [finite-literal-A])
Else, the result is (>= [finite-literal-B])
e.g. (>= 3) & (>= 5.5) = (>= 5.5) because (>= 5.5) is a sub-type of (>= 3)

(>= [finite-literal-A]) & (> [finite-literal-B]) = ...

If [finite-literal-A] == [finite-literal-B], then the result is (> [finite-literal-B])
If [finite-literal-A] > [finite-literal-B], then the result is (>= [finite-literal-A])
Else, the result is (> [finite-literal-B])

(> [finite-literal-A]) & (> [finite-literal-B]) = ...

If [finite-literal-A] >= [finite-literal-B], then the result is (> [finite-literal-A])
Else, the result is (> [finite-literal-B])
e.g. (> 3) & (> 5.5) = (> 5.5) because (> 5.5) is a sub-type of (> 3)

Intersection LtEq/Lt types
When taking the intersection of two LtEq/Lt types, the type with "fewer" values is the result,

(<= [finite-literal-A]) & (<= [finite-literal-B]) = ...

If [finite-literal-A] <= [finite-literal-B], then the result is (<= [finite-literal-A])
Else, the result is (<= [finite-literal-B])
e.g. (<= 3) & (<= 5.5) = (<= 3) because (<= 3) is a sub-type of (<= 5.5)

(<= [finite-literal-A]) & (< [finite-literal-B]) = ...

If [finite-literal-A] == [finite-literal-B], then the result is (< [finite-literal-B])
If [finite-literal-A] < [finite-literal-B], then the result is (<= [finite-literal-A])
Else, the result is (< [finite-literal-B])

(< [finite-literal-A]) & (< [finite-literal-B]) = ...

If [finite-literal-A] <= [finite-literal-B], then the result is (< [finite-literal-A])
Else, the result is (< [finite-literal-B])
e.g. (< 3) & (< 5.5) = (< 3) because (< 3) is a sub-type of (< 5.5)

Use Cases

To statically ensure an integer can fit in a MySQL UNSIGNED INT data type,
//TODO Propose numeric and range sum/subtraction/multiplication/division/mod/exponentiation types?
function insertToDb (x : int & (>= 0) & (<=<PHONE_NUMBER>)) {
    //Insert to database
}

To statically ensure a string is of a given length,
function foo (s : string & { length : int & (>= 1) & (<= 255) }) {
    //Do something with this non-empty string that has up to 255 characters
}

To statically ensure an array-like object has the appropriate length value,
function foo (arr : { length : int & (>= 0) }) {
    //Do something with the array-like object
}

To statically ensure we are only given finite numbers,
function foo (x : double) {
    //`x` is NOT NaN|Infinity|-Infinity
}

To statically ensure array indices exist?
function foo (arr : { [index : int & (>= 0) & (< 10)] : string }) {
    console.log(arr[0]); //OK
    console.log(arr[1]); //OK
    console.log(arr[2]); //OK
    console.log(arr[9]); //OK
    console.log(arr[10]); //Error
}

I would love to propose numeric and range addition/subtraction/multiplication/division/mod/exponentiation types but that seems out-of-scope with this issue

Would it be possible to have compiler did the flow analysis?
Suppose there is this function
function DoSomething(x : int & (>= 0) & (< 10)){
   // DoSomething
}

function WillError(x : int){
    DoSomething(x); // error; x is not >= 0 & < 10
}

function WillNotError(x : int){
    if(x >= 0 && x < 10)
        DoSomething(x); // not error by flow analysis
}

one more use case: i have a number for a function that represents a percentage. i want to limit inputs to being between 0 & 1.

This should have been implemented in the first version of TS. It's ridiculous that this issue is still being overlooked.

I just ran [...Array(256)].map((_,i) => i).join("|") to make my ugliest type definition yet

Nonnegative integers and small numbers are possible:
type ArrayT<T> = T extends (infer P)[] ? P : never;
type A = ArrayT<Range<5, 10>>;//5|6|7|8|9|10

Range:https://github.com/kgtkr/typepark/blob/master/src/list.ts

By "small numbers" you mean without using stage 3 BigInt?

A number that does not get stuck in the compiler's recursion limit

Maybe use .. for integers and ... for floats.

I would say that .. should mean inclusive range and ... exclusive. Just like in e.g. Ruby. See http://rubylearning.com/satishtalim/ruby_ranges.html

I'm not a fan of using a single period to differentiate between inclusive and exclusive ranges

Can I jump in? I think that this feature seen as a single enhancement for type specification is not likely the best way to go here.
type range = 1:2:100

This is how you define a numeric range in many 4gl platforms — specifically matrix-oriented ones.
You do it this way, because a uniform range is conventionally one of the best modelling approaches.
So a sequential range is this:
type sequence = 1:10

If that is not tokenizer friendly, this is not the right priority to focus on here in my opinion. I point this out hoping to not see one solution limit us in getting to the next.

Interesting that you bring up being able to define "step" sizes in a range type.
Beyond just "floating point" (no fixed step size) and "integer" (step size of 1, starts from an integer) ranges, I've never encountered a real life use case for ranges with other step sizes.
So, it's interesting to hear about it being a thing elsewhere. Now, I'll need to learn about 4gl because I've never heard of it before

Can I jump in? I think that this feature seen as a single enhancement for type specification is not likely the best way to go here.
type range = 1:2:Infinity // 1, 3, 5… Infinity

This is how you define a numeric range in many 4gl platforms — specifically matrix-oriented ones.
You do it this way, because a uniform range is conventionally one of the best modelling approaches.
So a sequential range is this:
type decmials = 1:10 // like 1 .. 10 with all decimals in between

And if just the integers:
type integers = 1:1:10 // 1, 2, 3, 4, 5, 6, 7, 8, 10

// OR

type integers = number.integers<1:10>

If we want to play around with syntax:
type something = 1::10 // whatever use cases need today

If that is not tokenizer friendly, this is not the right blocking priority to focus on here in my opinion. I point this out hoping to not see one solution limit us in getting to the next.

edit: What I fail to account for is the inclusiveness aspect — and here we must wonder if we are doing enough due diligence to understand why that was not an issue when people solved so many problems relying on uniform ranges that are implicitly inclusive of every number except when the increment did not exactly align with the end of the range.

Hmm looks like the way it's handled in Haskell. I think this is good. Generators will allow for lazy evaluation as well.

It's not like you can't have lazy evaluation with any other syntax =x

Interesting that you bring up being able to define "step" sizes in a range type.

I think of a range as start, end and increment. So if the increment rounds off to exactly the end then it is inclusive of that. Array indices and lengths as range functions are can be an array 0:1:9 has 10 index steps (length). So the range here can conveniently be integer & 0:9 for a type system that can more easily infer from combining those two expressions.
4GL is really a generic label, for me that was mostly MatLab

My point was that having only inclusive ranges would make using it in generics harder (unless you implement the hack-y type-level math operations).
Because, instead of only having "length" as a type parameter, you now need length and max index. And max index must equal length-1.
And, again, you can't actually check that is the case unless you implement those hack-y type level math operations

@AnyhowStep I was thinking of the best way to frame your concern — but maybe it helps to first clarify:
If we put the inclusive-or-not as specifically applicable to any n-1 problem (like this index/count scenario) aside, assuming that was independently solved somehow (just humour the thought), are there other scenarios for which numeric ranges would still require less declarative and/or unconventional syntax to properly describe?
I am getting at those being 2 separate aspects, you need numeric ranges that are conventionally aligned with the expectations of that domain and you also need predicates for index/count types... etc.

Positive numbers only.
declare let x : (> 0);
x = 0.1; //OK
x = 0.0001; //OK
x = 0.00000001; //OK
x = 0; //Error
x = 1; //OK
x = -1; //Error

With inclusive-only ranges,
declare let x : epsilon:epsilon:Infinity; //Where epsilon is some super-small non-zero, positive number

@AnyhowStep I hope you can appreciate that my intent is merely to make sure that if something called "Range as Number type" simply aligns with common expectations to the more conventional user (ie someone moving to TS wondering why the range emphasizes inclusivity over interval)
I honestly think that use cases should always drive features, and think that the issues relating to index and length are ones that many of us sometimes really miss. So I simply want to address that problem just under the correct label — is it a number type thing or an indexed type thing? I don't know the answer exactly, but I am hesitant to think that solving it as a number type thing will not inadvertently create far more problems for number type users not sharing the same understanding of these aspects.
So where else would fixing such a problem make sense to everyone is all I am wondering at this point, thoughts?

I'm dealing with an API that passes byte arrays, so I'd like to define a byte type:
type byte = 0x00..0xFF
type bytes = byte[]

This would also be useful when working with Uint8Array.

If you're like me and you're impatient about getting range types you can actually use at the moment, here's a code snippet of range types in action.
TL;DR,
Range types can work now
interface CompileError<_ErrorMessageT> {
    readonly __compileError : never;
}
///////////////////////////////////////////////
type PopFront<TupleT extends any[]> = (
    ((...tuple : TupleT) => void) extends ((head : any, ...tail : infer TailT) => void) ?
    TailT :
    never
);
type PushFront<TailT extends any[], FrontT> = (
    ((front : FrontT, ...tail : TailT) => void) extends ((...tuple : infer TupleT) => void) ?
    TupleT :
    never
);
type LeftPadImpl<TupleT extends any[], ElementT extends any, LengthT extends number> = {
    0 : TupleT,
    1 : LeftPad<PushFront<TupleT, ElementT>, ElementT, LengthT>
}[
    TupleT["length"] extends LengthT ?
    0 :
    1
];
type LeftPad<TupleT extends any[], ElementT extends any, LengthT extends number> = (
    LeftPadImpl<TupleT, ElementT, LengthT> extends infer X ?
    (
        X extends any[] ?
        X :
        never
    ) :
    never
);
type LongerTuple<A extends any[], B extends any[]> = (
    keyof A extends keyof B ?
    B :
    A
);

///////////////////////////////////////////////////////
type Digit = 0|1|2|3|4|5|6|7|8|9;
/**
 * A non-empty tuple of digits
 */
type NaturalNumber = Digit[];

/**
 * 6 - 1 = 5
 */
type SubOne<D extends Digit> = {
    0 : never,
    1 : 0,
    2 : 1,
    3 : 2,
    4 : 3,
    5 : 4,
    6 : 5,
    7 : 6,
    8 : 7,
    9 : 8,
}[D];

type LtDigit<A extends Digit, B extends Digit> = {
    0 : (
        B extends 0 ?
        false :
        true
    ),
    1 : false,
    2 : LtDigit<SubOne<A>, SubOne<B>>
}[
    A extends 0 ?
    0 :
    B extends 0 ?
    1 :
    2
];

//false
type ltDigit_0 = LtDigit<3, 3>;
//true
type ltDigit_1 = LtDigit<3, 4>;
//false
type ltDigit_2 = LtDigit<5, 2>;

/**
 * + Assumes `A` and `B` have the same length.
 * + Assumes `A` and `B` **ARE NOT** reversed.
 *   So, `A[0]` is actually the **FIRST** digit of the number.
 */
type LtEqNaturalNumberImpl<
    A extends NaturalNumber,
    B extends NaturalNumber
> = {
    0 : true,
    1 : (
        LtDigit<A[0], B[0]> extends true ?
        true :
        A[0] extends B[0] ?
        LtEqNaturalNumberImpl<
            PopFront<A>,
            PopFront<B>
        > :
        false
    ),
    2 : never
}[
    A["length"] extends 0 ?
    0 :
    number extends A["length"] ?
    2 :
    1
];
type LtEqNaturalNumber<
    A extends NaturalNumber,
    B extends NaturalNumber
> = (
    LtEqNaturalNumberImpl<
        LeftPad<A, 0, LongerTuple<A, B>["length"]>,
        LeftPad<B, 0, LongerTuple<A, B>["length"]>
    > extends infer X ?
    (
        X extends boolean ?
        X :
        never
    ) :
    never
);

//false
type ltEqNaturalNumber_0 = LtEqNaturalNumber<
    [1],
    [0]
>;
//true
type ltEqNaturalNumber_1 = LtEqNaturalNumber<
    [5,2,3],
    [4,8,9,2,3]
>;
//false
type ltEqNaturalNumber_2 = LtEqNaturalNumber<
    [4,8,9,2,3],
    [5,2,3]
>;
//true
type ltEqNaturalNumber_3 = LtEqNaturalNumber<
    [5,2,3],
    [5,2,3]
>;
//true
type ltEqNaturalNumber_4 = LtEqNaturalNumber<
    [5,2,2],
    [5,2,3]
>;
//false
type ltEqNaturalNumber_5 = LtEqNaturalNumber<
    [5,1],
    [2,5]
>;
//false
type ltEqNaturalNumber_6 = LtEqNaturalNumber<
    [2,5,7],
    [2,5,6]
>;

type RangeLt<N extends NaturalNumber> = (
    number &
    {
        readonly __rangeLt : N|undefined;
    }
);
type StringLengthLt<N extends NaturalNumber> = (
    string & { length : RangeLt<N> }
);

type AssertStringLengthLt<S extends StringLengthLt<NaturalNumber>, N extends NaturalNumber> = (
    LtEqNaturalNumber<
        Exclude<S["length"]["__rangeLt"], undefined>,
        N
    > extends true ?
    S :
    CompileError<[
        "Expected string of length less than",
        N,
        "received",
        Exclude<S["length"]["__rangeLt"], undefined>
    ]>
);
/**
 * String of length less than 256
 */
type StringLt256 = string & { length : RangeLt<[2,5,6]> };
/**
 * String of length less than 512
 */
type StringLt512 = string & { length : RangeLt<[5,1,2]> };

declare function foo<S extends StringLengthLt<NaturalNumber>> (
    s : AssertStringLengthLt<S, [2,5,6]>
) : void;

declare const str256 : StringLt256;
declare const str512 : StringLt512;

foo(str256); //OK!
foo(str512); //Error

declare function makeLengthRangeLtGuard<N extends NaturalNumber> (...n : N) : (
    (x : string) => x is StringLengthLt<N>
);

if (makeLengthRangeLtGuard(2,5,6)(str512)) {
    foo(str512); //OK!
}

declare const blah : string;
foo(blah); //Error

if (makeLengthRangeLtGuard(2,5,5)(blah)) {
    foo(blah); //OK!
}

if (makeLengthRangeLtGuard(2,5,6)(blah)) {
    foo(blah); //OK!
}

if (makeLengthRangeLtGuard(2,5,7)(blah)) {
    foo(blah); //Error
}

Playground

Using type-level addition, you can have, str512 + str512 and get a str1024
https://github.com/microsoft/TypeScript/issues/14833#issuecomment-513106939

Looking at @AnyhowStep solution I think I have better temporary solution. Remember type guards?:
/**
 * Just some interfaces
 */
interface Foo {
    foo: number;
    common: string;
}

interface Bar {
    bar: number;
    common: string;
}

/**
 * User Defined Type Guard!
 */
function isFoo(arg: any): arg is Foo {
    return arg.foo !== undefined;
}

/**
 * Sample usage of the User Defined Type Guard
 */
function doStuff(arg: Foo | Bar) {
    if (isFoo(arg)) {
        console.log(arg.foo); // OK
        console.log(arg.bar); // Error!
    }
    else {
        console.log(arg.foo); // Error!
        console.log(arg.bar); // OK
    }
}

doStuff({ foo: 123, common: '123' });
doStuff({ bar: 123, common: '123' });

So take a look at following code:
"use strict";
class NumberRange {
    constructor(min, max) {
        this.isInRange = (num, explicit = false) => {
            let inRange = false;
            if (explicit === false) {
                inRange = num <= this.max && num >= this.min;
            }
            else {
                inRange = num < this.max && num > this.min;
            }
            return inRange;
        };
        if (min > max) {
            throw new RangeError(`min value (${min}) is greater than max value (${max})`);
        }
        else {
            this.min = min;
            this.max = max;
        }
    }
}
const testRange = new NumberRange(0, 12);
if(testRange.isInRange(13)){
	console.log('yay')
}else {
  console.log('nope')
}

The problem here is that you can't do this,
declare const a : number;
declare let b : (>= 5);
const testRange = new NumberRange(12, 20);
if (testRange.isInRange(a)) {
  b = a; //ok
} else {
  b = a; //compile error
}

You may achieve this with current Typescript version:
// internal helper types
type IncrementLength<A extends Array<any>> = ((x: any, ...xs: A) => void) extends ((...a: infer X) => void) ? X : never;
type EnumerateRecursive<A extends Array<any>, N extends number> = A['length'] extends infer X ? (X | { 0: never, 1: EnumerateRecursive<IncrementLength<A>, N> }[X extends N ? 0 : 1]) : never;

// actual utility types
export type Enumerate<N extends number> = EnumerateRecursive<[], N>;
export type Range<FROM extends number, TO extends number> = Exclude<Enumerate<TO>, Enumerate<FROM> | TO> | FROM;

// usage examples:
type E1 = Enumerate<3>; // hover E1: type E1 = 0 | 1 | 3 | 2
type E2 = Enumerate<10>;  // hover E2: type E2 = 0 | 1 | 3 | 2 | 10 | 4 | 5 | 6 | 7 | 8 | 9

type R1 = Range<0, 5>; // hover R1: type R1 = 0 | 1 | 3 | 2 | 4
type R2 = Range<5, 11>; // hover R2: type R2 = 10 | 5 | 6 | 7 | 8 | 9

I followed the convention of having inclusive start and exclusive end indexes, but You may adjust it to Your needs.
The vs code hover hints in comments.
Notice that the numbers in the hover hints are randomly sorted.

Sadly it only works up to around 10 elements :(

@Shinigami92
With this approach, Enumerate handles up to 40.
This is still a limitation, but may be not so harsh in practice.
type GrowRangeStep<A extends Array<unknown>> = A['length'] extends infer T ? ((t: T, ...a: A) => void) extends ((...x: infer X) => void) ? X : never : never;
type GrowRange<A extends Array<unknown>, N extends number> = { 0: A, 1: GrowRange<GrowRangeStep<A>, N> }[N extends A['length'] ? 0 : 1];
type RangeArray<N extends number> = GrowRange<[], N>;
export type Enumerate<N extends number> = RangeArray<N> extends (infer E)[] ? E : never;
export type Range<FROM extends number, TO extends number> = Exclude<Enumerate<TO>, Enumerate<FROM>>;

type E1 = Enumerate<40>;
type E2 = Enumerate<10>;
type R1 = Range<0, 5>;
type R2 = Range<5, 34>;

@Shinigami92
With this approach, Enumerate handles up to 40.
This is still a limitation, but may be not so harsh in practice.
type PrependNextNum<A extends Array<unknown>> = A['length'] extends infer T ? ((t: T, ...a: A) => void) extends ((...x: infer X) => void) ? X : never : never;
type EnumerateInternal<A extends Array<unknown>, N extends number> = { 0: A, 1: EnumerateInternal<PrependNextNum<A>, N> }[N extends A['length'] ? 0 : 1];
export type Enumerate<N extends number> = EnumerateInternal<[], N> extends (infer E)[] ? E : never;
export type Range<FROM extends number, TO extends number> = Exclude<Enumerate<TO>, Enumerate<FROM>>;

type E1 = Enumerate<40>;
type E2 = Enumerate<10>;
type R1 = Range<0, 5>;
type R2 = Range<5, 34>;

And now it happened to be sorted somehow magically ;).

Typical use cases for me use ranges like [1, 255], [1, 2048], [1, 4096], [20, 80], etc. Creating large union types can make TS freak out/slow down. But those solutions definitely work for "smaller" ranges

@AnyhowStep
Knowing that recursion count is a limit, we should find the way to perform number division/multiplication by two in single non-recursive operation inside type definition to achieve these ranges.

Performance is still an issue. I've had to cull useful union types from large apps before for this reason - whilst it might be an interesting exercise, it's definitely not a solution.

There's still not pefect solutions I guess?

I hope this can be done as following in general way (but hard though).
type X => (number < 50 && number > 60 || number = 70) || (string.startsWith("+")

(i.e. normal javascript statement / function can be used here, except the variables are replaced by type)
In my understanding, modern language = normal logic + meta logic, where meta logic = code checking + code generation. A lot of works are just trying to merge meta logic syntax in an elegant way.

Maybe we can somehow assume range types not to be some kind of sugar, but to be core concept?
// number literal extend `number` despite the fact
// that `number` is not union of all number literals
type NumberLiteralIsNumber = 5 extends number ? true : false // true

// so if we will define Range (with some non-existing syntax which is clearly should be done in lib internals)
type Range<MIN extends number, MAX extends number> = MAX > MIN ? 5 and 2NaN : MAX === MIN ? MAX : MIN..MAX

// and assume that `number` is Range<-Infinity, +Infinity>
type NumberIsInfinitRange = number extends Range<-Infinity, +Infinity> ?
    Range<-Infinity, +Infinity> extends number ? true : false :
    false // true

// following things will be true
type AnyRangeIsNumber<T extends number, K extends Number> =
    Range<T, K> extends number ? true : false // true
type NestedRangeIsNumber<T extends number, K extends number, S extends number> =
    Range<T, Range<K, S>> extends number ? true : false // true

To complete this we need to declare behaviour on some cases

Range<T, T> === T by definition
Range<5, 1> === NaN by definition
Range<NaN, T> === Range<T, NaN> === NaN as such value cannot exist
Range<1 | 2, 5> === Range<2, 5> the posibility of larger number as first type  parameter restricts the range to be shorter
Range<1, 4 | 5> === Range<1, 4> the posibility of lower number as second type parameter restricts the range to be shorter
1.5 extends Range<1, 2> should be true by definition
Range<Range<A, B>, C> === NaN extends Range<A, B> ? NaN : Range<B, C> follows from 5 and 3
Range<A, Range<B, C>> === NaN extends Range<B, C> ? NaN : Range<A, B> follows from 6 and 3

And a little about Ranges inside Ranges:
type RangeIsInsideRange<T extends Range<any, any>, K extends Range<any, any>> =
    T extends Range<infer A, infer B>
        ? K extends Range<infer C, infer D>
            ? NaN extends Range<A, C>
                ? false
                : NaN extends Range<B, D>
                    ? false
                    : true
            : never
        : never

Range subtypes could even be defined in a generic way, as a type level comparison function (a: T, b: T) => '<' | '=' | '>'.
...is there a proposal for using regular JS functions at type level?

There's no proposal, per sey, but I have written a quick prototype before. There are large concerns over IDE performance and input sanitization, unfortunately.

@yudinns problem is Range exists at least at this name, so it may be confusing, see: https://developer.mozilla.org/en-US/docs/Web/API/range also I miss the functionality where I can define number series like <1, n+2> - step 2  starting from 1 or more complicated equation.

This TC39 proposal will probably reach stage 4 before this gets implemented.
The ticket is 3 years old.

https://github.com/Microsoft/TypeScript/issues/6579

It would also be cool if you could do something like number in range e.g. if 1 in 1..2 or inclusive if 1 in 1..=2 rust handles it well https://doc.rust-lang.org/reference/expressions/range-expr.html

Don't python and rust already have a typed range feature?
Can we just reimplement existing solutions in other languages instead of reinventing the wheel or making it extra generic with strings, floats etc while the main purpose and biggest usecase are number ranges. We can add more later when needed

I have encountered this on more than one occasion and came here search for a way to define a type that is a fraction between 0...1 - this is being discussed on https://news.ycombinator.com/item?id=24362658#24372935 because there is no correct word in English to define these types of values. If typescript can help here that would be excellent but it may be extremely difficult to enforce at the type level.

@andrewphillipo I saw that being discussed as well, and learned about the term Unit Interval from one of the answers on stack exchange, which seems to be the correct way of referring to that specific range in a generic context.
If ranges as types are ever implemented in typescript, perhaps UnitInterval could be defined as a global type, to encourage some common nomenclature around something that we use frequently in programming.

Yes UnitInterval is the correct name for the range 0...1 so it's correct for the type! Still not correct for the naming of the number so it would be excellent if this was available to describe our code more precisely - how does this work under the hood in Rust's type system - is it just a guard or?

If CantorSpace isn't too much of a stretch, I think that would be a fair definition of the "range" of "all" real numbers between [0, 1] as understood by a computer. Assigning these to values at compile time can't be inferred by a lower and upper bound of javascript's Math.floor or Math.ceil since Math.ceil(0) === 0, and Math.floor(1) === 1 which is unfortunate.
If the set of all numbers (0, 1) were used instead it'd work using the example above, but that's kind of bad to exclude values referenced as percentages in everyday language. If possible, having the compiler include the boundaries somehow would be nice, maybe through a strict === check against the edge cases 0 and 1.

or Maybe use 1~~3 for integers and 0.1~0.5 for floats ?

~ is already taken by the unary bitwise NOT operator.

Why we need to talk about those damn floats, the problem we have is with whole numbers. 99.99% is integer problem 0.001% is float problem.
No general solution easily possible so let's go for the number range of 0..10 as seen in most programming languages, as already implemented years ago.
Stop the float talking

Maybe the int case can be combined with this proposal:
https://gist.github.com/rbuckton/5fd81582fdf86a34b45bae82d842304c
For floats, I'm currently working on a different design proposal based on some ideas in this issue.

Just keep it simple with
x..y for whole numbers only.
0.1..2 would give an error
1..2.1 would also give an error
And any detectable non whole number.
Heck copy the implementation logic from
https://en.m.wikibooks.org/wiki/Ada_Programming/Types/range
Or
https://kotlinlang.org/docs/reference/ranges.html
Or
https://doc.rust-lang.org/reference/expressions/range-expr.html
and call it a day.
✅No need to reinvent the wheel
✅No need to account for floats
✅Consistency across language
✅Tested and copy able stable code from existing sources

It's worth the effort to solve floats, since "int" based type checking is trivial for numbers < 1000 by hard coding the type value as a union of every fixed integer 0..1000, so saying that there's "no need" to "re-invent the wheel" is a little ironic. Why not use what works already for simple use cases?
I would rather see for some room to allow for a type definition which understands things like irrational numbers. The ability to detect invariants at compile time when working with radians would be an interesting use case. Supporting τ as an argument to a range value boundary is a good target to claim that this feature works as intended imo.

Keep in mind that there is no explicit integer in javascript. Everything is just a number, which is stored as a float. If the range type operator is implemented, it should handle any value that number can handle.

@aMoniker depending on the definition of explicit: BigInt

Even for bigint, there are use cases unions can't solve like making sure a bigint fits within a MySQL signed/unsigned bigint

A suggestion like this might be cheating, but what about using intrinsic types for this feature?
// lib.es5.d.ts
type MinInclusive<N extends number> = intrinsic
type MaxInclusive<N extends number> = intrinsic
type MinExclusive<N extends number> = intrinsic
type MaxExclusive<N extends number> = intrinsic

// userland
type GreaterThanOrEqualTo8 = MinInclusive<8>
type GreaterThan8 = MinExclusive<8>
type GreaterThanOrEqualTo8AndLessThan22 = MinInclusive<8> & MaxExclusive<22>
type LessThan8OrGreaterThan22 = MaxExclusive<8> | MinExclusive<22> // nice thing about this is the ability to get the inverse of a range

A suggestion like this might be cheating, but what about using intrinsic types for this feature?
// lib.es5.d.ts
type GreaterThan<N extends number> = intrinsic
type GreaterThanOrEqualTo<N extends number> = N | GreaterThan<N>
type LessThan<N extends number> = intrinsic
type LessThanOrEqualTo<N extends number> = N | LessThan<N>

// userland
type GreaterThanOrEqualTo8 = GreaterThanOrEqualTo<8>
type GreaterThan8 = GreaterThan<8>
type GreaterThanOrEqualTo8AndLessThan22 = GreaterThanOrEqualTo8 & LessThan<22>
type LessThan3OrGreaterThan8 = LessThan<3> | GreaterThan8
type LessThan3AndGreaterThan8 = LessThan<3> & GreaterThan8 // never

A suggestion like this might be cheating, but what about using intrinsic types for this feature?
lib.es5.d.ts
type GreaterThan<N extends number> = intrinsic
type GreaterThanOrEqualTo<N extends number> = GreaterThan<N> | N
type LessThan<N extends number> = intrinsic
type LessThanOrEqualTo<N extends number> = LessThan<N> | N

userland
type GreaterThanOrEqualTo8 = GreaterThanOrEqualTo<8>
type LessThan22 = LessThan<22>
type GreaterThanOrEqualTo8_And_LessThan22 = GreaterThanOrEqualTo8 & LessThan22
type LessThan8_Or_GreaterThanOrEqualTo22 = LessThan<8> | GreaterThanOrEqualTo<22> // inverse of `GreaterThanOrEqualTo8_And_LessThan22`
type LessThan8_And_GreaterThanOrEqualTo22 = LessThan<8> & GreaterThanOrEqualTo<22> // `never`

@RyanCavanaugh

This really needs some compelling use cases, because the implementation of unions today is completely unsuited to realizing unions this large. Something that would happen if you wrote something like this ...

The following will be unsound without an int type:
const arr: string[] = ['a', 'b', 'c']
const item = arr[1.01]  // Typescript inferred this as string but actually it is undefined
console.log(item)  // Will print undefined, we miss inferred the type

Having the follow type will prevent this problem:
type TUInt = 0..4294967295;

Another use case for having Int32 and Int64 type specifically is when people start to annotation their code with it ... will open the door to better interoperability with other languages ... almost all statically typed languages have an integer type: Java, C#, C, Rust, F#, Go ... etc.
If I want to call a npm library written in TypeScript from C# for example, there are libraries that take TypeScript definitions and create an interface for me in C# but the problem is the number type is float which can't be used to index an array in C# without casing it ... etc.
Other use cases: easier to transpile between langauges, performance optimization ... etc

Note that one more case where this would be useful is interaction with WebAssembly, which has very explicit separate number types (I guess it was briefly mentioned as C# use-case, but wanted to clarify that it applies much wider than that).

+1

Already possible via TupleOf, specificially this log(n) algo: https://github.com/microsoft/TypeScript/issues/26223#issuecomment-674514787
Using that TupleOf as our basis:
type RangeOf<N extends number> = Partial<TupleOf<unknown, N>>["length"];

Example use case:
// number => 0..=32
types clz32Result = RangeOf<33>
type clz32 = (n: number) => clz32Result;

const clz: clz32 = Math.clz32 as clz32;

let x: clz32Result = clz(4);

// Error: This condition will always return 'false' since the types '0 | 1 | ... | 32' and '-1' have no overlap.
if (x === -1) {
    // ...
}

Already possible via TupleOf, specificially this log(n) algo: https://github.com/microsoft/TypeScript/issues/26223#issuecomment-674514787
Using that TupleOf as our basis:
type RangeOf<N extends number> = Partial<TupleOf<unknown, N>>["length"];

Example use case:
// number => 0..=32
types clz32Result = RangeOf<33>
type clz32 = (n: number) => clz32Result;

const clz: clz32 = Math.clz32 as clz32;

let x: clz32Result = clz(4);

// Error: This condition will always return 'false' since the types '0 | 1 | ... | 32' and '-1' have no overlap.
if (x === -1) {
    // ...
}

@amakhrov sorry maybe I wasn't clear enough; I want the same type for both cases.

@amakhrov sorry maybe I wasn't clear enough; I want the same type for both cases.

@Mouvedia
this combines RangeOf and RangeOf2 types from the comments above into a single variadic type that takes either 1 or 2 generic params.
type RangeOfVariadic<P extends number, T extends number | void = void> =
  T extends void ? RangeOf<P> : RangeOf2<P, Exclude<T, void>>;

type A = RangeOfVariadic<1, 3> // 1 | 2 | 3
type B = RangeOfVariadic<3> // 0 | 1 | 2 | 3

@Mouvedia
this combines RangeOf and RangeOf2 types from the comments above into a single variadic type that takes either 1 or 2 generic params.
type RangeOfVariadic<P extends number, T extends number | void = void> =
  T extends void ? RangeOf<P> : RangeOf2<P, Exclude<T, void>>;

type A = RangeOfVariadic<1, 3> // 1 | 2 | 3
type B = RangeOfVariadic<3> // 0 | 1 | 2 | 3

Now, for negative values, and decimals, we probably need a native implementation.

For any large values too. You can't exactly define uint32 using this type without hanging the compiler for a very long time.

Now, for negative values, and decimals, we probably need a native implementation.

For any large values too. You can't exactly define uint32 using this type without hanging the compiler for a very long time.

@amakhrov thanks.
Too bad you can't do Exclude<RangeOf<To>, RangeOf<From - 1>> that would cleaner than having to add | From.

@amakhrov thanks.
Too bad you can't do Exclude<RangeOf<To>, RangeOf<From - 1>> that would cleaner than having to add | From.

Now, for negative values, and decimals, we probably need a native implementation.

For any large values too. You can't exactly define uint32 using this type without hanging the compiler for a very long time.

Oh, of course, even RyanCavanaugh said:

This really needs some compelling use cases, because the implementation of unions today is completely unsuited to realizing unions this large.

@amakhrov thanks.
Too bad you can't do Exclude<RangeOf<To>, RangeOf<From - 1>> that would be cleaner than having to add | From.

That issue that I had referenced had an implementation of compile-time arithmetic, so it would probably be:
type _ = Exclude<RangeOf<To>, RangeOf<Sub<From, 1>>>

Credits to everyone over there, crazy stuff, cool nonetheless.

@amakhrov thanks.
Too bad you can't do Exclude<RangeOf<To>, RangeOf<From - 1>> that would be cleaner than having to add | From.

That issue that I had referenced had an implementation of compile-time arithmetic, so it would probably be:
type _ = Exclude<RangeOf<To>, RangeOf<Sub<From, 1>>>

Credits to everyone over there, crazy stuff, cool nonetheless.

@amakhrov there are 2 test cases that are still problematic:
RangeOf2<4,3>  // first argument should be inferior to the second
RangeOf2<-1,3> // negative integers are not part of ℕ

@amakhrov there are 2 test cases that are still problematic:
RangeOf2<4,3>  // first argument should be inferior to the second
RangeOf2<-1,3> // negative integers are not part of ℕ

How would these proposals affect the results of mathematical operations? Would we expect the following to work?
function foo(val: int & >0 & <20) { ... }

const a: int & >10 & <15 = 12;
const b: int & >0 & <5 = 4;

foo(a + b); // error?
foo(a - b); // error?
foo((a * b) % 10 + 1); // error?

If these kinds of type narrowing would work, then this proposal would be pretty neat. And it becomes is a whole lot more complex than just desugaring to unions.

@asciibits your syntax is awful, not readable. I like the original proposal with 1..10 though.
Re your expectation about mathematical operations... It already works with existing 1 | 2 | 3 | ... syntax:
let a: 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 = 10
a = a + 1

Type 'number' is not assignable to type '1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10'.

Though if you expect compiler to do calculations in compile time to do the checks, - it might be an overkill for the current proposal IMO. Not that I'm against it, but it should probably be a whole separate issue/PR. Not sure how it would play on performance, etc. But number ranges, - shouldn't devastate current performance, so definitely a like!

@JerryGreen I was borrowing the syntax from @AnyhowStep in comment https://github.com/microsoft/TypeScript/issues/15480#issuecomment-427790371 . There's at least three different comments on syntax, I picked the one I read last. On review, yeah that's would be pretty (an array of numbers between 10 and 20: Array<>10 & <20> - yeah, that's terrible). Updated to an alternate.
The 1..10 syntax is better, but not perfect. A dot after a digit already has a meaning: It's a decimal point. If this were to ever work with floats, it would be even worse: 1.2..2.3 - that's a lot of dots!
And yeah, Unions clearly wouldn't work in your and my examples, hence my question. I'm probably missing some complexity, but just thinking about it now, all the operators I can think of would have a relatively straight forward impact on the result's inferred  type.

fyi: I've created a separate proposal for interval types based on some ideas in this issue (especially @AnyhowStep and @btoo): Proposal: Interval Types
It covers some stuff mentioned here (minus integer types) and uses relational operators (>= etc) for narrowing types.

There can be problems in efficiency if this feature is extended to letters, like:
"bb"..."dd" where the compiler has to complete the sequence of the last strings in the range "b" : "bb" | "bc" | "bd" ... "bz" and jump backwards to the next strings in the range, the second"b", until it gets to the limit "dd", this can be resource consuming.

Here's another real-world-ish use case. I'm writing a sudoku solver: https://github.com/icecream17/solver/blob/main/src/Types.tsx

PLEASE! Add this.

I love this idea. I wonder is it anywhere on the Typescript roadmap for the future, or are there any blockers or difficulties that we're failing to consider, making implementation more complex?

It would be amazing if this feature were implemented！

The 1..10 syntax is better, but not perfect. A dot after a digit already has a meaning: It's a decimal point. If this were to ever work with floats, it would be even worse: 1.2..2.3 - that's a lot of dots!

just use parenteze, ts alreally allow it for design usages :  (1.2)..(2.3)

Another real word use case is latitude and longitude from coordinates.  One can go up to 180 and down to -180 the other can go from -90 to 90... We would want different types for each of these and due to them being any number in that range it would hardly make sense to specify every number... I really like 1..10 and 1...10 as a way to simplify this

Please don't comment -1 people thank you :)

Great Idea !

So, throwing my 2p into the mix:
I believe that an explicit format would be apropriate
e.g. RangeInt<1,10> or RangeFloat<0,1>
That potentially could have an alternative syntax
e.g. 1..10 and 1...10 as mentioned above
one I've not seen in the comments (not sure if I missed it) would be the use of the classic:
1-10 for one and presumably 1--10 for the other
alternatively of course -- and --- to avoid confusion
One of the other things that could come from this is the tooling to do something many have wanted for a long time, explicit integers.
For example, reworking the above syntax:
Int<1,10> and Float<1,10>
Adding in default values for <Min,Max> would give us
Int for "safe" integers (i.e. MAX_SAFE_INTEGER to MIN_SAFE_INTEGER
and
Int<0> for positive integers limited to MAX_SAFE_INTEGER
With the introduction of these basic mechanics we would be able to create a plethora of numerical types.
type IntByte = Int<0,255>;
type Nibble = Int<0,15>;
type UnixYear = Int<1970>;
type IntMonth = Int<1,12>;
type Count = Int<0>; // array.length being the first example
/** Fraction of a circle in radians */
type RadianFraction = Float<0, 2*Math.PI>;
interface LatLong = {
    Lat: Float<-90,90>,
    Long: Float<-180,180>,
}
function setRGBA(r: IntByte, g: IntByte, b: IntByte, a: Float<0,1> = 1) {...};

Here's the same example but with the dot "spread" notation:
type IntByte = 0..255;
type Nibble = 0..15;
type UnixYear = 1970..IntMax; // unsure how you'd do this sensibly in the notation with a default
type IntMonth = 1..12;
type Count = 0..;
/** Fraction of a circle in radians */
type RadianFraction = 0...2*Math.PI>;
interface LatLong = {
    Lat: -90...90,
    Long: -180...180,
}

And with the - and -- notation:
type IntByte = 0-255;
type Nibble = 0-15;
type RadianFraction = 0--2*Math.PI;
interface LatLong = {
    Lat: -90--90,
    Long: -180--180,
}

With -- and --- :
type IntByte = 0--255;
type IntNibble = 0--15;
type RadianFraction = 0---2*Math.PI;
interface LatLong = {
    Lat: -90---90,
    Long: -180---180,
}

The primary difficulty I imagine with this would be the combination of differing ranges in something:
const a: Float<1,5> = 0.34;
function DoThing(val: Float<0,10>) {...}
DoThing(a);

// ERROR: type Float<12,20> may have a value outside the range of Float<0,10>
const b: Float<12,20> = 16.3;
DoThing(b);

type Foo = Float<1,2> | Float<2,3>;
type Bar = Int<1,10> & Int<6,16>;

// ERROR: type resolves to never / type has no possible values
type Baz = Int<0,5> & Int<10,50>;

const a: 1...5 = 0.34;
function DoThing(val: 0...10) {...}
const b: 12..,20 = 16.3;
type Foo = 1...2 | 2...3;
type Bar = 1,..10 & 6..16;
type Baz = 0..5 & 10..50;

const a: 1--5 = 0.34;
function DoThing(val: 0--10) {...}
const b: 12--20 = 16.3;
type Foo = 1--2 | 2--3;
type Bar = 1-10 & 6-16;
type Baz = 0-5 & 10-50;

Concerning syntax:
I believe that an explicit integer type (e.g. `Int<[min],[max]>) will have to exist because of the issues with defining defaults with the alternative syntaxes.
Concerning the interactions between int and float:
I would propose any int can be trated as a float (e.g. floatFn(someInt)) but no float an be treated as an int unless restricted down like so: if(someFloat === 10) intOnlyFn(someFloat); the same way we do with other values.
The only other way is to convert to an int.
Concerning unions:
Once the syntax has been finalised, one could add a limited version of the unions solution for just integers with a compiler parameter that sets the maximum size of the union and a default value (e.g. 256 integers).
This would allow a large number of the use-cases that I - can come up with / have read - without (as far as I can tell) prohibitive processing cost.
Example:
type Byte = Int<0,255>; // 0 | 1 | 2 | 3 | ... | 255
type SByte = INT<-128,127>; // -128 | -127 | ... | 127
I believe that this may well solve over 50% of use-cases and require a tiny fraction of the coding.
P.S:
I have omitted strings for this example as I believe that if we're going to have something like that, it might as well be part of a larger, almost pseudo-RegEx, level of typing.

With this approach, Enumerate handles up to 40. This is still a limitation, but maybe not so harsh in practice.
@moccaplusplus Any way to not exclude the end TO index?

Well, since it seems that nowadays Typescript types are Turing complete (https://github.com/microsoft/TypeScript/issues/14833), there's nothing possible in typing system of Typescript.
On the other hand, I wouldn't really like to add some 40 lines of too complex absolute weirdo code, into my project, for such a simple thing as «number range». So to me it's not an issue of formal possibility but native convenience.
P.S. One can create some AI or something someday, just using types.

That's news to me. I bet someone is currently trying to make Tetris out of type definitions right now.

This would be good

~> With this approach, Enumerate handles up to 40. This is still a limitation, but maybe not so harsh in practice. @moccaplusplus Any way to not exclude the end TO index?~
I figured it out just in like two minutes of posting it. I split it up into an exclusive and inclusive enumerator.
type PrependNextNum<A extends Array<unknown>> = A['length'] extends infer T
  ? ((t: T, ...a: A) => void) extends (...x: infer X) => void
    ? X
    : never
  : never;

type EnumerateInternalExclusive<A extends Array<unknown>, N extends number> = {
  0: A;
  1: EnumerateInternalExclusive<PrependNextNum<A>, N>;
}[N extends A['length'] ? 0 : 1];

type EnumerateInternalInclusive<A extends Array<unknown>, N extends number> = {
  0: PrependNextNum<A>;
  1: EnumerateInternalInclusive<PrependNextNum<A>, N>;
}[N extends A['length'] ? 0 : 1];

export type EnumerateExclusive<N extends number> = EnumerateInternalExclusive<
  [],
  N
> extends (infer E)[]
  ? E
  : never;

export type EnumerateInclusive<N extends number> = EnumerateInternalInclusive<
  [],
  N
> extends (infer E)[]
  ? E
  : never;

export type Range<FROM extends number, TO extends number> = Exclude<
  EnumerateInclusive<TO>,
  EnumerateExclusive<FROM>
>;

type E1 = EnumerateExclusive<93>;
type E2 = EnumerateExclusive<10>;
type R1 = Range<0, 5>;
type R2 = Range<5, 34>;

this is cool, but it needs too much memory even from pretty small ranges
we need actual syntax support for this feature

FWIW, here's a 9 SLOC implementation for non-negative integers.
Hope it helps anyone.
// Increment / Decrement from:
// https://stackoverflow.com/questions/54243431/typescript-increment-number-type

// We intersect with `number` because various use-cases want `number` subtypes,
// including this own source code!

type ArrayOfLength<
  N extends number,
  A extends any[] = []
> = A["length"] extends N ? A : ArrayOfLength<N, [...A, any]>;
type Inc<N extends number> = number & [...ArrayOfLength<N>, any]["length"];
type Dec<N extends number> = number &
  (ArrayOfLength<N> extends [...infer A, any] ? A["length"] : -1);

type Range<Start extends number, End extends number> = number &
  (Start extends End ? never : Start | Range<Inc<Start>, End>);

What about the issue with incrementing by 2 or even 10 instead of 1?
input
type Foo = Range<0, 100, 10>

equivalent
type Foo = 0 | 10 | 20 | 30 | 40 | 50 | 60 | 70 | 80 | 90 | 100;

@Thaina I like your idea, since it allows for complex ranges. However, how would you make sure that two constraints are compatible? For example:
let num1: number extends >= 0 and <= 100 and % 10 == 0 = 0;
let num2: number extends >= -1 and <= 100 and % 10 == 0 = 0;

function foo(param0: number extends >= 0 and < 1337) {
  // do sth.
}

foo(num1); // OK, since the constraints are compatible
foo(0.1); // OK, since it matches the constraints
foo(num2); // ERROR!

I am fine with any tweak of syntax as long as it can reproduce the same pattern as C# could
But useless range is responsibility of the code's author. It was the exact same as writing useless if

There is also #50325

One potential compelling argument is allowing additional validation of conditions.
For example imagine if the indexOf function on strings/arrays was defined as returning something like -1..n. Then it would be possible to validate that the following conditions are invalid:

indexOf() >= -1 - "error - expression is always true"
indexOf() < -1 - "error - expression is always false"
indexOf() === -2 - "error - expression is always false"

It's a small win for sure, but it's great for documentation and code correctness.
We were talking about this in @typescript-eslint (https://github.com/typescript-eslint/typescript-eslint/issues/6126), but our issue is that without such a type-system representation we would essentially have to hard-code a list of functions and their expected return types within a lint rule. If there was a type-system representation then instead we could build a rule for the general case (if TS didn't include such checks).

Idea: By default, just store max and min (and step in some proposals).
If the range is too big, then say Exclude<Range<1, 100000>>, 7> can just be Range<1, 100000>. (At least initially)
This would solve the performance issues.
I think most of these use cases just want to use Range to check if a number is in the range (i.e. min <= num <= max, again accounting for step in some proposals) or some variant of that.

This feature already work ?

@Flaviano-Rodrigues No. This is a topic about how it should work and what we need to consider in order to get a solid implementation.

Oh, ok. I'm really excited to use this feature. case added

Hi,you can check my article  and or stackoverflow answer .

type ComputeRange<
    N extends number,
    Result extends Array<unknown> = [],
> =
    (Result['length'] extends N
        ? Result
        : ComputeRange<N, [...Result, Result['length']]>
    )

type Add<A extends number, B extends number> = [...ComputeRange<A>, ...ComputeRange<B>]['length']

type IsGreater<A extends number, B extends number> = IsLiteralNumber<[...ComputeRange<B>][Last<[...ComputeRange<A>]>]> extends true ? false : true

type Last<T extends any[]> = T extends [...infer _, infer Last] ? Last extends number ? Last : never : never

type RemoveLast<T extends any[]> = T extends [...infer Rest, infer _] ? Rest : never

type IsLiteralNumber<N> = N extends number ? number extends N ? false : true : false

type AddIteration<
    Min extends number,
    Max extends number,
    ScaleBy extends number,
    Result extends Array<unknown> = [Min]
> =
    IsGreater<Last<Result>, Max> extends true
    ? RemoveLast<Result>
    : AddIteration<
        Min, Max, ScaleBy, [...Result, Add<Last<Result>, ScaleBy>]
    >

// [5, 13, 21, 29, 37]
type Result = AddIteration<5, 40, 8>

Math.fl

// Error Type instantiation is excessively deep and possibly infinite.ts(2589)
type WorkMinute = AddIteration<0, 1439, 1>

Maybe we can implement by string type, for example we want to define types Hour/Minute or Time:
type zeroToNine = 0|1|2|3|4|5|6|7|8|9
type zeroToTwo = 0|1|2|''
type zeroToSix = 0|1|2|3|4|5|6|''

export type Hour = `${zeroToTwo}${zeroToNine}`
export type Minute = `${zeroToSix}${zeroToNine}`

export type Time =  `${Hour}:${Minute}`

Usage
export const startArchive = (_time: Time = '02:30') => {

}

Picking up a clean slate at #54925

6 years in! Would love to see this.

As of now we have more and more complex proposal that seem impossible to handle with just range. I think maybe we should considering generic constraint with pattern matching clause so we could write arbitrary guard logic
We could bring the whole pattern matching system from C# into typescript (include switch expression) and then allow using pattern matching at the type constraint
function DoSomething<T>(T value) : T extends number and >= 0 and <= 100 and % 10 === 0
{
    // value is 0 10 20 30 ... 100
}

DoSomething(60);
DoSomething(39); // error
let value = GetValue();
if(value extends number and >= 0 and <= 100 and % 10 === 0)
    DoSomething (value); // not error because same check

Or use patterns as RegExp like in #41160


segmentation fault upon reconnecting to Spark after a disconnect

Hi folks,
I'm getting a segfault memory error when attempting to reconnect to spark after disconnecting.
The only reason I am disconnecting is because I would like to release all of the memory that is being held by the underlying Java process after running spark jobs and I haven't found any way of doing that while keeping the connection alive. If someone can describe an alternative way of releasing the memory, I'd be very grateful.
Below is the code and the sessionInfo() output.
version <- "2.2.0"
config <- spark_config()
config[["sparklyr.defaultPackages"]] <- "org.apache.hadoop:hadoop-aws:2.7.3"
config[["spark.debug.maxToStringFields"]] <- 250
config[["spark.driver.maxResultSize"]] <- "30g"
config[["sparklyr.shell.driver-memory"]] <- "8G"
config[["sparklyr.shell.executor-memory"]] <- "2G"
config[["spark.hadoop.fs.s3a.access.key"]] <- Sys.getenv("AWS_ACCESS_KEY_ID")
config[["spark.hadoop.fs.s3a.secret.key"]] <- Sys.getenv("AWS_SECRET_ACCESS_KEY")
sc  <- spark_connect(master = "local", version = version, config = config)

## Do work

spark_disconnect(sc)
Sys.sleep(5)

sc  <- spark_connect(master = "local", version = version, config = config)

s> sessionInfo()
R version 3.4.3 (2017-11-30)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Debian GNU/Linux 9 (stretch)

Matrix products: default
BLAS: /usr/lib/openblas-base/libblas.so.3
LAPACK: /usr/lib/libopenblasp-r0.2.19.so

locale:
 [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C
 [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8
 [5] LC_MONETARY=en_US.UTF-8    LC_MESSAGES=C
 [7] LC_PAPER=en_US.UTF-8       LC_NAME=C
 [9] LC_ADDRESS=C               LC_TELEPHONE=C
[11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] sparklyr_0.7.0 dplyr_0.7.4

loaded via a namespace (and not attached):
 [1] Rcpp_0.12.15     dbplyr_1.2.1     pillar_1.2.1     compiler_3.4.3
 [5] plyr_1.8.4       bindr_0.1        base64enc_0.1-3  tools_3.4.3
 [9] digest_0.6.15    jsonlite_1.5     tibble_1.4.2     nlme_3.1-131
[13] lattice_0.20-35  pkgconfig_2.0.1  rlang_0.2.0      psych_1.7.8
[17] shiny_1.0.5      DBI_0.8          rstudioapi_0.7   parallel_3.4.3
[21] bindrcpp_0.2     httr_1.3.1       stringr_1.3.0    rprojroot_1.3-2
[25] grid_3.4.3       glue_1.2.0       R6_2.2.2         foreign_0.8-69
[29] tidyr_0.8.0      purrr_0.2.4      reshape2_1.4.3   magrittr_1.5
[33] backports_1.1.2  htmltools_0.3.6  assertthat_0.2.0 mnormt_1.5-5
[37] mime_0.5         xtable_1.8-2     httpuv_<IP_ADDRESS>   stringi_1.1.6
[41] lazyeval_0.2.1   broom_0.4.3

@lpatruno would you mind trying this fix https://github.com/rstudio/sparklyr/pull/1723? You can install this fix running:
devtools::install_github("rstudio/sparklyr")

The fix should properly clean memory to remove the need to restart the R session.
I'm interested in also fixing this segfault, but I need a repro which is usually only possible by providing a docker file to consistently reproduce, if you can get me one we can definitely investigate further.

Hi @javierluraschi thanks for the rapid response.
Unfortunately, I can't provide much more info in the way of a reproducible example because I'm working with proprietary data.
Running that install command resulted in the following error:
> devtools::install_github("rstudio/sparklyr")
Using GitHub PAT from envvar GITHUB_PAT
Downloading GitHub repo rstudio/sparklyr@master
from URL https://api.github.com/repos/rstudio/sparklyr/zipball/master
Installing sparklyr
'/usr/local/lib/R/bin/R' --no-site-file --no-environ --no-save --no-restore  \
  --quiet CMD INSTALL  \
  '/tmp/RtmperQjmz/devtools618160147/rstudio-sparklyr-3465d26'  \
  --library='/usr/local/lib/R/site-library' --install-tests

ERROR: dependencies ‘r2d3’, ‘forge’ are not available for package ‘sparklyr’
* removing ‘/usr/local/lib/R/site-library/sparklyr’
Installation failed: Command failed (1)

Then I would try:
install.packages("r2d3")
install.packages("forge")

devtools::install_github("rstudio/sparklyr")

The only way I've gotten this to work with seg faulting on the reconnect is by committing this crime:
spark_disconnect(sc)
system("kill $(pidof java)", intern = T)
Sys.sleep(10)

sc  <- spark_connect(master = "local", version = version, config = config)

Aside from the obvious hacxzor programming, is there cause for concern with this approach?
The current alternative is to just run separate docker containers for each job rather than disconnecting and reconnecting. But I'd like to avoid that if possible.

We appear to have "fixed" this issue somehow... In any case, segfault is indicative of a JVM bug rathern than a sparklyr issue. Sparklyr simply connects to a Spark instance and invokes some JVM methods, fetch computation results, etc. It cannot directly cause another process to segfault.


No printer on localhost

I have installed the package and Printnode. Set the api but when i do
print_r(Printing::printers());
Array is empty
Any hint please? Thanks

I am also getting this error
Array is empty
$printers = Printing::defaultPrinterId();
     dd($printers);

please help us. @rawilk

+1 here.
This bit of code produces an empty list:
$printers = Printing::printers();
dd($printers);

Result:
Illuminate\Support\Collection {#1349 ▼
  #items: []
}

But I can print if I specifically select a printer, so I know the API requests are working.

OK, worked it out.
This package is requiring an out of date printnode package which relies on "offset" in the API which is breaking on new accounts. "offset" was replaced with "after" in subsequent updates of the printnode-php package, but the required version isn't being updated.
In any case, in your composer.json replace:
"printnode/printnode-php": "^2.0@RC"
With:
"printnode/printnode-php": "master"
Obviously you might want to be a bit more strict on your version than just "master", but that's as far as my knowledge on the matter can help.

@JonoHall I have tried that also, but still does not getting any printers.

I plan on making some updates to how the PrintNode driver works behind the scenes which will hopefully help resolve this for people that have this issue.

I have the same problem but I'm using cups, not PrintNode. Any suggestions?. Thanks in advance


Feat/include new profiles

Added new set of borehole profiles, and with it, multilingual support.

Adjusted GroundTruth to work with new format. --> old format will not work any more. There is a functionality in the notebook that converts old ground_truth.json into the new one.
Added language detection.
Translated including and excluding expression into french.
Also comes with the EDA based on a different branch. Probably should be dropped here. Kept for the conversion script and the generation of test/train/eval splits. Can be dropped after the review.

LGTM.
For now, it's good to have the convert_ground_script here for reproducibility, but in future we can probable remove that script again, as we won't need to deal with the old format at all anymore?

I agree with this statement.


Use ABI-specific integer types

This will require Dart 2.16, but we can start using ABI-specific integer types with ffigen version 5.

Sine the ABI-specific integers will be part of dart:ffi in Dart 2.17, this should wait a bit longer.


Backup-ADFS command does not prompt for credentials when ran as domain admin

But if the command is ran with a domain service account/local admin that has ADFS/DKM permissions, the prompt always occurs.  This is problematic when attempting to execute the backup via scheduled task with credentials specified in the task.  The backup cmdlet still prompts for credentials.

Document Details
⚠ Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.

ID: a58b49ca-ae39-132e-adbd-6766a8019a89
Version Independent ID: fdf31266-bc9e-8880-0073-00cf1cad2897
Content: AD FS Rapid Restore Tool
Content Source: WindowsServerDocs/identity/ad-fs/operations/AD-FS-Rapid-Restore-Tool.md
Product: windows-server-threshold
GitHub Login: @billmath
Microsoft Alias: billmath

As discussed in #1831 , there is a suggested script/PS code example in that ticket:
import-module 'C:\Program Files (x86)\ADFS Rapid Recreation Tool\ADFSRapidRecreationTool.dll'

$Password = "This-is-the-Key-of-your-storage-account-and-can-be-found-in-your-Azure-Storage-Container-under-Access-Keys"
$pass = ConvertTo-SecureString -AsPlainText $Password -Force
$Username = "adfsbackups" #Name of your storage account
$cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $Username,$pass

Backup-ADFS -StorageType "Azure" -AzureConnectionCredentials $cred -AzureStorageContainer "adfsbackups" -EncryptionPassword "password" -BackupComment "ADFS Backup"

Not sure if it is practical or useful to you, but I thought it would be nice to reference it.


sizeof(int) gives 4, while AVR int is 2 bytes long

Hello, I was doing some programming and I found that EpoxyDuino returns 4 on sizeof(int). while in arduino it is said that an int is 2 bytes.
I used the followingin the makefile.
EPOXY_CORE := EPOXY_CORE_AVR

One way to fix it is by doing
#ifdef EPOXY_DUINO
#define int int16_t
#endif

in your header file, but it will break the libraries you use. Any way to 'inject' it into other libraries?

EpoxyDuino is not meant to be a perfect simulator of an AVR microcontroller. It aims to support the Arduino API under a Unix environment. The sizeof(int) is not defined by the C/C++ language, but is implementation defined. This means that the sizeof(int) is the size given by the C++ compiler under Unix, which is 4, which happens to be the same in all Arduino environments except for AVR. I mention this potential issue with EpoxyDuino at the top of the README (https://github.com/bxparks/EpoxyDuino).
If you have code that assumes sizeof(int) == 2, it is non-portable code and will not work under EpoxyDuino. If you have control over that code, the solution is to change it explicitly to int16_t, so that it becomes portable. If you don't have control over that code, then you will need to fork it and fix it, and maybe upstream it to the original author of that library.


Issue with the installation of the package

Hi so I have tried installing the package multiple times, Even tho it says the requirements are fulfilled.

Can you provide more info?

What all information do you need ? I would send those details here.

I have no idea what you're saying but perhaps try upgrading pip

Do you have a file in your project called solana.py perhaps?

Ya , I did have a file named solana.py Really sorry to distrub you all. Is there any contribution I can make in order to help the community of Solana py grow ?

No worries! A great thing to do would be find something in the Solana Cookbook that has a TypeScript example but not a Python example, and add a Python example to it https://solanacookbook.com/#contributing

Thanks alot... Closing the thread


layers/meta-rust: Remove unused submodule

This layer is now deprecated in favor of rust from meta-balena
Changelog-entry: Remove unused meta-rust submodule since we rely on rust from meta-balena now
Signed-off-by: Florin Sarbu<EMAIL_ADDRESS>

@balena-ci I self-certify!


Tinkerer (Armorer) infusions persisting through multiple uses on multiple pieces of equipment

I'm sure there are people who are gonna hate me for reporting  this one :(
The easiest way I can clarify this bug is by referencing the old Tinkerer on previous incarnations of this mod:
In CE2, the Tinkerer Infusions would reset after every Long Rest, meaning they had to be re-applied after every visit to a campfire.  This is the way the description for infusions suggests they are supposed to work.
When UB was released, the text for Tinkerer infusions didn't change, but they would persist through a long rest, which is much more convenient.  However, the text also says that an infusion can only be on one piece of equipment at a time, and applying it to a new piece would remove the infusion from the old.  This is not happening.
I recently hit lvl 10 on my Tinkerer, and wasn't sure if my Enhanced Defence and Enhanced Weapon infusions were automatically applied, or if I would have to apply them again to get the +2 instead of +1 from the infusion.  In trying to re-apply the Enhanced Defense infusion to my shield, it wouldn't let me (due to there already being a Enhanced Defense infusion on it).  So, I figured I would just apply it to my Armor (where my Enhanced Weapon infusion was) to reset it, and it would reset my Weapon infusion too (meaning I could re-apply the Weapon infusion on my armor afterwards, removing the Defense infusion and allowing me to add the Defense back to my shield)
However, I now have a Shield with +2 defense infusion on it, a set of +1 Plate Armor with the +2 defense infusion also on it, and my +2 Weapon infusion is ALSO on my Plate Armor, meaning I'm now currently "doubling up" on my Defense infusion, getting +4 from it (+2 from shield, +2 from plate armor) and still have my +2 weapon
There doesn't seem to be a way to reset the infusions so you can start it fresh either.
Please don't get me wrong, it would be very nice if we could keep the persisting through a long rest so you don't have to re-apply every infusion every time you sleep.  That's just a convenience.  However, the infusions also def shouldn't be able to be applied to more than one item each (or have multiple on a single item).  Breaks and unbalances the point of 'em when every party member has +2 def, +2 weapon, +2 focus, and mind sharpener.
Game V 1.4.33
UN V <IP_ADDRESS>
UB Bug reports.zip

@EnderWiggin

Armorer can stack up to 6 infusions at the same time at that level. It doesn't work exactly as the Tinkerer class.

About a month ago I've specifically removed most limits on infusion application and updated descriptions accordingly - you just can't apply same infusion to same item twice, and there's limit of only 1 infusion that grants +1 on a single weapon. I personally don't think that's too big of a buff, since infusions are still limited (or should be limited, clarify if this is not true) by amount that can be active at one time.
As for being unable to reset infusions - I'll add ability to stop all infusions, although this may require respec, not sure yet.


Missing build:dll script in package.json

Description
Hi,
in postsetup script run npm run build:dll`,  but seems it missed in the package.json file.
Versions

React-Boilerplate: 3.7.0

Hi. You are right. I forgot it there when switching to 3.7.0. Now build:dll is not needed. You can remove it from package.json. I am updating the master. After switching to 3.7.0, I didn't try npm setup.

I will check npm setup later in details. But if there are other issue please re-open. Thanks for the update !


Is pytorch-transformers useful for training from scratch on a custom dataset?

Hello,
I'm looking into the great repo, and I'm wondering if there is a feature that could allow me to train a, let's say, gpt2 model on a custom dataset of sequences.
Is it already provided in your codebase and features ? Otherwise I'll tinker with code on my own.
Thanks in advance and again, great job for the repo which is super useful.

This depends on the model you're interested in. For GPT2, for example, there's a class called GPT2LMHeadModel that you could use for pretraining with minimal modifications. For XLNet, the implementation in this repo is missing some key functionality (the permutation generation function and an analogue of the dataset record generator) which you'd have to implement yourself. For the BERT model in this repo, there appears to be a class explicitly designed for this (BertForPreTraining).

Hi, we don't provide efficient scripts for training from scratch but you can have a look at what Microsoft did for instance: https://azure.microsoft.com/en-us/blog/microsoft-makes-it-easier-to-build-popular-language-representation-model-bert-at-large-scale/
They shared all the recipes they used for training a full-scale Bert based on this library. Kudos to them!

I'd like to see efficient scripts for training from scratch too please. The Azure repo looks interesting, but looks very Azure-specific, and also bert specific. Would be nice to have training scripts within the hugging face repo itself.

@hughperkins
I wrote this post when I modified code to run on (custom) IMDB dataset for BERT model: https://medium.com/dsnet/running-pytorch-transformers-on-custom-datasets-717fd9e10fe2
Not sure if this helps you.

@hughperkins
I wrote this post when I modified code to run on (custom) IMDB dataset for BERT model: https://medium.com/dsnet/running-pytorch-transformers-on-custom-datasets-717fd9e10fe2
Not sure if this helps you.

Hi, we don't provide efficient scripts for training from scratch but you can have a look at what Microsoft did for instance: https://azure.microsoft.com/en-us/blog/microsoft-makes-it-easier-to-build-popular-language-representation-model-bert-at-large-scale/
They shared all the recipes they used for training a full-scale Bert based on this library. Kudos to them!

Indeed this seems very Azure specific and not very helpful. What would be helpful is showing minimal scripts for training transformers, say GPT2, on custom datasets from scratch. Training from scratch is basic requisite functionality for this library to be used in fundamental research as opposed to tweaking / fine-tuning existing results.


[Bug]: BadRequestError(400, 'search_phase_execution_exception', 'failed to create query: [knn] queries are only supported on [dense_vector] fields')

Bug Description
After I installed elasticsearch (version 8.9.0) using docker-ce on Ubuntu22.04, I tried to call the following code to store the index on elasticsearch.
import logging
import sys
import os
import openai
from llama_index.vector_stores.elasticsearch import ElasticsearchStore
from llama_index.core import StorageContext, ServiceContext
from llama_index.core import VectorStoreIndex, SimpleDirectoryReader
from llama_index.embeddings.openai import OpenAIEmbedding
from llama_index.core import Settings
from llama_index.core.node_parser.text import SentenceSplitter
from langchain.chat_models import ChatOpenAI
logging.basicConfig(stream=sys.stdout, level=logging.INFO)
logging.getLogger().addHandler(logging.StreamHandler(stream=sys.stdout))
import getpass
import openai

os.environ["OPENAI_API_KEY"] = getpass.getpass("OpenAI API Key:")

openai.api_key = os.environ["OPENAI_API_KEY"]

es = ElasticsearchStore(
    index_name="my_index",
    es_url="http://localhost:9200",
)

documents = SimpleDirectoryReader("./data/paul_graham/").load_data()

vector_store = ElasticsearchStore(
    es_url="http://localhost:9200",
    index_name="paul_graham",
)
storage_context = StorageContext.from_defaults(vector_store=vector_store)
index = VectorStoreIndex.from_documents(
    documents, storage_context=storage_context
)

query_engine = index.as_query_engine()
response = query_engine.query("what were his investments in Y Combinator?")
print(response)

But I encountered this error:
BadRequestError(400, 'search_phase_execution_exception', 'failed to create query: [knn] queries are only supported on [dense_vector] fields')

So I checked my elasticsearch database and found that the type of "vector_field" is "float", but it should actually be "dense_vector".
So I checked the file llama_index/llama-index-integrations/vector_stores/llama-index-vector-stores-elasticsearch/llama_index/vector_stores/elasticsearch/base.py. In line 242 of the file, that is, the "_create_index_if_not_exists" function:
if self.client.indices.exists(index=index_name):

This will always return true. In fact, in the init function(line176), the index has been created, but no data has been stored in it. So self.client.indices.exists mistakenly regards the empty index as having been successfully created (that is, created and stored data in it). Therefore, the else branch after line 246 will never be executed. So the data will never be created and stored in the index. When I try to execute the else branch after 246, my elasticsearch index is created normally and can be queried without the previous error.
Version
0.10.12
Steps to Reproduce

Install docker-ce on ubuntu22.04
Install elasticsearch 8.9.0
Create and start the container

docker run -p 9200:9200 \  -e "discovery.type=single-node" \  -e "xpack.security.enabled=false" \  -e "xpack.security.http.ssl.enabled=false" \  -e "xpack.license.self_generated.type=trial" \  docker.elastic.co/elasticsearch/elasticsearch:8.9.0

Install llama-index and llama-index-vector-stores-elasticsearch

pip install llama-index-vector-stores-elasticsearch
pip install llama-index

Call the following code

import logging
import sys
import os
import openai
from llama_index.vector_stores.elasticsearch import ElasticsearchStore
from llama_index.core import StorageContext, ServiceContext
from llama_index.core import VectorStoreIndex, SimpleDirectoryReader
from llama_index.embeddings.openai import OpenAIEmbedding
from llama_index.core import Settings
from llama_index.core.node_parser.text import SentenceSplitter
from langchain.chat_models import ChatOpenAI
logging.basicConfig(stream=sys.stdout, level=logging.INFO)
logging.getLogger().addHandler(logging.StreamHandler(stream=sys.stdout))
import getpass
import openai

os.environ["OPENAI_API_KEY"] = getpass.getpass("OpenAI API Key:")

openai.api_key = os.environ["OPENAI_API_KEY"]

es = ElasticsearchStore(
    index_name="my_index",
    es_url="http://localhost:9200",
)

documents = SimpleDirectoryReader("./data/paul_graham/").load_data()

vector_store = ElasticsearchStore(
    es_url="http://localhost:9200",
    index_name="paul_graham",
)
storage_context = StorageContext.from_defaults(vector_store=vector_store)
index = VectorStoreIndex.from_documents(
    documents, storage_context=storage_context
)

query_engine = index.as_query_engine()
response = query_engine.query("what were his investments in Y Combinator?")
print(response)

Relevant Logs/Tracbacks
No response

Thanks @rhondasu2002 for the detailed bug report! Am digging on this now, though at first glance I wonder if this has anything to do (though I feel it shouldn't) with the fact that you're creating an index="my_index" first, which I don't believe you end up using.

@rhondasu2002: I can confirm I was able to reproduce the bug on my own end. Here are my findings:

In reviewing the full traceback, I see that if self.client.indices.exist(index=index_name): line was returning a Coroutine since client is AsyncElasticsearch and thus needs to be await'ed.

I have a new PR that fixes this.
Once the PR lands and the version of llama-index is released, you will need to delete the paul_graham index locally before being able to run your script.
curl -X DELETE "localhost:9200/paul_graham?pretty"

If you are using a different port other than 9200, then simply replace it with the one that you are using.


use of MAX_PACKET_BYTES vs MAX_PAYLOAD_BYTES in receive_packet functions

A question:
        *packet_bytes = packet->payload_bytes;
        netcode_assert( *packet_bytes >= 0 );
        netcode_assert( *packet_bytes <= NETCODE_MAX_PACKET_BYTES );

Since packet_bytes is actually packet->payload_bytes, shouldn't the latter netcode_assert be comparing to NETCODE_MAX_PAYLOAD_BYTES?
Found in the following locations:
https://github.com/networkprotocol/netcode.io/blob/master/netcode.c#L3359
https://github.com/networkprotocol/netcode.io/blob/master/netcode.c#L4858

(in debug build obviously) :)


MINOR: improve RecordCollectorImpl

Found this while working on https://github.com/apache/kafka/pull/17169, but did not want to piggy-back this change to the other PR but isolate as it's unrelated cleanup.

After re-thinking, the test we remove because it failed actually exposed that the original idea of this PR is incorrect. We need to keep sendException inside StreamsProducer as we need a single instance per thread, shared across all tasks (ie, all RecordCollectorImpl -- we have one per task).


Interstitial show/hide

Hi,
i'm wondering if this plugin auto-manages delay or timing while showing interstitials ads.
I'm using Ionic and following this workflow to show interstitials ads

prepareInterstitial function with simple options as reported below

adId: adMobId.admob_interstitial_key_ios,
autoShow: false

showInterstitial function wrapped in isInterstitialReady function on several view enter

$scope.$on('$ionicView.enter', function() {
  if(window.AdMob){
    window.AdMob.isInterstitialReady(function(ready){
	if(ready){
	  window.AdMob.showInterstitial();
	}
    });
  }
});

However interstitials ads are shown only on first time when entering the view, or after some arbitrary time while navigating the app and entering one view which is supposed to show the ad.
Is this a want feature or it depends on my DFP settings (I've not set any delay or stuff like that)?
Have you got any hints about that?

The interstitial Ad is one time Ad, once it's dismissed, you need prepare again before show again.
You can listen to 'onAdDismiss' event (which is triggered when ad is closed by user), then call prepareInsterstitial() there.

Thank you for your support.
It was clear to me I was missing something!


Added Heapsort implementation in Java (issue #307)

@rdestrada : It would be great if you can add the description along with the issue number.
Feel free to use our contribution guidelines (https://github.com/fnplus/interview-techdev-guide/blob/master/CONTRIBUTING.md#how-to-contribute-an-implementation-code) for reference

Issue - https://github.com/fnplus/interview-techdev-guide/issues/307
@rdestrada : We have merged your code this time. But make sure to follow good Open Sources practices (https://github.com/fnplus/interview-techdev-guide/blob/master/CONTRIBUTING.md#how-to-contribute-an-implementation-code)

@rdestrada : Thanks for Contributing


F-Droid inclusion

It would be nice to have the app on F-Droid for FOSS users.
Izzy repo requirements
But as @IzzySoft mentioned here 8 offenders is too much.
Offending libs:
---------------
* Crashlytics (/com/crashlytics): Tracking
* Firebase Data Transport (/com/google/android/datatransport): NonFreeNet
* Google Maps API (/com/google/android/gms/maps): NonFreeDep,NonFreeNet
* Play Services Places Placereport (/com/google/android/gms/places_placereport): NonFreeDep,NonFreeNet
* Android Wear APIs (/com/google/android/gms/wearable): NonFreeDep
* Google Mobile Services (/com/google/android/gms): NonFreeDep
* Firebase (/com/google/firebase): NonFreeNet,NonFreeDep
* Firebase Analytics (/com/google/firebase/analytics): Tracking

8 offenders.

Is it possible to have an APK on GitHub without these? or Can you narrow it down (for izzyrepo release)?
Thankyou🙏

I removed the dependencies on firebase, which should eliminate 4 of them. However, if it is still not enough, I will be not able to help you futher. The reason is the app uses Google APIs to communicate with Wear Os, so the app for the Wear Os would be useless. Removal / changing of other dependencies would be costly / some features would be dropped.
The apks can be found here: https://github.com/Foxpace/SensorBox/releases/tag/v4.2.2-nf
I did it quickly, so if there are some remnants, I will take another look on it.


[Question] different .releaserc files

Does this extension support per package configurations ?
For example, I could have one package be deployed via github packages and another deployed via github container registry using one of the docker plugins ?

possible duplicate of: https://github.com/pmowrer/semantic-release-monorepo/issues/111


add kiali server deployment annotations

contributing to kiali-server helm chart to add deployment annotations to template.
we have a use case where use deployment annotations to mass target within our automation.

If you would like a feature like this added to Kiali, please submit a github issue first so it can be discussed with the community. Do not just submit a PR as it will likely not be accepted without a github issue in place with a discussion of the enhancement request.
In this case, I would have indicated that there is more to this than just adding to the server helm chart. Please see the developer checklist when you want to add a server config like this: https://github.com/kiali/kiali-operator/blob/master/DEVELOPING.adoc#are-you-altering-a-kiali-server-configuration-setting
A github issue will be required so we can track the PRs that will be required in at least the helm chart repo and the operator repo.

okay understood. I will close this PR and follow the contribution docs


how to train the model and reproduce the results？

This is an excellent work, but how to train the model and reproduce the results？

Hi, thanks for your interest. We are cleaning up the code and will release it as soon as it is ready.

+1