Michio JP

Michio JP

1548317107

Getting started with Reason React and BuckleScript

This tutorial will introduce OCaml, Reason React, and BuckleScript, and explain their relevance. To wrap things up, we will take a look at a demo project built with ReasonReact. ReasonReact is a simpler and much safer way to build React components in Reason, and with the help of BuckleScript, we can have access to a JavaScript version of all code written in Reason. More about this later in the tutorial.

Introduction

The importance of productivity in programming is very crucial to the success of any Software Engineer in particular, as it facilitates an implementation of features on time, working successfully with a very large team, and my favorite, being able to sleep at night without getting worried about the new code you just merged with the master branch.

There are many competing programming paradigms, each with their own approaches to application flow, syntax and other conventions.

Easy access to relevant tools, you will agree with me, will go a long way to not only make you productive as a Software Engineer but also enhance your current skill set.

The semantics

OCaml is an expressive and dynamic strictly typed general purpose programming language. It lays more emphasis on expressiveness and safety. Its been around for a while (over 20 years) now but its popularity has been on the lower side due to its small community. Most notable companies make use of it to minimize errors and improve speed. Facebook, for example, uses OCaml to developed type checkers like Hack for PHP and Flow for JavaScript.

The syntax

Reason on the other hand is not another programming language per say, but a new syntax and toolchain powered by OCaml. It provides a familiar, usable interface intended to make interoperation with JavaScript and adoption by JavaScript developers easier. In view of this, ReactReason was introduced to give JavaScript developers, especially the ReactJS community, to leverage the greater type system of Reason.

The compiler

BuckleScript compiles OCaml/Reason code down to plain JavaScript that can easily be shipped to virtually any browser in the world. One of the benefits of BuckleScript is the amazing speed at which it compiles down to human-readable JavaScript.

Getting started

Run the command below to globally install BuckleScript on your machine:

 $ npm install -g bs-platform 

Once the installation process is completed, we will now fully have access to the bsbcommand that would be used to easily initialize a quick Reason project.

Creating a basic project

By now, you should have BuckleScript installed successfully. To see it in action, let’s generate a lightweight Reason project template with:

 $ bsb -init reason-sample-project -theme basic-reason 

The boilerplate should have a similar project structure as shown here:

Next, run a command to build the project from the terminal in the root directory of the project:

 $ npm run build 

Did you notice a new file Demo.bs.js that was quickly generated for the project? The compiled version of Reason to JavaScript is housed by this file. Feel free to check and view it.

Lastly, type node src/demo.bs.js in your terminal to run the JavaScript output.

This will log a message Hello, BuckleScript and Reason! to the console. Now open the project with your favorite text editor and make a change to the message within the Js.log()method located in ./src/Demo.re , then proceed to build and see your changes.

Concepts overview

Reason introduces a new way of writing OCaml and still retains access to the beauty of static types. Let’s take a quick look at some basic concepts of Reason, such as variants, functions, and pattern-matching since we’ll be using it to build a demo.

Variants in Reason are data types and structures. It can be used to define sets of symbols and data structures. You can read more about variant here.

 /* ./src/Demo.re */ type animal = Cat(string) | Dog(string); 

We have the type of an animal which can either be a Cat or Dog and both will only accept a string as an argument.

Functions in Reason are declared with an arrow and a return expression. Declare one as shown here:

 /* ./src/Demo.re */ let speak = (animal) => switch (animal) { | Cat(name) => name ++ " says: meow" | Dog(name) => name ++ " says: woof" }; 

Here, what we have done is to declare a function speak and passed an argument using the type that was declared earlier. Within it, we used a switch expression and checked for every possible case of the animal variant, this is referred to as pattern-matching in Reason. One of the advantages of pattern-matching is that it is very exhaustive, you will get a warning in the console if you did not check for both cases.

Furthermore, for each of the variants, we passed a variable name and later concatenated it with a statement representing what we want each of the animal to say.

Now we can simply call the function and passed any of the types of animal into it:

 /* ./src/Demo.re */ Js.log(speak(Dog("Cooper"))); Js.log(speak(Cat("Buddy"))); 

Navigate to ./src/Demo.bs.js to see the equivalent JavaScript version of the functions declared in Reason above as compiled by BuckleScript.

Let’s build a todo app with Reason

To get a better grasp of the concept of building web applications with Reason, we’ll use Reason-scripts to build a simple todo list application. This will be a familiar experience for ReactJS users that are conversant with create-react-app. While building this app we will get a much better introduction to the syntax and type system of Reason.

Prerequisites

A basic understanding of React will be of great assistance with this tutorial. Before we get started, we need to install some required set of tools:

  1. We will be using create-react-app to create a boilerplate for this project. Run this command from your terminal to install it globally on your machine:
 $ npm i -g create-react-app 
  1. Finally head over to editor setup to get the Reason plugin for your favorite editor as this will help facilitate the development process.

