text:
Q: SQL Server 2012 Job History Missing I have a SQL Server 2012 database with a number of Agent jobs.  The jobs run without a problem but the job history is always empty.  Why?
I also note that running a job manually (right click and "Start Job at Step...") will run the job but the window showing progress of the job never closes.  It is as if the job steps complete but the job itself never completes.
All tasks have been executed as a sysadmin so permissions should not be an issue.
Running the jobs via sp_start_job results in the jobs completing but still no job history.
I've done all the usual checking/changing of jobhistory_max_rows_per_job etc.

A: You could use the following query to obtain all the details about how SQL Server, including SQL Server Agent, is configured, which might show you where something is configured incorrectly:
DECLARE @MasterPath nvarchar(512);
DECLARE @LogPath nvarchar(512);
DECLARE @ErrorLog nvarchar(512);
DECLARE @ErrorLogPath nvarchar(512);

SELECT @MasterPath=substring(physical_name, 1, len(physical_name) - charindex('\', reverse(physical_name)))
FROM master.sys.database_files
WHERE name=N'master';

SELECT @LogPath=substring(physical_name, 1, len(physical_name) - charindex('\', reverse(physical_name)))
FROM master.sys.database_files
WHERE name=N'mastlog';

SELECT @ErrorLog=cast(SERVERPROPERTY(N'errorlogfilename') as nvarchar(512));

SELECT @ErrorLogPath=substring(@ErrorLog, 1, len(@ErrorLog) - charindex('\', reverse(@ErrorLog)));

DECLARE @SmoRoot nvarchar(512);
EXEC master.dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE'
    , N'SOFTWARE\Microsoft\MSSQLServer\Setup'
    , N'SQLPath'
    , @SmoRoot OUTPUT;

IF OBJECT_ID('tempdb..#tmp_sp_get_sqlagent_properties') IS NOT NULL
DROP TABLE #tmp_sp_get_sqlagent_properties;
CREATE TABLE #tmp_sp_get_sqlagent_properties
(
    auto_start int null
    , msx_server_name sysname null
    , sqlagent_type int null
    , startup_account nvarchar(255) null
    , sqlserver_restart int null
    , jobhistory_max_rows int null
    , jobhistory_max_rows_per_job int null
    , errorlog_file nvarchar(255) null
    , errorlogging_level int null
    , error_recipient nvarchar(30) null
    , monitor_autostart int null
    , local_host_server sysname null
    , job_shutdown_timeout int null
    , cmdexec_account varbinary(64) null
    , regular_connections int null
    , host_login_name sysname null
    , host_login_password varbinary(512) null
    , login_timeout int null
    , idle_cpu_percent int null
    , idle_cpu_duration int null
    , oem_errorlog int null
    , sysadmin_only int null
    , email_profile nvarchar(64) null
    , email_save_in_sent_folder int null
    , cpu_poller_enabled int null
    , replace_alert_tokens_enabled int null
);

INSERT INTO #tmp_sp_get_sqlagent_properties
(
    auto_start
    , msx_server_name
    , sqlagent_type
    , startup_account
    , sqlserver_restart
    , jobhistory_max_rows
    , jobhistory_max_rows_per_job
    , errorlog_file
    , errorlogging_level
    , error_recipient
    , monitor_autostart
    , local_host_server
    , job_shutdown_timeout
    , cmdexec_account
    , regular_connections
    , host_login_name
    , host_login_password
    , login_timeout
    , idle_cpu_percent
    , idle_cpu_duration
    , oem_errorlog
    , sysadmin_only
    , email_profile
    , email_save_in_sent_folder
    , cpu_poller_enabled
    , replace_alert_tokens_enabled
)
EXEC msdb.dbo.sp_get_sqlagent_properties;

DECLARE @DatabaseMailProfile nvarchar(255);
DECLARE @AgentMailType int;
DECLARE @ServiceStartMode int;
DECLARE @ServiceAccount nvarchar(512);
DECLARE @AgtGroup nvarchar(512);

EXEC master.dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE'
    , N'SOFTWARE\Microsoft\MSSQLServer\SQLServerAgent'
    , N'DatabaseMailProfile'
    , @param = @DatabaseMailProfile OUT
    , @no_output = N'no_output';

EXEC master.dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE'
    , N'SOFTWARE\Microsoft\MSSQLServer\SQLServerAgent'
    , N'UseDatabaseMail'
    , @param = @AgentMailType OUT
    , @no_output = N'no_output';

EXEC master.sys.xp_instance_regread 'HKEY_LOCAL_MACHINE'
    , 'SYSTEM\CurrentControlSet\Services\SQLSERVERAGENT'
    , N'Start'
    , @ServiceStartMode OUTPUT;

EXEC master.sys.xp_instance_regread 'HKEY_LOCAL_MACHINE'
    , 'SYSTEM\CurrentControlSet\Services\SQLSERVERAGENT'
    , N'ObjectName'
    , @ServiceAccount OUTPUT;

EXEC master.dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE'
    , N'SOFTWARE\Microsoft\MSSQLServer\Setup'
    , N'AGTGroup'
    , @AgtGroup OUTPUT;

SELECT Items.*
FROM #tmp_sp_get_sqlagent_properties AS tsgsp
CROSS APPLY (VALUES
     ('Name', CAST(serverproperty(N'ServerName') AS sql_variant))
    , ('MsxServerName', ISNULL(tsgsp.msx_server_name,N''))
    , ('JobServerType', CONVERT(sql_variant, tsgsp.sqlagent_type))
    , ('SqlServerRestart', CONVERT(sql_variant, tsgsp.sqlserver_restart))
    , ('SqlAgentRestart', CONVERT(sql_variant, tsgsp.monitor_autostart))
    , ('MaximumHistoryRows', CONVERT(sql_variant, tsgsp.jobhistory_max_rows))
    , ('MaximumJobHistoryRows', CONVERT(sql_variant, tsgsp.jobhistory_max_rows_per_job))
    , ('ErrorLogFile', CONVERT(sql_variant, tsgsp.errorlog_file))
    , ('AgentLogLevel', CONVERT(sql_variant, tsgsp.errorlogging_level))
    , ('NetSendRecipient', CONVERT(sql_variant, ISNULL(tsgsp.error_recipient,N'')))
    , ('AgentShutdownWaitTime', CONVERT(sql_variant, tsgsp.job_shutdown_timeout))
    , ('SqlAgentMailProfile', CONVERT(sql_variant, ISNULL(tsgsp.email_profile,N'')))
    , ('SaveInSentFolder', CONVERT(sql_variant, CAST(tsgsp.email_save_in_sent_folder AS bit)))
    , ('WriteOemErrorLog', CONVERT(sql_variant, CAST(tsgsp.oem_errorlog AS bit)))
    , ('IsCpuPollingEnabled', CONVERT(sql_variant, CAST(tsgsp.cpu_poller_enabled AS bit)))
    , ('IdleCpuPercentage', CONVERT(sql_variant, tsgsp.idle_cpu_percent))
    , ('IdleCpuDuration', CONVERT(sql_variant, tsgsp.idle_cpu_duration))
    , ('LoginTimeout', CONVERT(sql_variant, tsgsp.login_timeout))
    , ('HostLoginName', CONVERT(sql_variant, ISNULL(tsgsp.host_login_name,N'')))
    , ('LocalHostAlias', CONVERT(sql_variant, ISNULL(tsgsp.local_host_server,N'')))
    , ('SqlAgentAutoStart', CONVERT(sql_variant, tsgsp.auto_start))
    , ('ReplaceAlertTokensEnabled', CONVERT(sql_variant, tsgsp.replace_alert_tokens_enabled))
    , ('DatabaseMailProfile', CONVERT(sql_variant, ISNULL(@DatabaseMailProfile,N'')))
    , ('AgentMailType', CONVERT(sql_variant, ISNULL(@AgentMailType, 0)))
    , ('SysAdminOnly', CONVERT(sql_variant, 1))
    , ('ServiceStartMode', CONVERT(sql_variant, @ServiceStartMode))
    , ('ServiceAccount', CONVERT(sql_variant, ISNULL(@ServiceAccount,N'')))
    , ('AgentDomainGroup', CONVERT(sql_variant, ISNULL(suser_sname(sid_binary(ISNULL(@AgtGroup,N''))),N'')))
    )Items(ItemName, ItemValue)
UNION ALL
SELECT Items.*
FROM (VALUES
      ('IsCaseSensitive', CAST(case when 'a' <> 'A' then 1 else 0 end AS bit))
    , ('MaxPrecision', @@MAX_PRECISION)
    , ('ErrorLogPath', @ErrorLogPath)
    , ('RootDirectory', @SmoRoot)
    , ('IsFullTextInstalled', CAST(FULLTEXTSERVICEPROPERTY('IsFullTextInstalled') AS bit))
    , ('MasterDBLogPath', @LogPath)
    , ('MasterDBPath', @MasterPath)
    , ('VersionString', SERVERPROPERTY(N'ProductVersion'))
    , ('Edition', CAST(SERVERPROPERTY(N'Edition') AS sysname))
    , ('ProductLevel', CAST(SERVERPROPERTY(N'ProductLevel') AS sysname))
    , ('IsSingleUser', CAST(SERVERPROPERTY('IsSingleUser') AS bit))
    , ('EngineEdition', CAST(SERVERPROPERTY('EngineEdition') AS int))
    , ('Collation', convert(sysname, serverproperty(N'collation')))
    , ('NetName', CAST(SERVERPROPERTY(N'MachineName') AS sysname))
    , ('IsClustered', CAST(SERVERPROPERTY('IsClustered') AS bit))
    , ('ResourceVersionString', SERVERPROPERTY(N'ResourceVersion'))
    , ('ResourceLastUpdateDateTime', SERVERPROPERTY(N'ResourceLastUpdateDateTime'))
    , ('CollationID', SERVERPROPERTY(N'CollationID'))
    , ('ComparisonStyle', SERVERPROPERTY(N'ComparisonStyle'))
    , ('SqlCharSet', SERVERPROPERTY(N'SqlCharSet'))
    , ('SqlCharSetName', SERVERPROPERTY(N'SqlCharSetName'))
    , ('SqlSortOrder', SERVERPROPERTY(N'SqlSortOrder'))
    , ('SqlSortOrderName', SERVERPROPERTY(N'SqlSortOrderName'))
    , ('BuildClrVersionString', SERVERPROPERTY(N'BuildClrVersion'))
    , ('ComputerNamePhysicalNetBIOS', SERVERPROPERTY(N'ComputerNamePhysicalNetBIOS'))
    )Items(ItemName, ItemValue)
ORDER BY Items.ItemName;

Of particular interest in the output would be:

MaximumHistoryRows
  MaximumJobHistoryRows

The above items should be set to a number high enough to ensure you see job history for all jobs.  If, for instance, MaximumHistoryRows is set to 10, but you have 50 jobs, you'll only see history for the 50 most recently ran jobs.  I realize you mention in your question that you've checked these numbers already - I just want to note that it's possible to configure those values in such a way as to severely limit the history you see in msdb.dbo.sysjobhistory.

A: While this only addresses a small part of your question (and you may already be aware):
When you right-click on a job and choose "Start Job at step...", the window that opens does not close automatically when the job is finished. You have to manually close the window (which can be done before or after the job completes).
Once the "Execute job" line in the window has a status (whether success or error), there should (normally) be an entry in sysjobhistory, even if the window hasn't closed (just confirmed in my system).

A: Check the "On Success" for the last step of your job. It should say "Quit the Job Indicating Success"
It won't close the window you used to start running the job, but it will commit the job history once all job steps are complete.
If the On Success is already correct it seems likely that one of the steps never completes, but with newer versions of SSMS you should see all completed steps regardless of whether the entire job completes.

A: Job Step - Advanced Options
If you are only missing the job steps in the history, then this solution might be for you.
When you create/modify a job step, you have an Advanced tab/page that can be configured. Here is a screen shot of what the advanced options look like:

You might have noticed the option Include step output in history. (Well you will have by now.) This option determines if the job step execution is logged in the job history table as described here:

Include step output in history
Select this option to include output from the job step in the job history.

Reference: Job Step Properties - New Job Step (Advanced Page) (Microsoft Docs)
SQL Server Agent Properties - SERVERNAME
If you open up the SQL Server Agent Properties window you can select the History tab/page and are presented with the following window:

Having the wrong values here, can delete the job history faster than you can blink an eye. The default values are as above in the screenshot. Consider entering the default values and try and see if you job starts logging job history again. You will have to stop and start the SQL Server Agent Service to ensure all changes take effect.

A: The issue was due to the connection to SQL Server being made over the loopback interface. There is a loopback check being performed which causes trusted connection via the loopback adapter to fail.
The solution is to disable the loopback check by adding an entry to the registry as per the article below. https://stackoverflow.com/questions/1538027/sspi-handshake-failed-with-error-code-0x8009030c-while-establishing-a-connection/18053759 (See loopback answer 28/07/2011)

A: I had a similar issue - the job worked, but no history was recorded
My job has six steps - Looking at John K N's comment above made me look at the Advanced tab and the box Include step output in history
Step 1 - the box was ticked
Steps 2-6 - the box was NOT ticked
So, I went through all the steps ticking that box
Next morning - I had History!
Being an awkward sort of cuss, I went through all six steps unticking
Next morning - I had History!
I ticked the box for Step 1, leaving the others unticked (so that it was back to the original state
Next morning - I had History!
So I suspect that the job had somehow fallen into Schrödinger's History - neither wanted nor unwanted.
Try changing something, maybe even just the text - it saves it and then works fine

A: I've got the same problem. Since June 16th 2018 there are no protocol entries for my agent jobs anymore. I checked already with your script and it looks fine for me.
So, I have no idea what can be the reason. It might be there is a mistake in the SQL server itself, but how can I detect it. I have created a test agent job with an simple SQL statement, also here no protocol. When I check the error protocols then the protocal says that it was written in db sysjobhistory, but nothing happened.
So, has someone an idea to solve the problem?
Thanks a lot.
Cheers Klaus


text:
Q: C++ linked list values changing retroactively EDIT: Solution Code included at the end.
I am trying to implement a linked list class that utilizes a node class as defined in the assignment. The below code block prints output as expected:
#include <iostream>
using namespace std;

// Node class as provided
class node {
    void *info;
    node *next;
public:
    node (void *v) {info = v; next = 0; }
    void put_next (node *n) {next = n;}
    node *get_next ( ) {return next;}
    void *get_info ( ) {return info;}
};

// Linked list class
class list {
    //Start of the linked list
    node *start;
public:
    list (int v) {
        start = new node (&v);
    }

    void insert (int value, int place=-1) {
        node *temp = new node (&value);

        if (place == 0) {
            temp->put_next(start);
            start = temp;
        } else {
            node *before = start;
            for (int i = 1; before->get_next() != 0; i++) {
                if (i == place) {
                    break;
                }
                before = before->get_next();
            }

            temp->put_next(before->get_next());
            before->put_next(temp);
        }
    }

    void remove(int place) {
        if (place == 0) {
            start = start->get_next();
        } else {
            node *curr = start;
            for (int i = 1; curr != 0; i ++) {
                if (i == place) {
                    curr->put_next(curr->get_next()->get_next());
                    break;
                }
                curr = curr->get_next();
            }
        }
    }

    void display() {
        for (node *current = start; current != 0; current = current->get_next()) {
            cout << *(static_cast<int*>(current->get_info())) << endl;
        }
    }
};

int main() {

    list *tst = new list(10);
    tst->display();
    cout << "Prepending 9" << endl;
    tst->insert(9,0);
    tst->display();
    cout << "Inserting 8" << endl;
    tst->insert(8,1);
    tst->display();
    cout << "Prepending 7" << endl;
    tst->insert(7,0);
    tst->display();

    tst->remove(0);

    cout << "Removed the first element:" << endl;
    tst->display();
    cout << endl;

//  cout << "Prepending 6" << endl;
//  tst->insert(6,0);
//  tst->display();

}

Creates this output:
10
Prepending 9
9
10
Inserting 8
9
8
10
Prepending 7
7
9
8
10
Removed the first element:
9
8
10

However, when I add this last statement to the end of the program flow in main:
tst->insert(6,0);

My output changes to this:
10
Prepending 9
9
10
Inserting 8
8
8
10
Prepending 7
7
7
7
10
Removed the first element:
134515798
134515798
10

What am I missing? How can adding a value later in execution change the output that happens before I even get to that point in the program flow?
I am using ideone.com as my IDE/to run the program, I've never had an issue before, but is that the issue?
Solution
#include <iostream>
using namespace std;

// Provided node class
class node {
    void *info;
    node *next;
public:
    node (void *v) {info = v; next = 0; }
    void put_next (node *n) {next = n;}
    node *get_next ( ) {return next;}
    void *get_info ( ) {return info;}
};

// List class template
template <class T>
class list {
    node *start;
public:
    list (T v) {
        start = new node (&v);
    }

    // Insert method
    void insert (T *value, int place=-1) {
        node *temp = new node (value);

        // If we're putting it at the beginning, then change the reference to start
        if (place == 0) {
            temp->put_next(start);
            start = temp;
        }

        // We're inserting it somewhere other than the beginning, handle appropriately
        else {
            node *before = start;

            // Loop to find preceeding node
            for (int i = 1; before->get_next() != 0; i++) {
                if (i == place) {
                    break;
                }
                before = before->get_next();
            }

            // Insert after preceeding node, and point at subsequent node
            temp->put_next(before->get_next());
            before->put_next(temp);
        }
    }

    // Remove function
    void remove(int place) {

        // If we're removing hte beginning, then change start pointer
        if (place == 0) {
            start = start->get_next();
        }

        // Find node to remove
        else {
            node *curr = start;
            for (int i = 1; curr != 0; i ++) {
                if (i == place) {
                    // Cut target node out of list
                    curr->put_next(curr->get_next()->get_next());
                    break;
                }
                curr = curr->get_next();
            }
        }
    }

    // Print nodes
    void display() {
        for (node *current = start; current != 0; current = current->get_next()) {
            cout << *(static_cast<T*>(current->get_info())) << endl;
        }
        cout << endl;
    }
};

int main() {
    int nine = 9;
    int eight = 8;
    int seven = 7;
    int six = 6;
    int five = 5;

    cout << "Create list holding '10'" << endl;
    list<int> *tst = new list<int>(10);

    cout << "Prepending 9" << endl;
    tst->insert(&nine,0);

    cout << "Inserting 8 at 2nd place" << endl;
    tst->insert(&eight,1);

    cout << "Appending 7" << endl;
    tst->insert(&seven);

    cout << "Prepending 6" << endl;
    tst->insert(&six,0);

    cout << "Inserting 5 at 3rd place" << endl;
    tst->insert(&five,2);

    cout << "Show completed list:" << endl;
    tst->display();

    cout << "Removing the first element:" << endl;
    tst->remove(0);
    tst->display();

    cout << "Removing the last element:" << endl;
    tst->remove(4);
    tst->display();

    cout << "Removing the second element:" << endl;
    tst->remove(1);
    tst->display();
}

A: You have undefined behavior in your code, because you save pointers to local variables, variables that goes out of scope once the function returns.
The variable I'm talking about is the argument value inside the insert function, once the insert function returns that pointer is no longer valid.
The quick solution? Don't store pointers, store a list of integers. Or maybe make the list (and node) a templated class and store by value.
If you truly want a list that can contain anything, the consider using e.g. Boost any.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to run Docker specific commands using Java Jsch I tried to do the following steps in java.
1. ssh to remote machine(done using jsch) as below .
import java.io.InputStream;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
public class JSchExampleSSHConnection {
public static void main(String[] args) {
    String host="hostname";
    String user="sshuser";
    String password="sshpwd";
    String command1="ls";
    try{

        java.util.Properties config = new java.util.Properties();
        config.put("StrictHostKeyChecking", "no");
        JSch jsch = new JSch();
        Session session=jsch.getSession(user, host, 22);
        session.setPassword(password);
        session.setConfig(config);
        session.connect();
        System.out.println("Connected");

        Channel channel=session.openChannel("exec");
        ((ChannelExec)channel).setCommand(command1);
        channel.setInputStream(null);
        ((ChannelExec)channel).setErrStream(System.err);

        InputStream in=channel.getInputStream();
        channel.connect();
        byte[] tmp=new byte[1024];
        while(true){
          while(in.available()>0){
            int i=in.read(tmp, 0, 1024);
            if(i<0)break;
            System.out.print(new String(tmp, 0, i));
          }
          if(channel.isClosed()){
            System.out.println("exit-status: "+channel.getExitStatus());
            break;
          }
          try{Thread.sleep(1000);}catch(Exception ee){}
        }
        channel.disconnect();
        session.disconnect();
        System.out.println("DONE");
    }catch(Exception e){
        e.printStackTrace();
    }

}
}

*Entering sudo su and password. Done using the below command .
        ((ChannelExec) channel).setCommand("echo 'password' | sudo -S docker ps -a");

unable to proceed with the next steps

*Enter docker exec -it dockername bash .

*Enter python manage.py cronName .

I tried the below steps to achieve step 3 and 4. Tried with Runtime.getRuntime().exec("docker exec >-it dockername bash"). Is there any other way to run these commands. Any suggestions on this.

A: Allocate a Pseudo-Terminal by:
channel.setPty(true);

For executing commands inside a docker running container, like:
docker exec -it <container-name> <command>


text:
Q: Most basic parallelization with C++11 theads fail I try to use C++11 theading library using g++ 4.7.
First I have a question: is it expected for a next release to not be required to link by hand the pthread library ?
So my program is :
#include <iostream>
#include <vector>
#include <thread>

void f(int i) {
    std::cout<<"Hello world from : "<<i<<std::endl;
}

int main() {
    const int n = 4;
    std::vector<std::thread> t;
    for (int i = 0; i < n; ++i) {
        t.push_back(std::thread(f, i));
    }
    for (int i = 0; i < n; ++i) {
        t[i].join();
    }
    return 0;
}

I compile with:
g++-4.7 -Wall -Wextra -Winline -std=c++0x -pthread -O3 helloworld.cpp -o helloworld

And it returns:
Hello world from : Hello world from : Hello world from : 32
2
pure virtual method called

terminate called without an active exception
Erreur de segmentation (core dumped)

What is the problem and how to solve it ?
UPDATE:
Now using mutex:
#include <iostream>
#include <vector>
#include <thread>
#include <mutex>

static std::mutex m;

void f(int i) {
    m.lock();
    std::cout<<"Hello world from : "<<i<<std::endl;
    m.unlock();
}

int main() {
    const int n = 4;
    std::vector<std::thread> t;
    for (int i = 0; i < n; ++i) {
        t.push_back(std::thread(f, i));
    }
    for (int i = 0; i < n; ++i) {
        t[i].join();
    }
    return 0;
}

It returns :
pure virtual method called
Hello world from : 2
terminate called without an active exception
Abandon (core dumped)

UPDATE 2:
Hum... It works with my default GCC (g++4.6) but it fails with the version of gcc I compiled by hand (g++4.7.1). Was there an option I forgot to compile g++ 4.7.1 ?

A: General edit:
In order to prevent use of cout by multiple threads simultaneously, that will result in character interleaving, proceed as follows:
1) declare before the declaration of f():
static std::mutex m;

2) then, guard the "cout" line between:
m.lock();
std::cout<<"Hello world from : "<<i<<std::endl;
m.unlock();

Apparently, linking against the -lpthread library is a must, for some unclear reasons. At least on my machine, not linking against -lpthread results in a core dump. Adding -lpthread results in proper functionality of the program.
The possibility of character interleaving if locking is not used when accessing cout from different threads is expressed here:
https://stackoverflow.com/a/6374525/1284631
more exactly: "[ Note: Users must still synchronize concurrent use of these objects and streams by multiple threads if they wish to avoid interleaved characters. — end note ]"
OTOH, the race condition is guaranteed to be avoided, at least in the C++11 standard (beware, the gcc/g++ implementation of this standard is still at experimental level).
Note that the Microsoft implementation (see: http://msdn.microsoft.com/en-us/library/c9ceah3b.aspx credit to @SChepurin) is stricter than the standard (apparently, it guarantees character interleaving is avoided), but this might not be the case for the gcc/g++ implementation.
This is the command line that I use to compile (both updated and original code versions, everything works well on my PC):
g++ threadtest.cpp -std=gnu++11 -lpthread -O3

OTOH, without the -lpthread, it compiles but I have a core dump (gcc 4.7.2 on Linux 64).
I understand that you are using two different versions of the gcc/g++ compiler on the same machine. Just be sure that you use them properly (not mixing different library versions).


text:
Q: How many times should an 11 sided biased coin be thown, so each of the unbiased sides occured atleast a 100 times If I have an 11 sided coin where p(1) up to p(10) has probability 0.01. And p(11) has probability 0.9.
How do I calculate after how many throws p(1) up to p(10) each occurred at least a 100 times.
Also how do I create a binominal distribution of this, to determine the minimum and maximum 95 or 99% amount?
I am seeking for a general formula to determine this, it is assumed that p(1)-p(n) of the unbiased side all have the same probability though.

A: You could approximate the problem by each side being independent and then the probability for all ten sides being above 100 is the probability for one side being above 100 to the power ten.
Below is a code example that compares this approximation with a simulation.

d = 100 ### cutoff-level
m = 20  ### number of bins/dice-sides
n = 5000 ### number of trials for histogram

### fucntion that repeats sampling untill all states are above d
sim <- function() {
  states = c(rep(FALSE,m),TRUE)
  cases = rep(0,m+1)
  count = 0
  while (prod(states) == 0) {
    count = count + 1
    s = sample(c(1:(m+1)),
               size = 1,
               prob = c(rep(0.1/m,m),0.9))
    cases[s] = cases[s] + 1
    if (cases[s] == d) {
      states[s] = TRUE
    }
  }
  return(count)
}

### do the simulation n times
set.seed(1)
sims <- replicate(n,sim())

### plot and compute histogram
h <- hist(sims, freq = 1, main = "histogram of simulation with curve of approximation",
     breaks = seq(20000,30000,400))

### compute approximate counts distribution function
ns = 1:max(h$breaks)
psingle <- 1-pbinom(d-1,ns,p=0.1/m)
pmult <- psingle^m

### add to historgram
counts = sapply( 1:length(h$mids), FUN = function(x) {
  pmult[h$breaks[x+1]]-pmult[h$breaks[x]]
})
lines(h$mids,counts*n)
points(h$mids,counts*n, pch = 21, col = 1, bg = 0)

A: You have to throw it at least 1000 times to have a positive probability of 100 for each. The probability is always less than 1 no matter how many time you throw the die.
Suppose I throw the die $N \ge 1000$ times and let $X_i$ denote the number of times side $i$ is observed.  $(X_1,...X_{11})$ has a multinomial distribution.
$$P[X_1 \ge 100, X_2 \ge 100, ...X_{10} \ge 100]$$
$$=\sum_{x_1=100}^{N-900}\sum_{x_2=100}^{N-800-x_1}\sum_{x_3=100}^{N-700-x_1-x_2}...\sum_{x_{10}=100}^{N-\sum_{j=1}^9x_j}P[X_1 =x_1, X_2 =x_2, ...X_{10} =x_{10}]$$
$$=\sum_{x_1=100}^{N-900}\sum_{x_2=100}^{N-800-x_1}\sum_{x_3=100}^{N-700-x_1-x_2}...\sum_{x_{10}=100}^{N-\sum_{j=1}^9x_j}\frac{N!}{x_1!x_2!...x_{10}!(N-\sum_{k=1}^{10}x_k)!}p_1^{x_1}p_2^{x_2}...p_{10}^{x_{10}}p_{11}^{N-\sum_{k=1}^{10}x_k}$$
You definitely do not want to try calculating that unless N is close to 1000.
For large $N$, $(X_1,...X_{10})$ is approximately multivariate normal with mean $(0.01 N, ..., 0.01 N)$ and variance matrix that has $0.01\times N\times(1-0.01)$ on the diagonal and $-0.01^2N$ off diagonal. see here
With $N=11600$, there is about 50% chance of having observed 100 of each face from 1-10.
R program:
library(mvtnorm)
N=11600
sigma=matrix(N*sqrt(0.01*0.01)*(0-sqrt(0.01*0.01)),ncol=10,nrow=10)
diag(sigma)=N*sqrt(0.01*0.01)*(1-sqrt(0.01*0.01))
as.numeric(pmvnorm(lower=rep(100,10),upper=rep(Inf,10),mean=rep(0.01*N,10),sigma=sigma))

For 95% chance, use $N=12900$
For 99% chance, use $N=13600$


text:
Q: PermissionError: [Errno 13] Permission denied: 'System Volume Information' when trying to copy files with python I am trying to create a program that copies files from the USB stick inserted into the computer to a folder within the hard drive. I keep getting this error:
PermissionError: [Errno 13] Permission denied: 'System Volume Information'
The code is
import os
import shutil
from shutil import copyfile
drives = [ chr(x) + ":" for x in range(65,90) if os.path.exists(chr(x) + ":") ]
print(drives)

if "E:" in drives:
    with open('backupNumbers.txt', 'r') as f:
        f_contents =f.readlines()
        numberofFolders = int(f_contents[0])
        numberofFolders += 1
    with open('backupNumbers.txt', 'w') as wf:
        wf.write(str(numberofFolders))

    def createFolder(directory):
        try:
            if not os.path.exists(directory):
                os.makedirs(directory)
        except OSError:
            print ('Error: Creating directory. ' +  directory)
    folderNumber = str(numberofFolders)
    createFolder('./' + "Backup " + folderNumber + '/')
    src = "E:\\"
    dest1 = "Y:\\Documents\\USB Copies\\"
    dest = str(dest1 + "Backup" + folderNumber)
    files = os.listdir(src)
    os.chdir(src)
    for file in files:
        with open(file) as f:
            print(file, f.read())
    for file in files:
        shutil.copy(file, dest)

The full traceback is
File "<ipython-input-4-fb59bc7c32b6>", line 1, in <module>
    runfile('E:/USB Backups/Automation.py', wdir='E:/USB Backups')

  File "C:\Users\Garret Langlois\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 827, in runfile
    execfile(filename, namespace)

  File "C:\Users\Garret Langlois\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 110, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "E:/USB Backups/Automation.py", line 30, in <module>
    with open(file) as f:

PermissionError: [Errno 13] Permission denied: 'System Volume Information'

A: System Volume Information is a special folder used by Windows to manage restore points.
You probably don't need to copy it yourself, and I'd suggest you just skip it.
But if you do want to get access to it, you can read about that here: https://support.microsoft.com/en-us/help/309531/how-to-gain-access-to-the-system-volume-information-folder


text:
Q: How to set bootstrap checkbox to true from javascript/typescript code? I have set a checkbox list using the following code:

  <input class="form-check-input" type="checkbox" value="" id="0" (change)="getSelectedCheckbox($event)" (checked)="getCheckedSites()"  >

      {{sites[0]}}

  <input class="form-check-input" type="checkbox" value="" id="1" (change)="getSelectedCheckbox($event)">

    {{sites[1]}}

  <input class="form-check-input" type="checkbox" value="" id="2" (change)="getSelectedCheckbox($event)">

    {{sites[2]}}

  <input class="form-check-input" type="checkbox" value="" id="3" (change)="getSelectedCheckbox($event)">

    {{sites[3]}}

  <input class="form-check-input" type="checkbox" value="" id="4" (change)="getSelectedCheckbox($event)">

    {{sites[4]}}

  <input class="form-check-input" type="checkbox" value="" id="5" (change)="getSelectedCheckbox($event)">

    {{sites[5]}}

I would like to set the state of a checkbox(whether checked or not) from the javascript/typescript file.
I am using Angular so I tried the following in the html file:
(checked)="getCheckedSites()

And in the typescript file, I wrote this method:
getCheckedSites(){
  return true
}

Obviously, it didn't work.
Any help?

A: As you are using Angular, you have two ways of doing this:
1: You can use the [checked] property, which receives a boolean value saying if the input is checked or not. This is only if you need one-way data binding.
2: You can use the [(ngModel)]. As it is an input, you can still assign a value using ngModel. But, in this case, this is two-way data binding and will change the value in your model if the user checks/unchecks the checkbox.
I created a demo in Stackblitz, so you can both ways better (open the browser console to see what's happening in the model): https://stackblitz.com/edit/checkbox-input-demonstration
You can take a better look in two-way data binding in this post: https://blog.thoughtram.io/angular/2016/10/13/two-way-data-binding-in-angular-2.html

A: I didn't quite get whether you want to check a checkbox,or see if it's checked, so i will give you 2 answers depending on what you want,using javascript:

*

*if you want to see if a checkbox is checked or not, you may use:
var check = document.getElementById("ID").checked; check = false if your element is unchecked,otherwise check = true;

*if you want to force check a checkbox you may use:
 document.getElementById("ID").checked = true;
PS: this solution you aim at a speceic checkbox using its ID, if you want to check all your checkboxes you better use the following code:
 var checkList = document.querySelectorAll("input[type=checkbox]");
    for(var i = 0;i < checkList.length;i++){
       // your operation here
   }


text:
Q: Create a collection of products that have a tier price for a particular customer group I want to create a page or tab within customer dashboards that shows all products that have a tier price for a customer group they are a member of. This will help customers who have contract prices for certain products to quickly browse and add these products to cart.
protected function _getProductCollection()
{
    /** @var $collection \Magento\Catalog\Model\ResourceModel\Product\Collection */
    $collection = $this->_productCollectionFactory->create();
    $collection->setVisibility($this->_catalogProductVisibility->getVisibleInCatalogIds());

    $collection = $this->_addProductAttributesAndPrices(
        $collection
    )->setPageSize(
        $this->getProductsCount()
    )->setCurPage(
        1
    );

    $collection->addTierPrice()
          ->getSelect()
          ->where('price_index.tier_price < price_index.price');

    $collection->where(cust_group = $customerGroup);
    return $collection;
}

How is a collection like above filtered to achieve this?
UPDATE
Unsure if filtering with customer group is really necessary magento collections seem to just do this anyway as error shows when playing with these collections:
2 exception(s):
Exception #0 (Zend_Db_Statement_Exception): SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')' at line 3, query was: SELECT COUNT(DISTINCT e.entity_id) FROM `catalog_product_flat_2` AS `e`
 INNER JOIN `catalog_category_product_index` AS `cat_index` ON cat_index.product_id=e.entity_id AND cat_index.store_id=2 AND cat_index.visibility IN(2, 4) AND cat_index.category_id='2'
 INNER JOIN `catalog_product_index_price` AS `price_index` ON price_index.entity_id = e.entity_id AND price_index.website_id = '2' AND price_index.customer_group_id = '4' WHERE (price_index.Final_price < price_index.price) AND (cust_group =)
Exception #1 (PDOException): SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')' at line 3

So I feel like i just need it to pull products that have a tier price and then it will show the products i need.
->where('price_index.tier_price < price_index.price');

The above filter works giving me the products with tier prices however this also shows the products for all groups also which i need to filter out. Something like below:
->where('price_index.Tier_price < price_index.price')
->where('price_index.customer_group_id != "ALL GROUPS"');

Upon looking at the database in the "catalog_product_index_price" price table there just seems to be a record set for each group id when all group is selected, so to solve this i think I can join this table to the 'catalog_product_entity_tier_price' table so that i can then filter out products that have the all_groups row set to 1 as this seems to have the data i need.
So i have added a join to the collection and filtered by all tier prices set to 0 to remove the tier prices for all groups:
 $collection->getSelect()->join('catalog_product_entity_tier_price as tier', 'price_index.entity_id = tier.entity_id');

 $collection->addFinalPrice()
          ->addMinimalPrice()
          ->getSelect()
          ->where('tier.all_groups = 0')
          ->where('price_index.Tier_price < price_index.price');

This seems to work perfectly allowing me to remove all products with tier prices set to "all_group" leaving just my collection of tier priced products within signed in users customer group. Feel a bit gutted i wasted the bounty now :P
SOLVED

A: It's possible to do this with the following collection:
protected function _getProductCollection()
{
    /** @var $collection \Magento\Catalog\Model\ResourceModel\Product\Collection */
    $collection = $this->_productCollectionFactory->create();
    $collection->setVisibility($this->_catalogProductVisibility->getVisibleInCatalogIds());

    $collection = $this->_addProductAttributesAndPrices(
        $collection
    )->setPageSize(
        $this->getProductsCount()
    )->setCurPage(
        1
    );

    $collection->getSelect()->join('catalog_product_entity_tier_price as tier', 'price_index.entity_id = tier.entity_id');

    $collection->addFinalPrice()
          ->addMinimalPrice()
          ->getSelect()
          ->where('tier.all_groups = 0')
          ->where('price_index.Tier_price < price_index.price');

    return $collection;
}

This gets all products with tier prices except for ones set in the all group so just the tier prices for that particular group are shown.
Since updating to 2.2.1 I'm not sure why but my Tier_Price column within price_index seems null for everything so returns an empty collection. For now i have overcome this by taking the tier price directly from the catalog_product_entity_tier_price. The where method now looks like below:
->where('tier.value < price_index.price');


text:
Q: How do I resolve mach-o architecture errors when using capybara-webkit and QT I am using capybara-webkit on OS X Lion.  I used brew to install QT, which seems to have installed successfully along with the capybara-webkit gem.  I'm getting the following errors and am not entirely sure how to resolve them.
I do some research online, but it looks like my architectures match up as running file on the plugin shows i386.  Any input?
2011-09-19 19:58:26.289 webkit_server[9927:107] Error loading /Library/Internet Plug-Ins/SharePointBrowserPlugin.plugin/Contents/MacOS/SharePointBrowserPlugin:  dlopen(/Library/Internet Plug-Ins/SharePointBrowserPlugin.plugin/Contents/MacOS/SharePointBrowserPlugin, 262): no suitable image found.  Did find:
    /Library/Internet Plug-Ins/SharePointBrowserPlugin.plugin/Contents/MacOS/SharePointBrowserPlugin: mach-o, but wrong architecture
2011-09-19 19:58:26.291 webkit_server[9927:107] Error loading /Library/Internet Plug-Ins/QuickTime Plugin.plugin/Contents/MacOS/QuickTime Plugin:  dlopen(/Library/Internet Plug-Ins/QuickTime Plugin.plugin/Contents/MacOS/QuickTime Plugin, 265): no suitable image found.  Did find:
    /Library/Internet Plug-Ins/QuickTime Plugin.plugin/Contents/MacOS/QuickTime Plugin: mach-o, but wrong architecture

A: I recently had a similar issue where rails was throwing the "but wrong architecture no suitable image found" error when starting rails console or the rails server.
Running file on the associatd .dylib files, and the gem, generally returned either an applicable x86_64 version, or a universal which included it.  Eventually, I traced it back to the actual version of Ruby I was running.  The /usr/bin/ruby executable itself was only i386 compatible.  This was really a shocker, as I assumed the new xcode and osx 10.7 would have brought me a 64 bit ruby.
Using RVM, I installed another instance of ruby (again 1.8.7).  Doing this required that I install a new instance of readline (for which I used homebrew, : brew install readline) and installed the rvm with rvm install 1.8.7 --with-readline-dir=/usr/local/Cellar/readline/6.2.1/.
After doing this, and switching to use my new ruby instance (rvm use 1.8.7), all my gems were gone (the RVM install somehow changed my default gem_path.)  gem install rake, followed by gem install bundler, and then bundle install got me up and running.
Long story short, make sure your ruby executable matches the instruction-set version that your ruby/rails packages are were built in.

A: I found the solution in the next link
https://github.com/thoughtbot/capybara-webkit/issues/157


text:
Q: How to set bottom postion style for v-snackbar vuetify component in Vuejs? I am trying to stack multiple v-snackbars from the bottom. The inline style to set bottom property doesn't seem to affect it.
Snackbar.vue
<template>

        <v-snackbar
           v-for="(snackbar, index) in snackbars"
           :key="index"
           v-model="snackbar.visible"
           :color="snackbar.color"
           :style="{ bottom: `${index * 60 + 8}px` }"
        >
          {{ snackbar.text }}                                                                                </v-snackbar>

</template>
...

App.vue
<template>
  <v-app>
    <ProgressCircular />
    <Snackbar />
    <v-main>
      <transition mode="out-in" name="fade">
        <router-view />
      </transition>
    </v-main>
  </v-app>
</template>

A: You need to add "absolute" attribute.
<v-snackbar
  v-for="(snackbar, index) in snackbars"
  :key="index"
  v-model="snackbar.visible"
  :color="snackbar.color"
  :style="{ bottom: `${index * 60 + 8}px` }"
  absolute
  bottom
>
  {{ snackbar.text }}
</v-snackbar>


text:
Q: TimerTask and ImageView.setBackgroundDrawable a no-go? I am trying to set an ImageView's background every x seconds.
The used Drawables are downloaded from a server, placed in a Vector and when they all have been downloaded I am starting a Timer and a TimerTask which simply has to set an ImageView in an Activity's Layout.
The problem is that I am getting a :
android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
I am guessing here thats because of the TimerTask, even though it simply calls a method from the original Activity which in turn sets the ImageView from the local Vector.
This exception isn't thrown every time though, but the times it does go through the ImageView won't show the Image, unless I force a refresh by clicking the device's "home" button and resuming the app... I have tried to force an update/refresh of the ImageView itself by calling forceLayout() and requestLayout() but that won't do anything :(
So any idea's how to solve these issues ? Should I implement like a Hnadler within the Timer/TimerTask ? Is that even possible ? Will it refresh my ImageView correctly ?

A: Timer works in a separate thread and (I think) launches it's TimerTasks in a separate threads also, and you can't change UI in a non UI thread (the main thread).
The right way, is to use handlers (read documentation, really easy to use, but more for primitive data exchange between non-ui and ui threads), or (the simpliest and more suitable for you) try:

imageView.post(
   new Runnable() {

        imageView.setBackground(...);

}
);

P.S. Usefull:
http://developer.android.com/reference/android/view/View.html#post(java.lang.Runnable)
http://developer.android.com/guide/appendix/faq/commontasks.html#threading


text:
Q: If for two sets of sets (not same sets) $\cup_{i=1}^{\infty} E_n = \cup_{i=1}^{\infty} F_n$, then can I conclude on $\mu(E_n)=\mu(F_n)$? If for two sets of sets (not same sets) $\cup_{i=1}^{\infty} E_n = \cup_{i=1}^{\infty} F_n$, then can I conclude on $\mu(E_n)=\mu(F_n)$?
The theory says that
$$\mu(\cup_{i=1}^{\infty} E_n)=\sum_{i=1}^{\infty} \mu(E_n)$$
But why would this mean that $\mu(E_n)=\mu(F_n)$?

A: In general, no, this will not hold.  Let $A$ be a set with positive measure.
Suppose that $E_n=A$ for $n$ odd and $E_n=\emptyset$ for $n$ even.
Similarly, suppose that $F_n=A$ for $n$ even and $F_n=\emptyset$ for $n$ odd.
Observe that $E_n\not=F_n$ for all $n$.
In this case $\mu(E_n)\not=\mu(F_n)$ for all $n$ (one is zero and the other is positive), but the unions of the sets are the same ($A$).

A: No, and a simple example would be $E_n=[-1,1]$ for all $n\geq 0$, and $F_0=[-1,1]$ and $F_n=\{0\}$ for $n\geq 1$.
In this case, $\cup_nE_n=\cup_n F_n=[-1,1]$ but $\mu(E_n)=2$ while $\mu(F_n)=0$ for $n>0$ ($\mu$ being the Lebesgue measure on reals).


text:
Q: How to clear locally cached OneDrive online-only files I recently needed to free up some space on my Dell Venue 8 Pro, running Windows 8.1, and realized that I had OneDrive set for all files to be available offline, meaning it was caching local copies of all files.  No problem, I thought.  I'll just change it globally to make the files available as online-only.  I've read that the files then do not consume space locally.  Instead, there are place holder shortcuts which allow browsing of the file structure, and files are only downloaded when accessed or marked to be available offline.
However, after changing the global OneDrive setting for all files to be online-only, the local files continue to consume their full space (13 GB).  I cannot delete the files as they are then deleted in the cloud.  I would have expected that after marking all the files as online-only, the bits would start deleting, or perhaps after some definable period of time of not being accessed.  Or at least have a button to manually flush the local OneDrive file cache.  Alas, 'tis not so.  How can I clear the local OneDrive file cache for online only files?

A: If you have set your files to online-only, you are probably being tricked by the new and wonderful
cloud integration of Windows 8.
From the Microsoft article
Online-only files and files available offline :

Online-only files, also called smart files, are a special kind of
  OneDrive file in Windows 8.1 and Windows RT 8.1. You can browse them
  on your PC, but the file contents are really in OneDrive, so they
  don't take up much of your disk space. Online-only files look like
  normal files on your PC, they have all the typical file info (like
  date modified, file type, and size), and you can search them. When you
  open online-only files from File Explorer and most apps, the file
  contents are downloaded automatically.

This wonderful transparency assumes that one has continuous Internet connectivity.
Imagine getting on a plane and suddenly discovering that those files thought to be on the PC are, in fact, not there. Only the "smart" placeholders are there, and stupidly enough can't be opened while offline.
In my book, this new system is utterly and absolutely broken and user-unfriendly.
Until it is fixed, you might be better off using another free online service which is not as well integrated into Windows.


text:
Q: Only keep first occurrence of duplicate column value if it has same value in another column I need to keep only the first occurrence of duplicate values in a column if they have the same value in another column. The other duplicates I need to replace with an empty string.  For instance, the text column saying,'how are you," should only display once because it has the same date as '2016-09-10' in the date column.
import pandas as pd

data = {'date': ['2016-09-10', '2016-09-10',
                 '2016-09-10', '2016-09-10',
                 '2016-09-12', '2016-09-12',
                 '2016-09-13', '2016-09-13'],
        'text': ['hey how are you', 'hey how are you', 'hey how are you', 'good thanks',
                  'good thanks', 'good thanks', 'good thanks', 'good thanks']}

df = pd.DataFrame(data)

The output is currently like this:
date           text
2016-09-10     hey how are you
2016-09-10     hey how are you
2016-09-10     hey how are you
2016-09-10     good thanks
2016-09-12     good thanks

My desired output is:
date           text
2016-09-10     hey how are you
2016-09-10
2016-09-10
2016-09-10     good thanks
2016-09-12     good thanks

A: Use DataFrame.duplicated with DataFrame.loc for set empty strings by condition:
df.loc[df.duplicated(['date','text']), 'text'] = ''

#if only 2 columns
#df.loc[df.duplicated(), 'text'] = ''
print (df)
         date             text
0  2016-09-10  hey how are you
1  2016-09-10
2  2016-09-10
3  2016-09-10      good thanks
4  2016-09-12      good thanks
5  2016-09-12
6  2016-09-13      good thanks
7  2016-09-13


text:
Q: How to create an application pool with appcmd? I have figured out I could associate an existing application pool with an existing site like this:
APPCMD.exe set app "sitename/" /applicationPool:"appPoolName"

But how do I create my own application pool with the name appPoolName, .NET version 4 and Integrated pipeline prior to this command?

A: This:
https://learn.microsoft.com/en-us/iis/get-started/getting-started-with-iis/getting-started-with-appcmdexe
should give you everything you need. In particular
appcmd add apppool /name:appPoolName /managedRuntimeVersion:"v4.0" /managedPipelineMode:"Integrated"
should do the job.


text:
Q: Não consigo ler uma entrada com espaços Eu fiz a seguinte função para dar entrada nos dados:
void entrada_dados(Time* time, int i){
    fscanf(stdin, "%s %d %d", time[i].nome, &time[i].gols_marcados, &time[i].gols_sofridos);
};

Um exemplo de input seria:
2
santos
30
23
inter
35
30

Chamo ela na main da seguinte maneira:
int main(void) {

  int n = 0;
  scanf("%d", &n);

  for(int i = 0; i < n; i++){
    entrada_dados(time, i);
 }

A ideia é chamar ela de acordo com a quantidade de times que vão ser inseridos nos parametros. Até então funciona tudo certo, o problema é quando eu tenho que inserir um time que tenha um espaço entre o nome, por exemplo: São Paulo.
Na saida, São Paulo fica como dois times diferentes e isso acaba bugando tudo. Tentei fazer da seguinte forma:
void entrada_dados(Time* time, int i){
    fscanf(stdin, "%[^\n] %d %d", time[i].nome, &time[i].gols_marcados, &time[i].gols_sofridos);
};

Mas também não funcionou.
Outra maneira que eu tentei foi:
void entrada_dados(Time* time, int i){
    fgets(time[i].nome, 100, stdin);
    scanf("%d", &time[i].gols_marcados);
    scanf("%d", &time[i].gols_sofridos);
  }

Mas também não funcionou. Tentei algumas outras coisas, mas também sem sucesso. Alguém pode explicar onde eu tô errando?

A:
Alguém pode explicar onde eu tô errando?

Nunca mistures fgets() com scanf() (ou fscanf()).
Usa sempre, exclusivamente, fgets() pata obter input do utilizador.
void entrada_dados(Time *time, int i) {
    char temp[100];
    fgets(time[i].nome, 100, stdin); // obtem "Sao Paulo\n"
    time[i].nome[strcspn(time[i].nome, "\n")] = 0; // remove o newline final
    fgets(temp, sizeof temp, stdin); // obtem, por exemplo, "30\n"
    time[i].gols_marcados = strtol(temp, NULL, 10); // falta validacao de erros
    fgets(temp, sizeof temp, stdin); // obtem, por exemplo, "23\n"
    time[i].gols_sofridos = strtol(temp, NULL, 10); // falta validacao de erros
}


text:
Q: how to give data-autoplay attribute inside css in html website i have a wordpress website, there is a slider in the homepage which is coming from some widget, the slider is static, when i inspected the element it was showing something like below:

<div class="swiper-container services-slider swiper-container-initialized swiper-container-horizontal" data-cols="3" data-autoplay="0">

now i want the slider to autoplay automatically, as i am not able to edit the code of the slider i am trying to put some css in the head section of the website so the slider plays, how can i add autoplay attribute inside css, please help, thanks in advance

A: With jquery something like this may work if the slider options have not already been rendered from the data attributes
$('.swiper-container').data('autoplay', 1)

Or
$('.swiper-container').attr('data-autoplay', 1)

With on ready
(function($){

  $(document).ready(function(){
      $('.swiper-container').attr('data-autoplay', 1)
  });

})(jQuery);


text:
Q: Normal (desktop) user-interface controls with QML? I'm currently porting one of my applications to C++ with QT as a GUI.
The QML-samples look pretty darn good, but the user-interface controls don't look like the normal ones on Windows and MacOS.
I would like to use the many cool features QML offers (like animations), but also have controls which look similar to the normal ones (as if I'd use standard QT).
Can I find some styled QML-controls somewhere or which approach would you recommend.

A: Hedge, there are 2 reasons why your UI didn't look native:
1) Qt Quick (QML) now is in a stage when only basic primitives are available. That means there are no actual UI elements (like Button, Tool Bar, etc.) available yet. There are just some of them like list views which are included in the basic set of components. There is some work that is going on by Qt guys and you can find some of the desktop components that are available here:
http://qt.gitorious.org/qt-components/desktop
Those will be look native on you desktop but they are in a very early and unstable stage at this moment.
2) Qt Quick (QML) is developed by a company named Qt Development Frameworks (former Trolltech) owned by Nokia which is in its turn is one of the largest cell phone manufactures in the world. Qt Quick is created for touch user interfaces on mobile and embedded platforms and initially was targeted for MeeGo platform. A set of QML components for MeeGo is being developed but according to Qt Development Frameworks blog is not available to the public by marketing reasons. The version that is available to the public is not outdated but you can get some idea about what is going on. Its available here:
http://qt.gitorious.org/qt-components
If your application is developed for desktop, I'd recommend to use C++/Qt for desktop framework which will provide the native look and feel for your application. Although Qt Development Frameworks recently stated that their main strategy becomes Qt Quick while passing the commercial licenses and support to a company named Digia. So maybe it makes sense to think about whether its worth to use the desktop version of Qt or not.
Hope that helps

A: You can embed QWidgets and use them from QML. It takes a little C++ and isn't as nice as pure QML widgets, but it works pretty well and gives you access to a lot of existing Qt functionality.
You can use a QGraphicsWidget as explained (briefly) here. Alternatively you can do the reverse: embed a QML interface inside a Qt GUI, using QDeclarativeView as explained here.

A: Dan, thats a way to do that but: I'd say it is a way to "just do it" without any consideration of whether its right or wrong. Further, I'm not saying that your solution is wrong, I'm just trying to explain why I believe applications should not be implemented in that way.
First of all, as I mentioned, Qt Quick, as follows from its name, is designed to create user interfaces quickly. Trying to embed Qt desktop widgets in the graphics scene will create an additional effort (which might be quite big - depending on the task) of exporting the APIs to the QML environment and making everything work. Architecture of a QML application is very different from the desktop. If you work with model-view-controller for example, exporting QTreeView and QItemDelegate to the QML and making it work may turn to a very complicated solution. In fact, if follow that concept, the easiest way would be to create all the UI in C++ backend and export the final solution to QML but that in fact is a desktop implementation that doesn't take any advantages of QML at all. If do implementations in that way, its much easier to use Qt Animation API that would provide the same "fluid" effects that QML does but just using purely QGraphicsView.
Second, if you want to use existing desktop widgets in QGraphicsView you will have to embed them as "proxy widgets" which, according to Nokia guys who work on Qt Quick and QML has big problems with performance.
Third, if you want to use QGraphicsWidget approach, it will lead you to the implementation of all widgets from scratch because there are no QGraphicsWidget-based widgets in Qt. Even for something as simple as Push Button widget you will need to write all the code yourself.
Fourth, as Nokia stated previously, they handed off Qt desktop support to a 3rd party company explaining that they focus all their effort on Qt Quick. So I would think about the maintainability of your application. Plus with upcoming QML Scene Graph all QML API will be moved on that implementation and I'm not sure whether there will still be possible to use desktop widgets with it.


text:
Q: LPC-Link2 Not Working as CMSIS-DAP with OpenOCD I'm working on a project with the NXP LPC824 using VisualGDB and OpenOCD. Using the LPCXpresso824-MAX dev board I had no trouble programming and debugging using OpenOCD. I am using the version of OpenOCD that comes with VisualGDB (0.10.0). I have recently built my first prototype PCB for this project and purchased an LPC-Link2 to use as a CMSIS-DAP debugger with it. However, I am unable to get the LPC-Link2 to work with OpenOCD. I keep getting a "CMSIS-DAP command CMD_INFO failed" error.
I have flashed the CMSIS-DAP firmware to the LPC-Link2, reinstalled the drivers, and followed any other troubleshooting tips I could find, but with no success. The LPC-Link2 works when flashed with the Segger J-Link firmware and also with the CMSIS-DAP firmware when debugging through MCUXpresso, so it does not appear to be a problem with the probe or the firmware but rather something specific to OpenOCD. There is nothing wrong with the target board because, as a workaround, I have removed the target MCU from the LPCXpresso824-MAX and am using its external debug header to debug the target MCU on my PCB.
Here is the output of my version of OpenOCD with the LPC-Link2 with debug turned on.
openocd.exe -f interface/cmsis-dap.cfg -c "debug_level 4"
Open On-Chip Debugger 0.10.0 (2019-08-28) [https://github.com/sysprogs/openocd]
Licensed under GNU GPL v2
For bug reports, read
        http://openocd.org/doc/doxygen/bugs.html
User : 14 6 options.c:60 configuration_output_handler(): debug_level: 4
User : 15 9 options.c:60 configuration_output_handler():
Info : 16 13 server.c:311 add_service(): Listening on port 6666 for tcl connections
Info : 17 16 server.c:311 add_service(): Listening on port 4444 for telnet connections
Debug: 18 19 command.c:143 script_debug(): command - init init
Debug: 20 21 command.c:143 script_debug(): command - target target init
Debug: 22 23 command.c:143 script_debug(): command - target target names
Debug: 23 26 target.c:1431 handle_target_init_command(): Initializing targets...
Debug: 24 59 cmsis_dap_usb.c:251 cmsis_dap_usb_open(): Cannot read product string of device 0x46d:0xc232
Debug: 25 65 cmsis_dap_usb.c:251 cmsis_dap_usb_open(): Cannot read product string of device 0x46d:0xc231
Debug: 26 1075 cmsis_dap_usb.c:409 cmsis_dap_usb_xfer(): error reading data: (null)
Error: 27 1081 cmsis_dap_usb.c:503 cmsis_dap_cmd_DAP_Info(): CMSIS-DAP command CMD_INFO failed.
Debug: 28 1088 command.c:630 run_command(): Command 'init' failed with error code -107
User : 29 1103 command.c:695 command_run_line():

Does anyone have any ideas as to what is going wrong? Is this a bug with OpenOCD? I have a workaround in place now so this is not holding up development, but it would be nice to get it working.


text:
Q: Why is func undefined in this context? So I have a function like
func()
{
    const curVal = this.curVal;
    const callAgain = () => { func(); };
    Axios.get('somecontroller/someaction')
        .then(response =>
        {
            const newVal = response.data.curVal;
            if(curVal === newVal)
                setTimeout(callAgain, 500);
            else
                // ....
        })
        .catch(response =>
        {
            // ...
        });
}

and my browser is complaining about the line
const callAgain = () => { func(); };

saying that func is undefined. Any idea why? How can I fix?

A: You cannot define a function the way you posted.
However, you can for example use the function keyword to define your function:
function func() {
    ...
}

func(); // it works!

Edit:
According to your comment, this is a object method declaration. In order to make this work, you first need to make sure your browser supports this particular ES2015 feature or if not, you transpile it to valid ES5.
Then you should be able to access the function using this.func():
 const callAgain = () => { this.func(); };

In case you are using func() e.g. as a callback for a DOM event, you also have to make sure that this is bound correctly in func, for example by explicitly binding it in the constructor:
constructor() {
    ...

    this.func = this.func.bind(this);
}

A: Define the function using either of the following:
function func(){ ... }

Or...
var func = function(){ ... }

When you define it like this:

func() { ... }

JavaScript thinks you're trying to execute an existing function called func, and then run the block of code { ... }


text:
Q: open link authentication using scrapy hello I have a trouble using scrapy
I want to scrap some data from clinicalkey.com
I have a id, password for my hospital and my hospital has authority of clinicalkey.com
so if I log in to my hospital's library page, I also can use clincalkey.com without authentication
But My scrapy script didn't work. I can't findout why this is not working
My script here
import scrapy

class MySpider(scrapy.Spider):
    name = 'myspider'

    def start_requests(self):
        yield scrapy.FormRequest(loginsite, formdata={'id': 'Myid', 'password': 'MyPassword'}, callback=self.after_login)

    def after_login(self, response):
        yield scrapy.Request(clinicalkeysite, callback=self.parse_datail)

    def parse_detail(self, response):
        blahblah

When I see the final response, It has message about "You need login"..

A: This site use json body form for authenification.
Try something like this:
body = '{"username":"{}","password":"{}","remember_me":true,"product":"CK_US"}'.format(yourname, yourpassword)
yield scrapy.FormRequest(loginsite, body=body, callback=self.after_login)


text:
Q: Mutiple cursors and other errors in jupyter notebook My jupyter notebook has been behaving differently from today morning. Following are the errors

*

*Whenever I run a cell its cursors remain there Check this one

*When I press "tab" for autocomplete. It just moves the line by tab instead of autocomplete or suggestion.

I tried uninstalling and installing anaconda (for LINUX). Can I anyone tell me why it is happening and how to fix it?


text:
Q: Installing virtualbox on kali linux I am running kali linux 2017.3 4.13.10-1kali2. I have tried to install and run virtualbox to practice on some old OSs. problem is virtualbox always doesn't work no matter how much I try to install different and random old versions.
`Kernel driver not installed (rc=-1908)
The VirtualBox Linux kernel driver (vboxdrv) is either not loaded or there is a permission problem with /dev/vboxdrv. Please reinstall the kernel module by executing
'/sbin/vboxconfig'
as root.
where: suplibOsInit what: 3 VERR_VM_DRIVER_NOT_INSTALLED (-1908) - The support driver is not installed. On linux, open returned ENOENT.`
This is probably because my kernel doesn't work with the newest virtualbox version. So I tried to install older versions of vb but it's still the same. I think I know that if I upgraded kali linux to it's newest release it will most probably fix it all, But you guys have no idea about how slow my internet connection is. So, I am asking if there's a trick to download and install vb version that is specifically compatible with my my current kernel version (which is 4.13.10-1kali2)?

A: Kali is not a general purpose Linux distribution. It comes with a custom kernel and other tricks.
Did you read this page : https://docs.kali.org/introduction/should-i-use-kali-linux ?
Maybe should you go to another distribution ( e.g. multi-boot to a Linux Mint - also Debian-based or other general purpose one).


text:
Q: What type of report has been created from JIRA? JIRA tracking issues by creating reports. It shows total estimate of the project, how many time have been taken by a project. What should be the outcome of the project?
Now my question is: What are the types of reports which have been generated in JIRA.

A:
We can generate following reports in JIRA:

1) Average Age Report:
It shows that how many issues are pending or unsolved. Accordingly it will generate a report and give you the particular picture of the project about pending issues.
2) Issue Created vs. Resolved Issues Report:
By the name we can understand that it will create reports for created issues and resolved issues report which will display whole the scenario of the project and display the work done by the Team.
3) Pie chart Report:
It will display issues status with different colors so we can identify the project status or sprint status easily.
4) Project Pivot Report:
It shows that how much time has been taken by the users for verifying project for the specific period?
5) Recently Created issue Report:
It will display all the detail for recently created issues which shows that how many percentage of the project is completed and how many project is pending.
6) All the dead line of the project have been followed or not, all the issues are solved or it has in progress status this all can be verified by reports.
7) We can create sprint report, Epic Report, Version Report, velocity chart, control chart, cumulative flow diagram too.

Progress Report has been shown from here:

Blue line indicates ideal task remaining and red line indicates actual task remaining.

With the help of Pie chart we can see that different status have been displayed with different colors:

8) It also gives reports of Project status or Sprint status.

A: 1) Average Age Report — Shows the average age (in days) of unresolved issues.
2) Created vs Resolved Issues Report — Shows the number of issues created vs the number of issues resolved over a given period of time.
3) Pie Chart Report — Shows the search results from a specified issue filter (or project) in a pie-chart, based on a statistic of your choice.
4) Resolution Time Report — Shows the average time taken to resolve issues.
5) Recently Created Issues Report — Shows the rate at which issues are being created.
6) Single Level Group By Report — Shows the search results from an issue filter, grouped by a field of your choice.
7) Time Since Issues Report — Shows the number of issues for which your chosen date field (e.g. 'Created') was set on a given date.
8) Time Tracking Report – Shows time to track information on issues for a particular version of a project.
9) User Workload Report * — Shows how much work a user has been allocated, and how long it should take.
10) Version Time Tracking Report * — Shows progress towards completing a given version, based on issues' work logs and time estimates.
11) Version Workload Report * — Shows how much outstanding work there is (per user and per issue) before a given version is complete.
12) Workload Pie Chart Report * — Shows the relative workload for assignees of all issues in a particular project or issue filter.


