text:
Q: My login page is not work The select query does not want to work. It goes directly to the login failed although I have enter the correct password.
I tried from another database and it works but from this table it does not want to work.
Another thing is whenever I start XAMPP it shows key _ buffer.
Is that what prevents my query from working?
Below is my code. Hoping from some help from you developers.
<?php
session_start();
$_SESSION['message']='';
$mysqli=new MySQLi('127.0.0.1','root','','learning_malaysia');

if(isset($_POST['login'])) {
    $username = $mysqli->real_escape_string($_POST['username']);
    $password = md5($_POST['password']);
    $sql="SELECT * FROM tutor_register WHERE username='$username' AND password='$password' LIMIT 1;";
    $result = mysqli_query($mysqli,$sql);

    if(mysqli_num_rows($result) > 0){
        $row = mysqli_fetch_array($result);
        if (($row['username']=='sithi') && ($row['password']=='202cb962ac59075b964b07152d234b70')){
            $_SESSION['user_type'] = $row;
            $_SESSION['password'] = $row;
            $_SESSION['message'] =  "Registration successful!";
            header("location:myresuming.html");
            exit();

        } else {
            $_SESSION['username'] = $row['username'];
            $_SESSION['profile'] = $row['profile'];
            $_SESSION['message'] =  "Registration successful!";
            header("location:Welcome.php");
            exit();
        }

    } else {
        $_SESSION['message'] = "Login Failed!";
    }
}

?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>form in Design</title>
<link rel="stylesheet" type="text/css" href="mystyle.css" />
<link rel="stylesheet" type="text/css" href="form.css" />

<?=$_SESSION['message']?>

<form class="form" action="" method="post" enctype="multipart/form-data" autocomplete="off">

      <input type="text" placeholder="User Name" name="username" required />
      <input type="password" placeholder="Password" name="password" autocomplete="new-password" required />
 <input type="submit" name="login" value="login" class="btn-login" />

</form>

A: <?php
session_start();
$_SESSION['message']='';
$mysqli=new MySQLi('127.0.0.1','root','','learning_malaysia');

if(isset($_POST['login'])) {
    $username = $mysqli->real_escape_string($_POST['username']);
    $password = md5($_POST['password']);
    $sql="SELECT * FROM tutor_register WHERE username='$username' AND password='$password' LIMIT 1;";
    $result = mysqli_query($mysqli,$sql);

    if(mysqli_num_rows($result) > 0){
        $row = mysqli_fetch_array($result);
        if (($row['username']=='sithi') && ($row['password']=='202cb962ac59075b964b07152d234b70')){
            $_SESSION['user_type'] = $row['user_type'];
            $_SESSION['password'] = $row['password'];
            $_SESSION['message'] =  "Registration successful!";
            header("location:myresuming.html");
            exit();

        } else {
            $_SESSION['username'] = $row['username'];
            $_SESSION['profile'] = $row['profile'];
            $_SESSION['message'] =  "Registration successful!";
            header("location:Welcome.php");
            exit();
        }

    } else {
        $_SESSION['message'] = "Login Failed!";
    }
}
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>form in Design</title>
<link rel="stylesheet" type="text/css" href="mystyle.css" />
<link rel="stylesheet" type="text/css" href="form.css" />

<?php echo $_SESSION['message']; ?>

<form class="form" action="" method="post" enctype="multipart/form-data" autocomplete="off">

      <input type="text" placeholder="User Name" name="username" required />
      <input type="password" placeholder="Password" name="password" autocomplete="new-password" required />
 <input type="submit" name="login" value="login" class="btn-login" />

</form>

try this.


text:
Q: Charting controls unavailable? I am just getting started on chart controls and started with this technet article.
http://msdn.microsoft.com/en-us/library/dd489237.aspx
Unfortunately, in spite of having chosen the required namespaces the chart control does not show up in the toolbox under data.
Am I missing something?

A: Still using webforms are we? You could just save yourself a lot of hassle and just use a javascript solution like this, your server will definately love you for it.
http://www.highcharts.com/
I've had a lot of good luck with this solution, it does mean uderstanding javascript but its not rocket science.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Slow down mp3 audio I love VLC's option of slowing down audio playback.
Now I want to take my mp3-files to a portable player and play them there. Unfortunately the player does not have a slow down option.
How can I convert mp3s so they sound like being played slowly using VLC?
I will prefer a command line tool, but will accept other free software tools for GNU/Linux.

A: I recommend using SoX like this:
sox <input> <output> tempo 0.5

This slows down <input>'s tempo by a factor of 2 and record the result to <output>.
You can add option --show-progress to display relevant information and progression percentage.
Note that if <input> is for instance normal.wav and <output> is half-tempo.ogg, SoX will detect the different audio encoding by itself (for more control on that part, read man sox).
The tempo algorithm should give similar results to VLC's scaletempo module. However you can try the alternative stretch algorithm:
sox <input> <output> stretch 2

The result is expected to be more synthetic (again, read man sox for details) and be aware that the parameter is the inverse of the one given to tempo (2 instead of 0.5 in this example).
SoX offers even more possibilities of time manipulation through speed, pitch and bend options that can be easily explored.
To install SoX using apt-get:
sudo apt-get install sox

To enable extra codecs (including MP3), add this library:
sudo apt-get install libsox-fmt-all

As a final note, I would come back to VLC since you can play your file slowed down from command line this way:
cvlc --rate 0.5 <input>

So there may be a way to ask VLC to save the result to some file, or to output audio to JACK and then use a JACK compatible recorder.

A: The following script does this using ffmpeg.
#!/bin/sh

# Usage:
#   slow_down.sh infile.mp3 outfile.mp3 0.75
#   Can't slow down more than by a factor of 0.5 (limitation of ffmpeg).