Creating the Reason React project

We’ll create our project using the create-react-app command. Navigate to your project folder and run a command that will create a project named reason-bucklescript-todo:

 $ create-react-app reason-bucklescript-todo --scripts-version reason-scripts 

Next, change directory into the newly created project and first, run npm link bs-platformand start the application with npm start or yarn start:

ReasonReact components

Similar to a ReactJS application, ReasonReact supports the use of components to structure an application. By default, the create-react-app already generated a basic App component for us. Navigate to ./src/App.re and edit as follow:

 /* ./src/App.re */ [%bs.raw {|require('./App.css')|}]; [@bs.module] external logo : string = "./logo.svg"; let component = ReasonReact.statelessComponent("App"); let make = (~message, _children) => { ...component, render: _self => <div className="App"> <div className="App-header"> <img src=logo className="App-logo" alt="logo" /> <h2> {ReasonReact.string(message)} </h2> </div> <div className="App-intro"> <Todo /> </div> </div>, }; 

Since the structure of the file above is similar to what we would have for other components, let’s take a quick look at some of its parts.

First, we required a stylesheet with [%bs.raw {|require('./App.css')|}]; at the top of the file. BuckleScript allows us to include some raw JavaScript code by using [%bs.raw ] and wrapping the JavaScript code with {| |}.

Defining a component

Next, a component can either be stateless or stateful. In ReasonReact, there are different ways of defining them:

  1. Stateless components: defined as ReasonReact.statelessComponent("componentName")
  2. Stateful components: defined as ReasonReact.reducerComponent("componentName")

Furthermore, we declared a make function which takes in two different parameters. The first parameter has a symbol ~ indicating that it was passed into the App component as a propsand the second parameter has _, this is a more explicit way of showing that the parameter isn’t used and ignored.

In addition, the …component spread operator indicated that the make function declared is building upon the component that was just defined. We also declare a render function with a single argument _self that is not used at the moment.

Rendering a string in ReasonReact is a little bit different than what we have in ReactJS, here you will have to wrap the string with a function named ReasonReact.string().

Finally, we included and rendered a component <Todo /> without importing any file, interesting right? In ReasonReact, every component is a module and doesn’t need to be imported before it can be used in another module. We’ll create this Todo component in a bit.

Creating components

For a better folder structure, we will group all new components in the same directory that will be named components. For BuckleScript to detect the Reason files and compile them easily to JavaScript we’ll need to edit the BuckleScript configuration file. Open ./bsconfig.json and add a new source as shown below:

    // ./bsconfig.json
{
  "name": "reason-scripts",
  "sources": [
    "src",
    "src/components" // Add this line
  ],
  ...
}

With the configuration above, any .re file created within the components directory will be compiled down to JavaScript. Before we start creating the required files, locate the srcdirectory and create another directory named components inside of it.

Set up the todo component