text:
Q: How to center image in Span How to center image in  tag?

           <h:graphicImage library="imgs" name="campus.png" width="25" height="25" style="align-content-center"/>

dot css
.dot {
     height: 75px;
     width: 75px;
     background-color: #bbb;
     border-radius: 50%;
     display: inline-block;
}

Don't worry about h:graphicImage, it is a JSF tag which translates to  in html. Any html class can be applied to it.
I am using Bootstrap 4.3.

A: .dot {
     display: block;
     margin-left: auto;
     margin-right: auto;
}

A: Try Display Flex and align items and justify content to center.
.dot {
 height: 75px;
 width: 75px;
 background-color: #bbb;
 border-radius: 50%;
 display: flex;
 align-items:center;
 justify-content:center;

 }

A: I gave this a try, I couldn't comment so I had to code this. I used position: absolute. Hope this helps!

.dot {
  height: 75px;
  width: 75px;
  background-color: #bbb;
  border-radius: 50%;
  display: inline-block;
}

.campus {
  position: absolute;
  top: 11.5%;
  left: 8%;
  transform: translate(-50%, -50%)
}


text:
Q: MVC 5 select dropdown no longer getting populated by jquery after changing the styling using a plugin I've just implemented bootstrap-select into my project, but I'm experiencing an issue with it.  In my project there are dropdown menus for departments and locations.  The location list is populated based on the selection of the department dropdown.  After adding the selectpicker class to the location dropdown, it no longer gets populated with data.  I'm guessing this plugin changes the dropdown in some way that is causing this to happen.
Javascript:
$(function () {
    $("#SelectedDepartment").change(function () {
        var self = $(this);
        var items="";
        $.getJSON("@Url.Action("GetLocations","Incident")/" + self.val(),
        function(data){
            $.each(data,function(index,item){
                items += "<option value='" + item.Value + "'>" + item.Text + "</option>";
            });
            $("#SelectedLocation").html(items);
        });
    });
});