if [ $# -lt 3 ]; then
  echo 1>&2 "$0: not enough arguments"
  exit 2
fi

rm -f $2 temp.mp4
ffmpeg -i $1 -filter_complex "[0:a]atempo=$3[a]" -map "[a]"  -c:a aac temp.mp4
ffmpeg -i temp.mp4 -ar 48000 $2
rm -f temp.mp4

This could probably be simplified, but I wasn't able to figure out how to combine the two ffmpeg commands into one.
I found that the output of this method sounded much, much better than the results from the two algorithms provided by sox. To me it sounds about as good as the results of slowing down audio in the youtube interface.


text:
Q: Octave - Accessing Values in octave_value_list I am working within a C++ development environment while using the Octave C++ API.
I would like to know how to access single values in a returned octave_value_list when calling functions.
For example when I am calling the clock-function im getting returned an octave_value_list which shows the following:

2014.0000 8.0000 22.0000 10.0000 1.0000 44.7120

I now would like to access each single value but Im somehow only able to get the year.
I am missing some syntax, maybe someone can help me.

A: Useful documentation to answer your question:

*

*doxygen for octave_value_list

*doxygen for octave_value

The values you mention are a multiple octave_values in an octave_value_list, or is it a an array of values in a single octave_value  in an octave_value_list?
Note that a single octave_value is not necessarily a scalar value. It can be a an array with n dimensions, and multiple  elements. It can be a struct, a struct array, or a cell array. It basically can be anything that an octave variable can be. For example, the call:
foo ([1 2 3], "string", {678, "other string"}, struct ("over", 9000))

will create an octave_value_list with 4 octave_values and:
foo ([1 2 3])

will still create an octave_value_list but with a single octave_value.
The first thing you need is to figure out what you actually have. You can use octave_value_list.length() to get an idea and you can get individual octave_values by simply indexing them with round brackets ().
for (int i =0; i < list.length (); i++)
    do_stuff_with (list(i));

Once you get an octave_value you can try to convert into many things.
std::string   s  = val.string_value ();
bool          b  = val.bool_value ();
boolMatrix    bm = val.bool_matrix_value ();
Cell          c  = val.cell_value ();
NDarray       nd = val.array_value ();
int           i  = val.int_value ();
Array<double> ad = val.vector_value ();

While you can use one of the is_x() methods of octave_value, the recommendation is to check the value of error_state after a conversion to check if anything went wrong. This will give a more natural Octave experience and will handle conversion between different types that you'd expect in Octave for you.


text:
Q: Error [ERR_HTTP_HEADERS_SENT] while looping through request I'm building a web scraping api for getting back all the working links from a page. I'm keep getting 'Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client' when i try to use res.send - for sending the results - which are a simple text of all the working links...i guess i'm doing something wrong with the way res.send is working....
    var express = require('express');
    var app = express();
    var request = require('request');
    var cheerio = require('cheerio');
    var url = 'https://www.pardes-hanna-karkur.muni.il/';

    app.get('/webscrape', function (req, res,next) {

    request(url, function(error, response, body){

      if(!error && response.statusCode == 200){
            $ = cheerio.load(body);
          links = $('a'); //jquery get all hyperlinks
      $(links).each(function(i, link){
        var linkRecieved = $(link).attr('href');
        if (linkRecieved.indexOf('www') > -1){
          var outStr='';
          request(linkRecieved, function(error, response, body){
            if(!error && response.statusCode == 200){
              res.send(linkRecieved);
              next();

            } else {
              res.send('false');
              next();
            }
          });

        }

      });

      }

    });

    })

    var server = app.listen(8081, function () {
      var host = server.address().address
      var port = server.address().port

      console.log( port)
    })

A: This is happening because you only can send response once for a request, on your code it'll try to send response everytime loop execute without an error, try sending response from outside loop


text:
Q: How would I turn this into a prepared statement? I'm new to prepared statements so I apologise in advance if this is a basic question but how would I turn the following code into a prepared statement and execute it later on?
<?php

$myQuery = "SELECT * FROM test WHERE ID=" . $_GET['ID'];

//run query
$result = $con->query($myQuery);
if (!$result) die('Query error: ' . mysqli_error($con));
?>

A: Take a look to http://www.w3schools.com/php/php_mysql_prepared_statements.asp, http://php.net/manual/en/mysqli.quickstart.prepared-statements.php (mysqli lib), or http://php.net/manual/en/pdo.prepared-statements.php (PDO lib).
Ex:
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Prepare statement
$stmt = $conn->prepare("SELECT * FROM test WHERE ID=?");

// set parameters
$stmt->bind_param("i", $_GET['ID']);

// execute
$stmt->execute();

// close resources
$stmt->close();
$conn->close();

A: To do the call you could use somethign like;
$sCompanyCode = 'fkjahj12321';
$con = new PDO("connection string");

$sql = "SELECT CompanyID From Companies WHERE CompanyCode = :CompanyCode";
$st = $con->query( $sql );
$st->bindValue(":CompanyCode", $sCompanyCode, PDO::PARAM_STR);
$st->execute();

To retrieve 1st or singular result;
if($row = $st->fetch()){
    return (int)$row[0];
}

For multiple results;
$aResults = array();
while ($row = $st->fetch()){
    $aResults[] = $row;
}


text:
Q: Automated export of SQL Server data I want to export large amounts of data, out of a SQL Server 2008 Enterprise, to a flat file. Then delete that data.  Naturally the delete must only happen if the export succeeds, so this must be synchronous.
Ideally this would be parametrized for date ranges. The filename also needs to change to reflect the exported data (i.e. exported_data_20110401_20110501.tsv, or similar)
I want this to be automated so that it can happen periodically.
What's the best workflow/tools to make this happen these days? The SSIS functionality seems a bit deprecated in SQL Server 2008?
Thanks.

A: SSIS is definitely the best tool for this job. I'm curious as to why you think it is deprecated in SQL Server 2008, because as far as I know it's the best and most widely available option for ETL in the SQL Server ecosystem.

A: SQL Server Integration Services (SSIS) is definitely not deprecated in SQL Server 2008.
You could use a dataflow task in SSIS to export the data to a flat file (which has the filename defined with an variable), and then have an executable task to DELETE, TRUNCATE or SWITCH OUT (if you're using partitions) the exported data.
You could also have a batch (.bat) file with analogous functions, using bcp to export the data and then running the appropriate SQL commands in the database using osql, for example.
bcp {params} && osql {params}

A: If SSIS is not an option, I would create a SQL Agent job, something like this

*

*Step 1. BCP flat files, on success goto step 2 else step 3

*Step 2. DELETE data from table, end

*Step 3. Error log

After that, you can schedule it run every night.

A: Have a look at this link:
http://www.wiseowl.co.uk/blog/s231/schedule_data_import_in_sql_server_pt1.htm
It does not tell you how to delete the data as you asked, but for anyone stumbling across this question in search of automated import or export of data from sql server to e.g. access, this link is an excellent start. It shows how to create an import/ export package, and more importantly, further posts also how to schedule it for routine excecution.


text:
Q: Organise my mutual recursive types Is it possible to have mutual recursive types ([<Struct>]) spread across different files? The types are directly under a namespace.
My solution is to put them in one big file and use type ... and ...  and ... etc construction. Is it the only way?

A: You can use a technique called untying the recursive knot where you parameterize one over the other.
So this:
type a = B of b
and b = A of a

becomes:
type 'b a = B of 'b
type b = A of b a


text:
Q: Accessing IP cameras with OpenCV First of all you have to understand a bit about my background. I have never worked with IP cameras before, but I will have to access multiple IP cameras simultaneously with OpenCV very soon. Apart from that, my network knowledge is not that much good.
Now the question. I know OpenCV can access IP cameras using its URL with the help of VideoCapture. There are number of questions in StackOverflow as well. But, the IP address is something that can be changed by time to time, it is dynamic. So even in a IP cam, the IP will change by time to time. So if this is the case, does this mean every time you try to access the cameras with OpenCV, you have to find the IP address of the camera manually and change the URL in OpenCV as well? I do not need to access the cameras via the internet, accessing locally is fine, via Wifi or network cables. How can I set a fixed IP address/ URL so the OpenCV code has nothing to change every time?
PS: I navigated through lot of websites (sites from more than 5 result pages of Google search) but the answers given are either too old or not that much convincing. So I decided to walk into StackOverflow for the answer.

A: If you can use local network, then Yes, you should use fixed IP address....if the Camera SDK is compatiable with OpenCV this you dont have have to worry about this and you can call VideoCapture directly. Or, you could use the camera SDK to get frames directly and then copy these frames to opencv image format and use opencv. This should not be too complicated.

A: If your router has a DHCP reservation feature, simply tell the router to always give an IP camera a certain IP.
Thus when the camera polls the DHCP server when it connects to the network, it will automatically receive its reserved IP. Other clients without a reservation will simply receive a random IP like normal. You might even think about doing this for all your computers and devices; it's quick and easy.


text:
Q: iPhone core data preset What is the best way to initialize Core Data database with content. My iPhone app will have a static database with products (data and images). How/where to store images, how to pre-populate database?

A: Here is what I did:

*

*Create the database inside the iPhone app

*I created the model in XCode and do a query against the database (this creates the database)

*My static data is a CSV file

*Use a Ruby script to read the CSV file

*Use the ruby gem sqlite3 to insert data into the database

*Copy back into project

Alternative:

*

*Store the CSV/XML file containing data inside the app

*Parse it on startup and create your NSMAnagedObjects

Tools/Resources:

*

*Base software for editing/viewing a sqlite3 database

Database Location:
I'm afraid I don't remember it on the top of my head but when you use the simulator your application will be built and copied into a directory. I think the path to your application will be something like this. The database depending on how it is setup is usually in the Documents folder.
~User/Library/Application Settings/iOS Simulator/<version>/<app id>/

A: Reference the official Apple docs provide a way to prepopulate data into Core Data:
Core Data Books
Within my own application, I replaced the function 'NSPersistentStoreCoordinator' within AppDeledate with this one :
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator{
if (_persistentStoreCoordinator != nil) {
    return _persistentStoreCoordinator;
}

NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"CoreDataBooks.CDBStore"];

/*
 Set up the store.
 For the sake of illustration, provide a pre-populated default store.
 */
NSFileManager *fileManager = [NSFileManager defaultManager];
// If the expected store doesn't exist, copy the default store.
if (![fileManager fileExistsAtPath:[storeURL path]]) {
    NSURL *defaultStoreURL = [[NSBundle mainBundle] URLForResource:@"CoreDataBooks" withExtension:@"CDBStore"];
    if (defaultStoreURL) {
        [fileManager copyItemAtURL:defaultStoreURL toURL:storeURL error:NULL];
    }
}

NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption, [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel: [self managedObjectModel]];

NSError *error;
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error]) {
    /*
     Replace this implementation with code to handle the error appropriately.

     abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.

     Typical reasons for an error here include:
     * The persistent store is not accessible;
     * The schema for the persistent store is incompatible with current managed object model.
     Check the error message to determine what the actual problem was.

     If the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application's resources directory instead of a writeable directory.

     If you encounter schema incompatibility errors during development, you can reduce their frequency by:
     * Simply deleting the existing store:
     [[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil]

     * Performing automatic lightweight migration by passing the following dictionary as the options parameter:
     @{NSMigratePersistentStoresAutomaticallyOption:@YES, NSInferMappingModelAutomaticallyOption:@YES}

     Lightweight migration will only work for a limited set of schema changes; consult "Core Data Model Versioning and Data Migration Programming Guide" for details.

     */
    NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
    abort();
}

return _persistentStoreCoordinator;

}
Hope this works, good luck!


text:
Q: How to use dx list in DevExtreme How to write correctly using dx-list?
I have an array
fields: Array<{field: string, direction: boolean}>

I'm writing like this
dx-list([items]="fields",
        selectionMode="single")

At the output I get a sheet, but I can not get the name

A: You can see a complete sample here
<dx-list
        #list
        [dataSource]="products">
            <div *dxTemplate="let data of 'item'">
                <div>{{data.field}}</div>
            </div>
    </dx-list>


text:
Q: Constantly Moving A Button Back And Forth In Vanilla JS The goal is to move a button from one div to another on click and then back to the other if clicked again and continue to do so each time it is clicked.
My problem is that the code I shared only runs once; what I need is for this behavior to run continuously.
const ham = document.getElementById('ham');
const mh = document.querySelector('.mobile-header');
const hc = document.querySelector('.header .content');

ham.addEventListener('click', function() {
    document.body.classList.toggle('nav-is-toggled');
    mh.insertAdjacentElement('afterbegin', ham);

    ham.addEventListener('click', function() {
        hc.insertAdjacentElement('afterbegin', ham);
    });
});

     X

A: You are adding a class to body, but there is no if-statement. See this example:

const ham = document.getElementById('ham');
const mh = document.querySelector('.mobile-header');

ham.addEventListener('click', function() {
  document.body.classList.toggle('nav-is-toggled');
  if (document.body.classList.contains('nav-is-toggled')) {
    mh.insertAdjacentElement('afterbegin', ham);
  } else {
    mh.insertAdjacentElement('afterend', ham);
  }
});

mobile-header

ham

A: The simpliest way :

const
  ham = document.getElementById('ham')
, mh  = document.querySelector('.mobile-header')
, hc  = document.querySelector('.header.content')
  ;
ham.onclick = () =>
  {
  let DomObj = document.body.classList.toggle('nav-is-toggled') ? mh : hc
  DomObj.insertAdjacentElement('afterbegin', ham)
  }
header, nav {
  height     : 3em;
  background : lightsteelblue;
  margin     : 1em;
  }

      XxxxxxxxxX

A: You can use two divs, and add js.
make two buttons, one in each div.
div2.style.display = block
let button1 = //select the button inside the 1st div
let div1 = //select the 1st div
let button2 = //…
let div2 = /…
button1.addEventListener(`click`, function(){div1.style.display = `none`
div2.style.display = block
})

button2.addEventListener(`click`, function(){div2.style.display = `none`
div1.style.display = block
})


