Q:

Find a string in a 2D array and then go to corresponding column

So I'm converting a CSV into an Array. The CSV has the first column which consists of titles the describe what is in that column. In my case: product ID | product name | product cost | quantity
I'm trying to go through the array, find the string item1 and then go to that item's quantity, which in the same line, but in a different column.
For example:
product ID | product name | product cost | quantity
-----001----- | -----item1----- | -----5.99----- | -----3-----
-----002----- | -----item2----- | -----2.99----- | -----5-----
So I want to go this array, find the string item1 in line index 1, then go to column index 3 to extract the quantity into a variable. Then I want to store into a variable to ultimately print out there are only 3 item1's left or something of the sort.
This is what I got so far:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

public class test2 {

    public static List<List<String>> csvToArray() {
        String fileName = "c:\\temp\\test.csv";
        File file = new File(fileName);

        // this gives you a 2-dimensional array of strings
        List<List<String>> lines = new ArrayList<>();
        Scanner inputStream;

        try {
            inputStream = new Scanner(file);

            while (inputStream.hasNext()) {
                String line = inputStream.next();
                String[] values = line.split(",");
                // this adds the currently parsed line to the 2-dimensional string array
                lines.add(Arrays.asList(values));
            }

            inputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        return lines;
    }

    public static void printArray(List<List<String>> lines){
        int lineNo = 1;
        for (List<String> line : lines) {
            int columnNo = 1;
            for (String value : line) {
                System.out.println("Line " + lineNo + " Column " + columnNo + ": " + value);
                columnNo++;
            }
            lineNo++;
        }
    }

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

As you can see, in the method printArray I'm just printing out the Array to get a reference of where I am, but once I try to add if's then Im getting lost.
Any help would be great :)

A:

Determine the indexes of the clumns of interest and iterate through the lines, printing and feeding a variable for future use along the way.
Creating a class to represent a csv line seems to be over-engineering here but depends on the requirements, of course.
Code is not tested.
/*
   Preprocessing:
   Determine column indexes of product name and quantity.
   Use the informstion available.

   Simple case: column indices are known beforehand.

   This code scans the csv header lines for given strings.
*/
final String s_HEADER_PRODUCT   = "product name";
final String s_HEADER_QUANTITY  = "quantity";

HashMap<String, int> quantities = new HashMap<String, int>();

int idxProduct   = -1;
int idxQuantity  = -1;

List<String> headers = lines[0];
int columnNo = 0;
for ( columnNo = 0; columnNo < headers.size(); columnNo++ ) {
    if ((idxProduct < 0)  && headers[columnNo].equals( s_HEADER_PRODUCT )) { idxProduct = columnNo; }
    if ((idxQuantity < 0) && headers[columnNo].equals( s_HEADER_QUANTITY )) { idxQuantity = columnNo; }
    if ((idxProduct >= 0) && (idxQuantity >= 0)) {
        break;
    }
}

/*
   Print out.
   After the loop, 'quantities' will hold a map of product names onto quantities.

   Assumptions:
      - Quantities are integer values.
      - Product names are unique within the file.
 */
lineNo = 0;
for (List<String> line : lines) {
    if (lineNo > 0) { // skip header line
        System.out.println("Item '" + line.get(idxProduct) + "': " + line.get(idxQuantity) + " specimens left.");
        quantities.put ( line.get(idxProduct), Integer.parseInt ( line.get(idxQuantity) );
    }
    lineNo++;
}


Q:

Converting empty string to $null back to the same variable

We have a few imports via PowerShell in to Active Directory that have a couple fields that come across as an empty string from the datasource, but need to be set as $null within Active Directory.
Since there are quite a few of these fields, I attempted to create a function that will convert an empty string to $null.
The trouble is that if I set the variable back to itself, it remains an empty string. If I set it as a new variable, it works fine.
function Get-ValueOrNull
{
    param(
        [Parameter(Mandatory=$true)]
        [AllowEmptyString()]
        [string]$Value
    )

    if ([string]::IsNullOrEmpty($Value))
    {
        return $null
    }

    return [string]$Value
}

function Test-Function
{
    param(
        [Parameter(Mandatory=$true)]
        [AllowEmptyString()]
        [string]$TestValue
    )
    $TestValue = Get-ValueOrNull -Value $TestValue
    $TestValue2 = Get-ValueOrNull -Value $TestValue

    Write-Host "TestValue: $($TestValue -eq $null)"
    Write-Host "TestValue2: $($TestValue2 -eq $null)"
}

Test-Function -TestValue ""

Here the output is
PS C:\> .\Test-Function.ps1
TestValue: False
TestValue2: True

This is clearly something I'm not understanding about Types in PowerShell function parameters. I can change the [string]$TestValue to $TestValue, and it will work.
function Test-Function
{
    param(
        [Parameter(Mandatory=$true)]
        [AllowEmptyString()]
        $TestValue
    )
    ...
}
...

Output:
PS C:\> .\Test-Function.ps1
TestValue: True
TestValue2: True

The reason I'd like to preserve the [string] parameter type is to enforce that it should be a string or an empty string. Can someone explain what is going on here?

A:

Once you've casted the variable as opposed to the value being assigned you are strictly typing that variable.
This is easier to see with an [int] because basically anything can be casted to a [string] successfully:
$v = [int]'5'
$v.GetType()  # int

$v = 'hello'
$v.GetType()  # string

[int]$v = '5'
$v.GetType()  # int

$v = 'hello'
# Exception:
# Cannot convert value "hello" to type "System.Int32". Error: "Input string was not in a correct format."

When you type a parameter, the variable that contains the parameter is the same way; you can reassign it, but the right side must be assignable / castabale / convertible to the left side's type.
A $null cast as [string] is an empty string:
([string]$null) -eq ([string]::Empty)  # True

You can still strongly type your parameter, if you use a different intermediate variable in the function that isn't, as you demonstrated with $TestValue2.


Q:

Squash Git Mirror Commits

I want to work on my repo in private using GitLab but keep a public copy of the master branch on GitHub for visibility and accessibility purposes. Is it possible to 'automate' the mirroring of the master branch of both the GitHub and GitLab remotes, but retain the commit history in the GitLab whilst squashing commits down to a single commit with the GitHub one (without having to remember to manually do this each time)?
This might be a bit of a far-fetched request, but git continues to amaze me with how powerful and flexible it is!

A:

Unless you are talking about a GitLab instance you are managing, you would still need a webhook that you run on your own server, and which is called by GitLab.com on every push.
See for example lowzj/gitlab-mirror-webhook (to be adapted in order to do what you want: a git merge --squash into a dedicated branch, and a git push to GitHub)
For a simple mirror (meaning without the squash step), GitLab proposes a mirror feature setting. This is easier than setting up a webhook... but less flexible.


Q:

PHP Undefined index in foreach loop makes no sense

This error makes no sense. Here is the code block and my explanation below.

<?php foreach($rows as $value): ?>
                              <?php   echo $value['authorname'] . "
\n";?>
                              <?php   echo $value['title'] . "
\n";?>
                              <?php   echo $value['rating'] . "
\n";?>
                              <?php   echo $value['imagelocation'] . "
\n";?>

                                            <input id="rate1" value="<?php echo $value['rating'];?>" type="number" class="rating" data-max="5" data-min="0"  data-size="sm" data-show-clear="false" readOnly="readOnly">
                                            <a href="<?php echo $value['sellerssite'];?>" target="#"><img class="img-responsive wow fadeInLeftBig animated" data-wow-duration="1.5s" src=<?php echo $value['$imagelocation'];?> alt=<?php echo $value['$authorname'];?>>

                                            <a href="<?php echo $value['sellerssite'];?>" class="btn btn-success" target="_blank">Buy this book

Author: <?php echo $value['$authorname'];?> - <?php echo $value['$title'];?>

                                                    <?php echo $value['$review'];?>

                        <?php endforeach; ?>

The echo statements right after the start of the foreach loop prints out each variable fine. It isn't until we get down to the html that there are issues.
This code feeds an array of data from a DB then builds blocks of html code depending on the amount of data. In this case, I am pulling 8 records so this loop creates 8 copies of this code block. The thing that is frustrating is the variable "$rating" injects in all 8 blocks but none of the other variables do even though they print correctly on the page in the echo statements.
Maybe it is the data in the variable? For example as the code is parsed the first variable evaluated is $rating and works. The next one is the src property in the img tag $imagelocation and has an actual value of img\book_covers\TrueConviction.jpg
Are _ and . special characters and causing the issue? My return values would have _ . \ and spaces.
Thanks for any help.

A:

I was right that it was the data IN the variables. The answer was urldecode. This solved my problems. I did this to all my variables.

<?php   $cleanauthorname = urldecode($value['authorname']);?>

Thanks for the help everyone.


Q:

Subordinate clause with two verbs

He suggested that tomorrow we find something to do together.

How to say this?

Er schlug vor, dass wir morgen finden, etwas zusammen zu tun.

or

Er schlug vor, dass wir morgen etwas zusammen zu tun finden.

A:

I would recommend using

"Er schlug vor, dass wir morgen etwas zusammen unternehmen (werden)."

or

"Er schlug vor, dass wir morgen etwas finden, was wir zusammen machen (können)."

This is not a 1:1 translation, but "unternehmen" can be used here as is does not have to be explicitely planned - e.g. "Lass uns etwas unternehmen" is used like "Let's do something".
If you want to have a 1:1 translation, it would be:

"Er schlug vor, dass wir morgen etwas finden, was wir zusammen machen."

Personally, i would not say it like that..
Edit: Integrated Alomvar's comment. Thank you Alomvar!


Q:

Git commit hook for when editor closed

I have implemented a commit hook to check the commit message and abort the commit if the message isn't formatted correctly. I've done this with the commit-msg hook.
However, this will only work if you commit with the -m flag. If you omit that flag (because you want to use your editor to add the message), then the commit hook will fail (no message).
From what I have read, both the pre-commit and commit-msg hook are fired before the editor is opened. Is there a way to do something similar that waits for the editor to be closed?

A:

Actually, the commit-msg hook is fired once the message is ready (so, after the user closes the editor), this hook is getting a path to a file with the message value.
From the docs:

The commit-msg hook takes one parameter, which again is the path to a temporary file that contains the commit message written by the developer.


Q:

Code returns nothing

The following program was made according to the book 'Head First C'. It is supposed to be able to find and return music tracks containing a search-word, but it returns nothing. Oh, and I tried to make a 'code' space - indented it by four, but forgive me if it doesn't work.
#include <stdio.h>
#include <string.h>

char tracks[][80] = {
      "I left my heart in Harvard Med School",
      "Newark, Newark - a wonderful town",
      "Dancing with a Dork",
      "From here to maternity",
      "The girl from Iwo Jima",
};

void find_track(char search_for[])
{

   int i;

    for (i = 0; i < 5; i++) {
        if (strstr(tracks[i], search_for))
            printf("Match found.Track %i : '%s'\n", i, tracks[i])
  }
}

int main()
{
    char search_for[80];
    printf("Search for : ");
    fgets(search_for, 80, stdin);
    find_track(search_for);
    return 0;
}

A:

You have 2 typos that will keep this code from compiling:

an extra comma after Jima in the array;
a missing semicolon at the end of the printf statement

If you did some printf debugging, you would see that strstr is returning NULL everytime, so a match is never found.
printf("%s", strstr( tracks[i], search_for ) );

Why is this? The input from stdin is not being terminated properly. You need to press ctrl+d (= EOF) after typing your search word.
In fact, you need to press it twice in order to end input and flush the buffer; then it runs as intended. Try it out. Example (it's case sensitive):
Iwo ctrl+dctrl+d


Q:

Searching for an element in list of lists

I am trying to search for an element in a list of lists, and return the second element of that list.
I am new to programming and I want to search for a word in a list of lists that look like this:
list = [['592', 'Frillish', 'Water', 'Ghost', '335', '55', '40', '50', '65', '85', '40', '5', 'False']
['593', 'Jellicent', 'Water', 'Ghost', '480', '100', '60', '70', '85', '105', '60', '5', 'False']
['594', 'Alomomola', 'Water', '', '470', '165', '75', '80', '40', '45', '65', '5', 'False']
['595', 'Joltik', 'Bug', 'Electric', '319', '50', '47', '50', '57', '50', '65', '5', 'False']]

What I have now is something like :
def search(word):
    result_of_search = []
    for i in list:
        if word in i:
            result_of_search.append.......

This is the part where i get stuck. I want to return the second element in the list , if the word exist in the list.

A:

This is how you should do:
[x[1] for x in lst if word in x]

Note that I have renamed your list to lst as list is a built-in.
In a function:
def search(word):
    return [x[1] for x in lst if word in x]

Read about list comprehensions.


Q:

How to set data to QComboBox using QAbstractTableModel (Model/View)?

I wish to be able to set the itemData of a combobox when populated using a QAbstractTableModel. However, I can only return one string from the model's data method.
Usually, when not using a model, this can be performed like so:
# Set text and data
combobox.addItem('Some text', 'some item data')

# Retrieve data from selected
item_data = combobox.itemData(combobox.currentIndex())

How can this be done, but using QAbstractTableModel?

I have a combobox, which I set a model to:
model = ProjectTableModel(projects)
combobox.setModel(model)

My model:
class ProjectTableModel(QtCore.QAbstractTableModel):

    def __init__(self, projects=[], parent=None):
        QtCore.QAbstractTableModel.__init__(self, parent)
        self._projects = projects

    def rowCount(self, parent):
        return len(self._projects)

    def columnCount(self, parent):
        return 2

    def data(self, index, role):
        row = index.row()
        column = index.column()

        if role == QtCore.Qt.DisplayRole and column == 0:
            project = self._projects[row]
            name = project.name()
            id = project.id()  # <----- how to add this as itemData?
            return name

A:

A QComboBox always uses a model to store its data. If you don't set a model yourself, it will create its own QStandardItemModel. Methods such as addItem and itemData simply store and retrieve values using whatever underlying model has been set. By default, the combo-box uses the Qt.UserRole to store item-data in the model. So your model just needs to do something like this:
def data(self, index, role):
    row = index.row()
    column = index.column()

    if role == QtCore.Qt.DisplayRole and column == 0:
        project = self._projects[row]
        name = project.name()
        return name
    elif role == QtCore.Qt.UserRole and column == 0:
        project = self._projects[row]
        id = project.id()
        return id

def setData(self, index, value, role):
    row = index.row()
    column = index.column()

    if role == QtCore.Qt.UserData and column == 0:
        project = self._projects[row]
        project.setId(value) # or whatever


Q:

Why does my credentials dialog freeze?

Everytime I try to login into some network resource, the windows credentials screen freezes (for example, when connecting to a Terminal Server via RDP or trying to access network folders). Already saved credentials are still working (credentials that Windows had saved before the problem started).
I already disabled the smart card reader, but it didn't solve the problem. All Windows updates have been installed.

A:

I had to uninstall de Dell Data Protection Security Tools. No more freezes since then.


Q:

Nightmare java leak... with loop and jdbc

When I run the following code in the profiler, I get a char[] and byte[] that build up until the program crashes due to a java heap out of memory exception.  Can someone tell me why?  Perhaps I am doing something fundamentally wrong.
package testleak;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import javax.swing.Timer;

    public class TestLeak
    {
        static String DB_USERNAME = "userName";
        static String DB_SUBSCRIPTION_EXPIRATION = "subscriptionExpiration";
        static String DB_REMOTE_ACCESS_ENABLED = "remoteAccessEnabled";
        static String DB_LOCAL_USERNAME = "root";
        static String DB_LOCAL_PASS = "root";
        public static void main(String[] args)
        {
            Timer timer = new Timer(2000, new ActionListener()
            {
                @Override
                public void actionPerformed(ActionEvent evt)
                {
                    TestLeak tester = new TestLeak();
                    try
                    {
                       tester.go();
                    }
                    catch (NumberFormatException n)
                    {
                    }
                    tester = null;
                }
            });
            timer.start();
            while (true)
            {
                //keep the program from ending...
            }

        }
        private void go() throws NumberFormatException
        {
            ResultSet results = null;
            Connection conn = null;
            Properties connectionProps = new Properties();
            try
            {
                connectionProps.put("user", "root");
                connectionProps.put("password", "root");
                conn = DriverManager.getConnection("jdbc:mysql://localhost:8889/myDataBase",
                        connectionProps);
                connectionProps = null;
                try
                {
                    String rawQuery = new String("SELECT " + TestLeak.DB_USERNAME + ", "
                            + TestLeak.DB_REMOTE_ACCESS_ENABLED
                            + ", " + TestLeak.DB_SUBSCRIPTION_EXPIRATION + " FROM myTable");
                    Statement statement = conn.createStatement();
                    try
                    {
                        statement.executeQuery(rawQuery);
                        results = statement.getResultSet();
                        rawQuery = null;
                        try
                        {
                            while (results.next())
                            {
                                String auth = new String(results.getString(TestLeak.DB_REMOTE_ACCESS_ENABLED));
                                if (auth.equals("1"))
                                {
                                    Long subExpires = Long.valueOf(results.getString(TestLeak.DB_SUBSCRIPTION_EXPIRATION));
                                    if (subExpires > System.currentTimeMillis())
                                    {
                                        System.out.println(results.getString(TestLeak.DB_USERNAME));
                                        System.out.println();
                                    }
                                    subExpires = null;
                                }
                                auth = null;
                            }
                        }
                        finally
                        {
                            results.close();
                        }
                    }
                    finally
                    {
                        statement.close();
                    }
                }
                finally
                {
                    conn.close();
                }
            }
            catch (SQLException e)
            {
                System.out.println(e.getMessage());
            }
        }
    }

I think I am releasing everything, but something must be preventing all objects from being released.  Why is it that all objects are not eligible for garbage collection when the go() method ends?  Every time I envoke garbage collection in the profiler I get another surviving generation.
Thanks.

A:

I would change this:
                        statement.executeQuery(rawQuery);
                        results = statement.getResultSet();

to this:
                        results = statement.executeQuery(rawQuery);

The latter is certainly the API-approved way to do this, and while I can't say for certain that the former is a problem, it certainly seems like it could create two separate result-sets, of which you only close one.

A:

Unfortunately you don't specify some details about the problem, for example, how big is the result set (# of rows), and how long does it take to run into out of memory exception.
I don't have access right now to the mysql driver you have, but I ran your same code with an H2 database, with 1000 rows in the myTable. The heap size of the JVM was stable during the test, without any memory leak. You can see that in the attached screenshot.
The heap size increased a little, then returned to the original position after the GC, up again, down again, on a very stable pattern.
You can run your app and then run the Jvisualvm and connect to your app to see, for example, if the number of results from the database is too large to fit into the existing memory. Which is my guess. In this case the blue line will rapidly go over the max memory.
If that's the case you run your application with -Xmx setting to increase the memory size.
If indeed there is a memory leak it is not in your code, but in the driver you're using. To confirm a memory leak, the blue line in the chart below will go up (allocating memory), the  GC will run (freeing up memory) but the blue line never gets back to it's original position  leaving behind some objects.


Q:

hidden images when scroll uitableview in iphone

I am doing this code
but when i scroll the uitableview image will disappear what i want i want when image once load then it will not disapper.
Please tell me what can i do in this.
__block NSData *image = nil;
dispatch_queue_t imageQueue = dispatch_queue_create("queueForCellImage", NULL);
dispatch_async(imageQueue, ^{
    NSString *thumbnailURL = @"http://www.bizfy.com/demo/biscoot/a1.png";
    image = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:thumbnailURL]];
    dispatch_async(dispatch_get_main_queue(), ^{
        cell.imageView.image = [UIImage imageWithData:image];
        [cell setNeedsLayout];
    });
});
dispatch_release(imageQueue);

A:

You should store the images in an NSArray, NSDictionary or even in the file system. Instead of only setting cell.imageView, try to store in a NSMutableArray or save to the disk, and in the next time cellForRowAtIndexPath is called, you access the image where you stored it.
Some code with the NSMutableDictionary solution, assuming you are using ARC (try to understand):
In your interface file, you declare a NSMutableDictionary *dictionaryImages;
In your implementation file, initiate it in viewDidLoad method: dictionaryImages = [NSMutableDictionaryImages dictionary];
Now, where you download your images, you also should insert the image in your dictionary (I'm not posting all your code, just the relevant parts from that piece)
NSString *thumbnailURL = @"http://www.bizfy.com/demo/biscoot/a1.png";
UIImage *imageForDictionary = [UIImage imageWithData:image];
[dictionaryImages setObject:imageForDictionary forKey:thumbnailURL];

And then, when cellForRowAtIndexPath is called, you associate it to the image (of course, if you have access to the thumbnailURL):
NSString *thumbnailURL = **get it from somewhere**;
UIImage *imageFromDictionary = [dictionaryImages objectForKey:thumbnailURL];
cell.imageView.image = imageFromDictionary;


Q:

Programming & Software Development News / Newsletters

I currently subscribe to MSDN Flash and Red Gate's developer newsletter, which is great. I'd like to find more sources. Where/Who else sends or posts news or articles about software development?

A:

http://statuscode.org/
http://www.hackernewsletter.com/

For more specific topics:

http://html5weekly.com/
http://javascriptweekly.com/
http://devopsweekly.com/

A:

CodeProject
has a nice weekly newsletter that features articles on various programming-related topics. Some are presentations of code submitted by contributors, while others discuss new developments in the software industry.

A:

Everyone has his/her own favorite sites, here are my favorite sites:

https://news.ycombinator.com/
http://www.gartner.com/newsroom/archive/
http://www.codinghorror.com/blog/
http://www.reddit.com/r/programming
http://mashable.com/apps-software/
http://www.drdobbs.com/
http://www.infoworld.com/news
http://slashdot.org/


Q:

How do I interpolate a field when updating documents in MongoDB?

I have a collection that looks like this:
{
    "_id" : ObjectId("5e5777b74db43342073051e0"),
    "a" : "b"
}
{
    "a" : "c",
    "_id" : ObjectId("5e5777f24db43342073051e4")
}

And I want to copy the value of each document’s a into a new array field so I end up with this:
{
    "_id" : ObjectId("5e5777b74db43342073051e0"),
    "a" : "b",
    "d": ["b"]
}
{
    "_id" : ObjectId("5e5777f24db43342073051e4"),
    "a" : "c",
    "d": ["c"]
}

I tried this command at the shell:
db.getCollection("C").updateMany({}, {
    $set: {
        "d.0": "$a"
    }
});

But that gave me:
{
    "_id" : ObjectId("5e5777b74db43342073051e0"),
    "a" : "b",
    "d" : {
        "0" : "$a"
    }
}
{
    "_id" : ObjectId("5e5777f24db43342073051e4"),
    "a" : "c",
    "d" : {
        "0" : "$a"
    }
}

$$a gave me the same result. How do I write this operation?

A:

In Mongo 4.2 the <update> document can also be an aggregation pipeline. Try this one:
db.getCollection("C").updateMany(
   {},
   [{
      $set: {
         "d": ["$a"]
      }
   }]
)


Q:

exit(0) is not terminating the program execution in my java code. Why?

public class TicTacToe{
    public static void main(String[] args){
        System.out.println("X starts the game");
        Scanner sc = new Scanner(System.in);
        char a[][] = new char[3][3];
        int n=0;
        int i = 0;
        int j = 0;
        while(n<9){
                System.out.println("Enter the coordinates but not" +i +" " +j);
                int x = sc.nextInt();
                int y = sc.nextInt();
                System.out.println("Enter X");
                a[x][y]=sc.next().charAt(0);
                n++;
                if(n>3){
                    if(a[0][0]=='X' && a[0][1]== 'X' && a[0][2]=='X'){
                        System.out.println("Congrats! X won");
                        exit(0);
                    }
                    else if(a[0][0]=='X' && a[1][0]== 'X' && a[2][0]=='X'){
                        System.out.println("Congrats! X won");
                        exit(0);
                    }
                    else if(a[1][0]=='X' && a[1][1]== 'X' && a[1][2]=='X'){
                        System.out.println("Congrats! X won");
                        exit(0);
                    }
                    else if(a[0][1]=='X' && a[1][1]== 'X' && a[2][1]=='X'){
                        System.out.println("Congrats! X won");
                        exit(0);
                    }
                    else if(a[2][0]=='X' && a[2][1]== 'X' && a[2][2]=='X'){
                        System.out.println("Congrats! X won");
                        exit(0);
                    }
                    else if(a[0][2]=='X' && a[1][2]== 'X' && a[2][2]=='X'){
                        System.out.println("Congrats! X won");
                        exit(0);
                    }
                    else if(a[0][0]=='X' && a[1][1]== 'X' && a[2][2]=='X'){
                        System.out.println("Congrats! X won");
                        exit(0);
                    }
                    else if(a[0][2]=='X' && a[1][1]== 'X' && a[2][0]=='X'){
                        System.out.println("Congrats! X won");
                        exit(0);
                    }
                }
                System.out.println("Enter the coordinates but not" +x +" " +y);
                i = sc.nextInt();
                j = sc.nextInt();
                System.out.println("Enter O");
                a[i][j]=sc.next().charAt(0);
                n++;
                if(n>3){
                    if(a[0][0]=='O' && a[0][1]== 'O' && a[0][2]=='O'){
                        System.out.println("Congrats! O won");
                        exit(0);
                    }
                    else if(a[0][0]=='O' && a[1][0]== 'O' && a[2][0]=='O'){
                        System.out.println("Congrats! O won");
                        exit(0);
                    }
                    else if(a[1][0]=='O' && a[1][1]== 'O' && a[1][2]=='O'){
                        System.out.println("Congrats! O won");
                        exit(0);
                    }
                    else if(a[0][1]=='O' && a[1][1]== 'O' && a[2][1]=='O'){
                        System.out.println("Congrats! O won");
                        exit(0);
                    }
                    else if(a[2][0]=='O' && a[2][1]== 'O' && a[2][2]=='O'){
                        System.out.println("Congrats! O won");
                        exit(0);
                    }
                    else if(a[0][2]=='O' && a[1][2]== 'O' && a[2][2]=='O'){
                        System.out.println("Congrats! O won");
                        exit(0);
                    }
                    else if(a[0][0]=='O' && a[1][1]== 'O' && a[2][2]=='O'){
                        System.out.println("Congrats! O won");
                        exit(0);
                    }
                    else if(a[0][2]=='O' && a[1][1]== 'O' && a[2][0]=='O'){
                        System.out.println("Congrats! O won");
                        exit(0);
                    }
                }
        }
        sc.close();
    }

    private static void exit(int i) {
        // TODO Auto-generated method stub

    }
}

I have written a code that implements Tic Tac Toe (with baby-steps). The exit(0) is not actually terminating the program execution once X or O wins the game. The program is still asking for the next input. How to terminate the code at that instant ?

A:

Your exit(0) is calling an empty method. Replace it by this:
private static void exit(int i) {
    System.exit(i);
}


Q:

Use self as parameter in a singleton

I have the following method-header in a singleton:
-(int) reconnectToServerForClass:(id)myClass

The parameter myClass is always the self-object of the calling class. Different ViewControllers in my project call this method so my question is this:
Is it possible to access myClass.view or what can I do to achieve that?

my intention is that I want to show a progress-hud for every ViewController that calls the method:
MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:myClass.view animated:YES];

Isn't there the need for casting myClass before I can access the view-property?

A:

If I understand correctly you can do the following:
-(int) reconnectToServerForClass:(UIViewController *)myClass
{
    //myClass.view
}

or inside the method
-(int) reconnectToServerForClass:(id)myClass
{
    if([myClass isKindOfClass:[UIViewController class]])
    {
        UIViewController *viewController = myClass; //edit as suggested by Peter Segerblom
        //viewController.view
    }
}

Which ever option you choose is that it will depend on how you use it and how you want to manage or limit the callers, in option 1 the parameter must be a sub class of UIViewController and the same for option 2 but the difference is that you can pass in anything but if the type is not UIViewController it will just do nothing.
Disclaimer: This code is not tested and typed from memory, so it might not compile, let me know if you come across issues and I will edit answer.


Q:

A word/phrase for “ not wanting to draw attention”

For example someone is looking to circumvent contacting the local club board by going to the head office to remove club membership as to not draw attention, in other words just getting it removed to not be hassled by the local club members for example or reduce the possibility for peace’s sake.
“not wanting to draw attention” was what I was thinking but I think there’s something  more eloquent/smarter sounding.

A:

[Wanting] to keep a low profile is a common expression for this.

keep a low profile

to avoid attracting attention to yourself:

He's been in a little trouble recently so he's trying to keep a low profile.

[Cambridge Dictionary]
There is also to keep your head down, which carries the sense of avoiding (a real threat of) trouble:

keep your head down

to try to avoid trouble or involvement in a difficult or dangerous situation by behaving in a quiet way, so that people will not notice
you

After unity, he had little time for Christian Democrats who had kept their heads down under the old regime.

[Collins CoBuild Dictionary]
Any clandestine approach to an operation could be said to be
backstairs ('backdoor' usually implies dodginess)

backstairs [adjective]

involving intrigue or scandal; secret

[Collins
or a sub-rosa activity

sub-rosa [adjective]

secretive, private

sub rosa [adverb]

in confidence: secretly

[Merriam-Webster]
And there is always the very safe option low-key:

low-key [adjective]

not elaborate, showy, or intensive; modest or restrained. [discreet]

their wedding was a very quiet, low-key affair

[Lexico]


Q:

How to load and repeat-x an image with php gd?

Suppose i have an image with width 1px and height 40px.
I want to load it with lets say imagecreatefrompng and want to x-repeat it, just like css repeat-x.
Is this possible with PHP GD?

A:

You have to specify width of output image, I have chosen 1024 to demonstrate:
$srcfile = 'bg.jpg';
$outfile = 'background.jpg';
list($src_w,$src_h,$src_type) = getimagesize($srcfile);

$out_w = 1024;
$out_h = $src_h;

$src = imagecreatefromjpeg($srcfile);
$out = imagecreatetruecolor($out_w, $out_h);

$curr_x = 0;
while($curr_x < $out_w){
    imagecopy($out, $src, $curr_x, 0, 0, 0, $src_w, $src_h);
    $curr_x += $src_w;
}

imagejpeg($out, $outfile, 100);
imagedestroy($src);
imagedestroy($out);


Q:

Названия ягод

Всякие земляники, голубики и черники — это понятно. Но вот откуда взялась малина (от слова "малый"?), брусника и клюква?

A:

МАЛИНА. Существует несколько объяснений этимологии этого слова. Так, допускается
образование его с пом. суф. -ин-а (как рябина) от и.-е. корня mel- > мал- со знач. цвета, окраски. Ему родственны: лтш. melns «черный»; лит. melsvas «синеватый»; лат. mulleus «красноватый». Другие полагают, что слово малина, возможно, образовано с суф. -ин-а от прил. малый «небольшой», поскольку ягода малины состоит из «малых» частей. Третьи
считают, что соврем. малина развилось из древн molina «малина», образованного от и.-е. mol-/mor-, и родственно лат. morum «ежевика», «тутовая ягода». (Цыганенко)
БРУСНИКА. Связано с брус, русск.-цслав. (о)брусити "гладить, точить", ст.-слав. събрысати, потому что спелые ягоды легко срываются. (Фасмер)
КЛЮКВА.  Некоторые исследователи возводят это слово к звукоподражанию клюк (ср. клюкать) -- от звука, издаваемого выжимаемыми ягодами. Родство с клюкать "шуметь"  допускает и другие исследователи, однако при этом видят в основе стар. название журавля; ср. журавлиха "клюква" (белор. журавіны "клюква"). Другие считают исходным знач. "болотная ягода" и сравнивают с ключевина "болото". (Фасмер)


Q:

Symfony2: deleted property still used in query

I deleted a property (teaser) from an enitiy (sale).
I used the CLi to update the database & entites:
$ php app/console doctrine:schema:update --complete --force
$ php app/console doctrine:generate:entities Our --no-backup
$ php app/console doctrine:cache:clear-metadata
$ php app/console doctrine:cache:clear-result

And i cleared the cache:
$ php app/console cache:clear --no-optional-warmers --no-warmup

Now i have a query created by query builder:
$qb = $this->createQueryBuilder('s');
$q = $qb
    ->select('s.id')
    ->leftJoin('s.bills','b')
    ->where('b.paid = true')
    ->getQuery()
    ->getResult();

This throws an error becuas eit generates a select statement that includes the old property:
Column not found: 1054 Unknown column 's0_.teaser' in 'field list'

I tried to understand how Doctrine executes the query but failed to find the source of the problem.
Does anyone have any clues?
UPDATE: I took the DQL from the query, generated by the querybuilder and then used that to create a new Query. Same Error. Then i changed one word in the DQL from uppercae to lowercase (LEFT is now Left) and that one executed just fine.
$q = $this->getEntityManager()
->createQuery('SELECT s,b FROM Our\BuyBundle\Entity\Sale s Left JOIN s.bills b WHERE s.id IN (:randomIds)')
->setParameter('randomIds', $allSaleIds);

So it seems the DQL Statement is cached somewhere, Using the DQL as a hash to get the corresponding SQL Statement.
I still can't quite figure out where and how to clear that cached Information. Especially given the fact that i deleted all content in the app/cache folder as well.
UPDATE2: Found the Solution. Had to clear the APC Cache manually since the console can't do that.
So the Solution would be:
$ php app/console doctrine:cache:clear-query

And if that doesn't work, clear your APC Cache.

A:

My Problem was the APC Cache.
I could not clear the query-cache in CLI (app/console) since the console can't (or is not allowed to) clear the APC Cache.
So i had to clear the APC Cache manually.
Solution is:
$ php app/console doctrine:cache:clear-result

And if that doesn't work, clear the APC Cache (or whatever cache you use) manually.


Q:

Part of my object disappears In camera view

Hi newbie in blender here.
does anybody know how to solve the problem?
Outside view show the whole 3d model, but on camera and rendered it comes out like this:

A:

You need to increase your camera's clipping end value:


Q:

How to sum over duplicates?

I have a list of the form:
{{1, 0, 1}, {2, 1, 2}, {1, 0, 3}, {2, 4, 2}, {2, 1, -1}, {1, 0 ,0}}

that I would like to sort such that I calculate the sum over the third column whenever the first two columns are equal.  I.e. in this case the output would be
{{1, 0, 1 + 3 + 0}, {2, 1, 2 + (-1)}, {2, 4, 2}}

or
 {{1, 0, 4},{2, 1, 1},{2, 4, 2}}

Is there an elegant way to do this?

A:

Flatten[{#[[1, {1, 2}]], Total[#[[All, 3]]]}] & /@ GatherBy[yourList, #[[{1, 2}]] &]

(*  {{1, 0, 4}, {2, 1, 1}, {2, 4, 2}} *)

How this works:
GatherBy[yourList, #[[{1, 2}]] &]

this gathers elements of your list based on matching the first and second elements in each sub-list (#[[{1, 2}]] &)
Once common elements are gathered (collected) you can total/sum all the third elements by mapping them onto Total

A:

 lists = {{1, 0, 1}, {2, 1, 2}, {1, 0, 3}, {2, 4, 2}, {2, 1, -1}, {1, 0, 0}}

Reap/Sow:
 Reap[Sow[#[[3]], {#[[{1, 2}]]}] & /@ lists, _,  Append[#1, Total@#2] &][[2]]

ReplaceRepeated:
 lists //. {a___, {x_, y_, z_}, b___, {x_, y_, w_}, c___} :> {a, {x, y, z + w}, b, c}

Cases + DeleteDuplicates:
 DeleteDuplicates@Cases[lists, {w : PatternSequence[_, _], _} :>
         {w, Total@(Last /@ Cases[lists, {w, _}])}]

all give

{{1, 0, 4}, {2, 1, 1}, {2, 4, 2}}

Update: In versions 10+, you can also use Merge:
KeyValueMap[Append]@Merge[Tr][Most @ # -> Last @ #& /@ lists]

{{1, 0, 4}, {2, 1, 1}, {2, 4, 2}}


Q:

How to Override View in Nopcommerce?

I am creating one plug-in using data-access and widget in nopCommerce.
In that i have created my widget that i want to display on ProductDetails Page by replacing (overriding) Product-Image & its thumbs.
But i don't know how to override views and even don't know is it possible in nopCommerce or not.
Please can anyone help me.
If possible please provide an example as well, so that i can understand actually how it overrides in nopcommerce.

A:

You can override views using custom themes (not plugins).
For example, to override product details page, copy appropriate cshtml files into \Themes\{YourThemeName}\Views\Catalog\{YourProductTemplateFile.cshtml} and then customize it for your needs.


Q:

Reading specific line

I want to read a specific line from an html source code.
Im storing the source into a string file and i want to read the line X.
So im using this method that i found on net
Public Shared Function ReadSpecifiedLine(file As String, lineNum As Integer) As String
    Dim contents As String = String.Empty
    Try
        Using stream As New StreamReader(file)
            contents = stream.ReadToEnd()
            Dim linesArray As String() = contents.Split(New Char() {ControlChars.Lf})

            If linesArray.Length > 1 Then
                If Not lineNum > linesArray.Length AndAlso Not lineNum < 0 Then
                    Return linesArray(lineNum)
                Else
                    Return linesArray(0)
                End If
            Else
                Return contents
            End If
        End Using
    Catch ex As Exception
        Return ex.ToString()
    End Try
End Function

For example im trying to read the 4th line and im getting this error.

System.ArgumentException: Illegal characters in path.
     at System.IO.Path.CheckInvalidPathChars(String path, Boolean checkAdditional)
     at System.IO.Path.GetFileName(String path)
     at System.IO.StreamReader..ctor(String path, Encoding encoding, Boolean detectEncodingFromByteOrderMarks, Int32 bufferSize, Boolean checkHost)
     at System.IO.StreamReader..ctor(String path)
     at WindowsApplication1.Form1.ReadSpecifiedLine(String file, Int32 lineNum) in C:\Users\Optimus\documents\visual studio 2012\Projects\WindowsApplication1\WindowsApplication1\Form1.vb:line 48

Any help would be appreciated.

A:

The method you posted assumes you are passing in the file path.  If you want to change it to accept the actual file contents, instead of the file path, you could simplify the method by getting rid of the stream object:
Public Shared Function ReadSpecifiedLine(contents As String, lineNum As Integer) As String
    Dim linesArray As String() = contents.Split(New Char() {ControlChars.Lf})
    If linesArray.Length > 1 Then
        If Not lineNum > linesArray.Length AndAlso Not lineNum < 0 Then
            Return linesArray(lineNum)
        Else
            Return linesArray(0)
        End If
    Else
        Return contents
    End If
End Function


Q:

Controller structure for a browser game module with filters and pagination

To get an idea of what the controller code reflects, here is a screenshot:

Basically, the idea is that you print out a list of football players which you can then filter by their name, price, field position, and team. I'm not sure whether it's better to handle all the scope logic within a single controller, or break it down into separate controllers, isolating the filters from the player list, pagination, and so on. I'm currently going with the single controller approach, and here's what I have:
app.controller('playersController', function($scope, $filter, minMax, buildOptions, PlayersModel, TeamsModel, CommonValues){
    $scope.basehref         = CommonValues.getBaseHref();
    $scope.imgbase          = CommonValues.getImgBase();
    $scope.players          = PlayersModel;
    $scope.teams            = TeamsModel;
    $scope.predicate        = 'team.name';
    $scope.minMax           = minMax($scope.players);

    $scope.filters          = { // filter model
        searchString: '',       // string input from user
        selectedTeam: {},       // selected team
        selectedTeamMs: [],     // selected teams from multiselect
        roles: {
            1: true,            // forward
            2: true,            // defense
            3: true,            // midfield
            4: true             // goalie
        },
        slider: {               // set up boundaries for slider filter
            min: $scope.minMax[0],
            max: $scope.minMax[1],
            step: 10000
        },
        pagination: {           // set up pagination
            totalItems: $scope.players.length,
            currentPage: 1,
            maxSize: 5,
            pages: buildPages()
        }
    };
    var cache = $scope.players;   // save original player model for later use

    /**********
     * Watchers
     **********/

    // watch for filter model changes, start filtering
    $scope.$watch('filters', function(newVal, oldVal){
        if (newVal !== oldVal || newVal.id !== oldVal.id || newVal.length !== oldVal.length) {
            var result;

            result = $filter('textFilter')(cache, $scope.filters);                 // filter by phrase
            result = $filter('roleFilter')(result, $scope.filters);                // filter by field position
            result = $filter('teamFilter')(result, $scope.filters.selectedTeamMs); // filter by team

            $scope.players = result;
        }
    }, true);

    /***********
     * Scope API
     ***********/

    // pagination logic
    $scope.changePage  = function(newVal, oldVal) {
        var maxSize    = $scope.filters.pagination.maxSize;
        var offset     = maxSize * oldVal;
        var result     = [];

        if (newVal < oldVal)  offset = (maxSize * newVal) - maxSize;

        for (var i = 0; i < cache.length; i++) {
            if (i >= offset) result.push(cache[i]);
        }
        $scope.players = result;
    };

    /****************
     * Helper methods
     ****************/
    function buildPages() {
        return null;
    }
});

Is it ok to encapsulate all the logic into that one controller, including helper methods, and so on, or should I refactor?

A:

First of all, for a better user experience, I would avoid pagination in favour of infinite scroll. Here is a simple Angular infinite scroll implementation
I presume you are aware of minification-proof technique .controller('name', ['$scope', function($scope){}], so won't go into that.
Next, I see many fields like $scope.players, $scope.teams, ..., mixed with $scope.filters, which can lead to namespace conflicts as the app grows. Hence I would gather all data-related fields into one object like $scope.data. Then you can simply pass the whole object from your service instead of assigning one-by-one.
The hard-coded declation $scope.predicate = 'team.name'; is mixed with others provided by the service. Perhaps it belongs to a Config service together with other hard-coded properties.
Also I presume you are aware of the difference between using $scope.field vs $scope.field.subfield in terms of their interactions with parent and child scopes.
EDIT.
Unless you know what you are doing, a recommended practice is to use $scope.field.subfield. That way, in a child controller, you have both read and write access to it. If instead you use $scope.field, then changing it from a child controller will add a variable on the local scope but won't change the parent scope as you likely intend, see here.
EDIT.
See also Misko's video on best practices, including putting the dot inside your $scope property.
minMax($scope.players); suggests that you are using service minMax just for one function. I would gather those functions into one bigger service like Utils. You already have lots of dependencies for your controller, so lowering that number can be a good thing. Similar for $scope.teams = TeamsModel;.
I am not sure why you define filters inside a controller, rather than with .filter as common.
Usually filters declared via .filter update themselves, so no need for watchers.


Q:

How to add glyphicon in input placeholder?

Please refer - https://jsfiddle.net/cyCFS/3218/

    <input type="search"
       class="form-control"
       placeholder="&#xe003" />

I want the glyphicon to show up as a placeholder in the input text box. But it does not render. Where as if I had put a font awesome icon hexa code, it renders.
How to make it work in glyphicon (without introduing any new tag like span or i just for showing the icon like
<i class= glyphicon-search"

A:

You need to add class glyphicon into it

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

  <input type="search" class="form-control glyphicon" placeholder="&#xe003" />


Q:

dataList auto fill other fields when an option is selected - AngularJs

I have a data-list of Names, i want to auto fill the phone number and the location fields when the name is selected, for now, the fields are getting their values from scopes on the angular controller by clicking on the  column, this is my code:
HTML SOURCE:

                Client

                    <input type="text" id="client_List" list="clientList" />
                    <datalist id="clientList">
                    <option ng-repeat="fc in facture_client_retour" data-tele="{{fc.phone_number}}" data-location="{{fc.location}}" data-id="{{fc.id}}" value="{{fc.fname}} {{fc.lname}} |{{fc.code}}" id="optIdFc">
                </datalist>

                Telephone
                {{clientPhoneNumber}}

                Location
                {{clientLocation}}

I am getting no errors and it works fine when click on the  to call the function getClientAttr(), but my need is to auto call this function when the option is selected.
JS SOURCE:
app.controller('facture_retour',function($scope, $http){
        $scope.facture_client_retour;
        angular.element(document).ready(function () {
            $scope.getAllClients();
    });

 /*This function is responsible of getting all clients Name and display them
 in the data-list */
$scope.getAllClients=function(){
            var url = '../php/mainPageFacture.php';
            var data = {"function":"getAllClients"};
            var options={
                type : "get",
                url : url,
                data: data,
                dataType: 'json',
                async : false,
                cache : false,
                success : function(response,status) {
                    $scope.facture_client_retour = response;
                    $scope.$apply();
                },
                error:function(request,response,error){
                    // alert("Error: " + error + ". Please contact developer");
                    swal({
                      title: "Please contact your software developer",
                      text: "ERROR: " + error,
                      type: "warning",
                      showCancelButton: false,
                      confirmButtonClass: "btn-info",
                      confirmButtonText: "Ok",
                      closeOnConfirm: true
                    });
                }
            };
            $.ajax(options);
            $scope.call=getClientAttr();
        }

 /*this function getting the other fields (phone number,location) values and
 display them by clicking on */
        $scope.getClientAttr=function(){
            //alert("here we go");
            var val = $('#client_List').val()
            var client_phone_number= $('#clientList option').filter(function() {
                return this.value == val;
            }).data('tele');

             $scope.clientPhoneNumber=client_phone_number;
                var val = $('#client_List').val()
                var client_location= $('#clientList option').filter(function() {
                    return this.value == val;
                }).data('location');
             $scope.clientLocation=client_location;
        }

    });

A:

add a ng-model to your input
<input type="text" ng-model="Data" id="client_List" list="clientList" />

you can add ng-click to your datalist option and set selected value to model
<datalist id="clientList">
    <option ng-repeat="fc in facture_client_retour" data-tele="{{fc.phone_number}}" data-location="{{fc.location}}" data-id="{{fc.id}}" value="{{fc.fname}} {{fc.lname}} |{{fc.code}}" id="optIdFc" ng-click="Data = fc">
</datalist>

and set values of location and phone number in your controller when model changes
  $scope.$watchCollection('Data', function(newValue, oldValue) {
    if(newValue != undefined)
      angular.forEach($scope.data, function(value, key) {
        if(value.name == newValue){
            $scope.clientPhoneNumber = value.phone_number;
            $scope.clientLocation = value.location;
        }
      });
  });


Q:

Identify this famous instrumental music played on the electric harp

At the end of the following interview (2:30), Enki Bello starts playing a piece of music:
Enki Bello TV NBC "Telemundo New York" Interview

A:

This is

Shakira - Hips don't lie


Q:

Resetting saved states in eclipse rcp

I'm saving some UI settings in a state of my view. In this case I'm saving the current column order of a table in a comma-seperated string.
@Override
public void saveState(final IMemento memento) {
    int[] columnOrder = tableViewer.getTable().getColumnOrder();
    StringBuilder order = new StringBuilder();
    for (int i = 0; i < columnOrder.length; i++) {
        order.append(columnOrder[i]);
        order.append(",");
    }
    IMemento viewMemento = memento.createChild(MyView.ID);
    viewMemento.putString("viewColumnOrder", order.toString());
    super.saveState(memento);
}

Is there a way to reset the state programmatically to the initial value? I tried to reset the perspective, but that didn't work. Also resetting the Workbench did not help me.

A:

There is no API to do this.
On Eclipse 4 starting the RCP with the -clearPersistedState flag should discard the saved state.
On Eclipse 4 the XML version of the IMemento is saved in the view MPart persisted state under the memento key - but this is an internal implementation detail which may change at any time.


Q:

Сборка Makefile для DL POLY 4

Пытаюсь сделать сборку makefile для программы DL POLY 4, однако при выполнении команды make gnu -f Makefile_MPI clean выводится ошибка:

make LD=gfortran \
LDFLAGS="-O3" \
FC="gfortran -c" \
FCFLAGS="-O3" \
EX=DLPOLY.Z BINROOT=../execute master
make[1]: вход в каталог «/home/rasul/desktop/blya/source»
make[1]: *** Нет правила для сборки цели «master».  Останов.
make[1]: выход из каталога «/home/rasul/desktop/blya/source»
Makefile_MPI:242: ошибка выполнения рецепта для цели «gnu»
make: *** [gnu] Ошибка 2
Краткое содержание makefile'a:

/*---CODE---*/

gnu:
    $(MAKE) LD=gfortran \
    LDFLAGS="-O3" \
    FC="gfortran -c" \
    FCFLAGS="-O3" \
    EX=$(EX) BINROOT=$(BINROOT) $(TYPE)

---------------------

master: message check $(OBJ_MOD) $(OBJ_ALL)
    $(LD) $(EXE) $(LDFLAGS) $(OBJ_MOD) $(OBJ_ALL)

# Message
message:
    @echo "DL_POLY_4 compilation in MPI mode"
    @echo
    @echo "'Use mpi_module' must change to 'Use mpi' in 'comms_module.f90'"
    @echo

# Check that a platform has been specified
check:
    @if test "${FC}" = "undefined"; then \
    echo; echo "*** FORTRAN90 compiler unspecified!"; \
    echo; echo "*** Please edit your Makefile entries!"; \
    echo; exit 99; \
    fi; \
    \
    if test "${LD}" = "undefined"; then \
    echo; echo "*** FORTRAN90 Linker-loaDer unspecified!"; \
    echo; echo "*** Please edit your Makefile entries!"; \
    echo; exit 99; \
    fi; \
    \
    mkdir -p $(BINROOT) ; touch dl_poly.f90

    /*---CODE---*/

Никогда не работал с makefile и fortran, помогите, пожалуйста.

A:

рекурсивно запускается программа make, которой не передаётся аргумент -f Makefile_MPI.
соответственно этот экземпляр программы make пытается интерпретировать первый из найденных в текущем каталоге файлов с именем: GNUmakefile, makefile, Makefile. и в этом файле (цитирую):

Нет правила для сборки цели «master».

простейшее решение для обхода этой недоработки разработчиков — запускайте программу make с нужной целью, не забыв добавить все упомянутые в логе аргументы, напрямую:
$ make -f Makefile_MPI LD=gfortran LDFLAGS="-O3" FC="gfortran -c" FCFLAGS="-O3" EX=DLPOLY.Z BINROOT=../execute master


Q:

Como Exibir varios valores de um JSON em PHP

Como posso exibir todos os valores de um JSON em PHP ??
Vou dar um exemplo , Uso o Código abaixo para requisitar o JSON

    $json_file = file_get_contents("http://backpack.tf/api/IGetUsers/v3/?steamids=76561198012598620");
    $json_str = json_decode($json_file, true);

As informações contidas no JSON São estas:

{
    "response": {
        "success": 1,
        "current_time": 1400075229,
        "players": {
            "76561198012598620": {
                "steamid": "76561198012598620",
                "success": 1,
                "backpack_value": {
                    "570": 5,
                    "440": 126.9475
                },
                "backpack_update": {
                    "570": 1399815523,
                    "440": 1400024876
                },
                "name": "Fiskie",
                "backpack_tf_reputation": 2,
                "notifications": 0
            }
        }
    }
}

Mas se uso $nome = $json_str["name"];
echo "$nome";
Para exibir o valor "name" a pagina parece não carregar , toda a tela fica branca..
Como posso exibir o valor "name" corretamente ?
Obrigado a todos que puderem me ajudar.

A:

$nome = $json_str["response"]["players"]["76561198012598620"]["name"];
echo "$nome";


Q:

GridLines not showing in a GridView with CSS reset?

I have a page which includes a css reset.  On that page, I have a gridview with the GridLines="Both" property set to true, but the grid lines are not appearing.  If I remove the css reset, the gridlines show up.  This is only happening in IE.  I want the reset and I want the gridlines to appear.  Does anyone know the solution to this?

A:

Make sure to call the stylesheet or style defining the gridlines appearing after you've called the reset stylesheet.
Failing that makes sure that there isn't a more-specific selector defined in the reset stylesheet, that's overriding the element styles for which you want gridlines to appear. There's also nothing stopping you defining the gridlines in the reset-stylesheet, just as a check to see where the overriding style's being defined.
But, as noted in Jab's comment to your question, using Firebug would be the fastest way to see where the styles are coming from. If you're using IE then, assuming you're on IE8, you can use Firebug too, albeit they're calling it Developer Tools.


Q:

Box2D physics editor for complex bodies

Is there any editor out there that would allow me to define complex entities, with joins connecting their multiple bodies, instead of regular single body entities? For example, an editor that would allow me to 'define' a car as having a main body with two circles as wheels, connected through joints.
Clarification:
I realize I haven't been clear enough about what I need. I'd like to make my engine data-driven, so all entities (and therefore their Box2D bodies) should be defined externally, not in code.
I'm looking for a program like Code 'N' Web's PhysicsEditor, except that one only handles single body entities, no joints or anything like that. Like PhysicsEditor, the program should be configurable so that I can save the data in whatever format I want to. Does anyone know of any such software?

A:

You may be interested in Physics Body Editor. That's an open-source tool handling bodies with multiple fixtures.
A big update is in progress, and next revision will support complex dynamic objects made of multiple rigid bodies linked with custom joints, as well as a scripting support for directly testing your bodies.
Hope you'll like it ;)

A:

R.U.B.E. is fantastic:
https://www.iforce2d.net/rube/
Its just does what it should and is not restricted to specific game engines like levelhelper..

A:

The Box2D website does list 3 editors that could be useful to you.
http://www.box2d.org/links.html
One of the links is dead however.  I was only able to check this one out:
http://www.brainblitz.org/BoxCAD/
There is an option to dump to code that I tried, and it does in fact give you the Box2D code of whatever you built on screen.  Looks pretty decent.


Q:

Free - jqgrid: Combine frozen column, grouping header and toolbar search

I'm using free-jqgrid v4.15.5 and have a problem with Frozen column, Toolbar searching and Header grouping.
I had a similar question here and got the solution from Oleg
And the problem arises when I incorporate the frozen column feature into the example. The search field in the Date column does not appear and the position of Inv No is not good. Demo here

$(document).ready(function () {
        var myData = [
                { id: "1", invdate: "2007-10-01", name: "test", note: "note", amount: "200.00", tax: "10.00", closed: true, ship_via: "TN", total: "210.00" },
                { id: "2", invdate: "2007-10-02", name: "test2", note: "note2", amount: "300.00", tax: "20.00", closed: false, ship_via: "FE", total: "320.00" },
                { id: "3", invdate: "2007-09-01", name: "test3", note: "note3", amount: "400.00", tax: "30.00", closed: false, ship_via: "FE", total: "430.00" },
                { id: "4", invdate: "2007-10-04", name: "test4", note: "note4", amount: "200.00", tax: "10.00", closed: true, ship_via: "TN", total: "210.00" },
                { id: "5", invdate: "2007-10-31", name: "test5", note: "note5", amount: "300.00", tax: "20.00", closed: false, ship_via: "FE", total: "320.00" },
                { id: "6", invdate: "2007-09-06", name: "test6", note: "note6", amount: "400.00", tax: "30.00", closed: false, ship_via: "FE", total: "430.00" },
                { id: "7", invdate: "2007-10-04", name: "test7", note: "note7", amount: "200.00", tax: "10.00", closed: true, ship_via: "TN", total: "210.00" },
                { id: "8", invdate: "2007-10-03", name: "test8", note: "note8", amount: "300.00", tax: "20.00", closed: false, ship_via: "FE", total: "320.00" },
                { id: "9", invdate: "2007-09-01", name: "test9", note: "note9", amount: "400.00", tax: "30.00", closed: false, ship_via: "TN", total: "430.00" },
                { id: "10", invdate: "2007-09-08", name: "test10", note: "note10", amount: "500.00", tax: "30.00", closed: true, ship_via: "TN", total: "530.00" },
                { id: "11", invdate: "2007-09-08", name: "test11", note: "note11", amount: "500.00", tax: "30.00", closed: false, ship_via: "FE", total: "530.00" },
                { id: "12", invdate: "2007-09-10", name: "test12", note: "note12", amount: "500.00", tax: "30.00", closed: false, ship_via: "FE", total: "530.00" }
        ],
            myGrid = $("#list");

        myGrid.jqGrid({
            datatype: 'local',
            data: myData,
            colNames: ['Inv No', 'Date', 'Client', 'Amount', 'Tax', 'Total', 'Closed', 'Shipped via', 'Notes'],
            colModel: [
                { name: 'id', index: 'id', width: 70, align: 'center', sorttype: 'int', frozen: true },
                {
                    name: 'invdate', index: 'invdate', width: 80, align: 'center', sorttype: 'date', frozen: true,
                    formatter: 'date', formatoptions: { newformat: 'd-M-Y' }, datefmt: 'd-M-Y'
                },
                { name: 'name', index: 'name', width: 70 },
                { name: 'amount', index: 'amount', width: 100, formatter: 'number', align: 'right' },
                { name: 'tax', index: 'tax', width: 70, formatter: 'number', align: 'right' },
                { name: 'total', index: 'total', width: 120, formatter: 'number', align: 'right' },
                {
                    name: 'closed', index: 'closed', width: 110, align: 'center', formatter: 'checkbox',
                    edittype: 'checkbox', editoptions: { value: 'Yes:No', defaultValue: 'Yes' },
                    stype: 'select', searchoptions: { sopt: ['eq', 'ne'], value: ':All;true:Yes;false:No' }
                },
                {
                    name: 'ship_via', index: 'ship_via', width: 120, align: 'center', formatter: 'select',
                    edittype: 'select', editoptions: { value: 'FE:FedEx;TN:TNT;IN:Intim', defaultValue: 'Intime' },
                    stype: 'select', searchoptions: { value: ':All;FE:FedEx;TN:TNT;IN:Intim' }
                },
                { name: 'note', index: 'note', width: 100, sortable: false }
            ],
            rowNum: 10,
            rowList: [5, 10, 20],
            //pager: '#pager',
            gridview: true,
            ignoreCase: true,
            rownumbers: false,
            sortname: 'invdate',
            viewrecords: true,
            sortorder: 'desc',
            //caption: 'Just simple local grid',
            height: '100%',
            shrinkToFit: false,
            width: 400
        });
        myGrid.jqGrid('filterToolbar', { stringResult: true, searchOnEnter: false, defaultSearch: "cn" });
        myGrid.jqGrid('setFrozenColumns');
        myGrid.jqGrid('setGroupHeaders', {
            useColSpanStyle: true, groupHeaders:
                [
                    { startColumnName: 'invdate', numberOfColumns: 5, titleText: "Group column 1" },
                    { startColumnName: 'closed', numberOfColumns: 3, titleText: "Group column 2" },
                ]
        });
        myGrid.jqGrid('setGroupHeaders', {
            useColSpanStyle: true, groupHeaders:
              [
                    { startColumnName: 'amount', numberOfColumns: 3, titleText: "Group column 3" },
                ]
        });
        $("#list_invdate,#list_closed,#list_ship_via,#list_note,#list_name").attr("rowspan", "2")
    });

And can anyone solve this problem for me? Thanks so much.
P/s: Oleg, I'm looking forward to your response.

A:

Sorry, but setGroupHeaders isn't really supported in common case if setGroupHeaders will be called more a one time. As a workaround one can change the value of rowspan attributes or to set the height of rows of frozen columns. In your case, the following code added at the end of your demo can fix the problem
var $frozenHDiv = myGrid.closest(".ui-jqgrid-view")
          .find(".frozen-div.ui-jqgrid-hdiv");

$frozenHDiv.find("tr.ui-jqgrid-labels")
          .children("th")
          .removeAttr("rowspan")

$frozenHDiv.find("tr.ui-jqgrid-labels").height(45);
$frozenHDiv.find("tr.ui-search-toolbar").height(22);

See https://plnkr.co/edit/sbDfCAg0h73G3Q3AaP2s?p=preview


Q:

Refreshing my fragment not working like I thought it should

I have this nice method in my ListFragment I call to fill out the details of my other fragment:
private void showClientDetails(int pos) {
        myCursor.moveToPosition(pos);
        int clientId = myCursor.getInt(0);
        if(mIsTablet) {

                // Set the list item as checked
                getListView().setItemChecked(mCurrentSelectedItemIndex, true);

                // Get the fragment instance
                ClientDetails details = (ClientDetails) getFragmentManager().findFragmentById(R.id.client_details);
                // Is the current visible recipe the same as the clicked? If so, there is no need to update

                if (details == null || details.getClientIndex() != mCurrentSelectedItemIndex) {
                        // Make new fragment instance to show the recipe
                        details = ClientDetails.newInstance(mCurrentSelectedItemIndex, clientId, mIsTablet);
                        // Replace the old fragment with the new one
                        FragmentTransaction ft = getFragmentManager().beginTransaction();
                        ft.replace(R.id.client_details, details);
                        // Use a fade animation. This makes it clear that this is not a new "layer"
                        // above the current, but a replacement
                        ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
                        ft.commit();
                }
        }
}

It is called when the user clicks on a client in the ListFragment view:
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
       mCurrentSelectedItemIndex = position;
           showClientDetails(position);
}

This works great, but then another FragmentActivity can change the data that this displays so I thought this would work:
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{

    super.onActivityResult(requestCode, resultCode, data);
            //update the client list incase a new one is added or the name changes
    if(requestCode==1899)
    {
      myCursor.requery();
      theClients.notifyDataSetChanged();
          showClientDetails(mCurrentSelectedItemIndex); //now if client was edited update their details in the details fragment
    }
}

Now I know the line:
if (details == null || details.getClientIndex() != mCurrentSelectedItemIndex) {
Prevents the block of code being reached when its called in my onActivityResult.  So if I remove that if statement, then things freak out and the ft.commit() has a hissy fit and gives me the error:
`07-08 16:53:31.783: ERROR/AndroidRuntime(2048): Caused by: java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
So I guess what I am trying to do isn't as cut and dry as it sounds, it makes no sense to me since I can do that onListItemClicked all day and the fragment displays the details of the newly clicked client constantly very well...
I even tried this in my onActivityResult:
//simulate a click event really fast to refresh the client details
showClientDetails(0);
showClientDetails(mCurrentSelectedItemIndex);

that does nothing, is it im trying to call something from the onActivityResult which isn't a Ui thread or what not?
I do have this in my code of the ListFragment as well
@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
outState.putInt("currentListIndex", mCurrentSelectedItemIndex);
}

Is this what the error is complaining about?

A:

The other FragmentActivity's action is performing a task which requires the Fragment to save its state via a call to onSaveInstanceState in preparation for a new instance being reconstructed. I've seen this for example when I was firing off an activity from a fragment which filled the entire screen as this resulted in the view being detached from the fragment, state needing to be saved etc.
You basically cannot call commit between onSaveInstanceState and the new instance of the fragment being recreated. See commit.
As for the solution, then either re-think to try and avoid the commit being called when it is or alternatively call commitAllowingStateLoss if you think it's OK for the UI to change unexpectedly on the user.

A:

I think the answer is to not do any fragment transactions in the onActivityResult. I believe what happens is that when the onActivityResult is called the activity it is in hasn't yet resumed and restarted its fragments.
Use a handler to post back the function call to the activity.
handler.post(new Runnable() {
    @Override
    public void run() {
        showClientDetails(mCurrentSelectedItemIndex);
    }
});


Q:

Build fails in unity using googlevr sdk, unable to convert classes into dex

I'm trying to build for daydream using the google-vr sdk, but am getting build errors in unity.
If I remove the plugins/android directory I am able to build but the build comes out buggy as hell. I am then prompted to install missing dependencies:
Import for GVRBackwardsCompatibility
After doing so am unable to build again, with unable to convert classes into dex format error.
Console shows this:
 CommandInvokationFailure: Unable to convert classes into dex format.
C:/Program Files/Java/jdk1.8.0_112\bin\java.exe -Xmx2048M -Dcom.android.sdkmanager.toolsdir="F:/Android/android-sdk\tools" -Dfile.encoding=UTF8 -jar "C:\Program Files\Unity 5.6.0b1\Editor\Data\PlaybackEngines\AndroidPlayer/Tools\sdktools.jar" -

stderr[
Uncaught translation error: java.lang.IllegalArgumentException: already added: Lcom/google/common/logging/nano/Vr;
Uncaught translation error: java.lang.IllegalArgumentException: already added: Lcom/google/common/logging/nano/Vr$VREvent;
Uncaught translation error: java.lang.IllegalArgumentException: already added: Lcom/google/common/logging/nano/Vr$VREvent$Application;
Uncaught translation error: java.lang.IllegalArgumentException: already added: Lcom/google/common/logging/nano/Vr$VREvent$AudioStats;
Uncaught translation error: java.lang.IllegalArgumentException: already added: Lcom/google/common/logging/nano/Vr$VREvent$AudioStats$RenderingMode;
Uncaught translation error: java.lang.IllegalArgumentException: already added: Lcom/google/common/logging/nano/Vr$VREvent$Bucket;
Uncaught translation error: java.lang.IllegalArgumentException: already added: Lcom/google/common/logging/nano/Vr$VREvent$Cyclops;
Uncaught translation error: java.lang.IllegalArgumentException: already added: Lcom/google/common/logging/nano/Vr$VREvent$Cyclops$Capture;
Uncaught translation error: java.lang.IllegalArgumentException: already added: Lcom/google/common/logging/nano/Vr$VREvent$Cyclops$Capture$Outcome;

UNEXPECTED TOP-LEVEL EXCEPTION:
java.lang.RuntimeException: Translation has been interrupted
    at com.android.dx.command.dexer.Main.processAllFiles(Main.java:613)
    at com.android.dx.command.dexer.Main.runMonoDex(Main.java:311)
    at com.android.dx.command.dexer.Main.run(Main.java:277)
    at com.android.dx.command.dexer.Main.main(Main.java:245)
    at com.android.dx.command.Main.main(Main.java:106)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at SDKMain.main(SDKMain.java:129)
Caused by: java.lang.InterruptedException: Too many errors
    at com.android.dx.command.dexer.Main.processAllFiles(Main.java:605)
    ... 9 more
]
stdout[
processing archive P:\_Unity\DayDreamv1\Temp\StagingArea\android-libraries\gvr-permissionsupport-release\libs\.\classes.jar...
processing com/google/gvr/permissionsupport/BuildConfig.class...
processing com/google/gvr/permissionsupport/PermissionsFragment.class...
processing com/google/gvr/permissionsupport/PermissionsFragment$1.class...
processing com/google/gvr/permissionsupport/PermissionsFragment$PermissionsCallback.class...
processing com/google/gvr/permissionsupport/TransitionVRActivity.class...
processing com/google/gvr/permissionsupport/TransitionVRActivity$1.class...
ignored resource P:\_Unity\DayDreamv1\Temp\StagingArea\android-libraries\gvr\libs\.\armeabi-v7a\libgvr.so
processing archive P:\_Unity\DayDreamv1\Temp\StagingArea\android-libraries\gvr\libs\.\classes.jar...
processing com/google/common/logging/nano/Vr.class...

Unity 5.6.0b1 //
Google VR SDK 1.10 //
win10 x64
Have tried changing manifest.xml in plugins/android to reflect target-sdk and tried changing same in unity editor
Any help much appreciated.

A:

it looks like you have a duplicates in a project. Please, check if you did not add the same library twice or something like that. As error stands issue in duplication in this

/google/common/logging/nano


Q:

Error with insterting values

I have problem with inserting values into my table.
Here is the script:
IF OBJECT_ID ('DEPT', 'table') IS NOT NULL
DROP TABLE DEPT;
GO

CREATE TABLE DEPT (
   DEPTNO NUMERIC(2) NOT NULL,
   DNAME VARCHAR(14),
   LOC VARCHAR(13),

   CONSTRAINT DEPT_PRIMARY_KEY PRIMARY KEY (DEPTNO));
GO

INSERT INTO DEPT VALUES (10,'ACCOUNTING','NEW YORK');
INSERT INTO DEPT VALUES (20,'RESEARCH','DALLAS');
INSERT INTO DEPT VALUES (30,'SALES','CHICAGO');
INSERT INTO DEPT VALUES (40,'OPERATIONS','BOSTON');
GO

IF OBJECT_ID ('EMP', 'table') IS NOT NULL
  DROP TABLE EMP;
GO

CREATE TABLE EMP (
  EMPNO NUMERIC(4) NOT NULL,
  ENAME VARCHAR(10),
  JOB VARCHAR(9),
  MGR NUMERIC(4) CONSTRAINT EMP_SELF_KEY REFERENCES EMP (EMPNO),
  HIREDATE DATETIME,
  SAL NUMERIC(7,2),
  COMM NUMERIC(7,2),
  DEPTNO NUMERIC(2) NOT NULL,

  CONSTRAINT EMP_FOREIGN_KEY FOREIGN KEY (DEPTNO)
    REFERENCES DEPT(DEPTNO),

  CONSTRAINT EMP_PRIMARY_KEY PRIMARY KEY (EMPNO));
GO

INSERT INTO EMP VALUES
(7839,'KING','PRESIDENT',NULL,'17-11-1981',5000,NULL,10);

INSERT INTO EMP VALUES
(7698,'BLAKE','MANAGER',7839,'1-05-1981',2850,NULL,30);

INSERT INTO EMP VALUES
(7782,'CLARK','MANAGER',7839,'9-06-1981',2450,NULL,10);

INSERT INTO EMP VALUES
(7566,'JONES','MANAGER',7839,'2-04-1981',2975,NULL,20);

INSERT INTO EMP VALUES
(7654,'MARTIN','SALESMAN',7698,'28-09-1981',1250,1400,30);

INSERT INTO EMP VALUES
(7499,'ALLEN','SALESMAN',7698,'20-02-1981',1600,300,30);

INSERT INTO EMP VALUES
(7844,'TURNER','SALESMAN',7698,'8-09-1981',1500,0,30);

INSERT INTO EMP VALUES
(7900,'JAMES','CLERK',7698,'3-12-1981',950,NULL,30);

INSERT INTO EMP VALUES
(7521,'WARD','SALESMAN',7698,'22-02-1981',1250,500,30);

INSERT INTO EMP VALUES
(7902,'FORD','ANALYST',7566,'3-12-1981',3000,NULL,20);

INSERT INTO EMP VALUES
(7369,'SMITH','CLERK',7902,'17-12-1982',800,NULL,20);

INSERT INTO EMP VALUES
(7788,'SCOTT','ANALYST',7566,'09-12-1982',3000,NULL,20);

INSERT INTO EMP VALUES
(7876,'ADAMS','CLERK',7788,'12-01-1983',1100,NULL,20);

INSERT INTO EMP VALUES
(7934,'MILLER','CLERK',7782,'23-01-1982',1300,NULL,10);

There is error while doing this:
INSERT INTO EMP VALUES  (7859, 'PHILIPPE', 'CLERK', 8219,
'1988-06-11', 1300, NULL, 10), (7594, 'SEBASTIEN', 'SALESMAN', 1292,
'1978-06-09', 3500, NULL, 10);

INSERT INTO EMP VALUES  (7956, 'MARTIN', 'DEALER', 4322, '1981-04-11',
2300, 0, 20), (7947, 'SIMON', 'CLERK', 7655, '1981-07-12', 1800, 200,
20);

INSERT INTO EMP VALUES  (7382, 'HUGO', 'ANALYST', 4564, '1982-05-11',
1300, 0, 30), (7291, 'MARC', 'SALESMAN', 9768, '1981-03-09', 3500,
NULL, 30);

INSERT INTO EMP VALUES  (7734, 'JOHN', 'MANAGER', 8678, '1983-11-11',
4300, 0, 40), (7359, 'TOMMY', 'CLERK', 5340, '1981-04-10', 1200, 100,
40);

Error:

The instruction INSERT is in conflict with constraint FOREIGN KEY SAME
  TABLE "EMP_SELF_KEY".

Can someone help? Thanks !

A:

In your second block of inserts into EMP, none of the MGR values (8219, 4322, 4564, 8678) appear as EMPNO values in your previous inserts, hence the foreign key violation. Those "managers" must be inserted as "employees" before they can be referenced by the foreign key.


Q:

Regex to parse URL from an excel formula

I have a formula in excel which upon reading from C# code looks like this
"=HYPERLINK(CONCATENATE(\"https://abc.efghi.rtyui.com/#/wqeqwq/\",#REF!,\"/asdasd\"), \"View asdas\")"

I want to use regex to fetch the URL from this string, i.e.
https://abc.efghi.rtyui.com/#/wqeqwq/#REF!/asdasd
The url can be different but the format of the formula will remain the same.
"=HYPERLINK(CONCATENATE(\"{SOME_STRING}\",#REF!,\"{SOME_STRING}\"), \"View asdas\")"

A:

Try it like this:
(?<=HYPERLINK\(CONCATENATE\(")[^"]+

Demo
The positive lookbehind allows us to skip part in-front of the URL from the full match.
If you have an arbitrary number of whitespace in-between add some \s*, e.g. see this example that also shows the escaped = at the beginning of the string.
Sample Code:
using System;
using System.Text.RegularExpressions;

public class Example
{
    public static void Main()
    {
        string pattern = @"(?<=HYPERLINK\(CONCATENATE\("")[^""]+";
        string input = @"=HYPERLINK(CONCATENATE(""https://abc.efghi.rtyui.com/#/wqeqwq/"",#REF!,""/asdasd""), ""View asdas"")";
        RegexOptions options = RegexOptions.Multiline;

        foreach (Match m in Regex.Matches(input, pattern, options))
        {
            Console.WriteLine("'{0}' found at index {1}.", m.Value, m.Index);
        }
    }
}

Addendum: Here is another technique that uses capturing groups and regex Replace to extract the resulting URL string (after CONCATENATE would have happened):
^\=HYPERLINK\(CONCATENATE\("([^"]+)",([^,]+),"([^"]+)".*$

Demo2
string pattern = @"^\=HYPERLINK\(CONCATENATE\(""([^""]+)"",([^,]+),""([^""]+)"".*$";
string substitution = @"$1$2$3";
string input = @"=HYPERLINK(CONCATENATE(""https://abc.efghi.rtyui.com/#/wqeqwq/"",#REF!,""/asdasd""), ""View asdas"")";

    Regex regex = new Regex(pattern);
    string result = regex.Replace(input, substitution, 1);


Q:

Can a Java Applet Access Local File System

I am creating a java applet, that gets information out of a JAR file on my local file system, and creates a jpanel to display in the applet.
I am getting the applet to load correctly on the appletViewer in Eclipse, but it will not load whenever i launch the Html file i created.
The html file is points to the class files, also to the external jars.
Any Suggestions?
Thanks

A:

Yes, if the applet is signed with the jarsigner tool.


Q:

Hazelcast Mancenter rises cpu usage

I have:
a) 1 server (4vcpu, 8GB) running a hazelcast node,
b) 1 server (4vcpu, 8GB) running a hazelcast mancenter on tomcat 7.
Both servers are in the same local network.
I've tested 2 scenarios:
Scenario 1) I've started a) and b). No data transfered. The cpu usage on a) was 0-10%.
Scenario 2) I've started a) and b). I've transfered a bulk of data to process on a) and waited until it finished (2h). When no data was left to process I've checked the cpu usage on a) - it was 30-110% (even after 8h). When I stopped mancenter on b) the cpu on a) went down to 0-10%. After starting mancenter again it rose to 30-110%.
I think that the cpu usage on a) after 1) and 2) should be the same.
I've analized the jvm's and noticed that a thread called MC.State.Sender was inactive in scenario 1 and active in scenario 2. Could this be draining out the cpu? Can this be limited via configuration?

Thx in advance for any help.
Here are the thread dumps from visualvm (I can also provide cpu profiler snapshots):
scenario1 thread dump
scenario2 thread dump

A:

I've noticed the problem when using Hazelcast 3.4 and Mancenter 3.4.1.
After update'ing the Hazelcast lib to 3.4.1 I couldn't repeat the problem.
I was performing different tests for a whole week and the problem didn't occur again. The solution is to keep mancenter and Hazelcast lib in the same version.


Q:

Is there a way to register custom metadata for a service in K8S Service Discovery?

I have my service (spring boot java application) running in a K8S cluster with 3 replicas(pods). My use-case requires me to deploy application contexts dynamically.
And i need to know which context is deployed on which of the 3 Pods through service discovery. Is there a way to register custom metadata for a service in K8S Service Discovery, like we do in Eureka using eureka.instance.metadata-map?

A:

In terms of Kubernetes, we have Deployments and Services.
Deployment is a description of state for ReplicaSet, which creates Pods. Pod consists of one or more containers.
Service is an abstraction which defines a logical set of Pods and a policy by which to access them.
In Eureka, you can set a configuration of Pods dynamically and reconfigure them on-fly, which does not match with Kubernetes design.
In Kubernetes, when you use 1 Deployment with 3 Replicas, all 3 Pods should be the same. It has no options or features to export any metadata for separate Pods under the Services into different groups because ReplicaSet, which contain Pods with same labels, is a group itself.
Therefore, the better idea is to use 3 different Deployments with 1 Replica for each, all of them with the same configuration. Or use some Springboot’s features, like its service discovery if you want to reload application context on-fly.


Q:

Java - How to retrieve all chrome tabs details?

I wish to use a class that provides the option to get all open tabs.
Unfortunately, I can only find code in js and other.. and I don't really know how to use it in my Java code..

A:

There is no way to find browser physical details with Java other than the request headers. You Cannot.
On the other hand you can send the info you found with Javascript to server(Java) through a request.


Q:

Fast way to and rows to dataframe based on number of column

I have the following data frame:
df1 = structure(c(3, 5, 8, 6), .Dim = c(2L, 2L))

I would like to add 3 rows:
(0,0)
(5,0)
(0,8)

i.e. for each column, I add a row that is the max of this column, the rest are zeros, and an all zero line. Any fast way to do this?

A:

One option is colMaxs from matrixStats, get the diag and rbind with the original matrix along with a 0 padded row
library(matrixStats)
rbind(df1, 0, diag(colMaxs(df1)))

If it is a data.frame (based on the title)
library(dplyr)
df2 %>%
   summarise_all(max) %>%
   diag %>%
   rbind(df2, 0, .)

data
df2 <- as.data.frame(df1)


Q:

Why am I getting a CPU usage of 0% all the time?

This is what im doing in form1:
void PopulateApplications()
{
    DoubleBufferedd(dataGridView1, true);

    int rcount = dataGridView1.Rows.Count;
    int rcurIndex = 0;

    foreach (Process p in Process.GetProcesses())
    {
        try
        {
            if (File.Exists(p.MainModule.FileName))
            {
                memoryUsage = Core.getallmemoryusage(p.ProcessName);
                Core.getcpu(p.ProcessName);
                cpuusage = Core.processes;

                var icon = Icon.ExtractAssociatedIcon(p.MainModule.FileName);
                Image ima = icon.ToBitmap();
                ima = resizeImage(ima, new Size(25, 25));
                ima = (Image)(new Bitmap(ima, new Size(25, 25)));
                String status = p.Responding ? "Running" : "Not Responding";

                if (rcurIndex < rcount - 1)
                {
                    var currentRow = dataGridView1.Rows[rcurIndex];
                    currentRow.Cells[0].Value = ima;
                    currentRow.Cells[1].Value = p.ProcessName;
                    currentRow.Cells[2].Value = cpuusage;
                    currentRow.Cells[3].Value = memoryUsage;
                    currentRow.Cells[4].Value = status;
                }
                else
                {
                    dataGridView1.Rows.Add(ima, p.ProcessName,cpuusage,memoryUsage, status);//false, ima, p.ProcessName, status);
                }

                rcurIndex++;
            }
        }
        catch ( Exception e)
        {
            string t = "error";
        }
    }

    if (rcurIndex < rcount - 1)
    {
        for (int i = rcurIndex; i < rcount - 1; i++)
        {
            dataGridView1.Rows.RemoveAt(rcurIndex);
        }
    }
}

Now the method in form1 PopulateApplications, I call it from a timer tick event each 5 seconds.
Then I loop each time over the processes and get the memory usage and CPU usage.
This are the methods of memory and CPU in the class Core.
With the memory method there is no problems. Working good and fast.
public static string getallmemoryusage(string processName)
{
    var counter = new PerformanceCounter("Process", "Working Set - Private", processName);
    privateMemeory = (counter.NextValue() / 1024 / 1024).ToString();
    //string.Format("Private memory: {0}k", counter.NextValue() / 1024 / 1024);
    return privateMemeory;
}

The problem is with the getcpu method. I need to make it sleep every 1000ms few times to get the CPU usage. If I use a breakpoint on this method, I will get the value in the end. The problem is when I call the method in form1 each 5 seconds it's also calling and doing this getcpu every 5 seconds and those threads sleep make it work very slow. If I will set the threads sleep to 10ms it will be faster but then I get on most processes 0% or 100% usage.
public static string  getcpu(string name)
{
    var cpuload = new PerformanceCounter("Processor", "% Processor Time", "_Total");

    processes = Convert.ToInt32(cpuload.NextValue()) + "%";
    System.Threading.Thread.Sleep(1000);

    processes = cpuload.NextValue() + "%";
    System.Threading.Thread.Sleep(1000);

    processes = cpuload.NextValue() + "%";
    System.Threading.Thread.Sleep(1000);

    processes = cpuload.NextValue() + "%";
    System.Threading.Thread.Sleep(1000);

    processes = cpuload.NextValue() + "%";
    System.Threading.Thread.Sleep(1000);

    return processes;
}

A:

When measuring % Processor Time, the Thread.Sleep(1000) is required since the .NextValue() call determines the time, the processor was used since the last call to .NextValue(). For further information on this calculation, check out http://blogs.msdn.com/b/bclteam/archive/2006/06/02/618156.aspx.
A couple of suggestions:
1) Since you are passing in the name of a process, I assume you want to measure the Processor Time of a single process. But as you are not using that parameter within your method, you are measuring the overall average system processor time instead.
So if you want to measure the performance for one single process, you could use something like:
public static double GetCpuUsage(Process process)
{
    PerformanceCounter cpuCounter = new PerformanceCounter();

    cpuCounter.CategoryName = "Process";
    cpuCounter.InstanceName = process.ProcessName;
    cpuCounter.CounterName = "% Processor Time";

    // The first call will always return 0
    cpuCounter.NextValue();
    // That's why we need to sleep 1 second
    Thread.Sleep(1000);
    // The second call determines, the % of time that the monitored process uses on
    // % User time for a single processor.
    // So the limit is 100% * the number of processors you have.
    double processorUsagePercent = cpuCounter.NextValue();

    // Hence we need to divide by the number of processors to get the average CPU usage of one process during the time measured
    return processorUsagePercent / Environment.ProcessorCount;
}

Please mind the difference between "Processor" and "Process" for the counter category.
2) Why are you calling .NextValue() multiple times in a row and then return only the last value? That makes your method so slow. The two calculations shown in the example above are sufficient.
3) When you want to monitor multiple processes, you do not have to wait one second in between every call to .NextValue(). You just have to make sure that at least one second has elapsed since the last time you called .NextValue() on a specific counter. So for multiple processes you could have a method like that:
public static Dictionary<Process, double> GetCpuUsages(Process[] processes)
{
    // One performance counter is required per process
    PerformanceCounter[] counters = new PerformanceCounter[processes.Length];

    // Instantiate a new counter per process
    for(int i = 0; i < processes.Length; i++)
    {
        PerformanceCounter processorTimeCounter = new PerformanceCounter(
            "Process",
            "% Processor Time",
            processes[i].ProcessName);
        // Call NextValue once to have a reference value
        processorTimeCounter.NextValue();
        // Add it to the array
        counters[i] = processorTimeCounter;
    }

    // Sleep one second to have accurate measurement
    Thread.Sleep(1000);
    // Here we store the processes along with their measurement in a dictionary
    Dictionary<Process, double> cpuUsageDictionary = new Dictionary<Process, double>();

    for (int i = 0; i < counters.Length; i++)
    {
        // Determine CPU usage and divide by the number of cores
        double cpuUsage = counters[i].NextValue() / Environment.ProcessorCount;
        // And now we add one key/value pair per process along with its cpu time measurement
        cpuUsageDictionary.Add(processes[i],  cpuUsage);
    }

    return cpuUsageDictionary;
}


Q:

Calling a control method in an Ajax call and error for converting array to string

I'm trying to call my controller method which calls a model method in an Ajax call.
Here is my Ajax call:
        $.ajax({
                    type: "POST",
                    async: false,
                                            dataType: "json",
                    url: "<?php echo base_url('siteController/fetchEmployees') ?>",
                    success: function(data)
                    {
                        html = "

ID	FName	 LName

";
                        for (var i = 0; i < data.length; i++)
                        {
                            html = html + "

" + data[i]['ID'] + "

" + data[i]['FName'] + "

" + data[i]['LName'] + "

";
                        }
                         html = html + "

";
                         $("#resultFrm2").html(html);
                    },
                    error: function() {
                        alert('error');
                    }
                });

and my siteController has the following method:
 public function fetchEmployees()
 {
    $this->load->model('user_model');
    return json_encode($this->user_model->getAll());
}

and my Model method is as following:
public function getAll()
{
    $q = $this->db->get('users');
    if ($q->num_rows() > 0) {
        foreach ($q->result() as $row) {
            $data[] = $row;
        }
        return $data;
    }
}

but since my return in controller is an array I get the following error:
A PHP Error was encountered

Severity: Notice

Message: Array to string conversion

Do you know how I can handle this issue?
If my question is not clear please let me know which part you need more clarification?
ADDED:
I did all of your suggestions and mentioned all of my changes in here too! but now there is no out put for Ajax however if in my controller instead of return json_encode($this->user_model->getAll()); I use var_dump( json_encode($this->user_model->getAll())); I can see data in response!
Thanks

A:

EDITED:
You need to return a json array
In your ajax call set
dataType: "json"

and in your fetchEmployees() function
echo json_encode($this->user_model->getAll());

This will transmit the php array as a string which will the be turned into a javascript array when received by your ajax function.


Q:

How to operate with SQL Query Output

I'd like to do a multiple SELECT query taking the WHERE argument as the first query output
SELECT id FROM hotel where group_id != 1;

Output: 1,3,4,5,6,7,9
Now I want to take those IDs (output of the first query) and do multiple SELECTs with them
SELECT user_id FROM users where hotel_id = [1,3,4,5,6,7,9];

A:

You can use the following solution using IN (with sub-query) instead of =:
-- ignore hotel_id with NULL using IN with sub-select
SELECT user_id
FROM users
WHERE hotel_id IN (
    SELECT id
    FROM hotel
    WHERE group_id <> 1
);

-- with hotel_id NULL using IN with sub-select
SELECT user_id
FROM users
WHERE hotel_id IN (
    SELECT id
    FROM hotel
    WHERE group_id <> 1
) OR hotel_id IS NULL;

Another solution can be the following using a INNER JOIN or LEFT JOIN:
-- ignore hotel_id with NULL using INNER JOIN
SELECT users.user_id
FROM users INNER JOIN hotel ON users.hotel_id = hotel.id
WHERE hotel.group_id <> 1

-- with hotel_id NULL using LEFT JOIN
SELECT users.user_id
FROM users LEFT JOIN hotel ON users.hotel_id = hotel.id
WHERE hotel.group_id <> 1 OR users.hotel_id IS NULL;

demo on dbfiddle.uk