First, let’s create a new file, TodoType.re in the components directory and paste the code below in it. This will define the data structure for the list of Todo items:

 /* ./src/components/TodoType.re / type item = { id: int, title: string, completed: bool, };

As pointed out earlier, every file in ReasonReact is a module and all the things defined at the top level of the file using the keywords let, type, and module are exposed to be used from other files. So in other components we will need to reference the TodoType component that we just created.

Todo component

Navigate to the src/components directory and create a new file Todo.re within it. Open the new file and paste in this code:

 / ./src/components/Todo.re / type state = { items: list(TodoType.item), inputText: string, }; type action = | InputText(string) | Toggle(int) | RemoveItem(int) | Submit; let component = ReasonReact.reducerComponent(“Todo”); let make = children => { let handleSubmit = state => { let newId: int = List.length(state.items); let newItem: TodoType.item = { id: newId, title: state.inputText, completed: false, }; let newList = [newItem, …state.items]; ReasonReact.Update({items: newList, inputText: “”}); }; { …component, initialState: () => { items: [{id: 0, title: “Fix more bugs”, completed: false}], inputText: “”, }, reducer: action => switch (action) { | InputText(newText) => ( state => ReasonReact.Update({…state, inputText: newText}) ) | Toggle(id) => (state => ReasonReact.Update({ …state, items: List.map((item: TodoType.item) => item.id == id ? { …item, TodoType.completed: ! TodoType.(item.completed), } : item, state.items, ), }) ) | RemoveItem(id) => ( state => ReasonReact.Update({ …state, items: List.filter( (item: TodoType.item) => item.id !== id, state.items, ), }) ) | Submit => (state => handleSubmit(state)) }, render: self => { let {items, inputText} = self.state; <div className=“app”> <div className=“app-header”> <div className=“title”> {ReasonReact.string(“Todo List”)} </div> </div> <Input submit=( => self.send(Submit)) value=inputText onInputText=(text => self.send(InputText(text))) /> <div className=“list”> ( ReasonReact.array( Array.of_list( List.map( (item: TodoType.item) => <Item key=(string_of_int(item.id)) item onRemove=(id => self.send(RemoveItem(id))) onToggle=(id => self.send(Toggle(id))) />, items, ), ), ) ) </div> </div>; }, }; };

The file above is an example of a stateful component in ReasonReact. And within it, first, we defined the state for the component and a set of actions that will be required to mutate the state of each item. And within the make function of the component, we defined a function named handleSubmit to handle the addition of new item and then update the existing todo list once created.

Next, we defined the initialState of the todo items and added a reducer method which takes the action as a parameter and used pattern-matching on the action type, returning a ReasonReact.Update which contains the new state.

Input component

This component will be used to add an item to a to-do list and therefore can be maintained as a stateless component since its main function is to emit an event that will trigger the handleSubmit function within the Todo component. Create this file within ./src/componentsand name it Input.re. Once you are done, paste the content below in it:

 / ./src/components/Input.re / let component = ReasonReact.statelessComponent(“Input”); let make = (~value, ~onInputText, ~submit, _children) => { …component, render: self => <div className=“input”> <input value placeholder=“Enter item and click add” onChange=( event => onInputText( ReactDOMRe.domElementToObj(ReactEventRe.Form.target(event))##value, ) ) /> <button onClick=( => submit())> (ReasonReact.string(“Add”)) </button> </div>, };

Item component

Finally, we will define a stateless component for rendering the items as they are being added. To do this, create a new file named Item.re within ./src/components directory and paste the code below:

 / ./src/components/Item.re / let component = ReasonReact.statelessComponent(“Item”); let make = (~item: TodoType.item, ~onRemove, ~onToggle, _children) => { …component, render: self => <div className=“item”> <input type=“checkbox” checked=item.completed onChange=( => onToggle(item.id)) /> <p> {ReasonReact.string(item.title)} </p> <button onClick=( => onRemove(item.id))> {ReasonReact.string(“Remove”)} </button> </div>, };

Stylesheet

Open ./src/App.css and paste the code below to add some styling to the application:

    / ./src/App.css */

  .App {
    text-align: center;
  }
  .App-logo {
    animation: App-logo-spin infinite 20s linear;
    height: 80px;
  }
  .App-intro {
    font-size: large;
    display: flex;
    justify-content: center;
    flex-direction: column;
    align-items: center;
  }
  .App-header {
    background-color: #222;
    height: 150px;
    padding: 20px;
    color: white;
  }
  .app {
    width: 500px;
    margin: 10px;
  }
  .app-header {
    margin: 10px;
  }
  .title {
    font-size: 25px;
    font-weight: 500;
  }
  .input {
    display: flex;
    justify-content: flex-start;
  }
  .input input {
    width: 80%;
    height: 30px;
    padding: 5px;
    font-size: medium;
  }
  .input button {
    background-color: green;
    color: white;
    font-size: medium;
    width: 30%;
    margin-left: 20px;
  }
  .list {
    margin-top: 25px;
  }
  .item {
    display: flex;
    border: #f5f5f5 2px solid;
    align-items: center;
    height: 30px;
    padding: 10px;
    margin-top: 5px;
    font-size: larger;
  }
  .item p {
    text-align: left;
    margin: auto;
  }
  .item button {
    padding: 10px;
    background-color: grey;
    font-size: 14px;
    opacity: 0.95;
  }
  @keyframes App-logo-spin {
    from {
      transform: rotate(0deg);
    }
    to {
      transform: rotate(360deg);
    }
  }

And that is it. You should have a functional todo app by now

Conclusion

I hope this very simple application was helpful enough to increase your enthusiasm for exploring Reason and its syntax.

We barely scratched the surface of some awesome features in Reason and BuckleScript. You can visit the documentation to learn more about it.

The source code for the todo app can be found here on GitHub.

#reactjs #javascript

What is GEEK

Buddha Community

Autumn  Blick

Autumn Blick

1598839687

How native is React Native? | React Native vs Native App Development

If you are undertaking a mobile app development for your start-up or enterprise, you are likely wondering whether to use React Native. As a popular development framework, React Native helps you to develop near-native mobile apps. However, you are probably also wondering how close you can get to a native app by using React Native. How native is React Native?

In the article, we discuss the similarities between native mobile development and development using React Native. We also touch upon where they differ and how to bridge the gaps. Read on.

A brief introduction to React Native

Let’s briefly set the context first. We will briefly touch upon what React Native is and how it differs from earlier hybrid frameworks.