text:
Q: Who is depicted in the statues on the Grandmaster's Palace in Thor: Ragnarok? In shots of the Grandmaster's Palace, you can see the heads of various Gladiator Champions carved on the side.  The Hulk is clearly being constructed on the top.  One of them (I'm fairly certain) was Beta Ray Bill.  Another may have been the Bi-Beast (hat tip to a commentor on io9).
Any idea who else was on there?  I seem to recall that there were five heads: Hulk, plus four completed ones.

A: Given this imperfect still, I might surmise the Man-Thing, Ares (the God of War), Beta Ray Bill and The Bi-Beast have all been champions at one point or another in the Grandmaster's games.

Each of these beings is highly formidable and given their capabilities would have made fine champions for the Grandmasters gladiatorial games.

Man-Thing: A creature formed of muck and science, the Man-Thing has two properties which would make it a fine gladiator.

*

*The first is that it's crazy durable. As long as you can keep it supplied with swamp and muck, it is effectively immortal and indestructible. It has increased its strength under certain circumstances allowing it to be as strong as the Hulk.

*Against people using conventional bashing weapons, they would eventually tire, or even possibly become afraid. Which is where its second power comes in: Who ever knows fear, burns at the Man-Thing's touch. The creature is sensitive to emotional states and if a creature becomes afraid of it, the Man-Thing will secrete sulfuric acid causing nasty caustic burns where ever the Man-Thing is touching it.

The Bi-Beast: A creature of fantastic strength and savagery, the Bi-Beast has strength and durability rivaling the Hulk's.

*

*Created as a creature purely designed to fight the Hulk and win, the Bi-Beast has changed in appearance and power levels over the years. He first appeared in The Incredible Hulk #169 (1973).
He probably made the Grandmaster a lot of money during his time as a gladiator due to his incredible strength and durability. His one weakness was his psychological instability.

Ares - God of War: The son of Zeus and Hera, Ares was worshiped as the god of war in ancient Greece and Rome. While physically not quite as powerful as the Bi-Beast or the Hulk, what Ares lacked in superhuman strength compared to both of those titans, he made up for in his sheer versatility, skill and capacity for violence.

*

*Ares was the god of brutal warfare and being trapped in an arena where most of the fighters were bigger and stronger but likely lacking the training his thousands of years of fighting had given him, would make him a long-running champion.

*How Ares might have come to be under the control of the Grandmaster is anyone's guess, since the Grandmaster was thought to have never been to Earth, Ares may have been a museum piece of the Collector and traded to the Grandmaster in the past.

*However he may have arrived here, his expertise in killing would have made him a crowd favorite until he made his escape. Being a god would give him a great degree of patience and he would have likely only spent a few years before escaping.

Beta Ray Bill: The cybernetic champion of the Korbinites, a species all but destroyed by the actions of the fire-demon Surtur, Bill protected the last of his species from destruction with the aid of his AI warship, Skuttlebutt.

*

*In the comics, even before his transformation into Beta Ray Thor, Bill had proven he had the fighting capacity to best Thor in a hand to hand struggle. He was also worthy of wielding Mjolnir which made his relationship with the Thunder God even more challenging.

*With his cybernetic reconstruction, Beta Ray Bill would have been a terror to face in the Grandmaster's games and would have likely remained a noted champion until he and Skuttlebutt figured out a way to escape. Bill's dedication to his people would not have allowed him to remain away from them for too long. Beta Ray Bill was created by Walt Simonson and first appeared in Thor #337 (1983).
In the comics, Odin was so impressed with Beta Ray Bill and his quest, he gave him his own hammer and enchanted it with capacities for energy manipulation similar to Mjolnir.

*Stormbreaker was a warhammer enchanted with powers similar to Mjolnir's. Bill can use it to fly, manipulate weather, absorb and channel various energies, teleport, and sense various energies.
This article was written by me and first appeared on Quora as part of the question: Who were the grand champions depicted on the Grandmaster's tower in Thor: Ragnarok?

A: In the actual film, Hulk on top, under him is Beta Ray Bill  and Ares, under Ares is BiBeast and then Manthing at the bottom, the one next to BiBeast is questionable.


text:
Q: Rotating Vectors in space I have two sets of vectors,
(* SET_1:  *)

A0 = {-23.645, 8.761, 19.186};
A1 = {8.909, 11.977, -26.572};
A2 = { 6.098, 8.537, 31.834};
A3 = {9.866, -32.131, -24.569};

(* SET_2:  *)

B0 = {-13.9469, 28.7731, -3.21699};
B1 = {-13.8077, -27.3636, 0.329735};
B2 = {2.94231, 23.5992, 23.8511};
B3 = {24.8123, -25.0087, -20.9639};

These two sets are such that A0 = B0, A1=B1, A2=B2, and A3=B3 (Let's say within experimental error) but only rotated in 3d space.
Now is there any way to know the rotation axis and angle of this transformation so that I can use this information for future use.

A: I think you want a single transformation function for all points, rather than one for each point independently as kglr's answer currently shows.
set1 = {A0, A1, A2, A3};
set2 = {B0, B1, B2, B3};

tF2 = FindGeometricTransform[
        set1, set2
         , TransformationClass -> "Rigid"
         , Method -> "FindFit"
      ][[2]];

Graphics3D[{
   {Red, PointSize[Large], Point[set1]},
   {Opacity[.15, Blue], Sphere[tF2@set2, 2]}
}]

A: If you are looking for a map  R.A[i]~B[i] ,i,0,1,2,3 :
First you have to define the rotationmatrix R
 ϕ = {{0, -φ3, φ2}, {φ3,0,-φ1}, {-φ2, φ1, 0}};
 φ = Simplify[Sqrt[Tr[-ϕ.ϕ/2]]]
 R = IdentityMatrix[3] + Sin[φ]/φ ϕ + (1 - Cos[φ])/φ^2 ϕ.ϕ ;

which depends on φ1, φ2, φ3
Now you can calculate the optimal rotation parameters φ1, φ2, φ3
 J = Total@MapThread[(R.#1 - #2 ).(R.#1 - #2 ) &, {{A0, A1, A2, A3},{B0, B1, B2, B3}}]
 sol=NMinimize[J, {φ1, φ2, φ3}]
 (* {2061.5, {φ1 -> -1.01538, φ2 ->1.45343, φ3 -> 1.3975}} *)

The optimal rotationmatrix is
Ropt=R /.sol[[2]]
(*{{-0.303462, -0.951876, 0.0429177},
{0.00554758, 0.043276,0.999048},
{-0.952827, 0.303411, -0.007852}} *)

Ropt.Transpose[Ropt] (*test:  should be identitymatrix[3] *)

A: You can use FindGeometricTransform:
tFs = MapThread[FindGeometricTransform[{#}, {#2}][[2]] &,
  {{A0, A1, A2, A3}, {B0, B1, B2, B3}}];

Graphics3D[{Red, PointSize[Large], Point[{A0, A1, A2, A3}], Opacity[.15, Blue],
  MapThread[Sphere[#@#2, 2] &, {tFs, {B0, B1, B2, B3}}]}]


text:
Q: Multiple onClick action I'm new in Android code and, well, I have a big question.
Someone can explain me how can I give an object different actions with a number of clicks?
I'm building an app and I want to do that: when you touch a view element 2 times (for example), this element change to another activity, and when you touch it 4 times, that app could send an SMS.
I have all the functions completed, but I don't know how to make that "touch actions".
Someone can help me please? :)

A: private int click_count = 0;
public void onClick(View v){
    count++;

   switch(count){
      case 2:
        //Two clicks
      break;
      case 4:
        //Three clicks
      break;
   }
}

A: Step 1: In button onclick
private int count = 0;
public void onClick(View v){

switch(v.getId == R.id.btn){

   count++;

   switch(count){
      case 2:
        //Two clicks
      break;
      case 4:
        //Three clicks
      break;
   }
}


text:
Q: Replace an element name while retaining the attributes with jquery I'm trying to create a jquery setup where all instances of  are changed to . It's easy enough to do with:
$("i").each(function(){
    $(this).replaceWith($('' + this.innerHTML + ''));
});

But what I am having trouble figuring out is how to change all the  tags but retain each ones individual attributes. So if I have Example Text I would like it to change to Example Text
Thanks for any help!

A: Wrong approach IMO.
I'd recommend replacing the actual elements themselves directly in the DOM. Maybe this question helps:
jQuery convert DOM element to different type

A: It is simple
$(this).attributes(); will get you all the attributes of the i tag for every instance simply place it into your replace function.
I am not sure how can you play with a function but in my knowledge code will be something like this.

$("i").each(function(){
var attribute = $(this).attributes();
$(this).replaceWith($(''

+ this.innerHTML + ''));
      });

Hope it helps.


text:
Q: What determines if your arrows break? Being long range and silent the bow is one of the most useful stealth options in the game with the added benefit of sometimes getting your ammo back. My roommate claims that arrows will always break unless you get a head shot, in which case they will always be recoverable. In my experience however being able to recover your arrow seemed more or less random.
So the question: Is there something that determines whether an arrow breaks or not? or is it actually random?

A: Your roommate was misled; the arrows break at random. There are some people who have tried numerous tests to find the exact percentage. The results range from 80% retrieval to 20% retrieval. This, along with the difference between torso vs. head shot, makes the overall percentage random.


text:
Q: Oracle Bind Variables, Procedures and a headache I am wondering if you can point me in the right direction. I have spent the last little while trying to work out how to use Bind Variables in block code with declares. My issues is that every time I try run the code block in SQL Developer, its returning the error "Bind Variable "disp" is NOT DECLARED.
In a non-block piece of code I can get the results I am expecting. The following I know works and I do get results for:
var disp varchar2(200);
begin
    test_procedure('test', 100, :disp);
end;
/
print :disp

The above code returns me a value, test100.
However, if I try move this into a block of code, that I could use as a single line in an external application (Java or PHP) I start running into trouble. What I have so far is:
declare
    disp varchar2(200);
begin
    test_procedure('test', 100, :disp);
end;
/
print :disp

When I run the above I am getting:

Bind Variable "disp" is NOT DECLARED

I have tried a few different approaches from using var inside the declare box to trying to reference the procedures variable definitions, however none are working for me

A: You don't prefix a local variable name with a colon.
declare
    disp varchar2(200);
begin
    test_procedure('test', 100, disp);
end;

is a valid PL/SQL block.  print is a SQL*Plus command, however, so it only works with SQL*Plus variables, not variables defined in PL/SQL blocks.  If you have enabled it, you could use dbms_output to print the value in PL/SQL
declare
    disp varchar2(200);
begin
    test_procedure('test', 100, disp);
    dbms_output.put_line( disp );
end;

In SQL Developer, you'd need to enable output first (View | DBMS Output to bring up the window in newer versions of SQL Developer).
dbms_output would not be an appropriate way to return data to a client application (or to do something where you're depending on a human to see the output in order to do something).  It's a useful package for doing very simple debugging or a quick proof of concept.  But you shouldn't assume that the caller of your code has allocated a buffer for dbms_output to write to or that it has any ability to read what you've written to dbms_output.


text:
Q: Получить одно фото с веб-камеры C++ Здравствуйте! Я знаю, что данная тема уже поднималась, но все же вопрос задам.
Как можно получить один кадр с веб-камеры средствами С++, без сторонних библиотек(имею ввиду OpenCV)? Как здесь можно использовать WinAPI?


text:
Q: Primes in integral domains Let $\mathcal O_{\mathbb K}$ be the ring of integers in a number field $\mathbb K$. It is easy to prove that the number of (non-associated) primes in $\mathcal O_{\mathbb K}$ is infinite.
On the other hand, for any field $\mathbb F$ there is only one (non-associated) prime in the power series ring $\mathbb F[[x]] $, namely the element x. Any integral domain that I imagine the question of finitude or infinity of primes is easy.
My question is: is there any integral domain in which the question of finitude or infinitude of prime elements is open? Or, at least, very difficult to prove?


text:
Q: OmniAuth using google oauth 2 strategy scope failure I'm working on getting calendar data from google using OmniAuth and the google-oauth-2 strategy.
If I put nothing into the scope field it works fine and I get the default info without the auth/failure message and I can use the app normally.
However the moment I add a scope, as in the example below, I get an "auth/failure?message=invalid_credentials".
Rails.application.config.middleware.use OmniAuth::Builder do
    provider :google_oauth2, ENV['TEST_KEY'], ENV['TEST_SECRET'], { :scope => 'https://www.google.com/calendar/feeds/' }
end

Is there something I'm missing or something I should change?

A: A quick e-mail from the google-oauth-2 strategy author pointed out the following:
If you don't include the profile scopes, it fails to authenticate.
By adding userinfo.email and userinfo.profile (along with the calendar scope) to the comma separated :scope list I was able to fix the problem.
Example:
Rails.application.config.middleware.use OmniAuth::Builder do
    provider :google_oauth2, ENV['TEST_KEY'], ENV['TEST_SECRET'],
           { :scope => 'userinfo.email, userinfo.profile, https://www.googleapis.com/auth/calendar' }
end

A: Funny, this didn't work for me.
I was able to make it work, removing the comma from the scope:
Rails.application.config.middleware.use OmniAuth::Builder do
    provider :google_oauth2, ENV['TEST_KEY'], ENV['TEST_SECRET'],
    { :scope => 'https://www.googleapis.com/auth/docs https://www.googleapis.com/auth/userinfo.profile' }
end


text:
Q: Trying to create an updating digital clock in flutter So I'm using a package called timebuilder that's rebuilding my widget. For DateFormat class I used this package.
 final String currentTime = getSystemTime();

 static String getSystemTime() {
   var now = new DateTime.now();
   return new DateFormat("H:m:s").format(now);
 }

 @override
 Widget build(BuildContext context) {
   return TimerBuilder.periodic(Duration(seconds: 1), builder: (context) {
     print("$currentTime");
     return Text(
       "$currentTime",
       style: TextStyle(
           color: Color(0xff2d386b),
           fontSize: 30,
           fontWeight: FontWeight.w700),
     );
   });
 }
}

I'm then displaying ClockWidget. My widget is rebuilding fine. But the value of currentTime remains what it initially was when I built my project. Any clues as to why currentTime isn't updating?

A: Remove static from  getSystemTime(),
Although I have created a working example from your code,
  String getSystemTime() {
      var now = new DateTime.now();
      return new DateFormat("H:m:s").format(now);
  }

            TimerBuilder.periodic(Duration(seconds: 1), builder: (context) {
                print("${getSystemTime()}");
                return Text(
                  "${getSystemTime()}",
                  style: TextStyle(
                      color: Color(0xff2d386b),
                      fontSize: 30,
                      fontWeight: FontWeight.w700),
                );
              }),

Output:


text:
Q: Unable to dismiss keyboard in iOS simulator I cannot get textFieldShouldEndEditing to call. I have re created the links in interface builder and tried, but nothing seems to work. Any idea why this would not be called?
Edit
 -(BOOL)textFieldShouldEndEditing:(UITextField *)textField
 {
     NSLog(@"Done editing...");
     [textField resignFirstResponder];
      return YES;
 }

A: You need the delegate!
Try to add in your .h this <UITextFieldDelegate>
and in your .m
_yourTextField.delegate = self.
It works.

A: Try this code .
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
 [Self.view EndEditing:YES];
 return YES;
}

Also use   _myTextField.delegate = self; in your  ViewDidLoad
And in your .h file, add <UITextFieldDelegate> after the name of your class.

A: you can try this code ...
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
 [textField resignFirstResponder];
 return YES;
}
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
  return YES;
}

I hope this will help you.
happy coding.

A: You should set your textField's delegate to the class where you implemented textFieldShouldEndEditing:.
You can do it two ways :
First, in InterfaceBuilder, ctrl-drag from the component to the viewController, and select "delegate".
Or, in the viewDidLoad of the class, add this line :
_myTextField.delegate = self;

For both ways, in your .h file, add <UITextFieldDelegate> after the name of your class.

A: Just for fun if you want to be really fancy, you can have keyboard disappear whenever user touches anywhere on the screen. Add this code in ViewDidLoad and it will work.
Read this Stackoverflow link too - Dismiss iphone keyboard
- (void)viewDidLoad
{

UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]
                                   initWithTarget:self
                                   action:@selector(dismissKeyboard)];

    [self.view addGestureRecognizer:tap];

}

-(void)dismissKeyboard
{
//here text1 is your custom UITextField
    [text1 resignFirstResponder];
}


text:
Q: NVIDIA DIGITS: Get accuracy for segmented images I am trying to use NVIDIA DIGITS to perform image segmentation (by following this article). After training the model, I was able to perform the segmentation on individual images.
Now I would like to give a list of test images and labeled images to DIGITS, and I want it to calculate accuracy for the input images. Is it possible to do it using DIGITS, if yes, then what are the steps? (options to select on framework while training/testing model, format of input file, folder structure, etc.)
Also, if DIGITS can't do it, then are there any other frameworks? (I read this post, but it would be better if I can directly use some plug-and-play framework, to begin with)
Thanks!


text:
Q: How can I return the state correctly in my Redux app? We have some todo list. We have initialState kind of of like...
initialState = [   {
  id: 0,
  title: "first",
  items: [
    {
      title: "one from first",
      id: 0,
      cards: [
        {
          id: 0,
          text: "111",
        },
        {
          id: 1,
          text: "222",
        },
      ],
    },
    {
      title: "two from first",
      id: 1,
      cards: [
        {
          id: 0,
          text: "www",
        },
        {
          id: 1,
          text: "zzz",
        },
      ],
    },
  ],   },   {
    id: 1,
    title: "second board",
    items: [
      {
        title: "first from second",
        id: 0,
        cards: [
          {
            id: 0,
            text: "asd",
          },
          {
            id: 1,
            text: "fasdf",
          },
        ],
      },
    ],   }, ];

We wont normalize this state for some reasons.
I have to add new List.
The reducer here:
switch(action) {
  case CONSTANTS.ADD_LIST:
    const newList = {
      title: action.payload.title,
      cards: [],
      id: listID,
    };
    listID += 1;

    return {
      ...state,
      [action.payload.boardID]: {
        ...state[action.payload.boardID],
        items: [...state[action.payload.boardID].items, newList],
      },
    };
}

Example. I want to add newList for items from board 1(starting from 0).
I tested another examples like the above and it's useless.
So I can't get why it's not working. I think I have some problems with docs redux and I can't get it.
Thanks!

A: Your initialState seems to be an Array and not an object:
initialState = [ {Board1},{Board2} ]

But your reducer seems to be returning an object, so perhaps thats a potential issue.
======
You could instead try the following changes in your reducer:

*

*make shallow copy of boardsArr aka initialState

*loop over each board and create a new board object

*Loop over each board object's items prop, and create its shallow copy

*loop each item's cards prop and create its copy

*finally replace the board's items you want and then

*return the newly created boardsArr

// Pseudo code inside reducer

const newBoardsArr = state.map(board => {
    return {
        ...board,
        items: board.items.map(item => ({
            ...item,
            cards: item.cards.map(card => ({
                ...card
            }))
        }))
    }
});

// lets say we want to update first board's items, then:

newBoardsArr[action.payload.boardID].items = newList;
return newBoardsArr;


text:
Q: OpenGL UVs behave weird? I'm trying to implement a system for creating GUIs with OpenGL. For some applications like bitmap-fonts it would be nice to have an offset for the textures that should be rendered on an object.
So my offset in the vertex shader looks like this:
UV = vec2(uv.x, 1.0f - uv.y) + vec2(texOffset.x, texOffset.y);

I tested my offset using a rectangle with an offset that I continuously make larger.
Adding this offset on the x-axis looks like this:
https://youtu.be/z7bKgb7zcPc which is fine.
Using my offset on the y-axis looks like this:
https://youtu.be/2S_duM5JK_w this is also fine.
But now applying the offset on the x- and y-axis looks like this:
https://youtu.be/t_aJbQwbagw which is not fine.
Shouldn't it move like this: https://youtu.be/0GzPRpIaabE?
Why does my result differ from what I expect?

A: So I found the problem. There isn't a bug in OpenGL, the problem is that my offset is wrong for the x axis.
I expected for a positive x offset, that the texture moves right. But I forgot to implement the flip that was required for that. But I didn't remember that, so from my expectation, the output was wrong, but it was just me...


text:
Q: How to get rid of undefined error when closing a dialog box? There are two components that transmit data between each other. If  just close the child dialog box without selecting data, then this error occurs:

Cannot read property 'contractor_id' of undefined

parent component:
...
dialogRef.afterClosed().subscribe(
  contractors => {
    this.form.get('SPR_CONTRACTORS_ID').patchValue(contractors.contractor_id)
    this.form.get('CONTRACTOR_NAME').patchValue(contractors.contractor_name)
  }
);
...

child component close:
  close() {
    this.dialogRef.close();
  }

How to fix this error if I just close the window without selecting data?

A: From what I can see: you get your contractors from the afterClose subscription but your close is returning nothing:
  close() {
    this.dialogRef.close(this.contractors);
  }

may be your solution (assuming contractors is defined in this component)

A: When you close your dialog, you don't pass anything to the close function, therefore the contractors value will be undefined in your dialogRef.afterClosed().subscribe block.
You can add a simple if-statement to prevent this error. If you now close your dialog and pass nothing, the form will not be updated as contractors is undefined.
 dialogRef.afterClosed().subscribe(
  contractors => {
    if (contractors) {
      this.form.get('SPR_CONTRACTORS_ID').patchValue(contractors.contractor_id)
      this.form.get('CONTRACTOR_NAME').patchValue(contractors.contractor_name)
    }
  }
);


text:
Q: HTTP Post Request (CSV File to ebay) with VBA The eBay CSV Manager enables to upload a CSV file to mark all paid and sent items as sent in eBays seller tool. My Excel Macro creates such a CSV file. Now, I want to upload this file via HTTP Post Request.
In eBays CSV Manager manual they say:

Files can only be uploaded via Token. This Token has to be send with the file every upload. It is virtually the key for the entry to the CSV Manager.

I already have the Token.
It goes on to say that

a HTTP Post request has to be sent to the eBay CSV Manager Server to upload the file via script. The HTTPS connection has to be started and the data has to be send together with the Token to the CSV Manager web adress https://bulksell.ebay.com/ws/eBayISA...ExchangeUpload

eBay has an example for the request in its CSV Manager manual:
POST /path/to/upload/script HTTP/1.0
Connection: Keep-Alive
User-Agent: My Client App v1.0
Host:
https://bulksell.ebay.com/ws/eBayISA...ExchangeUpload
Content-type: multipart/form-data;
boundary=THIS_STRING_SEPARATES
Content-Length: 256
--THIS_STRING_SEPARATES
Content-Disposition: form-data; name="token"
12345678987654321
--THIS_STRING_SEPARATES
Content-Disposition: form-data; name="file";
filename="listings.csv"
Content-Type: text/csv
... contents of listings.csv ...
--THIS_STRING_SEPARATES
The explanation of the example is:
State which method has to be applied to the ressource:
POST /path/to/upload/script HTTP/1.0
Connection type, user-agent and information to the host:
Connection: Keep-Alive
User-Agent: My Client App v1.0
Host:https://bulksell.ebay.com/ws/eBayISA...ExchangeUpload
Header with information to the content and the lenght of the file:
Content-type: multipart/form-data; boundary=THIS_STRING_SEPARATES
Content-Length: 256
Safety Token and content to be uploaded:
--THIS_STRING_SEPARATES
Content-Disposition: form-data; name="token"
12345678987654321
--THIS_STRING_SEPARATES
Content-Disposition: form-data; name="file"; filename="listings.csv"
Content-Type: text/csv
... contents of listings.csv ...
--THIS_STRING_SEPARATES
How to do the HTTP Request and how to integrate it to the VBA Code?

A: The concept of REST API is that you post a data file to the API end point. You need to use one of microsoft http add-on to conscruct the payload which contains the header and body and post it to the require API.
You would have multi part in your macro to achieve this function

*

*A login function where you would store the token

*A body constructor where you would read your excel data and transform it into a json format.

*A header constructor

*A post function where post the relevant data to the gateway api using the microsoft http document handler.

But if you are planning to send the CSV as data then its best to write a vbscript to quickly post the file to the API.


text:
Q: How do I avoid large number of svn:mergeInfo when merging trunk to a feature-branch in SVN I am trying to keep a feature branch up to date by merging trunk into the branch. Problem is, that about 2000 files that was there when the branch was created, and that has been left untouched on both the branch and on trunk is getting updated with nothing but svn:mergeinfo.
The project is rather large in scale, and the impact on our SVN history is so big, that it renders the merge commit history unusable as it is marking literally thousands of files changed, even though the only change to these files, is done by SVN itself.
I have tried

*

*Using the same client version as the Repo ( 1.5.2 )

*Using my current client version 1.6.10

*Merging a range of revisions, from branch start till head

I should mention, that I've been looking closely at the SVN documentation when trying this. So no rules should be broken ( eg. no switched subtrees, clean local copy etc.)

A: Bascially to clean up the repository you need to run the following on your integration branch so that the change fans out from there:-
C:> svn propdel svn:mergeinfo –R
i.e. you do it in the trunk so that future release and feature branches are not polluted. When merging existing branches you can ignore all svn:merginfo changes below the "merge root" as they will be inherited anyway.
I wrote a blog on this issue a while back which covers it in more detail:-
Cleaning up svn:mergeinfo Droppings
http://chrisoldwood.blogspot.com/2010/03/cleaning-up-svnmergeinfo-droppings.html

A: svn will add mergeinfo properties to individual files if it thinks their merge history differs from that of their parent directory. Once that has happened, every subsequent merge, no matter how harmless, will cause those mergeinfo properties to be updated. I found the first half of this article helpful to understand why that happens.
If you want to avoid these constant mergeinfo changes, you'll have to "tidy up" the existing mergeinfo properties on your branch. The safest, but most laborious, way is to run svn propget -R svn:mergeinfo on the branch, and then study the differences between the mergeinfo on individual files and the mergeinfo of their parent directory. You may find that the differences are small, and that "svn merge"ing a small number of individual revisions will be enough to trigger mergeinfo elision, causing all the individual mergeinfo properties to disappear.
If you're confident you understand how mergeinfo works, you can also just wade in and manually edit or remove the mergeinfo from the offending files.

A: If you have such mergeinfo on files which aren't really changed you or someone else does merges not from the working copy root...The only solution is to removed the svn:mergeinfo from the files, cause the only location is in the working copy root nowhere else.
And one other point you should update the repository to 1.6.X ..

A: As I am not confident with blind svn:merge-info property deletion, I have implemented a tool to analyze the current situation on a working copy and remove as much merge revisions as possible from non-root merge-info properties. After additional human checks and controls, the changes on the working copy can be committed.
Here it is: svn-clean-mergeinfo
Do not hesitate to report any issue about its usage to get it improved.


text:
Q: selenium action chains no effect I'm using selenium on python and want to open a new tab in chrome.
I tried
  ActionChains(driver).key_down(Keys.CONTROL).send_keys('t').key_up(Keys.CONTROL).perform()

but that makes no effect. nothing happened.
I've also tried
send_keys(Keys.CONTROL+'t')

but that also makes no effect.
How can I open a new tab in selenium?

A: It is possible to open a new tab the following way:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

browser = webdriver.Chrome()
browser.get('https://www.google.com')

q = browser.find_element_by_name('q')
q.send_keys(Keys.CONTROL, 't')

browser.close()

Chrome 44.0.2403.89 (64-bit), Selenium 2.46.1 on Ubuntu 12.04.
Notice that I am using , and not a + in the send_keys() function.

A: ActionChains(driver).key_down(Keys.CONTROL).send_keys(str('\u0074')).perform()

\u0074 represents the character 't'
To press other characters refer the unicode character table - http://unicode.org/charts/PDF/U0000.pdf

A:
For performing such automation operations you might wanna use something that's built over selenium to handle all such tasks like tab switching , automatic element finding , Special Key press and hold  :etc.

Take a look at : "webbot"
webbot works even for webpages with dynamically changing id and classnames and has more methods and features than selenium and mechanize.
Here's a small snippet
from webbot import Browser
web = Browser()
web.go_to('google.com')
web.click('Sign in')
web.type('mymail@gmail.com' , into='Email')
web.click('NEXT' , tag='span')
web.type('mypassword' , into='Password' , id='passwordFieldId') # specific selection
web.click('NEXT' , tag='span') # you are logged in ^_^

For your specific usage :
web.press( web.Key.CONTROL + 't' )


text:
Q: Is there any mistake in this code to make memory leak? I tried more than a time but every time gives the same error.
Fatal error: Out of memory (allocated 507510784) (tried to allocate 16384 bytes) in ..(location)..\accounts.php on line 51

The function
public function getUser($userBase, $allowID = true, $allowUName = true, $allowEmail = true, $allowHash = true) {
            // If nothing allowed!
            if ($allowID == false && $allowUName == false && $allowEmail == false && $allowHash == false) {
                return NULL;
            }
            if ( $allowID == true ) {
                // User ID
                $result = $this->conn->query( "SELECT * FROM `accounts` WHERE `id` = {$userBase}" );
                if ( $result && $result->num_rows > 0 ) {
                    return new user( $this->conn, $userBase );
                }
            }
            if ( $allowUName == true ) {
                // User Name
                $result = $this->conn->query( "SELECT * FROM `accounts` WHERE `username` = '{$userBase}'" );
                if ( $result && $result->num_rows > 0 ) {
                    return new user( $this->conn, $userBase );
                }
            }
            if ( $allowEmail == true ) {
                // Email
                $result = $this->conn->query( "SELECT * FROM `accounts` WHERE `email` = '{$userBase}'" );
                if ( $result && $result->num_rows > 0 ) {
                    return new user( $this->conn, $userBase );
                }
            }
            if ( $allowHash == true ) {
                $result = $this->conn->query( "SELECT * FROM `accounts` WHERE `hash` = '{$userBase}'" );
                if ( $result && $result->num_rows > 0 ) {
                    return new user( $this->conn, $userBase );
                }
            }
            return NULL;
        }

And this is how I do call it.
return this->getUser($uname, false, true, true, false);

I don't know the reason why it uses this huge memory.

A: Well so far, I understood the problem
The line containg new user which connects to database and loads it self again which causes an infinite loop trying to reach a result then fails!


text:
Q: How can I create dynamic Lambda Expressions I have a question, how do I add another filter and this I have to validate that was selected?
private Expression < Func < Entity.Modelos.Flux, bool >> Filter() {
    var dateStart = dtpDateStart.Value.Date;
    var dateEnd = dtpDateEnd.Value.Date;

    Expression < Func < Entity.Modelos.Flux, bool >> expr = null;

    expr = f = > f.DatFlux >= dateStart.Date && f.DatFlux <= dateEnd.Date;

    if (txtDescription.Text != String.Empty) {
        //add filter
    }

    return expr;
}

Update: I'll use the expression in this function:
public virtual IQueryable < T > Filter(Expression < Func < T, bool >> expressao) {
    return DbSet.Where(expressao).AsQueryable < T > ();
}

What I was trying to do is this but with an Expression
public List < Users > GetUsers(int ? id, string name) {
    using(DBContext ctx = new DBContext()) {
        IQueryable query = ctx.Usuarios;
        if (id.HasValue)
            query = query.Where(x = > x.ID == id);

        if (!string.IsNullOrEmpty(name))
            query = query.Where(x = > x.Name.StartsWith(name));

        return query.ToList();

    }
}

A: If this is just a demo of your requirements, then you can create and modify Expression Trees using the System.Linq.Expressions namespace.
However, in the case of your question, it would probably be easier to use EF:
bool filterDescription = !String.IsNullOrEmpty( txtDescription.Text );

expr = f =>
  (
    ( f.DatFlux >= dateStart.Date && f.DatFlux <= dateEnd.Date )
    &&
    ( !filterDescription || ... add filter ... )
  )
;

or normal C#:
if ( String.IsNullOrEmpty( txtDescription.Text ) )
{
  expr = f => f.DatFlux >= dateStart.Date && f.DatFlux <= dateEnd.Date;
}
else
{
  expr = f => f.DatFlux >= dateStart.Date && f.DatFlux <= dateEnd.Date
    &&
    ... add filter ...
  ;
}

A: Okay, well here is a sample on how to embed lambda statements. It's not your example, but here ya go:
Func<int, int, EventHandler> makeHandler =
    (dx, dy) => (sender, e) => {
        var btn = (Button) sender;
        btn.Top += dy;
        btn.Left += dx;
    };

btnUp.Click += makeHandler(0, -1);
btnDown.Click += makeHandler(0, 1);
btnLeft.Click += makeHandler(-1, 0);
btnRight.Click += makeHandler(1, 0);

A: It is simple.Visit this link
the tricky thing is invoking the OrderByAlias - using MakeGenericMethod may be the way, as shown in the link above.

A: Try this way:
private Expression<Func<Entity.Modelos.Flux, bool>> Filter()
{
    var dateStart = dtpDateStart.Value.Date;
    var dateEnd = dtpDateEnd.Value.Date;

    Func<Entity.Modelos.Flux, bool> expr = null;

    expr = f => f.DatFlux >= dateStart.Date && f.DatFlux <= dateEnd.Date;

    if(txtDescription.Text != String.Empty)
    {
       expr = f => expr(f) && f.Title.Equals(txtDescription.Text); // ← Your additional filter
    }

    return f => expr(f);
}

A: inherit from ExpressionVisitor
public class MyVisitor: ExpressionVisitor
{
    private LambdaExpression visitor;
    public Expression Modify(Expression expression, LambdaExpression visitor)
    {
        this.visitor = visitor;
        return Visit(expression);
    }

    protected override Expression VisitBinary(BinaryExpression b)
    {
        var binary = visitor.Body as BinaryExpression;

        return Expression.MakeBinary(ExpressionType.AndAlso, b, binary, b.IsLiftedToNull, b.Method);
    }
}

your Filter() method might look like this
    private Expression<Func<Entity.Modelos.Flux, bool>> Filter()
    {
        var dateStart = dtpDateStart.Value.Date;
        var dateEnd = dtpDateEnd.Value.Date;
        var description = txtDescription.Text;

        Expression<Func<Entity.Modelos.Flux, bool>> expr = null;

        expr = f => f.DatFlux >= dateStart.Date && f.DatFlux <= dateEnd.Date;

        if (description != String.Empty)
        {
            //add filter
            Expression<Func<Entity.Modelos.Flux, bool>> other = f => f.Description == description;

            var modifier = new MyVisitor();
            expr = (Expression<Func<Entity.Modelos.Flux, bool>>)modifier.Modify((Expression)expr, (LambdaExpression)other);
        }

        return expr;
    }

example
have a look at the following for more information
How to: Modify Expression Trees (C# and Visual Basic)


text:
Q: disable ecommerce I have a magento shop with several websites.
I would like to add a website for the technical support only and I want to disable the ecommerce function in that website only.
So far I found only solution where they recommend to disable core module which I can obviously not do as I have other websites.
Any solution on a website base?

A: For this, you have to disable all the backend functionality form where the user cannot order anything from that store like add to cart etc.


text:
Q: POST request with Multipart/form-data. Content-type With android ( two picture ) hi i upload two picture from android to a server and i receive just one picture (the first picture but not the second picture) please where is my error ??!
i think the error is in public int uploadFile(String sourceFileUri,String sourceFileUri2) but how correct him please
thanks
this is my layout

this is my java code for upload
        buttonmodifprofil = (TextView)alertDialogView.findViewById(R.id.buttonmodifprofil);
                editphoto = (TextView)alertDialogView.findViewById(R.id.editphoto);
                editphoto.setText("Uploading file path :- '/sdcard/android_1.png'");
                uploadimage_btn = (ImageView) alertDialogView.findViewById(R.id.joindreimage);
                uploadimage_btn.setOnClickListener( new OnClickListener(){
                @Override
                public void onClick(View view) {
                // To open up a gallery browser
                  Intent intent = new Intent();
                  intent.setType("image/*");
                  intent.setAction(Intent.ACTION_GET_CONTENT);
                  startActivityForResult(Intent.createChooser(intent, "Select Picture"),1);
                }});

                editlogo = (TextView)alertDialogView.findViewById(R.id.editlogo);
                editlogo.setText("Uploading file path :- '/sdcard/android_1.png'");
                uploadlogo_btn = (ImageView) alertDialogView.findViewById(R.id.joindrelogo);
                uploadlogo_btn.setOnClickListener( new OnClickListener(){
                @Override
                public void onClick(View view) {
                // To open up a gallery browser
                  Intent intent = new Intent();
                  intent.setType("image/*");
                  intent.setAction(Intent.ACTION_GET_CONTENT);
                  startActivityForResult(Intent.createChooser(intent, "Select Picture"),0);
                }});

                buttonmodifprofil.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog = ProgressDialog.show(MainClient.this, "", "Uploading file...", true);
                         new Thread(new Runnable() {
                                public void run() {
                                     runOnUiThread(new Runnable() {
                                            public void run() {
                                                editphoto.setText("uploading started.....");
                                            }
                                        });
                                 int response= uploadFile(editphoto.getText().toString(),editlogo.getText().toString());
                                 System.out.println("RES : " + response);
                                }
                              }).start();
                        }
                });

and this is the code for upload 2 file
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK) {
        if (requestCode == 1) {
        // currImageURI is the global variable I'm using to hold the content:
            Uri currImageURI = data.getData();
            System.out.println("Current image Path is ----->" +                          getRealPathFromURI(currImageURI));
           // TextView editphoto_path = (TextView) findViewById(R.id.editphoto);
            editphoto.setText(getRealPathFromURI(currImageURI));
        }
        else{
              // currImageURI is the global variable I'm using to hold the content:
            Uri currImageURI = data.getData();
            System.out.println("Current image Path is ----->" +                          getRealPathFromURI(currImageURI));
           // TextView editphoto_path = (TextView) findViewById(R.id.editphoto);
            editlogo.setText(getRealPathFromURI(currImageURI));
        }
    }
}

//Convert the image URI to the direct file system path of the image file
public String getRealPathFromURI(Uri contentUri) {
    String [] proj={MediaStore.Images.Media.DATA};
    @SuppressWarnings("deprecation")
    android.database.Cursor cursor = managedQuery( contentUri,
    proj,     // Which columns to return
    null,     // WHERE clause; which rows to return (all rows)
    null,     // WHERE clause selection arguments (none)
    null);     // Order-by clause (ascending by name)
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);
}

