EventEmitter's typesafe replacement

EventEmitter’s typesafe replacement

'evt' is intended to be a replacement for 'events'.
It enables and encourages functional programming and makes heavy use of typescript’s type inference features to provide type safety while keeping things concise and elegant 🍸.

Suitable for any JS runtime env (deno, node, old browsers, react-native …)

  • ✅ It is both a Deno and an NPM module. ( Achieved with Denoify )
  • ✅ Lightweight, no dependency.
  • ✅ No polyfills needed, the NPM module is transpiled down to ES3
  • ✅ React Hooks integration

Can be imported in TypeScript projects using version >= 3.4 (Mar 2019) and in any plain JS projects.

TL;DR*

import { Evt } from "evt";

const evtText = new Evt<string>();
const evtTime = new Evt<number>();

evtText.attach(text => console.log(text));
evtTime.attachOnce(time => console.log(time));

evtText.post("hi!"); //Prints "hi!"
evtTime.post(123);   //Prints "123"
evtTime.post(1234);  //Prints nothing

OR

import { Evt, to } from "evt";

const evt = new Evt<
    [ "text",  string ] | 
    [ "time",  number ]
>();

//Mind the '$' prefixing 'attach'
evt.$attach(to("text"), text => console.log(text));
evt.$attachOnce(to("time"), time => console.log(time));

evt.post(["text", "hi!"]);
evt.post(["time", 123]);
evt.post(["time", 1234]);

*Those are introductory examples, EVT can do much more than this.

Who is using it


Install / Import

In Deno:

import { Evt } from "https://deno.land/x/evt/mod.ts";

Anywhere else:

$ npm install --save evt
import { Evt } from "evt"; 

Import from HTML, with CDN

<script src="//unpkg.com/evt/bundle.min.js"></script>
<script>
    const { Evt } = window["evt"];
</script>

Try it

Run some examples

Motivations

There are a lot of things that can’t easily be done with EventEmitter:

  • Enforcing type safety.
  • Removing a particular listener ( if the callback is an anonymous function ).
  • Adding a one-time listener for the next event that meets a condition.
  • Waiting (via a Promise) for one thing or another to happen.
    Example: waiting at most one second for the next message, stop waiting if the socket disconnects.

Why would someone pick EVT over RxJS:

  • RxJS introduces a lot of abstractions. It’s a big jump from EventEmitter.
  • With RxJS It is often needed to resort to custom type guards, the filter operator breaks the type inference.
  • RxJS tends to be quite verbose.
  • It could be months before RxJS it eventually supports Deno.
  • No official guideline on how to integrate RxJS with React.

EVT is an attempt to address all these points while trying to remain as accessible as EventEmitter.

Get started

Download Details:

Author: garronej

Demo: https://www.evt.land/

Source Code: https://github.com/garronej/evt

#deno #nodejs #node #javascript

What is GEEK

Buddha Community

EventEmitter's typesafe replacement
Harsha  Shirali

Harsha Shirali

1669174554

Replace Elements in Python NumPy Array with Example

In this article, we will learn how to replace elements in Python NumPy Array. To replace elements in Python NumPy Array, We can follow the following examples.

Example 1 : Replace Elements Equal to Some Value

The following code shows how to replace all elements in the NumPy array equal to 8 with a new value of 20:

#replace all elements equal to 8 with 20
my_array[my_array == 8] = 20

#view updated array
print(my_array)

[ 4  5  5  7 20 20  9 12]

Example 2: Replace Elements Based on One Condition

The following code shows how to replace all elements in the NumPy array greater than 8 with a new value of 20:

#replace all elements greater than 8 with 20
my_array[my_array > 8] = 20

#view updated array
print(my_array)

[ 4  5  5  7  8  8 20 20]

Example 3: Replace Elements Based on Multiple Conditions

The following code shows how to replace all elements in the NumPy array greater than 8 or less than 6 with a new value of 20:

#replace all elements greater than 8 or less than 6 with a new value of 20
my_array[(my_array > 8) | (my_array < 6)] = 20

#view updated array
print(my_array)

[20 20 20  7  8  8 20 20]

#python 
 

Python String.Replace() – Function in Python for Substring Substitution

In this article you'll see how to use Python's .replace() method to perform substring substiution.

You'll also see how to perform case-insensitive substring substitution.

Let's get started!

What does the .replace() Python method do?

When using the .replace() Python method, you are able to replace every instance of one specific character with a new one. You can even replace a whole string of text with a new line of text that you specify.

The .replace() method returns a copy of a string. This means that the old substring remains the same, but a new copy gets created – with all of the old text having been replaced by the new text.

How does the .replace() Python method work? A Syntax Breakdown

The syntax for the .replace() method looks like this:

string.replace(old_text, new_text, count)

Let's break it down:

  • old_text is the first required parameter that .replace() accepts. It's the old character or text that you want to replace. Enclose this in quotation marks.
  • new_text is the second required parameter that .replace() accepts. It's the new character or text which you want to replace the old character/text with. This parameter also needs to be enclosed in quotation marks.
  • count is the optional third parameter that .replace() accepts. By default, .replace() will replace all instances of the substring. However, you can use count to specify the number of occurrences you want to be replaced.

Python .replace() Method Code Examples

How to Replace All Instances of a Single Character

To change all instances of a single character, you would do the following:

phrase = "I like to learn coding on the go"

# replace all instances of 'o' with 'a'
substituted_phrase = phrase.replace("o", "a" )

print(phrase)
print(substituted_phrase)

#output

#I like to learn coding on the go
#I like ta learn cading an the ga

In the example above, each word that contained the character o is replaced with the character a.

In that example there were four instances of the character o. Specifically, it was found in the words to, coding, on, and go.

What if you only wanted to change two words, like to and coding, to contain a instead of o?

How to Replace Only a Certain Number of Instances of a Single Character

To change only two instances of a single character, you would use the count parameter and set it to two:

phrase = "I like to learn coding on the go"

# replace only the first two instances of 'o' with 'a'
substituted_phrase = phrase.replace("o", "a", 2 )

print(phrase)
print(substituted_phrase)

#output

#I like to learn coding on the go
#I like ta learn cading on the go

If you only wanted to change the first instance of a single character, you would set the count parameter to one:

phrase = "I like to learn coding on the go"

# replace only the first instance of 'o' with 'a'
substituted_phrase = phrase.replace("o", "a", 1 )

print(phrase)
print(substituted_phrase)

#output

#I like to learn coding on the go
#I like ta learn coding on the go

How to Replace All Instances of a String

To change more than one character, the process looks similar.

phrase = "The sun is strong today. I don't really like sun."

#replace all instances of the word 'sun' with 'wind'
substituted_phrase = phrase.replace("sun", "wind")

print(phrase)
print(substituted_phrase)

#output

#The sun is strong today. I don't really like sun.
#The wind is strong today. I don't really like wind.

In the example above, the word sun was replaced with the word wind.

How to Replace Only a Certain Number of Instances of a String

If you wanted to change only the first instance of sun to wind, you would use the count parameter and set it to one.

phrase = "The sun is strong today. I don't really like sun."

#replace only the first instance of the word 'sun' with 'wind'
substituted_phrase = phrase.replace("sun", "wind", 1)

print(phrase)
print(substituted_phrase)

#output

#The sun is strong today. I don't really like sun.
#The wind is strong today. I don't really like sun.

How to Perform Case-Insensitive Substring Substitution in Python

Let's take a look at another example.


phrase = "I am learning Ruby. I really enjoy the ruby programming language!"

#replace the text "Ruby" with "Python"
substituted_text = phrase.replace("Ruby", "Python")

print(substituted_text)

#output

#I am learning Python. I really enjoy the ruby programming language!