View:

        Incident department/location:

        @Html.LabelFor(model => model.Departments, htmlAttributes: new { @class = "control-label col-md-4" })

            @Html.DropDownListFor(x => x.SelectedDepartment,
                                new SelectList(Model.Departments, "Value", "Text"), new { @class = "selectpicker", @title = "Select a Department"})
            @Html.ValidationMessageFor(model => model.Departments, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.Locations, htmlAttributes: new { @class = "control-label col-md-4" })

            @Html.DropDownListFor(x => x.SelectedLocation,
                                new SelectList(Model.Locations, "Value", "Text"), new { @class = "", @title = "Select a Location" })
            @Html.ValidationMessageFor(model => model.Locations, "", new { @class = "text-danger" })

A: Just use this :
$('#SelectedLocation').selectpicker('refresh');


text:
Q: iOS project won't build when certain pod files are included in files that are included in bridging header I found a bug that I'm kind of stumped by. Wondering if anyone else experienced this.
I have this MBProgressHud pod that I include in my ViewController.h. Presumably I'll use it in ViewController.m somewhere.
I also want to include ViewController.h in my bridging header so that I can write a Swift extension.
However, when I build and run, I get an error:

'MBProgressHUD.h' file not found

I've recreated the error in this project: https://github.com/zackshapiro/PodTest
Any help would be appreciated