public int uploadFile(String sourceFileUri,String sourceFileUri2) {
      String upLoadServerUri = "http://www.citations-inoubliables.com/mappnet/upload.php";
      String fileName = sourceFileUri;
      String fileName2 = sourceFileUri2;
      HttpURLConnection conn = null;
      DataOutputStream dos = null;
      String lineEnd = "\r\n";
      String twoHyphens = "--";
      String boundary = "*****";
      int bytesRead, bytesAvailable, bufferSize;
      byte[] buffer;
      int maxBufferSize = 1 * 1024 * 1024;
      int bytesRead2, bytesAvailable2, bufferSize2;
      byte[] buffer2;
      int maxBufferSize2 = 1 * 1024 * 1024;
      File sourceFile = new File(sourceFileUri);
      File sourceFile2 = new File(sourceFileUri2);
      if (!sourceFile.isFile()) {
       Log.e("uploadFile", "Source File Does not exist");
       return 0;
      }
      if (!sourceFile2.isFile()) {
          Log.e("uploadFile", "Source File Does not exist");
          return 0;
         }
          try { // open a URL connection to the Servlet
           FileInputStream fileInputStream = new FileInputStream(sourceFile);
           FileInputStream fileInputStream2 = new FileInputStream(sourceFile2);
           URL url = new URL(upLoadServerUri);
           conn = (HttpURLConnection) url.openConnection(); // Open a HTTP  connection to  the URL
           conn.setDoInput(true); // Allow Inputs
           conn.setDoOutput(true); // Allow Outputs
           conn.setUseCaches(false); // Don't use a Cached Copy
           conn.setRequestMethod("POST");
           conn.setRequestProperty("Connection", "Keep-Alive");
           conn.setRequestProperty("ENCTYPE", "multipart/form-data");
           conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
           conn.setRequestProperty("uploadImage", fileName);
           conn.setRequestProperty("uploadLogo", fileName2);
           dos = new DataOutputStream(conn.getOutputStream());

           dos.writeBytes(twoHyphens + boundary + lineEnd);
           dos.writeBytes("Content-Disposition: form-data; name=\"uploadImage\";filename=\""+ fileName + "\"" + lineEnd);
           dos.writeBytes("Content-Disposition: form-data; name=\"uploadLogo\";filename=\""+ fileName2 + "\"" + lineEnd);

           dos.writeBytes(lineEnd);

           bytesAvailable = fileInputStream.available(); // create a buffer of  maximum size
           bytesAvailable2 = fileInputStream2.available();

           bufferSize = Math.min(bytesAvailable, maxBufferSize);
           buffer = new byte[bufferSize];

           // read file and write it into form...
           bytesRead = fileInputStream.read(buffer, 0, bufferSize);

           while (bytesRead > 0) {
             dos.write(buffer, 0, bufferSize);
             bytesAvailable = fileInputStream.available();
             bufferSize = Math.min(bytesAvailable, maxBufferSize);
             bytesRead = fileInputStream.read(buffer, 0, bufferSize);
            }

           bufferSize2 = Math.min(bytesAvailable2, maxBufferSize2);
           buffer2 = new byte[bufferSize2];

           // read file and write it into form...
           bytesRead2 = fileInputStream2.read(buffer2, 0, bufferSize2);

           while (bytesRead2 > 0) {
             dos.write(buffer2, 0, bufferSize2);
             bytesAvailable2 = fileInputStream2.available();
             bufferSize2 = Math.min(bytesAvailable2, maxBufferSize2);
             bytesRead2 = fileInputStream2.read(buffer2, 0, bufferSize2);
            }

           // send multipart form data necesssary after file data...
           dos.writeBytes(lineEnd);
           dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

           // Responses from the server (code and message)
           serverResponseCode = conn.getResponseCode();
           String serverResponseMessage = conn.getResponseMessage();

           Log.i("uploadFile", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode);
           if(serverResponseCode == 200){
               runOnUiThread(new Runnable() {
                    public void run() {
                        editphoto.setText("File Upload Completed.");
                        Toast.makeText(MainClient.this, "File Upload Complete.", Toast.LENGTH_SHORT).show();
                    }
                });
           }

           //close the streams //
           fileInputStream.close();
           fileInputStream2.close();
           dos.flush();
           dos.close();

      } catch (MalformedURLException ex) {
          dialog.dismiss();
          ex.printStackTrace();
          Toast.makeText(MainClient.this, "MalformedURLException", Toast.LENGTH_SHORT).show();
          Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
      } catch (Exception e) {
          dialog.dismiss();
          e.printStackTrace();
          Toast.makeText(MainClient.this, "Exception : " + e.getMessage(),      Toast.LENGTH_SHORT).show();
          Log.e("Upload file to server Exception", "Exception : " + e.getMessage(), e);
      }
      dialog.dismiss();
      return serverResponseCode;
     }

