Two panels in one JFrame

Question: I know there have been many topics on this subject before and I have used Google extensively to figure this out, but whatever I do I cannot get two panels to display in one JFrame. I have tried many things including CardLayout but that didn't seem to work. I have a feeling this is a very easy solution..
The purpose is to see the difference between the two panels due to the random positioning.
Here are some of the java files (only pertinent code - there is also a Snowman.java but it just provides the drawing for the snowmen similar to ghost.java):
Ghost.java
import java.awt.*;

public class Ghost
{
private int x, y;
private String name;
private boolean happy;
private Color color;

public Ghost (Color shade, int upperX, int upperY, String a, boolean b)
{
  color = shade;
  x = upperX;
  y = upperY;
  name = a;
  happy = b;
}

public void draw (Graphics page)
{
  page.setColor(color);
  page.fillOval (x, y, 50, 125);
  page.fillRect (x+1, y+60, 49, 75); // body of ghost

  page.setColor(Color.black);
  page.fillOval (x+12, y+10, 8, 8);
  page.fillOval (x+32, y+10, 8, 8); // eyes

  page.setColor(Color.white);
  page.drawString(name, x+8, y-5); // name

  page.setColor(Color.black);
  if (happy == true)
     page.fillArc  (x+10, y+30, 33, 10, 180, 180);
  else
     page.fillArc  (x+10, y+30, 33, 10, 0, 180); // smile/frown
}

public void setColor (Color shade)
{
  color = shade;
}

public void setX (int upperX)
{
  x = upperX;
}

public void setY (int upperY)
{
  y = upperY;
}

HalloweenPanel.java :
import javax.swing.*;
import java.awt.*;
import java.util.Random;

public class HalloweenPanel extends JPanel
{
 private Ghost ghost1, ghost2, ghost3;
 private Snowman snowman1, snowman2;

 public HalloweenPanel()
 {
  setBackground (Color.black);

  Random rand = new Random();
  int randomX = rand.nextInt(700)+50;
  int randomY = rand.nextInt(400)+50;
  boolean randomHappy = (Math.random() < 0.5);
  boolean randomHappy2 = (Math.random() < 0.5);

  ghost1 = new Ghost (Color.white, randomX, randomY, "Scary", randomHappy2);
  ghost2 = new Ghost (Color.blue, randomX, 100, "Happy", true);
  ghost3 = new Ghost (Color.yellow, 300, randomY, "Scared", randomHappy);

  snowman1 = new Snowman (500, 50);
  snowman2 = new Snowman (750, 100);
  }

  public void paintComponent (Graphics page)
  {
  Random rand = new Random();
  int randomX2 = rand.nextInt(900);
  int randomY2 = rand.nextInt(500);
  super.paintComponent(page);
  ghost2.setX(randomX2);
  ghost3.setY(randomY2);
  ghost1.draw(page);
  ghost2.draw(page);
  ghost3.draw(page);
  snowman1.draw(page);
  snowman2.draw(page);
 }
}

HalloweenDriver.java:
import javax.swing.*;
import java.awt.*;

public class HalloweenDriver
{
public static void main (String[] args)
 {
  JFrame frame = new JFrame ("Halloween - Winter is Coming..");
  frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);

  JPanel mainPanel = new JPanel();
  HalloweenPanel panel = new HalloweenPanel();
  HalloweenPanel panel2 = new HalloweenPanel();

  mainPanel.setLayout(new GridLayout(1,0));

  mainPanel.add(panel);
  mainPanel.add(panel2);

  frame.add(mainPanel);

  frame.pack();
  frame.setVisible(true);
 }
}

Comment: Don't forget to call super.paintComponent and instead of using setPreferredSize, you should consider overriding the getPreferredSize method instead
Answer: frame.getContentPane().add(panel);
frame.getContentPane().add(panel2);

You are trying to add two panels to the CENTER of a BorderLayout. This can't be done.
Try:
frame.getContentPane().add(panel, BorderLayout.CENTER);
frame.getContentPane().add(panel2, BorderLayout.SOUTH);

to see the difference.
If this isn't what you want then try another layout manager. Read the Swing tutorial on Layout Managers.
Or, if you are trying to stack the two panels on top of one another (on the Z axis) then try the OverlayLayout. This is not covered in the tutorial so you will need to look at the API. You will also need to make the "top" panel non-opaque() so it doesn't paint over top of the bottom panel.
Comment: Read the tutorial on how a BorderLayout works. Your screen size is probably not big enough to display both components, so the SOUTH gets its preferred size and the CENTER gets what is left over. If you want them to be equal size then use a `GridLayout`. Again, the tutorial is your friend. `I am very new to java and am a student to this` - that is why I gave you a link to the tutorial. You need to take the time to read it to understand the basics of Swing.
Comment: Thank you for the comment. I tried adding the borderlayouts and both of them now display. However, the top one has a lot less space now than then bottom panel so some of the objects do not show up properly. How can I get both of the panels to have the same size? I looked into OverlayLayout and tried making a new container for that but it sort of meshed the two together. I am very new to java and am a student to this, so please forgive me. Thanks again!
Comment: I think I figured it all out. I edited the code above to reflect what I currently have. I got rid of the setPreferredsize. For the gridlayout I made one row and 0 columns to get them on the same level since when I made one column and zero rows I still had the same problem but I think it was a problem of my 15" screen size and not the code's fault. With them on one row all objects are always visible. As an aside, just re-running the program over and over shows how random isn't really random since a lot of the time the x and y positions are the same. Thanks again for all your help!

Two panels in one JFrame


How do I check whether a SQLite database file exists using Java?

Question: I get the name of database file from a user, and I want to check if that file already exists. If it does exist, I want to show an error message to user, but I don't know how to check if the file exists.
public static void databaseConnect(String dbName) throws Exception
{
  if (/*same name exists*/) // How do I check this?
  {
    System.out.print("This database name already exists");
  }
  else
  {
    Class.forName("SQLite.JDBCDriver").newInstance();
    conn = DriverManager.getConnection("jdbc:sqlite:/"+ dbName);
    stat = conn.createStatement();
  }
}

Comment: Are you really checking if it exists or if a connection has already been opened?
Comment: Note that the slash after "sqlite:" and before the file path is not necessary with several of the SQLite JDBC drivers I've used.
Comment: No just to check if this database file(with name dbName) already exists or not!
Answer: public static void databaseConnect(String dbName) throws Exception {

   File file = new File (dbName);

  if(file.exists()) //here's how to check
     {
         System.out.print("This database name already exists");
     }
     else{

           Class.forName("SQLite.JDBCDriver").newInstance();
           conn = DriverManager.getConnection("jdbc:sqlite:/"+ dbName);
           stat = conn.createStatement();

     }

Comment: @SunyGirl I will take a big leap and try to guess your ultimate goal. Are you trying to run SQL statements the first time you create a database, then never again? Such as an initialization script for your database?
Comment: No it does not work. When I want to create new database file it says that name exists!
Comment: That's because the database already exists. In all the answers the connection will only be created one time, ever even between multiple runs.
Comment: so what should I do?I guess I did not get you sorry.
Comment: yes Andrew exactly after that I will create tables. I want to tell users that he wanted to have another database file name same as previous ones.(each time my program runs I create a database in my folder)
Answer: Assuming that your dbName parameter indicates the path to the SQLite file ("-wal" and "-shm" companion files notwithstanding), you can use the Java java.io.File class and its exists() predicate:
final File f = new File(dbName);
if (f.exists())
{
  if (f.isDirectory())
  {
    // Warn about the designated name being a directory.
  }
  else
  {
    // Warn about the designated name already existing as a file.
  }
}

Other checks could be warranted too, such as whether the process has the privilege to create the file, though ultimately SQLite will do a better job ensuring that all its requirements can be fulfilled.
Comment: In that case, the directory portion of the path is implicitly "./", indicating the current working directory of the host process.
Comment: my dbName is the name of database file and no path included.
Comment: you mean this? File file = new File ("jdbc:sqlite:/"+sessionName);
Comment: @Suny: You have to strip the `jdbc:sqlite:` part for sure; possibly also the first slash (a little experiment will tell you for sure).
Answer: I've found that the best way to do this is to instead check the size of the file. If you execute:
return new File(DB_NAME).exists() should equal True.
You should get a true back because it will create it. Instead check to make sure the file size is greater than 0. At least in this case you know there's data in the file without attaching and querying for results.
Instead do:
return new File(DB_NAME).length() > 0
Answer: You can do something like this, I'm guessing you think you are creating a new file in your directory when you do "new File(name)", for what I've red, but that is not what is happening.
    public static void databaseConnect(String dbName) throws Exception {

      // new File(filename) does not create a new
      // file in your file system
      File file = new File (dbName);

      if (file.exists())
      { // the file already existed and the program will enter this block
        System.out.print("Do something");
      }
      else
      { //the file did not exist and you can send your error msg
        System.out.print("Do something else");
      }
    }

I misinterpreted your question a few times, my bad, but I think that's it.
Answer: Something like this?
public boolean databaseExist()
{
    File dbFile = new File(DB_PATH + DB_NAME);
    return dbFile.exists();
}

Comment: with this    File file = new File ("jdbc:sqlite:/"+sessionName);  it does not work!never goes to if condition!
Answer: late, may it help :
public boolean didPackageCreate() {

    File dbfile = this.getDatabasePath("app.db");
    if(dbfile.exists()){
        // db exist
    }else{
       // db doesn't exist
    }
}

Answer: To this day I believe this is the simplest way to achieve this. The couchbase lite database is created locally, so if it already exists, you add it to the config and create a Database instance to start working with it.
Here is the documentation: https://docs.couchbase.com/couchbase-lite/current/java/database.html#lbl-find-db-loc
import com.couchbase.lite.*;

 private static Database openOrCreateDatabase(String dbName) throws CouchbaseLiteException {
        DatabaseConfiguration config = new DatabaseConfiguration();
        File file=new File(config.getDirectory());
        if (!Database.exists(dbName,file)){
            System.out.println("Database created: "+dbName);
            return new Database(dbName, config);
        }else{
            config.setDirectory("../../"+dbName+".cblite2"); //path to your cblite folder
            return new Database(dbName, config);
        }
    }


Making Sense of 5/4 Time Signature

Question: I'm doing a composition with time signatures that alternate between 3/4 and 2/4. At first, the meter is a steady 2/4, before suddenly switching to 3/4. From that point on, the piece alternates between 3/4 and 2/4 consistently.
So the question is, is there fundamentally any difference between 5/4 and 3/4 + 2/4? If 5/4 is further subdivided into either 3 + 2 or 2 + 3, would it be better to turn any passage that alternates between 3/4 + 2/4 to 5/4?
Comment: I count that with five fingers tapping !
Answer: Writing in 5/4 is perfectly reasonable. You could also make the time signature either (3+2)/4, which would mean "five beats per measure, with a 3+2 pulse pattern", or you could write both time signatures next to each other, which would mean "alternate measures of 3/4 and 2/4."
<code>X:0
T:5/4 Time Signature Options
K:C
M:5/4
L:1/1
z | [M:3+2/4] z3/4 z2/4 || [M:32/44] z3/4 | z2/4 ||
</code>
(NOTE: the 4 should be centered at the bottom of the (2+3)/4 time signature.)
Loosely speaking, the fundamental differences would be these:

5/4 would mean one strong beat per measure (beat 1), and one semistrong beat per measure (beat 4).
(3+2)/4 would be equivalent to 5/4
[3/4][2/4] would mean two measures both with strong beats (beat 1, respectively).

These are interpretive rules of thumb, but phrasing or other musical considerations could make them more equivalent or less.
It also should be noted that the metric divisions within 5/4 time (3+2 or 2+3) can be clarified, if necessary, by the use of a dotted bar line. This is particularly helpful in a situation where the divisions change.
Comment: @user45266 Yeah, that's an unfortunately limitation of ABCjs. In fact, it's coded as 32/44, which is the only way to get a multiple time signature like that.
Comment: Obviously nonsensical as a symbol for a time signature, but when I first saw the (3/4)(2/4) example image, I read it as (32/44) and balked before I realized my mistake :)
Comment: "5/4 would mean...one semistrong beat per measure (beat 4)" – does it though? I agree that seems to be the most common, but in principle 5/4 could also be 2+3.
Comment: I'd go with either of the first 2 options.  The 32/44 thing, even if you fixed the spacing issue, is still more likely to be confusing to the reader.
Comment: Ah, makes sense. Nice workaround!
Comment: I really like "3 + 2 / 4."  I've never done that, but it makes perfect sense.
Comment: If I were reading the chart and the where the pulse was important, I'd prefer having it written in 5/4 and notated "2+3 Feel" or some such.
Comment: @leftaroundabout You're correct that in general 5/4 could be 3+2 or 2+3, but OP is specifically asking about notating a 3+2 division. (Very nice thought, BTW, about trying to fool with ABC with non-breaking spaces.)
Answer: Using 5/4 instead of constant changes between 3/4 and 2/4 would certainly de-clutter the score.
But is it useful clutter?  Maybe not.  Where the grouping is consistently 3+2, a single indication of that where the 5/4 starts should be sufficient.

