Gizzy Berry

Gizzy Berry

1575531542

Using IP2Location for Divert Traffic in a Next.js Website

In a world where online commerce has become the norm, we need to build websites that are faster, user friendly and more secure than ever. In this article, you’ll learn how to set up a Node.js powered website that’s capable of directing traffic to relevant landing pages based on a visitor’s country. You’ll also learn how to block anonymous traffic (e.g. Tor) in order to eliminate risks coming from such networks.

In order to implement these features, we’ll be using the IP2Proxy web service provided by IP2Location, a Geo IP solutions provider. The web service is a REST API that accepts an IP address and responds with geolocation data in JSON format.

ip2location website

Here are some of the fields that we’ll receive:

  • countryName
  • cityName
  • isProxy
  • proxyType
  • etc.

We’ll use Next.js to build a website containing the following landing pages:

  • Home Page: API fetching and redirection will trigger from this page
  • Landing Page: supported countries will see the product page in their local currency
  • Unavailable Page: other countries will see this page with an option to join a waiting list
  • Abuse Page: visitors using Tor networks will be taken to this page

Now that you’re aware of the project plan, let’s see what you need to get started.

Prerequisites

On your machine, I would highly recommend the following:

  • Latest LTS version of Node.js (v12)
  • Yarn

An older version of Node.js will do, but the most recent LTS (long-term support) version contains performance and debugging improvements in the area of async code, which we’ll be dealing with. Yarn isn’t necessary, but you’ll benefit from its faster performance if you use it.

As mentioned earlier, we’ll be using Next.js to build our website. If you’re new to it, you can follow their official interactive tutorial to quickly get up to speed.

IP2Location + Next.js Project Walkthrough

Project Setup

To set up the project, simply launch the terminal and navigate to your workspace. Execute the following command:

npx create-next-app

Feel free to give your app any name. I’ve called mine next-ip2location-example. After installation is complete, navigate to the project’s root and execute yarn dev. This will launch the Node.js dev server. If you open your browser and navigate to localhost:3000, you should see a page with the header “Welcome to Next.js”. This should confirm that we have a working app that runs without errors. Stop the app and install the following dependencies:

yarn add yarn add next-compose-plugins dotenv-load next-env @zeit/next-css bulma isomorphic-unfetch

We’ll be using Bulma CSS framework to add out-of-the-box styling for our site. Since we’ll be connecting to an API service, we’ll set up an .env file to store our API key. Do note that this file should not be stored in a repository. Next create the file next.config.js. at the root of the project and add the following code:

const withPlugins = require('next-compose-plugins')
const css = require('@zeit/next-css')
const nextEnv = require('next-env')
const dotenvLoad = require('dotenv-load')

dotenvLoad()

module.exports = withPlugins([
    nextEnv(),
    [css]
])

The above configuration allows our application to read the .env file and load values. Do note that the keys will need to have the prefix NEXT_SERVER_ in order to be loaded in the server environment. Visit the next-env package page for more information. We’ll set the API key in the next section. The above configuration also gives our Next.js app the capability to pre-process CSS code via the zeit/next-css package. This will allow us to use Bulma CSS framework in our application. Do note we’ll need import Bulma CSS code into our Next.js application. I’ll soon show you where to do this.

Obtaining API Key for the I2Proxy Web Service

As mentioned earlier, we’ll need to convert a visitor’s IP address into information we can use to redirect or block traffic. Simply head to the following link and sign up for a free trial key:

ip2proxy trial key packages

Once you sign up, you’ll receive the free API key via email. Create an .env file and place it at the root of your project folder. Copy your API key to the file as follows:

NEXT_SERVER_IP2PROXY_API=<place API key here>

This free key will give you 1,000 free credits. At a minimum, we’ll need the following fields for our application to function:

  • countryName
  • proxyType

If you look at the pricing section on the IP2Proxy page, you’ll note that the PX2 package will give us the required response. This means each query will costs us two credits. Below is a sample of how the URL should be constructed:

  • http://api.ip2proxy.com/?ip=8.8.8.8&key=demo&package=PX2

You can also submit the URL query without the IP. The service will use the IP address of the machine that sent the request. We can also use the PX8 package to get all the available fields such as isp and domain in the top-most package of the IP2Proxy Detection Web Service.

  • http://api.ip2proxy.com/?key=demo&package=PX8

In the next section, we’ll build a simple state management system for storing the proxy data which will be shared among all site pages.

Building Context API in Next.js

Create the file context/proxy-context and insert the following code:

import React, {
    useState,
    useEffect,
    useRef,
    createContext
} from 'react'

export const ProxyContext = createContext()

export const ProxyContextProvider = (props) => {
    const initialState = {
        ipAddress: '0.0.0.0',
        countryName: 'Nowhere',
        isProxy: false,
        proxyType: ''
    }

    // Declare shareable proxy state
    const [proxy, setProxy] = useState(initialState)
    const prev = useRef()

    // Read and Write Proxy State to Local Storage
    useEffect(() => {
        if (proxy.countryName == 'Nowhere') {
            const localState = JSON.parse(localStorage.getItem('ip2proxy'))
            if (localState) {
                console.info('reading local storage')
                prev.current = localState.ipAddress
                setProxy(localState)
            }
        } else if (prev.current !== proxy.ipAddress) {
            console.info('writing local storage')
            localStorage.setItem('ip2proxy', JSON.stringify(proxy))
        }
    }, [proxy])

    return(
        <ProxyContext.Provider value={[ipLocation, setProxy]}>
            {props.children}
        </ProxyContext.Provider>
    )
}

Basically, we’re declaring a sharable state called proxy that will store data retrieved from the IP2Proxy web service. The API fetch query will be implemented in pages/index.js. The information will be used to redirect visitors to the relevant pages. If the visitor tries to refresh the page, the saved state will be lost. To prevent this from happening, we’re going to use the useEffect() hook to persist state in the browser’s local storage. When a user refreshes a particular landing page, the proxy state will be retrieved from the local storage, so there’s no need to perform the query again. Here’s a quick sneak peek of Chrome’s local storage in action:

chrome local storage

Tip: In case you run into problems further down this tutorial, clearing local storage can help resolve some issues.

Displaying Proxy Information

Create the file components/proxy-view.js and add the following code:

import React, { useContext } from 'react'
import { ProxyContext } from '../context/proxy-context'

const style = {
    padding: 12
}

const ProxyView = () => {
    const [proxy] = useContext(ProxyContext)
    const { ipAddress, countryName, isProxy, proxyType } = proxy

    return (
        <div className="box center" style={style}>
            <div className="content">
                <ul>
                    <li>IP Address : {ipAddress} </li>
                    <li>Country : {countryName} </li>
                    <li>Proxy : {isProxy} </li>
                    <li>Proxy Type: {proxyType} </li>
                </ul>
            </div>
        </div>
    )
}

export default ProxyView

This is simply a display component that we’ll place at the end of each page. We’re only creating this to confirm that our fetch logic and application’s state is working as expected. You should note that the line const [proxy] = useContext(ProxyContext) won’t run until we’ve declared our Context Provider at the root of our application. Let’s do that now in the next section.

Implementing Context API Provider in Next.js App

Create the file pages/_app.js and add the following code:

import React from 'react'
import App from 'next/app'
import 'bulma/css/bulma.css'
import { ProxyContextProvider } from '../context/proxy-context'

export default class MyApp extends App {
  render() {
    const { Component, pageProps } = this.props

    return (
      <ProxyContextProvider>
        <Component {...pageProps} />
      </ProxyContextProvider>
    )
  }
}

The _app.js file is the root component of our Next.js application where we can share global state with the rest of the site pages and child components. Note that this is also where we’re importing CSS for the Bulma framework we installed earlier. With that set up, let’s now build a layout that we’ll use for all our site pages.

Constructing a Layout Template

Create the folder layout at the root of your project. Let’s move the file components/nav.js to layout/nav.js. Replace the current code with this:

import React from 'react'
import Link from 'next/link'

const Nav = () => (
  <nav className="navbar" role="navigation" aria-label="main navigation">
    <div className="navbar-brand">
      <a href="/" className="navbar-item"><strong>Product Store</strong></a>
    </div>
    <div className="navbar-menu">
      <a className="navbar-item" href="/">Home</a>
      <Link href='/landing'>
        <a className="navbar-item">Landing</a>
      </Link>
      <Link href='/unavailable'>
        <a className="navbar-item">Unavailable</a>
      </Link>
      <Link href='/abuse'>
        <a className="navbar-item">Abuse</a>
      </Link>
    </div>
  </nav>
)

export default Nav

Note that this is an incomplete navigation menu, as it’s meant to be fully responsive. Please look into the Navbar documentation to add support for tablet and mobile screens.

I’d also like to point out that the Home link doesn’t use the Link component. I did this intentionally so that when a user clicks on it, it will trigger a server GET request. The rest of the links will only perform client-side navigation.

Next up, create the file layout/layout.js and add the following code:

import Head from 'next/head'
import Nav from './nav'
import ProxyView from '../components/proxy-view'

const Layout = (props) => (
  <div>
    <Head>
      <title>IP2Location Example</title>
      <link rel='icon' href='/favicon.ico' />
    </Head>
    <Nav />
    <section className="section">
      <div className="container">
        {props.children}
        <ProxyView />
      </div>
    </section>
  </div>
)

export default Layout

Now that we have the Layout defined, let’s start to build our site pages, starting with the home page.

Building our Home Page

This is where we’ll perform our API fetch query for the IP2Proxy web service. We’ll save the response received in our ProxyContext state. First, we’ll quickly build just the UI. Open the file pages/index.js and replace the existing code with the following:

import Head from 'next/head'
import Layout from '../layout/layout'

const Home = () => {
  return (
    <Layout>
      <Head>
        <title>Home</title>
      </Head>

      <section className="hero is-light">
        <div className="hero-body">
          <div className="container">
            <h1 className="title">Home</h1>
            <h2 className="subtitle">Checking availability in your country...</h2>
          </div>
        </div>
      </section>
    </Layout>
  )
}

export default Home

Now is a good time to launch the Next.js dev server using the command yarn dev or npm run dev. You should get the following output:

home page layout

Notice that the ProxyView component is displaying the initial values we set up in the ProxyContextProvider. In the next section, we’ll perform a fetch action and update these values.

Performing a Fetch Query on the IP2Proxy Web Service

In this section, we’ll write an asynchronous function to perform the API fetch query. We’ll do this inside the getInitialProps function. The results will be passed down to the Home component where they’ll be saved to the proxy global state via the ProxyContext. In addition, we’ll use the built-in error page to render errors caught by our code. First, let’s define the getInitialProps function by updating the code in pages/index.js:

import fetch from 'isomorphic-unfetch'

//const Home...{}

Home.getInitialProps = async ({ req }) => {  
  if (req) { // This code'll run in server mode
    const api_key = process.env.NEXT_SERVER_IP2PROXY_API || 'demo'
    const ipAddress = req.headers['x-forwarded-for'] || req.connection.remoteAddress
    const localAddresses = ['::1', '127.0.0.1', 'localhost']
    // Construct IP2Proxy web service URL
    let proxyUrl = `https://api.ip2proxy.com/?key=${api_key}&package=PX2`
     // If ipAddress is not localhost, add it to the URL as a parameter
    if (!localAddresses.includes(ipAddress))
      proxyUrl = proxyUrl.concat(`&ip=${ipAddress}`)
    try {
      const response = await fetch(proxyUrl)
      const json = await response.json()
      console.log(json)
      if (json.response != 'OK')
        return { errorCode: 500, errorMessage: json.response }
      const { isProxy, proxyType, countryName } = json
      const newProxy = { ipAddress, isProxy, proxyType, countryName }
      return{ newProxy }
    } catch (error) {
      return { errorCode: error.code, errorMessage: error.message.replace(api_key, 'demo') }
    }
  }
  return { newProxy: null } // This line will run in client mode
}

