Create an account


Welcome, Guest
You have to register before you can post on our site.

Username
  

Password
  





Search Forums

(Advanced Search)

Forum Statistics
» Members: 20,139
» Latest member: demble8888
» Forum threads: 21,961
» Forum posts: 22,832

Full Statistics

Online Users
There are currently 3796 online users.
» 1 Member(s) | 3789 Guest(s)
Applebot, Baidu, Bing, DuckDuckGo, Google, Yandex, demble8888

 
  (Indie Deal) Cold Spaghetti Bundle & The GameCreators 2 Bundle
Posted by: xSicKxBot - 08-18-2022, 10:43 AM - Forum: Deals or Specials - No Replies

Cold Spaghetti Bundle & The GameCreators 2 Bundle

Cold Spaghetti Bundle | 6 Steam Games | 93% OFF
[www.indiegala.com]
Something refreshing, something unusual, something unexpected. This indie game bundle has it all and more: All Walls Must Fall, Firelight Fantasy: Resistance, Niflhel's Fables: The Book of Gypsies, Adventures at the North Pole, Freddy Spaghetti & its sequel.

https://www.youtube.com/watch?v=Tsf5Wjb1uAM
The GameCreators 2 Bundle | 98% OFF over $300-worth of content
[www.indiegala.com]
Become a gamedev on your own & create your dream video game with the help of GameGuru, AppGameKit & a vast selection of steam game assets, software and dlcs. From Modern to Retro, from constructions to military/medical assets, a giant array of options & tools are available for you to choose from.

Summer Deals Ending soon
[www.indiegala.com]
[www.indiegala.com]
[www.indiegala.com]
https://www.youtube.com/watch?v=5KZzppX-Ibg
Stay Inside, Stay Safe and Enjoy Good Games.
Check out IndieGala on Twitter, YouTube & Facebook[www.facebook.com]


https://steamcommunity.com/groups/indieg...0935068968

Print this item

  News - Thymesia: All Potion Recipes
Posted by: xSicKxBot - 08-18-2022, 10:43 AM - Forum: Lounge - No Replies

Thymesia: All Potion Recipes
Become the alchemist you've always been inside.

GameSpot may receive revenue from affiliate and advertising partnerships for sharing this content and from purchases through links.
Thymesia has a lot of unique mechanics we haven’t seen much in other soulslikes, and one of those is its intriguing potions system. Not only can you find and equip a variety of ingredients to add boons to your potions, but using specific ingredients together can result in recipes that grant additional helpful bonuses. Note, however, that some ingredients won’t be available until near the end of the game and may require you to revisit locations via sub quests. Also, you do not need to place the ingredients in order to achieve the desired recipe. We’ve compiled a full list of recipes below so that you can decide what works best for you.

Circulation
Effect: Recover 5 health every second
Advertisement
Ingredients: Fennel, Oregano, Clove

Refreshing
Effect: Recover 3 energy every second
Ingredients: Fennel, Oregano, Mint

Pain Relief
Effect: Reduces damage intake by 10%
Ingredients: Rosemary, Clove, Lavender

Focus
Effect: Increases memory shards drop amount by 10%
Ingredients: Rosemary, Mint, Thyme

Four Thieves Vinegar
Effect: Increases maximum health by 100
Ingredients: Rosemary, Sage, Thyme

Warming Up
Effect: Increases damage by 10%
Ingredients: Black Pepper, Garlic, Basil

Sweating
Effect: Gain a stack of “Defensive” buff
Ingredients: Mint, Black Pepper, Cinnamon

Courage
Effect: Gain a stack of “Offensive” buff
Ingredients: Mint, Lavender, Black Pepper

Print this item

  PC - Two Point Campus
Posted by: xSicKxBot - 08-18-2022, 10:43 AM - Forum: New Game Releases - No Replies

Two Point Campus



Build the university of your dreams with Two Point Campus, the sim with a twist from the makers of Two Point Hospital. Build, hire staff and run an academic institution packed with wild courses. Rather than typical academic fare, students in Two Point County enjoy a range of wild and wonderful courses: from Knight School (hey, we all have to learn jousting at some point in our lives), to the salivatory Gastronomy, where your students will build mouth-watering concoctions like giant pizzas and enormous pies.

Get to know your students, explore their individual personalities, wants and needs. Keep them happy with clubs, societies, gigs. Surround them with friends, help them develop relationships, furnish them with pastoral care and ensure they have the right amount of joie de vivre to develop into incredible individuals who will do the legacy of your university proud.

Publisher: Sega

Release Date: Aug 09, 2022




https://www.metacritic.com/game/pc/two-point-campus

Print this item

  [Tut] 7 Best Ways to Convert Dict to CSV in Python
Posted by: xSicKxBot - 08-17-2022, 01:53 PM - Forum: Python - No Replies

7 Best Ways to Convert Dict to CSV in Python

5/5 – (1 vote)

? Question: How to convert a dictionary to a CSV in Python?

In Python, convert a dictionary to a CSV file using the DictWriter() method from the csv module. The csv.DictWriter() method allows you to insert a dictionary-formatted row (keys=column names; values=row elements) into the CSV file using its DictWriter.writerow() method.

? Learn More: If you want to learn about converting a list of dictionaries to a CSV, check out this Finxter tutorial.

Method 1: Python Dict to CSV in Pandas


First, convert a list of dictionaries to a Pandas DataFrame that provides you with powerful capabilities such as the

Second, convert the Pandas DataFrame to a CSV file using the DataFrame’s to_csv() method with the filename as argument.

