text:
Q: SoundPool slowing down app I have a class called Sound.java that consists of 3 functions (initSound, addSound, and playSound).
public static void initSound(Context con) {
    mContext = con;
    soundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 0);
    soundPoolMap = new HashMap<Integer, Integer>();
    audioManager = (AudioManager)mContext.getSystemService(Context.AUDIO_SERVICE);
    streamVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
    streamVolume = streamVolume / audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
}

public static void addSound(int index, int SoundID) {
    soundPoolMap.put(index, soundPool.load(mContext, SoundID, 1));
}

public static void playSound(int index) {
    soundPool.play(soundPoolMap.get(index), streamVolume, streamVolume, 1, 0, 1f);
}

I called the initSound and addSound in the MainGame.java constructor.
Sound.initSound(getContext());
Sound.addSound(1, R.raw.machine_gun);

and called playSound inside a Thread (looping) in MainGame.java. PlaySound called every second when an event is triggered (for example, when an enemy is in sight, troops (more than one) will shoot (play the sound) continuously until the enemy is dead).
Sound.playSound(1);

The problem is when the sound plays, the app is slowing down.
I'm using soundpool because as far as I know for sound effects, soundpool is better than mediaplayer. (I've tried mediaplayer and the lag is even more.)
The sound file that I use is .wav (unsigned 8bit PCM, 1 Channel, 8000hz) with size 5.44KB.
Is there a better way to play effect sounds without slowing the game performance, or is mine wrong? I really appreciate any ideas and responses.

A: According to the SoundPool docs, it decodes to 16-bit PCM, so you could change to that and see if you get some performance out of that. Other than that, your code seems pretty similar (at least as far as I can remember) to stuff I've done before and I didn't see any significant perf problems (I believe I wasn't even using WAV, I was just using OGGs, but I don't remember for sure). Are you trying this on an actual device, or just the emulator?

A: I had the same problem. Then I've created a new thread for the soundpool and added 20ms sleep into the while loop. The problem is gone.


text:
Q: Passing XML parameter to a stored procedure via ASMX web service I have a SQL Server 2005 stored procedure that has a signature like this:
CREATE PROCEDURE [dbo].[ProcTRequest]
   @Pxml xml, @ClientCode varchar(10)
AS
BEGIN
  ...
END

I'm tasked with writing an .asmx web service that will call this stored procedure. This is where I'm having a block.
If the parameter @Pxml is specified as string in the C# web method, we get

Server was unable to process request.

Then tried XmlText as the type for @Pxml, which resulted in

Server was unable to process request. Method MyWebService.MyWebMethod can not be reflected. There was an error
  reflecting 'PXml'. ->; There was an error reflecting type
  'System.Xml.XmlText'. -> System.Xml.XmlText cannot be used as: 'xml
  element'.

What is the correct way to call this stored procedure from a C# web method? Please note that the @Pxml parameter will always be a well-formed XML.
The person that will be calling this web service is using Curl on a Unix system.
Though the requirement is an ASMX, if this can be implemented via WCF, can you please show me how with a piece of pseudo code? I'm not familiar with WCF yet.
Please help. Thank you.
UPDATE: This is how I call the SP
 [WebMethod]
 public string GetRequestID(string PXml, string clientcode)
    {
        Database db = DatabaseFactory.CreateDatabase();
        using (IDataReader dr = db.ExecuteReader("ProcRequestID", PXml, clientcode))
        {
            return dr["RequestID"].ToString();
        }
    }

A: Couldn't you use a string on the ASMX interface (so the caller send you a string), but inside the ASMX web service, you define the @PXml parameter on the stored procedure call as SqlDbType.Xml ? I think that ought to work ....
Something along the lines of :
[WebMethod]
public void MyWebMethod(string input, string clientCode)
{
        using (SqlConnection conn = new SqlConnection(your-connection-string-here))
        using (SqlCommand cmd = new SqlCommand("dbo.ProcTRequest", conn))
        {
            cmd.CommandType = CommandType.StoredProcedure;

            cmd.Parameters.Add("@Pxml", SqlDbType.Xml);
            cmd.Parameters.Add("@ClientCode", SqlDbType.VarChar, 10);

            cmd.Parameters["@Pxml"].Value = input;
            cmd.Parameters["@ClientCode"].Value = clientCode;

            conn.Open();
            cmd.ExecuteNonQuery();
            conn.Close();
        }
}

Since you're just calling the stored proc and not expecting a result set back - use ExecuteNonQuery instead of ExecuteReader.
Also vitally important : tell ADO.NET that you're calling a stored procedure! That's what this line does:
            cmd.CommandType = CommandType.StoredProcedure;

Otherwise, ADO.NET by default expects to get full inline SQL statement and might just not be able to parse and execute that ....

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why does npm install many packages into "/node_modules" instead of only one? I experience strange behavior of npm on npm install <package> command. Before it installed a package in its own dedicated directory. For example, I type this command:
$ npm i babel-preset-es2015

And I get only one /babel-preset-es2015 directory under /node_modules directory, like this:
node_modules/babel-preset-es2015

Now it populates my /node_modules with dozen strange packages. On babel-preset-es2015 installation it installs some 94 packages:

What a behavior is this? Is it normal? Why does it start happening? Is it some king of settings I activeted by mistake? My npm and node versions:
$ npm -v
3.3.12
$ node -v
v5.3.0

A: because you are using npm v3 which installs dependencies flattened, so dependencies of dependencies (and their dependencies ...) end up in same folder,
more on npm v3 changelog


text:
Q: Handling loyalty credits with different expiry date and calculation I'm creating a membership system with loyalty point for a restaurant.
Every member spend at the restaurant the merchant will issue loyalty point for member as cashback, and they were able to use the loyalty point in their account and act as money for transaction. And every points has its expiration date which is 3 months.
Here's the problem im facing:
The logic I write could not calculate the remaining points and add on to the rest if they were only use partial point.
This is my table
CREATE TABLE `transaction_record_tpg` (
  `trans_id` int(15) NOT NULL,
  `collected_datetime` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `expired_date` datetime NOT NULL,
  `user_id` int(15) NOT NULL,
  `m_debit` decimal(6,2) NOT NULL,
  `m_credit` decimal(6,2) NOT NULL,
  `collect_outlet` varchar(255) NOT NULL,
)

I would like to create a table that can automatically calculate user's debit/credit transaction record with different expiration date.
Below are the test case that I created:

From the table,
you can see that the member gained 15 pts at sept 1, and used 11 pts on sept 10 and oct 10 respectively.
So the user actually still has 4 pts left and the expiry date and collect date should remain the same which is (sept 1-dec 4).
Then the user gained 25 pts on oct 31 and dec 5 respectively, and on jan 10 used 10 pts, but by now the 4 pts from above CANNOT add into the calculate as the pts is already expired.
So we should only use 20pts that we gain from oct 31 to minus 10 pts, which left us 10pts plus 5 points from dec 5th.
So by now (25th feb 2020), the 10pts left from oct 31 is expired, which only left 5 pts in total.
So the computer should show me 5 points.
However the computer calculate as -16 pts which is obviously not the answer.
Here's the logic i use to pull out the result from database:
<?php

$member_session = $_SESSION['u_id'];
$get_member =
"SELECT(SELECT SUM(m_debit) AS metallic_point FROM transaction_record_tpg WHERE user_id = $member_session AND  expired_date >= CURRENT_DATE())
    -
    (SELECT SUM(m_credit) AS metallic_point FROM transaction_record_tpg WHERE user_id = $member_session)
    ";
?>

Can anyone tell me what went wrong and what should i do to fix the bug? Or is there a better way to record and do this kind of function?

A: To elaborate my suggestion in the comments, I would implement the following algorithm for spending points:

*

*Find the oldest still valid rows (say A and B) with a sum equal or larger than the required amount (X). How to select rows that sum to a certain value

*If such rows do not exist, return an error.

*Mark rows A and B as "spent"

*Calculate the remaining points (C = A + B - X)

*If C == 0 go to the end

*Find max expiration date (D) between A and B

*Create a new row with expiration date D and amount C.

*The end

Make sure to wrap all database calls into one transaction, or you could create a room for weird bugs and exploits.


text:
Q: Clear the float in CSS I have this code and I'm trying to clear the float using 2 methods:
overflow and clear, but it don't work as supposed to.

body {
  border: 1px solid;
  padding: 0 auto;
}

header {
  height: 25%;
  border-bottom: 1px solid;
}

header #logo {
  float: left;
  text-align: center;
  width: 25%;
}

header #titre {
  background: black;
  color: white;
  float: right;
  text-align: center;
  width: 75%;
}

#xd {}

nav {
  width: 25%;
  text-align: center;
  float: left;
}

section {
  border-left: 1px solid;
  width: 75%;
  float: right;
  text-align: center;
}

.clr {
  clear: both;
}
<!DOCTYPE html>

sécurité des réseaux

logo

#

#

#

#

#

Firewall (pare-feu)

        Chaque ordinateur connecté à internet (et d'une manière plus générale à n'importe quel réseau informatique) est susceptible d'être victime d'une attaque d'un pirate informatique. La méthodologie généralement employée par le pirate informatique consiste
        à scruter le réseau (en envoyant des paquets de données de manière aléatoire) à la recherche d'une machine connectée, puis à chercher une faille de sécurité afin de l'exploiter et d'accéder aux données s'y trouvant.

Cette menace est d'autant plus grande que la machine est connectée en permanence à internet pour plusieurs raisons :

La machine cible est susceptible d'être connectée sans pour autant être surveillée ;

La machine cible est généralement connectée avec une plus large bande passante ;

La machine cible ne change pas (ou peu) d'adresse IP.

I don't understand why the text are not at the line with the first element in nav.
And also the border it's not complete. Why this is happening and how to fix it?

A: See fiddle
Add CSS on this tag
section{box-sizing: border-box;}

A: In you code, you are assigning 25% width to nav and 75% width to section. But Section has a 1px border so in the end it's exceeding the 75% assigned. Hence, the whole section is placed under nav.
In your same code, removing the 1px border or making the section width 74% will work as you expect, because there is enough space for that extra pixel.
By the way, I don't think that clearing the float is what you are looking for.

body {
  border: 1px solid;
  padding: 0 auto;
}

header {
  height: 25%;
  border-bottom: 1px solid;
}

header #logo {
  float: left;
  text-align: center;
  width: 25%;
}

header #titre {
  background: black;
  color: white;
  float: right;
  text-align: center;
  width: 75%;
}

#xd {}

nav {
  width: 25%;
  text-align: center;
  float: left;
}

section {

  width: 75%;
  float: right;
  text-align: center;
}

.clr {
  clear: both;
}
<!DOCTYPE html>

sécurité des réseaux

logo

#

#

#

#

#

Firewall (pare-feu)

        Chaque ordinateur connecté à internet (et d'une manière plus générale à n'importe quel réseau informatique) est susceptible d'être victime d'une attaque d'un pirate informatique. La méthodologie généralement employée par le pirate informatique consiste
        à scruter le réseau (en envoyant des paquets de données de manière aléatoire) à la recherche d'une machine connectée, puis à chercher une faille de sécurité afin de l'exploiter et d'accéder aux données s'y trouvant.

