text:
Q: How to redirect from bucket root to subdirectory in AWS S3? I have an amazon S3 bucket serving a website from S3bucketurl.com/foo/index.html.
I would like to configure a redirection rule, that automatically rewrite the URL as follows:
Accessing S3bucketurl.com should automatically redirect to S3bucketurl.com/foo, and serve the index.html file contained in the subfolder foo.
I tried to set up the Redirection Rule as such:
<RoutingRules>
  <RoutingRule>
    <Condition>
      <KeyPrefixEquals>/</KeyPrefixEquals>
    </Condition>
    <Redirect>
      <ReplaceKeyWith>api</ReplaceKeyWith>
    </Redirect>
  </RoutingRule>
</RoutingRules>

which results in a 404:
404 Not Found

Code: NoSuchKey
Message: The specified key does not exist.
Key: index.html

I've also tried permutations of <ReplaceKeyWith>/api</ReplaceKeyWith>, <ReplaceKeyWith>api/</ReplaceKeyWith> and <ReplaceKeyWith>/api/</ReplaceKeyWith> to no avail.

A:
<KeyPrefixEquals>/</KeyPrefixEquals>

There are two problems, here: first, this matches a prefix, meaning there's an implicit * at the end.  Thst isn't what you want, here.  Also no key in an S3 bucket typically has a prefix of /.  The object key starts with the character after the leading slash.  Your <ReplaceKeyWith> is ignored because the prefix test never matches.  But rules are not the best solution, here.
The way to do what you want is this:
Upload an empty file to create a new object in the root of the bucket, named whatever name you use for your index documents, typically index.html.  Make it public unless your bucket policy makes everything public.
In the object metadata for this object, set x-amz-website-redirect-location to /api/ (or /foo/, or whatever path you intend).


text:
Q: how to skip the index in python for loop I have a list like this:
array=['for','loop','in','python']

for arr in array:
    print arr

This will give me the output
for
lop
in
python

I want to print
in
python

How can I skip the first 2 indices in python?

A: Use slicing.
array = ['for','loop','in','python']

for arr in array[2:]:
    print arr

When you do this, the starting index in the for loop becomes 2. Thus the output would be:
in
python

For more info on slicing read this: Explain Python's slice notation

A: Code:
array=['for','loop','in','python']
for arr in array[2:]:
    print arr

Output:
in
python

A: See Python slicing:
for arr in array[2:]:
    print arr

A: If you want to skip other lines or want to try different combination then you could do this
Code:
for i ,j in enumerate(array):
    if i not in (1,2):
        print j

Output:
for
python

A: Slicing is good, but if you're considered about performance, you might prefer itertools.islice:
import itertools
array = 'for loop in python'.split()
for x in itertools.islice(array, 2, None):
    print x

because the slice operator builds a completely new list, which means overhead if you just want to iterate over it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: VS2008 takes ages to close Using for VC++. It runs pretty fast and is generally great, but when exiting it often locks up (Visual Studio is not responding) for quite a long time. It seems to always exit successfully but what is it doing for all that time? Is it yet another NCB/Intellisense issue?
I have 2 plugins to VS:

*

*Visual Assist X

*VisualSVN


text:
Q: Installing PHP Extensions on RedHat I've installed PHP via Yum on RedHat (minimal install; no GUI), but in order for me to install an application on the system I need to install PHP Mcrypt extension. How does this work? Should I remove PHP via Yum and install from source and use the parameters in the above link (--with-mcrypt[=DIR])?

A: It's a separate package. In packaged Linux they break the separate compiled extensions into their own library and then include those. Try this
yum install php-mcrypt

I should also note that mcrypt may be deprecated in the future


text:
Q: Zend Framework routing camelcase controllers error I'm working on this application with ZendFramework 1.12, using default routing ( controller/action/params ) and everything goes fine in development ( Vagrant + CentOS box ).
But in production server (which is CentOS too) some routes, which uses CamelCase controllers, are not working. Ex.:
UserProfileController::indexAction() should map to /userProfile/index but when I try it redirects to /home
I know that using "-" to separate the names like in "/user-profile/index" it works. But, there's a lot of links in the entire application that need to be fixed.
Anyone knows a better way to make it work?


text:
Q: How to make variables from firebase database global in javascript     var rootRef = firebase.database().ref().child('Locations');

    rootRef.on("value", function(snapshot) {
             lat = snapshot.child('latitude').val();
             longi = snapshot.child('longitude').val();
             console.log(snapshot.child('latitude').val());
          }, function (error) {
             console.log("Error: " + error.code);
   });

When i console.log(lat); lat is undefined.
I am new to javascript. Is there any way it can be globally available?

A: Your console.log(lat) that is not shown on your snippet is outside the callback function and runs before the callback when lat is still undefined. You need to do whatever you want to do with it, inside the callback when it is available.
Read this article to get to understand callback functions a little better:
https://codeburst.io/javascript-what-the-heck-is-a-callback-aba4da2deced
I hope this was any help to you!


text:
Q: Oracle SQL - Determine due date using a 2nd table I am trying to figure out how to complete this task. I need to determine the due_date in the task_table based on the schedule in the duty_schedule table. There's not a consistent pattern of active days in the duty schedule, so I'm finding this to be difficult.
I need to select the 5th active day in the duty_schedule table after the task_date. Only days marked 1 in the Active column should be used to determine the due date. I've included sample tables including expected results.
I do not know how to approach this; if this can be done with a query or if a function needs to be created, or a better option?
TASK_TABLE:
TASK_NUM TASK_DATE DUE_DATE

     1 15-SEP-21 null
     2 19-SEP-21 null
     3 20-SEP-21 null
     4 22-SEP-21 null
     5 25-SEP-21 null
     6 26-SEP-21 null
     7 28-SEP-21 null

duty_schedule:
DAY_NUM DUTY_DATE     ACTIVE

     1 15-SEP-21          1
     2 16-SEP-21          0
     3 17-SEP-21          1
     4 18-SEP-21          1
     5 19-SEP-21          0
     6 20-SEP-21          0
     7 21-SEP-21          1
     8 22-SEP-21          1
     9 23-SEP-21          1
    10 24-SEP-21          0
    11 25-SEP-21          1
    12 26-SEP-21          1
    13 27-SEP-21          0
    14 28-SEP-21          1
    15 29-SEP-21          1
    16 30-SEP-21          1
    17 01-OCT-21          1
    18 02-OCT-21          0
    19 03-OCT-21          1
    20 04-OCT-21          0
    21 05-OCT-21          1

TASK_TABLE Expected results:
TASK_NUM TASK_DATE DUE_DATE

     1 15-SEP-21 23-SEP-21
     2 19-SEP-21 26-SEP-21
     3 20-SEP-21 26-SEP-21
     4 22-SEP-21 29-SEP-21
     5 25-SEP-21 01-OCT-21
     6 26-SEP-21 03-OCT-21
     7 28-SEP-21 05-OCT-21

Built sample tables using these:
CREATE TABLE TASK_TABLE (
task_num    number(2),
task_date   DATE,
due_date    DATE
);

INSERT INTO TASK_TABLE VALUES (1, '15-SEP-21', NULL);
INSERT INTO TASK_TABLE VALUES (2, '19-SEP-21', NULL);
INSERT INTO TASK_TABLE VALUES (3, '20-SEP-21', NULL);
INSERT INTO TASK_TABLE VALUES (4, '22-SEP-21', NULL);
INSERT INTO TASK_TABLE VALUES (5, '25-SEP-21', NULL);
INSERT INTO TASK_TABLE VALUES (6, '26-SEP-21', NULL);
INSERT INTO TASK_TABLE VALUES (7, '28-SEP-21', NULL);
COMMIT;

CREATE TABLE duty_schedule (
day_num NUMBER(3),
duty_date   DATE,
active      NUMBER(1)
);

INSERT INTO duty_schedule VALUES (1,'15-Sep-21',1);
INSERT INTO duty_schedule VALUES (2,'16-Sep-21',0);
INSERT INTO duty_schedule VALUES (3,'17-Sep-21',1);
INSERT INTO duty_schedule VALUES (4,'18-Sep-21',1);
INSERT INTO duty_schedule VALUES (5,'19-Sep-21',0);
INSERT INTO duty_schedule VALUES (6,'20-Sep-21',0);
INSERT INTO duty_schedule VALUES (7,'21-Sep-21',1);
INSERT INTO duty_schedule VALUES (8,'22-Sep-21',1);
INSERT INTO duty_schedule VALUES (9,'23-Sep-21',1);
INSERT INTO duty_schedule VALUES (10,'24-Sep-21',0);
INSERT INTO duty_schedule VALUES (11,'25-Sep-21',1);
INSERT INTO duty_schedule VALUES (12,'26-Sep-21',1);
INSERT INTO duty_schedule VALUES (13,'27-Sep-21',0);
INSERT INTO duty_schedule VALUES (14,'28-Sep-21',1);
INSERT INTO duty_schedule VALUES (15,'29-Sep-21',1);
INSERT INTO duty_schedule VALUES (16,'30-Sep-21',1);
INSERT INTO duty_schedule VALUES (17,'1-Oct-21',1);
INSERT INTO duty_schedule VALUES (18,'2-Oct-21',0);
INSERT INTO duty_schedule VALUES (19,'3-Oct-21',1);
INSERT INTO duty_schedule VALUES (20,'4-Oct-21',0);
INSERT INTO duty_schedule VALUES (21,'5-Oct-21',1);
COMMIT;

A: Use a correlated subquery in the SELECT clause or in the FROM clause. Here I am using the FROM clause:
select
  t.task_num,
  t.task_date,
  d.duty_date
from task_table t
outer apply
(
  select ds.duty_date
  from duty_schedule ds
  where ds.active = 1
  and ds.duty_date > t.task_date
  order by ds.duty_date
  offset 4 rows
  fetch next row only
) d
order by t.task_num;

Demo: https://dbfiddle.uk/?rdbms=oracle_18&fiddle=bdb05d7dfa12874ff03bb39f418524f0


text:
Q: Compare route with parameters Compare a route with parameters wrote by user and a route allowed by system.
I am creating a PHP routing system and I need compare two routes.
The following route is allowed by the system, setting the parameter name between {}:
name/{var}/{var2}/edit

And the following route is wrote by user, setting the parameter value between each /:
name/val/val2/edit

Thanks for your help!


text:
Q: lubuntu reduce size of vmlinuz file for PXE boot I have poor knowledge about Linux systems, but Windows XP support is over.
I have two older computers. I want install Lubuntu from PXE on this computers, but the problem is that they says "NBP is too big to fit in free base memory". What should I do ? The vmlinuz file (which I think makes the problem) is around 7 MB.


text:
Q: Java KeyEvent square movement I have a piece of code in which a KeyEvent is triggered when any of the arrow keys are pressed. This in turn causes a square to move across the screen.
Now I've noticed that when I press and hold the key, the square moves but the time after the initial movement to the subsequent movements is quite long if you understand what I mean? How would I go about diminishing this time?
Thanks!
import java.awt.*;
import javax.swing.*;
import squarequest.sprites.*;
import java.awt.event.*;

public class GamePanel extends JPanel{

    private final int HEIGHT = 400;
    private final int WIDTH = 600;
    private Square square;
    private Circle circle;

    public GamePanel(){

        addKeyListener(new DirectionListener());

        setBackground (Color.white);
        setPreferredSize(new Dimension(WIDTH, HEIGHT));
        setFocusable(true);

        square = new Square();

    }