salary = [{'Name':'Alice', 'Job':'Data Scientist', 'Salary':122000}, {'Name':'Bob', 'Job':'Engineer', 'Salary':77000}, {'Name':'Carl', 'Job':'Manager', 'Salary':119000}] # Method 1
import pandas as pd
df = pd.DataFrame(salary)
df.to_csv('my_file.csv', index=False, header=True)

Output:

Name,Job,Salary
Alice,Data Scientist,122000
Bob,Engineer,77000
Carl,Manager,119000

You create a Pandas DataFrame—which is Python’s default representation of tabular data. Think of it as an Excel spreadsheet within your code (with rows and columns).

The DataFrame is a very powerful data structure that allows you to perform various methods. One of those is the to_csv() method that allows you to write its contents into a CSV file.

  • You set the index argument of the to_csv() method to False because Pandas, per default, adds integer row and column indices 0, 1, 2, …. Again, think of them as the row and column indices in your Excel spreadsheet. You don’t want them to appear in the CSV file so you set the arguments to False.
  • You set the and header argument to True because you want the dict keys to be used as headers of the CSV.

If you want to customize the CSV output, you’ve got a lot of special arguments to play with. Check out this Finxter Tutorial for a comprehensive list of all arguments.

? Related article: Pandas Cheat Sheets to Pin to Your Wall

Method 2: Dict to CSV File


In Python, convert a dictionary to a CSV file using the DictWriter() method from the csv module. The csv.DictWriter() method allows you to insert data into the CSV file using its DictWriter.writerow() method.

The following example writes the dictionary to a CSV using the keys as column names and the values as row values.

import csv data = {'A':'X1', 'B':'X2', 'C':'X3'} with open('my_file.csv', 'w', newline='') as f: writer = csv.DictWriter(f, fieldnames=data.keys()) writer.writeheader() writer.writerow(data)

The resulting file 'my_file.csv' looks like this:


The csv library may not yet installed on your machine. To check if it is installed, follow these instructions. If it is not installed, fix it by running pip install csv in your shell or terminal.

Method 3: Dict to CSV String (in Memory)


To convert a list of dicts to a CSV string in memory, i.e., returning a CSV string instead of writing in a CSV file, use the pandas.DataFrame.to_csv() function without file path argument. The return value is a CSV string representation of the dictionary.

Here’s an example:

import pandas as pd data = [{'A':'X1', 'B':'X2', 'C':'X3'}, {'A':'Y1', 'B':'Y2', 'C':'Y3'}] df = pd.DataFrame(data)
my_csv_string = df.to_csv(index=False) print(my_csv_string) '''
A,B,C
X1,X2,X3
Y1,Y2,Y3 '''

We pass index=False because we don’t want an index 0, 1, 2 in front of each row.

Method 4: Dict to CSV Append Line


To append a dictionary to an existing CSV, you can open the file object in append mode using open('my_file.csv', 'a', newline='') and using the csv.DictWriter() to append a dict row using DictWriter.writerow(my_dict).

Given the following file 'my_file.csv':


You can append a row (dict) to the CSV file via this code snippet:

import csv row = {'A':'Y1', 'B':'Y2', 'C':'Y3'} with open('my_file.csv', 'a', newline='') as f: writer = csv.DictWriter(f, fieldnames=row.keys()) writer.writerow(row)

After running the code in the same folder as your original 'my_file.csv', you’ll see the following result:


Method 5: Dict to CSV Columns


To write a Python dictionary in a CSV file as a column, i.e., a single (key, value) pair per row, use the following three steps:

  • Open the file in writing mode and using the newline='' argument to prevent blank lines.
  • Create a CSV writer object.
  • Iterate over the (key, value) pairs of the dictionary using the dict.items() method.
  • Write one (key, value) tuple at a time by passing it in the writer.writerow() method.

Here’s the code example:

import csv data = {'A':42, 'B':41, 'C':40} with open('my_file.csv', 'w', newline='') as f: writer = csv.writer(f) for row in data.items(): writer.writerow(row)

Your output CSV file (column dict) looks like this:


Method 6: Dict to CSV with Header


Convert a Python dictionary to a CSV file with header using the csv.DictWriter(fileobject, fieldnames) method to create a writer object used for writing the header via writer.writeheader() without argument. This writes the list of column names passed as fieldnames, e.g., the dictionary keys obtained via dict.keys().

To write the rows, you can then call the DictWriter.writerow() method.

The following example writes the dictionary to a CSV using the keys as column names and the values as row values.

import csv data = {'A':'X1', 'B':'X2', 'C':'X3'} with open('my_file.csv', 'w', newline='') as f: writer = csv.DictWriter(f, fieldnames=data.keys()) writer.writeheader() writer.writerow(data)

The resulting file 'my_file.csv' looks like this:


Where to Go From Here

If you haven’t found your solution, yet, you may want to check out my in-depth guide on how to write a list of dicts to a CSV:

? Guide: Write List of Dicts to CSV in Python

Bonus Method 7: Vanilla Python


If you don’t want to import any library and still convert a list of dicts into a CSV file, you can use standard Python implementation as well: it’s not complicated and very efficient.

? Finxter Recommended: Join the Finxter community and download your 8+ Python cheat sheets to refresh your code understanding.

This method is best if you won’t or cannot use external dependencies.

  • Open the file f in writing mode using the standard open() function.
  • Write the first dictionary’s keys in the file using the one-liner expression f.write(','.join(salary[0].keys())).
  • Iterate over the list of dicts and write the values in the CSV using the expression f.write(','.join(str(x) for x in row.values())).