Cette menace est d'autant plus grande que la machine est connectée en permanence à internet pour plusieurs raisons :

La machine cible est susceptible d'être connectée sans pour autant être surveillée ;

La machine cible est généralement connectée avec une plus large bande passante ;

La machine cible ne change pas (ou peu) d'adresse IP.

What Jagdish Parmar propopses is also correct, as it includes the width of the border inside the total width of the box:
section{box-sizing: border-box;}

A: Try this, you have 100% + 1px
section {
  border-left: 1px solid;
  width: calc(75% - 1px); // Changed this line
  float: right;
  text-align: center;
}

Live JsFiddle - https://jsfiddle.net/grinmax_/4qq133mu/

A: your problem is  you have 100% + 1px
there is several method to solve that  one is trick of box module
section{box-sizing: border-box;}

other is to calculate your size before put it that also work very will


text:
Q: Ubuntu 11.04 and health of SSD I have to install Ubuntu 11.04 on server with 4 x 160 GB SSD raids maintained as RAID. I need to stick to v11.04 because it's required software we use.
I want to make sure, that I can safely install this version on Ubuntu on SSD disks. I heard, that some time ago Linux had some problems with block writing(?), what caused faster SSD ageing.

A: 11.04 and SSDs should get along just fine, although it makes me a bit nervous that you're dependent on an interim release for something in production - that doesn't have anything to do with the SSDs, though.
I've been using the same SSD on my home workstation with very heavy use (constant loading and reloading of VM images) since 9.04 or so, no issues; in general you really should not have any problems regardless.


text:
Q: When I have tried to run maze_solver code im not getting the output, how do I get the expected output? N = 4

def printSolution( sol ):

    for i in sol:
        for j in i:
            print(str(j) + " ", end ="")
        print("")

def isSafe( maze, x, y, visited):

    if x >= 0 and x < N and y >= 0 and y < N and maze[x][y] == 1 and visited[x][y] == True:
        return True

    return False

def solveMaze( maze ):

    sol = [ [ 0 for j in range(4) ] for i in range(4) ]
    visited = [ [ 0 for j in range(4) ] for i in range(4) ]

    if solveMazeUtil(maze, 0, 0, sol, visited) == False:
        print("Solution doesn't exist")
        print(-1)
        return False

    printSolution(sol)
    return True

def solveMazeUtil(maze, x, y, sol, visited):
    if x == N - 1 and y == N - 1 and maze[x][y]== 1:
        sol[x][y] = 1
        return True

    if isSafe(maze, x, y, visited) == True:
        sol[x][y] = 1
        if solveMazeUtil(maze, x + 1, y, sol, visited) == True:
            visited[x][y] = True
            return True
        if solveMazeUtil(maze, x - 1, y, sol, visited) == True:
            visited[x][y] = True
            return True

        if solveMazeUtil(maze, x, y - 1, sol, visited) == True:
            visited[x][y] = True
            return True
        if solveMazeUtil(maze, x, y + 1, sol, visited) == True:
            visited[x][y] = True
            return True

        sol[x][y] = 0
        return False

if __name__ == "__main__":

    maze = [ [1, 0, 0, 0],
            [1, 1, 0, 1],
            [0, 1, 0, 0],
            [1, 1, 1, 0] ]

    solveMaze(maze)

A: The following slight changes to your code allows it to work.
Made comments in code to highlight changes.
Code
# N = 4 -- removed (get dimension of maze using len function)

def printSolution( sol ):

    for i in sol:
        for j in i:
            print(str(j) + " ", end ="")
        print("")

def isSafe( maze, x, y, visited):
    N = len(maze)      # Get Maze dimensions (N x M) rather than hardcoding using N as a global
    M = len(maze[0])

    # x, y safe to use if not visited (original code had visited)
    #if x >= 0 and x < N and y >= 0 and y < N and maze[x][y] == 1 and visited[x][y] == True:
    # Can simplify x >= 0 and x < N to 0 <= x < M
    return 0 <= x < N and 0 <= y < M and maze[x][y] == 1 and not visited[x][y]

def solveMaze( maze ):
    N = len(maze)      # Get Maze dimensions (N x M) rather than hardcoding using N as a global
    M = len(maze[0])
    sol = [ [ 0 for j in range(M) ] for i in range(N) ]
    visited = [ [ 0 for j in range(M) ] for i in range(N) ]

    if not solveMazeUtil(maze, 0, 0, sol, visited): # preferred to checking for False
        print("Solution doesn't exist")
        print(-1)
        return False

    printSolution(sol)
    return True

def solveMazeUtil(maze, x, y, sol, visited):
    N = len(maze)      # Get Maze dimensions (N x M) rather than hardcoding using N as a global
    M = len(maze[0])

    if x == N - 1 and y == M - 1 and maze[x][y]== 1:
        sol[x][y] = 1
        return True

    if isSafe(maze, x, y, visited): # preferred to checking for True
        sol[x][y] = 1         # Try solution from current x, y position
        visited[x][y] = True  # Mark as visited so no other soltuion will use it

        # Recursive calls to solveMazeUtil can be simplfied to the following:
        if (solveMazeUtil(maze, x + 1, y, sol, visited) or
            solveMazeUtil(maze, x - 1, y, sol, visited) or
            solveMazeUtil(maze, x, y - 1, sol, visited) or
            solveMazeUtil(maze, x, y + 1, sol, visited)):
            return True   # Found a solution
        else:
            sol[x][y] = 0 # Couln't use x, y in solution
        return False
    else:
        return False

if __name__ == "__main__":
    print("Test 1")
    maze = [ [1, 0, 0, 0],
            [1, 1, 0, 1],
            [0, 1, 0, 0],
            [1, 1, 1, 0] ]
    solveMaze(maze)

    print("\nTest 2")
    maze = [ [1, 0, 0, 0],
            [1, 1, 0, 1],
            [0, 1, 0, 0],
            [1, 1, 1, 1] ]
    solveMaze(maze)

    print("\nTest 3")
    maze = [ [1, 0, 0, 0],
            [1, 1, 0, 1],
            [0, 1, 0, 0],
            [1, 1, 0, 1],
            [1, 1, 1, 1]]
    solveMaze(maze)

Output
Test 1
Solution doesn't exist
-1

Test 2
1 0 0 0
1 1 0 0
0 1 0 0
0 1 1 1

Test 3
1 0 0 0
1 1 0 0
0 1 0 0
0 1 0 0
0 1 1 1

OO Version
class Maze:
  def __init__(self, maze):
    # Constructor
    self.maze = maze

  def size(self):
    # Tuple for Maze dimensions
    return len(self.maze), len(self.maze[0])

  def isSafe(self, x, y, visited):
    '''
      Checks if okay to select cell x, y
    '''
    # Get Maze dimensions (N x M)
    N, M = self.size()

    # x, y safe to use if not visited (original code had visited)
    #if x >= 0 and x < N and y >= 0 and y < N and maze[x][y] == 1 and visited[x][y] == True:
    # Can simplify x >= 0 and x < N to 0 <= x < M
    return 0 <= x < N and 0 <= y < M and self.maze[x][y] == 1 and not visited[x][y]

  def solveMaze(self):
    '''
       Controlling function for Maze solver
    '''
    # Get Maze dimensions (N x M)
    N, M = self.size()

    sol = [ [ 0 for j in range(M) ] for i in range(N) ]
    visited = [ [ 0 for j in range(M) ] for i in range(N) ]

    if not self.solveMazeUtil(0, 0, sol, visited): # preferred to checking for False
      print("Solution doesn't exist")
      print(-1)
      return False

    self.printSolution(sol)
    return True

  def solveMazeUtil(self, x, y, sol, visited):
    '''
      Recursive Maze solver
    '''
    # Get Maze dimensions (N x M)
    N, M = self.size()

    if x == N - 1 and y == M - 1 and self.maze[x][y]== 1:
        sol[x][y] = 1
        return True

    if self.isSafe(x, y, visited): # preferred to checking for True
        sol[x][y] = 1         # Try solution from current x, y position
        visited[x][y] = True  # Mark as visited so no other soltuion will use it

        # Recursive calls to solveMazeUtil can be simplfied to the following:
        if (self.solveMazeUtil(x + 1, y, sol, visited) or
            self.solveMazeUtil(x - 1, y, sol, visited) or
            self.solveMazeUtil(x, y - 1, sol, visited) or
            self.solveMazeUtil(x, y + 1, sol, visited)):
            return True   # Found a solution
        else:
            sol[x][y] = 0 # Couln't use x, y in solution
        return False
    else:
        return False

  def printSolution(self, sol ):
    '''
      Format and print solution
    '''
    for i in sol:
      for j in i:
          print(str(j) + " ", end ="")
      print("")

if __name__ == "__main__":
    print("Test 1")
    maze = Maze([ [1, 0, 0, 0],
            [1, 1, 0, 1],
            [0, 1, 0, 0],
            [1, 1, 1, 0] ])

    maze.solveMaze()

    print("\nTest 2")
    maze = Maze([ [1, 0, 0, 0],
            [1, 1, 0, 1],
            [0, 1, 0, 0],
            [1, 1, 1, 1] ])
    maze.solveMaze()

    print("\nTest 3")
    maze = Maze([ [1, 0, 0, 0],
            [1, 1, 0, 1],
            [0, 1, 0, 0],
            [1, 1, 0, 1],
            [1, 1, 1, 1]])
    maze.solveMaze()

Output
Same as non-OO version


text:
Q: String.search("|") symbol result This is my code:
var sQuestionPropositionText = new String("This is a test|A");
for(var i=0; i < sQuestionPropositionText.length; i++){
console.log(sQuestionPropositionText[i] + " search result= " + sQuestionPropositionText[i].search("|"));
}

And this is what I got in the console:
T search result= 0
h search result= 0
i search result= 0
s search result= 0
  search result= 0
i search result= 0
s search result= 0
  search result= 0
a search result= 0
  search result= 0
t search result= 0
e search result= 0
s search result= 0
t search result= 0
| search result= 0
A search result= 0

Anyone knows why the "|" character is not found ?
Thanks for your time.

A: String#search expects a regular expression. If you give it a string, it converts it to a regex via new RegExp. | is special in regular expressions.
To search for a literal character or substring, use indexOf. You don't need a loop:
var sQuestionPropositionText = "This is a test|A";
var foundAt = sQuestionPropositionText.indexOf("|"); // 14

Or of course, you could escape it, but it's awkward in string form because \ is both the escape character in string literals and the escape character in regular expressions, so to put a \ in the regex to escape the |, you need two in the string literal (the first to escape the second):
var sQuestionPropositionText = "This is a test|A";
var foundAt = sQuestionPropositionText.search("\\|"); // 14

If you're going to use search, usually best to pass it a regex, not a string:
var sQuestionPropositionText = "This is a test|A";
var foundAt = sQuestionPropositionText.search(/\|/); // 14

Side note: There are virtually no situations in which new String is useful in JavaScript, which is why I removed it above.