A: Replace
#import "MBProgressHUD.h"

with
#import <MBProgressHUD/MBProgressHUD.h>

And all will be compiled. MBProgressHUD.h is a file from module MBProgressHUD therefore you can't include it with ""


text:
Q: Residual Gauge Freedom How are we still left with one Residual Gauge Freedom in the choice of Electromagnetic Potential after having already exploited the Gauge Freedom once.
As is mentioned in Halzen and Martin Section 6.9.
Doesn't choosing another scalar to induce Gauge Transformation spoils the Lorenz Gauge condition we have earlier?

A: When there are residual gauge freedoms, then it means that you are not fixing the gauge completely. For example, for the gauge
$$\nabla\cdot \vec{A}=0,\ A_0=0,$$
there is no residual gauge. But for some conditions such as $\partial^\mu\cdot A_\mu=0,$ the gauge isn't fixed completely. Because, if you take $A_\mu\rightarrow A_\mu+\partial_\mu\chi$ with $\partial^2\chi=0$, then $A_\mu+\partial_\mu\chi$ is also a gauge. To fix the gauge completely, you should assign more conditions, in our example, we can take, say $A_0=0$.


text:
Q: how to deal progressBar from another form Why does my attempt at this fail?
I made this public on Form1.Designer.cs
public System.Windows.Forms.ProgressBar progressBar1;