In this case, what I really wanted to do was to replace all instances of the word Ruby with Python.

However, there was the word ruby with a lowercase r, which I would also like to change.

Because the first letter was in lowercase, and not uppercase as I specified with Ruby, it remained the same and didn't change to Python.

The .replace() method is case-sensitive, and therefore it performs a case-sensitive substring substitution.

In order to perform a case-insensitive substring substitution you would have to do something different.

You would need to use the re.sub() function and use the re.IGNORECASE flag.

To use re.sub() you need to:

  • Use the re module, via import re.
  • Speficy a regular expression pattern.
  • Mention with what you want to replace the pattern.
  • Mention the string you want to perform this operation on.
  • Optionally, specify the count parameter to make the replacement more precise and specify the maximum number of replacements you want to take place.
  • The re.IGNORECASE flag tells the regular expression to perform a case-insensitive match.

So, all together the syntax looks like this:

import re

re.sub(pattern, replace, string, count, flags) 

Taking the example from earlier:

phrase = "I am learning Ruby. I really enjoy the ruby programming language!"

This is how I would replace both Ruby and ruby with Python:

import re

phrase = "I am learning Ruby. I really enjoy the ruby programming language!"

phrase = re.sub("Ruby","Python", phrase, flags=re.IGNORECASE)

print(phrase)

#output

#I am learning Python. I really enjoy the Python programming language!

Wrapping up

And there you have it - you now know the basics of substring substitution. Hopefully you found this guide helpful.

To learn more about Python, check out freeCodeCamp's Scientific Computing with Python Certification.

You'll start from the basics and learn in an interacitve and beginner-friendly way. You'll also build five projects at the end to put into practice and help reinforce what you learned.

Thanks for reading and happy coding!

Link: https://www.freecodecamp.org/news/python-string-replace-function-in-python-for-substring-substitution/

#python 

Python String.Replace()– 部分文字列置換のためのPythonの関数

この記事では、Pythonの.replace()メソッドを使用して部分文字列の置換を実行する方法を説明します。

また、大文字と小文字を区別しない部分文字列置換を実行する方法についても説明します。

始めましょう!

Pythonメソッドは何をし.replace()ますか?

Pythonメソッドを使用する.replace()と、特定の1つの文字のすべてのインスタンスを新しいものに置き換えることができます。テキストの文字列全体を、指定した新しいテキスト行に置き換えることもできます。

この.replace()メソッドは、文字列のコピーを返します。これは、古い部分文字列は同じままですが、新しいコピーが作成され、古いテキストがすべて新しいテキストに置き換えられることを意味します。

Pythonメソッドはどのように機能しますか?.replace()構文の内訳

.replace()メソッドの構文は次のようになります。

string.replace(old_text, new_text, count)

それを分解しましょう:

  • old_text.replace()を受け入れる最初の必須パラメーターです。置き換えたいのは古い文字またはテキストです。これを引用符で囲みます。
  • new_text.replace()を受け入れる2番目に必要なパラメータです。古い文字/テキストを置き換える新しい文字またはテキストです。このパラメーターも引用符で囲む必要があります。
  • countを受け入れるオプションの3番目のパラメーターです。.replace()デフォルトでは、部分文字列のすべてのインスタンスを.replace()置き換えます。ただし、を使用して、置換するオカレンスの数を指定できます。count

Python.replace()メソッドのコード例

単一の文字のすべてのインスタンスを置き換える方法

1つの文字のすべてのインスタンスを変更するには、次のようにします。

phrase = "I like to learn coding on the go"

# replace all instances of 'o' with 'a'
substituted_phrase = phrase.replace("o", "a" )

print(phrase)
print(substituted_phrase)

#output

#I like to learn coding on the go
#I like ta learn cading an the ga

上記の例では、文字を含む各単語が文字oに置き換えられていますa。

その例では、文字の4つのインスタンスがありましたo。具体的には、、、、、およびの単語toで見つかりました。codingongo

