text:
Q: How to managed multiple emit event using socket.io in javascript I've made a demo app to understand how socket.io 'emit' works. In client file I have defined a function that emit some value to server and this function is call in loop 5 times and server job is to return that value back to client.
My web client: client.html
    var socket = io('http://127.0.0.1:8586', {transports: ['websocket']});

    function test2( dataSend ){
        console.log("FUNCTION 'test2()' loop test - > emit to SRV: " + dataSend);

        socket.emit('emitFromClient', dataSend);

        socket.on('feedback_emitFromClient', function (data) { // listen to news event raised by the server
            console.log("Received data from server: " + JSON.stringify(data)); //+ " || typeof: " + typeof data["result"]);
        });
    }

    for (var i = 1; i <= 5; i++)
        test2(i);

NodeJS server app: server.js
 const express = require('express');
 const app = express();
 const http = require('http');
 const server = http.createServer(app);

app.use(express.static('socketTest1'));

const io = require('socket.io')(server);//, { origins: '*:*'});

io.sockets.on('connection', function(socket){
  console.log('a user connected!');

    var socketId = socket.id;
    var clientIp = socket.request.connection.remoteAddress;

    console.log("clientIp: " + clientIp + " || socketId: " + socketId);

     socket.on('emitFromClient', function (data) {
        console.log("debug -  received event (emitFromClient) from client, socket id: "  + socket.id  + " || value: " + data );
        let ts = Date.now();
        console.log("debug -  send data from SRV to client ->  data: " + data);
        socket.emit('feedback_emitFromClient', { result: Math.floor(ts/1000), data: data }); // Send data to client
     });

server.listen(8586, '127.0.0.1', function(){
  console.log('listening on *:8586');
});

In actual state I've received in console client something like that:
First, all emit events are done and then are displayed all data from server
  > EMIT event 1 from CLIENT, value: 1
  > EMIT event 2 from CLIENT, value: 2
  ..................................
  > EMIT event 5 from CLIENT, value: 5

  < Received data from server, value: 1
  < Received data from server, value: 2
  ........................................
  < Received data from server, value: 5

I want to modified this demo to work like this, after every single emit event to received an answer from server
 > EMIT event 1 from CLIENT, value: 1
 < Received data from server, value: 1

 > EMIT event 2 from CLIENT, value: 2
 < Received data from server, value: 2

Can anyone explain to me what I did wrong?

A: You did nothing wrong, you just expect a wrong thing.
You send all data at the same time
for (var i = 1; i <= 5; i++)
    test2(i);

Thats why you see the log
  > EMIT event 1 from CLIENT, value: 1
  > EMIT event 2 from CLIENT, value: 2
  ..................................
  > EMIT event 5 from CLIENT, value: 5

Because you are not waiting to the response to send the next.
If you want to wait for the response you should write something like:
const socket = io();

function emit(testSent){
    console.log("FUNCTION 'emit()' test - > emit to SRV: " + testSent);
    socket.emit('emitFromClient', testSent);
}

function test2( dataSend , numberOfReplys){
    var replies=0;
    emit(dataSend)
    socket.on('feedback_emitFromClient', function (data) { // listen to news event raised by the server
        console.log("Received data from server: " + JSON.stringify(data)); //+ " || typeof: " + typeof data["result"]);
        if(numberOfReplys>replies){
            emit(dataSend);
            replies++;
        }
    });
}

test2(5,5);

server log:
debug -  received event (emitFromClient) from client, socket id: Js3F7F267s0P5DRAAAAN || value: 5
debug -  send data from SRV to client ->  data: 5
debug -  received event (emitFromClient) from client, socket id: Js3F7F267s0P5DRAAAAN || value: 5
debug -  send data from SRV to client ->  data: 5
debug -  received event (emitFromClient) from client, socket id: Js3F7F267s0P5DRAAAAN || value: 5
debug -  send data from SRV to client ->  data: 5
debug -  received event (emitFromClient) from client, socket id: Js3F7F267s0P5DRAAAAN || value: 5
debug -  send data from SRV to client ->  data: 5
debug -  received event (emitFromClient) from client, socket id: Js3F7F267s0P5DRAAAAN || value: 5
debug -  send data from SRV to client ->  data: 5
debug -  received event (emitFromClient) from client, socket id: Js3F7F267s0P5DRAAAAN || value: 5
debug -  send data from SRV to client ->  data: 5

But a better way to do this is to save a timestamp and order all the messages dependending of this date before showing them.
Synchrony is complex =)


text:
Q: 32 bit Qt app crashes randomly on Windows 7 x64 We have an old codebase which we develop using C++ Qt framework (v4.6.3) under Windows XP SP3. The app that is built with that codebase is working free of problems under Windows XP.
Upon customer request we deployed the app to Windows 7 x64 machines. After that we came across with random crash issues in release build when we try to start the app. App consumes nearly 2GB of memory when it crashes. If we change app compatibility to Windows XP SP3, the crash problem goes away. Also crash never happens in debug mode.
We collected some logs about crash issue. Below logs are given:
1. Windows log after app crashes.
Problem signature:
  Problem Event Name: APPCRASH
  Application Name: kmclient3.exe
  Application Version: 0.0.0.0
  Application Timestamp: 55b72d4f
  Fault Module Name: KERNELBASE.dll
  Fault Module Version: 6.1.7601.18409
  Fault Module Timestamp: 53159a86
  Exception Code: e06d7363
  Exception Offset: 0000c42d
  OS Version: 6.1.7601.2.1.0.256.48
  Locale ID: 1055
  Additional Information 1: 9c29
  Additional Information 2: 9c2952f45ffd526b51f7caf2e8b92e02
  Additional Information 3: e72c
  Additional Information 4: e72c8eab1d594c6991d297d4615a53d6

2.WinDbg log when we attach debugger after the app crashes.
** wait with pending attach

Symbol search path is: E:\Symbols
Executable search path is:
ModLoad: 01220000 014f7000     E:\YERLISINYAL09\YAZILIM\build\TKM_crash_test\kmclient3.exe
ModLoad: 76dd0000 76f79000   C:\Windows\SYSTEM32\ntdll.dll
ModLoad: 76fb0000 77130000   ntdll.dll
ModLoad: 00000000`748f0000 00000000`7492f000   C:\Windows\SYSTEM32\wow64.dll
ModLoad: 00000000`74890000 00000000`748ec000   C:\Windows\SYSTEM32\wow64win.dll
ModLoad: 00000000`74880000 00000000`74888000   C:\Windows\SYSTEM32\wow64cpu.dll
ModLoad: 00000000`769f0000 00000000`76b00000   KERNEL32.dll
ModLoad: 00000000`74c30000 00000000`74c77000   KERNELBASE.dll
ModLoad: 00000000`596e0000 00000000`5971e000   UMEngx86.dll
ModLoad: 00000000`67000000 00000000`67211000   QtCore4.dll
ModLoad: 00000000`74ad0000 00000000`74bd0000   USER32.dll
ModLoad: 00000000`75310000 00000000`753a0000   GDI32.dll
ModLoad: 00000000`75100000 00000000`7510a000   LPK.dll
ModLoad: 00000000`75a60000 00000000`75afd000   USP10.dll
ModLoad: 00000000`76920000 00000000`769cc000   msvcrt.dll
ModLoad: 00000000`74c90000 00000000`74d30000   ADVAPI32.dll
ModLoad: 00000000`76760000 00000000`76779000   SECHOST.dll
ModLoad: 00000000`75220000 00000000`75310000   RPCRT4.dll
ModLoad: 00000000`74950000 00000000`749b0000   SspiCli.dll
ModLoad: 00000000`74940000 00000000`7494c000   CRYPTBASE.dll
ModLoad: 00000000`754c0000 00000000`7561c000   ole32.dll
ModLoad: 00000000`757b0000 00000000`757e5000   WS2_32.dll
ModLoad: 00000000`74c80000 00000000`74c86000   NSI.dll
ModLoad: 00000000`5a5a0000 00000000`5a62e000   MSVCP90.dll
ModLoad: 00000000`737f0000 00000000`73893000   MSVCR90.dll
ModLoad: 00000000`65000000 00000000`657a7000   QtGui4.dll
ModLoad: 00000000`749b0000 00000000`74a2b000   COMDLG32.dll
ModLoad: 00000000`757f0000 00000000`75847000   SHLWAPI.dll
ModLoad: 00000000`5ce00000 00000000`5ce84000   COMCTL32.dll
ModLoad: 00000000`75b00000 00000000`7674a000   SHELL32.dll
ModLoad: 00000000`76b10000 00000000`76b9f000   OLEAUT32.dll
ModLoad: 00000000`74bd0000 00000000`74c30000   IMM32.dll
ModLoad: 00000000`75120000 00000000`751ec000   MSCTF.dll
ModLoad: 00000000`5a560000 00000000`5a592000   WINMM.dll
ModLoad: 00000000`74810000 00000000`74861000   WINSPOOL.DRV
ModLoad: 00000000`61000000 00000000`61055000   QtXml4.dll
ModLoad: 00000000`66000000 00000000`66045000   QtSvg4.dll
ModLoad: 00000000`64000000 00000000`640ea000   QtNetwork4.dll
ModLoad: 00000000`62000000 00000000`62031000   QtSql4.dll
ModLoad: 00000000`70c40000 00000000`70cc0000   UxTheme.dll
ModLoad: 00000000`70c20000 00000000`70c33000   dwmapi.dll
ModLoad: 00000000`753a0000 00000000`75423000   CLBCatQ.DLL
ModLoad: 00000000`59540000 00000000`5969d000   inkobj.dll
ModLoad: 00000000`72110000 00000000`72124000   ATL.DLL
ModLoad: 00000000`00e90000 00000000`01020000   gdiplus.dll
ModLoad: 00000000`732c0000 00000000`732d6000   CRYPTSP.dll
ModLoad: 00000000`73270000 00000000`732ab000   RSAENH.dll
ModLoad: 00000000`72f30000 00000000`72f3e000   RpcRtRemote.dll
ModLoad: 00000000`59530000 00000000`5953d000   TpcPS.DLL
ModLoad: 00000000`10000000 00000000`10011000   qsqlmysql4.dll
ModLoad: 00000000`550e0000 00000000`55677000   libmysql.dll
ModLoad: 00000000`735f0000 00000000`735f8000   Secur32.dll
ModLoad: 00000000`72f90000 00000000`72fa0000   nlaapi.dll
ModLoad: 00000000`72f60000 00000000`72f70000   NAPINSP.dll
ModLoad: 00000000`72f40000 00000000`72f52000   PNRPNSP.dll
ModLoad: 00000000`734c0000 00000000`734fc000   MSWSOCK.dll
ModLoad: 00000000`72ee0000 00000000`72f24000   DNSAPI.dll
ModLoad: 00000000`72ed0000 00000000`72ed8000   WINRNR.dll
ModLoad: 00000000`6de50000 00000000`6de56000   rasadhlp.dll
ModLoad: 00000000`734b0000 00000000`734b5000   WSHTCPIP.dll
Break-in sent, waiting 30 seconds...
WARNING: Break-in timed out, suspending.
         This is usually caused by another thread holding the loader lock
(1a2c.106c): Wake debugger - code 80000007 (first chance)
*** ERROR: Symbol file could not be found.  Defaulted to export symbols for KERNELBASE.dll -
KERNELBASE!RaiseException+0x58:
74c3c42d c9              leave
0:000:x86> g
** ERROR: Symbol file could not be found.  Defaulted to export symbols for C:\Windows\SYSTEM32\ntdll.dll -
ntdll!NtWaitForWorkViaWorkerFactory+0xa:
00000000`76e22bba c3              ret
0:004> g
       ^ No runnable debuggees error in 'g'

3.WinDbg log when we open crash dump.
Loading Dump File [C:\Users\onur.ozcelik.BILISIM\Desktop\kmclient3.DMP]
User Mini Dump File with Full Memory: Only application data is available

Symbol search path is: E:\Symbols
Executable search path is:
Windows 7 Version 7601 (Service Pack 1) MP (12 procs) Free x86 compatible
Product: WinNt, suite: SingleUserTS
Machine Name:
Debug session time: Tue Jul 28 10:46:30.000 2015 (GMT+3)
System Uptime: 0 days 2:42:56.184
Process Uptime: 0 days 0:02:46.000
........................................................
*** ERROR: Symbol file could not be found.  Defaulted to export symbols for ntdll.dll -
eax=00000002 ebx=0000000b ecx=00000000 edx=00000000 esi=00000002 edi=00407c58
eip=76fd1f46 esp=036ffac4 ebp=036ffc24 iopl=0         nv up ei pl zr na pe nc
cs=0023  ss=002b  ds=002b  es=002b  fs=0053  gs=002b             efl=00000246
ntdll!NtWaitForWorkViaWorkerFactory+0x12:
76fd1f46 83c404          add     esp,4
0:000> g
       ^ No runnable debuggees error in 'g'

What causes the crash issue?
Any ideas or suggestions?

A: This simply means there is a bug in your program. Without seeing the code its hard to tell where. I would suggest using cout or printf or qDebug() to detect the last line upto where the code runs well. This will give you the area where error is occurring. This is how I resolved my bug in multi thread program. I would also suggest you to read this.

redpajama_set_name: RedPajamaStackExchange


text:
Q: INSERT INTO SELECT,copy value+ 'string' I need to copy a row .Copied row,I need to change value, this value + 'copy'
I made this sql..but it's not work..
INSERT INTO prizes_i18n (
  lang_id
  , translation_name
  , translation_desc
  , name
  , lang_path)
SELECT  prizes_s.lang_id
        , prizes_s.translation_name +  'copy'
        , prizes_s.translation_desc
        , prizes_s.name
        , prizes_s.lang_path
FROM    prizes_i18n prizes_s
WHERE   prizes_s.lang_id = 637;

Without + 'copy' its works.
Like this prizes_s.translation_name +  'copyy',but it's not work.

A: From this previous question you use MySQL? If so use concat for string concatenation.
SELECT 'foo' + 'bar' ...

Returns 0 in MySQL which would explain the error about doubles you are seeing.
INSERT INTO  prizes_i18n (lang_id, translation_name, translation_desc,
                          name, lang_path)
SELECT  prizes_s.lang_id,
    concat(prizes_s.translation_name, 'copy'),
    prizes_s.translation_desc, prizes_s.name, prizes_s.lang_path
FROM prizes_i18n prizes_s WHERE prizes_s.lang_id = 637;

A: Random guess...
prizes_s.translation_name + ' Copy' is too long for translation_name and you get string or binary data would be truncated error?
Is it SQL Server too? Is translation_name char or varchar?

A: INSERT INTO
prizes_i18n
(lang_id,translation_name,translation_desc,name,lang_path)
SELECT
prizes_s.lang_id
, concat(prizes_s.translation_name,'copy')
, prizes_s.translation_desc
, prizes_s.name
, prizes_s.lang_path
FROM
prizes_s WHERE prizes_s.lang_id = 637;
Also I think, that in your FROM clause the table prizes_i18n is unnecessary.


text:
Q: browsing (or downloading) R vignettes through ssh I am connected to my work computer (Linux Mint OS) through ssh. I am trying to use a package, but I need to read a documentation. Documentation is available via browseVignettes("package_name"). However since I am connected through the ssh, pdf file does not open. How can I download pdf to my local machine or read it through ssh? Package name is CODEX.
EDIT: I am on Mac OS

A: R uses the browseUrl function to open URLs in the browser. See https://stat.ethz.ch/R-manual/R-devel/library/utils/html/browseURL.html for more information.
You can change this option to your own function:
options(browser = function(url) {cat("R asked to open url: ", url, "\n")} )

Then either use X forwarding to launch a browser on your remote machine (e.g. firefox) and display it on your local screen, or use the SOCKS proxy functionality of SSH to connect via your MacOS browser.


text:
Q: Is it possible to declare a global variable for an event handler? How and where can the variable i below be declared as a global variable?(I get errors when I declare it above the main below MyClass)
    class MyClass
    {

        public static void Main()
        {

            mySerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);

        }

        public static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
        {
          int i;

         //
         my_method();
        }

    private static void my_method(){

    //

        }

}

In my code I want i to be stored as global variable for some reason to store the previous value of i.

A: class MyClass
{
    public static int i;

    public static void Main()
    {
        mySerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
    }

    public static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
    {
        i = 1;
        //
        my_method();
    }

    private static void my_method()
    {
        i = 2;
    }
}

You can refer to the below as to whether the variable should be public or protected. If it is only being referenced within the MyClass class then protected would suffice.
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/access-modifiers

A: Put this within your MyClass class:
private static int _i = 0;
private static List<int> _previousValuesOfI = new List<int>();

public static int I
{
    get => _i;
    set
    {
        if (_i != value)
        {
            _previousValuesOfI.Add(value);
        }

        _i = value;
    }
}

public static IEnumerable<int> PreviousIValues => _previousValuesOfI;

Now, anyone can get the current value of your global I through MyClass.I.  They can also set the current value of I the same way.  But, when they do, you track the previous versions, which are available from the PreviousIValues property (with the oldest version first).  If you want to have the oldest version last, consider using _previousValuesOfI.Insert(0, value); instead of _previousValuesOfI.Add(value);


text:
Q: Powershell to extract SQL returning quotes instead of blanks I have a Powershell script that I'm using to extract data from our SQL database to a csv file. The fields need to match the database this is merging with, so I'm using '' to return blank fields for fields our database doesn't have. The problem is the scope needs these to be blank and PS is returning quotes. How do I get rid of the quotes?
I believe this is the relevant code:
$LocaltopRows = "top 10"
$LocalFieldDelimter = "|"
$LocalDNE = "DNEinDB"
$localFileExtension = ".csv"
$LocalNullDate = ""
$folderPath = "\Export"
$LocalLogPath = "\Logs"
$DBServer = "SERVER"
$DBName = "DB"
$dbCompanyName = "COMPANY"

$TESTFIELD  = "'TEST' as [TEST Text]"
$TESTFIELD2  = "'' as [Blank Code]"

$Connection = new-object system.data.sqlclient.sqlconnection
$Connection.ConnectionString ="server=$DBServer;database=$DBName;Connection Timeout=0;trusted_connection=True"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand   #setting object to use sql commands

$SqlQuery = @"
SELECT $LocaltopRows
    $TESTFIELD2
    ,$TESTFIELD
    FROM [$DBName].[dbo].[$dbCompanyName`$Table] as TEST