and I can check it shares Form
public partial class Form3 : Form

and then tried this to update increment on another form "form3"
Form1.progressBar1.Increment(10);

I made this somewhat weird try because I saw simple "classname.variablename" for using data from another form working...
PS. If I am lucky enough to understand your generous answers... I think I will be able to bite off more of your further suggestions like "how about try inheritance" or "make instance for this"... :)

A: The problem with your attempt is that you are trying to access an instance member through the class name, rather than an actual instance reference.
When you create the Form3 instance, you need to pass it the reference to the Form1 instance, preferably via the constructor. E.g.:
partial class Form3 : Form
{
    private readonly Form1 _form1;

    public Form3(Form1 form1)
    {
        _form1 = form1;
    }
}

Then you can access the ProgressBar instance like this:
_form1.progressBar1.Increment(10);

Note, however, that making the progressBar1 field public really isn't the right thing to do. It gives callers more access than they need, when your classes should be designed to give only the minimum access required.
It would be better to keep the field private and do something like this:
partial class Form1 : Form
{
    public void IncrementProgress(int i)
    {
        progressBar1.Increment(i);
    }
}

Then you'd access it like this :
_form1.IncrementProgress(10);

(still passing the Form1 instance to the constructor of Form3, of course).

Edit:
It's worth mentioning that I agree with the general sentiment expressed in the question comments that a better approach is for Form3 to expose some kind of progress event, and for Form1 to subscribe to that, rather than requiring Form3 to specifically know about the Form1 class at all.
The above code examples address the specific question, but if you are interested in a better design, it would look something like this:
partial class Form3 : Form
{
    public event EventHandler IncrementProgress;