and this is php code
<?php

     $output_users_icons = "uploads/";
     $output_offices_icons = "uploads/";
     $ok_upload_image;
     $ok_upload_logo;
     $err_post=0;
     if(isset($_FILES["uploadImage"])|isset($_FILES["uploadLogo"]))
     {     /* Upload Image User */
            if ($_FILES["uploadImage"]["error"] > 0)
            {
                $ok_upload_image = 0;
            }
            else
            {
                $ok_upload_image = 1;
                $path = $_FILES['uploadImage']['name'];
                $ext = pathinfo($path, PATHINFO_EXTENSION);
                move_uploaded_file($_FILES["uploadImage"]["tmp_name"],$output_users_icons."21.jpg");
            }
           /* END */

            /* Upload Image User */
            if ($_FILES["uploadLogo"]["error"] > 0)
            {
                $ok_upload_logo = 0;
            }
            else
            {
                $ok_upload_logo = 1;
                move_uploaded_file($_FILES["uploadLogo"]["tmp_name"],$output_offices_icons. $_FILES["uploadLogo"]["name"]);
            }
           /* END */

     }
    ?>


text:
Q: Maximise the given equation in less than O(n^2) Given an array how to find the max value of
    (ar[j]-ar[i]-1)*(min(ar[i],ar[j]))

