teleren/devto huggingface dataset:
Business rules engine library on PHP
Tags: businessrules, php
Published: 2019-07-30 10:26:24

A few months ago, I wrote a library that implements BRE (Business Rules Engine).

**What is this library for?**

This library allows you to simplify the writing of rules for business processes, such as complex discounts calculation or giving bonuses to your customers or any other logic.

It can be useful for you if you frequently change certain conditions in your code.

**What features does this library provide?**

It allows you to move these conditions to configuration files or create web interface that can edit configurations.

You can write rules in JSON or YAML format and store them into files or in the some database.

Example of Yaml config

```
node: condition
if:
  node: collection
  type: and
  elements:
  - node: context
    context: withdrawalCount
    operator: equal
    value: 0
  - node: context
    context: inGroup
    operator: arrayContain
    value:
      - testgroup
      - testgroup2
then:
  node: context
  context: getDepositSum
  description: "Giving 10% of deposit's sum as discount for the next order"
  modifiers: 
    - "$context * 0.1"
  params:
    discountType: "VIP client"
else:
  node: value
  description: "Giving 5% for the next order"
  value: 5
```

Process rule in PHP

```PHP
// Create a parser 
$parser = new YamlBuilder(new OperatorFactory());

// Load rules from a file or other sources
$node = $parser->parseFile('Yaml/testOneNodeWithRuleGreaterThan.yaml');

// Define contexts
$contextFactory = new ContextFactory([
    'getDepositSum' => InGroup::class,
    'withdrawalCount' => WithdrawalCount::class,
    'depositCount' => DepositCount::class,
    'utmSource' => UtmSource::class,
]);

// Here you can use PSR-11 container to resolve objects, callable or just class names
$contextFactory->setContainer($container);

// Instantiating tree(rules) processor
$treeProcessor = (new TreeProcessor())->setContextFactory($contextFactory);

// And process the rules
$result = $treeProcessor->process($node);
```

If you know PHP, you have a little time and maybe you are interested in such a library - leave a comment to my code.

See the full code on the https://github.com/prohalexey/TheChoice
JavaScript: 3 key differences between Arrow Functions and Normal Functions
Tags: javascript, webdev, uiweekly
Published: 2019-07-30 10:23:30

Hello Everyone,

This is my first post and I wish to write something about "Arrow Functions". I wanted to show the difference between The Arrow Functions and The Normal Functions!