    void SomeMethodWhereProgressHappens()
    {
        // ... make some progress

        // Then raise the progress event
        EventHandler handler = IncrementProgress;

        if (handler != null)
        {
            handler(this, EventArgs.Empty);
        }

        // ... then make some more progress, etc.
    }
}

and in your Form1 class:
partial class Form1 : Form
{
    void SomeMethodThatShowsForm3()
    {
        Form3 form3 = new Form3();

        form3.IncrementProgress += (sender, e) => progressBar1.Increment(10);
        form3.Show();
    }
}

Note that in this approach, the Form3 class doesn't have any code at all that depends on the Form3 class specifically, and Form1 does not need to expose the ProgressBar instance in any way, not even via some proxy method.
Finally note that the reason an event is appropriate in this scenario is because of the callback nature of the operation. There are other scenarios where some caller, e.g. the code instantiating the class object itself, simply wants to set certain properties that map to control properties. In this case, the delegation/proxy approach I showed as the initial solution is still appropriate. It's a good technique to learn and use when it applies.

A: You need to create a public property on Form1:
public ProgressBar MyProgressBar
{
    get
    {
        return progressBar1;
    }
}

Then you can access it from Form3:
form1.MyProgressBar.Increment(10);

You'll probably need to create a property in Form3 also:
public Form MainForm
{
    get; set;
}

