teleren/devto huggingface dataset:
Help me understand how AWS Lambda reuses object
Tags: help, aws
Published: 2020-01-23 01:12:50

Good day to all of you, 

I'm a complete newbie on AWS Lambda. Currently, I'm building an app which has an OO pattern with clean architecture on top of it for ease of testing on the handler function like so

```js
async function setupBotHandler(): Promise<void> {
  const connection = await connectToDatabase();

  const serviceMap = new Map<string, BotService>();

  const announcementRepository = connection.getCustomRepository(
    AnnouncementRepositoryTypeORM,
  );
  const categoryRepository = connection.getCustomRepository(
    CategoryRepositoryTypeORM,
  );
  const stateRepository = connection.getCustomRepository(
    StateRepositoryTypeORM,
  );

  const announcementService = new BotAnnouncementService(
    announcementRepository,
    categoryRepository,
  );

  serviceMap.set(announcementService.identifier, announcementService);

  endpointHandler = new BotEndpointHandler(serviceMap, stateRepository);
}

export async function handler(
  event: APIGatewayEvent,
  context: Context,
): Promise<APIGatewayProxyResult | void> {
  if (!endpointHandler) {
    await setupBotHandler();
  }

  return await endpointHandler.handler(event, context);
}
```

My main concern is about reusing execution context. I've heard that lambda reuses any variables declared outside the handler functions if the container decides to reuse the execution context, which is why we must check if the object exist or not (from the `if` the statement in my case).