の代わりに含むようtoに、のような2つの単語だけを変更したい場合はどうなりますか?codingao

1つの文字の特定の数のインスタンスのみを置き換える方法

1つの文字の2つのインスタンスのみを変更するには、countパラメーターを使用して2つに設定します。

phrase = "I like to learn coding on the go"

# replace only the first two instances of 'o' with 'a'
substituted_phrase = phrase.replace("o", "a", 2 )

print(phrase)
print(substituted_phrase)

#output

#I like to learn coding on the go
#I like ta learn cading on the go

単一の文字の最初のインスタンスのみを変更したい場合は、countパラメーターを1に設定します。

phrase = "I like to learn coding on the go"

# replace only the first instance of 'o' with 'a'
substituted_phrase = phrase.replace("o", "a", 1 )

print(phrase)
print(substituted_phrase)

#output

#I like to learn coding on the go
#I like ta learn coding on the go

文字列のすべてのインスタンスを置き換える方法

複数の文字を変更する場合、プロセスは似ています。

phrase = "The sun is strong today. I don't really like sun."

#replace all instances of the word 'sun' with 'wind'
substituted_phrase = phrase.replace("sun", "wind")

print(phrase)
print(substituted_phrase)

#output

#The sun is strong today. I don't really like sun.
#The wind is strong today. I don't really like wind.

上記の例では、単語は単語sunに置き換えられましたwind。

文字列の特定の数のインスタンスのみを置き換える方法

の最初のインスタンスのみをに変更する場合はsun、パラメーターをwind使用して1に設定します。count

phrase = "The sun is strong today. I don't really like sun."

#replace only the first instance of the word 'sun' with 'wind'
substituted_phrase = phrase.replace("sun", "wind", 1)

print(phrase)
print(substituted_phrase)

#output

#The sun is strong today. I don't really like sun.
#The wind is strong today. I don't really like sun.

Pythonで大文字と小文字を区別しない部分文字列置換を実行する方法

別の例を見てみましょう。


phrase = "I am learning Ruby. I really enjoy the ruby programming language!"

#replace the text "Ruby" with "Python"
substituted_text = phrase.replace("Ruby", "Python")

print(substituted_text)

#output

#I am learning Python. I really enjoy the ruby programming language!

この場合、私が本当にやりたかったのは、単語のすべてのインスタンスを。に置き換えることでしRubyたPython。

rubyただ、小文字の単語もありましたのでr、これも変えたいと思います。

最初の文字は小文字であり、で指定した大文字でRubyはないため、同じままで、に変更されませんでしたPython。

この.replace()メソッドは大文字と小文字を区別するため、大文字と小文字を区別する部分文字列置換を実行します。

大文字と小文字を区別しない部分文字列の置換を実行するには、別のことを行う必要があります。

re.sub()関数を使用してre.IGNORECASEフラグを使用する必要があります。

使用するre.sub()には、次のことを行う必要があります。

  • reを介してモジュールを使用しますimport re。
  • 正規表現を指定しpatternます。
  • replaceパターンに何をしたいかを述べてください。
  • stringこの操作を実行する対象を指定します。
  • 必要に応じcountて、置換をより正確にするためのパラメーターを指定し、実行する置換の最大数を指定します。
  • re.IGNORECASEフラグは、大文字と小文字を区別しない一致を実行するように正規表現に指示します。

したがって、構文はすべて次のようになります。

import re

re.sub(pattern, replace, string, count, flags) 

前の例をとると:

phrase = "I am learning Ruby. I really enjoy the ruby programming language!"

これは私が両方Rubyとrubyを置き換える方法ですPython:

import re

phrase = "I am learning Ruby. I really enjoy the ruby programming language!"

phrase = re.sub("Ruby","Python", phrase, flags=re.IGNORECASE)

print(phrase)

#output

#I am learning Python. I really enjoy the Python programming language!