So when you open Form3, you'll do this:
Form3 form3 = new Form3();
form3.Show();
form3.MainForm = this;


text:
Q: Bind Icon in dropdown list in Vue Js I have a dropdown in Vue.Js, I need to Bind Font Awesome icon after each dropdown items.
I am new to Vue.js so please guide how to do that. I am using below code to bind items in dropdown
<select id="testID" v-model="testModel" v-on:change="changeEvent">
  <option v-bind:value="da" v-for="da in data.Users">
    {{da.DisplayText}}
  </option>
<select>

What i have tried so Far
I tried to use  element inside option tag but did not get any thing. I tried below syntax also
<select id="testID" v-model="testModel" v-on:change="changeEvent">
  <option v-bind:value="da" v-for="da in data.Users">
    {{da.DisplayText}}

  </option>
<select>

I tried Image tag also but no luck so far. I am using  tag because i need to raise a javascript event on mouse over of each drop down item.
Please help

A: Instead use the Unicode version of the icon instead.
For the circle icon the unicode value is 
Link to icon.
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.1/css/font-awesome.min.css" rel="stylesheet"/>
<select id="testID" v-model="testModel" v-on:change="changeEvent">
    <option v-bind:value="da" v-for="da in data.Users">{{da.DisplayText}} </option>
</select>

Check out this related post. Should answer your question.


text:
Q: Regex to match content in last set of brackets, regardless of how many empty or filled brackets there are Really struggling with this... trying to write a regex that pulls out the content in the last set of brackets even if there is no content (blank string). If it's helpful, the brackets will not nest inside one another.
Examples:
[][] => ""
[][a] => "a"
[a][] => ""
"a" => null
[][a][c][d][b] => "b"
ad[a][c][d] => "d"
[a][ra]dds[c] => "c"

A: Why not go with something simple:
var re = /\[([^\]]+)\]/gim;

Looking back on it, it looks like a jumble of brackets. But it just finds two brackets and captures the character(s) inside them.
To find the last match, you just iterate through the array of matches.
If there is no match, but you still want to know if there are any empty brackets, you can JS's built in functions for strings. (I think it's indexOf("[]")). That will be faster than doing a regex.
Simple!

A: var re = /\[([^[]*)\]$/;

This is similar to @Laurel's solution, but uses $ to find the last set of brackets directly, and allows it to be empty.

A: This solves your problem in one go without having to recheck the string:
var re = /.*\[([^\]]*)\]/;

The reason why this works is because the .* is greedy and will select everything up until the last instance of [ (anything but "]") ], with this last instance being the match. Thus, match 1 will have your expected result.
Here's the railroad diagram:

Here's the Regex101.
And here is a Stack Snippet of the test strings and match strings:

var testStrings = ['[][]', '[][a]', '[a][]', 'a', '[][a][c][d][b]', 'ad[a][c][d]', '[a][ra]dds[c]', '[a][ra]dasdf[c]asdf', '[][][]asdf', '[][]asdf][]', '[][a][asdfas][awef]asdf][]'];

var re = /.*\[([^\]]*)\]/;

testStrings.forEach(function(str) {
    var res = str.match(re) && str.match(re)[1]; /* re.exec(str) instead of str.match(re) also works */
    document.querySelector('.matchString').insertAdjacentHTML('beforeend', `<div>Match String: <span class='results'>${res}</span></div>`);

  document.querySelector('.testString').insertAdjacentHTML('beforeend', `<div>Test String: <span class='results'>${str}</span></div>`);
});
.testString {
  width: 50%;
  height: auto;
  float: left;
}

.matchString {
  width: 50%;
  height: auto;
  float: right;
}

.results {
  font-weight: bold;

}


text:
Q: How do I choose an ImageReader buffer type for my Android camera app? I have an app with a camera function. I'm using the Android Camera2 API. I've found that some Android devices (e.g. Nexus 6p, Nexus 5) work better if the ImageReader is configured to provide JPEGs:
imageReader = ImageReader.NewInstance(width, height, ImageFormatType.Jpeg, 2);

And some Android devices (e.g. Nexus 7 2013) work better if the ImageReader is configured to provide, say, RGBA_8888:
imageReader = ImageReader.NewInstance(width, height, (ImageFormatType)1 /* PixelFormat.RGBA_8888 */, 2);

The device that works better with JPEGs spits out this error if I use RGBA_8888:
[ImageReader_JNI] Producer output buffer format: 0x22, ImageReader configured format: 0x1

