问:
Error using sqlalchemy to create tables in postgresql
I am working with sqlalchemy (python 2.7) trying to create several tables in a postgresql (9.5) database. ubuntu 16.04

Using the abstraction of sqlalchemy I am having problems creating the tables with their primary and foreign keys for some reason.

Any help would be much appreciated.

Stacktrace and Error message and source code lastly:

```<code>Traceback (most recent call last):
  File "create_db.py", line 49, in <module>
    Base.metadata.create_all(engine)
  File "/home/chris/workspace/final_project/env/local/lib/python2.7/site-packages/sqlalchemy/sql/schema.py", line 3918, in create_all
    tables=tables)
  File "/home/chris/workspace/final_project/env/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1929, in _run_visitor
    conn._run_visitor(visitorcallable, element, **kwargs)
  File "/home/chris/workspace/final_project/env/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1538, in _run_visitor
    **kwargs).traverse_single(element)
  File "/home/chris/workspace/final_project/env/local/lib/python2.7/site-packages/sqlalchemy/sql/visitors.py", line 121, in traverse_single
    return meth(obj, **kw)
  File "/home/chris/workspace/final_project/env/local/lib/python2.7/site-packages/sqlalchemy/sql/ddl.py", line 733, in visit_metadata
    _is_metadata_operation=True)
  File "/home/chris/workspace/final_project/env/local/lib/python2.7/site-packages/sqlalchemy/sql/visitors.py", line 121, in traverse_single
    return meth(obj, **kw)
  File "/home/chris/workspace/final_project/env/local/lib/python2.7/site-packages/sqlalchemy/sql/ddl.py", line 767, in visit_table
    include_foreign_key_constraints=include_foreign_key_constraints
  File "/home/chris/workspace/final_project/env/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 945, in execute
    return meth(self, multiparams, params)
  File "/home/chris/workspace/final_project/env/local/lib/python2.7/site-packages/sqlalchemy/sql/ddl.py", line 68, in _execute_on_connection
    return connection._execute_ddl(self, multiparams, params)
  File "/home/chris/workspace/final_project/env/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1002, in _execute_ddl
    compiled
  File "/home/chris/workspace/final_project/env/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1189, in _execute_context
    context)
  File "/home/chris/workspace/final_project/env/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1402, in _handle_dbapi_exception
    exc_info
  File "/home/chris/workspace/final_project/env/local/lib/python2.7/site-packages/sqlalchemy/util/compat.py", line 203, in raise_from_cause
    reraise(type(exception), exception, tb=exc_tb, cause=cause)
  File "/home/chris/workspace/final_project/env/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1182, in _execute_context
    context)
  File "/home/chris/workspace/final_project/env/local/lib/python2.7/site-packages/sqlalchemy/engine/default.py", line 470, in do_execute
    cursor.execute(statement, parameters)

sqlalchemy.exc.ProgrammingError: (psycopg2.ProgrammingError) there is no unique constraint matching given keys for referenced table "filerecord"
 [SQL: '\nCREATE TABLE prodrecord (\n\tproductcode INTEGER NOT NULL, \n\tproductname VARCHAR(80), \n\tproductversion VARCHAR(80), \n\topsystemcode VARCHAR(50) NOT NULL, \n\tmfgcode VARCHAR(50) NOT NULL, \n\tlanguage VARCHAR(80), \n\tapplicationtype VARCHAR(80), \n\tPRIMARY KEY (productcode, opsystemcode, mfgcode), \n\tUNIQUE (productcode, opsystemcode, mfgcode), \n\tFOREIGN KEY(productcode) REFERENCES filerecord (productcode), \n\tFOREIGN KEY(opsystemcode) REFERENCES osrecord (opsystemcode), \n\tFOREIGN KEY(mfgcode) REFERENCES mfgrecord (mfgcode)\n)\n\n']
</code>```

create_db.py source

```<code>from sqlalchemy import Column, ForeignKey, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy import create_engine
from sqlalchemy.schema import UniqueConstraint

Base = declarative_base()

class FileRecord(Base):
    __tablename__ = 'filerecord'
    sha1 = Column(String(80))
    md5 = Column(String(80))
    crc32 = Column(String(80))
    filename = Column(String(80))
    filesize = Column(Integer)
    productcode = Column(Integer, primary_key=True, unique=True)
    opsystemcode = Column(String(50))
    specialcode = Column(String(50))

class MfgRecord(Base):
    __tablename__ = 'mfgrecord'
    mfgcode = Column(String(80), primary_key=True, unique=True)
    mfgname = Column(String(80))

class OSRecord(Base):
    __tablename__ = 'osrecord'
    opsystemcode = Column(String(80), primary_key=True, unique=True)
    opsystemname = Column(String(80))
    opsystemversion = Column(String(80))
    mfgcode = Column(String(80))

class ProdRecord(Base):
    __tablename__ = 'prodrecord'
    productcode = Column(Integer, ForeignKey('filerecord.productcode'), primary_key=True)
    productname = Column(String(80))
    productversion = Column(String(80))
    opsystemcode = Column(String(50), ForeignKey('osrecord.opsystemcode'), primary_key=True)
    mfgcode = Column(String(50), ForeignKey('mfgrecord.mfgcode'), primary_key=True)
    language = Column(String(80))
    applicationtype = Column(String(80))
    __table_args__ = (UniqueConstraint
                        (productcode, opsystemcode, mfgcode),)

if __name__ == "__main__":
    db_string = "postgres://postgres:Drpepper1@localhost:5432/project"
    engine = create_engine(db_string)
    Base.metadata.create_all(engine)
</code>```

答:
Obviously @univerio's comment above solved the problem, but that solution is not valid in a production setting--where dropping all the tables is simply not an option. One of the popular (and incredibly powerful) ways of managing a database, and the accompanying migrations that follow, is by using Alembic. It was written by the same guy who wrote SQLAlchemy, and I cannot recommend it enough. Here are a few more articles on that same topic:

https://www.compose.com/articles/schema-migrations-with-alembic-python-and-postgresql/
https://realpython.com/blog/python/flask-by-example-part-2-postgres-sqlalchemy-and-alembic/

Body:
I am working with sqlalchemy (python 2.7) trying to create several tables in a postgresql (9.5) database. ubuntu 16.04

Using the abstraction of sqlalchemy I am having problems creating the tables with their primary and foreign keys for some reason.

Any help would be much appreciated.

Stacktrace and Error message and source code lastly:

Traceback (most recent call last):
  File "create_db.py", line 49, in <module>
    Base.metadata.create_all(engine)
  File "/home/chris/workspace/final_project/env/local/lib/python2.7/site-packages/sqlalchemy/sql/schema.py", line 3918, in create_all
    tables=tables)
  File "/home/chris/workspace/final_project/env/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1929, in _run_visitor
    conn._run_visitor(visitorcallable, element, **kwargs)
  File "/home/chris/workspace/final_project/env/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1538, in _run_visitor
    **kwargs).traverse_single(element)
  File "/home/chris/workspace/final_project/env/local/lib/python2.7/site-packages/sqlalchemy/sql/visitors.py", line 121, in traverse_single
    return meth(obj, **kw)
  File "/home/chris/workspace/final_project/env/local/lib/python2.7/site-packages/sqlalchemy/sql/ddl.py", line 733, in visit_metadata
    _is_metadata_operation=True)
  File "/home/chris/workspace/final_project/env/local/lib/python2.7/site-packages/sqlalchemy/sql/visitors.py", line 121, in traverse_single
    return meth(obj, **kw)
  File "/home/chris/workspace/final_project/env/local/lib/python2.7/site-packages/sqlalchemy/sql/ddl.py", line 767, in visit_table
    include_foreign_key_constraints=include_foreign_key_constraints
  File "/home/chris/workspace/final_project/env/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 945, in execute
    return meth(self, multiparams, params)
  File "/home/chris/workspace/final_project/env/local/lib/python2.7/site-packages/sqlalchemy/sql/ddl.py", line 68, in _execute_on_connection
    return connection._execute_ddl(self, multiparams, params)
  File "/home/chris/workspace/final_project/env/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1002, in _execute_ddl
    compiled
  File "/home/chris/workspace/final_project/env/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1189, in _execute_context
    context)
  File "/home/chris/workspace/final_project/env/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1402, in _handle_dbapi_exception
    exc_info
  File "/home/chris/workspace/final_project/env/local/lib/python2.7/site-packages/sqlalchemy/util/compat.py", line 203, in raise_from_cause
    reraise(type(exception), exception, tb=exc_tb, cause=cause)
  File "/home/chris/workspace/final_project/env/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1182, in _execute_context
    context)
  File "/home/chris/workspace/final_project/env/local/lib/python2.7/site-packages/sqlalchemy/engine/default.py", line 470, in do_execute
    cursor.execute(statement, parameters)

sqlalchemy.exc.ProgrammingError: (psycopg2.ProgrammingError) there is no unique constraint matching given keys for referenced table "filerecord"
 [SQL: '\nCREATE TABLE prodrecord (\n\tproductcode INTEGER NOT NULL, \n\tproductname VARCHAR(80), \n\tproductversion VARCHAR(80), \n\topsystemcode VARCHAR(50) NOT NULL, \n\tmfgcode VARCHAR(50) NOT NULL, \n\tlanguage VARCHAR(80), \n\tapplicationtype VARCHAR(80), \n\tPRIMARY KEY (productcode, opsystemcode, mfgcode), \n\tUNIQUE (productcode, opsystemcode, mfgcode), \n\tFOREIGN KEY(productcode) REFERENCES filerecord (productcode), \n\tFOREIGN KEY(opsystemcode) REFERENCES osrecord (opsystemcode), \n\tFOREIGN KEY(mfgcode) REFERENCES mfgrecord (mfgcode)\n)\n\n']

create_db.py source

from sqlalchemy import Column, ForeignKey, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy import create_engine
from sqlalchemy.schema import UniqueConstraint

Base = declarative_base()

class FileRecord(Base):
    __tablename__ = 'filerecord'
    sha1 = Column(String(80))
    md5 = Column(String(80))
    crc32 = Column(String(80))
    filename = Column(String(80))
    filesize = Column(Integer)
    productcode = Column(Integer, primary_key=True, unique=True)
    opsystemcode = Column(String(50))
    specialcode = Column(String(50))

class MfgRecord(Base):
    __tablename__ = 'mfgrecord'
    mfgcode = Column(String(80), primary_key=True, unique=True)
    mfgname = Column(String(80))

class OSRecord(Base):
    __tablename__ = 'osrecord'
    opsystemcode = Column(String(80), primary_key=True, unique=True)
    opsystemname = Column(String(80))
    opsystemversion = Column(String(80))
    mfgcode = Column(String(80))

class ProdRecord(Base):
    __tablename__ = 'prodrecord'
    productcode = Column(Integer, ForeignKey('filerecord.productcode'), primary_key=True)
    productname = Column(String(80))
    productversion = Column(String(80))
    opsystemcode = Column(String(50), ForeignKey('osrecord.opsystemcode'), primary_key=True)
    mfgcode = Column(String(50), ForeignKey('mfgrecord.mfgcode'), primary_key=True)
    language = Column(String(80))
    applicationtype = Column(String(80))
    __table_args__ = (UniqueConstraint
                        (productcode, opsystemcode, mfgcode),)

if __name__ == "__main__":
    db_string = "postgres://postgres:Drpepper1@localhost:5432/project"
    engine = create_engine(db_string)
    Base.metadata.create_all(engine)


来源: stackexchange

问:
Attach process stderr in the case of an error
I am running a bunch of integration tests on a single executable. The program signals an error condition by its return code and might print some (diverse but still useful) output to stderr.

I am currently using the process library as follows:

```<code>         ${result} =         Run Process        ${prog}        ${src}
         Should Be Equal As Integers    ${result.rc}    0
</code>```

This works fine in the case of succeeding tests, but in the case of errors it does not yield any meaningful information. Is there a way to attach the stderr stream to the log file in the case of failing tests? I am reluctant to add in for every test case to not clutter the log file, but if that is the only option, I would appreciate a hint on how to do this the orthodox way as well.

答:
From the documentation at Process documentation, you can redirect stderrto a file:

Standard output and error streams

By default processes are run so that their standard output and standard error streams are kept in the memory. This works fine normally, but if there is a lot of output, the output buffers may get full and the program can hang.
Additionally on Jython, everything written to these in-memory buffers can be lost if the process is terminated.
To avoid the above mentioned problems, it is possible to use stdout and stderr arguments to specify files on the file system where to redirect the outputs. This can also be useful if other processes or other keywords need to read or manipulate the outputs somehow.
Given stdout and stderr paths are relative to the current working directory. Forward slashes in the given paths are automatically converted to backslashes on Windows.
As a special feature, it is possible to redirect the standard error to the standard output by using stderr=STDOUT.
Regardless are outputs redirected to files or not, they are accessible through the result object returned when the process ends. Commands are expected to write outputs using the console encoding, but output encoding can be configured using the output_encoding argument if needed.

Examples:

```<code>${result} = Run Process program stdout=${TEMPDIR}/stdout.txt    stderr=${TEMPDIR}/stderr.txt
Log Many    stdout: ${result.stdout}    stderr: ${result.stderr}
${result} = Run Process program stderr=STDOUT
Log all output: ${result.stdout}
</code>```

Note that the created output files are not automatically removed after the test run. The user is responsible to remove them if needed.

ContentLicense: CC BY-SA 3.0

Body:
I am running a bunch of integration tests on a single executable. The program signals an error condition by its return code and might print some (diverse but still useful) output to stderr.

I am currently using the process library as follows:

         ${result} =         Run Process        ${prog}        ${src}
         Should Be Equal As Integers    ${result.rc}    0

This works fine in the case of succeeding tests, but in the case of errors it does not yield any meaningful information. Is there a way to attach the stderr stream to the log file in the case of failing tests? I am reluctant to add in for every test case to not clutter the log file, but if that is the only option, I would appreciate a hint on how to do this the orthodox way as well.

Body:
From the documentation at Process documentation, you can redirect stderrto a file:

Standard output and error streams

By default processes are run so that their standard output and standard error streams are kept in the memory. This works fine normally, but if there is a lot of output, the output buffers may get full and the program can hang.
Additionally on Jython, everything written to these in-memory buffers can be lost if the process is terminated.
To avoid the above mentioned problems, it is possible to use stdout and stderr arguments to specify files on the file system where to redirect the outputs. This can also be useful if other processes or other keywords need to read or manipulate the outputs somehow.
Given stdout and stderr paths are relative to the current working directory. Forward slashes in the given paths are automatically converted to backslashes on Windows.
As a special feature, it is possible to redirect the standard error to the standard output by using stderr=STDOUT.
Regardless are outputs redirected to files or not, they are accessible through the result object returned when the process ends. Commands are expected to write outputs using the console encoding, but output encoding can be configured using the output_encoding argument if needed.

Examples:

${result} = Run Process program stdout=${TEMPDIR}/stdout.txt    stderr=${TEMPDIR}/stderr.txt
Log Many    stdout: ${result.stdout}    stderr: ${result.stderr}
${result} = Run Process program stderr=STDOUT
Log all output: ${result.stdout}

Note that the created output files are not automatically removed after the test run. The user is responsible to remove them if needed.


问:
get next immediate same date using php

i need to get immediate date like if i select date is 05 then output will be 2017-07-05 cause select date already passed

if i select 12 then output will be 2017-06-12 cause this date future date

final if i select previous date of current month then output will be next month same date and if i select future date of current month then output will be same month

i have tired but not working this

```<code>$today = date("Y-m-d");
$next_payment_date = date('Y-m-d', strtotime('+1 month', $today));
</code>```

or

```<code>$time = time();
date("Y-m-d", mktime(0,0,0,date("n", $time),date("j",$time)- 1 ,date("Y", $time)));
</code>```

thanks in your advance

答:
One more option:

https://3v4l.org/Me2Kh

```<code>$input = 12;
$day = date("d");

if ($input > $day){
    $date = date("Y-m-"). str_pad($input,2,"0", STR_PAD_LEFT);
}else{

    $date = date("Y-m-",strtotime("+1 month")). str_pad($input,2,"0", STR_PAD_LEFT);
}

echo $date;
</code>```

I use str_pad to keep two digit day number.

Title: get next immediate same date using php

Body:
i need to get immediate date like if i select date is 05 then output will be 2017-07-05 cause select date already passed

if i select 12 then output will be 2017-06-12 cause this date future date

final if i select previous date of current month then output will be next month same date and if i select future date of current month then output will be same month

i have tired but not working this

$today = date("Y-m-d");
$next_payment_date = date('Y-m-d', strtotime('+1 month', $today));

or

$time = time();
date("Y-m-d", mktime(0,0,0,date("n", $time),date("j",$time)- 1 ,date("Y", $time)));

thanks in your advance

Body:
One more option:

https://3v4l.org/Me2Kh

$input = 12;
$day = date("d");

if ($input > $day){
    $date = date("Y-m-"). str_pad($input,2,"0", STR_PAD_LEFT);
}else{

    $date = date("Y-m-",strtotime("+1 month")). str_pad($input,2,"0", STR_PAD_LEFT);
}

echo $date;

I use str_pad to keep two digit day number.


问:
TURN server broken - Coturn
Just a bit of background first.

I have installed coturn server in my local machine (Behind a firewall and with local IP).
I have created a port forwarding for cotrun server lets say my local ip is: 192.168.0.11:3478  is mapped with my public ip 10.1.10.212:3478.

When I use some online utility to check my public IP has this port open it? that utility shows that it is open.

I am trying to test this server using this fiddle: Code to test TURN server

I removed the stun configuration from it, and added my live ip and port. And when I try to test it, it says your TURN server is broken in console on web browser. And I see failed as output.

I have also used following commands to create a user from this link.
Wiki to Coturn Configuration

```<code>// created test user
sudo turnadmin -a -u test -r  test -p test

// enabling admin support in web (not sure how to access it in browser)
sudo turnadmin -A -u test -p test
</code>```

I start the turn server using following command:
turnserver -L 192.168.0.11 -a -f -v -X -r test

I have enabled the "TURNSERVER_ENABLED"

```<code>/etc/default/coturn
TURNSERVER_ENABLED=1
</code>```

Screenshot of my about:webrtc:

Please find the below attached Screen shot for my about:webrtc. I am not sure what is missing.

EDIT-1
I can also see the incoming packet message processed, error 401: Unauthorized in the console of TURN server

EDIT-2
I resolved the TURN server related issue, added the turn server in client code as well, still facing issue, call is not going through,

Update
Here is what I found, the reason why it wasn't working earlier was due to a defective router in the network. This thing has harassed me for almost a month (however the internet used to work fine). But I found that there is a loss of packets and I switch to LAN cable I even avoided the firewall of the organization and there it was working just fine. Then I configured the rules in firewall and it started working as well.

答:
A few issues that might be causing this:

The -X option requires an argument - the external IP if the TURN server is behind a NAT.

If you are setting all your parameters on the command line, you should include -n to ensure that it does not load an unrelated configuration file.

TURNSERVER_ENABLED=1 is to start turnserver with default configuration at system boot. You do not want this if you are starting turnserver manually from the command line.

https://github.com/coturn/coturn/blob/master/README.turnserver

ContentLicense: CC BY-SA 4.0

Title: TURN server broken - Coturn

Body:
Just a bit of background first.

I have installed coturn server in my local machine (Behind a firewall and with local IP).
I have created a port forwarding for cotrun server lets say my local ip is: 192.168.0.11:3478  is mapped with my public ip 10.1.10.212:3478.

When I use some online utility to check my public IP has this port open it? that utility shows that it is open.

I am trying to test this server using this fiddle: Code to test TURN server

I removed the stun configuration from it, and added my live ip and port. And when I try to test it, it says your TURN server is broken in console on web browser. And I see failed as output.

I have also used following commands to create a user from this link.
Wiki to Coturn Configuration

// created test user
sudo turnadmin -a -u test -r  test -p test

// enabling admin support in web (not sure how to access it in browser)
sudo turnadmin -A -u test -p test

I start the turn server using following command:
turnserver -L 192.168.0.11 -a -f -v -X -r test

I have enabled the "TURNSERVER_ENABLED"

/etc/default/coturn
TURNSERVER_ENABLED=1

Screenshot of my about:webrtc:

Please find the below attached Screen shot for my about:webrtc. I am not sure what is missing.

EDIT-1
I can also see the incoming packet message processed, error 401: Unauthorized in the console of TURN server

EDIT-2
I resolved the TURN server related issue, added the turn server in client code as well, still facing issue, call is not going through,

Update
Here is what I found, the reason why it wasn't working earlier was due to a defective router in the network. This thing has harassed me for almost a month (however the internet used to work fine). But I found that there is a loss of packets and I switch to LAN cable I even avoided the firewall of the organization and there it was working just fine. Then I configured the rules in firewall and it started working as well.


问:
push cloned <option> into array
The Code as follows

```<code>var options = $("#select> option").clone();

$('#btn').on('click',function(e){

       e.preventDefault();
       var copyEl = [];
       copyEl.push("<select id='select"+i+"'class='select form-control'>");
       options.each(function(){
                console.log(this);
                copyEl.push(this);
            });

      copyEl.push("</select>");

      copyEl = $(copyEl.join(''));

      $('#div').after(copyEl.clone());

});
</code>```

this is what i do find when inspect the element

[object HTMLOptionElement][object HTMLOptionElement][object HTMLOptionElement][object HTMLOptionElement][object HTMLOptionElement][object HTMLOptionElement][object HTMLOptionElement][object HTMLOptionElement][object HTMLOptionElement][object HTMLOptionElement][object HTMLOptionElement][object HTMLOptionElement][object HTMLOptionElement][object HTMLOptionElement][object HTMLOptionElement][object HTMLOptionElement][object HTMLOptionElement][object HTMLOptionElement][object HTMLOptionElement][object HTMLOptionElement]

the console print

```<code><option id='1'>Toy</option>
<option id='2'>Story</option>
</code>```

which is result that i do need to push in the array , this code was working fine with the <datalist> but is not working with <select> any way to add the
to the array ?

答:
I think you want create select dynamically using cloned options. Use jQuery(html, attributes) to create selected then .append() cloned options to select.

```<code>$('#btn').on('click', function (e) {
    e.preventDefault();
    var select = $("<select>", { id : 'select' + i,
         'class': 'select form-control'
    });
    select.append(options);
    $('#div').after(select);
});
</code>```

As per comment, use outerHTML property

```<code>options.each(function(){
    copyEl.push(this.outerHTML);
});
</code>```

Title: push cloned <option> into array

Body:
The Code as follows

var options = $("#select> option").clone();

$('#btn').on('click',function(e){

       e.preventDefault();
       var copyEl = [];
       copyEl.push("<select id='select"+i+"'class='select form-control'>");
       options.each(function(){
                console.log(this);
                copyEl.push(this);
            });

      copyEl.push("</select>");

      copyEl = $(copyEl.join(''));

      $('#div').after(copyEl.clone());

});

this is what i do find when inspect the element

[object HTMLOptionElement][object HTMLOptionElement][object HTMLOptionElement][object HTMLOptionElement][object HTMLOptionElement][object HTMLOptionElement][object HTMLOptionElement][object HTMLOptionElement][object HTMLOptionElement][object HTMLOptionElement][object HTMLOptionElement][object HTMLOptionElement][object HTMLOptionElement][object HTMLOptionElement][object HTMLOptionElement][object HTMLOptionElement][object HTMLOptionElement][object HTMLOptionElement][object HTMLOptionElement][object HTMLOptionElement]

the console print

<option id='1'>Toy</option>
<option id='2'>Story</option>

which is result that i do need to push in the array , this code was working fine with the <datalist> but is not working with <select> any way to add the
to the array ?

Body:
I think you want create select dynamically using cloned options. Use jQuery(html, attributes) to create selected then .append() cloned options to select.

$('#btn').on('click', function (e) {
    e.preventDefault();
    var select = $("<select>", { id : 'select' + i,
         'class': 'select form-control'
    });
    select.append(options);
    $('#div').after(select);
});

As per comment, use outerHTML property

options.each(function(){
    copyEl.push(this.outerHTML);
});


问:
Prevent a property from being called twice
I have a window with a few text fields and an OK and Cancel button. When I click OK it needs to validate my fields and do stuff with them if they're valid and display an error message if they're not.

In my ViewModel I've got

```<code>public ICommand OKCommand { get; private set; }
public Action ErrorAction { get; set; }

OKCommand = new BaseCommand(_ =>
{
    if (string.IsNullOrEmpty(ErrorMessage))
    {
        // Do stuff with the contents of the fields
        ...
    }
    else ErrorAction();
});

public string ErrorMessage
{
    get
    {
        // Gets the error message for the fields
        ...
    }
}
</code>```

And in my code behind I've got

```<code>if (ViewModel.ErrorAction == null) ViewModel.ErrorAction = new Action(() => MessageDialog.ShowError(ViewModel.ErrorMessage));
</code>```

My issue is ErrorMessage is called twice when there's an error, first in the OKCommand and again by ErrorAction.

The only solutions I can think of are

Accept the second call - it's not the end of the world.

Determine whether there is an error in OKCommand and set ErrorMessage if appropriate

Something like this

```<code>private bool HasError
{
    get
    {
        // Do the same as ErrorMessage but populate ErrorMessage and return a bool
        ...
    }
}

OKCommand = new BaseCommand(_ =>
{
    if (!HasError)
    {
        // Do stuff with the contents of the fields
        ...
    }
    else ErrorAction();
});
</code>```

While both work I don't think either is great - the first has a second call and the second adds a level of indirection. Are there any alternatives?

答:
There is a simple way to validate a TextBox Text:

it's called ValidationRule

You can directly see  that there is an error(Error in MouseOverMessage) and the Button is disabled

```<code><Window x:Class="TestWpf.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:TestWpf"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <local:MyValidatorProperties x:Key="properties"/>
        <local:MyCustomValidationRule x:Key="validator" />
        <Style x:Key="textBoxInError" TargetType="{x:Type TextBox}">
            <Style.Triggers>
                <Trigger Property="Validation.HasError" Value="true">
                    <Setter Property="BorderBrush" Value="Red"/>
                    <Setter Property="BorderThickness" Value="2" />
                    <Setter Property="ToolTip"
                         Value="{Binding RelativeSource={x:Static RelativeSource.Self},
                        Path=(Validation.Errors)[0].ErrorContent}"/>
                </Trigger>
            </Style.Triggers>
        </Style>
        <ControlTemplate x:Key="validationTemplate">
            <DockPanel>
                <TextBlock Foreground="Red" FontSize="17">!</TextBlock>
                <AdornedElementPlaceholder/>
            </DockPanel>
        </ControlTemplate>
    </Window.Resources>
    <Grid>
        <TextBox x:Name="tbName" Height="23" Validation.ErrorTemplate="{StaticResource validationTemplate}" Style="{StaticResource textBoxInError}" Margin="10,10,349,286">
            <TextBox.Text>
                <Binding Path="myName" Source="{StaticResource properties}"
                         UpdateSourceTrigger="PropertyChanged" >
                    <Binding.ValidationRules>
                        <local:MyCustomValidationRule Type="myName" ValidatesOnTargetUpdated="True" />
                    </Binding.ValidationRules>
                </Binding>
            </TextBox.Text>
        </TextBox>
        <Button x:Name="btnCreate" Content="Create" Width="58" Height="23" Margin="174,10,285,286" >
            <Button.Style>
                <Style TargetType="Button">
                    <Setter Property="IsEnabled" Value="False"/>
                    <Style.Triggers>
                        <MultiDataTrigger>
                            <MultiDataTrigger.Conditions>
                                <Condition Binding="{Binding Path=(Validation.HasError), ElementName=tbRepositoryName}" Value="False"/>
                            </MultiDataTrigger.Conditions>
                            <Setter Property="IsEnabled" Value="True"/>
                        </MultiDataTrigger>
                    </Style.Triggers>
                </Style>
            </Button.Style>
        </Button>
    </Grid>
</Window>
</code>```

Code behind:

ValidatiorClass:

```<code>using System.Globalization;
using System.Text.RegularExpressions;
using System.Windows.Controls;

namespace TestWpf
{
    class MyCustomValidationRule : ValidationRule
    {
        public string Type { get; set; }
        public override ValidationResult Validate(object p_value, CultureInfo p_cultureInfo)
        {
            switch (Type)
            {
                case "myName":
                    string a_strValue = p_value as string;
                    if (!string.IsNullOrEmpty(a_strValue))
                    {
                        Match a_match = Regex.Match((string)p_value, @"^[a-zA-Z\d]+$");
                        return a_match.Success ? new ValidationResult(true, "Name is valid!") : new ValidationResult(false, $"Input should be a Valid Name (a-z, A-Z, 0-9)");
                    }
                    return new ValidationResult(false, "Empty name!");
                default:
                    return new ValidationResult(false, $"UnkownValidation Parameter: " + Type);
            }
        }
    }
}
</code>```

Property bound to TextBox:

```<code>using System.ComponentModel;

namespace TestWpf
{
    class MyValidatorProperties : INotifyPropertyChanged
    {
        private string m_myName = "";

        public string myName
        {
            get
            {
                return m_myName;
            }
            set
            {
                if (m_myName != value)
                {
                    m_myName = value;
                    OnPropertyChanged("myName");
                }
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
        private void OnPropertyChanged(string info)
        {
            PropertyChanged?.Invoke(null, new PropertyChangedEventArgs(info));
        }
    }
}
</code>```

PS:
If you don't want to disable the Button and show a message instead you can replace the Button with:

```<code><Button x:Name="btnCreate" Content="Create" Width="58" Height="23" Click="btnCreate_Click" />
</code>```

And add the method:

```<code>private void btnCreate_Click(object sender, RoutedEventArgs e)
{
   if(System.Windows.Controls.Validation.GetHasError(tbName))
   {
      //Show Message
   }
}
</code>```

Body:
I have a window with a few text fields and an OK and Cancel button. When I click OK it needs to validate my fields and do stuff with them if they're valid and display an error message if they're not.

In my ViewModel I've got

public ICommand OKCommand { get; private set; }
public Action ErrorAction { get; set; }

OKCommand = new BaseCommand(_ =>
{
    if (string.IsNullOrEmpty(ErrorMessage))
    {
        // Do stuff with the contents of the fields
        ...
    }
    else ErrorAction();
});

public string ErrorMessage
{
    get
    {
        // Gets the error message for the fields
        ...
    }
}

And in my code behind I've got

if (ViewModel.ErrorAction == null) ViewModel.ErrorAction = new Action(() => MessageDialog.ShowError(ViewModel.ErrorMessage));

My issue is ErrorMessage is called twice when there's an error, first in the OKCommand and again by ErrorAction.

The only solutions I can think of are

Accept the second call - it's not the end of the world.

Determine whether there is an error in OKCommand and set ErrorMessage if appropriate

Something like this

private bool HasError
{
    get
    {
        // Do the same as ErrorMessage but populate ErrorMessage and return a bool
        ...
    }
}

OKCommand = new BaseCommand(_ =>
{
    if (!HasError)
    {
        // Do stuff with the contents of the fields
        ...
    }
    else ErrorAction();
});

While both work I don't think either is great - the first has a second call and the second adds a level of indirection. Are there any alternatives?

Body:
There is a simple way to validate a TextBox Text:

it's called ValidationRule

You can directly see  that there is an error(Error in MouseOverMessage) and the Button is disabled

<Window x:Class="TestWpf.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:TestWpf"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <local:MyValidatorProperties x:Key="properties"/>
        <local:MyCustomValidationRule x:Key="validator" />
        <Style x:Key="textBoxInError" TargetType="{x:Type TextBox}">
            <Style.Triggers>
                <Trigger Property="Validation.HasError" Value="true">
                    <Setter Property="BorderBrush" Value="Red"/>
                    <Setter Property="BorderThickness" Value="2" />
                    <Setter Property="ToolTip"
                         Value="{Binding RelativeSource={x:Static RelativeSource.Self},
                        Path=(Validation.Errors)[0].ErrorContent}"/>
                </Trigger>
            </Style.Triggers>
        </Style>
        <ControlTemplate x:Key="validationTemplate">
            <DockPanel>
                <TextBlock Foreground="Red" FontSize="17">!</TextBlock>
                <AdornedElementPlaceholder/>
            </DockPanel>
        </ControlTemplate>
    </Window.Resources>
    <Grid>
        <TextBox x:Name="tbName" Height="23" Validation.ErrorTemplate="{StaticResource validationTemplate}" Style="{StaticResource textBoxInError}" Margin="10,10,349,286">
            <TextBox.Text>
                <Binding Path="myName" Source="{StaticResource properties}"
                         UpdateSourceTrigger="PropertyChanged" >
                    <Binding.ValidationRules>
                        <local:MyCustomValidationRule Type="myName" ValidatesOnTargetUpdated="True" />
                    </Binding.ValidationRules>
                </Binding>
            </TextBox.Text>
        </TextBox>
        <Button x:Name="btnCreate" Content="Create" Width="58" Height="23" Margin="174,10,285,286" >
            <Button.Style>
                <Style TargetType="Button">
                    <Setter Property="IsEnabled" Value="False"/>
                    <Style.Triggers>
                        <MultiDataTrigger>
                            <MultiDataTrigger.Conditions>
                                <Condition Binding="{Binding Path=(Validation.HasError), ElementName=tbRepositoryName}" Value="False"/>
                            </MultiDataTrigger.Conditions>
                            <Setter Property="IsEnabled" Value="True"/>
                        </MultiDataTrigger>
                    </Style.Triggers>
                </Style>
            </Button.Style>
        </Button>
    </Grid>
</Window>

Code behind:

ValidatiorClass:

using System.Globalization;
using System.Text.RegularExpressions;
using System.Windows.Controls;

namespace TestWpf
{
    class MyCustomValidationRule : ValidationRule
    {
        public string Type { get; set; }
        public override ValidationResult Validate(object p_value, CultureInfo p_cultureInfo)
        {
            switch (Type)
            {
                case "myName":
                    string a_strValue = p_value as string;
                    if (!string.IsNullOrEmpty(a_strValue))
                    {
                        Match a_match = Regex.Match((string)p_value, @"^[a-zA-Z\d]+$");
                        return a_match.Success ? new ValidationResult(true, "Name is valid!") : new ValidationResult(false, $"Input should be a Valid Name (a-z, A-Z, 0-9)");
                    }
                    return new ValidationResult(false, "Empty name!");
                default:
                    return new ValidationResult(false, $"UnkownValidation Parameter: " + Type);
            }
        }
    }
}

Property bound to TextBox:

using System.ComponentModel;

namespace TestWpf
{
    class MyValidatorProperties : INotifyPropertyChanged
    {
        private string m_myName = "";

        public string myName
        {
            get
            {
                return m_myName;
            }
            set
            {
                if (m_myName != value)
                {
                    m_myName = value;
                    OnPropertyChanged("myName");
                }
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
        private void OnPropertyChanged(string info)
        {
            PropertyChanged?.Invoke(null, new PropertyChangedEventArgs(info));
        }
    }
}

PS:
If you don't want to disable the Button and show a message instead you can replace the Button with:

<Button x:Name="btnCreate" Content="Create" Width="58" Height="23" Click="btnCreate_Click" />

And add the method:

private void btnCreate_Click(object sender, RoutedEventArgs e)
{
   if(System.Windows.Controls.Validation.GetHasError(tbName))
   {
      //Show Message
   }
}


问:
Include path relative to props file in visual studio
I'm trying to create property file with include path to use in all my c++ project.

Here is repository structure.

```<code>/
    /Libs
        /Libs2
            A.h
         B.h
    /Sln1
        Sln1.sln
        Proj1.vcxproj
    Sln2.sln
    Proj2.vcxproj
    Props.props
</code>```

I want use property file (Props.props) to add the following include path to both projects ( C:\\Libs;C:\\Libs\Libs2).

Currently I have macro in my property file:

```<code>Name          Value
ProjRoot      C:\<path to rep root>
</code>```

And I use it in include string: $(ProjRoot)\Libs;$(ProjRoot)\Libs\Libs2

The problem with this solution is hardcoded absolute path in macro value. If my repository will be cloned on another drive I will have to change it manually.

Can I use path relative to property file in macro value?

I.e.:

```<code>Name          Value
ProjRoot      ./
</code>```

Where ./ will resolve to path of Props.props file in all projects which will use this property file.

I cannot use $(SolutionDir) and $(ProjectDir) because there are may solutions and projects in different nesting level so path relative to them would not work.

Thank you.

答:
Do do this one should manually edit props file and include the following:

```<code><PropSheetPath>$([System.IO.Path]::GetFullPath('$(MSBuildThisFileDirectory)'))</PropSheetPath>
</code>```

This will create property PropSheetPath with property file folder.

Found the answer here:

https://social.msdn.microsoft.com/Forums/vstudio/en-US/2817cae7-3a71-4701-839a-9bf47af7c498/property-sheets-macro-to-reference-location-of-property-sheet?forum=vcgeneral

Body:
I'm trying to create property file with include path to use in all my c++ project.

Here is repository structure.

/
    /Libs
        /Libs2
            A.h
         B.h
    /Sln1
        Sln1.sln
        Proj1.vcxproj
    Sln2.sln
    Proj2.vcxproj
    Props.props

I want use property file (Props.props) to add the following include path to both projects ( C:\\Libs;C:\\Libs\Libs2).

Currently I have macro in my property file:

Name          Value
ProjRoot      C:\<path to rep root>

And I use it in include string: $(ProjRoot)\Libs;$(ProjRoot)\Libs\Libs2

The problem with this solution is hardcoded absolute path in macro value. If my repository will be cloned on another drive I will have to change it manually.

Can I use path relative to property file in macro value?

I.e.:

Name          Value
ProjRoot      ./

Where ./ will resolve to path of Props.props file in all projects which will use this property file.

I cannot use $(SolutionDir) and $(ProjectDir) because there are may solutions and projects in different nesting level so path relative to them would not work.

Thank you.

Body:
Do do this one should manually edit props file and include the following:

<PropSheetPath>$([System.IO.Path]::GetFullPath('$(MSBuildThisFileDirectory)'))</PropSheetPath>

This will create property PropSheetPath with property file folder.

Found the answer here:

https://social.msdn.microsoft.com/Forums/vstudio/en-US/2817cae7-3a71-4701-839a-9bf47af7c498/property-sheets-macro-to-reference-location-of-property-sheet?forum=vcgeneral


问:
Observable closes, in case of error. How to resolve it?
Please take a look at this expression:

```<code>Observable.interval(10000)
.switchMap(() => this.http.get(url))
.catch (err => Observable.empty())
.subscribe(data => render(data))
</code>```

Each 10 seconds we make an http call. If an error happens, observable closes, it doesn't make any calls anymore. How to prevent that?

答:
This is the expected behaviour.  According to the documentation,

In an Observable Execution, zero to infinite Next notifications may be
  delivered. If either an Error or Complete notification is delivered,
  then nothing else can be delivered afterwards.

Body:
Please take a look at this expression:

Observable.interval(10000)
.switchMap(() => this.http.get(url))
.catch (err => Observable.empty())
.subscribe(data => render(data))

Each 10 seconds we make an http call. If an error happens, observable closes, it doesn't make any calls anymore. How to prevent that?


问:
Scrolling DIV on static body scroll
I have a static body element and a DIV inside it, which height is 500px. It has overflow: visible and text longer than 500px. I want to scroll that DIV while I have mouse pointer over body (which doesn't have any scrollbars itself).

Any directions?

Pic related - the mouse pointer is outside of the DIV I want to scroll

答:
You may try it</p>

```<code>$(document).ready(function(){
   if ($('selector:hover').length != 0) {
    $(document).scrollTo('selector');
 }
});
</code>```

Title: Scrolling DIV on static body scroll

Body:
You may try it

$(document).ready(function(){
   if ($('selector:hover').length != 0) {
    $(document).scrollTo('selector');
 }
});


问:
jquery/javascript - hide div if containing image is broken
i have a div with the class 'userFeatureProductImage'. this div is repeated however occasionally a broken image might come through so i want to hide the div as a precaution if this does happen. how can i do this?</p>

答:
The load event is only fired if an image is valid:</p>

```<code>$('.userFeatureProductImage').hide();
$('.userFeatureProductImage img').load(function() {
  $(this).closest('.userFeatureProductImage').show();
});
</code>```

ContentLicense: CC BY-SA 2.5

Body:
The load event is only fired if an image is valid:

$('.userFeatureProductImage').hide();
$('.userFeatureProductImage img').load(function() {
  $(this).closest('.userFeatureProductImage').show();
});


问:
Unable to start MySQL from XAMPP Control Panel
I am learning SQL with Udemy courses and I am currently doing a course called 'Learning database design using MySQL'.

I have downloaded XAMPP and the course video start MySQL directly from the XAMPP control panel. I however am not able to start MySQL via the control panel. This is the message i get:

*

```<code>20:56:08  [mysql]   Attempting to start MySQL app...
20:56:09  [mysql]   Status change detected: running
20:56:12  [mysql]   Status change detected: stopped
20:56:12  [mysql]   Error: MySQL shutdown unexpectedly.
20:56:12  [mysql]   This may be due to a blocked port, missing dependencies,
20:56:12  [mysql]   improper privileges, a crash, or a shutdown by another method.
20:56:12  [mysql]   Press the Logs button to view error logs and check
20:56:12  [mysql]   the Windows Event Viewer for more clues
20:56:12  [mysql]   If you need more help, copy and post this
20:56:12  [mysql]   entire log window on the forums
20:56:29  [mysql]   Problem detected!
20:56:29  [mysql]   Port 3306 in use by ""C:\Program Files\MySQL\MySQL Server 5.7\bin\mysqld.exe" --defaults-file="C:\ProgramData\MySQL\MySQL Server 5.7\my.ini" MySQL57"!
20:56:29  [mysql]   MySQL WILL NOT start without the configured ports free!
20:56:29  [mysql]   You need to uninstall/disable/reconfigure the blocking application
20:56:29  [mysql]   or reconfigure MySQL and the Control Panel to listen on a different port
20:56:29  [mysql]   Attempting to start MySQL app...
20:56:30  [mysql]   Status change detected: running
20:56:33  [mysql]   Status change detected: stopped
20:56:33  [mysql]   Error: MySQL shutdown unexpectedly.
20:56:33  [mysql]   This may be due to a blocked port, missing dependencies,
20:56:33  [mysql]   improper privileges, a crash, or a shutdown by another method.
20:56:33  [mysql]   Press the Logs button to view error logs and check
20:56:33  [mysql]   the Windows Event Viewer for more clues
20:56:33  [mysql]   If you need more help, copy and post this
20:56:33  [mysql]   entire log window on the forums
</code>```

*

I have logs that i can add if required. Also, i have downloaded sql community edition already and have used the command line functionality, however it is not running when trying to launch via the control panel.

I really want to learn so would really appreciate anyone who can help me overcome this issue.

Thanks
Graham

答: First you should install MySQL separately. Then go to the folder where you have installed xampp (default is c:). Go to phpMyAdim folder you will see config.inc.php file ,open it with any editor and put your MySQL password. Hopefully that'll work (by default its blank). </p>

Body:
I am learning SQL with Udemy courses and I am currently doing a course called 'Learning database design using MySQL'.

I have downloaded XAMPP and the course video start MySQL directly from the XAMPP control panel. I however am not able to start MySQL via the control panel. This is the message i get:

*

20:56:08  [mysql]   Attempting to start MySQL app...
20:56:09  [mysql]   Status change detected: running
20:56:12  [mysql]   Status change detected: stopped
20:56:12  [mysql]   Error: MySQL shutdown unexpectedly.
20:56:12  [mysql]   This may be due to a blocked port, missing dependencies,
20:56:12  [mysql]   improper privileges, a crash, or a shutdown by another method.
20:56:12  [mysql]   Press the Logs button to view error logs and check
20:56:12  [mysql]   the Windows Event Viewer for more clues
20:56:12  [mysql]   If you need more help, copy and post this
20:56:12  [mysql]   entire log window on the forums
20:56:29  [mysql]   Problem detected!
20:56:29  [mysql]   Port 3306 in use by ""C:\Program Files\MySQL\MySQL Server 5.7\bin\mysqld.exe" --defaults-file="C:\ProgramData\MySQL\MySQL Server 5.7\my.ini" MySQL57"!
20:56:29  [mysql]   MySQL WILL NOT start without the configured ports free!
20:56:29  [mysql]   You need to uninstall/disable/reconfigure the blocking application
20:56:29  [mysql]   or reconfigure MySQL and the Control Panel to listen on a different port
20:56:29  [mysql]   Attempting to start MySQL app...
20:56:30  [mysql]   Status change detected: running
20:56:33  [mysql]   Status change detected: stopped
20:56:33  [mysql]   Error: MySQL shutdown unexpectedly.
20:56:33  [mysql]   This may be due to a blocked port, missing dependencies,
20:56:33  [mysql]   improper privileges, a crash, or a shutdown by another method.
20:56:33  [mysql]   Press the Logs button to view error logs and check
20:56:33  [mysql]   the Windows Event Viewer for more clues
20:56:33  [mysql]   If you need more help, copy and post this
20:56:33  [mysql]   entire log window on the forums

*

I have logs that i can add if required. Also, i have downloaded sql community edition already and have used the command line functionality, however it is not running when trying to launch via the control panel.

I really want to learn so would really appreciate anyone who can help me overcome this issue.

Thanks
Graham


问:
Dynamic initialisation of 3D array c++
I have a 3-dimensional space X-Y-Z discretised into cells. Each cell has a certain density value associated with it. I want to be able to store the density values in a 3-D array so that I can recall them by index i.e.

density_ijk = x[i][j][k];

I have the following class definition:

```<code>class A {
public:
    A(int a, int b, int c);

private:
    double ***x;
}

A::A(int a, int b, int c){
   x = new double**[a];
   for(int i=0;i<a;i++){
        x[i] = new double*[b];
        for(int j=0;j<b;j++){
            x[i][j] = new double[c];
        }
    }
}
</code>```

It builds successfully, however at runtime EXC_BAD_ACCESS(code=1, address=0x0) is generated.

Is there a dangling pointer somewhere in my code? What could I be doing wrong?

My main is:

```<code>int main(int argc, const char * argv[]) {

    int numX=100, numY=100, numZ=10;

    A testImplementation(numX, numY, numZ);

    return 0;
}
</code>```

Source 1: https://www.codeproject.com/Articles/83080/Dynamic-Three-Dimensional-Arrays-in-C-C-C-Java
Source 2: http://www.cplusplus.com/forum/general/24347/

Thanks!

答:
Don't use owning raw pointers

```<code>class A {
public:
    A(std::size_t a, std::size_t b, std::size_t c);

private:
    std::vector<std::vector<std::vector<double>>> x;
}

A::A(std::size_t a, std::size_t b, std::size_t c)
  : x(a, std::vector<std::vector<double>>(b, std::vector<double>(c, 0.))) {}
</code>```

If you want to fiddle with a, b and c first, write a method to do that.

```<code>class A {
public:
    A(std::size_t a, std::size_t b, std::size_t c);

private:
    std::vector<std::vector<std::vector<double>>> x;
    std::vector<std::vector<std::vector<double>>> fiddle_input(std::size_t a, std::size_t b, std::size_t c);
}

A::A(std::size_t a, std::size_t b, std::size_t c) : x(fiddle_input(a, b, c)) {}

std::vector<std::vector<std::vector<double>>> A::fiddle_input(std::size_t a, std::size_t b, std::size_t c) {
    /*Some implementation*/
    return {new_a, {new_b, {new_c, 0.}}};
}
</code>```

The compiler is allowed (and post c++17 required) to only construct one 3d vector with this return by value.

Title: Dynamic initialisation of 3D array c++

Body:
I have a 3-dimensional space X-Y-Z discretised into cells. Each cell has a certain density value associated with it. I want to be able to store the density values in a 3-D array so that I can recall them by index i.e.

density_ijk = x[i][j][k];

I have the following class definition:

class A {
public:
    A(int a, int b, int c);

private:
    double ***x;
}

A::A(int a, int b, int c){
   x = new double**[a];
   for(int i=0;i<a;i++){
        x[i] = new double*[b];
        for(int j=0;j<b;j++){
            x[i][j] = new double[c];
        }
    }
}

It builds successfully, however at runtime EXC_BAD_ACCESS(code=1, address=0x0) is generated.

Is there a dangling pointer somewhere in my code? What could I be doing wrong?

My main is:

int main(int argc, const char * argv[]) {

    int numX=100, numY=100, numZ=10;

    A testImplementation(numX, numY, numZ);

    return 0;
}

Source 1: https://www.codeproject.com/Articles/83080/Dynamic-Three-Dimensional-Arrays-in-C-C-C-Java
Source 2: http://www.cplusplus.com/forum/general/24347/

Thanks!

Body:
Don't use owning raw pointers

class A {
public:
    A(std::size_t a, std::size_t b, std::size_t c);

private:
    std::vector<std::vector<std::vector<double>>> x;
}

A::A(std::size_t a, std::size_t b, std::size_t c)
  : x(a, std::vector<std::vector<double>>(b, std::vector<double>(c, 0.))) {}

If you want to fiddle with a, b and c first, write a method to do that.

class A {
public:
    A(std::size_t a, std::size_t b, std::size_t c);

private:
    std::vector<std::vector<std::vector<double>>> x;
    std::vector<std::vector<std::vector<double>>> fiddle_input(std::size_t a, std::size_t b, std::size_t c);
}

A::A(std::size_t a, std::size_t b, std::size_t c) : x(fiddle_input(a, b, c)) {}

std::vector<std::vector<std::vector<double>>> A::fiddle_input(std::size_t a, std::size_t b, std::size_t c) {
    /*Some implementation*/
    return {new_a, {new_b, {new_c, 0.}}};
}

The compiler is allowed (and post c++17 required) to only construct one 3d vector with this return by value.


问:
How to consider following and previous rows of each observation in R
I need to create 2 columns: PRETARGET and TARGET based on several conditions.

To create PRETARGET, for each row of my data (for each participant PPT and trial TRIAL) I need to check that the CURRENT_ID is associated with a value of 0 in the column CanBePretarget, and that the following row is the value of CURRENT_ID + 1. If these conditions are fulfil, then I would like to have a value of 0, if they are not fulfil a value of 1.

To create TARGET, for each row of my data (for each participant PPT and trial TRIAL) I need to check that the CURRENT_ID is associated with a value of 0 in the column CanBeTarget, and that the previous row is the value of CURRENT_ID - 1. If these conditions are fulfil, then I would like to have a value of 0, if they are not fulfil a value of 1.

In addition, if the result in PRETARGET is 1, then the value of the next row in TARGET should also be 1.

I have added the desired output in the following example.

I was thinking to use for loops and ifelse statements, but I am not sure how to consider the following/previous row of each observation.

```<code>PPT   TRIAL PREVIOUS_ID CURRENT_ID  NEXT_ID CURRENT_INDEX CanBePretarget CanBeTarget    PRETARGET   TARGET
ppt01 11    2           3           4       3             0              0              0           1
ppt01 11    3           4           3       4             1              0              1           0
ppt01 11    4           5           6       8             0              0              1           1
ppt01 11    6           7           8       10            0              0              1           1
ppt01 11    7           10          11      18            0              1              0           1
ppt01 11    10          11          12      19            0              0              0           0
ppt01 11    11          12          14      20            1              0              1           0
ppt01 12    1           2           1       2             1              0              1           1
ppt01 12    2           3           4       5             0              0              1           1
ppt01 12    5           6           6       8             0              0              0           1
ppt01 12    6           7           7       10            0              0              0           0
ppt01 12    7           8           9       12            0              0              0           0
ppt01 12    8           9           9       13            0              0              0           0
ppt01 12    9           10          11      16            0              0              0           0
ppt01 12    10          11          11      17            0              0              0           0
ppt01 13    1           2           2       2             1              0              1           1
ppt01 13    3           3           3       10            0              0              1           1
ppt01 13    4           5           6       13            0              0              0           1
ppt01 13    5           6           7       14            0              0              1           0
ppt01 13    9           9           10      19            0              0              0           1
ppt01 13    9           10          10      20            0              0              0           0
ppt01 13    10          11          12      22            0              0              0           0
ppt01 13    11          12          12      23            0              0              1           0
ppt01 14    10          11          11      15            0              0              0           1
ppt01 14    11          12          12      17            0              0              1           0
</code>```

答:
This can be achieved by using dplyr

```<code>df.new <- df %>%
          mutate(PRETARGET1 = abs(as.numeric(CanBePretarget == 0 & lead(CURRENT_ID, default = 0) == (CURRENT_ID + 1)) - 1)) %>%
          group_by(PPT, TRIAL) %>%
          mutate(TARGET1 = abs(as.numeric((CanBeTarget == 0 & lag(CURRENT_ID, default = 0) == (CURRENT_ID - 1)) ) -1),
                 TARGET1 = ifelse(lag(PRETARGET1, default = 0) == 1, 1, TARGET1))
</code>```

To compare to your results, I created PRETARGET1 and TARGET1.

Body:
I need to create 2 columns: PRETARGET and TARGET based on several conditions.

To create PRETARGET, for each row of my data (for each participant PPT and trial TRIAL) I need to check that the CURRENT_ID is associated with a value of 0 in the column CanBePretarget, and that the following row is the value of CURRENT_ID + 1. If these conditions are fulfil, then I would like to have a value of 0, if they are not fulfil a value of 1.

To create TARGET, for each row of my data (for each participant PPT and trial TRIAL) I need to check that the CURRENT_ID is associated with a value of 0 in the column CanBeTarget, and that the previous row is the value of CURRENT_ID - 1. If these conditions are fulfil, then I would like to have a value of 0, if they are not fulfil a value of 1.

In addition, if the result in PRETARGET is 1, then the value of the next row in TARGET should also be 1.

I have added the desired output in the following example.

I was thinking to use for loops and ifelse statements, but I am not sure how to consider the following/previous row of each observation.

PPT   TRIAL PREVIOUS_ID CURRENT_ID  NEXT_ID CURRENT_INDEX CanBePretarget CanBeTarget    PRETARGET   TARGET
ppt01 11    2           3           4       3             0              0              0           1
ppt01 11    3           4           3       4             1              0              1           0
ppt01 11    4           5           6       8             0              0              1           1
ppt01 11    6           7           8       10            0              0              1           1
ppt01 11    7           10          11      18            0              1              0           1
ppt01 11    10          11          12      19            0              0              0           0
ppt01 11    11          12          14      20            1              0              1           0
ppt01 12    1           2           1       2             1              0              1           1
ppt01 12    2           3           4       5             0              0              1           1
ppt01 12    5           6           6       8             0              0              0           1
ppt01 12    6           7           7       10            0              0              0           0
ppt01 12    7           8           9       12            0              0              0           0
ppt01 12    8           9           9       13            0              0              0           0
ppt01 12    9           10          11      16            0              0              0           0
ppt01 12    10          11          11      17            0              0              0           0
ppt01 13    1           2           2       2             1              0              1           1
ppt01 13    3           3           3       10            0              0              1           1
ppt01 13    4           5           6       13            0              0              0           1
ppt01 13    5           6           7       14            0              0              1           0
ppt01 13    9           9           10      19            0              0              0           1
ppt01 13    9           10          10      20            0              0              0           0
ppt01 13    10          11          12      22            0              0              0           0
ppt01 13    11          12          12      23            0              0              1           0
ppt01 14    10          11          11      15            0              0              0           1
ppt01 14    11          12          12      17            0              0              1           0

Body:
This can be achieved by using dplyr

df.new <- df %>%
          mutate(PRETARGET1 = abs(as.numeric(CanBePretarget == 0 & lead(CURRENT_ID, default = 0) == (CURRENT_ID + 1)) - 1)) %>%
          group_by(PPT, TRIAL) %>%
          mutate(TARGET1 = abs(as.numeric((CanBeTarget == 0 & lag(CURRENT_ID, default = 0) == (CURRENT_ID - 1)) ) -1),
                 TARGET1 = ifelse(lag(PRETARGET1, default = 0) == 1, 1, TARGET1))

To compare to your results, I created PRETARGET1 and TARGET1.


问:
Check if a number is prime?
I'm trying to make an app that checks whether a number is prime or not.

Can someone help me to check the number?

I need a simple answer, not incredibly advanced algorithms. I'm new to programming.

答:
I cannot reply because of reputation I have, but I find Wayne Ellery's method is brilliant. However just a little fix if it's possible..

```<code>// that's Swift 3.1
import Foundation

func isPrime(_ number: Int) -> Bool {
    // right below
    if number == 2 || number == 3 { return true }
    let maxDivider = Int(sqrt(Double(number)))
    return number > 1 && !(2...maxDivider).contains { number % $0 == 0 }
}
</code>```

All dividers of integer number with value more than sqrt(number) aren't necessary.

Title: Check if a number is prime?

Body:
I cannot reply because of reputation I have, but I find Wayne Ellery's method is brilliant. However just a little fix if it's possible..

// that's Swift 3.1
import Foundation

func isPrime(_ number: Int) -> Bool {
    // right below
    if number == 2 || number == 3 { return true }
    let maxDivider = Int(sqrt(Double(number)))
    return number > 1 && !(2...maxDivider).contains { number % $0 == 0 }
}

All dividers of integer number with value more than sqrt(number) aren't necessary.


问:
Ansible: Changing permissions of files but not of directory
I need to set the permissions of the files under a directory but I don't want to change the permission of the directory.

I tried this:

```<code>- name: chmod 444
  file: /dir recurse=yes state=directory owner=abc group=abc mode=0444
</code>```

But it will modify the directory permission also. Is it possible?

答:
Not in one task.

You need first to find files and then execute the file module with the appropriate settings against the list.

```<code>- find:
    path: /dir
    file_type: file
    recurse: yes
  register: find_result

- file:
    path: "{{ item.path }}"
    owner: abc
    group: abc
    mode: 0444
  with_items: "{{ find_result.files }}"
</code>```

Body:
I need to set the permissions of the files under a directory but I don't want to change the permission of the directory.

I tried this:

- name: chmod 444
  file: /dir recurse=yes state=directory owner=abc group=abc mode=0444

But it will modify the directory permission also. Is it possible?

Body:
Not in one task.

You need first to find files and then execute the file module with the appropriate settings against the list.

- find:
    path: /dir
    file_type: file
    recurse: yes
  register: find_result

- file:
    path: "{{ item.path }}"
    owner: abc
    group: abc
    mode: 0444
  with_items: "{{ find_result.files }}"


问:
Zooming beyond 13 throws resolution error in ArcGis JS API
I have a very basic example for a map:
(JsFiddle)

```<code>require(["esri/map"],
    function(Map) {
        var baseMap = new Map("map", {
            basemap: "terrain",
            center: [10, 51],
            zoom: 12,
            maxZoom: 22
        });
    });
</code>```

When I exceed a certain zoom level I am receiving the following error:

```<code>init.js:587 Uncaught TypeError: Cannot read property 'resolution' of undefined
at Object.__getExtentForLevel (init.js:587)
at Object._extentUtil (init.js:579)
at Object._wheelZoom (init.js:1254)
at Object.<anonymous> (init.js:63)
at Object.c [as onMouseWheel] (init.js:119)
at Object._fire (init.js:1279)
at Object._onMouseWheelHandler (init.js:1286)
at HTMLDivElement.<anonymous> (init.js:63)
</code>```

A couple of other applications hosted internally using the same code (but based on 3.13) are able to zoom in until one can see all street names and house numbers.

What is causing these errors?

答:
It looks like the "terrain" basemaps' resolution is not as high as one could wish for as an end user and ESRI forgot to limit the zooming capability on that basemap.

Switching to osm, topo or streets resolves the issue.

The solution is to change basemap: "terrain", to basemap: "topo",.

Body:
I have a very basic example for a map:
(JsFiddle)

require(["esri/map"],
    function(Map) {
        var baseMap = new Map("map", {
            basemap: "terrain",
            center: [10, 51],
            zoom: 12,
            maxZoom: 22
        });
    });

When I exceed a certain zoom level I am receiving the following error:

init.js:587 Uncaught TypeError: Cannot read property 'resolution' of undefined
at Object.__getExtentForLevel (init.js:587)
at Object._extentUtil (init.js:579)
at Object._wheelZoom (init.js:1254)
at Object.<anonymous> (init.js:63)
at Object.c [as onMouseWheel] (init.js:119)
at Object._fire (init.js:1279)
at Object._onMouseWheelHandler (init.js:1286)
at HTMLDivElement.<anonymous> (init.js:63)

A couple of other applications hosted internally using the same code (but based on 3.13) are able to zoom in until one can see all street names and house numbers.

What is causing these errors?


答:
You could try

options = document.getElementById("selectID").outerHTML;
 copyEL.push(options);

This will include the HTML for the select menu, so you don't need to append that. It will also include the options, with HTML.

Title: push cloned <option> into array

Body:
The Code as follows

var options = $("#select> option").clone();

$('#btn').on('click',function(e){

       e.preventDefault();
       var copyEl = [];
       copyEl.push("<select id='select"+i+"'class='select form-control'>");
       options.each(function(){
                console.log(this);
                copyEl.push(this);
            });

      copyEl.push("</select>");

      copyEl = $(copyEl.join(''));

      $('#div').after(copyEl.clone());

});

this is what i do find when inspect the element

[object HTMLOptionElement][object HTMLOptionElement][object HTMLOptionElement][object HTMLOptionElement][object HTMLOptionElement][object HTMLOptionElement][object HTMLOptionElement][object HTMLOptionElement][object HTMLOptionElement][object HTMLOptionElement][object HTMLOptionElement][object HTMLOptionElement][object HTMLOptionElement][object HTMLOptionElement][object HTMLOptionElement][object HTMLOptionElement][object HTMLOptionElement][object HTMLOptionElement][object HTMLOptionElement][object HTMLOptionElement]

the console print

<option id='1'>Toy</option>
<option id='2'>Story</option>

which is result that i do need to push in the array , this code was working fine with the <datalist> but is not working with <select> any way to add the
to the array ?


问:
Transforming data in Django. Want to be able to apply sums to a decimal field
I have a model like this.

```<code>#models.py
class Payment(models.Model):
    unit_price = models.DecimalField(max_digits=12, decimal_places=2)
    discount = models.DecimalField(max_digits=12, decimal_places=2)
    payment_terms = models.CharField(max_length=80)
    amount = models.DecimalField(max_digits=12, decimal_places=2)
    VAT = models.DecimalField(max_digits=4, decimal_places=2)

    def __unicode__(self):
        return unicode(self.unit_price)

class Invoice(models.Model):
    client = models.ForeignKey(Client)
    payment = models.ForeignKey(Payment)
    date = models.DateField()
    invoice_no = models.CharField(max_length=16)
    work_orders = models.ManyToManyField(Work_Order)
    contract_info = models.ForeignKey(Contract_Info)

    def __unicode__(self):
                return self.invoice_no
</code>```

What I want to focus is payment so try forgetting everything else. Here is my views.py.

```<code>#views.py
@login_required
def invoice_details(request, id=1):
    invoices_list = Invoice.objects.filter(pk=id)
    invoice = get_object_or_404(Invoice, pk=id)
    client = invoices_list[0].client
    work_orders = invoices_list[0].work_orders
    payment = invoices_list[0].payment

    return render_to_response(('invoice_details.html', locals()), {'work_orders': work_orders,'payment':payment,'client': client, 'invoice': invoice ,'invoices_list': invoices_list}, context_instance=RequestContext(request))
</code>```

And here is my template.

```<code><h1>invoice_details.html<h1>
{{ payment.amount }}
</code>```

The template displays the payment amount in a decimal value. What I want to be able to do is some sums with  {{payment.amount}}. Suppose if I wanted to multiply whatever the value

{{payment.amount}} by let say 2. How would I do this?

答:
Here is the answer:

```<code>#views.py
subtotal = payment.amount * 2
return render_to_response(('invoice_details.html', locals()), {'work_orders': work_orders,'payment':payment,'client': client, 'invoice': invoice ,'invoices_list': invoices_list, 'subtotal':subtotal}, context_instance=RequestContext(request))
</code>```

In a template put this custom tag (I think that what it is) to represent the value.

```<code>{{ subtotal }}
</code>```

Body:
I have a model like this.

#models.py
class Payment(models.Model):
    unit_price = models.DecimalField(max_digits=12, decimal_places=2)
    discount = models.DecimalField(max_digits=12, decimal_places=2)
    payment_terms = models.CharField(max_length=80)
    amount = models.DecimalField(max_digits=12, decimal_places=2)
    VAT = models.DecimalField(max_digits=4, decimal_places=2)

    def __unicode__(self):
        return unicode(self.unit_price)

class Invoice(models.Model):
    client = models.ForeignKey(Client)
    payment = models.ForeignKey(Payment)
    date = models.DateField()
    invoice_no = models.CharField(max_length=16)
    work_orders = models.ManyToManyField(Work_Order)
    contract_info = models.ForeignKey(Contract_Info)

    def __unicode__(self):
                return self.invoice_no

What I want to focus is payment so try forgetting everything else. Here is my views.py.

#views.py
@login_required
def invoice_details(request, id=1):
    invoices_list = Invoice.objects.filter(pk=id)
    invoice = get_object_or_404(Invoice, pk=id)
    client = invoices_list[0].client
    work_orders = invoices_list[0].work_orders
    payment = invoices_list[0].payment

    return render_to_response(('invoice_details.html', locals()), {'work_orders': work_orders,'payment':payment,'client': client, 'invoice': invoice ,'invoices_list': invoices_list}, context_instance=RequestContext(request))

And here is my template.

invoice_details.html

{{ payment.amount }}

The template displays the payment amount in a decimal value. What I want to be able to do is some sums with  {{payment.amount}}. Suppose if I wanted to multiply whatever the value

{{payment.amount}} by let say 2. How would I do this?

Body:
Here is the answer:

#views.py
subtotal = payment.amount * 2
return render_to_response(('invoice_details.html', locals()), {'work_orders': work_orders,'payment':payment,'client': client, 'invoice': invoice ,'invoices_list': invoices_list, 'subtotal':subtotal}, context_instance=RequestContext(request))

In a template put this custom tag (I think that what it is) to represent the value.

{{ subtotal }}


问:
XQuery error XPST0003 syntax error
I want to query a site and generate HTML. I am new to XQuery.
I am using eXide from eXist-db. I tried to use oXygen but keep having troubles with the eXist-db.
Besides that I don't understand why this code does not work in eXide:

```<code>xquery version "3.0";
import module namespace http =  "http://exist-db.org/xquery/httpclient";
import module namespace util =  "http://exist-db.org/xquery/util";

declare option exist:serialize "method=xhtml  media-type=text/html";

let $spreadsheet-url := 'https://docs.google.com/spreadsheets/d/1rNHWMonN4RSnvxMYpkqeGHG_bBz-WpxCI-2_Wc/gviz/ tq?tqx=out:json'

let $spreadsheet-response := http:get(xs:anyURI($spreadsheet-url), true(),  <Headers/>)

let $body :=  util:base64-decode($spreadsheet-response/httpclient:body/text())

let $x :=  parse-json(substring-before(substring-after($body,'('),');'))

let $odk-server:="http//192.168.0.104"

let $amp:="&"

let $gmap-api-key:="AIzaSyCYC9h9pMGGvREo................"

return
    <html>
        <head>
            <title>Results</title>
        </head>
        <body>
            <table>
                <tr>
                    <th>Mapa</th>
                    <th>Detalhes</th>
                </tr>
                {
                    for $data in $x?table?rows?*
                        let $latitude := $data?c(11)?v
                        let $longitude := $data?c(12)?v
                        let $map-url := concat("https://maps.googleapis.com/api/staticmap?center=",$latitude,",", $longitude, $amp, "zoom=18", $amp, "size=400x400", $amp, "markers=color:blue|", $latitude,",",$longitude, $amp,"key=",$gmap-api-key)

                        let $name:= $data?c(8)?v
                        let $age:=$data=?c(9)?v
                        let $date:=$data?c(10)?f
                        let $image:= replace($data?c(15)?v,"http://aggregate.defaultdomain", $odk-server)
                        return
                            <tr>
                                <td><img src='{$map-url}' alt="map"/></td>
                                <td>
                                    <img src='{$image}' height="200" width="200" alt="imagem"/>
                                <p>{$name}</p><p>{$age}</p><p>{$date}</p>
                                </td>
                                <td>
                                </td>
                            </tr>

                }

            </table>

        </body>
    </html>
</code>```

It gives me an error in line 34 saying it was expected
 and found *,

答:
There is a typo at the end of the following line, namely a missing comma between the variable and the string in $amp"key=".

```<code>let $map-url := concat("https://maps.googleapis.com/api/staticmap?center=",$latitude,",",
        $longitude, $amp, "zoom=18", $amp, "size=400x400", $amp, "markers=color:blue|",
        $latitude,",",$longitude, $amp"key=",$gmap-api-key)
</code>```

Everything else seems to be syntactically correct.

If eXide does not support the syntax $array?* for getting all entries of an array, you can try rewriting it from

```<code>for $data in $x?table?rows?*
[...]
</code>```

to

```<code>let $rows := $x?table?rows
for $i in 1 to array:size($rows)
let $data := $rows($i)
[...]
</code>```

Title: XQuery error XPST0003 syntax error

Body:
I want to query a site and generate HTML. I am new to XQuery.
I am using eXide from eXist-db. I tried to use oXygen but keep having troubles with the eXist-db.
Besides that I don't understand why this code does not work in eXide:

xquery version "3.0";
import module namespace http =  "http://exist-db.org/xquery/httpclient";
import module namespace util =  "http://exist-db.org/xquery/util";

declare option exist:serialize "method=xhtml  media-type=text/html";

let $spreadsheet-url := 'https://docs.google.com/spreadsheets/d/1rNHWMonN4RSnvxMYpkqeGHG_bBz-WpxCI-2_Wc/gviz/ tq?tqx=out:json'

let $spreadsheet-response := http:get(xs:anyURI($spreadsheet-url), true(),  <Headers/>)

let $body :=  util:base64-decode($spreadsheet-response/httpclient:body/text())

let $x :=  parse-json(substring-before(substring-after($body,'('),');'))

let $odk-server:="http//192.168.0.104"

let $amp:="&"

let $gmap-api-key:="AIzaSyCYC9h9pMGGvREo................"

return

            <title>Results</title>

                    Mapa
                    Detalhes

                {
                    for $data in $x?table?rows?*
                        let $latitude := $data?c(11)?v
                        let $longitude := $data?c(12)?v
                        let $map-url := concat("https://maps.googleapis.com/api/staticmap?center=",$latitude,",", $longitude, $amp, "zoom=18", $amp, "size=400x400", $amp, "markers=color:blue|", $latitude,",",$longitude, $amp,"key=",$gmap-api-key)

                        let $name:= $data?c(8)?v
                        let $age:=$data=?c(9)?v
                        let $date:=$data?c(10)?f
                        let $image:= replace($data?c(15)?v,"http://aggregate.defaultdomain", $odk-server)
                        return

{$name}

{$age}

{$date}

                }

It gives me an error in line 34 saying it was expected
 and found *,

Body:
There is a typo at the end of the following line, namely a missing comma between the variable and the string in $amp"key=".

let $map-url := concat("https://maps.googleapis.com/api/staticmap?center=",$latitude,",",
        $longitude, $amp, "zoom=18", $amp, "size=400x400", $amp, "markers=color:blue|",
        $latitude,",",$longitude, $amp"key=",$gmap-api-key)

Everything else seems to be syntactically correct.

If eXide does not support the syntax $array?* for getting all entries of an array, you can try rewriting it from

for $data in $x?table?rows?*
[...]

to

let $rows := $x?table?rows
for $i in 1 to array:size($rows)
let $data := $rows($i)
[...]


问:
Android "Cannot resolve symbol" for setOnCheckedChangeListener and buttonView
I'm trying to create a switch which when enabled hides a button called button but it returns an error for SetOnCheckedChangeListener and buttonView which says Cannot resolve symbol

```<code>package com.jordthedev.firstapplication;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.ToggleButton;

public class MainActivity extends AppCompatActivity {
    int count = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    }

    public void switchActivity(View v){
        startActivity(new Intent(MainActivity.this, SecondActivity.class));
    }

    ToggleButton toggle = (ToggleButton) findViewById(R.id.toggleButton);
    toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                toggle.setVisibility(toggle.INVISIBLE);
            } else {
                toggle.setVisibility(toggle.VISIBLE);
            }
        }
    });

}
</code>```

答:
Maybe you have to place ToggleButton in onCreate() method try below code</p>

```<code>package com.jordthedev.firstapplication;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.ToggleButton;

public class MainActivity extends AppCompatActivity {
    int count = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final ToggleButton toggle = (ToggleButton) findViewById(R.id.toggleButton);
        toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    toggle.setVisibility(toggle.INVISIBLE);
                } else {
                    toggle.setVisibility(toggle.VISIBLE);
                }
            }
        });
    }

    public void switchActivity(View v){
        startActivity(new Intent(MainActivity.this, SecondActivity.class));
    }

}
</code>```

Body:
I'm trying to create a switch which when enabled hides a button called button but it returns an error for SetOnCheckedChangeListener and buttonView which says Cannot resolve symbol

package com.jordthedev.firstapplication;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.ToggleButton;

public class MainActivity extends AppCompatActivity {
    int count = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    }

    public void switchActivity(View v){
        startActivity(new Intent(MainActivity.this, SecondActivity.class));
    }

    ToggleButton toggle = (ToggleButton) findViewById(R.id.toggleButton);
    toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                toggle.setVisibility(toggle.INVISIBLE);
            } else {
                toggle.setVisibility(toggle.VISIBLE);
            }
        }
    });

}

Body:
Maybe you have to place ToggleButton in onCreate() method try below code

package com.jordthedev.firstapplication;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.ToggleButton;

public class MainActivity extends AppCompatActivity {
    int count = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final ToggleButton toggle = (ToggleButton) findViewById(R.id.toggleButton);
        toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    toggle.setVisibility(toggle.INVISIBLE);
                } else {
                    toggle.setVisibility(toggle.VISIBLE);
                }
            }
        });
    }

    public void switchActivity(View v){
        startActivity(new Intent(MainActivity.this, SecondActivity.class));
    }

}


问:
MySql join multiple select subquery
-SOLUTION-

```<code>SELECT Table1.unvan, Table2.sayi FROM
(SELECT id , unvan FROM unvan WHERE id IN
(SELECT unvani FROM personel WHERE gorev_yeri IN
(SELECT id FROM gorev_yeri WHERE il_id="34") ) ) AS Table1
JOIN
( SELECT unvani as id , count(*) AS sayi FROM personel WHERE gorev_yeri IN (SELECT id FROM gorev_yeri WHERE il_id="34") GROUP BY unvani ) AS Table2
ON Table1.id = Table2.id
</code>```

-EDIT-

When I use join with as I get this error : #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'AS table1

I have 2 query and I want join them.

It is first.

```<code>SELECT id
     , unvan
  FROM unvan
 WHERE id IN (SELECT unvani
                FROM personel
               WHERE gorev_yeri IN (SELECT id
                                      FROM gorev_yeri
                                     WHERE il_id="34")
              )
</code>```

It is second one.

```<code>SELECT unvani as id
     , count(*) AS sayi
 FROM personel
WHERE gorev_yeri IN (SELECT id
                       FROM gorev_yeri
                        WHERE il_id="34") GROUP BY unvani
</code>```

I need this:

unvan|sayi

--------|----

答:
Based from error provided

It should be like this:

```<code>SELECT `Table1`.unvan, `Table2`.id
FROM
(
    SELECT id
    , unvan
   FROM unvan
   WHERE id IN (SELECT unvani
            FROM personel
           WHERE gorev_yeri IN (SELECT id
                                  FROM gorev_yeri
                                 WHERE il_id="34")
          )
) AS `Table1`

JOIN

(
SELECT unvani as id
 , count(*) AS sayi
 FROM personel
 WHERE gorev_yeri IN (SELECT id
                   FROM gorev_yeri
                    WHERE il_id="34") GROUP BY unvani
) AS `Table2`

ON `Table1`.id = `Table2`.id
</code>```

Title: MySql join multiple select subquery

Body:
-SOLUTION-

SELECT Table1.unvan, Table2.sayi FROM
(SELECT id , unvan FROM unvan WHERE id IN
(SELECT unvani FROM personel WHERE gorev_yeri IN
(SELECT id FROM gorev_yeri WHERE il_id="34") ) ) AS Table1
JOIN
( SELECT unvani as id , count(*) AS sayi FROM personel WHERE gorev_yeri IN (SELECT id FROM gorev_yeri WHERE il_id="34") GROUP BY unvani ) AS Table2
ON Table1.id = Table2.id

-EDIT-

When I use join with as I get this error : #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'AS table1

I have 2 query and I want join them.

It is first.

SELECT id
     , unvan
  FROM unvan
 WHERE id IN (SELECT unvani
                FROM personel
               WHERE gorev_yeri IN (SELECT id
                                      FROM gorev_yeri
                                     WHERE il_id="34")
              )

It is second one.

SELECT unvani as id
     , count(*) AS sayi
 FROM personel
WHERE gorev_yeri IN (SELECT id
                       FROM gorev_yeri
                        WHERE il_id="34") GROUP BY unvani

I need this:

unvan|sayi

--------|----

Body:
Based from error provided

It should be like this:

SELECT `Table1`.unvan, `Table2`.id
FROM
(
    SELECT id
    , unvan
   FROM unvan
   WHERE id IN (SELECT unvani
            FROM personel
           WHERE gorev_yeri IN (SELECT id
                                  FROM gorev_yeri
                                 WHERE il_id="34")
          )
) AS `Table1`

JOIN

(
SELECT unvani as id
 , count(*) AS sayi
 FROM personel
 WHERE gorev_yeri IN (SELECT id
                   FROM gorev_yeri
                    WHERE il_id="34") GROUP BY unvani
) AS `Table2`

ON `Table1`.id = `Table2`.id


问:
How to simplify Logic Gate - mux simulation
When trying to make an multiplexor how do you go from this:

```<code> Not(in=a, out=nota);
    Not(in=b, out=notb);
    Not(in=sel, out=notsel);
    And(a=a, b=b, out=aAndb);
    And(a=a, b=notb, out=aAndNotb);
    And(a=nota, b=b, out=bAndNota);
    And(a=aAndb, b=sel, out=aAndBAndSel);
    And(a=aAndb, b=notsel, out=aAndBAndNotSel);
    And(a=aAndNotb, b=notsel, out=aAndNotBAndNotSel);
    And(a=bAndNota, b=sel, out=bAndNotaAndSel);
    Or(a=aAndBAndSel, b=aAndBAndNotSel, out=o1);
    Or(a=o1, b=aAndNotBAndNotSel, out=o2);
    Or(a=o2, b=bAndNotaAndSel, out=out);
</code>```

to this:

```<code>    Nand(a=sel, b=sel, out=notsel);
    Nand(a=a, b=notsel, out=asel);
    Nand(a=b, b=sel, out=bnotsel);
    Nand(a=asel, b=bnotsel, out=out);
</code>```

my answer are always very long and i'm not sure how you would go about finding a more elegant solution.

```<code>MUX Truth Table Answers
|   a   |   b   |  sel  |  out  |
|   0   |   0   |   0   |   0   |
|   0   |   0   |   1   |   0   |
|   0   |   1   |   0   |   0   |
|   0   |   1   |   1   |   1   |
|   1   |   0   |   0   |   1   |
|   1   |   0   |   1   |   0   |
|   1   |   1   |   0   |   1   |
|   1   |   1   |   1   |   1   |
</code>```

答:
That simplifies to:

```<code>BS + AS'
</code>```

Or to use different notation:

```<code>(B & S) ∨ (A & ~S)
</code>```

Body:
When trying to make an multiplexor how do you go from this:

 Not(in=a, out=nota);
    Not(in=b, out=notb);
    Not(in=sel, out=notsel);
    And(a=a, b=b, out=aAndb);
    And(a=a, b=notb, out=aAndNotb);
    And(a=nota, b=b, out=bAndNota);
    And(a=aAndb, b=sel, out=aAndBAndSel);
    And(a=aAndb, b=notsel, out=aAndBAndNotSel);
    And(a=aAndNotb, b=notsel, out=aAndNotBAndNotSel);
    And(a=bAndNota, b=sel, out=bAndNotaAndSel);
    Or(a=aAndBAndSel, b=aAndBAndNotSel, out=o1);
    Or(a=o1, b=aAndNotBAndNotSel, out=o2);
    Or(a=o2, b=bAndNotaAndSel, out=out);

to this:

    Nand(a=sel, b=sel, out=notsel);
    Nand(a=a, b=notsel, out=asel);
    Nand(a=b, b=sel, out=bnotsel);
    Nand(a=asel, b=bnotsel, out=out);

my answer are always very long and i'm not sure how you would go about finding a more elegant solution.

MUX Truth Table Answers
|   a   |   b   |  sel  |  out  |
|   0   |   0   |   0   |   0   |
|   0   |   0   |   1   |   0   |
|   0   |   1   |   0   |   0   |
|   0   |   1   |   1   |   1   |
|   1   |   0   |   0   |   1   |
|   1   |   0   |   1   |   0   |
|   1   |   1   |   0   |   1   |
|   1   |   1   |   1   |   1   |

Body:
That simplifies to:

BS + AS'

Or to use different notation:

(B & S) ∨ (A & ~S)


问:
Print PDF file using Foxit Reader and C#
My program prints silently via the PDF reader Foxit Reader in a new process.

On occasion, my program attempts to print two PDFs at the same time, which causes one of them to fail to print.

Here is my code:

```<code>string filename = "file.pdf";

string fileDir1 = @"C:\Program Files (x86)\Foxit Software\Foxit Reader\FoxitReader.exe";

Process pdfProcess = new Process();
pdfProcess.StartInfo.FileName = fileDir1;
pdfProcess.StartInfo.Arguments = string.Format(@"/t {0} {1}", filename ,"pos-80");
pdfProcess.StartInfo.CreateNoWindow = true;
pdfProcess.StartInfo.WorkingDirectory = Path.GetDirectoryName(fileDir1);
pdfProcess.Start();

if (!pdfProcess.WaitForExit(2500))
{
    pdfProcess.Kill();

}
</code>```

Please help me resolve this issue.

答:
Make sure you have Foxit open.

```<code>using System.Diagnostics;

List<Process> Processlist = Process.GetProcesses().ToList();
</code>```

This gives you a list of currently running processes.

```<code>foreach(Process p in Processlist)
{
    Console.WriteLine("Process " + p.Id + " is named '" + p.ProcessName + "'");

}
</code>```

When running the above code, you should see the name of the Foxit process in your output window.

Alternatively, put a break-point on the foreach line and hover over the list to see all the names that way.

```<code>bool IsFoxitProcessRunning = false;

foreach(Process p in Processlist)
{
    if(p.ProcessName == "Foxit process name here") //Replace with the name of the foxit process
    {
        IsFoxitProcessRunning  = true;

    }

}
</code>```

Now, only start a new Foxit process if one isn't already running.

```<code>if(!IsFoxitProcessRunning)
{
    //insert code to run next foxit process here.

}
</code>```

Notes:

You may need to implement a queue to keep track of pdfs waiting to run.

You may also wish to alert IT support if a Foxit is waiting more 5 or 10 mins  to run.

You could choose to make Processlist a class attribute, and periodically refresh Processlist using a Timer, by calling Processlist = Process.GetProcesses().ToList(); on the Tick event. every 30 seconds or so while a PDF is waiting to be printed.

Body:
My program prints silently via the PDF reader Foxit Reader in a new process.

On occasion, my program attempts to print two PDFs at the same time, which causes one of them to fail to print.

Here is my code:

string filename = "file.pdf";

string fileDir1 = @"C:\Program Files (x86)\Foxit Software\Foxit Reader\FoxitReader.exe";

Process pdfProcess = new Process();
pdfProcess.StartInfo.FileName = fileDir1;
pdfProcess.StartInfo.Arguments = string.Format(@"/t {0} {1}", filename ,"pos-80");
pdfProcess.StartInfo.CreateNoWindow = true;
pdfProcess.StartInfo.WorkingDirectory = Path.GetDirectoryName(fileDir1);
pdfProcess.Start();

if (!pdfProcess.WaitForExit(2500))
{
    pdfProcess.Kill();

}

Please help me resolve this issue.

Body:
Make sure you have Foxit open.

using System.Diagnostics;

List<Process> Processlist = Process.GetProcesses().ToList();

This gives you a list of currently running processes.

foreach(Process p in Processlist)
{
    Console.WriteLine("Process " + p.Id + " is named '" + p.ProcessName + "'");

}

When running the above code, you should see the name of the Foxit process in your output window.

Alternatively, put a break-point on the foreach line and hover over the list to see all the names that way.

bool IsFoxitProcessRunning = false;

foreach(Process p in Processlist)
{
    if(p.ProcessName == "Foxit process name here") //Replace with the name of the foxit process
    {
        IsFoxitProcessRunning  = true;

    }

}

Now, only start a new Foxit process if one isn't already running.

if(!IsFoxitProcessRunning)
{
    //insert code to run next foxit process here.

}

Notes:

You may need to implement a queue to keep track of pdfs waiting to run.

You may also wish to alert IT support if a Foxit is waiting more 5 or 10 mins  to run.

You could choose to make Processlist a class attribute, and periodically refresh Processlist using a Timer, by calling Processlist = Process.GetProcesses().ToList(); on the Tick event. every 30 seconds or so while a PDF is waiting to be printed.


问:
Mailboxer - All recipients except the originator of a conversation
Using Mailboxer I can find all participants in a conversation as

@participants = @conversation.participants

I can find the originator of a conversation using

@originator = @conversation.originator

Now I am trying to find all the participants except the originator.

@participants.delete_if { |participant| participant == @originator}

it is working fine but I wonder if there a better way of doing this? Thanks

答:
None of the available helpers returns the participants without the originator. I expected recipients would help, but it does what participants do.
Both the methods returns all recipients with originator included.

```<code># File 'app/models/mailboxer/conversation.rb', line 78

def participants
  recipients
end

# File 'app/models/mailboxer/conversation.rb', line 72

def recipients
  return [] unless original_message
  Array original_message.recipients
end
</code>```

You can use reject instead of delete_if but it is more or less the same. I recommend you to keep the current approach as it looks clean and better.

Body:
None of the available helpers returns the participants without the originator. I expected recipients would help, but it does what participants do.
Both the methods returns all recipients with originator included.

# File 'app/models/mailboxer/conversation.rb', line 78

def participants
  recipients
end

# File 'app/models/mailboxer/conversation.rb', line 72

def recipients
  return [] unless original_message
  Array original_message.recipients
end

You can use reject instead of delete_if but it is more or less the same. I recommend you to keep the current approach as it looks clean and better.