React Native is a popular JavaScript framework that Facebook has created. You can use this open-source framework to code natively rendering Android and iOS mobile apps. You can use it to develop web apps too.

Facebook has developed React Native based on React, its JavaScript library. The first release of React Native came in March 2015. At the time of writing this article, the latest stable release of React Native is 0.62.0, and it was released in March 2020.

Although relatively new, React Native has acquired a high degree of popularity. The “Stack Overflow Developer Survey 2019” report identifies it as the 8th most loved framework. Facebook, Walmart, and Bloomberg are some of the top companies that use React Native.

The popularity of React Native comes from its advantages. Some of its advantages are as follows:

  • Performance: It delivers optimal performance.
  • Cross-platform development: You can develop both Android and iOS apps with it. The reuse of code expedites development and reduces costs.
  • UI design: React Native enables you to design simple and responsive UI for your mobile app.
  • 3rd party plugins: This framework supports 3rd party plugins.
  • Developer community: A vibrant community of developers support React Native.

Why React Native is fundamentally different from earlier hybrid frameworks

Are you wondering whether React Native is just another of those hybrid frameworks like Ionic or Cordova? It’s not! React Native is fundamentally different from these earlier hybrid frameworks.

React Native is very close to native. Consider the following aspects as described on the React Native website:

  • Access to many native platforms features: The primitives of React Native render to native platform UI. This means that your React Native app will use many native platform APIs as native apps would do.
  • Near-native user experience: React Native provides several native components, and these are platform agnostic.
  • The ease of accessing native APIs: React Native uses a declarative UI paradigm. This enables React Native to interact easily with native platform APIs since React Native wraps existing native code.

Due to these factors, React Native offers many more advantages compared to those earlier hybrid frameworks. We now review them.

#android app #frontend #ios app #mobile app development #benefits of react native #is react native good for mobile app development #native vs #pros and cons of react native #react mobile development #react native development #react native experience #react native framework #react native ios vs android #react native pros and cons #react native vs android #react native vs native #react native vs native performance #react vs native #why react native #why use react native

Shubham Ankit

Shubham Ankit

1657081614

How to Automate Excel with Python | Python Excel Tutorial (OpenPyXL)

How to Automate Excel with Python

In this article, We will show how we can use python to automate Excel . A useful Python library is Openpyxl which we will learn to do Excel Automation

What is OPENPYXL

Openpyxl is a Python library that is used to read from an Excel file or write to an Excel file. Data scientists use Openpyxl for data analysis, data copying, data mining, drawing charts, styling sheets, adding formulas, and more.

Workbook: A spreadsheet is represented as a workbook in openpyxl. A workbook consists of one or more sheets.

Sheet: A sheet is a single page composed of cells for organizing data.

Cell: The intersection of a row and a column is called a cell. Usually represented by A1, B5, etc.

Row: A row is a horizontal line represented by a number (1,2, etc.).

Column: A column is a vertical line represented by a capital letter (A, B, etc.).

Openpyxl can be installed using the pip command and it is recommended to install it in a virtual environment.

pip install openpyxl

CREATE A NEW WORKBOOK

We start by creating a new spreadsheet, which is called a workbook in Openpyxl. We import the workbook module from Openpyxl and use the function Workbook() which creates a new workbook.

from openpyxl
import Workbook
#creates a new workbook
wb = Workbook()
#Gets the first active worksheet
ws = wb.active
#creating new worksheets by using the create_sheet method

ws1 = wb.create_sheet("sheet1", 0) #inserts at first position
ws2 = wb.create_sheet("sheet2") #inserts at last position
ws3 = wb.create_sheet("sheet3", -1) #inserts at penultimate position

#Renaming the sheet
ws.title = "Example"

#save the workbook
wb.save(filename = "example.xlsx")

READING DATA FROM WORKBOOK

We load the file using the function load_Workbook() which takes the filename as an argument. The file must be saved in the same working directory.

#loading a workbook
wb = openpyxl.load_workbook("example.xlsx")

 

GETTING SHEETS FROM THE LOADED WORKBOOK

 

#getting sheet names
wb.sheetnames
result = ['sheet1', 'Sheet', 'sheet3', 'sheet2']

#getting a particular sheet
sheet1 = wb["sheet2"]

#getting sheet title
sheet1.title
result = 'sheet2'

#Getting the active sheet
sheetactive = wb.active
result = 'sheet1'

 

ACCESSING CELLS AND CELL VALUES

 

#get a cell from the sheet
sheet1["A1"] <
  Cell 'Sheet1'.A1 >

  #get the cell value
ws["A1"].value 'Segment'

#accessing cell using row and column and assigning a value
d = ws.cell(row = 4, column = 2, value = 10)
d.value
10

 

ITERATING THROUGH ROWS AND COLUMNS

 

