text:
Q: Array vs. ArrayList when position is important I'm a Java newbie with a quick Array vs. ArrayList question. I have an array of objects that can grow or reduce in size, but it's very important for me to maintain the position they were in relative to each other in the array. I'm thinking because of this I need to use Array instead of an ArrayList which can condense/shift elements around if they are removed/added.
The practical example: In my first Java application that I'm slugging through to learn the nuances of this language I'm making a basic poker game simulator. I have Player objects in an array representing the seats they are sitting at, and it's important to know where the dealer button (index) was placed before rotating it. Players being removed or added from an ArrayList will change the indices of the players, and that can throw off the next Player to get it. Dealer button movement is very player-placement specific.
Long story short - is using an Array the best way of handling elements in an array-type structure that need to maintain their position in the array? Is there a better method or logic to accomplish this? I apologize for the simple question but I couldn't find any other alternatives and wanted to confirm that this is the best route to take.
EDIT:
To further clarify, let me give an example of why ArrayList's element movement won't work:
Take three players and their indices in the array:
0 : Player One (Dealer button)
1: Player Two
2: Player Three
If player two (index one) gets up from the table before the dealer button is rotated, depending on the rules player one will keep the button and the blinds will be adjusted accordingly (there's other variants of this rule, but the one I like to use). In an ArrayList, the internal array will be condensed and player three will end up getting the button an extra round before he should. I need to track the empty seat that was active during the hand but was emptied before the round was over and the button moved.
I'm starting to realize that the concept of a "seat" is going to be more complicated, I need to track state on it, including "player just sat down while hand in progress," "player got up while hand in progress," etc.  @Stephen P - I think you're right about this, I'm going to need to track them separately and cannot use a simple array structure to determine the logic. Timing of when the elements are added and/or removed is paramount to the application logic, and simply examining if an element is there or not won't cut it.
For the Seats themselves, I'm learning towards ArrayList since the Seats will now always be there, no empties. The Seat will just have a reference to the Player object if one is sitting there as well as WHEN that player arrived. Thanks everyone!

A: With ArrayList, you can make your players sit tight by using set(int index, T value). You just have to fill the arrayList with nulls first:
List<Player> seats = new ArrayList<>(Collections.nCopies(numPlayers,(Player)null));
seats.set(2,player); // Place a player in the third chair
seats.set(1,null); // Empty the second chair

A:
Long story short - is using an Array the best way of handling elements
  in an array-type structure that need to maintain their position in the
  array? Is there a better method or logic to accomplish this? I
  apologize for the simple question but I couldn't find any other
  alternatives and wanted to confirm that this is the best route to
  take.

Position shouldn't be your most important criterion for choosing array vs. ArrayList, at least I don't believe it should be.
Arrays are covariant, and more performant most of the time.  They mix poorly (if at all) with Java generics which is really kind of a big deal a lot of the time.  You cannot create a reference to a new instance of an array of a non-reifiable type (though you can receive one, but buyer beware).
ArrayLists, as a part of the Java Collections API, are invariant.  For this reason they work much better with Java generics and, according to Joshua Bloch (Essential Java, 2nd Ed), should be favored much of the time.  ArrayLists should often be less performant (and less concise) than arrays.  Moreover, as part of the Java Collections API, ArrayLists are more flexible because they extend the List interface which enables you to change implementations from ArrayList to any other List provided that your own class that implements the List is well encapsulated (i.e. the ArrayList is not part of your class's exported API).
There are other differences, of course, but these are the ones that really stand out.  If you were really concerned about performance, you could create your own List implementation that was backed by arrays (like ArrayList is) in order to get a feature or the API contract you really wanted.  Otherwise, to me, it sounds like you should be using ArrayList (or even other Collection type such as Map (suggested)).

A: If you have a constant number of seats, you can use either an array or an ArrayAist. If you want to increase the number of seats, you will need an Arraylist, because regular arrays are immutable. See this for more information on the immutability of arrays: Why is an array's length immutable? An ArrayList will never move around its contents if you only use the get(int index) and set(int index, E element)
Also, it is bad practice to let null mean something, even if that something is nothing.
The code:
seat ArrayList initialization
List<Person> seats = new ArrayList<Person>(max_Number_Of_Seats_here);
for(Person person : seats)
{
    person = new Person("");
}
//You can then set people like this:
seats.set(seat_index_here, new Person("Darkprozac"));

And have the parameter for the constructor for the class Person be its name.
Person constructor
...
public String name;
public Person(String name)
{
    this.name = name;
...

You can then check if the Person's name is "", and if it is, skip that person:
Check if seat is empty
...
for(Person person : seats)
{
    if(person.name.equals(""))
    {
        //do nothing
    }
    else
    {
        doSomething();
    }
}
...

You can also wrap a Person in a Seat class:
Seat Class
public class Seat
{
    public Person person;
    public String state;
    public Seat(String name)
    {
        if(name.equals("");
        {
            state = "empty";
        }
        else
        {
            state = "full";
            person = new Person(name);
        }
    }
}

and then modify seat ArrayList initialization and Check if seat is empty accordingly.
Thanks to MrBackend for pointing out that I was wrong about ArrayLists initializing as null.

A: I would use a map, specifically, a TreeMap.
NavigableMap<Integer, Player> seats = new TreeMap<Integer, Player>();
Integer first = seats.firstKey();
Integer next = seats.nextKey(first);

This gives the benefits of a map, you don't have to worry about seats shifting (even accidentally), and you can still navigate seats easily.
The map manages its own storage (unlike an array) and does not have a risk of shifting indices (unlike an ArrayList).


text:
Q: Using nodejs async to process a large xml file (with relationships) I have to process a large XML file (around 25 mb in size), and organize the data into documents to import into MongoDB.
The issue is, there are around 5-6 types of elements in the xml document, each with around 10k rows.
After fetching one xml node of type a, I have to fetch it's corresponding elements of types b,c,d, etc.
What I am trying to do in node:

*

*Fetch all the rows of type a.

*For each row, using xpath, find its corresponding related rows, and create the document.

*Insert document in mongodb

If there are 10k rows of type a, the 2nd step runs 10k times. I am trying to get this to run in parallel so that the thing doesn't take forever. Hence, async.forEach seemed to be the perfect solution.
async.forEach(rowsA,fetchA);
My fetchrelations function is sort of like this
var fetchA = function(rowA) {
//covert the xml row into an object
    var obj = {};
    for(i in rowA.attributes) {
    attribute = rowA.attributes[i];
    if(attribute.value === undefined)
        continue;
    obj[attribute.name] = attribute.value;
    }
    console.log(obj.someattribute);
    //first other related rows,
    //callback inserts the modified object with the subdocuments
    findRelations(obj,function(obj){
        insertA(obj,postInsert);
    });
};

After I try to run this, the console.log in the code only runs about once in every 1.5 seconds, not parallely for every row as I expected. I have been scratching my head and trying to figure this out for the past two hours, but I am not sure what I am doing wrong.
I am not very adept with node, so please be patient.

A: It looks to me like you're not declaring and calling the callback function which async will pass to your iterator function (fetchA). See the forEach documentation for an example.
Your code probably needs to look more like...
var fetchA = function(rowA, cb) {
//covert the xml row into an object
    var obj = {};
    for(i in rowA.attributes) {
    attribute = rowA.attributes[i];
    if(attribute.value === undefined)
        cb();
    obj[attribute.name] = attribute.value;
    }
    console.log(obj.someattribute);
    //first other related rows,
    //callback inserts the modified object with the subdocuments
    findRelations(obj,function(obj){
        insertA(obj,postInsert);
        cb();  // You may even need to call this within insertA or portInsert if those are asynchronous functions.
    });
};

redpajama_set_name: RedPajamaStackExchange


text:
Q: Out of memory error, while reading large CSV file (millions of lines) in java I am getting out of memory error while reading large CSV file in java. How can I deal with this problem. I increased the heap size, I also tried using BufferedReader, but still the same problem persist. Here is my code
public class CsvParser {
    public static void main(String[] args) {
        try {
            FileReader fr = new FileReader((args.length > 0) ? args[0] : "data.csv");
            Map<String, List<String>> values = parseCsv(fr, " ", true);
            System.out.println(values);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static Map<String, List<String>> parseCsv(Reader reader, String separator, boolean hasHeader)
            throws IOException {
        Map<String, List<String>> values = new LinkedHashMap<String, List<String>>();
        List<String> columnNames = new LinkedList<String>();
        BufferedReader br = null;
        br = new BufferedReader(reader);
        String line;
        int numLines = 0;
        while ((line = br.readLine()) != null) {
            if (StringUtils.isNotBlank(line)) {
                if (!line.startsWith("#")) {
                    String[] tokens = line.split(separator);
                    if (tokens != null) {
                        for (int i = 0; i < tokens.length; ++i) {
                            if (numLines == 0) {
                                columnNames.add(hasHeader ? tokens[i] : ("row_" + i));
                            } else {
                                List<String> column = values.get(columnNames.get(i));
                                if (column == null) {
                                    column = new LinkedList<String>();
                                }
                                column.add(tokens[i]);
                                values.put(columnNames.get(i), column);
                            }
                        }
                    }
                    ++numLines;
                }
            }
        }
        return values;
    }
}

A: Do not try to build your custom parser. Your implementation will probably not be fast or flexible enough to handle all corner cases.
You should try uniVocity-parsers CSV parser to handle that for you. It comes with a built in CSV parser, which is the fastest parser among any other for java. Disclosure: I am the author of this library. It's open-source and free (Apache V2.0 license).
It is extremely memory efficient and we built a custom parser on top of its architecture to parse a 42GB MySQL dump file, with more than 1 billion rows, for this project
Here's a quick and diry example of how to use uniVocity-parsers CSV parser:
CsvParserSettings settings = new CsvParserSettings();
CsvParser parser = new CsvParser(settings);

// parses all rows in one go.
List<String[]> allRows = parser.parseAll(new FileReader(yourFile));

A: If you want to load everything in memory, you need memory.
By loading the complete file in memory you wil always have the risk of OutOfMemory errors.
If you really need all data always accessible you can start thinking of using a database. An embedded database like sqlite is easy to integrate, little overhead and is able to manage the data on disk. This way no mather how large your files are, you will not have a memory issue.

A: Memory is a limited resource so if you want to deal with large files you need to have an approach of dealing with portions of it. I suggest taking a look at RandomAccessFile and MappedByteBuffer of the NIO library. Is the best solution i can think of your problem. You can access the data of the files without loading it entirely to the memory. take a look at this link for a quick head start.

A: it's not the csv-file itself, which fills the memory up, it's the values variable which contains the "copy" of the file itself + certain object overhead.
I also saw, that you are "transposing" your original csv-file. That means, that, as other posters already mentioned, you HAVE to use some file-based storage to keep the memory fingerprint at minimum, or add more RAM to you computer and hope that it helps

A: Assuming: C columns, L lines, B characters per field, and 64-bit JVM:

*

*The data from the CSV file has roughly C×L×B characters, so it takes (32 + 24  +2×B)C×L×B bytes of memory to store all the values as strings. Consider interning them if the values repeat, or storing as UTF-8 byte arrays in (24 + B)C×L×B bytes. Or, if you feel confident, combine the two and implement an interning pool for byte arrays.

*LinkedList takes 40 bytes per node, so it's another 40×C×L bytes. ArrayLists are smaller, they take only 8 bytes per node, and also faster in almost every use case, including yours.
You need at least (96 + 2×B)×L×C bytes of memory, plus a bit of overhead. If you switch to ArrayLists and byte arrays, you should need about (32 + B)×L×C plus overhead.

A: Rather than loading it all into memory, try doing a bit at a time.
Something like a LineNumberReader or a BufferedReader should help you manage this.


text:
Q: Does a default_random_engine have a type? Well suppose i have a default_random_engine in C++ does the value he generates have a type?If so it is possible to do something like
    sum = sum + generator;
and suppose sum has a predefined type

A:
Does a default_random_engine have a type?

Yes. It is a typedef of one of the other engines.
§26.5.5

Remark: The choice of engine type named by this typedef is implementation-defined. [ Note: The
  implementation may select this type on the basis of performance, size, quality, or any combination of
  such factors, so as to provide at least acceptable engine behavior for relatively casual, inexpert, and/or
  lightweight use. Because different implementations may select different underlying engine types, code
  that uses this typedef need not generate identical sequences across implementations. — end note ]

All of the random engines export the type Engine::result_type which is the return type of Engine::result_type Engine::operator().
result_type is a typedef of the UIntType which is the first template argument.
e.g.:
std::mersenne_twister_engine<std::uint_fast32_t,
                         32, 624, 397, 31,
                         0x9908b0df, 11,
                         0xffffffff, 7,
                         0x9d2c5680, 15,
                         0xefc60000, 18, 1812433253>

In which the return type of operator() is std::uint_fast32_t.


text:
Q: Microsoft PPL parallel_for_each with boost filesystem directory_iterator using Visual Studio 2010 SP1
so i have a std::for_each iterating on lots of files using the boost::filesystem library.
since those iterations dont mess with each other i was trying to get multi threading working on it, so im trying to use VS 2010 library PPL.
old: for_each(directory_iterator(path), directory_iterator(), <lambda function>);
new: parallel_for_each(directory_iterator(path), directory_iterator(), <lambda function>);
thing is, the parallel_for_each one doesnt compile because it asks for a random access iterator or a forward access iterator which i assume directory_iterator is not.
is there a way i can make directory_iterator work in this case? maybe with a diferent iterator that i dont know about or maybe some kind of cast?
tried searching for an answer on the web, but PPL with boost isnt really that much talked yet.
thanks in advance.

A: If most of your time is spent loading files, you're only slowing yourself down by trying to load multiple files. That said, if your work is processing-bound, you could do something like this:
for each file // serial
{
    load file into memory
    spawn task to process file // concurrent
}

wait until tasks to complete

For that, you'll want to use the tasks.


text:
Q: Why does Stanford CoreNLP NER-annotator load 3 models by default? When I add the "ner" annotator to my StanfordCoreNLP object pipeline, I can see that it loads 3 models, which takes a lot of time:
Adding annotator ner
Loading classifier from edu/stanford/nlp/models/ner/english.all.3class.distsim.crf.ser.gz ... done [10.3 sec].
Loading classifier from edu/stanford/nlp/models/ner/english.muc.7class.distsim.crf.ser.gz ... done [10.1 sec].
Loading classifier from edu/stanford/nlp/models/ner/english.conll.4class.distsim.crf.ser.gz ... done [6.5 sec].
Initializing JollyDayHoliday for SUTime from classpath: edu/stanford/nlp/models/sutime/jollyday/Holidays_sutime.xml as sutime.binder.1.
Reading TokensRegex rules from edu/stanford/nlp/models/sutime/defs.sutime.txt
Reading TokensRegex rules from edu/stanford/nlp/models/sutime/english.sutime.txt
Reading TokensRegex rules from edu/stanford/nlp/models/sutime/english.holidays.sutime.txt

Is there a way to just load a subset that will work equally? Particularly, I am unsure why it is loading the 3-class and 4-class NER models when it has the 7-class model, and I'm wondering if not loading these two will still work.

A: You can set which models are loaded in this manner:
command line:
-ner.model model_path1,model_path2

Java code:
 props.put("ner.model", "model_path1,model_path2");

Where model_path1 and model_path2 should be something like:
"edu/stanford/nlp/models/ner/english.all.3class.distsim.crf.ser.gz"

The models are applied in layers.  The first model is run and its tags applied.  Then the second, the third, and so on.  If you want less models, you can put 1 or 2 models in the list instead of the three default, but this will change how the system performs.
If you set "ner.combinationMode" to "HIGH_RECALL", all models will be allowed to apply all of their tags.  If you set "ner.combinationMode" to "NORMAL", then a future model cannot apply any tags set by previous models.
All three models in the default were trained on different data.  For instance, the 3-class was trained with substantially more data than the 7-class model.  So each model is doing something different and their results are all being combined to create the final tag sequence.


text:
Q: Click on the customer and return your sales How do I click on the customer and return your sales?
That is, I want to click on the customer and that he filter that customer sales.
In fact I think I'm unable to think, because I thought the following:

*

*Customer link must be a value that when I click enters the sales page, only filtering sales.

Look what I tried, but without success.
#models.py
#views.py
class SaleList(ListView):
    template_name = 'sale_list.html'
    model = Sale
    context_object = 'sale_list'
    paginate_by = 20

...

    def get_queryset(self):
        s = Sale.objects.all()
        if self.request.GET.get('filter_sale', False):
            s = s.filter(customer='filter_sale')
        return s

#customer_list.html
...
{% for customer in object_list %}

        {{ customer.full_name }}
...

#sale_list.html
@Daniel Roseman but now it does not return all sales when I click on sales, probably because of SaleList class is unique or because of urls.
url(r'^sale/$', SaleList.as_view(), name='sale_list'),
url(r'^sale/(?P<id>\d+)/$', SaleList.as_view(), name='sale_list'),
url(r'^sale/(?P<pk>\d+)/$', SaleDetailView.as_view(), name='sale_detail'),

A: Well, firstly you need to define a URL for the sales list view that includes the ID of the customer whose details you want to see:
url(r'^sales/(?P<id>\d+)/$', SaleList.as_view(), name='sale_list'),

Then you need to provide a link in the customer list to that view:
{% for customer in object_list %}

        {{ customer.full_name }}

and then you need to filter by that ID in the queryset for the sales list view:
def get_queryset(self):
    s = Sale.objects.filter(customer=self.kwargs['id'])
    return s


text:
Q: Object at index i only showing last image In the following method:
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{

I currently have 22 of the following:
if ([[annotation title] isEqualToString:@"Arcadian Winery"]) {
    [profileIconView setImage:[UIImage imageNamed:@"arcadian.png"]];
}
if ([[annotation title] isEqualToString: @"Babcock Winery and vineyards"]) {
    [profileIconView setImage:[UIImage imageNamed:@"babcock.png"]];
}
if ([[annotation title] isEqualToString:@"Bonny Doon Vineyard"]) {
    [profileIconView setImage:[UIImage imageNamed:@"bonnyDoon.png"]];
}

I Would like to replace it with the following array but it keeps returning only last object.
 NSArray *wineryTitle = [NSArray arrayWithObjects:
                       @"Arcadian Winery",
                       @"Babcock Winery and vineyards",
                       @"Bonny Doon Vineyard",
                       @"Castoro Cellars",
                       @"Dry Creek Vineyard",
                       @"Gary Farrell Wines, Inc.",
                       @"Equinox Methode Champenoise",
                       @"Figge Cellars",
                       @"Frog's Leap Winery",
                       @"Heitz Wine Cellars",
                       @"Kathryn Kennedy",
                       @"Merryvale Vineyards",
                       @"Manzoni Estate Vineyard",
                       @"Marilyn Remark Winery",
                       @"Bernardus Vineyards & Winery",
                       @"Nickel & Nickel",
                       @"Opolo Vineyards, Inc.",
                       @"Riverbench Vineyard and Winery",
                       @"Steven Kent Winery",
                       @"Storrs Winery",
                       @"Talley Vineyards",
                       @"Thomas Fogarty Winery",
                       nil];

NSArray *wineryImage = [NSArray arrayWithObjects:
                        @"arcadian.png",
                        @"babcock.png",
                        @"bonnyDoon.png",
                        @"castoro.png",
                        @"dryCreek.png",
                        @"garyFarrell",
                        @"EquinoxMethodeChampenoise.png",
                        @"figge.png",
                        @"frogsLeap.png",
                        @"heitz.png",
                        @"kathrynKennedy.png",
                        @"merryvale.png",
                        @"manzoni.png",
                        @"mailynRemark.png",
                        @"bernardus.png",
                        @"nickelAndNickel.png",
                        @"opolo.png",
                        @"riverbench.png",
                        @"stevenKent.png",
                        @"storrs.png",
                        @"talley.png",
                        @"thomasFogarty.png",
                        nil];

for (int i = 0; i < 22; i++) {

    UIImageView *profileIconView = [[UIImageView alloc] init];

    if ([[wineryTitle objectAtIndex:i] isEqualToString:[wineryTitle objectAtIndex:i]]) {
        [profileIconView setImage:[UIImage imageNamed:[wineryImage objectAtIndex:i]]];
    }

    profileIconView.frame = CGRectMake(0, 0, 40, 33);
    pinView.leftCalloutAccessoryView = profileIconView;
    [profileIconView release];

}

return pinView;

The array is looping through the string of titles properly, but always returning only the last image to the annotation.

A: This is guaranteed to always return the last item because the condition in your if statement is always true:
if ([[wineryTitle objectAtIndex:i] isEqualToString:[wineryTitle objectAtIndex:i]]) {
    [profileIconView setImage:[UIImage imageNamed:[wineryImage objectAtIndex:i]]];
}

You're comparing [wineryTitle objectAtIndex:i] to [wineryTitle objectAtIndex:i], which always will be true.
Did you mean to compare the wineryTitle to, for example, some property of your annotation? For example, if you wanted to use the title of the annotation:
if ([[wineryTitle objectAtIndex:i] isEqualToString:[annotation title]]) {
    // do something
}

Or, if you want to take advantage of the syntax of the new compilers:
if ([wineryTitle[i] isEqualToString:[annotation title]]) {
    // do something
}

Thus yielding (putting a little more logic in the if block) something like:
for (int i = 0; i < 22; i++) {
    if ([wineryTitle[i] isEqualToString:[annotation title]]) {
        UIImageView *profileIconView = [[UIImageView alloc] init];
        profileIconView.frame = CGRectMake(0, 0, 40, 33);
        profileIconView.image = [UIImage imageNamed:wineryImage[i]];
        pinView.leftCalloutAccessoryView = profileIconView;
        [profileIconView release];
        break;
    }
}

A: btw your if conditions are all mutually exclusive. Instead of
if (...) {
    // ...
}
if (...) {
    // ...
}
if (...) {
    // ...
}

please do:
if (...)  {
    // ...
} else if (...) {
    // ...
} else if (...) {
    // ...
}

if you ever really need all this.
It'll reduce your carbon footprint.
In addition, NSArray has inspection methods that allow you to return the index of the object you're interested in. For example.


text:
Q: PHP+AJAX: How to make toggle for sorting data? I have a very simple page, where is the list of users from database. On this page is a table containing these information, with name, surname, age, city.
I would like to make a toggle, when I click on the name title and all names would be sorted as ASC and then when I click again on the name title, all names would be sorted as DESC in the real time.
Could you give me please an advice how to do that?
Thanks

A: Honestly you should consider JavaScript/jQuery for this:
Table Sorter for jQuery

A: Take a look at the Datatables Plugin for jQuery.  I use it extensively for exactly this, and it's fairly easy to implement.  The forums get pretty good response times too.


text:
Q: Select all unique combinations of a single list, with no repeats, using LINQ (Part 2) John Skeets answer to this question, Select all unique combinations of a single list, with no repeats, using LINQ, works awesomely.
However, can someone break down component by component the inner workings of how the first answer is working:
List<int> slotIds = new List<int> {1, 2, 3};
var query = slotIds.SelectMany((value, index) => slotIds.Skip(index + 1),
                              (first, second) => new { first, second });

A: It's roughly equivalent in concept to this, although the actual execution model is different of course (lazy etc):
for (int i = 0; i < slotIds.Count; i++)
{
    int first = slotIds[i];
    for (int j = i + 1; j < slotIds.Count; j++)
    {
        int second = slotIds[j];
        results.Add(new { first, second });
    }
}

The SelectMany taking a projection from value and index is a way of using both first and i to make an inner loop. We need the index so that we can skip index + 1 values, which is equivalent to the j loop starting at i + 1 in the above code.
Does that help? If not, could you pinpoint which bit is confusing?
EDIT: Aargh - I hadn't realized that the other question you were referring to started out with this code! I think it's still useful though, to give the paragraph below something to hang on...
If you understood the alternative (query expression) version of my answer, then the first version is similar, just using an overload of SelectMany which allows you to use both the value and index in the "outer" sequence.


text:
Q: Ubuntu 16.04, PHP-FPM times out at boot with libsodium-php module The Issue (Modified: with REPRO STEPS!)
To repro, spin up a new VPS with Ubuntu 16.04 (probably works with any Debian distro, but not tested) and follow these instructions:
Through experimentation I boiled down the instructions to the absolute minimum necessary to repro
apt-get install php7.0 php7.0-dev php-pear
apt-get install libsodium-dev
pecl install libsodium
echo "extension=libsodium.so" >> /etc/php/7.0/fpm/php.ini
shutdown -r 0

When I reboot the server (shutdown -r 0) PHP-FPM is dead (confirm via service php7.0-fpm status)
If I run service php7.0-fpm start, it starts up in a matter of milliseconds with no issue.
I've created an issue on the libsodium-php tracker in hopes someone can find a solution there: https://github.com/jedisct1/libsodium-php/issues/94
The Question
Now that I've narrowed down the issue, what I'm really looking for is either:

*

*A way to figure out why it's timing out (is there a good way to profile what resources are being accessed or what a boot-time process is doing?)

*A way to fix it (is there some way to alter the boot order so that libsodium boots last, in case it's a dependency issue?)
New Updates
I've continued to look into this and figured out that all of PHP is stalling during the initialization of the libsodium library (the call to sodium_init()). This call takes about 3-4 minutes to complete, and until this time has passed even a call to php -v fails.
As a workaround I have added the following to /lib/systemd/system/php7.0-fpm.service:
TimeoutStartSec=600

This causes my web server to return HTTP status code 502 for a couple of minutes after a reboot but eventually it starts working again (better than manually having to log in and fix it)
I will try to get in contact with the developers of libsodium and libsodium-php to find a better solution, however for now I believe I have solved this myself:
The Solution

*

*When something isn't running at startup, begin investigation with journalctl -u <service>

*If it's timing out, try a fresh install -- disable all extensions, modules, plugins, remove custom config, etc. If the fresh install works, enable things one at a time until you find the cause

*If you absolutely need the plugin / extension / whatever then you can increase the timeout by modifying the *.service file and adding TimeoutStartSec=...

A: The issue lies with the libsodium PHP extension. I have initiated conversation with the developer of libsodium to work on a fix. For now:
The Solution

*

*When something isn't running at startup, begin investigation with journalctl -u <service>

*If it's timing out, try a fresh install -- disable all extensions, modules, plugins, remove custom config, etc. If the fresh install works, enable things one at a time until you find the cause

*If you absolutely need the plugin / extension / whatever then you can increase the timeout by modifying the *.service file and adding TimeoutStartSec=...


text:
Q: Adding junk character in currency symbol while exporting data to CSV I am getting strange Issue that whenever I am exporting the data in csv which have a currency symbol, It has added junk extra character in the data beside the currency symbol.
For example if My data = France - Admin Fee 1 x £100
I am getting the result like = France - Admin Fee 1 x £100 when i open this in Excel. My code is :
<html>
<head>

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

var buffer = "France - Admin Fee 1 x £100";
buffer = "\"" + buffer + "\"";
// buffer = "" + euro; //"\u2034";

var uri = "data:text/csv;charset=UTF," + encodeURIComponent(buffer);
var fileName = "InvoiceData.csv";

var link = document.createElement("a");
if (link.download !== undefined) { // feature detection
    // Browsers that support HTML5 download attribute
    link.setAttribute("href", uri);
    link.setAttribute("download", fileName);
}
else if (navigator.msSaveBlob) { // IE 10+
    link.addEventListener("click", function (event) {
        var blob = new Blob([buffer], {
            "type": "data:text/csv;charset=UTF;"
        });
        navigator.msSaveBlob(blob, fileName);
    }, false);
}
else {
    // it needs to implement server side export

}
link.innerHTML = "Export to CSV";
link.click();
}
</script>
</head>
<body>
<input type="button" value="Download CSV" onclick="CreateCSV()" />
</body>
</html>

When i open the same in notepad. I cannot see the junk character. I am very thankful if you can get me a work around.

A: The character set should probably be UTF-8. Also check the unicode for the £, I do believe it is u2034. You can find a chart here, and it lists it as U+00A3. If you have something more advanced than just Notepad, like Notepad++ for example, check the encoding type when you open the time. Excel can be finicky.


text:
Q: RestSharp XML DOCTYPE error when request is in JSON I've been trying to use RestSharp Library in order to make requests, but when I've tried to make a POST request this error keeps emerging!!

Here is the code:
private readonly string contentType = "application/json";

try
{
    var restClient = new RestClient(new Uri(InvoiceExpressURLS.URL_createClient));

    string clientJsonRequest =
    JsonConvert.SerializeObject(
        JsonConvert.DeserializeObject("{\"client\":" + JsonConvert.SerializeObject(newClient) + "}")
    );

    var request = new RestRequest(Method.POST);
    request.RequestFormat = DataFormat.Json;
    request.AddHeader("Content-Type", contentType);
    request.AddJsonBody(clientJsonRequest);

    var restResponse = await restClient.ExecuteTaskAsync<object>(request);
    if (restResponse.IsSuccessful)
    {
        response.responseObject = restResponse.Data;
        response.responseMessage = string.Format("The client \"{0}\" was successfuly created.", newClient.name);
    }
    else
    {
        response.responseStatus = restResponse.StatusCode;
        response.responseMessage = restResponse.ErrorMessage;
    }
}
catch (Exception e)
{
    response.responseStatus = HttpStatusCode.InternalServerError;
    response.responseMessage = e.Message;
    response.responseObject = e;
}


text:
Q: ajax not work on firefox but works on chrome i am trying to insert to database using ajax. it works on chrome but does work on firefox. pls i need your help.here is my code
i got these on the console
Use of inputEncoding is deprecated.

 FormData { }

This my script
$(document).ready(function() {
$('.comment-block').load('connection/profile_comment.php');
$("#pcom").on('submit', function(e){
    e.preventDefault();
    var myForm = new FormData($(this)[0]);
    console.warn(myForm);
    $.ajax({
        type:'POST',
        url: 'connection/profile_comment.php',
        data : new FormData($(this)[0]),
        cache: false,
        contentType:false,
        processData: false,
        beforeSend: function(){
            $("#loading").show().fadeOut(5000);
        },
        success: function(data){
            //$('.comment-block').load('connection/profile_comment.php');
            console.log(data);
            $("#loading").hide();
            $("#success").show().fadeOut(5000);
            $("#pcom").find("#profile_comment").val("");
            $('.comment-block').html(data);
        },
        error: function(data){
            $("#error").show().fadeOut(5000);
        }
    });
});
});

and connection/profile_comment.php
    if (isset($_POST['pcomment']))
    {
    $comment=$_POST['profile_comment'];
    $student_id=$_POST['student_id'];
    $sendcomment=$dbh->prepare("INSERT INTO profile_comment (student_id,  commenter_id, comment) VALUES (:student_id,:commenter_id,:comment)");
    $sendcomment->bindParam(':student_id', $student_id);
    $sendcomment->bindParam(':commenter_id', $user_id);
    $sendcomment->bindParam(':comment', $comment);
    $sendcomment->execute();
    }

A: First fix this:
$("#pcom").on('submit', function(){
    return false;

To this:
$("#pcom").on('submit', function(event){
        event.preventDefault();

If doesn't work, add this next to last code (before $.ajax(... ):
var myForm = new FormData($(this)[0]);
console.warn(myForm);

And tell us what is showed on console


text:
Q: How to derive group velocity dispersion (GVD)? I'm trying to arrive to the following expression to group velocity dispersion:
$$\text{GVD} = \frac{\lambda^3}{2 \pi c^2} \frac{d^2n}{d \omega^2}.$$
I know that GVD can be expressed as:
$$\text{GVD} = \frac{d}{d\omega}\left( \frac{1}{v_g} \right)$$
where
$$\frac{1}{v_g} = \frac{dk}{d\omega}
\\k = \frac{\omega}{c} n(\omega)
\\\omega = \frac{2\pi c}{\lambda}$$
and the refraction index depends on the wavelength.
How can I arrive at the first GVD expression knowing the others?

A: I believe there should be a second derivative of refractive index with respect to the wavelength in the GVD definition as otherwise the values would look different.
As you have already indicated, inverse of the group velocity is defined $\frac{1}{v_{g}} = \frac{dk}{d \omega}$ and $k = \frac{\omega n(\omega)}{c}$. Therefore, we can find the value by performing the derivation with a product rule:
$$ \frac{dk}{d \omega} = \frac{1}{c} \left(n(\omega) + \frac{dn(\omega)}{d\omega}\right)  = \frac{1}{v_g}\tag{1}$$
However, at the end, we want everything to be expressed in wavelength so we apply the chain rule:
$$ \frac{dn}{d\omega} = \frac{dn}{d\lambda_{0}} \frac{d\lambda_{0}}{d \omega}\tag{2}$$
We know that wavelength in the vacuum is related to the angular frequency $\lambda_{0} = \frac{2\pi c}{\omega}$ and we can find the derivative with respect to the angular frequency:
$$\frac{d\lambda_{0}}{d \omega} = \frac{-\lambda_{0}^{2}}{2\pi c} \tag{3}$$
Substituting $(3)$ into $(2)$ and then into $(1)$ we obtain:
$$\frac{1}{v_g} = \frac{1}{c} \left(  n(\lambda_{0}) - \lambda_{0} \frac{dn}{d \lambda_{0}} \right) \tag{4}$$
So now for the group velocity dispersio we have: $\mathrm{GVD}=\frac{d}{d \omega}(\frac{1}{v_{g}})$. Again, we need to apply the chain rule to obtain the correct variable:
$$ \frac{d}{d\omega} = \frac{d}{d\lambda_{0}} \frac{d\lambda_{0}}{d \omega} \tag{5}$$
Now, by having $(4)$, $(5)$ and GVD definition, we combine everything and apply the product rule:
$$ \mathrm{GVD} = \frac{d}{d \omega} \left( \frac{1}{v_{g}} \right) = \frac{-\lambda_{0}^{2}}{2\pi c} \frac{d}{d \lambda_{0}} \left[ \frac{1}{c} \left( n(\lambda_{0}) - \lambda_{0} \frac{dn(\lambda_{0})}{d\lambda_{0}}\right ) \right] = \frac{\lambda_{0}^{3}}{2\pi c^{2}} \frac{d^{2}n(\lambda_{0})}{d \lambda_{0}^{2}}$$


text:
Q: Using survfit object's formula in survdiff call I'm doing some survival analysis in R, and looking to tidy up/simplify my code.
At the moment I'm doing several steps in my data analysis:

*

*make a Surv object (time variable with indication as to whether each observation was censored);

*fit this Surv object according to a categorical predictor, for plotting/estimation of median survival time processes; and

*calculate a log-rank test to ask whether there is evidence of "significant" differences in survival between the groups.

As an example, here is a mock-up using the lung dataset in the survival package from R. So the following code is similar enough to what I want to do, but much simplified in terms of the predictor set (which is why I want to simplify the code, so I don't make inconsistent calls across models).
library(survival)

# Step 1: Make a survival object with time-to-event and censoring indicator.
# Following works with defaults as status = 2 = dead in this dataset.
# Create survival object
lung.Surv <- with(lung, Surv(time=time, event=status))

# Step 2: Fit survival curves to object based on patient sex, plot this.
lung.survfit <- survfit(lung.Surv ~ lung$sex)
print(lung.survfit)
plot(lung.survfit)

# Step 3: Calculate log-rank test for difference in survival objects
lung.survdiff <- survdiff(lung.Surv ~ lung$sex)
print(lung.survdiff)

Now this is all fine and dandy, and I can live with this but would like to do better.
So my question is around step 3. What I would like to do here is to be able to use information in the formula from the lung.survfit object to feed into the calculation of the differences in survival curves: i.e. in the call to survdiff. And this is where my domitable [sic] programming skills hit a wall. Below is my current attempt to do this: I'd appreciate any help that you can give! Once I can get this sorted out I should be able to wrap a solution up in a function.
lung.survdiff <- survdiff(parse(text=(lung.survfit$call$formula)))
## Which returns following:
# Error in survdiff(parse(text = (lung.survfit$call$formula))) :
# The 'formula' argument is not a formula

A: As I commented above, I actually sorted out the answer to this shortly after having written this question.
So step 3 above could be replaced by:
lung.survdiff <- survdiff(formula(lung.survfit$call$formula))

But as Ben Barnes points out in the comment to the question, the formula from the survfit object can be more directly extracted with
lung.survdiff <- survdiff(formula(lung.survfit))

Which is exactly what I wanted and hoped would be available -- thanks Ben!


text:
Q: mysqldump not found in jenkinsfile When I used mysqldump command in Jenkinsfile of Gogs (git) to backup my database, I got an error in Jenkins build says that mysqldump not found, even I build first mysql container. Anyone can help ?
Thanks,
Mahmoud

A: Do you have mysql client on your jenkins server?
Maybe when you builded your projec with jenkins it not foud a mysqldump in your jenkins server, then you will need to install the mysql client to use mysqldump, to install mysql client you can use these line:
sudo apt-get install mysql-client-5.1


text:
Q: Curvature and Riemannian metric Hi all,
I am going to give a talk in a seminar about the general theme 'sum of squares'. My interests lie in Differential Geometry, so I recalled that the curvature is a local invariant, an obstruction to the metric being locally a sum of squares of coordinate differentials.
Can some people suggest me some good books which clearly illustrate the relation between the curvature and the metric? Also, do you guys have other suggestions about 'sum of squares' in Geometry? Thanks a lot!

A: This is maybe late for your seminar, but a classical textbook about Riemannian geometry, including relations between curvature and metric tensor, with any signature, is
Riemannian geometry by L.P.Eisenhart
Another very interesting book for you could be
Spaces of constant curvature by J. A. Wolf
Indeed, it seems that you are searching for the Riemannian manifolds whose metric element can be written as sum and/or difference of squares of coordinate differentials. This implies that the curvature is constant and equal to 0. As shown in Wolfs'book, this can be locally realized by several manifolds with different "global geometry". As example in dimension 2, $ds^2=dx^2+dy^2$ can be realized on the (Euclidean) plane, on the cylinder, on the torus, on the Moebius strip and on the Klein bottle, while $ds^2=dx^2-dy^2$ on the (Minkowski) plane, on the torus and on the Klein bottle.


text:
Q: How can I check if a publishing page exists before creating it by code in sharepoint? I got this code
PublishingPage newPage = pWeb.GetPublishingPages().Add(fileName, layout);
                        newPage.Title = title;

However if the page exists it throws an exception and I want to check easily if it exists before

A: You could try this :
SPWeb web = properties.Feature.Parent as SPWeb;
PublishingWeb pWeb = PublishingWeb.GetPublishingWeb(web);
foreach (PublishingPage page in pWeb.GetPublishingPages())
{
    if (page.Name.Equals("myPage.aspx"))
    {
        // Do your stuff here
    }
}

Or if you find it's not fast enough you could try this:
pWeb.GetPublishingPages().ToList().Find(x => x.Name.Equals(filename))


text:
Q: Fragment still visible after pressing the back button I want to have a Fragment which provides the ability to create someting.
After that i want to show the new "someting" in another fragment. After pressing the back button on the device i want to go back to the MainFragment and not to the CreateFragment (this works well). But after that the ShowFragment is still visible.
Here is my code:
In my MainActivity i got a MainFragment which has a button "Create".
After tap the button i load a "Create" Fragment.
fragmentManager.beginTransaction()
           .replace(R.id.container, CreateFragment.newInstance())
           .addToBackStack("Create")
           .commit();

If the user has entered some details he taps the "Ok" Button. This fires the following on the MainActivity.
fragmentManager.beginTransaction()
            .replace(R.id.container, ShowFragment.newInstance(id))
            .commit();

So far so good, but here comes the problem.
If the user taps the back button on the device he gets back to the MainFragment BUT the ShowFragment is still visible (under the MainFragment).
Update
This is what happens:
MainFragment > CreateFragment > ShowFragment > (BACK Button) > MainFragment (ShowFragment in the back)

A: Just pop the ShowFragment from the stack on the onBackPress Event as below:
@Override
public void onBackPressed() {
    final Fragment fragment = fragmentManager.findFragmentById(R.id.container);
    if (fragment != null) {
        fragmentManager.popBackStack();
    } else {
        super.onBackPressed();
    }
}

A: Press the back button of fragment ShowFragment within your ShowFragment fragment will call the onBackPressed() method. Then when you call method popBackStack(), it will return you back to the CreateFragment.
Sample code -
public void onBackPressed()
{
  FragmentManager fm = getActivity().getSupportFragmentManager();
  fm.popBackStack();
}

See the post how-to-back-to-previous-fragment-on-pressing-manually-back-button-of-indivisual-fragment for more info with similar situation.


text:
Q: In Karate DSL, calling a javascript file returns java.lang.RuntimeException I have a javascript file I want to call. contents are below. When I tried calling the file, I keep getting a "no variable found with name: response" even though there is clearly a variable defined. The file executes fine within command-line using node so the javascript function is valid. Any thoughts? I attached the error message in a screenshot.
Javascript content in snippet below.
Karate script:
Scenario: Call JavaScript:
    * def sample = read('classpath:reusable/gen-data.js')

    * print someValue

function createTestData(sampleJson, fieldsToChange, numRecords) {
    var testData = [];

    for (var i = 0; i < numRecords; i++) {
        var copy = JSON.parse(JSON.stringify(sampleJson));

        fieldsToChange.forEach(function(fieldToChange) {
            copy[fieldToChange] = copy[fieldToChange] + i;
        });

        testData.push(copy);
    }

    return {content: testData};
}

var testData = {

  "country": "US",
  "taskStatusCode" : "Closed",
  "facilityCode" : "US_203532",

};

function getTestData() {

  String testData = JSON.stringify(createTestData(testData, ["taskStatusCode", "facilityCode"], 1), null, 1);

  console.log("all done getTestData()");
  console.log("test data: \n" + testData);

  return testData;
};

console.log("calling getTestData()");
getTestData();

A: I think this error is thrown when the JavaScript is not correct. For example in my case this JS file:
/* Set the custom authentication header */
function fn() {
    var authToken = karate.get('authToken');
    var out = {};
    out['Auth-Token'] = authToken
    return out;
}

This file will produce the "no variable found with name: response".
The reason is because "the right-hand-side (or contents of the *.js file if applicable) should begin with the function keyword." according to the karate docs (link).
Now by moving the comment and making the function keyword the first bit of text it works as expected:
function fn() {
/* Set the custom authentication header */
    var authToken = karate.get('authToken');
    var out = {};
    out['Auth-Token'] = authToken
    return out;
}

In the OP, the function keyword is the first thing in the file, but there is javascript outside the original function -- which I don't think is legal for karate syntax. In other words, everything has to be in the outer function.

A: My workaround was to use java instead of JavaScript.


text:
Q: How to solve limit whose function uses another function as a parameter? I am given the limit bellow. How do I solve this problem? I am thrown off by the f(f(x)). I believe the answer is -2 but am not sure and would like an explanation.

A: If $x \le -2$ then $f(x) = 2$.  And $f(2) = -1$.
For any $\epsilon > 0$ if $\delta = 1$ then $|x-(-3)| < \delta \implies -4 < x < -2\implies f(x) = 2 \implies f(f(x)) =-1$ and $|f(f(x)) - (-1)| = |f(2) - (-1)| = |(-1)-(-1)| = 0 < \epsilon $.
And that is the very definition of $\lim\limits_{x\to -3} f(f(x)) = -1$.


text:
Q: Is there a way to allow a `unique` key to be the same on a max of 3 records? Is there a way to allow a unique key to be the same on a max of 3 records?
I have a table with urls in it. I don't want my program to put the same url in more than three records. It has a reason for three, but any more is too much. Any idea how I can make that happen?

A: Are the URLs coming from a normalized URL table and hence you just have UrlIDs in this table, or is this the source table for URLs? The distinction here is important because you are implying that, in the case of this table being the source of the URLs (which it sounds like it is), you are planning on creating a UNIQUE Constraint or Index on the URL field. Even if they did allow for specifying the number of allowed entries per distinct value, this plan still wouldn't work due to indexes only allowing up to 900 bytes. A lot of URLs are way over that limit, and considering that you should be using NVARCHAR to store the URLs (since they can have Unicode characters in them, even if that is somewhat rare, hence you should also enable DATA_COMPRESSION if you are using Enterprise Edition and SQL Server 2008 or newer) that is only 450 (generally speaking) characters, which is even more limiting.
You should create an AFTER INSERT, UPDATE trigger to enforce this rule. Using a trigger will allow you to enforce this rule regardless of the source of the INSERT or UPDATE, whereas putting this logic into stored procedures is not guaranteed to catch all attempts to insert or update the table, especially ad hoc queries.
In terms of performance, depending on how many rows this table will have over time, it certainly will slow things down a little to have to do this check each time. You should find ways to narrow down a subset of the data for faster searching so that you don't hold up all INSERT and UPDATE queries. Some things to consider:

*

*Normalize the URLs out to another table. URLs can be up to 2048 characters (I believe) so if you know that you will generally have repeats, create a separate URL table that will have the unique URLs and just place a UrlID in this table. Then you can easily index the UrlID Foreign Key field. This approach will save tons of disk space, make the trigger much faster, and actually make most queries (especially those that don't need the URL text) against this table faster as you will be fitting many more rows on each data page.

*If you need to keep the URL in this table, add a UrlHash VARBINARY field and populate that with the result of HASHBYTES. The UrlHash field can also be indexed in which case you could consider adding the Url field to that index as an INCLUDE column (which doesn't have the 900 byte limit, but also is not sorted and has no statistics). Then your trigger can search on the HASHBYTES value of the incoming value and any entries that match would then compare the full URL text. Yes, you need to compare both in the case where the hash value matches since there can be collisions on the hash values across different source strings. But it would help you easily eliminate non-matches which should be the vast majority of the time.
This UrlHash field should be a non-Persisted Computed Column (and indexed as noted above). This will ensure that the hash value is always in sync with the source string. The reason for "non"-Persisted is that being PERSISTED is not required for that value to be in the index, and the value is only needed for the index, so there is no reason to take up the extra space. Please see the MSDN documentation for Indexes on Computed Columns for more details, if interested.


text:
Q: Transfer specific data from 1 datatable to another error How can I transfer the contents of one of my Datatable to a new Datatable? I am filtering out the contents of my Datatable as the filtering would work when I check on certain checkboxes. So what I did was to do this:
//dt & dt2 are Datatables, dt has all of the data and dt2 is a blank Datatable
string fieldcheck=  "2"
for (var f = 0; f < dt.Rows.Count; f++ )
{
    if (dt.Rows[f]["nameID"].ToString() == fieldcheck)
    {
        dt2.Rows.Add(dt.Rows[f]);
    }
}

But an error is saying that the row already belongs to another table. How can I transfer the specific row to the empty Datatable?

A: You cannot add a DataRow to a DataTable that belongs to another DataTable. Note that every row reference it's table via Table property.
You either have to add them manually by copying all fields or use DataTable.ImportRow:
dt2.ImportRow(dt.Rows[f]);

Another approach for your requirement is using Linq-To-DataTable which can simplify your code:
var matchingRows = dt.AsEnumerable()
    .Where(r => r.Field<string>("Name") == fieldcheck)
DataTable dt2 = matchingRows.Any() ? matchingRows.CopyToDataTable() : dt.Clone();

Note that CopyToDataTable  throws an exception if there is no matching row. That's why i've used the conditional operator and DataTable.Clone as fallback value which creates an empty table with the same schema.


text:
Q: Dynamic Sender Profile randomly works This is such a strange case. I created a dynamic sender profile which randomly shows the right sender and otherwise shows the default one. I will tell you step by step what I did:

*

*Creating a journey with entry event: API Event.

*Created a Data Extension with NO primary key, because there is no unique value in this data extension. And added the right fields containing the following fields: CreatedByName and CreatedByEmail.

*Salesforce API call which sends all the data needed to the created data extension including the two fields named above.

*Email is created with a HTML block with customer key: "e-signature-reminder" and contains the following code:

%%[
var @fromName, @fromEmail
   set @fromName = AttributeValue("CreatedByName")
   set @fromEmail = AttributeValue("CreatedByEmail")
]%%

*

*Sender profile is created as follows:

From Name:
%%[ContentBlockByKey("e-signature-reminder")]%%%%=v(@fromName)=%%

From Email:
%%[ContentBlockByKey("e-signature-reminder")]%%%%=v(@fromEmail)=%%

*

*Within the journey added the email with the HTML block. As Sender Profile, I select the sender profile which i just created.

*Activated the journey.

The result is random. Sometimes it shows me the: populated fields CreatedByName and CreatedByEmail and sometimes it doesn't. The email addresses which appear in the CreatedByEmail field are email addresses part of the validated domain so no problems there. What do i do wrong?

A: Is this DE associated to allcontacts (Contact Builder)?This happens when your association with the subscriberkey is 1 to N, so SFMC will populate the first result they find in the DE.
It happens the same with the filter criteria when you use a data extension as a entry of a Journey


text:
Q: Single Connection object at a time Basically i just want work only single sql connection at a time, wait other connection until first close.
Class myConnection
{
        private static Connection con=null;
        public void getConnection()
        {
            con= DriverManager.getConnection("jdbc:sqlite:"
                    + properties.getProperty("sqliteDatabase"));
        }
        public void closeConnection()
        {
         con.close();
        }
        public static void main(String s[]){
           myConnection m1=new myConnection();
           m1.getConnection();
          //m1 object using con variable
           myConnection m2=new myConnection();
          //m1.still executing query using con object
          m2.getConnection();
          //i should not allow m2 access con object till con object is null
}

i know it is not a right program. i just tried to explain what i want to do.
In short, i want single connection should work, wait another until connection is close.

A: I suggest to use http://commons.apache.org/proper/commons-dbcp/ for this purpose
BasicDataSource ds = new BasicDataSource();
ds.setUrl(url);
ds.setMaxActive(1);

now only one thread can get a connection from pool, others will block

A: You can create pool of Connection object with size 1. For example have : ConnectionProvider class.

A: Implement signleton pattern on Connection Class.
 Class myConnection
{
        private static Connection con=null;
        public synchronized void getConnection()
        {
            con= DriverManager.getConnection("jdbc:sqlite:"
                    + properties.getProperty("sqliteDatabase"));
        }
        public synchronized void closeConnection()
        {
         con.close();
        }
        public static void main(String s[]){
           myConnection m1=new myConnection();
           m1.getConnection();
          //m1 object using con variable
           myConnection m2=new myConnection();
          //m1.still executing query using con object
          m2.getConnection();
          //i should not allow m2 access con object till con object is null
}

Synchronized method can be called once at a time, No two objects can call synchronized method at the same time, If they call then one will have to wait for other.


text:
Q: How to measure http timing in .NET Core? CURL is the powerful tool to run the http test on the API endpoint and it provides details timing measurement like lookup, connect, appconnect, pretransfer,starttransfer
How do we capture the similar measurement in .NET Core Web API? we use the system.Net.HttpClient to make a call between two service. Is there any way to capture the details of the response time?


text:
Q: using jquery to manipulating html table in Bootstrap, isn't working I have a table on a site I am working on. I used Bootstrap 3 for styling and navigation. I need to add data using jQuery, and to be able to do live searching once it has some data in it. Adding data dynamically doesn't seem to work for me in this case(or i cant make it work!!)
Here is the sample code, both html and jQuery:
html

                <form class="form-inline" role="form">

                            <input class="form-control " type="number" id="minAge" placeholder="Min.">

                            <input class="form-control " type="number" id="maxAge" placeholder="Max">

                </form>

              ..
              ..
              ..

                            Name
                            Age

              ..
              ..
              ..

jQuery
 var people = [
        {name: "person1", age: 15},
        {name: "person2", age: 17}
       ];

var rows = [],
        $minValue = $("#minAge"),
        $maxValue = $("#maxAge"),
        $table = $("#filter-table");

function createRows() {
        people.forEach(function(person) {
            var $row = $("

");
            $row.append($("	").text(person.name));
            $row.append($("	").text(person.age));

            rows.push({
                person: person,
                $element: $row
            });
        });
    }
function addRowToTable() {
        var $tbody = $("

");
        rows.forEach(function (row) {
            $tbody.append(row.$element);
        });

        $table.append($tbody);
    }

A: try to use
jQuery('selector')

instead
$('selector')

A: Checkout out this js fiddle - http://jsfiddle.net/ndjuhjed/
The only thing I changed were your variable names, like $minValue to minValue. And it works, i.e. the values are added to the table. In jquery/javascript variable names should be simple descriptive names. You don't need the $ prepended to it. That pattern is used in PHP.
On another note, if you are looking for live html table filtering you might wanna use jquery plugins like - https://datatables.net/

A: $minValue = $("#minAge");
if you want to get the value of "#minAge", you may do this
$minValue = $("#minAge").val();

A: Thanks for your answers, The code above will work correctly if form tags are removed from the code.
**<form class="form-inline" role="form">**

           <input class="form-control " type="number" id="minAge" placeholder="Min.">

           <input class="form-control " type="number" id="maxAge" placeholder="Max">

**</form>**


text:
Q: Android onInterceptTouchEvent, get childs in ViewGroup I have a layout(like board) like this that contains cells(buttons)
| A | B | C | D |
-----------------
| E | F | G | H |
-----------------
| I | J | K | L |
-----------------
| X | Y | Z | W |

I'm adding Cells programmatically, they contains letters I set.
public void addCells(String letters){
    removeAllViews();
    int let = 0;
    for (int j = 0; j < 4; j++){
        for (int i = 0; i < 4; i++){
            String currentLetter = ""+letters.charAt(let);
            //Cell object that contains it's position and letter.
            Cell cell_ = new Cell(this.getContext(), new Point(i , j), new Letter(currentLetter));
            this.addView(cell_);
            this.cells[i][j] = cell_;
            let++;
        }
    }
}

My aim is connecting cells by finger moving like this:

I'm returning true from onTouchEvent() so I can capture all touchs in ViewGroup onInterceptTouchEvent()
public boolean onTouchEvent(MotionEvent motionEvent) {
    return true;
}

But I couldn't get the logic. How can I access a certain child object by click/touch in that ViewGroup?
When I click to 'A' letter, I want to access that cell object.

A: In general:

*

*The parent view intercepts all touch events (x,y)
onInterceptTouchEvent() { return true; }

*On touch event, the parent finds the inner view that match the event location
onTouchEvent() { // see below }

*Perform action on that view (Light it up, update data, etc)

How the parent can find the inner view?
You can do it in 2 ways,
1) Have a data structure ([][]) for the board that holds a reference to the cells views. Then you know what is the touch event X,Y so if all cells are equal simply calculate the correct cell based on the cells size and location.
View[][] board;
// Add the Views to the board in creation loop

int cellWidth = board[0][0].getMeasuredWidth();
int cellHeight = board[0][0].getMeasuredHeight();

int tragetX = (int)(x / cellWidth);
int targetY = (int)(y / cellHeight);

View targetCell = board[targetX][targetY];

// Do something with targetCell

2) Iterate on all the parent children (last to first is best), and calculate the child view location inside the parent location and with combination of it's size determine if that child is the target or not.
View targetChild = null;
int[] loc = new int[2];
for (int i = getChildCount()-1; i >= 0; i--) {
    View child = getChildAt(i);
    child.getLocationInWindow(loc);
    if (x >= loc[0] && x <= loc[0]+child.getMeasuredWidth() &&
        y >= loc[1] && y <= loc[1]+child.getMeasuredHeight()) {
        targetChild = child;
        break;
    }
}
// Do something with targetChild

The above is an example, please write a better code :) (reuse loc, etc...)


text:
Q: Clyther-how to get started? I don't get what Clyther is or how to use it.
My stuff:
  ATI OpenCl SDK (just dl'd)
  clyther beta (just dl'd)
  windows 7 pro 64 bit
  active python 3.1.2
  Xfxs Ati radeon 5850 video card
I downloaded the ATI OpenCl SDK and the clyther beta from sourceforge. Then I tooke the sample 'reduce' function from the sourceforge documents and pasted the code into notepad and named it clythersample.py.  When I double-click the file or open it in the interactiveshell, it gives an error message on the first line.
Is naming the file .py wrong? I guess clyther is its own lqnguage and not really python? Can I write python code and in the middle of the program, write a chunk of clyther code? Will python IDEs (esp. Wing understand and debug it?) Will it work with python 3 or do I need 2.6?  Is 64 bit os ok?
(I'm not a programme or technically competent, so things like its a python API for OpenCl or it had C bindings for python don't mean a whole lot).

A: Clyther is a Python package for High-Performance Computing (HPC) using, for example, video cards with multiple Graphics Packaging Units (GPUs) or (less frequently) multi-core processors.  Clyther is for parallel processing of algorithms or data sets that would normally take a lot of time to process serially.  Meaning, if you have a problem that can be split into many smaller problems, then Clyther is a useful package to use.  Additionally, your problem must be something that can use numpy arrays.
Clyther is a nice package to use if you have the problem it is intended to solve.  It makes it fairly easy to write Python code to run on multiple processes.
If that's not the problem you need to solve, then Clyther probably won't help you.

A: When you name the file .py (the file extension associated with python.exe) and double-click it, how is windows supposed to know it's supposed to run the file with CLyther?

Is naming the file .py wrong? I guess clyther is its own lqnguage and not really python?

Documentation compares it with Cython - so I suppose it's an extension to the language, i.e. they take Python and bolt more features on it.

Can I write python code and in the middle of the program, write a chunk of clyther code?

From the goals of the project, it should (like Cython) ultimately be able to accept all or most Python code. So, yes - but of course you'd have to run the whole program with CLyther.

Will python IDEs (esp. Wing understand and debug it?)

Not natively, I suppose.
Side note: The project is in a very early stage of developement (very first beta-release), so don't expect things to run smoothly right now.


text:
Q: Eclipse "This selection cannot be launched and there are no recent launches" processing error I've been trying to do processing in eclipse by downloading processing and running it with eclipse. Every time I try to run anything it says "This selection cannot be launched and there are no recent launches" I've looked around for the same problem but none of them are for processing and mostly just for default java or android I've tried to make a run configuration but to no avail.
code
import processing.core.PApplet;
import processing.core.PImage;

public class processing extends PApplet
{
PImage background;
PImage paddleImage;

public void setup()
{
    size(800, 600);
    background = loadImage("background.png");
    paddleImage = loadImage("paddle.png");
}
public void draw()
{
    background(background);
}
public class Paddle
{
    PImage sprite;
    float xPos;
    float yPos;

    public Paddle(PImage paddleSprite, float xStart, float yStart)
    {
        sprite = paddleSprite;
        xPos = xStart;
        yPos = yStart;
    }
}
}

A: If you're running in eclipse, you need a main() method.
public static void main(String... args){
    String[] pArgs = {"MySketch"};
    MySketch mySketch = new MySketch();
    PApplet.runSketch(pArgs, mySketch);
}

This code assumes you have a class named MySketch that extends PApplet.


text:
Q: How to force-update the container image of a Container Action? I went through the following steps to create a container action:
https://docs.github.com/en/free-pro-team@latest/actions/creating-actions/creating-a-docker-container-action
It uses this code to create the image:

After 1st run, the workflow creates an image, and then the workflow uses the same image created, so the workflow runs much quicker.
The problem is that when I change the files inside the container (for example entrypoint.sh in the example link above), the container image is not being updated. It keeps using the older version of the file inside the outdated image.
How to force-update the container image of a Container Action?


text:
Q: union between two has_many associations I use rails 4.1 with Postgres and I have a model like this one:
class User < ActiveRecord::Base
  has_many :events
  has_many :event_memberships
  has_many :shared_events, through: :event_memberships, source: event

  def all_events
    #... code goes here
  end
end

I'd like to do an union between events and shared_events associations but I can't make it work.
The only thing I can make it work is this:
def all_events
  events + shared_events
end

But it will execute 2 SQL queries instead of one and I won't be able to order or limit the results.
I have also tried something like this:
def all_events
  User.find_by_sql("(#{events.to_sql}) UNION (#{shared_events.to_sql})")
end

Or this method https://coderwall.com/p/9hohaa
But both methods throw this error:
PG::UndefinedParameter: ERROR:  there is no parameter $1

That seems to be known bug in rails 4+ and it won't be resolved https://github.com/rails/rails/issues/13686
So my only option here seems to write plain old SQL.
Anyone with a better idea ?


text:
Q: Scheduled Task 'hangs' and blocks Octopus when it is trying to disable the task In our organization Octopus is used to deploy on-premise web applications and background tasks on a Windows Server. During deployment Octopus disables all scheduled tasks before deploying several console applications as scheduled tasks.
We have a long standing problem with Octopus being unable to disable the scheduled task because according to the status the task is 'running'. Although the status is 'running' we can see in the logging the console application has finished it's process and stopped running but the task still keeps the status 'running' for a long time (console app finishes in seconds but the task stays open for more than 10 minutes, sometimes 50 minutes or more).
The deployment of Octopus is blocked because of the 'running' state of the task. The weird thing here is that at the moment you open the Scheduled Task Manager the task suddenly finishes and Octopus continues it's deployment process with the next step.
This problem makes quick deployments impossible. Has anyone seen this kind of behavior before and found a solution for it?


text:
Q: How to go to Grid view directly when SQL is executed in TOAD? I have this issue which is really annoying.
When I run a query in TOAD (version 11.5.1.2), it shows the result in Script Output tab, and then within its child Output tab.
The Output tab shows unformatted data, like this:
EMPLOYEE_AWARD_ID   AWARD_ID EMPLOYEE_ID INVESTED_AMT_ANNUAL INVESTED_AMT_CLIFF
----------------- ---------- ----------- ------------------- ------------------
MATCHING_AMT_ANNUAL MATCHING_AMT_CLIFF INVESTED_SHARES_ANNUAL
------------------- ------------------ ----------------------
INVESTED_SHARES_CLIFF MATCHING_SHARES_ANNUAL MATCHING_SHARES_CLIFF
--------------------- ---------------------- ---------------------
MATCHING_SHARES_FRAC_AMT INVESTED_SHARES_FRAC_AMT TOTAL_INVESTED_DIVIDEND_SHARES
------------------------ ------------------------ ------------------------------
TOTAL_MATCHING_DIVIDEND_SHARES TSR_SHARES EPS_SHARES TSR_AMOUNT EPS_AMOUNT
------------------------------ ---------- ---------- ---------- ----------
            16813        103         450                   0                  0
                  0                  0                    182
                    0                    182                     0
                       0                        0                              0
                             0          0          0          0          0

1 row selected.

I want to make TOAD open the Script Output -> Grid 1 tab by default, whenever I run a query, because this tabl shows the result in the form of a grid ... Or it should open Data Grid tab instead, which also shows the result in a data grid.
Anyone know how to do this ?
Currently I have to manually switch to the Grid 1 or Data Grid tab manually, everytime I run a query, and this very annoying ! :(

A: Found it!
Instead of hitting F5 to execute your SQL statement, instead press the "green arrow head" icon to execute the statement.
I have the default layout and this button is on the left hand side just above the tab containing my SQL query.
Unfortunately I do not have sufficient privileges to upload images, so can't send a screenshot.

A: F5 is Execute as Statement - Raw Output
F9 is Execute as Script - Grid Output (Alternate: CTRL-ENTER)
When running as a Statement and switching to grid, you'll be in the Script Output tab which has actions available (copy/select all, etc). When running as a Script you have a Data Grid view you'll have only export action. You can switch views at either output.
You can remap the function keys if you are accustomed to F5.
EDIT: The version I based my response on is for Toad for Oracle 11.6

A: The button that sends output directly to the grid is located on the Execute toolbar and looks like this:

You can set it to execute via F5 by doing the following:

*

*Choose View->ToadOptions

*Left side scroll and under Toolbars/Menus choose Shortcuts

*Right side click on 'Execute Statement' (F9 is shown as shortcut on mine)

*Hit F5

*Click on 'Execute as Script' (F5 is still shown as shortcut here)

*Hit F9

A: You can use Ctrl + Enter to execute the sql command and get the Data Grid view.


text:
Q: Форма авторизации HTML&PHP в модальном окне Есть форма с авторизацией. Когда вводим логин и пароль которые не содержаться в СУБД, то страница просто обновляется. Это можно было бы сделать намного проще, но вот форма находится в модальном окне. Т.е. если делать проверку уже в php файле, тогда только при нажатии на кнопку авторизации срабатывает файл php и выводит сообщении об ошибке. Дык в чем суть, можно ли сделать проверку на существование пользователя прямо в HTML, ну или на крайняк в js? Спасибо.

A: Используйте ajax

*

*Делаем отдельный обработчик для авторизации auth.php

$errors = [];
if (!authUser($login, $pass)) { // некий метод для авторизации
    $errors[] = 'Ошибка авторизации';
}

// тут мы либо рендерим форму авторизации с учетом ошибки
return render($errors);

// или возвращаем только ошибки
return json_encode($errors);

*Делаем обработчик формы в js

$('.auth-form').on('submit', function(e){
    e.preventDefault(); // чтоб страница не обновилась
    var form = $(this);
    $.ajax({
        url: form.attr('action'),
        data: form.serialize(),
        success: function(response){
            // если это html
            $('.form-container').html(response);
            // если это json
            $('.errors', form).html(''); // чистим ошибки
            if (response.errors) {
                for(var i=0; i<response.errors.length; i++) {
                   $('.errors', form).append('<p>'+response.errors[i]+'</p>');
                }
            } else {
                // ошибок нет, скорее всего нас авторизовали
                // можно просто перезагрузить страницу
                location.href = location.href;
            }
        }
    });
});


text:
Q: What happens in the event that the cooling radius is shorter than the virial radius of a Cold Dark Matter Halo? The cooling radius of a cold dark matter halo is defined to be the time at which the cooling time $t_{cool} = t_{free fall}$
where
$$t_{cool}=\frac{\rho \varepsilon }{\Lambda \left ( T \right )n_{H}^{2}},\quad t_{free fall}=\sqrt{\frac{3 \pi}{32 G \left ( \rho + \rho_{dm} \right )}}$$
In the case where there is a spherical gas cloud gravitationally drawn towards a gaseous halo with the cooling radius $r_{cool} > r_{virial}$, the spherical gas cloud cools rapidly and contracts rapidly, prohibiting hydrostatic equilibrium from taking place. The result is a spherical gas cloud collapsing by the free fall time $t_{free fall}$.
What actually happens then in the event that the cooling radius $r_{cool}$ is smaller than the virial radius of the gaseous halo? What is the resulting dynamics?


text:
Q: how to make button in ionic + css I need to design toolbar in ionic .I am able to make that tool bar but it is not look similar to as in below pic.In given image  buttons are  small height , small font  .Second thing it second button is bigger than than rest .In given image all button have different width .Can we make same button in ionic
I tried to do so in ionic but I am not able to make same as above how I will make same this type of toolbar in ionic as show in image
here is my code
![

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

  <title>Tabs Example</title>

  <link href="//code.ionicframework.com/nightly/css/ionic.css" rel="stylesheet">

<ion-view>
    <ion-header-bar align-title="center" class="bar-balanced">

Account

    </ion-header-bar>
    <ion-content>

            Details
            Related
            sad
            ss

    </ion-content>
</ion-view>
]

A: try adding this in css at the bottom else you may need to use !important.
.button-bar > .button:first-child{
  border-top-left-radius: 10px !important;
  border-bottom-left-radius: 10px !important;
}

.button-bar > .button:last-child{
    border-top-right-radius: 10px !important;
  border-bottom-right-radius: 10px !important;
}

I have updated the Sample

A: You need to check ionic doc, and more specially  : http://ionicframework.com/docs/components/#button-sizes
There you can see that you can set up different size :
I assume that if you change all your buttons with button-small that will make your trick Disputes