text:
Q: Get Latest Updated from a column of folder IDs Hello I have a column with a list of Google Drive folder links and I would like to get latest updated date of all the files contained in the folders.
Example
By looking around I was able to build the following scripts which works fine by giving me the list of all the files contained in the folder and their latest update.
function onOpen() {
  var spreadsheet = SpreadsheetApp.getActive();
  var menuItems = [
    {name: 'UpdateCheck', functionName: 'files'},
  ];
  spreadsheet.addMenu('Menu', menuItems);
}

function files() {
  var ui = SpreadsheetApp.getUi();
  var result  = ui.prompt("Paste the ID of Google Drive Folder");
  var folderId = result.getResponseText();

  var folder = DriveApp.getFolderById(folderId);
  var files = folder.getFiles();
  var output = [];
  while (files.hasNext()) {
    var file = files.next();
    output.push([file.getName(), file.getLastUpdated()]);
  }
  output.sort(function(a, b) {
    return a[0] == b[0] ? 0 : a[0] < b[0] ? -1 : 1;
  });
   SpreadsheetApp.getActiveSpreadsheet().insertSheet().getRange(2, 1, output.length, output[0].length).setValues(output);

However I have to use the UI to open each link, copy and paste the ID from the URL in the input field. I would like to just read the column range, get the IDs from the strings without duplicates and run my script and have my result in a new tab. Any help would be great.

A: I believe your current situation and your goal are as follows.

*

*You have a sheet that the folder links are put to the column "D" in your providing image.

*You want to retrieve the folder ID from the links and want to retrieve the filename and the value of getLastUpdated() of all files in the folders.

*You want to put the retrieved data on a new sheet.
Modified script:
Please set the sheet names of srcSheetName and dstSheetName.
function myFunction() {
  var srcSheetName = "Sheet1"; // Please set the source sheet name.
  var dstSheetName = "Sheet2"; // Please set the destination sheet name.

  // Retrieve folder links from "D2:D" and check the duplication.
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName(srcSheetName);
  var folderIds = [...new Set(sheet.getRange("D2:D" + sheet.getLastRow()).getRichTextValues().flatMap(([d]) => {
    var url = d.getLinkUrl();
    if (url && /^https:\/\/drive\.google\.com\/drive\/folders\/.+/.test(url)) {
      return [url.split("/")[5].trim()];
    }
    return [];
  }))];

  // Create an array for putting to sheet.
  var res = folderIds.flatMap(id => {
    var folder = DriveApp.getFolderById(id);
    var files = folder.getFiles();
    var temp = [];
    while (files.hasNext()) {
      var file = files.next();
      temp.push([file.getName(), file.getLastUpdated()]);
    }
    return temp;
  });

  // Put the array to the destination sheet.
  ss.insertSheet(dstSheetName).getRange(1, 1, res.length, 2).setValues(res);
}

About some unclear points, I guessed as follows.

*

*I couldn't understand the format of folder links in the cells. In this modification, I guessed that the folder link is like https://drive.google.com/drive/folders/###.

*I couldn't understand get the IDs from the strings without duplicates. In this modification, the duplication of retrieved folder IDs is checked.
References:

*

*getValues()

*insertSheet(sheetName)

*setValues(values)
Added:
From the following your replying,

Quick question, when I run it I get an Unexpected error while getting the method or property getFolderById on object DriveApp at line var res = folderIds.flatMap(id => {     var folder = DriveApp.getFolderById(id); it's solvable or should I open another thread?

the folder link was indeed incorrect instead of https://drive.google.com/drive/folders/### the format was https://drive.google.com/corp/drive/u/0/folders/####?resourcekey=#### so I correct the code with /^https://drive.google.com/corp/drive/u/0/folders/.+/.test(url)) {       return [url.split("/")[8].trim()]; but now I get 1CHKEThZJ0P-ISv0g0MoGjCCqdZuuJJyA?resourcekey=0-1gzYTJvJv1XDwF2Hx4HvEQ and I need to find a way to get rid of everything right before the "?"

For this, I modified my proposed script as follows.
Modified script:
function myFunction() {
  var srcSheetName = "Sheet1"; // Please set the source sheet name.
  var dstSheetName = "Sheet2"; // Please set the destination sheet name.

  // Retrieve folder links from "D2:D" and check the duplication.
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName(srcSheetName);
  var folderIds = [...new Set(sheet.getRange("D2:D" + sheet.getLastRow()).getRichTextValues().flatMap(([d]) => {
    var url = d.getLinkUrl();
    if (url) {
      if (/^https:\/\/drive\.google\.com\/drive\/folders\/.+/.test(url)) {
        return [url.split("/")[5].trim()];
      } else if (/^https:\/\/drive\.google\.com\/.+\/drive\/u\/0\/folders\/.+/.test(url)) {
        return [url.split("/")[8].trim().split("?")[0]];
      }
    }
    return [];
  }))];

  // Create an array for putting to sheet.
  var res = folderIds.flatMap(id => {
    try {
      var folder = DriveApp.getFolderById(id);
      var files = folder.getFiles();
      var temp = [];
      while (files.hasNext()) {
        var file = files.next();
        temp.push([file.getName(), file.getLastUpdated()]);
      }
      return temp;
    } catch (e) {
      console.log({id, msg: e.message});
    }
  });

  // Put the array to the destination sheet.
  ss.insertSheet(dstSheetName).getRange(1, 1, res.length, 2).setValues(res);
}

*

*By this modification, 2 kinds of URLs like https://drive.google.com/drive/folders/### and https://drive.google.com/corp/drive/u/0/folders/####?resourcekey=#### can be used, and when an error occurs when the files are retrieved from the folder, you can see the folder ID at the log. And, the script is not stopped.


text:
Q: With PHP / sqlite3, how can I add a column if it does not exist in a table? I'm looking for a way to add a column to a table only if it does not exist yet in a PHP script using sqlite3. It looks like SQL alone cannot help me here, for example with something like
ALTER TABLE items ADD COLUMN IF NOT EXISTS new_col INTEGER;

Well, I was thinking about hacks like trying to run a query and, if it fails, conclude the column doesn't exist yet :
if ($db->querySingle('SELECT new_col FROM items') === FALSE) {
    // False means the query failed
    $db->exec('ALTER TABLE items ADD COLUMN new_col INTEGER');
}

update_stuff_with_new_column($db);

I guess it should work, but what if the query failed for another reason (say, a transaction is running) ?
There are a few other solutions I can think of, but they all look the same : "if the query fails, the column probably does not exist, create it". Is there a better way to do it ?

A: You can find the SQL of the CREATE TABLE statement in the sqlite_master table; you'll need to parse it to see if new_col is defined yet:
sqlite> create table items (col1, col2);
sqlite> select sql from sqlite_master where type = 'table' and name = 'items';
CREATE TABLE items (col1, col2)
sqlite> alter table items add column new_col;
sqlite> select sql from sqlite_master where type = 'table' and name = 'items';
CREATE TABLE items (col1, col2, new_col)

Addendum:
Additional ways to see if a column already exists in a table include:
Try to prepare (sqlite3_prepare_v2) a statement of the form
select ColumnToCheck from TableToCheck;

and see if it gives an error (thanks to Igor Tandetnik!).
Or use the
PRAGMA table_info(myTable)

documented here.

A: php file
===========

<?php

define(DB_USER,'root');
define(DB_PASS,'');
define(DB_NAME,'DATABASENAME');

//Load the class

/* Creating Connection for database where we want to make changes using sql file */

$con = mysql_connect('localhost',DB_USER,DB_PASS) or die ("error in connecting $sitename ");
mysql_select_db(DB_NAME,$con) or die("error in databse selction in $sitename");

/* getting content from sql file where we have updated fields */
$fp= file_get_contents('blank_hotel_version_1.0.sql', true);

/* getting list of create table query from sql file content */

$pattern_gettable = '/CREATE TABLE IF NOT EXISTS (.*?) ;/is';

preg_match_all($pattern_gettable,$fp,$tables);

foreach($tables[0] as $value):
    mysql_query($value,$con) or die(mysql_error());
endforeach;

//exit;

/* getting Database table list */

$tables_db ="*";
if($tables_db == '*')
{
    $tables_db = array();
    $result = mysql_query('SHOW TABLES');
    while($row = mysql_fetch_row($result))
    {
        $tables_db[] = $row[0];
    }
}
else
{
    $tables_db = is_array($tables_db) ? $tables_db : explode(',',$tables_db);
}

foreach($tables_db as $tablename):
     $pattern = "CREATE TABLE IF NOT EXISTS `{$tablename}`";

    foreach($tables[0] as $value):

        if(strpos($value,$pattern)=== false):

        else:

            /*getting columns  list from perticular table query of sql file */

            $pattern_cloumn="/CREATE TABLE IF NOT EXISTS `{$tablename}` \((.*?) PRIMARY KEY/is";
            preg_match_all($pattern_cloumn,$value,$columns);

            /*Replacing comma with # so that while we exploade we can easily make array of columns othere wise it make problem for enum(..) datatype or comment */
            $pattern_cm="/\n/ims";
            $columns[1][0]= preg_replace($pattern_cm,"#",$columns[1][0]);
            $colmn=explode("#",$columns[1][0]);
            array_shift($colmn);

            /*Getting name of columns currently we have columns with sql query like "`id` int(11) not null," and we get column name like 'id' into $columnnames array */
            $columnnames=array();
            foreach($colmn as $cols):
                $pattern = '/`(.*?)`/is';
                preg_match_all($pattern, $cols ,$namecols);

                array_push($columnnames,$namecols[1][0]);
            endforeach;

            /*Getting column names from database table */
            $column_query="SHOW COLUMNS FROM {$tablename}";
            $result_clm=mysql_query($column_query);
            $colum_db_array=array();
            while($row_clm=mysql_fetch_array($result_clm))
            {
                array_push($colum_db_array,$row_clm['Field']);
            }

            foreach($columnnames as $key=>$value_cols)
            {
                /*if column not exists in database table then we add column into table */

                if(!in_array($value_cols,$colum_db_array) && $value_cols!="")
                {

                    if(substr($colmn[$key],strlen($colmn[$key])-2)=="',")
                    {
                        $query_cl="ALTER TABLE {$tablename} ADD ".substr($colmn[$key],0,strlen($colmn[$key])-1);
                    }
                    else
                    {
                        $query_cl="ALTER TABLE {$tablename} ADD ".substr($colmn[$key],0,strlen($colmn[$key])-1);
                    }

                    mysql_query($query_cl) or die(mysql_error());
                }
            }
        endif;

    endforeach;

endforeach;

exit;

?>

Sql File
========

-- --------------------------------------------------------

--
-- Table structure for table `advertising`
--

CREATE TABLE IF NOT EXISTS `advertising` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `image` varchar(255) NOT NULL,
  `title_tag` varchar(255) NOT NULL,
  `alt_tag` varchar(255) NOT NULL,
  `d_order` int(11) NOT NULL,
  `is_visible` varchar(11) NOT NULL DEFAULT 'Y',
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;

--
-- Dumping data for table `advertising`
--

-- --------------------------------------------------------

--
-- Table structure for table `advertising_enquiry`
--

CREATE TABLE IF NOT EXISTS `advertising_enquiry` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `advertising_id` varchar(255) NOT NULL,
  `name` varchar(255) NOT NULL,
  `address` varchar(255) NOT NULL,
  `city` varchar(255) NOT NULL,
  `state` varchar(255) NOT NULL,
  `country` varchar(255) NOT NULL,
  `phone` varchar(255) NOT NULL,
  `mobile` varchar(255) NOT NULL,
  `email` varchar(255) NOT NULL,
  `website` varchar(255) NOT NULL,
  `enquiry` text NOT NULL,
  `budget` varchar(255) NOT NULL,
  `create_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=15 ;

--
-- Dumping data for table `advertising_enquiry`
--

-- --------------------------------------------------------

--
-- Table structure for table `agents`
--

CREATE TABLE IF NOT EXISTS `agents` (
  `id` int(3) NOT NULL AUTO_INCREMENT,
  `agent_name` varchar(150) NOT NULL,
  `contact` varchar(1000) NOT NULL,
  `cat_id` int(3) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=9 ;

--
-- Dumping data for table `agents`
--

-- --------------------------------------------------------

--
-- Table structure for table `amenities`
--

CREATE TABLE IF NOT EXISTS `amenities` (
  `id` int(3) NOT NULL AUTO_INCREMENT,
  `am_name` varchar(200) NOT NULL,
  `type` enum('H','R','RE') DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=234 ;

--
-- Dumping data for table `amenities`
--

This may help you thanks

redpajama_set_name: RedPajamaStackExchange


text:
Q: Bootstrap: Logo not centering on landing page I have a full screen background image for my website landing page with my logo in the centre. The website uses Bootstrap and is fully responsive. The logo is vertically and horizontally aligned in my browser window and when the window is resized the logo correctly stays in the centre. But when viewing on a phone or tablet the image background images resizes correctly but the logo does not stay in the centre of the page, but is situated to the right of the screen with half of it obscured.
Any ideas on how I might rectify this? The website landing page is live you can find it at www.burnser.com
Here's the code:

And here's the CSS I'm using:
#full-screen-background-image {
z-index: -999;
min-height: 100%;
min-width: 1024px;
width: 100%;
height: auto;
position: fixed;
top: 0;
left: 0;
}

.centered {
position: fixed;
top: 50%;
left: 50%;
/* bring your own prefixes */
transform: translate(-50%, -50%);
}

Any help would be much appreciated.

A: Looks fine on my phone. Try another browser and also try to prefix transform.
.centered {
  position: fixed;
  top: 50%;
  left: 50%;
  /* bring your own prefixes */
  -webkit-transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
}

Btw, 1MB background image is huge. You should blur that noise out to reduce size of image.


text:
Q: Getting error (800A0035) referencing a line of code that has already been executed I am writing a script right now which makes use of the File System Object to read a text file and later delete it. The part of the code in which this occurs I have written as a function. I have tested this function, along with some other functions which it depends on, and it works fine. But in the final product it is just one part of a script with 16 different functions/subroutines. After incorporating it into the final product, this file fails to work. Or, at least Windows script host tells me that it doesn't.
I have tested using Echo statements to track down the issue, since the line that WSH references should have executed properly, based on the fact that code after the line in question works when I run the script. I get an Echo when I echo after the function call (I have written a simple function to make the script wait before calling more functions, and the echo statement is after that, so the function definitely completes execution before the error occurs). I have also tried inserting an echo statement into the beginning of the next function to be called (literally directly after I instantiate the second function), and then I don't get an echo.
Here is the function in question. The line the error references is the one with Set objRECID.
Function PullRecords
  Set objWSH = CreateObject("WScript.Shell")
  Set objFSO = CreateObject("Scripting.FileSystemObject")

  strIP = "192.168.1.185"
  strOutFileCMD = ".output OUT" & strIP & ".txt"
  strOutFile = "C:\Users\" & GetLoggedOnUsername & "\Documents\SQLite3\" & "OUT" & strIP & ".txt"     'Output of each element grab
  strCommand = "FROM ZCDataField WHERE RECORD_ID="
  strRECIDPath = "C:\Users\" & GetLoggedOnUsername & "\Documents\SQLite3\" & "RECID" & strIP &     ".txt" 'Output of GetRECID
  strFinalCSVPath = "C:\Users\" & GetLoggedOnUsername & "\Documents\SQLite3\" & strIP & ".csv"
  strSQLite3Path = "C:\Users\" & GetLoggedOnUsername & "\Documents\SQLite3\"
  strProcName = "SQLite3.exe"

  'Element ID's (for reference)
  'intpt_item = "275426222"
  'intpt_description = "275466434"
  'intpt_custitem = "275466431"
  'intpt_qty = "275466713"
  'intpt_name = "275466710"
  'intpt_date = "275435183"
  'intpt_unixmil = "275578832"

  'Options for text files
  intForReading = 1
  intForWriting = 2
  intForAppending = 8
  boolOverwriteTrue = True
  boolOverwriteFalse = False

  Set objCSV = objFSO.CreateTextFile(strFinalCSVPath,boolOverwriteTrue) 'Creates final CSV to be     written to/
  Set objRECID = objFSO.OpenTextFile(strRECIDPath,intForReading)

  'Cycles through records
  Do Until objRECID.AtEndOfStream
   strRECID = objRECID.ReadLine
   Set objELID = objFSO.OpenTextFile(strSQLite3Path & "Element IDs.txt",intForReading) 'Need this      here so that script restarts at beginning of file each time.
   'Cycles through elements
   Do Until objELID.AtEndOfStream
    Set objBAT = objFSO.CreateTextFile(strSQLite3Path & strIP & dblUnixT &     ".bat",boolOverwriteTrue)
     objBAT.Write ("cd /D C:\Users\" & GetLoggedOnUsername & "\Documents\SQLite3")
     objBAT.WriteLine
     objBAT.Write ("sqlite3 " & strIP & ".db < " & strIP & ".txt")
    objBAT.Close

    Set objBAT = Nothing
    Set objCMDS = objFSO.CreateTextFile(strSQLite3Path & strIP & ".txt",boolOverwriteTrue)
     objCMDS.Write (".mode tabs")
     objCMDS.WriteLine
     objCMDS.Write (strOutFileCMD)
     objCMDS.WriteLine
     strELID = objELID.ReadLine  'Gets ELEMENT_ID
     objCMDS.Write ("SELECT VALUE_TXT,VALUE_NUM " & strCommand & strRECID & " AND ELEMENT_ID=" &     strELID &  ";") 'Gets element
     objCMDS.WriteLine
     objCMDS.Write (".exit") 'Exits SQLite3
    objCMDS.Close
    Set objCMDS = Nothing
    objWSH.Run(strSQLite3Path & strIP & dblUnixT & ".bat")

    'Makes script wait until BAT is done.
    intRunning  = 1
    Do Until intRunning = 0
     intRunning = IsRunning(strProcName)
    Loop

    Wscript.Sleep(500)

    Set objOut = objFSO.OpenTextFile(strOutFile)
    strOut = objOut.ReadLine
    objOut.Close
    Set objOut = Nothing
    objCSV.Write strOut & ","
    Loop
  'Make string of line and then delete 1 character on right to get rid of ,. Then replace line.
   objCSV.Write Chr(8)
   objCSV.WriteLine
   objELID.Close
   Set objELID = Nothing
  Loop

  objCSV.Close
  objRECID.Close
  Set objCSV = Nothing
  Set objRECID = Nothing
  objFSO.DeleteFile strRECIDPath

  'objFSO.DeleteFile strOutFile

  InvertText(strFinalCSVPath)
  PullRecords = strFinalCSVPath

  Call FuncSubEndToken
End Function

In case it is useful, here is the FuncSubEndToken function that I call.
Function FuncSubEndToken
 intFuncSubEndToken = 1
End Function

And here is how I am using it when I call the PullRecords Function.
Call PullRecords
 'FuncSubEndTokenWait
 Do Until intFuncSubEndToken = 1
 Loop
 intFuncSubEndToken = 0

Any help would be greatly appreciated.
Edit: I have tried using On Error Resume Next and I just get wscript hanging after the parts that I posted. It doesn't even enter the next function.
Edit 2: I have tried commenting out the line that deletes the file that is needed for the PullRecords function, even though that line is executed after the function is done with the file. It now is apparent that is calling this function twice and another function twice (and then it errors out part way through that). I have looked and both of these functions are only ever called once (and they are not in loops, so that is definitely not the issue). I do call a function and pass it the output of both of these functions, in the order that they seem to be running. But I am not here calling the functions themselves. But perhaps wscript thinks that I am?
Edit 3: I have deleted the function that uses the return of the other two functions (well, commented it out), and I still get the same issue.

A: So, I have now figured out the issue. It would seem that I was somewhat misinformed on how functions work when trying to get their output. I thought that you called a function and then the function name was the output. But, it would seem that you do not need to use a call statement to execute a function. So, while trying to use the output of my functions I have been inadvertently calling them.


text:
Q: Vue.js unit testing best practice It's a general question. but i am curious to ask: there are many packages for vue js unit testing.

*

*Vue Test Utils

*Vue Jest

*Vue Cypress
which one would be best practice or recommended for enterprise project?

A: These are not comparable, as each of them serve a different purpose.
From documentation of each of these libraries:
vue-test-utils

Vue Test Utils is the official unit testing utility library for Vue.js.

vue-jest

... To teach Jest how to process *.vue files, we will need to install and configure the vue-jest preprocessor.

cypress-vue-unit-test

A little helper to unit test Vue components in the open source Cypress.io E2E test runner

If you have no preference and looking for a place to start, then definitely start with official documentation: Choosing a test runner


text:
Q: How to set form input as a variable in a Json printing php file? I have two php files, file A and file B that get data from the same database.  File A displays the data in a paragraph on the site while File B is used by AJAX to display data in a graph created with graph.js. Both files do their job, except.
In both files I have a variable called $employeeNumber which is the name of an input field in a form used by the user to input whichever employee number they would like to view the data of. File A allows me to use
$employeeNumber = $_POST["employeeNumber"]; to get the input and displays data accurately but File B won't allow me to use $_POST[], $_REQUEST[], or $_GET[]. Instead it forces me to hardcode the unique number. This is not desired.
File B is meant to get the input entered into the form, and update the graph with the data relating to the employee number entered.
I used echo $row["empnumber"]; for File A to display the data and for File B I used print json_encode($data); Could this be where I went wrong?
File B (Doesn't update graph unless I hardcode employeeNum)
<?php

header('Content-Type: application/json');

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydb";

//BELOW IS WHERE THE ISSUE LIES.
//WHEN I HARDCODE THE UNIQUE NUMBER LIKE THIS, THE GRAPH UPDATES ACCORDINGLY. WITH ACCURATE DATA FROM THE EMPLOYEE THAT THE UNIQUE NUMBER BELONGS TO.

$employeeNum = 8020;

//THIS (BELOW) I ANTICIPATED WOULD GET THE EMPLOYEE NUMBER FROM THE USERS INPUT IN THE FORM WHICH I HAVE NOW INCLUDED BUT IT PRODUCES AN ERROR.

$employeeNum = $_POST["employeeNum"]; //this is line 9

//HERE IS THE ERROR WHEN I OPEN THE Graphdata.php FILE

Notice:  Undefined index: employeeNum in C:\wamp64\www\Graphdata.php on line 9

Warning:  Invalid argument supplied for foreach() in C:\wamp64\www\Graphdata.php on line 22

Fatal error:  Uncaught Error: Call to a member function close() on bool in C:\wamp64\www\Graphdata.php:26
Stack trace:
#0 {main}
  thrown in C:\wamp64\www\Graphdata.php on line 26

//Connect to database
$dbconnect = new mysqli($servername, $username, $password, $dbname);

//If failed to connect
if(mysqli_connect_error()){
    die("Database connection error".mysqli_connect_error());
}
//Create query
$sql = "SELECT Mathematics, English, Afrikaans, Geography, Physics, History, Life_Orientation FROM studentresults WHERE employeeNumber = $employeeNum";

//Run query
$result = $dbconnect->query($sql);

//Produce result
$data = array();
foreach ($result as $row){ //THIS IS LINE 22
    $data[] = $row;
}

$result -> close();

$dbconnect -> close();

//Print the result
print json_encode($data);
?>

File A (Works fine)

<?php

//connecting to database
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "mydb";
    $employeeNum = $_POST["employeeNum"];

    $connect = new mysqli($servername, $username, $password, $dbname);

//checking connection

    if (mysqli_connect_error()) {
        die ("Database connection failed: ". mysqli_connect_error());
    }

// Query the database
        $sql = "SELECT Salary FROM myEmployees WHERE employeeNumber = $employeeNum";

        $result = $connect->query($sql);

//print out result
while($row = mysqli_fetch_array($result)) {
        echo $row["English"];
    }

$result -> close();
?>

Here's the AJAX code making the request
$.ajax({

//Graphdata.php is the name of FILE B

    url: "http://localhost/Graphdata.php",
    type: "GET",
    success : function(data){
        console.log(data);

        var Salary = [];
        var timeWorked = [];
        var Age = [];
        var userid = [];

        for(var i in data){

            userid.push("UserID " + data[i].userid);
            Salary.push(data[i].Salary);
            Age.push(data[i].Age);
            timeWorked.push(data[i].timeWorked);

        }
//Create the graph
        var ctx = document.getElementById('myChart').getContext('2d');

var chart = new Chart(ctx, {

Here is the form code.
<form action="Graphdata.php" method="post">

Username

<input class="inp1" type="text" name="name">

Password

<input class="inp2" type="password" name="email">

Employee ID

<input id = "employeeNum" class="inp3" type="int" name="employeeNum">

A: The problem is that when you call via AJAX, you are not passing any data along to the back end.
Further, when you use method=GET, the $_POST array will be empty.
Change your method to POST, and include the data like this:
$.ajax({
  method: "POST",
  url: "http://localhost/Graphdata.php",
  data: {employeeNum: someValue}
  ...
})


text:
Q: Bootstrap login button not the color I'm expecting In my app/views/users/sessions/new.html.slim, I have:
.container
  = form_for(resource, as: resource_name, url: session_path(resource_name), html: {class: "form-signin"}) do |f|
    h2.form-signin-heading
      = t('users.mailer.registrations.sessions.new.please_sign_in')
    .form-group
      .sr-only
        = f.label t('users.sessions.new.email_address')
      = f.email_field :email, class: 'form-control form-signin email_input', autofocus: true, placeholder: "Email Address", required: ""
      .sr-only
        = f.label t('users.sessions.new.password')
      = f.password_field :password, class: 'form-control form-signin password_input', autofocus: true, placeholder: "Password", required: ""
    - if devise_mapping.rememberable?
      .checkbox
        label
          = f.check_box :remember_me
          = t('users.sessions.new.remember_me')
    .form-group
      = f.submit t('users.mailer.sessions.new.log_in'), class: "form-control button.btn.btn-lg.btn-primary.btn-block"
    .form-group
      .col-md-offset-4.col-md-8
       = render "devise/shared/links"

In my assets/stylesheets/signin.css.scss, (I import it into applicatio.css.scss), I have:
.form-signin {
  max-width: 330px;
  padding: 15px;
  margin: 0 auto;
}
.form-signin body {
  padding-top: 40px;
  padding-bottom: 40px;
  background-color: #ee
}
.form-signin .form-signin-heading,
.form-signin .checkbox {
  text-align: center;
  margin-bottom: 10px;
}
.form-signin .checkbox {
  font-weight: normal;
}
.form-signin .form-control {
  position: relative;
  height: auto;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  padding: 10px;
  font-size: 16px;
}
.form-signin .form-control:focus {
  z-index: 2;
}
.form-signin .email_input {
  margin-bottom: -1px;
  border-bottom-right-radius: 0;
  border-bottom-left-radius: 0;
}
.form-signin .password_input {
  margin-bottom: 10px;
  border-top-left-radius: 0;
  border-top-right-radius: 0;
}

I am expecting the login button to be blue, but it's white. Any idea what I'm doing incorrectly?

A: Wrong class on submit form helper, you should make it like this:

 f.submit t('users.mailer.sessions.new.log_in'), class: "form-control btn btn-lg btn-primary btn-block"

Divide classes with spaces.

A: You can create your own button the following way (You'll have to change the color hex code)
CSS:
  .btn-example {
  color: #fff;
  background-color: #0000ff;
  border: 0px solid #0000ff !important;
  }

  .btn-example:hover {
  color: #fff;
  background-color: #1a1aff;
  }

Your html button class would be:
form-control btn btn-example

EDIT: Since your using SASS it would be:
.btn-example {
color: #fff;
background-color: #0000ff;
border: 0px solid #0000ff !important;
&:hover {
  color: #fff;
  background-color: #1a1aff;
  }
}


text:
Q: Mongoose findOneAndUpdate with Schema _id set to false Typically, I would search / find the document. If a document is found, then I would update it... if not found then I would create it.
I'm Looking for a more efficient way to do this, from reading the docs - I've cobbled together the following (I'm also using hapi.js)
    const Schema = mongoose.Schema;

    let ProductSchema = new Schema({
        sku: String,
        active: Boolean,
        category: String,
        description: String,
        freeShipping: Boolean
    });

.... ProductSchema is exported, and required as 'Products'.. its used to create a new product. I pass in my payload (already validated through Joi).
     let product = new Products(request.payload);

        Products.findOneAndUpdate(
            { sku : request.payload.sku },
            {$set: product },
            { upsert: true,  new: true, runValidators: true },
            function(err, result) {
            if (err) {
                console.error(err);
                return reply(Boom.badRequest('Error saving product'));
            }

            return reply(result);

        });

*

*upsert: true - says create if not found.

*new: true - returns the    newly created or updated document (the
result)

*runValidators: true -    should force the data (the product) to be validated against the schema.

However, I hit a problem with instantiating the product - Mongoose automatically inserts an "_id".
"_ids" are immutable. So when I try to update, I get the following error:
{ MongoError: After applying the update to the document {_id: ObjectId('59cc33812e36f3d0272dc28e') , ...}, the (immutable) field '_id' was found to have been altered to _id: ObjectId('59cc3c21e0938d99c2716989')

So, my first thought was - create the object using literal notation... I then have control to omit the "_id"...
However, doing this meant that the object was not created / validated by the schema...
I then read that you can suppress the creation an _id, by setting _id to false in your schema. I did this, and now get an object thats validated without an _id. Updating / creating now works without throwing errors.
Suppressing the "_id" field in my schema doesn't seem like much of an issue, as the Mongo server will always create a new _id for every entry. I'm using the SKU as my unique key.
However, I'm mindful that I arrived here through poking around and trying to figure things out.
So the nub of my question is - is my approach flawed?


text:
Q: Create a workflow/dialogue where prompt updates existing field? I am relatively new to Dynamics CRM and I have an issue on the Opportunity entity where users don't update the 'Est. Close Date'.
Therefore a lot of the dates are in the past - is there a way that a dialogue/box can appear where the user enters a new date which updates the 'Est. Close Date' field?

A: As mentioned from your comment,
Req is when user opens Opportunity Record and if Est close date is empty or < Today's date then force user to update Est close Date.
Solution:
You can achieve this using Javascript.

*

*Run your Javascript on event (Onload) of opportunity

*Check if your Form is of type update formContext.ui.getFormType();
You can check that here

*

*Now check if Est. Close Date is empty or less than today's date

*if condition is satisfied that means user should enter new value for field Est. Close Date

*So how can we force user to enter new value?

*First make that field empty and then make that field Business Req.

*In this way user will have to update value

There are few more conditions you can check such as
Onchange of Est. Close Date
check if Est. Close Date always >= todays date so that user will not enter false date.
You will have to test your all use cases.


text:
Q: url_for raises BuildError, but view with that name and arguments exists I want to add autocomplete to a text field.  However, when I try to use url_for to pass the autocomplete url to JavaScript, I get werkzeug.routing.BuildError BuildError: ('autocomplete', {}, None).
Priting out app.url_map shows <Rule '/autocomplete' (HEAD, OPTIONS, GET) -> autocomplete>.
How do I fix this error?
@app.route('/autocomplete',methods=['GET'])
def autocomplete():
    URL = 'http://www.amis.pk/DistrictCities.aspx'
    City_Data = scrape(URL)
    City_Data = sorted(City_Data, key=lambda x: x.name)
    return jsonify(json_list=City_Data)

{{ url_for("autocomplete") }}


text:
Q: Accessing customer contact details with QBSDK According to the QBSDK v12 and v13 OSR documentation, the SDK returns contact details (phone, email, etc.) for each of the contacts associated with a customer. In other words,  tags within the contact. But when I query a customer that has multiple  contacts associated with it, all I get is:
<Contact>Thing One</Contact>  (for the contact flagged as primary)
<AltContact>Thing Two</AltContact>   (for the contact flagged as secondary)
<AdditionalContactRef>
  <ContactName>Main Phone</ContactName>   (the main phone # for CUSTOMER, not contact)
  <ContactValue>425-555-1212</ContactValue>
</AdditionalContactRef>
etc...

The phone # and email set up for each contact is not included in the response XML. This is with QB Premier 2014 and QBSDK v13. Am I missing something, or does QB not yet return the contact details, which are supposedly supported by the SDK?

A: If I understand the question correctly, you are looking for the ContactsRet element.
You should be able to request ContactsRet element using the IncludeRetElement element.
From the OSR:
<CustomerRet>
  <ContactsRet>                                 <!-- optional, may repeat -->
    <ListID>       IDTYPE       </ListID>       <!-- required -->
    <TimeCreated>  DATETIMETYPE </TimeCreated>  <!-- required -->
    <TimeModified> DATETIMETYPE </TimeModified> <!-- required -->
    <EditSequence> STRTYPE      </EditSequence> <!-- required -->
    <Contact>      STRTYPE      </Contact>      <!-- optional -->
    <Salutation>   STRTYPE      </Salutation>   <!-- optional -->
    <FirstName>    STRTYPE      </FirstName>    <!-- required -->
    <MiddleName>   STRTYPE      </MiddleName>   <!-- optional -->
    <LastName>     STRTYPE      </LastName>     <!-- optional -->
    <JobTitle>     STRTYPE      </JobTitle>     <!-- optional -->
    <AdditionalContactRef>                      <!-- must occur 0 - 5 times -->
      <ContactName>STRTYPE</ContactName>        <!-- required -->
      <ContactValue>STRTYPE</ContactValue>      <!-- required -->
    </AdditionalContactRef>
  </ContactsRet>
</CustomerRet>


text:
Q: Check if form has submitted in aspx all I have an ASP form. When the page loads it runs a method using the Page_Load event handler. When the user submits the form if it didn't correctly revalidate it returns to the page but I do not want the method for the Page_Load to run.
Is there a way I can check if the form has been submitted previously without needing to check a specific field within the form.
Thanks for any help you can provide.

A: In your Page_Load method, only do your processing if IsPostBack is false)
//Page_Load method
If (!IsPostBack)
{
  // Code in here should only run when the page first loads.
  // It will not run if a user clicks a button on the page.
}

A: Try this:
if(IsPostBack){

    Response.Write("Form posted!");

}

http://msdn.microsoft.com/en-us/library/system.web.ui.page.ispostback.aspx


text:
Q: Android SIP profile locked after reinstall I'm using the SIP stack in Android 2.3.x+ (actually testing on Motorola Xoom though) and have successfully got a softphone working.  However, I uninstalled the app (without unregistering the SIP profile, so it is still registered).  Upon reinstalling the app, when using the same profile details (which is a requirement - don't want to change phone numbers/domains every time I uninstall), android says:
only creator or radio can query on the profile

So I can never use that profile again, as I can never become the creator as I uninstalled the app!
This seems like a huge flaw - the user would have to know that he must logout of the service before uninstalling, and if he doesn't, the app becomes useless!
Am I missing something obvious?  Can I get access to this profile, or delete it, in a user-friendly way?
Thanks,
Ed

A: Rebooting device fixed the problem.


text:
Q: Output of first order system does not become 0 when its input is 0 - solver settings? I am simulating the following first order system (ode45 10^-3 relative tolerance - default settings):

The scope (magenta - square wave, yellow - filter output):

The pulse generator makes a square wave. The funny thing is that the output of the first order system does not become 0 when its input is 0 (when the square wave comes back to 0).
I guess it's a solver issue. Have you seen this before? I have some 0 comparisons in my code so I should change those to some tolerance levels. Is this a good solution? Or should I change the solver settings?

A: I assume this is because the frequency of the square wave is too fast and there's not enough time for the system dynamics to come back to to zero. Try reducing the frequency of the square wave.
You might also want to specify a maximum step size in the solver settings other than the default to improve the resolution of the plot (e.g. 1s). The default max step size is the simulation stop time divided by 20 so it can be quite coarse.

A: As suggested in another answer, the problem here is that you are letting the solver take too large a time step.  The default "maximum step size" is set to "auto".  What this means is a step size of (StopTime-StartTime)/50.  You seem to have set a large Stop Time, and hence the max step size is very large.
If you need to run the simulation for a long time then you need to change the step size from its default to something much smaller.


text:
Q: React Native Expo - Does document directory path get modified on App update? In my application i save a batch of images locally using the Expo FileSystem and storing their fully uri in redux (file://......). I transform the image to base64 and store this in the document directory, as a file, whenever an image is taken. When the user uploads the batch of images to firebase I utilze the uploadBytes function, thus converting the base64 file to bytes. However, when I update the app through Testflight or App Store I am not able to view or upload images that already have been taken. Is this because the Document directory path is modified upon update?
Docs for filesystem: https://docs.expo.dev/versions/latest/sdk/filesystem/

A: Fixed: Seems like updating the app does change the file path. Therefore, it was solved by first fetching the relative document path and appending the desired file e.g FileSystem.documentDirectory + ${nameOfFile}


text:
Q: jQuery ajax issue with search I'm working on the functionality of searching images in a ajax based div which is also loading the data in a div container.
I have the following code and it works fine, if I am not executing any search criteria. If I add search, it throws error in all browsers in jquery min.js file. I am using version 1.11.1 for this. Different browsers show different errors.
jQuery code:
$(document).ready(function() {
    $("#finder").blur(executeFunction);
    function executeFunction(page) {
        page = typeof parseInt(page) == "number" ? page : 1;
        $.ajax
        ({
            type: "POST",
            url: "find.php",
            data: {
                page: page,
                search: encodeURIComponent( $('#finder').val() )
            },
            success: function(msg)
            {
                $(document).ajaxComplete(function(event, request, settings)
                {
                    $("#container").html(msg);
                });
            }
        });
    }
    executeFunction(1);
});

HTML code:
<input type="finder" id="finder" />

Without search all work fine..
Here is the error I received in Firefox:
TypeError: 'initUIEvent' called on an object that does not implement interface UIEvent.

...unction(a,b){var c,d=[],e=function(a,b){b=m.isFunction(b)?b():null==b?"":b,d[d.l...

Chrome Error:
Uncaught TypeError: Illegal invocation jquery-latest.min.js:4e jquery-latest.min.js:4Vc jquery-latest.min.js:4Vc jquery-latest.min.js:4Vc jquery-latest.min.js:4Vc jquery-latest.min.js:4Vc jquery-latest.min.js:4Vc jquery-latest.min.js:4m.param jquery-latest.min.js:4m.extend.ajax jquery-latest.min.js:4loadData (index):112m.event.dispatch jquery-latest.min.js:3r.handle

Opera Error:
Uncaught RangeError: Maximum call stack size exceeded

every time i search, the error counter is increasing with same error message
IE 11 Error:
Argument not optional

A: I did not try recreating this issue just a hunch.
typeof parseInt(page) == "number"

The above statement is always true. If page is event-object the parseInt of page is NaN which will return true for the above statement.
I think the following will be better
$("#finder").blur(function(e) {
   executeFunction(1);
});

Other things.
You are binding one instance of following ajaxCompleteEvent every time an ajax request complete. In other words the result is being written to the page multiple times.
      $(document).ajaxComplete(function(event, request, settings){
            $("#container").html(msg);
      });

Why don't you simply use
$("#container").html(msg);

in its place?


text:
Q: Суммирование данных preg_match_all Всем привет!
Жутко подтупливаю, есть функция поиска слов в тексте, произвожу поиск по циклу, после если слова нашлись, мне нужно получить сумму всех найденных слов, но что-то я не могу понять как это сделать. Код снизу, вопрос как суммировать $result найденных данных?
$url = "В разделе отдельные промышленные металлодекторы интернет-магазина  представлено оборудование от ведущих мировых производителей.";
$filt = array ('промышленные','мировых,оборудование');
function txtsearch($url, $filt) {

foreach ($filt as $filter)
    { preg_match_all("/(?<![\w\d])$filter(?![\w\d])/siu", mb_strtolower($url), $result);
        echo $result;
    }
    }

A: Как я понимаю, надо всего лишь воспользоваться array_count_values для подсчёта.
Ну и сделать косметическую правку в виде implode('|', $filterArr).
Пример:
$text = <<<TEXT
В разделе отдельные промышленные промышленные промышленные
металлодекторы интернет-магазина
представлено оборудование от ведущих мировых производителей. супер пупер мировых производителей!
TEXT;

$filterArr = array('промышленные','мировых','оборудование');

preg_match_all("/(?<![\w\d])".implode('|', $filterArr)."(?![\w\d])/siu", mb_strtolower($text), $searchResult);

$filterCountValues = array_count_values($searchResult[0]);

foreach ($filterCountValues as $word => $count) {
    echo 'слово "' . $word . '" встретилось ' . $count . ' раз(а)
';
}

В $searchResult[0] будет массив:
    Array (
        [0] => промышленные
        [1] => промышленные
        [2] => промышленные
        [3] => оборудование
        [4] => мировых
        [5] => мировых
    )

Вывод:
слово "промышленные" встретилось 3 раз(а)
слово "оборудование" встретилось 1 раз(а)
слово "мировых" встретилось 2 раз(а)

P.S. Возможно нужен вывод количества раз всех слов, даже если они не встречались, тогда цикл такой:
foreach ($filterArr as $word) {
    $tpl = 'слово "' . $word . '" встретилось ';
    $tpl .= isset($filterCountValues[$word]) ? $filterCountValues[$word] : 0;
    $tpl .= ' раз(а)
';

    echo $tpl;
}

A: function txtsearch($url, $filt) {

 $count_txtsearch = 0;
foreach ($filt as $filter)
    {
        preg_match("/(?<![\w\d])$filter(?![\w\d])/siu", mb_strtolower($url), $result);

        $count_txt = count($result);
        $count_txtsearch+=$count_txt;

    }
        if ( $count_txtsearch > 0) {
        return 1;
        } else {
        return 0;
        }
    }


text:
Q: FileSystemWatcher not detecting changes properly I was trying to make an application which can popup a notify message whenever a new row is added to the database.i was using mysql and changed the default engine to csv engine so that i can use the FileSystemWatcher to detect any changes.The filesystemwatcher is triggering whenever a row is deleted but the problem is its not triggering changed event when a new row is added to the database.I also observed that when a row is deleted the "Date Modified" is changing but when I add a new row its not updating. Please help me.
private void button1_Click(object sender, EventArgs e)
{
    FileSystemWatcher fsw = new FileSystemWatcher();
    fsw.Path = "C:\\xampp\\mysql\\data\\doubts\\";
    fsw.EnableRaisingEvents = true;
    fsw.Changed += new FileSystemEventHandler(func);
}

private void func(Object obj,FileSystemEventArgs e)
{
    notifyIcon1.Icon = SystemIcons.Application;
    notifyIcon1.BalloonTipText =
        "Addition of new row to the database detected...";
    notifyIcon1.ShowBalloonTip(4000);
}

A: I would recommend that you poll the database periodically to check for changed records.
If your query is expensive, you could create an AFTER INSERT or AFTER UPDATE trigger which inserts into another table, then poll that table.
If this still is not sufficient, you can do this: From your application, run a command like
SELECT "WaitForChanges", SLEEP(999);

Create a trigger which kills this select via the KILL QUERY command: How to do this from a stored procedure.


text:
Q: TNS Protocol adapter error while starting Oracle SQL*Plus Whenever I try to login into SQL*Plus (11g Standar Edition Win 64) I get an error related to some connection error.
I try to login as sys as sysdba and provide the password.
All the services are started. I'm on Windows 7.
Any help would be appreciated.

A: Ensure the OracleService is running. I keep running into this error, but when I go into Services, find OracleServiceXE and manually start it, the problem is resolved. I have it set to start automatically, but sometimes it just seems to stop on its own; at least, I can't find anything I am doing to stop it.

A: Try typing all of this on the command line:
sqlplus / as sysdba

As what you are doing is starting sqlplus and then using sys as sysdba as the user-name which is incorrect as that is not a valid user. By using the above command Oracle is using your system login credentials to access the db.
Also, I would confirm that the sqlplus executable you are running is the correct one by checking your path - ensure it is in the bin of the server installation directories.

A: Use this command, in command prompt
sqlplus userName/password@host/serviceName

A: You are getting ORA-12560: TNS:protocol adaptor error becuase you didn't start the Oracle database.
You can start Oracle database like this.
From START-> select Oracle Database 11g Express Edition( 11g or what ever your database type.you can find this from All Programs).
Then inside this folder  there is a DB icon with green color spot.
It is the Start Service icon.Click it.Then it will take some seconds and start the service.

After getting the above message,again try to connect through the SQL plus command line by giving user name and password.

A: Enter SQL*Plus with:
sqlplus /nolog

And then:
connect sys@<SID> AS sysdba

A: Try
sqlplus sys/<your password>@<your SID> as sysdba

A: Go to Start --> Run--> type " services.msc"
Select the OracleService name, Right Click, Start.
Wait for a while and then your service will start. Then go to your sql command line window and try to connect to your user. I hope you can do that now.

A: You might have set oracle not to start automatically. Goto Start and search for Services. Scroll down and look for OracleServiceORCL (or OracleServiceSID). Double click and change startup type to automatic if it is set as manual.

A: Another possibility (esp. with multiple Oracle homes)
set ORACLE_SID=$SID
sqlplus /nolog
conn / as sysdba;

A: The major issue might be the oracle database itself may not have started.
So, you need to manually go via

run command -> services.msc

check for OracleXEService surely, it may be disabled

right click go to properties-> set it to Automatic and press Ok. Then
  just right click again and start.

This will start
your database making you to connect to it
Finally, In sqlplus command line,
connect as sysdba
enter username as admin
then press enter, you'll be connected

A: Make sure your oracle services are running automatically.
Just press Win+R. Type services.msc in textbox then press O to find oracle services.
In your PC name might be like OracleserviceXYZ.
Right click on highlighted services.


text:
Q: Divergence of sum containing number of divisors function. Show that
$\sum_{n\ge{2}}\frac{d(n)}{n\log^2n}$
is divergent.
I've tried to do this using the comparison test, i.e looking for a divergent series with a summand smaller than the summand in the given sum, but the obvious choices ($\frac{1}{n\log^2n}$) seem to converge. Can the Abel test and the divergence of $\sum_{n\ge{2}}d(n)$ (which is determined by the limit as $x\rightarrow\infty$ of the asymptotic expansion) bee used to somehow state that the given sum is divergent? If not what test should be used?

A: This is a partial answer.
If you prove that you are allowed to use Cauchy's condensation test, you can observe that
$$\sum_{n\geq 2} \frac{2^nd(2^n)}{2^n \log^2 2^n} = \frac{1}{\log^2 2}\sum_{n\geq 2} \frac{n+1}{n^2}$$
is a divergence series, hence your series is divergent.


text:
Q: Cordova 6.3.1 plugin.xml set minSdkVersion doesn't work I'm working on a plugin for cordova and would like to set the minimum sdk version. However it isn't overwritten when I try to use these options in the plugin.xml file:
<platform name="android">
    <preference name="android-minSdkVersion" value="16" />
    <preference name="android-targetSdkVersion" value="23" />
</platform>

or in the manifest tag
<config-file target="AndroidManifest.xml" parent="/manifest">
     <uses-sdk android:minSdkVersion="16" android:targetSdkVersion="23" />
</config-file>

These ways are both phonegap ways to set the sdk versions and, if I'm correct, still cordova ways. But the first one gives an error:
Failed to install 'plugin.demo':Error: Variable(s) missing: ANDROID-MINSDKVERSION, ANDROID-TARGETSDKVERSION

And the second option just add a new row with uses-sdk, which also creates a lot of errors.
How do I set the sdk version in cordova (v6+)?

A: <config-file target="res/xml/config.xml" parent="/*">
    <preference name="android-minSdkVersion" value="15" />
</config-file>


text:
Q: how it possible to search in atom or sublime text with Logical Operators I wan't to know how can i use Logical Operators like

& (and)

or

|| (or)

in find and replace panel in sublime or atom editor.
tanx

A: Enable Regular Expressions (It's going to be the symbol at the bottom right that looks like .*), and then you can do something like @media|span in the search bar.


text:
Q: Number of faces of convex hull If you have $n$ points in $d$-dimensional Euclidean space, the number of faces of the convex hull is potentially exponential I understand. How can this be proved?

A: Here is an example: Consider the $2d$ points $\pm e_i$, where $(e_1,\ldots, e_d)$ is the standard basis of ${\mathbb R}^d$. Their convex hull $C^d$ is a "generalized octahedron", called crosspolytope:
$$C^d=\left\{{\bf x}\in{\mathbb R}^d\ \biggm|\ \sum_{i=1}^d |x_i|\leq1\right\}\ .$$
$C^2$ is a square with sidelength $\sqrt{2}$, $C^3$ an octahedron. In general $C^d$ has $2^d$ simplicial facets, corresponding to the $2^d$ possible choices of the sign when choosing $+e_i$ or $-e_i$ for $1\leq i\leq d$ as vertices of a facet.

A: It seems that can be proved the converse, because the convex hull of a subset $A$ of $d$-dimensional Euclidean space is a union of $d$-dimensional simplexes with vertices from $A$, by Carathéodory Theorem; so your set is a union of no greater than $\binom n{d+1}$ simplexes. :-)


text:
Q: How many ideals in the number field $\mathcal O_K=\mathbb Z[\sqrt{-5}]$ corresponding to norm $18=3^2\cdot 2$ Let $K=\mathbb Q(\sqrt{-5})$, so $\mathcal O_K=\mathbb Z[\sqrt{-5}]$.
This requires the follow-up question because the norm is now not squarefree.
So now the question how many ideals we can find in $\mathbb Q(\sqrt{-5})$ corresponds to norm $18$
Now $(2)= (2,1+\sqrt{-5})^2=\mathfrak p^2$ and $(3)= (3,1+\sqrt{-5})(3,1-\sqrt{-5})=\mathfrak q \mathfrak q'$
So can we say that any ideal norm $18$ should be combination of $\mathfrak p, \mathfrak q, \mathfrak q'$? I think no, because if we eliminate one of them the norm should drop (since $(2)$ is ramified and has no couple prime ideal with the same norm which can replace it in a possible combination).
So how to attack this problem?

A: Let $I \subset O_K$ be an ideal of norm $18$. Let $\mathfrak{r} \supset I$ be a prime ideal, then the norm of $\mathfrak{r}$ (a power of its residue characteristic) divides the norm of $I$ which is $18$, so the residue characteristic of $\mathfrak{r}$ is $2$ or $3$, so $\mathfrak{r}$ is $\mathfrak{p}$, $\mathfrak{q}$ or $\mathfrak{q}'$.
It follows that $I$ can be written as $\mathfrak{p}^a\mathfrak{q}^b(\mathfrak{q}')^c$ for some integers $a,b,c \geq 0$.
Then use the norm to find how many triples $(a,b,c)$ do the trick.


text:
Q: Deadlock occurring in a Non Clustered Column store Index ( MS SQL Server) I have created Non Clustered Column store index for one of my table (For Example :ClientData is the table name) which contains about 100 columns and more than 2 million rows. I noticed multiple Dead locks after creating column store indexes .
While creating the index , i have some SQL jobs which should run continuously, and those SQL Jobs contains multiple transactions and these transactions are using same table (For Example :ClientData is the table name ) to insert/delete/update the records . When i run the sql query to check the locked objects, i noticed SQL query is returning locked Object name along with Transaction name and some other columns in a result set.  When i checked the transaction name from result set, i noticed same transactions which are used in Stored procedure to run SQL job .
Will transaction causes any issues ?
If Issues with Transactions from Continuously running SQL JOB, How do i avoid dead locks With out stopping my SQL JOB
Could anyone help me on this ?
I have used below query to check locked objects
SELECT  L.request_session_id AS SPID,
DB_NAME(L.resource_database_id) AS DatabaseName,
O.Name AS LockedObjectName,
P.object_id AS LockedObjectId,
L.resource_type AS LockedResource,
L.request_mode AS LockType,
ST.text AS SqlStatementText,
ES.login_name AS LoginName,
ES.host_name AS HostName,
TST.is_user_transaction as IsUserTransaction,
AT.name as TransactionName,
CN.auth_scheme as AuthenticationMethod
FROM    sys.dm_tran_locks L
JOIN sys.partitions P ON P.hobt_id = L.resource_associated_entity_id
JOIN sys.objects O ON O.object_id = P.object_id
JOIN sys.dm_exec_sessions ES ON ES.session_id = L.request_session_id
JOIN sys.dm_tran_session_transactions TST ON ES.session_id = TST.session_id
JOIN sys.dm_tran_active_transactions AT ON TST.transaction_id = AT.transaction_id
JOIN sys.dm_exec_connections CN ON CN.session_id = ES.session_id
CROSS APPLY sys.dm_exec_sql_text(CN.most_recent_sql_handle) AS ST
WHERE   resource_database_id = db_id()
ORDER BY L.request_session_id

Thanks,
Shankar


text:
Q: MS Access runtime error 2115 In Ms Access, I have two unbound combo-boxes: StateBox and DVPCBox.  StateBox is simply a list of U.S. states and DVPCBox contains Employee Names from a query based on the value of StateBox.
I'm trying to set the value of DVPCBox equal to the first item in its list.  Since the list of Employees is based on the value of StateBox, I need the value of DVPCBox to update every time StateBox changes.  I tried the following:
Private Sub StateBox_AfterUpdate()
    Me.DVPCBox.Requery
    If (Me.DVPCBox.ListCount = 1) Then
        Me.DVPCBox.SetFocus
        Me.DVPCBox.ListIndex = 0 //<-Error here
    End If
End Sub

But I got runtime error 2115 - The macro or function set to the BeforeUpdate or ValidationRule property for this field is preventing Microsoft Office Access from saving the data in the field.
The strangest thing to me is that I'm not even using the BeforeUpdate Event or ValidationRule (as far as I'm aware.)

A: ItemData(0) is the first combo box value.  So set the combo equal to that.
Private Sub StateBox_AfterUpdate()
    Me.DVPCBox.Requery
    If (Me.DVPCBox.ListCount >= 1) Then
        Me.DVPCBox.SetFocus
        'Me.DVPCBox.ListIndex = 0 //<-Error here
        Me.DVPCBox = Me.DVPCBox.ItemData(0)
    End If
End Sub

I also changed ListCount >= 1 because I assumed you wanted to do the same thing when the combo includes 2 or more rows.


text:
Q: Crontab : better make 10 cron or one cron calling 10 files? I'm using crontab since a long time and i was wondering if it's better to make 10 cron or to make 1 cron calling 10 files?
My cron task look like that :
*/1 * * * * wget -o /dev/null -O /dev/null "http://localhost/website1/task.php"
...
*/1 * * * * wget -o /dev/null -O /dev/null "http://localhost/website20/task.php"

And i got like 40 or 50 cron task in total (all calling for some pages on localhost, at different intervals)
So i would like to know if it's not better to make only one task calling a file which will include the php files for my 20 websites, like :
cron task n1 =>
*/1 * * * * wget -o /dev/null -O /dev/null "http://localhost/call_task.php"

with "call_task.php" calling for :
http://localhost/website1/task.php
to
http://localhost/website20/task.php

Regards,

A: Both methods will work, but I would always try to group files together. This makes it much easier to manage your cron jobs.
You could also create shell skripts for your jobs, e.g.:
hourly.sh:
wget "http://my/hourly/url1"
wget "http://my/hourly/url2"

15minutes.sh:
wget "http://my/15minutes/url1"
wget "http://my/15minutes/url2"

...and set these in your cronjob:
0 * * * * * sh hourly.sh
0,15,30,45 * * * * sh 15minutes.sh

This way you get your scripts easily manageable, you can keep track what to download in which frequency and it keeps your crontab small and manageable.


text:
Q: Хэширование алгоритмом CRC Объясните как работает этот алгоритм ибо хорошей, понятной информации по этому алгоритму я не нашел. Все описывают в математических формулах, а я хочу понять саму суть алгоритма. То как он работает, а в частности, что он он делает с поступившими данными.

A: Задача crc очень проста - в соответствии с поступившими байтами поставить им в соответствие 4 байта (или 2, crc бывают разные). При этом выполняются следующие условия:

*

*у одинаковых входных данных будет одинаковый crc.

*у разных входных данных будет разный crc, но может быть и одинаковый.

*у входных данных, которые отличаются совсем немножко (несколько бит), скорее всего будут разные crc.

Само вычисление описано в википедии и в конце концов сводится к математическим формулам. Но если отбросить все это, то в сухом остатке остается в основном xor и сдвиг. То есть, с входного потока читаем данные, сдвигаем/ксорим.
Возьмем в википедии очень простой crc8 и разберем
/*
  Name  : CRC-8
  Poly  : 0x31    x^8 + x^5 + x^4 + 1 - над его выбором сидят математики и криптоаналитики
  Init  : 0xFF над этим также
  Revert: false
  XorOut: 0x00
  Check : 0xF7 ("123456789") контрольное значение, что бы проверить реализацию
  MaxLen: 15 байт(127 бит) - обнаружение
    одинарных, двойных, тройных и всех нечетных ошибок
*/
unsigned char Crc8(unsigned char *pcBlock, unsigned int len)
{
    // начальное значение. Выбирается с потолка или экспериментально
    unsigned char crc = 0xFF;
    unsigned int i;

    while (len--) // пока у нас есть данные
    {
        crc ^= *pcBlock++; // ксорим очередной байт

        for (i = 0; i < 8; i++)
            // применяем полином. тут просто ксорим и/или сдвигаем.
            crc = crc & 0x80 ? (crc << 1) ^ 0x31 : crc << 1;
    }

    return crc;
}

В принципе, если полином пуст, то результат это просто последовательно проксоренные байты (для crc8) или int'ы (для crc32).
В википедии описаны разлиные значения полиномов и начальных значний (все те магические константы) для различных модификаций алгорима. Какое выбрать - это сложная задача, тут математики пусть сидят и думают. Для своих приложений главное, чтобы с двух сторон был один и тот же алгоритм.


text:
Q: multipartRequest to send multiple images to server using volley ,but it is taking more time to upload images I am taking photos from camera and keeping in a list of upto 5 images .To send these imagelist, I am using the volley multipartRequest but it is taking a lot of time to upload the images to server . I even tried compressing the images into byte string format before storing in the list
Any solution?


text:
Q: leaflet js: javascript listener to draw circle around a map Attempting to draw a circle around a location on a map using a javascript listener. The map is rendered using leaflet js. This code works, but only when clicking on the map layer and not the markers. Is there a way for it to listen to marker on click as well and draw a circle around it?
// Declare a global variable to store the circle layer
var clickCircle;

// Disable the default double-click zoom behavior
map.doubleClickZoom.disable();

// Add a click event listener to the map
map.on('click', function(e) {
  // If the circle layer already exists, remove it from the map
  if (clickCircle) {
    map.removeLayer(clickCircle);
  }

  // Create a new circle layer using the latitude and longitude of the click event
  clickCircle = L.circle(e.latlng, {
    color: 'steelblue',
    fillColor: 'steelblue',
    fillOpacity: 0.5,
    radius: 4023
  }).addTo(map);
});

A: Yes you can add a click listener to a marker and then get the latlng from the marker:
marker.on('click', (e)=>{
   var markerLayer = e.target;

  // If the circle layer already exists, remove it from the map
  if (clickCircle) {
    map.removeLayer(clickCircle);
  }

  // Create a new circle layer using the latitude and longitude of the click event
  clickCircle = L.circle(markerLayer.getLatLng(), {
    color: 'steelblue',
    fillColor: 'steelblue',
    fillOpacity: 0.5,
    radius: 4023
  }).addTo(map);
});


text:
Q: SharePoint CSS Registration adding "25" to "/Style%2520Library/" for font definitions We have font definition files that are referenced from a CSS file that is included in our SharePoint Online Master Page.  They are .woff, .svg, .avg, .ttf, .otf.   The CSS is loaded with CSS Registration like this:
<SharePoint:CssRegistration Name="/Style%20Library/content/app/css/app.css" runat="server"/>
For some reason SharePoint will append a 25 to the Style Library path where we have the fonts stored where the HTTP escape code for space is, turning %20, or space, into %2520.  "Style Library" is the only part of the URL with a space in it.
While it should be /Style%20Library/ it's coming as /Style%2520Library/
In the CSS file, which is in a folder under "Style Library", they are referenced like this:
@font-face {
    font-family: "Effra Light";
    src: url(../css/fonts/Effra_Std_Lt.woff),
         url(../css/fonts/Effra_Std_Lt.svg),
         url(../css/fonts/Effra_Std_Lt.ttf),
         url(../css/fonts/Effra_Std_Lt.eot),
         url(../css/fonts/Effra_Std_Lt.otf);
}

And finally I've noticed that this error does not happen as frequently when directly opening a page via a URL for the first time.  It happens more frequently when a Page is re-loaded by SharePoint, like when a User clicks on a List operation or changes the Page to Edit Page mode.  Obviously, one of the SharePoint mechanics is altering the URL.  How to prevent this?
Perhaps a related ticket here

A: I had the same problem. In the masterpage, we had this:
<SharePoint:CssRegistration Name="<% $SPUrl:~sitecollection/Style%20Library/Branding/css/Seattle.css %>" runat="server" />

For some reason, SharePoint re codifies the %20 adding %2520 that gives error in some cases not loading the CSS.
To solve this, replace the %20 for a space in the registration, like this:
<SharePoint:CssRegistration Name="<% $SPUrl:~sitecollection/Style Library/Branding/css/Seattle.css %>" runat="server" />

SharePoint will transform Style Library to Style%20Library automatically without the 25, doing the trick and working just fine.


text:
Q: Problems creating a Batch script to detect files and directories that have dots in their names The problem I'm having is that my file names use dots, but no spaces.
My folder names use spaces, not dots.
For example, I have a file named:
C:\Files\One.Two.Three.Four.12.34.5.pdf

The corresponding folder is named:
C:\Files\One Two Three Four

I would like a script that would detect all of the .pdf files in the C:\Files directory, all of the folders in the C:\Files directory, and then figure out which folder the file should be placed into based on the naming structure given previously.
I'm having a problem with the dots being in the file name, but not in the folder name, as well as the fact that there's the extra 12.34.5 at the end of the file name that is not in the corresponding folder name. Also, the extra stuff after the One.Two.Three.Four tend to change randomly. It's not always 12.34.5.
Any help I could get would be greatly appreciated.

A: If you want this to happen:
file: "cat.dog.bird.tree.2345.pdf" to folder: "cat dog bird tree"
file: "egg.bacon.bread.coffee.efgh.pdf" to folder: "egg bacon bread coffee"
file: "mother.father.sister.brother.pdf" to folder: "mother father sister brother"
file: "one.two.three.four.5678.pdf" to folder: "one two three four"

...you can capture the first 4 tokens of the file name and put them back together with spaces instead of dots to form the folder name.
@echo off
for /f "delims=" %%A in ('dir /s /b *.pdf') do (
    for /f "tokens=1-4 delims=." %%B in ("%%~nA") do (
        echo file: "%%A" to folder: "%%B %%C %%D %%E"
        )
    )

Note: this assumes that all .pdf files in the folder where the batch script is, and all subfolders, have this format: token1.token2.token3.token4 followed by some characters (or no more characters), then the .pdf extension.


text: Q: Evaluation of $\int_0^\infty\frac{-\ln{x}}{x^2+1}\ln\left(1-\frac{\ln{x}}{x^2+1}\right)\,dx$? The numerical approximation for this intergral is $$\eqalign{J&=-\int_0^\infty\frac{\ln{x}}{x^2+1}\ln\left(1-\frac{\ln{x}}{x^2+1}\right)\,dx\\&\approx0.98484651030802740204425597709883071906753522\dots}$$ Since $\ln x\geq-\ln\left(1-\frac{\ln{x}}{x^2+1}\right)$ holds for all $x\gt 0$, and knowing that $\int_0^\infty\frac{\ln^2(x)}{x^2+1}dx=\frac{\pi^3}{8}$, it can be concluded that $J$ must converge. $J$ bears slight similarity to this question, but the methods used in its answer don't seem readily applicable. I've tried making the substitution $x=e^{-y}$ to get $$\eqalign{J&=\int_{-\infty}^{\infty}\frac{y}{e^y+e^{-y}}\ln\left(1+\frac{y}{e^{-2y}+1}\right)dy\\&=\frac{1}{2}\int_0^\infty y\,\mathrm{sech}(y)\ln\left(\frac{2\cosh(y)+ye^y}{2\cosh(y)-ye^{-y}}\right)dy,}$$ but I'm lost on how to proceed from there. Does $J$ have a closed form? I certainly hope so, even if it involves special functions.


text:
Q: What GNU/Linux command-line tool would I use for performing a search and replace on a file? What GNU/Linux command-line tool would I use for performing a search and replace on a file?
Can the search text, and replacement, be specified in a regex format?

A: Consider Ruby as an alternative to Perl.  It stole most of Perl's one-liner commandline args (-i, -p, -l, -e, -n) and auto-sets $_ for you like Perl does and has plenty of regex goodness.  Additionally Ruby's syntax may be more comfortable and easier to read or write than Perl's or sed's.  (Or not, depending on your tastes.)
ruby -pi.bak -e '$_.gsub!(/foo|bar/){|x| x.upcase}' *.txt
vs.
perl -pi.bak -e 's/(foo|bar)/\U\1/g' *.txt
In many cases when dealing with one-liners, performance isn't enough of an issue to care whether you use lightweight sed or heavyweight Perl or heaveier-weight Ruby.  Use whatever is easiest to write.

A: sed 's/a.*b/xyz/g;' old_file > new_file

GNU sed (which you probably have) is even more versatile:
sed -r --in-place 's/a(.*)b/x\1y/g;' your_file

Here is a brief explanation of those options:

-i[SUFFIX], --in-place[=SUFFIX]
edit files in place (makes backup if extension supplied)
-r, --regexp-extended
use extended regular expressions in the script.

The FreeBSD, NetBSD and OpenBSD versions also supports these options.
If you want to learn more about sed, Cori has suggested this tutorial.

A: sed, the stream editor, and yes, it uses regex.

A: Perl was invented for this:
perl -pi -e 's/foo/bar/g;' *.txt

Any normal s/// pattern in those single quotes. You can keep a backup with something like this:
perl -pi.bak -e 's/foo/bar/g;' *.txt

Or pipeline:
cat file.txt | perl -ne 's/foo/bar/g;' | less

But that's really more sed's job.


text:
Q: Delphi 2010 won't include Large icons We're just adding support for Window 7 to our in-house applications and we're having problems with including support for large icons to the applications.
I've created a .ico file in IcoFX with the default range of icons included, and assigned this to the project in Delphi 2010.  However when I run the application the icon displayed is the default (32x32?) icon.
Is the problem that I'm compiling the application on a Windows XP machine rather than on Windows 7?
[Update] I've confirmed that XE2 includes all the icon sizes on compile - certainly when compiling on Windows 7.

A: It might by the Windows IconCache database. This is one problem I've run into in similar situations. Some Delphi development machines still show icons from several years back because the IconCache only stores the path, not any hash of the file's content.
Click on this link to find out how to clear the IconCache:
https://www.google.com/search?q=reset+iconcache+windows


text:
Q: Javascript onClick"display: none;" doesn't work I have a an image that when you click, this function runs.
function img(num) {
    var src = "images/main" + num + ".jpg";
    document.getElementById("popover-image").src = src;
    $("#sheet").css("display", "block");
}

When you click on the "X" (image), this function runs:
function close() {
    $("#sheet").css("display", "none");
}

but it doesn't work.
Here is how my image is set up:
<img src="images/x.png" alt="Exit" onclick="close()" />

A: John Koerner's code:
$("#closeButton").click(function () {
    $("#sheet").css("display", "none");
});

Your event handler wasn't being attached properly.

A: You can do like this also, by using class name
( function($) {
  $(".btn-remove").click(function() {
    $(this).css("display", "none");
  });
} ) ( jQuery );

A: We're all a little baffled that you read how to call the jQuery .css function but not .show(), hide(), or attr().  For what it's worth, here's the link to the hide function page. JQuery is the answer. I can't think of a reason not to use it everywhere.
I think what you're trying to do is:
$(document).ready( function() {
  $("img").on("click", function(num) {
     var src = "images/main" + num + ".jpg";
     $("#popover-image").attr("src", src);
     $("#sheet").attr("display", "block");
  });
  $("img[alt=Exit]").on("click", function() {
     $("#sheet").attr("display", "none");
  });
});


text:
Q: Insert an HTML icon within a Javascript new div In this Django project, there is a Javascript function creating a new div in which we display some data.
    for (var i = 0; i < files.length; i++) {
        var newDiv = document.createElement('div');
        newDiv.setAttribute("class","files_div");
        //Call the helper function to check if it's a PDF
        newDiv.setAttribute("onclick","check_files(this)")
        console.log(files[i]) //Print the files
        newDiv.innerHTML = files[i];
        divParent.appendChild(newDiv);
    }

I need to add icons next to this data. For example, a pdf icon if it's a pdf file.
How do you add icons in Javascript once a new div is created?

A: Have you considered a css-based solution on this? You can add an icon to any element using pseudo elements. This adds another element next to .pdf which you can style to fit your purpose. Using background-image allows you to add an icon.

.pdf {
  padding-left: 35px;
  position: relative;
}

.pdf:before {
  content: "";
  height: 20px;
  width: 20px;
  display: block;
  background: url("https://via.placeholder.com/20");
  position: absolute;
  left: 0;
}

PDF


text:
Q: error while installing Symfony , Declaration DependencyInjection PSR php, what to do? Use:
symfony new my_project_nasdame --version=lts
[OR]
composer create-project symfony/website-skeleton my_project_name
[OR]
symfony new test_project332
php7.4
Everywhere a mistake
    lexcodfh@artek:~/tmp [130] $ ~/.symfony/bin/symfony new test_new_project
    * Creating a new Symfony project with Composer
     [KO]
Script cache:clear returned with error code 255
!!
!!  Fatal error: Declaration of Symfony\Component\DependencyInjection\ServiceLocator::has(string $id) must be compatible with Psr\Container\ContainerInterface::has($id) in /home/l/lexcodfh/tmp/test_new_project/vendor/symfony/dependency-injection/ServiceLocator.php on line 46
!!  Symfony\Component\ErrorHandler\Error\FatalError {#89
!!    -error: array:4 [
!!      "type" => 64
!!      "message" => "Declaration of Symfony\Component\DependencyInjection\ServiceLocator::has(string $id) must be compatible with Psr\Container\ContainerInterface::has($id)"
!!      "file" => "/home/l/lexcodfh/tmp/test_new_project/vendor/symfony/dependency-injection/ServiceLocator.php"
!!      "line" => 46
!!    ]
!!    #message: "Compile Error: Declaration of Symfony\Component\DependencyInjection\ServiceLocator::has(string $id) must be compatible with Psr\Container\ContainerInterface::has($id)"
!!    #code: 0
!!    #file: "./vendor/symfony/dependency-injection/ServiceLocator.php"
!!    #line: 46
!!  }
!!
Script @auto-scripts was called via post-update-cmd

  unable to run /home/l/lexcodfh/.local/bin/composer create-project symfony/skeleton /home/l/lexcodfh/tmp/test_new_project  --no-interaction: exit status 255

    lexcodfh@artek:~/tmp [1] $

Solution that is not applicable on hosting:
https://github.com/symfony/symfony/issues/40393
Need help

A: Use the apt remove php7.4-psr php-psr command for Debian-based distributions


text:
Q: Using unique short and double value I have a C array of shorts and an array of longs. I want to be able to define when one of the array slots is not able to be filled by a function that calls it because there is insufficient or missing data. The valid values in both cases can be positive or negative, but I can safely assume that the values will never come close to the maximum value that can be placed in a short or a double.
This is a Windows 64-bit app, and I have been using SHRT_MAX as the short unique number. My questions are:

*

*What is the equivalent of SHRT_MAX that I could use for double?

*Is there a better way of doing this rather than resorting to SHRT_MAX and double max?

A: I assume you're using the maximum value to indicate a null parameter in the array. This is a common technique and is totally valid.
As for the max double, you want DBL_MAX from <float.h>.

A: The macros are there for exactly the reason you are using them - so this is good (and portable)
Have a look at DBL_MAX

A: 1) You can use DBL_MAX from float.h or numeric_limits<double>::max()
2) Using the maximum values seems fine as long as you're sure that they will never be "normal" values. Otherwise you could use a little object that knows whether the number was changed:
struct Input
{
    short value;
    bool isTransformed;

    Input() : value(0), isTransformed(false) {}
};

A: You can use a signaling NaN (numeric_limits::signaling_NaN). That way, if somebody tries to use it, they will take a floating point exception.


text:
Q: Tag incorrectly enumerated as MIFARE Classic, SAK = 32 I have a Sony Xperia Z3. I am using it to interact with MIFARE Classic smart cards.
When using a native MIFARE card, I'm able to read the card correctly.
However if I'm using a MIFARE Classic emulated, I get a SAK that is not correct. In stead of 0x38 I get 0x20 (32) and the following error when using  MifareClassic.get(tag)
java.lang.RuntimeException: Tag incorrectly enumerated as MIFARE Classic, SAK = 32

I don't know why my mobile incorrectly reads the SAK.
The same card is correctly read on other devices supporting MIFARE as a Nexus S, etc.
Any idea why this exception?
TA

A: Try to use this patch as tag = cleanupTag(tag) before calling MifareClassic.get(tag)
For more information read MifareClassicTool Sony Z3 issue
private Tag cleanupTag(Tag oTag){
    if (oTag == null)
        return null;

    String[] sTechList = oTag.getTechList();

    Parcel oParcel = Parcel.obtain();
    oTag.writeToParcel(oParcel, 0);
    oParcel.setDataPosition(0);

    int len = oParcel.readInt();
    byte[] id = null;
    if (len >= 0) {
        id = new byte[len];
        oParcel.readByteArray(id);
    }
    int[] oTechList = new int[oParcel.readInt()];
    oParcel.readIntArray(oTechList);
    Bundle[] oTechExtras = oParcel.createTypedArray(Bundle.CREATOR);
    int serviceHandle = oParcel.readInt();
    int isMock = oParcel.readInt();
    IBinder tagService;
    if (isMock == 0) {
        tagService = oParcel.readStrongBinder();
    } else {
        tagService = null;
    }
    oParcel.recycle();

    int nfca_idx = -1;
    int mc_idx = -1;
    short oSak = 0;
    short nSak = 0;

    for (int idx = 0; idx < sTechList.length; idx++) {
        if (sTechList[idx].equals(NfcA.class.getName())) {
            if (nfca_idx == -1) {
                nfca_idx = idx;
                if (oTechExtras[idx] != null
                        && oTechExtras[idx].containsKey("sak")) {
                    oSak = oTechExtras[idx].getShort("sak");
                    nSak = oSak;
                }
            } else {
                if (oTechExtras[idx] != null
                        && oTechExtras[idx].containsKey("sak")) {
                    nSak = (short) (nSak | oTechExtras[idx].getShort("sak"));
                }
            }
        } else if (sTechList[idx].equals(MifareClassic.class.getName())) {
            mc_idx = idx;
        }
    }

    boolean modified = false;

    if (oSak != nSak) {
        oTechExtras[nfca_idx].putShort("sak", nSak);
        modified = true;
    }

    if (nfca_idx != -1 && mc_idx != -1 && oTechExtras[mc_idx] == null) {
        oTechExtras[mc_idx] = oTechExtras[nfca_idx];
        modified = true;
    }

    if (!modified) {
        return oTag;
    }

    Parcel nParcel = Parcel.obtain();
    nParcel.writeInt(id.length);
    nParcel.writeByteArray(id);
    nParcel.writeInt(oTechList.length);
    nParcel.writeIntArray(oTechList);
    nParcel.writeTypedArray(oTechExtras, 0);
    nParcel.writeInt(serviceHandle);
    nParcel.writeInt(isMock);
    if (isMock == 0) {
        nParcel.writeStrongBinder(tagService);
    }
    nParcel.setDataPosition(0);

    Tag nTag = Tag.CREATOR.createFromParcel(nParcel);

    nParcel.recycle();

    return nTag;
}

A: The SAK value is not a magic value that you could use to distinguish different NFC tags. Instead it is a bit masked value that defines some capabilities of the RF protocol.
Unfortunately the google Android code uses the SAK for mifare card identification as you can see in this code here: MifareClassic.java
What happens in your Xperia Z3 is probably that the NFC controller and NFC stack correctly detect the tag as Mifare compatible and report it as such. Once you try to use the tag you run into the problems you've mentioned.
The Nexus S is likely running a fixed version of the MifareClassic.java code and avoids the problem.
What can you do about it: From an application perspective nothing really. It's a bug in the Android OS. If you have root access you could do it the hard way and patch the member function on the fly.


text:
Q: BASH MySQL Query to Comma Separated File I have the following bash script:
#!/bin/sh

MYSQLHOST="mysql.remote-host.com"
MYSQLDB="mysqldb"
MYSQLTABLE="table"
MYSQLUSER="user"
MYSQLPASS="pass"
MYSQLDUMP="Report/report.csv"
LOG="Report/report.log"

MYSQLOPTS="--user=${MYSQLUSER} --password=${MYSQLPASS} --host=${MYSQLHOST} ${MYSQLDB}"

echo "Report Begin: $(date)"
 echo "MySQL Dump Begin: $(date)" >> ${LOG}
  echo "SELECT ${MYSQLTABLE}.created_at, ${MYSQLTABLE}.product_options FROM ${MYSQLTABLE} WHERE ${MYSQLTABLE}.product_id=1 ORDER BY ${MYSQLTABLE}.created_at" | mysql ${MYSQLOPTS} > ${MYSQLDUMP}
 echo "MySQL Dump End: $(date)" >> ${LOG}
echo "Report Successful: $(date)"

This ouputs my MySQL Query into a "TAB" separated file report.csv.  However, I need to have it output to a "COMMA" separated file.  I realize I could create another script to convert this file from TAB to COMMA separated, however, I'd rather save the step if I can.  So how can I have MySQL dump the file in comma separated format?
EDIT:
I did find this solution: How do you output MySQL query results in csv format (to the screen, not to a file)?
However I can't seem to get it to work:
echo "SELECT CONCAT_WS(',', ${MYSQLTABLE}.created_at, ${MYSQLTABLE}.product_options) FROM ${MYSQLTABLE} WHERE ${MYSQLTABLE}.product_id=1 ORDER BY ${MYSQLTABLE}.created_at" | mysql ${MYSQLOPTS} > ${MYSQLDUMP}

Doesn't work :(

A: Run the following:
echo "SELECT CONCAT_WS(',', ${MYSQLTABLE}.created_at, ${MYSQLTABLE}.product_options) FROM ${MYSQLTABLE} WHERE ${MYSQLTABLE}.product_id=1 ORDER BY ${MYSQLTABLE}.created_at" | \
mysql ${MYSQLOPTS}  | tr '\t' ',' > ${MYSQLDUMP}

The tr command replaces one char with another.

A: Here's an example SQL query that outputs to a comma-separated file:
SELECT a,b,a+b INTO OUTFILE '/tmp/result.txt'
  FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
  LINES TERMINATED BY '\n'
  FROM test_table;

Re comments:  Fair enough, the INTO OUTFILE syntax writes to a file on the database server host, not the host where the shell script and the mysql client is running.
The mysql client doesn't have a csv output mode, it only has the bars-and-dashes tabular format (with the --table or -t flags), tab-separated format (with the --batch or -B flags), HTML format (--html or -H) and XML (--xml or -X).
If you have content in your database that contains tabs, then either convert tabs to something else using the REPLACE() SQL function, or else output in one of the other formats and try to convert that to csv:
mysql ... --table --skip-column-names |
sed -e 's/  *|  */,/g' \
    -e 's/^|  *//' \
    -e 's/  *|$//' \
    -e '/^+--/d'

A: You don't need another script to do that. Just change:
> ${MYSQLDUMP}

at the end of your line to read:
| sed 's/\x09/,/g' > ${MYSQLDUMP}

But you need to be careful that your data doesn't have commas in it or they'll be mis-recognized by whatever uses the CSV file (but you may have that problem with tabs already).

A: Why not use
SELECT ${MYSQLTABLE}.created_at, ${MYSQLTABLE}.product_options INTO outfile '${MYSQLDUMP}' FROM ${MYSQLTABLE} FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' LINES TERMINATED BY '\n' WHERE ${MYSQLTABLE}.product_id=1 ORDER BY ${MYSQLTABLE}.created_at

A: Found a simple perl 1-liner that seems to do the trick:
perl -F"\t" -lane 'print join ",", map {s/"/""/g; /^[\d.]+$/ ? $_ : qq("$_")} @F '

-Perl Script
So the line in my script looks like this:
        echo "SELECT ${MYSQLTABLE}.created_at, ${MYSQLTABLE}.product_options FROM ${MYSQLTABLE} WHERE ${MYSQLTABLE}.product_id=1 ORDER BY ${MYSQLTABLE}.created_at" | mysql ${MYSQLOPTS} | perl -F"\t" -lane 'print join ",", map {s/"/""/g; /^[\d.]+$/ ? $_ : qq("$_")} @F ' > ${MYSQLDUMP}

Thanks for all the help, Especially from Bill Karwin, I wanted to add a VoteUp to your answer but I don't have enough reputation :(
Once I get more rep, I'll circle back and vote your answer up.
Thanks again.


text:
Q: Getting .aspauth cookie through https This worked well on http, but doesn't work on https.
private Cookie GetAuthCookie(string user, string pass)
    {
        var http = WebRequest.Create(_baseUrl+"Users/Login") as HttpWebRequest;
        http.AllowAutoRedirect = false;
        http.Method = "POST";
        http.ContentType = "application/x-www-form-urlencoded";
        http.CookieContainer = new CookieContainer();
        var postData = "UserName=" + user + "&Password=" + pass + "&RememberMe=true&RememberMe=false&ReturnUrl=www.google.com";
        byte[] dataBytes = System.Text.Encoding.UTF8.GetBytes(postData);
        http.ContentLength = dataBytes.Length;
        using (var postStream = http.GetRequestStream())
        {
            postStream.Write(dataBytes, 0, dataBytes.Length);
        }
        var httpResponse = http.GetResponse() as HttpWebResponse;
        return httpResponse.Cookies[FormsAuthentication.FormsCookieName];
    }

A: Its probably an SSL cert issue, you'll see this with accessing SSL via WebClient or WebRequest depending on the situation with your certificate issuer. See this prior question for details on how to get around this.


text:
Q: Dangers of storing rvalue references in templates Consider following piece of code:
#include <functional>

template<class T>
class factory {
public:
    factory(T &&t) : t_(std::forward<T>(t)) {}

private:
    T &&t_;
};

template<class T>
factory<T> make_factory(T &&t) {
    return factory<T>(std::forward<T>(t));
}

int main(){
    int i = 3;
    auto bar = make_factory(i); //now it will store int &
    auto foo = make_factory(5); //now will store int &&
    return 0;
}

This is of course simplification of code but shows my general idea - I am considering storing references to rvalues. As far as I know in the first case the deduced type will be int & so the factory will be valid until leaving of the scope (due to reference collapsing). My questions are

*

*Is the foo object causing undefined behaviour?

*If not, for how long is the stored rvalue reference valid (I mean, what's its scope)?

*Are there any caveats that I am missing?

EDIT:
I thought this is enough but I see I have to clarify. I want to achieve something like this:
template<class T>
class factory {
public:
    factory(T &&t) : t_(std::forward<T>(t)) {}

    auto make() const & {
        return wrap(t_);
    }

    auto make() && {
       return wrap(/*what here, move(t_), forward<T>(t_) ?*/);
    }
private:
    T t_;//or maybe T&& here?
};

I do not want to copy the member unless I really have to. I would like to do something like forwarding through the factory class.

A: Generally do this:
template<class T>
class factory {
public:
  factory(T &&t) : t_(std::forward<T>(t)) {}

private:
  T t_; // could be a lvalue ref
};

and it just works.  Really.  Yep, that case too.
Rvalues should not outlive their enclosing statement; so your make factory should not return a struct containing an rvalue ref.


text:
Q: MFC and dynamic linking I am stuck with a MFC problem.
I have read a lot about linking, static vs dynamic, and the differences between them.
My project is an open source project, with approx 2000 files which I haven't written, I have just tweaked the project.
My problem now is that I want to be able to clone the program to another computer.
The first computer can run the program, I assume this is possible since VS 2008 proffesional is installed which means that all DLL's are present. On the second computer, the program starts but freezes, I do assume that this means that it can't find a DLL or perhaps a wrong version.
I have tried static linking, but since the project contains a lof of _AFXDLL code it is impossible to compile. I have used depends.exe to generate a dependency report, parsed the report and checked if all files exists. On both computer all DLL-files are present.
My question is, is there anyway of knowing why my program freezes? Installing VS on a machine seemed to do the trick, so I assume VS pro copies some important files that I am not aware of. If so, is there a nice way of finding those files?

A: Problem is now solved!
The answer was simple, the CRT- and MFC-files had different versions. To make sure that the versions are always the same, one can redistribute the files along with the application. Jochen Kalmbach wrote a very simple and precise tutorial on how to do that here.
I hope this answer helps someone else! :)


text:
Q: jQuery auto scroll - easy fix I have a jquery script which scrolls down the body of the page until it reaches the bottom.
        var div = $('body');
        setInterval(function(){
            var pos = div.scrollTop();
            div.scrollTop(++pos);
            }, 100).scrollTop(0);

This script works fine however I need to to almost instantly jump back up to the top of the page after completing this process and then repeat over and over. I have played around with it but not having much luck. If anyone has an easy fix that would be fantastic.
Gambit

A: Look here:
var div = $('div.autoscrolling');
setInterval(function(){
    var pos = div.scrollTop();
    div.scrollTop(++pos);
}, 100)

jQuery auto scroll vertically in a div


text:
Q: Mocking Objective-C code in Swift Unit-Tests NOTE: This isn't my actual code, I re-typed it in a simple fashion on to here for your help.

I have this class written in Objective-C
@interface MySpecialManager <NSObject>

+ (MySpecialManager *)sharedInstance;
-(void)someFunctionWithParamOne:(NSString *)paramOne andParamTwo:(NSString *)paramTwo;
-(void)someFunctionWithParamOne:(NSString *)paramOne andParamTwo:(NSString *)paramTwo success:(void (^)(NSString *))success failure:(void (^)(NSError *error))failure;

@end

I have unit tests (in Swift) for the second function with the success/failure blocks but I am now trying to write unit tests for the first function. All this function does is call the second function. Therefore, I was thinking the best way to test this would be to just check that the second function does indeed get called and with the correct parameters. Therefore, I thought mocking/stubbing was the way to go forward but I am struggling to understand how exactly to unit test this.
From much Googling I read that creating my own Mock object would be the way to go forward so I have this now (written in Swift):
class MockMySpecialManager: NSObject, MySpecialManagerProtocol {

var functionOneWasCalled = false
var functionTwoWasCalled = false

func someFunctionWithParamOne(paramOne: String!, andParamTwo paramTwo: String!) {
    functionOneWasCalled = true
}

func someFunctionWithParamOne(paramOne: String!, andParamTwo paramTwo: String!, success: ((String!) -> Void)!, failure: ((NSError!) -> Void)!) {
    functionTwoWasCalled = true
}

If in my test though I initialise a MockMySpecialManager and call the first method, it won't call the second one as it just updates the boolean, correct? I could update the mock function to call the second but that feels like cheating and not a real unit test as its not testing my code. How can I test this?
I somehow (or so I think) need to set the manager to MySpecialManager.sharedInstace(), call the first method and then check if my second method was called on the mock.
Any help? What am I misunderstanding/where am I going wrong?

A: Your current MOC class is actually a complete replacement of the target class, so you aren't actually testing it at all.
If your MOC was a subclass of the target class instead, and only implemented the second method, then the test can call the first method and the MOC can verify that the second method was called.
Often you would use a mocking library to assist with this, and those libraries allow you different ways to do the same thing as above.
Alternatively you wouldn't MOC the target class, you would MOC all of its dependencies. Then your test checks that the dependencies are called appropriately and with the requisite parameters. Then your first and second method tests are the same setup but with slightly different expectations.


text:
Q: Trying to print multiline string on one line (string stored as variable) I'm working on the MIT intro to computation and programming course and I'm trying to store a multi-line string in a variable that I can use for the program to interact with the user.
I know about the """ for inputting long lines of code with carriage return inserting a newline character (I think I phrased that somewhat accurately).
What I'm running into is the string being stored look shitty in my code and it looks a lot cleaner to use the triple quote but I still want it to print out on one line.  I am trying to store it in a variable like so:
inputRequest = """
Enter 'h' to indicate the guess is too high.
Enter 'l' to indicate the guess is too low.
Enter 'c' to indicate the guess is correct.
"""

and I tried to call that variable in my console like this:
print(inputRequest, end=" ")

but it still prints out on three separate lines.  Is there an efficient way to do this so that my code doesn't look messy?  Storing the string in a variable seems like a good way to cut down on my typing when I need to call that particular output for the user to interact with, but I'm sure there are better ways to do this.  Thanks!

A: You can place backslashes at the end of each line to prevent the newline character from printing in your strings.
inputRequest = """\
    Enter 'h' to indicate the guess is too high. \
    Enter 'l' to indicate the guess is too low. \
    Enter 'c' to indicate the guess is correct. \
    """

print(inputRequest)

If you want, you can also use separate strings for the same purpose.
inputRequest = \
    "Enter 'h' to indicate the guess is too high. " \
    "Enter 'l' to indicate the guess is too low. " \
    "Enter 'c' to indicate the guess is correct. " \

print(inputRequest)

A: Your problem is that the string contains intrinsic EOL characters.  The print statement doesn't add any new-lines, but they're already embedded in what you tell it to print.  You need to replace those, such as:
print(inputRequest.replace("\n", "  ")

Result:
Enter 'h' to indicate the guess is too high.  Enter 'l' to indicate the guess is too low.  Enter 'c' to indicate the guess is correct.

A: Answers are kind of all over the place here.. Here is a usefull experiment for you. Type the following line into your IDE:
text = "This is string1. This is string2. This is string3"

Now manually format the string by pressing enter after each punctuation, you will get:
text = "This is string1." \
       "This is string2." \
       "This is string3."

The above is string concatenation and would provide what your looking for in a "clean" way. The accepted answer is not exactly as "clean" as it could be but since were: "arguing semantics" XD

A: You can create a single-lined string over multiple lines:
inputRequest = ("Enter 'h' to indicate the guess is too high. "
                "Enter 'l' to indicate the guess is too low. "
                "Enter 'c' to indicate the guess is correct.")

A: Following code will help you to achieve what you are trying to do:
print("Enter 'h' to indicate the guess is too high.",
"Enter 'l' to indicate the guess is too low.",
"Enter 'c' to indicate the guess is correct.")

Or alternatively you can alternate the quotes.First line of the following code illustrates the point:
print('Enter "h" to indicate the guess is too high.',
  "Enter 'l' to indicate the guess is too low.",
  "Enter 'c' to indicate the guess is correct.")

Hope this is what you were trying to achieve and this helped ;)
Cheers!


text: Q: how can I use cAdvisor to collect IP information? I want to use cAdvisor to build a monitor system, and this system will be used to collect the information of docker containers, but now I have a problem: I can't collect IP address information. So how can I solve this problem? Thank you!