export default Home

Next, let’s update our Home component:

import React, {
  useContext,
  useEffect,
} from 'react'
import Error from 'next/error'
import { ProxyContext } from '../context/proxy-context'

const Home = ({newProxy, errorCode, errorMessage}) => {

  // Display error messages
  if (errorCode) {
    return <Error statusCode={errorCode} title={errorMessage} />
  }

  // Save new proxy state
  const [proxy, setProxy] = useContext(ProxyContext)  
  useEffect(() => {
    let ignore = false
    if(newProxy && !ignore) {
      setProxy(newProxy)
    }
     return () => { ignore = true; }
  }, [newProxy])

  // return (...
}

After you’ve saved the changes, refresh the page. You should now see the fields in ProxyView component update. Take note of the output displayed in the terminal:

{
  response: 'OK',
  countryCode: 'KE',
  countryName: 'Kenya',
  proxyType: '-',
  isProxy: 'NO'
}

The above information should reflect the country you’re in. The next step is to redirect, but let’s first build our missing landing pages.

Building Landing Pages

The landing pages are quite simple to build, as they have minimal logic. Use the navigation menu to confirm each page is rendering properly once you’ve added the code below for each of the files:

pages/landing.js:

import React, { useContext } from 'react'
import Head from 'next/head'
import Layout from '../layout/layout'
import { ProxyContext } from '../context/proxy-context'

const Landing = () => {
    let localPrice = 25000 // Kenyan Shilling
    let exchangeRate = 0;
    let currencySymbol = ''
    const [proxy] = useContext(ProxyContext)
    const { countryName } = proxy

    switch (countryName) {
        case 'Kenya':
            exchangeRate = 1;
            currencySymbol = 'KShs.'
            break;
        case 'United Kingdom':
            currencySymbol = '£'
            exchangeRate = 0.0076;
            break;
        default:
            break;
    }
    // Format localPrice to currency format
    localPrice = (localPrice * exchangeRate).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '><,')

    return (
        <Layout>
            <Head>
                <title>Landing</title>
            </Head>

            <section className="hero is-warning">
                <div className="hero-body">
                    <div className="container">
                        <h1 className="title">Landing Page</h1>
                        <h2 className="subtitle">Product is available in {countryName}!</h2>
                        <button className="button is-link"><strong>Order Now</strong>  -  {currencySymbol} {localPrice} </button>
                    </div>
                </div>
            </section>
        </Layout>
    )
}

export default Landing

landing page

pages/unavailable.js:

import React, { useContext } from 'react'
import Head from 'next/head'
import Layout from '../layout/layout'
import { ProxyContext } from '../context/proxy-context'

const Unavailable = () => {
    const [proxy] = useContext(ProxyContext)
    const { countryName } = proxy

    return (
        <Layout>
            <Head>
                <title>Unavailable</title>
            </Head>

            <section className="hero is-dark">
                <div className="hero-body">
                    <div className="container">
                        <h1 className="title">Sorry. Product is not available in <strong>{countryName}</strong> </h1>
                        <h2 className="subtitle">Click to join waiting list</h2>
                        <button className="button is-link">Subscribe to Alert Notification</button>
                    </div>
                </div>
            </section>
        </Layout>
    )
}

export default Unavailable

unavailable page

pages/abuse.js:

import React from 'react'
import Head from 'next/head'
import Layout from '../layout/layout'

const Abuse = () => (
    <Layout>
        <Head>
            <title>Abuse</title>
        </Head>

        <section className="hero is-danger">
            <div className="hero-body">
                <div className="container">
                    <h1 className="title">Sorry! TOR Visitors not allowed</h1>
                    <h2 className="subtitle">As much as we respect individual privacy, we would rather protect ourselves from users abusing privacy networks </h2>
                </div>
            </div>
        </section>
    </Layout>
)

export default Abuse

abuse page

Now that we’ve implemented all our landing pages, we need to redirect to them automatically. Head over to the next section.

Diverting Traffic to Relevant Landing Pages

To perform redirection in Next.js, we’ll need to use the useRouter hook from the next/router package in order to access the router component. We’ll use the function router.replace() to perform the redirection. There are two different redirection actions we need to define:

  1. The first redirection is for blocking Tor traffic and diverting to the “abuse” page.
  2. The second redirection is for diverting traffic to either the “landing” or the “unavailable” pages.

Open pages/index.js and add the following code:

import { useRouter } from 'next/router'

const Home = ({newProxy, errorCode, errorMessage}) => {
  //...

  // Declare router
  const router = useRouter();

  // Redirect if Proxy Type is TOR
  useEffect(() => {
    if (proxy.proxyType == 'TOR') {
      router.replace('/abuse')
    }
  }, [proxy])

  // Redirect based on visitor's country
  const { countryName } = proxy
  useEffect(() => {
    if (countryName != 'Nowhere' && newProxy.proxyType !== 'TOR') {
      redirectPage(router, countryName)
    }
  }, [proxy]);

  //...
}

const redirectPage = (router, countryName) => {
  let redirectPage;
  switch (countryName) {
    case 'Kenya': // Replace with your country's name
      redirectPage = '/landing'
      break
    case 'United Kingdom':
      redirectPage = '/landing'
      break
    default:
      redirectPage = '/unavailable'
  }
  router.replace(redirectPage)
}

In the redirectPage function, replace “Kenya” with the name of your country. You can add more countries if you like. However, for testing purposes, we need to restrict the number of countries, since there’s a limit to the number of countries supported by a proxy service. Speaking of testing, we need to deploy our application first.

Tip: If you’d like to manually test without deploying, simply assign the ipAddress constant with an IP address from another country. You can also test TOR IP addresses by grabbing one from this list of Tor IPs.

Deploying our Next.js Application

The simplest and fastest way to deploy our Next.js application to a production server is using Zeit’s serverless deployment platform. All you have to do to get started is to install their Now CLI. You’ll only need to verify your email address to use the free service.