The device that works better with RGBA buffers spits out this warning if I use JPEGs: (It still works, but it's slow enough that the captured picture is dark.)
[ImageReader_JNI] ImageReader_lockedImageSetup: Receiving JPEG in HAL_PIXEL_FORMAT_RGBA_8888 buffer.

I have to do some processing on what I get back, so ultimately it would be better if I could configure the camera to just spit out some sort of bitmap rather than a JPEG, since I have to convert the JPEG to a Bitmap before continuing.
How should I choose what buffer type to pass to the ImageReader?

A: The only guaranteed formats that all camera devices must support are YUV_420_888 and JPEG; even at that, LEGACY-level devices generally only support JPEG at maximum resolution (and YUV_420_888 at preview resolutions, not generally higher than 1080p).
You should be checking the list of supported formats in the device's StreamConfigurationMap instead of just blindly trying some - while some devices may support random formats not listed in their official list, there's not much guarantee about how well they'll do so.
JPEG capture tends to be slower because LEGACY-level devices assume that when you want a JPEG, you want maximum still capture quality, which takes more post-processing than just a preview frame; plus, LEGACY devices may do flash metering and firing.  LIMITED or better devices allow you to control the post-processing quality, so it's not tied to the output format, and also generally support higher resolutions of YUV capture.
I'd generally stay away from RGBA if you want wide support - it working with LEGACY devices is a bit of a quirk, and LIMITED and better devices are unlikely to support it.
When you say that JPEG works, but is slow enough that the captured image is dark, I'm a bit confused - why does slowness mean a dark image? Or do you just mean the images come out dark?


text:
Q: Uniform convergence of $f_n = (n^a x^2)/(n^2 +x^3)$ My question is, if you have the sequence $$f_n = \frac{n^\alpha x^2}{n^2 +x^3}$$ on $[0, \infty)$, for values of a for $0<\alpha<2$ does the sequence uniformly converge?
I guess another way to think about it is what values can $a$ take such that
$$\lim_{n \rightarrow \infty} \left(\sup_{x \in [0,\infty)}\left[\frac{n^a x^2}{n^2 +x^3}\right]\right) = 0. $$
I'm having trouble proving this.. but I think that intuitively, $\alpha$ can be less than or equal to 1.
Thanks for the help.

A: If you work the problem out using the technique, then you will find that the maximum is achieved at

$$x=(2n^2)^{1/3}$$

and is given by

$$ \frac{ 2^{ \frac{2}{3}} }{3} n^{ a - \frac{2}{3}}.$$

Now, you should be able to finish the problem.


text:
Q: hide a div when user zoom out on touch screen device I need to hide a div using jQuery when user on touch scale down to original scale
var zoom = document.documentElement.clientWidth / window.innerWidth;
    $(window).resize(function(){
        var zoomNew =
         document.documentElement.clientWidth / window.innerWidth;
        if (zoomNew < zoom){
            galleryZoomOut();
        }

    });

    function galleryZoomOut() {
        $('#gallery_container').hide();
    }

but for some reason is not working


text:
Q: Extend the Stone-Weierstrass theorem to high dimension? I am thinking of if there is high dimensional extension to the well known Stone-Weirstrass theorem.
Wikipedia says it is possible to extend the 1D theorem to 2D, i.e.
If  f  is a continuous real-valued function defined on the set [a, b] × [c, d] and ε > 0, then there exists a polynomial function p in two variables such that | f (x, y) − p(x, y) | < ε for all x in [a, b] and y in [c, d].
Is it free to say it also works on 3D or multi-D? Or some additional conditions are required?

A: In fact, Wikipedia says that the Stone-Weierstrass theorem can be extended to continuous real-valued functions over an arbitrary Hausdorff and compact topological space $X$.
It particular: this means that if $f$ is a continuous real-valued function defined on any closed and bounded subset $X \subset \mathbb{R}^n$ for any $n\in \mathbb N$, then for any $\epsilon > 0$, there exists a polynomial $p(x_1,\dots,x_n)$ such that
$$
|f(x_1,\dots,x_n) - p(x_1,\dots,x_n)| < \epsilon
$$
For any $(x_1,x_2,\dots,x_n) \in X$.
This certainly includes the $n$-dimensional rectangles $X = [a_1,b_1]\times \cdots \times [a_n ,b_n]$.


text:
Q: Spring Boot JPA One To Many and Many to One With Multiple Tables I have 5 Tables, A User can have many module/role/plant. user_master is the main table with user details and user_roles is the sub table with module/role/plant details. My doubt is how to write the relationship in Model Class.
user_master
------------
user_id int(10) unsigned
first_name  varchar(50)
last_name   varchar(50)
mail_id varchar(80)
user_status tinyint(4)
is_deleted  tinyint(4)
created_by  int(10)
created_date    date
modified_by int(10)
modified_date   date

user_roles
-----------
user_role_id    int(10) unsigned
user_id int(10) unsigned
module_master_id    int(10) unsigned
role_master_id  int(10) unsigned
plant_master_id int(10) unsigned

module_master:
module_master_id    int(10) unsigned
module_code int(10)
module_name varchar(50)
active_flag tinyint(4)

role_master:
role_master_id  int(10) unsigned
module_master_id    int(10) unsigned
role_code   int(10)
role_name   varchar(50)
active_flag tinyint(4)

plant_master:
plant_master_id int(10) unsigned
plant_code  int(10)
plant_name  varchar(50)
active_flag tinyint(4)

The remaining module/role/plant have their own masters, master_id are primary key to master tables.
I just want to write user_master and user_roles model class. One-to-many & many-to-one mapping is required.

A: For one to many, you can have like below in your entity class:

*

*@OneToMany in user entity
@OneToMany(mappedBy = "user")
private List<Role> roles;

*@ManyToOne at roles side
@ManyToOne
@JoinColumn(name = "user")
private User user;

@ManyToMany
@ManyToMany(cascade = {
    CascadeType.PERSIST,
    CascadeType.MERGE
})
@JoinTable(name = "user_role",
    joinColumns = @JoinColumn(name = "user_id"),
    inverseJoinColumns = @JoinColumn(name = "role_id")
)
private List<Role> roles= new ArrayList<>();

and role side:
    @ManyToMany(mappedBy = "role")
    private List<User> users = new ArrayList<>();

here is an example to have many to many with emdeded:
    @Entity
    public class UserRoleMaster implements Serializable {

    @EmbeddedId
    private UserRoleMasterId id;

    @ManyToOne
    @JoinColumn(name = "user_master_id", referencedColumnName = "user_master_id", insertable = false, updatable = false)
    private UserMaster userMaster;

    @ManyToOne
    @JoinColumn(name = "user_roles_id", referencedColumnName = "user_roles_id", insertable = false, updatable = false)
    private UserRoles userRoles;

    //getter  //setter //constructures

       @Embeddable
       public static class UserRoleMasterId implements Serializable {

        @Column(name = "user_master_id")
        protected Long userMasterId;

        @Column(name = "user_roles_id")
        protected Long userRolesId;
       //constrcture //getter //setters
   }
 }


text:
Q: mysqltuner - Write Key buffer hit rate I'm pasting section of MySQL Tuner result regarding MyISAM Metrics.
[OK] Currently running supported MySQL version 5.5.57-0ubuntu0.14.04.1-log
[OK] Operating on 64-bit architecture

-------- Performance Metrics -----------------------------------------------------
[--] Up for: 25d 1h 40m 20s (6M q [3.149 qps], 170K conn, TX: 15G, RX: 1G)
[--] Reads / Writes: 90% / 10%

-------- MyISAM Metrics ----------------------------------------------------------
[!!] Key buffer used: 20.1% (80M used / 402M cache)
[OK] Key buffer size / total MyISAM indexes: 384.0M/31.6M
[OK] Read Key buffer hit rate: 99.9% (7M cached / 4K reads)
[!!] Write Key buffer hit rate: 1.2% (2M cached / 25K writes)

I'm looking for way to improve or optimize the Write Key buffer hit rate. Or why is it so bad?
I don't know which server variables may play role in this result, so please let me know what variables should I paste here or if you need any specific details.
Thanks for help!
UPDATE 2017-08-11 13:56 CET
I did some more tests based on recommendations from @RolandoMySQLDBA and it really seems I should not worry about this metric. After I lowered the key_buffer_size, the Write buffer key hit rate improved directly. However, I couldn't measure any improvement in speed of reads. I assume it's because there was not enough memory for cache, so almost all writes went through. I still don't really understand what is the good or bad thing about Write buffer key hit rate, but it seems to be related to optimal size of key buffer based on the data and index in database.

A: OK, the hit rate is low.  But let's put things in perspective...  25K writes in 25 days is so insignificant (< 1/minute) as to be the least of your worries.  5K/minute would be a concern.
If you are having performance problems, locate the slowest query and study it -- its indexes, its formulation, etc.
The "key buffer" applies to MyISAM tables, of which you have only 1.  The InnoDB statistics are not listed.
For further discussion, see http://mysql.rjweb.org/doc.php/mysql_analysis

A: You are still using MyISAM ??? OUCH !!!
All kidding aside, you need two status variables:

*

*Key_write_requests : The number of requests to write a key block to the MyISAM key cache

*Key_writes : The number of physical writes of a key block from the MyISAM key cache to disk

You want the ratio Key_writes/Key_write_requests to be as close to 1 (100%) as possible. I wrote a nice set of queries you can run to see such ratios. You can find it in my Jun 17, 2013 answer to the post MyISAM key buffer
Perhaps just running FLUSH TABLES; will clear away whatever index changes are lingering. If your system does not do heavy writes, this is probably all you need.
I recommend converting everything you have to InnoDB so your database can survive a crash. After all, you do not want any changes to an index to linger.
Take a quick look at the InnoDB Plumbing (picture from Percona CTO Vadim Tkachenko)

See the InnoDB Buffer Pool on the Left ? It has an Insert Section responsible for index changes. InnoDB would automatically flush index changes for you. No such mechanism exists for MyISAM. So, please convert to InnoDB ASAP.
UPDATE 2017-08-07 15:25 EDT
If you must go on using MyISAM, you should look into using Dedicated MyISAM Key Caches. You can create a key buffer for specific set of MyISAM tables. In your case, you would create a dedicated key cache for the one table with the FULLTEXT indexes. You would have to judge how big or how small to make the cache.
Suppose your table with the FULLTEXT indexes is mydb.myfull.
You could then run this to find the proper size rounded up to the nearest MB
SELECT index_length,((FLOOR(index_length / 1048576) + 1) * 1048576) index_length_rounded
FROM information_schema.tables WHERE table_schema='mydb' and table_name='myfull';

Whatever number comes back for index_length_rounded is the size you use.
Please look up my posts about how to create Dedicated MyISAM Key Caches.
I would not worry too much about this since the INSERTs and UPDATEs seems so rare.


text:
Q: Rename .id column in ldply Is there a way to assign a custom name to the column that is normally named .id in the result of ldply?
> ldply(setNames(1:3, 1:3), function(i) data.frame(j=1/i))
  .id         j
1   1 1.0000000
2   2 0.5000000
3   3 0.3333333

I know I can call rename on the result, but I'd like to do it in one call. Any suggestions?
Note that adply suffers from a similar problem:
> adply(as.array(setNames(1:3, 1:3)), 1, function(i) data.frame(j=1/i))
  X1         j
1  1 1.0000000
2  2 0.5000000
3  3 0.3333333

Another related question addresses the issue of renaming the "data" columns, but the answer also fails to provide a solution for the .id column.

A: I have proposed an implementation, let's see if it makes it into official plyr. Basically, a new parameter .idname that allows specifying the name of the .id column, with an option to drop it altogether by passing NULL:
> ldply(setNames(1:3, 1:3), function(i) data.frame(j=1/i), .idname='i')
  i         j
1 1 1.0000000
2 2 0.5000000
3 3 0.3333333

. Install the tweaked version using
library(devtools)
install_github('plyr', 'krlmlr', ref='140-142-id')

EDIT: This is now available in plyr 1.8.1 on CRAN:
> ldply(setNames(nm=1:3), function(i) data.frame(j=1/i), .id='i')

A: You seem comfortable using setNames, so you can move the "j" and the "newname" assingment to a convenient wrapper.
setNames( ldply(setNames(1:3, 1:3), function(i) data.frame(1/i)) , c("newname", "j") )
  newname         j
1       1 1.0000000
2       2 0.5000000
3       3 0.3333333


text:
Q: Changing \@itemdepth value to control indentation I would like to be able to control the nesting level of an item (so that I can align the text with text that is at a deeper level of nesting.)  I have been able to read the value of \@itemdepth counter.  I was not able to change it.  Is it possible to change the value of \@itemdepth from my file and if so, how would I do it?  Or is there a better way to do what I want to do?  Thanks for any help you can provide.
A sample of the code I would like to get working.  I am new to LaTeX and the code likely has several errors in it.  Any help would be appreciated.
\documentclass{article}
\usepackage{amssymb, amsmath}
\usepackage{ifthen}

\makeatletter   % needed to access \@itemdepth
\newcounter{hangparsindentedlevel}

\newenvironment{hangpars}[1][0]{%
   \begin{list}{}{%
      \setcounter {hangparsindentedlevel}{\@itemdepth}%
      \ifthenelse {#1 > 0} { %
         \setcounter {\@itemdepth}{#1}%
         }%
         {%
         \relax%
         }%
      \setlength{\itemindent}{-\leftmargin}%
      \setlength{\listparindent}{-\leftmargin}%
      \setlength{\partopsep}{0in} \setlength{\parskip}{0in} \setlength{\topsep}{0in}%
      }%
      \item{}%
   }%
   {\end{list}}%
\makeatother

\begin{document}

\begin{hangpars}[0]
test text 1.  test text 1. test text 1.  test text 1. test text 1.  test text 1. test text 1.  test text 1. test text 1.  test text 1.

\begin{hangpars}[2]
test text 2.  test text 2. test text 2.  test text 2. test text 2.  test text 2. test text 2.  test text 2. test text 2.  test text 2.
\end{hangpars}

test text 3.  test text 3. test text 3.  test text 3. test text 3.  test text 3. test text 3.  test text 3. test text 3.  test text 3.

\end{hangpars}

\end{document}

The output I was hoping for would have the firt line of the paragraph with test text 1 starting at the left most edge and all subsequent lines of the paragraph would be indented one level.
The first line of the paragraph with test text 2 (with the hangpars[2]) would start indented two levels from the left edge and all subsequent lines of the paragraph would be indented three levels.
The last paragraph would be formated as the first paragraph was.
test text 1.  test text 1. test text 1.  test text 1. test text 1.
      test text 1. test text 1.  test text 1. test text 1.
      test text 1.
            test text 2.  test text 2. test text 2.  test text 2.
                  test text 2.  test text 2. test text 2.  test
                  text 2. test text 2.
test text 3.  test text 3. test text 3.  test text 3. test text 3.
      test text 3. test text 3.  test text 3. test text 3.
      test text 3.

A: If that is all you want to do it is easiest just to use a list environment, such as the enumitem package.
There is a lot more flexibility that is already built into this environment, so unless there really is a good reason to build your own, I would try to see if you can accomplish what you want with an existing package.  Here I have defined a new hangpars list for you and specified some settings to be used at each level of the list. Adjust these as you wish.  The code below produces:

\documentclass{article}
\usepackage{enumitem}

\newlist{hangpars}{itemize}{5}%
\setlist[hangpars]{label={}}% no labels for all levels
\setlist[hangpars,1]{leftmargin=0cm,itemindent=-0.7cm}%
\setlist[hangpars,2]{leftmargin=2cm,itemindent=-0.7cm}%
\setlist[hangpars,3]{leftmargin=4cm,itemindent=-0.7cm}%
\setlist[hangpars,4]{leftmargin=5cm,itemindent=-0.7cm}%

\begin{document}
\begin{hangpars}
\item test text 1.  test text 1. test text 1.  test text 1. test text 1.
test text 1. test text 1.  test text 1. test text 1.
test text 1.
\begin{hangpars}
\item test text 2.  test text 2. test text 2.  test text 2.
test text 2.  test text 2. test text 2.  test
text 2. test text 2.
\end{hangpars}
\end{hangpars}
\begin{hangpars}
\item test text 3.  test text 3. test text 3.  test text 3. test text 3.
test text 3. test text 3.  test text 3. test text 3.
test text 3.
\end{hangpars}
\end{document}


text:
Q: d3 Adding cells to an existing table I'm having some problems getting this to work.  I have an existing HTML table and would like to use d3 to append some data to the table.
Here's the HTML table:

       Header 1
       Header 2
       Header 3
       Header 4
       Header 5
       Header 6

For now I just want to append some additional headers to this so I use d3

I hope this isn't too hard to understand without having the actual data available.  Basically my data set has values for every month for the next several years.  I want to create a new  header for each month in the data set.  Currently my code above is appending  headers to my original table but it's missing the first 6 months of the data set.  I suspect my d3 code is starting to append the data at the first Header which is not what I want obviously.
I also tried giving my 6th header an ID and appending to that but it didn't quite work out well.  It seemed to have started a new row of headers underneath it. Besides I feel like that isn't the proper way of doing this.

A: Did this by creating a new class so that d3 appends new types of  instead of "thinking" I want to select the  already there.: