text:
Q: Obtain the best move from MiniMax algorithm in Tic-Tac-Toe game I'm trying to implement MiniMax algorithm based on Wikipedia pseudocode in Tic-Tac-Toe game written in C. However, I can't manage to obtain the best possible move. Here's my code:
#include <stdio.h>
#include <stdbool.h>
#include <string.h>

// compile and run: gcc minimax.c -std=c99 && ./a.out

int max(int x, int y) {
  return x > y ? x : y;
}

int min(int x, int y) {
  return x < y ? x : y;
}

int whoWon(char ch) {
  switch (ch) {
    case 'O':
      return -1;
      break;
    case 'X':
      return 1;
      break;
  }
}

void printArray(char array[]) {
  printf("# START\n"
         "%c | %c | %c\n"
         "--|---|--\n"
         "%c | %c | %c\n"
         "--|---|--\n"
         "%c | %c | %c\n"
         "# END\n\n", array[0], array[1], array[2], array[3], array[4], array[5], array[6], array[7], array[8]);
}

int anyWinners(char board[])
{
  int i;

  /* check every row */
  for(i = 0; i < 7; i += 3)
    if(board[i] != ' ' && board[i] == board[i+1] && board[i] == board[i+2])
      return whoWon(board[i]);

  /* check every column */
  for(i = 0; i < 3; i++)
    if(board[i] != ' ' && board[i] == board[i+3] && board[i] == board[i+6])
      return whoWon(board[i]);

  /* check diagonals */
  if(board[4] != ' ' && ((board[0] == board[4] && board[0] == board[8]) || (board[2] == board[4] && board[2] == board[6])))
    return whoWon(board[4]);

  return 0;
}

int fullBoard(char board[]) {
  for (int i = 0; i < 9; ++i) {
    if (board[i] == ' ')
      return 0;
  }
  return 1;
}

int minimax(char node[], int depth, bool maximizingPlayer, int * move) {
  int terminalNode = anyWinners(node);
  if (depth == 0 || terminalNode || fullBoard(node)) {
    printf("################## END OF SUBTREE ##################\n");
    return terminalNode;
  }

  int bestValue, val;
  if (maximizingPlayer) {
    bestValue = -2;
    for (int i = 0; i < 9; ++i) {
      if (node[i] == ' ') {
        char child[9];
        strcpy(child, node);
        child[i] = 'X';

        // debug
        printArray(child);

        val = minimax(child, depth - 1, false, move);

        // debug
        printf("X: ^^ i = %d ^^ depth = %d ^^ val = %d\n", i, depth, val);

        //bestValue = max(bestValue, val);
        if (val > bestValue) {
          bestValue = val;
          if (depth == 9) *move = i;
        }
      }
    }
    return bestValue;
  } else {
    bestValue = 2;
    for (int i = 0; i < 9; ++i) {
      if (node[i] == ' ') {
        char child[9];
        strcpy(child, node);
        child[i] = 'O';

        // debug
        printArray(child);

        val = minimax(child, depth - 1, true, move);

        // debug
        printf("O: ^^ i = %d ^^ depth = %d ^^ val = %d\n", i, depth, val);

        bestValue = min(bestValue, val);
      }
    }
    return bestValue;
  }
}

int main() {
  int move = -999; // initialize only for debug

  // X will always win no matter what, first best move for X is 8
  // char board[] = {'O', ' ', ' ',
  //                 ' ', ' ', ' ',
  //                 'X', 'X', ' '};

  // best move for X is 3
  char board[] = {'O', 'O', ' ',
                  ' ', 'X', 'X',
                  ' ', ' ', ' '};

  // Initial call for maximizing player
  int result = minimax(board, 9, true, &move);
  printf("minimax returned: %d\n", result);
  printf("chosen move: %d\n", move);

  return 0;
}

Code prints board for each move with state of all variables. There are also two failing tests commented out in main. Right now algorithm returns bad moves and I can't find the error.

A: I see two problems:

*

*The heuristic is wrong

*There is a problem with strcpy.

The heuristic is wrong
The Wikipedia pseudo-code says:
if depth = 0 or node is a terminal node
    return the heuristic value of node

Your implementation does this:
if depth = 0 or node is a terminal node
    return 1 if X wins, -1 if O wins, 0 if it is a draw

But that isn't a very good heuristic.  With that heuristic, all the possible ways that X could win are equally weighted.  So if X finds a way to win in 3 moves, that is weighted just the same as if X finds a way to win in 2 moves, and that is weighted just the same as if X finds a way to win in 1 move.
So, here is what happens in your test case:

*

*X tries position 2.

*O tries position 3.

*X tries position 6.

*This is a terminal node.  X wins.  So return positive 1.

Heuristic for this decision path = 1
Another possibility it hits is:

*

*X tries position 3.

*This is a terminal node.  X wins.  So return positive 1.

Heuristic for this decision path = 1
Since both of these solutions have the same heuristic, so they are both of equal value.  You probably meant for this solution to be suboptimal, because it took too many moves to win.  I suggest a heuristic based on the number of moves it took to get here, multiplied who the winner is.  So if X wins in 1 moves, heuristic is 5000.  If X wins in 2 moves, then heuristic is 2500.  If O wins in 2 moves, heuristic is -2500.  Something like that.
There is a problem with strcpy
This line:
strcpy(child, node);

should be:
memcpy(child, node, 9*sizeof(char));

Because "node" is not a null terminated string.  When I run this on VS2013/Windows 8.1 my output is garbage because.  You might be getting lucky on your platform.


text:
Q: How to bind Xpage with 3 datasources I have 3 forms (A,B,C) in my database. I am using LocNumber as the unique key to bind them together (although I could of course use UNID).
I want to present the user(s) with one Xpage that has these three forms. I have made a CC for A,B, and C and bound them to the correct form in the datasource.
My save button does a validate and then saves datasources.
But how do I "bind" the three cc's together on the page? In form B I have a LocNumber field. Do I create a field in cc B for LocNumber bind it to LocNumber on the form but load it with the value from UNID on form 1?
This must be a solved problem.
BTW, I choose to chunk everything like this as I will have a separate group of people to edit each set of fields (in form A,B,C).

A: I also prefer to use a uniqueKey like @Unique() for instance.  Though in XPages you need to wrap it in a session.evaluate() to get the old school style.
Anyway - first you might want to rethink this. there isn't a need to chunk this up between 3 forms/documents.  You could do it all with one and put each chunk into a Panel and compute the read only property so it's true for people that don't have editor access and false for people that do.  That works really well.
for the custom controls.  I would pass in the key as a custom property.  Then inside each use that to compute to the document so it's available to you.  SSJS to getdocumentbykey type of thing.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Word count algorithm issue So I am trying to make a word count program where the user can paste text in to get a word count of type text in to get a word count. The typing text in works for the most part but sometimes I get a string index out of range error when I try to go back and replace text. The pasting works but I am having issues with the string index being out of range issue here as well. My logic works like this: a space equals a word, two spaces back to back is minus one word, and the end of the string counts as a word. I am relatively new to Java and I thought this was going to be an easy thing to make, I was wrong! Some help/explanation would be appreciated!
 public static int getWordCount(String getInput, int e){
    int numberOfWords = 0;
    char l1 = 0;
    char l2 = 0;
    StringBuilder convertInput = new StringBuilder(getInput);
    System.out.println(convertInput);
    for (int i = 0, i1 = 1; i < getInput.length();i++, i1++){
        l2 = convertInput.charAt(i);
        if (l2 == ' '){
            numberOfWords += 1;
            l1 = convertInput.charAt(i1);
        }
        if (i == getInput.length() - 1){
            numberOfWords += 1;
        }
        if (l2 == ' ' && l1 == ' '){
            numberOfWords -= 1;
        }
    }
    return numberOfWords;
 } // end of getWordCount method

A: you can do this easy and quick with:
String phrase = "word1 word2 word3 word4";
String delims = " "; //u can declare more delims here like delims = " ,.{[]}\";
String[] tokens = phrase.split(delims);

tokens.length = number of words in your string


text:
Q: Swift: Changing the hight of subview programmatically I'm implementing a subview but I need to change the subview high programmatically but. This is how I'm changing the high:
    func changeHigh() {
        UIView.animate(withDuration: 1.0, animations: {
            self.frame = CGRect(x: 0, y: 0, width: self.frame.width, height: self.frame.height - 50)

            self.buttonConstraint.constant = 10
        })
    }

But the problem with this implementation is animating also the position of the view. All I want is to change the high with out changing the position.
Any of you knows why is changing the position of the subview?
I'll really appreciate you help.

A: First, to change the height, you can just modify the size.height property of the frame.
self.frame.size.height -= 50 /// this will make it 50 pts less

Also, you should change constraints outside the animation block, not inside. Then, call layoutIfNeeded() to animate it.
Here's how your code should look:
func changeHigh() {
    self.buttonConstraint.constant = 10
    UIView.animate(withDuration: 1.0, animations: {
        self.frame.size.height -= 50
        self.layoutIfNeeded()
    })
}


text:
Q: View not displaying inside RadioGroup I want to get something like this

So I want a divider that divides the two radio buttons knowing the fact that Radio Group is a child class of Linear Layout with default oreintation set to vertical However If I do so. It is not happening. below is my tried xml code :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/bottomSheet"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingStart="20dp"
    android:paddingEnd="20dp"
    android:paddingTop="24dp"
    android:paddingBottom="16dp"
    android:background="@drawable/bottom_sheet_back"
    app:layout_behavior="@string/bottom_sheet_behavior">

    <TextView
        android:id="@+id/txtBottomNeft"
        .... />

    <ImageView
        android:id="@+id/imgBottomNeft"
        ... />

    <RadioGroup
        android:id="@+id/radioGroup"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/txtBottomNeft"
        android:layout_marginTop="32dp"
        android:orientation="vertical">

        <RadioButton
            android:id="@+id/radioIndian"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:checked="true"
            android:fontFamily="@font/lato"
            android:text="Indian Citizen"
            android:textColor="#2B2E33"
            android:textSize="16sp" />

        <View
            android:layout_width="match_parent"
            android:layout_height="0.3dp"
            android:layout_marginTop="16dp"
            android:layout_marginBottom="14dp" />

        <RadioButton
            android:id="@+id/radioForeign"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:fontFamily="@font/lato"
            android:text="Foreign/Dual Passport Holder"
            android:textColor="#2B2E33"
            android:textSize="16sp" />
    </RadioGroup>

    <LinearLayout
        ...">

        <Button
            ..../>

        <Button
            ..../>
    </LinearLayout>
</RelativeLayout>

output of the above code:

A: You can just add a background color to your view between the buttons
<View
android:layout_width="match_parent"
android:layout_height="0.3dp"
android:background="@android:color/black"
android:layout_marginTop="16dp"
android:layout_marginBottom="14dp" />

To make it shorter add margin to the right and left. Here are also some other options.


text:
Q: Multithreaded Uploader I want to upload huge files (between 2 to 40 GB) to Azure Blob Storage.
First I successfully split each file to chunks (each chunk = 2 MB).
Then I upload chunks one by one, after each chunk is uploaded successfully I update a temp file to be able to resume the upload in case the application is closed.
Now I want to make the uploading operation Multithreaded.
After reviewing the TPL I got confused where to start!
any guidance where to start with TPL?
void Upload(int segmentId)
{
    try
    {
        string blockId = GetBlockId(segmentId);
        var segment = GetSegment(FilePath, segmentId, SeqmentSize);
        var md5Hash = CalcMd5Hash(segment);

        var blob = new CloudBlockBlob(_link.Uri);
        using (var memoryStream = new MemoryStream(segment))
        {
            blob.PutBlock(blockId, memoryStream, md5Hash);
        }

        SerializeStatus();
    }
    catch (Exception exception)
    {
        ...
    }
}

A: I built something similar long time back (though I used async approach rather than TPL) where I wanted to upload really large blobs with resumable capability. Here's what I did :

*

*First based on the block size, I split the file into chunks. Each chunk is assigned an id. I then created an object which hold the chunk id and the status of that chunk. For simplicity, I kept the following statuses for a chunk - NotStarted, Successful, and Failed.

*I then created a collection of these chunks and serialized that data into a file.

*Based on the number of parallel threads (let's say x), I fetch x items from the collection where status is NotStarted. Then I processed these chunks in parallel. I passed the chunk id as user state so that when I get a call back, based on the upload status, I update the collection accordingly and serialize the data back.

*Once all chunks have been uploaded, I checked if there were any failed chunks. If there were any, I retry those chunks.

*Once all chunks are successfully completed, I simply create a block list from the chunks collection and commit that block list. If the commit block list operation is successful, I simply deleted that file containing chunks data.

Hope this helps.
Update
Do take a look at this pseudo code and see if this helps you:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace UploadLargeBlob
{
    class Program
    {
        static void Main(string[] args)
        {
            List<ChunkInformation> chunksToUpload = new List<ChunkInformation>();
            CreateChunkCollection("MyVeryLargeFile", 2*1024*1024);
            int numberOfParallelThreads = 8;
            do
            {
                var chunksToProcess = chunksToUpload.Where(c => c.Status == ChunkStatus.NotStarted || c.Status == ChunkStatus.Failed).Take(numberOfParallelThreads);
                if (chunksToProcess.Count() == 0)
                {
                    break;
                }
                List<Task> tasks = new List<Task>();
                try
                {
                    foreach (var chunk in chunksToProcess)
                    {
                        tasks.Add(Task.Factory.StartNew(() =>
                            {
                                DoUpload(chunk);
                            }, chunk));
                    }
                    Task.WaitAll(tasks.ToArray());
                }
                catch (AggregateException excep)
                {
                    foreach (var task in tasks)
                    {
                        if (task.Exception != null)
                        {
                            ChunkInformation chunk = task.AsyncState as ChunkInformation;
                            chunk.Status = ChunkStatus.Failed;
                            //Now serialize the data.
                        }
                    }
                }
            }
            while (true);
        }

        static void DoUpload(ChunkInformation chunk)
        {
            //Do the actual upload

            //Update chunk status once chunk is uploaded
            chunk.Status = ChunkStatus.Successful;

            //Serialize the data.
        }

        static void CreateChunkCollection(string fileName, int chunkSize)
        {
        }
    }

    public class ChunkInformation
    {
        public string Id
        {
            get;
            set;
        }

        public ChunkStatus Status
        {
            get;
            set;
        }
    }

    public enum ChunkStatus
    {
        NotStarted,
        Successful,
        Failed
    }
}


text:
Q: Resize text when mouse enter I have next fiddle jsfiddle where I want to resize text instead of image
Bootstrap

text

text

text

text

CSS
body {
height:1000px;
width:100%;
background-color:#F0F0F0;
}

#header_div {
width:100%;

JS:
 $(document).ready(function () {
   $(".header img").mouseleave(function () {
       $(this).stop().animate({
           height: "50px"
       }, 600);
   });

   $(".header img").mouseenter(function () {
       $(this).stop().animate({
           height: "100px"
       }, 600);
   });

   $(".text div").mouseleave(function () {
       $(this).stop().animate({
           height: "50px"
       }, 600);
   });

   $(".text div").mouseenter(function () {
       $(this).stop().animate({
           height: "100px"
       }, 600);
   });
 })

So as image, I can change size of image, but text don´t get bigger. Any help is very appreciated. Regards

A: Use fontSize to change the size of the text. So replace height with fontSize Modify your ".text div" events like this.
$(".text div").mouseleave(function () {
       $(this).stop().animate({
           fontSize: "50px"
       }, 600);
   });

   $(".text div").mouseenter(function () {
       $(this).stop().animate({
           fontSize: "100px"
       }, 600);
   });

See the fiddle.


text:
Q: Get results from WPDB I have this scenario that I can't figure out:
Inside table wp_comment I need to list all user_id (not duplicate) with comment_type=complete.
I tried this:
$results = $GLOBALS['wpdb']->get_results( "SELECT * FROM wp_comments WHERE comment_type='sensei_course_status' AND comment_approved='complete'", ARRAY_A );

$corsisti = $results[user_id];

// I need to print only ids to put this array in
get_users( include=> '$corsisti' )

The database screenshot:

A: You can use the wpdb::get_col() method to retrieve an array with values from a single column:
$corsisti = $GLOBALS['wpdb']->get_col( "SELECT `user_id` FROM wp_comments WHERE comment_type='sensei_course_status' AND comment_approved='complete'");

Then simply use the result in get_users (you do not need the quotes):
$users = get_users( include=> $corsisti );


text:
Q: Plotting the surface of a sphere onto a circle I am trying to create an animation of a sphere rotating but only 2π of the surface of this object can be seen, so I require the ability to plot regions (separation into longitude and latitude) onto a circle and to have them defined by parameters such that they can be altered for rotation using two angles (theta and phi from spherical polar coordinates).
I have tried a few things, but the only time a made anything worthwhile was using tricontour:
import matplotlib.pyplot as plt
import matplotlib.tri as tri
import numpy as np
from math import *

r=1.0
N=360

circlexy = np.asarray([[r*cos(radians(i)), r*sin(radians(i))]
                   for i in np.arange(0,N,0.1)])
circlez = [r*(cos(radians(j)))*sin(radians(j))
       for j in np.arange(0,N,0.1)]

x1 = circlexy[:,0]
y1 = circlexy[:,1]
z1=circlez

plt.figure()
plt.gca().set_aspect('equal')
plt.tricontourf(x1, y1, z1, 3)
plt.show()

However, this plot is not very smooth and even if it were to be it is not very helpful as z1 is required to be the same length as x1 and y1 and so I cannot see a way to define two angles (this plot only rotates in one plane).
I could well have made errors above as my experience in coding is not particularly broad. What would be best to use to make such a plot? Thank you for your time.


text:
Q: 7 segment display with given sequence I need to design the 7 segment display which show the numbers of 1-7-2-9-0-2-0-9 with the flip-flops. But I can't make the karnough map because of the repeated numbers of 2-9-0. Can you help me with this ?

A: You can have two different machine states produce the same output, there's no need to use the same state to represent the repeated digits.
call your machine states s1 s2 s3 s4 etc. they have a simple progression where each changes to the next state on a clock signal. you need 8 one for each place in your output (or more depending on what happens after the last digit.)
Now draw a Karnaugh map for each segment of the 7 segment vs the flip-flops or counters you used to make the states.

A: I think you are saying that your problem is that the same present state can go to different next states depending on whereabouts in the sequence you are. For example a present state of 2 can go to a next state of 9 or 0 and a present state of 0 can go to a next state of 9 or 2.
A way forward for you would be to design a 3 bit synchronous up counter with JK flipflops (or use a standard chip) which counts upwards from 0 to 7 (you have 8 states). Then decode off the counter outputs so that when the counter is at 0, 1 is displayed. A count of 1 displays 7. A count of 2 displays 2 etc etc.
You would then solve the K-maps with Q1, Q2 and Q3 counter outputs on the K-map axis. A K-map would be required to minimize the logic for each display segment, so 7 K-maps in all for the display.
Not forgetting that, if you decide to design your own up counter, you'd need another set of K-maps to design it. If you use JK flipflops then you'd need another 6 K-maps in addition to the 7 required to minimise the display driver logic.
This design is instead of trying to design a state machine which steps through your 8 states.

A: You can try similar this way, driving directly from AND gates for common cathode display (for com. anode  via transistor). You need to add another 6 AND gates (8 together). For repeating numbers just put OR after repeating ANDs and use diode combination only once.


text:
Q: Profile change is not working with gradle in jhipster 7 Changing profiles doesn't work in an app generated with jhipster (v7.3 & 7.4) and gradle. I followed this. When I run from command-line gradlew -Pprod, the app always starts in dev profile:
No active profile set, falling back to default profiles: dev,api-docs

I think something broke in the generators as nobody is providing the spring.profiles.active property. I miss it.replace('#spring.profiles.active#', profiles)} in the profile_prod.gradle file that I saw in previous releases. I added it, now application.yml in build folder contains spring: profiles: active: prod, but the app keeps defaulting to dev.
This is my profile_prod.gradle:
dependencies {
    testImplementation "com.h2database:h2"
}
def profiles = "prod"
if (project.hasProperty("no-liquibase")) {
    profiles += ",no-liquibase"
}
if (project.hasProperty("api-docs")) {
    profiles += ",api-docs"
}
springBoot {
    buildInfo()
}
bootRun {
    args = []
}
processResources {
    println 'I'm running -Pprod!'
    inputs.property('version', version)
    inputs.property('springProfiles', profiles)
    filesMatching("**/application.yml") {
        filter {
            it.replace("#project.version#", version)
        }
    }
}

A: This seems like a bug, I opened an issue, meanwhile this workaround works:

*

*In profile_prod.gradle, add to the processResources config: filter { it.replace('#spring.profiles.active#', profiles) }

*Remove or comment bootstrap.yml file, it has an empty spring.profiles.active that overwrites the previous replacement.


text:
Q: Input only digits and control buttons I want to input Salary with any value: 550,49, 2222,12, 9,3 and so on. But need to use control button like this: ,, backspace, ctrl + c, ctrl + v, ctrl + a.
Salary is TextBox with ShortcutsEnabled = true and event:
private void TbSalary_KeyPress(object sender, KeyPressEventArgs e)
{
    char number = e.KeyChar;
    if ((e.KeyChar <= 47 || e.KeyChar >= 58) && number != 8 && number != 44)
         //digits, BackSpace and ,
    {
        e.Handled = true;
    }
}

If remove this condition, the specified combinations will work. But not only numbers are entered.
Should I add tracking of all combinations here? Or is it possible to implement this task in another way?
MaskedTextBox requires a fixed number of characters with some "mask". But the Salary is different. Can be **,**, ******,* or *** and etc.
UPDATE
Prevent entering more than two numbers after the decimal point
if (number < ' ')
{
    return;
}
if (number >= '0' && number <= '9')
{
    if (this.Text.Contains(',')
        && this.SelectionLength == 0
        && this.SelectionStart > this.Text.IndexOf(',')
        && this.Text.Length - this.Text.IndexOf(',') > 2)
    {
        e.Handled = true;
    }

    return;
}