Here’s the concrete code example:

salary = [{'Name':'Alice', 'Job':'Data Scientist', 'Salary':122000}, {'Name':'Bob', 'Job':'Engineer', 'Salary':77000}, {'Name':'Carl', 'Job':'Manager', 'Salary':119000}] # Method 3
with open('my_file.csv','w') as f: f.write(','.join(salary[0].keys())) f.write('n') for row in salary: f.write(','.join(str(x) for x in row.values())) f.write('n')

Output:

Name,Job,Salary
Alice,Data Scientist,122000
Bob,Engineer,77000
Carl,Manager,119000

In the code, you first open the file object f. Then you iterate over each row and each element in the row and write the element to the file—one by one. After each element, you place the comma to generate the CSV file format. After each row, you place the newline character 'n'.

Note: to get rid of the trailing comma, you can check if the element x is the last element in the row within the loop body and skip writing the comma if it is.

? Related Tutorial: How to Convert a List to a CSV File in Python [5 Ways]

Programming Humor – Python


“I wrote 20 short programs in Python yesterday. It was wonderful. Perl, I’m leaving you.”xkcd

Where to Go From Here?


Enough theory. Let’s get some practice!

Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.

To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

You build high-value coding skills by working on practical coding projects!

Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?

? If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!



https://www.sickgaming.net/blog/2022/08/...in-python/

Print this item

  [Tut] How to Upload Files to Google Drive with JavaScript
Posted by: xSicKxBot - 08-17-2022, 01:53 PM - Forum: PHP Development - No Replies

How to Upload Files to Google Drive with JavaScript

by Vincy. Last modified on August 15th, 2022.

This article gives a working example script to learn how to upload files to Google Drive via JavaScript.

Creating a JavaScript solution to the Drive file upload process is very simple. It uses gapi library to implement this feature on the client side.

In a recently posted tutorial, we created an example code for achieving Google Drive upload in PHP.

Prerequisites


It needs two libraries loaded to achieve JavaScript via Google Drive upload.

  1. Google sign-in library for identity verification.
  2. Google API client library for JavaScript-based API access.

Added to that, create the API app and get the credentials.

  1. Enable the Google Drive API.
  2. Get the API key and Web client id from the Google developer console.

Go to the Google developer console and click “Create Credentials” to set the API key and web client id. We have seen how to get the Google API keys from the developer console in previous articles.

Steps to upload files to Google Drive with JavaScript


These are the steps to implement uploading files from an application to Google Drive using JavaScript.

  1. Authorize by proving the identity via Google sign-in API (GSI) library challenge.
  2. Get the access token.
  3. Prepare the upload request by specifying the Google drive directory target (optional).
  4. Hit Google Drive V3 endpoint to post file content and metadata via JavaScript FormData.

authorize and upload to google drive

Example code for uploading files to Drive


The below code shows the landing page interface in HTML and the JavaScript asset created for uploading the files to Google Drive.

HTML code to display controls for requesting authorization and upload


When landing on the home page, it displays an Authorize button in the UI. On clicking this button, it shows the Google sign-in overlay dialog to proceed with the authorization request.

In this step, the user must prove their identity to have access to upload to the Drive directory.

index.php

<!DOCTYPE html>
<html>
<head>
<title>Google Drive upload using JavaScript</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" type="text/css" href="css/style.css" />
<link rel="stylesheet" type="text/css" href="css/form.css" />
<style>
#content { display: none;
}
</style>
</head>
<body> <!--Add HTML buttons to sign in and sign out--> <div class="phppot-container"> <h1>Google Drive upload using JavaScript</h1> <div> <div class="row"> <input type="button" id="authorize_button" on‌click="handleAuthClick()" value="Authorize"> <input type="button" id="signout_button" on‌click="handleSignoutClick()" value="Sign Out"> </div> </div> <div id="content" class="success message"><?php if(isset($message)) { echo $message; } ?></div> </div> <script type="text/javascript" src="./js/gapi-upload.js"></script> <script async defer src="https://apis.google.com/js/api.js" on‌load="gapiLoaded()"></script> <script async defer src="https://accounts.google.com/gsi/client" on‌load="gisLoaded()"></script>
</body>
</html>

JavaScript to handle user authorization and file upload sequence


This JavaScript code initializes the gapi and gsi on a callback of loading these Google JavaScript libraries.

It also contains the handlers to trigger API requests for the following actions.

  1. Google authorization with identity proof.
  2. Upload files with the access token.
  3. Refresh gapi upload action once authorized.
  4. Signout.

This JavaScript code requires the authorization credentials to be configured. Set the CLIENT_ID and API_KEY in this script before running this example.

In this example, it sets the Google Drive folder id to upload the file via JavaScript. This configuration is optional. If no target is needed, remove the parameter from the file meta array.

js/gapi-upload.js