in time O(n) or O(nlogn)

A: If the input is always nonnegative, then there is no point in using anything but the maximum element of ar as ar[j]; any product that doesn't use ar[j] there can be increased by using ar[j]. Thus, we can find the maximum value in O(n) time and try it against all possible values of ar[i] in O(n) time to solve the problem.
If the input is not required to be nonnegative, the maximum product must use the maximum ar[j] or the minimum ar[j]. Again, we can find the maximum and the minimum and try them against all possible ar[i] values.


text:
Q: Multiple inputs to a convolutional neural network with one output? Is there a standard way to input multiple images into a CNN and condense the information down into a singular image in the end? I'm working on an HDR dataset where you have multiple images of the same scene and put them together to form an image with less noise.
What I have tried to do is set the separate images as channels, but I'm unsure if this is appropriate as the outputs were weird.

A: *

*Is this implementable?

Yes! Any neural network, regardless of number or type of layers, is nothing more than some function f: I → O, so as long as your different inputs belong to the same type you can freely pass as many of them through your network as you please, getting equally many outputs on the other side of the black box. These can be in turn used in any way you desire through any other function g: O x O → O' (could be addition, tensor multiplication, concatenation or something fancier like another neural network).

*Does this make sense?

No answer here; this largely depends on what you are expecting your function to be doing, what your data are and what your end-goal is. Are you assuming that all of your inputs obey the same statistical properties or have similar underlying patterns? In that case, you could argue that the same function can model them. Keep in mind that by applying them in parallel (i.e. asynchronously) you're keeping your function blind to potential cross-dependencies between the two inputs, which in some cases makes complete sense. To make this a bit clearer, if your different inputs are the different channels of a single image, I think this is the wrong approach; each channel may convey different information, and keeping your network unaware of how each channel affects each other, while forcing it to create meaningful abstractions using the same function over all of them doesn't sound like a great idea. On the other hand, if your different images are e.g. photos of an object from different angles and the sub-network you're applying them to is some sort of classifier over their features (already obtained through another CNN, for instance), then it could make sense to model both using the same function.


text:
Q: VBA, Vlookup formula object required I am getting object required run-time error '424'.
Dim LastRowTwo As Long, TargetRange As Variant, ws As Worksheet

Set ws = Sheets("Reconciliation")

    TargetRange = ws.Range("B2:B" & LastRowTwo)
        With TargetRange
            .Formula = "=IFERROR(VLOOKUP(A2, 'ATP Final'!$G:$G, 1, FALSE), ""N/A"")"
            .Value = .Value
        End With

How can I fix this error?

A: Targetrange is currently declared as a variant and is missing the Set keyword on assignment. This is causing the line TargetRange = ws.Range("B2:B" & LastRowTwo) to implicitly add a .value and load the range's values into a two dimensional array. You want the actual range object with all its methods and properties.
Dim TargetRange As Range
...
set TargetRange = ws.Range("B2:B" & LastRowTwo)
...


text:
Q: Inequality involving positive real numbers Let $x_1,x_2,\cdots x_n,x_{n+1}$ be any real numbers greater than or equal to $1$.

