Support
Quality
Security
License
Reuse
kandi has reviewed generator and discovered the below as its top functions. This is intended to give you an instant insight into generator implemented functionality, and help decide if they suit your requirements.
A code generator for MyBatis.
How can I make an object with an interface like a random number generator, but that actually generates a specified sequence?
# make it a generator
def _rng():
while True:
yield np.random.randint(2,20)//2
# a non-random number generator
def _nrng():
numbers = np.arange(1,10.5,0.5)
for i in range(len(numbers)):
yield numbers[i]
rng = _rng()
nrng = _nrng()
for j in range(10):
print('random number', next(rng))
print('non-random number', next(nrng))
-----------------------
class NotRandom:
numbers = np.arange(1,10.5,0.5)
last_index = -1
@classmethod
def nrng(cls):
cls.last_index += 1
if cls.last_index < len(cls.numbers):
return cls.numbers[cls.last_index]
# else:
return None
# Create an alias to the classmethod
nrng = NotRandom.nrng # Note this is OUTSIDE the class
print(nrng()) # 1.0
print(nrng()) # 1.5
print(nrng()) # 2.0
class NotRandom:
def __init__(self):
self.numbers = np.arange(1,10.5,0.5)
self.last_index = -1
def nrng(self):
self.last_index += 1
if self.last_index < len(self.numbers):
return self.numbers[self.last_index]
# else:
return None
# Create an object. Then create an alias to its method
nrng = NotRandom().nrng
another_notrandom = NotRandom()
nrng2 = another_notrandom.rng
print(nrng()) # 1.0
print(nrng()) # 1.5
print(nrng2()) # 1.0
print(nrng()) # 2.0
print(nrng2()) # 1.5
-----------------------
class NotRandom:
numbers = np.arange(1,10.5,0.5)
last_index = -1
@classmethod
def nrng(cls):
cls.last_index += 1
if cls.last_index < len(cls.numbers):
return cls.numbers[cls.last_index]
# else:
return None
# Create an alias to the classmethod
nrng = NotRandom.nrng # Note this is OUTSIDE the class
print(nrng()) # 1.0
print(nrng()) # 1.5
print(nrng()) # 2.0
class NotRandom:
def __init__(self):
self.numbers = np.arange(1,10.5,0.5)
self.last_index = -1
def nrng(self):
self.last_index += 1
if self.last_index < len(self.numbers):
return self.numbers[self.last_index]
# else:
return None
# Create an object. Then create an alias to its method
nrng = NotRandom().nrng
another_notrandom = NotRandom()
nrng2 = another_notrandom.rng
print(nrng()) # 1.0
print(nrng()) # 1.5
print(nrng2()) # 1.0
print(nrng()) # 2.0
print(nrng2()) # 1.5
-----------------------
class NotRandom:
numbers = np.arange(1,10.5,0.5)
last_index = -1
@classmethod
def nrng(cls):
cls.last_index += 1
if cls.last_index < len(cls.numbers):
return cls.numbers[cls.last_index]
# else:
return None
# Create an alias to the classmethod
nrng = NotRandom.nrng # Note this is OUTSIDE the class
print(nrng()) # 1.0
print(nrng()) # 1.5
print(nrng()) # 2.0
class NotRandom:
def __init__(self):
self.numbers = np.arange(1,10.5,0.5)
self.last_index = -1
def nrng(self):
self.last_index += 1
if self.last_index < len(self.numbers):
return self.numbers[self.last_index]
# else:
return None
# Create an object. Then create an alias to its method
nrng = NotRandom().nrng
another_notrandom = NotRandom()
nrng2 = another_notrandom.rng
print(nrng()) # 1.0
print(nrng()) # 1.5
print(nrng2()) # 1.0
print(nrng()) # 2.0
print(nrng2()) # 1.5
-----------------------
class NotRandom:
numbers = np.arange(1,10.5,0.5)
last_index = -1
@classmethod
def nrng(cls):
cls.last_index += 1
if cls.last_index < len(cls.numbers):
return cls.numbers[cls.last_index]
# else:
return None
# Create an alias to the classmethod
nrng = NotRandom.nrng # Note this is OUTSIDE the class
print(nrng()) # 1.0
print(nrng()) # 1.5
print(nrng()) # 2.0
class NotRandom:
def __init__(self):
self.numbers = np.arange(1,10.5,0.5)
self.last_index = -1
def nrng(self):
self.last_index += 1
if self.last_index < len(self.numbers):
return self.numbers[self.last_index]
# else:
return None
# Create an object. Then create an alias to its method
nrng = NotRandom().nrng
another_notrandom = NotRandom()
nrng2 = another_notrandom.rng
print(nrng()) # 1.0
print(nrng()) # 1.5
print(nrng2()) # 1.0
print(nrng()) # 2.0
print(nrng2()) # 1.5
-----------------------
def nrng_gen():
yield from range(10)
nrng = nrng_gen()
nrng_func = lambda: next(nrng)
for i in range(10):
print(nrng_func())
class NRNG:
def __init__(self):
self.numbers = range(10)
self.state = -1
def __call__(self):
self.state += 1
return self.numbers[self.state]
nrng = NRNG()
for i in range(10):
print(nrng())
-----------------------
def nrng_gen():
yield from range(10)
nrng = nrng_gen()
nrng_func = lambda: next(nrng)
for i in range(10):
print(nrng_func())
class NRNG:
def __init__(self):
self.numbers = range(10)
self.state = -1
def __call__(self):
self.state += 1
return self.numbers[self.state]
nrng = NRNG()
for i in range(10):
print(nrng())
-----------------------
that_function(nrng().__next__)
that_function(partial(next, nrng()))
that_function(iter(np.arange(1,10.5,0.5)).__next__)
import numpy as np
from functools import partial
# a random number generator
rng = lambda : np.random.randint(2,20)//2
# a non-random number generator
def nrng():
numbers = np.arange(1,10.5,0.5)
for i in range(len(numbers)):
yield numbers[i]
def that_function(rng):
print(*(rng() for j in range(10)))
that_function(rng)
that_function(nrng().__next__)
that_function(iter(np.arange(1,10.5,0.5)).__next__)
that_function(partial(next, nrng()))
4 6 1 3 8 7 3 6 2 1
1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5
1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5
1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5
-----------------------
that_function(nrng().__next__)
that_function(partial(next, nrng()))
that_function(iter(np.arange(1,10.5,0.5)).__next__)
import numpy as np
from functools import partial
# a random number generator
rng = lambda : np.random.randint(2,20)//2
# a non-random number generator
def nrng():
numbers = np.arange(1,10.5,0.5)
for i in range(len(numbers)):
yield numbers[i]
def that_function(rng):
print(*(rng() for j in range(10)))
that_function(rng)
that_function(nrng().__next__)
that_function(iter(np.arange(1,10.5,0.5)).__next__)
that_function(partial(next, nrng()))
4 6 1 3 8 7 3 6 2 1
1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5
1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5
1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5
-----------------------
that_function(nrng().__next__)
that_function(partial(next, nrng()))
that_function(iter(np.arange(1,10.5,0.5)).__next__)
import numpy as np
from functools import partial
# a random number generator
rng = lambda : np.random.randint(2,20)//2
# a non-random number generator
def nrng():
numbers = np.arange(1,10.5,0.5)
for i in range(len(numbers)):
yield numbers[i]
def that_function(rng):
print(*(rng() for j in range(10)))
that_function(rng)
that_function(nrng().__next__)
that_function(iter(np.arange(1,10.5,0.5)).__next__)
that_function(partial(next, nrng()))
4 6 1 3 8 7 3 6 2 1
1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5
1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5
1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5
-----------------------
that_function(nrng().__next__)
that_function(partial(next, nrng()))
that_function(iter(np.arange(1,10.5,0.5)).__next__)
import numpy as np
from functools import partial
# a random number generator
rng = lambda : np.random.randint(2,20)//2
# a non-random number generator
def nrng():
numbers = np.arange(1,10.5,0.5)
for i in range(len(numbers)):
yield numbers[i]
def that_function(rng):
print(*(rng() for j in range(10)))
that_function(rng)
that_function(nrng().__next__)
that_function(iter(np.arange(1,10.5,0.5)).__next__)
that_function(partial(next, nrng()))
4 6 1 3 8 7 3 6 2 1
1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5
1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5
1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5
-----------------------
that_function(nrng().__next__)
that_function(partial(next, nrng()))
that_function(iter(np.arange(1,10.5,0.5)).__next__)
import numpy as np
from functools import partial
# a random number generator
rng = lambda : np.random.randint(2,20)//2
# a non-random number generator
def nrng():
numbers = np.arange(1,10.5,0.5)
for i in range(len(numbers)):
yield numbers[i]
def that_function(rng):
print(*(rng() for j in range(10)))
that_function(rng)
that_function(nrng().__next__)
that_function(iter(np.arange(1,10.5,0.5)).__next__)
that_function(partial(next, nrng()))
4 6 1 3 8 7 3 6 2 1
1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5
1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5
1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5
-----------------------
>>> def f():
yield 10
yield 20
yield 30
>>> g = f().__next__
>>> g()
10
>>> g()
20
>>> g()
30
-----------------------
# Get the first n numbers (10 in this case)
for i,j in enumerate(nrng()):
if i > 9:
break
print('random number', rng())
print('non-random number', j)
# Or this if you want to get all numbers in nrng()
for j in nrng():
print('random number', rng())
print('non-random number', j)
Why is `np.sum(range(N))` very slow?
/* Fast addition by keeping temporary sums in C instead of new Python objects.
Assumes all inputs are the same type. If the assumption fails, default
to the more general routine.
*/
from functools import singledispatch
def sum_range(range_, /, start=0):
"""Overloaded `sum` for range, compute arithmetic sum"""
n = len(range_)
if not n:
return start
return int(start + (n * (range_[0] + range_[-1]) / 2))
sum = singledispatch(sum)
sum.register(range, sum_range)
def test():
"""
>>> sum(range(0, 100))
4950
>>> sum(range(0, 10, 2))
20
>>> sum(range(0, 9, 2))
20
>>> sum(range(0, -10, -1))
-45
>>> sum(range(-10, 10))
-10
>>> sum(range(-1, -100, -2))
-2500
>>> sum(range(0, 10, 100))
0
>>> sum(range(0, 0))
0
>>> sum(range(0, 100), 50)
5000
>>> sum(range(0, 0), 10)
10
"""
if __name__ == "__main__":
import doctest
doctest.testmod()
-----------------------
/* Fast addition by keeping temporary sums in C instead of new Python objects.
Assumes all inputs are the same type. If the assumption fails, default
to the more general routine.
*/
from functools import singledispatch
def sum_range(range_, /, start=0):
"""Overloaded `sum` for range, compute arithmetic sum"""
n = len(range_)
if not n:
return start
return int(start + (n * (range_[0] + range_[-1]) / 2))
sum = singledispatch(sum)
sum.register(range, sum_range)
def test():
"""
>>> sum(range(0, 100))
4950
>>> sum(range(0, 10, 2))
20
>>> sum(range(0, 9, 2))
20
>>> sum(range(0, -10, -1))
-45
>>> sum(range(-10, 10))
-10
>>> sum(range(-1, -100, -2))
-2500
>>> sum(range(0, 10, 100))
0
>>> sum(range(0, 0))
0
>>> sum(range(0, 100), 50)
5000
>>> sum(range(0, 0), 10)
10
"""
if __name__ == "__main__":
import doctest
doctest.testmod()
-----------------------
# sum_range: 1.4830789409988938
# sum_rangelist: 3.6745876889999636
%%timeit x = list(range(N))
...: sum(x)
# npsum_range: 16.216972655000063
# npsum_fromiterrange:3.47655400199983
# sum_arange: 16.656015603000924
# sum_list_arange: 19.500842117000502
# sum_arange_tolist: 4.004777374000696
# npsum_arange: 0.2332638230000157
# array_basic: 16.1631146109994
# array_dtype: 16.550737804000164
# array_iter: 3.9803170430004684
-----------------------
# sum_range: 1.4830789409988938
# sum_rangelist: 3.6745876889999636
%%timeit x = list(range(N))
...: sum(x)
# npsum_range: 16.216972655000063
# npsum_fromiterrange:3.47655400199983
# sum_arange: 16.656015603000924
# sum_list_arange: 19.500842117000502
# sum_arange_tolist: 4.004777374000696
# npsum_arange: 0.2332638230000157
# array_basic: 16.1631146109994
# array_dtype: 16.550737804000164
# array_iter: 3.9803170430004684
-----------------------
# sum_range: 1.4830789409988938
# sum_rangelist: 3.6745876889999636
%%timeit x = list(range(N))
...: sum(x)
# npsum_range: 16.216972655000063
# npsum_fromiterrange:3.47655400199983
# sum_arange: 16.656015603000924
# sum_list_arange: 19.500842117000502
# sum_arange_tolist: 4.004777374000696
# npsum_arange: 0.2332638230000157
# array_basic: 16.1631146109994
# array_dtype: 16.550737804000164
# array_iter: 3.9803170430004684
-----------------------
# sum_range: 1.4830789409988938
# sum_rangelist: 3.6745876889999636
%%timeit x = list(range(N))
...: sum(x)
# npsum_range: 16.216972655000063
# npsum_fromiterrange:3.47655400199983
# sum_arange: 16.656015603000924
# sum_list_arange: 19.500842117000502
# sum_arange_tolist: 4.004777374000696
# npsum_arange: 0.2332638230000157
# array_basic: 16.1631146109994
# array_dtype: 16.550737804000164
# array_iter: 3.9803170430004684
-----------------------
# sum_range: 1.4830789409988938
# sum_rangelist: 3.6745876889999636
%%timeit x = list(range(N))
...: sum(x)
# npsum_range: 16.216972655000063
# npsum_fromiterrange:3.47655400199983
# sum_arange: 16.656015603000924
# sum_list_arange: 19.500842117000502
# sum_arange_tolist: 4.004777374000696
# npsum_arange: 0.2332638230000157
# array_basic: 16.1631146109994
# array_dtype: 16.550737804000164
# array_iter: 3.9803170430004684
-----------------------
# sum_range: 1.4830789409988938
# sum_rangelist: 3.6745876889999636
%%timeit x = list(range(N))
...: sum(x)
# npsum_range: 16.216972655000063
# npsum_fromiterrange:3.47655400199983
# sum_arange: 16.656015603000924
# sum_list_arange: 19.500842117000502
# sum_arange_tolist: 4.004777374000696
# npsum_arange: 0.2332638230000157
# array_basic: 16.1631146109994
# array_dtype: 16.550737804000164
# array_iter: 3.9803170430004684
-----------------------
# sum_range: 1.4830789409988938
# sum_rangelist: 3.6745876889999636
%%timeit x = list(range(N))
...: sum(x)
# npsum_range: 16.216972655000063
# npsum_fromiterrange:3.47655400199983
# sum_arange: 16.656015603000924
# sum_list_arange: 19.500842117000502
# sum_arange_tolist: 4.004777374000696
# npsum_arange: 0.2332638230000157
# array_basic: 16.1631146109994
# array_dtype: 16.550737804000164
# array_iter: 3.9803170430004684
-----------------------
# sum_range: 1.4830789409988938
# sum_rangelist: 3.6745876889999636
%%timeit x = list(range(N))
...: sum(x)
# npsum_range: 16.216972655000063
# npsum_fromiterrange:3.47655400199983
# sum_arange: 16.656015603000924
# sum_list_arange: 19.500842117000502
# sum_arange_tolist: 4.004777374000696
# npsum_arange: 0.2332638230000157
# array_basic: 16.1631146109994
# array_dtype: 16.550737804000164
# array_iter: 3.9803170430004684
-----------------------
# sum_range: 1.4830789409988938
# sum_rangelist: 3.6745876889999636
%%timeit x = list(range(N))
...: sum(x)
# npsum_range: 16.216972655000063
# npsum_fromiterrange:3.47655400199983
# sum_arange: 16.656015603000924
# sum_list_arange: 19.500842117000502
# sum_arange_tolist: 4.004777374000696
# npsum_arange: 0.2332638230000157
# array_basic: 16.1631146109994
# array_dtype: 16.550737804000164
# array_iter: 3.9803170430004684
-----------------------
# sum_range: 1.4830789409988938
# sum_rangelist: 3.6745876889999636
%%timeit x = list(range(N))
...: sum(x)
# npsum_range: 16.216972655000063
# npsum_fromiterrange:3.47655400199983
# sum_arange: 16.656015603000924
# sum_list_arange: 19.500842117000502
# sum_arange_tolist: 4.004777374000696
# npsum_arange: 0.2332638230000157
# array_basic: 16.1631146109994
# array_dtype: 16.550737804000164
# array_iter: 3.9803170430004684
-----------------------
tmp = list(range(10_000_000))
# Numpy implicitly convert the list in a Numpy array but
# still automatically detect the input type to use
np.sum(tmp)
tmp = list(range(10_000_000))
# The array is explicitly converted using a well-defined type and
# thus there is no need to perform an automatic detection
# (note that the result is still wrong since it does not fit in a np.int32)
tmp2 = np.array(tmp, dtype=np.int32)
result = np.sum(tmp2)
-----------------------
tmp = list(range(10_000_000))
# Numpy implicitly convert the list in a Numpy array but
# still automatically detect the input type to use
np.sum(tmp)
tmp = list(range(10_000_000))
# The array is explicitly converted using a well-defined type and
# thus there is no need to perform an automatic detection
# (note that the result is still wrong since it does not fit in a np.int32)
tmp2 = np.array(tmp, dtype=np.int32)
result = np.sum(tmp2)
How would you implement a lazy "range factory" for C++20 ranges that just calls a generator function?
class iterator {
public:
using value_type = decltype(std::declval<F>()());
using difference_type = std::ptrdiff_t;
iterator() = default;
void operator++(int);
bool operator==(const iterator&) const {
return false;
}
// ...
};
template<typename F>
class generate2 : public std::ranges::view_interface<generate2<F>> {
public:
auto begin() {
value_ = generator_func_();
return iterator{*this};
}
std::default_sentinel_t end() const noexcept { return std::default_sentinel; }
class iterator {
public:
//...
value_type operator*() const {
return parent_->value_;
}
private:
generate2* parent_;
};
private:
F generator_func_;
std::remove_cvref_t<std::invoke_result_t<F&>> value_;
};
-----------------------
class iterator {
public:
using value_type = decltype(std::declval<F>()());
using difference_type = std::ptrdiff_t;
iterator() = default;
void operator++(int);
bool operator==(const iterator&) const {
return false;
}
// ...
};
template<typename F>
class generate2 : public std::ranges::view_interface<generate2<F>> {
public:
auto begin() {
value_ = generator_func_();
return iterator{*this};
}
std::default_sentinel_t end() const noexcept { return std::default_sentinel; }
class iterator {
public:
//...
value_type operator*() const {
return parent_->value_;
}
private:
generate2* parent_;
};
private:
F generator_func_;
std::remove_cvref_t<std::invoke_result_t<F&>> value_;
};
Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: Package subpath './lib/tokenize' is not defined by "exports" in the package.json of a module in node_modules
nvm uninstall <version>
nvm uninstall v17.0.1
nvm install --lts
-----------------------
nvm uninstall <version>
nvm uninstall v17.0.1
nvm install --lts
-----------------------
nvm uninstall <version>
nvm uninstall v17.0.1
nvm install --lts
-----------------------
npm install -g n
sudo n stable
sudo n 16.8.0
export N_PREFIX=$HOME/.n
export PATH=$N_PREFIX/bin:$PATH
-----------------------
npm install -g n
sudo n stable
sudo n 16.8.0
export N_PREFIX=$HOME/.n
export PATH=$N_PREFIX/bin:$PATH
-----------------------
npm install -g n
sudo n stable
sudo n 16.8.0
export N_PREFIX=$HOME/.n
export PATH=$N_PREFIX/bin:$PATH
-----------------------
npm install -g n
sudo n stable
sudo n 16.8.0
export N_PREFIX=$HOME/.n
export PATH=$N_PREFIX/bin:$PATH
-----------------------
npm audit fix --force
npm install react-scripts@latest
-----------------------
npm audit fix --force
npm install react-scripts@latest
-----------------------
npm update
npm start
-----------------------
rm -rf node_modules yarn.lock
yarn add -D react-scripts@latest
yarn build
rm -rf node_modules package-lock.json
npm install -D react-scripts@latest
npm install
npm run build
-----------------------
rm -rf node_modules yarn.lock
yarn add -D react-scripts@latest
yarn build
rm -rf node_modules package-lock.json
npm install -D react-scripts@latest
npm install
npm run build
-----------------------
brew uninstall --ignore-dependencies node
brew install node@16
brew link node@16
-----------------------
brew uninstall node
-----------------------
npm install
`npm install --legacy-peer-deps`
npm start
-----------------------
npm install
`npm install --legacy-peer-deps`
npm start
-----------------------
npm install
`npm install --legacy-peer-deps`
npm start
-----------------------
npm install react@latest react-dom@latest
npm install next@12
Can you compress angular image assets on build?
const { src, dest } = require("gulp");
const sharpResponsive = require("gulp-sharp-responsive");
const compress = () =>
src("images/*.{png,jpg}")
.pipe(
sharpResponsive({
formats: [
// jpeg
{ width: 256, format: "jpeg", rename: { suffix: "-256" } },
{ width: 512, format: "jpeg", rename: { suffix: "-512" } },
{ width: 1024, format: "jpeg", rename: { suffix: "-1024" } },
// webp
{ width: 256, format: "webp", rename: { suffix: "-256" } },
{ width: 512, format: "webp", rename: { suffix: "-512" } },
{ width: 1024, format: "webp", rename: { suffix: "-1024" } },
// avif
{ width: 256, format: "avif", rename: { suffix: "-256" } },
{ width: 512, format: "avif", rename: { suffix: "-512" } },
{ width: 1024, format: "avif", rename: { suffix: "-1024" } },
],
})
)
.pipe(dest("src/assets/compressed"));
module.exports = {
compress,
};
"scripts": {
"prebuild": "gulp compress",
// ...
},
<!-- {{image}} is the image name -->
<picture *ngIf="image">
<!-- avif -->
<source
srcset="assets/compressed/{{image}}-256.avif"
media="(max-width: 512px)"
type="image/avif"
/>
<source
srcset="assets/compressed/{{image}}-512.avif"
media="(max-width: 1024px)"
type="image/avif"
/>
<source
srcset="assets/compressed/{{image}}-1024.avif"
media="(max-width: 2048px)"
type="image/avif"
/>
<!-- webp -->
<source
srcset="assets/compressed/{{image}}-256.webp"
media="(max-width: 512px)"
type="image/webp"
/>
<source
srcset="assets/compressed/{{image}}-512.webp"
media="(max-width: 1024px)"
type="image/webp"
/>
<source
srcset="assets/compressed/{{image}}-1024.webp"
media="(max-width: 2048px)"
type="image/webp"
/>
<!-- jpeg -->
<source
srcset="assets/compressed/{{image}}-256.jpg"
media="(max-width: 512px)"
type="image/jpeg"
/>
<source
srcset="assets/compressed/{{image}}-512.jpg"
media="(max-width: 1024px)"
type="image/jpeg"
/>
<source
srcset="assets/compressed/{{image}}-1024.jpg"
media="(max-width: 2048px)"
type="image/jpeg"
/>
<!-- original -->
<img src="assets/compressed/{{ image }}-1024.jpg" />
</picture>
-----------------------
const { src, dest } = require("gulp");
const sharpResponsive = require("gulp-sharp-responsive");
const compress = () =>
src("images/*.{png,jpg}")
.pipe(
sharpResponsive({
formats: [
// jpeg
{ width: 256, format: "jpeg", rename: { suffix: "-256" } },
{ width: 512, format: "jpeg", rename: { suffix: "-512" } },
{ width: 1024, format: "jpeg", rename: { suffix: "-1024" } },
// webp
{ width: 256, format: "webp", rename: { suffix: "-256" } },
{ width: 512, format: "webp", rename: { suffix: "-512" } },
{ width: 1024, format: "webp", rename: { suffix: "-1024" } },
// avif
{ width: 256, format: "avif", rename: { suffix: "-256" } },
{ width: 512, format: "avif", rename: { suffix: "-512" } },
{ width: 1024, format: "avif", rename: { suffix: "-1024" } },
],
})
)
.pipe(dest("src/assets/compressed"));
module.exports = {
compress,
};
"scripts": {
"prebuild": "gulp compress",
// ...
},
<!-- {{image}} is the image name -->
<picture *ngIf="image">
<!-- avif -->
<source
srcset="assets/compressed/{{image}}-256.avif"
media="(max-width: 512px)"
type="image/avif"
/>
<source
srcset="assets/compressed/{{image}}-512.avif"
media="(max-width: 1024px)"
type="image/avif"
/>
<source
srcset="assets/compressed/{{image}}-1024.avif"
media="(max-width: 2048px)"
type="image/avif"
/>
<!-- webp -->
<source
srcset="assets/compressed/{{image}}-256.webp"
media="(max-width: 512px)"
type="image/webp"
/>
<source
srcset="assets/compressed/{{image}}-512.webp"
media="(max-width: 1024px)"
type="image/webp"
/>
<source
srcset="assets/compressed/{{image}}-1024.webp"
media="(max-width: 2048px)"
type="image/webp"
/>
<!-- jpeg -->
<source
srcset="assets/compressed/{{image}}-256.jpg"
media="(max-width: 512px)"
type="image/jpeg"
/>
<source
srcset="assets/compressed/{{image}}-512.jpg"
media="(max-width: 1024px)"
type="image/jpeg"
/>
<source
srcset="assets/compressed/{{image}}-1024.jpg"
media="(max-width: 2048px)"
type="image/jpeg"
/>
<!-- original -->
<img src="assets/compressed/{{ image }}-1024.jpg" />
</picture>
-----------------------
const { src, dest } = require("gulp");
const sharpResponsive = require("gulp-sharp-responsive");
const compress = () =>
src("images/*.{png,jpg}")
.pipe(
sharpResponsive({
formats: [
// jpeg
{ width: 256, format: "jpeg", rename: { suffix: "-256" } },
{ width: 512, format: "jpeg", rename: { suffix: "-512" } },
{ width: 1024, format: "jpeg", rename: { suffix: "-1024" } },
// webp
{ width: 256, format: "webp", rename: { suffix: "-256" } },
{ width: 512, format: "webp", rename: { suffix: "-512" } },
{ width: 1024, format: "webp", rename: { suffix: "-1024" } },
// avif
{ width: 256, format: "avif", rename: { suffix: "-256" } },
{ width: 512, format: "avif", rename: { suffix: "-512" } },
{ width: 1024, format: "avif", rename: { suffix: "-1024" } },
],
})
)
.pipe(dest("src/assets/compressed"));
module.exports = {
compress,
};
"scripts": {
"prebuild": "gulp compress",
// ...
},
<!-- {{image}} is the image name -->
<picture *ngIf="image">
<!-- avif -->
<source
srcset="assets/compressed/{{image}}-256.avif"
media="(max-width: 512px)"
type="image/avif"
/>
<source
srcset="assets/compressed/{{image}}-512.avif"
media="(max-width: 1024px)"
type="image/avif"
/>
<source
srcset="assets/compressed/{{image}}-1024.avif"
media="(max-width: 2048px)"
type="image/avif"
/>
<!-- webp -->
<source
srcset="assets/compressed/{{image}}-256.webp"
media="(max-width: 512px)"
type="image/webp"
/>
<source
srcset="assets/compressed/{{image}}-512.webp"
media="(max-width: 1024px)"
type="image/webp"
/>
<source
srcset="assets/compressed/{{image}}-1024.webp"
media="(max-width: 2048px)"
type="image/webp"
/>
<!-- jpeg -->
<source
srcset="assets/compressed/{{image}}-256.jpg"
media="(max-width: 512px)"
type="image/jpeg"
/>
<source
srcset="assets/compressed/{{image}}-512.jpg"
media="(max-width: 1024px)"
type="image/jpeg"
/>
<source
srcset="assets/compressed/{{image}}-1024.jpg"
media="(max-width: 2048px)"
type="image/jpeg"
/>
<!-- original -->
<img src="assets/compressed/{{ image }}-1024.jpg" />
</picture>
Convert a bytes iterable to an iterable of str, where each value is a line
import re
find_rule = re.compile("([^\r\n]*)(\r\n|\r|\n)?")
def converter(byte_data):
left_d = ""
for d in byte_data:
# Used to save the previous match result in the `for` loop
prev_result = None
# Concatenate the last part of the previous data with the current data,
# used to deal with the case of `\r\n` being separated.
d = left_d + d.decode()
left_d = ""
# Using `find_rule.finditer` the last value("") will be invalid
for match_result in find_rule.finditer(d):
i = match_result.group()
if not i:
# The program comes to this point, indicating that i == "", which is the last matching value
left_d, prev_result = prev_result.group(), None
continue
if prev_result:
if prev_result.group(2) is None:
# The program goes here, represented as the last valid value matched
left_d = prev_result.group()
else:
# Returns the previous matched value
yield prev_result.group()
# Save the current match result
prev_result = match_result
else:
yield left_d
for i in (converter(iter((
b'col_1,\r',
b'\nc',
b'ol_2\n1',
b'\n,"val;\r',
b'ue"\n')))
):
print(repr(i))
'col_1,\r\n'
'col_2\n'
'1\n'
',"val;\r'
'ue"\n'
-----------------------
import re
find_rule = re.compile("([^\r\n]*)(\r\n|\r|\n)?")
def converter(byte_data):
left_d = ""
for d in byte_data:
# Used to save the previous match result in the `for` loop
prev_result = None
# Concatenate the last part of the previous data with the current data,
# used to deal with the case of `\r\n` being separated.
d = left_d + d.decode()
left_d = ""
# Using `find_rule.finditer` the last value("") will be invalid
for match_result in find_rule.finditer(d):
i = match_result.group()
if not i:
# The program comes to this point, indicating that i == "", which is the last matching value
left_d, prev_result = prev_result.group(), None
continue
if prev_result:
if prev_result.group(2) is None:
# The program goes here, represented as the last valid value matched
left_d = prev_result.group()
else:
# Returns the previous matched value
yield prev_result.group()
# Save the current match result
prev_result = match_result
else:
yield left_d
for i in (converter(iter((
b'col_1,\r',
b'\nc',
b'ol_2\n1',
b'\n,"val;\r',
b'ue"\n')))
):
print(repr(i))
'col_1,\r\n'
'col_2\n'
'1\n'
',"val;\r'
'ue"\n'
-----------------------
class ReadableIterator(io.IOBase):
def __init__(self, it):
self.it = iter(it)
def read(self, n):
# ignore argument, nobody actually cares
# note that it is *critical* that we suppress the `StopIteration` here
return next(self.it, b'')
def readable(self):
return True
-----------------------
from itertools import groupby, chain
bytes_iter = (
b'col_1,',
b'c',
b'ol_2\n',
b'1,"val;',
b'ue"\n'
)
def make_strings(G):
strings = chain.from_iterable(map(bytes.decode, G))
for k, g in groupby(strings, key=lambda c: c not in '\n\r'):
if k:
yield ''.join(g)
list(make_strings(bytes_iter))
# ['col_1,col_2', '1,"val;ue"']
-----------------------
import codecs
import csv
import io
def yield_bytes():
chunks = [
b'col_1,',
b'c',
b'ol_2\n1',
b',"val',
b'ue"\n',
b'Hello,'
b'\xe4\xb8',
b'\x96',
b'\xe7',
b'\x95\x8c\n'
b'\n'
]
for chunk in chunks:
yield(chunk)
decoder = codecs.getincrementaldecoder('utf-8')()
def yield_encoded_bytes():
s = None
for bytes in yield_bytes():
s = decoder.decode(bytes, final=False)
if s:
yield s.encode('utf-8')
class ReadableIterator(io.IOBase):
def __init__(self, it):
self.it = iter(it)
def read(self, n):
# ignore argument, nobody actually cares
# note that it is *critical* that we suppress the `StopIteration` here
return next(self.it, b'')
def readable(self):
return True
f = io.TextIOWrapper(ReadableIterator(yield_encoded_bytes()))
for row in csv.reader(f):
print(row)
['col_1', 'col_2']
['1', 'value']
['Hello', '世界']
[]
-----------------------
import codecs
import csv
import io
def yield_bytes():
chunks = [
b'col_1,',
b'c',
b'ol_2\n1',
b',"val',
b'ue"\n',
b'Hello,'
b'\xe4\xb8',
b'\x96',
b'\xe7',
b'\x95\x8c\n'
b'\n'
]
for chunk in chunks:
yield(chunk)
decoder = codecs.getincrementaldecoder('utf-8')()
def yield_encoded_bytes():
s = None
for bytes in yield_bytes():
s = decoder.decode(bytes, final=False)
if s:
yield s.encode('utf-8')
class ReadableIterator(io.IOBase):
def __init__(self, it):
self.it = iter(it)
def read(self, n):
# ignore argument, nobody actually cares
# note that it is *critical* that we suppress the `StopIteration` here
return next(self.it, b'')
def readable(self):
return True
f = io.TextIOWrapper(ReadableIterator(yield_encoded_bytes()))
for row in csv.reader(f):
print(row)
['col_1', 'col_2']
['1', 'value']
['Hello', '世界']
[]
Problem Updating to .Net 6 - Encrypting String
using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
{
var plainTextBytes = new byte[cipherTextBytes.Length];
var decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
memoryStream.Close();
cryptoStream.Close();
return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
}
using (var plainTextStream = new MemoryStream())
{
cryptoStream.CopyTo(plainTextStream);
var plainTextBytes = plainTextStream.ToArray();
return Encoding.UTF8.GetString(plainTextBytes, 0, plainTextBytes.Length);
}
using (var plainTextReader = new StreamReader(cryptoStream))
{
return plainTextReader.ReadToEnd();
}
-----------------------
using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
{
var plainTextBytes = new byte[cipherTextBytes.Length];
var decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
memoryStream.Close();
cryptoStream.Close();
return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
}
using (var plainTextStream = new MemoryStream())
{
cryptoStream.CopyTo(plainTextStream);
var plainTextBytes = plainTextStream.ToArray();
return Encoding.UTF8.GetString(plainTextBytes, 0, plainTextBytes.Length);
}
using (var plainTextReader = new StreamReader(cryptoStream))
{
return plainTextReader.ReadToEnd();
}
-----------------------
using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
{
var plainTextBytes = new byte[cipherTextBytes.Length];
var decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
memoryStream.Close();
cryptoStream.Close();
return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
}
using (var plainTextStream = new MemoryStream())
{
cryptoStream.CopyTo(plainTextStream);
var plainTextBytes = plainTextStream.ToArray();
return Encoding.UTF8.GetString(plainTextBytes, 0, plainTextBytes.Length);
}
using (var plainTextReader = new StreamReader(cryptoStream))
{
return plainTextReader.ReadToEnd();
}
-----------------------
var decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
return new StreamReader(cryptoStream).ReadToEnd();
-----------------------
var decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
return new StreamReader(cryptoStream).ReadToEnd();
-----------------------
int totalRead = 0;
int maxRead = 16;
while (totalRead < plainTextBytes.Length)
{
var countLeft = plainTextBytes.Length - totalRead;
var count = countLeft < 16 ? countLeft : maxRead;
int bytesRead = cryptoStream.Read(plainTextBytes, totalRead, count);
totalRead += bytesRead;
if (bytesRead == 0) break;
}
Ensure that an argument can be iterated twice
if isinstance(x, zip):
x = list(x)
-----------------------
def print_twice(x):
val = x
for i in range(2):
for i in val: print(i)
-----------------------
def print_twice(x):
x = list(x)
for i in x: print(i)
for i in x: print(i)
from collections.abc import Collection
x = list(x) if not isinstance(x, Collection) else x
from collections.abc import Iterator
x = list(x) if isinstance(x, Iterator) else x
x = list(x) if iter(x) is x else x
-----------------------
def print_twice(x):
x = list(x)
for i in x: print(i)
for i in x: print(i)
from collections.abc import Collection
x = list(x) if not isinstance(x, Collection) else x
from collections.abc import Iterator
x = list(x) if isinstance(x, Iterator) else x
x = list(x) if iter(x) is x else x
-----------------------
def print_twice(x):
x = list(x)
for i in x: print(i)
for i in x: print(i)
from collections.abc import Collection
x = list(x) if not isinstance(x, Collection) else x
from collections.abc import Iterator
x = list(x) if isinstance(x, Iterator) else x
x = list(x) if iter(x) is x else x
-----------------------
def is_iterator(x):
return iter(x) is x
for obj in [
# not iterators
[1, 2, 3],
(1, 2, 3),
{1: 2, 3: 4},
range(3),
# iterators
(x for x in range(3)),
iter([1, 2, 3]),
zip([1, 2], [3, 4]),
filter(lambda x: x % 2 == 0, [1, 2, 3]),
map(lambda x: 2 * x, [1, 2, 3]),
]:
name = type(obj).__name__
if is_iterator(obj):
print(name, 'is an iterator')
else:
print(name, 'is not an iterator')
list is not an iterator
tuple is not an iterator
dict is not an iterator
range is not an iterator
generator is an iterator
list_iterator is an iterator
zip is an iterator
filter is an iterator
map is an iterator
if iter(x) is x:
x = list(x)
-----------------------
def is_iterator(x):
return iter(x) is x
for obj in [
# not iterators
[1, 2, 3],
(1, 2, 3),
{1: 2, 3: 4},
range(3),
# iterators
(x for x in range(3)),
iter([1, 2, 3]),
zip([1, 2], [3, 4]),
filter(lambda x: x % 2 == 0, [1, 2, 3]),
map(lambda x: 2 * x, [1, 2, 3]),
]:
name = type(obj).__name__
if is_iterator(obj):
print(name, 'is an iterator')
else:
print(name, 'is not an iterator')
list is not an iterator
tuple is not an iterator
dict is not an iterator
range is not an iterator
generator is an iterator
list_iterator is an iterator
zip is an iterator
filter is an iterator
map is an iterator
if iter(x) is x:
x = list(x)
-----------------------
def is_iterator(x):
return iter(x) is x
for obj in [
# not iterators
[1, 2, 3],
(1, 2, 3),
{1: 2, 3: 4},
range(3),
# iterators
(x for x in range(3)),
iter([1, 2, 3]),
zip([1, 2], [3, 4]),
filter(lambda x: x % 2 == 0, [1, 2, 3]),
map(lambda x: 2 * x, [1, 2, 3]),
]:
name = type(obj).__name__
if is_iterator(obj):
print(name, 'is an iterator')
else:
print(name, 'is not an iterator')
list is not an iterator
tuple is not an iterator
dict is not an iterator
range is not an iterator
generator is an iterator
list_iterator is an iterator
zip is an iterator
filter is an iterator
map is an iterator
if iter(x) is x:
x = list(x)
Proper way to DI NSwag auto-generated client
<ItemGroup>
<OpenApiReference Include="OpenAPIs\swagger.json" CodeGenerator="NSwagCSharp" Namespace="xxx" ClassName="Client">
<SourceUri>https://localhost:44353/swagger/v1/swagger.json</SourceUri>
<Options>/UseBaseUrl:false /GenerateClientInterfaces:true</Options>
</OpenApiReference>
</ItemGroup>
-----------------------
public partial class MyApiClient : IMyApiClient
{
[ActivatorUtilitiesConstructor] // This ctor will be used by DI
public MyApiClient(HttpClient httpClient, IOptions<MyApiClientOptions> clientOptions)
: this(clientOptions.Value.Url, httpClient) // Call generated ctor
{
}
}
How to alias generic types for decorators
import unittest
from typing import *
T = TypeVar("T", bound=unittest.TestCase)
def decorate(func: Callable[[T], None]) -> Callable[[T], None]:
def decorated_function(self: T) -> None:
return func(self)
return decorated_function
decorator_variable: Callable[[Callable[[T], None]], Callable[[T], None]] = decorate
U = Callable[[T], None]
my_decorate: Callable[[U[T]], U[T]] = decorator_variable
-----------------------
class TD(Protocol):
"""Type of any callable `(T -> None) -> (T -> None)` for all `T`"""
def __call__(self, __original: Callable[[T], None]) -> Callable[[T], None]:
...
my_decorate: TD = decorate
-----------------------
class TD(Protocol):
"""Type of any callable `(T -> None) -> (T -> None)` for all `T`"""
def __call__(self, __original: Callable[[T], None]) -> Callable[[T], None]:
...
my_decorate: TD = decorate
QUESTION
How can I make an object with an interface like a random number generator, but that actually generates a specified sequence?
Asked 2022-Mar-31 at 13:47I'd like to construct an object that works like a random number generator, but generates numbers in a specified sequence.
# a random number generator
rng = lambda : np.random.randint(2,20)//2
# a non-random number generator
def nrng():
numbers = np.arange(1,10.5,0.5)
for i in range(len(numbers)):
yield numbers[i]
for j in range(10):
print('random number', rng())
print('non-random number', nrng())
The issue with the code above that I cannot call nrng
in the last line because it is a generator. I know that the most straightforward way to rewrite the code above is to simply loop over the non-random numbers instead of defining the generator. I would prefer getting the example above to work because I am working with a large chunk of code that include a function that accepts a random number generator as an argument, and I would like to add the functionality to pass non-random number sequences without rewriting the entire code.
EDIT: I see some confusion in the comments. I am aware that python's random number generators generate pseudo-random numbers. This post is about replacing a pseudo-random-number generator by a number generator that generates numbers from a non-random, user-specified sequence (e.g., a generator that generates the number sequence 1,1,2,2,1,0,1
if I want it to).
ANSWER
Answered 2022-Mar-29 at 00:47You can call next()
with a generator or iterator as an argument to withdraw exactly one element from it. Saving the generator to a variable beforehand allows you to do this multiple times.
# make it a generator
def _rng():
while True:
yield np.random.randint(2,20)//2
# a non-random number generator
def _nrng():
numbers = np.arange(1,10.5,0.5)
for i in range(len(numbers)):
yield numbers[i]
rng = _rng()
nrng = _nrng()
for j in range(10):
print('random number', next(rng))
print('non-random number', next(nrng))
Community Discussions, Code Snippets contain sources that include Stack Exchange Network
No vulnerabilities reported
Save this library and start creating your kit
Explore Related Topics
Save this library and start creating your kit