// TODO: Set the below credentials
const CLIENT_ID = 'SET-YOUR-CLIENT-ID';
const API_KEY = 'SET-YOUR-API-KEY'; // Discovery URL for APIs used by the quickstart
const DISCOVERY_DOC = 'https://www.googleapis.com/discovery/v1/apis/drive/v3/rest'; // Set API access scope before proceeding authorization request
const SCOPES = 'https://www.googleapis.com/auth/drive.file';
let tokenClient;
let gapiInited = false;
let gisInited = false; document.getElementById('authorize_button').style.visibility = 'hidden';
document.getElementById('signout_button').style.visibility = 'hidden'; /** * Callback after api.js is loaded. */
function gapiLoaded() { gapi.load('client', initializeGapiClient);
} /** * Callback after the API client is loaded. Loads the * discovery doc to initialize the API. */
async function initializeGapiClient() { await gapi.client.init({ apiKey: API_KEY, discoveryDocs: [DISCOVERY_DOC], }); gapiInited = true; maybeEnableButtons();
} /** * Callback after Google Identity Services are loaded. */
function gisLoaded() { tokenClient = google.accounts.oauth2.initTokenClient({ client_id: CLIENT_ID, scope: SCOPES, callback: '', // defined later }); gisInited = true; maybeEnableButtons();
} /** * Enables user interaction after all libraries are loaded. */
function maybeEnableButtons() { if (gapiInited && gisInited) { document.getElementById('authorize_button').style.visibility = 'visible'; }
} /** * Sign in the user upon button click. */
function handleAuthClick() { tokenClient.callback = async (resp) => { if (resp.error !== undefined) { throw (resp); } document.getElementById('signout_button').style.visibility = 'visible'; document.getElementById('authorize_button').value = 'Refresh'; await uploadFile(); }; if (gapi.client.getToken() === null) { // Prompt the user to select a Google Account and ask for consent to share their data // when establishing a new session. tokenClient.requestAccessToken({ prompt: 'consent' }); } else { // Skip display of account chooser and consent dialog for an existing session. tokenClient.requestAccessToken({ prompt: '' }); }
} /** * Sign out the user upon button click. */
function handleSignoutClick() { const token = gapi.client.getToken(); if (token !== null) { google.accounts.oauth2.revoke(token.access_token); gapi.client.setToken(''); document.getElementById('content').style.display = 'none'; document.getElementById('content').innerHTML = ''; document.getElementById('authorize_button').value = 'Authorize'; document.getElementById('signout_button').style.visibility = 'hidden'; }
} /** * Upload file to Google Drive. */
async function uploadFile() { var fileContent = 'Hello World'; // As a sample, upload a text file. var file = new Blob([fileContent], { type: 'text/plain' }); var metadata = { 'name': 'sample-file-via-js', // Filename at Google Drive 'mimeType': 'text/plain', // mimeType at Google Drive // TODO [Optional]: Set the below credentials // Note: remove this parameter, if no target is needed 'parents': ['SET-GOOGLE-DRIVE-FOLDER-ID'], // Folder ID at Google Drive which is optional }; var accessToken = gapi.auth.getToken().access_token; // Here gapi is used for retrieving the access token. var form = new FormData(); form.append('metadata', new Blob([JSON.stringify(metadata)], { type: 'application/json' })); form.append('file', file); var xhr = new XMLHttpRequest(); xhr.open('post', 'https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart&fields=id'); xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken); xhr.responseType = 'json'; xhr.onload = () => { document.getElementById('content').innerHTML = "File uploaded successfully. The Google Drive file id is <b>" + xhr.response.id + "</b>"; document.getElementById('content').style.display = 'block'; }; xhr.send(form);
}

Google Drive JavaScript Upload Response


Once authorized, the JavaScript calls the uploadFile() function to hit the Google Drive V3 API to post the file binary.

The below screenshot shows the uploaded Google Drive file id in the success message.

After sign-in, the landing page UI will display the signout option. It also shows a Refresh button to trigger upload action again in case of any issues on uploading.

file upload ack with google drive file id
Download

↑ Back to Top



https://www.sickgaming.net/blog/2022/08/...avascript/

Print this item

  (Indie Deal) PMCW Intelligence Document No. 010178. Codename: Vorax
Posted by: xSicKxBot - 08-17-2022, 01:53 PM - Forum: Deals or Specials - No Replies

PMCW Intelligence Document No. 010178. Codename: Vorax

PMCW Intelligence Document No. 010178.

Information in our possession is conflicting, but it seems that the infection has spread very quickly within a few days, perhaps even in a few hours.
It seems that in the hours immediately following the outbreak of the infection, 43rd NATO airborne battalion was sent to the island but all contacts were lost after only 8 hours.

PMCW considers this matter with the utmost importance.
Objectives of team W1 are:

  • Locate the biolab
  • Take in vitro samples of the pathogen (codename: "Vorax")
  • Liquidate surviving medical personnel (optionally) and any witnesses.
In NO case must the presence of the PMCW be revealed.

Every W1 squad member is equipped with cyanide capsules.
Squad commander is authorized to start liquidation procedure in case of emergency.

Proceed with the utmost caution.



THE ENVIRONMENT

The island is vast and offers a wide variety of natural resources. There are also several settlements, a main village, a hotel and tourist attractions.
In the event of an emergency landing, or loss of tactical equipment, each squad member is trained to survive in a hostile environment.
As a good mercenary of a private military company, you know how to use local plants and herbs to make ointments and medications to treat state effects such as burns, bleeding, relieve your stress or simply restore your health.
But more importantly, you can use building materials provided by nature to make rudimentary melee weapons, traps, barricades and much more. Even a silent bow, very useful for knocking out the infected without being detected.

THE INFECTION

It seems that the infected are the side effect of the virus grown in the bio-laboratory.
Probably when a security flaw opened, the virus spread to the island.

It is not yet clear whether it spreads by air or through aquifers but what is certain is that biomass, similar to fleshy appendages that are sometimes glimpsed in the environment, are one of the final stages of the virus.
The biomass therefore seems to be responsible for the mutations that occurred to the civilian inhabitants and to the military personnel who rushed to contain the first stages of the infection.
Contact with non-bottled liquids or non-canned food is therefore strictly prohibited.

Mutates are fast, extremely aggressive and above all voracious.
The first to be devoured were the breeding animals of the surrounding farms and estates.
For this reason, any living being, human or animal, is for them a prey.

Apparently they do not devour each other ( to be confirmed ).

Finally, it seems that they are photosensitive.
At least the infected humans.
Our drones have in fact observed the absence of external diurnal activity by the mutants, even if some animal species that have come into contact with the pathogen, such as stray dogs, wolves, wild boars and bears, do not seem to suffer from photosensitivity.

It is therefore recommended to exercise extreme caution at night.


OPERATIONAL INFO

You will land in the North area, a few hundred meters from the bio-laboratory, at 4.30 in the morning.
The helicopter will wait 25 minutes and then will take off.

https://store.steampowered.com/app/1874190/Vorax





https://steamcommunity.com/groups/indieg...4769029421

Print this item

  PC - Recipe for Disaster
Posted by: xSicKxBot - 08-17-2022, 01:53 PM - Forum: New Game Releases - No Replies

Recipe for Disaster



Recipe for Disaster is a restaurant management and social simulation game that puts you in the shoes of an inexperienced, but ambitious, head chef working towards fulfilling your lifelong dream of becoming an internationally renowned restaurateur. Along this journey you will be tasked with carefully designing restaurants, hiring and managing the right staff, customising food menus, and experimenting with ingredients to create tasty new dishes that will impress your customers. Sounds idyllic right?

Wrong.

Blazing a trail through the highly competitive, fast-paced and stress-inducing world of the food-service industry will be anything but straightforward. After all, this is an industry built around people, and keeping everyone happy, motivated, and fulfilled will require nothing short of a miracle!

Recipe for Disaster is a restaurant management sim with a devious social twist. Contend with wilful staff, questionable cooking skills, demanding customers, and unreliable suppliers as you embark on a culinary misadventure to become the ultimate head chef!

Publisher: Kasedo Games

Release Date: Aug 05, 2022




https://www.metacritic.com/game/pc/recipe-for-disaster

Print this item

  News - Call Of Duty: Modern Warfare 2 Beta Dates, Early Access, And Details
Posted by: xSicKxBot - 08-17-2022, 01:53 PM - Forum: Lounge - No Replies

Call Of Duty: Modern Warfare 2 Beta Dates, Early Access, And Details

Call of Duty: Modern Warfare 2 will launch on October 28, rebooting the title in 2022 and reuniting players with the series' iconic characters from Task Force 141. Here is everything you need to know in order to get hands-on with the game before launch.

Modern Warfare 2 MP beta platforms and dates

Activision has announced that Modern Warfare 2's multiplayer beta will be open to everyone, regardless of platform or whether you've preordered the game. However, PlayStation users will get first access to the beta, and those who preorder the game will get early access as well.

Continue Reading at GameSpot

https://www.gamespot.com/articles/call-o...01-10abi2f

Print this item

  [Tut] How Neural Networks Learn
Posted by: xSicKxBot - 08-16-2022, 04:55 PM - Forum: Python - No Replies

How Neural Networks Learn

5/5 – (1 vote)
YouTube Video

Artificial neural networks have become a powerful tool providing many benefits in our modern world. They are used to filter out spam, to perform voice recognition, and are even being developed to drive cars, among many other things.

As remarkable as these tools are, they are readily within the grasp of almost anyone. If you have technical interest and have some experience with computer programming you can build your own neural networks.

But before you learn the hands-on details of building neural networks you should learn some of the fundamentals of how they work. This article will cover one of those fundamentals – how neural networks learn.

Note: This article includes some algebra and calculus. If you’re not comfortable with algebra, you should still be able to understand the content from the graphs and descriptions. The calculus is not done in any detail. Again you should still be able to follow along from the descriptions. You will not learn the details of how the calculations are done. Instead, you will gain an intuitive understanding of what is going on.

Before learning this, you should be familiar with the basics of how neural networks are structured and how they operate. The article “The Magic of Neural Networks: History and Concepts” covers these basics. Still, we offer the following brief refresher.

Basic Fundamentals: How Neural Networks Work


Figure 1 shows an artificial neuron.

Figure 1: artificial neuron

Signals from other neurons come in through multiple inputs, each multiplied by its corresponding weight (Weights express the connection strengths between the neuron and each of its upstream neurons.).

A bias is input as well (bias expresses a neuron’s inherent activation, independent of its input from other neurons.). All these inputs add together, and the resulting total signal is then processed through the activation function (A sigmoid function is shown here.).

Figure 2: neural network classifying an image (Dog photo by Garfield Besa)

Figure 2 shows a network of these neurons. Signals are introduced on the input side, and they progress through the network, passing through neurons and along their connections, getting processed by the calculations described above. How the signals are processed, depends on the weights and biases among all the neurons.

? The key takeaway is that it is the settings of the weights and biases that establish how the network as a whole computes. In other words, the learning and memory of the network is encoded by the weights and biases.

So how does one program these weights and biases?

They are set by training the network with samples and letting it learn by example. The details of how that is done is the subject of this article.

Overview of How Neural Networks Learn


As mentioned, a neural network’s learning and memory is encoded by the connection weights and biases of the neurons throughout the network.

These weights and biases are set by training the network on examples by following this six-step training procedure:

  1. Provide a sample to the network.
  2. Since the network is untrained, it will probably get the wrong answer.
  3. Compute how far this answer is from the correct answer. This error is known as loss.
  4. Calculate what changes in the weights and biases will make the loss smaller.
  5. Make adjustments to those weights and biases as determined by those calculations.
  6. Repeat this again and again with numerous samples until the network learns to answer the samples correctly.

Presenting Samples and Calculating Loss


Let’s review some of this in more detail while considering a use case.

Imagine we want to train a network to estimate crowd size.

To do this we must first train the network with a large set of images of crowds. For each image the number of people are counted. We then include labels indicating correct crowd size for each picture. This is known as a training set.

The pictures are submitted to the network, which then indicates its crowd estimate for each picture. Since the network is not trained, it surely gets the estimate wrong for each image.

For each image/label pair, the network calculates the loss for that sample.

Multiple possible choices can be used for calculating loss. One can choose any calculation that appropriately expresses how far the network’s answer is from the correct answer.

An appropriate choice for crowd-size loss estimate is the square error:


where:


Suppose we submit an image showing a crowd size of 500 people. Figure 3 shows how the error varies for crowd estimates around the true crowd size of 500 people.

Figure 3

If the Network guesses 350 people the loss is 22500. If the network guesses 600 people the loss is 10000.

Clearly, the loss is minimized when the network guesses the correct crowd size of 500 people.

But recall we said it is the weights and biases in the network that encode its learning and memory, so it is the weights and biases that determine if the network gets the right answer. So we need to adjust the weights and biases so that the network gets closer to the correct answer for this image.

In other words, we need to change the weights and biases to minimize the loss. To do that, we need to figure out how the loss varies when we vary the weights and biases.

Minimizing Loss: Calculus and the Derivative


So how do we calculate how loss changes when we vary weights and biases?

This is where calculus comes in.

(Don’t worry if you don’t know calculus, we’ll show you everything you need to know, and we’ll keep it intuitive.)

Calculus is all about determining how one variable is affected by changes in another variable.

(Strictly speaking there’s more to calculus than that, but this idea is one of the core ideas of calculus.)

? The loss L depends on network output y, but y depends on input, and on weights w and biases b. So there is a somewhat long and complicated chain of dependencies we have to go through to figure out how L varies when w and b vary.

However, for the sake of learning, let’s instead start by just examing how L varies when y varies, since this is simpler and will help develop an intuition for calculus.

How L depends on y is somewhat easy – we saw the equation for it earlier, and we saw the graph of that equation in Figure 3. We can tell by looking at the graph that if the network guesses 350 then we need to increase the output y in order to reduce the loss, and that if the network guesses 600 then we need to decrease the output y in order to reduce the loss.

But with neural networks, we never have the luxury of being able to examine the graph of the loss to figure it out.

We can, however, use calculus to get our answer. To do this, we do what is called taking the derivative.

Here is the derivative of the equation for the graph in Figure 3 (note, we will not explain how this is calculated, that is the domain of a calculus course.):


This is typically referred to as “taking the derivative of L with respect to y”. You can read that dL/dy as saying “this is how L changes when y changes”. Now let’s calculate how L changes when y changes at the point y = 350:


So at y = 350, for every bit y increases, L decreases by 300. That implies that when we increase y the loss will decrease.

Now let’s calculate how L changes when y changes at the point y = 600:


So at y = 600, for every bit y increases, L increases by 200. Since we want to decrease L, that means we need to decrease y.

These calculations match what we concluded from looking at the graph.

You can also read dL/dy as saying “this is the slope of the graph”.

This makes sense: at point y = 350 the slope of the graph is -300 (sloping down steeply), while at point y = 600 the slope of the graph is 200 (sloping up, not quite so steeply).

So by using calculus and taking the derivative, we can figure out which way to change y to reduce the loss L, even when we can’t see the graph to figure it out.

Recall, however, that we want to figure out how to change the weights and biases to reduce the loss L. Also recall there is a chain of dependencies, of L depending on y, which itself depends on w and b (for several layers worth of w and b!), and on input.

So a full description could result in some rather complicated equations and some difficult derivatives. For those curious about the math details, the method for figuring out derivatives when there is such dependencies is called the chain rule.

Fortunately, with modern neural network software, the computer takes care of calculating derivatives and keeping track of and resolving the chains of dependencies in the derivatives. Just understand that, even if we can’t see its graph:

  • there is some relationship between the loss L and the weights w and biases b (a “graph”)
  • there is some set of weights and biases where the loss L is at a minimum for a given input
  • we can use calculus to figure out how to adjust the weights and biases to minimize loss

The Loss Surface and Gradient Descent


Let’s consider a very simple case where there are just two weights, w1 and w2, and no biases. The graph of L as a function of w1 and w2 might look like figure 4.

Figure 4: bowl-shaped error graph

In this example, with two independent weights, we end up with a bowl-shaped surface for the loss graph. In this case, the loss is minimized when w1 = 4 and w2 = 3. In the beginning, when the network is not yet trained the weights (initially set to small random numbers) are almost certainly not at the correct values for the loss to be at a minimum.

We still figure out which direction to change the weights to reduce the loss by taking the derivative.

Only this time, since there are two independent variables, we take the derivative with respect to each independently.

? Important: The result is, for any given point on the loss surface, a direction (a vector, or an arrow) pointing in which direction the loss increases the fastest (“uphill”). This is known as the gradient (instead of derivative). Since we want to reduce loss, we move in the opposite direction, the negative of the gradient.

The larger point is we are still using calculus to figure out which direction to change weights to reduce loss. Repeatedly doing this moves the weights closer to the values which make the network give the correct answer for a given input. This is known as gradient descent.

However, most neural networks have many more than two weights, typically dozens for any given layer.

But the same ideas still apply: if we have a layer consisting of 16 weighted connections, the loss is a 16-dimensional surface! You can’t visualize it but it still exists mathematically, and the same principles apply!

You can still calculate the gradient, that is the derivative with respect to all 16 w’s, and figure out which direction to change the w’s to minimize the loss.

So how much do we adjust the weights and biases?

Typically they are adjusted just a small amount. This is because large adjustments can cause problems.

Refer to the loss surface shown in Figure 4. If too large a step is made, you could jump right across the loss surface bowl, even going so far as to make the loss worse!

? The adjustment step size is known as the learning rate. Figuring out the best learning rate is one of the tricks to optimizing your network that a neural network engineer has to work out.

Backpropagation


Ultimately all of the weights and biases throughout the network have to be adjusted to minimize loss. This is done back from the loss, working back layer by layer to the beginning of the network, a process called backpropagation.

It has to be done this way because you can’t figure out how the first layer’s weights and biases affect loss until you know how the second layer’s weights and biases affect loss; you can’t tell how the second layer’s weights and biases effect loss until you know how the third layer’s weights and biases effect loss, and so on.

So calculations and adjustments are done starting with the last layer, then working back to the second to the last layer, and so on back to the first layer.

So that’s the core algorithm of training a neural network:

  1. Present example image.
  2. Calculate the loss.
  3. Adjust the network weights and biases through backpropagation, calculating gradient descent, and making adjustments layer by layer.

Batch Size


However, recall that the objective of the training is to adjust the weights and biases for all of the images, not just one.

So how does one train the network, one image at a time, or using the entire set of all training images? Either choice is a possibility.

? Ultimately the loss we want to minimize is the loss for the entire set of training samples, so a natural choice might be to run all samples through the network before making adjustments to the weights and biases. This is known as batch processing.

However performing so many calculations before making adjustments can be very demanding on computer resources and can slow the training process down.

? How about adjusting weights and biases for each individual training sample? Optimum weights and biases will be different for each training sample, and this variation can introduce large randomness into the gradient descent. This is known as stochastic gradient descent.

To better understand the importance of this refer to the hypothetical loss curve in figure 5:

Figure 5: local and global minimum

Notice that there is more than one minimum: there is a local minimum at point B, which is not quite the lowest loss, and a global minimum at point A that is truly the minimum where the loss is lowest.

It is truly possible (even likely) to get loss curves like this, with multiple local minima, and it’s also possible for the network to get stuck in one of these local minima.

The randomness of single sample training can help knock the network out of a local minimum if it gets stuck in one, so there is some benefit to stochastic gradient descent.

However, the randomness can be so extreme that it can actually knock the network out of the true global minimum if it happens to reach it before a training cycle ends. This can slow the training as the network has to work back down to minimize the loss again.

So in practice, it turns out the best approach is to use minibatches. These are batch sizes of perhaps a few hundred samples that are run through the network, and then adjustments are made.

The network runs through mini batch after many batch until the entire set of training samples has been processed. This has enough randomness to it that it has the same benefit as stochastic gradient descent of pushing the network out of local minima, but not so much randomness that the loss can get worse.

Running through the entire set of training samples once is called an epoch.

Typically networks must run through many epochs to become fully trained. Also the ordering and grouping of training samples within and between batches is randomized from epoch to epoch. This is to avoid overfitting.

? Overfitting is when the network performs successfully on the training samples, but fails on samples it has not seen before. This is like a person memorizing a set of samples, rather than generalizing characteritics from those samples so that it can be successful on new samples.

After training the network is then tested on a test set. This is a set of samples the network has not seen before. This allows one to assess how well the trained network performs. It checks to see how effective the network is on unknown samples, and checks to make sure overfitting has not occurred.

How Neural Networks Learn


So that is the full process of how neural networks learn:

  1. Train the network by presenting it minibatches of samples from the training set.
  2. The training algorithm calculates the loss for the minibatch.
  3. The algorithm calculates the gradient of the loss.
  4. The network adjusts weights and biases according to the gradient calculations, through the process of backpropagation and gradient descent.
  5. Running this sequence through all training samples is called an epoch.
  6. This is then repeated for multiple epochs, until the network is successfully trained on the training set.
  7. Finally the network is tested on a test set to make sure it works successfully and does not suffer from overfitting.

We hope you have found this lesson on how neural networks learn informative.

We wish you happy coding!



https://www.sickgaming.net/blog/2022/08/...rks-learn/

Print this item

  [Tut] Disable mouse right click, cut, copy, paste with JavaScript or jQuery
Posted by: xSicKxBot - 08-16-2022, 04:55 PM - Forum: PHP Development - No Replies

Disable mouse right click, cut, copy, paste with JavaScript or jQuery

by Vincy. Last modified on August 14th, 2022.

Before learning how to disable the cut, copy, paste and right-click event in JavaScript we should know first Why.

Why we need this is, for copying and manipulating content displayed on the client. It lets the user struggle to do the following for example.

  1. Take the copyrighted site content by copy and paste.
  2. Save media files by right-clicking and saving assets.

We implement this disabling by using the below steps. The first two of them are mandatory and the 3rd one is optional.

  1. Listen to the event type cut, copy, paste and right-click.
  2. Prevent the default behavior with the reference of the event object.
  3. Acknowledge users by showing alert messages [optional step].

View Demo

disable cut copy paste right click

Example 1 – Disabling cut, copy, paste and mouse right-click events


This JavaScript disables the cut, copy, paste and right-click on a textarea content.

It defines a callback invoked on document ready event. It uses jQuery.

In this callback, it listens to the cut, copy, paste and the mouse right-click action requests.

When these requests are raised this script prevents the default behavior. Hence, it stops the expected action based on the cut, copy, and other requests mentioned above.

$(document).ready(function() { $('textarea').on("cut", function(e) { e.preventDefault(); alertUser('Cut'); }); $('textarea').on("copy", function(e) { e.preventDefault(); alertUser('Copy'); }); $('textarea').on("paste", function(e) { e.preventDefault(); alertUser('Paste'); }); $("textarea").on("contextmenu", function(e) { e.preventDefault(); alertUser('Mouse right click'); });
}); function alertUser(message) { $("#phppot-message").text(message + ' is disabled.'); $("#phppot-message").show();
}

HTML with Textarea and alert box


This HTML has the textarea. The JavaScript targets this textarea content to disable the cut, copy and more events.

Once disabled the default behavior, the UI should notify the user by displaying a message.

So, it contains an HTML alert box to show a red ribbon with a related error message to let the user understand.

It includes the jQuery library with a CDN URL. Insert the above script next to the jQuery include then run the example.

The downloadable at the end of this article contains the complete working example.

<!DOCTYPE html>
<html>
<head>
<title>Disable mouse right click, cut, copy, paste with JavaScript or jQuery</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" type="text/css" href="css/style.css" />
<link rel="stylesheet" type="text/css" href="css/form.css" />
<style>
#phppot-message { display: none;
}
</style>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script> </head> <body> <div class="phppot-container"> <h2>Disable mouse right click, cut, copy, paste</h2> <textarea name="notes" class="full-width" rows="5"></textarea> <div id="phppot-message" class="error"></div> </div>
</body>
</html>

Example 2 – Thin version using jQuery


This example is a thin version of the above. It also uses the jQuery library to disable the cut, copy paste and right-click events.

This binds all the events to be disabled. It has a single-line code instead of creating exclusive listeners for each event.

This method has a slight disadvantage. That is, it shows a generic message while stopping any one of the cut, copy, paste and right-click events.

In the first method, the acknowledgment message is too specific. That message gives more clarity on what is triggered and what is disabled and prevented.

But, the advantage of the below example is that it is too thin to have it as a client-side feature in our application.

$(document).ready(function() { $('textarea').bind('cut copy paste contextmenu', function(e) { e.preventDefault(); $("#phppot-message").text('The Cut copy paste and the mouse right-click are disabled.'); $("#phppot-message").show(); });
});

Example 3 – For JavaScript lovers


Do you want a pure JavaScript solution for this example? The below script achieves this to disable cut, copy, paste and right-click.

It has no jQuery or any other client-side framework or libraries. I believe that the frameworks are for achieving a volume of effects, utils and more.

If the application is going to have thin requirements, then no need for any framework.

HTML with onCut, onCopy, onPaste and onContextMenu attributes


The Textarea field in the below HTML has the following callback attributes.

  • onCut
  • OnCopy
  • onPaste
  • onContextMenu

In these event occurrences, it calls the disableAction(). It sends the event object and a string to specify the event occurred.

<textarea name="notes" class="full-width" rows="5" on‌Cut="disableAction(event, 'Cut');" on‌Copy="disableAction(event, 'Copy');" on‌paste="disableAction(event, 'Paste');" on‌contextmenu="disableAction(event, 'Right click');"></textarea>
<div id="phppot-message" class="error"></div>

JavaScript function called on cut, copy, paste and on right click


In the JavaScript code, it reads the event type and disables it.

The event.preventDefault() is the common step in all the examples to disable the cut, copy, paste and right click.

function disableAction(event, action) { event.preventDefault(); document.getElementById("phppot-message").innerText = action + ' is disabled.'; document.getElementById("phppot-message").style.display = 'block';
}

Disclaimer


The keyboard or mouse event callbacks like onMouseDown() or onKeyDown lags in performance. Also, it has its disadvantages. Some of them are listed below.

  1. The keys can be configured and customized. So, event handling with respect to the keycode is not dependable.
  2. On clicking the mouse right, it displays the menu before the onMouseDown() gets and checks the key code. So, disabling mouse-right-click is failed by using onMouseDown() callback.
  3. Above all, an user can easily disable JavaScript in his browser and use the website.

View DemoDownload

↑ Back to Top



https://www.sickgaming.net/blog/2022/08/...or-jquery/

Print this item

 
Latest Threads
Temu Polska Kod Rabatowy ...
Last Post: demble8888
1 minute ago
Aktywny Kod Temu [ald9115...
Last Post: demble8888
2 minutes ago
50% Discount Temu Coupon ...
Last Post: anniket986
1 hour ago
40% Off Temu Coupon Code ...
Last Post: anniket986
1 hour ago
["UniQue"]"$40 off"Temu C...
Last Post: anniket986
1 hour ago
Temu Black Friday Sale [a...
Last Post: anniket986
1 hour ago
$$»New $100 Off TEMU coup...
Last Post: anniket986
1 hour ago
NEW Coupon Code $100 Off ...
Last Post: anniket986
1 hour ago
["Limited"] {{$100 off}}T...
Last Post: anniket986
2 hours ago
Black Ops (BO1, T5) DLC's...
Last Post: SeX
2 hours ago

Forum software by © MyBB Theme © iAndrew 2016