"@

Here's the entire code in case I missed something relevant.
$ErrorActionPreference="SilentlyContinue"
Stop-Transcript | out-null
$ErrorActionPreference = "Continue"

###############################################################################
#### Set Country, Server and Database

$runTest = $true

if( $runTest )
{
    # Testing parameters
    $LocaltopRows = "top 10"
    $LocalFieldDelimter = "|"
    $LocalDNE = "DNEinDB"
    $localFileExtension = ".csv"
    $LocalNullDate = ""
    $folderPath = "\Export"
    $LocalLogPath = "\Logs"
    $DBServer = "DB"
    $DBName = "DB"
    $dbCompanyName = "COMP"

}
else
{

    $LocaltopRows = $global:topRows
    $LocalFieldDelimter = $global:FieldDelimter
    $LocalDNE = $global:DNE
    $LocalNullDate = $global:NullDate
    $localFileExtension  = $global:FileExtension
    $folderPath = $global:ExportPath
    $LocalLogPath = $global:LogPath

    $DBServer = $global:SQLServerName
    $DBName = $global:DataBaseName
    $dbCompanyName = $global:CompanyName
}

" "
"----------------------------------------------"
"TEST Export"
"----------------------------------------------"
" "

###############################################################################
#### Set Date Variables

# date for SQL Query
$dateQ = Get-Date -Format d

# date for writing to text file
$tdate = Get-Date -Format "yyyyMMdd"
$formatedDate = $tdate.ToString()

###############################################################################
#### Create Log file

# set file name
$fileFilter = "Log_Test_" + $formatedDate
$tfil = $fileFilter + "*"
$fname = $fileFilter + ".txt"

if( !(Test-Path $LogPath) )
{
    New-Item $LogPath -ItemType directory
}

$Lpath = $LogPath + "\$fname"

# if the file already exists, then rename it
if( Test-Path $Lpath)
{
    #"Log File Exists, I will create a backup and make a new one"

    $numFiles = (Get-ChildItem $LogPath -Filter $tfil).Count

    $newFileName = $fileFilter + "_0" + $numFiles.ToString() + ".txt"

    Rename-Item $Lpath $newFileName

}

Start-Transcript -path $LogPath -append

" "
"----------------------------------------------"
"TEST Assign Export"
"----------------------------------------------"
" "

# required Fields
$TESTFIELD  = "'TEST' as [TEST Text]"
$TESTFIELD2  = "'' as [Blank Code]"

###############################################################################
#### Create output file

# set file name
$fileFilter = "TEST"# + $formatedDate
$tfil = $fileFilter + "*"
$fname = $fileFilter + $localFileExtension

if( !(Test-Path $folderPath) )
{
    New-Item $folderPath -ItemType directory
}

$fpath = $folderPath + "\$fname"

# if the file already exists, then rename it
if( Test-Path $fpath)
{
    #"File Exists, I will create a backup and make a new one"

    $numFiles = (Get-ChildItem $folderPath -Filter $tfil).Count

    $newFileName = $fileFilter + "_0" + $numFiles.ToString() + $localFileExtension

    Rename-Item $fpath $newFileName

}

###############################################################################
#### SQL Connection Settings

$Connection = new-object system.data.sqlclient.sqlconnection
$Connection.ConnectionString ="server=$DBServer;database=$DBName;Connection Timeout=0;trusted_connection=True"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand   #setting object to use sql commands

### Connect to Database and Run Query