A: Please, don't use magic numbers like 47, let's work with characters. We should allow these characters:

*

*'0'..'9' range (numbers)

*control characters (which are below space ' ') for tab, backspace etc.

*',' (comma) as a decimal separator

All the other characters should be banned.
Code:
private void TbSalary_KeyPress(object sender, KeyPressEventArgs e)
{
    char number = e.KeyChar;
    TextBox box = sender as TextBox;

    if (number >= '0' && number <= '9' || number < ' ')
        return; // numbers as well as backspaces, tabs: business as usual
    else if (number == ',') {
        // We don't want to allow several commas, right?
        int p = box.Text.IndexOf(',');

        // So if we have a comma already...
        if (p >= 0) {
            // ... we don't add another one
            e.Handled = true;

            // but place caret after the comma position
            box.SelectionStart = p + 1;
            box.SelectionLength = 0;
        }
        else if (box.SelectionStart == 0) {
            // if we don't have comma and we try to add comma at the 1st position
            e.Handled = true;

            // let's add it as "0,"
            box.Text = "0," + box.Text.Substring(box.SelectionLength);
            box.SelectionStart = 2;
       }
    }
    else
        e.Handled = true; // all the other characters (like '+', 'p') are banned
}

Please, note, that there is possibility to Paste incorrect value (say, "bla-bla-bla") into TbSalary TextBox; to prevent it you can use TextChanged event:
private void TbSalary_TextChanged(object sender, EventArgs e) {
  TextBox box = sender as TextBox;

  StringBuilder sb = new StringBuilder();

  bool hasComma = false;

  foreach (var c in box.Text)
    if (c >= '0' && c <= '9')
      sb.Append(c);
    else if (c == ',' && !hasComma) {
      hasComma = true;

      if (sb.Length <= 0) // we don't start from comma
        sb.Append('0');

      sb.Append(c);
    }

  string text = sb.ToString();

  if (!text.Equals(box.Text))
    box.Text = text;
}


text:
Q: Error while uploading file on Net4India I am new in asp.net. I am trying to upload an image from sub-directory to root. It works fine while debugging the code. But when i upload on IIS it gives an
Access to the path 'C:\inetpub\wwwroot\APBooksHosting\HomeImage\Desert.jpg' is denied.

My directory structure :
-ROOT-books-users-create-HomePage.aspx (Page from where i try to upload an file)
-ROOT-HomeImage ("It is the folder where i want to upload an file")
I am using this code to upload an file
namespace WebApplication1.books.users.Create
{
 public partial class Homeimage : System.Web.UI.Page
 {

    public void upload image()
    {
       if (homeimguploader.HasFile)
       {

                String path = Server.MapPath("~/HomeImage/");
                String ext = Path.GetExtension(homeimguploader.FileName);

                if (ext == ".jpg" || ext == ".png" || ext == ".gif")
                {

                    homeimguploader.SaveAs(path + homeimguploader.FileName);
                    homeimage = homeimguploader.FileName;
                }
       }
    }
 }
}

A: For permission issue you can use below code:
// Get full permissons
var permission = new FileIOPermission(FileIOPermissionAccess.Write, "Full Physical Path Here");
var permissionSet = new PermissionSet(PermissionState.None);
permissionSet.AddPermission(permission);
if (permissionSet.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet))
{
      //your code here
}


text:
Q: Create instance of a type in another domain I'm reading a code which is creating an instance of a type in another Domain by reflection. Why do we need to do this? What is the advantages of this kind of instance creation?
AppDomain _domain = AppDomain.CreateDomain("ServerImporterDomain");
var type = typeof (ServerImporter);
ServerImporter si = _domain.CreateInstanceAndUnwrap(type.Assembly.FullName, type.FullName) as ServerImporter;

A: Some reasons for this would be:

*

*Security sandboxing. The app domain that you create can run at a lower trust level than the main application. This doesn't seem to be the case here as you are not passing an AppDomainSetup to the CreateDomain call.

*Memory management. If a given assembly requires large amounts of memory and you know that you only need to use that assembly for a short time, you can load it into its own domain and then unload it when you're done with it.

*Different domains can handle uncaught exceptions differently and have different ProcessExit handlers.

A good writeup is at http://blogs.msdn.com/b/cclayton/archive/2013/05/21/understanding-application-domains.aspx.


text:
Q: Prove that a red-black tree with $n$ internal nodes has height at most $2\lg(n+1)$ I cannot understand the first paragraph of the proof, which comes from the known book Introduction to Algorithms, third-edition, and I consider it has some errors, could anyone help me check about it?
Possible errors:

*

*It first prove the case $\text{height(x)=0},$ then it says "For inductive steps, consider a node $x$ that has positive height".
From my understanding of inductive proof, the base case should be able to trigger the inductive statement. I mean: the "first domino" should trigger the next one, so the statement should be something like non-negative height.

*It says "each child has a black-height of either $\text{bh}(x)$ or $\text{bh}(x)-1$", but when applying, only the latter is used: $(2^{\text{bh}(x)-1}-1)+(2^{\text{bh}(x)-1}-1)+1=2^{\text{bh}(x)}-1$.

Paragraph from the book:

A: There is no error.

*

*When we consider a node $x$ of height $n$, say, in the induction step, our induction hypothesis is that the result is true for all nodes having height less than $n$. Thus, every node considered after the base case of height $0$ does have positive height: saying that we're considering a node $x$ that has positive height is merely saying that we're considering a node that isn't part of the base case. If $x$ has height $1$, we're just assuming the result for nodes of height $0$, and we've already proved that the result holds for them. If $x$ has height $2$, we're assuming the result for nodes of height $0$ and $1$, and so on. This is just an instance of what is sometimes called strong (or complete) induction.

*First, there is no harm in failing to use information if that information is not needed for the argument. However, in this case all of the information is used. First, we note that each child of $x$ has height less than $x$, so the induction hypothesis says that if $y$ is a child of $x$, the result is true for the subtree rooted at $y$: it contains at least $2^{\operatorname{bh}(y)}-1$ internal nodes. If $y$ is red, $\operatorname{bh}(y)=\operatorname{bh}(x)$, and the subtree rooted at $y$ contains at least $2^{\operatorname{bh}(x)}-1$ internal nodes. If $y$ is black, $\operatorname{bh}(y)=\operatorname{bh}(x)-1$, and the subtree rooted at $y$ contains at least $2^{\operatorname{bh}(x)-1}-1$ internal nodes. In all cases, therefore, the subtree rooted at $y$ contains at least $$\min\left\{2^{\operatorname{bh}(x)}-1,2^{\operatorname{bh}(x)-1}-1\right\}=2^{\operatorname{bh}(x)-1}-1$$ internal nodes, but we needed the information about both possible colors of child in order to establish this bound. We can now conclude that the subtree rooted at $x$ has at least $$\left(2^{\operatorname{bh}(x)-1}-1\right)+\left(2^{\operatorname{bh}(x)-1}-1\right)=2\cdot 2^{\operatorname{bh}(x)-1}-2=2^{\operatorname{bh}(x)}-2$$ internal nodes that are the internal nodes of the two subtrees rooted at the children of node $x$. Finally, node $x$ itself is an internal node of the subtree rooted at $x$ and is not in the subtrees rooted at the children of node $x$, so the subtree rooted at $x$ must in fact have at least $2^{\operatorname{bh}(x)}-2+1=2^{\operatorname{bh}(x)}-1$ internal nodes. This completes the induction step.


text:
Q: about having rows with different datatype to be shown in datagridview in application form Hi guys how do you produce a gridview where first row contains text and second row contains a combobox?
i tried the code below but it renders the combobox control into a simple text saying the total item of the combobox.
        // create columns
        DataColumn column1 = new DataColumn();
        column1.Caption = "Attribute";
        column1.ColumnName = "Attribute";
        column1.DataType = typeof(string);

        DataColumn column2 = new DataColumn();
        column2.Caption = "Value";
        column2.ColumnName = "Value";
        column2.DataType = typeof(object);

        DataTable dt = new DataTable();
        dt.Columns.Add(column1);
        dt.Columns.Add(column2);

        // populate field
        DataRow row1 = dt.NewRow();
        row1.ItemArray = new object[] { "Id", "1" };

        DataRow row2 = dt.NewRow();
        row2.ItemArray = new object[] { "Name", "Vincent" };

        ComboBox cbox = new ComboBox();
        cbox.DropDownStyle = ComboBoxStyle.DropDownList;
        cbox.Items.AddRange(new object[]{1,2,3,4,5});

        DataRow row3 = dt.NewRow();
        row3.ItemArray = new object[] { "Num of Siblings",  cbox};

        DataRow row4 =dt.NewRow();
        row4.ItemArray = new object[] { "Age", "21" };

        dt.Rows.Add(row1);
        dt.Rows.Add(row2);
        dt.Rows.Add(row3);
        dt.Rows.Add(row4);

        // populate to datagridview
        dataGridView1.DataSource = dt;
        dataGridView1.Refresh();

are there any other way? i can also separate the combobox from the datagridview control like when the cell (supposed to be the combobox) is clicked, it will popup a dialogbox with combobox in it (2nd form) but this will make the user fill uncombfortable.
the user require me to have this kind of functionality and it should be in datagridview (fields got it from xml (dynamic fields)). the content of dropdown is just a sample, it will be given different values like when entering gender it will have male and female items instead.
Thanks in advance.

A: Try this to add textbox and combobox in same column but different rows See reference
                    dataGridView1.ColumnCount = 2; // Create 2 text box columns
                    dataGridView1.Columns[0].HeaderText = "Name";
                    dataGridView1.Columns[0].Width = 350;
                    dataGridView1.Columns[1].HeaderText = "Value";
                    dataGridView1.Columns[1].Width = 150;

                    DataGridViewRow heterow0 = new DataGridViewRow();
                    DataGridViewTextBoxCell textBoxCell = new DataGridViewTextBoxCell();
                    textBoxCell.Value = "Turn Over Based On";
                    DataGridViewComboBoxCell comboCell = new DataGridViewComboBoxCell();
                    comboCell.Items.Add("Chip Transaction");
                    comboCell.Items.Add("Win/Loss");

                    heterow0.Cells.Add(textBoxCell);
                    heterow0.Cells.Add(comboCell);
                    dataGridView1.Rows.Add(heterow0); // this row has a combo in first cell

A: If you mean this...
      column1    column2   column3
 row1:combobox1,combobox2,combobox2,.....
 row2: textbox1, textbox2, textbox3,......