Then for $n\ge 2,$ I was trying to verify  the validity of the inequality
$$\frac{n-1}{n}\sum_{k=1}^n\frac{1}{1+x_k}+\frac{1}{1+x_{n+1}}+\frac{1}{1+x_1.x_2.\cdots.x_n}\ge \frac{n}{n+1}\sum_{k=1}^{n+1}\frac{1}{1+x_k}+\frac{1}{1+x_1x_2\cdots x_nx_{n+1}}.$$ May I kindly seek your suggestions?

Same result can be tried when $x_1,x_2,\cdots x_n,x_{n+1}$ are non-negative real numbers less than or equal to $1$.

A: An attempt towards the solution:
We need to prove
$$(n^2-1)\sum_{k=1}^n\frac{1}{1+x_k}+\frac{n(n+1)}{1+x_{n+1}}+\frac{n(n+1)}{1+x_1.x_2.\cdots.x_n}\ge n^2\sum_{k=1}^{n+1}\frac{1}{1+x_k}+\frac{n(n+1)}{1+x_1x_2\cdots x_nx_{n+1}},$$ which is équivalent to $$\frac{n}{1+x_{n+1}}+\frac{n(n+1)}{1+x_1.x_2.\cdots.x_n}-\frac{n(n+1)}{1+x_1x_2\cdots x_nx_{n+1}}-\sum_{k=1}^n\frac{1}{1+x_k}\geq 0.$$
When $x_{n+1}=1$  the result is true. But  for very large values of $x_n,x_{n+1} (x_{n}\rightarrow\infty, x_{n+1}\rightarrow\infty)$ the above inequality is not true.
Hope my argument is correct!

A: The inequality is equal to
$$\frac{n-1}{n}\Big(\sum_{k=1}^n\frac{1}{1+x_k}\Big)+\frac{1}{1+x_{n+1}}+\frac{1}{1+x_1.x_2.\cdots.x_n} \ge \frac{n}{n+1}\Big(\sum_{k=1}^{n}\frac{1}{1+x_k}\Big)+\frac{n}{n+1}\Big(\frac{1}{1+x_{n+1}}\Big)+\frac{1}{1+x_1x_2\cdots x_nx_{n+1}}$$

We know that $\frac{n-1}{n}>\frac{n}{n+1}$ hence
$$\frac{n-1}{n}\Big(\sum_{k=1}^n\frac{1}{1+x_k}\Big)\ge\frac{n}{n+1}\Big(\sum_{k=1}^{n}\frac{1}{1+x_k}\Big)$$
Since $1>\frac{n}{n+1}$
$$\frac{1}{1+x_{n+1}}\ge\frac{n}{n+1}\Big(\frac{1}{1+x_{n+1}}\Big)$$
Since $a\le b \implies \frac{1}{a} \ge \frac{1}{b}$ hence
$$\frac{1}{1+x_{n+1}}\ge\frac{1}{1+x_1.x_2.\cdots.x_n.x_{n+1}}$$
Adding the three equations above gives us the inequality we seek. $\ _\square$


text:
Q: Como resolver TypeError: list indices must be integers or slices, not Cliente Estou tentando criar um códiggo que seria como um sistema de barbearia, criei uma classe Cliente e algumas funções dentro dela incluindo uma função para gravar os dados em um Json.
Porém ao tentar executar a função Salvar, exepcificamente em "Funcionario": self.identification,"horario": horariosList[horarioEscolha]  para salvar  em um Json ocorre o seguingte erro: TypeError: list indices must be integers or slices, not Cliente
Como posso resolver este problema?
import json

caminho_arquivo = 'agenda.json'

pessoa = [
{
  "id": 0,
  "nome": "Raquel Matos",
  "funcao": "corte",
  "horarios": [
    "manha", "tarde", "noite"
  ],
  "preco": 1.8
},
{
  "id": 1,
  "nome": "Kessy Alves",
  "funcao": "corte",
  "horarios": [
    "manha", "tarde", "noite"
  ],
  "preco": 1.8
}
]

for horas in pessoa:
    horariosList = (horas['horarios'])
    horariosList1 = (horas['horarios'])
    horariosList2 = (horas['horarios'])

print(horariosList)

#horariosList = ["manha", "tarde", "noite"]

class Cliente:
    def __init__(self, nome= 'not defined', telefone= 'not defined', identification  = 'not defined'):
        self.nome = nome
        # self.funcao = funcao
        # self.horarios = horarios
        self.telefone = telefone
        self.identification = identification

    def Menu_Principal(self):
        print("=-==-=-==-=-==-=-==-=-==-=-==-=")
        print(f"[ {agendar} ] AGENDAR")
        print(f"[ {n2} ] FINANCEIRO")

    def Cliente(self):
        print("=-==-=-==-=-==-=-==-=-==-=-==-=")
        print('CADASTRAR CLIENTE ')

    def HorarioFuncionarios(self):
        id2 = int(self.identification)
        ide = 0 #variavel enumera funcionarios
        for pessoas in pessoa:
            print(f"{ide} - {pessoas['nome']}")
            ide += 1
            #print(list(enumerate(nomesP, 0)))
        for pessoas2 in pessoa:
            print("FUNCIONARIO ESCOLHIDO")
            print(pessoa[id2]['nome'])

    def salvar(self):
        # p1= self.nome
        # p2=self.telefone
        # info = [vars(p1),  vars(p2)]
        info = {'nome': self.nome, 'telefone': self.telefone}
        infoFinal = [
            {
                "name": self.nome,
                "tel": self.telefone,
                "Funcionario": self.identification,
                "horario": horariosList[horarioEscolha]
            }]
        print(info)

        dados = info
        with open(caminho_arquivo, 'w', encoding='utf8') as arquivo:
            json.dump(infoFinal, arquivo, indent=2, ensure_ascii=False)
        return dados
        Cliente.append(info)
agendar = 1
n2 = 2

while True:
    print('ESCOLHA UMA OPÇÃO')
    print(f"[ {agendar} ] Agendar")
    print(f"[ {n2} ] Financeiro")
    opcao = int(input("Informe uma opção? "))
    if opcao == 1:
        nom = Cliente(nome=input('NOME: '), telefone=input('TELEFONE: '))
        nom2 = Cliente(identification=input('Digite o id do funcionario'))
        print(nom2.identification)

        print('horario funcionario***')

        nom2.HorarioFuncionarios()
        print("ESCOLHA UM HORARIO")
        print(list(enumerate(horariosList, 0)))

        horarioEscolha = Cliente(identification=int(input("SELECIONE UM HORARIO PELO ID INDICADO ")))
        if horarioEscolha == 1:
            print(f"HORARIO ESCOLHIDO {horariosList[horarioEscolha]}")
            horariosEscolhido= horariosList[horarioEscolha]

            horariosList.pop(horarioEscolha)
            print("Horarios Disponiveis")
            print(horariosList)

        else:
            print("invalido")

        nom.salvar()

        print(f'++++++++++++++++\n O usuario {nom.nome},\n com o numero de telefone {nom.telefone}\n selecionou o profissional {nom2.identification} no periodo da ')

    elif opcao == 2:
        print('opcao 2')
    else:
        print('opção não existe')

A: É porque "horarioEscolha" é uma instancia de Client e não um inteiro, pela sua lógica ai é só fazer:
horariosList[horarioEscolha.identification]

que vai funcionar. Mas aconselho que reveja sua classe e principalmente sua função que inputa dados pois tá bem confusa e vai gerar mais bugs futuros.


text:
Q: Summing values in read_csv Python I have a table in csv using pandas:
Name     A   B   C
aa       0   5   7
aa       1   2   3
aa       1   5   6
aa       0   8   9
aa       1   8   9
aa       1   8   9
ab       0   8   9
ab       1   8   9
ab       1   8   9
ab       1   8   9
ac       0   8   9
ac       0   8   9

What i need to do is to summ all the C for equal Name if A=1, so the output should be like Name: {first of B: sum(C for this A)}.
I need a separate sum for each patch of 1 in A.
For example, first 1 for aa appears in the second line, so we take B for this (here its 2), then take C. We go to the next line, A=1 again, then we sum its C with the previous C (from the 2nd line). The 4th A=0, so we don't take this string and go ahead. The 5th A=1 again, so we do the first step again: keep B=8 and sum all the next C that have A=1
For example,
aa: {2:3+6, 8:9+9} //here 2 is B when A=1 for the first time
ab: {8: 9+9+9}
ac: {*nothing, because no 1*}

I know it's easy, but i'm new in python and got stuck with iterating through columns

A: I think you need helper column count and then groupby and agg first value by first and sum. Then you need subset by mask df.A == 1 and last you can drop columns A and count:
df['count'] = (df['A'].diff(1) != 0).astype('int').cumsum()
print df
   Name  A  B  C  count
0    aa  0  5  7      1
1    aa  1  2  3      2
2    aa  1  5  6      2
3    aa  0  8  9      3
4    aa  1  8  9      4
5    aa  1  8  9      4
6    ab  0  8  9      5
7    ab  1  8  9      6
8    ab  1  8  9      6
9    ab  1  8  9      6
10   ac  0  8  9      7
11   ac  0  8  9      7

df = df.groupby(['Name','A', 'count']).agg({'B' : 'first', 'C' : 'sum'}).reset_index()
print df
  Name  A  count   C  B
0   aa  0      1   7  5
1   aa  0      3   9  8
2   aa  1      2   9  2
3   aa  1      4  18  8
4   ab  0      5   9  8
5   ab  1      6  27  8
6   ac  0      7  18  8

df = df[df.A == 1]
print df
  Name  A  count   C  B
2   aa  1      2   9  2
3   aa  1      4  18  8
5   ab  1      6  27  8

df = df.drop(['A','count'], axis=1)
print df
  Name   C  B
2   aa   9  2
3   aa  18  8
5   ab  27  8

How I get column count:
print df['A'].diff(1)
0    NaN
1      1
2      0
3     -1
4      1
5      0
6     -1
7      1
8      0
9      0
10    -1
11     0
Name: A, dtype: float64

print df['A'].diff(1) != 0
0      True
1      True
2     False
3      True
4      True
5     False
6      True
7      True
8     False
9     False
10     True
11    False
Name: A, dtype: bool

print (df['A'].diff(1) != 0).astype('int')
0     1
1     1
2     0
3     1
4     1
5     0
6     1
7     1
8     0
9     0
10    1
11    0
Name: A, dtype: int32

print (df['A'].diff(1) != 0).astype('int').cumsum()
0     1
1     2
2     2
3     3
4     4
5     4
6     5
7     6
8     6
9     6
10    7
11    7
Name: A, dtype: int32


text:
Q: how to run a .click on elems parent sibling selector? Below is my most recent attempt:
var aSl = document.querySelector('input[id^="blahblah"]');
aSl.closest("span.k-icon.k-i-expand").click();

It returned:
myjs.js:181 Uncaught TypeError: Cannot read property 'closest' of null
I have also tried parent.sibling in place of .closest above - that returned '...parent is not a function' error.
Below is my mark-up:
::before <--- this is what I'm trying to run .click() on

   <input type="checkbox" tabindex="-1" id="blahblah-blah" class="k-checkbox">
...

Update, I have just tried this as well; per a comment with no avail:
var el = document.querySelector('input[id^="blahblah"]');
el.parentNode.parentNode.click();

A: The closest() method traverses the Element and its parents (heading toward the document root) until it finds a node that matches the provided selector string. Will return itself or the matching ancestor. If no such element exists, it returns null.
What you desire to get is actually a sibling of the parent of aS1, hence the output is null.
You would have got the desired element if the code was like this.

   ::before

        <input type="checkbox" tabindex="-1" id="blahblah-blah" class="k-checkbox">
        ...

Also note that there was no parent element with class name 'k-i-collapse'.

A: As said on the comment, it seems you are mixing jquery's API with DOM API, stick to one of them and you'll get the result (assuming that the selector for blahblah actually finds an object)


text:
Q: Trying to understand the math behind backpropagation in neural nets I am currently trying to understand the math used training neural network, in which gradient descent is used to minimize the error between the target and extracted. I currently following/reading this tutorial
So an example:
Given a network like this:

We wish to minimize the error function being for one training set (x,y)
\begin{align}
J(W,b; x,y) = \frac{1}{2} \left\| h_{W,b}(x) - y \right\|^2.
\end{align}
(question:  Why multiplying a half?)
Which for M training sets would become
\begin{align}
J(W,b)
&= \left[ \frac{1}{m} \sum_{i=1}^m \left( \frac{1}{2} \left\| h_{W,b}(x^{(i)}) - y^{(i)} \right\|^2 \right) \right]
                       + \frac{\lambda}{2} \sum_{l=1}^{n_l-1} \; \sum_{i=1}^{s_l} \; \sum_{j=1}^{s_{l+1}} \left( W^{(l)}_{ji} \right)^2
\end{align}
(question: Why the second term?  and why computing the average of the error than the exact error, and try to minimize it)
Using partial the partial derivative on the cost function, one can compute the gradient in which the weight and bias has to descent to minimize it.
\begin{align}
W_{ij}^{(l)} &= W_{ij}^{(l)} - \alpha \frac{\partial}{\partial W_{ij}^{(l)}} J(W,b) \\
b_{i}^{(l)} &= b_{i}^{(l)} - \alpha \frac{\partial}{\partial b_{i}^{(l)}} J(W,b)
\end{align}
Where $\alpha$ the determine the amount of the gradient to be used.
As far is backpropagation being most usefull here as it provides an efficient way for computing the partial probabilities as such.
\begin{align}
\frac{\partial}{\partial W_{ij}^{(l)}} J(W,b) &=
\left[ \frac{1}{m} \sum_{i=1}^m \frac{\partial}{\partial W_{ij}^{(l)}} J(W,b; x^{(i)}, y^{(i)}) \right] + \lambda W_{ij}^{(l)} \\
\frac{\partial}{\partial b_{i}^{(l)}} J(W,b) &=
\frac{1}{m}\sum_{i=1}^m \frac{\partial}{\partial b_{i}^{(l)}} J(W,b; x^{(i)}, y^{(i)})
\end{align}
(question: Again why average and the second term?)
They they futher explain how one can get derivative for  a training set (x,y)
First they define an error term $\delta^{(l)}_i$ which contains the information "how much of the error in the output was caused by node $i$ in layer $l$". The error seen in the output node $\delta^{(l)}_i$, can easily be computed as:
\begin{align}
\delta^{(n_l)}_i
= \frac{\partial}{\partial z^{(n_l)}_i} \;\;
\frac{1}{2} \left\|y - h_{W,b}(x)\right\|^2 = - (y_i - a^{(n_l)}_i) \cdot f'(z^{(n_l)}_i)
\end{align}
in which $z^{(l)}_i$ is denote the total weighted sum of inputs to unit $i$ in layer $l$, including the bias term. Example: $\textstyle z_i^{(2)} = \sum_{j=1}^n W^{(1)}_{ij} x_j + b^{(1)}_i$  and $a_{i}^(l)$ is the activation of node $i$ in layer $l$ $a^{(l)}_i = f(z^{(l)}_i)$.
(question: Not sure i understand how they derived partial derivative.. I understand why they do that - don't understand the result though)
This is where things begin become weird and my intuition is not following whats going on...
The error term of each node $i$ and layer $l$ can be defined as
$$\delta^{(l)}_i = \left( \sum_{j=1}^{s_{l+1}} W^{(l)}_{ji} \delta^{(l+1)}_j \right) f'(z^{(l)}_i)$$
Which then by some magic give the wanted partial derivatives..
\begin{align}
\frac{\partial}{\partial W_{ij}^{(l)}} J(W,b; x, y) &= a^{(l)}_j \delta_i^{(l+1)} \\
\frac{\partial}{\partial b_{i}^{(l)}} J(W,b; x, y) &= \delta_i^{(l+1)}.
\end{align}

A: Preliminaries
(1) One fact that would seem to helpful to you would be that, if you have
$$
x_1 = {\arg\min_x} \;\;f(x)
$$
Then, if $c\in\mathbb{R}$ and $x_2 = {\arg\min_x} \;cf(x) $, we have $x_1=x_2$. In other words, when optimizing a function, the optimal input is unchanged by multiplication of the energy function by a constant.
This has led to all sorts of random constants being multiplied to energy functions being optimized, to give them a slightly more pleasant flavour. For instance, when the energy function has a squared term, it is common to multiply by $1/2$ so that the inevitable factor of $2$ that comes from differentiation is canceled out. Or, when the energy is the sum of something like $E=\sum_{x\in S} f(x)$, it is common to consider $\tilde{E}=(1/|S|)\sum_{x\in S} f(x)$ instead, since it has the nice interpretation of being the average or expected error.
(2)
The second fact is related to regularization (see also here). Basically, learning models, especially the more powerful ones, can overfit to the data. For instance, when millions of parameters are present, there are probably many ways to produce the same function with different weights.
However, some of these are worse than others. Regularization tries to penalize the more ridiculous ones, to reduce overfitting.
From a Bayesian perspective, this is akin to placing a prior on the parameters.
Answer
(1) Multiplication by $1/2$ is due to fact (1) above; it is merely a notational pleasantry.
(2) [a] The second term is the regularization term. In this case, the idea is that a weight of $1$ is inherently more reasonable than a weight of $10^{100000^{10}}$; the second term prevents this from happening.
Practically speaking, this "gently constrains" the parameter space to models with small weights, to reduce overfitting. In some cases, it can also be practically helpful to sparsify the weights by regularization. [b]
Minimizing the average error, again as above from fact (1), is merely not practically important except insofar as it provides a nicer interpretation.
(3) Same as (2).
(4) I'm not sure which result is confusing you, but it's probably the notation, which is describing a situation more complete than the diagram. In any case, if
\begin{align}
J(W,b; x,y) = \frac{1}{2} \left\| h_{W,b}(x) - y \right\|^2,
\end{align}
for the final layer,
we get the error in the final output node as:
\begin{align*}
\delta^{(n_\ell)}_i &= \frac{\partial}{\partial z_i^{(n_\ell)}} \frac{1}{2}(y-h_{W,b})^2\\ &= (y-h_{W,b})(-1)\frac{\partial}{\partial z_i^{(n_\ell)}}h_{W,b}(x)\\
&= -(y - a_i^{(n_\ell)})\frac{\partial}{\partial z_i^{(n_\ell)}}f(z_i^{(n_\ell)})\\
&= -(y - a_i^{(n_\ell)})\;f'(z_i^{(n_\ell)})\\
\end{align*}
But how do we do the hidden layers for $\ell\leq n_\ell - 1$?
Recall that the output of a node is written:
$$
a^{(\ell+1)}_i = f(z^{(\ell+1)}_i) = f\left( b_i^{(\ell)}+\sum_j W_{ij}^{(\ell)}a_j^{(\ell)} \right)
$$
Then we can see how the output of higher layers varies as the inner layers are altered. This will be important because in backprop we are using the error in the later layers to define the error in the earlier layers. Thus:
$$
\frac{ \partial z^{(\ell+1)}_k }{ \partial W_{ij}^{(\ell)} }
= a_j^{(\ell)}\delta_{ki}
$$
where the $\delta_{ki}$ is the Kronecker delta. Further,
$$
\frac{ \partial z^{(\ell+1)}_j }{ \partial z^{(\ell)}_i }
= \frac{ \partial  }{ \partial z^{(\ell)}_i } \sum_k W_{ji}^{(\ell)} f(z_j^{(\ell)}) + b_j^{(\ell)} = W_{ji}^{(\ell)} f'(z_i^{(\ell)})
$$
Now then, let's consider the rate of change of error at the inner hidden nodes, as its output varies. Keep in mind that the inner layers feed-forward to determine the output of the later layers, but the later layers feed backward to determine the error of the inner layers. Thus the chain rule is over the later layers as
\begin{align}
\delta_i^{(\ell)} = \frac{\partial J}{\partial z_i^{(\ell)}}
= \frac{\partial}{\partial z_i^{(\ell)}}\sum_j
\underbrace{
   \frac{\partial J}{\partial z_j^{(\ell+1)}} }_{\delta_j^{(\ell+1)}}
   \frac{\partial z_j^{(\ell+1)}}{\partial z_j^{(\ell)}}
= \sum_j \delta_j^{(\ell+1)} W_{ji}^{(\ell)} f'(z_i^{(\ell)})
= f'(z_i^{(\ell)}) \sum_j W_{ji}^{(\ell)} \delta_j^{(\ell+1)}
\end{align}
as the linked tutorial states. Then we can compute the variation with respect to the weights at the hidden layer via the chain rule over the later layers as before, writing:
$$
\frac{\partial J}{\partial W_{ij}^{(\ell)}}
=
\sum_k \frac{\partial J}{\partial z_k^{(\ell+1)}}
       \frac{\partial z_k^{(\ell+1)}}{ \partial W_{ij}^{(\ell)} }
= \sum_k \delta_k^{(\ell+1)} a^{(\ell)}_j \delta_{ki}
= \delta_i^{(\ell+1)} a^{(\ell)}_j
$$
using the results we calculated earlier.
Similar methods apply to the derivatives wrt the bias term.


text:
Q: 401 error when using API from CPanel for first time I have used API data from websites like Microsoft, Knowbe4, ninja, ITglue, twitch, etc. However I am having trouble understanding the authentication for Cpanel.
I have an API key that I obtained from the cpanel website.
Cpanel authorization: https://api.docs.cpanel.net/cpanel/tokens/
It says:

Using an API token
To call a UAPI function with an API token, run the following command from the command line:
curl -H'Authorization: cpanel username:APITOKEN' 'https://example.com:2083/execute/Module/function?parameter=value'

So I tried using python but I am getting a 401 error which relates to the password or api key.
Here is my code:
import requests

bluehostapi = "ANAPIKEY"
bluehosturl = "https://cpanel-box5504.bluehost.com:2083/cpsess4830273370/"
header = {"Authorization": "cpanel", "username":bluehostapi}
buuserrequest = requests.get(bluehosturl+"execute/email",headers=header)
print(buuserrequest)

But I always get back:
<Response [401]>

I also tried putting https://cpanel-box5504.bluehost.com:2083/cpsess4830273370/execute/mail into google chrome's address bar directly as the docs said that you can go to the api url directly. However when I did I received an error saying:
{"warnings":null,"status":0,"data":null,"messages":null,"errors":["Failed to load module "": "Cpanel::API::" is not a valid name for a Perl module."],"metadata":{}}

My main goal is to test connecting to cpanel's api so I can retrieve all the usernames and emails of my clients programmably.