Q: why the kill function does not work in linux
Possible Duplicate:
Child process receives parent’s SIGINT

the is my code in below
The function is
after the father receive the signal of CTRL-C.
the father process send signal to son1 and son2;
after the son1 and son2 exit, the father process exit;
but the result does not like that;
this is the answer
son1
son2
^Cheeell
the son1 id 5963
the son2 id 5964
Parent process is killed !!

who can help me, thank you before!!
#include <stdio.h>
#include <sys/signal.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>

#define SIGNAL_TO_SON1 10
#define SIGNAL_TO_SON2 12

#define FLAG_MSG_NO 0
#define FLAG_MSG_YES 1

int parent_msg = FLAG_MSG_NO;
void signal_sendToParent( int sig )
{
    printf("heeell\n");
    parent_msg = FLAG_MSG_YES;
}

int son1_flag = FLAG_MSG_NO;
void signal_handle_son1( int sig )
{
    printf("handle_son1\n");
    son1_flag = FLAG_MSG_YES;
}

int son2_flag = FLAG_MSG_NO;
void signal_handle_son2( int sig )
{
    printf("handle_son2\n");
    son2_flag = FLAG_MSG_YES;
}

int main( void )
{
    int pid1, pid2;
    if ( ( pid1 = fork() ) < 0 )
    {
        printf("erro!!!!");
        return -1;
    }

    if ( pid1  > 0 )
    {
        // in the parent
        while( ( pid2 = fork() ) == -1);
        if ( pid2 == 0 )
        {
            signal( SIGNAL_TO_SON2, signal_handle_son2 );
            printf("son2\n");
            // in the son2;
            while ( son2_flag != FLAG_MSG_YES );
            {
                printf("Child process 2 is killed by parent !!\n");
                exit(0);
            }
        }else{
            // setup the signal
            signal( SIGINT, signal_sendToParent );
            while ( parent_msg != FLAG_MSG_YES );
            {
                kill( pid1, SIGNAL_TO_SON1 );
                kill( pid2, SIGNAL_TO_SON2 );
                wait(0);
                printf("the son1 id %d\n", pid1 );
                printf("the son2 id %d\n", pid2 );

                wait(0);
                int status , pid ;
                while( ( pid = waitpid( -1, &status, 0 ) )  > 0 )
                {
                    printf("child %d \n", pid );
                }
                printf("Parent process is killed !!\n");
                exit(0);
            }
        }
    }else{
        // in the son1;
        printf("son1\n");
        signal( SIGNAL_TO_SON1, signal_handle_son1 );
        while ( son1_flag != FLAG_MSG_YES );
        {
            printf("Child process 1 is killed by parent !!\n");
            exit(0);
        }
    }

    return 0;
}

A: to get what you want you must ignore SIGINT in the childs.
see this What happens to a SIGINT (^C) when sent to a perl script containing children?
In short Ctrl-C is send to all processes in the foreground group.
That means your child processes get SIGINT too, they do not have a handler and get killed.
signal( SIGINT, SIG_IGN );

add in the child code, near setting the other signal handler.


Q: Hybris Backoffice update with ant updatesystem I want to update backoffice with ant updatesystem, I'm doing it this way:
ant updatesystem -DconfigFile=configWithBackofficeExt.json

For example - I have "Administration" and "MyWidget" widgets, I want to remove "Product Cockpit", so I remove config from *extension-backoffice-widgets.xml.
And now, If I run my ant command - dropdownlist with widgets not updated.
If I run an update from HAC or in backoffice with F4, all works fine.
As far as I understand, there is no web-context when I running ant command, so there are no beans responsible for update/rebuild of widgets.xml(composed widget config, which we can see in orchestrator).
Is there any way to attach backoffice web context, so that beans would be available when ant command called. Or maybe there is a more elegant way to do it?
Ps: I know about config properties to update backoffice on startup/login, but still prefer to do it with ant.

A: Finally, after research, I haven't find appropriate way to update backoffice with ant updatesystem.
To update backoffice upon application start or/and login to backoffice we can use these properties:
backoffice.cockpitng.reset.triggers=start,login
backoffice.cockpitng.reset.scope=widgets,cockpitConfig

When the application starts, configuration files will be reassembled and saved. This won't take much time(I didn't notice any impact on application startup time, with all OOTB backoffice extensions enabled, sometimes app took 10 sec longer to start, sometimes 10 sec faster).


Q: google tag manager v2 basic configuration I'm not getting hits on google analytics I'm working on a cordova/phonegap project. I'm using a plugin for GTM that allows me to track events.
The problem is that I'm not getting hits on google analytics.
According with the developer it's working fine, and from my testing, everything seems ok, no errors at all on Javascript console, and all events are firing correctly.
Since I'm new with GTM, I believe that I'm missing something on configureting it.
These are my confs:
First, the GA tag:

I used the built-in trigger "Any event" so it triggers every time an event is registered.
This is the config I set for the GA tag, I want it to trigger on every event, that's why I left empty the fields

And the GTM container type I'm using is "mobile".
For I what haver been reading so far is far different from GTM V1 where I had to create macros, and another tag to be able to track this same information.
I tried manual triggers such as, "Event matches RegEx .*" (which I believe it's the same as the built-in "Any event" trigger)

A: You have to fill in the Category and Action field at the very least for GA to register a hit. (Categoira, Accion, I guess)
Those aren't filter fields, they are the fields sent in an event hit.  You will need to use something like the macros {{element text}} or something you want to record to see hits in GA.
Check out the Event Tracking Guide by Google for more details.


Q: What should be the lucene indexing and searching strategy for providing search capabilities to end user over set of unrelated business objects? I want to provide ability to end user to do a free form search over all business objects. The user will provide Lucene search expression. The business objects are completely unrelated and have nothing in common.
Each business object comprises of there own specific attributes. For the sake of this question, the following are the business objects:
Blog
{
    Title;
    Body;
}
User
{
    FirstName;
    LastName;
    Country;
    EmailAddress;
    Gender(M/F);
}
How could I create an index which can serve the following use-cases:

*

*Free form text search in both - Blog and User. For e.g. Search those users and blog entries where the word 'India' appears. End user should not be required to specify ORing between all Lucene document fields.

*Free form text search for only users. For e.g. Search for those users where the word 'yahoo' appears. End user should not be required to specify ORing between all Lucene document fields related to User.

*Free form text search for only blog entries. For e.g. Search for those blog entries where either of the word 'Skeet Async' appears. End user should not be required to specify ORing between all Lucene document fields related to Blog.

*Free form text search by attributes for blog entries. For e.g. Search those blog entries where 'asynchronous' appears in the 'Title' attribute.

*Free form text search by attributes for users. For e.g. Search those users where 'Skeet' appears in the 'LastName' attribute.
How to define the index strategy - single index or multiple index, analyzer to use, how to provide context in the search query, etc.
Thanks.

A: For the given business objects, simplest way is to have lucene documents with the following fields:
title, body, firstName, lastName, country, emailAddress, gender

You might want to have title and user-related fields as STORED.
Choice of analyzers depends on your search requirements (like do you want to support partial matches, suffix queries, stemming etc).
Queries for the given use-cases:
1) title:india OR body:india OR country:india
2) title:yahoo OR body:yahoo OR emailAddress:yahoo
3) title:(Skeet OR Async) OR body:(Skeet OR Async)
4) title:asynchronous
5) lastName:skeet


Q: SetInterval several elements at the same time Jquery I have this code, It appends comments after clicking on comment button. (the php processes via other function)....
I want to simulate that every comment was posted at certain time, and the set interval after a while work independently with each li appendend.
PROBLEM
In the snippet it is shown that if I post a  comment set interval works with it to show how long time ago it was posted (need format but it has the idea).
The problem is that anytime I post a new comment, set intervals reloads all the previous times and shows the same results for all the comments.

$('.comment').on('click', function(){
        timeIni=$.now();

          comment=$(".textarea").val();
            $("#comments").append("
"+comment+" 1s"+"
");

            $(".textarea").val("");

      //adding the time to looks like
       /* */ setInterval(function(){
            time=$.now();
          tempo="time: "+time;
             $("#comments span").text(tempo);
                           }, 2000);

        });
textarea{
height:30px;
width:200px;
border:1px solid red;
display:block;
}

      <textarea class=textarea></textarea>
       <input type=submit class="comment" value='comment' />

I want every comments shows its own time interval, according with the time it was posted.
Other try using .each()
https://jsfiddle.net/s8650s18/16/

A: You need to declare your variables with a keyword such as var, let, const otherwise the variable becomes global. All boils down to a scoping issue.
let timeIni = Number($.now());

Here is the fiddle working: https://jsfiddle.net/s8650s18/22/


Q: After Upgrade to Ubuntu 20.04: "Oh no! Something went wrong" I upgraded to Ubuntu 20.04 today, choosing LightDM over gdm3 during the upgrade. During the upgrade I was asked if I wanted to keep or replace /etc/sane.d/dll.conf file. I decided for keeping it.
Now, without actively rebooting, the "Oh no! Something went wrong" screen appeared.
As I am still inexperienced with this kind of troubleshooting, I feel it wouldn't be safe to just try out answers from other threads that don't have exactly the same 'history'.
Solutions I read included
Ctrl+Alt+F4 and trying to login and get more information from the command line (Oh no! Something has gone wrong on restart).
Is that safe to do?
Ideally, I'd like to save my data that is stored on an encrypted harddrive before trying to fix errors. I'd like to avoid reinstalling the OS.
From reading other threads, I know this post may be criticised as not being precise enough or haven't tried enough, but really I cannot get more information from that white screen myself and don't want to risk ruining everything just to provide more information...
Thank you for your help!! :)
Edit: I have no idea if the problem is related to lvm2-activation-generator, as in Ubuntu 19.10 “Something has gone wrong” after update from 19.04
This and other solutions include booting from a live usb. Can I do this 'safely' by simply switching the laptop off at this stage? Do I have to do sth before?

A: My question has been answered with the help of Ollie:

*

*sudo apt-get update returned
Could not get lock /var/lib/apt/lists/lock. It is held by process 22027 (focal)

*I tried to identify the process with ps aux | grep -i apt and ps -aux | grep -iE "apt-get" which didn't work, but I could identify it with pgrep focal which gave me its process ID. I killed it with sudo kill <process_id>.

*do-release-upgrade worked for me only without the -y option. It returned
There is no development version of an LTS available.
To upgrade to the latest non-LTS development release
set Prompt=normal in /etc/update-manager/release-upgrades

*Then I ran  sudo apt-get upgrade -y and got the message  0 upgraded, 0 newly installed, 0 to remove and 1 not upgraded. The 1 not upgraded was an expired libc++1 package.
Rebooting the computer, Ubuntu 20.04 worked well.
I then installed the current version of this libc++1 package via Synaptic.

A: This will go a long way toward making that "Oh no something went wrong!" sign go away.  First, press Ctrl+Alt+F3 to trigger the CLI, and login.  Execute the command:
sudo apt-get update && sudo apt-get dist-upgrade

to continue upgrading.  Your machine will install the missing resources, and finish upgrading, and then you just have to clean up and reboot:
sudo apt-get clean && sudo apt-get autoremove && sudo reboot