However, some tutorials on the net ([example](https://www.sitepoint.com/getting-started-node-js-aws-lambda/)) doesn't seem to check if some variable which the handler function depends on already exist or not.

Should I stick to what I've done or should I do it like this:

```js
const connection = await connectToDatabase();

const serviceMap = new Map<string, BotService>();

const announcementRepository = connection.getCustomRepository(
  AnnouncementRepositoryTypeORM,
);
const categoryRepository = connection.getCustomRepository(
  CategoryRepositoryTypeORM,
);
const stateRepository = connection.getCustomRepository(
  StateRepositoryTypeORM,
);

const announcementService = new BotAnnouncementService(
  announcementRepository,
  categoryRepository,
);

serviceMap.set(announcementService.identifier, announcementService);

const endpointHandler = new BotEndpointHandler(serviceMap, stateRepository);

export const handler = endpointHandler.handler;
```

Any explanation will be appreciated. Thank you!
Run git from any directory: git -C Vs --git-dir
Tags: git, opensource
Published: 2020-01-23 00:38:37

The more I dig into Git the more I come across some cool features that I’ve never used before although I’ve been using Git for years.

One of those cool features is being able to run Git from any directory (not necessarily the repo’s directory) by sending some extra parameters to the git command.

### **git -C \<path\> \<command\>**

Runs the command as if git was started in **\<path\>** instead of the current working directory.

For example, if I’m working on a certain project, and then I decided to check the status of another project really quick, I can either cd to the other project, run git status and then cd back to the previous project and continue my work.

Or I can do it all in one command using `git -C path/to/other/repo status`

![](https://cdn-images-1.medium.com/max/2000/1*62OI8v5jmIcFQ820C4pP0Q.png)

### **git --git-dir=\<path\> \<command\>**

Another way you can accomplish the same thing as `git -C` is by using `—-git-dir`. Git directory is the .dir folder that Git adds to your repo.

For example, `git --git-dir=myrepo/.git status` But be careful if you decided to use this parameter, you’ll need to set the work tree as well to make sure that Git will run your command across the correct [work tree](https://git-scm.com/docs/git-worktree), like this:

`git --git-dir=myrepo/.git --work-tree=myrepo status`

![](https://cdn-images-1.medium.com/max/2000/1*TakGyh45DyFieNRmfTTftw.png)

**What is a work tree?**

The difference between git work tree and git repository can be a bit confusing at first, think of the work tree as a tree (graph) that’s tracking every single change you make in your repo. A Git repo can have multiple work trees, which is another cool feature you can read more about [here](https://git-scm.com/docs/git-worktree).

Given that both git -C and git --git-dir can help you accomplish the same thing, which one should you go with? git -C is the answer. It was added to git years after --git-dir to make it easier for you to run git from another working directory, and as you can tell it’s much easier to use ;)
A .NET Native Alternative to JSON.NET (a.k.a. Newtonsoft.Json) for Dynamics 365 Plugins
Published: 2020-01-23 17:12:56

---
title: A .NET Native Alternative to JSON.NET (a.k.a. Newtonsoft.Json) for Dynamics 365 Plugins
published: true
date: 2020-01-23 00:00:00 UTC
tags: 
canonical_url: https://www.mehmetseckin.com/2020/01/23/a-dotnet-native-alternative-to-json-net-for-dynamics-365.html
---

# A .NET Native Alternative to JSON.NET (a.k.a. Newtonsoft.Json) for Dynamics 365 Plugins

23 January 2020, Birmingham, UK

## Background

JSON.NET (a.k.a Newtonsoft.Json) is a powerful JSON library. But when working with Dynamics 365 plug-ins, it needs to be combined into your plug-in DLL using ILMerge. This works fine, but using ILMerge for plug-in and custom workflow assemblies is [unsupported](https://cloudblogs.microsoft.com/dynamics365/no-audience/2010/11/09/how-to-reference-assemblies-from-plug-ins/?source=crm) and can jeopardise your support agreement.

If you don’t want to use ILMerge, or unable to for some reason, you can use `DataContractJsonSerializer` for most JSON tasks [JSON.NET](https://www.newtonsoft.com/json/help/html/JsonNetVsDotNetSerializers.htm) is capable of.

## Show me the code

Here is an example drop-in replacement class with the same interface as JSON.NET:

```
using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;

public static class JsonConvert
{
    public static string Serialize<T>(T obj)
    {
        using (var stream = new MemoryStream())
        {
            GetSerializer<T>().WriteObject(stream, obj);
            return Encoding.UTF8.GetString(stream.ToArray());
        }
    }

    public static T Deserialize<T>(string json)
    {
        using (var stream = new MemoryStream())
        {
            using (var writer = new StreamWriter(stream))
            {
                writer.Write(json);
                writer.Flush();
                stream.Position = 0;
                return (T)GetSerializer<T>().ReadObject(stream);
            }
        }
    }

    private static DataContractJsonSerializer GetSerializer<T>()
    {
        var settings = new DataContractJsonSerializerSettings
        {
            UseSimpleDictionaryFormat = true
        };

        return new DataContractJsonSerializer(typeof(T), settings);
    }
}

```

This can be used in the same way as JSON.NET:

```
// Serialize a Person object into a JSON string
string json = JsonConvert.Serialize(person);

// Deserialize a string into a Person object.
var person = JsonConvert.Deserialize<Person>(json);


using System.Runtime.Serialization;

[DataContract]
public class Person
{
    [DataMember]
    public string FullName { get; set; }

    [DataMember]
    public Dictionary<string, string> Attributes { get; set; }
}

```

Hope this saves someone a minute or two!
Where do you save your go to Documentation.
Tags: beginners, codenewbie, a11y, discuss
Published: 2020-01-23 00:34:32

Normally I add bookmarks in the browser but this last time I made a dashboard on pinterest.

I wonder how you save those resources or documentation? 
Those who you may go back and see them again.

I take the opportunity to leave the link to my board where you can find documentation about accessibility on the web #a11y.

 [a11y (508 compliant)](https://pin.it/odz2hmu5tvdhvk) 

> Documentation Is a big part of the beginner path
 
Code 🐒
Hi, I'm MJ!
Tags: personal, introduction
Published: 2020-01-22 23:50:04

Hi there! I'm MJ. I just graduated from Middlebury College, a small liberal arts school in Vermont, where I graduated with double major in computer science & psychology. During my time, I did internships in UXUI, full stack, and product to learn about potential careers. Now, I'm working as an associate mobile engineer with Disney, specifically on android (though I do own an iPhone).

#Some background

To take a step back, the reason I got into computer science was because I participated in one of the first Girls Who Code programs back in 2013, where I made a website that matched potential owners with adoptable animals based on personality. Thats when I saw how much of an impact that technology can have on our society, but I also realized the lack of exposure to coding, especially in underserved communities, which is how I became passionate about doing coding initiatives and social impact projects. 

#A bit of my 2020 goals 

As a junior developer, my current goal is to learn as much about android development in hopes that one day I'll have the opportunity to speak at tech conferences. I'm starting this blog to have a collection of technical concepts I'm learning as well as non-technical (though just as important) topics. Maybe one day it'll help others too!

##Ethical Living: 
A couple of months ago, I attended the Write/Speak/Code conference and learned about many of the ethical issues with tech. Currently, I'm using this [ethical resources site](https://ethical.net/) to move from "bad" products. I don't shop from Amazon, deleted my Facebook account, and no longer host my personal website on GitHub. 


## Ableist language: 
Something else I learned at the W/S/C conference was ableist language, which I want to avoid/minimize as much as possible from doing this upcoming year.

##Reading:
I really enjoy reading about social issues and tech ethics (am always open to recommendations). Feel free to take a peek at my [book list](https://www.goodreads.com/review/list/108461096). I'm a big fan of the library (I highly recommend checking out NoName's bookclub, super cool initiative) and local bookshops.


##Writing: 
I'm hoping to write more about my journey in tech, whether it's technical content or personal professional experiences working in the field. I plan to continue writing about my experiences with coding initiatives on my medium blog, while keeping this one more focused on my experiences as a junior developer. 

Here are some ideas I'm hoping to share soon:

- How I'm learning android development & kotlin
- To be a male ally
- 7 years post-Girls Who Code
- Android Architecture: MVP
- My journey transitioning using ethical technology

I doubt many will read this post (hi to my supportive friends who I'll be sharing this with), but I'm excited to start my journey and can't wait to connect with others on this site :) Thanks for reading!
How much effort should be put into e-mail?
Tags: career, productivity
Published: 2020-01-22 23:12:06

If you're like me and have inbox anxiety on more days than you would like, I find concise messages that are formatted properly work best in about 7/10 messages. No crazy cursive fonts and walls of text.

Embrace Teams or Slack. They all have potential flaws at times but can be more convenient than email.

Use Outlook rules to auto-sort what you want. 

Measure twice, send once, and all that jazz!

What other e-mail tips, etiquette, and user interfaces do you have to share?  <3
SQL Telefon Numarası Sorunu
Tags: sql, format, telefon
Published: 2020-12-26 13:45:34

---
title: SQL Telefon Numarası Sorunu
published: true
date: 2020-01-22 13:19:29 UTC
tags: SQL,format,telefon
canonical_url: 
---

Başında 0 olan, 0 ve boşluk olan, aralarda boşluk olan telefon numaralarını formatlamak için kullanılabilir.  
  
” 0212 123 12 12″  
“0212 123 12 12”  
“212 123 12 12”  
“212 123 1212”  
“212 1231212”  
gibi formatları biçimlendirir.

```sql

...  
CASE 
     WHEN LEN(REPLACE(@TELEFON, ' ', '')) = 10 THEN LEFT(REPLACE(@TELEFON, ' ', ''), 10)
     ELSE SUBSTRING(REPLACE(@TELEFON, ' ', ''),2,LEN(REPLACE(@TELEFON, ' ', '')))
END AS Telefon

...

```

Basit halinin dışına çıkmak isteyenler [bu linke](http://enestas.net/Detay/ms-sql-telefon-formatlama-fonksiyonu) göz atabilir.

**EDİT:** Enes hocam ulaştı bana ve şöyle bir not iletti;

> _ **“Sizin örnek komutunuza alternatif olarak daha basit ve sade haliyle şu komut da kullanılabilir;”** _

```sql

RIGHT((REPLACE(@TELEFON,' ','')),10)

```
Set cwd to script directory
Tags: linux, bash, shell
Published: 2020-01-22 22:53:00

Perhaps this will be the smallest snippet I've ever posted, and yet, one of the most useful. If you have a script that you want to be able to invoke from anywhere and yet not worry about relative paths, use this.

```
cd "${0%/*}"
```

This works great when you have a script in a subdirectory that builds a dockerfile, and you want it to look for the relative Dockerfile.
Difference between `is` and `==` - Python Tips
Tags: python
Published: 2020-01-22 22:51:20

We can compare 2 variables with `is` and `==` in Python:


```python
>>> a = None
>>> b = None
>>> a is b
True
>>> a == b
True
```

But what's the difference between these two?

The short answer is: `is` compares two variable's ID, and `==` compares their value.

Let's see an integer example:

```python
>>> a = 2
>>> b = 2
>>> a is b
True
>>> a == b
True
>>> id(a)
4343713584
>>> id(b)
4343713584
```

We can see `a` and `b` 's value are equal, and because their ID are the same, so `is` returns True too.

Let's see another example which `is` returns "False":

```python
>>> a = 257
>>> b = 257
>>> a is b
False
>>> a == b
True
>>> id(a)
4347529424
>>> id(b)
4347529360
```

Let both `a` and `b` to be 257, we can see their values are equal, but `is` returns False.

Let's try 256:

```python
>>> a = 256
>>> b = 256
>>> a is b
True
>>> a == b
True
>>> id(a)
4343721712
>>> id(b)
4343721712
```

Wait, if we use 256, both `is` and `==` returns True, because their ID and value are the same. But if we just increase one to 257, `is` will return False, so what happened here? Is 257 a special number in Python?

The answer is, to save some speed, Python put some small integers inside a pool. We all have the experience like using a loop to increase an integer from 1 to 10, since those small integers are frequently used, Python will create them once, and if there is another variable trying to use it, Python won't create a new one, it will just give this variable a reference to that number which is already created in the pool.

By default, Python put integers between [-5, 257) to that small integer pool, if you are interested, you can check [CPython's source code here](https://github.com/python/cpython/blob/3.8/Objects/longobject.c#L19).

So this explained why `is` and `==` both returned True for 256. But for 257, Python will created two separated integer object to `a` and `b`, thus, their ID are different.

We can verify this with -5 and -6 too:

```python
>>> a = -5
>>> b = -5
>>> a is b
True
>>> a = -6
>>> b = -6
>>> a is b
False
```


### Reference
* https://github.com/python/cpython/blob/3.8/Objects/longobject.c#L19
just wondering how the devto web app ended up on my desktop ?
Tags: browser
Published: 2020-01-22 22:45:58

just wondering how the devto web app ended up on my desktop ? probably clicked something i shouldnt have

also is this the sort of webapp google are shuting down soon ?

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/4v46p5ifloqxjgumbsw7.png)
Two Numbers You Need to Know Before Negotiating Salary (video)
Tags: career, tips, salary, advice
Published: 2020-01-22 22:42:59

There are two numbers that you need to know before going into a job negotiation.

SHOW NOTES
☆ Online compensation resources ☆
☆ Glassdoor: http://glassdoor.com/
☆ Levels.fyi: https://www.levels.fyi/
☆ Coding school graduate spreadsheet: https://docs.google.com/spreadsheets/d/1JR4KrVH1dygniLiLFAMTvdSp5gGLVKKkOxBYiPQagvE/edit?usp=sharing
☆ Mega salary spreadsheet: https://docs.google.com/spreadsheets/u/1/d/1rGCKXIKt-7l5gX06NAwO3pjqEHh-oPXtB8ihkp0vGWo/htmlview
☆ Gitlab pay calculator: https://about.gitlab.com/handbook/people-group/global-compensation/calculator/
☆ Buffer pay calculator: https://buffer.com/salary/senior-engineer-2/average/

HAVE A CANDIDATE QUESTION YOU WANT US TO ANSWER?
☆ CandidatePlanet@gmail.com

OTHER WAYS TO CONSUME THIS CONTENT:
☆ Youtube ☆ https://www.youtube.com/channel/UCdvny6qs8e4VUJIG01puw2Q
☆ Newsletter ☆ https://www.dangoormendel.com/blog (sign up at top of blog)
☆ Podcast ☆ https://candidate-planet.simplecast.com
☆ Dev.to ☆ https://dev.to/candidateplanet

MORE ABOUT DANGOORMENDEL:
☆ DangoorMendel ☆ https://www.dangoormendel.com
☆ Speaking Inquiries ☆ CandidatePlanet@gmail.com
☆ Potential Clients ☆ hello@dangoormendel.com
☆ Lusen on LinkedIn https://www.linkedin.com/in/lus
☆ Lusen on Twitter ☆ https://twitter.com/staycalmcomic
☆ Adam on LinkedIn ☆ https://www.linkedin.com/in/adamdangoor
☆ Adam on Twitter ☆ https://twitter.com/adamdangoor
How does materialize css perceive icon names?
Tags: css, html
Published: 2020-01-22 22:20:54

I used the materialize css framework. I wondered about the working logic.
How does the icon perceive their names?
How does it make it possible to show icons by name?

In the example below,
When I write 'delete', the delete icon is displayed.

https://imgshare.io/image/screenshot-9.kmLA8
An Introduction To TypeScript: Static Typing and Interfaces
Published: 2020-01-22 22:07:39

TypeScript is a strongly-typed superset of JavaScript in which means it adds some syntactical benefits to the language while still letting you write normal JavaScript if you want to. It encourages a more declarative style of programming through utilizing features such as:

- Static typing
- Interfaces
- Modules
- Classes

## Variables

```javascript
let name = "Sam"

let age = 40

let enjoysCoding = true
```

```javascript
let name: string = "Sam"

let age: number = 40

let enjoysCoding: boolean = true
```
There isn't much of a difference here. The difference is we are explicitly telling our program what type each variable is. Telling our program such specific information gives our system the opportunity to catch errors that we may have down the road.

If were to reassign our age variable to another type:

```javascript
let age = 40

age = 'forty-five'
```

TypeScript would have a red underline on the reassigned variable expressing an error:

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/ecyh1n5jeibh7yv8c8gh.png)


## Interface

```javascript
interface Person {
    firstname: string;
    lastname: string;
}
```

Interfaces are used to define the structure of objects. In our example above, we are expliciting that any variable of type Person will be an object comprising of a firstname and lastname property in which are both string types. You can think of this as we are creating custom types for our object.

Why is this useful? It explicits to the compiler in addition to your future self and other developers what type of data to expect. We are modelling the object properties allowing us to reference them in case we need to debug them. It's a common practice to put your interfaces at the top of TS files. This gives the developer an idea of the data types used for each property.

## Functions

```javascript
function greeter(person: Person):string {
    return "Hello, " + person.firstname + " " + person.lastname;
}
```

Our greeter function passes in a person parameter in which we are expecting it to be from type Person from the Interface. This promotes us to use the interface Person's first name and last name and prevent headaches as passing in the wrong Interface would throw error right away. Further, the :string after the function parameters states the data type we expect this function to return when we invoke it.


## Installation:

1) Typescript Playground: 

https://www.typescriptlang.org/play/

2) Local setup

```javascript
npm install -g typescript
```

```javascript
# greeter.ts

function greeter(person: string) {
    return "Hello, " + person;
}

var user = "Will User";

document.body.innerHTML = greeter(user);
```

On the command line, run the TypeScript compiler:
```javascript
tsc greeter.ts
```

Output:

```javascript
function greeter(person) {
    return "Hello, " + person;
}

var user = "Will";

document.body.innerHTML = greeter(user);
```
stop async-std task
Tags: rust, async, futures, asyncstd
Published: 2020-01-22 12:52:00

---
title: stop async-std task
published: true
description: rust async-std
tags: rust, async, futures, async-std
---

I have a situation:

connect to a websocket & send ping message via rest.(It's ridiculous, but the biggest cryptocurrency exchange [Binance's websocket api](https://github.com/binance-exchange/binance-official-api-docs/blob/master/user-data-stream.md#pingkeep-alive-a-listenkey) require this).

```rust
fn main() {
    task::block_on(async {
        loop { // loop for handle reconnect
            connect to websocket
            task::spawn(async move {
                loop {
                    // delay 30 minutes
                    // rest put
                }
            }); // send rest ping/pong
            read the push message
            // when websocket disconnect finish this iteration
        }
    });
}
```

The problem is: when iteration finished, the spawn task will run forever.

We can use async-std channel here to recv the stop message and break the loop.

The new problem: When we delay this task, how to get notice that out loop iteration finished?

***futures::select*** solved this problem.


```rust
use async_std::sync::{channel, Receiver};
use async_std::task;
use futures::future::{Fuse, FusedFuture, FutureExt};
use futures::select;
use std::time::Duration;

fn main() {
    task::block_on(async move {
        let mut idx: i32 = 0;
        loop {
            idx = idx + 1;
            let (_s, r) = channel::<i32>(1);
            let h = task::spawn(async move {
                loop {
                    let fut = async {
                        task::sleep(Duration::from_secs(2)).await;
                        println!("{} do something!", idx);
                    }.fuse();
                    let mut fut = Box::pin(fut);
                    let mut stop = Box::pin(r.recv().fuse());
                    select! {
                        _ = fut=> {},
                        _ = stop => break,
                    }
                }
            });

            task::sleep(Duration::from_secs(5)).await;
            println!("{} exit", idx);
        }
    });
}
```
Gitkraken - Learn about
Tags: git, gitkraken, github
Published: 2020-01-22 21:42:38

If you are a programmer or if you are just getting involved in all this, surely you have heard "Github" once. The thing is that programmers use Github to store libraries and control versions.

What is controlling versions?
If you are new to programming, this is what you must learn to do. In short, it is to make a backup or "commits".
This is very useful to fix bugs or add new features to your project.

Now, what is Gitkraken?
GitKraken is a powerful and elegant cross platform graphical interface for git.
Where we can keep complete track of our repositories, see branches, tags, create new, all the history of our work, commits etc

GitKraken is cross platform, therefore we can use it in windows, linux and mac os.
Has two plans, one free forever and another payment which offers much more functionality, an annual plan of $ 5 per month and another of $ 60 per year.

Why use Gitkraken?
- Excellent interface design
- Very fast
- It integrates with Github very well
- It has many keyboard shortcuts
- Constant maintenance and bug fixes
- The use is not complicated