#looping through each row and column
for x in range(1, 5):
  for y in range(1, 5):
  print(x, y, ws.cell(row = x, column = y)
    .value)

#getting the highest row number
ws.max_row
701

#getting the highest column number
ws.max_column
19

There are two functions for iterating through rows and columns.

Iter_rows() => returns the rows
Iter_cols() => returns the columns {
  min_row = 4, max_row = 5, min_col = 2, max_col = 5
} => This can be used to set the boundaries
for any iteration.

Example:

#iterating rows
for row in ws.iter_rows(min_row = 2, max_col = 3, max_row = 3):
  for cell in row:
  print(cell) <
  Cell 'Sheet1'.A2 >
  <
  Cell 'Sheet1'.B2 >
  <
  Cell 'Sheet1'.C2 >
  <
  Cell 'Sheet1'.A3 >
  <
  Cell 'Sheet1'.B3 >
  <
  Cell 'Sheet1'.C3 >

  #iterating columns
for col in ws.iter_cols(min_row = 2, max_col = 3, max_row = 3):
  for cell in col:
  print(cell) <
  Cell 'Sheet1'.A2 >
  <
  Cell 'Sheet1'.A3 >
  <
  Cell 'Sheet1'.B2 >
  <
  Cell 'Sheet1'.B3 >
  <
  Cell 'Sheet1'.C2 >
  <
  Cell 'Sheet1'.C3 >

To get all the rows of the worksheet we use the method worksheet.rows and to get all the columns of the worksheet we use the method worksheet.columns. Similarly, to iterate only through the values we use the method worksheet.values.


Example:

for row in ws.values:
  for value in row:
  print(value)

 

WRITING DATA TO AN EXCEL FILE

Writing to a workbook can be done in many ways such as adding a formula, adding charts, images, updating cell values, inserting rows and columns, etc… We will discuss each of these with an example.

 

CREATING AND SAVING A NEW WORKBOOK

 

#creates a new workbook
wb = openpyxl.Workbook()

#saving the workbook
wb.save("new.xlsx")

 

ADDING AND REMOVING SHEETS

 

#creating a new sheet
ws1 = wb.create_sheet(title = "sheet 2")

#creating a new sheet at index 0
ws2 = wb.create_sheet(index = 0, title = "sheet 0")

#checking the sheet names
wb.sheetnames['sheet 0', 'Sheet', 'sheet 2']

#deleting a sheet
del wb['sheet 0']

#checking sheetnames
wb.sheetnames['Sheet', 'sheet 2']

 

ADDING CELL VALUES

 

#checking the sheet value
ws['B2'].value
null

#adding value to cell
ws['B2'] = 367

#checking value
ws['B2'].value
367

 

ADDING FORMULAS

 

We often require formulas to be included in our Excel datasheet. We can easily add formulas using the Openpyxl module just like you add values to a cell.
 

For example:

import openpyxl
from openpyxl
import Workbook

wb = openpyxl.load_workbook("new1.xlsx")
ws = wb['Sheet']

ws['A9'] = '=SUM(A2:A8)'

wb.save("new2.xlsx")

The above program will add the formula (=SUM(A2:A8)) in cell A9. The result will be as below.

image

 

MERGE/UNMERGE CELLS

Two or more cells can be merged to a rectangular area using the method merge_cells(), and similarly, they can be unmerged using the method unmerge_cells().

For example:
Merge cells

#merge cells B2 to C9
ws.merge_cells('B2:C9')
ws['B2'] = "Merged cells"

Adding the above code to the previous example will merge cells as below.

image

UNMERGE CELLS

 

#unmerge cells B2 to C9
ws.unmerge_cells('B2:C9')

The above code will unmerge cells from B2 to C9.

INSERTING AN IMAGE

To insert an image we import the image function from the module openpyxl.drawing.image. We then load our image and add it to the cell as shown in the below example.

Example:

import openpyxl
from openpyxl
import Workbook
from openpyxl.drawing.image
import Image

wb = openpyxl.load_workbook("new1.xlsx")
ws = wb['Sheet']
#loading the image(should be in same folder)
img = Image('logo.png')
ws['A1'] = "Adding image"
#adjusting size
img.height = 130
img.width = 200
#adding img to cell A3

ws.add_image(img, 'A3')

wb.save("new2.xlsx")

Result:

image

CREATING CHARTS

Charts are essential to show a visualization of data. We can create charts from Excel data using the Openpyxl module chart. Different forms of charts such as line charts, bar charts, 3D line charts, etc., can be created. We need to create a reference that contains the data to be used for the chart, which is nothing but a selection of cells (rows and columns). I am using sample data to create a 3D bar chart in the below example:

Example

import openpyxl
from openpyxl
import Workbook
from openpyxl.chart
import BarChart3D, Reference, series