Often, when asked during a client interview or a job interview, people tend to give maximum ONE difference. But in actual, there are 3 Major differences:
1. "this" - Arrow Functions do not have their own context
![](https://thepracticaldev.s3.amazonaws.com/i/tklas8nnm76hwojxgbxr.png)

2. "arguments" - Unable to access "arguments" inside function to know what arguments are passed to the function
![](https://thepracticaldev.s3.amazonaws.com/i/87r3syzaodenw48b4ugv.png)

3. "Class" - Cannot used Arrow Functions as a class as arrow functions do not have a constructor/don't behave like a constructor
![](https://thepracticaldev.s3.amazonaws.com/i/ezv8y627p2mx3pvnopeg.png)

If you want to see the hands-on on this, have a look at this short video:

{% youtube HoJqZKU0ciE %}

Please leave your feedback on what do you think. Thank you.
Day 7: Hey look, I got a list of elephants
Tags: android, career, architecture
Published: 2019-07-30 09:59:55

Hi there, it's day 7 of [my job hunt journey](https://dev.to/rahulchowdhury/day-1-looking-out-2eih).

# Yesterday's work

Implementing Jetpack's Navigation component was a breeze. It's great to see how far Android app development has come.

The core Android team has done a fabulous job in making common use cases easy to implement so that developers can focus more on the business logic of their apps.

Apart from that, I did a little bit of refactoring here and there.

# Today?

I started working on fetching a list of elephants from the [Elephant API](https://elephant-api.herokuapp.com/).

When it came to caching a list of elephants, I had 2 options:

* **Solution A**: Serialise and store a list of elephants in the local DB, separate from the previous `Elephant` model.
* **Solution B**: Store all elephant objects in the list as individual records, as they were stored in the elephant profile screen.

There were pros and cons of both approaches but ultimately I decided to go with solution B.

### Pros and cons
* **Solution A**: 
    * _Pros_: It's easy to implement and check for last update time to determine whether the list needs to be re-fetched.
    * _Cons_: Not flexible. Have to maintain similar data in 2 places. Can result in data inconsistency. For example, let's say the list of elephants is refreshed in the main screen and the list data in DB is updated with the latest copy. However, the profile screen still fetches cached data from individual elephant entities which might not have the latest copy because their cache time hasn't yet expired.
* **Solution B**:
    * _Pros_: Data is consistent because elephant details on both the list screen and the profile screen are fetched from the same DB row. Thus, if one screen updates the data, the other screen automatically gets the latest update.
    * _Cons_: Caching logic is not straightforward like solution A because there is more than 1 item to check staleness of data.

This is the logic that I applied to determine the staleness of the list:

```kotlin
private suspend fun refreshElephantListIfNeeded() {
    val staleTime = System.currentTimeMillis() - Constants.Time.FRESHNESS_PERIOD_IN_MILLIS
    val staleElephants = elephantDao.loadStaleElephants(staleTime)

    if (staleElephants.isNotEmpty()) {
        val elephantListResponse = elephantApiService.fetchElephants()
        val normalisedElephants = elephantListResponse
            .filter { it.name != null }
            .map { it.toElephant() }

        elephantDao.saveMultiple(normalisedElephants)
    }
}
```

You can find the updated project here: https://github.com/rahulchowdhury/elly

I'm also exploring my options to test repositories for my app. Let's see what I find.
Create Awesome Button Hover Animation - HTML5 CSS3 Tutorial
Tags: codepen, html, animation, css
Published: 2019-07-30 09:45:54


---
title: Create Awesome Button Hover Animation - HTML5 CSS3 Tutorial
published: true
description: 
tags: codepen, html, Animation, CSS
---


{% codepen https://codepen.io/ahmadbassamemran/pen/dxvmmZ %}
<hr/>
[Do Not Forget To Like & Subscribe In The Channel:](https://www.youtube.com/AhmadEmran?sub_confirmation=1)
<hr/>
{% youtube RXUjd9uYnkA %}
Typescript and external libraries
Tags: typescript, javascript, todayilearned
Published: 2019-07-30 09:28:56

Today I learned how to make external libraries "visible" to Typescript. I asked the question on StackOverflow as [How to define items to be ignored in Typescript](https://stackoverflow.com/questions/57265371/how-to-define-items-to-be-ignored-in-typescript/57267702#57267702) which you can read now or later.

As you may recall, I started using Typescript yesterday. It's made a big difference already to the quality of my code so I thought I'd use it on other things, like [Lychen](https://github.com/axtens/Lychen) and related in-house projects that use [ClearScript](https://github.com/microsoft/ClearScript) to add JavaScript as an extension language.

The difficulty I was having in VSCode was how to make the various C# objects that I had exposed to JavaScript comprehensible to Typescript so that I wasn't being constantly flagged with things that weren't actually errors.

The example I gave on StackOverflow was of an object that talks to a proxy provider.
```javascript
  that.getMyIP = function () {
    var request = new CSRestRequest();
    request.AddParameter("user", username);
    request.AddParameter("pass", password);
    request.AddParameter("command", "getmyip");
    var response = client.Execute(request);
    return response.Content.trim();
  };
```
`CSRestRequest` is a symbol injected into the JavaScript interpreter from the C# side. It's a wrapping of a RestSharp object. Typescript was flagging `CSRestRequest` and the `AddParameter` methods as 'problems'. 

Kudos to [SciFiThief](https://stackoverflow.com/users/5235638/scifithief) who pointed me at the [documentation](https://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html) and gave a brief example. Subsequent contributors added more detail.

Now I have a file in my ts folder called `external.d.ts` which contains
```javascript
declare class CSRestRequest {
    constructor (str?:any) ;
    AddParameter(a:string, b:string) : any;
}

declare class CSRestClient {
    constructor(str?:string);
    Execute:(client:any);
}
```
And now my editing experience is improved and I can focus on the the code at hand and not be distracted by the wiggly red lines of false-positives under my code.
How to become a Front-end developer in 2019?
Tags: angular, frontend, javascript
Published: 2019-07-30 09:11:13

Front End Development or Client-Side Development is the practice of coding in technologies like HTML, CSS, and Javascript in a website. The practice involves converting Data into a Graphical Interface for a user to view and interact. Growth in Front-end development is excellent and there are plenteous opportunities available, especially because companies now want their customers to have a good experience while using their Web applications. Want to get hired as a Front End Developer in 2019? Acquire skills in Front End Development, Build live Projects and Get Guaranteed Interviews with edWisor.

read more:- http://bit.ly/2xQJhGM
Save the planet, clean your mailbox
Tags: tutorial, discuss
Published: 2019-07-30 09:03:41

Every day we receive and send dozens of emails. Emails are intangible things, we tend to forget that datacenters and servers are needed to have access to our mailboxes 24 hours a day 7 days a week.

[Mike Berners-Lee](https://en.wikipedia.org/wiki/Mike_Berners-Lee) wrote a book about carbon footprint of everyday products called _"How bad are bananas? The carbon footprint of everything"_. He estimates the carbon footprint of an email to **4 grams of CO2** which is about **130 kg per person per year**. To make it more meaningful, it is equivalent to **1000 kilometers** driven by car.

To reduce our carbon footprint let's clean our mailboxes! I did it yesterday and removed about **40 000 emails** (my mailbox is aged of ten years). There are tools to help you removing emails and unsubscribe newsletters (only **10% of newsletters are opened**) such as [cleanfox](https://www.cleanfox.io) (they also plant trees in Zambia to reduce their own carbon footprint). For those using **Gmail** there are also [tips](https://www.laptopmag.com/articles/delete-gmail-messages-bulk) to remove easily your old emails like `older_than` filter.

Do you have other tech tips to reduce our personal carbon footprint ?
How to break out of the forEach in Javascript/NodeJS
Tags: javascript, foreach, break, exit
Published: 2019-07-30 08:39:07

---
title: How to break out of the forEach in Javascript/NodeJS
published: true
tags: JavaScript, Foreach, Break, Exit

---


It’s simple.

Use “some” or “every” instead of “forEach”

Use of Array.prototype.some

The some() method checks if at least one element of the array meets the condition implemented by the function provided.

Example:

![](https://thepracticaldev.s3.amazonaws.com/i/hnuowjqtz95ey4tnjaxc.png)

The result should look like:

> 1 
> 2
> "Result:" true

More info: https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/Array/some

---

Use of Array.prototype.every

The every() method returns a Boolean, true if all the elements in the array pass the condition implemented by the given function and false if one does not fulfill it.

Example:

![](https://thepracticaldev.s3.amazonaws.com/i/allhznsqvmisvx7ma4kj.png)


The result should look like:

> 1 
> 2 
> “Result:” false

More info: https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/Array/every


That’s all folks
Post and Share your settings of Yet another dictionary look up and text translator
Tags: firefox, addon
Published: 2019-07-30 08:05:32

[Yet another dictionary look up and text translator – Get this Extension for 🦊 Firefox](https://addons.mozilla.org/firefox/addon/yadattawa/ "Yet another dictionary look up and text translator – Get this Extension for 🦊 Firefox")

Surround the JSON code with "&#x60;&#x60;&#x60;json" and "&#x60;&#x60;&#x60;".

Example:
<pre>
&#x60;&#x60;&#x60;json
{
    "name": "Google translate",
    "url": "translate.google.com/#view=home&op...",
    "tooltip": true,
    "action": "fetch",
    "viewin": "tooltip"
}
&#x60;&#x60;&#x60;
</pre>

```json
{
    "name": "Google translate",
    "url": "translate.google.com/#view=home&op...",
    "tooltip": true,
    "action": "fetch",
    "viewin": "tooltip"
}
```
Refactoring towards decorators in Rails
Tags: ruby, refactor
Published: 2019-07-30 07:36:02

### Decorators

They wrap an object and extend its functionality without modifying the object itself.

### The problem
 
Say you have the following view.

```erb
 <p>Name: <%= @company.name.titleize %></p>

 <p>Email: <%= @company.email_private? 'Private' : @company.email %></p>

 <p>Sign Up At: <%= @company.sign_up_at.strftime('%d. %m. %Y.') %></p>
```

It's bad because the view should not care about how to display the data, it should just display it.

### The Decorator object

```ruby
class CompanyDecorator < SimpleDelegator
  def display_name
    name.titleize
  end

  def protected_email
    return "Private" if email_private?
    email
  end

  def formatted_sign_up_at
    sign_up_at.strftime("%d %b %Y")
  end
end
```

### The implementation

Nice, let's see how the controller looks now.

```ruby
class CompanyController < ApplicationController
  def show
    company = Company.find(params[:id])
    @decorated_company = CompanyDecorator.new(company)
  end
end
```

Now, the view

```erb
 <p>Name: <%= @decorated_company.display_name %></p>

 <p>Email: <%= @decorated_company.protected_email %></p>

 <p>Birthday: <%= @decorated_company.formatted_sign_up_at %></p>
```

### Final thoughts

Not only looks better, testing this approach is much simpler.

This does not only applies for Rails apps, this pattern could be used anywhere in Ruby.
How to wrap text around image on Word document in Java
Tags: wraptext, wrappingstyle, image, javawordapi
Published: 2019-07-30 07:12:21

---
title: How to wrap text around image on Word document in Java
published: True
description: Wrap text around image in Java Applications
tags: wrap text, wrapping style, image, Java word API
---

We usually add image to the Word document to make the document attractive and beautiful. The image is in line with the text by default after we add it with the word document. If we want to move the image freely or if we'd like to wrap the text around the image in a more natural way, we need to wrap text around image to set the position for the image and text. There are several kinds of wrapping styles we can select in word as below.
<li>In Line with Text- Default</li>
<li>Square- To wrap text around the border of the image</li>
<li>Tight- To wrap text tightly around the image</li>
<li>Through- To fill in the negative space around the image</li>
<li>Top and Bottom- To place the image on its own line</li>
<li>Behind the Text- To display the text over the image</li>
<li>In Front of Text- To display the image over the text</li>

This article will show you how to set the wrapping style to adjust the position of the image in Java applications with the help of [Free Spire.Doc for Java](https://www.e-iceblue.com/Introduce/free-doc-for-java.html).

Full codes of how to wrap text around image:

```java
import com.spire.doc.*;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.documents.TextWrappingStyle;
import com.spire.doc.documents.TextWrappingType;
import com.spire.doc.fields.DocPicture;

public class WrapText {
    public static void main(String[] args) throws Exception {

        Document doc = new Document();
        doc.loadFromFile("Sample.docx");

        Section sec = doc.getSections().get(0);

        Paragraph para = sec.getParagraphs().get(0);
        DocPicture picture = para.appendPicture("logo.png");

        //Set image width and height
        picture.setWidth(150f);
        picture.setHeight(125f);

        //Set text wrapping style to Square
        picture.setTextWrappingStyle(TextWrappingStyle.Square);
        picture.setTextWrappingType(TextWrappingType.Both);
        //Save the document to file
        doc.saveToFile("Output/WrapStyle.docx");
        doc.close();

    }
}
```

Effective screenshot of the text wrapping style at Square:
![Wrap Text](https://thepracticaldev.s3.amazonaws.com/i/nd29dsxycu7ot868y7qq.png)
 
##More information:##
Website: https://www.e-iceblue.com/
Support Forum: [Free Spire.Doc for Java](https://www.e-iceblue.com/forum/spire-doc-f6.html)
Refactoring towards query objects in Rails
Tags: rails, refactor
Published: 2019-07-30 07:10:18

### Query Objects

They store complex SQL queries, data aggregation, and filtering methods.


### The problem
 
Say you have the following view.

```ruby
class PostsController < ApplicationController
  def index
    @posts = Post
      .joins('LEFT OUTER JOIN users ON users.id = posts.author_id')
      .where(published: true)
      .where('view_count > ?', params[:min_view_count])
      .where('users.first_name LIKE ?', "#{params[:author_name]}%")
end
```

It's a lot of code for a controller, so let's refactor it to use a Query Object.

### The PostsQuery object

```ruby
class PostsQuery
  def self.call(params = {}, relation = Post.all)
    relation = published(relation)
    relation = minimal_view_count(relation, params[:view_count])
    relation = author_first_name_like(relation, params[:first_name])
    relation
  end

  def self.published(relation)
    relation.where(published: true)
  end

  def self.minimal_view_count(relation, view_count)
    return relation unless view_count.present?
    relation.where('view_count > ?', view_count)
  end

  def self.author_first_name_like(relation, first_name)
    return relation unless first_name.present?
    with_authors(relation)
      .where('users.first_name LIKE ?', "#{first_name}%")
  end

  def self.with_authors(relation)
    relation.joins('LEFT OUTER JOIN users ON users.id = posts.author_id')
  end
end
```

### The implementation

Nice, let's see how the controller looks now.

```ruby
class PostsController < ApplicationController
  def index
    @posts = PostsQuery.call(params)
  end
end
```

### Final thoughts  

Not only looks better, testing this approach is much simpler.

This does not only applies for Rails apps, this pattern could be used anywhere in Ruby.
Affect - algebraic effects for Ruby
Tags: ruby, algebraiceffects
Published: 2019-07-30 06:45:17

---
title: Affect - algebraic effects for Ruby
published: true
description: 
tags: ruby, algebraic-effects
---

[Affect](https://github.com/digital-fabric/affect) is a tiny Ruby gem providing a way to isolate and handle side-effects in your Ruby programs. It can make it easier to test your code, and provide a cleaner separation between your program logic and external entities such as I/O, databases, files etc. Affect is also useful for implementing dependency injection. Go read the [docs](https://github.com/digital-fabric/affect#readme).
What's your favorite sports team?
Tags: watercooler
Published: 2019-07-30 06:18:09

Soccer ⚽️ is the major sports in Germany. I am also a big fan and regularly visit home and away matches of my favorite team Hannover 96. They currently play in the second division. I own a season ticket (which does not cost more than 170 USD) so I can visit all home matches if I want to.

I also watch American Football 🏈 lately. American Football gets a lot of screen time in German TV lately, however I am not that much into the rules and tactics. My favorite teams in Football are the 49ers (I traveled to San Francisco a few times and I really like the city) and the Dallas Cowboys.

What are your favorite sports teams?
Example to Convert any Input Value in MD5 in React Native
Tags: reactnative, android, ios, javascript
Published: 2019-07-30 03:26:34

---
title: Example to Convert any Input Value in MD5 in React Native
published: true
description:Example to Convert any Input Value in MD5 in React Native 
tags: #reactnative #android #ios #js
---

Source : <a href="https://www.skptricks.com/2019/07/example-to-convert-any-input-value-in-md5-react-native.html" > Example to Convert any Input Value in MD5 in React Native</a>


This tutorial explains how to convert input text value to MD5 in react native application. This example we are going to use MD5 function to convert our Input Text into MD5, in another word it will hashing messages with MD5.

 MD5 stands for ‘Message-Digest algorithm 5’. The MD5 algorithm is used as a cryptographic hash function or a file fingerprint. It is non-reversible and very safe for password security.
This type of hashing technique helps to encrypt the  password of user from password textinput field.

<img src="https://1.bp.blogspot.com/-jYJqxh1Rp_Y/XT5u_ZSY5EI/AAAAAAAADIg/YpA5FfgFTGYCpSm7Hs4bZSQ9EwWZYzkqwCLcBGAs/s400/example-to-convert-any-input-value-in-md5-react-native.jpg" />

<a href="https://www.skptricks.com/2019/07/example-to-convert-any-input-value-in-md5-react-native.html" > Click here to read more...</a>
Nuster, a cache server based on HAProxy, now supports disk persistence 
Tags: showdev, devops, linux
Published: 2019-07-30 04:13:45

---
title: Nuster, a cache server based on HAProxy, now supports disk persistence 
published: true
description: 
tags: showdev,devops,opensource,linux
---

nuster v3.0.0.19 released, now supports disk persistence

https://github.com/jiangwenyuan/nuster

There are four MODEs.

- off: default, disable disk persistence, data are stored in memory only
- only: save data to disk only, do not store in memory
- sync: save data to memory and disk(kernel), then return to the client
- async: save data to memory and return to the client, cached data will be saved to disk later by the master process

```
nuster rule off   disk off   ttl 1m if { path_beg /disk-off } 
nuster rule only  disk only  ttl 1d if { path_beg /disk-only }
nuster rule sync  disk sync  ttl 1h if { path_beg /disk-sync }     
nuster rule async disk async ttl 2h if { path_beg /disk-async } 
nuster rule others ttl 100  
```
   
1. /disk-offwill be cached only in memory
2. /disk-onlywill be cached only in disk
3. /disk-syncwill be cached in memory and in disk, then return to the client
4. /disk-asyncwill be cached in memory and return to the client, cached data will be saved to disk later
5. other requests will be cached only in memory
Are There Good Recruiters?
Tags: discuss, recruiters, recruiting
Published: 2019-07-30 03:54:34

---
title: Are There Good Recruiters?
published: true
description: A discussion on recruiters.
tags: #discuss,#recruiters,#recruiting
---

So I always hear people make fun of recruiters (myself included), or talk about awful experiences with them but I never really hear anyone say anything good. 

I'm interested to hear if anyone has ever had a good experience with recruiters and would care to share. Maybe some tips on how to spot good recruiters. I think that could help many people in the future.