Best of luck!

A: To solve this problem in my case, I used the recovery mode option in the GRUB menu and then selected the option to start a root shell. Then I ran these commands
apt-get update && sudo apt-get dist-upgrade
apt-get clean && sudo apt-get autoremove
apt-get remove nvidia-340

I had wrongly installed this nvidia package that was causing my issues.

A: I had the same issue on ubuntu 20, I've tried many things but what worked for me was removing the gnome and gnome-shell and reinstalling:
$ sudo apt-get upgrade && sudo apt-get update
$ sudo apt-get upgrade
$ sudo dpkg --configure -a
$ sudo apt-get remove gnome-session gnome gnome-shell
$ sudo apt-get autoremove
$ sudo apt install ubuntu-desktop
$ sudo reboot

similar to was described here. (but my problem wasn't my user)

A: I had the same issue while upgrading my Ubuntu 18.04 to Ubuntu 20.04. some of the packages got crashed up. Mainly it is showing due to interruption of dpkg operations while booting the system.
Here's what I did to resolve this problem.
Firstly, press Ctrl+Alt+F3 together in order to open the terminal, then enter your login credentials and execute these following commands given below:-
sudo apt-get update && sudo apt-get upgrade
sudo dpkg --configure -a
sudo apt-get clean && sudo apt-get autoremove
sudo reboot

This will resolve the problem of dpkg having been interrupted.

A: First try to see if you can successfully login with another user account.
If everything works, try deleting/moving the .config directory in your home folder.
$ rm -rf ~/.config/

This will probably delete a bunch of settings which will go back to their default values; but it solved the issue for me.

A: I faced this problem and solved it by
First, go to tty: Ctrl + Alt + F3, and login.
Then, as dpkg was locking things, I deleted all lock log files
sudo rm /var/lib/apt/lists/lock /var/cache/apt/archives/lock /var/lib/dpkg/lock /var/lib/dpkg/lock-frontend

as described here.
Finally, I resumed the release upgrade by following the steps given in this answer.

A: This worked for me.
Lets say you always login using: USER1
First check: If we can login to other user. Lets say other user: USER2
(Note: If you don't have another user, create a new user)
If you are successful in login using user USER2
Probably, this is issue of config file of the user.
Rename ~/.config to ~/.config.bak.
Then, try to login to that user
You can always get shell using CTRL+ALT+F2 and login with user.

A: Encountered the same problem updating from 21.10 to 22.04 had an unstable internet connection and encountered the oh no screen. I resolved my internet first, then what worked for me was

Ctrl + Alt + F5

The enter login credentials after that run
sudo apt --fix-broken install
sudo apt-get update && sudo apt-get upgrade
sudo apt dist-upgrade
sudo apt-get clean && sudo apt-get autoremove

A: when I upgrade Ubuntu 20.04 to Ubuntu 22.04
this same error occurred on my laptop.
Oh no! Something has gone wrong.
A problem has occurred and the system can't recover Please contact a system administrator
Atteched Screenshot
So I can forcibly reboot my laptop and then
Firstly, press Ctrl+Alt+F3 together in order to open the terminal, then enter my login credentials username first and then password and execute these following commands given below:-
apt --fix-broken install


Q: Do four natural numbers exist which satisfy these constraints? Do four natural numbers $a,b,c$ and $d$ exist such that the following three conditions are true?
$$a^2+b^2+2d^2=c^2$$
$$\sqrt{a^2+d^2}\in\mathbb{N}$$
$$\sqrt{b^2+d^2}\in \mathbb{N}$$

A: The smallest example is $a=9, b=16, c = 25, d = 12$.  Of course, any integer multiple of this will do.  There are other solutions as well.

A: You want $(a^2+d^2)+(b^2+d^2)=c^2$ and also $a^2+d^2=x^2$ and $b^2+d^2=y^2$.
The solutions of $x^2+y^2=c^2$ are $x=2mnk,y=(m^2-n^2)k,c=(m^2+n^2)k$ where $(m,n)=1$ and $m>n$.
Now we have the equations $a^2+d^2=(2mnk)^2$ and $b^2+d^2=((m^2-n^2)k)^2$.
Do the same and see what happens:)

A: For any Pythagorean triple $(x,y,z)$ (such  that $x^2+y^2=z^2$)
denote
$$
a=x^2,\\
b=y^2,\\
c=z^2,\\
d=xy.
$$
Then
$$
a^2+b^2+2d^2 = a^2+b^2+2ab = (a+b)^2=z^4=c^2,
$$
$$
a^2+d^2=x^4+x^2y^2=x^2(x^2+y^2)=(xz)^2,
$$
$$
b^2+d^2=y^4+x^2y^2=y^2(y^2+x^2)=(yz)^2.
$$


Q: Objective c UIlabel is hang for a while when API is called As title, when users click a button as many times as they want, the uilabel will be updated to the number and the app will call an api to post the number to the server. Everything works fine except when the api is being called, the uilabel will hang for 2 - 5 seconds and will not update even the user is pressing the button. I have tried calling api in the background and update the ui in the main queue, it works but still will hang for a little while like 1 - 3 seconds. The reason I need to post the count to server is because there will be many users pressing the button simultaneously thus the label will be updated to total of all users.
The flow: Users press button, as many as they want, uilabel will be updated to how many times the users have pressed the button, every 5 seconds an api will be called to post the count, uilabel will update the number again.
Any suggestion to fix or enhance this issue? Thank you
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
[MyApiManager postHitCount:hitCountModel block:^(id object, NSError *error)
 {
     dispatch_async(dispatch_get_main_queue(), ^{
         [self setUpCount];
     });

     if ([self checkError:error])
         return;
 }];
});

A: You need to add loader (activityIndicator) while your process start and hide while process complete .
And you need to manage that while process is working user not interact any thing in the current view
// Start here
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
[MyApiManager postHitCount:hitCountModel block:^(id object, NSError *error)
 {
     dispatch_async(dispatch_get_main_queue(), ^{
         [self setUpCount];
         // stop here
     });

     if ([self checkError:error])
          // stop here
         return;

 }];
});


Q: Animation in iOS 14 widget I can't find solution to implement kind of ProgressBar in Widget. I see, that Text component should be changed if has type .timer for example. I see default widget Clock, with nice animation of moving arrow. But am I able to implement custom animation in widget?

A: According to a Frameworks Engineer on Developer Apple Forum:

Animations and pan/zoom gesture do not work in widgets built with WidgetKits. Checkout https://developer.apple.com/videos/play/wwdc2020/10028/, where what works and doesn't.

Throughout the WWDC20 Meet WidgetKit video mentioned above, Apple stresses that Widgets are not mini-apps, so they don't support gesture based views (like scroll views) or animations. Widgets are meant to only have glanceable information. From WWDC20 Meet WidgetKit Video Transcript:

These widgets are not mini-apps. We do not support scrolling within the widget, interactive elements like switches and other system controls, nor videos or animated images.


Q: Get the Guid (not the entry ID) of an Outlook Message As mentioned in this post, it is possible to grab the entryID from Outlook messages.
But the problem is if theses messages are moved to another folder, the ID changes.
So, I guess I need the GUID, but I don't know how I can grab this via a macro in Outlook. Can anyone help me figure this out?

A: Use PR_SEARCH_KEY (http://schemas.microsoft.com/mapi/proptag/0x300B0102 for PropertyAccessor and Folder.GetTable filter).


Q: Post closed three times as duplicate? I don't know if this is related to the multiple-migrate problems or the slow response problems but looking at the revision history of this question - makes me wonder - what the heck happened?

A: There was a massive CPU spike on one of the web servers (4 cpus, all pegged) which caused some strange behavior.
Closing as too localized.


Q: scope of variable in nodejs inside a function How to scope datat ?
Here datat is empty.
And i would like to put data in a var so i can use it outside the function.
var datat;
twit.search('#louieck', {include_entities:true,page:paget,maxid:maxidt}, function(data) {

// and output to the console:

datat =  data;

});
sys.puts(sys.inspect(datat));

Regards
Bussiere

A: 'datat' is scoped outside your function. twit.search is async and therefore may not return 'data' before you check 'datat' with sys.inspect.
This should let you see datat:
var datat;
twit.search('#louieck', {include_entities:true,page:paget,maxid:maxidt}, function(data) {

    // and output to the console:
    datat =  data;
    sys.puts(sys.inspect(datat));

});

But ideally you'd use a callback like this...
var datat;
var callback = function(d){
    sys.puts(sys.inspect(d));

    datat = d;
    // do something more with datat

};

twit.search('#louieck', {include_entities:true,page:paget,maxid:maxidt}, function(data) {

    callback(data);

});

EDIT - simplified as per comment...
var datat;
var callback = function(d){
  sys.puts(sys.inspect(d));
  datat = d;
  // do something more with datat
};
twit.search('#louieck', {include_entities:true,page:paget,maxid:maxidt},callback(data));


Q: Create mutation between related types in GraphQL I'm using GraphQL to try to create a record that has a relation to another type.  The types are Task and Day
datamodel.graphql:
type Task {
  id: ID! @unique
  content: String!
  completed: Boolean!
  dateToDo: Day!
}

type Day {
  id: ID! @unique
  content: String!
  tasks: [Task]
}

I want to create a task so that it has a reference of the date it should be completed (from the Day type)
schema.graphql
type Mutation {
  createTask(content: String!, completed: Boolean!, dateToDo: ID! ): Task!
}

my mutation resolver looks like this:
const Mutations = {
  async createTask(parent, args, ctx, info) {

    const task = await ctx.db.mutation.createTask(
      {
        data: {
          dateToDo: {
            connect: {
              id: args.dateToDo
            }
          },
          ...args
        }
      },
      info
    );

    return task;
  },

when I run this mutation to create the task:
mutation CREATE_ONE_TASK  {
  createTask(
    content: "a new task",
    completed: false,
    dateToDo: "cjqycv9dtjklr09179y9zfntq")
  {
    id
  }
}

I get this error:

"message": "Variable \"$_v0_data\" got invalid value
  {\"dateToDo\":\"cjqycv9dtjklr09179y9zfntq\",\"content\":\"a new
  task\",\"completed\":false}; Expected type
  DayCreateOneWithoutTasksInput to be an object at value.dateToDo.",

My questions are: Am I using connect correctly in the mutation resolver? And what the heck is DayCreateOneWithoutTasksInput (I see its been automagically added in prisma.graphql) and how do I use it to create a Task that has a relation to a Day's ID?

A: The mutation to create the task has the following shape:
mutation b {
  createTask(
    data: {
      content: "Task1"
      completed: false
      dateToDo: { connect: { id: "cjqzjvk6w000e0999a75mzwpx" } }
    }
  ) {
    id
  }
}

The type DayCreateOneWithoutTasksInput Prisma is asking for is autogenerated and is the one expected for the field dataToDo. The name means that Prisma would accept a type that creates one Day node but does not have the field tasks or a type that specifies a connection. The WithoutTasksInput part states is there because the type can only be used nested in a mutation where you start from a task, Prisma therefore already has the value to fill in for the tasks field on the nested Day node and you do not need to specify it if you create the day instead of connecting an existing one.
If you use the Playground you can explore the schema that contains all the types on the right side.
schema explorer in the playground
Hope that helps!


Q: why doesn't std::remove_copy_if() actually remove? Could this be the worst named function in the STL? (rhetorical question)
std::remove_copy_if() doesn't actually appear to do any removing. As best I can tell, it behaves more like copy_if_not.
The negation is a bit confusing, but can be worked around with std::not1(), however I might be misunderstanding something as I cannot fathom what this function has to do with removing - am I missing something?
If not, is there an STL algorithm for conditionally removing (moving?) elements from a container & putting them in another container?
Editing to add an example so readers are less confused.
The following program appears to leave the input range (V1) untouched:
#include <vector>
#include <iostream>
#include <algorithm>
#include <iterator>

using std::cout;
using std::endl;

int main (void)
{
    std::vector<int> V1, V2;
    V1.push_back(-2);
    V1.push_back(0);
    V1.push_back(-1);
    V1.push_back(0);
    V1.push_back(1);
    V1.push_back(2);

    std::copy(V1.begin(), V1.end(), std::ostream_iterator<int>(cout, " "));
    cout << endl;

    std::remove_copy_if(
        V1.begin(),
        V1.end(),
        std::back_inserter(V2),
        std::bind2nd(std::less<int>(), 0));

    std::copy(V2.begin(), V2.end(), std::ostream_iterator<int>(cout, " "));
    cout << endl;
    std::copy(V1.begin(), V1.end(), std::ostream_iterator<int>(cout, " "));
    cout << endl;
}

It outputs:
-2 0 -1 0 1 2
0 0 1 2
-2 0 -1 0 1 2

I was expecting so see something like:
-2 0 -1 0 1 2
0 0 1 2
0 0 1 2 ? ? ?

Where ? could be any value. But I was surprised to see that the input range was untouched, & that the return value is not able to be used with (in this case) std::vector::erase(). (The return value is an output iterator.)

A:
is there an STL algorithm for conditionally removing (moving?) elements from a container & putting them in another container?

The closest thing I can think of is std::stable_partition:
std::vector<int> v;
// ...
auto it = std::stable_partition(v.begin(), v.end(), pick_the_good_elements);
std::vector<int> w(std::make_move_iter(it), std::make_move_iter(v.end()));
v.erase(it, v.end());

Now v will contain the "good" elements, and w will contain the "bad" elements.

A:
Could this be the worst named function in the STL?

A bit of background information: in the standard library (or the original STL), there are three concepts, the containers, the iterators into those containers and algorithms that are applied to the iterators. Iterators serve as a cursor and accessor into the elements of a range but do not have a reference to the container (as mentioned before, there might not even be an underlying container).
This separation has the nice feature that you can apply algorithms to ranges of elements that do not belong to a container (consider iterator adaptors like std::istream_iterator or std::ostream_iterator) or that, belonging to a container do not consider all elements (std::sort( v.begin(), v.begin()+v.size()/2 ) to short the first half of the container).
The negative side is that, because the algorithm (and the iterator) don't really know of the container, they cannot really modify it, they can only modify the stored elements (which is what they can access). Mutating algorithms, like std::remove or std::remove_if work on this premise: they overwrite elements that don't match the condition effectively removing them from the container, but they do not modify the container, only the contained values, that is up to the caller in a second step of the erase-remove idiom:
v.erase( std::remove_if( v.begin(), v.end(), pred ),
         v.end() );

Further more, for mutating algorithms (those that perform changes), like std::remove there is a non-mutating version named by adding copy to the name: std::remove_copy_if. None of the XXXcopyYYY algorithms are considered to change the input sequence (although they can if you use aliasing iterators).
While this is really no excuse for the naming of std::remove_copy_if, I hope that it helps understanding what an algorithm does given its name: remove_if will modify contents of the range and yield a range for which all elements that match the predicate have been removed (the returned range is that formed by the first argument to the algorithm to the returned iterator). std::remove_copy_if does the same, but rather than modifying the underlying sequence, it creates a copy of the sequence in which those elements matching the predicate have been removed. That is, all *copy* algorithms are equivalent to copy and then apply the original algorithm (note that the equivalence is logical, std::remove_copy_if only requires an OutputIterator, which means that it could not possibly copy and then walk the copied range applying std::remove_if.
The same line of reasoning can be applied to other mutating algorithms: reverse reverses the values (remember, iterators don't access the container) in the range, reverse_copy copies the elements in the range to separate range in the reverse order.

If not, is there an STL algorithm for conditionally removing (moving?) elements from a container & putting them in another container?

There is no such algorithm in the STL, but it could be easily implementable:
template <typename FIterator, typename OIterator, typename Pred>
FIterator splice_if( FIterator first, FIterator last, OIterator out, Pred p )
{
   FIterator result = first;
   for ( ; first != last; ++first ) {
      if ( p( *first ) ) {
         *result++ = *first;
      } else {
         *out++ = *first;
      }
   }
   return result;
}

A:
If not, is there an STL algorithm for conditionally removing (moving?) elements from a container & putting them in another container?

Not really. The idea is that the modifying algorithms are allowed to "move" (not in the C++ sense of the word) elements in a container around but cannot change the length of the container. So the remove algorithms could be called prepare_for_removal.
By the way, C++11 provides std::copy_if, which allows you to copy selected elements from one container to another without playing funny logic games with remove_copy_if.

A: You are right, that is what it does... std::remove_copy_if copies the vector, removing anything that matches the pred.
std::remove_if ... removes on condition (or rather, shuffles things around).

A: I agree that remove is not the best name for this family of functions.
But as Luc said, there's a reason for it working the way it does, and the GoTW item that he mentions explains how it works. remove_if works exactly the same way as remove - which is what you would expect.
You might also want to read this Wikibooks article.


Q: Retrieve correct data from Core Data? I have a REST API and I want to save the responses with Core Data. I was trying to implement DATAStack and Sync but I can't understand how they work. I know I can save an object into Core Data and retrieve them. But I don't find how to retrieve the objects related to an specific URL that I requested before
e.g:
GET my_url.com/home_page

{
  "posts":[
       {
         "id": 1,
         "title": "Example Post",
       },
       {
         "id": 2,
         "title": "Another example",
       }
      ]
}

and
GET my_url.com/another_page

{
  "posts":[
       {
         "id": 4,
         "title": "This is another post",
       },
       {
         "id": 5,
         "title": "Last Post",
       }
      ]
}

How do I get data from Core Data related to an URL request?


Q: Load data from SQL file to Realm Is it possible to have a SQL file inside Swift project where Realm database will import data as soon as project will be executed? I want to use a 30MB+ file of data... and don't want to download it all from a JSON API.

A: Why not bundle a prebuilt Realm file as part of your application instead? To do this you'll need to:

*

*Create the prebuilt Realm file, either using Realm Browser or a simple Mac app of your own creation.

*Add the prebuilt Realm file to your app target in your Xcode project, ensuring that it appears in the Copy Bundle Resources build phase.

*Add code similar to that found in the above link to your app to have it open the prebuilt Realm file as read-only. Alternatively, you could copy the file out of your app bundle into the user's documents or cache directory and open it read-write.


Q: Finding limit to $\lim_{x \to 2^+} \frac{\sin(x)}{x(x-2)}$ I need to find limit for:
$$
\lim_{x \to 2^+} \frac{\sin(x)}{x(x-2)}.
$$
The first thing that comes to mind is simplifying with $\lim_{x \to 0} \sin(x)/x = 1$; however, we have limit going to 2.
I tried to  first rewrite the expression with limit going to zero. We could do this by replacing $x$ with $t = x-2$:
$$\lim_{t \to 0^+} = \frac{\sin(t+2)}{(t+2)t}$$
But I get stuck here. The first instinct is to try and extract $\sin(x)/x$ from this expression to simplify it. But I have no idea how.

A: Let be $x-2:=y$. We have
$$\lim_{x \to 2^+} \frac{\sin(x)}{x(x-2)}=\lim_{y \to 0^+}\frac{\sin(y+2)}{y(y+2)}=\lim_{y \to 0^+}\frac{\sin(y+2)}{(y+2)}\cdot \lim_{y \to 0^+}\frac 1y=\frac{\sin 2}{2}\times (+\infty)=+\infty$$

A: As noticed
$$\lim_{x\to2^+} \dfrac{\sin(x)}{x} = \dfrac{\sin(2)}{2}=c>0$$
$$\lim_{x\to2^+} \frac1{x-2}=\infty$$
and then
$$\lim_{x \to 2^+} \frac{\sin(x)}{x(x-2)}=\lim_{x\to2^+} \dfrac{\sin(x)}{x}\frac1{x-2} = \infty$$

A: You actually don't have anything special to do here, you have:
$$\lim_{x\to2^+} \dfrac{\sin(x)}{x} = \dfrac{\sin(2)}{2}$$
Which is a finite non-zero quantity. With that,
$$\lim_{x\to2^+} \dfrac{\sin(x)}{x\cdot(x-2)} = \dfrac{\sin(2)}{2\cdot(x-2)} = +\infty$$


Q: Converting a Pandas datetime index on a DataFrame object to *MultiIndex* with the levels "month" and "year" Say I have a table of data with monthly datetime indices (the following code gives two years, january through december):
import pandas as pd
import numpy as np
from datetime import datetime
N = 12*2
c = [datetime(1970 + i//12, (i%12)+1, 1) for i in range(N)]
d = pd.DataFrame(np.random.rand(N), index=c)
print(d)

What is the best way to convert the DateTimeIndex into a MultiIndex with the separate levels month and year? Perhaps there is a way to do this with groupby, but I'm not sure.

A: You can construct a MultiIndex object from the year and month and assign it to the data frame's index:
import pandas as pd
d.index = pd.MultiIndex.from_arrays([d.index.year, d.index.month])

d.index
# MultiIndex(levels=[[1970, 1971], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]],
#            labels=[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]])

d.head()

#                  0
#1970   1   0.657130
#       2   0.047241
#       3   0.984799
#       4   0.868508
#       5   0.678536

A: d.index = pd.MultiIndex.from_tuples(d.reset_index()['index'].\
                                    apply(lambda x:(x.year,x.month)))


Q: MediaPlayer audio doesn't stop immediately when stop() is called A button has onClickMethod openTheLock() which makes an ImageView visible and starts an audio. On tapping on the ImageView it disappears and the audio stops. Audio is initialized in onCreate(). The problem is the audio doesn't stop immediately when the ImageView is tapped. What could be the reason?
MediaPlayer jokerAudio;

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_earth_room);
        jokerAudio= MediaPlayer.create(EarthRoomActivity.this, R.raw.joker_laugh);
    }
public void openTheLock(View v){
    if(selectedItem == R.id.key_er_item || keyUsed == true){
    jokerAudio.start();
    ImageView joker = (ImageView)parentLayout.findViewById(R.id.joker);
    joker.setVisibility(View.VISIBLE);
    joker.setOnClickListener(new OnClickListener(){
        @Override
        public void onClick(View view) {
            jokerAudio.stop();
            view.setVisibility(View.INVISIBLE);
        }
    });
    }

A: If you are not using the MediaPlayer again then you can try releasing the MediaPlayer.
joker.setOnClickListener(new OnClickListener(){
        @Override
        public void onClick(View view) {
            jokerAudio.stop();
            jokerAudio.reset();
            jokerAudio.release();
            view.setVisibility(View.INVISIBLE);
        }
    });

However if you are using MediaPlayer again later in your code don't forget to reinitialize it again.


Q: Contact form using nodemailer is not working I have created a contact form and trying to use nodemailer to send the message to my email, but not sure where is the issue.
I created a server.js and put it in the main folder while Mailer.js that contain the form in components
I am not sure how the server know that I want to use the form
this is my first project on React and I think I still don't understand some basics of React
const express = require('express');
const bodyParser = require('body-parser');
const exphbs = require('express-handlebars');
const path = require('path');
const nodemailer = require('nodemailer');

const app = express();

// View engine setup
app.engine('handlebars', exphbs());
app.set('view engine', 'handlebars');

// Static folder
app.use('/public', express.static(path.join(__dirname, 'public')));

// Body Parser Middleware
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.get('/', (req, res) => {
  res.render('contact');
});

app.post('/send', (req, res) => {
  const output = `

You have a new contact request

Contact Details

Name: ${req.body.name}

Email: ${req.body.email}

Message

${req.body.message}

  `;

  // create reusable transporter object using the default SMTP transport
  let transporter = nodemailer.createTransport({
    service: 'gmail',
    auth: {
        user: process.env.EMAIL, // generated ethereal user
        pass: process.env.PASSWORD  // generated ethereal password
    },
    tls:{
      rejectUnauthorized:false
    }
  });

  // setup email data with unicode symbols
  let mailOptions = {
      from: process.env.EMAIL, // sender address
      to: email, // list of receivers
      subject: 'Node Contact Request', // Subject line
      text: 'Hello world?', // plain text body
      html: output // html body
  };

  // send mail with defined transport object
  transporter.sendMail(mailOptions, (error, info) => {
      if (error) {
          return console.log(error);
      }
      console.log('Message sent: %s', info.messageId);
      console.log('Preview URL: %s', nodemailer.getTestMessageUrl(info));

      res.render('contact', {msg:'Email has been sent'});
  });
  });

app.listen(3000, () => console.log('Server started...'));

This is the form
import React from 'react';
import "./Mailer.scss";
const Mailer = () =>{

    return (

Contact Us

            <form method="POST" className="form" action="send">

                Name
                <input type="text" name="name" className="input"/>

                Email
                <input type="email" name="email" className="input"/>

                Message
                <textarea name="message" rows='4' className="input"/>
                <input type="submit" value="Send"/>

            </form>

    );
};

export default Mailer;

this is what I get when I click on SEND

A: From what I could gather, you're posting to the wrong URL.
In your server app, you create a post handler for /send
However, in your React App, you post to /xxxxx/send (You obscured the xxxxx part)
I advise that you replace your
<form method="POST" className="form" action="send">

With
<form method="POST" className="form" action="http://127.0.0.1:3000/send">

And try again


Q: c# html - hide kendo grid when empty I have the following Kendo grid in my html code and am trying to hide it if there is no data. I am confused on how to do this since I am using a datasource and not iterating through something to add data.
 @(Html.Kendo().Grid<CustomerQuickHistory>()
                  .Name("TransactionDetails")
                  .Columns(cols => {
                      cols.Bound(c => c.DateOfItem).Format("{0:MM/dd/yyyy}");
                      cols.Bound(c => c.ProductName);
                      cols.Bound(c => c.Price);
                  })
                  .DataSource(ds => ds
                      .Ajax()
                      //.Group(g => g.Add(d => d.CustomerName))
                      .Sort(s => s.Add(ad => ad.DateOfItem).Descending())
                      .Read(r => r.Action("TransactionHistory_Read", "Customers", new { customerId = Model.CustomerId }))
                  )
                  )

A: What about using the DataBound event handler to define check the dataSource binded and show or hide the grid.
Here is an example of something similar, but in this case it shows a message when the grid is empty.
http://blog.falafel.com/displaying-message-kendo-ui-grid-empty/
code example:

 @(Html.Kendo().Grid<Kendo.Mvc.Examples.Models.ProductViewModel>()
        .Name("grid")
        .Columns(columns =>
        {
            columns.Bound(p => p.ProductName).Title("Product Name");
            columns.Bound(p => p.UnitPrice).Title("Unit Price");
            columns.Bound(p => p.UnitsInStock).Title("Units In Stock");
        })
        .Events(events => events.DataBound("onGridDataBound"))
        .DataSource(dataSource => dataSource
            .Ajax()
            .Read(read => read.Action("Products_Read", "Grid"))
         )
    )

<script>

  function onGridDataBound(e){
    var grid = e.sender;

    if (grid.dataSource.total() == 0 ){
    //Hide grid
      $(grid).hide();
    }
    else{
      //Show grid
      $(grid).show();
    }
  }

</script>


Q: How to download receipt and invoice from stripe through my site I am using stripe from payment. After payment using invoice id how can i download receipt and invoice from my site


Q: Not able to install J2OBJC using terminal I have download the J2OBJC version and while running the command on terminal
A:j2objc-master $ make dist
I am getting below error
building j2objc jar
javac: invalid source release: 1.8
Usage: javac
use -help for a list of possible options
make[1]: * [/Users/Downloads/j2objc-master/translator/build_result/j2objc.jar] Error 2
make: * [translator] Error 2
Please suggest

A: That's a javac error, stating that the version of javac on your system (which is part of the JDK you have installed) does not support the j2objc project's Java 8 minimum version. Upgrade your system to JDK 8 from Oracle to support this minimum.


Q: 503 Error After Microsoft Request Routing Is Installed - 32 bit 64 bit madness I have a requirement to install the Microsoft Request Routing component for IIS 7.5 running on a Windows 2008 R2 SP1 64Bit machine.
After installing Microsoft Request Routing via the Web Platform installer our ASP.NET 4.0 application gets a "HTTP Error 503. The service is unavailable."
The Windows event log error details says:
The Module DLL 'C:\Program Files\IIS\Application Request Routing\requestRouter.dll' could not be loaded due to a configuration problem. The current configuration only supports loading images built for a AMD64 processor architecture. The data field contains the error number. To learn more about this issue, including how to troubleshooting this kind of processor architecture mismatch error, see http://go.microsoft.com/fwlink/?LinkId=29349.

I can make this error go away by changing the application pool to run in 32 bit mode by changing the "Enable 32-Bit Applications" setting to true.
However I would prefer not to have to do that to resolve the issue.
My questions are:

*

*Why is the Microsoft Request Routing feature trying to load a 32 bit version, isn't there a 64 bit version for it?

*How do I resolve this issue without having to change my application pool to a 32 bit mode?

A: having done some research into this I can inform you that there are currently two version of Microsoft's Application Request Routing one for 32-bit architecture and the other for 64-bit.
Although it does not say, I would presume that the Web Platform Installer version is only for 32-bit, in order to get a 64-bit specific version you are going to have to download from one these two locations:
http://blogs.iis.net/wonyoo/archive/2011/04/20/how-to-install-application-request-routing-arr-2-5-without-web-platform-installer-webpi.aspx
or
http://www.microsoft.com/en-us/download/details.aspx?id=7173
the blog (first URL) gives details on how to install into IIS once you have downloaded.
hope this proves useful.

A: What processor architecture are you using?
The error seems to suggest that only 64bit AMD processors are currently supported, perhaps it might be worth looking into a solution more specific to your processor.
I'm guessing your using an Intel CPU?
I'm aware that there are certain scenarios where running IIS in 32 bit mode on a 64 bit system is required.

A: it might be worth looking at these installation guidelines on the IIS site found at this address:
http://www.iis.net/learn/extensions/installing-application-request-routing-%28arr%29/install-application-request-routing
if these don't solve the issue it might well be worth either posting on the IIS forum:
http://forums.iis.net/
or posting on technet forum:
http://social.technet.microsoft.com/Forums/en-gb/categories/


Q: Multiplex IC 5 inputs and 5 outputs custom? Hey all I am wanting to know if there is an IC that allows me to do the following:

*

*Have 5 inputs

*Have 5 outputs

*Ability to take any input # and direct it to any output #

The latter bullet there is the main goal.

So in the image example above say that I needed the following examples:

Input 1 to output on output 4.
Input 3 output to Output 1.
Input 3 output to Output 3.
Input 4 output to Output 1.
Input 1 output to Output 1.
Input 2 output to Output 5.
...and so on....

What I would be hooking up to the input would be either Ground, 5V or 3.3V which would need to output the same as its input.
Note that I plan on using an Arduino so if the IC requires interaction from the Arduino in order to switch the outputs then I will have the means to do so.
Update
I will need to be able to use all of the inputs and outputs at the same time.
Example:

Input 1 --> Output 4 (5v)
Input 2 --> Output 1 (RX)
Input 3 --> Output 5 (TX)
Input 4 --> Output 2 (3.3v)
Input 5 --> Output 3 (gnd)

Is there any IC that would allow me to do the above?
What I am looking to accomplish is taking this layout:

and connecting those pogo pins to the multiplex/demultiplexer/crossbar switch/cross point switch in order to allow for different pcb models that have different pin layouts in order to flash firmware to them using the FTDI.
Hopefully knowing that allows you to understand the overall design of what I am trying to do.

A: What you're describing is a crosspoint switch.
Your question says that you want to pass 0 V, 3.3 V or 5 V signals through it. If this means LVTTL and TTL logic levels, with the output voltage remaining as the input voltage, you'd best use an analogue crosspoint switch.
I've previously used the ADG2188 8x8 device in a 32-pin package. There are other parts around but larger packages and higher costs come into play and you haven't stated your criteria there.

The ADG2188 input-to-output mapping is controlled through an I2C interface, rather than direct digital signals. As you'd need a lot of the latter, a serial bus like I2C is is to be expected.
Note that the ADG2188 requires a power supply rail that is 2 V higher than the largest voltage it is switching. In your case, it would need at least a 7 V supply to switch your 5 V signals.
Being an analogue crosspoint switch, it can carry any voltage in the range from its Vss supply pin voltage up to 2 V short of its Vdd supply pin voltage. Vss can go to 0 V if you're not carrying negative voltages, which you apparently aren't.


Q: find common files between two directories - exclude file extension I have two directories with files that end in two different extensions:
Folder A called profile (1204 FILES)
file.fasta.profile
file1.fasta.profile
file2.fasta.profile

Folder B called dssp (1348 FILES)

file.dssp
file1.dssp
file2.dssp
file3.dssp #<-- odd one out

I have some files in folder B that are not found in folder A and should be removed for example file3.profile would be deleted as it is not found in folder A. I just want to retain those that are common in their filename, but excluding extension to end up with 1204 files in both
I saw some bash lines using diff but it does not consider this case, where the ones I want to remove are those that are not found in the corresponding other file.

A: Here is a way to do it:

*

*for both A and B directories, list the files under each directory, without the extension.

*compare both lists, show only the file that does not appear in both.

Code:
#!/bin/bash

>a.list
>b.list

for file in A/*
do
    basename "${file%.*}" >>a.list
done

for file in B/*
do
    basename "${file%.*}" >>b.list
done

comm -23 <(sort a.list) <(sort b.list) >delete.list

while IFS= read -r line; do
    rm -v A/"$line"\.*
done < "delete.list"

# cleanup
rm -f a.list b.list delete.list

*

*"${file%.*}" removes the extension

*basename removes the path

*comm -23 ... shows only the lines that appear only in a.list

EDIT May 10th: my initial code listed the file, but did not delete it.  Now it does.

A: Try this Shellcheck-clean Bash program:
#! /bin/bash -p

folder_a=PATH_TO_FOLDER_A
folder_b=PATH_TO_FOLDER_B

shopt -s nullglob
for ppath in "$folder_a"/*.profile; do
    pfile=${ppath##*/}
    dfile=${pfile%.profile}.dssp
    dpath=$folder_b/$dfile
    [[ -f $dpath ]] || echo rm -v -- "$ppath"
done

*

*It currently just prints what it would do.  Remove the echo once you are sure that it will do what you want.

*shopt -s nullglob makes globs expand to nothing when nothing matches (otherwise they expand to the glob pattern itself, which is almost never useful in programs).

*See Removing part of a string (BashFAQ/100 (How do I do string manipulation in bash?)) for information about the string manipulation mechanisms used (e.g. ${ppath##*/}).

A: With find:
find 'folder A' -type f -name '*.fasta.profile' -exec sh -c \
'! [ -f "folder B/$(basename -s .fasta.profile "$1").dssp" ]' _ {} \; -print

Replace -print by -delete when you will be convinced that it does what you want.
Or, maybe a bit faster:
find 'folder A' -type f -name '*.fasta.profile' -exec sh -c \
'for f in "$@"; do [ -f "folder B/$(basename -s .fasta.profile "$f").dssp" ] || echo rm "$f"; done' _ {} +

Remove echo when you will be convinced that it does what you want.

A: Python version:
EDIT: now suports multiple extensions
#!/usr/bin/python3

import glob, os

def removeext(filename):
    index = filename.find(".")
    return(filename[:index])

setA = set(map(removeext,os.listdir('A')))
print("Files in directory A: " + str(setA))

setB = set(map(removeext,os.listdir('B')))
print("Files in directory B: " + str(setB))

setDiff = setA.difference(setB)
print("Files only in directory A: " + str(setDiff))

for filename in setDiff:
    file_path = "A/" + filename + ".*"
    for file in glob.glob(file_path):
        print("file=" + file)
        os.remove(file)

Does pretty much the same as my bash version above.

*

*list files in A

*list files in B

*get the list of differences

*delete the differences from A

Test output, done on Linux Mint, bash 4.4.20
mint:~/SO$ l
drwxr-xr-x 2 Nic3500 Nic3500 4096 May 10 10:36 A/
drwxr-xr-x 2 Nic3500 Nic3500 4096 May 10 10:36 B/

mint:~/SO$ l A
total 0
-rw-r--r-- 1 Nic3500 Nic3500 0 May 10 10:06 file1.fasta.profile
-rw-r--r-- 1 Nic3500 Nic3500 0 May 10 10:06 file2.fasta.profile
-rw-r--r-- 1 Nic3500 Nic3500 0 May 10 10:14 file3.fasta.profile
-rw-r--r-- 1 Nic3500 Nic3500 0 May 10 10:36 file4.fasta.profile
-rw-r--r-- 1 Nic3500 Nic3500 0 May 10 10:06 file.fasta.profile
mint:~/SO$ l B
total 0
-rw-r--r-- 1 Nic3500 Nic3500 0 May 10 10:05 file1.dssp
-rw-r--r-- 1 Nic3500 Nic3500 0 May 10 10:06 file2.dssp
-rw-r--r-- 1 Nic3500 Nic3500 0 May 10 10:06 file3.dssp
-rw-r--r-- 1 Nic3500 Nic3500 0 May 10 10:05 file.dssp

mint:~/SO$ ./so.py
Files in directory A: {'file1', 'file', 'file3', 'file2', 'file4'}
Files in directory B: {'file1', 'file', 'file3', 'file2'}
Files only in directory A: {'file4'}
file=A/file4.fasta.profile

mint:~/SO$ l A
total 0
-rw-r--r-- 1 Nic3500 Nic3500 0 May 10 10:06 file1.fasta.profile
-rw-r--r-- 1 Nic3500 Nic3500 0 May 10 10:06 file2.fasta.profile
-rw-r--r-- 1 Nic3500 Nic3500 0 May 10 10:14 file3.fasta.profile
-rw-r--r-- 1 Nic3500 Nic3500 0 May 10 10:06 file.fasta.profile


Q: Should I prevent branching if there will be perfect pattern so prediction should be good? My question is very much related to this question but something remained unclear for me after reading that question and very good answer.
So as I understand it, the processor executing the code makes a branch prediction such that it already does the processing towards one branch in the hope that branch will be the one that needs to be executed. If it is wrong it will have to reroll some instructions which takes time.
As I understand it the prediction is based on the pattern in the past.
So now my question would be: if I know for sure there will be a pattern in what the if statement will evaluate to, is that just as fast when the decision would have been made at compile time?
More specific for my case, I have a template function and I could do template specialization such that the decision is made on compile time, but in my opinion the code will be more clear if I use std:is_same inside my function. But speed is also highly important for my application so if speed might be compromised I would still rather go for template specialization although that will be less readable/maintainable in my specific case. (I could make the template specialization more readable as well, but it's a big code (not fully written by me) and I rather not go through the whole code and change many things to make it nice again. Yes basically I'm lazy.)
(I think the question can go without MWE but if not I'll add some)


Q: Open any link in new tab I want to be able to open any link in a new tab, but some websites (example) work like this:
Whenever I click on a link, the link opens in the current tab so neither right-click, middle-click nor Ctrl+Click work.
Is there a way around this?
EDIT2: As you seem to mistake that only SOME, not ALL the links are regular, this shows the behavior of the links on the site.
EDIT: Notice that not all of the links in the example work like regular links. What I actually want to accomplish is to easily (a) compare the definitions of multiple words or (b) branch out and compare the definitions of multiple referenced words, but the individual links for words open in the same tab.

A: It appears that dictionary.com is using ReactJS. according to this Why does CTRL-click not open some links in a new tab? and google for reactjs not opening links in new tabs will probably give you more information as well.
as @DavidPostill♦ noted, right clicking and selecting "open link in new tab" works well...
I also noted that your example site manipulates the history, so going to the site, clicking on a few links, and going back to the startpage is not possible.
If right clicking and choosing "open in new tab" is not acceptable, then you may be able to use a macro (if your keyboard/mouse or a third party plugin for windows) supports it


Q: Rust serde deserialize dynamic trait I have a recursive data structure in my pet-project:
(this is a simplified example)
pub trait Condition {
        fn validate(&self, s: &str) -> bool;
}

pub struct Equal {
    ref_val: String,
}
impl Condition for Equal {
    fn validate(&self, s: &str) -> bool { self.ref_val == s }
}

pub struct And<A, B> where A: Condition + ?Sized, B: Condition + ?Sized {
    left: Box<A>,
    right: Box<B>,
}

impl<A, B> Condition for And<A, B> where A: Condition + ?Sized, B: Condition + ?Sized {
    fn validate(&self, s: &str) -> bool { self.left.validate(s) && self.right.validate(s) }
}

and i want to serialize and de-serialize the condition trait (using serde) eg.:
fn main() {

    let c = And {
        left: Box::new(Equal{ ref_val: "goofy".to_string() }),
        right: Box::new(Equal{ ref_val: "goofy".to_string() }),
    };

    let s = serde_json::to_string(&c).unwrap();

    let d: Box<dyn Condition> = serde_json::from_string(&s).unwrap();
}

Because serde cannot deserialize dyn traits out-of-the box, i tagged the serialized markup, eg:
#[derive(PartialEq, Debug, Serialize)]
#[serde(tag="type")]
pub struct Equal {
    ref_val: String,
}

and try to implement a Deserializer and a Vistor for Box<dyn Condition>
Since i am new to Rust and because the implementation of a  Deserializer and a Visitor is not that straightforward with the given documentation, i wonder if someone has an idea how to solve my issue with an easier approach?
I went through the serde documentation and searched for solution on tech sites/forums.
i tried out typetag but it does not support generic types
UPDATE:
To be more precise: the serialization works fine, ie. serde can serialize any concrete object of the Condition trait, but in order to deserialize a Condition the concrete type information needs to be provided. But this type info is not available at compile time. I am writing a web service where customers can upload rules for context matching (ie. Conditions) so the controller of the web service does not know the type when the condition needs to be deserialized.
eg. a Customer can post:
{"type":"Equal","ref_val":"goofy"}

or
{"type":"Greater","ref_val":"Pluto"}

or more complex with any combinator ('and', 'or', 'not')
{"type":"And","left":{"type":"Greater","ref_val":"Gamma"},"right":{"type":"Equal","ref_val":"Delta"}}

and therefore i need to deserialze to a trait (dyn Condition) using the type tags in the serialized markup...

A: I would say the “classic” way to solve this problem is by deserializing into an enum with one variant per potential “real” type you're going to deserialize into. Unfortunately, And is generic, which means those generic parameters have to exist on the enum as well, so you have to specify them where you deserialize.
use serde::{Deserialize, Serialize};
use serde_json; // 1.0.91 // 1.0.152

pub trait Condition {
    fn validate(&self, s: &str) -> bool;
}

#[derive(PartialEq, Debug, Serialize, Deserialize)]
pub struct Equal {
    ref_val: String,
}
impl Condition for Equal {
    fn validate(&self, s: &str) -> bool {
        self.ref_val == s
    }
}

#[derive(PartialEq, Debug, Serialize, Deserialize)]
pub struct And<A, B>
where
    A: Condition + ?Sized,
    B: Condition + ?Sized,
{
    left: Box<A>,
    right: Box<B>,
}

impl<A, B> Condition for And<A, B>
where
    A: Condition + ?Sized,
    B: Condition + ?Sized,
{
    fn validate(&self, s: &str) -> bool {
        self.left.validate(s) && self.right.validate(s)
    }
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(untagged)]
enum Expr<A, B>
where
    A: Condition + ?Sized,
    B: Condition + ?Sized,
{
    Equal(Equal),
    And(And<A, B>),
}

fn main() {
    let c = And {
        left: Box::new(Equal {
            ref_val: "goofy".to_string(),
        }),
        right: Box::new(Equal {
            ref_val: "goofy".to_string(),
        }),
    };

    let s = serde_json::to_string(&c).unwrap();

    let d: Expr<Equal, Equal> = serde_json::from_str(&s).unwrap();
    println!("{d:?}");
}

Prints And(And { left: Equal { ref_val: "goofy" }, right: Equal { ref_val: "goofy" } })

A: I removed the generics from the combinator conditions, so i can now use typetag like @EvilTak suggested:
#[derive(Serialize, Deserialize)]
#[serde(tag="type")]
pub struct And {
    left: Box<dyn Condition>,
    right: Box<dyn Condition>,
}
#[typetag::serde]
impl Condition for And {
    fn validate(&self, s: &str) -> bool { self.left.validate(s) && self.right.validate(s) }
}

(on the downside, i had to remove the derive macros PartialEq, and Debug)
Interesting side fact: i have to keep the #[serde(tag="type")] on the And Struct because otherwise the typetag will be omitted in the serialization (for the primitive consitions it is not needed)
UPDATE: typetag adds the type tag only for trait objects so the #[serde(tag="type")] is not needed...


Q: Is there a way to have "default" or "placeholder" values in Excel? I've got a spreadsheet with cells that I want to be user-editable, but that I also want to have "default" or "placeholder" values in, whenever there is no user-entered data.  There's a couple good use cases for this:

*

*Prevent formula errors, while providing reasonable assumptions when a user has not entered (or has deleted) their own value.

*

*I could use conditional formatting to alert the user to default values, so as to prevent their ignorance of them - they can then make an informed choice as to whether that value is still appropriate or not for the intended calculations.

*Give a short description of what is intended to be entered in the cell, without having to have a separate "instructions" segment or document.  This would also eliminate the need for a nearby "Label" cell, in some cases where it's really not appropriate.

To accomplish what I want, I need some formula, script, or other advanced spreadsheet option that will do the following:

*

*Show the default value in the cell before user enters data.

*Allow the default value to be found by any formulas referencing the cell, when there is no user-entered data in that cell.

*Allow the user to freely (naturally, exactly as they would do with any "normal" cell) overwrite the displayed value with their own value or formula, and have the user-entered data found by any formulas referencing the cell.

*When cell is blanked by deletion of user input, revert to default value.

Is there a way to do this in Excel, or am I asking too much of a spreadsheet program here?

A: There is no built in way to do this, you will need to create your own.
One possibility is this:

*

*For each cell you want a default for, create a worksheet scoped named range referencing that cell, and in the comment field enter the required default value

*Add the Workbook module Workbook_SheetChange event
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
    Dim nm As Name
    Dim cl As Range

    On Error Resume Next
    For Each cl In Target.Cells
        If IsEmpty(cl) Then
            For Each nm In Sh.Names
                If nm.RefersToRange.Address = cl.Address Then
                    Application.EnableEvents = False
                    If IsNumeric(nm.Comment) Then
                        nm.RefersToRange.Value = Val(nm.Comment)
                    Else
                        nm.RefersToRange.Value = nm.Comment
                    End If
                    Application.EnableEvents = True
                    Exit For
                End If
            Next
        End If
    Next
End Sub

What this does is:

*

*Any time a cell is changed the event code is run

*If a cell that changed is empty

*

*Look for a Worksheet scoped Named Range that references the cell

*If found copy the Name comment into the cell value, converting to numeric is appropriate

A: I use a method that works like this:
-- a simple example for school records:

*

*col A are the row titles: student ID, last name, first name, birth date, age...

*col B is the ghost column: width 1, left justify, increase indent 1, protected, font color gray, no text wrap

*col C are the entry fields

-- Col B values are loaded with whatever you want to show in col C as the default. Values can come from an accompanying helper sheet, a formula that updates as the cells are filled in, another spreadsheet with default values, error messages...
-- so, when the student ID is entered, the last name, first name, birth date, address, parents, etc immediately show as ghost values in the rows below. There is nothing in any of the col C cells so the ghost values in col B extend into col C. (Numeric and date values must be formatted with a text() function.) After verifying the child's information, the operator continues down to fill in the class schedule, homeroom teacher...
-- If something needs to be changed the cell is typed into, which signals that something for that child is different. (Family name, parent's name, address...)
-- or, the last name and first name could be entered, leaving the ID blank, and the ghost value would show the child ID from the master spreadsheet.
-- A helper sheet could show helper text that disappears once the cell in col C is touched. Or, spreadsheet logic can determine that the helper text is no longer appropriate or should show something different.
The ghost values are searchable, can be gray for default text or red for warnings, and refresh automatically as the accompanying spreadsheets are updated.
A limitation is that the ghost text cannot wrap into col C.


Q: Does dependency injection (in NestJS, for example) depends on TypeScript features? When applying the dependency injection pattern in NestJS, like in this example from the documentation:
import { Controller, Get, Post, Body } from '@nestjs/common';
import { CreateCatDto } from './dto/create-cat.dto';
import { CatsService } from './cats.service';
import { Cat } from './interfaces/cat.interface';

@Controller('cats')
export class CatsController {
  constructor(private catsService: CatsService) {}

  // Some other methods...
}

How does this work? As far as I understand, TypeScript will be compiled to plain JavaScript, and then the class type (CatsService) will disappear. How does NestJS know what class to inject in this case?

A: Dependency injection does not depend on the typescript. Whenever we boot up the nest app, a Dependency Injection (DI) container gets created for us. DI is just an object.
Nest will look at the all different classes that we created except controllers. It will register all those different classes with the DI container. The container will check all the dependencies that are required for each class and map this class to its dependencies:
   class1 ---> dependencies
   class2 ---> dependencies
   class3 ---> it might now have any dependency

Then eventually we want to create the controller. we tell DI to create the controller with the required dependencies. DI will look at the constructor argument and see all the dependencies that are required. the container will see that it needs to create a service and service needs to create some dependencies.
So DI container will create the instances of required dependencies and store each instance internally so if in the future another class needs to those instances it can use them. Now dependencies are already created and DI container will use those to create the Controller and return it.
As you see we do not worry about creating all those services ourselves. DI container will take care of it for us.
Dependency injection is used for reusing the code and test the app easier.

A: Take a look at the example. This:
@Injectable()
export default class RequestService {
  constructor(
    @InjectRepository(RequestEntity)
    private requestEntityRepository: Repository<RequestEntity>,
  ) {}

Is being transpiled to this:
let RequestService = class RequestService {
    constructor(requestEntityRepository) {
        this.requestEntityRepository = requestEntityRepository;
    }
...

RequestService = __decorate([
    common_1.Injectable(),
    __param(0, typeorm_1.InjectRepository(RequestEntity_1.default)),
    __metadata("design:paramtypes", [typeorm_2.Repository])
], RequestService);
exports.default = RequestService;

A: Dependency injection in general does not depend on typescript, and even in NestJS it can be done in (mostly) plain JavaScript by using Babel as a transpiler. I've gone into a bit of detail here about how the decorators work with typescript, and Semyon Volkov has shown how the decorators transpile as well. So inherently, no, it doesn't depend on Typescript, the way Nest wants you to do it (being opinionated and all) does.
In your example, Nest will read the type of design:paramtypes and see that there is a CatsService class, so it knows to match up the class names and inject a CatsService here. There's a lot more going on under the hood, when it comes to keeping track of what modules have access to what, but that's the general idea.


Q: Assigning to a quosure in R / dplyr / rlang Within a function, I want to update-in-place the values of columns specified by the user, where the user specified column names are captured via enquo(). So, here's a simplified example:
f1 <- function(df, x, y) {
    x <- enquo(x)
    y <- enquo(y)

    df %>%
        mutate((!! x) := (!! x)^2,
               (!! y) := (!! y)+1)
}

dat <- data.frame(a=1:10, b=10:1)
f1(dat, x=a, y=b)

This fails with an error: "The LHS of := must be a string or a symbol".
I've also tried replacing, for example, (!! x) with quo_get_expr(x) and f_text(x), but get the same error. For example:
f1 <- function(df, x, y) {
    x <- enquo(x)
    y <- enquo(y)

    df %>%
        mutate(quo_get_expr(x) := (!! x)^2,
               quo_get_expr(y) := (!! y)+1)
}

Can anyone point out what I'm doing wrong?
I'm using R 4.1, dplyr 0.7.4, and rlang 0.2.0
Thanks in advance.

A: You need to use quo_name.  This works:
f1 <- function(df, x, y) {
  x <- enquo(x)
  y <- enquo(y)

  df %>%
    mutate(
     !!quo_name(x) := (!!x)^2,
     !!quo_name(y) := (!!y)+1)
}

dat <- data.frame(a=1:10, b=10:1)
f1(dat, x=a, y=b)


Q: Why my key commands are not working My issue is that my javascript is not seeing when i push my key down to move the object on the screen.
So here is my java script code:
var canvas = document.getElementById("maincanvas");
var context = canvas.getContext("2d");

var keys = [];

var width = 500,
  height = 400,
  speed = 3;

var player = {
  x: 10,
  y: 10,
  width: 20,
  height: 20
};

window.addEventListener("keydown", function (e) {
  keys[e.keycode] = true;
}, false);
window.addEventListener("keyup", function (e) {
  delete keys[e.keycode];
}, false);
/*
up - 38
down - 40
left - 37
right - 39
*/

function game() {
  update();
  render();
}

function update() {
  if (keys[38]) player.y -= speed;
  if (keys[40]) player.y += speed;
  if (keys[37]) player.x -= speed;
  if (keys[39]) player.x += speed;
}

function render() {
  context.clearRect(0, 0, 100, 100)

  context.fillRect(player.x, player.y, player.width, player.height);
}

setInterval(function () {
  game();
}, 1000 / 30);

if you can not tell i am very new to this and just learning the basics.

A: The value you want out of the event object is called keyCode, not keycode:

var canvas = document.getElementById("maincanvas");
var context = canvas.getContext("2d");

var keys = [];

var width = 500,
  height = 400,
  speed = 3;

var player = {
  x: 10,
  y: 10,
  width: 20,
  height: 20
};

window.addEventListener("keydown", function(e) {
  keys[e.keyCode] = true;
}, false);
window.addEventListener("keyup", function(e) {
  delete keys[e.keyCode];
}, false);
/*
up - 38
down - 40
left - 37
right - 39
*/

function game() {
  update();
  render();
}

function update() {
  if (keys[38]) player.y -= speed;
  if (keys[40]) player.y += speed;
  if (keys[37]) player.x -= speed;
  if (keys[39]) player.x += speed;
}

function render() {
  context.clearRect(0, 0, 100, 100)

  context.fillRect(player.x, player.y, player.width, player.height);
}

setInterval(function() {
  game();
}, 1000 / 30);
<canvas id="maincanvas"></canvas>

A: Another issue you might be running into is that keys is an array and you are treating it like an object. keys[38] is looking for a key at index 38 NOT a key with a value of 38. Set keys = {};
Edit Never mind, I see you are just setting the index at 38. I would say it's a little bit of a weird approach, consider using an object rather than an array.


Q: How React rerenders tree, if both parent and child components are dependent from one Redux store prop? I have Layout component, which checks if a user is logged in. It simply examines user prop in Redux store. If it is, it renders children, otherwise Login.

*

*Layout.jsx
const Layout = ({ user, children }) => {
  if (user) return children;
  return <Login />;
};

export default connect(state => ({ user: state.user }))(Layout);

*

*Profile.jsx
const Profile = ({ user }) => <div>{user.name}</div>;

export default connect(state => ({ user: state.user }))(Profile);

*

*App itself

<Layout>
  <Profile />
</Layout>

The issue is when Profile component is rendered and I log out, I get can not read property name of undefined.
I expect Profile component not to be rendered at all, because it is how Layout works. But looks like React first tries updating Profile component and fails.
For now I ended up returning null from Profile if there is no user, but it's not ideal.
So if both parent and child components are dependent on one Redux store prop, React rerenders them from down to the top, from top to down, or simultaneously? Is there a canonical or best practice way to avoid it?


Q: Error MSB3073 when creating a Monogame C# project in Visual Studio 2019 So I'm trying to simply create a new Monogame project in Visual Studio 2019 with C#, and every time I create a new project, the following error appears:
Error MSB3073 - The command "dotnet C:\Users\<name>\.nuget\packages\monogame.content.builder.task\3.8.0.1641\build\\..\tools\netcoreapp3.1\any\mgcb.dll /quiet /@:"E:\Programming\Locally-stored projects\C Family\C#\Monogame -OxygOS\Game1\Game1\Content\Content.mgcb" /platform:DesktopGL /outputDir:"E:/Programming/Locally-stored projects/C Family/C#/Monogame - OxygOS/Game1/Game1/Content/bin/DesktopGL/Content" /intermediateDir:"E:/Programming/Locally-stored projects/C Family/C#/Monogame - OxygOS/Game1/Game1/Content/obj/DesktopGL/Content" /workingDir:"E:/Programming/Locally-stored projects/C Family/C#/Monogame - OxygOS/Game1/Game1/Content/"" exited with code 1. Game1   C:\Users\<name>\.nuget\packages\monogame.content.builder.task\3.8.0.1641\build\MonoGame.Content.Builder.Task.targets    138

The only files in the projects are ones that are automatically created as part of the Monogame Cross-platform template.
I've already looked on Google and Stack Overflow, and, while there are answers, I haven't found any that have helped me.
Apologies if I messed up while creating the post, this is my first Stack Overflow question :D I may have messed up the formatting somewhere so sorry in advance if  I have.

A: It is a better approach that you would use the terminal to create your project (and then open them in Visual Studio). It is far more convenient for the Monogame community to release NuGet templates of the projects rather than releasing plugins for Visual Studio, and therefore it is safe to assume that Monogame won't be releasing such plugins for Visual Studio anytime soon.
Make sure you have dotnet-sdk installed and the Monogame tools are installed by doing all the steps mentioned here, Including the last two scripts
dotnet tool install --global dotnet-mgcb-editor
mgcb-editor --register

and
dotnet new --install MonoGame.Templates.CSharp

Now use the command dotnet new to view all the templates. You will probably see an output such as

Templates                                                   Short Name               Language          Tags
------------------------------------------------------      -------------------      ------------      ----------------------
...
...
MonoGame Android Application                                mgandroid                [C#]              MonoGame
MonoGame Cross-Platform Desktop Application (OpenGL)        mgdesktopgl              [C#]              MonoGame
MonoGame iPhone/iPad Application                            mgios                    [C#]              MonoGame
MonoGame Windows Universal Application (CoreApp)            mguwpcore                [C#]              MonoGame
MonoGame Windows Universal Application (XAML)               mguwpxaml                [C#]              MonoGame
MonoGame Windows Desktop Application (Windows DirectX)      mgwindowsdx              [C#]              MonoGame
MonoGame NetStandard Library                                mgnetstandard            [C#]              MonoGame
MonoGame Pipeline Extension                                 mgpipeline               [C#]              MonoGame
MonoGame Shared Library Project                             mgshared                 [C#]              MonoGame
...
...

Select the project you want to create, for example
dotnet new mgwindowsdx -o MyGame

This will create a folder "MyGame" and put the code for your game. You can open the .csproj file using Visual Studio.


Q: Choose window manager from command line I didn't know what Window Manager I should use: I like both Gnome/Unity of Ubuntu and LXDE of Lubuntu: sometimes I need lightweight (example maximize battery - Lubuntu), sometimes I need (want) Unity graphical design and Gnome apps.
So, I have Ubuntu. I have installed lxde by
sudo apt-get install lxde

Now, to improve boot speed, I don't want to use graphical login but command line login.
After login, I want to start the X server with the Window Manager I need in that moment: Gnome/Unity or LXDE.
What I have to do to start from terminal gnome/unity or lxde? I need to know both instruction! Thank you!!

A: Gnome, Unity and LXDE are desktop environments. However, they are not attached to the display manager(which starts the X servers, user sessions and greeter). Therefore, you can download a console display manager to have command-line login but graphical desktop.
I'd suggest you to use CDM (download link).
Just download the zip file from the link and do the following commands:
unzip ghost1227-cdm-[version].zip
cd ghost1227-cdm-[version]/
sudo ./install.sh

To autostart cdm when you log in your account, copy the content of /usr/share/doc/cdm/profile.sh to the tail of your shell profile (~/.profile, etc.).


Q: webpack -- how to include nodejs module for js/jsx in non-current directory Trying to include a npm module in my jsx.
My dir structure is something like:
   app/
     node_modules/
     webpack.config.json
     package.json
     main.js

   react/
     myreact1.jsx
     myreact2.jsx

Note: purposely do not want a package.json & node_modules in react/
I've figured out that I have to do this for webpack2 config:
   resolve: {
     modules: ["node_modules", path.resolve(__dirname, "node_modules")
   }

This forces webpack to first always try ./node_modules, then default to app/node_modules
However, for the module I'm trying to include in myreact.jsx (npm: "request"), this module uses alot of native node libraries like "fs" and "tls", etc.
webpack now gives me this error:
Abbreviated error:
ERROR in ./~/request/lib/har.js
Module not found: Error: Can't resolve 'fs' in '/myproj/app/node_modules/request/lib'
 @ ./~/request/lib/har.js 3:9-22
 @ ./~/request/request.js
 @ ./~/request/index.js
 @ ../react/myreact1.jsx
 @ ./app.jsx
 @ ./main.js

Display-error-details version of the error:
ERROR in ./~/request/lib/har.js
Module not found: Error: Can't resolve 'fs' in '/myproj/app/node_modules/request/lib'
resolve 'fs' in '/myproj/app/node_modules/request/lib'

How do I get webpack to correctly find the native node modules 'fs', 'tls', 'net' etc for 'request' module and the other 3rd party modules it uses inside it's own node_modules?
Thanks for any help


Q: JsnLog error posting in angular 4 with elmah at server side We are using Asp.net Web API 2 - Server side
Angular 4 in client side (angular-cli)
We have integrated Elmah on the server side for error handling.
We have integrated Jsnlog in the client side.
Our angular released version is hosted in http://ng.local.com and API released version is hotsed in http://api.local.com/. Now, We have gone through the docs of Jsnlog configuration. But, facing issue in error posting to the server (to our api released http://api.local.com/) i.e missing some configuration.
Can anyone know the configuration for Jsnlog to have the URL of the API server.

A: There is information found here to configure the endpoint for JSNLog.  Take a look at the "Configuring JSNLog" Section of this page (http://jsnlog.com/Documentation/HowTo/Angular2Logging and http://jsnlog.com/Documentation/JSNLogJs/AjaxAppender/SetOptions).
But to summarize, just add this line to your app.module.ts before the @NgModule({...
// Set the endpoint for JSNLog.

JL().setOptions({ 'appenders': [JL.createAjaxAppender('example appender').setOptions({'url': [Your Desired Endpoint Address] + '/jsnlog.logger'})] });

@NgModule({
...


Q: After Geoserver 2.8.2 Setup I have set up Geoserver 2.8.2 and, i am getting error below when i try to see functions under data part like (Layer, Workspace, Storage, Layer Preview)
I have read about regional settings and i changed those as English, United Kingdom, but it doesnt work.
org.apache.wicket.WicketRuntimeException: Exception in rendering component: [Component id = filterMatch]
    at org.apache.wicket.Component.renderComponent(Component.java:2725)
    at org.apache.wicket.markup.html.WebComponent.onRender(WebComponent.java:62)
    at org.apache.wicket.Component.render(Component.java:2517)
    at org.apache.wicket.MarkupContainer.renderNext(MarkupContainer.java:1440)
    at org.apache.wicket.MarkupContainer.renderComponentTagBody(MarkupContainer.java:1603)
    at org.apache.wicket.MarkupContainer.renderAssociatedMarkup(MarkupContainer.java:696)
    at org.apache.wicket.markup.html.panel.Panel.onComponentTagBody(Panel.java:114)
    at org.apache.wicket.Component.renderComponent(Component.java:2686)
    at org.apache.wicket.MarkupContainer.onRender(MarkupContainer.java:1538)
    at org.apache.wicket.Component.render(Component.java:2517)
    at org.apache.wicket.MarkupContainer.renderNext(MarkupContainer.java:1440)
    at org.apache.wicket.MarkupContainer.renderComponentTagBody(MarkupContainer.java:1603)
    at org.apache.wicket.MarkupContainer.onComponentTagBody(MarkupContainer.java:1527)
    at org.apache.wicket.markup.html.form.Form.onComponentTagBody(Form.java:1995)
    at org.apache.wicket.Component.renderComponent(Component.java:2686)
    at org.apache.wicket.MarkupContainer.onRender(MarkupContainer.java:1538)
    at org.apache.wicket.Component.render(Component.java:2517)
    at org.apache.wicket.MarkupContainer.renderNext(MarkupContainer.java:1440)
    at org.apache.wicket.MarkupContainer.renderComponentTagBody(MarkupContainer.java:1603)
    at org.apache.wicket.MarkupContainer.renderAssociatedMarkup(MarkupContainer.java:696)
    at org.apache.wicket.markup.html.panel.Panel.onComponentTagBody(Panel.java:114)
    at org.apache.wicket.Component.renderComponent(Component.java:2686)
    at org.apache.wicket.MarkupContainer.onRender(MarkupContainer.java:1538)
    at org.apache.wicket.Component.render(Component.java:2517)
    at org.apache.wicket.MarkupContainer.renderNext(MarkupContainer.java:1440)
    at org.apache.wicket.MarkupContainer.renderComponentTagBody(MarkupContainer.java:1603)
    at org.apache.wicket.MarkupContainer.onComponentTagBody(MarkupContainer.java:1527)
    at org.apache.wicket.Component.renderComponent(Component.java:2686)
    at org.apache.wicket.MarkupContainer.onRender(MarkupContainer.java:1538)
    at org.apache.wicket.Component.render(Component.java:2517)
    at org.apache.wicket.MarkupContainer.autoAdd(MarkupContainer.java:229)
    at org.apache.wicket.markup.resolver.MarkupInheritanceResolver.resolve(MarkupInheritanceResolver.java:66)
    at org.apache.wicket.markup.resolver.ComponentResolvers.resolve(ComponentResolvers.java:81)
    at org.apache.wicket.MarkupContainer.renderNext(MarkupContainer.java:1444)
    at org.apache.wicket.MarkupContainer.renderComponentTagBody(MarkupContainer.java:1603)
    at org.apache.wicket.MarkupContainer.onComponentTagBody(MarkupContainer.java:1527)
    at org.apache.wicket.Component.renderComponent(Component.java:2686)
    at org.apache.wicket.MarkupContainer.onRender(MarkupContainer.java:1538)
    at org.apache.wicket.Component.render(Component.java:2517)
    at org.apache.wicket.MarkupContainer.autoAdd(MarkupContainer.java:229)
    at org.apache.wicket.markup.resolver.MarkupInheritanceResolver.resolve(MarkupInheritanceResolver.java:73)
    at org.apache.wicket.markup.resolver.ComponentResolvers.resolve(ComponentResolvers.java:81)
    at org.apache.wicket.MarkupContainer.renderNext(MarkupContainer.java:1444)
    at org.apache.wicket.MarkupContainer.renderAll(MarkupContainer.java:1554)
    at org.apache.wicket.Page.onRender(Page.java:1575)
    at org.apache.wicket.Component.render(Component.java:2517)
    at org.apache.wicket.Page.renderPage(Page.java:913)
    at org.apache.wicket.request.target.component.BookmarkablePageRequestTarget.respond(BookmarkablePageRequestTarget.java:261)
    at org.apache.wicket.request.AbstractRequestCycleProcessor.respond(AbstractRequestCycleProcessor.java:105)
    at org.apache.wicket.RequestCycle.processEventsAndRespond(RequestCycle.java:1258)
    at org.apache.wicket.RequestCycle.step(RequestCycle.java:1329)
    at org.apache.wicket.RequestCycle.steps(RequestCycle.java:1436)
    at org.apache.wicket.RequestCycle.request(RequestCycle.java:545)
    at org.apache.wicket.protocol.http.WicketFilter.doGet(WicketFilter.java:484)
    at org.apache.wicket.protocol.http.WicketServlet.doGet(WicketServlet.java:138)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
    at org.springframework.web.servlet.mvc.ServletWrappingController.handleRequestInternal(ServletWrappingController.java:159)
    at org.springframework.web.servlet.mvc.AbstractController.handleRequest(AbstractController.java:153)
    at org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter.handle(SimpleControllerHandlerAdapter.java:48)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:778)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
    at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:487)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1093)
    at org.geoserver.filters.ThreadLocalsCleanupFilter.doFilter(ThreadLocalsCleanupFilter.java:28)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1084)
    at org.geoserver.filters.SpringDelegatingFilter$Chain.doFilter(SpringDelegatingFilter.java:75)
    at org.geoserver.wms.animate.AnimatorFilter.doFilter(AnimatorFilter.java:71)
    at org.geoserver.filters.SpringDelegatingFilter$Chain.doFilter(SpringDelegatingFilter.java:71)
    at org.geoserver.filters.SpringDelegatingFilter.doFilter(SpringDelegatingFilter.java:46)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1084)
    at org.geoserver.platform.AdvancedDispatchFilter.doFilter(AdvancedDispatchFilter.java:50)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1084)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:311)
    at org.geoserver.security.filter.GeoServerCompositeFilter$NestedFilterChain.doFilter(GeoServerCompositeFilter.java:69)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:116)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:83)
    at org.geoserver.security.filter.GeoServerCompositeFilter$NestedFilterChain.doFilter(GeoServerCompositeFilter.java:73)
    at org.geoserver.security.filter.GeoServerCompositeFilter.doFilter(GeoServerCompositeFilter.java:92)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
    at org.geoserver.security.filter.GeoServerCompositeFilter$NestedFilterChain.doFilter(GeoServerCompositeFilter.java:69)
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
    at org.geoserver.security.filter.GeoServerCompositeFilter$NestedFilterChain.doFilter(GeoServerCompositeFilter.java:73)
    at org.geoserver.security.filter.GeoServerCompositeFilter.doFilter(GeoServerCompositeFilter.java:92)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
    at org.geoserver.security.filter.GeoServerAnonymousAuthenticationFilter.doFilter(GeoServerAnonymousAuthenticationFilter.java:54)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
    at org.geoserver.security.filter.GeoServerCompositeFilter$NestedFilterChain.doFilter(GeoServerCompositeFilter.java:69)
    at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:182)
    at org.geoserver.security.filter.GeoServerCompositeFilter$NestedFilterChain.doFilter(GeoServerCompositeFilter.java:73)
    at org.geoserver.security.filter.GeoServerCompositeFilter.doFilter(GeoServerCompositeFilter.java:92)
    at org.geoserver.security.filter.GeoServerUserNamePasswordAuthenticationFilter.doFilter(GeoServerUserNamePasswordAuthenticationFilter.java:116)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
    at org.geoserver.security.filter.GeoServerCompositeFilter$NestedFilterChain.doFilter(GeoServerCompositeFilter.java:69)
    at org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter.doFilter(RememberMeAuthenticationFilter.java:146)
    at org.geoserver.security.filter.GeoServerCompositeFilter$NestedFilterChain.doFilter(GeoServerCompositeFilter.java:73)
    at org.geoserver.security.filter.GeoServerCompositeFilter.doFilter(GeoServerCompositeFilter.java:92)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
    at org.geoserver.security.filter.GeoServerCompositeFilter$NestedFilterChain.doFilter(GeoServerCompositeFilter.java:69)
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
    at org.geoserver.security.filter.GeoServerSecurityContextPersistenceFilter$1.doFilter(GeoServerSecurityContextPersistenceFilter.java:53)
    at org.geoserver.security.filter.GeoServerCompositeFilter$NestedFilterChain.doFilter(GeoServerCompositeFilter.java:73)
    at org.geoserver.security.filter.GeoServerCompositeFilter.doFilter(GeoServerCompositeFilter.java:92)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:173)
    at org.geoserver.security.GeoServerSecurityFilterChainProxy.doFilter(GeoServerSecurityFilterChainProxy.java:135)
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:259)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1084)
    at org.geoserver.filters.LoggingFilter.doFilter(LoggingFilter.java:83)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1084)
    at org.geoserver.filters.GZIPFilter.doFilter(GZIPFilter.java:42)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1084)
    at org.geoserver.filters.SessionDebugFilter.doFilter(SessionDebugFilter.java:48)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1084)
    at org.geoserver.filters.FlushSafeFilter.doFilter(FlushSafeFilter.java:44)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1084)
    at org.vfny.geoserver.filters.SetCharacterEncodingFilter.doFilter(SetCharacterEncodingFilter.java:109)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1084)
    at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:360)
    at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
    at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:181)
    at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:726)
    at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:405)
    at org.mortbay.jetty.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:206)
    at org.mortbay.jetty.handler.HandlerCollection.handle(HandlerCollection.java:114)
    at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
    at org.mortbay.jetty.Server.handle(Server.java:324)
    at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:505)
    at org.mortbay.jetty.HttpConnection$RequestHandler.headerComplete(HttpConnection.java:828)
    at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:514)
    at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:211)
    at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:380)
    at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:395)
    at org.mortbay.thread.BoundedThreadPool$PoolThread.run(BoundedThreadPool.java:450)
Caused by: java.lang.IllegalArgumentException: Unmatched braces in the pattern.
    at java.text.MessageFormat.applyPattern(Unknown Source)
    at java.text.MessageFormat.<init>(Unknown Source)
    at org.apache.wicket.model.StringResourceModel.getString(StringResourceModel.java:546)
    at org.apache.wicket.model.StringResourceModel.load(StringResourceModel.java:647)
    at org.apache.wicket.model.StringResourceModel.load(StringResourceModel.java:181)
    at org.apache.wicket.model.LoadableDetachableModel.getObject(LoadableDetachableModel.java:120)
    at org.apache.wicket.model.StringResourceModel$AssignmentWrapper.getObject(StringResourceModel.java:241)
    at org.apache.wicket.model.StringResourceModel$AssignmentWrapper.getObject(StringResourceModel.java:216)
    at org.apache.wicket.Component.getDefaultModelObject(Component.java:1720)
    at org.apache.wicket.Component.getDefaultModelObjectAsString(Component.java:1739)
    at org.apache.wicket.markup.html.basic.Label.onComponentTagBody(Label.java:114)
    at org.apache.wicket.Component.renderComponent(Component.java:2686)
    ... 138 more


Q: Freeing map of struct I am working with a very large map of pointer to struct. It is growing over the lifetime of the program (I use it as a buffer) and I wrote a function that is supposed to reduce it size when it is called.
type S struct {
 a uint32
 b []uint32
}

s := make(map[uint32]*S)

for k, v := range s {
  delete(s, k)
  s[k] = &S{a: v.a}
}

I remove b from every element of the map, so I expected the size of the map in memory to shrink (b is a slice of length > 10). However the memory is not freed, why?

A: The size of the map value &S, a pointer, is the same irrespective of the capacity of slice b.
package main

import (
    "fmt"
    "unsafe"
)

type S struct {
    a uint32
    b []uint32
}

func main() {
    size := unsafe.Sizeof(&S{})
    fmt.Println(size)

    size = unsafe.Sizeof(&S{b: make([]uint32, 10)})
    fmt.Println(size)

    s := make(map[uint32]*S)

    for k, v := range s {
        delete(s, k)
        s[k] = &S{a: v.a}
    }
}

Output:
8
8

A slice is represented internally by
type slice struct {
    array unsafe.Pointer
    len   int
    cap   int
}

When you set &S{a: v.a} you set b to initial values: array to nil and len and cap to zero. The memory formerly occupied by the underlying array is returned to the garbage collector for reuse.

A: The map size is bounded to the maximum size it had at any point. Because you store pointers (map[uint32]*S) and not values the deleted objects will get garbage collected eventually but usually not immediately and that why you don’t see it in top/htop like monitors.
The runtime is clever enough and reserves memory for future use if the system is not under pressure or low on resources.
See https://stackoverflow.com/a/49963553/1199408 to understand more about memory.
In your example you don't need to call delete. You will achieve what you want just by clearing the slice in the struct.
type S struct {
 a uint32
 b []uint32
}

s := make(map[uint32]*S)

for k, v := range s {
  v.b = []uint32{}
}


Q: Add Web Interface to existing Project I tried to understand this several times allready, but still have not found out how this should be done.
I want to create a web interface for some existing console or swing application. Something like the web interface SABNzb offers (I know, it's Python – it's just an example).
I have looked at several technologies allready, like creating web services using a tomcat server, or java server pages/faces, but all the tutorials that I found so far start with "Create a new Web Project..." at wich point I stop because this is not what I want! I have a finished an application in which I want to integrate a web interface, not some web service that instantiates my program as a local variable and uses its code. So basicaly it feels like all the tutorials I find are the wrong way around.
The core procedure of this is clear, the application should listen for http requests on a port I choose and answer with a created html code to it. So basicaly I could open a port using a socket and write an html page to its output on connect. But this rather feels like inventing the wheel all over again, also I'm not sure how an interactive web page would work this way.
Maybe I am thinking somewhat strange here or did not understand how some of these things work, but I am pretty unexperienced with web technologies, so grasping the concept is rather hard at the moment. Can anyone point me to a tutorial that shows how this might be done, or some other source of information on it?

A: You don't need JSP or JSF; all you need is a servlet.  It's an HTTP listener class.  You can do REST with that.
The moment you say that you have to deploy your servlet in a WAR on a servlet/JSP engine.  Tomcat is a good choice.
Google for a servlet tutorial and you'll be on your way.
My First Tomcat Servlet

A: Ok, thanks to duffymos answer and comments i realized i was actualy searching with the wrong keywords.
Embedded web server is the thing i was looking for.
Like Simple or build in HTTPServer class in java.