    public void paintComponent(Graphics g){
        super.paintComponent(g);
        square.display(g);

    }

    public class DirectionListener implements KeyListener{

        @Override
        public void keyReleased(KeyEvent event) {}

        @Override
        public void keyTyped(KeyEvent event) {}

        @Override
        public void keyPressed(KeyEvent event) {

            switch(event.getKeyCode()){

            case KeyEvent.VK_UP:

                square.moveUp();
                break;
            case KeyEvent.VK_DOWN:

                square.moveDown();
                break;
            case KeyEvent.VK_LEFT:

                square.moveLeft();
                break;
            case KeyEvent.VK_RIGHT:

                square.moveRight();
                break;
            }
            repaint();

        }
    }
}

A: *

*Use a Swing Timer for the actual movement.

*Start the Timer on key press

*Stop it on key release.

*Or better still, keep the timer always running, but only moving the sprite based on the state of a map, one that holds a Direction enum key and a Boolean value.

*Better to use key bindings rather than KeyListeners.

e.g.,
import java.awt.*;
import javax.swing.*;
//!! import squarequest.sprites.*;
import java.awt.event.*;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.Map;

public class GamePanel extends JPanel {
   private static final int ANIMATION_DELAY = 15;
   private final int HEIGHT = 400;
   private final int WIDTH = 600;
   private Square square;
   private EnumMap<Direction, Boolean> dirMap = new EnumMap<>(Direction.class);
   private Map<Integer, Direction> keyToDir = new HashMap<>();
   // !! private Circle circle;
   private Timer animationTimer;

   public GamePanel() {
      for (Direction dir : Direction.values()) {
         dirMap.put(dir, Boolean.FALSE);
      }
      keyToDir.put(KeyEvent.VK_UP, Direction.UP);
      keyToDir.put(KeyEvent.VK_DOWN, Direction.DOWN);
      keyToDir.put(KeyEvent.VK_LEFT, Direction.LEFT);
      keyToDir.put(KeyEvent.VK_RIGHT, Direction.RIGHT);
      // !! addKeyListener(new DirectionListener());
      setKeyBindings();
      setBackground(Color.white);
      setPreferredSize(new Dimension(WIDTH, HEIGHT));
      setFocusable(true);
      square = new Square();
      animationTimer = new Timer(ANIMATION_DELAY, new AnimationListener());
      animationTimer.start();
   }

   private void setKeyBindings() {
      int condition = WHEN_IN_FOCUSED_WINDOW;
      final InputMap inputMap = getInputMap(condition);
      final ActionMap actionMap = getActionMap();
      boolean[] keyPressed = { true, false };
      for (Integer keyCode : keyToDir.keySet()) {
         Direction dir = keyToDir.get(keyCode);
         for (boolean onKeyPress : keyPressed) {
            boolean onKeyRelease = !onKeyPress; // to make it clear how bindings work
            KeyStroke keyStroke = KeyStroke.getKeyStroke(keyCode, 0,
                  onKeyRelease);
            Object key = keyStroke.toString();
            inputMap.put(keyStroke, key);
            actionMap.put(key, new KeyBindingsAction(dir, onKeyPress));
         }
      }
   }

   public void paintComponent(Graphics g) {
      super.paintComponent(g);
      square.display(g);
   }

   // public class DirectionListener implements KeyListener {
   // @Override
   // public void keyReleased(KeyEvent event) {
   // int keyCode = event.getKeyCode();
   // if (keyToDir.keySet().contains(keyCode)) {
   // Direction dir = keyToDir.get(keyCode);
   // dirMap.put(dir, false);
   // }
   // }
   //
   // @Override
   // public void keyTyped(KeyEvent event) {
   // }
   //
   // @Override
   // public void keyPressed(KeyEvent event) {
   // int keyCode = event.getKeyCode();
   // if (keyToDir.keySet().contains(keyCode)) {
   // Direction dir = keyToDir.get(keyCode);
   // dirMap.put(dir, true);
   // }
   // }
   // }

   private class AnimationListener implements ActionListener {
      @Override
      public void actionPerformed(ActionEvent evt) {
         boolean repaint = false;
         for (Direction dir : Direction.values()) {
            if (dirMap.get(dir)) {
               square.move(dir);
               repaint = true;
            }
         }
         if (repaint) {
            repaint();
         }
      }
   }

   private class KeyBindingsAction extends AbstractAction {
      private Direction dir;
      boolean pressed;

      public KeyBindingsAction(Direction dir, boolean pressed) {
         this.dir = dir;
         this.pressed = pressed;
      }

      @Override
      public void actionPerformed(ActionEvent evt) {
         dirMap.put(dir, pressed);
      }
   }

   private static void createAndShowGUI() {
      GamePanel gamePanel = new GamePanel();
      JFrame frame = new JFrame("GamePanel");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(gamePanel);
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
      gamePanel.requestFocusInWindow();
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGUI();
         }
      });
   }
}

enum Direction {
   UP(0, -1), DOWN(0, 1), LEFT(-1, 0), RIGHT(1, 0);
   private int incrX;
   private int incrY;

   private Direction(int incrX, int incrY) {
      this.incrX = incrX;
      this.incrY = incrY;
   }

   public int getIncrX() {
      return incrX;
   }

   public int getIncrY() {
      return incrY;
   }
}

class Square {
   private int x = 0;
   private int y = 0;
   private int w = 20;
   private int h = w;
   private int step = 1;
   private Color color = Color.red;
   private Color fillColor = new Color(255, 150, 150);
   private Stroke stroke = new BasicStroke(3f, BasicStroke.CAP_ROUND,
         BasicStroke.JOIN_ROUND);

   public void display(Graphics g) {
      Graphics2D g2d = (Graphics2D) g.create();
      g2d.setColor(fillColor);
      g2d.fillRect(x, y, w, h);
      g2d.setStroke(stroke);
      g2d.setColor(color);
      g2d.drawRect(x, y, w, h);
      g2d.dispose();
   }

   public void setStep(int step) {
      this.step = step;
   }

   public void move(Direction dir) {
      x += step * dir.getIncrX();
      y += step * dir.getIncrY();
   }

//   public void moveRight() {
//      x++;
//   }
//
//   public void moveLeft() {
//      x--;
//   }
//
//   public void moveUp() {
//      y--;
//   }
//
//   public void moveDown() {
//      y++;
//   }
}


text:
Q: How can I automatically add allowfullscreen to every new iframe I'm using codes like this in my blog:
<iframe width="560" height="315" src="https://www.youtube-nocookie.com/embed/0eBDVy5nihM?rel=0" frameborder="0" allowfullscreen></iframe>

And my question is simple, how can I automatically add allowfullscreen to every new iframe using javascript/jQuery?
Also, I presume the script should identify if there's the tag allowfullscreen added already.
I couldn't find a solution anywhere else.

A: Should be just this:
$('iframe').attr('allowFullScreen', '');

There is no need to check for allready set allowfullscreen as there will be no error if it is.

A: From here: https://stackoverflow.com/a/3774041/3764994
and here: Set IFrame allowfullscreen with javascript
To get all the iframe elements use getElementsByTagName(), then iterate over those with a for loop:
Something like this:
var i, frames;
frames = document.getElementsByTagName("iframe");
for (i = 0; i < frames.length; ++i)
{
      // The iFrame
    if (!frames[i].hasAttribute("allowfullscreen")) {
        frames[i].setAttribute('allowFullScreen', '')
    }
}


text:
Q: How make CRC-6 table Please let me know what's wrong with the code I made
void make_crc_table( void ) {
    int i, j;
    unsigned long poly, c;

    poly = 0x03;    // X^6 + x + 1

    for ( i = 0; i < 256; i++ ) {
        c = i >> 2;
        for ( j = 0; j < 8; j++ ) {
            c = ( c & 0x20 ) ? poly ^ ( c << 1 ) : ( c << 1 );
        }
        crctable[i] = (uint8_t) c;
    }
}

Thanks for the help.

A: You need to calculate starting at the high bit of the bytes. Get rid of the >> 2 (that just results in doing the same calculation four times). Do this to calculate from the high bit:
c = c & 0x80 ? (c << 1) ^ (poly << 2) : c << 1;

Then when saving:
crctable[i] = (c >> 2) & 0x3f;

Not required, but there's no reason for the unsigned long, so just make that unsigned.


text:
Q: PHP array failing to POST with other form data I have an array named $content_ids which I am trying to post as a hidden field in a form.
I found out how to do this from another answer here but I cant get it to work.
Here are just a few of my inputs including the hidden field for the array
echo "<input type=\"hidden\" value=\"1\" name=\"e\">";
foreach($content_ids as $ids)
{
    echo "<input type=\"hidden\" value=\"".$ids."\" name=\"ids[]\">";
}
echo "<input type=\"hidden\" value=\"".$content[$x]['TranslationID']."\" name=\"translationID\">";

Trying to print_r($_POST['ids']) shows nothing
Trying this:
if($_POST['ids'] != ""){
    echo "hello";
}

also gives nothing. But the rest of the data is passing through ok.
Anybody any idea why?
Edit to add:  Tested to make sure the array actually contains the data at the point of placing it into the hidden field. printing out the array immediately before the hidden field is set and all displays ok.
Edit to add: how the array is made:
$content_ids = array();
    for($i = 0; $i < count($content); $i++)
    {
        $content_ids[] = array_push($content_ids, $content[$i]['ContentID']);
    }

the output for the array is:
Array ( [0] => 2222 [1] => 1 [2] => 1111 [3] => 3 )
I actually dont know why index 1 or index 3 are there. They are not part of the data from the database. It should only contain 1111 and 2222.

A: I have run this code and able to get all posted values
   <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    </head>
    <body>
    <form action ="" method="POST" >
    <?php
    //supose your values are
    $content_ids = array('10','20');
    $x = 1;
    $content[$x]['TranslationID'] =20;
    // your code
    echo "<input type=\"hidden\" value=\"1\" name=\"e\">";
    foreach($content_ids as $ids)
    {
        echo "<input type=\"hidden\" value=\"".$ids."\" name=\"ids[]\">";
    }
    echo "<input type=\"hidden\" value=\"".$content[$x]['TranslationID']."\" name=\"translationID\">";

    ?>
    <input type="submit" />
    </form>
    </body>
    </html>
    <?php print_r($_POST); ?>

Here the output
Array ( [e] => 1 [ids] => Array ( [0] => 10 [1] => 20 ) [translationID] => 20 )

A: I found the problem. I believe the issue was with the creation of the array.
The only thing I changed was:
$content_ids = array();
    for($i = 0; $i < count($content); $i++)
    {
        $content_ids[] = array_push($content_ids, $content[$i]['ContentID']);
    }

And I changed it to this:
$content_ids = array();
    for($i = 0; $i < count($content); $i++)
    {
        array_push($content_ids, $content[$i]['ContentID']);
    }

I dont know how but this seems to have fixed both the unwanted indexes in the array and the failure to post as a hidden field.
I am now getting the array successfully as a POST variable. Thank you all for the help


text:
Q: DNS not resolving 3rd level sub domain I have a site working on a VM with Debian and Apache.
The site is sitename.example.com . Now, I need to add a subdomain like subdomain.sitename.example.com on the same IP.
What have I done until now:
000-default.conf
<VirtualHost 192.167.102.49:80>