text:
Q: How to null check when we test the false value? I am getting consoled both null and false became true value. but i need only check against false and true alone from the Boolean. how to achieve that?
here is my code :
var x = {name:null} //gives true. but i am looking to avoid null
var y = {name:false}
var z = {name:true}

console.log(!x.name);
console.log(!y.name);
console.log(!z.name);

A: You could check the type and if necessary the value.

var x = { name: null },
    y = { name: false },
    z = { name: true };

console.log(typeof x.name === 'boolean');
console.log(typeof y.name === 'boolean');
console.log(typeof z.name === 'boolean');

A: You can't, unless you explicitly check for null. null, just like undefined, 0, '', etc. is a falsy value, meaning any time you use the Boolean negation ! it will return true.
The best you could do is add some code to make sure the value does not equal null.
const x = {name:null};
const y = {name:false};
const z = {name:true};

console.log(!x.name && x.name !== null); // false
console.log(!y.name && y.name !== null); // true
console.log(!z.name && z.name !== null); // false

Hope this helps!


text:
Q: Prove the absolute inequality in the integrals Let $a\in R$, $f: \Bbb [a,\infty)   \to\Bbb R$  be an integrable function on every [a, b] where a $<$ b. Suppose $$\int_a^{\infty}|f(x)|\\ $$ and $$\int_a^{\infty}f(x)\\ $$ converge.  Prove:
$$\left|\int_a^{\infty} f(x)\right| \le \ \int_a^{\infty}|f(x)|\\$$

A: $$
 -|f(x)| \le f(x) \le |f(x)| \quad \text{ for all } x \ge a
$$
implies
$$
-\int_a^{\infty}|f(x)| \, dx \le \int_a^{\infty}f(x) \, dx \le \int_a^{\infty}|f(x)| \, dx
$$
and therefore
$$
\left|\int_a^{\infty} f(x) \, dx \right| \le \ \int_a^{\infty}|f(x)| \, dx \, .
$$
The last step uses that for real numbers $a$ and $b$,  $|a| \le b$ is equivalent to $-b \le a \le b$.


text:
Q: Approximating a double integral in MATLAB by double summation I am trying to approximate a double integral numerically using MATLAB by using the concept of double sum. Assuming the function I am trying to integrate is over x and y can i do the following,
result=0;
for i=1:0.1:x
for j=1:0.1:y
fun(i,j)= x(i).*y(j)*0.1^2; %the function I want to integrate times the increment
result = result + fun(i,j);
end
end

Also does anyone know what would the best increment be to best approximate the integral?
I appreciate any advice !

A: Numerical integration is a rather complex subject. Probably, the best standard option would be to use (http://www.mathworks.nl/help/matlab/ref/integral2.html#btdgcqq)
result = integral2(fun,xmin,xmax,ymin,ymax)

If you're interested in numerical integration in general, please take a look at Wiki (http://en.wikipedia.org/wiki/Numerical_integration). For specific implementations, Numerical Recipes is a good reference point (http://www.it.uom.gr/teaching/linearalgebra/NumericalRecipiesInC/  , sorry, no Matlab version there)


text:
Q: How to loop through 1 CPT with 2 Taxonomies I have a CPT (Products) which has 2 taxonomies (Industry and department)
I have the loop which delivers a "Product by Industry" which works
Industry 1
• result 1
• result 2
Industry 2
• result 1
• result 2
(see below)
<?php
$post_type = 'products';
$tax = 'industry';
$tax_terms = get_terms($tax);

if ($tax_terms) {
    foreach ($tax_terms  as $tax_term) {
        $args=array(
            'post_type' => $post_type,
            "$tax" => $tax_term->slug,
            'post_status' => 'publish',
            'posts_per_page' => -1,
            'caller_get_posts'=> 1
        );

        $my_query = null;
        $my_query = new WP_Query($args);

        if( $my_query->have_posts() ) {
            echo '
' . $tax_term->name .'
';
            while ($my_query->have_posts()) : $my_query->the_post();
                ?>

<a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?>

                <?php
            endwhile;
        }
        wp_reset_query();
    }
}

... but what I want is for each result to be prefixed with it's department name
ie.
Industry 1
• (department) result 1
• (department) result 2
Industry 2
• (department) result 1
• (department) result 2
Any help would be appreciated!

A: You probably want to use wp_get_post_terms().

*

*If a product is always associated to only one category – which has no child if hierarchical – (what I understand from your example), adding below snippet within your while loop should do it (not tested).
<?
$cat = wp_get_post_terms( get_the_ID(), 'department' );
echo '(' . $cat->name . ')';
?>

*If however a product can have several categories, it's not much more complicated. Above $cat will have to be $cats – just add a foreach loop to go throught it. In this case you may also want to specify the 3rd parameter of wp_get_post_terms(), which is by default the array $wp_gpt_args=array('order' => 'ASC', 'orderby' => 'name', 'fields' => 'all'). You will find the various options in the Codex article on wp_get_object_terms, that is actually called by wp_get_post_terms() and share the same arguments.

EDIT 24/10/2014
I've modified the snippet above with the correct taxonomy name and added the non hierarchical condition to the first point.
As it seems you don't need the full object to be returned, I added in the snippet below one argument so that the function will only return terms' names. From your comments, I can imagine $cat will now be an array of strings containing both parents and children terms.
To only display the top parent terms, you can apply either the trick suggested here or the idea behind it, which would give the following:
<?
$wp_gpt_args = array( 'fields' => 'names' );
$deps = wp_get_post_terms( get_the_ID(), 'department', $wp_gpt_args );
$top_dep = $deps[0]; //i.e. the first line of $deps array
echo '(' . $top_dep . ')';
?>


text:
Q: use external JS resource in Sencha Architect I'm trying to use an external JavaScript resource in Sencha Architect.
Say I want the GridFilter feature in my app.
I added the FiltersFeature.js as a JavaScript resource in Architect - ok!
I required 'Ext.ux.grid.FiltersFeature' in my grid - ok!
But now I want to config my grid, and when I open Grid features in the config area, it will not offer the Filters feature.
How can I make Architect do this?

A: It seems that SA does not offer custom grid features. But it can be easily done by using process config in your grid.
1# Select your grid, find the config panel, click on add process config:

2# In the function you can specify any config of your grid.

If you have any other features in your grid, don't forget to re-write them in the process config and delete any features from the original grid definition.
Now when you preview your project, your grid should have this feature enabled.


text:
Q: Inactive bash terminal runaway error messages In a Fedora 30 bash terminal, I use the pdflatex executable to     convert a *.tex
file to a *.pdf file.  Then, I go back to my editor, to make more changes to the
*.tex file.  I've noticed that sometimes, (but not always), while I am editing
(i.e. when the bash terminal is supposed to be inactive), the bash terminal
will create runaway error messages, similar to what is shown below.  Typing
Ctrl-C will stop the messages.  If it is relevant, the bash terminal's font is
"Monospace Regular", and my Fedora desktop is Cinnamon.
What is causing these runaway error messages?
"Error (64198): Illegal character ')'"
"Error: font resource is not a dictionary"
"Error (64198): Illegal character ')'"
"Error: font resource is not a dictionary"
...
"Error: Unknown font tag 'F16'"
"Error (1995): No font in show/space"
"Error (2011): No font in show/space"
"Error: Unknown font tag 'F17'"
"Error (2023): No font in show/space"
"Error: Unknown font tag 'F16'"
"Error (2062): No font in show/space"
...


text:
Q: .Net problem "Illegal characters in path." Hi all ok I'm not a .net developer I'm from a PHP, python background and I'm not sure what to do with this.
I have the following error when trying to load one of our sites. Please can someone help

[ArgumentException: Illegal characters in path.]
   System.IO.Path.CheckInvalidPathChars(String path) +7491109
   System.IO.Path.GetFileName(String path) +19
   System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize) +16
   System.Xml.XmlDownloadManager.GetStream(Uri uri, ICredentials credentials) +77
   System.Xml.XmlUrlResolver.GetEntity(Uri absoluteUri, String role, Type ofObjectToReturn) +54
   System.Xml.XmlTextReaderImpl.OpenUrlDelegate(Object xmlResolver) +74
   System.Threading.CompressedStack.runTryCode(Object userData) +70
   System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData) +0
   System.Threading.CompressedStack.Run(CompressedStack compressedStack, ContextCallback callback, Object state) +108
   System.Xml.XmlTextReaderImpl.OpenUrl() +186
   System.Xml.XmlTextReaderImpl.Read() +208
   System.Xml.XPath.XPathDocument.LoadFromReader(XmlReader reader, XmlSpace space) +217
   System.Xml.XPath.XPathDocument..ctor(String uri, XmlSpace space) +116
   System.Xml.XPath.XPathDocument..ctor(String uri) +6
   OpenBay.Utils.XPathUtils.GetNodes(String xpathQuery, String xmlFile) +30
   OpenBay.Wms.Controllers.SiteController.SetErrorPages(Site site) +21
   OpenBay.Wms.Controllers.SiteController.GetSite(Uri uri, DirectoryInfo dir, String applicationName) +104
   OpenBay.Wms.HttpModule.UrlProcessHttpModule.GetSiteParameters(HttpApplication app, RequestInfo info) +172
   OpenBay.Wms.HttpModule.UrlProcessHttpModule.ProcessRequest(Object o, EventArgs args) +338
   System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +68
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +75
thanks guys

A: Your code will call System.IO.Path.CheckInvalidPathChars, which in turn checks for the the following:

*