If we were to deploy our application now, it would run as expected. However, it will hit the 20 free credit limit, as we’ve designed our app to use the demo key if we haven’t specified an API key. To upload our key now, simply execute the following command:

now secrets add NEXT_SERVER_IP2PROXY_API <ip2proxy api key>

You can learn more about managing environment variables and secrets on the Zeit dashboard here. With that defined, deploying our application is as simple as executing the following command:

now --prod

The command will automatically run the build process, then deploy it to Zeit’s servers. The whole process should run under a minute. The production server URL will be automatically copied to your clipboard. Simply open a new tab on your browser and paste the URL. You should see something similar to below:

production deploy

Testing the Site with Free Proxy Services

To confirm that our application can redirect based on the country of origin, we’re going to use a free proxy service to emulate different locations. Simply input your application’s public URL and pick a server, or leave it at random.

hma proxy form

In my case, the countries Kenya and United Kingdom will direct to the landing page.

hma proxy landing

Any other country will redirect to the “unavailable” page.

hma proxy unavailable

Testing the Site with Tor Browser

Let’s now see if our website can block traffic originating from Tor networks. Simply visit the Tor website and install the Tor browser for your platform. Here’s a screenshot of what the website should look like:

tor browser test

Tip: In case you experience difficulty installing Tor on you computer, you may find it easier installing and running Tor browser on your Android or IOS device.

Local Database Option

Before we end this article, I’d like to mention that IP2Location offers database versions of their web services. It comes in the form of a CSV file which can be imported into any database system you prefer. Instead of querying the remote web service, you can build your own local web service using the database, which should result in a faster response. Do note that when you purchase a database, it gets updated on a daily basis. Hence, you’ll need to automate the process of downloading and importing new data to your local database on a daily basis.

Are you wondering how we’re going to deploy a database in a serverless architecture? It’s quite simple. Deploy your database to a cloud service such as MongoDb or FaunaDb. However, deploying your database on a different server negates the benefits of having a local database. My recommendation is to use Docker containers to package and deploy your application and database within the same server or data center to gain the speed benefits.

Summary

I hope you now have the confidence to build a site that can redirect users to relevant landing pages based on the country they’re browsing from. With the information provided by IP2Location services, you can take your website a few steps further by:

  • offering different coupons or offers to different geographic locations
  • implementing credit card fraud detection by comparing a visitor’s location with the actual cardholder’s geographic address.

If you look over at IP2Location web service, you’ll notice that it offers a different set of geolocation fields you can use in your application. If you’d like to combine both the IP2Location and IP2Proxy web services in one application, you can look at this project I built earlier that will show you how it’s done.

Originally published by Michael Wanyoike at https://www.sitepoint.com

#nodejs #next #javascript #webdev

What is GEEK

Buddha Community

Using IP2Location for Divert Traffic in a Next.js Website
Chloe  Butler

Chloe Butler

1667425440

Pdf2gerb: Perl Script Converts PDF Files to Gerber format

pdf2gerb

Perl script converts PDF files to Gerber format

Pdf2Gerb generates Gerber 274X photoplotting and Excellon drill files from PDFs of a PCB. Up to three PDFs are used: the top copper layer, the bottom copper layer (for 2-sided PCBs), and an optional silk screen layer. The PDFs can be created directly from any PDF drawing software, or a PDF print driver can be used to capture the Print output if the drawing software does not directly support output to PDF.

The general workflow is as follows:

  1. Design the PCB using your favorite CAD or drawing software.
  2. Print the top and bottom copper and top silk screen layers to a PDF file.
  3. Run Pdf2Gerb on the PDFs to create Gerber and Excellon files.
  4. Use a Gerber viewer to double-check the output against the original PCB design.
  5. Make adjustments as needed.
  6. Submit the files to a PCB manufacturer.

Please note that Pdf2Gerb does NOT perform DRC (Design Rule Checks), as these will vary according to individual PCB manufacturer conventions and capabilities. Also note that Pdf2Gerb is not perfect, so the output files must always be checked before submitting them. As of version 1.6, Pdf2Gerb supports most PCB elements, such as round and square pads, round holes, traces, SMD pads, ground planes, no-fill areas, and panelization. However, because it interprets the graphical output of a Print function, there are limitations in what it can recognize (or there may be bugs).

See docs/Pdf2Gerb.pdf for install/setup, config, usage, and other info.


pdf2gerb_cfg.pm

#Pdf2Gerb config settings:
#Put this file in same folder/directory as pdf2gerb.pl itself (global settings),
#or copy to another folder/directory with PDFs if you want PCB-specific settings.
#There is only one user of this file, so we don't need a custom package or namespace.
#NOTE: all constants defined in here will be added to main namespace.
#package pdf2gerb_cfg;

use strict; #trap undef vars (easier debug)
use warnings; #other useful info (easier debug)


##############################################################################################
#configurable settings:
#change values here instead of in main pfg2gerb.pl file

use constant WANT_COLORS => ($^O !~ m/Win/); #ANSI colors no worky on Windows? this must be set < first DebugPrint() call

#just a little warning; set realistic expectations:
#DebugPrint("${\(CYAN)}Pdf2Gerb.pl ${\(VERSION)}, $^O O/S\n${\(YELLOW)}${\(BOLD)}${\(ITALIC)}This is EXPERIMENTAL software.  \nGerber files MAY CONTAIN ERRORS.  Please CHECK them before fabrication!${\(RESET)}", 0); #if WANT_DEBUG

use constant METRIC => FALSE; #set to TRUE for metric units (only affect final numbers in output files, not internal arithmetic)
use constant APERTURE_LIMIT => 0; #34; #max #apertures to use; generate warnings if too many apertures are used (0 to not check)
use constant DRILL_FMT => '2.4'; #'2.3'; #'2.4' is the default for PCB fab; change to '2.3' for CNC

use constant WANT_DEBUG => 0; #10; #level of debug wanted; higher == more, lower == less, 0 == none
use constant GERBER_DEBUG => 0; #level of debug to include in Gerber file; DON'T USE FOR FABRICATION
use constant WANT_STREAMS => FALSE; #TRUE; #save decompressed streams to files (for debug)
use constant WANT_ALLINPUT => FALSE; #TRUE; #save entire input stream (for debug ONLY)