$SqlQuery = @"
SELECT $LocaltopRows
    $TESTFIELD2
    ,$TESTFIELD
    FROM [$DBName].[dbo].[$dbCompanyName`$Table] as TEST
"@

if( $runTest)
{
    " "
    "Number of Records Found: "
    $Connection.open()
    $SqlCmd.CommandText = $SqlQuery
    $SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
    $SqlAdapter.SelectCommand = $SqlCmd
    $SqlCmd.Connection = $Connection
    $DataSet = New-Object System.Data.DataSet
    $SqlAdapter.SelectCommand.CommandTimeout=6000
    $SqlAdapter.Fill($DataSet)
    $Connection.Close()

    $DataSet.Tables[0] | Export-Csv -path $fpath -NoTypeInformation -Delimiter $LocalFieldDelimter -Encoding UTF8

     (Get-Content $fpath | Select-Object ) | Set-Content $fpath

}
else
{
    " "
    "Number of Records Found: "
    $Connection.open()
    $SqlCmd.CommandText = $SqlQuery
    $SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
    $SqlAdapter.SelectCommand = $SqlCmd
    $SqlCmd.Connection = $Connection
    $DataSet = New-Object System.Data.DataSet
    $SqlAdapter.SelectCommand.CommandTimeout=6000
    $SqlAdapter.Fill($DataSet) #| Out-Null
    $Connection.Close()

    $DataSet.Tables[0] | Export-Csv -path $fpath -NoTypeInformation -Delimiter $LocalFieldDelimter -Encoding UTF8

}

Here's the result I'm getting versus the result I need:
"TEST Text"|"Blank Code"
"TEST"|""
"TEST"|""
"TEST"|""
"TEST"|""
"TEST"|""
"TEST"|""
"TEST"|""
"TEST"|""
"TEST"|""
"TEST"|""

"TEST Text"|"Blank Code"
"TEST"|
"TEST"|
"TEST"|
"TEST"|
"TEST"|
"TEST"|
"TEST"|
"TEST"|
"TEST"|
"TEST"|


text:
Q: XXX_* type in generated *.pb.go file I'm working on a tutorial about gRPC. When I generated the .pb.go file, I'm getting some XXX_* type in my struct.
This is my consignment.proto file:
syntax = "proto3";

package go.micro.srv.consignment;

service ShippingService {
    rpc CreateConsignment(Consignment) returns (Response) {}
}

message Consignment {
    string id = 1;
    string description = 2;
    int32 weight = 3;
    repeated Container containers = 4;
    string vessel_id = 5;
}

message Container {
    string id = 1;
    string customer_id = 2;
    string origin = 3;
    string user_id = 4;
}

message Response {
    bool created = 1;
    Consignment consignment = 2;
}

This is the struct in the .pb.go file. Can someone tell me why are there 3 XXX types in my struct? Shouldn't the struct be reflecting what I'm defining in my proto?
type Consignment struct {
    Id                   string       `protobuf:"bytes,1,opt,name=id" json:"id,omitempty"`
    Description          string       `protobuf:"bytes,2,opt,name=description" json:"description,omitempty"`
    Weight               int32        `protobuf:"varint,3,opt,name=weight" json:"weight,omitempty"`
    Containers           []*Container `protobuf:"bytes,4,rep,name=containers" json:"containers,omitempty"`
    VesselId             string       `protobuf:"bytes,5,opt,name=vessel_id,json=vesselId" json:"vessel_id,omitempty"`
    XXX_NoUnkeyedLiteral struct{}     `json:"-"`
    XXX_unrecognized     []byte       `json:"-"`
    XXX_sizecache        int32        `json:"-"`
}

A: If you want to specifically exclude them when generating, you can add this to your file
import "github.com/gogo/protobuf/gogoproto/gogo.proto";
option (gogoproto.goproto_unkeyed_all) = false;
option (gogoproto.goproto_unrecognized_all) = false;
option (gogoproto.goproto_sizecache_all) = false;

edit: Styling

A: The XXX_ types are used by the Protobuf library to store unknown fields.  When you decode a proto, there may be additional fields in the serialized data that the library doesn't know what to do with.  This can happen, for instance, when the reader and writer of the data are using different copies of the proto file.  This is a feature to help with backwards compatibility between clients and serves built at different times.
Additionally, the XXX fields allow you to expose extensions, which were part of Proto2.  They were removed in Proto3 in favor of Any, but the library still needs to support them.
As for what you should do with these?   I would just leave them alone, and don't reference them.  You don't need to set them, and you don't need to read them.  The Go protobuf library will handle them for you.

A: The official protobuffer generator for golang still includes the XXX_ fields and the issue is still open and decisions are pending on wether to remove it ot not but you can use the gogo third party generator. I am using it for a long time without a problem. Just use the gogofaster_out
https://github.com/gogo/protobuf
Here are the section that discussed about exclude the XXX_ fields

More Speed and more generated code
Fields without pointers cause less time in the garbage collector. More
  code generation results in more convenient methods.
Other binaries are also included:

protoc-gen-gogofast (same as gofast, but imports gogoprotobuf)
protoc-gen-gogofaster (same as gogofast, without XXX_unrecognized, less pointer fields)
protoc-gen-gogoslick (same as gogofaster, but with generated string, gostring and equal methods)

Installing any of these binaries is easy. Simply run:

go get github.com/gogo/protobuf/proto
  go get github.com/gogo/protobuf/{binary}
  go get github.com/gogo/protobuf/gogoproto

After installing the lib use
protoc --gogofaster_out=plugins=grpc


text:
Q: MSE is 'scale dependent'. R-squared seems a better measure of fit for regressions. Are there others? Mean-Squared Error is scale dependent. For example if I have an MSE of 0.1 and multiply all of X and Y by 100, redo my regression and calculate MSE, I get an MSE of 1000.0. ((y_true-y_regr)^2 ---> 100^2*(y_true-y_regr)^2)
Whilst MSE is very useful/powerful and has its own meaning, the fact in and of itself that its value is large or small does not necessarily give meaning in 'goodness of fit' in and of itself. Thus it is integral but has a slightly different interpretation.
R-squared has its own pros/cons but seems a better measure and 'normalised' to the data itself. Are there other 'universal' (non-scale dependent etc.) measures of 'goodness of fit'?
Would correlations or even mutual information between y_true and the predicted regression y_regr be useful for how well a regression of any type, including neural networks etc., fits the data it is trying to predict?

A: I would argue that $R^2$ is not a universal "grade" for a model where $R^2=90\%=0.9$ is an $\text{A}$ that makes us happy and $R^2=40\%=0.4$ is an $\text{F}$ that makes us sad. It might be that $R^2=0.4$ is excellent performance for a task or that $R^2=0.9$ is rather pedestrian for a different task.
In that sense, I do not believe there to be an easy loss function that grades your model quality. To say that, you must know the costs of making wrong predictions. If you make a prediction that misses the true value by $3$, put that in context. If that is three meters when you are trying to measure how far away another town is, then I'd say that's pretty good. If you're trying to measure how tall someone is, such performance does not sound so good.
Likewise, if you get $R^2 = 0.9$, put that in context. If you have a large reduction in variance, it could be because you have small errors, or it could be that the original data had a huge variance, so even reducing the variance to be merely "large" gives you a high $R^2$, even though you need to have "modest" errors to have a useful model.

A: RMSE tells us how far the model residuals are from zero on average, i.e. the average distance between the observed values and the predicate values. However, Willmott et. al. suggested that RMSE might be misleading to assess the model performance since RMSE is a function of the average error and  the distribution of squared errors. Chai recommended to use both RMSE and mean absolute error (MAE). It is better to report both metrics. By the way, $R^2$ is misleading as well since it increases for higher number of predictors. I would recommend to use adjusted $R^2$. This metric is kinda gold standard goodness of fit test. Attached articles will give u more explanations.
Reference:
http://www.jstor.org/stable/24869236
https://gmd.copernicus.org/articles/7/1247/2014/


text:
Q: Using matplotlib to scroll through 2D slices of overlapping 3D images I have this piece of code which works perfectly fine for scrolling through 2D slices of a 3D numpy array.
import matplotlib.pyplot as plt
import numpy as np

class IndexTracker(object):
    def __init__(self, ax, X):
        self.ax = ax
        ax.set_title('use scroll wheel to navigate images')

        self.X = X
        rows, cols, self.slices = X.shape
        self.ind = self.slices // 2

        self.im = ax.imshow(self.X[:, :, self.ind], cmap="gray")
        self.update()

    def onscroll(self, event):
        print("%s %s" % (event.button, event.step))
        if event.button == 'up':
            self.ind = (self.ind + 1) % self.slices
        else:
            self.ind = (self.ind - 1) % self.slices
        self.update()

    def update(self):
        self.im.set_data(self.X[:, :, self.ind])
        self.ax.set_ylabel('slice %s' % self.ind)
        self.im.axes.figure.canvas.draw()

def plot3d(image):
    fig, ax = plt.subplots(1, 1)
    tracker = IndexTracker(ax, image)
    fig.canvas.mpl_connect('scroll_event', tracker.onscroll)
    plt.show()

if __name__ == "__main__":
    img = np.array([[[0, 0, 0], [0, 1, 0], [0, 0, 0]],
                     [[0, 0, 0], [1, 1, 1], [0, 0, 0]],
                     [[0, 0, 0], [0, 1, 0], [0, 0, 0]]])

    plot3d(img)

I would like to have the same functionality but for scrolling through two, equally sized, 3D numpy arrays at the same. One of the arrays shall be displayed with a certain level of opacity and a different color scheme, so both arrays can be inspected at the same time. Without scrolling, for a 2D slice, this can be achieved easily:
img1 = np.array([[[0, 0, 0], [0, 1, 0], [0, 0, 0]],
                 [[0, 0, 0], [1, 1, 1], [0, 0, 0]],
                 [[0, 0, 0], [0, 1, 0], [0, 0, 0]]])

img2 = np.array([[[0, 0, 0], [0, 1, 0], [0, 0, 0]],
                 [[0, 1, 0], [0, 1, 0], [0, 1, 0]],
                 [[0, 0, 0], [0, 1, 0], [0, 0, 0]]])

plt.imshow(img1[:, :, 1], cmap="gray")
plt.imshow(img2[:, :, 1], cmap="jet", alpha=0.25)
plt.show()

I tried to extend the IndexTracker class to accept a second 3D array and display one slice of each volume (with the same index) using imshow(). Also, it was intended to update the displayed images on each scroll event using set_data(). However, this did not succeed.
import numpy as np
import matplotlib.pyplot as plt

class IndexTracker(object):
    def __init__(self, ax, X, Y):
        self.ax = ax
        self.X = X
        self.Y = Y
        _, _, self.slices = X.shape
        self.ind = self.slices // 2

        self.im = ax.imshow(self.X[:, :, self.ind], cmap="gray")
        self.im = ax.imshow(self.Y[:, :, self.ind], cmap="jet", alpha=0.25)

        self.update()

    def onscroll(self, event):
        print("%s %s" % (event.button, event.step))
        if event.button == 'up':
            self.ind = (self.ind + 1) % self.slices
        else:
            self.ind = (self.ind - 1) % self.slices
        self.update()

    def update(self):
        self.im.set_data(self.X[:, :, self.ind])
        self.im.set_data(self.Y[:, :, self.ind])

        self.ax.set_ylabel('slice %s' % self.ind)
        self.im.axes.figure.canvas.draw()

def plot3d(image1, image2):
    image1 = np.rot90(image1, k=-1)
    image2 = np.rot90(image2, k=-1)
    fig, ax = plt.subplots(1, 1)
    tracker = IndexTracker(ax, image1, image2)
    fig.canvas.mpl_connect('scroll_event', tracker.onscroll)
    plt.show()

if __name__ == "__main__":
    img1 = np.array([[[0, 0, 0], [0, 1, 0], [0, 0, 0]],
                     [[0, 0, 0], [1, 1, 1], [0, 0, 0]],
                     [[0, 0, 0], [0, 1, 0], [0, 0, 0]]])
    img2 = np.array([[[0, 0, 0], [0, 1, 0], [0, 0, 0]],
                     [[0, 1, 0], [0, 1, 0], [0, 1, 0]],
                     [[0, 0, 0], [0, 1, 0], [0, 0, 0]]])

    plot3d(img1, img2)

Do you have any idea on how to solve the given problem using matplotlib? Ideally by extending the first code snippet containing the IndexTracker class.
Edit:
Added second image as parameter to plot3d() call

A: Happily enough if you keep track of the two Axes.imshow objects (returned by plt.imshow) separately, then matplotlib will deal with the layering of the images for you. Then you can use set_data on each of these individually. When doing so you need to keep the same colormap and alpha values for each of the images, you can accomplish this using a combination of im.to_rgba and im.get_alpha. Here are the modifications you need to make to your class for this too work:
class IndexTracker(object):
    def __init__(self, ax, X, Y):
        ...

        self.im1 = ax.imshow(self.X[:, :, self.ind], cmap="gray")
        self.im2 = ax.imshow(self.Y[:, :, self.ind], cmap="jet", alpha=.25)

        ...

    def update(self):
        im1_data = self.im1.to_rgba(self.X[:, :, self.ind], alpha=self.im1.get_alpha())
        im2_data = self.im2.to_rgba(self.Y[:, :, self.ind], alpha=self.im2.get_alpha())

        self.im1.set_data(im1_data)
        self.im2.set_data(im2_data)

        ...


text:
Q: Hi, I'm new to Ubuntu & can't get my DVDRW to work at all, please help I am running 14.04 64bit.
New to Ubuntu & learning as fast as I can.
I had a dvdrom in the system but it wasn't working (turns out I had a bad cable)
I switched it out with a working DVDRW from another system I wasn't using any more.
The tray opens and closes
The status led blinks green when I insert a disc (CDDA, DVD, DATA)
I hear the drive spool up but it doesn't do any more than that.
I can run some commands in terminal but need assistance with the required command lines.
Much appreciated :)

A: There is a strong possibility that a wrong-state error is present. You may have cleared the drive via the hardware while the computer was doing a shutdown. This creates a wrong-state error.
If a disk is removed from a optical drive, while the system is shutting down, I have found that the driver can become confused, and upon restart, the system still thinks there is a disk in the drive, when in fact it is empty. You will see the drive icon in the Launcher, even though the drive is empty. System cannot read a empty drive that is thought to be occupied.
Just right-click upon the drive icon, and eject the drive. Then close the drive and insure that the icon is flushed from the Launcher. Then Restart the system. Then install a disk and see if it reads. This has fixed many problems for me.
The above is a clear defect in the command routing software in the hardware layer. All other OS's check the contents of the drive at boot time and flush the active mode if nothing is in the drive, regardless of the last state record. Ubuntu has not fixed this error and it has been present forever. I always make sure the drive is empty before I shutdown the computer, to preclude this error.
Hope that helps, have fun and good luck!


text:
Q: Loaded query tables either shows error in refresh or leave many blank rows between tables Dears,
I really need your help with this one as it's driving me crazy, I have 3 queries loaded as tables under each other in my excel workbook.

when I choose the properties option: insert cells for new data, delete unused cells from properties >> it shows an error message in refresh (it would move cells in a table on your worksheet).
and when I go for the second option: insert entire rows for new data, it refreshes but leaves many blank rows between each table and the second one.
What shall I do to refresh all queries in the workbook without messing up the form .. as I just need to leave 1 empty row between each loaded table?


text:
Q: Fastest way to restore Windows 7's original MBR? I have removed GRUB's partition, and I wanted to restore the original Windows boot part. WinToFlash failed again to make my pendrive bootable, thus I'm in a bit of a trouble now.
I looked all around, but I couldn't find any easy way to do this.
What is the easiest and fastest way to restore the MBR?
(I've got no Windows 7 DVD with me right now. And fetching the DVD is not really fast with a slower connection.)

A: Make a System Repair Disc on another W7 PC, it needs to be the same bit version as the one you are repairing, 32 or 64bit Windows 7.
Once you have the System Repair Disc,

Insert the Windows 7 installation or System Repair DVD and boot from your DVD drive. You may have to change the boot order through system BIOS to boot from your DVD.
Choose your default "Language," "Time" and "Keyboard Input" on the first window and click "Next."
Click on the "Repair Your Computer" option to gain access to the System Recovery window. Now choose "Command Prompt" to run the Bootsect.exe utility. Bootsect is located inside the boot folder so change your directory to boot. Now run bootsect /nt60 C:\ if you had Windows 7 initially installed in the C partition. Alternatively, you can run bootsect /nt60 SYS or bootsect /nt60 ALL to repair the system partition or all partitions. Eject the DVD and restart your computer. Your computer should now boot Windows 7 again.

Source
Secondary Source
Completion:
As stated in the comments below, one has also to use the /mbr option in order to fix MBR, which is necessary to remove GRUB from MBR.


text:
Q: Setting values from the UI for Javascript I would like to be able to set values of integers from the UI and have it set to javascript. Basically I'm working with a C3 chart, I'm using the max and min functions. I would like to have a user change those values from the UI and in turn change the value of the javascript. Here is the function that sets the y axis of the chart:
Function:
$(function(){
  instance.axis.max();
});

You can basically set the value as the parameter of max. This works as I intend it to but how can I make it dynamic from the UI. Right now I have this text field setup that I would like to wire up to change the max value here is the text field
HTML text field:
<div class="y-axis">
  <input type="number" id="replyNumber" min="0" data-bind="value:replyNumber" />
</div>

Is there a way I can set a data attribute to the html and have it set to the javascript?

A: Your are using JQuery. So, you can do this as below
$(function(){
  var number = $("#replyNumber").attr('min');
  //if this is not number then convert it into number.
  // number = Number(number);
  instance.axis.max(number);
});


text:
Q: Do all pods work with the Multiplatform apps in the new Xcode beta? can somebody help me with my problem?
I want to make an iOS/macOS app with the new Xcode 12 beta 2, and I use the pod SwiftyJSON in that project. It is a Multiplatform project, and for the iOS part everything works perfectly fine. But when I set the build target to macOS, Xcode shows me the error message "No such module 'SwiftyJSON'".
I use two other pods in that project (SwiftyXMLParser and Alamofire) and they work just fine (no error message, maybe that's because the compiler cancels the build but I don't think so, its the second pod that gets imported in the file).
Is that a problem with Cocoapods, that it doesn't support Multiplatform apps yet? Doesn't seem like it, there is a separate import section for macOS and iOS, but I'm no expert. Or do I have to do some special setup in Xcode to get these pods to work for macOS (maybe a problem with the beta?)? Or is the SwiftyJSON pod not compatible with macOS?
Or am I just dumb? (probably true)
Thanks for every answer you can give me


text:
Q: No puedo ingresar datos en la base de datos mysql mediante un formulario php Tengo un formulario de registro de usuario, y al ejecutarlo, me dice que se ha conectado correctamente, y que el usuario se ha registrado, pero al entrar en mysqladmin, no hay ningún registro en la base de datos.
Tengo el siguiente código del formulario:
<?php
include 'conexiongeografs.php';
$username =$_POST["Nom"];
$apellidos =$_POST["Cognoms"];
$municipi =$_POST["Municipi"];
$comarca =$_POST["Comarca"];
$email =$_POST["Email"];
$ambit =$_POST["ambit professional"];
$especialitzacio =$_POST["especialitzacio"];
$comment =$_POST["comment"];
$insertar = "INSERT INTO jos_users1(Nom,Cognoms,Municipi,Comarca,Email,ambit professional,especialitzacio,comment) VALUES ('$username','$apellidos','$municipi','$comarca','$email','$ambit','$especialitzacio','$comment')";

$resultado = mysqli_query($conexion,$insertar);
if(!$resultado) {
        echo 'usuari registrat correctament';
    }
    else
    {
        echo 'error al registrarse ';
    }

mysqli_close($conexion);
?>

Este de la conexión:
<?php
$conexion =mysqli_connect("localhost","geografs_geo","geo020908");
if (!$conexion) {
echo 'erroral conectar a la base de datos';
}
else {
echo 'conectado a la base de datos';
}

... y por último, el del formulario:
<form action="registreobert.php" method="post" role="form">

Nom
    <input type="text" class="form-control" id="username"
           placeholder="Introdueix el teu nom">

Cognoms
    <input type="text" class="form-control" id="apellidos"
           placeholder="Introdueix el teu cognom">

Municipi
    <input type="text" class="form-control" id="municipi"
           placeholder="Introdueix el teu municipi">

Comarca
    <input type="text" class="form-control" id="comarca"
           placeholder="Introdueix la teva comarca">

Email
    <input type="email" class="form-control" id="email"
           placeholder="Introdueix el teu email">

<select class="form-control" name="ambit professional" id="ambit">
<option>ÀMBIT PROFESSIONAL</option>
<option>ADMINISTRACIÓ</option>
<option>CONSULTORIA</option>
<option>RECERCA</option>
<option>EDUCACIÓ</option>
<option>ALTRES</option>
</select>

<select class="form-control" name="especialitzacio" id="especialitzacio">
  <option>ESPECIALITZACIÓ</option>
  <option>PLANIFICACIÓ TERRITORIAL I URBANÍSTICA</option>
  <option>MEDI AMBIENT, PAISATGE, PATRIMONI NATURAL</option>
  <option>TECNOLOGIES DE LA INFORMACIÓ GEOGRÀFICA</option>
  <option>DESENVOLUPAMENT SOCIOECONÒMIC TERRITORIAL, TURISME</option>
  <option>EDUCACIÓ, RECERCA, SOCIETAT DEL CONEIXEMENT</option>
  <option>PREVENCIÓ DE RISCOS</option>
  <option>MOBILITAT I TRANSPORT</option>
</select>

  Altres especialitzacions (especificar):
  <textarea class="form-control" rows="3" id="comment"></textarea>

<button type="submit" class="btn btn-primary">Enviar</button>

</form>

pego otra vez los codigos del formulario:

Nom

Cognoms

Municipi

Comarca

Email

ÀMBIT PROFESSIONAL
ADMINISTRACIÓ
CONSULTORIA
RECERCA
EDUCACIÓ
ALTRES

  ESPECIALITZACIÓ
  PLANIFICACIÓ TERRITORIAL I URBANÍSTICA
  MEDI AMBIENT, PAISATGE, PATRIMONI NATURAL
  TECNOLOGIES DE LA INFORMACIÓ GEOGRÀFICA
  DESENVOLUPAMENT SOCIOECONÒMIC TERRITORIAL, TURISME
  EDUCACIÓ, RECERCA, SOCIETAT DEL CONEIXEMENT
  PREVENCIÓ DE RISCOS
  MOBILITAT I TRANSPORT

  Altres especialitzacions (especificar):

Enviar

el codigo

sigue mal os dejo la estructura dela base de datos por si esto fuera el problema
id  int(11)         No  Ninguna AUTO_INCREMENT  Cambiar Cambiar Eliminar Eliminar

Primaria Primaria
Único Único
Índice Índice
Más

2   username    varchar(20) utf8_spanish_ci     No  Ninguna     Cambiar Cambiar Eliminar Eliminar

Primaria Primaria
Único Único
Índice Índice
Más

3   apellidos   varchar(20) utf8_spanish_ci     No  Ninguna     Cambiar Cambiar Eliminar Eliminar

Primaria Primaria
Único Único
Índice Índice
Más

4   municipi    varchar(30) utf8_spanish_ci     No  Ninguna     Cambiar Cambiar Eliminar Eliminar

Primaria Primaria
Único Único
Índice Índice
Más

5   comarca varchar(30) utf8_spanish_ci     No  Ninguna     Cambiar Cambiar Eliminar Eliminar

Primaria Primaria
Único Único
Índice Índice
Más

6   email   varchar(20) utf8_spanish_ci     No  Ninguna     Cambiar Cambiar Eliminar Eliminar

Primaria Primaria
Único Único
Índice Índice
Más

7   ambit   varchar(60) utf8_spanish_ci     No  Ninguna     Cambiar Cambiar Eliminar Eliminar

Primaria Primaria
Único Único
Índice Índice
Más

8   especialitzacio varchar(60) utf8_spanish_ci     No  Ninguna     Cambiar Cambiar Eliminar Eliminar

Primaria Primaria
Único Único
Índice Índice
Más

9   comment text

A: Usa backticks (`) cuando te encuentres con un campo que incluya espacios (en tu caso el campo ambit professional)
INSERT INTO jos_users1(Nom,Cognoms,Municipi,Comarca,Email,`ambit professional`,especialitzacio,comment) VALUES ('$username','$apellidos','$municipi','$comarca','$email','$ambit','$especialitzacio','$comment')

A: La forma de enviar datos de un FORM (etiqueta html) es mediante los name, cada input debe tener una NAME ASI:
<input type="text"  id="username" name="username">

Asi le envias el 'username'.

A: Aquí te envío corregido el formulario y el insert: "Nuevo: Así como esta este código deberías tener todo el formulario."
 <form action="aqui va el nombre de la ruta donde esta el codigo del insert" method="POST">

    nom
    <input type="text" class="form-control" name="nom" placeholder="Introdueix la teva nom">

    Cognoms
    <input type="text" class="form-control" name="Cognoms" placeholder="Introdueix la teva Cognoms">

    Municipi
    <input type="text" class="form-control" name="Municipi" placeholder="Introdueix la teva Municipi">

    Comarca
    <input type="text" class="form-control" name="comarca" placeholder="Introdueix la teva comarca">

    Email
    <input type="email" class="form-control" name="email"  placeholder="Introdueix el teu email">

  <select class="form-control" name="ambit_professional" id="ambit">
  <option>ÀMBIT PROFESSIONAL</option>
  <option>ADMINISTRACIÓ</option>
  <option>CONSULTORIA</option>
  <option>RECERCA</option>
  <option>EDUCACIÓ</option>
  <option>ALTRES</option>
  </select>

<select class="form-control" name="especialitzacio" id="especialitzacio">
  <option>ESPECIALITZACIÓ</option>
  <option>PLANIFICACIÓ TERRITORIAL I URBANÍSTICA</option>
  <option>MEDI AMBIENT, PAISATGE, PATRIMONI NATURAL</option>
  <option>TECNOLOGIES DE LA INFORMACIÓ GEOGRÀFICA</option>
  <option>DESENVOLUPAMENT SOCIOECONÒMIC TERRITORIAL, TURISME</option>
  <option>EDUCACIÓ, RECERCA, SOCIETAT DEL CONEIXEMENT</option>
  <option>PREVENCIÓ DE RISCOS</option>
  <option>MOBILITAT I TRANSPORT</option>
</select>

  Altres especialitzacions (especificar):
  <textarea class="form-control" rows="10" cols="30" id="comment" name="comment"></textarea>

<button type="submit" class="btn btn-primary">Enviar</button>

</form>

Al estar usando un formulario sin javascript debe tener el atributo name en todos los input que deseas guardar.
En el archivo de ejecución sería así:
<?php
include 'conexiongeografs.php';
$username =$_POST["nom"];
$apellidos =$_POST["cognoms"];
$municipi =$_POST["municipi"];
$comarca =$_POST["comarca"];
$email =$_POST["email"];
$ambit =$_POST["ambit"];
$especialitzacio =$_POST["especialitzacio"];
$comment =$_POST["comment"];
$insertar = "INSERT INTO jos_users1(nom,cognoms,municipi,comarca,email,ambit,especialitzacio,comment) VALUES ('$username','$apellidos','$municipi','$comarca','$email','$ambit','$especialitzacio','$comment')";

$resultado = mysqli_query($conexion,$insertar);
if(!$resultado) {
        echo 'usuari registrat correctament';
    }
    else
    {
        echo 'error al registrarse ';
    }

mysqli_close($conexion);
?>

Si te fijas en los datos que compartiste del formulario, no están algunos datos que intentas guardar en la tabla, no sé si lo omitiste en el post apropósito o realmente falta agregarlos al formulario,.
Lo otro es que en programación los nombres de variables debe usarlos según las reglas camelCase o underscore.
Datos de conexión :
$conexion =mysqli_connect("localhost","usuario","contraseña",'base_de_datos');
if (!$conexion) {
echo 'erroral conectar a la base de datos';
}
else {
echo 'conectado a la base de datos';
}

A: Más cerca aún de la respuesta de @kira es que a todos los campos del formulario les falta el atributo name y el valor de ese atributo debe ser el mismo que está usando en la variable post. Como ejemplo:
Campo del formulario:
<input type="text" class="form-control" name=""Nom" id="username"
           placeholder="Introdueix el teu nom">

Valor obtenido en el PHP:
$username = $_POST["Nom"];

De este modo se recibe el valor del campo Nom


text:
Q: How to plot x axis with month?
I want to plot a dataframe df1. The x axis contains month and the y-axis counts. My x axis is just a black bar because of too many values. I tried a lot but nothing works. Is there a simple way to plot just every 5th date for example?
I think the problem is that the month are date times and I can't build the minimum and maximum?

df1 = pd.read_csv('hello.csv')

plt.plot(df1['a'],df1['b'])
plt.show()

My data frame df1 is:
a       b
2006-06,211.0
2006-07,212.41176470588235
2006-08,238.26315789473685
2006-09,239.9375
2006-10,266.1111111111111
2006-11,265.22222222222223
2006-12,283.3333333333333
2007-01,290.0
2007-02,307.5
2007-03,325.0
2007-04,343.05882352941177
2007-05,340.42105263157896
2007-06,353.75
2007-07,348.5
2007-08,359.6111111111111
2007-09,346.5625
2007-10,365.57894736842104
2007-11,358.7647058823529
2007-12,372.8333333333333
2008-01,381.8888888888889
2008-02,396.25
2008-03,422.94117647058823
2008-04,428.6666666666667
2008-05,418.5882352941176
2008-06,433.0
2008-07,440.4736842105263
2008-08,470.375
2008-09,481.3529411764706
2008-10,489.44444444444446
2008-11,485.125
2008-12,514.5714285714286
2009-01,515.375
2009-02,535.3125
2009-03,555.0555555555555
2009-04,557.7222222222222
2009-05,533.375
2009-06,567.7222222222222
2009-07,575.1111111111111
2009-08,582.5294117647059
2009-09,569.1666666666666
2009-10,611.1176470588235
2009-11,591.6470588235294
2009-12,634.6428571428571
2010-01,647.9375
2010-02,655.375
2010-03,672.7368421052631
2010-04,678.5882352941177
2010-05,667.8235294117648
2010-06,689.5
2010-07,657.4117647058823
2010-08,679.1111111111111
2010-09,661.2222222222222
2010-10,685.75
2010-11,676.5555555555555
2010-12,692.3571428571429
2011-01,691.9411764705883
2011-02,697.4375
2011-03,720.5263157894736
2011-04,723.5
2011-05,694.7222222222222
2011-06,705.7222222222222
2011-07,677.9375
2011-08,693.7368421052631
2011-09,671.2352941176471
2011-10,685.1176470588235
2011-11,669.9444444444445
2011-12,708.3076923076923
2012-01,674.9444444444445
2012-04,748.0
2012-05,811.0526315789474
2012-06,863.6875
2012-07,843.1666666666666
2012-08,885.5
2012-09,857.75
2012-10,876.8421052631579
2012-11,863.1764705882352
2012-12,917.6666666666666
2013-01,933.4444444444445
2013-03,975.0625
2013-04,994.0
2013-05,1019.6666666666666
2013-06,1063.625
2013-07,1057.8947368421052
2013-08,1102.1764705882354
2013-09,1046.4117647058824
2013-10,1153.1052631578948
2013-11,1107.25
2013-12,1155.3076923076924
2014-01,1191.3529411764705
2014-02,1240.5
2014-03,1272.764705882353
2014-04,1316.9444444444443
2014-05,1310.3529411764705
2014-06,1349.4117647058824
2014-07,1403.8947368421052
2014-08,1412.375
2014-09,1409.0555555555557
2014-10,1472.9444444444443
2014-11,1421.8125
2014-12,1473.2142857142858
2015-01,1476.9375
2015-02,1495.75
2015-03,1546.111111111111
2015-04,1563.7777777777778
2015-05,1499.0
2015-06,1583.111111111111
2015-07,1594.2222222222222
2015-08,1618.1176470588234
2015-09,1595.8333333333333
2015-10,1706.3529411764705
2015-11,1652.8823529411766
2015-12,1691.0714285714287
2016-01,1717.125
2016-02,1746.7058823529412
2016-03,1945.4736842105262
2016-04,2329.375
2016-05,2408.4444444444443
2016-06,2404.222222222222
2016-07,2184.4375
2016-08,2160.6315789473683
2016-09,2402.176470588235
2016-10,2481.823529411765
2016-11,2372.0
2016-12,2153.0
2017-01,2145.777777777778
2017-02,2213.5625
2017-03,2309.6111111111113
2017-04,2295.8125
2017-05,2116.7894736842104
2017-06,2093.8823529411766

A: In order to show every nth value, what you can do is to set the x-ticks value.
x = df1['a']
plt.xticks(np.arange(0, len(x), 1.0)) #you can replace 1 with the step interval

Or else, what you can do to further improve the visibility and keep the accuracy is to rotate the x axis inputs by modifying the x-ticks with a rotation variable.
import matplotlib.pyplot as plt

x = [1, 2, 3, 4]
y = [1, 4, 9, 6]
labels = ['Frogs', 'Hogs', 'Bogs', 'Slogs']

plt.plot(x, y)
# You can specify a rotation for the tick labels in degrees or with keywords.
plt.xticks(x, labels, rotation='vertical') # You can input an integer too.
# Pad margins so that markers don't get clipped by the axes
plt.margins(0.2)
# Tweak spacing to prevent clipping of tick-labels
plt.subplots_adjust(bottom=0.15)
plt.show()


text:
Q: Высота тега Body - HTML (почему так?) Доброго всем дня.
Сделал следующее:
<body style="margin:0; padding:0px; background-image: url('images/bg_for_pages.jpg'); border: solid 1px #FF0000;">

И увидел, что тег body заканчивается не на max.высота браузера (FireFox), а по контенту.
Т.е. он не заполняет всё окно браузера. Как такое возможно?

Даже параметр height:100%; не исправил ситуации.
A: @I_CaR, чтобы это работало, у всех предков выбранного тэга должна быть указана высота.
html, body {
    height: 100%;
}

Посмотреть пример (серым цветом залит тэг body)
A: Для html задается min-height:100% и position:relative;
Для body - если нужно, чтобы было только по высоте окна - height:100%. Если нужно, чтобы тянулось и ниже за html-ом, то тоже min-height:100%
html {
  position:relative;
  min-height: 100%;
}
body {
  height:100%;
}


text:
Q: Show that 2 representations are not equivalent and find all the irreducible representations of G. Show that 2 representations are not equivalent and find all the irreducible representations of $G$.
The group $G=T_{16}$ has order 16 and presentation given by $G=\langle a,b : a^8=b^2=1, b^{-1}ab=a^{-1} \rangle.$
Take $n = e^{2πi/8}$. For $1 ≤ j ≤ 3$, there is a representation $p_j(a) : G → \operatorname{GL}(2,\mathbb{C})$ determined by
$$p_j(a)=\begin{bmatrix}n^j & 0 \\ 0 & n^{-j}\end{bmatrix}$$
and
$$p_j(b)=\begin{bmatrix}0 & 1 \\ n^{4j} & 0\end{bmatrix}$$
(b.) If $1≤j,k≤3$ and $j$ is not equal to $k$, show that $p_j$ and $p_k$ are not equivalent. Hint: You may wish to consider characters.
So I am confused because does this mean I consider $p_1(a)$ with $p_2(b)$, $p_3(b)$ and $p_2(a)$ with $p_1(b)$, $p_3(b)$ and $p_3(a)$ with $p_1(b)$ and $p_2(b)$?
Also, I know that the definition of two representations being equivalent is that, $\sigma$ and $p$ are equivalent if there exists $T$ such that $\sigma(g)=T^{-1}p(g)T$, but the only example of have is where the lecturer just plucks the matrix $T$ out of thin air, saying she knows it works because she wrote the question and this doesn't help me at all!
The hint says to look at the characters, so I assume this question is answered easiest by doing that, so I just calculate the trace of each matrix and if the traces are not equal then the representations are not equivalent? I would appreciate guidance on answering a similar question using the matrices approach though in case I am asked to do that in my exam.
(c.) Find all the irreducible representations of $G$, briefly explaining why you have discovered them all.
I haven't tried this part yet, but I thought I would ask it now and can get help in it when I have finished the previous part.
Thanks!


text:
Q: Can I use "new ServerSocket(0)" with openshift I have developed an application that allows multiple players to play together on line at various games such shifumi, poker, chess and so on. It works very well on my localhost. I would like to publish it. So I decided to use openshift to do this.
But there is a problem.
It seems it come from this statement : new ServerSocket(0). I do this inside the doPost method of an HttpServlet.
Could you tell me I don't have the permission to do this (new ServerSocket(0)) inside an openshift server?

A: I think you have a couple of issues going on here.
The first is that when you call new ServerSocket(0), it is going to try to find a socket that it can bind to, probably on either 0.0.0.0 (all ip addresses/interfaces) or 127.0.0.1, neither of which is allowed on OpenShift.
According to the documentation (located here: http://download.java.net/jdk7/archive/b123/docs/api/java/net/ServerSocket.html) you can use one of the overloaded methods to provide an ip address to bind to, which should be your OPENSHIFT__IP (where  could be jbosseap, jbossas, wildfly, jbossews, etc).
ServerSocket(int port, int backlog, InetAddress bindAddr)

Your second issue is a bit more complicated, basically what ports you can bind to.  OpenShift allows user code to bind to ports 15000-20000, depending on what ports are not being used by other applications or services.  However, none of those ports are open to the public internet, they are all internal ports for internal communications, so if you are trying to let a client connect to them, it won't work.  The only ports that are publicly available are 80/443/8000/8443, and your application must bind to port 8080 on your OPENSHIFT__IP to be able to be reached using your app-domain.rhcloud.com public url.  You can check out this article to read more about how all of the binding and routing works: https://developers.openshift.com/en/managing-port-binding-routing.html
Hopefully that answers the question about why that piece of code is not working.


text:
Q: java.lang.IllegalArgumentException: Invalid boolean @Value("${com.test.isTestEnable") I am getting
**Caused by: org.springframework.beans.TypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'java.lang.Boolean'; nested exception is java.lang.IllegalArgumentException: **
I believe this happens due to missing spring place holder config. But I have the bean initialised in application context and still getting this error. Can any one help me out??
    @Value("${com.test.isTestEnable")
    public Boolean isTestEnable;

Spring Properties Class
public class SpringPropertiesUtil extends PropertyPlaceholderConfigurer {

    private static HashMap<String, String> systemPropertiesMap;

    private int springSystemPropertiesMode = SYSTEM_PROPERTIES_MODE_FALLBACK;

    public static String getProperty(final String name) {
        return systemPropertiesMap.get(name);
    }

    @Override
    protected void processProperties(final ConfigurableListableBeanFactory beanFactory, final Properties props) throws BeansException {
        super.processProperties(beanFactory, props);
        systemPropertiesMap = new HashMap<String, String>();
        for (final Object key : props.keySet()) {
            final String keyStr = key.toString();
            final String valueStr = resolvePlaceholder(keyStr, props, springSystemPropertiesMode);
            systemPropertiesMap.put(keyStr, valueStr);
        }
    }

    @Override
    public void setSystemPropertiesMode(final int systemPropertiesMode) {
        super.setSystemPropertiesMode(systemPropertiesMode);
        springSystemPropertiesMode = systemPropertiesMode;
    }

my application-context file
  <bean id="placeholderConfig" class="com.test.SpringPropertiesUtil">
        <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
        <property name="locations">
            <list>
                <value>file:${config.path}/application.properties</value>
                <value>file:${config.path}/log.properties</value>
            </list>
        </property>
    </bean>

A: Your real issue was just a typo at @Value("${com.test.isTestEnable") - you're missing a closing curly bracket } at the end of the expression
This should work completely fine:
    @Value("${com.test.isTestEnable}")
    public Boolean isTestEnable;

A: Try changing the following line
@Value("${com.test.isTestEnable")

to
@Value("#{new Boolean('${com.test.isTestEnable}')}")

OR
@Value("#{T(Boolean).parseBoolean('${com.test.isTestEnable}')}")


text:
Q: this following code is not run by GPU but my original code with mnist run with gpu? my original keras.Tensorflow 2.0 is run by GPU
but i try to run this code
for label in range(10):
    print('***** label {} *****'.format(label))
    y_c = model.output[0, label]
    grads = keras.backend.gradients(y_c, model.input)[0]
    saliency = keras.backend.function([model.input], [grads])

    idx_coord = np.where(y_test == label)[0]
    X = np.zeros((batch_size, 28, 28, 1))
    for batch in range(batch_size):
        X[batch,...,0] = x_test[idx_coord[batch]]/255

    Y = np.array([[1 if label==i else 0 for i in range(10)] for _ in range(batch_size)])

    for batch in tqdm.trange(batch_size):
        x_input = X[batch,...,0].copy()
        y_input = Y[batch].copy()

        score_list = []
        if isplot:
            plt.figure(figsize=(30,30))

        for it in range(iteration):
            score = model.evaluate(x_input[np.newaxis,...,np.newaxis], y_input[np.newaxis,...], verbose=0)[1]
            score_list.append(score)

            #img, gradmap =get_gradcam(x_test[idx], model, idx,"conv2d_33")
            gradmap = np.abs(np.squeeze(get_smoothgrad(x_input[np.newaxis,...,np.newaxis], saliency, sigma=sigma)))

            if isplot:
                plt.subplot(1,20,2*(it%10)+1)
                plt.imshow(np.squeeze(x_input))
                plt.subplot(1,20,2*(it%10)+2)
                plt.imshow(np.squeeze(gradmap))
                if it%10 == 9:
                    plt.show()
                    plt.figure(figsize=(30,30))

            coord = np.where(gradmap == gradmap.max())
            x_input[coord] = 0.

        tot_score[label].append(score_list)

I'm not sure how this batch thing work with mnist
but gpu is not running with this code

*

*what is this batch is different then train batch ?

*why this code is not run by gpu?


text:
Q: Non-Strict Saddle Point vs Local Minima While going through Escaping Saddle Points Efficiently, I came across the definition of Strict Saddle Point. They define a stationary point to be a strict saddle if at least one of the eigenvalue of the Hessian Matrix is negative. This implies a non-strict saddle point will have all eigenvalues of the Hessian Matrix greater than or equal to zero. But, isn't this a sufficient and necessary condition for local minima? What is the difference between a non-strict saddle point and a local-minima?

A: When the Hessian is singular, i.e., some eigenvalues are $=0$,  then the character of the critical point cannot be decided from looking at the Hessian alone. The problem then becomes algebraically much more complicated.
The function $f(x,y):=x^2-y^2$ has a strict saddle point at $(0,0)$. The function $$g(x,y):=x^2+\alpha y^4\ +{\rm higher\ order\ terms}$$ has a strict local minimum at $(0,0)$ when $\alpha>0$, and a "non strict" saddle point when $\alpha<0$. When $\alpha=0$ you have to look at the higher order terms.

A: That definition of saddle point does not agree wih my undersanding of the concept. Perhaps they should have defined "saddle point" as " critical point where the Hessian has at least one positive eigenvalue and at least one negative eigenvalue" and "local minimum" as " critical point where the Hessian has all eigenvalues positive." Another  difficulty is the scope of "non-." Is a "non-strict saddle point" a saddle point that is not strict or is it any point that is not a strict saddle point? A third problem with the approach to local extrema via eigenvalues of the Hessian is that what we are really interested in is the behaviour of the Hessian as a quadratic form.It is certatainly true that any real symmetric matrix, such as the Hessian, can be orthogonally diagonalized with the eigenvalues on the diagonal and that in any diagonalization by congruence ( Orthogonal diagonalization is a special case of diagonalization by congruence.) the number of positive, negative and 0 diagonal terms is the same as in any other orthogonal diagonalization. (Sylvester's theorem). However, finding the eigenvalues of an $n \times n$ matrix involves solving an equation of degree $n$ whereas a symmetric matrix can be easily diagonalized by congruence over any field of characteristic $\ne 2.$

A: For a function $f\colon\mathbb{R}^n\to\mathbb{R}$, the condition $\nabla^2f(x^*)\succeq 0$ is necessary for $x^*$ to be an unconstrained local minimum of $f$, but it is in general not sufficient. Consider $f\colon\mathbb{R}\to\mathbb{R}$ defined by $f(x)=x^3$. Then $\nabla f(x) = 3x^2$ and $\nabla^2 f(x) = 6x$. Therefore, at $x^*=0$, the function satisfies both the first- and second-order necessary conditions for optimality, i.e. $\nabla f(x^*) = 0$ and $\nabla^2 f(x^*) = 0 \succeq 0$. However, $x^*=0$ is clearly not a local minimum of this function. Indeed, it is a saddle point, but this information cannot be ascertained by the Hessian, since the second-order information at $x^*=0$ does not encapsulate enough information about the geometry of $f$ in that neighborhood. To determine the true optimality (more precisely, lack there of) of $x^*=0$ for this function, you could look at the third-order term in the Taylor series expansion of $f$ around $x^*=0$.
The authors' definition of strict saddle reflects the trouble we see in the above example. In particular, a strict saddle is a saddle point whose behavior can be ascertained by the second-order information given by the Hessian. Analyzing these points avoids the issues with nonstrict saddles where we would need to look beyond second-order information.


text:
Q: How to change this.props in child when parent state changes in React JS? new to React JS here. I have a setup where I an App parent component that has a initialFormInput state holding a recipe object. A function is passed from the parent component to a child component called EditRecipeButton that can change this state to a specific recipe that is called from an edit button.
This state in the parent is mapped to a state in a child AddRecipe component with a via this.props and my reasoning is that whenever the parent component state changes this state in AddRecipe changes as well. But that doesn't happen, what am I doing wrong here?
Here is my code:
var App = React.createClass({

  getInitialState(){

    return{

      showModal:false,

      recipeKeys: [ ],

      recipes: [ ],

      initialFormInput: {name: "", ingredients: []}

    }

  },

  open: function(){

    this.setState({showModal:true});

  },

    close: function(){

    this.setState({showModal:false});

  },

  editRecipe: function(recipe){

    console.log(recipe);

    this.setState({initialFormInput: recipe}, function(){

      this.open();

    });

  },

  render: function(){

    return(

Recipe Box

        <RecipeList recipes = {this.state.recipes} deleteRecipe = {this.deleteRecipe} editRecipe={this.editRecipe} />
        <AddRecipeButton openModal = {this.open}/>
        <AddRecipe closeModal = {this.close} showModal={this.state.showModal} addRecipeKey = {this.addRecipeKey} initialFormInput = {this.state.initialFormInput}/>

    )

  }

var RecipeList = function (props) {

    return (

            {

          props.recipes.map( (item,index) => <RecipeItem recipe={item} deleteRecipe = {props.deleteRecipe} editRecipe={props.editRecipe}/> )

            }

    );
};

var RecipeItem = React.createClass({

getInitialState: function(){

    return {displayIngredients: false}

},

toggleRecipe: function() {

  this.setState({displayIngredients: !this.state.displayIngredients})

},

render: function() {

    return(

{this.props.recipe.name}

Ingredients

        {this.props.recipe.ingredients.map((item) => <IngredientItem ingredient={item} />)}

       <ButtonToolbar>
         <DeleteRecipeButton deleteRecipe = {this.props.deleteRecipe} recipeName={this.props.recipe.name}/>
         <EditRecipeButton editRecipe = {this.props.editRecipe} recipe={this.props.recipe}/>
       </ButtonToolbar>

    )

}

});

var IngredientItem = function(props){

  return (

{props.ingredient}

  )

};

var EditRecipeButton = React.createClass({

  render: function(){

   return (

     <Button bsStyle="default" bsSize="small" onClick={() => this.props.editRecipe(this.props.recipe)}>Edit</Button>

   )

  }

});

var AddRecipe = React.createClass({
//Form in modal to add recipe

  getInitialState(){

    return {

     name: this.props.initialFormInput.name,

     ingredients: this.props.initialFormInput.ingredients

    };

  },

  getValidationStateName(){

    var length = this.state.name.length;

    if(length > 0) {

      return "success";

    } else {

      return "error";

    }

  },

  getValidationStateIngredients(){

    var length = this.state.ingredients.length;

    if(length > 0){

      return "success";

    } else {

      return "error";

    }

  },

  handleInput: function(key,e){

    var input = e.target.value;

    if(key === "ingredients"){

        input = e.target.value.split(",");

    }

    var update = {};

    update[key] = input;

    this.setState(update, function(){

      console.log(this.state);

    });

  },

 handleSubmit(){

   var recipe = JSON.stringify({name: this.state.name, ingredients: this.state.ingredients});

   localStorage.setItem(this.state.name, recipe);

   var recipeObject= JSON.parse(recipe);

   this.props.addRecipeKey(recipeObject);

   this.props.closeModal();

   this.setState({name: "", ingredients: []});

  },

  render: function(){

    return (

        <Modal show={this.props.showModal} onHide={this.props.closeModal}>
            <Modal.Header closeButton>
              <Modal.Title>Add a Recipe Here</Modal.Title>
            </Modal.Header>
            <Modal.Body>
              <form>
        <FormGroup controlId="formNameText" validationState = {this.getValidationStateName()}>
          <ControlLabel>Recipe</ControlLabel>
          <FormControl
            type="text"
            placeholder="Give your recipe a name"
            value={this.state.name}
            onInput={this.handleInput.bind(this,'name')}
            />
          <FormControl.Feedback />
        </FormGroup>

        <FormGroup controlId="formIngredientsTextarea" validationState = {this.getValidationStateIngredients()}>
          <ControlLabel>Ingredients</ControlLabel>
          <FormControl
            componentClass="textarea"
            placeholder="Insert your ingredients, separated by a comma"
            value={this.state.ingredients}
            onInput={this.handleInput.bind(this,'ingredients')}
          />
          <FormControl.Feedback />

        </FormGroup>

        <Button bsStyle="primary" onClick={this.handleSubmit}>Submit</Button>
      </form>
            </Modal.Body>
        </Modal>

      )
  }

});

ReactDOM.render(<App />, document.getElementById('app'));

});

So this does not change when the parent state changes:
getInitialState(){

    return {

     name: this.props.initialFormInput.name,

     ingredients: this.props.initialFormInput.ingredients

    };

  },

A: As the name suggests, getInitialState only provides the initial state of a component. Subsequent update won't trigger that function.
You need to to implement componentWillReceiveProps to update the state in when props change. From the docs:

componentWillReceiveProps() is invoked before a mounted component receives new props. If you need to update the state in response to prop changes (for example, to reset it), you may compare this.props and nextProps and perform state transitions using this.setState() in this method.
Note that React may call this method even if the props have not changed, so make sure to compare the current and next values if you only want to handle changes. This may occur when the parent component causes your component to re-render.

A: If you want to share state across components use redux isntead. Also maintain a separate file for each component.
This link might help you
Step by Step Guide To Building React Redux Apps


text:
Q: Проблема с функцией onclick

btn.onclick = function() {
  if (man.value = 'man') {
    document.getElementsByClassName('circle')[0].style.backgroundColor = "blue";
  } else if (woman.value = 'woman') {
    document.getElementsByClassName('circle')[0].style.backgroundColor = "red";
  }
}
<form name="f2">
  <input type="radio" id="man" name="radio" value="man">

man

  <input type="radio" id="woman" name="radio" value="woman">

woman

</form>

Вобщем, при клике на

btn.onclick = function() {
  if (man.value = 'man') {
    document.getElementsByClassName('circle')[0].style.backgroundColor = "blue";
  } else if (woman.value = 'woman') {
    document.getElementsByClassName('circle')[0].style.backgroundColor = "red";
  }
}
.circle {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  background-color: #000;
  position: absolute;
  left: 40%;
  right: 40%;
  top: 100px;
}
<form name="f2">
  <input type="radio" id="man" name="radio" value="man">

man

  <input type="radio" id="woman" name="radio" value="woman">

woman

</form>

В общем, помогите разобраться, так как я новичок в JS и не очень понимаю в чем проблема: При клике на man, затем на кнопку,  circle должен менять цвет на синий. Если  на woman, то на красный

A:

document.querySelector(".circle").onclick = function() {
  if (man.checked) {
    document.getElementsByClassName('circle')[0].style.backgroundColor = "blue";
  } else if (woman.checked) {
    document.getElementsByClassName('circle')[0].style.backgroundColor = "red";
  }
}
.circle {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  background-color: #000;
  position: absolute;
  left: 40%;
  right: 40%;
  top: 100px;
}
<form name="f2">
  <input type="radio" id="man" name="radio" value="man">

man

  <input type="radio" id="woman" name="radio" value="woman">

woman

</form>


text:
Q: If I understand correctly: C# Equality operator ( == ) and order of operands Similar questions have been asked, but I'm not sure I understand the answers correctly. I am referring to a situation where the equality operator is overridden in one or both classes. Please explain if I'm right. If I write if(a == b) { ... }, then equality operator of the class of "a" is used and in case of if(b == a) { ... } is used then equality operator defined in the class of "b". The equality operator of which class is used if I write if(null == a) { ... }.

A:
situation where the equality operator is overridden in one or both classes

We can do that and test... something like the following?
class A
{
    public static bool operator == (A a, B b)
    {
        Console.WriteLine("A");
        return false;
    }

    public static bool operator != (A a, B b)
    {
        Console.WriteLine("A");
        return false;
    }

    public static bool operator == (B b, A a)
    {
        Console.WriteLine("A");
        return false;
    }

    public static bool operator != (B b, A a)
    {
        Console.WriteLine("A");
        return false;
    }

    public override bool Equals(object o)
    {
        return false;
    }

    public override int GetHashCode()
    {
        return 0;
    }
}

class B
{
    public static bool operator == (A a, B b)
    {
        Console.WriteLine("B");
        return false;
    }

    public static bool operator != (A a, B b)
    {
        Console.WriteLine("B");
        return false;
    }

    public static bool operator == (B b, A a)
    {
        Console.WriteLine("B");
        return false;
    }

    public static bool operator != (B b, A a)
    {
        Console.WriteLine("B");
        return false;
    }

    public override bool Equals(object o)
    {
        return false;
    }

    public override int GetHashCode()
    {
        return 0;
    }
}

Then you write code such as:
A a = new A();
B b = new B();
if (a == b)
{
    // ...
}

Then you get:

CS0034 Operator '==' is ambiguous on operands of type 'A' and 'B'

Does that answer your question? Have a look at the code, when you define the operator == you specify the types of the parameters, and the compiler uses that to choose the operator to call. In this case it finds two operators that have operands A and B in that order and that results in an ambiguous call (the compiler does not know - does not have a way to decide - which one to use).

If I write if(a == b) { ... }, then equality operator of the class of "a" is used and in case of if(b == a) { ... } is used then equality operator defined in the class of "b"

That depends on the types of the operands. If you always put the operant of the type of the current class as first, then that is true. For example:
void Main()
{
    A a = new A();
    B b = new B();
    if (a == b)
    {
        // ...
    }
}

class A
{
    public static bool operator == (A a, B b)
    {
        Console.WriteLine("A");
        return false;
    }

    public static bool operator != (A a, B b)
    {
        Console.WriteLine("A");
        return false;
    }

    public override bool Equals(object o)
    {
        return false;
    }

    public override int GetHashCode()
    {
        return 0;
    }
}

class B
{
    public static bool operator == (B b, A a)
    {
        Console.WriteLine("B");
        return false;
    }

    public static bool operator != (B b, A a)
    {
        Console.WriteLine("B");
        return false;
    }

    public override bool Equals(object o)
    {
        return false;
    }

    public override int GetHashCode()
    {
        return 0;
    }
}

Output: A.
However, if define the operators with the operands in the opposite order...
void Main()
{
    A a = new A();
    B b = new B();
    if (a == b)
    {
        // ...
    }
}

class A
{
    public static bool operator == (B b, A a)
    {
        Console.WriteLine("A");
        return false;
    }

    public static bool operator != (B b, A a)
    {
        Console.WriteLine("A");
        return false;
    }

    public override bool Equals(object o)
    {
        return false;
    }

    public override int GetHashCode()
    {
        return 0;
    }
}

class B
{
    public static bool operator == (A a, B b)
    {
        Console.WriteLine("B");
        return false;
    }

    public static bool operator != (A a, B b)
    {
        Console.WriteLine("B");
        return false;
    }

    public override bool Equals(object o)
    {
        return false;
    }

    public override int GetHashCode()
    {
        return 0;
    }
}

Output: B.

The equality operator of which class is used if I write if(null == a) { ... }

First, let us be clear. B or any other classes are irrelevant here. They do not affect the outcome of this comparison, because you are not using them here. It would be very inconvenient if they did.
Let us try:
void Main()
{
    A a = new A();
    if (null == a)
    {
        // ...
    }
}

class A
{
    public static bool operator == (A a, B b)
    {
        Console.WriteLine("A");
        return false;
    }

    public static bool operator != (A a, B b)
    {
        Console.WriteLine("A");
        return false;
    }

    public override bool Equals(object o)
    {
        return false;
    }

    public override int GetHashCode()
    {
        return 0;
    }
}

class B
{
    public static bool operator == (B b, A a)
    {
        Console.WriteLine("B");
        return false;
    }

    public static bool operator != (B b, A a)
    {
        Console.WriteLine("B");
        return false;
    }

    public override bool Equals(object o)
    {
        return false;
    }

    public override int GetHashCode()
    {
        return 0;
    }
}

Output: .
We get no output, because the called operator is none of the ones defined here... intead it is using the default operator (the one for object).
Wait! What if I change the order of operands?
void Main()
{
    A a = new A();
    if (null == a)
    {
        // ...
    }
}

    class A
{
    public static bool operator == (B b, A a)
    {
        Console.WriteLine("A");
        return false;
    }

    public static bool operator != (B b, A a)
    {
        Console.WriteLine("A");
        return false;
    }

    public override bool Equals(object o)
    {
        return false;
    }

    public override int GetHashCode()
    {
        return 0;
    }
}

class B
{
    public static bool operator == (A a, B b)
    {
        Console.WriteLine("B");
        return false;
    }

    public static bool operator != (A a, B b)
    {
        Console.WriteLine("B");
        return false;
    }

    public override bool Equals(object o)
    {
        return false;
    }

    public override int GetHashCode()
    {
        return 0;
    }
}

Output: A.
Now we are using the operator on A because it matches the operand types better than the default operator does.

A: Simply try it out.
public class Program
{
    public static void Main()
    {
        var foo = new Foo();

        if(foo == null)
        {
        }

        if(null == foo)
        {
        }
    }
}

public class Foo
{
    public static bool operator ==(Foo a, Foo b)
    {
        Console.WriteLine("Foo operator == called");
        return ReferenceEquals(a, b);
    }

    public static bool operator !=(Foo a, Foo b)
    {
        Console.WriteLine("Foo operator != called");
        return !(a == b);
    }

    public override bool Equals(object obj)
    {
        Console.WriteLine("Foo Equals() called");
        return ReferenceEquals(this, obj);
    }

    public override int GetHashCode()
    {
        Console.WriteLine("Foo GetHashCode() called");
        return base.GetHashCode();
    }
}

Output:
Foo operator == called
Foo operator == called

So in both cases the equality operator of class Foo will be called.


text:
Q: How to query NVIDIA GPU parameters for a certain PID? I know with nvidia-smi an overview is generated like:
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 375.66                 Driver Version: 375.66                    |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|===============================+======================+======================|
|   0  Quadro P4000        Off  | 0000:01:00.0     Off |                  N/A |
| N/A   43C    P0    26W /  N/A |    227MiB /  8114MiB |      0%      Default |
+-------------------------------+----------------------+----------------------+

+-----------------------------------------------------------------------------+
| Processes:                                                       GPU Memory |
|  GPU       PID  Type  Process name                               Usage      |
|=============================================================================|
|    0      1724    G   /usr/bin/X                                     219MiB |
|    0      8074    G   qtcreator                                        6MiB |
+-----------------------------------------------------------------------------+

However, for the parameters I'd like to break it down for each process (e.g. GPU usage, used memory). I can't find a respective query, but then again I can't imagine that such a basic function is not implemented. Hence
Is there an easy way to display the GPU parameters for each process?

A: I don't think it gets any closer to nvidia-smi pmon:
# gpu     pid  type    sm   mem   enc   dec    fb   command
# Idx       #   C/G     %     %     %     %    MB   name
    0    1750     G     1     0     0     0   179   X
    0    3734     G     0     0     0     0     7   qtcreator


text:
Q: Is there a way to spawn zombies at certain coordinates? For my adventure map, I need to know if you can spawn zombies at certain coordinates using command blocks. Allowing them to spawn naturally in the dark is not an option.

A: Use the summon command.
/summon [mob] [x] [y] [z]
For example:
/summon Zombie 32 56 21 will spawn a zombie at XYZ 32, 56, 21


text:
Q: Manual Decompilation References I'm looking for book titles or papers about how to decompile X86 Disassembly into C/C++ code MANUALLY.
Well , I know about many tools that do the job , but I think doing it manually is more efficient even if it's a slow process.

A: If you are VERY used to looking at disassembly from a particular compiler, you MAY be able to come up with decent C or C++ code. But it's a TERRIBLY slow process even then. Just taking one small function (say a for-loop, a couple of if-statements and some basic math) and reconstructing it back into source code can take half an hour for me, and I don't think I'm terribly bad at it. Of course, one of the main points is identifying commonly used algorithms, such as linked lists, binary trees, string management, vector management, etc.
Doing it by machine will give you a lot of the work done for you, but even then, it can take days to do even a few hundred lines of orginal C++ code into something that is actually readable.


text:
Q: $9n^2-4$ only generates one prime? Why? Instead of doing the work I was supposed to be doing, I played around with some numbers, and I noticed that for $n\in\mathbb{N}$, $9n^2-4$ only seems to generate a prime for $n=1$.
Can anyone explain why?
EDIT: Please don't judge me.

A: $$9n^2 - 4 = (3n-2)(3n+2)$$
which is composite for $\forall n\gt 1$.

A: On the other hand, if $n$ is a Markov number, also http://oeis.org/A002559 then $9n^2 - 4$ is the sum of two squares, which you don't see every day.
$$ 9n^2 - 4 = x^2 + y^2  $$
               n        9n^2 - 4             x      y
   1           1              5              2      1
   2           2             32              4      4
   3           5            221             14      5
   4          13           1517             34     19
   5          29           7565             86     13
   6          34          10400            100     20
   7          89          71285            266     23
   8         169         257045            502     71
   9         194         338720            556    172
  10         233         488597            679    166
  11         433        1687397            961    874
  12         610        3348896           1636    820
  13         985        8732021           2786    985
  14        1325       15800621           3875    886
  15        1597       22953677           4286   2141
  16        2897       75533477           7586   4241
  17        4181      157326845          12341   2242
  18        5741      296631725          17197    946
  19        6466      376282400          19372   1004
  20        7561      514518485          22486   2983
  21        9077      741527357          26971   3754
  22       10946     1078334240          32716   2828
  23       14701     1945074605          43709   5882
               n      9n^2 - 4             x      y


text:
Q: opencv cv::max behavior unexpected I'm using cv::max with an uninitialized Mat object, and error happens when passing the uninitialized object as the 1st param:
Mat a=Mat::ones(2,3, CV_32S);
Mat b;
max(a, b); // 1. OK
max(b, a); // 2. OpenCV Error

The error message is:

OpenCV Error: Sizes of input arguments do not match (The operation is
  neither 'a rray op array' (where arrays have the same size and type),
  nor 'array op scalar' , nor 'scalar op array') in cv::binary_op, file
  C:\builds\2_4_PackSlave-win32-vc
  11-shared\opencv\modules\core\src\arithm.cpp, line 1021

My question: Should not the two calls be of the same effect theorectically? Is that a implementation imperfection or my misunderstanding?
EDIT:
I'm using vs2012 with OpenCV2.4.8 x86 on win7 x64

A: This was a bug, but has now been fixed. Please see http://code.opencv.org/issues/3696#note-7 for comment stating that the bug has been fixed.
Note: An equivalent problem existed for cv::min.


text:
Q: @EnableWebSecurity possible with Pre-Authentication? I'm trying Spring Security 3.2RC2. Is it possible to use @EnableWebSecurity with Pre-Authentication? I cannot find a configurer for that.

A: Use this annotation: @EnableGlobalMethodSecurity
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class HelloMethodSecurityConfig {
    ...
}

Source


text:
Q: Subscribe to "GetValue" of a DependencyProperty I have a DependencyProperty in my UserControl -
public static readonly DependencyProperty ColumnConfigDataProperty =
    DependencyProperty.Register("ColumnConfigData", typeof(string), typeof(MyUserControl), new PropertyMetadata("", new PropertyChangedCallback(OnColumnConfigChanged)));

public string ColumnConfigData
{
    get{ return (string)GetValue(ColumnConfigDataProperty);}
    set { SetValue(ColumnConfigDataProperty, value); }
}

When the client application (that uses my UserControl) tries to access the DependencyProperty, I want to update the DependencyProperty with a new value. I didn't get how to subscribe to GetValue of the DependencyProperty.


text:
Q: Loading Circle in Visual C# 2010? Instead of a regular progress bar, how can I make a circle with spokes that rotate telling the user that that my program is loading?
EDIT: I want it in Windows Forms
Ok thanks Tim, your solution works. I had to set the image by code since importing it in the designer froze it up.

A: I normally go to http://ajaxload.info/ and put one of their animated GIFs in a PictureBox.

A: This is the one I actually used in one of my apps
Circular Progress indicator.This second one is for WPF apps.


text:
Q: How to change the background image of tab bar in Objective-C? I am develop in objective-C. I want to change the tab bar background like the following picture:

And the code is like the following:
UIImage *tabBarBackground = [UIImage imageNamed:@"tabbaritem_background.png"];
[[UITabBar appearance] setBackgroundImage:tabBarBackground];

But after setting the background image , the background is not at the correct place like the following:

The background image should be place at the bottom like the background in above picture.
Did I missing something ? Can someone help me ?
Thanks in advance.

A: I think is somewhere you go wrong, check if is this steps:

*

*In the storyboard change the ViewController's background color for test.

*Embed the ViewController in Tab Bar Controller

*In the ViewController.m you can set the tabbar bacground color:
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    [[UITabBar appearance] setBackgroundColor:[UIColor grayColor]]; // Here you can set the converted color form image, make sure the imageSize fit.
}

*The result is below:

A: I think the method - (UIImage *)resizableImageWithCapInsets:(UIEdgeInsets)capInsets resizingMode:(UIImageResizingMode)resizingMode you can try, because your backgroudimage's size is not equal to tabbar'size.

A: Try this method to change your image to a ScaleImage.
+(UIImage *)getScaleImageNamed:(NSString *)name{
    UIImage *nomalImage = [UIImage imageNamed:name];

    CGFloat hInset = floorf(nomalImage.size.width / 2);
    CGFloat vInset = floorf(nomalImage.size.height / 2);

    UIImage *res = [nomalImage resizableImageWithCapInsets:UIEdgeInsetsMake(vInset, hInset, vInset, hInset)];

    return res;
}

A: Steps you may miss, hope that can help.

*

*Make sure you have imported the background image (e.g. in Assets.xcassets)

*Use resizableImageWithCapInsets: to resize the background image

*Put the UIAppearance settings in AppDelegate.m:
[[UITabBar appearance] setBackgroundImage:[[UIImage imageNamed:@"tabbaritem_background.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 0, 0, 0)]];


text:
Q: Do xaml animations block the main thread? Do the xaml animations block the main thread? I'm showing a big grid with lots of data and several animations and even with everything (but the property changes) on background threads the UI is far from being smooth.
As I have several Dispatcher.BeginInvoke (and some Invoke when needed) I was thinking that maybe the animations make the invokes to go slower. Am I right?
Thanks in advance.

A: I'd recommend investing in a profiler.  Certainly, animations run on the UI thread and heavy use of animations might be the cause of the choppiness, but there is no way for us to know for sure.
My preference for profiling C# is dotTrace, but there are tons of others out there.  There are even WPF-specific diagnostic tools from Microsoft in the WPF Performance Suite, but I haven't tried them.


text:
Q: PHP : Difference b/w new self and new object() I  was watching  PHP video lectures . I have user class in my project directory  now  in tutorial inside a static function  its instantiated like this
 private static function  instantiate($result){
 $object = new self;
 //here goes loop
 }

and somewhere  its used like this
$object= new user();

Will  someone please guide me about  the concept  of   first case  where it says new self

A: "self" is a keyword that references the current class. It is only available inside the class' code.
You can use it to call methods on your own class, but due to binding you can also use it to call methods on a superclass.
Consider the following example:
class TestA {
  public static function makeNewInstance() {
    return new TestA();
  }
}

class TestB extends TestA {
}

Now, calling TestB::makeNewInstance(); will return an instance of TestA. (TestB inherits the method, but it's linked directly to TestA so will still return that)
Compare with this one:
class TestA {
  public static function makeNewInstance() {
    return new self();
  }
}

class TestB extends TestA {
}

Now, calling TestB::makeNewInstance() will return an instance of TestB. (Since self references the active class, and you're calling it on TestB, the contents of "self" is now TestB instead of TestA.
Hope that explains for you. Otherwise, maybe some more detail in your question would help attract more specific answers.

A: self points to the class in which it is written. Refer What does new self(); mean in PHP?
$object= new user(); // It makes the object of the class user - outside from the user class


text:
Q: How to include Javascript & jQuery into HTML I am doing a sample application. In my application I am trying to insert javascript into the html. But I am not getting the desired result.
I had downloaded a tab form and this link provides a demo what it actually looks like
My jsp file
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <%@taglib uri="http://www.springframework.org/tags/form"
prefix="form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"    "http://www.w3.org/TR/html4/loose.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Insert title here</title>

        Home

 Home

 Teams

 Events

The team

About us

Contact us

                new entry1

                new entry2

                new entry3

I had placed the files inside web-inf/views/tab/ and the

tab

folder contains

demo.css, script.js, jquery-2.0.3.js.

the ing files are contained in

views/img

The script.js file
   $(document).ready(function(){

$('#navigationMenu li .normalMenu').each(function(){

    $(this).before($(this).clone().removeClass().addClass('hoverMenu'));

});

$('#navigationMenu li').hover(function(){

    $(this).find('.hoverMenu').stop().animate({marginTop:'0px'},200);

},

function(){

    $(this).find('.hoverMenu').stop().animate({marginTop:'-25px'},200);

});

    });

and the demo.css
/* Page styles */

   body,h1,h2,h3,p,td,quote,small,form,input,ul,li,ol,label{
margin:0px;
padding:0px;
   }

  body{
margin-top:20px;
font-family:Arial, Helvetica, sans-serif;
color:#51555C;
height:100%;
font-size:12px;
   }

  /* Navigation menu styles */

    ul{
height:25px;
font-family:Arial, Helvetica, sans-serif;
font-size:12px;
   }

 ul li{
border:1px solid #444444;
display:inline-block;
float:left;
height:25px;
list-style-type:none;
overflow:hidden;
    }

  ul li a, ul li a:hover,
     ul li a:visited{
text-decoration:none;
      }

      .normalMenu, .normalMenu:visited,
    .hoverMenu, .hoverMenu:visited,
    .selectedMenu,.selectedMenu:visited {
outline:none;
padding:5px 10px;
display:block;
    }

   .hoverMenu,.hoverMenu:visited,
      .selectedMenu,.selectedMenu:visited {
margin-top:-25px;
background:url(img/grey_bg.gif) repeat-x #eeeeee;
color:#444444;
    }

     .selectedMenu,.selectedMenu:visited {
margin:0;
  }

  .normalMenu, .normalMenu:visited{
color:white;
background:url(img/dark_bg.gif) repeat-x #444444;
   }

i want to get the output like this http://demo.tutorialzine.com/2009/09/stylish-navigation-menu-jquery/#. what i am getting is same as the above tab,but the animation is not working andt when i select the second tab first one still showing highlited. On checking i found that the

script.js

file is not reading. Even if we delete the

script.js

file the result is same that is the tab will shows up but no animation and first tab is always highlited.
thanks in advance

A: In the jquery UI documentation you will see they call the script after the dom elements have been created.  Try moving the script tags to just befor the body close tags and see if that works