Translate

Saturday, 30 November 2019

Python String Comparison

In this tutorial we are going to see different methods by which we can compare strings in Python. We will also see some tricky cases when the python string comparison can fail and golden rules to get string comparison always right.

Python strings are Immutable. 

This means that once you have created a string then it cannot be modified, if you do modify it then it will create a new python string. Example below will explain the fact.

str1 = 'TheCrazyProgrammer'
str2 = 'TheCrazyProgrammer'

print(id(str1))  # Prints 54154496
print(id(str2))  # Prints 54154496

str1 += '.com'

print(id(str1))  # Prints 54154400

Here when we make change in str1 then the id of the string changes that confirms that a new string object is created. Now one more question remains i.e. why str1 and str2 have the same id ? 

That is because python do memory optimizations and similar string object are stored as only one object in memory. This is also the case with small python integers. 

Now getting to string comparison there are two different methods by which we can compare strings as below.

Python String Comparison

Method 1: Comparing Using is Operator

is and is not operator is used to compare two strings as below:

str1 = 'TheCrazyProgrammer'

str2 = 'TheCrazyProgrammer'

if str1 is str2 :
    print("Strings are equal")  # Prints String are equal 
else :
    print("String are not equal")

The two strings to be compared are written on either side of the is operator and the comparison is made. is operator compares string based on the memory location of the string and not based on the value stored in the string. 

Similarly to check if the two values are not equal the is not operator is used. 

Method 2: Comparing Using == Operator

The == operator is used to compare two strings based on the value stored in the strings. It’s use is similar to is operator.

str1 = 'TheCrazyProgrammer'

str2 = 'TheCrazyProgrammer'

if str1 == str2 :
    print("Strings are equal")  # Prints String are equal 
else :
    print("String are not equal")

Similarly to check if the two strings are not equal the != is used. 

Why the python string being immutable is important?

Even the python strings weren’t immutable then a comparison based on the memory location would not be possible and therefore is and is not operator cannot be used. 

Both of the comparison methods above are case sensitive i.e. ‘Cat’ and ‘cat’ are treated differently. Function below can be used to first convert the string in some particular case and then use them.

  • .lower() : makes the string lowercase 
  • .upper() : makes the string uppercase

So if both strings are first converted into a similar case and then checked then it would make the comparison case insensitive indirectly. Example below will make things more clear. 

str1 = 'TheCrazyProgrammer'

str2 = 'tHecRazyprogrammer'

if str1 == str2 :
    print("Strings are equal")
else :
    print("String are not equal") # Prints String are not equal

if str1.upper() == str2.upper() :
    print("Strings are equal")   # Prints String are equal
else :
    print("String are not equal")

The golden line to remember whenever using the == and is operator is 

== used to compare values and is used to compare identities.

One more thing to remember here is:

if x is y is then x == y is true

It is easily understandable as x and y points to the same memory locations then they must have the same value at that memory location. But the converse is not true. Here is an example to support the same:

a = {"a":1}
c = a.copy()

print(a is c)  # Prints False
print(a == c) # Prints True

In this example c is at a new memory location and that’s why a is c prints false.

The post Python String Comparison appeared first on The Crazy Programmer.



Friday, 29 November 2019

Black Friday 2019 for Designers and Developers

Black Friday deals for designers and developers 2019

This article was created in partnership with Mekanism. Thank you for supporting the partners who make SitePoint possible.

Black Friday is one of the best opportunities of the year to get all kinds of new stuff, including digital web tools and services. Some companies are offering huge discounts to heavily increase their sales, while others already have excellent offers for their customers and partners.

In this article, you’ll find free and premium web tools and services, and also some of the best Black Friday WordPress deals. We included website builders, UI Kits, Admins themes, WordPress themes, effective logo and brand identity creators, and much more. There’s a web tool or service for everyone in this showcase of 38 excellent solutions.

Let’s start.

1. Free and Premium Bootstrap 4 Admin Themes and UI Kits

Dashboardpack

DashboardPack is one of the main suppliers of free and premium Bootstrap 4 admin themes and UI kits, being used by tens of thousands of people with great success. Here you’ll find free and premium themes, made with great attention to detail — HTML5 themes, React themes, Angular themes, and Vue themes.

On the DashboardPack website there’s a dedicated section of Freebies. Here there are four gorgeous dashboard themes (HTML, Angular, Vue, and React) that you can see as a live demo and use for free.
Between November 29 and December 3, you have 50% discount for all templates and all license types (Personal, Developer, and Lifetime). Use this coupon code: MADBF50.

2. Total Theme

Total Theme

Total Theme is a super powerful and complete WordPress theme that is flexible, easy to use and customize. It has brilliant designs included, and other cool stuff.

With over 38k happy users, Total Theme is a popular WordPress theme. It comes loaded with over 80 builder modules, over 40 premade demos that can be installed with 1-click, 500 styling options, and a friendly and lightning-fast interface.

The premade demos cover niches like Business, One Page, Portfolio, Personal, Creative, Shop, Blog, Photography, and more. Total Theme will help you achieve pretty much any goal — from scratch using the included Visual Page Builder, or by editing a demo design.

A limited-time 50% off Total Theme offer is valid from November 26 2019 (12pm AEDT) through December 3 2019 (8pm AEDT). Discount already applied.

3. Tailor Brands

Tailor Brands

Imagine if your dream business idea had a name, a face, and branded documents that made it official. With Tailor Brands’ online logo maker and design tools, you can instantly turn that dream idea into a living, breathing company! Design a logo in 30 seconds, customize it to your liking, and put it on everything — from professional business cards to online presentations.

Tailor Brand’s mission is to be the biggest branding agency powered by AI. It’s a huge goal but it is achievable, and they already have a top position on this ladder.

Designing a logo with Tailor Brands is super simple and you don’t need any special skills or previous experience to get a top logo design. You write the logo name you like, add a tagline (optional step), indicate which industry is your logo is for, choose if you want an icon-, name- or initial-based logo, choose from left and right (you’ll get designs as examples), and the powerful AI will present you plenty of logo designs to choose from. It’s super simple and straightforward.

Go ahead and design a logo with Tailor Brands.

4. Freelance Taxes

Bonsai Freelance Taxes

Bonsai is the integrated suite of products used by the world’s best creative freelancers.

With the latest addition of freelance taxes to the product lineup, Bonsai is more prepared than ever to help with everything your freelance business needs.

Be prepared for tax season and spend just seconds getting an overview of what you owe in annual or quarterly taxes.

Bonsai’s freelance tax software looks at your expenses, automatically categorizes them, and highlights which are deductible and to what percentage.

All Bonsai products are deeply integrated with each other to ensure it can fit every work style. Other features you should know about include contracts, proposals, time-tracking, and invoicing.

Start your free trial of Bonsai today and be ready for your freelance taxes ahead of time!

5. Codester

Codester

Codester is a huge marketplace where web designers and developers can find thousands of premium scripts, codes, app templates, themes (of all kinds), plugins, graphics, and much more. Always check the Flash Sale section where hugely discounted items are being sold.

6. Mobile App Testing

TestingBot