#DebugPrint(sprintf("${\(CYAN)}DEBUG: stdout %d, gerber %d, want streams? %d, all input? %d, O/S: $^O, Perl: $]${\(RESET)}\n", WANT_DEBUG, GERBER_DEBUG, WANT_STREAMS, WANT_ALLINPUT), 1);
#DebugPrint(sprintf("max int = %d, min int = %d\n", MAXINT, MININT), 1); 

#define standard trace and pad sizes to reduce scaling or PDF rendering errors:
#This avoids weird aperture settings and replaces them with more standardized values.
#(I'm not sure how photoplotters handle strange sizes).
#Fewer choices here gives more accurate mapping in the final Gerber files.
#units are in inches
use constant TOOL_SIZES => #add more as desired
(
#round or square pads (> 0) and drills (< 0):
    .010, -.001,  #tiny pads for SMD; dummy drill size (too small for practical use, but needed so StandardTool will use this entry)
    .031, -.014,  #used for vias
    .041, -.020,  #smallest non-filled plated hole
    .051, -.025,
    .056, -.029,  #useful for IC pins
    .070, -.033,
    .075, -.040,  #heavier leads
#    .090, -.043,  #NOTE: 600 dpi is not high enough resolution to reliably distinguish between .043" and .046", so choose 1 of the 2 here
    .100, -.046,
    .115, -.052,
    .130, -.061,
    .140, -.067,
    .150, -.079,
    .175, -.088,
    .190, -.093,
    .200, -.100,
    .220, -.110,
    .160, -.125,  #useful for mounting holes
#some additional pad sizes without holes (repeat a previous hole size if you just want the pad size):
    .090, -.040,  #want a .090 pad option, but use dummy hole size
    .065, -.040, #.065 x .065 rect pad
    .035, -.040, #.035 x .065 rect pad
#traces:
    .001,  #too thin for real traces; use only for board outlines
    .006,  #minimum real trace width; mainly used for text
    .008,  #mainly used for mid-sized text, not traces
    .010,  #minimum recommended trace width for low-current signals
    .012,
    .015,  #moderate low-voltage current
    .020,  #heavier trace for power, ground (even if a lighter one is adequate)
    .025,
    .030,  #heavy-current traces; be careful with these ones!
    .040,
    .050,
    .060,
    .080,
    .100,
    .120,
);
#Areas larger than the values below will be filled with parallel lines:
#This cuts down on the number of aperture sizes used.
#Set to 0 to always use an aperture or drill, regardless of size.
use constant { MAX_APERTURE => max((TOOL_SIZES)) + .004, MAX_DRILL => -min((TOOL_SIZES)) + .004 }; #max aperture and drill sizes (plus a little tolerance)
#DebugPrint(sprintf("using %d standard tool sizes: %s, max aper %.3f, max drill %.3f\n", scalar((TOOL_SIZES)), join(", ", (TOOL_SIZES)), MAX_APERTURE, MAX_DRILL), 1);

#NOTE: Compare the PDF to the original CAD file to check the accuracy of the PDF rendering and parsing!
#for example, the CAD software I used generated the following circles for holes:
#CAD hole size:   parsed PDF diameter:      error:
#  .014                .016                +.002
#  .020                .02267              +.00267
#  .025                .026                +.001
#  .029                .03167              +.00267
#  .033                .036                +.003
#  .040                .04267              +.00267
#This was usually ~ .002" - .003" too big compared to the hole as displayed in the CAD software.
#To compensate for PDF rendering errors (either during CAD Print function or PDF parsing logic), adjust the values below as needed.
#units are pixels; for example, a value of 2.4 at 600 dpi = .0004 inch, 2 at 600 dpi = .0033"
use constant
{
    HOLE_ADJUST => -0.004 * 600, #-2.6, #holes seemed to be slightly oversized (by .002" - .004"), so shrink them a little
    RNDPAD_ADJUST => -0.003 * 600, #-2, #-2.4, #round pads seemed to be slightly oversized, so shrink them a little
    SQRPAD_ADJUST => +0.001 * 600, #+.5, #square pads are sometimes too small by .00067, so bump them up a little
    RECTPAD_ADJUST => 0, #(pixels) rectangular pads seem to be okay? (not tested much)
    TRACE_ADJUST => 0, #(pixels) traces seemed to be okay?
    REDUCE_TOLERANCE => .001, #(inches) allow this much variation when reducing circles and rects
};

#Also, my CAD's Print function or the PDF print driver I used was a little off for circles, so define some additional adjustment values here:
#Values are added to X/Y coordinates; units are pixels; for example, a value of 1 at 600 dpi would be ~= .002 inch
use constant
{
    CIRCLE_ADJUST_MINX => 0,
    CIRCLE_ADJUST_MINY => -0.001 * 600, #-1, #circles were a little too high, so nudge them a little lower
    CIRCLE_ADJUST_MAXX => +0.001 * 600, #+1, #circles were a little too far to the left, so nudge them a little to the right
    CIRCLE_ADJUST_MAXY => 0,
    SUBST_CIRCLE_CLIPRECT => FALSE, #generate circle and substitute for clip rects (to compensate for the way some CAD software draws circles)
    WANT_CLIPRECT => TRUE, #FALSE, #AI doesn't need clip rect at all? should be on normally?
    RECT_COMPLETION => FALSE, #TRUE, #fill in 4th side of rect when 3 sides found
};

#allow .012 clearance around pads for solder mask:
#This value effectively adjusts pad sizes in the TOOL_SIZES list above (only for solder mask layers).
use constant SOLDER_MARGIN => +.012; #units are inches

#line join/cap styles:
use constant
{
    CAP_NONE => 0, #butt (none); line is exact length
    CAP_ROUND => 1, #round cap/join; line overhangs by a semi-circle at either end
    CAP_SQUARE => 2, #square cap/join; line overhangs by a half square on either end
    CAP_OVERRIDE => FALSE, #cap style overrides drawing logic
};
    