ServerAdmin webmaster@localhost
DocumentRoot /home/iamanuser/www/subdomain/public_html
ServerName subdomain.sitename.example.com
ServerAlias subdomain.example.com

</VirtualHost>

apache2.conf
<Directory /home/iamanuser/www/subdomain/>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
<VirtualHost 192.167.102.49:80>
ServerName www.subdomain.sitename.example.com
DocumentRoot /home/iamanuser/www/subdomain/public_html
</VirtualHost>

etc/hosts
192.167.102.49 sitename.example.com
192.167.102.49 subdomain.sitename.example.com

sitename.example.com works perfect, but everytime I go for subdomain.sitename.example.com the DNS can't be resolved.
I'm literally going crazy, please help me. Thanks in advance.

A: Are you trying to access this from the machine that has these entries in /etc/hosts?
You might also want to check /etc/nsswitch.conf to check that 'hosts' comes before 'dns' etc.
You can use getent hosts subdomain.sitename.domain.com to see what would be returned to an application when it does a lookup (do this from your [Linux] client)

A: chrome is known for ignoring /etc/hosts file.
There's an answer on superuser that tells you how to fix that:
- Go to chrome://settings

- Click on "Show advanced settings..."

- Unmark the Predict network actions to improve page load performance box.

- Check if the DNS prefetching is really disabled by going to
chrome://dns. You should see there something like DNS
pre-resolution and TCP pre-connection is disabled. If the
prefetching is not disabled, you'll see some tables there.


text:
Q: How to terminate a process by name AND location using C WinAPI? I searched and found a way to terminate a process only by name:
void KillProcessByName(TCHAR *szPName)
{
    HANDLE hSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPALL, NULL);
    PROCESSENTRY32 pEntry;
    pEntry.dwSize = sizeof (pEntry);
    BOOL hRes = Process32First(hSnapShot, &pEntry);
    while(hRes)
    {
        if(!_tcsicmp(pEntry.szExeFile, szPName))
        {
            HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, 0,
                                          (DWORD) pEntry.th32ProcessID);
            if (hProcess != NULL)
            {
                TerminateProcess(hProcess, 9);
                CloseHandle(hProcess);
            }
        }
        hRes = Process32Next(hSnapShot, &pEntry);
    }
    CloseHandle(hSnapShot);
}

However, I can't find a member called szLocation or sth alike in the PROCESSENTRY32 structure. I need to distinguish two processes with the same name, but different locations.

A: You can simply read szExeFile from PROCESSENTRY32.
Or you can use GetModuleFileNameEx to return the full path to the executable file associated with a process handle.


text:
Q: writeOGR, read OGR does not provide X Y coordinates, which I need after clipping shapefile in R I have made shapefiles from CSV by using the packages raster and rgdal, but I'd like to clip these shapefiles to a certain area, which I can do.
However, when I write try to write.csv it does not work.
Also, I lose X and Y after writeOGR.
datansd = read.csv("..csv", header=T,sep=",")
### tell R what the coordinates are and define the coordinate system ###
coordinates(datansd) = c("X","Y")
proj4string(datansd) = CRS("+init=epsg:32614")
### write the shapefile, dsn is the target folder, layer is the name of the shapefile ###
writeOGR(datansd, dsn = "Shapes", layer = "July2013UD5", driver = "ESRI     Shapefile")
sdata <- readOGR(dsn="C:.", layer="July2013UD5")
# READ POINT SHAPEFILE TRAINING DATA
> head(sdata)
  name       Value Value2      Value3 sampleID
  1 29435 98.94331        1 1.056688    w764
  2 29436 98.87749        1 1.122505    w764
  3 29437 98.83189        1 1.168107    w764
  4 29438 98.78847        1 1.211534    w764
  5 29439 98.77276        1 1.227239    w764
  6 29440 98.78549        1 1.214514    w764
> enclosure <- readOGR(dsn="C:.", layer="polygon")
  OGR data source with driver: ESRI Shapefile
  Source: "C:..", layer: "polygon"
  with 12 features and 13 fields
  Feature type: wkbPolygon with 2 dimensions
> plot(enclosure)
> points(sdata)
> data <- spTransform(sdata, CRS(proj4string(enclosure))) # transform  CRS
> points(data)
> head(data)
  name       Value Value2      Value3 sampleID
  1 29435 98.94331        1 1.056688    w764
  2 29436 98.87749        1 1.122505    w764
  3 29437 98.83189        1 1.168107    w764
  4 29438 98.78847        1 1.211534    w764
  5 29439 98.77276        1 1.227239    w764
  6 29440 98.78549        1 1.214514    w764
> data_subset <- data[enclosure, ]
> plot(enclosure)
> points(data_subset)
> head(data_subset)
    name     Value Value2   Value3 sampleID
    378 31632 96.04780        1 3.952204    w764
    379 31633 95.86989        1 4.130108    w764
    380 31634 95.69978        1 4.300223    w764
    381 31635 95.41422        1 4.585780    w764
    382 31636 95.09640        1 4.903604    w764
    383 31637 94.67770        1 5.322302    w764
> write.csv(data_subset,file ="C:...csv", row.names = FALSE)
> data_subset = read.csv("Shapes/July2013UD5clip.csv",  header=T,sep=",")
> coordinates(datansd) = c("X","Y")
    Error in `coordinates<-`(`*tmp*`, value = c("X", "Y")) :
    setting coordinates cannot be done on Spatial objects, where they have already   been set
> writeOGR(data_subset, dsn = "Shapes", layer = "July2013UD5clip", driver =           "ESRI Shapefile")
    Error: inherits(obj, "Spatial") is not TRUE