With over eight years of experience, this App and Browser Testing service is powerful, easy to use and provides you with a big number of features tailored to help you improve your product. Use TestingBot for automated web and app testing, for live web and app testing, for visual testing, and much more.

Start a free, 14-day trial, no credit card required.

7. FunctionFox

FunctionFox

The leading choice for creative professionals, FunctionFox gives you simple yet powerful time-tracking and project-management tools that allow you to keep multiple projects on track, forecast workloads, reduce communication breakdowns and stay on top of deadlines through project scheduling, task-based assignments, internal communication tools and comprehensive reporting. Don't let deadlines and due dates slip past!

Try a free demo today at FunctionFox.

8. Taskade: Simple Tasks, Notes, Chat

Taskade

Taskade is a unified workspace where you can chat, write, and get work done with your team. Edit projects in real time. Chat and video conference on the same page. Keep track of tasks across multiple teams and workspaces. Plan, manage, and visualize projects. And much more.

With Taskade, you can build your own workspace templates. You can start from a blank page or you can choose between a Weekly Planner, Meeting Agenda, Project Board, Mindmap, and more (you'll find lots of templates to start with). Everything you need can be fully configured to be a perfect fit.

9. Live Chat Software

Live Chat Software

AppyPie is a professional and super-easy-to-use Live Chat solution that will help you reach out to your clients and offer them real-time responsive and support through your website and mobile, using the platform live chat software.

This is a brilliant way to quickly increase conversions, make more sales (you can answer questions from people that want to buy), and increase the level of happiness of your customers. (Whatever problem they may have, they know that you're there to help fast.)

Request an invite to test the platform.

10. Mobirise Website Builder

Mobirise

Mobirise is arguably the best website builder in 2019, which you can use to create fast, responsive, and Google-friendly websites in minutes, with zero coding, and only drag-and-drop.

This brilliant builder is loaded with over 2,000 awesome website templates to start with, with eCommerce and Shopping Cart, sliders, galleries, forms, popups, icons, and much more.

In this period there is a 94% discount, so take it.

11. Newsletter Templates

Newsletter Templates

MailMunch is a powerful drag-and-drop builder that's loaded with tons of beautiful, pre-designed newsletter templates, with advanced features like Template Blocks and a Media Library to make the workflow even smoother, and a lot more. There's no coding required to use MailMunch.

Start boosting your conversions with MailMunch.

12. Astra Theme: Elementor Templates

Astra

Elementor is the most powerful website builder on the market, being used by millions of people with great success. To get out of the crowd, you can supercharge Elementor with 100+ free and premium templates, by using this bundle.

Free to use.

13. Schema Pro

Schema Pro

Creating a schema markup is no longer a task! With a simple click and select interface you can set up a markup in minutes. All the markup configurations you will set are automatically applied to all selected pages and posts.

Get Schema Pro and outperform your competitors in search engines.

14. Rank Math SEO

Rank Math SEO

Rank Math is the most powerful and easy-to-use WordPress SEO plugin on the market, making your website rank higher in search engines in no time. After a quick installation and setup, Rank Math SEO does the whole the job with no supervision.

The post Black Friday 2019 for Designers and Developers appeared first on SitePoint.



5 Insider Threat Solutions You Should Follow in 2019

How Can I Protect My Assets? There are five main pillars of organization security that every successful business needs to

5 Insider Threat Solutions You Should Follow in 2019 on Latest Hacking News.



Week in security with Tony Anscombe

ESET researchers detail how the operators of the Stantinko botnet have expanded their toolset with a new means of profiting from computers under their control

The post Week in security with Tony Anscombe appeared first on WeLiveSecurity



Smartwatch exposes locations and other data on thousands of children

A device that is supposed to help parents keep track of their children and give them a peace of mind can be turned into a surveillance device for bad actors

The post Smartwatch exposes locations and other data on thousands of children appeared first on WeLiveSecurity



Europol Shuts Down 'Imminent Monitor' RAT Operations With 13 Arrests

In a coordinated International law enforcement operation, Europol today announced to shut down the global organized cybercrime network behind Imminent Monitor RAT, yet another hacking tool that allows cybercriminals to gain complete control over a victim's computer remotely. The operation targeted both buyers and sellers of the IM-RAT (Imminent Monitor Remote Access Trojan), which was sold to

Thursday, 28 November 2019

5 scams to watch out for this shopping season

Black Friday and Cyber Monday are just around the corner and scammers are gearing up to flood you with bogus offers

The post 5 scams to watch out for this shopping season appeared first on WeLiveSecurity



Two Discontinued Software Development Kits Found Secretly Harvesting Data From Facebook And Twitter

While data harvesting has always been a problem for Facebook, a recent incident also involved Twitter. Reportedly, Facebook and Twitter

Two Discontinued Software Development Kits Found Secretly Harvesting Data From Facebook And Twitter on Latest Hacking News.



Delay, Sleep, Pause, & Wait in JavaScript

Timing Issues in JavaScript: Implementing a Sleep Function

Many programming languages have a sleep function that will delay a program's execution for a given number of seconds. This functionality is absent from JavaScript, however, owing to its asynchronous nature. In this article, we'll look briefly at why this might be, then how we can implement a sleep function ourselves.

Understanding JavaScript's Execution Model

Before we get going, it's important to make sure we understand JavaScript's execution model correctly.

Consider the following Ruby code:

require 'net/http'
require 'json'

url = 'https://api.github.com/users/jameshibbard'
uri = URI(url)
response = JSON.parse(Net::HTTP.get(uri))
puts response['public_repos']
puts "Hello!"

As one might expect, this code makes a request to the GitHub API to fetch my user data. It then parses the response, outputs the number of public repos attributed to my GitHub account and finally prints "Hello!" to the screen. Execution goes from top to bottom.

Contrast that with the equivalent JavaScript version:

fetch('https://api.github.com/users/jameshibbard')
  .then(res => res.json())
  .then(json => console.log(json.public_repos));
console.log("Hello!");

If you run this code, it will output "Hello!" to the screen, then the number of public repos attributed to my GitHub account.

This is because fetching data from an API is an asynchronous operation in JavaScript. The JavaScript interpreter will encounter the fetch command and dispatch the request. It will not, however, wait for the request to complete. Rather, it will continue on its way, output "Hello!" to the console, then when the request returns a couple of hundred milliseconds later, it will output the number of repos.

If any of this is news to you, you should watch this excellent conference talk: What the heck is the event loop anyway?.

You Might Not Actually Need a Sleep Function

Now that we have a better understanding of JavaScript's execution model, let's have a look at how JavaScript handles delays and asynchronous operations.

Create a Simple Delay Using setTimeout

The standard way of creating a delay in JavaScript is to use its setTimeout method. For example:

console.log("Hello");
setTimeout(() => {  console.log("World!"); }, 2000);

This would log "Hello" to the console, then after two seconds "World!" And in many cases, this is enough: do something, wait, then do something else. Sorted!

However, please be aware that setTimeout is an asynchronous method. Try altering the previous code like so:

console.log("Hello");
setTimeout(() => { console.log("World!"); }, 2000);
console.log("Goodbye!");

It will log:

Hello
Goodbye!
World!

Waiting for Things with setTimeout

It's also possible to use setTimeout (or its cousin setInterval) to keep JavaScript waiting until a condition is met. For example, here's how you might use setTimeout to wait for a certain element to appear on a web page:

function pollDOM () {
  const el = document.querySelector('my-element');

  if (el.length) {
    // Do something with el
  } else {
    setTimeout(pollDOM, 300); // try again in 300 milliseconds
  }
}

pollDOM();

This assumes the element will turn up at some point. If you're not sure that's the case, you'll need to look at canceling the timer (using clearTimeout or clearInterval).

If you'd like to find out more about JavaScript's setTimeout method, please consult our tutorial which has plenty of examples to get you going.

The post Delay, Sleep, Pause, & Wait in JavaScript appeared first on SitePoint.



Wednesday, 27 November 2019

Magento Marketplace Suffers Data Breach Exposing Users' Account Info

If you have ever registered an account with the official Magento marketplace to bought or sold any extension, plugin, or e-commerce website theme, you must change your password immediately. Adobe—the company owning Magento e-commerce platform—today disclosed a new data breach incident that exposed account information of Magento marketplace users to an unknown group of hackers or individuals.

Cryptocurrency exchange loses US$50 million in apparent hack

UPbit has announced that, as a precaution, all transactions will remain suspended for at least two weeks

The post Cryptocurrency exchange loses US$50 million in apparent hack appeared first on WeLiveSecurity



Over 12,000 Google Users Hit by Government Hackers in 3rd Quarter of 2019

As part of its active efforts to protect billions of online users, Google identified and warned over 12,000 of its users who were targeted by a government-backed hacking attempt in the third quarter of this year. According to a report published by Google's Threat Analysis Group (TAG), more than 90 percent of the targeted users were hit with "credential phishing emails" that tried to trick

The Hacker News 2020 Cybersecurity Salary Survey – Call for Participation

For the first time, The Hacker News launches a comprehensive Cybersecurity Salary Survey aimed to provide insights into the payment standards of security positions, enabling security professionals to benchmark their salaries against their peers, as well as get clear insights into the leading roles, certifications, geo- and industry- components that factor a cybersecurity position payroll.

Software Development Outsourcing: Reasons to Opt for It

Do you know that great feel when a splendid idea comes to your mind? You generate a solution that will simplify, optimize, improve people’s lives. After brainstorming, you come up with its advanced form: now, you know for sure how to build an app that will be considerably better than the rival tools. But wait a minute… Do you really know how to build this app? Do you have a deep vision of the development process? Or are you an experienced IT engineer that can do all by yourself? Even if you are, that’s too hard to bring a great idea to life on your own.

Who can help you with high-quality software products development? Obviously, you need to build cooperation with a team of skilled engineers. Today, we are going to discuss the available methods, explain why it is the best option to outsource app development and have a glance at top IT companies that will help you with it.

Software Development Outsourcing

In-house Developers vs Freelance Specialists vs Outsourcing Partner

Typically, you can choose from 3 most popular options:

In-house Developers

This type of cooperation means that you hire engineers to work together with you right in your office. It sounds pretty attractive: building a product shoulder to shoulder, you can be fully aware of its specifics. Besides, you can build close business relations with your co-workers. But after deep research, you discover the disadvantages: hiring on-site developers is a time-consuming and expensive process.

First of all, you need to rent a convenient office and decide on how to maintain it effectively. After that, you need to hire HR and recruitment experts to help you with a search. IT engineers are in high demand: a qualified software developer may get up to a dozen job offers per week. Developers hardly look for a job; a job finds them instead. Thus, you need to get ready to invest much time and money in recruitment. Onboarding processes take time, too.

And last but not least, software engineers’ salaries in the US are high. Thus, let’s proceed with 2 more options.

Freelance Specialists

There’s much fish in the ocean; there are many engineers on freelance platforms like Upwork. You can find here everyone you need: from a QA engineer with minimum salary expectation to a UI/UX designer with sky-high hourly rates. You can get access to their portfolios and testimonials but it’s not so easy to find a reliable partner here.

There are 2 hidden pitfalls:

  • How many specialists you need?
  • What is their reputation?

You look for a whole development team so take a deep breath and start browsing hundreds of pages with candidates’ profiles, study their works and be attentive to details. It will take much time and attention to hire 4-6 engineers to delegate the development tasks to.

Take into account that these people have never worked together. Issues may occur anytime; and it may negatively affect your product design.

Outsourcing

Nowadays, software development outsourcing is the best method for high-quality app production. It allows to:

  • Start development process fast;
  • Set strict deadlines and break into the unoccupied niche right on time;
  • Work with well-educated, highly-skilled and experienced engineers;
  • Extend your business boundaries;
  • Save money.

We have analyzed the statistics provided by job search websites along with good old Statista and Glassdoor. Now, we can confidently say it is much cheaper to build cooperation with a team of developers overseas than to hire on-site experts.

NB: product’s quality won’t suffer.

Outsourcing to Ukraine

There are so many outsourcing destinations! We have thought much about which one to choose to help you to reach success. Some of the outsourcing destinations are extremely cheap; others have convenient work hours. And there is the one that combines these factors and an opportunity to work with brilliant talents that speak English flawlessly. The developers work in a convenient time zone and their salary won’t eat your budget. These engineers are based in Ukraine, one of the greatest outsourcing destinations.

Why should you pay your attention to Ukraine?

  • A huge amount of resources: there are more than 185,000 IT experts in this country;
  • Seniority: more than 60,000 IT engineers have more than 5 years of experience;
  • Companies: many Ukrainian IT outsourcing companies are included in the top 100 ITO companies list;
  • Clients: such successful business giants as Microsoft, Samsung, Huawei, Siemens outsource their development to Ukraine.

Top 5 Ukrainian Outsourcing Companies To Take A Look At

The choice is hard. There are so many service providers in the market and there isn’t even enough time to consider all of them! We have shortlisted medium-size outsourcing companies, analyzed their ratings on Clutch and their former customers’ opinions. So take a look at the best representatives of Ukrainian outsourcing companies:

Intellectsoft

Here, custom mobile app development is the engineers’ primary skill. The company works with medium and large businesses from all over the world. We have noticed the products for Jaguar in the company’s portfolio.

Clockwise Software

Company’s specialists can help you with full-cycle product development. They deal with everything from deep requirements’ analysis to high-quality development and further app’s support. The engineers have expertise in building products for supply chain, eCommerce industry, marketing needs etc.

Echo

The company builds products for clients from North America and Western Europe. Company’s founders claim to have a huge pool of Ukrainian IT talents: in case you are looking for a dedicated team, Echo can build a great one for your needs.

Sigma Software

Have you ever organized your flights with Scandinavian Airlines? Sigma has developed software products for these world-known airlines. Sigma’s specialists work mostly with eCommerce, Big Data and business automation projects.

Devcom

Almost 20 years in the market! This is quite an impressive result. The company operates in Lviv and works with logistics, healthcare, financial and eCommerce software products.

To make the right choice, don’t miss a chance to get acquainted with the representatives and find out more about each business. Consider not only hard skills but also soft skills and communication. And don’t hesitate to delegate important tasks to qualified experts.

The post Software Development Outsourcing: Reasons to Opt for It appeared first on The Crazy Programmer.



Understanding module.exports and exports in Node.js

Working with Modules in Node.js

In programming, modules are self-contained units of functionality that can be shared and reused across projects. They make our lives as developers easier, as we can use them to augment our applications with functionality that we haven't had to write ourselves. They also allow us to organize and decouple our code, leading to applications that are easier to understand, debug and maintain.

In this article, I'll examine how to work with modules in Node.js, focusing on how to export and consume them.

Different Module Formats

As JavaScript originally had no concept of modules, a variety of competing formats have emerged over time. Here's a list of the main ones to be aware of:

  • The Asynchronous Module Definition (AMD) format is used in browsers and uses a define function to define modules.
  • The CommonJS (CJS) format is used in Node.js and uses require and module.exports to define dependencies and modules. The npm ecosystem is built upon this format.
  • The ES Module (ESM) format. As of ES6 (ES2015), JavaScript supports a native module format. It uses an export keyword to export a module's public API and an import keyword to import it.
  • The System.register format was designed to support ES6 modules within ES5.
  • The Universal Module Definition (UMD) format can be used both in the browser and in Node.js. It's useful when a module needs to be imported by a number of different module loaders.

Please be aware that this article deals solely with the CommonJS format, the standard in Node.js. If you'd like to read into any of the other formats, I recommend this article, by SitePoint author Jurgen Van de Moere.

Requiring a Module

Node.js comes with a set of built-in modules that we can use in our code without having to install them. To do this, we need to require the module using the require keyword and assign the result to a variable. This can then be used to invoke any methods the module exposes.

For example, to list out the contents of a directory, you can use the file system module and its readdir method:

const fs = require('fs');
const folderPath = '/home/jim/Desktop/';

fs.readdir(folderPath, (err, files) => {
  files.forEach(file => {
    console.log(file);
  });
});

Note that in CommonJS, modules are loaded synchronously and processed in the order they occur.

Creating and Exporting a Module

Now let's look at how to create our own module and export it for use elsewhere in our program. Start off by creating a user.js file and adding the following:

const getName = () => {
  return 'Jim';
};

exports.getName = getName;

Now create an index.js file in the same folder and add this:

const user = require('./user');
console.log(`User: ${user.getName()}`);

Run the program using node index.js and you should see the following output to the terminal:

User: Jim

So what has gone on here? Well, if you look at the user.js file, you'll notice that we're defining a getName function, then using the exports keyword to make it available for import elsewhere. Then in the index.js file, we're importing this function and executing it. Also notice that in the require statement, the module name is prefixed with ./, as it's a local file. Also note that there's no need to add the file extension.

Exporting Multiple Methods and Values

We can export multiple methods and values in the same way:

const getName = () => {
  return 'Jim';
};

const getLocation = () => {
  return 'Munich';
};

const dateOfBirth = '12.01.1982';

exports.getName = getName;
exports.getLocation = getLocation;
exports.dob = dateOfBirth;

And in index.js:

const user = require('./user');
console.log(
  `${user.getName()} lives in ${user.getLocation()} and was born on ${user.dob}.`
);

The code above produces this:

Jim lives in Munich and was born on 12.01.1982.

Notice how the name we give the exported dateOfBirth variable can be anything we fancy (dob in this case). It doesn't have to be the same as the original variable name.

Variations in Syntax

I should also mention that it's possible to export methods and values as you go, not just at the end of the file.

For example:

exports.getName = () => {
  return 'Jim';
};

exports.getLocation = () => {
  return 'Munich';
};

exports.dob = '12.01.1982';

And thanks to destructuring assignment, we can cherry-pick what we want to import:

const { getName, dob } = require('./user');
console.log(
  `${getName()} was born on ${dob}.`
);

As you might expect, this logs:

Jim was born on 12.01.1982.

The post Understanding module.exports and exports in Node.js appeared first on SitePoint.



Tuesday, 26 November 2019

Latest Kali Linux OS Added Windows-Style Undercover Theme for Hackers

You can relate this: While working on my laptop, I usually prefer sitting at a corner in the room from where no one should be able to easily stare at my screen, and if you're a hacker, you must have more reasons to be paranoid. Let's go undercover: If you're in love with the Kali Linux operating system for hacking and penetration testing, here we have pretty awesome news for you. Offensive

Malicious Android SDKs Caught Accessing Facebook and Twitter Users Data

Two third-party software development kits integrated by over hundreds of thousands of Android apps have been caught holding unauthorized access to users' data associated with their connected social media accounts. In a blog post published yesterday, Twitter revealed that an SDK developed by OneAudience contains a privacy-violating component which may have passed some of its users' personal

Stantinko botnet adds cryptomining to its pool of criminal activities

ESET researchers have discovered that the criminals behind the Stantinko botnet are distributing a cryptomining module to the computers they control

The post Stantinko botnet adds cryptomining to its pool of criminal activities appeared first on WeLiveSecurity



Monday, 25 November 2019

Quick Tip: How to Sort an Array of Objects in JavaScript

If you have an array of objects that you need to sort into a certain order, you might be tempted to reach for a JavaScript library. But before you do, remember that you can do some pretty neat sorting with the native Array.sort function.

In this article, we'll show you how to sort an array of objects in JavaScript with no fuss or bother.

To follow along, you'll need a knowledge of basic JavaScript concepts, such as declaring variables, writing functions, and conditional statements. We'll also be using ES6 syntax. You can get a refresher on that via our extensive collection of ES6 guides. This popular article was updated in November 2019.

Sort an array of objects in JavaScript

Basic Array Sorting

By default, the JavaScript Array.sort function converts each element in the array that needs to be sorted into a string, and compares them in Unicode code point order.

const foo = [9, 1, 4, 'zebroid', 'afterdeck'];
foo.sort(); // returns [ 1, 4, 9, 'afterdeck', 'zebroid' ]

const bar = [5, 18, 32, new Set, { user: 'Eleanor Roosevelt' }];
bar.sort(); // returns [ 18, 32, 5, { user: 'Eleanor Roosevelt' }, Set {} ]

You may be wondering why 32 comes before 5. Not logical, huh? Well, actually it is. This happens because each element in the array is first converted to a string, and "32" comes before "5" in Unicode order.

It’s also worth noting that unlike many other JavaScript array functions, Array.sort actually changes, or mutates the array it sorts.

const baz = ['My cat ate my homework', 37, 9, 5, 17];
baz.sort(); // baz array is modified
console.log(baz); // shows [ 17, 37, 5, 9, 'My cat ate my homework' ]

To avoid this, you can create a new instance of the array to be sorted and modify that instead. This is possible using an array method that returns a copy of the array. For example, Array.slice:

const sortedBaz = baz.slice().sort(); // a new instance of the baz array is created and sorted

Or if you prefer a newer syntax, you can use the spread operator for the same effect:

const sortedBaz = [...baz].sort(); // a new instance of the baz array is created and sorted

The output is the same in both cases:

console.log(baz); // ['My cat ate my homework', 37, 9, 5, 17];
console.log(sortedBaz); // [ 17, 37, 5, 9, 'My cat ate my homework' ]

The post Quick Tip: How to Sort an Array of Objects in JavaScript appeared first on SitePoint.



Data Breaches That Occurred in 2019 and How Cybersecurity Frameworks Can Work To Prevent Them

Data breaches are expensive. A company that suffers a data breach will spend about $4 million to recover lost information

Data Breaches That Occurred in 2019 and How Cybersecurity Frameworks Can Work To Prevent Them on Latest Hacking News.



Remote Work: Tips, Tricks and Best Practices for Success

Remote Work: Tips, Tricks and Best Practices for Success

There are lots of advantages to working away from the office, both for developers and for the companies that employ them. Think about avoiding the daily commute, the cost of office space, the cost of living in or traveling to the city for rural or international workers, the inconvenience of office work for differently abled people or those with unusual family or life responsibilities, and the inflexibility of trying to keep traditional 9–5 hours as more and more of our workforce adapts to the gig economy by taking on second jobs or part-time side hustles.

Remote work can help address many of these difficulties while improving team transparency and putting the focus of work back on the reasons you were hired for your job in the first place. It also opens up a world of possibilities for companies, including broader recruitment opportunities, improved worker transparency, lower infrastructure costs, and more scalable business models based on actual worker productivity.

But working from home or from a co-working space can also present new challenges, and learning how to recognize them and overcome them can make the difference between a productive, happy work experience and endless hours of misery, loneliness, and frustration.

Think I’m being overdramatic? Let me explain.

I’ve had the experience of being the remote worker who didn’t think he needed to pay attention to interpersonal office dynamics, or keep track of his time and accomplishments. I’ve worked long into the evening because I didn’t notice when the work day ended. I’ve struggled with inefficient tools that might have worked fine in an office environment, but proved woefully inadequate when it came to remote collaboration.

So I’ve learned to cope with these issues myself, and for years I’ve been coaching engineering teams by working on-site, remotely, and in various combinations of the two. Depending on your situation, there are a number of useful tools, tricks, and fundamental practices that can make your remote working experience so much better than it is today — for yourself, your team, your manager, and your company.

Remote Self-management

For better or for worse, most of us are used to having a manager decide what our working hours are, where we’re going to sit, what equipment we’re going to use, and whom we’re going to collaborate with. That’s a luxury that comes with the convenience of working together in a shared space, where management can supervise and coordinate our efforts. It may not always feel luxurious, but you may well find yourself missing the support of an attentive manager when you start working from home and realize you have to make these decisions for yourself.

Set a Schedule and Stick to It!

The first tip I offer for anyone starting out a remote role is to establish the hours you’re going to work, and stick to those hours.

It’s not as easy as it sounds. When you’re working from home, you won’t have all of the little cues that come with office life to tell you when to pause for lunch, when to take a break, and when to stop working for the day. Working from a co-working space or a coffee shop can help, but it’s not the same as having your colleagues around you to exert that not-so-subtle social pressure. What’s more, if you start to feel anxious about whether people at the office know how hard you’re working, you may find yourself wanting to compensate by putting in a few extra hours.

Some people find that it's easier to compartmentalize remote work by using a co-working space, simulating the effect of going out to work and then coming back at the end of the day. If you're working from home, your professional and personal lives can start to blend. You’re going to find yourself washing the dishes, feeding the cat, answering the telephone, and attending to all the other chores that crop up in your living space. And you know what? That’s just fine! … as long as it doesn't start to interfere with your productivity on the job.

Decide up front on your morning and afternoon work hours and respect them. Write them down somewhere you won’t forget to see them, so you can’t pretend you don’t know what they are. The same advice applies to teams working together in an office or people using co-working spaces, but it’s even more critical if you're working from home.

Let Everyone Know When and Where You'll Be Working

Building on the theme of scheduling, a remote worker needs to let anyone who works with them know how to get in touch, and may need to encourage that kind of contact regularly. Remote workers can feel isolated or even excluded — left out of important decisions because people at the office simply forgot about them. It's up to the person who’s working off site to make their existence known throughout the work day, and to advocate for visibility.

This can be easier said than done. One of the advantages of remote work is the ability to focus without interruption for extended periods. Sometimes just the knowledge that the bubble of isolation can be broken is enough to foster distraction and make it harder to concentrate. This can make the experience draining and unproductive, and negate most of the advantages.

It's not a bad idea to start off just using email to stay in touch with the team for typical group communications. And as a personal productivity tip, try to establish set times during the day to check that email — perhaps three or so over the course of a day. Checking your email constantly can establish a pattern of behavior that puts your attention at the mercy of anyone who wants to reach out to you for anything at any time. Email is asynchronous by nature, so use that to your advantage when you're working from home.

Apart from direct communication, it's good to get your team using a messaging tool such as Slack or HipChat. These services can run in the background on every team member's computer, or even on their mobile devices, providing a shared space for inter-team, intra-team, and cross-functional messaging. There are secure ways for companies to make services like these available for sensitive internal communications, and they can work both on site and off site, establishing virtual shared message boards to keep teams aligned.

The post Remote Work: Tips, Tricks and Best Practices for Success appeared first on SitePoint.



Aircraft Warning Lights Used By Planes to Avoid Obstacles Found Exposed to The Open Internet

Aircraft warning lights are obviously an important part of aviation since they facilitate the airplanes in tracking obstacles. A slight glitch

Aircraft Warning Lights Used By Planes to Avoid Obstacles Found Exposed to The Open Internet on Latest Hacking News.



Key features and best practices to look out for when purchasing a laptop

Cybersecurity is no longer a term, reserved only for the super paranoid nerds and/or conspiracy theorists. With hackers getting increasingly

Key features and best practices to look out for when purchasing a laptop on Latest Hacking News.



Google Expands Their Android Bug Bounty Program To Award Up To $1.5 Million

Google has recently made a lucrative announcement for bug bounty hunters. Reportedly, Google expanded their bug bounty program for Android

Google Expands Their Android Bug Bounty Program To Award Up To $1.5 Million on Latest Hacking News.



How to Disable Link in JavaScript?

In this tutorial, I will tell you how to disable link using javascript. As there are many ways to disable hyperlink like we can use event handler, getelmentbyid and set attribute method which is used to get and set value, attribute on any  HTML element. So, following are the ways to stop the link functionality.

How to Disable Link in JavaScript?

Method 1: Using CSS

To disable hyperlink the main CSS property that we use is pointer events. Check the code given below.

index.html

<!DOCTYPE html>
<html>
  <head>
    <title>
      Disable HTML href link using JS
    </title>
    <style>
      a.disabled {
        pointer-events: none;
      }
    </style>
  </head>

  <body style="text-align:center;">
    <h1 style="color:red;">
      Hello World
    </h1>
    <a href="https://www.thecrazyprogrammer.com/" id="linkId">
      LINK
    </a>
    <br /><br />
    <button onclick="disableLink()">
      disable  
    </button>
    <p id="linkStatus" style="color:green; font-size: 20px; font-weight: bold;"></p>
  </body>
</html>

<script>
                        let link = document.getElementById('linkId');
                        let down = document.getElementById('linkStatus');
                        function disableLink() {
                        link.setAttribute('class', 'disabled');
                        link.setAttribute('style', 'color: black;');
                        down.innerHTML = 'Link disabled';
                        }
</script>

Method 2: Using Function

<a href="https://www.thecrazyprogrammer.com/" id='TheLink'>test</a>
<input type='button' value="Disable" onclick="disableLink( 'TheLink', this );">

<script type="text/javascript">
  function disableLink(linkID, objButton) {
      const el = document.getElementById(linkID);
      if (!el.onclick) {
        el.onclick = function() {
          return false;
        };
        objButton.value = "Enable";
      } else {
        el.onclick = function() {
          return true;
        };
        objButton.value = "Disable";
      }
    }
</script>

Method 3: Using Event Handler

Event handler used to handle any action like inputting data, calling methods etc.

Example:

<a id="openSite" href="https://www.thecrazyprogrammer.com/">open website</a>
<button onclick=disablelink('openSite')>Disable link </button>

<style>
.disabledLink
{
color: #333;
text-decoration : none;
cursor: default;
}
</style>

<script>
function disablelink(linkID)
{
var hlink = document.getElementById(linkID);
if(!hlink)
return;
hlink.href = "#";
hlink.className = "disabledLink";
}
</script>

You can replace # (hash) with javascript:void (0) event handler.

Comment down below if you have queries or know any other way to disable hyperlink in javascript.

The post How to Disable Link in JavaScript? appeared first on The Crazy Programmer.



CyberwarCon – the future of nation‑state nastiness

How the field of play has changed and why endpoint protection often comes down to doing the basics, even in the face of increasingly complex threats

The post CyberwarCon – the future of nation‑state nastiness appeared first on WeLiveSecurity



Vulnerability Hit Truecaller App Potentially Affecting Millions Of Users

The popular call-blocking application Truecaller has recently made it to the news due to a security flaw. A researcher discovered

Vulnerability Hit Truecaller App Potentially Affecting Millions Of Users on Latest Hacking News.



Sunday, 24 November 2019

Ginp – The Latest Android Banking Trojan Found Active In The Wild

Once again, a new banking Trojan variant has surfaced online that draws attention owing to its typical features. Termed ‘Ginp’,

Ginp – The Latest Android Banking Trojan Found Active In The Wild on Latest Hacking News.



OnePlus Discloses Data Breach Impacting Users’ Personal Information

The smartphone brand OnePlus has recently made it to the news owing to a cybersecurity incident. As revealed by the

OnePlus Discloses Data Breach Impacting Users’ Personal Information on Latest Hacking News.



Spoofing Vulnerability Found In Microsoft Outlook For Android

Microsoft recently disclosed a vulnerability in Outlook for Android that risked millions of devices. Exploiting the bug could permit cross-site

Spoofing Vulnerability Found In Microsoft Outlook For Android on Latest Hacking News.



T-Mobile Reveals A Security Breach Affecting Prepaid Users

Adding one more to the count of data breaches this year, now joins the cellular firm T-Mobile. Recently, T-Mobile has

T-Mobile Reveals A Security Breach Affecting Prepaid Users on Latest Hacking News.



Twitter Users Finally Offered 2FA Account Security Options Other Than SMS

Twitter has recently announced a major update in their system that may bring a sigh of relief for some users.

Twitter Users Finally Offered 2FA Account Security Options Other Than SMS on Latest Hacking News.



Saturday, 23 November 2019

Android Camera App Vulnerability Could Allow Attackers to Spy On Users

Google and Samsung smartphones reportedly had a serious security flaw that could allow spying on users. The vulnerability existed in

Android Camera App Vulnerability Could Allow Attackers to Spy On Users on Latest Hacking News.



DSXS | An open source, simple and effective XSS scanner that can be easily customized

Damn Small XSS Scanner (DSXS) is a great tool for finding cross site scripting vulnerabilities, the tool has been developed

DSXS | An open source, simple and effective XSS scanner that can be easily customized on Latest Hacking News.



Jetpack WordPress Plugin Vulnerability Affected Numerous Websites – Patch Now!

Heads up WordPress admins! A researcher has found a critical vulnerability in the Jetpack WordPress plugin. Fortunately, a fix is

Jetpack WordPress Plugin Vulnerability Affected Numerous Websites – Patch Now! on Latest Hacking News.



Dozens of Severe Flaws Found in 4 Popular Open Source VNC Software

Four popular open-source VNC remote desktop applications have been found vulnerable to a total of 37 security vulnerabilities, many of which went unnoticed for the last 20 years and most severe could allow remote attackers to compromise a targeted system. VNC (virtual network computing) is an open source graphical desktop sharing protocol based on RFB (Remote FrameBuffer) that allows users to

Friday, 22 November 2019

OnePlus Suffers New Data Breach Impacting Its Online Store Customers

Chinese smartphone maker OnePlus has suffered a new data breach exposing personal and order information of an undisclosed number of its customers, likely, as a result of a vulnerability in its online store website. The breach came to light after OnePlus started informing affected customers via email and published a brief FAQ page to disclose information about the security incident. According

Boost Your Personal Security With These Killer 2019 Black Friday and Cyber Monday Deals

If you're like most consumers, you're probably looking forward to the upcoming Black Friday and Cyber Monday sale events. Who wouldn't want to get all sorts of products and services at massive discounts? But while most consumers are typically eyeing personal gadgets and entertainment appliances, you may want to consider scoring deals on personal security software and devices. Everyone's

Week in security with Tony Anscombe

ESET researchers publish their findings on Mispadu, a banking trojan targeting Brazil and Mexico, and on DePriMon, a downloader with a unique installation technique

The post Week in security with Tony Anscombe appeared first on WeLiveSecurity



Even Small Business Need Penetration Testing - Here’s Why

Image: Unsplash Since you’re a small business,...

[[ This is a content summary only. Visit my website for full links, other content, and more! ]]

Google offers up to $1.5 million bounty for remotely hacking Titan M chip

With its latest announcement to increase bug bounty rewards for finding and reporting critical vulnerabilities in the Android operating system, Google yesterday set up a new challenging level for hackers that could let them win a bounty of up to $1.5 million. Starting today, Google will pay $1 million for a "full chain remote code execution exploit with persistence which compromises the Titan

Should cybersecurity be taught in schools?

Experts weigh in on whether schools should teach kids the skills they need to safely reap the benefits of the online world

The post Should cybersecurity be taught in schools? appeared first on WeLiveSecurity



Russian Hacker Behind NeverQuest Banking Malware Gets 4 Years in U.S. Prison

A Russian hacker who created and used Neverquest banking malware to steal money from victims' bank accounts has finally been sentenced to 4 years in prison by the United States District Court for the Southern District of New York. Stanislav Vitaliyevich Lisov, 34, was arrested by Spanish authorities at Barcelona–El Prat Airport in January 2017 on the request of the FBI and extradited to the

Thursday, 21 November 2019

T-Mobile Suffers Data Breach Affecting Prepaid Wireless Customers

Are you a T-Mobile prepaid customer? If yes, you should immediately create or update your associated account PIN/passcode as additional protection. The US-based telecom giant T-Mobile today disclosed a yet another data breach incident that recently exposed potentially personal information of some of the customers using its prepaid services. What happened? In a statement posted on its website,

Create a Toggle Switch in React as a Reusable Component

Implementing a Toggle Switch in React JS as a Reusable Component

In this article, we're going to create an iOS-inspired toggle switch using React components. By the end, we'll have built a simple demo React App that uses our custom toggle switch component.

We could use third-party libraries for this, but building from scratch allows us to better understand how our code is working and allows us to customize our component completely.

Forms provide a major means for enabling user interactions. The checkbox is traditionally used for collecting binary data — such as yes or no, true or false, enable or disable, on or off, etc. Although some modern interface designs steer away from form fields when creating toggle switches, I'll stick with them here due to their greater accessibility.

Here's a screenshot of the component we'll be building:

The final result

Getting Started

We can start with a basic HTML checkbox input form element with its necessary properties set:

<input type="checkbox" name="name" id="id" />

To build around it, we might need an enclosing <div> with a class, a <label> and the <input /> control itself. Adding everything, we might get something like this:

<div class="toggle-switch">
  <input type="checkbox" class="toggle-switch-checkbox" name="toggleSwitch" id="toggleSwitch" />
  <label class="toggle-switch-label" for="toggleSwitch">
        Toggle Me!
  </label>
</div>

In time, we can get rid of the label text and use the <label> tag to check or uncheck the checkbox input control. Inside the <label>, let's add two <span>s that help us construct the switch holder and the toggling switch itself:

<div class="toggle-switch">
  <input type="checkbox" class="toggle-switch-checkbox" name="toggleSwitch" id="toggleSwitch" />
  <label class="toggle-switch-label" for="toggleSwitch">
    <span class="toggle-switch-inner"></span>
    <span class="toggle-switch-switch"></span>
  </label>
</div>

Converting to a React Component

Now that we know what needs to go into the HTML, all we need to do is to convert the HTML into a React component. Let's start with a basic component here. We'll make this a class component, and then we'll convert it into hooks, as it's easier for new developers to follow state than useState:

import React, { Component } from "react";

class ToggleSwitch extends Component {
  render() {
    return (
      <div className="toggle-switch">
        <input
          type="checkbox"
          className="toggle-switch-checkbox"
          name="toggleSwitch"
          id="toggleSwitch"
        />
        <label className="toggle-switch-label" htmlFor="toggleSwitch">
          <span className="toggle-switch-inner" />
          <span className="toggle-switch-switch" />
        </label>
      </div>
    );
  }
}

export default ToggleSwitch;

At this point, it's not possible to have multiple toggle switch sliders on the same view or same page due to the repetition of ids. We could leverage React's way of componentization here, but in this instance, we'll be using props to dynamically populate the values:

import React, { Component } from "react";

class ToggleSwitch extends Component {
  render() {
    return (
      <div className="toggle-switch">
        <input
          type="checkbox"
          className="toggle-switch-checkbox"
          name={this.props.Name}
          id={this.props.Name}
        />
        <label className="toggle-switch-label" htmlFor={this.props.Name}>
          <span className="toggle-switch-inner" />
          <span className="toggle-switch-switch" />
        </label>
      </div>
    );
  }
}

export default ToggleSwitch;

The this.props.Name will populate the values of id, name and for (note that it is htmlFor in React JS) dynamically, so that you can pass different values to the component and have multiple of them on the same page. Also, the <span> tag doesn't have an ending </span> tag; instead it's closed in the starting tag like <span />, and this is completely fine.

The post Create a Toggle Switch in React as a Reusable Component appeared first on SitePoint.



A Review Of Yodot Recovery Software For Windows And Mac

While SD cards provide a wonderful means to store photos, videos, and other data, they need careful handling since they

A Review Of Yodot Recovery Software For Windows And Mac on Latest Hacking News.



Python 2 Will Die Soon – Know Why? | End of Python 2 in Jan 2020

Back late in 2006, when Python 3.0 came into introduction, the volunteers and officials felt the need that users should migrate from the old version (Python 2) to the newer version.

Since they did not want to hurt Python programmers, so they decided to end Python 2.0 in 2015. They officially announced this news late back in 2008 that sunset of Python 2 would take place in 2015.

“But thanks to Python lovers! they didn’t migrate to Python 3.0 in seven years of the deadline.”

Many of them did, but the vast majority didn’t. So, it was then decided to extend the end of Python 2 in 2020. And now the volunteers, as well as officials, are earnest for the concern of migrating from the older version to the newer one.

What is the deadline for migrating the source code of Python 2 to version 3.0?

The effect shall start from the 1st of January, 2020. The Python Announcement Mailing List and The National Cyber Security Centre (NCSC), in August, has given the statement that organizations should migrate code off Python 2. Because of the effect from January 2020, it should never receive any security update.

Why is this necessary?

There are only a few obvious reasons for shutting down of Python 2 and that are:

  • Python 3 is not retrograde compatible with Python 2. As a result, significant changes in Python 3 are not portable with the older version.
  • Python Volunteers have also claimed that there are many improvements which Python 2 cannot handle.
  • Working on improvements with Python 2 and Python 3 simultaneously restricts users and volunteers to make Python language faster.

Another major reason that has faced major organizations was a change in the syntax of the print statement, which reduces much code. So, the majority of libraries and organizations were hesitant to migrate.

Further, in past years, Python 3 introduced substantial improvements that have helped itself to become the precise version but was not co-related with existing projects that are already working.

Consequences of not migrating to Python 3

Python 2 is going to die soon

Image Source

If people continue using Python 2, it would be hard for volunteers and aid agencies to help resolve any issues. As a result, volunteers who use Python to make software cannot use new things in Python 3.

The security updates are further stopped for Python 2.0. If users receive any catastrophic security issue, volunteers cannot help them in any concern. Also, this could result in slowing down of software and other people who rely on particular software.

If any user still wishes to continue with Python 2, sooner or later they have to face issues which might lead to catastrophic situation and loss of data.

With no further security updates for Python 2, the declaration also states that your data and information would no longer be safe. So, it’s good to migrate as soon as possible.

The post Python 2 Will Die Soon – Know Why? | End of Python 2 in Jan 2020 appeared first on The Crazy Programmer.



Registers as “Default Print Monitor”, but is a malicious downloader. Meet DePriMon

ESET researchers have discovered a new downloader with a novel, not previously seen in the wild installation technique

The post Registers as “Default Print Monitor”, but is a malicious downloader. Meet DePriMon appeared first on WeLiveSecurity



Wednesday, 20 November 2019

Compile-time Immutability in TypeScript

Compile-time Immutability in TypeScript

TypeScript allows us to decorate specification-compliant ECMAScript with type information that we can analyze and output as plain JavaScript using a dedicated compiler. In large-scale projects, this sort of static analysis can catch potential bugs ahead of resorting to lengthy debugging sessions, let alone deploying to production. However, reference types in TypeScript are still mutable, which can lead to unintended side effects in our software.

In this article, we'll look at possible constructs where prohibiting references from being mutated can be beneficial.

Primitives vs Reference Types

JavaScript defines two overarching groups of data types:

  • Primitives: low-level values that are immutable (e.g. strings, numbers, booleans etc.)
  • References: collections of properties, representing identifiable heap memory, that are mutable (e.g. objects, arrays, Map etc.)

Say we declare a constant, to which we assign a string:

const message = 'hello';

Given that strings are primitives and are thus immutable, we’re unable to directly modify this value. It can only be used to produce new values:

console.log(message.replace('h', 'sm')); // 'smello'
console.log(message); // 'hello'

Despite invoking replace() upon message, we aren't modifying its memory. We're merely creating a new string, leaving the original contents of message intact.

Mutating the indices of message is a no-op by default, but will throw a TypeError in strict mode:

'use strict';

const message = 'hello';
message[0] = 'j'; // TypeError: 0 is read-only

Note that if the declaration of message were to use the let keyword, we would be able to replace the value to which it resolves:

let message = 'hello';
message = 'goodbye';

It's important to highlight that this is not mutation. Instead, we're replacing one immutable value with another.

Mutable References

Let's contrast the behavior of primitives with references. Let's declare an object with a couple of properties:

const me = {
  name: 'James',
  age: 29,
};

Given that JavaScript objects are mutable, we can change its existing properties and add new ones:

me.name = 'Rob';
me.isTall = true;

console.log(me); // Object { name: "Rob", age: 29, isTall: true };

Unlike primitives, objects can be directly mutated without being replaced by a new reference. We can prove this by sharing a single object across two declarations:

const me = {
  name: 'James',
  age: 29,
};

const rob = me;

rob.name = 'Rob';

console.log(me); // { name: 'Rob', age: 29 }

JavaScript arrays, which inherit from Object.prototype, are also mutable:

const names = ['James', 'Sarah', 'Rob'];

names[2] = 'Layla';

console.log(names); // Array(3) [ 'James', 'Sarah', 'Layla' ]

What's the Issue with Mutable References?

Consider we have a mutable array of the first five Fibonacci numbers:

const fibonacci = [1, 2, 3, 5, 8];

log2(fibonacci); // replaces each item, n, with Math.log2(n);
appendFibonacci(fibonacci, 5, 5); // appends the next five Fibonacci numbers to the input array

This code may seem innocuous on the surface, but since log2 mutates the array it receives, our fibonacci array will no longer exclusively represent Fibonacci numbers as the name would otherwise suggest. Instead, fibonacci would become [0, 1, 1.584962500721156, 2.321928094887362, 3, 13, 21, 34, 55, 89]. One could therefore argue that the names of these declarations are semantically inaccurate, making the flow of the program harder to follow.

Pseudo-immutable Objects in JavaScript

Although JavaScript objects are mutable, we can take advantage of particular constructs to deep clone references, namely spread syntax:

const me = {
  name: 'James',
  age: 29,
  address: {
    house: '123',
    street: 'Fake Street',
    town: 'Fakesville',
    country: 'United States',
    zip: 12345,
  },
};

const rob = {
  ...me,
  name: 'Rob',
  address: {
    ...me.address,
    house: '125',
  },
};

console.log(me.name); // 'James'
console.log(rob.name); // 'Rob'
console.log(me === rob); // false

The spread syntax is also compatible with arrays:

const names = ['James', 'Sarah', 'Rob'];
const newNames = [...names.slice(0, 2), 'Layla'];

console.log(names); // Array(3) [ 'James', 'Sarah', 'Rob' ]
console.log(newNames); // Array(3) [ 'James', 'Sarah', 'Layla' ]
console.log(names === newNames); // false

Thinking immutably when dealing with reference types can make the behavior of our code clearer. Revisiting the prior mutable Fibonacci example, we could avoid such mutation by copying fibonacci into a new array:

const fibonacci = [1, 2, 3, 5, 8];
const log2Fibonacci = [...fibonacci];

log2(log2Fibonacci);
appendFibonacci(fibonacci, 5, 5);

Rather than placing the burden of creating copies on the consumer, it would be preferable for log2 and appendFibonacci to treat their inputs as read-only, creating new outputs based upon them:

const PHI = 1.618033988749895;

const log2 = (arr: number[]) => arr.map(n => Math.log2(2));
const fib = (n: number) => (PHI ** n - (-PHI) ** -n) / Math.sqrt(5);

const createFibSequence = (start = 0, length = 5) =>
  new Array(length).fill(0).map((_, i) => fib(start + i + 2));

const fibonacci = [1, 2, 3, 5, 8];
const log2Fibonacci = log2(fibonacci);
const extendedFibSequence = [...fibonacci, ...createFibSequence(5, 5)];

By writing our functions to return new references in favor of mutating their inputs, the array identified by the fibonacci declaration remains unchanged, and its name remains a valid source of context. Ultimately, this code is more deterministic.

The post Compile-time Immutability in TypeScript appeared first on SitePoint.



Six Tips to Safely Shop Online During Black Friday and Cyber Monday 2019

The Thanksgiving weekend is just right around the corner. While some would still associate the upcoming holiday as time to

Six Tips to Safely Shop Online During Black Friday and Cyber Monday 2019 on Latest Hacking News.



Macy’s Became The Latest Victim Of MageCart Attack

It hasn’t been a while since we heard of a MageCart attack, however now, Macy’s has disclosed a similar attack. As

Macy’s Became The Latest Victim Of MageCart Attack on Latest Hacking News.



What does it take to attract top cybersecurity talent?

From professional backgrounds to competitive salaries – a study delves into what it takes to build strong cybersecurity teams

The post What does it take to attract top cybersecurity talent? appeared first on WeLiveSecurity



The Ultimate 2019 Security Team Assessment Template

Assessing the performance of your security team is critical to both knowing your current posture, as well as planning ahead. 'The Ultimate 2019 Security Team Assessment Template' is the first attempt to capture all the main KPIs of the security team main pillars, saving CIOs and CISOs the time and effort of creating such an assessment from scratch and providing them with a simple and

The Cyber Essentials Checklist: How Accreditation Can Help Executives Grow Their Business

Since the dawn of the computer era, entrepreneurs and hackers have been in a constant race to outwork each other.

The Cyber Essentials Checklist: How Accreditation Can Help Executives Grow Their Business on Latest Hacking News.



3 ways an attacker may compromise a phone without the victims knowledge

We carry our mobile phones everywhere with us. These devices store our personal information. If this data falls into the

3 ways an attacker may compromise a phone without the victims knowledge on Latest Hacking News.



Official Monero Site Hacked to Distribute Cryptocurrency Stealing Malware

What an irony — someone hacked the official website of the Monero cryptocurrency project and quietly replaced legitimate Linux and Windows binaries available for download with malicious versions designed to steal funds from users' wallets. The latest supply-chain cyberattack was revealed on Monday after a Monero user spotted that the cryptographic hash for binaries he downloaded from the