まとめ

そして、あなたはそれを持っています-あなたは今、部分文字列置換の基本を知っています。このガイドがお役に立てば幸いです。

Pythonの詳細については、freeCodeCampのPython認定を使用したScientificComputingをご覧ください。

あなたは基本から始めて、相互作用的で初心者に優しい方法で学びます。また、最後に5つのプロジェクトを構築して実践し、学んだことを強化するのに役立てます。

読んでくれてありがとう、そして幸せなコーディング!

リンク:https ://www.freecodecamp.org/news/python-string-replace-function-in-python-for-substring-substitution/

#python 

With Ubuntu Linux, use replace command

The replace command is used to make changes or replace strings of text in files or the standard input.It looks for all occurrences of string or text from and replaces it with string or test to. If you’re a student or new user looking for a Linux system to begin with, the easiest place to start is Ubuntu Linux OS. It’s a great Linux operating system for beginners. Ubuntu is an open source Linux operating systems that runs on desktops, laptops, server and other devices.

#linux ubuntu #replace #replace command #ubuntu linux #linux

EventEmitter's typesafe replacement

EventEmitter’s typesafe replacement

'evt' is intended to be a replacement for 'events'.
It enables and encourages functional programming and makes heavy use of typescript’s type inference features to provide type safety while keeping things concise and elegant 🍸.

Suitable for any JS runtime env (deno, node, old browsers, react-native …)

  • ✅ It is both a Deno and an NPM module. ( Achieved with Denoify )
  • ✅ Lightweight, no dependency.
  • ✅ No polyfills needed, the NPM module is transpiled down to ES3
  • ✅ React Hooks integration

Can be imported in TypeScript projects using version >= 3.4 (Mar 2019) and in any plain JS projects.

TL;DR*

import { Evt } from "evt";

const evtText = new Evt<string>();
const evtTime = new Evt<number>();

evtText.attach(text => console.log(text));
evtTime.attachOnce(time => console.log(time));

evtText.post("hi!"); //Prints "hi!"
evtTime.post(123);   //Prints "123"
evtTime.post(1234);  //Prints nothing

OR

import { Evt, to } from "evt";

const evt = new Evt<
    [ "text",  string ] | 
    [ "time",  number ]
>();

//Mind the '$' prefixing 'attach'
evt.$attach(to("text"), text => console.log(text));
evt.$attachOnce(to("time"), time => console.log(time));

evt.post(["text", "hi!"]);
evt.post(["time", 123]);
evt.post(["time", 1234]);

*Those are introductory examples, EVT can do much more than this.

Who is using it


Install / Import

In Deno:

import { Evt } from "https://deno.land/x/evt/mod.ts";

Anywhere else:

$ npm install --save evt
import { Evt } from "evt"; 

Import from HTML, with CDN

<script src="//unpkg.com/evt/bundle.min.js"></script>
<script>
    const { Evt } = window["evt"];
</script>

Try it

Run some examples

Motivations

There are a lot of things that can’t easily be done with EventEmitter:

  • Enforcing type safety.
  • Removing a particular listener ( if the callback is an anonymous function ).
  • Adding a one-time listener for the next event that meets a condition.
  • Waiting (via a Promise) for one thing or another to happen.
    Example: waiting at most one second for the next message, stop waiting if the socket disconnects.

Why would someone pick EVT over RxJS:

  • RxJS introduces a lot of abstractions. It’s a big jump from EventEmitter.
  • With RxJS It is often needed to resort to custom type guards, the filter operator breaks the type inference.
  • RxJS tends to be quite verbose.
  • It could be months before RxJS it eventually supports Deno.
  • No official guideline on how to integrate RxJS with React.

EVT is an attempt to address all these points while trying to remain as accessible as EventEmitter.

Get started

Download Details:

Author: garronej

Demo: https://www.evt.land/

Source Code: https://github.com/garronej/evt

#deno #nodejs #node #javascript