wb = openpyxl.load_workbook("example.xlsx")
ws = wb.active

values = Reference(ws, min_col = 3, min_row = 2, max_col = 3, max_row = 40)
chart = BarChart3D()
chart.add_data(values)
ws.add_chart(chart, "E3")
wb.save("MyChart.xlsx")

Result
image


How to Automate Excel with Python with Video Tutorial

Welcome to another video! In this video, We will cover how we can use python to automate Excel. I'll be going over everything from creating workbooks to accessing individual cells and stylizing cells. There is a ton of things that you can do with Excel but I'll just be covering the core/base things in OpenPyXl.

⭐️ Timestamps ⭐️
00:00 | Introduction
02:14 | Installing openpyxl
03:19 | Testing Installation
04:25 | Loading an Existing Workbook
06:46 | Accessing Worksheets
07:37 | Accessing Cell Values
08:58 | Saving Workbooks
09:52 | Creating, Listing and Changing Sheets
11:50 | Creating a New Workbook
12:39 | Adding/Appending Rows
14:26 | Accessing Multiple Cells
20:46 | Merging Cells
22:27 | Inserting and Deleting Rows
23:35 | Inserting and Deleting Columns
24:48 | Copying and Moving Cells
26:06 | Practical Example, Formulas & Cell Styling

📄 Resources 📄
OpenPyXL Docs: https://openpyxl.readthedocs.io/en/stable/ 
Code Written in This Tutorial: https://github.com/techwithtim/ExcelPythonTutorial 
Subscribe: https://www.youtube.com/c/TechWithTim/featured 

#python 

Monty  Boehm

Monty Boehm

1659453850

Twitter.jl: Julia Package to Access Twitter API

Twitter.jl

A Julia package for interacting with the Twitter API.

Twitter.jl is a Julia package to work with the Twitter API v1.1. Currently, only the REST API methods are supported; streaming API endpoints aren't implemented at this time.

All functions have required arguments for those parameters required by Twitter and an options keyword argument to provide a Dict{String, String} of optional parameters Twitter API documentation. Most function calls will return either a Dict or an Array <: TwitterType. Bad requests will return the response code from the API (403, 404, etc).

DataFrame methods are defined for functions returning composite types: Tweets, Places, Lists, and Users.

Authentication

Before one can make use of this package, you must create an application on the Twitter's Developer Platform.

Once your application is approved, you can access your dashboard/portal to grab your authentication credentials from the "Details" tab of the application.

Note that you will also want to ensure that your App has Read / Write OAuth access in order to post tweets. You can find out more about this on Stack Overflow.

Installation

To install this package, enter ] on the REPL to bring up Julia's package manager. Then add the package:

julia> ]
(v1.7) pkg> add Twitter

Tip: Press Ctrl+C to return to the julia> prompt.

Usage

To run Twitter.jl, enter the following command in your Julia REPL

julia> using Twitter

Then the a global variable has to be declared with the twitterauth function. This function holds the consumer_key(API Key), consumer_secret(API Key Secret), oauth_token(Access Token), and oauth_secret(Access Token Secret) respectively.

twitterauth("6nOtpXmf...", # API Key
            "sES5Zlj096S...", # API Key Secret
            "98689850-Hj...", # Access Token
            "UroqCVpWKIt...") # Access Token Secret
  • Ensure you put your credentials in an env file to avoid pushing your secrets to the public 🙀.

Note: This package does not currently support OAuth authentication.

Code examples

See runtests.jl for example function calls.

using Twitter, Test
using JSON, OAuth

# set debugging
ENV["JULIA_DEBUG"]=Twitter

twitterauth(ENV["CONSUMER_KEY"], ENV["CONSUMER_SECRET"], ENV["ACCESS_TOKEN"], ENV["ACCESS_TOKEN_SECRET"])

#get_mentions_timeline
mentions_timeline_default = get_mentions_timeline()
tw = mentions_timeline_default[1]
tw_df = DataFrame(mentions_timeline_default)
@test 0 <= length(mentions_timeline_default) <= 20
@test typeof(mentions_timeline_default) == Vector{Tweets}
@test typeof(tw) == Tweets
@test size(tw_df)[2] == 30

#get_user_timeline
user_timeline_default = get_user_timeline(screen_name = "randyzwitch")
@test typeof(user_timeline_default) == Vector{Tweets}

#get_home_timeline
home_timeline_default = get_home_timeline()
@test typeof(home_timeline_default) == Vector{Tweets}

#get_single_tweet_id
get_tweet_by_id = get_single_tweet_id(id = "434685122671939584")
@test typeof(get_tweet_by_id) == Tweets

#get_search_tweets
duke_tweets = get_search_tweets(q = "#Duke", count = 200)
@test typeof(duke_tweets) <: Dict