*double quote (")

*left angle bracket (<)

*right angle bracket (>)

*veritical bar (|)
and for control characters less than 32 decimal (space).
So Make sure your path doesn't contain them.
Edit:
comment from Guy Lowe

my issue was my unescaped \ in c:\ making it c:\ fixed it

A: Nice Stacktrace, but the invalid path would be more helpful.
In my oponion, the path provided to OpenBay.Utils.XPathUtils.GetNodes(string, string) has some invalid arguments. Use System.IO.Path.CheckInvalidPathChars() to check which characters are invalid and maybe contained in the argument provided to the method above.

A: Please look at this link, I am using VS 2019:
VS Test cases issue, NUnit


text: Q: DelauneyMesh in 4d and higher Is there any way to find the DelauneyMesh in 4D (or higher)? Its documentation implies that it should be possible "A Delaunay mesh consists of intervals (in 1D), triangles (in 2D), tetrahedra (in 3D), and n-dimensional simplices (in nD)." But then it fails without error (and there are no 4D examples anywhere). I guess it does not actually work for 4D or higher? Are there any user-made algorithms out there. Is there a fundamental obstacle to making this? (Scales too terrible with n?)


text:
Q: How to find which template is used in existing Xcode project? I have one iOS application existing project and i have opened it in Xcode-7 but i want know which template is used in that?

A: In most cases, you can determine it by looking at the Story Board (*.storyboard, often * is Main).
Here we see the possible templates.

Then, how the typical story board layout looks for the...

*

*Master-Detail Application

*Page-Based Application

*Single View Application

*Tabbed Application

*Game (which also features SpriteKit framework)


text:
Q: what event is activated when data is added to an iframe after POST I have a form that has an iframe target on the same page. When the form has successfully submitted it writes something to the iframe. When that happens, I then want other things to happen, too. I will do this via jquery/javascript. But what event is activated by this? Or, is there another event that is activated when the submit is completed.
(The reason I'm doing this is instead of using AJAX for file submission in Django. I don't want to use AJAX because it causes a whole other set of issues with submitting a file to my django Form.)

A: Posting back causes a full page refresh so you should be able to put your post-submission code in:
$(document).ready(function () {
    // solve all of the world's problems
});


text:
Q: Trying to render raw OpenGL into a QtQuick application, seems that QQuickWindow::setClearBeforeRendering is not working? I'm using Qt 5.4, QtQuick 2.4.
Basically, I'd like to be able to render raw OpenGL into an application written in QtQuick/QML, and I would like to do so while using QQmlApplicationEngine.
The main tutorial I have gone through is the (seemingly) pretty standard one, found here.
However, this tutorial uses a QQuickView rather than a QQmlApplicationEngine to load the QML UI.  If I change the code to use a QQmlApplicationEngine, the GL rendering no longer works, and I really don't understand why.
The code in this GitHub repository promises to draw raw OpenGL into a QtQuick application using QQmlApplicationEngine, and even manages to keep this promise, but it does so by hooking into QQuickWindow::afterRendering (see line 79 of squircle.cpp).  If this signal/slot connection is changed to hook into QQuickQindow::beforeRendering, the GL portion of the scene again appears unrendered.  This is IMO the simplest example that reproduces the issue I am having (except for some boilerplate hanging around).
QQuickWindow::clearBeforeRendering appears to (correctly) be set to false (line 86 of the same file).
Am I missing something?

A: I was having this same problem when upgrading to Qt 5.4.  The workaround that I found is to change the background color on the main QML ApplicationWindow item.
Main.qml...
ApplicationWindow
{
  id: mainWindow
  width: 800
  height: 600
  color: "black"

Putting anything other than "white" in the color property works for me.  For some reason making the background white overrides setClearBeforeRendering(false) when trying to draw with OpenGL in a QQuickItem using the beforeRendering() signal.
It doesn't matter what color you use since you have to clear the background using glClear in your custom OpenGL code anyway and that will be the one that is seen when the drawing is done.
Just don't use white!
I'm assuming this is a bug until someone tells me otherwise.

A: In Qt 5.4 the Window.contentItem property was introduced and painting of ApplicationWindow content area was changed. I used a custom item derived from QQuickFramebufferObject to fix it. You can find example on GitHub.
In my example, when the FBO__ macros is not defined the code from QtQuick Scenegraph OpenGL-under-Qml example is used. And the setClearBeforeRendering(false) is not working anymore. I believe ApplicationWindow erases the whole window background when GUI rendering occurs. I had an idea to intercept somehow (by flags property and event handlers) the erase background event, but still has not performed it. A custom item based on QQuickFramebufferObject works fine, but I think it has a memory overhead compared to painting in QQuickQindow::beforeRendering().


text:
Q: Python Find permutable list in a dict list Given
listOfDict = [{'ref': 1, 'a': 1, 'b': 2, 'c': 3},
              {'ref': 2, 'a': 4, 'b': 5, 'c': 6},
              {'ref': 3, 'a': 7, 'b': 8, 'c': 9}]

Lets' consider a list of permutable integer
[7,8,9]=[7,9,8]=[8,7,9]=[8,9,7]=[9,7,8]=[9,8,7] # (3!)

Each of this list has a unique mapping ref, so how given for (8,7,9) can I get ref=3 ?
Also in real case I might until 10 (a,b,c,d,e,f,g,h,i,j)...

A: You can generate a dictionary that maps the values as frozenset to the value of ref:
listOfDict = [{'ref': 1, 'a': 1, 'b': 2, 'c': 3},
              {'ref': 2, 'a': 4, 'b': 5, 'c': 6},
              {'ref': 3, 'a': 7, 'b': 8, 'c': 9}]

keys = ['a', 'b', 'c']

out = {frozenset(d[k] for k in keys): d['ref'] for d in listOfDict}
# {frozenset({1, 2, 3}): 1,
#  frozenset({4, 5, 6}): 2,
#  frozenset({7, 8, 9}): 3}

example:
check = frozenset((8,7,9))

out[check]
# 3

but I don't know in advance the name of the other keys!
Then use this approach:
out = {}
for d in listOfDict:
    d2 = d.copy() # this is to avoid modifying the original object
    out[frozenset(d2.values())] = d2.pop('ref')
out

or as a comprehension:
out = dict(((d2:=d.copy()).pop('ref'), frozenset(d2.values()))[::-1]
           for d in listOfDict)

A: Here is a commented solution to your problem. The idea is to compare the sorted list of the values in a, b, c etc with the sorted values in list_of_ints. The sorted values will be the same for all permutations of a given set of numbers.
def get_ref(list_of_ints):
    # Loop through dictionaries in listOfDict.
    for dictionary in listOfDict:
        # Get list of values in each dictionary.
        vals = [dictionary[key] for key in dictionary if key != "ref"]
        if sorted(vals) == sorted(list_of_ints):
            # If sorted values are equal to sorted list of ints, return ref.
            return dictionary["ref"])

By the way, I believe it would be cleaner to structure this data as a dict of dicts in the following way:
dicts = {
    1: {'a': 1, 'b': 2, 'c': 3},
    2: {'a': 4, 'b': 5, 'c': 6},
    3: {'a': 7, 'b': 8, 'c': 9}
}

The code would then be:
def get_ref(list_of_ints):
    for ref, dictionary in dicts.items():
        if sorted(dictionary.values()) == sorted(list_of_ints):
            return ref

Assuming that all integers in the permutations are unique, the code can be simplified further using sets instead of sorted lists.

A: Since its a list of dict I can call each dict as it self by using for loop
and record the first number on ref
for i in listOfDict:
    ref_num=i["ref"]

and to turn dictunary to list we simply use:
z=list(i.values())

then the last step is to find if its the same input list if so we print/return the ref number
if z[1:]==InputList:
        return ref_num

and the code should be like this:
listOfDict = [
{"ref": 1,
 "a": 1,
 "b": 2,
 "c": 3},
{"ref": 2,
    "a": 4,
    "b": 5,
    "c": 6},
{"ref": 3,
    "a": 7,
    "b": 8,
    "c": 9},]

def find_ref_Num(InputList):
for i in listOfDict:
    ref_num=i["ref"]
    z=list(i.values())
    if z[1:]==InputList:
        return ref_num

print ("your ref number is: "+str(find_ref_Num([7,8,9])))


text:
Q: validate date with Moment in React is there a way to display a default message when the date passed to Moment is invalid?
<Moment fromNow>not-a-date</Moment>

I´m getting Invalid Date.

A: Tage a look
Check if date is a valid one
you should not use moment as jsx element, it is an normal class.

A: getDate() {
    if (!this.props.date || check for invalid date) {
        return "Alternative Message on Invalid date"
    }

    return  <Moment fromNow>{this.props.date}</Moment>
}

render() {
    return this.getDate()
}

A: getDate() {
    if (!this.props.date || this.props.date===" " || check for invalid date criteria)
{
        return "Alternative Message on Invalid date"
    }

    return  <Moment fromNow>{this.props.date}</Moment>
}

render() {
    return this.getDate()
}


text:
Q: How to test a UWP App running on a windows computer for zoom functionality I am sorry but I might have to ask a really silly question as I have been googling for quite some time and can't seem to find the answer for my issue. I am currently developing a Xamarin cross platform application and my application has a zoom functionality implemented. However, unlike real tablets and phones which we can use our fingers to do the zooming, I am unsure as to how to test zooming on a windows computer for a UWP application installed using my mouse and keyboard.
Any kind soul willing to give me some advice on how to zoom using mouse and keyboard on a windows computer for a UWP app?

A: *

*Holding the Ctrl key down while scrolling the mouse scroll wheel

*Holding the Ctrl key down (with the Shift key, if no numeric keypad is available) and pressing the plus (+) or minus (-)

Both optical zoom and resizing interactions are performed through the pinch and stretch gestures (moving fingers farther apart zooms in and moving them closer together zooms out), or by holding the Ctrl key down while scrolling the mouse scroll wheel, or by holding the Ctrl key down (with the Shift key, if no numeric keypad is available) and pressing the plus (+) or minus (-) key.

Ref: UWP Optical zoom and resizing


text:
Q: In Foundry, how can I parse a dataframe column that has a JSON response I am trying to bring in JIRA data into Foundry using an external API. When it comes in via Magritte, the data gets stored in AVRO and there is a column called response. The response column has data that looks like this...

[{"id":"customfield_5","name":"test","custom":true,"orderable":true,"navigable":true,"searchable":true,"clauseNames":["cf[5]","test"],"schema":{"type":"user","custom":"com.atlassian.jira.plugin.system.customfieldtypes:userpicker","customId":5}},{"id":"customfield_2","name":"test2","custom":true,"orderable":true,"navigable":true,"searchable":true,"clauseNames":["test2","cf[2]"],"schema":{"type":"option","custom":"com.atlassian.jira.plugin.system.customfieldtypes:select","customId":2}}]

Due to the fact that this imports as AVRO, the documentation that talks about how to convert this data that's in Foundry doesn't work. How can I convert this data into individual columns and rows?
Here is the code that I've attempted to use:
from transforms.api import transform_df, Input, Output
from pyspark import SparkContext as sc
from pyspark.sql import SQLContext
from pyspark.sql.functions import udf
import json
import pyspark.sql.types as T

@transform_df(
    Output("json output"),
    json_raw=Input("json input"),
)
def my_compute_function(json_raw, ctx):

    sqlContext = SQLContext(sc)

    source = json_raw.select('response').collect()  # noqa

    # Read the list into data frame
    df = sqlContext.read.json(sc.parallelize(source))

    json_schema = T.StructType([
        T.StructField("id", T.StringType(), False),
        T.StructField("name", T.StringType(), False),
        T.StructField("custom", T.StringType(), False),
        T.StructField("orderable", T.StringType(), False),
        T.StructField("navigable", T.StringType(), False),
        T.StructField("searchable", T.StringType(), False),
        T.StructField("clauseNames", T.StringType(), False),
        T.StructField("schema", T.StringType(), False)
    ])

    udf_parse_json = udf(lambda str: parse_json(str), json_schema)

    df_new = df.select(udf_parse_json(df.response).alias("response"))

    return df_new

# Function to convert JSON array string to a list
def parse_json(array_str):
    json_obj = json.loads(array_str)
    for item in json_obj:
        yield (item["a"], item["b"])

A: Parsing Json in a string column to a struct column (and then into separate columns) can be easily done using the F.from_json function.
In your case, you need to do:
df = df.withColumn("response_parsed", F.from_json("response", json_schema))

Then you can do this or similar to get the contents into different columns:
df = df.select("response_parsed.*")

However, this won't work as your schema is incorrect, you actually have a list of json structs in each row, not just 1, so you need a T.ArrayType(your_schema) wrapping around the whole thing, you'll also need to do an F.explode before selecting, to get each array element in its own row.
An additional useful function is F.get_json_object, which allows you to get json one json object from a json string.
Using a UDF like you've done could work, but UDFs are generally much less performant than native spark functions.
Additionally, all the AVRO file format does in this case is to merge multiple json files into one big file, with each file in its own row, so the example under "Rest API Plugin" - "Processing JSON in Foundry" should work as long as you skip the 'put this schema on the raw dataset' step.

A: I used the magritte-rest connector to walk through the paged results from search:
type: rest-source-adapter2
restCalls:
  - type: magritte-paging-inc-param-call
    method: GET
    path: search
    paramToIncrease: startAt
    increaseBy: 50
    initValue: 0
    parameters:
      startAt: '{%startAt%}'
    extractor:
      - type: json
        assign:
          issues: /issues
        allowNull: true
    condition:
      type: magritte-rest-non-empty-condition
      var: issues
    maxIterationsAllowed: 4096
cacheToDisk: false
oneFilePerResponse: false

That yielded a dataset that looked like this:

Once I had that, this parsed expanded and parsed the returned JSON issues into a properly-typed DataFrame with fields holding the inner structure of the issue as a (very complex) struct:
import json
from pyspark.sql import Row
from pyspark.sql.functions import explode

def issues_enumerated(All_Issues_Paged):

    def generate_issue_row(input_row: Row) -> Row:
        """
        Generates a dataframe of each responses issue array as a single array record per-Row
        """
        d = input_row.asDict()
        resp_json = d['response']
        resp_obj = json.loads(resp_json)
        issues = list(map(json.dumps,resp_obj['issues']))

        return Row(issues=issues)

    # array-per-record
    unexploded_df = All_Issues_Paged.rdd.map(generate_issue_row).toDF()
    # row-per-record
    row_per_record_df = unexploded_df.select(explode(unexploded_df.issues))
    # raw JSON string per-record RDD
    issue_json_strings_rdd = row_per_record_df.rdd.map(lambda _: _.col)
    # JSON object dataframe
    issues_df = spark.read.json(issue_json_strings_rdd)
    issues_df.printSchema()
    return issues_df


text:
Q: Problema con IIf y '[']' En una caja de texto de un formulario, se puede meter un código sólo con caracteres normales o bien caracteres seguidos de otro código entre corchetes: [xxxxxxx]. Dependiendo del tipo de entrada, hay que devolver una cadena u otra.
Si la cadena lleva corchetes, éstos se eliminan. Si no los lleva, da error, porque los busca igualmente. El objetivo es conseguir que esto no pase.
En la parte principal del programa, tengo:
If Me!Proveedor = "BIMBO" Then
Me!NombreProducto = Left(BuscaNombre("BIMBO", Mid(Me!Producto, InStr(1, Me!Producto, "[") + 1, (InStr(1, Me!Producto, "]")) - (InStr(1, Me!Producto, "[")) - 1)), 50)