#number of elements in each shape type:
use constant
{
    RECT_SHAPELEN => 6, #x0, y0, x1, y1, count, "rect" (start, end corners)
    LINE_SHAPELEN => 6, #x0, y0, x1, y1, count, "line" (line seg)
    CURVE_SHAPELEN => 10, #xstart, ystart, x0, y0, x1, y1, xend, yend, count, "curve" (bezier 2 points)
    CIRCLE_SHAPELEN => 5, #x, y, 5, count, "circle" (center + radius)
};
#const my %SHAPELEN =
#Readonly my %SHAPELEN =>
our %SHAPELEN =
(
    rect => RECT_SHAPELEN,
    line => LINE_SHAPELEN,
    curve => CURVE_SHAPELEN,
    circle => CIRCLE_SHAPELEN,
);

#panelization:
#This will repeat the entire body the number of times indicated along the X or Y axes (files grow accordingly).
#Display elements that overhang PCB boundary can be squashed or left as-is (typically text or other silk screen markings).
#Set "overhangs" TRUE to allow overhangs, FALSE to truncate them.
#xpad and ypad allow margins to be added around outer edge of panelized PCB.
use constant PANELIZE => {'x' => 1, 'y' => 1, 'xpad' => 0, 'ypad' => 0, 'overhangs' => TRUE}; #number of times to repeat in X and Y directions

# Set this to 1 if you need TurboCAD support.
#$turboCAD = FALSE; #is this still needed as an option?

#CIRCAD pad generation uses an appropriate aperture, then moves it (stroke) "a little" - we use this to find pads and distinguish them from PCB holes. 
use constant PAD_STROKE => 0.3; #0.0005 * 600; #units are pixels
#convert very short traces to pads or holes:
use constant TRACE_MINLEN => .001; #units are inches
#use constant ALWAYS_XY => TRUE; #FALSE; #force XY even if X or Y doesn't change; NOTE: needs to be TRUE for all pads to show in FlatCAM and ViewPlot
use constant REMOVE_POLARITY => FALSE; #TRUE; #set to remove subtractive (negative) polarity; NOTE: must be FALSE for ground planes

#PDF uses "points", each point = 1/72 inch
#combined with a PDF scale factor of .12, this gives 600 dpi resolution (1/72 * .12 = 600 dpi)
use constant INCHES_PER_POINT => 1/72; #0.0138888889; #multiply point-size by this to get inches

# The precision used when computing a bezier curve. Higher numbers are more precise but slower (and generate larger files).
#$bezierPrecision = 100;
use constant BEZIER_PRECISION => 36; #100; #use const; reduced for faster rendering (mainly used for silk screen and thermal pads)

# Ground planes and silk screen or larger copper rectangles or circles are filled line-by-line using this resolution.
use constant FILL_WIDTH => .01; #fill at most 0.01 inch at a time

# The max number of characters to read into memory
use constant MAX_BYTES => 10 * M; #bumped up to 10 MB, use const

use constant DUP_DRILL1 => TRUE; #FALSE; #kludge: ViewPlot doesn't load drill files that are too small so duplicate first tool

my $runtime = time(); #Time::HiRes::gettimeofday(); #measure my execution time

print STDERR "Loaded config settings from '${\(__FILE__)}'.\n";
1; #last value must be truthful to indicate successful load


#############################################################################################
#junk/experiment:

#use Package::Constants;
#use Exporter qw(import); #https://perldoc.perl.org/Exporter.html

#my $caller = "pdf2gerb::";

#sub cfg
#{
#    my $proto = shift;
#    my $class = ref($proto) || $proto;
#    my $settings =
#    {
#        $WANT_DEBUG => 990, #10; #level of debug wanted; higher == more, lower == less, 0 == none
#    };
#    bless($settings, $class);
#    return $settings;
#}

#use constant HELLO => "hi there2"; #"main::HELLO" => "hi there";
#use constant GOODBYE => 14; #"main::GOODBYE" => 12;

#print STDERR "read cfg file\n";

#our @EXPORT_OK = Package::Constants->list(__PACKAGE__); #https://www.perlmonks.org/?node_id=1072691; NOTE: "_OK" skips short/common names

#print STDERR scalar(@EXPORT_OK) . " consts exported:\n";
#foreach(@EXPORT_OK) { print STDERR "$_\n"; }
#my $val = main::thing("xyz");
#print STDERR "caller gave me $val\n";
#foreach my $arg (@ARGV) { print STDERR "arg $arg\n"; }

Download Details:

Author: swannman
Source Code: https://github.com/swannman/pdf2gerb

License: GPL-3.0 license

#perl 

NBB: Ad-hoc CLJS Scripting on Node.js

Nbb

Not babashka. Node.js babashka!?

Ad-hoc CLJS scripting on Node.js.

Status

Experimental. Please report issues here.

Goals and features

Nbb's main goal is to make it easy to get started with ad hoc CLJS scripting on Node.js.

Additional goals and features are:

  • Fast startup without relying on a custom version of Node.js.
  • Small artifact (current size is around 1.2MB).
  • First class macros.
  • Support building small TUI apps using Reagent.
  • Complement babashka with libraries from the Node.js ecosystem.

Requirements

Nbb requires Node.js v12 or newer.

How does this tool work?

CLJS code is evaluated through SCI, the same interpreter that powers babashka. Because SCI works with advanced compilation, the bundle size, especially when combined with other dependencies, is smaller than what you get with self-hosted CLJS. That makes startup faster. The trade-off is that execution is less performant and that only a subset of CLJS is available (e.g. no deftype, yet).

Usage

Install nbb from NPM:

$ npm install nbb -g

Omit -g for a local install.

Try out an expression:

$ nbb -e '(+ 1 2 3)'
6

And then install some other NPM libraries to use in the script. E.g.:

$ npm install csv-parse shelljs zx

Create a script which uses the NPM libraries:

(ns script
  (:require ["csv-parse/lib/sync$default" :as csv-parse]
            ["fs" :as fs]
            ["path" :as path]
            ["shelljs$default" :as sh]
            ["term-size$default" :as term-size]
            ["zx$default" :as zx]
            ["zx$fs" :as zxfs]
            [nbb.core :refer [*file*]]))

(prn (path/resolve "."))

(prn (term-size))

(println (count (str (fs/readFileSync *file*))))

(prn (sh/ls "."))

(prn (csv-parse "foo,bar"))

(prn (zxfs/existsSync *file*))

(zx/$ #js ["ls"])

Call the script:

$ nbb script.cljs
"/private/tmp/test-script"
#js {:columns 216, :rows 47}
510
#js ["node_modules" "package-lock.json" "package.json" "script.cljs"]
#js [#js ["foo" "bar"]]
true
$ ls
node_modules
package-lock.json
package.json
script.cljs

Macros

Nbb has first class support for macros: you can define them right inside your .cljs file, like you are used to from JVM Clojure. Consider the plet macro to make working with promises more palatable:

(defmacro plet
  [bindings & body]
  (let [binding-pairs (reverse (partition 2 bindings))
        body (cons 'do body)]
    (reduce (fn [body [sym expr]]
              (let [expr (list '.resolve 'js/Promise expr)]
                (list '.then expr (list 'clojure.core/fn (vector sym)
                                        body))))
            body
            binding-pairs)))

Using this macro we can look async code more like sync code. Consider this puppeteer example:

(-> (.launch puppeteer)
      (.then (fn [browser]
               (-> (.newPage browser)
                   (.then (fn [page]
                            (-> (.goto page "https://clojure.org")
                                (.then #(.screenshot page #js{:path "screenshot.png"}))
                                (.catch #(js/console.log %))
                                (.then #(.close browser)))))))))

Using plet this becomes:

(plet [browser (.launch puppeteer)
       page (.newPage browser)
       _ (.goto page "https://clojure.org")
       _ (-> (.screenshot page #js{:path "screenshot.png"})
             (.catch #(js/console.log %)))]
      (.close browser))

See the puppeteer example for the full code.

Since v0.0.36, nbb includes promesa which is a library to deal with promises. The above plet macro is similar to promesa.core/let.

Startup time

$ time nbb -e '(+ 1 2 3)'
6
nbb -e '(+ 1 2 3)'   0.17s  user 0.02s system 109% cpu 0.168 total

The baseline startup time for a script is about 170ms seconds on my laptop. When invoked via npx this adds another 300ms or so, so for faster startup, either use a globally installed nbb or use $(npm bin)/nbb script.cljs to bypass npx.

Dependencies

NPM dependencies

Nbb does not depend on any NPM dependencies. All NPM libraries loaded by a script are resolved relative to that script. When using the Reagent module, React is resolved in the same way as any other NPM library.

Classpath

To load .cljs files from local paths or dependencies, you can use the --classpath argument. The current dir is added to the classpath automatically. So if there is a file foo/bar.cljs relative to your current dir, then you can load it via (:require [foo.bar :as fb]). Note that nbb uses the same naming conventions for namespaces and directories as other Clojure tools: foo-bar in the namespace name becomes foo_bar in the directory name.

To load dependencies from the Clojure ecosystem, you can use the Clojure CLI or babashka to download them and produce a classpath:

$ classpath="$(clojure -A:nbb -Spath -Sdeps '{:aliases {:nbb {:replace-deps {com.github.seancorfield/honeysql {:git/tag "v2.0.0-rc5" :git/sha "01c3a55"}}}}}')"

and then feed it to the --classpath argument:

$ nbb --classpath "$classpath" -e "(require '[honey.sql :as sql]) (sql/format {:select :foo :from :bar :where [:= :baz 2]})"
["SELECT foo FROM bar WHERE baz = ?" 2]

Currently nbb only reads from directories, not jar files, so you are encouraged to use git libs. Support for .jar files will be added later.

Current file

The name of the file that is currently being executed is available via nbb.core/*file* or on the metadata of vars:

(ns foo
  (:require [nbb.core :refer [*file*]]))

(prn *file*) ;; "/private/tmp/foo.cljs"

(defn f [])
(prn (:file (meta #'f))) ;; "/private/tmp/foo.cljs"

Reagent

Nbb includes reagent.core which will be lazily loaded when required. You can use this together with ink to create a TUI application:

$ npm install ink

ink-demo.cljs:

(ns ink-demo
  (:require ["ink" :refer [render Text]]
            [reagent.core :as r]))

(defonce state (r/atom 0))

(doseq [n (range 1 11)]
  (js/setTimeout #(swap! state inc) (* n 500)))

(defn hello []
  [:> Text {:color "green"} "Hello, world! " @state])

(render (r/as-element [hello]))

Promesa

Working with callbacks and promises can become tedious. Since nbb v0.0.36 the promesa.core namespace is included with the let and do! macros. An example:

(ns prom
  (:require [promesa.core :as p]))

(defn sleep [ms]
  (js/Promise.
   (fn [resolve _]
     (js/setTimeout resolve ms))))

(defn do-stuff
  []
  (p/do!
   (println "Doing stuff which takes a while")
   (sleep 1000)
   1))

(p/let [a (do-stuff)
        b (inc a)
        c (do-stuff)
        d (+ b c)]
  (prn d))
$ nbb prom.cljs
Doing stuff which takes a while
Doing stuff which takes a while
3

Also see API docs.

Js-interop

Since nbb v0.0.75 applied-science/js-interop is available:

(ns example
  (:require [applied-science.js-interop :as j]))

(def o (j/lit {:a 1 :b 2 :c {:d 1}}))

(prn (j/select-keys o [:a :b])) ;; #js {:a 1, :b 2}
(prn (j/get-in o [:c :d])) ;; 1

Most of this library is supported in nbb, except the following:

  • destructuring using :syms
  • property access using .-x notation. In nbb, you must use keywords.

See the example of what is currently supported.

Examples

See the examples directory for small examples.

Also check out these projects built with nbb:

API

See API documentation.

Migrating to shadow-cljs

See this gist on how to convert an nbb script or project to shadow-cljs.

Build

Prequisites:

  • babashka >= 0.4.0
  • Clojure CLI >= 1.10.3.933
  • Node.js 16.5.0 (lower version may work, but this is the one I used to build)

To build:

  • Clone and cd into this repo
  • bb release

Run bb tasks for more project-related tasks.

Download Details:
Author: borkdude
Download Link: Download The Source Code
Official Website: https://github.com/borkdude/nbb 
License: EPL-1.0

#node #javascript

Why Use WordPress? What Can You Do With WordPress?

Can you use WordPress for anything other than blogging? To your surprise, yes. WordPress is more than just a blogging tool, and it has helped thousands of websites and web applications to thrive. The use of WordPress powers around 40% of online projects, and today in our blog, we would visit some amazing uses of WordPress other than blogging.
What Is The Use Of WordPress?

WordPress is the most popular website platform in the world. It is the first choice of businesses that want to set a feature-rich and dynamic Content Management System. So, if you ask what WordPress is used for, the answer is – everything. It is a super-flexible, feature-rich and secure platform that offers everything to build unique websites and applications. Let’s start knowing them:

1. Multiple Websites Under A Single Installation
WordPress Multisite allows you to develop multiple sites from a single WordPress installation. You can download WordPress and start building websites you want to launch under a single server. Literally speaking, you can handle hundreds of sites from one single dashboard, which now needs applause.
It is a highly efficient platform that allows you to easily run several websites under the same login credentials. One of the best things about WordPress is the themes it has to offer. You can simply download them and plugin for various sites and save space on sites without losing their speed.

2. WordPress Social Network
WordPress can be used for high-end projects such as Social Media Network. If you don’t have the money and patience to hire a coder and invest months in building a feature-rich social media site, go for WordPress. It is one of the most amazing uses of WordPress. Its stunning CMS is unbeatable. And you can build sites as good as Facebook or Reddit etc. It can just make the process a lot easier.
To set up a social media network, you would have to download a WordPress Plugin called BuddyPress. It would allow you to connect a community page with ease and would provide all the necessary features of a community or social media. It has direct messaging, activity stream, user groups, extended profiles, and so much more. You just have to download and configure it.
If BuddyPress doesn’t meet all your needs, don’t give up on your dreams. You can try out WP Symposium or PeepSo. There are also several themes you can use to build a social network.

3. Create A Forum For Your Brand’s Community
Communities are very important for your business. They help you stay in constant connection with your users and consumers. And allow you to turn them into a loyal customer base. Meanwhile, there are many good technologies that can be used for building a community page – the good old WordPress is still the best.
It is the best community development technology. If you want to build your online community, you need to consider all the amazing features you get with WordPress. Plugins such as BB Press is an open-source, template-driven PHP/ MySQL forum software. It is very simple and doesn’t hamper the experience of the website.
Other tools such as wpFoRo and Asgaros Forum are equally good for creating a community blog. They are lightweight tools that are easy to manage and integrate with your WordPress site easily. However, there is only one tiny problem; you need to have some technical knowledge to build a WordPress Community blog page.

4. Shortcodes
Since we gave you a problem in the previous section, we would also give you a perfect solution for it. You might not know to code, but you have shortcodes. Shortcodes help you execute functions without having to code. It is an easy way to build an amazing website, add new features, customize plugins easily. They are short lines of code, and rather than memorizing multiple lines; you can have zero technical knowledge and start building a feature-rich website or application.
There are also plugins like Shortcoder, Shortcodes Ultimate, and the Basics available on WordPress that can be used, and you would not even have to remember the shortcodes.

5. Build Online Stores
If you still think about why to use WordPress, use it to build an online store. You can start selling your goods online and start selling. It is an affordable technology that helps you build a feature-rich eCommerce store with WordPress.
WooCommerce is an extension of WordPress and is one of the most used eCommerce solutions. WooCommerce holds a 28% share of the global market and is one of the best ways to set up an online store. It allows you to build user-friendly and professional online stores and has thousands of free and paid extensions. Moreover as an open-source platform, and you don’t have to pay for the license.
Apart from WooCommerce, there are Easy Digital Downloads, iThemes Exchange, Shopify eCommerce plugin, and so much more available.

6. Security Features
WordPress takes security very seriously. It offers tons of external solutions that help you in safeguarding your WordPress site. While there is no way to ensure 100% security, it provides regular updates with security patches and provides several plugins to help with backups, two-factor authorization, and more.
By choosing hosting providers like WP Engine, you can improve the security of the website. It helps in threat detection, manage patching and updates, and internal security audits for the customers, and so much more.

Read More

#use of wordpress #use wordpress for business website #use wordpress for website #what is use of wordpress #why use wordpress #why use wordpress to build a website

Eva  Murphy

Eva Murphy

1625674200

Google analytics Setup with Next JS, React JS using Router Events - 14

In this video, we are going to implement Google Analytics to our Next JS application. Tracking page views of an application is very important.

Google analytics will allow us to track analytics information.

Frontend: https://github.com/amitavroy/video-reviews
API: https://github.com/amitavdevzone/video-review-api
App link: https://video-reviews.vercel.app

You can find me on:
Twitter: https://twitter.com/amitavroy7​
Discord: https://discord.gg/Em4nuvQk

#next js #js #react js #react #next #google analytics

Strategic Ways to Increase Your Website Traffic With the Use of Whatsapp Messages

There are several ways you can make use of WhatsApp to gain website traffic. We at AppClues Infotech have listed some ways that will help you to boost your website traffic by developing an app like Whatsapp.

For more info:
Website: https://www.appcluesinfotech.com/
Email: info@appcluesinfotech.com
Call: +1-978-309-9910

#ways to boost website traffic #website traffic with whatsapp #whatsapp marketing for business #whatsapp marketing strategy #increase your websites traffic #make an app like whatsapp