#test sending/deleting direct messages
#commenting out because Twitter API changed. Come back to fix
# send_dm = post_direct_messages_send(text = "Testing from Julia, this might disappear later $(time())", screen_name = "randyzwitch")
# get_single_dm = get_direct_messages_show(id = send_dm.id)
# destroy = post_direct_messages_destroy(id = send_dm.id)
# @test typeof(send_dm) == Tweets
# @test typeof(get_single_dm) == Tweets
# @test typeof(destroy) == Tweets

#creating/destroying friendships
add_friend = post_friendships_create(screen_name = "kyrieirving")

unfollow = post_friendships_destroy(screen_name = "kyrieirving")
unfollow_df = DataFrame(unfollow)
@test typeof(add_friend) == Users
@test typeof(unfollow) == Users
@test size(unfollow_df)[2] == 40

# create a cursor for follower ids
follow_cursor_test = get_followers_ids(screen_name = "twitter", count = 10_000)
@test length(follow_cursor_test["ids"]) == 10_000

# create a cursor for friend ids - use barackobama because he follows a lot of accounts!
friend_cursor_test = get_friends_ids(screen_name = "BarackObama", count = 10_000)
@test length(friend_cursor_test["ids"]) == 10_000

# create a test for home timelines
home_t = get_home_timeline(count = 2)
@test length(home_t) > 1

# TEST of cursoring functionality on user timelines
user_t = get_user_timeline(screen_name = "stefanjwojcik", count = 400)
@test length(user_t) == 400
# get the minimum ID of the tweets returned (the earliest)
minid = minimum(x.id for x in user_t);

# now iterate until you hit that tweet: should return 399
# WARNING: current versions of julia cannot use keywords in macros? read here: https://github.com/JuliaLang/julia/pull/29261
# eventually replace since_id = minid
tweets_since = get_user_timeline(screen_name = "stefanjwojcik", count = 400, since_id = 1001808621053898752, include_rts=1)

@test length(tweets_since)>=399

# testing get_mentions_timeline
mentions = get_mentions_timeline(screen_name = "stefanjwojcik", count = 300) 
@test length(mentions) >= 50 #sometimes API doesn't return number requested (twitter API specifies count is the max returned, may be much lower)
@test Tweets<:typeof(mentions[1])

# testing retweets_of_me
my_rts = get_retweets_of_me(count = 300)
@test Tweets<:typeof(my_rts[1])

Want to contribute?

Contributions are welcome! Kindly refer to the contribution guidelines.

Linux: Build Status 

CodeCov: codecov

Author: Randyzwitch
Source Code: https://github.com/randyzwitch/Twitter.jl 
License: View license

#julia #api #twitter 

Mathew Rini

1615544450

How to Select and Hire the Best React JS and React Native Developers?

Since March 2020 reached 556 million monthly downloads have increased, It shows that React JS has been steadily growing. React.js also provides a desirable amount of pliancy and efficiency for developing innovative solutions with interactive user interfaces. It’s no surprise that an increasing number of businesses are adopting this technology. How do you select and recruit React.js developers who will propel your project forward? How much does a React developer make? We’ll bring you here all the details you need.

What is React.js?

Facebook built and maintains React.js, an open-source JavaScript library for designing development tools. React.js is used to create single-page applications (SPAs) that can be used in conjunction with React Native to develop native cross-platform apps.

React vs React Native

  • React Native is a platform that uses a collection of mobile-specific components provided by the React kit, while React.js is a JavaScript-based library.
  • React.js and React Native have similar syntax and workflows, but their implementation is quite different.
  • React Native is designed to create native mobile apps that are distinct from those created in Objective-C or Java. React, on the other hand, can be used to develop web apps, hybrid and mobile & desktop applications.
  • React Native, in essence, takes the same conceptual UI cornerstones as standard iOS and Android apps and assembles them using React.js syntax to create a rich mobile experience.

What is the Average React Developer Salary?

In the United States, the average React developer salary is $94,205 a year, or $30-$48 per hour, This is one of the highest among JavaScript developers. The starting salary for junior React.js developers is $60,510 per year, rising to $112,480 for senior roles.

* React.js Developer Salary by Country

  • United States- $120,000
  • Canada - $110,000
  • United Kingdom - $71,820
  • The Netherlands $49,095
  • Spain - $35,423.00
  • France - $44,284
  • Ukraine - $28,990
  • India - $9,843
  • Sweden - $55,173
  • Singapore - $43,801

In context of software developer wage rates, the United States continues to lead. In high-tech cities like San Francisco and New York, average React developer salaries will hit $98K and $114per year, overall.

However, the need for React.js and React Native developer is outpacing local labour markets. As a result, many businesses have difficulty locating and recruiting them locally.

It’s no surprise that for US and European companies looking for professional and budget engineers, offshore regions like India are becoming especially interesting. This area has a large number of app development companies, a good rate with quality, and a good pool of React.js front-end developers.

As per Linkedin, the country’s IT industry employs over a million React specialists. Furthermore, for the same or less money than hiring a React.js programmer locally, you may recruit someone with much expertise and a broader technical stack.

How to Hire React.js Developers?

  • Conduct thorough candidate research, including portfolios and areas of expertise.
  • Before you sit down with your interviewing panel, do some homework.
  • Examine the final outcome and hire the ideal candidate.

Why is React.js Popular?

React is a very strong framework. React.js makes use of a powerful synchronization method known as Virtual DOM, which compares the current page architecture to the expected page architecture and updates the appropriate components as long as the user input.

React is scalable. it utilises a single language, For server-client side, and mobile platform.

React is steady.React.js is completely adaptable, which means it seldom, if ever, updates the user interface. This enables legacy projects to be updated to the most new edition of React.js without having to change the codebase or make a few small changes.

React is adaptable. It can be conveniently paired with various state administrators (e.g., Redux, Flux, Alt or Reflux) and can be used to implement a number of architectural patterns.

Is there a market for React.js programmers?
The need for React.js developers is rising at an unparalleled rate. React.js is currently used by over one million websites around the world. React is used by Fortune 400+ businesses and popular companies such as Facebook, Twitter, Glassdoor and Cloudflare.

Final thoughts:

As you’ve seen, locating and Hire React js Developer and Hire React Native developer is a difficult challenge. You will have less challenges selecting the correct fit for your projects if you identify growing offshore locations (e.g. India) and take into consideration the details above.

If you want to make this process easier, You can visit our website for more, or else to write a email, we’ll help you to finding top rated React.js and React Native developers easier and with strives to create this operation

#hire-react-js-developer #hire-react-native-developer #react #react-native #react-js #hire-react-js-programmer

Franz  Becker

Franz Becker

1651604400

React Starter Kit: Build Web Apps with React, Relay and GraphQL.

React Starter Kit — "isomorphic" web app boilerplate   

React Starter Kit is an opinionated boilerplate for web development built on top of Node.js, Express, GraphQL and React, containing modern web development tools such as Webpack, Babel and Browsersync. Helping you to stay productive following the best practices. A solid starting point for both professionals and newcomers to the industry.

See getting started guide, demo, docs, roadmap  |  Join #react-starter-kit chat room on Gitter  |  Visit our sponsors:

 

Hiring

Getting Started

Customization

The master branch of React Starter Kit doesn't include a Flux implementation or any other advanced integrations. Nevertheless, we have some integrations available to you in feature branches that you can use either as a reference or merge into your project:

You can see status of most reasonable merge combination as PRs labeled as TRACKING

If you think that any of these features should be on master, or vice versa, some features should removed from the master branch, please let us know. We love your feedback!

Comparison

 

React Starter Kit

React Static Boilerplate

ASP.NET Core Starter Kit

App typeIsomorphic (universal)Single-page applicationSingle-page application
Frontend
LanguageJavaScript (ES2015+, JSX)JavaScript (ES2015+, JSX)JavaScript (ES2015+, JSX)
LibrariesReact, History, Universal RouterReact, History, ReduxReact, History, Redux
RoutesImperative (functional)DeclarativeDeclarative, cross-stack
Backend
LanguageJavaScript (ES2015+, JSX)n/aC#, F#
LibrariesNode.js, Express, Sequelize,
GraphQL
n/aASP.NET Core, EF Core,
ASP.NET Identity
SSRYesn/an/a
Data APIGraphQLn/aWeb API

Backers

♥ React Starter Kit? Help us keep it alive by donating funds to cover project expenses via OpenCollective or Bountysource!

lehneres Tarkan Anlar Morten Olsen Adam David Ernst Zane Hitchcox  

How to Contribute

Anyone and everyone is welcome to contribute to this project. The best way to start is by checking our open issues, submit a new issue or feature request, participate in discussions, upvote or downvote the issues you like or dislike, send pull requests.

Learn More

Related Projects

  • GraphQL Starter Kit — Boilerplate for building data APIs with Node.js, JavaScript (via Babel) and GraphQL
  • Membership Database — SQL schema boilerplate for user accounts, profiles, roles, and auth claims
  • Babel Starter Kit — Boilerplate for authoring JavaScript/React.js libraries

Support

License

Copyright © 2014-present Kriasoft, LLC. This source code is licensed under the MIT license found in the LICENSE.txt file. The documentation to the project is licensed under the CC BY-SA 4.0 license.


Author: kriasoft
Source Code: https://github.com/kriasoft/react-starter-kit
License: MIT License

#graphql #react