then this will do it
List<string> newlist = new List<string>() { "12", "34", "56", "78", "90" };

            dataGridView1.ColumnHeadersBorderStyle = DataGridViewHeaderBorderStyle.Sunken;
            dataGridView1.ColumnCount = newlist.Count;

            foreach (DataGridViewColumn c in dataGridView1.Columns)
            {
                c.HeaderText = "yourvalue";
                c.HeaderCell.SortGlyphDirection = SortOrder.Ascending;
                c.DefaultCellStyle = new DataGridViewCellStyle() { BackColor = Color.AntiqueWhite, Alignment = DataGridViewContentAlignment.MiddleCenter };

            }

            DataGridViewRow dgr = new DataGridViewRow();
            DataGridViewRow dgr1 = new DataGridViewRow();
            //DataGridViewColumnCollection dgcc = new DataGridViewColumnCollection(dataGridView1);
            foreach (string s in newlist)
            {
                DataGridViewTextBoxCell tc = new DataGridViewTextBoxCell();
                DataGridViewComboBoxCell cc = new DataGridViewComboBoxCell();
                cc.Sorted = true;
                cc.Items.Add(s);
                tc.Value = s;
                dgr.Cells.Add(cc as DataGridViewCell);
                dgr1.Cells.Add(tc);
            }

            dataGridView1.Rows.AddRange(new DataGridViewRow[] { dgr, dgr1 });

in my example i used a list but you can use what you need,just bear in mind that the foreach assigning the string to each cell was for demonstration ,you can add the values as you require.


text:
Q: how to use Server.HtmlEncode with textbox in ASP.NET? When i am entering a value like "" in textbox then its throwing following error.

Someone told me to use Server.HTMLencode/Server.HTMLdcode. but i dont know how to use it with textbox. Please help me.

A: you must pass special caracter in your textbox for example < or > ...
you can adjust ValidateRequest to false in order to authorize, you adjust on your page
<%@ Page validateRequest="false" %>

link : http://www.asp.net/whitepapers/request-validation

A: If you want to allow these values, add ValidateRequest="false" to the <%@ page declaration
Be aware that this does leave you more vulnerable to potential XSS attacks, etc.

A: If you use .NET 4.5 you can set the requestValidationMode to 4.5:
<httpRuntime requestValidationMode="4.5" />

And then access the unvalidated querystring of form field data with:
Request.Unvalidated.Form["name"];

Then you can html decode the string to prevent XSS, I recommend to use the AntiXSS library for this (it's baked in ASP.NET 4.5).


text:
Q: While-loop doesn't work when more elements are added I have a while loop that compares elements from two different lists in each if-elif statement and appends the indices when all the criteria are met. This code works but when I add two more if-elif statements, it doesn't and I'm not sure why.
This code works:
i = 0
while i < len(startDate):
    j = 0
    while j < len(stopDate) and i < len(startDate):
        if startDate[i] != stopDate[j]:
            j += 1
        elif startDate[i] == stopDate[j]:
            if stopTime[j] < startTime[i]:
                j += 1
            elif stopTime[j] > startTime[i]:
                if startBehavior[i] != stopBehavior[j]:
                    j += 1
                elif startBehavior[i] == stopBehavior[j]:
                    interval.append(i)
                    interval.append(j)
                    i += 1

This code does not:
    i = 0
while i < len(startDate):
    j = 0
    while j < len(stopDate) and i < len(startDate):
        if startDate[i] != stopDate[j]:
            j += 1
        elif startDate[i] == stopDate[j]:
            if stopTime[j] < startTime[i]:
                j += 1
            elif stopTime[j] > startTime[i]:
                if startBehavior[i] != stopBehavior[j]:
                    j += 1
                elif startBehavior[i] == stopBehavior[j]:
                    if startInitiator[i] != stopInitiator[j]:
                        j += 1
                    elif startInitiator[i] == stopInitiator[j]:
                        if startReceiver[i] != stopReceiver[j]:
                            j += 1
                        elif startReceiver[i] == stopReceiver[j]:
                            interval.append(i)
                            interval.append(j)
                            i += 1

A: I believe that a much cleaner way to write your code is :
i = 0
while i < len(startDate) and j < len(stopDate):
    j = 0
    if startDate[i] == stopDate[j] and startBehavior[i] == stopBehavior[j] and \
       startInitiator[i] == stopInitiator[j] and startReceiver[i] == stopReceiver[j] and \
       stopTime[j] > startTime[i]:
           interval.append(i)
           interval.append(j)
               i += 1
    else:
        j+=1

Tell us if it works.

A: Rewriting it in a more "pythonic" way (even if data restructuration might improve quality) :
def criteria_respected(startDate, stopDate, startTime, stopTime,
                       startBehavior, stopBehavior, startInitiator,
                       stopInitiator, startReceiver, stopReceiver):
    if startDate != stopDate:
        return False
    if startTime >= stopTime:
        return False
    if startBehavior != stopBehavior:
        return False
    if startInitiator != stopInitiator:
        return False
    if startReceiver != stopReceiver:
        return False
    return True

interval = list()
for i in range(len(startDate)):
    for j in range(len(stopDate)):
        if criteria_respected(startDate[i], stopDate[j], startTime[i], stopTime[j], startBehavior[i], stopBehavior[j], startInitiator[i], stopInitiator[j], startReceiver[i], stopReceiver[j]):
            interval.append(i)
            interval.append(j)

I can't test it without your input.
The problem might be you only increase  i when all condition are met, if they never met, endless loop. If they do met, you don't [i][j+1]
Also ">=" on the second condition, that may have made you loop indefinitely on specific dataset. Did you have the same dataset for both versions?
If it doesn't work, can you give us the input and output wanted?


text:
Q: FileOutputStream append on SD I have a problem till now I can not understand.
os = new FileOutputStream(file,doAppend);
The file is on SD. If doAppend is false the file is saved correctly. If I split file in blocks and use first write with doAppend=false and successive with true the file is not saved correctly (as it is truncated).
The same function saves also to private folder on device but uses just os = activity.openFileOutput(red.m_slika_ime, Context.MODE_PRIVATE+Context.MODE_APPEND);
Between saving to SD or private the only difference is in OutputStream instantiation.
Since on private folder all works as expected it should be the FileOutputStream with append on Sd that is not working correctly.
Is this a known issue? workaround?
Thanks

A: It was my stupid error. I was elsewhere, each time before writing to SD, erasing my own file.
Happens:)
Thanks Luke anyway


text:
Q: Unable to obtain Android SupportMapFragment I have looked at several posted solutions to similar questions, but none of them have worked. In the code below findFragmentById always returns null. I'm invoking MapLocationFragment from another fragment.
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MapLocationFragment extends Fragment implements OnMapReadyCallback {
    private String tag;

    private OnFragmentInteractionListener mListener;

    public MapLocationFragment() {}   // Required

    private FragmentActivity context;
    private GoogleMap mMap;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        Log.d(tag, "onAttach");
        this.context = (FragmentActivity)context;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        tag = this.getClass().getSimpleName();
        Log.d(tag, "onCreate");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Log.d(tag, "onCreateView");

        View view = inflater.inflate(R.layout.fragment_map, container, false);

        SupportMapFragment frag1 = (SupportMapFragment) getChildFragmentManager()
              .findFragmentById(R.id.mapFragment);

        mapFragment.getMapAsync(this);

        return view;
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        // ...
    }
}

And the fragment layout (tried both fragment and FrameLayout)
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/mapFragment"
    android:name="com.google.android.gms.maps.SupportMapFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.spireon.fai.fleetlocate.MapLocationFragment">
</fragment>

A: First, there is no android:name attribute for a FrameLayout. That is an attribute for <fragment>.
So, let's pretend that instead of <FrameLayout>, you have <fragment> instead, as you hint in your question.
In that case, your problem is that you are trying to find R.id.mapFragment before you inflate the layout that contains R.id.mapFragment. You need to inflate the layout before you can use findViewById() or findFragmentById() to access the contents of that layout.

A: use :
MapFragment mapFragment = (MapFragment) getFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

inside your xml File use:
<fragment
            android:id="@+id/map"
            android:name="dz.android.grcm.WorkaroundMapFragment"
            android:layout_width="match_parent"
            android:layout_height="300dp"
            android:fragmentExitTransition="@layout/yourXmlFile" />

inside your manifest :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="packageName"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="17"
        android:targetSdkVersion="23" />

     <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true"/>

    <permission
      android:name="packageName.permission.MAPS_RECEIVE"
      android:protectionLevel="signature"/>

    <uses-permission android:name="packageName.permission.MAPS_RECEIVE"/>
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >

        <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="your_APIKEY_"/>

        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />

        <activity android:name="packageName.Time_Picker"
             android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>

</manifest>

for me it works with google_play_services_version : 7095000 and Android API 23
don't forget API_KEY, you have to générate it, refer to this link : console.developers.google.com
try it i hope it helps you .

A: After creating a new emulator, it started to work using the getChildFragmentManager() call. Thanks for the answers.

A: i have the same problem with SupportMapFragment i don't find it inside gms library the solution is to add this class WorkaroundMapFragment to your package:
package dz.android.grcm;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import com.google.android.gms.maps.MapFragment;;

public class WorkaroundMapFragment extends MapFragment {
    private OnTouchListener mListener;

    @SuppressWarnings("deprecation")
    @Override
    public View onCreateView(LayoutInflater layoutInflater, ViewGroup viewGroup, Bundle savedInstance) {
        View layout = super.onCreateView(layoutInflater, viewGroup, savedInstance);

        TouchableWrapper frameLayout = new TouchableWrapper(getActivity());

        frameLayout.setBackgroundColor(getResources().getColor(android.R.color.transparent));

        ((ViewGroup) layout).addView(frameLayout,
                new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));

        return layout;
    }

    public void setListener(OnTouchListener listener) {
        mListener = listener;
    }

    public interface OnTouchListener {
        public abstract void onTouch();
    }

    public class TouchableWrapper extends FrameLayout {

        public TouchableWrapper(Context context) {
            super(context);
        }

        @Override
        public boolean dispatchTouchEvent(MotionEvent event) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    mListener.onTouch();
                    break;
                case MotionEvent.ACTION_UP:
                    mListener.onTouch();
                    break;
            }
            return super.dispatchTouchEvent(event);
        }
    }
}

then you call this class like this :
public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.inscriptionmed);
        MapFragment mapFragment = (MapFragment) getFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
        // *************Fix Scroll Map*******************************
        if (map == null) {
            map = ((WorkaroundMapFragment) getFragmentManager()
                    .findFragmentById(R.id.map)).getMap();
            map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
            map.getUiSettings().setZoomControlsEnabled(true);
            map.setMyLocationEnabled(true);
            mScrollView = (ScrollView) findViewById(R.id.partentScroll);

            ((WorkaroundMapFragment) getFragmentManager().findFragmentById(
                    R.id.map))
                    .setListener(new WorkaroundMapFragment.OnTouchListener() {
                        @Override
                        public void onTouch() {
                            mScrollView
                                    .requestDisallowInterceptTouchEvent(true);
                        }
                    });

        }


text:
Q: Is there a function in excel that compares two similar (but not the same) cells and outputs a yes or no? I have a checking column built, with the intention of confirming two company names are the same. The two company names come from different programs, thus showing different formatting.
For example - BLACKROCK TRUST, INC. vs. Blackrock trust 1156
These are both the same company, so I wanted a column confirming "yes" these are the same because they share a certain percentage of the same characters. I tried transforming the company names, but this file is rather large, and has thousands of companies.
Thank you for any help!
I tried a number of IF based statements, but I feel like there is something easier that I am missing? My excel skills are rather intermediate, but not to the point of using VBA or something macro related.

A: I have had to do this before. Depending on how cumbersome are willing to get with "helper" columns that you can hide, I suggest the following answer using intermediate excel skills to test the similarity of two strings. The core assumption is that the first characters of the name will generally be the same and the differences will be in the formatting, suffix, or non-informative characters
Step 1: Create a helper column for each name with the following formula:
=SUBSTITUTE(LOWER(TRIM(CLEAN(A10)))," ","")
This will remove spaces and make each string lower case. You could also substitute "" for other non-distinguishing characters or strings in your data if they are common (for example, ",inc" ",llc" "." "," etc.).
Step 2: you now have two modified strings (let's say they are in cells C10 and D10). Populate cells E9:V9 with a sequentially increasing number, e.g. 3 4 5 6 ....
Step 3: Populate cells E10:V10 with the following formula to compare the first N characters of each string, where N is the values you have in cells E9:V9
=IF(EXACT(LEFT($C10,E$9),LEFT($D10,E$9)),E$9/MIN(LEN($C10),LEN($D10)))
This will tell you the % of leading characters that are the same between the two strings
Step 4: Select a threshold for likely match and populate column W with the following
=MAX(E10:V10)>0.8
This will indicate true for any two strings that match at least 80% of the leading characters. Your blackrock example only matched 78%, so 80% may be too high of a threshold but you can also flag ones that are close and check those manually


text:
Q: How to send parameters with hyperlink HREF in jade and access it in routes expressJs I am sending parameter from my jade
 a(href="/service-labourJobcardnumber=#{Jobcardnumber}") add labour

but it is not treating it as a parameter.How to send the parameter with jade and how can i access it in my index.js routes.
This is my index.js code
router.get('/service-labour/:Jobcardnumber', function(req, res) {
var db = req.db;
    var locals = {};
    console.log(req.params); return;
    locals.Jobcardnumber = req.body.Jobcardnumber;
            res.render('service-labour', locals);
});

But its not working.

A: Thanks for your response but i found the answer my mistake was i was using
locals.Jobcardnumber = req.params.Jobcardnumber;

but it should be
locals.Jobcardnumber = req.query.Jobcardnumber;


text:
Q: Converting string to unsigned char I've spent a while trying to get a string to turn into an array of unsigned chars, but no luck.
I'm doing an AES implementation and I have everything set up except the input reading part.
This is the code I have ATM.
string text = "E3 FD 51 12" ;
    int size = text.length();

    unsigned char* charText = new unsigned char[size/2];
    int i = 0;
    std::istringstream text_2(text);

    unsigned int c;
    unsigned char ch;
    while (text_2 >> hex >> c)
    {
        ch = c;
        cout <<ch;
    }

I want my string to be in the charText array. The string reads perfectly into the unsigned int, but when I try to place it in the array or in the unsigned char (ch), it gives me gibbrish.
Any help would be great.

A: Simply output the char as int.
while (text_2 >> hex >> c)
{
    ch = c;
    cout << hex << ( int )ch;
}


text:
Q: How to calculate two data in one array? I'm a beginner in php, I want to calculate two data from one array, but I still don't understand how.
For example, I have one data array
$array = (1,2,3,4);

and I want the output like this
1x2 = 2
1x3 = 3
1x4 = 4
2x3 = 6
2x4 = 8
3x4 = 12

I try some code but didn't help, and now I got stuck.
sorry my language is not good.

A: Just use two loops to iterate over the data:
<?php
$input = [1, 2, 3, 4];
foreach ($input as $left) {
  foreach ($input as $right) {
    if ($left < $right) {
      echo sprintf("%dx%d = %d\n", $left, $right, $left*$right);
    }
  }
}

For bigger data sets you might want to optimize it. Faster but harder to read:
<?php
$input = [1, 2, 3, 4];
foreach ($input as $key => $left) {
  foreach (array_slice($input, $key+1) as $right) {
    echo sprintf("%dx%d = %d\n", $left, $right, $left*$right);
  }
}

The output obviously is:
1x2 = 2
1x3 = 3
1x4 = 4
2x3 = 6
2x4 = 8
3x4 = 12


text:
Q: ZF2 Currency Format I am using ZF2 for my project. And this is an e-commerce site. So I am dealing with currencies.
In ZF2 there is a view helper named currencyFormat()
I am from Turkey so my main currency format is TRY (This is the ISO code of Turkish Lira). But in Turkey we do not use TRY as Currency icon. The icons are "$" for USD, € for "EUR" and "TL" for Turkish Lira (TRY).
So when I format a currency for TRY I am doing it like this in view script:
<?php
echo $this->currencyFormat(245.40, 'TRY', 'tr_TR');
?>

The result of this code is "245.40 TRY". But it has to be "245.40 TL"
Is there a way to solve this? I do not want to use replacement function.

A: I'm guessing when you say I do not want to use replacement function you mean it would be laborious to do a str_replace every time you call the helper. The solution would be to replace the helper with your own. Here's a quick how to
First create a helper of your own which extends the existing helper and handles the replacement if necessary...
<?php
namespace Application\View\Helper;

use Zend\I18n\View\Helper\CurrencyFormat;

class MyCurrencyFormat extends CurrencyFormat
{
    public function __invoke(
        $number,
        $currencyCode = null,
        $showDecimals = null,
        $locale       = null
    ) {
       // call parent and get the string
       $string = parent::__invoke($number, $currencyCode, $showDecimals, $locale);
       // format to taste and return
       if (FALSE !== strpos($string, 'TRY')) {
           $string = str_replace('TRY', 'TL', $string);
       }
       return $string;
    }
}

Then in Module.php, implement the ViewHelperProviderInterface, and provide it with details of your helper
//Application/Module.php
class Module implements \Zend\ModuleManager\Feature\ViewHelperProviderInterface
{

     public function getViewHelperConfig()
     {
         return array(
             'invokables' => array(
                  // you can either alias it by a different name, and call that, eg $this->mycurrencyformat(...)
                  'mycurrencyformat'  => 'Application\View\Helper\MyCurrencyFormat',
                  // or if you want to ALWAYS use your version of the helper, replace the above line with the one below,
                  //and all existing calls to $this->currencyformat(...) in your views will be using your version
                  // 'currencyformat'  => 'Application\View\Helper\MyCurrencyFormat',
              ),
         );
     }
}

A: As of 1 March 2012 sign for Turkish Lira is TRY. http://en.wikipedia.org/wiki/Turkish_lira
So ZF outputs it right I think.


text:
Q: Как передать атрибуты из html в ruby-файл? Добрый день, уважаемое сообщество!
Я не знаю, как правильно сформулировать мой вопрос. Я тщетно пытаюсь найти ответ на свой вопрос уже несколько дней, но везде натыкаюсь на руководства по Rails. Но я не хочу использовать рельсы или какие-либо другие фреймворки. Наверняка мою задачу можно решить без их использования.
У меня есть, например, файл index.html:
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
  </head>
  <body>
    <form>
      <label for="total">
        Укажите сумму:
      </label>
      <input type="text" name="total" id="total" required="required">
      <input type="submit" value="Сохранить">
    </form>
  </body>
</html>

И есть, например, файл main.rb:
require "sqlite3"

db = SQLite3::Database.open "salary.sqlite"

total = gets.chomp
db.execute "INSERT INTO salary (total) VALUES (?)", [total]
db.close

if total >= 1
  puts "Всё ОК!"
else
  puts "Что-то пошло не так..."
end

Подскажите, пожалуйста, как мне передать значение атрибута, заполняемого пользователем на форме в index.html, в руби-файл main.rb, чтобы он уже в свою очередь сохранил данные в базу данных?
Заранее огромное спасибо за помощь!

A: Есть несколько способов.

*

*CGI.

Способ особенно популярен для php. Суть метода в том, что веб-сервер (Apache или Nginx) будут просто вызывать нужный скрипт. Ответ должен быть помещён в стандартный поток вывода (puts). Вот статья, в которой есть пример составления cgi скриптов на руби.
Но нужно понимать, что без веб-сервера "не полетит". По настройкам веб-сервера подсказать не могу. Кроме того, процесс будет "рождаться чтобы умереть". Т.е. нужно будет позаботиться чтобы при каждом запросе всё инициализировалось заново (конфиги, подключение к бд и прочее)

*Написать Rack-совместимое приложение. И использовать rack-сервер вроде puma или unicorn.

Это уже сложнее. Хоть и не на много - просто нужно реализовать структуру приложения, удовлетворяющую Rack-интерфейсу. Зато будет в результате будет многопоточный бэкенд сервер, который можно использовать как самостоятельно, так и совместно с веб-серверами врое Apache и Nginx (для прода рекоммендуется делать именно так).

*Использовать родной рубёвый WebRick.

Имхо, самый самый муторный и самый ненадёжный способ. У этого компонента специфичный интерфейс (по ссылке выше есть примеры) и он не очень хорошо зерекомендовал себя при работе с конкурирующими запросами.
Конечно, он лишён некоторых недостатков CGI, но не так эффективен, как Rack + Бэкенд сервер. К тому же, сделать Rack-интерфейс гораздо проще.


text:
Q: ibm t61 battery isn't charged I've just bought an IBM T61 laptop and it has a non-orginal battery. Everything was ok (laptop worked without being plugged in), but something has changed, and now the battery isn't charged. Power Manager says:

This system may not support batteries that are not genuine Lenovo-made  or authorized. This sytem will contunue to boot, but may not charge unauthorized batteries

Here is a screenshot:

A: I have a (genuine) T400 myself, and while shopping for batteries on Amazon, I read some tales of woe from people who tried saving money and bought cheap OEM "Thinkpad-compatible" batteries and ran into the same issue.
Apparently, this is Lenovo's way to block competition. For their side, I read a claim that cheap, no-QA batteries may cause fire hazard and they are just trying to protect their users. I tended to scoff at that (just like I scoff at HP for blocking non-original inkjet cartridges), until I bought a cheapo power adapter for my T400, to replace the original. Boy, that thing heats up - even when the laptop is not connected.
All this long story just to say: take the battery out and make sure it's an original Lenovo. If it isn't - get an original one. If it is, there may be a Power Manager upgrade that will support it.
Good luck!


text:
Q: How to calculate time difference with previous row of a data.frame by group The problem I am trying to solve is that I have a data frame with a sorted POSIXct variable in it. Each row is categorized and I want to get the time differences between each row for each level and add that data back into a new variable. The reproducible problem is as below.
The below function is just for creating sample data with random times
for the purpose of this question.
random.time <- function(N, start, end) {
  st <- as.POSIXct(start)
  en <- as.POSIXct(end)
  dt <- as.numeric(difftime(en, st, unit="sec"))
  ev <- sort(runif(N, 0, dt))
  rt <- st + ev
  return(rt)
}

The code for simulating the problem is as below:
set.seed(123)
category <- sample(LETTERS[1:5], 20, replace=TRUE)
randtime <- random.time(20, '2015/06/01 08:00:00', '2015/06/01 18:00:00')
df <- data.frame(category, randtime)

The expected resulting data frame  is as below:
>category randtime timediff (secs)
>A  2015-06-01 09:05:00 0
>A  2015-06-01 09:06:30 90
>A  2015-06-01 09:10:00 210
>B  2015-06-01 10:18:58 0
>B  2015-06-01 10:19:58 60
>C  2015-06-01 08:14:00 0
>C  2015-06-01 08:16:30 150

Each subgroup in the output will have the first row with timediff value of 0 as there is no previous row. I was able to group by category and call the following function to calculate the differences but could not get it to collate the final output for all category groups.
getTimeDiff <- function(x) {
  no_rows <- nrow(x)
  if(no_rows > 1) {
    for(i in 2:no_rows) {
      t <- x[i, "randtime"] - x[i-1, "randtime"]
    }
  }
}

I have been at this for two days now without luck so would greatly appreciate any help.
Thanks.

A: Try this:
library(dplyr)
df %>%
  arrange(category, randtime) %>%
  group_by(category) %>%
  mutate(diff = randtime - lag(randtime),
         diff_secs = as.numeric(diff, units = 'secs'))

#   category            randtime             diff   diff_secs
#     (fctr)              (time)           (dfft)       (dbl)
# 1        A 2015-06-01 11:10:54         NA hours          NA
# 2        A 2015-06-01 15:35:04   4.402785 hours   15850.027
# 3        A 2015-06-01 17:01:22   1.438395 hours    5178.222
# 4        B 2015-06-01 08:14:46         NA hours          NA
# 5        B 2015-06-01 16:53:43 518.955379 hours 1868239.364
# 6        B 2015-06-01 17:37:48  44.090950 hours  158727.420

You may also want to add replace(is.na(.), 0) to the chain.

A: In base R you can use:
# creating an ordered data.frame
df <- data.frame(category, randtime)
df <- df[order(df$category, df$randtime),]

# calculating the timedifference
# option 1:
df$tdiff <- unlist(tapply(df$randtime, INDEX = df$category,
                          FUN = function(x) c(0, `units<-`(diff(x), "secs"))))
# option 2:
df$tdiff <- unlist(tapply(df$randtime, INDEX = df$category,
                          FUN = function(x) c(0, diff(as.numeric(x)))))

which gives:

> df
   category            randtime      tdiff
6         A 2015-06-01 11:10:54     0.0000
15        A 2015-06-01 15:35:04 15850.0271
18        A 2015-06-01 17:01:22  5178.2223
1         B 2015-06-01 08:14:46     0.0000
17        B 2015-06-01 16:53:43 31137.3227
19        B 2015-06-01 17:37:48  2645.4570
3         C 2015-06-01 10:09:50     0.0000
7         C 2015-06-01 12:46:40  9409.9693
9         C 2015-06-01 13:56:29  4188.4578
10        C 2015-06-01 14:24:18  1669.1326
12        C 2015-06-01 14:54:25  1807.1447
14        C 2015-06-01 15:05:07   641.7068
2         D 2015-06-01 09:28:16     0.0000
13        D 2015-06-01 14:55:40 19644.8313
4         E 2015-06-01 10:18:58     0.0000
5         E 2015-06-01 10:53:29  2071.2223
8         E 2015-06-01 13:26:26  9176.6263
11        E 2015-06-01 14:33:25  4019.0319
16        E 2015-06-01 15:57:16  5031.4183
20        E 2015-06-01 17:56:33  7156.8849

If you want minutes or hours, you can use "mins" or "hours" instead of "secs".

An alternative with the data.table package:
library(data.table)
# creating an ordered/keyed data.table
dt <- data.table(category, randtime, key = c("category", "randtime"))

# calculating the timedifference
# option 1:
dt[, tdiff := difftime(randtime, shift(randtime, fill=randtime[1L]), units="secs"), by=category]
# option 2:
dt[, tdiff := c(0, `units<-`(diff(randtime), "secs")), by = category]
# option 3:
dt[ , test := c(0, diff(as.numeric(randtime))), category]

which results in:

> dt
    category            randtime           tdiff
 1:        A 2015-06-01 11:10:54     0.0000 secs
 2:        A 2015-06-01 15:35:04 15850.0271 secs
 3:        A 2015-06-01 17:01:22  5178.2223 secs
 4:        B 2015-06-01 08:14:46     0.0000 secs
 5:        B 2015-06-01 16:53:43 31137.3227 secs
 6:        B 2015-06-01 17:37:48  2645.4570 secs
 7:        C 2015-06-01 10:09:50     0.0000 secs
 8:        C 2015-06-01 12:46:40  9409.9693 secs
 9:        C 2015-06-01 13:56:29  4188.4578 secs
10:        C 2015-06-01 14:24:18  1669.1326 secs
11:        C 2015-06-01 14:54:25  1807.1447 secs
12:        C 2015-06-01 15:05:07   641.7068 secs
13:        D 2015-06-01 09:28:16     0.0000 secs
14:        D 2015-06-01 14:55:40 19644.8313 secs
15:        E 2015-06-01 10:18:58     0.0000 secs
16:        E 2015-06-01 10:53:29  2071.2223 secs
17:        E 2015-06-01 13:26:26  9176.6263 secs
18:        E 2015-06-01 14:33:25  4019.0319 secs
19:        E 2015-06-01 15:57:16  5031.4183 secs
20:        E 2015-06-01 17:56:33  7156.8849 secs


text:
Q: How can I Iterate through PHP multi-dimension array that has label -> value structure New to PHP (from C#). I have an array ($metaarray), which if I json_encode() to the screen, it has this value:
[
{
    "measure":"Walking","record":"steps","latestres":"6870","datet":"2022-08-31"
},{
    "measure":"","record":"kilograms","latestres":"117","datet":"2022-09-12"
},{
    "measure":"","record":"","latestres":null,"datet":"2022-09-12"
},{
    "measure":"Walking","record":"steps","latestres":"6840","datet":"2022-09-12"
},{
    "measure":"Bodyweight","record":"kilograms","latestres":"92","datet":"2022-09-12"
},{
    "measure":"Benchpress","record":"kilograms","latestres":"90","datet":"2022-09-12"
}
]

Is there an easy way for me to iterate through the metaarray - or to easily reference a record - eg. I would normally do something like:
    $latestres = $metaarray[0][2];

...which should be "6870" - however it doesn't return any result when I do that.
Is there a way I can easily reference a particular value (eg. first record, "latestres" or 3rd value) in the above array?

A: I don't know if this helps you, but $data[2] does not represent third item in an array, unless the array happens to be created linearly (called a list). In PHP, 2 is actually the key to a map (name/value pair). So unless there is actually a key with that index, you can't access it. You can see a demo of what I'm talking about here.
You can get around the feature/limitation by using one of the tricks from this answer: https://stackoverflow.com/a/24825397/231316
function getNthItemFromArray(array $array, int $idx)
{
    return $array[array_keys($array)[$idx]];
}

Obviously you'd add some guards.
As everyone notes, you should really start with your data before the encode. However, assuming that for whatever you have a JSON string, you can tell the decoder to give you an associative array instead of an object. Putting that all together you could do something like:
$json = <<<EOT
[
{
    "measure":"Walking","record":"steps","latestres":"6870","datet":"2022-08-31"
},{
    "measure":"","record":"kilograms","latestres":"117","datet":"2022-09-12"
},{
    "measure":"","record":"","latestres":null,"datet":"2022-09-12"
},{
    "measure":"Walking","record":"steps","latestres":"6840","datet":"2022-09-12"
},{
    "measure":"Bodyweight","record":"kilograms","latestres":"92","datet":"2022-09-12"
},{
    "measure":"Benchpress","record":"kilograms","latestres":"90","datet":"2022-09-12"
}
]
EOT;

$decoded = json_decode($json, true);

echo getNthItemFromArray($decoded[0], 2);

function getNthItemFromArray(array $array, int $idx)
{
    return $array[array_keys($array)[$idx]];
}

Demo here: https://3v4l.org/POdma


text:
Q: Implementing Circular Buffer Found this interview question and trying to solve it with Java.

Q:Design a function to gives real time statistics of your web
  traffic,count one day's website visit ,count one week's website visit.

I understand that this will require a circular data structure. Which one will be appropriate in case of Java implementation CircularBuffer or Circular LinkedList.If circular buffer is not right solution then what is?

A: I would do this like this.
private long dayCount = 0;
private long lastSixDaysCount = 0;

// called once per day
public void rollDayCount() {
    saveDayCountToDB(dayCount);
    lastSixDaysCount = sumLastSixDaysFromDB();
    dayCount = 0;
}

public void incrementCount() {
    dayCount++;
}

public long getDayCount() {
    return dayCount;
}

public long getWeekCount() {
    return dayCount + lastSixDaysCount;
}

If you need to, you can make the fields volatile and synchronized on incrementCount()

A: Nothing to do with circular buffers - however, have a look at Buffer Utils from apache
The trick is to drop data when you capacity is exceeded, you can do this by creating an array with fixed size. Then use a readpointer and writerpointer. when the writepointer overlaps and is at the same position with the readpointer, move both.
If you show your existing code, we'll help you.

A: If it is simply counting the no of visitors than it is a tricky multithreading question to count no of unique visitors. This is one of the best places where you can use AtomicInteger.
AtomicInteger atomicInteger = new  AtomicInteger();
public void increment(){
    Integer present=null;
    Integer expect=null;
    do{
        present=atomicInteger.get();
        expect = present+1;
    }while(!atomicInteger.compareAndSet(present, expect));
}

If you have to clear it after some threshold than it's also simple. Hope it helps.

A: Maybe a CircularFifoBuffer is what you are looking for. As others wrote, I don't know if a circular structure is really what you need, but the Common-Collection-Utils from Apache already implement a circular buffer


text:
Q: Illegal left hand side of blocking assignment I am new to verilog. I am writing the code for a 10x16 Round-Shift register. Can you help me with the error and also if any optimizations can be done?
module shift_reg_v(
    output [15:0] word_out
);

integer i;
integer j;

reg [159:0] coeff;
reg [15:0] word;

initial
begin
    for (i=0;i<160;i=i+1)
    begin
        coeff[i] = 0;
    end

    for (i=0;i<16;i=i+1)
    begin
        word[i] = 0;
    end
end

always
begin
for (j=0;j < 10;j = j+1)
begin
    for (i=0;i < 16;i = i+1)
    begin
        if (j==0)
        begin
            word[i] = coeff[(16*(j+1))+i];
        end
        else
        begin
            coeff[(16*j)+i] = coeff[(16*(j+1))+i];
        end
    end
end

coeff[159:144] = word[15:0];
word_out[15:0] = word[15:0];

end
endmodule

The program is showing 2 errors at the output line:
word_out[15:0] = word[15:0];

A: Referring to error:

Error-[IBLHS-NONREG] Illegal behavioral left hand side
  a.sv, 42
Non reg type is not valid on the left hand side of this assignment
  The offending expression is : word_out[15:0]
  Source info: word_out[15:0] = word[15:0];

The LHS of any procedural assignment statement must be of reg type. Procedural assignment statements assign values to reg, integer, real, or time variables and can not assign values to wire. Note that reg can hold or store some value depending on some triggering event, while wire cannot store any value.
Make word_out as reg as follows:
module shift_reg_v(
    output reg [15:0] word_out
);

Referring to the warning:

Warning-[PALF] Potential always loop found
  a.sv, 24
  This always block has no event control or delay statements, it might
  cause    an infinite loop in simulation.

Moreover, you have not given any sensitivity for always block execution. This might result in infinite loop. There is no triggering control for always block. Henceforth the block shall execute infinitely.
Use always @(*) (or always_comb in SystemVerilog) for automatic sensitivity list in combinational logic.
As a side note, you might have a clk, as clocking input to the module and make the always block work on the edge of clock. This will help in modelling sequential logic. (Note the usage of nonblocking assignments <= in case of sequential logic).
Refer this PDF for difference between reg and nets.Also, this always block might be useful.

A: Also, you need to correct following code :-
coeff[i] = 0;
It is a bit assignment and  should clearly specify that as coding practice.
coeff[i] = 'h0;


text:
Q: How to assign dataframe to array R I have an array I am trying to iterate through, but when I try to assign to it and I get to the second 3rd dimension, I'm thrown an error.
  dataSetsTrain <- array(NA,dim=c(nrecords,ncol(set),numFolds))

  for(k in 1:numFolds)
  {
    objTrain <-set[folds!=k,]
    objTest <- set[folds==k,]

    dataSetsTrain[,,k] = objTrain
    #same/similar error
    #dataSetsTrain[,,k] -> objTrain
  }

Error
Error in dataSetsTrain[, , k] <- objTrain :
  incorrect number of subscripts
> dataSetsTrain[,,k]
Error in dataSetsTrain[, , k] : incorrect number of dimensions

A: You can use simplify2array() with the help of splitting the matrix by a factor. Using the iris dataset:
simplify2array(lapply(split(iris[, -5], iris[5]), as.matrix))

And a smaller subset:
DF <- iris
lst <- split(iris[, -5], iris[5])

simplify2array(lapply(lst, function(x) as.matrix(x[1:5, ])))

, , setosa

  Sepal.Length Sepal.Width Petal.Length Petal.Width
1          5.1         3.5          1.4         0.2
2          4.9         3.0          1.4         0.2
3          4.7         3.2          1.3         0.2
4          4.6         3.1          1.5         0.2
5          5.0         3.6          1.4         0.2

, , versicolor

  Sepal.Length Sepal.Width Petal.Length Petal.Width
1          7.0         3.2          4.7         1.4
2          6.4         3.2          4.5         1.5
3          6.9         3.1          4.9         1.5
4          5.5         2.3          4.0         1.3
5          6.5         2.8          4.6         1.5

, , virginica

  Sepal.Length Sepal.Width Petal.Length Petal.Width
1          6.3         3.3          6.0         2.5
2          5.8         2.7          5.1         1.9
3          7.1         3.0          5.9         2.1
4          6.3         2.9          5.6         1.8
5          6.5         3.0          5.8         2.2


text:
Q: DB2 SQL update using 3 tables, update 1, join with 2 more to select rows to update I'm working with 3 tables. Based on the contents of 1 or more fields in each table, I need to update 1 of the tables with constant data. My select works great to discover how many records will need to be updated, but I can't seem to get the update to work.  I co-worker, with more DB2 SQL experience, sent me code to try.  His runs without error, but doesn't get the join and 'where' conditions correct to update only the needed records - it is updating way too many records.
Here is the select that is working correctly:
select *
    from mylib.tabcp
inner join mylib.tabc c on cpactnum = c.actnum
inner join mylib.tabt t on cpactnum = t.actnum and cptagid = t.tagid
where (cpstatus = 'Active' and t.tagsts = 'P' and (c.actsts = 'A' or c.actsts = 'D'))

tabcp has these fields:  cpactnum    cpstatus   cptagid
tabc has:  actnum    actsts
tabt has:  actnum  tagid tagsts
I need to update some fields in tabcp when:  tabcp status is active, tabc status is A or D and tabt status is P
Here is the update my co-worker gave me - it runs, doesn't get any errors, but doesn't correctly select the records to update.
update tabcp
set cpstatus = 'Inactive',
    cpdelstamp = current_timestamp,
    cpdeldate = current_date,
    cpdeltime = current_time,
    cpdeluser = current_user
where cpstatus = 'Active'
and cpactnum in
 (select e.cpactnum from tabcp e
    inner join tabc c on e.cpactnum = c.actnum
    inner join tabt k on e.cpactnum = k.actnum
                     and e.cptagid = k.tagid
 where c.actsts in ('A','D') and k.tagsts = 'P')

I am too unfamiliar with DB2 SQL updating.  I've tried various changes and, thus far, I just haven't gotten the 'combination' correct.
Can anyone help me, please?
Thank you!

A: UPDATE mylib.tabcp p
set cpstatus = 'Inactive',
    cpdelstamp = current_timestamp,
    cpdeldate = current_date,
    cpdeltime = current_time,
    cpdeluser = current_user
WHERE EXISTS
(
SELECT 1
FROM mylib.tabc c, mylib.tabt t
WHERE
p.cpactnum = c.actnum
and p.cpactnum = t.actnum and p.cptagid = t.tagid
and p.cpstatus = 'Active' and t.tagsts = 'P' and c.actsts in ('A', 'D')
)

A: Please try this code
enter code here
update tp
set cpstatus = 'Inactive',
cpdelstamp = current_timestamp,
cpdeldate = current_date,
cpdeltime = current_time,
cpdeluser = CURRENT_USER
from mylib.tabcp tp
where cpstatus = 'Active'
and cpactnum in
(select e.cpactnum from tabcp e
inner join tabc c on e.cpactnum = c.actnum
inner join tabt k on e.cpactnum = k.actnum
                 and e.cptagid = k.tagid
where c.actsts in ('A','D') and k.tagsts = 'P')


text:
Q: Create global QHash variable using qt c++ I am creating a basic chat application using qt c++ in which server has to serve the multiple clients using threads, now i want to store socket descriptors and name of the respective user using QHash variable.
so i am really not understanding how to declare a global QHash variable so that each thread can update the values to that variable.
I did try storing socket descriptor into sqlite database but it did worked out. How to proceed further?

A: You can always make evertything global declaring it with the necessary visibility or make it static though it is bad practice to work with global storage accessed by the threads directly. If you really want to keep the track of sockets you can create a sort of cache where the thread could register and unregister new/complete chat session. Also, you have to think about concurecny a bit since multiple threads could register at the same moment and it breaks your code at this moment.

A: Put your hash into a class. Then read about thread safety and about QMutex.


text:
Q: 3-point counterterm in scalar QED I'm working on the 1-loop corrections to scalar QED. I'm using dimensional regularization and on-shell regularization. In trying to compute the counterterm for the 3-point graph I come across the following integral:
$$e^3\int \Big[\frac{d^4k}{(2\pi)^4}\frac{(q_1^\mu+k^\mu)}{k^2-m^2+i\epsilon}\times \frac{1}{(k-q_1)^2+i\epsilon}\times (2k^\rho+p^\rho)\times\frac{(q^2_\mu+p_\mu+k_\mu)}{(p+k)^2-m^2+i\epsilon}\Big].$$
This is associated to the graph

Using a Feynman parameter, we can simplify:
$$ = 2e^3\int \frac{d^4k}{(2\pi)^4}\int_0^1 dxdydz\delta(x+y+z-1)\frac{(q_1+k)\cdot(q_2+p+k)(2k^\rho+p^\rho)}{[(k+yp-zq)^2-\Delta+i\epsilon]^3}$$
where here we have let $\Delta = -xyp^2+(1-z)^2m^2$.  Then, as is the standard procedure, we shift $k\rightarrow k-yp+zq_1$ to make the denominator $(k^2-\Delta)^3$. The numerator gets a bit complicated under this transformation, but we should be able to simplify it in such a way that we can easily use dimensional regularization, let $d =4-\epsilon$, and expand about $\epsilon =0$ to find the divergent part.
This calculation is very similar to that done in Chapter 17.2 of Schwartz's quantum field theory where he computes the anomalous magnetic moment. However, I can't use the same techniques used there to simplify the numerator here.
Any help would be greatly appreciated. I need this to determine the 3-vertex counterterm of scalar QED. Maybe there is a shortcut to computing this that doesn't involve such a messy calculation?


text:
Q: autoreleased with no pool in place - just leaking I am currently receiving the error :
2000-01-03 06:51:27.-641 mytestapp[470:5c03
] *** __NSAutoreleaseNoPool(): Object 0x15a5a0
of class __NSArrayM >autoreleased with no pool in place - just leaking

From investigation of the other stackoverflow links, this problem seems to occur when people do not create an autorelease pool before a thread selector and drain it after.
However, I have attempted to accommodate this and still am stumped.
I have the code here on pastebin. If anyone can help it would be greatly appreciated.
Thanks

A: "create an autorelease pool before a thread selector and drain it after" What? where have you heard this?
You must have understood it wrong. You don't put an autorelease pool on the original thread -- that's useless. You are supposed to put it in the new thread, just around all the code that will execute in the thread. In your case, that means inside the block -- create it at the beginning of the body of the block, and drain it at the end of the body of the block.

A: You need an autoreleasepool in place in the main.m, else any object that attempts to recieve the autorelease message will "just leak" with no pool in place.  Unfortunately, that mutable array is probably a framework object, so your pool would do nothing to fix it.


text:
Q: SQL table structure for less structured or unpredictable data I'm new to (My)SQL and it's been difficult to find good info on best practices of table design.
I want to save sequences of moves on a chess board, say I have an array $a = ['e4 e5', 'Nf3 Nc6', ...]
Being new, my first idea is a dumb little table with 2 columns, one for the Game ID and one for the moves. The moves (array) would be serialized and stored in a string. I guess this would technically work, but reading and writing potentially huge serialized arrays from a DB - perhaps on every page load - seems suboptimal to me.
Caching the array on the user side might not be possible for various reasons and is not something I'm curious about.
I'm interested in learning how to best store data that can't be entirely predicted in it's format (e.g. the number of moves can vary from 1 to 1000).

A: Rather than storing the entire game history in a single row, why not store the game ID, the move, and the sequence number of that move.
That way you would retrieve the entire history of a given game by doing something like
SELECT *
  FROM MovesTable
 WHERE gameID = id
 ORDER BY sequence

A: In general, I would use a table in one of the following forms:

*

*GameId, MoveNumber, Move

*GameId, MoveNumber, FromSquare, ToSquare

Which one you use will depend on what you will need to query against and how the data will be presented, but I would lean toward the latter suggestion.
You can then combine this with a parent table that contains the GameId and some data about the game itself, such as dates or players.
If you're only going to consume the moves as an entire block - that is you always want the entire move chain and never will query into individual moves - you could store the string as you suggest. This has the added benefit that there is only one row of data to return, which will be very fast. The downside of course is that you will have to deserialize/parse the data once you receive it.

A: I'd do something like
Game, MoveNumber, Move
----------------------
Game1, 1, e4 e5
Game1, 2, Nf3 Nc6
...
Game2, 1, ....

A: You will need a number of tables, one for the players, one for games, one for the pieces and one for moves.
A game would have players and colours and things like date and time
A piece would tell you how it moves, is it a knight or a queen etc.
A player would have the player's name etc.
A move would have the piece, game, player, start position and end position
You would link these tables together by relationships based on id fields in each of the tables.

A: Try two tables.
First table contains information pertaining to each game. Who are the players, where and when did they play, who won, and whatever other information is pertinent to each game and makes each game unique.
Games
Game_id PK
Move_id FK
Black_name
White_name
Game_Location
Game_Date
Game_Time
Winner
The second table contains all the moves for each game. This contains all the pertinent information for each move: was a piece taken, was the other player put in check, was this a regular move or did they castle, etc.
Moves
Move_id PK
Move_number
Who_moved
Piece_moved
Square_from
Square_to
Piece_taken
Move_type
Check_YorN
Now each row in the Games table (game) is joined to many rows (moves) in the Moves table.


text:
Q: How to use Regexp in mysql queries? I have a mysql table like following
jobno | duration
----------------
1     |  1 hr
2     |  3 hrs
3     |  1 hr 30 mins
4     |  2 hrs 15 mins
5     |  1 hr 15 min
6     |  45 mins
7     |  30 min

Is it possible to select the jobs with duration less than 2 hrs ?
After spending a lot of time in google i found that there is regexp function in mysql. But is that applicable in this case?
Am new to mysql. Pls help me guys.

A: select * from TableName where duration NOT REGEXP '^([^1]|[1-9][0-9]+) hr.*'

Try this.This will work.See here
For less than 3 you can use
select * from TableName where duration  REGEXP '^([1-2] hr|[0-9]+ min).*'

http://www.sqlfiddle.com/#!2/ba4de/12/0
Similarly for 4 use [1-3] and so on.

A: Seeing your duration column format. why cant you just use like:
select * from yourTableName where duration like '1 hr%' or duration NOT like '%hr%';

or if you are looking for flexibility like below 4 hours try this:
select * from yourTableName
where duration REGEXP '^[1-3].*$' or duration not like "%hr%";

A: You can try this (without using REGEX):
select * from TableName
where (duration not like '%hr%')
      OR (duration like '1 hr%')

Result:
JOBNO   DURATION
1       1 hr
3       1 hr 30 mins
5       1 hr 15 min
6       45 mins
7       30 min

Sample result in SQL Fiddle.
Explanation:
The first condition in WHERE clause will fetch the records with duration doesn't contain the word 'hr' (which will be the minutes only). Second condition is to fetch duration starting with 1 hr, which will be the duration between 1hr-2hr.
EDIT:
To make it more flexible, you can do this:
select * from TableName
where (duration not like '%hr%')
      OR (CAST(SUBSTRING(duration,1,2) AS UNSIGNED) < 4)

Result:
JOBNO   DURATION
1       1 hr
2       3 hrs
3       1 hr 30 mins
4       2 hrs 15 mins
5       1 hr 15 min
6       45 mins
7       30 min

Sample result in SQL Fiddle.

A: Do not attempt to solve the problem in SQL, the language is not rich enough.  Instead, use Perl or PHP or some language that has a good REGEXP library.

*

*Add a new column.

*Fetch the rows, convert them in your application language, then UPDATE the new column.

*Drop the existing column -- or keep it for human readability.

A: Yes, probably. It will be painful and is really over-engineering a solution here.
The general purpose of a database is to speed up access and, in general, regular expressions are expensive. Another problem here is that there might not be a promise about how these time strings are stored. In the example that you give, you need to parse out the number value to decide if "hr" or "hrs" should be expected next.
I would suggest instead storing the durations in seconds (as a MySQL INT). You can then quickly and easily search and sort on that INT:
jobno | duration
-------------------
1     |  3600
2     |  10800
3     |  5400
4     |  8100
5     |  4500
6     |  2700
7     |  1800

The "less than two hours" query would then look like this:
SELECT `jobno` FROM `jobs` WHERE `duration` < 7200;


text:
Q: iOS 10.3.1 - Apple iPhone - Photos app shows 295 images; none found on device internal storage I am using iOS 10.3.1 on iPhone 5S.
When I connect to my Windows 10 PC using USB and view the device in Windows Explorer, I can navigate to the iPhone\Internal Storage\DCIM\ folder - which is empty (I recently moved all my other photos onto hard disk).
When I open Photos app on the iPhone, I see 295 images.
They all appear in "My Albums" in the album "iPhone".
I do not have the option to delete the image. When I tap tools I see "This photo is not editable. Do you want to duplicate it and edit a copy?" with the option to 'Duplicate and Edit'.
Is there any way to retrieve these images via Windows Explorer interface? Must I manually 'Duplicate and Edit' all 295 images in order to have a copy to backup via Windows Explorer file system?
I am trying to backup all images from the device before I reset to factory original settings and list for sale.

A: I have no explanation for how the photos came to be read-only on the device, and hidden from the internal file system, but the solution to make a backup was:
On the device, navigate to the album.
Select All images, then choose 'Duplicate to Edit' which places copies into Camera Roll.
Once the duplicates are created, any of the usual methods for backup worked.
In my case, I could plug in with USB cord to my Windows PC, and transfer using Windows Explorer by navigating to iPhone\Internal Storage\DCIM\XXXX.

A: According to the iOS Security Guide to get access to your data from the PC you need to unlock your device by entering passcode. Actual citation: "Starting in iOS 11, the user is also required to enter their passcode". I have a problem when photo entering applications see zero photos like four times of five (it appeared that sometimes I actually unblock my phone with passcode).
Any chance you unblocked your phone with TouchID and see empty DCIM folder on PC?


text:
Q: Infix to Postfix I am trying to create a program to convert an infix expression to post fix and evaluate it using a stack. The three files are below. When I run the code I get a segmentation fault. The debugger in Xcode says that it occurs between the push and the two pop calls in the middle file in the evaluate_postfix function. Can anyone help me with why this is seg faulting?
#include <stdio.h>
#include <stdlib.h>
#include "stack.h"

stack* create_stack(void)
{
    stack* newPtr = malloc(sizeof(stack));
    newPtr->size = 0;
    newPtr->stack = NULL;

    return newPtr;
}

void push(stack *s, int val)
{
    node* newPtr = (node*) malloc(sizeof(node));
    newPtr->data = val;
    newPtr->next = s->stack;
    s->stack = newPtr;
    s->size++;
}

void pop(stack *s)
{
    node* newPtr = NULL;
    node* tempPtr = NULL;

    tempPtr = s->stack;
    newPtr = tempPtr->next;
    free(tempPtr);
    s->stack = newPtr;
    s->size--;

}

int top(stack *s)
{
    int num;
    node* newPtr = NULL;
    newPtr = s->stack;
    num = newPtr->data;

    return num;
}

int isEmpty(stack *s)
{
    if(s->stack == NULL)
    {
        return 1;
    }

    else
    {
        return 0;
    }
}

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include "stack.h"
#include <string.h>

#define MAX_EQU_LEN 100

static int prec(char operator)
{
    switch (operator)
    {
        case '*':
            return 5;
        case '/':
            return 4;
        case '%':
            return 3;
        case '+':
            return 2;
        case '-':
            return 1;
        default:
            break;
    }

    return 0;
}

static int isNumeric(char* num)
{
    if(atoi(num) == 0)
    {
        return 0;
    }
    return 1;
}

char* infix_to_postfix(char* infix)
{
    int i,a=0;
    char* postfix = malloc(MAX_EQU_LEN);
    stack* s = create_stack();

    for(i=0;infix[i]!='\0';i++){

        if(!isNumeric(&((infix[i]))))
        {
            postfix[a]=infix[i];
            a++;
        }
        else if(isEmpty(s))
            push(s,infix[i]);
        else if(prec(infix[i])>prec(s->stack->data))
                push(s,infix[i]);
        else
            {
                postfix[a]=s->stack->data;
                a++;
                pop(s);
                if(!isEmpty(s)){
                    while(prec(s->stack->data)<= prec (infix[i]))
                    {
                        postfix[a]=s->stack->data;
                        a++;
                        pop(s);
                    }
                }
                else
                    push(s,infix[i]);
            }
        }
    return postfix;

}

int evaluate_postfix(char* postfix) {

    int i,result = 0;
    int right = 0, left = 0;
    char* token = NULL;
    stack* s = create_stack();
    s->size = strlen(postfix);
    node* tempPtr = NULL;
    for(i = 0; i < s->size ; i++)
    {

        token = strtok(postfix, " ");
        if(isNumeric(token) == 1)
        {

            atoi(token);
            push(s, *token);
        }
        else
        {
            left = tempPtr->data;
            pop(s);
            right = tempPtr->data;
            pop(s);
            switch(*token)
            {
                case '+':
                    result = left + right;
                    break;
                case '-':
                    result = left - right;
                    break;
                case '*':
                    result = left * right;
                    break;
                case '/':
                    result = left / right;
                    break;
                case '%':
                    result = left % right;
                    break;

            }
            push(s, result);
        }
        strtok(NULL, " ");
    }
    return result;

}
#include <stdio.h>
#include <string.h>
#include "calculator.h"

#define BUFFERSIZE 100

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

    char buffer[BUFFERSIZE];
    if (argc != 2) {
        printf("correct ussage: %s <input file>\n", argv[0]);
        return 1;
    }

    FILE* fp = fopen(argv[0], "r");

    if(fp == NULL) {
        printf("unable to open file: %s\n", argv[1]);
        return 1;
    }

    while(fgets(buffer, BUFFERSIZE, fp)) {
        if (buffer[strlen(buffer)-1] == '\n') {
            buffer[strlen(buffer)-1] = '\0';
        }
        char *postfix = infix_to_postfix(buffer);
        int result = evaluate_postfix(postfix);
        printf("%s = %d\n", buffer, result);
    }

    return 0;
}

A: Each call to strtok() that doesn't contain a NULL pointer as its first argument resets the internal pointer of the strtok() function to the beginning of the string.
At the beginning of the loop in your int evaluate_postfix(char* postfix); function, you call
token = strtok(postfix, " ");

Which means that at the beginning of the loop, token ALWAYS pointers to the first non-space character at the beginning of postfix. So each loop it would see an operator, and try to pop() two values from the stack. But your stack would quickly deplete, and the stack will begin to point to garbage data (s->size < 0).
token = strtok(postfix, " ");

for(i = 0; i < s->size ; i++)
  {
  ....
  token = strtok(NULL, " ");
 }

Should fix your issue.