La función a la que llama tiene como argumentos:
BuscaNombre(ByVal Tipo As String, ByVal Codigo As String) As String

El valor de Producto, que es una caja de texto que está en el formulario activo, es en este caso "zxc". Lo que creo que pasa con este código es que al usar el Mid, el inStr y demás para dar valor al argumento, si en la cadena de entrada no encuentra símbolos del tipo [ o ] que son los que parece estar buscando, da error.
Si esta hipótesis es correcta, ¿Cómo se podría solucionar para que en el caso que no hubiera símbolos de entrada, el código entrara correctamente en la función?
Una posible solución es ésta:
Me!NombreProducto = iif(InStr(1, Me!Producto, "["), Left(BuscaNombre("BIMBO", Mid(Me!Producto, InStr(1, Me!Producto, "[") + 1, (InStr(1, Me!Producto, "]")) - (InStr(1, Me!Producto, "[")) - 1)), 50), Left(BuscaNombre("BIMBO", Me!Producto.text), 50)

Pero no funciona, el editor de texto de VBA Access da error. ¿Alguien tiene una pista de por qué?

A: La solución sería dividir el IF según haya corchetes o no:
If InStr(1, Me!Producto, "[")>0 or InStr(1, Me!Producto, "]")>0 Then
'hacer algo si hay corchetes
Else
'hacer otra cosa cuando no hay corchetes
End If


text:
Q: need help with logparser on iis logs I am using logparser 2.2 and need a script that does two things:

*

*finding urls that contain a value within referer

*need to loop over 30 folders

logparser -rpt:-1 "select count()INTO feeds.txt from u_ex100302.log where to_lowercase(cs(Referer)) like '/feeds%'"

A: for (1,2,3) do logparser "select count()INTO feeds.txt from %%i\u_ex100302.log where to_lowercase(cs(Referer)) like '/feeds%%'"


text:
Q: Command not found when running as other user with sudo I am trying to run psql with user postgres. When I run sudo su - postgres AND THEN  psql from within the new session, it is working smoothly. In fact, the ~/.bashrc in that session with use postgres has the correct PATH.
However, if I run sudo -u postgres psql, I get sudo: psql: command not found. Even though the session where I am running this command (I use the FISH shell) has the correct PATH as well, and I can invoke psql without the full path with my user.
I need to invoke the command as sudo -u postgres psql, how can this behavior be explained?
Edit: if (from FISH) I switch to BASH and run sudo -u postgres psql, it works! I guess it has to do with the FISH path then...
Edit 2: The issue seems to be that the PATH is reset when using sudo.
➜  ~ psql
psql: error: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: FATAL:  role "opc" does not exist
➜  ~ sudo -u postgres psql
sudo: psql: command not found
➜  ~ echo $PATH
/home/opc/.local /home/opc/.local/bin /usr/pgsql-15/bin /usr/pgsql-15/bin /usr/local/bin /usr/bin /usr/local/sbin /usr/sbin
➜  ~ sudo echo $PATH
/home/opc/.local /home/opc/.local/bin /usr/pgsql-15/bin /usr/pgsql-15/bin /usr/local/bin /usr/bin /usr/local/sbin /usr/sbin
➜  ~ sudo -u postgres /usr/pgsql-15/bin/psql
could not change directory to "/home/opc": Permission denied
psql (15.1)
Type "help" for help.

postgres=#

But if I echo $PATH with sudo, it seems fine...

A: This is caused by a sudo configuration that has the "secure_path" setting. This causes sudo to reset $PATH to a hardcoded "known safe" value. This might be enabled by your distribution.
When you run sudo bash, that bash will read its settings, including .bashrc, and if you set $PATH in that it will then, of course, have that $PATH again.
But if you run a command without going through a shell that resets $PATH, you'll get the hardcoded setting.
It's possible to change that setting by running sudo visudo and changing the line that says
Defaults secure_path="some:path:here"

to
Defaults !secure_path

An alternative is to just run the command via the fully qualified path, like
sudo -u postgres (command -s psql)

One more comment about your tests:

sudo echo $PATH

This doesn't do what you want. The $PATH will be expanded by the shell that runs sudo, and so sudo won't ever see anything but the value of it. It is exactly equivalent to running sudo echo /home/opc/.local /home/opc/.local/bin /usr/pgsql-15/bin ....
You might want to use something like
sudo env

or
sudo sh -c 'echo $PATH'

instead.


text:
Q: 'Authorize' only specific routes of a resource There is this method authorizeResource() which applies specific policies to all routes (except the index route). Is there a way to apply policies only on specific routes, analogous to this function:
Route::resource('photo', 'PhotoController', ['only' => [
    'index', 'show'
]]);

A: Yes, authorizeResource accepts an $options array as a third parameter. Just pass null for the second argument and the syntax for options is the same as it is for route middleware.
public function __construct()
{
    $this->authorizeResource(Photo::class, null, [
        'only' => ['create', 'store'],
    ]);
}

A: You can realistically define middleware in the controller:
public PhotoController extends Controller {
    public function __construct() {
         $this->middleware("can:save,photo")->only(["save","edit"]);   //You get the idea
    }
}

This assumes you've written a proper policy (check https://laravel.com/docs/5.4/authorization)

A: Despite pointed out by @JeffPucket in his answer, the only option didn't work for me. I'm running Laravel 5.5 and what did work was the inverse logic:
public function __construct()
{
    $this->authorizeResource(Photo::class, null, [
        'except' => [ 'index', 'show' ],
    ]);
}

Notice that you should pass to that option the actions (controller's methods) you don't want to apply your policy. In this case, index and show will bypass the authorization middleware.
Just for comparison, here are the results from php artisan route:list when using each option:
only
+--------+-----------+------------------------+-----------------+------------------------------------------------+--------------------------------------------------+
| Domain | Method    | URI                    | Name            | Action                                         | Middleware                                       |
+--------+-----------+------------------------+-----------------+------------------------------------------------+--------------------------------------------------+
|        | POST      | comment                | comment.store   | App\Http\Controllers\CommentController@store   | web,auth,can:create,App\Http\Controllers\Comment |
|        | GET|HEAD  | comment                | comment.index   | App\Http\Controllers\CommentController@index   | web,auth,can:view,App\Http\Controllers\Comment   |
|        | GET|HEAD  | comment/create         | comment.create  | App\Http\Controllers\CommentController@create  | web,auth,can:create,App\Http\Controllers\Comment |
|        | GET|HEAD  | comment/{comment}      | comment.show    | App\Http\Controllers\CommentController@show    | web,auth,can:view,comment                        |
|        | PUT|PATCH | comment/{comment}      | comment.update  | App\Http\Controllers\CommentController@update  | web,auth,can:update,comment                      |
|        | DELETE    | comment/{comment}      | comment.destroy | App\Http\Controllers\CommentController@destroy | web,auth,can:delete,comment                      |
|        | GET|HEAD  | comment/{comment}/edit | comment.edit    | App\Http\Controllers\CommentController@edit    | web,auth,can:update,comment                      |
+--------+-----------+------------------------+-----------------+------------------------------------------------+--------------------------------------------------+

except
+--------+-----------+------------------------+-----------------+------------------------------------------------+--------------------------------------------------+
| Domain | Method    | URI                    | Name            | Action                                         | Middleware                                       |
+--------+-----------+------------------------+-----------------+------------------------------------------------+--------------------------------------------------+
|        | POST      | comment                | comment.store   | App\Http\Controllers\CommentController@store   | web,auth,can:create,App\Http\Controllers\Comment |
|        | GET|HEAD  | comment                | comment.index   | App\Http\Controllers\CommentController@index   | web,auth                                         |
|        | GET|HEAD  | comment/create         | comment.create  | App\Http\Controllers\CommentController@create  | web,auth,can:create,App\Http\Controllers\Comment |
|        | GET|HEAD  | comment/{comment}      | comment.show    | App\Http\Controllers\CommentController@show    | web,auth                                         |
|        | PUT|PATCH | comment/{comment}      | comment.update  | App\Http\Controllers\CommentController@update  | web,auth,can:update,comment                      |
|        | DELETE    | comment/{comment}      | comment.destroy | App\Http\Controllers\CommentController@destroy | web,auth,can:delete,comment                      |
|        | GET|HEAD  | comment/{comment}/edit | comment.edit    | App\Http\Controllers\CommentController@edit    | web,auth,can:update,comment                      |
+--------+-----------+------------------------+-----------------+------------------------------------------------+--------------------------------------------------+

As you can see above, the middleware is only applied to specific routes when using except.
Perhaps this is a bug in the framework. But it's hard to confirm that since this option doesn't seem to be documented. Even details on authorizeResource() method are non-existing.


text:
Q: Using Paypal REST api and PHP cURL to post invoice (draft) constantly returns 415 Unsupported Media Type I am using paypal's create invoice sample json from their website
I am getting a token well-enough, which I submit with the post and since the error isn't 401 Unauthorized but rather 415 Unsupported Media Type (and now recently 500 Internal Server Error) which leads me to believe that I'm likely getting that part right... so I will offer some code in hopes somebody catches something obvious that I'm missing:
createPaypalInvoice.php
function paypalCreateDraftRequest($token,$jsondraft){
    global $url;
    $sUrl = "/v1/invoicing/invoices";
    $accept = "Accept:application/json";
    $acceptlang = "Accept-Language:en_US";
    $contenttype = "Content-Type: application/json";
    $contentlen = "Content-Length: " . strlen($jsondraft);
            // $jsondraft is a string of json from paypal example
    $authorization = "Authorization: Bearer ".$token["access_token"];
    $headers = array($accept,$acceptlang,$contenttype,$contentlen,$authorization);
    $fields_string = $jsondraft;
    $ch = curl_init();
    $options = array (CURLOPT_RETURNTRANSFER => true, // return web page
        CURLOPT_FAILONERROR => true,
        CURLOPT_URL => $url.$sUrl,
        CURLOPT_HTTPHEADER => $headers,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POSTFIELDS => $fields_string,
        CURLOPT_HEADER => false,                      // don't return headers
        CURLOPT_SSL_VERIFYPEER => false,              // TODO: fix certificate provider list problem later
        CURLOPT_CONNECTTIMEOUT => 6,                  // timeout on connect
        CURLOPT_TIMEOUT => 10  );                      // timeout on response

    curl_setopt_array ( $ch, $options );
    try {
        $result=curl_exec( $ch );
        $log->LogDebug($result);
        //$header = curl_getinfo ( $ch );
        $err = curl_errno ( $ch );
        $errmsg = curl_error ( $ch );
        curl_close($ch);
        if ($errmsg) throw new Exception($errmsg);
        return $result;
     } catch (Exception $e) {  throw $e;  }

}

example invoice from paypal:
{
    "merchant_info": {
    "email": "dennis@sample.com",
        "first_name": "Dennis",
        "last_name": "Doctor",
        "business_name": "Medical Professionals, LLC",
        "phone": {
        "country_code": "001",
            "national_number": "5032141716"
    },
    "address": {
        "line1": "1234 Main St.",
            "city": "Portland",
            "state": "OR",
            "postal_code": "97217",
            "country_code": "US"
    }
},
    "billing_info": [
    {
        "email": "example@example.com"
    }
],
    "items": [
    {
        "name": "Sutures",
        "quantity": 100,
        "unit_price": {
            "currency": "USD",
            "value": 5
        }
    }
],
    "note": "Medical Invoice 16 Jul, 2013 PST",
    "payment_term" :{
    "term_type": "NET_45"
},
    "shipping_info": {
    "first_name": "Sally",
        "last_name": "Patient",
        "business_name": "Not applicable",
        "address": {
        "line1": "1234 Broad St.",
            "city": "Portland",
            "state": "OR",
            "postal_code": "97216",
            "country_code": "US"
        }
    }
}

A: I discovered the problem:
From paypal's invoice documentation:

Note: The merchant specified in an invoice must have a PayPal account
  in good standing.

Evidently the sample account "dennis@sample.com" should not be used. When I used my own sandbox account for merchant information everything magically worked...
Perhaps someone else might have this problem and the solution is now published. Maybe my sample code might be of assistance as well...

A: I am unable to find examples that show the use of Accept/Accept-Language in the PayPal REST documents.
$accept = "Accept:application/json";
$acceptlang = "Accept-Language:en_US";

I would remove these from your header and see if this changes the error you are getting.


text:
Q: zsh substitution, can't do regex with repetition I'm trying to perform ZSH variable substitution, but I'm having to do it the lame way, by piping through cut. Is it possible to perform this operation entirely within ZSH?

i=./riak.logs.cloudstoragea08/2014-08-07T15:47:49.540310/console.log.2014-07-31-05
echo ${${i/\.\//}:s/\/*//}
riak.logs.cloudstoragea08/2014-08-07T15:47:49.540310/console.log.2014-07-31-05
echo ${${i/\.\//}}
riak.logs.cloudstoragea08/2014-08-07T15:47:49.540310/console.log.2014-07-31-05
echo ${echo ${i/\.\//} | cut -d/ -f 1}
zsh: bad substitution:
echo $(echo ${i/\.\//} | cut -d/ -f 1)
riak.logs.cloudstoragea08

A: i=./riak.logs.cloudstoragea08/2014-08-07T15:47:49.540310/console.log.2014-07-31-05
j=${i:2}
echo ${j%%/*}

Alternatively:
expr $i : '\.\/\([^/]*\)/'


text:
Q: Permissions for PSExec run from SQL job I have the following in a CMDExec type SQL Job step (details changed):
D:\path\PSExec.exe \\servername -accepteula -u "domain\username" -p password D:\path\executable.exe

This works fine.
However, I have set up a proxy in SQL Server for the same user account - which the job is using, so you'd think I wouldn't need the -u and -p arguments.
But if I don't supply them I get the error:
Unhandled Exception: System.Data.SqlClient.SqlException: Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'.

which is from SQL Server, because the remote executable connects to SQL as the same user context.
Why doesn't this work, and can I make it work without including the credentials in the job detail? (or a batch file, or similar)
Thanks
P.S. The SQL Server connected to by the remote executable is the same one as the job is run in, if it helps!

A: The reason is because Kerberos is not running!
Thanks to Marc Jellinek on LinkedIn SQLDBA group :)


text:
Q: Full Screen PIN request I'd like to show a full screen PIN request (e.g. a dedicated activity) when my Application is resumed. How can I achieve this? I'm thinking about creating a flag ASKING_PIN on Application context, specifically on Application resume lifecycle, then sending an event to all activities. The first one that catch that event, update the flag to TRUE and show the PIN request.
@Override
public void onActivityResumed(Activity activity) {
    // POST PIN event on EventBus
}

Will this work as expected? Any other possible solutions? Important note: when the user dismiss the PIN activity should be able to see the latest activity that was interacting with. Many thanks in advance.

A: Create one BaseActivity, and have every other activity inherit from that one. On the BaseActivity's onResume add your condition for launching the PIN lock, and if that's satisfied, launch your PinLockActivity.


text:
Q: How can i union sql query I have to queries:
SELECT * FROM `posts` WHERE `id` = '{$id}'
SELECT * FROM `post_votes` WHERE `post` = '{$id}' AND `user` = '{$user}'

Can I join them together into one query (some column names are similar) and get assoc array using mysqli_fetch_assoc?
Thank you.

A: I'm not sure to understand exactly your tables structures but I think what you are looking for is UNION ALL
So your query might look like:
SELECT col_1, col_2 FROM `posts` WHERE `id` = '{$id}'*
UNION ALL
SELECT col_1, col_2 FROM `post_votes` WHERE `post` = '{$id}' AND `user` = '{$user}'

If posts and post_votes don't have same column names you will have to use aliases.
See https://www.techonthenet.com/postgresql/union_all.php fore more details


text: Q: Are there any conditions on when an irreducible polynomial in several variables generate a maximal ideal? In the one variable case ($k[x]$ where $k$ is a field), we know that a polynomial is irreducible iff the ideal it generates is maximal. Now, reviewing the proof, it is clear that this proof doesn't carry over to the multivariable case, but are there any conditions on when a polynomial in $k[x_1,x_2,...,x_n]$ generates a maximal ideal? (We can assume k is a algebraically closed field).


text:
Q: Doing an F test, only sample size, means, and stdev given I've attempted to Google this problem to no avail. This is a homework question.
There are 2 groups. For each, the sample size, sample mean, sample standard deviation is given. Raw data isn't provided.
How do I use an F test to test for the difference between the 2 means?

A: An F statistic is given by the ratio of two independent chi-square random variables. Under the null hypothesis, the two populations have the same mean: $$\mu_{pooled} = \frac{n_1 \mu_1  + n_2 \mu_2 }{n_1 + n_2}$$.
And so, under the null hypothesis:
$$\left(\frac{  \bar{X_1} - \mu_{pooled} } {\mbox{SE} (\bar{X}_1)}\right) ^2 \sim \chi^2_1$$
And similarly for the second population.


text:
Q: DecimalFormat WITHOUT scientific notation I have a DecimalFormat like this:
DecimalFormat df = new DecimalFormat("#,###.###");

Then I have 3 methods which just return a float value for time, potential and current, with many decimals in case of the two last ones. So I'm trying to get an output message with the 3 values formated, so:
System.out.println("t="+df.format(getTime())+"(s), v="+df.format(getPotential())+"(V), i="+df.format(getI())+"(A)");

Time just count seconds from 0 to 10, without any decimal, and looks ok until it gets to 10. Then it shows 1E+1. I just don't understand why, since I have read at the API and it shouldn't be in scientific notation if I don't use an 'E' character at the DecimalFormat.
Also, potential goes from 0 to a certain value, using 3 decimals. Looks OK, but from 0 to 0.01, it appears with 4 decimals, being the last one always 0.
Any explanation to this behaviour of DecimalFormat? What am I doing wrong?

A: Maybe it would be simpler to use printf in your case :
System.out.printf("t=%d(s) v=%.2f(V) i=%.2f(A)\n", getTime(), getPotential(), getI());


text:
Q: XML file reading when item is nested in same bracket I have this code in a Javascript function that reads an XML file:
var title = $(this).children('Title').text();

This works for this XML code
<Title>
Nice long title
</Title>

In the same XML file I have information nested within the brackets like this:
<ProductSearch>

 <Products totalResultsAvailable="0" firstResultPosition="1" totalResultsReturned="0" searchOperator="or"/>

</ProductSearch>

What code do I require to extract the totalResultsAvailable integer? Thanks in advance.

A: var totalResultsAvailable = $(this).children('ProductSearch').children('Products').getAttribute("totalResultsAvailable");


text:
Q: Font-weight in local Windows environment I'm using Windows 10 and reformatted my computer the other day.
What isn't new is that sometimes Windows will combine font families (i.e. Arial Black, Arial Bold, Arial Narrow, et cetera) into one "file".
What is new, however, it will not allow me to change the font-weight property to make use of different weights when developing locally now. Before I could change the value of font-weight to, say, 600 (or 700 or lighter or bold or whatever) and the type would change accordingly.
For what it's worth, I'm using @font-face and have imported the font to the desired folder. I've tried creating separate @font-face declarations for the individual font names, which didn't work. For instance...
@font-face {
  font-family: bahn;
  src: url('../bahnschrift.ttf') format('truetype');
}

@font-face {
  font-family: bahn-light;
  src: url('../bahnschrift light.ttf') format('truetype');
}

/* etc */

Any idea how to fix this??


text:
Q: not sure why toggling to show content isn't pushing down next piece of content Not a full-time front-end developer but need to finish this.
I am pulling some images from an ajax request and pushing them into a div and hiding it.  Here's a screenshot of the problem:

When I toggle the class to display it, the images show (wave pictures in screenshot) and DOES push down the other content.
However, there is a border-top on the next piece of content and this seems to stay in place (the blue border in screenshot).
If I highlight the image content in Firebug, it really doesn't show up. How would I make it so that the border of the next element gets pushed down correctly?
thx
edit 1
removed float:left for @Ramon - seems to remove issue but now things are not running inline. Is there another way to set them up rather than float:left. Would a horizontal list break onto multiple lines?

A: You must check many things, among them:

*

*Check that the blue border element is not positioned absolutely.

*This is just a trick, just put a:

 between both.
3 Check if there are any unclosed html element like the div we can see in the code pasted above.
4 Check if any element involved is floating or has the top css attribute set.
For more help, please give a little bit more information. Hope that helps,


text:
Q: Prevent Delphi IDE creating component icons at design time I have created a custom control TOuterControl that is the parent for multiple TInnerControls.
Everything is working fine except that the IDE is creating icons for each the child TInnerControl's (InnerControl1 and InnerControl2 in the screenshot). How do I prevent the IDE from generating the icons?

unit TestControl;

interface

Procedure Register;

implementation

Uses
    Classes,
    Controls,
    SysUtils,
    DesignEditors,
    DesignIntf,
    VCLEditors;

Type

TOuterControl = Class;

TInnerControl = Class(TComponent)
Protected
    FOuterControl : TOuterControl;

    function GetParentComponent: TComponent; Override;
    Function HasParent : Boolean; Override;
    procedure SetParentComponent                  (Value: TComponent); Override;
End;

TOuterControl = Class(TCustomControl)
Protected
    FInnerControls : TList;

    Procedure Paint; Override;
Public
    Constructor Create(AOwner : TComponent); Override;
    Procedure AddInnerControl(AInnerControl : TInnerControl);
    procedure GetChildren(Proc: TGetChildProc; Root: TComponent); override;
End;

TOuterControlEditor = Class(TDefaultEditor)
Public
    Procedure ExecuteVerb(Index : Integer);          Override;
    Function  GetVerb    (Index : Integer) : String; Override;
    Function  GetVerbCount      : Integer;           Override;
End;

procedure TOuterControl.AddInnerControl(AInnerControl: TInnerControl);
begin
    AInnerControl.FOuterControl := Self;;
    FInnerControls.Add(AInnerControl);
    Invalidate;
end;

constructor TOuterControl.Create(AOwner: TComponent);
begin
    inherited;

    FInnerControls := TList.Create;
end;

procedure TOuterControl.GetChildren(Proc: TGetChildProc; Root: TComponent);
var
    I : Integer;
begin
    inherited;

    For I := 0 To FInnerControls.Count - 1 Do
        Proc(FInnerControls[I]);
end;

procedure TOuterControl.Paint;
begin
    inherited;

    Canvas.FillRect(ClientRect);
    Canvas.TextOut(0,0, Format('Inner Control Count = %d', [FInnerControls.Count]));
end;

function TInnerControl.GetParentComponent: TComponent;
begin
    Result := FOuterControl;
end;

function TInnerControl.HasParent: Boolean;
begin
    Result := True;
end;

procedure TInnerControl.SetParentComponent(Value: TComponent);
begin
    If Value Is TOuterControl Then
        If FOuterControl <> Value Then
    Begin
        FOuterControl := TOuterControl(Value);
        FOuterControl.AddInnerControl(Self);
    End;
end;

procedure TOuterControlEditor.ExecuteVerb(Index: Integer);
Var
    OuterControl : TOuterControl;
    InnerControl : TInnerControl;
begin
    inherited;

    OuterControl := TOuterControl(Component);

    If Index = 0 Then
    Begin
        InnerControl := TInnerControl.Create(OuterControl.Owner);
        OuterControl.AddInnerControl(InnerControl);
    End;
end;

function TOuterControlEditor.GetVerb(Index: Integer): String;
begin
    Result := 'Add Inner';
end;

function TOuterControlEditor.GetVerbCount: Integer;
begin
    Result := 1;
end;

Procedure Register;
Begin
    RegisterComponents('AA', [TOuterControl]);
    RegisterComponentEditor(TOuterControl, TOuterControlEditor);
End;

Initialization
    Classes.RegisterClasses([TInnerControl]);

end.

A: You can prevent them from appeaing on the form with:
RegisterNoIcon([TInnerControl]);

More info on RegisterNoIcon can be found at http://docwiki.embarcadero.com/VCL/e/index.php/Classes.RegisterNoIcon
It's a little confusing having classes with a name that end with "Control" that aren't normal visual controls though.

A: If TInnerControl is meant to be used only inside a TOuterControl, then you should call SetSubComponent(True) during/after the TInnerControl's creation.

A: When you create the inner controls, you tell them that their owner is the form (the owner of the outer control). Therefore, the form draws them, just like it draws all the other components it owns. You probably want the outer control to own the inner ones.


text:
Q: Not getting correct date from database Not getting correct date from database on the following lines. The actual date in database is 04/30/2016 09:30:00 PM but I'm getting it as 01/01/0001 12:00:00 AM. Not sure what's going on.
 DateTime fromDb =  sqlReader.GetDateTime(1);
 DateTime toDb = sqlReader.GetDateTime(2);

Here is the full method:
 private bool IsRoomAlreadyTaken(String room, DateTime fromUser, DateTime toUser)
    {
        bool roomAlreadyTaken = false;
        using (SqlConnection sqlConnection = new SqlConnection(connectionString))
        {
            SqlCommand sqlCmd = new SqlCommand("SELECT Id, convert(varchar(30), DateFrom, 131), convert(varchar(30), DateTo, 131) FROM Access_Privilege where RoomId = @RoomId", sqlConnection);
            sqlCmd.Parameters.AddWithValue("@RoomId", room);
            sqlConnection.Open();
            SqlDataReader sqlReader = sqlCmd.ExecuteReader();
            while (sqlReader.Read())
            {
                DateTime fromDb =  sqlReader.GetDateTime(1); //On this line
                DateTime toDb = sqlReader.GetDateTime(2); //On this line

                if (DateTime.Compare(fromUser, fromDb) == 0 && TimeSpan.Compare(fromUser.TimeOfDay, fromDb.TimeOfDay) > 0 && TimeSpan.Compare(toUser.TimeOfDay, toDb.TimeOfDay) <0)
                {
                    roomAlreadyTaken = true;
                }
            }
            sqlReader.Close();
        }
        return roomAlreadyTaken;
    }

Edit after trying the following suggestions from @ManOVision:
From the docs: "No conversions are performed; therefore, the data retrieved must already be a DateTime object."
I've had trouble in the past with SqlDataReader.Get[type] before. Try switching it to Convert.ToDateTime(sqlReader.GetValue(1).ToString()) or at least check what sqlReader.GetValue(1) returns from the database.
Results, with the following lines altered:
MessageBox.Show("sqlReader.GetValue(1)-->" + sqlReader.GetValue(1));
MessageBox.Show("sqlReader.GetValue(2)-->" + sqlReader.GetValue(2));
DateTime fromDb =  Convert.ToDateTime(sqlReader.GetValue(1).ToString());
DateTime toDb = Convert.ToDateTime(sqlReader.GetDateTime(2).ToString());

sqlReader.GetValue(1) returns 23/07/1437 9:30:12:000 PM and sqlReader.GetValue(2) returns 23/07/1437 10:30:12:483 PM. With GetValue(), time seems to be have returned correctly but somehow date is still messed up. This experiment proves that the record that is being returned from the DB is the correct one. But date value is still being lost in conversion.
On further execution of the program, Convert.ToDateTime(sqlReader.GetValue(1).ToString()) throws the following error:
String was not recognized as a valid DateTime.

at System.DateTimeParse.Parse(String s, DateTimeFormatInfo dtfi, DateTimeStyles styles)
   at System.Convert.ToDateTime(String value)
   at SGFinalProjectRoomAllocationSystem.ManageAccessForm.IsRoomAlreadyTaken(String room, DateTime fromUser, DateTime toUser) in c:\Projects\SGFinalProjectRoomAllocationSystem\SGFinalProjectRoomAllocationSystem\ManageAccessForm.cs:line 222
   at SGFinalProjectRoomAllocationSystem.ManageAccessForm.ValidatePrivilegs(String emp, String room, DateTime from, DateTime to) in c:\Projects\SGFinalProjectRoomAllocationSystem\SGFinalProjectRoomAllocationSystem\ManageAccessForm.cs:line 246
   at SGFinalProjectRoomAllocationSystem.ManageAccessForm.grntAccssBtn_Click(Object sender, EventArgs e) in c:\Projects\SGFinalProjectRoomAllocationSystem\SGFinalProjectRoomAllocationSystem\ManageAccessForm.cs:line 283
   at System.Windows.Forms.Control.OnClick(EventArgs e)
   at System.Windows.Forms.Button.OnClick(EventArgs e)
   at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
   at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
   at System.Windows.Forms.Control.WndProc(Message& m)
   at System.Windows.Forms.ButtonBase.WndProc(Message& m)
   at System.Windows.Forms.Button.WndProc(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
   at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
   at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
   at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
   at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
   at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
   at System.Windows.Forms.Application.Run(Form mainForm)
   at SGFinalProjectRoomAllocationSystem.Program.Main() in c:\Projects\SGFinalProjectRoomAllocationSystem\SGFinalProjectRoomAllocationSystem\Program.cs:line 19

A: Try DateTime.Parse method. MSDN
DateTime fromDb =  DateTime.Parse(sqlReader[1].ToString());
 DateTime toDb = DateTime.Parse(sqlReader[2].ToString());
Or Try DateTime.TryParse method. MSDN
DateTime fromDb;
if(DateTime.TryParse(sqlReader[1].ToString(), out fromDb))
    //Conversion Successful. fromDb is set
else
    //Conversion Unsuccessful

A: Convert methods were causing the problem. Removing them from the query solved it.
Code with the problem:
SqlCommand sqlCmd = new SqlCommand("SELECT Id, convert(varchar(30), DateFrom, 131), convert(varchar(30), DateTo, 131) FROM Access_Privilege where RoomId = @RoomId", sqlConnection);

Working code.
SqlCommand sqlCmd = new SqlCommand("SELECT Id, DateFrom, DateTo FROM Access_Privilege where RoomId = @RoomId", sqlConnection);

A: From the docs: "No conversions are performed; therefore, the data retrieved must already be a DateTime object."
I've had trouble in the past with SqlDataReader.Get[type] before. Try switching it to Convert.ToDateTime(sqlReader.GetValue(1).ToString()) or at least check what sqlReader.GetValue(1) returns from the database.


text:
Q: Does Java recognize infinite loops? Given the following code sample:
public class WeirdStuff {

    public static int doSomething() {
        while(true);
    }

    public static void main(String[] args) {
        doSomething();
    }
}

This is a valid Java program, although the method doSomething() should return an int but never does. If you run it, it will end in an infinite loop. If you put the argument of the while loop in a separate variable (e.g. boolean bool = true) the compiler will tell you to return an int in this method.
So my question is: is this somewhere in the Java specification and are there situation where this behavior might be useful?

A: If you are asking if infinite loops can be useful, the answer is yes.  There are plenty of situations where you want something running forever, though the loop will usually be terminated at some point.
As to your question: "Can java recognized when a loop will be infinite?"  The answer is that it is impossible for a computer to have an algorithm to determine if a program will run forever or not.  Read about: Halting Problem
Reading a bit more, your question is also asking why the doSomething() function does not complain that it is not returning an int.
Interestingly the following source does NOT compile.
public class test {
  public static int doSomething() {
   //while(true);
   boolean test=true;
   while(test){

   }
  }
  public static void main(String[] args) {
   doSomething();
  }
}

This indicates to me that, as the wiki page on the halting problem suggests, it is impossible for there to be an algorithm to determine if every problem will terminate, but this does not mean someone hasn't added the simple case:
while(true);

to the java spec.  My example above is a little more complicated, so Java can't have it remembered as an infinite loop.  Truely, this is a weird edge case, but it's there just to make things compile.  Maybe someone will try other combinations.
EDIT: not an issue with unreachable code.
import java.util.*;

public class test {
  public static int doSomething() {
   //while(true);
   while(true){
    System.out.println("Hello");
   }
  }
  public static void main(String[] args) {
   doSomething();
  }
}

The above works, so the while(true); isn't being ignored by the compiler as unreachable, otherwise it would throw a compile time error!

A: I'll just quote the Java Language Specification, as it's rather clear on this:

This section is devoted to a precise explanation of the word "reachable." The idea is that there must be some possible execution path from the beginning of the constructor, method, instance initializer or static initializer that contains the statement to the statement itself. The analysis takes into account the structure of statements. Except for the special treatment of while, do, and for statements whose condition expression has the constant value true, the values of expressions are not taken into account in the flow analysis.

...

A while statement can complete normally iff at least one of the following is true:

*

*The while statement is reachable and the condition expression is not a constant expression with value true.

*There is a reachable break statement that exits the while statement.

...

Every other statement S in a nonempty block that is not a switch block is reachable iff the statement preceding S can complete normally.

And then apply the above definitions to this:

If a method is declared to have a return type, then every return statement (§14.17) in its body must have an Expression. A compile-time error occurs if the body of the method can complete normally (§14.1).
In other words, a method with a return type must return only by using a return statement that provides a value return; it is not allowed to "drop off the end of its body."
Note that it is possible for a method to have a declared return type and yet contain no return statements. Here is one example:
class DizzyDean {
  int pitch() { throw new RuntimeException("90 mph?!"); }
}

A: Java specification defines a concept called Unreachable statements. You are not allowed to have an unreachable statement in your code (it's a compile time error). A while(true); statement makes the following statements unreachable by definition. You are not even allowed to have a return statement after the while(true); statement in Java. Note that while Halting problem is undecidable in generic case, the definition of Unreachable Statement is more strict than just halting. It's deciding very specific cases where a program definitely does not halt. The compiler is theoretically not able to detect all infinite loops and unreachable statements but it has to detect specific cases defined in the spec.

A: Yes, you can see these 'infinite' loops in some threads, for example server threads that listen on a certain port for incoming messages.

A:
So my question is: is this somewhere in the Java specification

The program is legal Java according to the specification.  The JLS (and Java compiler) recognize that the method cannot return, and therefore no return statement is required.  Indeed, if you added a return statement after the loop, the Java compiler would give you a compilation error because the return statement would be unreachable code.

and are there situation where this behavior might be useful?

I don't think so, except possibly in obscure unit tests.
I occasionally write methods that will never return (normally), but putting the current thread into an uninterruptible infinite busy-loop rarely makes any sense.

A: After rereading the question....
Java understands while(true); can never actually complete, it does not trace the following code completely.
boolean moo = true;
while (moo);

Is this useful? Doubtful.

A: You might be implementing a general interface such that, even though the method may exit with a meaningful return value, your particular implementation is a useful infinite loop (for example, a network server) which never has a situation where it should exit, i.e. trigger whatever action returning a value means.
Also, regarding code like boolean x = true; while (x);, this will compile given a final modifier on x. I don't know offhand but I would imagine this is Java's choice of reasonable straightforward constant expression analysis (which needs to be defined straightforwardly since, due to this rejection of programs dependent on it, it is part of the language definition).

A: Some notes about unreachable statements:
In java2 specs the description of 'unreachable statement' could be found. Especially interesting the following sentence:

Except for the special treatment of while, do, and for statements whose condition expression has the constant value true, the values of expressions are not taken into account in the flow analysis.

So, it is not obviously possible to exit from while (true); infinite loop. However, there were two more options: change cached values or hack directly into class file or JVM operating memory space.


text:
Q: Does comparing string representation of dates in a binary tree implementation offer any advantages over comparing dates directly? Does lexical comparation of Dates (or DateTimes) offer any advantages when constructing Binary Search Trees over direct comparation of Dates (or DateTimes) when constructing the tree using the date as a key? The newer dates will always follow after the dates that were already added, which would result in a degenerate tree when comparing the dates. I would like to know if using a lexical comparation of the string representation of the date will help with this issue.
P.S. If this question is not appropriate for SO, please comment, I will remove it.


text:
Q: php класс для icq Потребовалось добавить в icq чат бота который периодически бы писал сообщения.
Попробовал несколько решений на php из сети, но все они очень старые и не заработали.
Может подскажет кто рабочий вариант для обмена сообщений в ** групповой чат-**icq.
C Уважением, Waik

A: Использую библиотеку WebIcqPro.class.php ссылка на github. Вроде работает.


text:
Q: Adjoint operator of OU generator The generator an OU process is given by
$$A = \operatorname{tr}(QD^2)+\langle Bx,D\rangle.$$
This one possesses an invariant measure given by
$$d\mu(x) = b(x) \ dx \text{ with } b(x) = \frac{1}{(4\pi)^{N/2} \vert Q_{\infty} \vert^{1/2}} e^{-\langle Q_{\infty}^{-1}x,x \rangle /4},$$
where $Q_{\infty}= \int_0^{\infty} e^{sB} Q e^{sB^*} \ ds.$
I read that $A$ is self-adjoint on $L^2(\mathbb R^n, d\mu)$ if and only if $QA^*=AQ,$ but I have never seen an argument for this.
In particular, what I am mainly interested in, is there anywhere an explicit representation of the adjoint operator of $A$?

A: The argument is a bit tricky. Assume for simplicity that $Q=I$, then $BQ_\infty+Q_\infty B^*=-I$. Next decompose $A$ as a self-adjoint part plus a remainder, namely introduce the form $a(u,v)=\int_{\mathbb R^n} \nabla u \nabla v \, d\mu$ which corresponds to $A_1=\Delta-\frac 12 Q_\infty ^{-1} x \cdot \nabla$ and write $A=A_1+C$ with $C=(Bx+\frac 12 Q_\infty^{-1} x) \cdot \nabla$.
A computation shows that $C$ is skew-adjoint in $L^2_\mu$, so that $A$ is self-adjoint iff $C=0$ or $B=-\frac 12 Q_\infty^{-1}$, in particular $B=B^*$. On the other hand, if $B=B^*$, we can diagonalize $B$ and check that $B=-\frac12 Q_\infty^{-1}$ so that $A=A_1$ is self-adjoint. This answers to the first question. Concerning the second, $A^*=A_1-C$, but I dooubt that one can compute it explicitely without knowing $Q_\infty$.


text:
Q: How to convert Java Hashmap Hierarchy to its equivalent in Redis Cache? I have the following Job class representing runs of a job. I have a list of start and end times in Job class because the same Job can be rerun.
public class Job {

      private final List<Timestamp> jobStartTimes = new SortedList<>();
      private final List<Timestamp> jobEndTimes = new SortedList<>();
      private String jobName;
      private String jobKey;
      private String host;
      ....
      ....
}

I have this Map for querying jobs given jobkey.
public class JobMap {

         /**
         * Here value of 'String' key is jobKey
         */
         private final Map<String, Job> jobCache;
}

I have also created the following hierarchy of hashmaps for storing (starttime, jobKey) and (endtime, jobkey) entries in Map so that I can retrieve job records faster. This is needed because my queries are timestamp based, for ex: return all jobs that ran between x and y timestamp.
public class YearCache<T> {

        /**
         * Here value of 'Integer' key is month number (0, 11)
         */
        private final Map<Integer, MonthCache> monthCache;
}

public class MonthCache {

        /**
         * Here value of 'Integer' key is week number in a month(0, 4)
         */
        private final Map<Integer, WeekCache> weekCache;
}

public class WeekCache {

        /**
         * Here value of 'Integer' key is day number in a week (0, 6)
         */
        private final Map<Integer, DayCache> dayCache;
}

private class DayCache
{
        /**
         * Here value of 'Integer' key is hour value in a day (0, 23)
         * T is of type String representing jobKey
         */
         private final NavigableMap<Integer, NavigableMap<Timestamp, Set<T>>> hourCache;
}

I want to get rid of this Java hashmaps and move to Redis Cache. How can I model this hierarchy in Redis Cache?

A:
This is needed because my queries are timestamp based, for ex: return all jobs that ran between x and y timestamp.

Take a look at Sorted Set Time Series Pattern in Redis Time Series Patterns. Details can be found here. You might have to tweak the example by a bit to suit your need. Excerpt from the doc:
+---------------+-------------+
| Timestamp     | Temperature |
+---------------+-------------+
| 1511533205001 | 21          |
+---------------+-------------+
| 1511533206001 | 22          |
+---------------+-------------+

You can query like this:
> ZADD temperature 1511533205001 21
(integer) 1
> ZADD temperature 1511533206001 22
(integer) 1
> ZRANGEBYSCORE temperature -inf +inf WITHSCORES
1) "22"
2) "1511533206001"
3) "21"
4) "1511533207001"

This is a simple example. The link discusses an extension to this approach to handle a specific corner case.
For your case, given that you have jobStartTime and jobEndTime, you might have to use separate sets for jobStarts and jobEnds keyed by the timestamp in which the job was started/ended. Then:
Let x denote the start and y denote the end of a job

*

*Query all the jobs that were started after x from jobStarts set

*Query all the jobs that completed before y but started after x from jobsEnds set

*Repeated values from the results of step 1 and 2 yields the jobs that were started after x and ended before y
In your code:
public class Job {

      private final List<Timestamp> jobStartTimes = new SortedList<>();
      private final List<Timestamp> jobEndTimes = new SortedList<>();
      ....
      private String jobKey;
      ....
}

you're storing all the runs as part of the job. It's better to segregate the job runs separately from the job so that the job details can be cached separately in a set called jobs. Then the values of sets jobStarts and jobEnds can be the jobKey using which you can look up the details from the jobs set which stores the job details separately.