Is there any need for dotted barlines?  Not, I think in a bar as short as just 5 beats.  Maybe in 10/4, 11/4 etc.

You might be able to make the problem go away completely by notating in 5/8, where beaming can easily indicate groups.
Answer:
"From that point on, the piece alternates between 3/4 and 2/4 consistently."

Alternates on what scale?
If it alternates each measure consistently, then it really is the concept of additive time...

3+2
 4

But if it goes a few measures of 3/4 then changes to a few measures of 2/4 alternating meter at a phrase level then it probably should change time signatures accordingly.

Making Sense of 5/4 Time Signature


Rename hostname

Question: If you rename the PC's hostname at the PC while it is connected to the domain, will it find that original hostname in AD and rename it there as well?
Answer: Yes, Active Directory should automatically update with the new workstation name.  If you have multiple domain controllers in different sites, it may take some time for the change to replicate across all controllers (depending on topology and settings).
Answer: Yes, it will rename the computer account in the domain.

Rename hostname


PHP: Update database using script

Question: Hi I'm having an issue with a small php script. I am trying to get my user to change the status of a "job" so I am having to use option and post.
I can get the option answer but not the id. So how do I pass the id to then new script bellow are the scripts.
<?php
$conx; //connection object to the server
$comd;//instance of a command object
$sql; //string variable to hold the SQL commands
$itemsAdded; //numeric var to hold num records added to table (1 or 0)
$dbpath;

$db = realpath("../Database/iceserv.mdb");

$conn = new COM('ADODB.Connection') or exit('Cannot start ADO.');

$connStr = "PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=$db";

$conn->Open($connStr);

$sql = "SELECT callback.*,  status.stat_disc AS Status
FROM callback INNER JOIN  status ON callback.callback_STATID = status.stat_ID";

$rs = $conn->Execute($sql);
if (!$rs) {exit("Error in SQL");}
echo "<form method='post' action='../scripts/update_stat.php' id='status' name='status'>

";
echo " Cutomer ID	";
echo "Customer First Name	";
echo "Customer Surname	";
echo "Customer Phone Number	";
echo "Customer Reason For Callback	";
echo "Callback Status	";
echo "Change Status	";
echo "	";

while (!$rs->EOF) {

     $callid=$rs->Fields['callback_ID']->Value;
     //echo $callid;
     $fname=$rs->Fields['callback_fname']->Value;
     $sname=$rs->Fields['callback_sname']->Value;
     $phone=$rs->Fields['callback_phnum']->Value;
     $reason=$rs->Fields['callback_reason']->Value;
     $status=$rs->Fields['Status']->Value;
     echo "
$callid	";
     echo "$fname	";
     echo "$sname	";
     echo "$phone	";
     echo "$reason	";
     echo "$status	";
     //echo "<input type='text' name='calledid' value = '$callid'>	";
     echo"<select name ='status' size='1'>
     <option value =''>Choose status</option>
     <option value ='1'>Open </option>
     <option value ='2'>Waiting Qoute</option>
     <option value ='3'>Closed </option>
     </select>";
     echo  "<input type='submit' name='submit_btn' id='submit_btn' value='Update' class='submit_btn1'</input>

</form>";

  exit;
  }
?>

So the above script is calling and pulling the information from the database
    <?php

    //variable listing and usage
    $conx; //connection object to the server
    $comd;//instance of a command object
    $sql_comd; //string variable to hold the SQL commands
    $itemsAdded; //numeric var to hold num records added to table (1 or 0)
    $dbpath;

        $db = realpath("../Database/iceserv.mdb");

        $conn = new COM('ADODB.Connection') or exit('Cannot start ADO.');

        $connStr = "PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=$db";

        $conn->Open($connStr);
              $id = $_POST['callid'];
              echo "ID is " +$id;
              $option= $_POST['status'];

    $sql_comd="UPDATE callback
    SET callback_STATID=$option
    WHERE callback_ID=$id
    ";
    $conn->Execute($sql_comd);

//$result = null;
$conn = null;

header('Location: ../admin/callback.php');

?>

The above script is trying to update the table but the id is not passing through so how do I get the ID to be passed to the script?
Please ask if ive been unclear
Comment: I don't understand what you are asking, but I want to point out that you have yourself wide open to SQL injection.  Please read up on using prepared queries with PDO.  In addition, you cannot use relative paths in a 302 redirect (which is what you are doing with the location header).
Answer: You can set the value of the select like: <option value ='{$callid}|1'>Open </option> and then explode by "|" to split the result list($id,$option)=explode("|",$_REQUEST['status'])
Comment: Thank you for the quick response would I do this on the update script ie second script?
Comment: @andy the first part in the html and the second in the action script (don't forget to replace $_REQUEST['status'] with $option)
Comment: that worked thank you very much.  I'll know work on stoping my scripts being open to SQL injections thank you
Comment: @andy - better use my solution :) it is straight forward and not a workaround like messing up 2 data in one field.
Answer:
<input type="hidden" name="calledid" value="<?=$callid;?>" />

My bad.
<button name="calledid" type="submit" value="<?=$callid;?>">Submit</button>

Use it instead of your input.
Comment: bad ideea...he only needs one callid (for one specific row)

PHP: Update database using script


Configuring ASP.NET web site in IIS 6.0

Question: I have installed IIS and .NET 4.0 on Windows Server 2003.
I have a web ready website that that targets .NET 4.0 and have updated the default website home directory to map to the website's directory.
When I visit the website in a web browser (localhost, localhost:80), I get a 404 error (File or directory not found).
Here is the IP address so you can see for yourself. http://126.96.36.199/
How do I get my ASP.NET 4.0 website to run?
Answer:
Did you install ASP.NET in the using the Add or Remove Programs dialog box on the Control Panel?
In IIS Manager: did you allow the ASP.NET Web Service Extension?

See this Technet article about Installing ASP.NET (IIS 6.0).
Comment: I had to allow the ASP.NET Web Service Extension. Thanks!
Comment: This wasn't exactly what was wrong with my installation, but it pointed me in the right direction.  I had to allow ASP.NET in Web Service Extensions (Start > IIS Manager > [server](local computer) > Web Service Extensions > ASP.NET(2 or 4) > Allow.  Thanks for the link!
Answer: You need to install IIS before installing .NET 4.0. If IIS is installed after .NET 4.0, you need to use command prompt and run the aspnet_regiis tool located in the .net 4.0 directory.

Configuring ASP.NET web site in IIS 6.0


Asp Net MVC longPolling

Question: Tenho um projeto asp net mvc 5, verifiquei que a cada segundo é feita uma requisição, passando esses parametros = transport=longPolling&connectionToken="", e como resposta vem {"C":"d-5B01A8B9-CN,0|Dw,B|Dx,0","M":[]}, que seria isso?
Comment: Possivelmente é uma conexão socket feita por JavaScript. Sua aplicação tem SignalR instalado?
Comment: Não tem, e percebi também que só aparece essas requisições quando estou em ambiente de desenvolvimento.
Answer: Dando uma pesquisada na net, verifiquei que esse comportamento ocorre, porque está utilizando o Browser Link do Visual Studio 2013.
O Browser Link é um recurso do Visual Studio 2013, que cria um canal de comunicação entre o ambiente de desenvolvimento e um ou mais navegadores web. Você pode usar o navegador o link para atualizar seu aplicativo da web em vários navegadores ao mesmo tempo, o que é útil para testes de cross-browser.
Para desativar, é só remover essa opção:

https://stackoverflow.com/questions/19917595/net-localhost-website-consistently-making-get-arterysignalr-polltransport-long
http://www.asp.net/visual-studio/overview/2013/using-browser-link

Asp Net MVC longPolling


Cisco Switch NTP client Clock is unsynchronized, stratum 16, no reference clock

Question: I am trying to configure a cisco switch as a ntp client, however I cannot get past the show ntp status of Clock is unsynchronized, stratum 16, no reference clock. I've tried setting the clock close to the UTC time, but i still don't show time synced. First I thought it was due to a bug I was reading about regarding Win32Timeservice, or something like that, however I confirmed that this is a NTPD server (10.0.0.8) running on Unix.
Here is running-config
ntp server 10.0.0.8

Here is show ntp status
Clock is unsynchronized, stratum 16, no reference clock
nominal freq is 119.2092 Hz, actual freq is 119.2092 Hz, precision is 2**17
reference time is 00000000.00000000 (00:00:00.000 UTC Mon Jan 1 1900)
clock offset is 0.0000 msec, root delay is 0.00 msec
root dispersion is 0.00 msec, peer dispersion is 0.00 msec

Here is show ntp associations:
      address         ref clock     st  when  poll reach  delay  offset    disp
 ~10.0.0.8     188.8.131.52      16    11   128  377     1.8  24018.     4.7
 * master (synced), # master (unsynced), + selected, - candidate, ~ configured

Here is show ntp associatsions detail:
10.0.0.8 configured, insane, invalid, stratum 16
ref ID 184.108.40.206, time D4452E2F.F4727CEA (18:59:59.954 UTC Wed Nov 7 2012)
our mode active, peer mode active, our poll intvl 512, peer poll intvl 256
root delay 0.00 msec, root disp 8.65, reach 377, sync dist 13.535
delay 1.45 msec, offset 24014.6042 msec, dispersion 4.17
precision 2**20, version 3
org time D4452E2F.F472894E (18:59:59.954 UTC Wed Nov 7 2012)
rcv time D4452E17.F0E5117A (18:59:35.940 UTC Wed Nov 7 2012)
xmt time D4452E17.F083A829 (18:59:35.939 UTC Wed Nov 7 2012)
filtdelay =     1.45    2.44    1.80    1.71    1.91    1.72    1.31    2.37
filtoffset = 24014.6 24016.5 24018.8 24021.3 24023.6 24026.1 24028.7 24030.7
filterror =     0.02    0.99    1.79    2.76    3.74    4.71    5.69    6.67

Here is my debug ntp
1d03h: NTP: xmit packet to 10.0.0.8:
1d03h:  leap 3, mode 1, version 3, stratum 0, ppoll 64
1d03h:  rtdel 0000 (0.000), rtdsp 10001 (1000.015), refid 00000000 (0.0.0.0)
1d03h:  ref 00000000.00000000 (00:00:00.000 UTC Mon Jan 1 1900)
1d03h:  org D4452CBB.F7C546BE (18:53:47.967 UTC Wed Nov 7 2012)
1d03h:  rec D4452CA3.F093A140 (18:53:23.939 UTC Wed Nov 7 2012)
1d03h:  xmt D4452CE3.F082CDCD (18:54:27.939 UTC Wed Nov 7 2012)
1d03h: NTP: rcv packet from 10.0.0.8 to 10.0.0.30 on Vlan20:
1d03h:  leap 0, mode 1, version 3, stratum 0, ppoll 64
1d03h:  rtdel 0000 (0.000), rtdsp 0108 (4.028), refid 494E4954 (22.214.171.124)
1d03h:  ref D4452CFB.F76D2086 (18:54:51.966 UTC Wed Nov 7 2012)
1d03h:  org D4452CE3.F082CDCD (18:54:27.939 UTC Wed Nov 7 2012)
1d03h:  rec D4452CFB.F76B8A2C (18:54:51.966 UTC Wed Nov 7 2012)
1d03h:  xmt D4452CFB.F76D2DB1 (18:54:51.966 UTC Wed Nov 7 2012)
1d03h:  inp D4452CE3.F0F5FBCA (18:54:27.941 UTC Wed Nov 7 2012)

I'm not really sure whwere to go to from here. I know under show ntp associations detail if insane or invalid or stratum 16 is in there the cisco switch won't sync time.
Here is the ntp.conf
server 0.north-america.pool.ntp.org
server 1.north-america.pool.ntp.org
server 2.north-america.pool.ntp.org
server 3.north-america.pool.ntp.org

server  127.127.1.0     # local clock
fudge   127.127.1.0 stratum 10

restrict 127.0.0.1

Answer: This debug line makes me curious about the validity of your NTP master:
1d03h: NTP: rcv packet from 10.0.0.8 to 10.0.0.30 on Vlan20:
1d03h:  leap 0, mode 1, version 3, stratum 0, ppoll 64

So your NTP server is declaring it is stratum 0 - that's not going to work.
I labbed this out with two routers to make sure how the format should look like from the NTP master.
.Mar  1 00:55:51.533: NTP: rcv packet from 10.0.0.8 to 10.0.0.30 on Serial0/0:
.Mar  1 00:55:51.537:  leap 0, mode 4, version 3, stratum 5, ppoll 64

Note the reasonable stratum from my NTP master (simple config on the master router was "ntp master 5")
NTP is a finicky protocol to be sure, but I'd take a closer look at your NTP master.   One other thing that tends to help with NTP is to set network devices clock 'close' to the clock the NTP master will ultimately provide.
Masters whose updates are off by a very far distance from what the switch thinks the time should be can also be declared insane, or at the best case take a long time to converge.
Comment: This is the ntp.conf
server 0.north-america.pool.ntp.org
server 1.north-america.pool.ntp.org
server 2.north-america.pool.ntp.org
server 3.north-america.pool.ntp.org

server  127.127.1.0     # local clock
fudge   127.127.1.0 stratum 10

restrict 127.0.0.1
Comment: Also, ntp master on the cisco switch. I don't have that command available. The switch is a C3750 v12.2
Comment: Thanks again, I finaly got it to sync. I ended up making sure my NTPD server had a master selected, then I did a reload on the Cisco Switch.
Comment: Good to hear!  Rarely do you want an internal switch to actually be a NTP master - its more useful for testing than anything.  Generally you want your master to be an atomic clock or something useful :)


Finding polynomial without constant term that commutes with $f(x)=x^3+3x$

Question: Consider the polynomial $f(x)=x^3+3x$ over $\mathbb{Z}$.
I am trying to find a polynomial $g(x)$ $(\neq f^{\circ n})$ of any degree (or series) without constant term which commutes with $f$ (or any iteration $f^{\circ n}, ~n \geq 1)$ under composition.
Trivially, any $g(x)=x$, is another polynomial (or series) commutes with $f(x)$.
By hand it seems to be laborious.
Suppose I start with an investigation if there are degree $2$ polynomial $g(x)=ax+bx^2$ such that $f \circ g=g\circ f$. Then
\begin{align}
&f(g(x))=f(ax+bx^2)=3(ax+bx^2)+(ax+bx^2)^3=3ax+3bx^2+a^3x^3+3a^2bx^4+3ab^2x^5+b^3x^6, \\
&g(f(x))=g(x^3+3x)=a(x^3+3x)+b(x^3+3x)^2=3ax+ax^3+bx^6+6bx^4+9bx^2
\end{align}
Comparing both equations, we get $b=0$ and $a=a^3 \Rightarrow a=\pm 1$. In this case $g(x)=\pm 1$, the trivial one.
Suppose I start with an investigation if there are degree $3$ polynomial $g(x)=ax+bx^2+cx^3$ such that $f \circ g=g\circ f$. Then
\begin{align}
&f(g(x))=f(ax+bx^2+cx^3)=3(ax+bx^2+cx^3)+(ax+bx^2+cx^3)^3=3ax+3bx^2+3cx^3+c^3x^9+3bc^2x^8 \hspace{3cm}+(3ac^2+3b^2c)x^7+(6abc + b^3)x^6 + (3a^2c + 3ab^2)x^5 + 3a^2bx^4 + a^3x^3, \\
&g(f(x))=g(x^3+3x)=a(x^3+3x)+b(x^3+3x)^2+c(x^3+3x)^3=3ax+ax^3+2bx^6+6bx^4+9bx^2+cx^9+9cx^7+27cx^5+27cx^3
\end{align}
Comparing both sides we get $b=0$ and the following equations:
\begin{align}
a^3-a=24c, \\
a^2c=9c, \\
3ac^2=9c,\\
c^3=c.
\end{align}
Solving these, we see $c^3=c$ and $3ac^2=a^2c$. These two gives us $c=0$ or $c=\pm 1$. If $c \neq 0$, then $a=\pm 3$. Thus $g(x)=\pm (3x+ x^3)$, which is equivalent to $f(x)$ upto signs.
Suppose I start with an investigation if there are degree $4$ polynomial $g(x)=ax+bx^2+cx^3+dx^4$ such that $f \circ g=g\circ f$. Then it becomes laborious.
Is there any way to find non-trivial $g$ with the help of PARI/GP or SAGE ?
Edit 1: According to the hints given by @achille hui, I have found that $g(x)=-5x-5x^3-x^5$  commutes with $x^3+3x$. However, I am looking for an polynomial whose first degree coefficient is $3$ or multiple of $3$. I would appreciate one such example.
Edit 2:  But I need to find the polynomial with degree one coefficient, a multiple of $3$ and it is certainly possible as $f$ commutes with its iteration and each iteration has the degree one coefficient , a multiple of 3
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/132539/discussion-on-question-by-learner-finding-polynomial-without-constant-term-that).
Answer: We have $$f(x):=x^3+3x$$ and you already found $$h(x)=x^5+5x^3+5x$$ with $$h(f(x))=f(h(x))$$
but the coefficient of $x$ of $h$ is not divisible by $3$. But $$g(x)=h(f(f(x)))$$
has this property because
$$g(x)=h(f(f(x)))=f(h(f(x))=(h(f(x))^3+3(h(f(x))$$
and the lowest non vanishing  power of $(h(f(x))^3$ is $x^3$ and all coefficients of $x$ in $3(h(f(x))$ are divisible by $3$.
And
$$g(f(x))=h(f(f(f(x)))=f(h(f(f(x)))=f(g(x))$$
(I missed that g(x):=h(f(x)) already has the required property- It is equal to the degree 15 polynomial I calculated in the second part of this post)
The polynomial $g(x)$ is
$${{x}^{45}}+45 {{x}^{43}}+945 {{x}^{41}}+12300 {{x}^{39}}
\\+111150 {{x}^{37}}+740259 {{x}^{35}}+3764565 {{x}^{33}}+14945040 {{x}^{31}}\\
+46955700 {{x}^{29}}+117679100 {{x}^{27}}+236030652 {{x}^{25}}+378658800 {{x}^{23}}\\
+483841800 {{x}^{21}}+488494125 {{x}^{19}}+384942375 {{x}^{17}}+232676280 {{x}^{15}}\\
+105306075 {{x}^{13}}+34512075 {{x}^{11}}+7811375 {{x}^{9}}+1138500 {{x}^{7}}\\
+95634 {{x}^{5}}+3795 {{x}^{3}}+45 x$$
which can be factored to
$$x\, \left( {{x}^{2}}+3\right) \, \left( {{x}^{4}}+5 {{x}^{2}}+5\right) \, \left( {{x}^{6}}+6 {{x}^{4}}+9 {{x}^{2}}+3\right) \,\\
 \left( {{x}^{8}}+7 {{x}^{6}}+14 {{x}^{4}}+8 {{x}^{2}}+1\right) \, \\
\left( {{x}^{24}}+24 {{x}^{22}}+252 {{x}^{20}}+1519 {{x}^{18}}\\
+5796 {{x}^{16}}+14553 {{x}^{14}}+24206 {{x}^{12}}+26169 {{x}^{10}}\\
+17523 {{x}^{8}}+6623 {{x}^{6}}+1182 {{x}^{4}}+72 {{x}^{2}}+1\right) $$
Here is a smaller one
${{x}^{15}}+15 {{x}^{13}}+90 {{x}^{11}}+275 {{x}^{9}}+450 {{x}^{7}}+378 {{x}^{5}}+140 {{x}^{3}}+15 x$
I calculated some polynomials with Maxima. The following commute with $f$ and are the only one with nonnegative leading coefficient and a highest power less or equal $15$:
$$0$$
$$x$$
$$x^3+3x$$
$$x^5+5x^3+5x$$
$$x^7+7x^5+14x^3+7x$$
$${{x}^{9}}+9 {{x}^{7}}+27 {{x}^{5}}+30 {{x}^{3}}+9 x$$
$${{x}^{11}}+11 {{x}^{9}}+44 {{x}^{7}}+77 {{x}^{5}}+55 {{x}^{3}}+11 x$$
$${{x}^{13}}+13 {{x}^{11}}+65 {{x}^{9}}+156 {{x}^{7}}+182 {{x}^{5}}+91 {{x}^{3}}+13 x$$
$${{x}^{15}}+15 {{x}^{13}}+90 {{x}^{11}}+275 {{x}^{9}}+450 {{x}^{7}}+378 {{x}^{5}}+140 {{x}^{3}}+15 x$$
Note that
$${{x}^{9}}+9 {{x}^{7}}+27 {{x}^{5}}+30 {{x}^{3}}+9 x=f(f(x))$$
and
$${{x}^{15}}+15 {{x}^{13}}+90 {{x}^{11}}+275 {{x}^{9}}+450 {{x}^{7}}+378 {{x}^{5}}+140 {{x}^{3}}+15 x = h(f(x))$$
where $$h(x)=x^5+5x^3+5$$
If we call these polynomials (excluding 0) $h_1,h_3,h_5,\ldots, h_{15}$, so the index $i$ of $h_i$ is the degree of the polynomials, the following holds:
$$h_i(x)=(x^2+2)h_{i-1}(x)-h_{i-2}(x)$$

Here is an online version of Maxima. This is how I calculated the coefficients of $h_9$ by comparing the coefficients of $(f(g(x))$ and $g(f(x))$ N:9 is the degree of the polynomial g(x). The statement starting with empty checks if all coefficients of the difference $(f(g(x))-g(f(x))$ become $0$. If the result of this statement is false, the solution is invalid. This happens if we choose $N$ and even number.
f(x):=x^3+3*x;
N:9;
g(x):=x^N+sum(a[i]*x^(i-1),i,1,N);
d:f(g(x))-g(f(x)),expand$
coeff_list:makelist(coeff(d,x,i),i,3*N,0,-1)$
eqn_list:makelist(coeff_list[i],i,2,N+1)$
var_list:makelist(a[i],i,1,N)$
solutions:solve(eqn_list,var_list);
emptyp(sublist(coeff_list,lambda([t], is(t#0)))),solutions;
expression:g(x);
expression,solutions;

Here is the same algorithm implemented as SmPy scirpt.

These polynomials are related to Chebyshev Polynomials  as some commenters pointed out.
In the comments alex.jordan linked to A082985  and Lubin mentions the comments of achillehui of the OPs questions, which contains references to a paper  on this topic by F.J.Ritt, Permutable Rational Functions.
Comment: These are Čebyšev polynomials of some sort. It's Ritt's Theorem, referenced by @achillehui.
Comment: See https://oeis.org/A082985.
Comment: @learner I seems that the number of terms becomes too large to be handled by the program, In you case your  polynomial is f(f(x)), where f(x)=x^3+6*x^2+9*x, so you can try to find a g, such that g(f(x))=f(g(x)) and this g is commutative with your polynomial too, The Maxima command `polydecomp(x*(x+3)^2*(x*(x+3)^2+3)^2,x)` will calculate f.
Comment: Ahh! It is excellent. I already found out the f(f(x)) one. But you found lots. I really appreciate your help
Comment: @mirace173, just one comment. You have created $g(x)=9x+30x^3+27x^5+9x^7+{{x}^{9}}$. Let $h(x)=x^m, \ m \geq 2$. Can you help me to create another polynomial $q(x)$ such that $(g(x))^m=q(x^m)$. For $m=1$, it is trivial taking $g(x)=q(x)$. But for $m \geq 2$, I don't know
Comment: @learner I think this should be a new question an I think I am not able to help you.
Comment: @miracle173, thanks a lot. It was very helpful answer. The `code` was beautiful. I just checked by running
Comment: @miracle173, you mean $h_9$ not $H_9$
Comment: @miracle173, I tried to find out a polynomial which commutes with $x^9+18x^8+135x^7+546x^6+1287x^5+1782x^4+1386x^3+540x^2+81x$ using your Maxima code, but not giving. Can you please look into it ? Thanks
Comment: @learner What is the purpose of all these polynomials? Why do you need them?
Comment: @miracle173, I am constructing a commuting family of polynomials and do some theoretical study that is in my mind. Your answer was very helpful and I can start my study once I know a polynomial $h(x)$ that commutes with $x (x+3)^2 \left(x (x+3)^2+3\right)^2$. I tried with your Maxima code but failed. Can you help me just once more ? Thanks
Comment: @miracle173, Thanks. I used your trick to ask Maxima to give a polynomial which commute with $x^3+6x^2+9x$  and I got $g$ and this $g$ commutes with $f(f(x))$, the polynomial in my question. Thanks a lot. But can you tell me why did you wrote the command `polydecomp`, i didn't use it and also don't know how to use it.
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/132560/discussion-between-miracle173-and-learner).


Are truth tables valid for universal statements? Why or why not?

Question: I'm reading the book on Discrete Mathematics by Kevin Ferland. In Section 1.5, he says truth tables are not an option for statements involving universal quantifiers.
It seems to me that a statement such as "$\forall\ x \in \mathcal{U}, p(x)$" is either true or false always. I can think of examples: "Any rational number is real." This is a universal statement, and it is true.
Is it possible to choose a universal set $\mathcal{U}$ and condition $p$ so that "$\forall\ x \in \mathcal{U}, p(x)$" does not evaluate to a logical statement (something that is either true or false, but not both)? If so, can you please give a concrete example? If not, why then can I not create a truth table, and going further, why can't I validate argument forms using the truth table?
As an example, let's try to validate the following argument form using a truth table.
\begin{align*}
\forall\ x \in \mathcal{U}, p(x)\vee q(x)\\
\forall\ x \in \mathcal{U}, \neg p(x)\\
\therefore, \forall\ x \in \mathcal{U}, q(x)
\end{align*}
So, we need to show that whenever the premises are both true, the conclusion is also true. Since it's hard to write $\forall$ in the table, assume each of the columns is preceded by $\forall\ x \in \mathcal{U}$. In other words, each statement is universal.
<code>p(x)  q(x)  p(x) v q(x)  ~p(x)  q(x)
----+-----+------------+------+-----
  T |  T  |    T       |   F  |  T
  T |  F  |    T       |   F  |  F
  F |  T  |    T       |   T  |  T
  F |  F  |    F       |   T  |  F
</code>
Now, whenever the premises are both true, the conclusion is true. So one would think that the argument form is valid. And indeed, it is valid. You can certainly use universal instantiation and proofs of basic argument forms (which CAN be validated with truth tables) to show that the argument form is valid. This is the way that makes sense to me.
What confuses me is why is the above method flawed? (In general).
Any explicit examples you can give me would greatly help! Thanks in advance.
Comment: How does your truth table method distinguish between $(\forall x\in\mathcal U)\,\neg p(x)$ and $\neg(\forall x\in\mathcal U)\, p(x)$?
Comment: Let $\mathcal U=\Bbb R$ and for all $x\in \mathcal U$ let $p(x)$ mean $x\leq 0$ and $q(x)$ mean $x>0$. The third column corresponds to $\forall x\in \Bbb R(x\leq 0\lor x>0)$ which is a logical truth (something which is always true). However $\forall x\in \Bbb R(x\leq 0)\lor \forall x\in \Bbb R(x>0)$ isn't true, in fact it's false, because clearly each of the atoms is false. I really dislike what I'm saying because this isn't propositional calculus, you can't just give truth values to statements as you wish. They have truth values on their own. I'm just trying to convince you it doesn't work.
Comment: Since it's not easy to write all that in the way I formed the table, let's just say $\neg p(x)$ means $\forall\ x \in \mathcal{U}, \neg p(x)$.
Comment: @gnat79 What rules are you applying to get the third column? Note that once you add universal quantifiers, the disjunction won't work the same way.-
Comment: Git Gud, can you explain why they don't work the same way? I think you are getting at the problem I'm having.
Comment: @Git Thank you for the concrete example. I can see what you mean now.
Answer: Suppose $\mathcal{U}$ was some arbitrary set of infinite cardinality.
I think the issue that the book is touching on is that for some arbitrary statement containing a universal quantifier (like $\forall x \in \mathcal{U} \ p(x)$), although it does have a truth value, you cannot use a truth table to find that value directly by testing all values of $x$. (since you would have to have an infinitely large table to get all of the cases)
What made your example doable with a truth table was that in that particular case, you did not have to consider every possible $x$ (which could be infinite), you only needed to care about $p(x), q(x), p(x) \vee q(x)$, which can only take on finitely many values.
Comment: Thanks. I don't see how it matters how you test the statement. Even if you need infinitely many values of $x$ to test it (which I agree, you do), it is still either true or false universally. I think... Of course, that depends on the universe, but once you pick it, and assuming you are super human, you can determine it. So no matter what, (and depending on the universe), you can always determine the truth value of the statement.

With my truth table, I don't mean "fix a particular $x$", I mean the statements to be universal. I was not clear about that.
Comment: "Of course, that depends on the universe, but once you pick it, and assuming you are super human, you can determine it." 1) You still haven't stated *how* that determination process would go and 2) we're not super human, so why bother pretending we are?
Comment: "With my truth table, I don't mean "fix a particular x", I mean the statements to be universal. I was not clear about that." I never said fix a particular $x$. What I was pointing out is that you took a set of infinite cardinality, and in that instance can boil it down into a finite number of cases. That's not something that is a possibility in the general case.
Comment: It doesn't seem to me that the number of things in the set affects the truth value of the statement, even if it is a universal statement. If there is a particular $x$ so that $p(x)$ is not true, then the statement $\forall x \in \mathcal{U}, p(x)$ is false. On the other hand, no matter the cardinality of $\mathcal{U}$, if all $x \in \mathcal{U}$ make $p(x)$ true, then the statement $\forall\ x \in \mathcal{U}, p(x)$ is true. I appreciate your efforts; unfortunately this isn't sinking in for me. It seems I'm missing a subtlety.
Comment: The number of things in the set doesn't affect whether or not the statement can be true or false; but it *does* affect how the heck you can find out. If the set is finite, you can just test for every member of the set. Such a method doesn't work if the set has an infinite number of elements.
Comment: How this applies to truth tables is that barring some other statement that makes evaluation much simpler, you can't avoid having to test every member of the set.
Answer: The only problem I see with this is that it seems you might think it's okay for $\mathcal{U}$
to be the universe.
Are you in fact saying that?
What do you mean by a "universal set?"
If instead $\mathcal{U}$
is some other set guaranteed by the axioms of ZFC,
then the axiom of specification guarantees that for any formula $p$
there exists a set $S=\{x\in\mathcal{U}\mid p(x)\}$.
It is then either true or false that $S=\mathcal{U}$,
and the trueness or falsehood if this equation is equivalent to that of your statement $\forall x\in\mathcal{U}:p(x)$.
Upon making the desired truth table then, we are merely considering the truth values that result from varying $p$ and $q$, not from varying $x$.
This puts us in exactly the same situation as we would be for an ordinary truth table, thus I don't see any problem. You just have to write it correctly.
Answer: Remember that FOL is stronger than propositional logic.  Ie. there are statements in FOL that can not be expressed in propositional logic.  Your statement is not one of these.
Consider
\begin{align*}
\forall\ x \in \mathcal{U}, p(x)\vee q(x)\\
\neg p(a)\vee\forall\ x\in\mathcal{U}, q(x)\\
\therefore q(a)
\end{align*}
What does your thruth table look like?


Como salvar no banco as opções de checkbox?

Question: Preciso salvar as frutas e os valores em campos diferente no banco"
PHP:
<?php
   session_start();
   //if (!isset($_SESSION["usuario"])){echo "";}
   include "funciones.php";
   date_default_timezone_set("America/Sao_Paulo");

   if (isset($_POST["edit_fruta_x"])){

      $_SESSION["idrelatorio"]=$_POST["relatorio"];//Se o usuário escolheu da lista um projeto     para diagnosticar, guardo o seu IDprojeto para referenciar
      $_SESSION["idbanca"]=$_POST["banca"];
      $_SESSION["idfruta"]=$_POST["fruta"];

      unset($_POST["fruta"]);

      lerbanca($_SESSION['idbanca']);//procura os dados da banca escolhida
      lerlocalizacao($_SESSION["idrelatorio"]);
   }

   else{
      $_SESSION["idrelatorio"]=$_POST["relatorio"];
      $_SESSION["idbanca"]=$_POST["banca"];

      lerlocalizacao($_SESSION["idrelatorio"]);
      unset($_SESSION['idfruta']);
      unset($_SESSION['fruta']);
   }

?>

HTML:

<form class="form-signin" action='salvafrutas.php' method="post">

bancas de frutas

1. Lista de Frutas

1.Tipo de frutas

Características	valores

1. uva	<input id="uva" type="checkbox"     name="comportamento[]" value="6"  <?php if(isset($_SESSION['comportamento'])){echo (strpos($_SESSION['comportamento'],'6')!==false) ? 'checked="checked"' : '';}?> onclick="apaga_nao1(this)"> 6

2. banana	<input id="banana" type="checkbox" name="comportamento[]" value="0" <?php if(isset($_SESSION['comportamento'])){echo (strpos($_SESSION['comportamento'],'0')!==false) ? 'checked="checked"' : '';}?> onclick="apaga_nao1(this)"> 0

3. maça	<input id="maça" type="checkbox" name="comportamento[]" value="3" <?php if(isset($_SESSION['comportamento'])){echo (strpos($_SESSION['comportamento'],'3')!==false) ? 'checked="checked"' : '';}?> onclick="apaga_nao1(this)"> 3

4. pera	<input id="pera" type="checkbox" name="comportamento[]" value="4" <?php if(isset($_SESSION['comportamento'])){echo (strpos($_SESSION['comportamento'],'')!==false) ? 'checked="checked"' : '';}?> onclick="apaga_nao1(this)"> 4

<input id='btgravar' type='image' src="salvar.png" title='SALVAR' width='70' height='70'/>
</form>

Comment: Boa, ficou mais claro! Já dei o meu voto para reabrir. O que quer gravar na BD? Quando tem no HTML `name="comportamento[]"` isso vai fazer com que no PHP chegue uma array onde tem valores do `value` do HTML. Ou seja, se alguém escolher todas as checkboxes vai ter algo como `array(6, 0, 3,4);`, é isso que quer guardar na BD ou quer o nome da fruta também? Pode explicar melhor toda a informação que quer salvar nd BD desse formulário?
Comment: Você precisa fazer um array com o nome das frutas, interligado ao código que você atribuiu no value do seu select html.  Exemplo: $frutas = array(0=>"banana", 3=>"maca", 4=>"pera", 6=>"uva"); $nomedafruta = $frutas[$_POST["comportamento"]]; (apenas exemplo, é necessário fazer um foreach no $_POST["comportamento"] pra poder pegar todos os marcados...)
Comment: Então @MarianaGomes - Dentro do foreach, se você tiver feito a array $frutas como eu disse (declare no inicio do seu php), você terá a fruta com $frutas[$value]... Se você quer o conteúdo separado por /, voce precisa fazer:
    $comporta['comportamento'] .= $value.":".$frutas[$value]."/";
Dessa forma voce terá o numero selecionado, dois pontos (:), e o nome da fruta, seguido de uma barra (/).
Comment: Bom dia Mariana, pode responder á minha pergunta/comentário em cima?
Comment: @Sergio, eu preciso salvar as frutas e os valores, mas em campos diferentes no banco de dados.
Answer: Tanto campos CheckBox quanto campos RadioButton servem de um mesmo proposito, eu tenho um exemplo que faço da seguinte forma:
HTML:
DES2 <input type="checkbox" name="motivo[]" id="DES2" onclick="checar(this.id)" value="0" />
DES3 <input type="checkbox" name="motivo[]" id="DES3" onclick="checar(this.id)" value="0" />
DES4 <input type="checkbox" name="motivo[]" id="DES4" onclick="checar(this.id)" value="0" />

JS:
function checar(idObj) {
    val = idObj;
    idObj = "#" + idObj;
    if ($(idObj).is(':checked')) {
        $(idObj).val(val);
    } else {
        $(idObj).val(0);
    }
}

Como é enviado ao dar submit no formulário:

Explicando... eu envio em forma de array e faço o tratamento no PHP como segue abaixo...
PHP:
    $_POST["DES2"] = 0;
    $_POST["DES3"] = 0;
    $_POST["DES4"] = 0;

    $checkBox = $_POST['motivo'];
    if ($checkBox) {
        $i = 0;
        foreach ( $checkBox as $value ) {
            switch ($value) {
                case "DES2" :
                    $_POST["DES2"] = 1;
                    break;
                case "DES3" :
                    $_POST["DES3"] = 1;
                    break;
                case "DES4" :
                    $_POST["DES4"] = 1;
                    break;
                default :break;
                $i++;
            }
        }
    }

O modo como você salva no banco fica a seu critério....
Existem outros modos de fazer isso, as vezes até mais fáceis... porém depende da sua implementação, dos padrões da empresa e talz


The equation of a curve which is almost similar to Gaussian curve (normal distribution curve) with $2$ asymptotes

Question: We know that the equation of the following curve could be of the form $y=A+Be^{ax^2+bx+c}$ where $A,B,a,b,c$ are constants.

Which has one horizontal asymptote.

I have (almost) same kind of curves (Maybe same as the above one but in more general form). The following has two horizontal asymptotes. What could be its equation?

Please suggest me an explicit (& not piecewise) function.

Any help would be appreciated. THANKS!
Answer: You can add an s-shaped function.
E.g.
$$5e^{-x^2}+\tanh(2x+x^3).$$
Make sure that it tends to its asymptotes faster than the Gaussian, to avoid a local minimum.
Answer: Here is a solution obtained by adding to a gaussian function a modified $\arctan \ (= \tan^{-1})$ function, namely
$$f(x)=e^{-x^2}+a \arctan(b(x+c))$$
with $a=0.05;b=10;c=0.7.$
I have featured in red the derivative of this function.


How do i count and sum the values from the database

Question: I have a table in mysql which holds the values in integers, my table is something like this.

I want to sum up the values of a particular column, for example i want to calculate the total amount, total cashpaid and total balance. hwo do i do it?
Answer: Use SUM() function of MySQL like this:
select SUM(amount) from tablename;
select SUM(cashpaid) from tablename;
select SUM(balance) from tablename;

OR you can group them into one:
select SUM(amount), SUM(cashpaid), SUM(balance) from tablename;

Answer: if you want to do it in one single query:
SELECT SUM(amount) as total_amount, SUM(cashpaid) as total_paid,SUM(balance) as total_balance FROM tablename;

to count element use COUNT()
SELECT COUNT(*) FROM tablename;

it's better to use aliases for the column names when using this functions.
Comment: is it? i will be considering to use the aliases then. thank you for the tip.
Answer: Try out this:
select SUM(amount) AS total_amount, SUM(cashpaid) AS total_cashpaid, SUM(balance) AS total_balance  from tablename;

Answer: try
select sum(amount), sum(cashpaid), sum(balance) from tablename

Answer: For counting the total number of records use count() function.
like:
select count(amount) from table_name;

It will return from above table in your question 3.
For Sum Use SUM() in SELECT query.
Like:
select SUM(amount) as total_amount,SUM(cashpaid) as total_cash_paid,SUM(balance) as total_balance from table_name;

after as is your new column name which will automaticaly create after executing of query.


Como uso variáveis dentro desse código PHP + MySQLi?

Question: Meu código retorna o seguinte erro:

Parse error: syntax error, unexpected T_VARIABLE in /home/a2015539/public_html/envio.php on line 28

O código é este:
<code>// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "INSERT INTO cadastro (nome, sexo, dia, mes, ano)
VALUES ('"$nome"','"$sexo"','"$dia"','"$mes"','"$ano"')";

if ($conn->query($sql) === TRUE) {
echo "<script type= 'text/javascript'>alert('New record created successfully');</script>";
} else {
echo "<script type= 'text/javascript'>alert('Error: " . $sql . "<br>" . $conn->error."');</script>";
}

$conn->close();
}
</code>
Answer: Erro de digitação. Você não concatenou os valores.
Solução:
<code>$sql = "INSERT INTO cadastro (nome, sexo, dia, mes, ano)
VALUES ('".$nome."','".$sexo."','".$dia."','".$mes."','".$ano."')";
</code>
Vale dizer que os dados precisam ser sanitizados antes da inserção:
<code>$nome_sanitizado = $conn->real_escape_string( $nome );
</code>
E ao inserir algo como:
<code>"..... VALUES ('".$nome_sanitizado."',
</code>
Isto evita corrupção da query em valores com aspas e caracteres especiais, e minimiza a chance de Injeção de SQL
Comment: Obrigado pela ajuda @Bacco
Answer: altere essa linha
<code>$sql = "INSERT INTO cadastro (nome, sexo, dia, mes, ano)
VALUES ('"$nome"','"$sexo"','"$dia"','"$mes"','"$ano"')";
</code>
para
<code>$sql = "INSERT INTO cadastro (nome, sexo, dia, mes, ano)
VALUES ('".$nome."','".$sexo."','".$dia."','".$mes."','".$ano."')";
</code>
os pontos servem para unir suas variáveis com as strings
Comment: Obrigado pela ajuda @Italo Rodrigo


Is it appropriate to use Pearson Correlation Coefficient when data has repeated observations per unit?

Question: Goal
I want to find the strength of relationship (correlation) between two variables measured for 40 drivers.
Data
My dataset has 2 variables, tau_inv = a sensory quantity and ED_bpf = brake pedal force. These are measured repeatedly per driver for 40 drivers. participant name is also included:
    > dput(df)
structure(list(participant = structure(c(33L, 33L, 33L, 17L,
17L, 10L, 4L, 4L, 30L, 29L, 39L, 25L, 37L, 37L, 13L, 13L, 11L,
11L, 11L, 19L, 32L, 6L, 26L, 26L, 27L, 27L, 21L, 21L, 9L, 9L,
18L, 7L, 7L, 38L, 14L, 14L, 35L, 23L, 40L, 40L, 31L, 28L, 16L,
16L, 34L, 34L, 3L, 3L, 12L, 36L, 36L, 15L, 1L, 1L, 1L, 8L, 8L,
2L, 2L, 2L, 24L, 20L, 20L, 5L, 22L), .Label = c("driver: 01",
"driver: 02", "driver: 03", "driver: 04", "driver: 05", "driver: 06",
"driver: 07", "driver: 08", "driver: 09", "driver: 10", "driver: 11",
"driver: 12", "driver: 13", "driver: 14", "driver: 15", "driver: 16",
"driver: 17", "driver: 18", "driver: 19", "driver: 20", "driver: 21",
"driver: 22", "driver: 23", "driver: 24", "driver: 25", "driver: 26",
"driver: 27", "driver: 28", "driver: 29", "driver: 30", "driver: 31",
"driver: 32", "driver: 33", "driver: 34", "driver: 35", "driver: 36",
"driver: 37", "driver: 38", "driver: 39", "driver: 40"), class = "factor"),
    tau_inv = c(0.08, 0.11, 0.16, 0.1, 0.17, 0.11, 0.12, 0.19,
    0.19, 0.13, 0.09, 0.17, 0.13, 0.14, 0.08, 0.11, 0.08, 0.16,
    0.22, 0.19, 0.16, 0.21, 0.13, 0.24, 0.11, 0.11, 0.09, 0.14,
    0.15, 0.17, 0.13, 0.14, 0.19, 0.11, 0.17, 0.24, 0.15, 0.19,
    0.07, 0.13, 0.25, 0.14, 0.13, 0.22, 0.11, 0.2, 0.16, 0.21,
    0.12, 0.13, 0.18, 0.13, 0.05, 0.09, 0.14, 0.16, 0.2, 0.07,
    0.14, 0.2, 0.23, 0.12, 0.16, 0.16, 0.15), ED_bpf = c(3.8,
    3, 5.5, 1, 5.1, 8.8, 4.1, 12.6, 12.5, 10.8, 5.4, 8, 5.4,
    6.6, 3.7, 4.8, 4.2, 3.9, 5.9, 6.8, 11.2, 9.9, 7.2, 8.5, 5.2,
    9, 5, 5.5, 5.4, 11, 6.9, 5, 9.2, 7.2, 6.1, 10.6, 9.5, 8.8,
    3.3, 8.8, 10, 7.5, 3.4, 7.1, 4, 5, 5.3, 7.9, 10.8, 7, 5.5,
    7.8, 4.1, 3.4, 7.8, 5.1, 7.6, 6.4, 3.6, 8.7, 11.4, 5.6, 7,
    13.3, 2.4)), row.names = c(NA, -65L), class = c("tbl_df",
"tbl", "data.frame"))

What I have done
I have estimated the pearson correlation coefficient as shown in the plot below:
library(ggplot2)
library(ggpubr)
  ggplot(data = df,
         aes(x = tau_inv,
             y = ED_bpf)) +
  geom_point(alpha = 0.5) +
  stat_smooth(method = "lm", se =F) +
  stat_cor(method = "pearson", label.x = 0.0025, label.y = 0)

Question
I am concerned that because there are multiple data points of the same driver (see the participant column), the pearson correlation coefficient might not be the best method to find the strength of the relationship. My concern is due to the reason that if I were to fit a regression model here, it is better to use linear mixed effects model than the simple linear regression model due to the repeated observatios.
So, my question is: Is it okay for me to use pearson correlation coefficient as I am using it here? Or should I use a different method?
Answer: It is your decision whether or not to be satisfied with the method, based on your domain knowledge.
Based on your "goal" description, here's what I would do if I were you: since I'm looking for the strength of the relationship between those 2 variables, I'm perfectly fine using the correlation coefficient. I'm considering each pair of data as a separate experiment. If some of the drivers "conducted" more than just one experiments for me, that's perfectly fine, those experiments are still valuable.
However, if you wanted to take into account who the actual driver is, that's a different story. For example, if you wanted to investigate which driver reacted faster (e.g. were they drunk or not while driving, in case they are even human), then you could compare the measurements and see who's reacting too slow even with strong sensory input.
Comment: Thanks. This makes sense. I am going ahead with the correlation coefficient.
Answer: If you're just calculating the statistical metric of the correlation, that statistical measure is the same regardless of how the data is generated. However, there can be problems with further interpretations of that metric. For instance, I see that a p-value of 0.000009 is included on your graph. The p-value depends on both the correlation coefficient and the number of observations, and assumes that those observations are independent. Since they aren't independent, the p-value is not reliable. A related issue is Simpson's paradox.
An example of how using simple correlation would lead to too strong of a conclusion: suppose you're looking the correlation between exercise and diet, and you look at just two people (say, Alice and Bob). Normally, calculating the p-value for $n=2$ is useless; you're always going to get $r=1$, so an $r$ of $1$ is not significant. If you look at these two people over a thousand days, and record this as $n = 2000$, you're going to be overestimating the significance. Any difference between Alice and Bob is going to look like a correlation between exercise and diet, when it's really just a difference between Alice and Bob.
If Alice does a lot of exercise and doesn't eat much, and Bob eats a lot and doesn't exercise much, then it's going to look like there's a negative correlation between exercise and diet. The stronger the difference between Alice and Bob, compared to the differences within each person's individual numbers, the stronger the correlation will appear. There's going to be a dependence between the data points in that if a datapoint has high exercise, it's probably one of Alice's data points, and thus probably has low diet.
Comment: Thanks. I better not include the p-value then.
Comment: I would add that considering experiments done by the same driver as independent or dependent is also a decision influenced by business domain knowledge, not just quantitative methodology. I have a strong intuition that in your case, these experiments would still satisfy the criteria of independence.

Think of something like this: just because you have already measured one of the driver's data once, does that mean that the same driver's next data collection is compromised or biased? For example, does the driver know about it and next time, would be more careful
Comment: @BalázsPukli It's possible that the data is independent, but assuming that it's independent is no longer valid. The driver doesn't need to be "compromised". If each driver has their own mean for the two metrics, then their data will cluster around those means. I've edited to try to make that clearer.


cmake invalid numeric arguments

Question: Windows 10
VS2019
Cmake 3.20.5
https://github.com/ftexchange/ftx/tree/master/cpp
Whenever I try to run the cpp files (rest_test.cc), I would receive command line error D8021: invalid numeric argument '/Werror' etc. for many of the flags here
set(CMAKE_CXX_STANDARD 17)

set(CMAKE_CXX_FLAGS "-Wall -Werror -Wfatal-errors -Wpedantic -Wextra -Wmissing-include-dirs -Wconversion -Wsign-conversion -pthread")
add_compile_options(-Wall -Werror -Wfatal-errors -Wpedantic -Wextra -Wmissing-include-dirs -Wconversion -Wsign-conversion -pthread)

I'm not sure how to proceed
Comment: Because there is no argument `/Werror` in MSVC? You should remove it.
Answer: Those flags are for a GCC-compatible compiler, not MSVC. You'll have to remove them from the build you've encountered (or authored).
The reason for the "invalid numeric argument" is because MSVC numbers its warning levels. For example, to enable all (too many) warnings, you could pass /W4. MSVC tries to parse error as a number because it is expecting to find a flag like /W1 or /W3.
Such flags do not belong in the CMakeLists.txt file to begin with. Setting CMAKE_CXX_FLAGS is bad practice for exactly the reason you just experienced. Keep this in mind as you learn CMake: only things that are absolutely required to build your project belong in the CMakeLists.txt. Warning flags are not absolutely required.
Comment: "Setting `CMAKE_CXX_FLAGS` is a bad practice for exactly the reason you just experienced." - The only reason OP is experienced is that the project isn't prepared for MSVC, as it has no check for the compiler when adding the *compiler-specific* options. By itself, there is nothing bad in setting `CMAKE_CXX_FLAGS`. See e.g. [that question](https://stackoverflow.com/questions/45955272/modern-way-to-set-compiler-flags-in-cross-platform-cmake-project) about the proper ways for doing that in multiplatform manner.
Comment: @Tsyvarev - I completely disagree. I would love to buy you a coffee and talk about it sometime.
Comment: @Tsyvarev - I have commented on the answer you linked me to. The notion of a "compiler-specific" option goes down to the compiler _version_, not just its command-line syntax. Putting warnings (and especially warnings-as-errors) in the CMakeLists.txt (as opposed to a toolchain or preset) is a recipe for headaches.

cmake invalid numeric arguments


I can't delete property of result from mongoosejs findone

Question: I want result to be sent without password. Then I do:
Delete req.session.user.password
res.send(req.session.user)

Password still remains there. Why?
How can I delete a property that I don't want to response back?
Answer: You need to convert your mongoose user model object into a plain JavaScript object before deleting the password.
var user = req.session.user.toObject();
delete user.password;
res.send(user);


Using File chooser to get the absolute path of a file into a jTextField

Question: I have made an application to browse through files and get the absolute path of the file into a text field. although I can browse through files when i click the browse button the file path doesn't appear on the text field. Can you help me with identifying the error.
Thanks in advance
private void browse3ActionPerformed(java.awt.event.ActionEvent evt) {
        JFileChooser Chooser = new JFileChooser();
        Chooser.setMultiSelectionEnabled(true);
        Chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        int result = Chooser.showDialog(this,"Open/Save");
        if(result == JFileChooser.APPROVE_OPTION)
        {
            File file = Chooser.getSelectedFile();
            resultFilePath = file.getAbsolutePath();
         }

    }

Answer: Your error in next. You select file but you don't set its path to your JTextField. You need to use setText(String text) method of your textField. Read tutorial for TextFields. It will be looking like next:
 File file = Chooser.getSelectedFile();
 textField.setText(file.getAbsolutePath());

here textField its your JTextField for path of file.


Kendo ui grid with dropdownlists

Question: I have a kendo ui grid with dropdownlists in the cells. The problems is that I lose the selected row when somebody select a new value in a dropdownlist. Can somebody help me with this?
Comment: Not enough information to help you. Please post your view model and grid configuration.
Answer: What is probably happening is that the selection of an item in the DropDownList is changing the value on the bound data item. This causes the DataSource to fire a "change" event so hat the table knows it needs to update. The way the Kendo Grid is written, when it gets a change event from the DataSource, it recreates the table cells. I'm pretty sure the existing table cells get removed from the DOM and a new set added in its place. When this happens, the selection is getting removed.

One way to preserve the selected row would be to add a function handler to the grid's "change" event, and save the uid of the selected data item. Then on the "dataBound" event, you can re-select that row.
For example:
<code>var selectedUid;

$("#grid").kendoGrid({
    ...

    change: function () {
        selectedUid = this.select().data("uid");
    }

    dataBound: function () {
        if(selectedUid) {
            this.select($(this.element).find('tr[data-uid="' + selectedUid + '"]'));
        }
    }
});
</code>
Comment: Can you help me to put a callback? Is there possible to do something like that in Kendo?
Comment: I'm not sure what you mean. The function above is set as a callback to the `dataBound` event for the grid when it is passed in the options.

Kendo ui grid with dropdownlists


How to add a Google Maps containing GeoRss Feeds on a page - don't know exactly what module to use

Question: I have developed a Google maps following the example from https://developers.google.com/maps/documentation/javascript/examples/layer-georss but I am new to Drupal and I don't know how to include it on a page. Could someone please tell me what module should I use?
Some guidance would be very much appreciated!
Answer: Try to use GMap module. This module solve your issue.
How to use ?
If your issues not solved then try to use any of these modules :

Simple Google Maps
Google Maps Location

For GeoRSS try to use below module :

GeoRSS
Google Maps Tools
Comment: Thank you very much! I have tried the Gmap module right now, but the problem is that I can add locations but cannot add GeoRss feeds on the map.Maps Location Module also focuses on one location from what I understood. What else would you recommend?
Comment: check my updated answer. I hope this may help you.
Comment: Thank you, but the problem is that GeoRss and Google Maps Tools are not compatible with Drupal 7.x since only a version for 6.x is offered


What is the easiest way to find the inverse of the following block diagonal matrix?

Question: Consider, for $\sigma^2_u, \sigma^2_e > 0$, the matrix
$$\mathbf{X} = \begin{bmatrix}
\sigma^2_u+\sigma^2_e & & & \\
 & \sigma^2_u+\sigma^2_e\ \\
& & \sigma^2_u+\sigma^2_e & \sigma^2_u \\
& & \sigma^2_u & \sigma^2_u+\sigma^2_e
\end{bmatrix}$$
where all other entries are $0$. What is the easiest way to find the inverse of $\mathbf{X}$?
I thought about adjoining $\mathbf{X}$ to $\mathbf{I}_4$: $$\left[\begin{array}{cccc}
\sigma^2_u+\sigma^2_e & & & \\
 & \sigma^2_u+\sigma^2_e\ \\
& & \sigma^2_u+\sigma^2_e & \sigma^2_u \\
& & \sigma^2_u & \sigma^2_u+\sigma^2_e\end{array}\right|\left.\begin{array}{cccc}
1 &  & & & \\
  & 1 & & \\
  &   & 1 & \\
  &   &   & 1
\end{array}\right]$$
and thought about dividing each row by $\sigma^2_u+\sigma^2_e =: K$:
$$\left[\begin{array}{cccc}
1 & & & \\
 & 1\ \\
& & 1& \sigma^2_u/K \\
& & \sigma^2_u/K & 1\end{array}\right|\left.\begin{array}{cccc}
1/K &  & & & \\
  & 1/K & & \\
  &   & 1/K & \\
  &   &   & 1/K
\end{array}\right]$$
but I'm not sure how to proceed from here.
I am well-aware of this formula but would like to avoid it.
Comment: Just continue gaussian elimination as you would do it usually: the $(3,3)$ element will be the next pivot. When the left matrix is upper triangular, use backsubstitution, as usual (or row operations "upward").
Comment: @Jean-ClaudeArbaut Sorry, I've read about pivoting but am not familiar with the concept. Could you elaborate?
Answer: You got
$$\left[\begin{array}{cccc}
1 & & & \\
 & 1\ \\
& & 1& \sigma^2_u/K \\
& & \sigma^2_u/K & 1\end{array}\right|\left.\begin{array}{cccc}
1/K &  & & & \\
  & 1/K & & \\
  &   & 1/K & \\
  &   &   & 1/K
\end{array}\right]$$
Now do the row operation $Row_4\leftarrow Row_4-\sigma^2_u/K Row_3$:
$$\left[\begin{array}{cccc}
1 & & & \\
 & 1\ \\
& & 1& \sigma^2_u/K \\
& & 0 & 1-(\sigma^2_u/K)^2\end{array}\right|\left.\begin{array}{cccc}
1/K &  & & & \\
  & 1/K & & \\
  &   & 1/K & \\
  &   &  -\sigma^2_u/K^2 & 1/K
\end{array}\right]$$
Divide the last row by $1-(\sigma^2_u/K)^2=1/\lambda$
$$\left[\begin{array}{cccc}
1 & & & \\
 & 1\ \\
& & 1& \sigma^2_u/K \\
& & 0 & 1\end{array}\right|\left.\begin{array}{cccc}
1/K &  & & & \\
  & 1/K & & \\
  &   & 1/K & \\
  &   &  -\lambda\sigma^2_u/K^2 & \lambda/K
\end{array}\right]$$
Finally do the row operation $Row_3\leftarrow Row_3 - \sigma^2_u/KRow_4$
$$\left[\begin{array}{cccc}
1 & & & \\
 & 1\ \\
& & 1& 0 \\
& & 0 & 1\end{array}\right|\left.\begin{array}{cccc}
1/K &  & & & \\
  & 1/K & & \\
  &   & 1/K+\lambda\sigma^4_u/K^3 & -\lambda\sigma^2_u/K^2\\
  &   &  -\lambda\sigma^2_u/K^2 & \lambda/K
\end{array}\right]$$
And you are done. Notice that even without doing the gaussian elimination on the full matrix, it would have been possible to anticipate that only the lower right corner would be modified. Hence it's equivalent to invert only this $2\times2$ matrix, and to invert the other diagonal elements separately. Or, if you prefer, to invert the blocks separately (there are two $1\times1$ blocks and one $2\times 2$).
Answer: If
$\mathbf{X} =
\begin{bmatrix}
      A & & & \\
      & B & & \\
      & & C & \\
      & & & D
\end{bmatrix}$ is a block-diagonal matrix, then
$\mathbf{X}^{-1} =
\begin{bmatrix}
        A^{-1} &        &        &        \\
               & B^{-1} &        &        \\
               &        & C^{-1} &        \\
               &        &        & D^{-1}
\end{bmatrix}$
So
$\mathbf{X}^{-1} =
\begin{bmatrix}
\dfrac{1}{\sigma^2_u+\sigma^2_e} & & &
\\
 & \dfrac{1}{\sigma^2_u+\sigma^2_e}
\\
 & &
     \dfrac{\sigma_u^2+\sigma_e^2}{\sigma_e^2(2\sigma_u^2+\sigma_e^2)}
 & -\dfrac{\sigma^2_u}{\sigma_e^2(2\sigma_u^2+\sigma_e^2)}
\\
 &
 & -\dfrac{\sigma^2_u}{\sigma_e^2(2\sigma_u^2+\sigma_e^2)}
 & \dfrac{\sigma_u^2+\sigma_e^2}{\sigma_e^2(2\sigma_u^2+\sigma_e^2)}
\end{bmatrix}$
where
$\begin{bmatrix}
    \sigma^2_u+\sigma^2_e & \sigma^2_u \\
    \sigma^2_u & \sigma^2_u+\sigma^2_e
\end{bmatrix}^{-1}
=
\dfrac{1}{\sigma_e^2(2\sigma_u^2+\sigma_e^2)}
\begin{bmatrix}
    \sigma^2_u+\sigma^2_e & -\sigma^2_u \\
    -\sigma^2_u & \sigma^2_u+\sigma^2_e
\end{bmatrix}$


find jquery event origin instance caller

Question: Don't know if the title of this question is correct.
Anyway, I'll try.
Question:
In a js library I build function/objects in this way:
    function demo(o) {
        var d ={
            $table:$('#'+o.tableId)
            // other parameters
        };
        $.extend(this, {
            param1: false,
            myMethod: function () {
                d.$table.on("click", "tbody td", {org: this}, function (ev) {
                    ev.data.org.tabEvent({
                        action: $(this).data("action"),
                        cell: $(this).data("cell")
                    });
                });
                return this;
            },
            tabEvent:function(ev){
                // here I can manage the data from the demo instance
            },
            init:function () {

            }
        });
    }

    var demoInstance = new demo({
        tableId: "tab1"
    });

demoInstance.init();

My target is to work form the same instance in every situation.
So, in "myMethod" I hanged the "click" event on a table and every event is returned to original instance by means of the passed object:
ev.data.org.
Is this a correct writing style?
Have you any smart solution?
Answer: Given the purpose of your code it would make more send to create it as a jQuery plugin, which you instantiate on the elements required. Try this:

$.fn.demo = function() {
  let init = function() {
    // perform whatever initialisation actions you need here...
  }

  let tabEvent = function() {
    // here I can manage the data from the demo instance
    var $cell = $(this);
    console.log($cell.data('action'), $cell.data('cell'));
  }

  init();
  return this.on('click', 'tbody td', tabEvent);
}

$('table').demo();

      Table 1 / Cell 1

      Table 2 / Cell 2


How to make calculations on hexadecimal numbers with awk?

Question: I have a file containing a list of hexadecimal numbers, as 0x12345678 one per line.
I want to make a calculation on them. For this, I thought of using awk. But if printing an hexadecimal number with awk is easy with the printf function, I haven't find a way to interpret the hexadecimal input other than as text (or 0, conversion to integer stops on the x).
awk '{ print $1; }'                     // 0x12345678
awk '{ printf("%x\n", $1)}'             // 0
awk '{ printf("%x\n", $1+1)}'           // 1                 // DarkDust answer
awk '{ printf("%s: %x\n", $1, $1)}'     // 0x12345678: 0

Is it possible to print, e.g. the value +1?
awk '{ printf(%x\n", ??????)}'          // 0x12345679

Edit: One liners on other languages welcomed! (if reasonable length ;-) )
Answer: In the original nawk and mawk implementations the hexadecimal (and octal) numbers are recognised. gawk (which I guess you are using) has the feature/bug of not doing this. It has a command line switch to get the behaviour you want: --non-decimal-data.
echo 0x12345678 | mawk '{ printf "%s: %x\n", $1, $1 }'
0x12345678: 12345678

echo 0x12345678 | gawk '{ printf "%s: %x\n", $1, $1 }'
0x12345678: 0

echo 0x12345678 | gawk --non-decimal-data '{ printf "%s: %x\n", $1, $1 }'
0x12345678: 12345678

Comment: However, it seems that mawk is restricted to 32 bits numbers:
```$ echo 0xa12345678 | mawk '{ printf "%s: %x\n", $1, $1 }'

0xa12345678: 7fffffff```
Comment: if u want it re-print it to hex, yes, it's limited to signed 32-bit ints, but just for reading in, it can read it a LOT more, even at reduced precision :
 echo 0xFACEBEACEBEFACEEFFFACEFACFACEBEFACEEFFFACEFACFACEBEFACEEFFFACEFACFACEBEFACEEFFFACEFACFACEBEFACEEFFFACEFACFACEBEFACEEFFFACEFACFACEBEFACEEFFFACEFACFFACEEFFFACEFACFACEEACEBEFACEEFFFACEFACFACEBEFACEEFFFACEFACFACEBEFACEEFFFACEFACFACEBEFACEEFFFACEFACFACECFAD | mawk '{ printf("%.3f-bits :: %.f\n",log($0)/log(2),$0) }'
1007.970-bits :: 26874249890840347008951537650970489156010462996064997379117454191627840106815525889891……...
Comment: i just tested it …. straight up reading is limited to 2^1024 cap of IEEE 754 double-precision format.  it can also substring the input properly, so u can parse it section by section if you have a high-precision library/function that can give u an exact value.
Comment: for the same input to work without calling other functions in gawk, either -n (non-decimal input) or posix mode -P (capital P, -p is pretty print). those or strtonum( ) are still double-precision float format limited. GMP is needed to get exact. even if the 0x prefix isn't present in the input, one can prepend  ( please see my response at bottom at this page for better formatting)
Comment: The manual recommends not to use [`--non-decimal-data`](https://www.gnu.org/software/gawk/manual/html_node/Nondecimal-Data.html): *This option may disappear in a future version of gawk.*
Answer: gawk has the strtonum function:
% echo 0x12345678 | gawk '{ printf "%s: %x - %x\n", $1, $1, strtonum($1) }'
0x12345678: 0 - 12345678

Answer: Maybe you don't need awk at all, as string/number conversion is hairy. Bash versions 3 and 4 are very powerful. It is often simpler, clearer and more portable to stay in Bash, and maybe use grep and cut etc.
For example, in Bash hexadecimal numbers are converted naturally:
$ printf "%d" 0xDeadBeef
3735928559
$ x='0xE'; printf "%d %d %d" $x "$x" $((x + 1))
14 14 15

Hope this helps.
Answer: here are the different combinations of their behaviors :
using this command
'BEGIN { print 0xFACECAFEFEED^2, -0xFEEDCAFEFACEBEEFDEADFACEFEED7,
 -"0xCAFECAFECAFECAFECAFECAFECAFECAFECAFECAFECAFECAFECAFECAFE" }'

gawk -e (GNU Awk 5.1.0, API: 3.0 (GNU MPFR 4.1.0, GNU MP 6.2.1))
  76046928626116243263483543552 -82729151009071240233065844435845120 0

gawk -P -e
  00 0
  -21377898657284658184582485743897013874545437686817998522919218577408

gawk -c -e
  00 0 0

gawk -n -e
  76046928626116243263483543552 -82729151009071240233065844435845120
  -21377898657284658184582485743897013874545437686817998522919218577408

gawk -S -e
  76046928626116243263483543552 -82729151009071240233065844435845120 0

gawk -M

 76046928626116245157029816169
 -82729151009071239007500567260950231 0

gawk -l mpfr
  76046928626116243263483543552 -82729151009071240233065844435845120 0

nawk (macos awk version 20200816)
 00 0 -2.13778986572846581845824857439e+67

mawk 1.3.4
 00 0 -2.13779e+67

mawk2-beta (18.104.22.168)
 00 0 0

In fact, if one has a custom awk-script library that works across multiple awk variants, but also wanna take their idiosyncrasies into account, one approach would be use the difference in outputs here to auto-flag, with relatively few combinations left where one needs a tie-breaker.
Answer: *** this is only an extension of my comment following schot's response, strictly for proper formatting purposes.
echo FACEBEACEBEFACEEFFFACEEEFFFACEFACFACEB |
    mawk '{ printf("%s\n%.f\n%x\n%.f\n",$0,$0,"0x"$0,"0x"$0) }'

FACEBEACEBEFACEEFFFACEEEFFFACEFACFACEB
0
ffffffff
5593196314036579851314282024549245003233230848

5593196314036579608368524797845507287542639851 #exact


Is there an R optimization package that can handle integer constraints and non-linear objective functions?

Question: I am looking for an optimization routine that can optimize a non-linear objective function with integer constraints. NuOPT for S-Plus, CPLEX, or Matlab include powerful optimization packages for these kinds of optimizations?
Is there any similar kind of package for R? Or is there an optimization procedure (perhaps genetic algorithms) that can solve this problem?
For what it's worth I'm performing a portfolio mean-variance optimization.
Comment: Interesting question. Did (or do) you see anything relevant under the Optimisation CRAN Task View http://cran.r-project.org/web/views/Optimization.html
Comment: @user603, in a deleted reply, has pointed out that this is likely a *quadratic* program (because that is what CPLEX does and, I would like to add, portfolio mean-variance optimization is usually formulated as a quadratic program).  Usually one is much better off using optimizers written specifically for quadratic programs rather than with general-purpose nonlinear optimizers.  That can help limit the search for packages.
Answer: The most recent issue of The R Journal contains Differential Evolution with DEoptim, which illustrates how to use DEoptim for portfolio optimization.
Answer: If you are willing to pay for it, there is an interface between R and NAG NAGFWrappers
That includes all sort of optimization algorithms, if you know NAG, all chapter E04 is in there.
Obviously you could interface R with NAG writing some C++ code before the package was available, but now it's easier.


Is this constraint a special case of signomial programming?

Question: I am a post graduate student in Electrical Engineering and I am working in optimization. Suddenly, I was running into a situation where my problem has a constraint in the form of
$${x_1}{x_2}{x_3} - \left( {\frac{1}{3}{{\left( {{x_1}} \right)}^3} + \frac{1}{3}{{\left( {{x_2}} \right)}^3} + \frac{1}{3}{{\left( {{x_2}} \right)}^3}} \right) \le 0$$
From what I learn about signomial programming the signomial constraint should look like

$${x_1}{x_2}{x_3} - \left[ {\frac{1}{3}{{\left( {{x_1}} \right)}^3} + \frac{1}{3}{{\left( {{x_2}} \right)}^3} + \frac{1}{3}{{\left( {{x_2}} \right)}^3}} \right] \le 1$$
However, there is no $1$ on the right hand sign of my problem. How can I circumvent this ?
As a follow up question, I want to know if signomial programming can be solved efficiently like the usual convex optimization problem ?
Thank you very much !
Answer: You can simplify your constraint by using this formula
$$x_1^3 +x_2^3 +x_3^3 -3x_1x_2x_3 = (x_1+x_2+x_3)(x_1^2+x_2^2+x_3^2-x_1x_2-x_2x_3-x_3x_1)$$
Then the constraint becomes
$$x_1+x_2+x_3 \ge 0$$


Há alguma técnica para aplicar manutenção no código?

Question: Além de aplicar a alta coesão e baixo acoplamento, como lidar com códigos como esse? Podem ser até legíveis mas esse excesso de operadores lógicos, não vejo ser possível refatorar nem com switch-case.
                        if (!entry.isDirectory()
                        && !entry.getName().startsWith("__MACOSX/")
                        && !entry.getName().startsWith("_images/")
                        && !entry.getName().contains("/_images")
                        && !entry.getName().contains("/._")
                        && !entry.getName().contains("/_img")
                        && !entry.getName().contains("/imgs")
                        && !entry.getName().contains("/_old")) {
                    String filename = Util.buildFilename(nome);
                    filenameMap.put(filename, nome);

                    if (!nome.startsWith("[.]")
                            && (nome.toLowerCase().endsWith(".swf")
                            || nome.toLowerCase().endsWith(".gif")
                            || nome.toLowerCase().endsWith(".jpg") || nome
                            .toLowerCase().endsWith(".jpeg"))) {
                        files.add(dest + nome);
                    }

                    File destFile = FileUtils.getFile(dest, filename);

                    copyInputStream(zipFile.getInputStream(entry),
                            new BufferedOutputStream(new FileOutputStream(destFile)));
                }

SonarQube

Expressions should not be too complex
The complexity of an expression is defined by the number of &&, || and
  condition ? ifTrue : ifFalse operators it contains. A single
  expression's complexity should not become too high to keep the code
  readable.
Comment: Creio que lhe ajudaria a ter respostas mais bem colocadas se você incluisse na sua pergunta qual é a intenção (isto é, a função) deste trecho de código. Se você deseja "filtrar" padrões de arquivos, talvez a melhor resposta seja realmente uma combinação das duas que você já tem: criar uma função que receba o arquivo e uma lista de padrões a serem ignorados, e então usar expressões regulares para verificar o arquivo para cada padrão da lista.
Comment: Alguma resposta resolveu o problema?
Answer: Neste caso pouca coisa pode ser feita. Estes analisadores de código não distinguem a intenção. O que pode melhorar um pouco é criar a condição em um método e no if apenas chamar o método que retornará um booleano. Não sei se vai satisfazer totalmente o analisador ou vai apenas mudar a reclamação de lugar, mas deixa o código mais semântico.
De fato o switch não faria sentido aí.
A outra resposta dá uma solução mas tem uma brincadeira que diz que quando você tenta solucionar um problema com RegEx você passa ter dois problemas. Isto tem lá seu fundo de verdade, ainda que talvez não seja o caso para o que você está fazendo especificamente.
Eu particularmente criaria uma função genérica que faça a verificação passando uma lista de textos. Mas pode tentar com RegEx para ver se gosta da solução.
Note que pode ser que a lógica não apresente o resultado desejado em todas as situações. Como não conheço a exata situação mas me parece que há chance de produzir falsos positivos em alguns casos onde os path pode estar em uma ordem diferente.
Answer: Você está basicamente fazendo comparações de Strings pra definir o fluxo do código. Expressões regulares podem deixar seu código mais limpo.
Lesson: Regular Expressions
Java Regex - Tutorial
Entretanto, expressões regulares podem se tornar confusas de ler e difíceis de rastrear durante o debug. Recomendo isolar o método que faz o teste e implementar um bom teste unitário para validá-lo.
Um pouco de código pra te inspirar:
public static void main(String[] args) {
    String regularExpression =
            "(" +
            "(__MACOSX/.*)" +
            "|(_images/.*)" +
            "|(.*/_images.*)" +
            "|(.*/\\._.*)" +
            "|(.*/_img*)" +
            "|(.*/imgs*)" +
            "|(.*/_old*)" +
            ")";

    System.out.println("__MACOSX/".matches(regularExpression));
    System.out.println("_images/".matches(regularExpression));
    System.out.println("/_images".matches(regularExpression));
    System.out.println("/._".matches(regularExpression));
    System.out.println("/_img".matches(regularExpression));
    System.out.println("/imgs".matches(regularExpression));
    System.out.println("/_old".matches(regularExpression));
}

Answer: Não existe uma técnica padrão infelizmente, porém existem sim várias técnicas, eu não sei se esta é o melhor, porém é algo que podemos aplicar (baseado em SOen) seria criar uma variável e testando uma condição de cada vez, por exemplo:
boolean returnValue;

returnValue = !entry.isDirectory();
returnValue &= !entry.getName().startsWith("__MACOSX/");
returnValue &= !entry.getName().startsWith("_images/");
returnValue &= !entry.getName().contains("/_images");
returnValue &= !entry.getName().contains("/._");
returnValue &= !entry.getName().contains("/_img");
returnValue &= !entry.getName().contains("/imgs");
returnValue &= !entry.getName().contains("/_old");

if (returnValue) {
    String filename = Util.buildFilename(nome);
...

Estes operadores são chamados de  bitwise/bit-a-bit:

& (AND) - Exemplo: a & b - retorna true se a e b forem ambos true. Senão retorna false. Ambas expressões a e b são sempre avaliadas.
|  (OR)  - Exemplo: a | b - retorna true se a ou b for true. Senão retorna false. Ambas expressões a e b são sempre avaliadas.
^ (OR exclusivo) - Exemplo: a ^ b - retorna true se a for true e b for false ou vice-versa. Senão retorna false

Você também pode fazer uma verificação linha por linha reaproveitando o returnValue:
boolean returnValue;

returnValue = !entry.isDirectory();
returnValue = returnValue &&!entry.getName().startsWith("__MACOSX/");
returnValue = returnValue &&!entry.getName().startsWith("_images/");
returnValue = returnValue &&!entry.getName().contains("/_images");
returnValue = returnValue &&!entry.getName().contains("/._");
returnValue = returnValue &&!entry.getName().contains("/_img");
returnValue = returnValue &&!entry.getName().contains("/imgs");
returnValue = returnValue &&!entry.getName().contains("/_old");

if (returnValue) {
    String filename = Util.buildFilename(nome);
...

Ao meu ver este segundo exemplo é mais fácil de fazer a manutenção.


Ensemble of different kinds of regressors using scikit-learn (or any other python framework)

Question: I am trying to solve the regression task. I found out that 3 models are working nicely for different subsets of data: LassoLARS, SVR and Gradient Tree Boosting. I noticed that when I make predictions using all these 3 models and then make a table of 'true output' and outputs of my 3 models I see that each time at least one of the models is really close to the true output, though 2 others could be relatively far away.
When I compute minimal possible error (if I take prediction from 'best' predictor for each test example) I get a error which is much smaller than error of any model alone. So I thought about trying to combine predictions from these 3 diffent models into some kind of ensemble. Question is, how to do this properly? All my 3 models are build and tuned using scikit-learn, does it provide some kind of a method which could be used to pack models into ensemble? The problem here is that I don't want to just average predictions from all three models, I want to do this with weighting, where weighting should be determined based on properties of specific example.
Even if scikit-learn not provides such functionality, it would be nice if someone knows how to property address this task - of figuring out the weighting of each model for each example in data. I think that it might be done by a separate regressor built on top of all these 3 models, which will try output optimal weights for each of 3 models, but I am not sure if this is the best way of doing this.
Answer: Actually, scikit-learn does provide such a functionality, though it might be a bit tricky to implement. Here is a complete working example of such an average regressor built on top of three models. First of all, let's import all the required packages:
from sklearn.base import TransformerMixin
from sklearn.datasets import make_regression
from sklearn.pipeline import Pipeline, FeatureUnion
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestRegressor
from sklearn.neighbors import KNeighborsRegressor
from sklearn.preprocessing import StandardScaler, PolynomialFeatures
from sklearn.linear_model import LinearRegression, Ridge

Then, we need to convert our three regressor models into transformers. This will allow us to merge their predictions into a single feature vector using FeatureUnion:
class RidgeTransformer(Ridge, TransformerMixin):

    def transform(self, X, *_):
        return self.predict(X).reshape(len(X), -1)

class RandomForestTransformer(RandomForestRegressor, TransformerMixin):

    def transform(self, X, *_):
        return self.predict(X).reshape(len(X), -1)

class KNeighborsTransformer(KNeighborsRegressor, TransformerMixin):

    def transform(self, X, *_):
        return self.predict(X).reshape(len(X), -1)

Now, let's define a builder function for our frankenstein model:
def build_model():
    ridge_transformer = Pipeline(steps=[
        ('scaler', StandardScaler()),
        ('poly_feats', PolynomialFeatures()),
        ('ridge', RidgeTransformer())
    ])

    pred_union = FeatureUnion(
        transformer_list=[
            ('ridge', ridge_transformer),
            ('rand_forest', RandomForestTransformer()),
            ('knn', KNeighborsTransformer())
        ],
        n_jobs=2
    )

    model = Pipeline(steps=[
        ('pred_union', pred_union),
        ('lin_regr', LinearRegression())
    ])

    return model

Finally, let's fit the model:
print('Build and fit a model...')

model = build_model()

X, y = make_regression(n_features=10)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)

model.fit(X_train, y_train)
score = model.score(X_test, y_test)

print('Done. Score:', score)

Output:
Build and fit a model...
Done. Score: 0.9600413867438636

Why bother complicating things in such a way? Well, this approach allows us to optimize model hyperparameters using standard scikit-learn modules such as GridSearchCV or RandomizedSearchCV. Also, now it is possible to easily save and load from disk a pre-trained model.
Comment: When using this approach, is there a simple way to extract which algo is being used when/what fraction of each algo?
Comment: Perhaps looking at coefficients of the resulting linear model (`model.named_steps['lin_regr'].coef_`) will give you some insights into how much each model in an ensemble contributes to the final solution.
Comment: This is just kinda proof-of-concept example, I didn't address a model selection here. I think such models should be optimized as a whole, i.e., optimizing hyper-parameters of all the built-in models simultaneously using the cross-validation approach.
Comment: @constt Wouldn't you need to use cross_val_predict in your base models? It seems like your top-level model would get an overoptimistic signal from your base models as this is currently implemented.
Comment: if we put n_targets=1 `X, y = make_regression(n_features=10, n_targets=1)` it gives dimension error. can anyone please explain what to do?
Comment: @constt `model.fit(X_train, y_train)` this line gives me error, when i make data set like this `X, y = make_regression(n_features=10, n_targets=1)`.
Comment: If I give `n_targets=1` (or, do not specify it), I get an error: `ValueError: Expected 2D array, got 1D array instead... Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.` Well, I did the suggested reshape to both X and y, separately as well as both together, but the error does not go away. Furthermore, when I did `X = np.array(X)`, I got a `Win 32 PermissionError`. How do I fix these errors when my target has only 1 column?
Comment: Sorry guys, I haven't been here for a while. Please check out edits I made for transformer classes' `transform` methods, now the model works for `1D` training data.
Comment: It gets stuck during the `model.fit(X_train, y_train)`, even with small number of samples, and it produces deprecated warnings `DeprecationWarning: numpy.core.umath_tests is an internal NumPy module and should not be imported. It will be removed in a future NumPy release.`.
Comment: @shahar_m Dunno, for me it works like a charm. No warnings. Python 3.6.9, scikit-learn 0.23.1, numpy 1.18.4
Comment: @constt I'm using scikit-learn version 0.19.2 since it's the only one that supports onnx conversion.
Answer: Ok, after spending some time on googling I found out how I could do the weighting in python even with scikit-learn. Consider the below:
I train a set of my regression models (as mentioned SVR, LassoLars and GradientBoostingRegressor). Then I run all of them on training data (same data which was used for training of each of these 3 regressors). I get predictions for examples with each of my algorithms and save these 3 results into pandas dataframe with columns 'predictedSVR', 'predictedLASSO' and 'predictedGBR'. And I add the final column into this datafrane which I call 'predicted' which is a real prediction value.
Then I just train a linear regression on this new dataframe:
 #df - dataframe with results of 3 regressors and true output

 from sklearn linear_model
 stacker= linear_model.LinearRegression()
 stacker.fit(df[['predictedSVR', 'predictedLASSO', 'predictedGBR']], df['predicted'])

So when I want to make a prediction for new example I just run each of my 3 regressors separately and then I do:
 stacker.predict()

on outputs of my 3 regressors. And get a result.
The problem here is that I am finding optimal weights for regressors 'on average, the weights will be same for each example on which I will try to make prediction.
If anyone has any ideas on how to do stacking (weighting) using the features of current example it would be nice to hear them.
Comment: @harrison4 because I was doing regression, not classification task? So I wanted to 'weight' output from each model. Anyway, this is a bad approach, good one is described here: http://stackoverflow.com/a/35170149/3633250
Comment: Wow, I like very much this approach! But why did you used `LinearRegression()` instead of  `LogisticRegression()` model?
Comment: Yeah, sorry you're right! thanks for sharing the link!
Answer: If your data has obvious subsets you could run a clustering algorithm like k-means and then associate each classifier with the clusters it performs well on.  When a new data point arrives, then determine what cluster it's in and run the associated classifier.
You could also use the inverse distances from the centroids to get a set of weights for each classifier and predict using a linear combination of all of the classifiers.
Comment: Interesting idea, though requires lots of work in order to appy it. Thanks for paper!
Comment: I found a paper tested this stategy (along with a comparison of some similar ideas): [paper](http://pages.bangor.ac.uk/~mas00a/papers/lkKES00.pdf)
Answer: I accomplish a type of weighting by doing the following, once all your models are fully trained up and performing well:

Run all your models on a large set of unseen testing data
Store the f1 scores on the test set for each class, for each model
When you predict with the ensemble, each model will give you the most likely class, so weight the confidence or probability by the f1 score for that model on that class.  If you're dealing with distance (as in SVM, for example), just normalize the distances to get a general confidence, and then proceed with the per class f1 weighting.

You can further tune your ensemble by taking measure of percent correct over some time. Once you have a significantly large, new data set scored, you can plot threshold in steps of 0.1, for instance, against percent correct if using that threshold to score, to get an idea of what threshold will give you, say, 95% correct for class 1, and so on.  You can keep updating the test set and f1 scores as new data come in and keep track of drift, rebuilding the models when thresholds or accuracy fall.
Comment: That's interesting, but it works only for classification tasks, as far as I see, while I am trying to solve regression task. Thus I can't compute F1 score.


How can I inform a script called from a udev rule of the device that triggered the rule?

Question: I've got a udev rule
ACTION=="add", SUBSYSTEM=="block", KERNEL=="vd[c-z]", ENV{DEVICE_NAME}="KERNEL" RUN+="/usr/local/bin/udevtest"

where devices vd[c-z] trigger the rule and call my script. I am trying to pass the exact name of the device that triggers the script with the $DEVICE_NAME environment variable but it doesn't seem to be being picked up by the called script.
How is this done?
I am trying to write this for Debian and Ubuntu, so I don't think udisks2 can be used.
Answer: Instead of using an environment variable, can you pass it in to the script as an argument? Something like:
RUN+="/usr/local/bin/udevtest %k"
RUN+="/usr/local/bin/udevtest $KERNEL"

Assuming your script can be modified to handle arguments
Comment: YES. I should've  read man 5  udev, the section that starts with:
`The NAME, SYMLINK, PROGRAM, OWNER, GROUP, MODE and RUN fields support simple string substitutions.`