> sdata <- readOGR(dsn="C:../Shapes", layer="July2013UD5clip")
    Error in ogrInfo(dsn = dsn, layer = layer, encoding = encoding, use_iconv        =      use_iconv,  :
    Cannot open layer

When I get the X, Y back into the shapefile attribute table, I then
want to extract the raster values to the points and then write.csv of the
points with their coordinates and new attributes.
How do I get the X, Y in the final product?

A: After this line
data_subset <- data[enclosure, ]

You have a (subsetted) SpatialPointsDataFrame. You an write that to disk as a 'shapefile'. If you want to write it as a table (csv), with the coordinates, you should do
write.csv(data.frame(data_subset), 'file.csv')

To extract values from a raster and then write to a csv file, you could do
e <- extract(raster, data_subset)
d <- data.frame(data_subset, e)
write.csv(d, 'file.csv')


text:
Q: Undefined variable: query (foreach) I get this error message below
 A PHP Error was encountered
 Severity: Notice
 Message: Undefined variable: query
 Filename: views/home.php
 Line Number: 121

Backtrace:
File: C:\wamp\www\ci\application\views\home.php
Line: 121
Function: _error_handler

File: C:\wamp\www\ci\application\controllers\Home.php
Line: 20
Function: view

File: C:\wamp\www\ci\index.php
Line: 292
Function: require_once

Please help!

class Home extends CI_Controller
{
function __construct() {
    parent::__construct();
    $this->load->database();
    $this->load->model("login_model", "getSearch");

    if(empty($this->session->userdata('c.contact_id'))) {
        $this->session->set_flashdata('flash_data', '
Ooops. You don\'t have access!
');
        redirect('login');
    }
}

public function index() {
    $this->load->view('home');
}

public function logout() {
    $data = ['c.contact_id', 'email'];
    $this->session->unset_userdata($data);

    redirect('login');
}

function searches(){
    $contact_id = $this->session->userdata('c.contact_id');
    $data['c.contact_id'] = $contact_id;
    $data['query'] = $this->login_model->getSearch($contact_id);
    $this->load->view('home', $data);
}
}

class Login_model extends CI_Model
{
function __construct() {
    parent::__construct();
    $this->load->database();
}

public function validate_user($data) {
    $this->db->distinct();
    $this->db->select('c.contact_id, name, email, password, level, c.statusid');
    $this->db->from('contact c');
    $this->db->join('deliveryreg d', 'c.contact_id = d.idcontact');
    $this->db->join('ClientLogin cl', 'cl.idcontact = c.contact_id');
    $this->db->where('c.statusid = 1');
    $this->db->where('email', $data['email']);
    $this->db->where('password', $data['password']);

    $query = $this->db->get();
    return $query->num_rows();
}

public function getSearch(){
    $this->db->distinct();
    $this->db->select(" s.id AS 'searchid',s.description as 'searchname',so.id AS 'sourceid',so.description as 'service'");
    $this->db->from('contact c');
    $this->db->join('deliveryreg d', 'c.contact_id = d.idcontact');
    $this->db->join('searchsource ss', 'ss.id = d.idsearchsource');
    $this->db->join('search s', 's.id = ss.idsearch');
    $this->db->join('source so', 'so.id = ss.idsource');
    $this->db->where('c.statusid = 1');
    $this->db->where('email');
    $ids = array('1','5','8');
    $this->db->where_in('so.id', $ids);
    $this->db->order_by('s.description', 'so.description');

    $query = $this->db->get();
    return $query->result();
}

function __destruct() {
    $this->db->close();
}

}
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>PEAR | Professional Evaluation And Research</title>

    <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">

    <link rel="stylesheet" href="<?php echo base_url();?>assets/css/bootstrap.min.css">

    <link rel="stylesheet" href="<?php echo base_url();?>assets/css/custom.css">

    <link rel="stylesheet" href="<?php echo base_url();?>assets/css/bootstrap.vertical-tabs.css">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">

    <link rel="stylesheet" href="https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css">

    <link rel="stylesheet" href="<?php echo base_url();?>assets/css/AdminLTE.min.css">

    <link rel="stylesheet" href="<?php echo base_url();?>assets/css/skins/skin-green.min.css">

          PEAR

          PEAR

            Toggle navigation

                  Advanced Filtering

                  Exporting

                <a href="<?= site_url('home/logout') ?>">
                  Logout

              <img src="<?php echo base_url();?>assets/img/user-avatar.png" class="img-circle" alt="User Image">

Hi, there!

               Online

HEADER

               Searches
              <?php foreach ($query as $search_row){ ?>

--- Select all ---

<input type="checkbox"> <?php echo $search_row->searchname;?>

<input type="checkbox"> Search B

<input type="checkbox"> Search C

              <?php }?>

               Services

--- Select all ---

<input type="checkbox"> Print

<input type="checkbox"> Broadcast

<input type="checkbox"> Online

               Calendar

               Facebook

DASHBOARD

        </section

Overview

Keystories

Region

Media Type

Byline

Trends

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sequi labore omnis adipisci nisi quibusdam consequuntur officiis repellendus tempora doloremque eum, maxime, vel, reiciendis consectetur consequatur obcaecati, saepe voluptates. Minus, soluta.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sequi labore omnis adipisci nisi quibusdam consequuntur officiis repellendus tempora doloremque eum, maxime, vel, reiciendis consectetur consequatur obcaecati, saepe voluptates. Minus, soluta.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sequi labore omnis adipisci nisi quibusdam consequuntur officiis repellendus tempora doloremque eum, maxime, vel, reiciendis consectetur consequatur obcaecati, saepe voluptates. Minus, soluta.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sequi labore omnis adipisci nisi quibusdam consequuntur officiis repellendus tempora doloremque eum, maxime, vel, reiciendis consectetur consequatur obcaecati, saepe voluptates. Minus, soluta.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sequi labore omnis adipisci nisi quibusdam consequuntur officiis repellendus tempora doloremque eum, maxime, vel, reiciendis consectetur consequatur obcaecati, saepe voluptates. Minus, soluta.

        Copyright © <?php  echo date("Y");?> PEAR | Professional Evalution and Research. All rights reserved.

A: Here nothing pass the value to view page like this $data['query']="";
public function index() {
$data['query']=""; // here you made the mistake, if you want pass any value
$this->load->view('home');
}

if you want pass any value, otherwise in home.php view page you are using $query variable. remove it or in view page write the query and execute.
foreach ($query->result() as $search_row) {
//your functions
}

Should use result function $query->result() in foreach loop

A: In your constructor:
$this->load->model("login_model");
/* not: $this->load->model("login_model", "getSearch"); */
/* it just creates an alias for login_model, e.g. $this->getSearch->some_model_method(...) */

As getSearch is a method in your model, now you can do:
$data['query'] = $this->login_model->getSearch($contact_id);

Also, note that you will still get an undefined variable error using your index() method, because there you do not provide the $query variable to the home view. With your current code, you only provide it to the home view via the searches() method. I don't know what you're trying to do exactly, but an easy fix would be to test for the existence of $query in the view:
<?php if($query){ foreach ($query as $search_row){ /* ... */ } } ?>


text:
Q: Data driven pages - toolbox I am trying to convert regular python script to toolbox. This is the regular code which works:
import arcpy
strOutpath = "C:\Users\name\Desktop\New Folder"
mxd = arcpy.mapping.MapDocument("CURRENT")
for pageNum in range(1, mxd.dataDrivenPages.pageCount + 1):
 mxd.dataDrivenPages.currentPageID = pageNum
 pageorder = mxd.dataDrivenPages.pageRow.BR
 pageindex = mxd.dataDrivenPages.pageRow.KARTA
 pdfname = pageorder + "-" + pageindex + ".pdf"
 arcpy.mapping.ExportToPDF(mxd, strOutpath + pdfname, resolution="300dpi", image_compression="Adaptive", jpeg_compression_quality="85", colorspace="RGB", picture_symbol="VECTORIZE_BITMAP")
del mxd

And this is the my example for script to input as script for toolbox:
import arcpy
strOutpath = arcpy.GetParameterAsText(0)
mxd = arcpy.GetParameterAsText(1)
for pageNum in range(1, mxd.dataDrivenPages.pageCount + 1):
 mxd.dataDrivenPages.currentPageID = pageNum
 pageorder = arcpy.GetParameterAsText(2)
 pageindex = arcpy.GetParameterAsText(3)
 pdfname = pageorder + "-" + pageindex + ".pdf"
 arcpy.mapping.ExportToPDF(mxd, strOutpath + pdfname, resolution="300dpi", image_compression="Adaptive", jpeg_compression_quality="85", colorspace="RGB", picture_symbol="VECTORIZE_BITMAP")

As parameters, I entered this:
strOutpath = FOLDER
mxd = ArcMap document
pageorder = field
pageindex = field

And when I try to input the values, I get empty fields. There is clearly something wrong with the second code and input variables, but I don't know what.

EDIT:
When I edit my code, based on the comment ArtWork21 gave, when only output folder and mxd are user-generated, this is the code:
import arcpy
strOutpath = arcpy.GetParameterAsText(0)
mxd = arcpy.GetParameterAsText(1)
for pageNum in range(1, mxd.dataDrivenPages.pageCount + 1):
 mxd.dataDrivenPages.currentPageID = pageNum
 pageorder = mxd.dataDrivenPages.pageRow.BR
 pageindex = mxd.dataDrivenPages.pageRow.KARTA
 pdfname = pageorder + "-" + pageindex + ".pdf"
 arcpy.mapping.ExportToPDF(mxd, strOutpath + '\\' + pdfname, resolution="300dpi", image_compression="Adaptive", jpeg_compression_quality="85", colorspace="RGB", picture_symbol="VECTORIZE_BITMAP")
del mxd

This is the error:
Traceback (most recent call last):
File "C:\Users\name\Desktop\script.py", line 4, in <module>
for pageNum in range(1, mxd.dataDrivenPages.pageCount + 1):
AttributeError: 'unicode' object has no attribute 'dataDrivenPages'
Failed to execute (Script).

And these are my variables:

So, now I now I am just trying zo get the last one script to work, where I only enter output folder, and input mxd.

A: You need to still make the map document object from its parameter path, and make sure the data driven page is enabled and saved within the map doc, try:
mxdPath = arcpy.GetParameterAsText(1)
mxd = arcpy.mapping.MapDocument(mxdPath)

for pageNum in range(1, mxd.dataDrivenPages.pageCount + 1):
  # continue on


text:
Q: How to run the scripts without give the apk path in the setup function which is already installed in my phone using on Appium Python? Already app is installed in my phone without give the app path in setup function can i able to run the scripts in Unit-test in Python?

A: Yes, you can run tests on the device without providing a path to the .apk location if the app is already installed on the device.
What you need to do is provide appPackage and appActivity. For example for Youtube app appPackage and appActivity could be:
"appPackage": "com.google.android.youtube",
"appActivity": "com.google.android.youtube.StartActivity"

appPackage is let's say technical name for the app developers need to give, while appActivity refers to the functionality of the app, i.e. screen you are currently on.
To find out appPackage and appActivity easy way is to open the app on your connected device (emulator or real device) and execute from Terminal/Command prompt window:
dumpsys window windows | grep -E 'mCurrentFocus'
this will give you for example:
com.google.android.youtube\com.google.android.youtube.StartActivity
first part is appPackage and part after \ is appActivity
You can find more about it in this article: http://www.automationtestinghub.com/apppackage-and-appactivity-name/
and here: http://appium.io/docs/en/writing-running-appium/android/activity-startup/
Hope that helps.


text:
Q: Deleting Wine from my chromebook I recently tried to install a game called league of legends on my chromebook by downloading wine. It looked like it was working but I think I ran out of sapce. I am now trying to delete it becasue it is affecting other applications. When I looked at other threads I tried following them, but nothing worked. Can someone help me?
when I type in:
sudo apt-get remove wine* --purge
and later it allows me to type [Y/N]
It says:
dpkg: unrecoverable fatal error, aborting:
unable to flush /var/lib/dpkg/updates/tmp.i after padding: No space left on device
E: Write error - write (28: No space left on device)
E: Sub-process dpkg --set-selections returned an error code (2)
E: Couldn't record the approved state changes as dpkg selection states


text:
Q: For which values of a is A invertible? I am given a square matrix A with a along the pivot positions. I know that in order for matrix A to be invertible, a cannot equal 0. Are there any other values of a that would make this matrix not invertible? How can we tell?
Given Matrix A


text:
Q: No logro guardar nombre de imagen en mi tabla Intento hacer un upload de imágenes, el cual la imagen si me la sube a la ruta especificada, pero también quiero guardar el nombre de la imagen en la tabla el cual no me lo guarda.
Ya le hice un: var_dump("$logotipo"); el cual me aparece vacio: string(0) ""
Este es el formulario de donde subo la imagen:
<form id="regiration_form" action="procesamientos/recibedatos.php" method="post" enctype="multipart/form-data">

        Logotipo
        <input type="file" class="form-control" id="log" name="logotipo" accept="image/*" required>

</form>

Y este es el archivo que se encarga de subir la imagen al servidor, y grabar el  nombre de la imagen:
recibedatos.php:
<?php
include 'conexion.php';
$dbname = "mi_bd";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}

$logotipo= $_POST["logotipo"];

$uploadedfileload="true";
$uploadedfile_size=$_FILES['logotipo']['size'];
 echo $_FILES['logotipo']['name'];
 if ($_FILES['logotipo']['size']>200000) {
$msg=$msg."El archivo es mayor que 200KB, debes reduzcirlo antes de subirlo
";
$uploadedfileload="false";
}
 if (!($_FILES['logotipo']['type'] =="image/jpeg" OR $_FILES['logotipo']['type'] =="image/gif"))
{
$msg=$msg." Tu archivo tiene que ser JPG o GIF. Otros archivos no son permitidos
";
$uploadedfileload="false";
}
 $file_name=$_FILES['logotipo']['name'];
 $add=$_SERVER['DOCUMENT_ROOT']."/farmaciayanalisis/imagenes/farmacia/$file_name";
if($uploadedfileload=="true"){
if(move_uploaded_file ($_FILES['logotipo']['tmp_name'], $add))
{
 //Si la imagen es la correcta se inserta los datos en la tabla.
$sql= "INSERT INTO datos(logotipo)
VALUES ($logotipo')";
}else{
echo "Error al subir el archivo";
}
 }else{
echo $msg;
}

if ($conn->multi_query($sql) === TRUE) {
  echo "Datosinsertados correctamente";
} else {
  echo "Error al registrar Datos: " . $conn->error;
}

$conn->close();

?>

A: Estás intentando asignar a la variable $logotipo la variable $_POST['logotipo'], pero esto no es así.
Cuando envías un archivo mediante el formulario, tienes que acceder al mismo mediante $_FILES. Fíjate, que de hecho en tu código, para guardar la imagen en el servidor, comprobar el tipo de archivo etc, estás usando $_FILES y no $_POST.
Para obtener el nombre puedes utilizar:
$_FILES['logotipo']['name']

Lo cual ya estás haciendo más adelante al asignar dicho dato a $file_name.
Puedes ver más información de los datos de $_FILES con:
print_r($_FILES);


text:
Q: Auto change cell color based on auto updated cell value in google sheets I need a way/script to auto change the cell background between red and green if the updated cell value which is "=GOOGLEFINANCE("EURUSD")" is higher or lower from the previous update.
Is this even possible to do ?
Any help is highly appreciated.
I tried to modify this code to match my needs but this code doesn't even seem to be working, it keeps spitting: "TypeError: Cannot read properties of undefined (reading 'range')"
function onEdit(e)
{
  var ss = event.range.getSheet();
  if (ss.getName() !== 'Sheet11') return; // Get out quickly
  var changedCell = event.source.getActiveRange();
  var changedCellB8 = changedCell.getB8Notation();
  if (changedCellB8 !== 'B13') return;

  var c = event.value;  // We know we edited cell B3, just get the value
  var background = 'white'; // Assume 1 <= c <= 2
  if (c > 2) {
    background = 'red';
  }
  else if (c < 1) {
    background = 'black';
  }
  changedCell.setBackground(background);
  ss.getRange("B8").setBackground(background);
}

A: You will need conditional formatting.  I think that's what it's call.  I do most things with code.  The cell changes due to formulas do not generate onEdit triggers
conditional format builder

A: Your code is erroring out because the event parameter is first referred to as e and later as event. Therefore event is undefined, and event.range cannot be read. You can replace e with event to fix the error (but that will still not make the code to do what you want.)
The bigger issue is that you cannot catch formula updates with the onEdit() simple trigger — it only catches manual edits of cell values. Try an "on change" installable trigger instead.


text:
Q: Problems with getting Tables from Databases using sqlsrv_query in php I am having problems with sqlsrv_query in PHP. I get the following warning:
Warning: sqlsrv_query() expects parameter 1 to be resource, null given in C:\xampp\htdocs\Status.php on line 76

Notice: Array to string conversion in C:\xampp\htdocs\Status.php on line 76
A error occured: Array

This is my code:
<?php

$conn = OpenConnectionMsSQL();
#var_dump($conn);
$sql_select = "Select state_desc from sys.databases";
$params = array();

$query = sqlsrv_query($conn, $sql_select, $params) or die('A error occured:' . sqlsrv_errors());

$res = sqlsrv_num_rows($query);
while($row = sqlsrv_fetch_assoc($res))
{ echo ($row['state_desc']); }

?>

and this is my connection code:
<?php
    function OpenConnectionMsSQL()
    {
        try{
            $serverName = "***";
            $database = "***";
            $uid = "***";
            $pwd = "***";

            $connectionOptions = array("Database"=>"$database","Uid"=>"$uid","PWD"=>"$pwd");
            $conn = sqlsrv_connect($serverName, $connectionOptions);
            if($conn == false)
                die( print_r( sqlsrv_errors(), true));
            }

        catch(Exception $e)
            {
                exit("
"."Verbindung fehlgeschlagen!". "
". "Server Stopped"."
");#.$e->getMessage());
                exit("");#.$e->getMessage();

            }
    }

?>

How do I fetch my results correctly?

A: I just forgot to use sql_fetch_array, so I couldn't fetch my results.
The following snippet fixes the problem
$sql_select = "Select state_desc,name from sys.databases where name='master'";
$sql_version = "Select @@version as Version";
$stmt = sqlsrv_query($conn, $sql_select) or die('A error occured: ' . print_r( sqlsrv_errors(), true));
$version = sqlsrv_query($conn, $sql_version) or die('A error occured: ' . print_r( sqlsrv_errors(), true));

if (sqlsrv_has_rows($version)) {
    $data2 = sqlsrv_fetch_array( $version, SQLSRV_FETCH_ASSOC);

    echo "Serverinfo: ".$data2['Version']."
"."
";
} else {
    echo "No data found";
}


text:
Q: Include the content of a jsp in a servlet I have this servlet:
public class SaveImage extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = null;
        try {
            out = response.getWriter();
            out.println("<html>");
            ...

            // I want to include here the content of this jsp:
            // /WEB-INF/mybox.jsp
            // (also, with the full context of the servlet)

            ...
            out.println("</html>");
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Is there a problem doing it (response already committed?), how can I do this?

A: THANKS ozho , YOU HAVE HELPED ME TO give final shape to 2 year old pending project. Thanks.
Actually to redirect the request of tomcat from sun web server 7 to application server, since the jsps are not shown in tomcat directly, technique is to use a passthrough in app.config and let the tomcat handle the requests.
            import java.io.IOException;

            import javax.servlet.RequestDispatcher;
            import javax.servlet.ServletContext;
            import javax.servlet.ServletException;
            import javax.servlet.http.HttpServlet;
            import javax.servlet.http.HttpServletRequest;
            import javax.servlet.http.HttpServletResponse;

            /**
             * Servlet implementation class MY... Parvez Ahmad Hakim
             */
            public class MY extends HttpServlet {
                private static final long serialVersionUID = 1L;

                /**
                 * @see HttpServlet#HttpServlet()
                 */
                public MY() {
                super();
                // TODO Auto-generated constructor stub
                }

                /**
                 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
                 */
                protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

                    String pageName =request.getParameter("req");
                    if(pageName==null){
                        pageName="IC_LIC_Login.jsp";// default page
                    }
                    request.getRequestDispatcher(pageName).include(request, response);

                }

                /**
                 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
                 */

                protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                    String pageName =request.getParameter("req");

                    request.getRequestDispatcher(pageName).include(request, response);
                }

            }

A: request.getRequestDispatcher("/WEB-INF/my.jsp").include(request, response);

But you should not a servlet for outputting html like that. Just use a jsp, with either <jsp:include /> or <%@ include file=".." %>


text:
Q: finding max catches if you can move at a certain speed while objects appear at particular timestamps? I faced this problem in an interview, I couldn't solve it in interview.
I recall a similair problem that i solved during IOI though cannot recall it.
Given N houses in a line.
each of M pokemon makes an appearance at a house exactly once.
ex - a pokemon appears for an instant at 5th house at time = 6.
another pokemon appears for an instant at 7th house at time = 1.
and so on.
we start at house P, we can move at speed of X house/sec. find max number of pokemon you can catch?
All i can think of is greedy or bruteforce but bruteforce is exponential and greedy is incorrect.

A: Observation: Each Pokemon disappears right after they appear, so we need to be at a house at time=x to catch the Pokemon. If we can not make it in time, we never stop there.
Solution: create a new directed graph G=(V,A) where each v_i in V represents a house h_i = house(v_i) where a Pokemon appears at time t(v_i).
Create A containing arc u->v, for each such pair if t(u)+distance(house(u),house(v)) =< t(v). In other words: if it is possible to catch Pokemon at at house(v) after Pokemon at house(u), given the time constraints.
Create a root s of the DAG and create an arc s->u for u in V if distance(P, house(u)) <= t(u).
Now, for example, with a depth-first search, you can find the longest path and reconstruct the route you take in the original instance.


text:
Q: What is the earliest timestamp value that is supported in ZIP file format? I am trying to store dates as latest modification timestamp in a ZIP -file. It seems that ZIP format support only dates after 1980-01-01 as a last modification time (at least via Java API java.util.zip.ZipEntry )
Is this correct? Is the earliest supported modification timestamp really 1980-01-01 00:00:00? I tried to find some references to verify this but I couldn't find any.

A:
Zip entry timestamps are recorded only
  to two 2 second precision. This
  reflects the accuracy of DOS
  timestamps in use when PKZIP was
  created. That number recorded in the
  Zip will be the timestamp truncated,
  not the nearest 2 seconds.
When you archive and restore a file,
  it will no longer have a timestamp
  precisely matching the original. This
  is above and beyond he similar problem
  with Java using 1 millisecond
  precision and Microsoft Windows using
  100 nanosecond increments. PKZIP
  format derives from MS DOS days and
  hence uses only 16 bits for time and
  16 bits for date. There is defined an
  extended time stamp in the revised
  PKZIP format, but Java does not use
  it.
Inside zip files, dates and times are
  stored in local time in 16 bits, not
  UTC as is conventional, using an
  ancient MS DOS format. Bit 0 is the
  least signifiant bit. The format is
  little-endian. There was not room in
  16 bit to accurately represent time
  even to the second, so the seconds
  field contains the seconds divided by
  two, giving accuracy only to the even
  second.
This means the apparent time of files
  inside a zip will suddenly differ by
  an hour compared with their
  uncompressed counterparts every time
  you have a daylight saving change. It
  also means that the a zip utility will
  extract a different UTC time from a
  Zip member date depending on which
  timezone the calculation was done.
  This is ridiculous. PKZIP format needs
  a modern UTC-based timestamp to avoid
  these anomalies.
To make matters worse, Standard tools
  like WinZip or PKZIP will always round
  the time up to the next even second
  when they restore, thereby possibly
  making the file one second to two
  seconds younger. The JDK (i.e.
  javaToDosTime in ZipEntry rounds the
  time down, thereby making the file one
  to two seconds older.
The format does not support dates
  prior to 1980-01-01 0:00 UTC. Avoid
  file dates 1980-01-01 or earlier
  (local or UTC time).
Wait! It gets even worse. Phil Katz,
  when he documented the Zip format, did
  not bother to specify whether the
  local time used in the archive should
  be daylight or standard time.
And to cap it off… Info-ZIP, JSE and
  TrueZIP apply the DST schedule (days
  where DST began and ended in any given
  year) for any date when converting
  times between system time and DOS
  date/time. This is as it should be.
  Vista's Explorer, 7-Zip and WinZip
  apply only the DST savings, but do not
  apply the schedule. So they use the
  current DST savings for any date when
  converting times between system time
  and DOS date/time. This is just
  sloppy.

http://mindprod.com/jgloss/zip.html
tar files are so much better.


text:
Q: Can not pass metadata with metamask deeplink This is the deep-link:
ethereum:0xBaa11D872cfD22c4D9525E1011af790bB56d656E@1337?value=1e18&data=somedata
And this is the QR that is generated from the url above

i am not able to receive the metadata from payment receive event in solidity contract
this is the event log:
{
  logIndex: 0,
  transactionIndex: 0,
  transactionHash: '0x8d504a1253f30bbc43c5212434dc7dc52a122afc2d08cf6e2c496e34fb316ecd',
  blockHash: '0xcf91cdab48a97255c52532732fff9091a7ff5f371a6552f94aaac55a95fb42b1',
  blockNumber: 33,
  address: '0xBaa11D872cfD22c4D9525E1011af790bB56d656E',
  type: 'mined',
  id: 'log_8ce94ba5',
  returnValues: Result {
    '0': '0x49372600c1BD394922c0B6463611DeD4CbeDAf45',
    '1': '1000000000000000000',
    '2': null,
    _from: '0x49372600c1BD394922c0B6463611DeD4CbeDAf45',
    _amount: '1000000000000000000',
    data: null
  },
  event: 'MoneyReceivedWithData',
  signature: '0xf7d31a904a564a801af9dfae1796bd5fd339d215fedc9314fbfbcffb5c14f205',
  raw: {
    data: '0x0000000000000000000000000000000000000000000000000de0b6b3a764000000000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000000',
    topics: [
      '0xf7d31a904a564a801af9dfae1796bd5fd339d215fedc9314fbfbcffb5c14f205',
      '0x00000000000000000000000049372600c1bd394922c0b6463611ded4cbedaf45'
    ]
  }

this is the solidity functions:
Event:
 event MoneyReceived(address indexed _from, uint256 _amount);

Fallback function:
 fallback() external payable {
     emit MoneyReceived(msg.sender, msg.value);
 }

and as you can see the "data" field in the "returnValues" field is null.
Please help. I found no way to pass a metadata to transaction via mobile metamask QR scan transfer (same as deep-link). I need to understand how to build a proper deep-link url to pass the necessary data to my solidity event-emiter or is it a way to pass a metadata as a parameter through deep-link.


text:
Q: How to Save text over image with jquery I am new to javascript. i have the following code of javascript and html. the problem is that when i download the image the text written by the javascript dose not show on the downloaded image. or you can say in other words the text dose not print on the image. which i want to achieve.
following is the code

<script type="text/javascript">
  jQuery(function($){

    var textover_api;

    $('#target').TextOver({}, function() {
      textover_api = this;

    });

  });

</script>
<img src="demo.jpg" id="target" />

i want to achieve the functionality like http://addtext.com/.
thanking in advance.

A: You can make use of HTML5 using canvas and return the base64 data example here:
Source:Javascript; Adding text on image using canvas and save to image
draw();

function draw() {

    var canvas = document.getElementById('idCanvas');
    var context = canvas.getContext('2d');

    var imageObj = new Image();

  imageObj.onload = function() {
    context.drawImage(imageObj, 0, 0);
    context.font = "40px Calibri";
    context.fillStyle = "red";
    context.fillText("My TEXT!", 50, 300);

    var canvas = document.getElementById('idCanvas');
    var dataURL = canvas.toDataURL();

    alert(dataURL);
  }
imageObj.setAttribute('crossOrigin', 'anonymous');
imageObj.src = "http://lorempixel.com/400/200/";
};`

<canvas id="idCanvas" width="576" height="577"></canvas>

http://jsfiddle.net/hmr7c8po/


text:
Q: Is it possible to disable injection of implicit constructor methods/calls? The Java compiler generates constructors and injects super constructor calls in many circumstances.
For example,
class Foo {
    Foo() {}
}

becomes
class Foo {
    Foo() {
        super();
    }
}

I am not keen on the different circumstances and I would like to make the code explicit.
How do you disable the Java compiler from doing this if it is possible?

A: You cannot disable the Java compiler from making calls to super - this is one of the core principles how object orientation was designed in Java.
You might however be able to tell your IDE to always display these calls (or not).
However I recommend to stick with the standard - every Java developer knows about it and what might look a bit odd and unfamiliar to you now will become perfectly reasonable after a short time... :)

A: Default constructor. If you don't define a constructor for a class, a default parameterless constructor is automatically created by the compiler. The default constructor calls the default parent constructor (super()) and initializes all instance variables to default value (zero for numeric types, null for object references, and false for booleans).
Default constructor is created only if there are no constructors. If you define any constructor for your class, no default constructor is automatically created.
The first statement in any subclass constructor is ALWAYS super(). There is no need to make a call to it because it will be supplied automatically if the superclass have a default constructor without params.
If the parent class doesn't have a default constructor, you have to add an super(params) call.
Remember all classes implicitly will extend Object if they do not extend any class explicitly


text:
Q: phantomjs and simple examples gives TypeError: Attempting to change the setter of an unconfigurable property I'm working my way through the phantomjs examples but TypeError: Attempting to change the setter of an unconfigurable property.  errors keep popping up.  I wanted to pipe returned values to files but they are full of these error messages even with the simple examples see below.
var webPage = require('webpage');
var page = webPage.create();

page.settings.userAgent = 'Mozilla/5.0 (Linux; Android 9; SM-G960F Build/PPR1.180610.011; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/74.0.3729.157 Mobile Safari/537.36';

page.open('http://m.bing.com', function(status) {

  var title = page.evaluate(function() {
    return document.title;
  });

  console.log(title);
  phantom.exit();

});

Produces:
Bing
TypeError: Attempting to change the setter of an unconfigurable property.
TypeError: Attempting to change the setter of an unconfigurable property.

It should send back just Bing any workarounds?
I'm using PhantomJS 2.1.1 on Ubuntu 18.04 64bit.

A: As baptx stated there is a problem with ubuntu package, install it directly from the official source.
However it didn't solve my problem, I got an error with libssl_conf.so. The way I solved it was:
export OPENSSL_CONF=/dev/null


text:
Q: Update last activity based on the changes in the current activity in android? I have two activities A and B. I am currently in Activity A and from A I an starting activity B. Now After finish the work on B, based on the changes in the activity B I want to update the Activity A.

A: It sounds like startActivityForResult() is what you're looking for.
Example - Activity A starts Activity B with startActivityForResult().  When Activity B finishes it can return information back to Activity A via onActivityResult().
Google has a code example online: http://developer.android.com/reference/android/app/Activity.html#StartingActivities

A: Simply Override the onResume() Method of your first activity to accommodate new changes.
It will work for sure :)


text:
Q: Large .zip files download incomplete I am a severe novice, but I did quite a lot of research before posting, so I hope you can help.
I'm trying to serve a large .zip file that is hosted on an Apache server, about 6.4 Gb.  The file shows complete download in browser, but in fact only about 500Mb have been downloaded.  This seems like a very common problem and have found a lot of other posts and information on the web, but the problem has been persistent for me.
Large Zip file offered for download using php
IE download incomplete even though it claims success
Large zip downloads failing only in IE
I have been testing with Chrome 39.0.2171.71, but I get the same problem with FireFox and IE.  I think my file is much larger than what others have been posting about, therefore perhaps their solutions helped the situation, but didn't fix the root problem.  I have a second .zip file that is about 400Mb, and I use the same http headers with success.
The most useful article I have found is this: http://perishablepress.com/http-headers-file-downloads/ and I have copied much of the php shown below from that source, as it appears other posters on this website have done.
I have also tried using X-SendFile, but I don't think my webhost has the appropriate Apache module installed.  I've spent all day working on this, and have run out of ideas!  I have used a download manager with success, I don't know if this was just by chance or what, but I don't want to require my clients to have to download and install a separate program just to get the .zip file.
<?php
// HTTP Headers for ZIP File Downloads

// set example variables
$filename = "huge.zip";
$filepath = "****";

// http headers for zip downloads
// header("X-Sendfile: $filepath$filename");
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"".$filename."\"");
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($filepath.$filename));
set_time_limit(0);
ob_end_flush();
@readfile($filepath.$filename);
?>

Here are the response headers when I run the php above

Remote Address:76.162.142.242
Request URL:****/GetSW.php
Request Method:GET
Status Code:200 OK

Request Headers

Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8
Authorization:Basic ******
Connection:keep-alive
Cookie:_ga=GA1.2.1176828605.1417985823
DNT:1
Host:www.teamursa.org
Referer:http://www.teamursa.org/****.html
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36

Response Headers

Cache-Control:public
Connection:Keep-Alive
Content-Description:File Transfer
Content-Disposition:attachment; filename="huge.zip"
Content-Length:6720560824
Content-Transfer-Encoding:binary
Content-Type:application/octet-stream
Date:Sun, 07 Dec 2014 22:16:57 GMT
Expires:0
Keep-Alive:timeout=3, max=120
Pragma:public
Server:Apache
X-Powered-By:PHP/5.2.17

A: You might need to increase the memory limit on the server. Try the below just after the opening PHP tag
ini_set('memory_limit','16M');
And just keep increasing from 16M

A: I recommend you try using a web browser to download file directly, meaning you go to the address that file is stored at. E.g www.example.com/downloads/download.zip Hope this helps


text:
Q: add hours to new Date only showing NaN I know there are many questions like this when I googled it, and I cannot seem to make it work. I use Safari as my bowser, which is new to me since OS X Yosemite.  But, I cannot figure this one out.
All I am trying to do, using Keith Wood countdown plugin, is get a datetime from a database and add 2 hours.  Here is the code:
$(data).each(function(key, value) {

    var box = '';

    box += '
'+value.question+'
';
    box += '

';

    var newYear = new Date(value.added);
    var endtime = newYear.setHours(newYear.getHours() + (2));

    console.log(value.added);
    console.log(endtime);

    $('#listQuestions').append(box);
    $('#timer'+value.qid).countdown({until: endtime});

});

It seems pretty simple, I tried to make the new adjusted date (with the extra two hours) a new Date again, but that gave me the same problem.
Here is the output in console:

With console.log(new Date(endtime);
2014-10-24 19:48:01
Invalid Date
2014-10-24 19:39:14
Invalid Date
2014-10-24 19:30:23
Invalid Date

and:

With console.log(endtime):
2014-10-24 19:56:14
NaN
22014-10-24 19:48:01
NaN
2014-10-24 19:39:14
NaN
2014-10-24 19:30:23
NaN

Worth noting I have tried many examples I have found with adding hours to dates, but none of them worked, so this example seems the most logical, but I am doing something stupidly wrong. Any ideas?
UPDATE
With the help from below, I have some issues which perhaps I did not really make clear in my explaining.
It looks like the date coming in from a cycle jquery(ajax)/php/database/php(echo)/jquery(ajax) looks like this:

2014-10-24 19:30:23

I do not think the above is a valid date, but a string. I think this because if I add this:
newYear = new Date(value.added);

I get Invalid Date. So any getHours() request cannot be evaluated, and so gives an error.
I have tried breaking down the string, and recreate a new date like this:
var dt  = newYear.split(/\-|\s/);
endDate = new Date(dt[2] + '/' + dt[1] + '/' + dt[0] + ' ' + dt[3]);
console.log(endDate.getFullYear());

But the above gives me a NaN.
The reason I think its a string is if i put the following code:
if(String(value.added)){
                console.log('isString Date')
            } else {
                console.log('is Not String Date')
            }

console prints isString Date
And this explains why the countdown works, but does not give an accurate time.  The database is mySQL.
So is it because the time is being passed through php, and then JS, as the database is column is set to datetime ?

A: Just in case I tested with the last update to the question, and adding the 'T' fixes the problem:
var newYear = new Date(value.added.replace(" ", "T"));

That should fix the problem. Since there should be at most one space, there should be no need for any additional tests.

Update as my first answer was assuming the start date was invalid. End date is actually the problem:
var endtime = newYear.setHours(newYear.getHours() + (2));

That is certainly taking a risk as it may not work in all implementations. Plus it modifies newYear directly, so I would not otherwise see the point in creating a new variable.
I would suggest the following to fix the problem:
var endtime = new Date(newYear.getTime() + 7200000);

where 7,200,000 is 2 * 60 * 60 * 1000, or the number of milliseconds in 2 hours.

According to ECMAScript 5, the date format is parsed using the parse() function (15.9.4.2).
This tells you that the language tries to convert your string with a format similar to what x.toUTCString() would produce, which should be what you show in your output. This should match the simplified ISO 8601 format, without the need for the 'T' between the date and time:
YYYY-MM-DD HH:mm:ss.sssZ

From what I understand, the .sssZ is not required, but you could try something like this:
var newYear = new Date(value.added + ".000Z");

You may want to also check 15.9.5.42 toUTCString() and 15.9.5.43 toISOString().
However, if you are saying that you previously extracted a string from a Date object using toUTCString() and the conversion going back fails, then there is a bug in that JavaScript implementation, because ECMAScript clearly says that such a round trip should return the exact same value:

If x is any Date object whose milliseconds amount is zero within a particular implementation of ECMAScript, then all of the following expressions should produce the same numeric value in that implementation, if all the properties referenced have their initial values:

  x.valueOf()
  Date.parse(x.toString())
  Date.parse(x.toUTCString())
  Date.parse(x.toISOString())


text:
Q: Diff files and mark as yellow in Java Does anyone could recommend a framework or a java api that could help me compare two files? I would to compare both and mark one as yellow where we have the differences, like Tortoise do as example.

A: This question and its answers seem to be related to what you are asking. There referred APIs and libraries include
NetBeans Diff API
google-diff-match-patch


text:
Q: execute perforce commands through python I am writing a simple script which will sync one perforce directory through python however I am not able to do so.
It is not allowing me to execute anything in that [perforce] directory through script.
         Can someone please suggest me how I can run commands like p4 login,p4 sync in that directory?

A: There is an officially supported python API for perforce.
You should use that instead of subprocess because it allows you to treat a p4 connection as an object and manipulate it using the API instead of manually parsing the output of the p4 command.

A: Running "p4 sync" without any other arguments will sync the files mapped to the current directory by the current client workspace. When running the command from a Python script you'll need to be aware of where the scrip is actually running.
For debugging purposes, try running "p4 info" first: it'll show what the current working directory is, as well as showing you the rest of your Perforce environment details.
If you always want the script to sync the same directory, no matter where you run it, you might want to consider specifying a path to sync. For example:

*

*Depot syntax: p4 sync //depot/path/to/dir/...

*Local syntax (Windows): p4 sync c:\users\user\path\to\dir...

*Local syntax (*nix): p4 sync /home/user/path/to/dir/...

If you're client workspace, user or perforce server configuration is configured on a directory basis by P4CONFIG or being set by P4V, you may want to add the global options for these settings to the command as global options. For example:

*

*p4 -p server:1666 -c client_ws -u user sync //depot/path/to/dir/...

As you're running the commands from Python, you might find that the P4Python scripting API makes the configuration easier:
https://www.perforce.com/perforce/r14.2/manuals/p4script/python.programming.html

A: If P4Python is more than you want to deal with there is a Python class in the Perforce Workshop that provides that wraps the command line with the P4Python interface.
P4Python-esque CLI wrapper for Python

A: I have had good success running Perforce commands from Python, using the ActiveState Python 2.7, with the P4Python plugin.  You will need a p4 definition line, like the following:
p4Params = {'Port': "perforce_server_name:1666", \
            'Pass': "mypassword", \
            'User': "myname", \
            'Client': "myclient"}

Plus you'll need the P4 and P4Exception libraries:
from P4 import P4,P4Exception

With that in hand, you can perform most any Perforce command with the following construct.  This function syncs to Rev #0 to remove all controlled files from some depot location "depotPath":
  def removeWorkFiles(depotPath,p4Params):
  """Tell Perforce to remove the version files from the workspace"""
    p4 = P4(client=p4Params['Client'], port=p4Params['Port'], password=p4Params['Pass'])
    p4.user = p4Params['perfUser']
    try:
      p4.connect()                 # Connect to the Perforce Server
      p4.run_login()
      deletePath = depotPath + "#0"
      p4.run("sync", "-f", deletePath) # force to version "0", ie remove from workspace
      p4.disconnect()
    except P4Exception:
      for e in p4.errors:          # Display errors
        logging.error( e)

I highly recommend you read Perforce's P4 Python help page at:
https://www.perforce.com/perforce/r14.2/manuals/p4script/python.programming.html
This will give you some perspective, though it is not complete.  Hope this helps

A: If you know exact perforce commands that you could run in a CMD shell, you can make use of os.system('cmd '). You can also take a look at os.popen and subprocess.call to do the same thing.

A: There's p4swamp which is also a wrapper for the CLI
from p4swamp import p4

result = p4('sync')
print(result)


text:
Q: Formating window values with jq I would like to take the json output of window values from a program. The output of it currently is:
[
  3067,
  584
]
[
  764,
  487
]

But I need it to be formatted like: 3067,584 764x487. How would I go about doing this using jq or other commands?
I'm not very experienced with jq and json formatting in general, so I'm not really sure where to start. I have tried looking this up but am still not really sure how to do it.

A: If your input is a stream of JSON arrays, you could use jq's -s/--slurp command-line option.  Join the first array with comma, the second array with "x"; and finally join both strings with a space:
$ jq -sr '[(.[0]|join(",")), (.[1]|join("x"))] | join(" ")' <<JSON
[
  3067,
  584
]
[
  764,
  487
]
JSON
3067,584 764x487

Alternatively, simply use string interpolation:
jq -sr '"\(.[0][0]),\(.[0][1]) \(.[1][0])x\(.[1][1])"'

A: A solution that does not --slurp would be using input for every other array:
jq -r 'join(",")+" "+(input|join("x"))'

3067,584 764x487

Demo


text:
Q: Roots of a finite field and closure of a finite field According to Milne for each power $q=p^n$ there exists a field $\mathbb{F}_q$ with $q$ elements. I would like to understand what exactly happens with the roots of this.
Let us consider the very simple case where $p=3$, $n=2$ and thus $q=9$. Then the roots of $\mathbb{F}_q$ must be given by
$$
x^{9}-x = 0 \Rightarrow x=0 \text{ or } x^8-1=0
$$
Already we see the trivial root $x=0$. Then, another one is $x=1$ since $x^8=1$. After that I am confused with the rest of the roots since it is not very clear to me what are the exact modulo rules for this kind of fields. Any help?
And since I already asked the above let me ask one more question. For the specific example what would be the algebraic closure $\mathbb{F}$ of $\mathbb{F}_9$? What is the usual way to find such a closure?
Thanks a lot.

A: On the algebraic closure:
1) It is $\mathbb{F}_{3^n} \subset \mathbb{F}_{3^m}$ if and only if $n$ divides $m$.
2) In $\mathbb{F}_{3^n}$, all polynomials of degree $n$ factorize.
3) So in the field $F=\cup_k \mathbb{F}_{3^{k!}}$ (which is infinite of course), all polynomials factorize. This is the algebraic closure of $\mathbb{F_3}$.


text:
Q: CakePHP 2.x Project with unknown folder structure and database file, using EnvSwitcher Class I have a new project that is using a plugin class called EnvSwitcher. I went to set up the database file and the database.php file is empty, except for two lines I have never seen:
App::uses('EnvSwitcher', 'Lib/EnvSwitcher');
EnvSwitcher::includeBaseFile(__FILE__);

The project does not load, only gets white screen. I tried adding the database connect info to the file, and nothing. Tried to even replace the two lines with regular database info, and still nothing. What is going on with this?

A: It's an Environment switching class. You are using the class here:
https://github.com/angelxmoreno/CakePHP-Environment-Switcher/blob/master/EnvSwitcher.php
Check in folder: Config/env/_default/
There should be copies of your config files there to modify.
If there is more than folder in: Config/envs, then there should be a copy of the files in each one to switch between environments.


text:
Q: Auction style countdown timer JS, ASP.net, SQL Server I'm trying to display a countdown timer for Number of Days,Hours,Minutes,Seconds left until Auction is over on my website.
I've followed this tutorial for a countdown timer:
https://www.sitepoint.com/build-javascript-countdown-timer-no-dependencies/
My problem is i'm storing a datetime timestamp in my SQL table that says when the auction is over and I can pull this into my website via a Token but it would be in this format 2017-01-02 03:00:00.000 in the JS file of the example at the bottom it's in this format: var deadline = new Date(Date.parse(new Date()) + 15 * 24 * 60 * 60 * 1000);
I've found the following article that explains how to take my datetime column in SQL an pull minutes, seconds, hours but it's not all on 1 field.
http://sqlhints.com/2014/02/23/how-to-get-time-hour-minute-second-and-millisecond-part-from-datetime-in-sql-server/
I'm not sure how to modify this JS so that it can read my end date/time from the table directly in it's native datetime format.
JS:
function getTimeRemaining(endtime) {
  var t = Date.parse(endtime) - Date.parse(new Date());
  var seconds = Math.floor((t / 1000) % 60);
  var minutes = Math.floor((t / 1000 / 60) % 60);
  var hours = Math.floor((t / (1000 * 60 * 60)) % 24);
  var days = Math.floor(t / (1000 * 60 * 60 * 24));
  return {
    'total': t,
    'days': days,
    'hours': hours,
    'minutes': minutes,
    'seconds': seconds
  };
}

function initializeClock(id, endtime) {
  var clock = document.getElementById(id);
  var daysSpan = clock.querySelector('.days');
  var hoursSpan = clock.querySelector('.hours');
  var minutesSpan = clock.querySelector('.minutes');
  var secondsSpan = clock.querySelector('.seconds');

  function updateClock() {
    var t = getTimeRemaining(endtime);

    daysSpan.innerHTML = t.days;
    hoursSpan.innerHTML = ('0' + t.hours).slice(-2);
    minutesSpan.innerHTML = ('0' + t.minutes).slice(-2);
    secondsSpan.innerHTML = ('0' + t.seconds).slice(-2);

    if (t.total <= 0) {
      clearInterval(timeinterval);
    }
  }

  updateClock();
  var timeinterval = setInterval(updateClock, 1000);
}

var deadline = new Date(Date.parse(new Date()) + 15 * 24 * 60 * 60 * 1000);
initializeClock('clockdiv', deadline);


text:
Q: Using multiple audio sources for a media player in Android Studio I want to create a media player with multiple sounds and play one at random when a button is clicked.
I tried using the MediaPlayer.create() function but I can only set one audio source.
I also tried using the setDataSource() function but this only seems to work for resources that are stored outside the application (as far as I know).
String meowsounds[] = new String[]{
                "R.raw.meowcat1",
                "R.raw.meowcat2",
                "R.raw.meowcat3",
                "R.raw.meowcat4",
                "R.raw.meowcat5",
        };
        MediaPlayer mp = new MediaPlayer();
        meow.setOnClickListener((view) ->{
            Random random = new Random();
            int r = random.nextInt(6-1) + 1;
        try{
            mp.setDataSource(meowsounds[r]);
            mp.prepare();
            mp.start();
        }catch(Exception e){e.printStackTrace();}
    });

This code doesn't give any error while running but doesn't play anything on click
EDIT: Updated code which works on first click but not on subsequent clicks:
meow.setOnClickListener((view) ->{
            Random random = new Random();
            int r = random.nextInt(6-1) + 1;
            Toast.makeText(MainActivity.this,Integer.valueOf(r).toString(),Toast.LENGTH_SHORT).show();
            try{
                if(r==1)
                    fileDescriptor = MainActivity.this.getResources().openRawResourceFd(R.raw.meowcat1);
                else if (r==2)
                    fileDescriptor = MainActivity.this.getResources().openRawResourceFd(R.raw.meowcat2);
                else if (r==3)
                    fileDescriptor = MainActivity.this.getResources().openRawResourceFd(R.raw.meowcat3);
                else if (r==4)
                    fileDescriptor = MainActivity.this.getResources().openRawResourceFd(R.raw.meowcat4);
                else
                    fileDescriptor = MainActivity.this.getResources().openRawResourceFd(R.raw.meowcat5);
                mp.setDataSource(fileDescriptor.getFileDescriptor(), fileDescriptor.getStartOffset(), fileDescriptor.getLength());
                mp.prepare();
                mp.start();
            }catch(Exception e){e.printStackTrace();}
        });

A: R - is the class with constants. "R.raw.meowcat1" - is the simple string and it is not constant which consider link to file.
First, you need to create int array of raw constants, but not string array of simple strings.
Second, If you want to play file from raw, you need to create AssetFileDescriptor for this raw file and use in setDataSource method. For example:
    AssetFileDescriptor fileDescriptor = getContext().getResources().openRawResourceFd(R.raw.meowcat1);
    mediaPlayer.setDataSource(fileDescriptor.getFileDescriptor(), fileDescriptor.getStartOffset(), fileDescriptor.getLength());

And don't forget please release codec in onDestroy method.


text:
Q: Different icons for multiple Select2 dropdowns I am currently using Select2 to make my dropdowns searchable. I have gotten to the point of where I can change the icon but now when I am calling Select2 on another drop-down and change the icon it shows up twice. This is the code I have at the moment;
    $(".where__heading").select2({
        placeholder: "Try 'Belfast'",
        allowClear: false,
    });
    $('b[role="presentation"]').hide();
    $('.select2-selection__arrow').append('');

   Calling in it again below on a different dropdown....

    $(".how__long").select2({
        placeholder: "1-2 days",
        allowClear: false,
    });
    $('b[role="presentation"]').hide();
    $('.select2-selection__arrow').append('');

I can't seem to figure this out. Do I just need to make this more precise;
$('.select2-selection__arrow').append('');

Thanks for the help :)

A: Yes, it needs to be more precise. Something like this would work.
$('.where__heading').next().find('span.select2-selection__arrow').append('');
$('.how__long').next().find('span.select2-selection__arrow').append('');


text:
Q: Robotium with parameter Is there any way from which i can run a single test case multiple times with different data in robotium tesing of an android application.
Just like parameterized juint testing.
public class UserTest extends
        ActivityInstrumentationTestCase2<MainActivity> {

public UserTest() {
        super(TestActivity.class);
    }

    @Override
    public void setUp() throws Exception {
        // setUp() is run before a test case is started.

        // This is where the solo object is created.
        solo = new Solo(getInstrumentation(), getActivity());
    }

public void testUserData1() throws Exception {

        // UserBean
        Bean bean = setUp.get(0);
        dataTest(bean);

    }

    public void testUserData2() throws Exception {

        // UserBean
        Bean bean = setUp.get(1);
        dataTest(bean);

    }
public void dataTest(Bean bean) {
        Log.e("testAddNote userbean", bean.toString());

        // Login
        solo.enterText(0, bean.getUserName());
        solo.enterText(1, bean.getPassWord());
        solo.clickOnButton(0);
}

this the way currently i am running test cases is there a way by which dataTest(Bean) can be executed multiple times with setUp elements as parameters.Means i have to call single method multiple times with different parameters.

A: I just notice that this only works if you are using https://code.google.com/p/zohhak/
In that case you can do:
@TestWith({
           "2,  true",
           "6,  false",
           "19, true"
})
public void testPrimeNumberValidator(int number, boolean isPrime) {
assertThat(…
}


text:
Q: get_post_meta doesnt work after moving wordpress website I have this small piece of code that doesn't work when i MOVE a WordPress website to another location, (IT DOES WORK ON THE ORIGINAL LOCATION):
function displayCustomFields() {
global $post;
$rt_gallery_images = get_post_meta( $post->ID, "rtthemert_gallery_images");
var_dump ($rt_gallery_images);
}

var_dump displays:
array( 0 => boolean false )

But if I remove the meta_value like the following code :
function displayCustomFields() {
global $post;
$rt_gallery_images = get_post_meta( $post->ID);
var_dump ($rt_gallery_images);
}

the var_dump shows:
'rtthemert_gallery_images' => array
      0 => string 'a:1:{i:0;s:72:"/ssold/wp-content/uploads/2012/10/picture-3.jpg";}' (length=81)

and the rest of the meta values
I have exactly the same code in both location, why it works on the original and not on the copy ?

A: I realized what was the problem, the db has been migrated and some serialized data has been mistakenly edited. I was able to solve this by running the code on the following page:
http://alexscammon.com/2011/06/migrating-wordpress-blogs-fixing-the-serialization/


text:
Q: How to get data from logged users in views.py? (Django social-auth-app-django) I've successfully logged in my facebook account using Social-Auth-App-Django. Now I need to get my user ID so that I can filter the database using the user's ID but I don't have any idea how to do it. In django template it looks like this {{ user.id }} but I don't know how to get it in views.py
Here's my template code for login into facebook

         Login with Facebook

And here's my code in views.py
    @login_required
    def home(request):
         items = Products.objects.filter(product_owner__id=user_id)
         return render(request, 'seller.html', {
             "items": items
    })

user_id is what I actually need.
Thanks in advance!

A: The way you do that would be;
@login_required
def home(request):
    items = Products.objects.filter(product_owner=request.user)
    return render(
        request,
        'seller.html',
        {
            "items": items
        }
    )

If you didn't have the login_required decorator this wouldn't work however. In that case you'd have to check that they're authenticated.
That scenario would look more like;
def home(request):
    if request.user.is_authenticated:
        items = Products.objects.filter(product_owner=request.user)
    else:
        items = Products.objects.none()

    return render(
        request,
        'seller.html',
        {
            "items": items
        }
    )

Docs relating to this can be found here; https://docs.djangoproject.com/en/3.0/topics/auth/default/#authentication-in-web-requests


text:
Q: Как построить матрицы по данным отношениям? Есть 2 вида отношений a = {(x, y) ∈ R^2 | x + y = 0} и b = {(x, y) ∈ N^2 | y = x^2}. Как по ним построить матрицы?
Я правильно понимаю, что в случае a - это будет матрица из нулей, в которой на местах x и y будут единицы, если x + y = 0, а в случае b - это матрица из нулей, в которой на местах x и y будут единицы, если y = x^2?
Пример b

  x 1 2 3 4 5 6 7 8 9
y +------------------
1 | 1 0 0 0 0 0 0 0 0
2 | 0 0 0 1 0 0 0 0 0
3 | 0 0 0 0 0 0 0 0 1
4 | 0 0 0 0 0 0 0 0 0

Но как строить такие матрицы? Они ведь бесконечные. Как мне, например, перемножить 2 матрицы по отношению b?


text:
Q: how use OAuth 2.0 from google for post blogger api? when requesting post for blogger api like
https://www.googleapis.com/blogger/v3/blogs/blogid/posts?key=my key
Authorization: /* OAuth 2.0 token here */ required
How get and use this token and I get josn client_id and client_secret?
body josn is

{
  "kind": "blogger#post",
  "blog": {
    "id": "xxxxxxxxx"
  },
  "title": "A new post",
  "content": "content..."
}


text:
Q: Am I right to choose NetBeans over Eclipse? I'm a student, want to star some small Java projects, for fun and learning. I think GUI designer would be important, so guess NetBeans would be my choice. However, the company I'm working in and many many other people I know are using Eclipse. So...

*

*Am I making the right decision (choosing NetBeans)?

*Which one of these two do you prefer, and why?

*just curios: Is there any other Java SDK out there?

A: IDEs and SDKs are not the same thing. Netbeans and Eclipse are IDEs (Integrated Development Environment). SDK is "Software development kit", basically, java, the compiler, and a whole bunch of other tools that you shouldn't worry about for now.
With the JDK alone, you can write java in a text editor and compile on the command line. IDEs are intended to simplify this process. Both Netbeans and Eclipse are powerful tools, but you're likely to be better off using what people around you are using so that you can learn from them.

A: Both Netbeans and Eclipse are good choices when it comes to java IDE, they both offer beginners a host of features and plugins that will make learning Java a lot easier.  If you MUST HAVE a GUI designer then I would recommend netbeans (as its the only GUI designer I've actually tried) but for a beginner I recommend not using a designer all together.  Especially just starting out learning how to design a GUI via code is useful. Java's windowing APIs are pretty simple to learn and shouldn't present too much of a challenge. My recommendation would be to just pick an IDE (either netbeans or eclipse) and start learning to code (don't worry about the GUI at first).  Once you feel comfortable coding you can worry about GUI designers or not -- they're useful tools for rapid design but can also complicate the learning process.

A: I personally use Eclipse, but Netbeans is also very good. If you want to use the GUI designer, I would go with Netbeans because their GUI designer is much better. It is all preference. There is also products like JBuilder, Check out this page for a whole bunch of IDE's. http://www.webdeveloper.com/java/java_ides.html

A: *

*Looking at other products is always a good decision.

*Eclipse is a very strong machine when used with plugins.

*SDK ? Means IDE ? Intellij Idea is the next IDE I am going to test. Just for curiosity.

A: I don't use GUI designers so won't comment on that aspect. Both are free so try each of them out. A lot of IDE choice boils down to personal preference, I'm a fan of text editors and command lines. No one can give you the "right"  answer since no one is you and this is a fairly subjective area.

A: I'd say look for features that you are interested in and give all suitable IDEs a try.  I'd been using eclipse for 5 years mostly because it was free and I liked in more than NetBeans.  I just recently started using IntelliJ and like it a lot more but am paying the price for not having switched earlier.

A: Yes, if you like Netbeans, you should choose it over Eclipse.  Choosing the IDE in which you  more comfortable will help you learn Java and the tools much quicker.  At a later date, it will probably be worthwhile to try Eclipse or IntelliJ.  Each IDE has its strengths.  I started with Netbeans and found it a much more initiative IDE than Eclipse.  However, Eclipse is also an excellent IDE.  Now I frequently use IntelliJ and Netbeans, and I kick around in Eclipse from time to time.


text:
Q: How to commit offset manually in Kafka Sink Connector I have a Kafka Sink Task which is listening to a Kafka topic via
put() method.
But I do not want to auto commit the offset as I have some processing logic once record is fetched from Kafka.
After fetching the records from Kafka, if the processing is successful then only I want to commit the offset else it should read from the same offset again.
I can see there is method commitSync() in Kafka consumer but cannot find an alternative in Sink Connector for the same.

A: Sink Kafka Connector-Commit
If the option(enable.auto.commit) is False, automatically commit every 60 seconds according to the option(offset.flush.interval.ms) below. and if there is no error in your put() method, it will be committed normally.
offset.flush.interval.ms
Interval at which to try committing offsets for tasks.

Type: long
Default: 60000
Importance: low

To manage offset in Sink Kafka
Kafka Connect should commit all the offsets it passed to the connector via preCommit. But if your preCommit returns an empty set of offsets, then Kafka Connect will record no offsets at all. enter link description here
SinkTask.java

/**
 * Pre-commit hook invoked prior to an offset commit.
 *
 * The default implementation simply invokes {@link #flush(Map)} and is thus able to assume all {@code currentOffsets} are committable.
 *
 * @param currentOffsets the current offset state as of the last call to {@link #put(Collection)}},
 *                       provided for convenience but could also be determined by tracking all offsets included in the {@link SinkRecord}s
 *                       passed to {@link #put}.
 *
 * @return an empty map if Connect-managed offset commits are not desired, otherwise a map of committable offsets by topic-partition.
 */
public Map<TopicPartition, OffsetAndMetadata> preCommit(Map<TopicPartition, OffsetAndMetadata> currentOffsets) {
    flush(currentOffsets);
    return currentOffsets;
}

or
SinkTaskContext.java

/**
 * Request an offset commit. Sink tasks can use this to minimize the potential for redelivery
 * by requesting an offset commit as soon as they flush data to the destination system.
 *
 * This is a hint to the runtime and no timing guarantee should be assumed.
 */
void requestCommit();

A: Add this property : ("enable.auto.commit", "false")
enable.auto.commit has a default value of true and a second property auto.commit.interval.ms has a default value of 5000


text:
Q: Visual Studio Unit test ShimsContext messing with Garbage Collector Here is an interesting question: Why does the garbage collection not work for the simple unit test initialization example below? At least for me running VS2013 .NET 4.5 I eventually run out of memory and get a out of memory exception.
The shimmed method is needed, without that the garbage collector works just fine also inside the ShimsContext.
This is boiled down from one of my tests where a large xml file was parsed with several million temporary object creations, eventually leaving me without any memory.
Class under test
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MemoryTester
{
    public class Program
    {
        static void Main(string[] args)
        {
        }

        static void MethodToFake()
        {
            Console.WriteLine("This is the original method");
        }
    }

    public class OutsideClass
    {
        public OutsideClass()
        {
        }

        ~OutsideClass()
        {

        }
    }
}

Unit test class
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.QualityTools.Testing.Fakes;

namespace Tests
{
    [TestClass]
    public class MemoryTests
    {
        protected IDisposable Context;

        [TestInitialize]
        public void InitTest()
        {
            using (ShimsContext.Create())
            {
                MemoryTester.Fakes.ShimProgram.MethodToFake = () =>
                {
                    Console.WriteLine("This is the shimmed method");
                };

                while (true)
                {
                    //This will never be garbage collected, why?
                    MemoryTester.OutsideClass nc = new MemoryTester.OutsideClass();
                }
            }

            while (true)
            {
                //Outside of ShimsContext, we will garbage collect just fine
                MemoryTester.OutsideClass nc = new MemoryTester.OutsideClass();
            }
        }

        [TestMethod]
        public void AttributeSerializerMemoryTest()
        {
            Assert.IsTrue(true);
        }

        private TestContext testContextInstance;
        public TestContext TestContext
        {
            get
            {
                return testContextInstance;
            }
            set
            {
                testContextInstance = value;
            }
        }
    }
}