text:
Q: Sides Elimination in directed cyclic graph or Tournament (graph) I wanted an algorithm to eliminate the sides of a cyclic directed graph or mostly a Tournament and output a tree kind of structure with minimum number of sides.
The elimination should be based on the weight of the sides, as described below in as a simple real world example.
If there are three friends A,B,C. Take a scenario of borrowing & returning money between each other.
Person A has to transfer Person B - $10.
Person B has to transfer Person C - $20.
Person C has to transfer Person A - $20.
In the final settlement to minimize the number of transfers between each other we can rearrange the above to something like "Person B will transfer Person A - $10" and everything is settled.
I am looking for some algorithm which will work for any number of nodes when weight of each side and direction is given.
Given that the graph can be rearranged and chances are high that the graph might be a "Tournament" where each node is connected to all the nodes in the graph, what would be the best approach I follow.

A: n - 1 edges is pretty easy to obtain. First compute everyone's "net worth", put the borrowers in one list, put the lenders in another, and then repeatedly make a transfer from the borrower at the front of the line to the lender, removing one or both if they are saturated (returned to zero).
The preceding algorithm is a 2-approximation. Minimizing the number of transfers means maximizing the number of doubly-saturating transfers, which is a knapsack-like problem that's at least weakly NP-hard. There's an exponential-time dynamic program that might be suitable for small n (naive is more like n^n).


text:
Q: Use ldapjs with bluebird promise I posted something similar here: Use ldapjs with promise. Unfortunately, it is still unsolved.
This time I tried bluebird and hopefully I can get some luck.
// https://www.npmjs.com/package/ldapjs
var Promise = require('bluebird');
var ldap = Promise.promisifyAll( require('ldapjs') );
var config  = require('./config');
var print_r = require('print_r').print_r;

var my_filter = "(&(objectCategory=person)(objectClass=user)" + "(cn=" + 'someone' + "))";
var ldap_username = config.ad.username;
var ldap_password = config.ad.password;
var ldap_url = config.ad.url;
var ldap_dn_search = config.ad.dn_search;

process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
ldap.Attribute.settings.guid_format = ldap.GUID_FORMAT_B;

var opts = {
  filter: my_filter,
  scope: 'sub',
};

//test
console.log(my_filter);
console.log(ldap_username);
console.log(ldap_password);
console.log(ldap_url);
console.log(ldap_dn_search);

/* NOTE: This code is working!!!
client.bind(ldap_username, ldap_password, function (err) {
  client.search(ldap_dn_search, opts, function (err, search) {
    search.on('searchEntry', function (entry) {
      var user = entry.object;
      console.log(user);
    });
  });
});
*/

// I tried to rewrite the code above with promise
ldap.createClientAsync({
  url: ldap_url
})
.then(function(client){
  console.log('bind'); // No print
  return client.bindAsync(ldap_username, ldap_password);
})
.then(function() {
  console.log('search'); // No print
  return client.searchAsync(ldap_dn_search, opts);
})
.then(function(search) {
    // No flow here
  search.on('searchEntry', function (entry) {
    var user = entry.object;
    console.log(user);
  });
})

The script doesn't output anything. It is waiting for something in terminal.

A: Using Bluebird Promises, the easy way to do this is to create your client normally, and then run the promisifyAll() on the client.
var ldap = require('ldapjs');
var Promise = require('bluebird');

var client = ldap.createClient({
  url: 'ldap://my-server:1234',
});

Promise.promisifyAll(client);

Now you can call client.addAsync() and client.searchAsync() and such.
client.bindAsync(secUserDn, secUserPassword)
  .then(doSearch) // if it works, call doSearch
  .catch(function (err) { // if bind fails, handle it
    console.error('Error on bind', err)
  });

function doSearch(data) {
  client.searchAsync('CN=A Test,OU=Users,DC=website,DC=com', options)
    .then(function (data) { // Handle the search result processing
      console.log('I got a result');
    })
    .catch(function (err) { // Catch potential errors and handle them
      console.error('Error on search', err);
    });
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Splitting text file in Python - delimeter issue I try to split a file by delimeter: "}., but the delimeter is not found and as a result I get only one new file with the same content as the original one. The code is:
with  open('okladki_200_01') as fp:
    contents = fp.read()

    i = 1
    for entry in contents.split('"}.'):

        f= open("okladka_%s" % i,"w+")
        f.write(entry)
        f.close()
        i += 1

Can you help, please?
EDIT:
The content of the file is like:
{"base64Image":"/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB\nAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/2wBDAQEBAQEBAQEBAQEBAQEBAQEBAQEB\nAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/wAARCAusFMADASIA\nAhEBAxEB/8QAHwAAAgIBBQEBAAAAAAAAAAAAAgQAAwUBBgcICQoL/8QAaRAAAQEFBAcDBwgHBQYD\nAwEZAwIBBBESEwAhIiMFFDEyM0FDUVNhBiRCY3GBkQcIFTRSc6GxRGKDk8HR8FRyo+HxCRYlZLPD\ndILTFzWEkp [...] 3aIiVoL1pmNQxjWr27\nPBnhatT94NfdwDzDBz9aSP/Z\n","elementHashcode":-1794239528,"imageOrientation":6,"type":"BOOK"}
{"base64Image":"/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB\nAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB

And I think I just found the problem... HxD viewer displays 0x0A ASCII character as a dot, but it is New Line. So I should look for '"}\n'

A: Move contents.split('"}.') into its own variable.
lines = contents.split('.}"')

for entry in lines:
    ...

Code :
with  open('textfile') as fp:
    contents = fp.read()

i = 1

lines = contents.split('.}"')

for entry in lines:
    f= open("textfile_%s" % i,"w+")
    f.write(entry)
    f.close()
    i += 1

fp.close()

A: Do you actually need to check for brackets? In your case it seems like your input file is already formatted with 1 content = 1 line, so our delimiter could be \n instead and we can use readlines().
Here is a possible solution:
with  open('okladki_200_01') as fp:
    lines = fp.readlines() # this is a list of strings.

    i = 1
    for line in lines:
        entry = line.lstrip("{").rstrip("}\n") # some clean-up.
        f = open("okladka_%s" %i ,"w+")
        f.write(entry)
        f.close()
        i += 1


text:
Q: Selected radio button taking value of previous one I am coding a quiz in a JSP and have a problem where the radio buttons don't seem to be working properly. The questions are stored in a MySQL database and retrieved using procedures. When the user clicks on a radio button and submits it, the code will always output 'Incorrect' even if the correct answer is selected. Whilst running through the code, I have noticed that the radio buttons seem to skip back to the previous question's answer.
For example, for question 1, the selected radio button does not return anything. On question 2, the radio button returns the answer from question 1. On question 3, it returns the answer in the same position as question 2, and so on.
How do I fix this?
I am aware that using scriptlets is bad practice; this will be resolved after I complete the development of my code.
<%
//Initalising necessary variables to be used in connection stream
Connection conn = null;
ResultSet rs = null;
Statement st = null;

//Setting SCORE and QID to 0
//Checking to see if SCORE and QID already exist
//If so, the existing value is retrieved and overwritten
//The variables now hold the existing values
int score = 0;
if(request.getParameter("score")!=null) {
      score=Integer.parseInt(request.getParameter("score"));
    }
int QID=1;
if(request.getParameter("QID")!=null) {
 QID=Integer.parseInt(request.getParameter("QID"));
}

//Setting up connection stream to MySQL database on the server
//Using my credentials to log in and access tables
try {
    Class.forName("org.mariadb.jdbc.Driver");
    conn = DriverManager.getConnection(
            "jdbc:mariadb://URL;

//Calling procedure to obtain question description from the stored question table in stored database
    CallableStatement stmt = conn.prepareCall("{call GetQuestionTitle(?, ?)}");
        stmt.setInt(1, QID);
        stmt.registerOutParameter(2, Types.VARCHAR);
        stmt.execute();
        String description = stmt.getString(2);
%>
<%

//Calling all procedures to obtain the answers to each question stored in the database
    CallableStatement answer1 = conn.prepareCall("{call GetAnswer1(?, ?)}");
        answer1.setInt(1, QID);
        answer1.registerOutParameter(2, Types.VARCHAR);
        answer1.execute();
        String answerOne = answer1.getString(2);

    CallableStatement answer2 = conn.prepareCall("{call GetAnswer2(?, ?)}");
        answer2.setInt(1, QID);
        answer2.registerOutParameter(2, Types.VARCHAR);
        answer2.execute();
        String answerTwo = answer2.getString(2);

    CallableStatement answer3 = conn.prepareCall("{call GetAnswer3(?, ?)}");
        answer3.setInt(1, QID);
        answer3.registerOutParameter(2, Types.VARCHAR);
        answer3.execute();
        String answerThree = answer3.getString(2);

    CallableStatement answer4 = conn.prepareCall("{call GetAnswer4(?, ?)}");
        answer4.setInt(1, QID);
        answer4.registerOutParameter(2, Types.VARCHAR);
        answer4.execute();
        String answerFour = answer4.getString(2);

%>
<%
//Defining String variable CHOSENANSWER to store value of user-selected radio button
String chosenAnswer="";
if(request.getParameter("button")!=null)
{
chosenAnswer=request.getParameter("button").toString();
}

//Calling procedure to obtain the CorrectAnswer from database
CallableStatement stmt2 = conn.prepareCall("{call GetCorrectAnswer(?, ?)}");
    stmt2.setInt(1, QID);
    stmt2.registerOutParameter(2, Types.VARCHAR);
    stmt2.execute();
    String CorrectDescription = stmt2.getString(2);
    System.out.println("\nCorrect Answer: " + CorrectDescription);

%>
<%
//For all questions up to Question 20 and not beyond:
if (QID < 21){
%>

<form name="Quiz" method="post" action='Quiz.jsp'>

Quiz

 QUESTION <%=QID%>

<%=description%>

1: <input type="radio" name="button" value= "<%=answerOne%>" /><%=answerOne%>

2: <input type="radio" name="button" value="<%=answerTwo%>" /><%=answerTwo%>

3: <input type="radio" name="button" value="<%=answerThree%>" /><%=answerThree%>

4: <input type="radio" name="button" value="<%=answerFour%>" /><%=answerFour%>

<input type="submit" value="Next" name="submit">

<%
//Check to see if selected radio button matches CorrectAnswer procedure value
       if(chosenAnswer.equals(CorrectDescription)) {
           %>

        <input name="score" type="HIDDEN" value="<%=score+1%>" id="scoreField">

Correct!

       <%

        }
            else{
                 %>

                 <input name="score" type="HIDDEN" value="<%=score%>" id="scoreField">

Incorrect!

                 <%
    }
System.out.println(chosenAnswer);
%>
<%
//Passing score as a session attribute so that it remains as a variable on page refresh and redirect
//session.setAttribute("Score", score);

%>

<input name="QID" type="HIDDEN" value="<%=QID+1%>" id="thisField">
</form>

I have only included the parts of the code that I think is neccessary to the question.

A: When your page get loads for the first time , your QID is 1 then you increment that  i.e : <%=QID+1%>" and when you submit your QID becomes 2 so i think the problem is here CallableStatement stmt2 = conn.prepareCall("{call GetCorrectAnswer(?, ?)}");.. here QID which you will pass is 2 then the CorrectDescription will fetch correct answer of question 2 not question 1 , that's why its giving Incorrect! . Now to solve this you can add one new input under your <form> tag. i.e:
<input type="hidden" name="current_question" value="<%=QID%>"/>

and then get it like below :
    int previous_question_no;
    String chosenAnswer="";
    if(request.getParameter("button")!=null)
    {
    chosenAnswer=request.getParameter("button").toString();
    //getting question no which is submitted
    previous_question_no=Integer.parseInt(request.getParameter("current_question"));

    }
   //Calling procedure to obtain the CorrectAnswer from database
    CallableStatement stmt2 = conn.prepareCall("{call GetCorrectAnswer(?, ?)}");
   //passing same question no
        stmt2.setInt(1, previous_question_no);
        stmt2.registerOutParameter(2, Types.VARCHAR);
        ..


text: Q: Is there anyway to make a certain project in a solution Readonly in VS2010 I currently have multiple projects inside a solution in VS2010. Sometimes while working on one project inside the solution I need to look at some files from a different solution. However I am always afraid that I might make some accidental changes to the project that I am only referring to. Is there any way to make a project readonly inside a solution in VS2010 ?


text:
Q: Adding a 'Folder Group' using Outlook API I am trying to add a Folder Group to outlook using the Office API.  I can successfully add folders but I cannot figure out how to add a higher level folder

I would like to add my folder on the level of My Contacts or iCloud but I cant figure out how.  Im not even sure how to do it in outlook other than right-clicking My Contacts and making a new Folder Group then I have to create the folder under an exisitng group and then move it to my new group
Any ideas on how to acheive this programmatically
Thanks
Matt

A: In Outlook API class for "Folder Groups" is NavigationGroup.
Which could be gotten from Explorer class.
The code below creates NavigationGroup with name "New Folder Group" and then adds outlook folder "New Folder" in this group. Code is very simple and doesn't check if any group or folder already exists or any other errors. Just sample to describe how API works.
string navigationGroupName = "New Folder Group";
string folderName = "New Folder";

ContactsModule contactsModule = Globals.ThisAddIn.Application.ActiveExplorer().NavigationPane.Modules.GetNavigationModule(OlNavigationModuleType.olModuleContacts) as ContactsModule;

NavigationGroup navigationGroup = contactsModule.NavigationGroups.Create(navigationGroupName);

Folder contactFolder = (Folder) Globals.ThisAddIn.Application.Session.GetDefaultFolder(OlDefaultFolders.olFolderContacts).Folders.Add(folderName, OlDefaultFolders.olFolderContacts);

navigationGroup.NavigationFolders.Add(contactFolder);


text:
Q: Make each div fade in after 0.2 seconds sequentially, not ascynchronously I have the following function which makes every div inside #pic-grid fade and zoom in.
I want each div to fade in in sequence, but slightly overlapping. The transition of each fade-in is 0.2 so I want the first div to fade in at 0.1 (already set in code by the setTimeout for 100) and then the second div should start loading in after only 0.1s (100 milliseconds).
I have tried adding setTimeout to the .each() function but it doesn't seem to transition at all.
function fadeInImages(parentDiv){
            setTimeout(function(){
                $(parentDiv).children('div').each(function () {
                        console.log(this);
                        $(this).css('opacity','1').css('transform','scale(1)');
                });
            }, 100);
        }

Codepen: http://codepen.io/franhaselden/pen/RWyxqJ

A: Here is my code, simple, no timeouts, no delays:
DEMO http://codepen.io/anon/pen/MaGQvm
var i = 0;
var length = $('#pic-grid').children('div').length;
doAnimate(i, length);
function doAnimate(i, length){
  if(i < length){
     $($('#pic-grid').children('div')[i]).animate({"opacity": 1}, 100, function(){doAnimate(i + 1, length);});
  }
}

A: You can use this code:
JS:
var animate = function(fadeIn, time, offset) {

  $(fadeIn).each(function() {
    var me = $(this);
    setTimeout(function() {
      me.css({
        'opacity': 1,
        'transform': 'scale(1)'
      });
    }, time)
    time = time + offset;
  });
}

animate('#pic-grid > div', 0, 500);

CODEPEN

A: This code is based primarily on your codepen, with some minor tweaks:
setTimeout(function() {
  // We need to store the time delay so we can increment it
  var t = 0;
  $('#pic-grid').children('div').each(function() {
    // setTimeout looses the "this" scope, so set a variable here to use in setTimeout
    var _this = $(this);
    setTimeout(function() {
      _this.css('opacity', '1').css('transform', 'scale(1)')
    }, (++t * 200));
  });
}, 100);

http://codepen.io/anon/pen/OyZzdd

A: use below code
DEMO
var i = 0;
var divLength = $('#pic-grid').children('div').length;
var interval = setInterval(function() {

  $('#pic-grid').children('div:eq('+i+')').css('opacity', '1').css('transform', 'scale(1)')
  if(divLength == (i + 1)){
    clearInterval(interval)
  }
  i++;

}, 200);

A: See http://codepen.io/anon/pen/RWyxmY
$('#pic-grid').children('div').hide();
setTimeout(function() {
  var timeSpanMS = 200;
  $('#pic-grid').children('div').each(function(i) {
    console.log(this);
    $(this).delay( i*(timeSpanMS/2) ).fadeIn(timeSpanMS);
  });
}, 100);


text:
Q: How do you install PHPUnit without using PEAR on Mac OS X 10.5? I am having trouble installing PEAR, but I really only want to install PHPUnit. Does anyone have experience doing this?

A: Install via GIT
You can follow the instructions from the Git README: https://github.com/sebastianbergmann/phpunit/
"git" the files and drop them in your home directory
cd ~ && mkdir phpunit && cd phpunit
git clone git://github.com/sebastianbergmann/phpunit.git
git clone git://github.com/sebastianbergmann/dbunit.git
git clone git://github.com/sebastianbergmann/php-file-iterator.git
git clone git://github.com/sebastianbergmann/php-text-template.git
git clone git://github.com/sebastianbergmann/php-code-coverage.git
git clone git://github.com/sebastianbergmann/php-token-stream.git
git clone git://github.com/sebastianbergmann/php-timer.git
git clone git://github.com/sebastianbergmann/phpunit-mock-objects.git
git clone git://github.com/sebastianbergmann/phpunit-selenium.git

setup a personal binary path
cd ~ && mkdir bin
vi ~/.profile
>> export PATH=$HOME/bin:$PATH
>> :wq
source ~/.profile

create the executable
touch ~/bin/phpunit
chmod 755 ~/bin/phpunit

write the executable
#!/usr/bin/env php
<?php

// set main method
define('PHPUnit_MAIN_METHOD','PHPUnit_TextUI_Command::main');

// add phpunit to the include path
$paths = scandir($_ENV['HOME'].'/phpunit');
$includes = array();
foreach($paths as $path){
    if (!preg_match('/^\./', $path)){
        $includes[] = $_ENV['HOME'].'/phpunit/' . $path;
    }
}
set_include_path(implode(PATH_SEPARATOR,$includes).PATH_SEPARATOR.get_include_path());

// set the auto loader
require 'PHPUnit/Autoload.php';

// execute
PHPUnit_TextUI_Command::main();

test the executable
which phpunit
phpunit --version

A: From the PHPUnit installation guide:

Although using the PEAR Installer is the only supported way to install PHPUnit, you can install PHPUnit manually. For manual installation, do the following:

*

*Download a release archive from http://pear.phpunit.de/get/ and extract it to a directory that is listed in the include_path of your php.ini configuration file.

*Prepare the phpunit script:

*

*Rename the phpunit.php script to phpunit.

*Replace the @php_bin@ string in it with the path to your PHP command-line interpreter (usually /usr/bin/php).

*Copy it to a directory that is in your path and make it executable (chmod +x phpunit).

*Prepare the PHPUnit/Util/Fileloader.php script:

*

*Replace the @php_bin@ string in it with the path to your PHP command-line interpreter (usually /usr/bin/php).

A: Andrew, I am wrestling with installing PHPUnit at the moment. Found out that it helps a lot if restart your Webserver after updating the include_path in php.ini.
Now looking for the exact location of the PHP command line interpreter (that is how I got here). I'll keep you informed.
Sabine

A: I just installed it today. My steps were as follows:

*

*download from /get/ - I used 3.3.9.tgz

*extract all files into the pear directory (pear-phpunit, PHPUnit/, etc...)

*change the @php_bin@ to point to my php binary (/usr/bin/php) in the files mentioned above

*create a symlink from pear-phpunit to /usr/local/bin/phpunit ( ln -s /usr/share/php/pear/pear-phpunit /usr/local/bin/phpunit )

A: I recently made a github fork of phpunit that currently works (mostly) without the use of pear. It might work for you.


text:
Q: Retrofit returns content length 0 with spring data rest I am using spring boot application with spring data rest deployed on heroku. I have a /api/userDatas end point on which an entity can be created by a POST request. I have tested it using Postman and it gets created.
Now I am using retrofit on android to perform the same functionality. But the problem is that entity gets created on the server but onFailure() always gets called. I have debugged and found that content-length is always 0.
CreateUser
private void createUser() {
        Gson gson = new GsonBuilder()
                .setLenient()
                .create();

        HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
        logging.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient client = new OkHttpClient.Builder().addInterceptor(logging).build();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(ServeNetworking.ServeURLS.getBaseURL())
                .addConverterFactory(GsonConverterFactory.create())
                .client(client)
                .build();

        ServeNetworking serveNetworking = retrofit.create(ServeNetworking.class);
        Call<UserData> getUserByIdResponseCall = serveNetworking.socialConnectAPI(userData);
        getUserByIdResponseCall.enqueue(new Callback<UserData>() {
            @Override
            public void onResponse(Call<UserData> call, Response<UserData> response) {
                Log.d("getUserById", "onResponse");
                Toast.makeText(OTPVerificationActivity.this, "userId : onResponse", Toast.LENGTH_LONG).show();
                /**
                 * Save data in local db and navigate to map screen.
                 */

                ActivityAnimationUtils.presentActivity(OTPVerificationActivity.this, MapActivity.class);

                try{
                    DBManager.getDBManager(OTPVerificationActivity.this).setIsVerified(true);
                } catch (Exception e){
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(Call<UserData> call, Throwable t) {
                Log.d("getUserById", "onFailure");
                Utils.showSnackBar(OTPVerificationActivity.this,"Somethign went wrong", root);
            }
        });
    }

and interface:
public interface ServeNetworking {

    @POST("/api/userDatas")
    @Headers({ "Content-Type: application/json;charset=UTF-8"})
    Call<UserData> socialConnectAPI(
            @Body UserData user
    );

    @GET("/api/userDatas/{userId}")
    @Headers({ "Content-Type: application/json; charset=utf-8"})
    Call<UserData> getUser(
            @Path("userId") String userId
    );

    /**
     * this class is used to get the donor base urls...
     */
    class ServeURLS{
        private static String baseURL="https://fabrimizer-serve.herokuapp.com";

        public static String getBaseURL() {
            return baseURL;
        }

    }
}

I am getting following error:
java.io.EOFException: End of input at line 1 column 1 path $

A: Found the solution.
added Accept header in ServeNetworking:
@POST("/api/userDatas")
    @Headers({ "Content-Type: application/json,"Accept: application/json"})
    Call<UserData> socialConnectAPI(
            @Body UserData user
    );


text:
Q: Vue + Laravel in Heroku I am trying to upload my Laravel+Vue.js on Heroku, but the components do not appear, only the blades
I did the following steps:

*

*git init

*echo "web: vendor/bin/heroku-php-apache2 public/" > Procfile

*heroku create

*heroku buildpacks:add heroku/nodejs

*heroku config:set NPM_CONFIG_PRODUCTION=false

*package.json:
"scripts": {
   "postinstall": "npm run prod"
}

*

*heroku config:set APP_KEY="My app key"

*git push heroku master


text:
Q: Enforce synchronicity in multi agent systems In an effort to learn both scala and akka I'm writing a Battleship game. I've not started actually writing any code yet, I'm merely thinking about how things would work.
I have agents for ships and player fleets, and messages such as "shot fired", "hit", "miss", "all ships killed". My first stumbling block is that when player 1 shoots it creates a burst of events, and player 2 must wait until all has settled before he can play his turn. How can I make sure of that ? I thought maybe I'd always send a reply no matter what, and then count that a sender receive exactly as many answers as messages sent. Maybe Battleship isn't the best candidate application for agents.
This also brings the question of making the difference between receiving no answer because the message was not processed yet, the agent didn't reply anything, or the agent died. But I'll save that one for later.

A: There are a number of things you might want to do here:

*

*Have the first actor receive replies to each of its messages and then send a your turn message to the second actor

*Send a message to the second actor indicating how many events in a given turn must be received
These are achievable as follows:
import akka.pattern._
(d1 ? m1) zip (d2 ? m2) pipeTo that

in the above example, d1/2 are the destination actors, m1/2 are the messages to be sent. The replies from these actors are zipped together (into a Tuple2) and forwarded on to the second actor (that in the example)
The second mechanism is a bit more involved; I've written similar things using SyncPoints. So, something like this:
case class SyncPoint(id: UUID, participants: ActorRef*)
object SyncPoint {
  def newFor(participants: ActorRef*) = SyncPoint(UUID.createRandomUUID, participants)
}

Then the creator of a message sends out a SyncPoint to the ultimate observer first
val sync = SyncPoint.newFor(d1, d2)
that ! sync

Now the ultimate receiver knows it is expecting a message on this SyncPoint for each participant.
d1 ! SyncPart(m1, sync)
d2 ! SyncPart(m2, sync)

Where
case class SyncPart(msg: Any, sync: SyncPoint)

The actors d1 and d2 will forward on to that when they have processed their part in the message.
case class SyncPartial(sync: SyncPoint, participant: ActorRef)

In this way, that knows it is expecting messages from a number of participants and can then track when these participants have performed their processing.


text:
Q: What happens to FK if I drop a table with set foreignkey_checks=0 in MySQL? When I drop some tables with set foreign_key_checks=0, then are the constraints(like foreign keys) on those tables also dropped? Or we will end up with some orphan constraints, that are not related to any tables at all?

A: No it only drop the table with the triggers on it
other tables views remains


text:
Q: Can't access some sites after connecting to VPN Like the title says, after connecting to my work's VPN I can't access some sites that I could 2 days ago. I tried connecting from another computer (using the same credentials), and everything works as expected, so it seems that something is wrong with my main computer.
I have used the build-in Windows 10 VPN but also tried SmartVPN (which also creates a VPN connection using the build-in Windows 10 VPN, but I thought I should give it a try). I've also made sure to use the default gateway on remote network.
Things I've noticed:

*

*I can access google.com, youtube.com

*I can't access github.com, monday.com

*I can ping github.com, monday.com succesfully

I've also tried multiple browsers after the above results, because a successful ping didn't make sense to me, but no luck there.
VPN Type: L2TP/IPsec with pre-shared key

A: I've solved my problem by reducing my VPN's interface MTU to 1360.
ping sends 32 bytes by default, while the interface uses the MTU value which in my case (VPN interface) was 1400. (I found it with netsh interface ipv4 show subinterfaces while connected to VPN)
So trying to ping github.com (which was successful before) like ping -f -l 1400 github.com, I was sending 1400 bytes of data and this was failing.
I tried reducing this value till it was successful and then I changed my default MTU for the VPN interface to this value netsh interface ipv4 set subinterface "Name of VPN Interaface Here" mtu=1360 store=persistent


text:
Q: Issue with Pandas: ImportError libstdc++.so.6 inside a Conda environment running PyCharm IDE I am using PyCharm IDE from within a Conda environment and I am writing some python 3.10 code that uses the Pandas. This is on a brand new Linux Ubuntu 20.04 build (about a couple of days old) and I'm running into library issues:
import pandas._libs.window.aggregations as window_aggregations
ImportError: /lib/x86_64-linux-gnu/libstdc++.so.6: version `GLIBCXX_3.4.29' not found (required by /home/anthony/anaconda3/envs/CPRD-software/lib/python3.10/site-packages/pandas/_libs/window/aggregations.cpython-310-x86_64-linux-gnu.so)

I've tried updating LD_LIBRARY_PATH to include the libstdc++.so.6 location but that didn't work.
I've looked inside the ./lib directory of my environment (~/anaconda3/env/CPRD-software/lib) and I can see:
libstdc++.so.6 -> /usr/lib/x86_64-linux-gnu/libstdc++.so.6

Also, when I've tried numerous ways of installing Pandas (pip, conda and within PyCharm IDE) it always installs version 1.4.4, and never 1.5.0 including when I've tried conda install pandas=1.5.0.
I'm not sure where to start and I am loath to "hack" around too much without having a firmer grasp on a possible solution.

A: Try running these following commands
sudo add-apt-repository ppa:ubuntu-toolchain-r/test -y
sudo apt-get update
sudo apt-get upgrade libstdc++6 -y


text:
Q: How do I substitute based on character and position in word I have one word per cell. I need to substitute characters with other characters based on a range of conditions, as follows.
Condition 1 - if the word contains an 'l' double it to 'll'.
Condition 2 - if the first vowel in the word is an 'e', split the word with an apostrophe after said 'e'.
Condition 3 - the last vowel of each word becomes an 'i'.
Condition 4 - if the word ends in 'a','e','i','o', add an m to the end.
Ideally, I'd like them all to work in one formula, but each working separately would suffice. I can apply in a chain, cell to cell.
Condition 1 - SUBSTITUTE(SUBSTITUTE(E2,"l","ll"),"L","Ll")
This is successful.
Condition 2 - SUBSTITUTE("e","e'",1)
Applies to every 'e', rather than only when it is the first vowel in the word.
Together, these work as =SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(E2,"l","ll"),"L","Ll"),"e","e'",1)
Condition 3 - NO CURRENT FORMULA
Condition 4 - IF(RIGHT(TRIM(F2),1)="a",F2&"m",F2&"")
Works for a single letter (in this case "a"), but not for all required letters at once.

A: Use regexreplace(), like this:
=lambda(
  data, regexes, replaceWith,
  byrow(
    data,
    lambda(
      word,
      if(
        len(word),
        reduce(
          trim(word), sequence(counta(regexes)),
          lambda(
            acc, regexIndex,
            regexreplace(
              acc,
              "(?i)" & index(regexes, regexIndex),
              index(replaceWith, regexIndex)
            )
          )
        ),
        iferror(1/0)
      )
    )
  )
)(
  A2:A10,
  { "l", "^([^aeiou]*)(e)", "[aeiou]([^aeiou]*)$", "([aeio])$" },
  { "ll", "$1e-", "i$1", "$1m" }
)

The formula will only deal with lowercase letters because that is what is specified by the question. To replace uppercase letters as well, prefix the first index() with "(?i)" & . Note that case will not be retained.


text:
Q: Add a column of zeros to table sql server
Possible Duplicate:
Add column, with default value, to existing table in SQL Server

I have a table in sql server, but want to add a extra column full of zeros
What would be the best approach to do this
att1 att2
---------
1.0   5.8
2.7   3.8
5.1   6.8

becomes
att1 att2  extra
----------------
1.0   5.8   0.0
2.7   3.8   0.0
5.1   6.8   0.0

A: I understand this column will always have value of 0.0. Then it does not have to be a real column
CREATE TABLE extraColumn (
     att1   float  NULL
    ,att2   float  NULL
    ,extra AS 0.0
)

But if you need that, you can persist it
CREATE TABLE extraColumn (
     att1   float  NULL
    ,att2   float  NULL
    ,extra AS 0.0  PERSISTED
)

A: If I recall correctly, it should be something like:
ALTER TABLE table_name
ADD extra REAL DEFAULT 0

See: http://msdn.microsoft.com/en-us/library/ms190273.aspx
See: Add a column with a default value to an existing table in SQL Server


text:
Q: NSolve claims there are no solutions in Reals but finds them without restriction to Reals When trying to answer this question I've discovered what looks like a bug in NSolve introduced in version 11.1.0.
$Version

"11.1.0 for Microsoft Windows (64-bit) (March 13, 2017)"

With setup
Clear[dBeta, solnEquation, solnFun];

dBeta[k_Integer, x_, var1_] = Derivative[k, 0][Beta[#1, #2, 2] &][x, var1];
solnEquation[var1_, var2_, x_] = Sum[Binomial[5, k]*dBeta[k, x, var1]*var2^k, {k, 0, 5}];
equation[var1_, var2_, x_] := solnEquation[var1, var2, x] == Beta[2, 2];

Solve is able to find two solutions for var1 = 2, var2 = 1/10:
sol = Solve[equation[2, 1/10, x] && 0 < x < 1, x, Reals];
equation[2, 1/10, x] /. Normal@sol // N

Solve::incs: Warning: Solve was unable to prove that the solution set found is complete.
{True, True}

While NSolve claims that there are no solutions in the real domain:
NSolve[equation[2, 1/10, x] && 0 < x < 1, x, Reals]

{}

But without this restriction it finds two solutions in the real domain:
NSolve[equation[2, 1/10, x] && 0 < x < 1, x]
equation[2, 1/10, x] /. %

{{x -> 0.328152}, {x -> 0.741041}}

{True, True}

In version 11.0.1 NSolve gives correct answer for the real domain:
$Version

"11.0.1 for Microsoft Windows (64-bit) (September 20, 2016)"

NSolve[equation[2, 1/10, x] && 0 < x < 1, x, Reals]

{{x -> 0.3281517106189123`}, {x -> 0.7410414526199698`}}

Is it a bug in version 11.1.0?

A: A possible cure for your problem is to use FunctionExpand[] to ensure that the incomplete beta function is expanded to the actual polynomial it represents. Thus:
NSolve[FunctionExpand[equation[2, 1/10, x]] && 0 < x < 1, x, Reals]
   {{x -> 0.3281517106189123}, {x -> 0.7410414526199698}}

A: This is a precision issue
$Version

(* "12.0.0 for Mac OS X x86 (64-bit) (April 7, 2019)" *)

Clear[dBeta, solnEquation, solnFun];

dBeta[k_Integer, x_, var1_] = Derivative[k, 0][Beta[#1, #2, 2] &][x, var1];
solnEquation[var1_, var2_, x_] =
  Sum[Binomial[5, k]*dBeta[k, x, var1]*var2^k, {k, 0, 5}];
equation[var1_, var2_, x_] := solnEquation[var1, var2, x] == Beta[2, 2];

sol = Solve[equation[2, 1/10, x] && 0 < x < 1, x, Reals];

Note that using machine precision the imaginary parts are only approximately zero.
sol // N

(* {{x -> ConditionalExpression[0.328152 + 0. I,
    0.0420629 + 0. I ∈ Reals]}, {x ->
   ConditionalExpression[0.741041 + 0. I, 0.138925 + 0. I ∈ Reals]}} *)

The solutions are exact
equation[2, 1/10, x] /. sol // FullSimplify

(* {True, True} *)

However, when using NSolve for this problem you cannot use machine precision. Use arbirary-precision by specifying the WorkingPrecision
NSolve[equation[2, 1/10, x] && 0 < x < 1, x, Reals,
 WorkingPrecision -> 15]

(* {{x -> 0.328151710618912}, {x -> 0.741041452619970}} *)

EDIT: Alternatively, since 0 < x < 1implies thatx` is real just use
NSolve[equation[2, 1/10, x] && 0 < x < 1, x]

(* {{x -> 0.328152}, {x -> 0.741041}} *)


text:
Q: How to use dynamic from in Camel route or restart route without stopping application I have existing Spring Boot application that uses Camel framework for getting data from different folders. All routes poll data in similar way:
from(fileUriWithCurrentDay(path, config.getParams())).routeId(ROUTE_ID)

where method defined as follows:
public static String fileUriWithCurrentDay(String path, Map<String, String> params) {
path = path.endsWith(SEPARATOR) ? path : path + SEPARATOR;
return "file:" + path + currentDayPath() + fileParams(params);
}

and returns something like depending on the day:
c:/test/data/2021/242?noop=true&idempotent=false&autoCreate=false&includeExt=xml&scheduler=spring&scheduler.cron = "0 0 13 ? * *"

The cron is set to start one time per day. When cron time is reached the route starts to perform its job and finishes it correctly. But on the next day it starts to poll the same folder, e.g. 242 but it should be 243.
So the problem is: from endpoint should be calculated dynamically at its start.
I've read about dynamic from: in Camel, but didn't find any information that such option is supported out of the box.
I've tried to use pollEnrich() option using header that is calculated, but it seem doesn't support dynamic endpoints as returns next error:

org.apache.camel.ResolveEndpointFailedException Dynamic expressions
with ${ } placeholders is not allowed. Use the fileName option to set
the dynamic expression.

How from endpoint can be refreshed after route is started?
I also see 2 possible solutions but didn't know will it help:

*

*Restart routes for recalculating from endpoint uri.

*Restart whole Camel context. Currently all routes are marked as Spring @Component.

A: Unlike other EIP component, string in routeId and from endpoint are fixed once the route is created (unless you recreate the route with another from endpoint url). Thus, 2 possible direction to move on. One way is to recreate the route with new from endpoint url and another is to lookup parameter in the component to support your action.

*

*Recreate consumer route with same routeId in same CamelContext

*

*Trigger below action daily (e.g. use timer route)

*Use RouteBuilder to build route config (with same consumer route id and new from endpoint url)

*recreate route using addRoutes method of CamelContext class with new route config

*Leverage filterDirectory in file component

*

*Set file path to common root folder (i.e. c:/test/data)

*Enable recursive to lookup sub-directories

*Use filterDirectory to filter directory base on simple language

*

*From simple language documentation, date command of simple language is using java.text.SimpleDateFormat

*From Oracle doc, SimpleDateFormat do support both year and Day in year (assume 242 and 243 in your example are day in year)

Disclaimer
I did not use filterDirectory before, way 2 is deduce from Camel documentation.

A: Looking at the documentation for the File component what you are trying to do is not possible purely with the from-endpoint URI.
I would suggest using a common base directory in the URI and creating an implementation of GenericFileFilter that you'd use with the from-endpoint. It allows for a lot of freedom in implementing the logic for which files are and which aren't processed.
To read files from base/path/2021 create something like this:

@Component
public class FileFilter<T> implements GenericFileFilter<T> {
    @Override
    public boolean accept(GenericFile<T> file) {
        if (file.isDirectory()) {
            return "2021".equals(file.getFileName());
        }
        return file.getFileName().startsWith("2021/");
    }
}

with endpoint URI like this:
file://base/path?recursive=true&filter=#fileFilter
When implementing the GenericFileFilter you should be mindful that accept() will be called for the directories as well.


text:
Q: Relative efficiency of matching versus adjustment to handle confounding effects in highly disproportionate populations I am reviewing a paper where the authors compare cancer outcomes (binary) between two groups, one having a small sample size of 200 and the other having over 55,000.
The authors then claim that, due to the imbalance and in order to minimize confounding effects, they matched individuals from the larger group to the smaller.
My question is: is there a rule-of-thumb about how much efficiency can be gained by doing this? It was my understanding that if you matched on a factor, you would also have to adjust for it in a multivariate analysis. Assuming that the matching/adjustment factor is not in the causal pathway but it's not a confounder, then including that factor in the analysis leads to an efficiency loss with adjustment, but can the same be said of matching?

A: The answer depends on what type of study this is. In a cohort study, matched factors do not need to be included in the analysis and can improve efficiency by ensuring positivity for all important confounders. In a case-control study, matching improves efficiency if the matched factors are actually confounders, but match factors must be included in the analysis in order to address confounding.
I suspect in the paper you describe the authors have matched to ensure positivity of important, since the first sample is so small, and not specifically to improve efficiency.


text:
Q: ¿Cómo podría saber la id del  en el que se encuentra un determinado elemento? Agrego a la "dama" dentro de una id de una determinada caja (esto se realiza en una función a parte)
$("#" + ladyid + "").appendTo("#" + boxid + "");

pues lo que quiero saber en la otra funcion (la de abajo), es saber a que id (de las cajas) ha ido la dama
setInterval(function() {

                var lady1 = ;
                var lady2 = ;
                var lady3 = ;
                var lady4 = ;
                var lady5 = ;
                var lady6 = ;
                var lady7 = ;
                var lady8 = ;

            });

Lo que pretendo es que el programa sepa todo el rato en que div se encuentra cada elemento, y esta información añadirla a una variable

A: Esto lo puedes hacer usando la propiedad parent() para saber cual es el div padre en el que se encuentra la dama y posteriormente usar .attr('id') para sacar el id del mismo. Te dejo un ejemplo para que lo veas más claro:

var dama = $("#dama").appendTo("#primero");
alert(dama.parent().attr('id'));
.contenedor{
  position: relative;
  border: 1px white solid;
  width: 300px;
  height: 300px;
  background-color: blue;
}

#dama{
  position: absolute;
  width: 200px;
  height: 200px;
  background-color: yellow;
}

En tu caso si estás en una función distinta deberías de usar $("#dama").parent().attr('id');


text:
Q: Вопрос по аллокатору C++ Допустим, есть некая программа, назовем ее просмотрщик картинок, которая для размещения картинок в памяти использует предоставляемый системой heap.

Пользователь загружает в программу череду картинок размером по 4 Кb каждая, пока не исчерпывается весь heap.

Затем пользователь удаляет пару картинок из несмежных областей памяти, высвобождая тем самым объем памяти, равный 16 Kb (он удалил 4 картинки).

Вопрос, сможет ли он после произведенных операций, загрузить в программу картинку размером 16 Kb?

A: Даже если он поудаляет половину картинок, но только с четными номерами, то скорее всего не сможет выделить память под 8 кб картинку.
Ответ - с большой вероятностью что не сможет. Если только структура, которая хранит картинки не умеет размещаться в нескольких областях.


text:
Q: How to forward iterator calls to a class's private member? I have a class like,
class A {
public:
    // .. public methods
private:
    std::list<int> m_list;
};

I would like for the begin() and end() operator to correctly work for A. So that A.begin(), B.end() == m_list.begin(), m_list.end().  What's the best way to "forward" all appropriate iterator calls to the m_list member? The goal is for all STL algorithms to work "as expected" for my class A, as though it was really a list.

A: It's tempting to inherit from std::list<int> rather than composing it, to achieve this.
I know people say "don't inherit from standard containers" as a general rule and they're usually talking about the lack of a virtual destructor, a rationale which doesn't really come into play here because you're not likely to be storing std::list<int>*s pointing to your A (right? I mean, you're clearly not doing so currently!).
However, even that "edge case" falls apart on Windows when you want to export A; you end up exporting the whole bloomin' standard library and all hell breaks loose.
This brings us back to… "don't inherit from standard containers".

What then?
Aliases and member functions. :D
You can often get away with implementing just the following:
begin()
cbegin()

end()
cend()

rbegin()
crbegin()

rend()
crend()

and forwarding them directly to m_list, e.g.
auto begin() { return m_list.begin(); }
auto begin() const { return m_list.begin(); }
auto cbegin() const { return m_list.cbegin(); }

You may also wish to define some member types, matching std::list's, for full drop-in compatibility. It depends what you need to do. Personally I'd just add forwarding things as and when you need them. You'll probably find yourself needing to define at least the iterator aliases though.

A: You can also inherit privately from the type. Private inheritance is just like composition, but lets you forward member functions easily:
struct A : private std::list<int> {
    // make some members public
    using std::list<int>::begin;
    using std::list<int>::end;
    using std::list<int>::cbegin;
    using std::list<int>::cend;
    using std::list<int>::rbegin;
    using std::list<int>::rend;
    using std::list<int>::crbegin;
    using std::list<int>::crend;

private:
    auto m_list() const& noexcept -> std::list<int> const& { return *this; }
    auto m_list() & noexcept -> std::list<int>& { return *this; }
};

A: The simpliest way is often the greatest:
class A {
public:
    // .. public methods

    using iterator = std::list<int>::iterator;

    iterator begin() {
      return m_list.begin();
    }

    iterator begin() const {
      return m_list.begin();
    }

    iterator end() {
      return m_list.end();
    }

    iterator end() const {
      return m_list.end();
    }
private:
    std::list<int> m_list;
};

Of course, you also have to implement the const_iterator equivalent if you wish, and also the reverse iterator methods rbegin() and rend()


text:
Q: How to relate two different dataframes to make calculations I know how to work and computing math/statistics with one dataframe. But, what happens when I have to deal with two? For example:
> df1
   supervisor salesperson
1 Supervisor1        Matt
2 Supervisor2      Amelia
3 Supervisor2     Philip

> df2
  month   channel Matt Amelia Philip
1   Jan  Internet   10     50     20
2   Jan Cellphone   20     60     30
3   Feb  Internet   40     40     30
4   Feb Cellphone   30    120     40

How can I compute the sales by supervisor grouped by channel in a efficient and generalizable way?. Is there any methodology or criteria when you need to relate two or more dataframes in order to compute the data you need?
PS: The number are the sales made by each sales person.

A: Here is the idea of converting to long and merging using tidyverse,
library(tidyverse)

df2 %>%
 gather(salesperson, val, -c(1:2)) %>%
 left_join(., df1, by = 'salesperson') %>%
 spread(salesperson, val, fill = 0) %>%
 group_by(channel, supervisor) %>%
 summarise_at(vars(names(.)[4:6]), funs(sum))

which gives,

# A tibble: 4 x 5
# Groups:   channel [?]
  channel   supervisor  Amelia  Matt Philip
  <fct>     <fct>        <dbl> <dbl>  <dbl>
1 Cellphone Supervisor1     0.   50.     0.
2 Cellphone Supervisor2   180.    0.    70.
3 Internet  Supervisor1     0.   50.     0.
4 Internet  Supervisor2    90.    0.    50.

NOTE: You can also add month in the group_by


text:
Q: Import Partial & Comment Out in SASS I have a _reset.scscs partial that I want to import into my app.scss file but I want to comment it out so that the final app.css looks something like:
/* If you need a reset uncomment the lines below */
/* html, body, etc { margin: 0; padding: 0; border: 0;} */

.foo {
  background: blue;
}

Edit #1
_reset.scss
html, body, etc { margin: 0; padding: 0; border: 0;}

(notice that the contents _reset.scss are not commented out. I want the user of my library to still be able to @import "reset"; and the code not be commented out. So I guess I'm essentially asking if sass can import and then wrap that import in a comment? If not how would one accomplish this?

A: That is what import is for.
@import 'reset';

Just comment it out like you want in your _reset.scss file and it will import it fine as long as you are using css comments ( /* comment */ ) not sass comments ( // sass comment ). sass comments do not get output when compiled.
You can find documentation about sass comments here:
http://sass-lang.com/documentation/file.SASS_REFERENCE.html#comments


text:
Q: Laravel can't add new column to table I'm want to add new enum column status to customers table. But when im trying to run migrations I'm get this errors:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'status' in 'where clause' (SQL: select * from `customers` where `customers`.`deleted_at` is null and `status` = 1)

  [PDOException]
  SQLSTATE[42S22]: Column not found: 1054 Unknown column 'status' in 'where clause'

Migration:
 public function up()
{
    Schema::table('customers', function (Blueprint $table) {
        $enum = [
            'activated' => 1,
            'deactivated' => 0
        ];
        $table->enum('status', $enum);
    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::table('customers', function (Blueprint $table) {
        $table->dropColumn('status');
    });
}

A: Your enum value should not be an associative array
$enum = ["activated","deactivated"];


text:
Q: iOS in-app purchase review failure I'm trying to find the reason, why in app purchase get in .fail state when app is in review, while everything works while testing on my devices, both with my account and sandbox accounts. Here is what I get from apple:
Specifically, your app failed to complete an in-app purchase and displayed an error alert. Please refer to the attached screenshot.
Next Steps
When validating receipts on your server, your server needs to be able to handle a production-signed app getting its receipts from Apple's test environment. The recommended approach is for your production server to always validate receipts against the production App Store first. If validation fails with the error code "Sandbox receipt used in production," you should validate against the test environment instead.
Why they may ask about some receipts validating, there is no such things in most of the tutorials. In apple documentation there is some article about receipts but it is referred to renewable subscriptions.
The sentence about "your server" is also not clear, since I don't have own servers as far as I know.
Did I miss something ?
here is the code, which leads to alert from their screenshot
 func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
    for transaction:AnyObject in transactions {
        if let trans = transaction as? SKPaymentTransaction {
            switch trans.transactionState {

            case .purchased:
                complete(transaction: transaction as! SKPaymentTransaction)
                break

            case .failed:
                print("failed")
                fail(transaction: transaction as! SKPaymentTransaction) //alert from screenshot fires
                break
            case .restored:
                restore(transaction: transaction as! SKPaymentTransaction)
                break

            default:
                break
            }}}
}


text:
Q: Dependent collection duplicates when I save entity I have following domain mapping:
@Entity
@Table(name = "terminal_admin_role")
public class AdminRole {

    @Id
    @Column(name = "role_id", nullable = false, unique = true)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "user_id")
    @SequenceGenerator(name = "user_id", sequenceName = "user_id")
    private Long adminId;

    @Column(name = "role")
    private String role;

    public AdminRole(String role) {
        this.role = role;
    }

    public AdminRole() {
    }

    // get set

    @Override
    public String toString(){
        return role;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (!(o instanceof AdminRole)) {
            return false;
        }

        AdminRole adminRole = (AdminRole) o;

        if (!role.equals(adminRole.role)) {
            return false;
        }

        return true;
    }

    @Override
    public int hashCode() {
        return role.hashCode();
    }
}

and
@Entity
@Table(name = "terminal_admin")
public class TerminalAdmin {
    @ManyToMany(fetch=FetchType.EAGER,cascade=CascadeType.ALL)
    @JoinTable(name = "admin_role", joinColumns = {
        @JoinColumn(name = "admin_id", nullable = false) },
        inverseJoinColumns = { @JoinColumn(name = "role_id",
                nullable = false) })
    private Set<AdminRole> adminRoles;
    //...
}

and following code to execute:
controller:
@RequestMapping(value = "/admin/addNewAdmin")
public String adminUsers(@ModelAttribute @Valid TerminalAdmin terminalAdmin,
        BindingResult bindingResult, ModelMap model, Principal principal, HttpSession session) {
    ...
    terminalAdmin.setCreateDate(Calendar.getInstance());
    terminalAdminService.saveTerminalAdmin(terminalAdmin);
    ...
 }

service:
@Override
@Transactional
public void saveTerminalAdmin(TerminalAdmin newAdmin) {
    String rawPassword = newAdmin.getPassword();
    newAdmin.setPassword(passwordEncoder.encode(newAdmin.getPassword()));
    terminalAdminDao.save(newAdmin);
    emailService.sendAdminCreatedEmail(rawPassword, newAdmin.getEmail(), newAdmin.getAdminRoles());
    emailService.sendAdminRegisteredForAdminEmail(newAdmin);
}

dao:
@Override
@Transactional
public void save(TerminalAdmin terminalAdmin) {
    sessionFactory.getCurrentSession().save(terminalAdmin);
}

After it I see that admin roles binded to user duplicated in AdminRole table in database.
What Do I wrong? I have wrote equals method.
P.S.
before saving in debug  I see following values:

A: Because in your new TerminalAdmin, the AdminRole it is referring does not contain ID.  ID is the identity of entities.  It does not use equals() to identify the identity.  Without IDs, Hibernate simply treat it as a new AdminRole to be persisted to DB (as you have set corresponding cascade options in TerminalAdmin)
There are some choices you may take

*

*Change the ID of your AdminRole to the role String, or/and

*Lookup the correct AdminRole by role string, and set them in your new TerminalAdmin entity, or/and

*Contains the AdminRole ID in the incoming request, etc...


text:
Q: Difference between List lst = new List() and List<> lst = new List() I just want to know the difference between List<string> lst = new List()  and List<> lst = new List()

A: There is no List type. List<T> (or List(Of T) in VB) is a generic. It means that the list can only hold a type you pass in.
For instance:
List<string> list1 = new List<string>();
list1.Add("hello"); // OK
list1.Add(123); // Compiler error

List<int> list2 = new List<int>();
list2.Add("hello"); // Compiler error
list2.Add(123); // OK

You can read more about the generic list at MSDN.
If you want an un-typed list, you can use an ArrayList:
ArrayList list = new ArrayList();
list.Add("hello"); // OK
list.Add(123); // OK

But then you must know the type when you use an item from the list, since it can be any object.


text:
Q: What is the result of a yield expression in Python? I know that yield turns a function into a generator, but what is the return value of the yield expression itself?  For example:
def whizbang():
    for i in range(10):
        x = yield i

What is the value of variable x as this function executes?
I've read the Python documentation: http://docs.python.org/reference/simple_stmts.html#grammar-token-yield_stmt and there seems to be no mention of the value of the yield expression itself.

A: You can also send values to generators. If no value is sent then x is None, otherwise x takes on the sent value. Here is some info: http://docs.python.org/whatsnew/2.5.html#pep-342-new-generator-features
>>> def whizbang():
        for i in range(10):
            x = yield i
            print 'got sent:', x

>>> i = whizbang()
>>> next(i)
0
>>> next(i)
got sent: None
1
>>> i.send("hi")
got sent: hi
2


text:
Q: A beautiful geometry problem
Let $PP'$ and $QQ'$ be two parallel lines tangent to a circle of center $C$ and radius $r$ in the points $P$ and $Q$, respectively. $P'Q'$ cuts de circle in $M$ and $N$. Let $Y$ and $X$ be the points in which $Q'Q$ is cut by $PN$ and $PM$, respectively. Given the lengths $PP'= p$, $QQ'= q$ and $2r = d$, find the lengths $QY = y$ and $QX = x$.

I've been struggling with this problem for a couple of days, so a hint or a solution would be welcome.
Now, what makes this problem beautiful is the fact that if you let $p=-\dfrac{2a}b$ and $q =-\dfrac{c}{2b}$ then the lengths $y$ and $x$ will be the real roots of the equation $ax^2 + 2bx + c = 0$.

A: I hadn't seen @Takahiro's argument, but mine follows the same basic approach (streamlined slightly with the help of some trig):

$$\begin{align}
\triangle PP^\prime M\sim \triangle XQ^\prime M &\implies
\frac{|\overline{XQ^\prime}|}{|\overline{PP^\prime}|} = \frac{d\sin^2\theta}{d\cos^2\theta} \quad \left( = \tan^2\theta \right)\\[4pt]
&\implies \frac{q+x}{p} = \frac{x^2}{d^2}
\end{align}$$
where $d$ is the diameter of the circle. Likewise, we have (but don't show)
$$\frac{q-y}{p} = \frac{y^2}{d^2}$$
Thus, $x$ and $-y$ (note ---as Takahiro did--- the sign change!) are roots of
$$ z^2 p - d^2 z - d^2 q = 0 \tag{$\star$}$$

Unfortunately, the substitutions $p = -\frac{2a}{b}$ and $q = -\frac{c}{2b}$ transform $(\star)$ into
$$4 a z^2 + 2 b d^2 z - c d^2 = 0 \tag{$\star\star$}$$
which is not the "beautiful" relation promised. Perhaps OP intended $p = -\frac{2 a r^2}{b} = -\frac{ad^2}{2b}$ and $q = \frac{c}{2b}$. (I'm not sure I see what's so "beautiful" about those rather ad hoc assignments, however.)

A: $MX=x*\dfrac x{\sqrt{d^2+x^2}}$
,$MQ=\sqrt{x^2-\dfrac{x^4}{d^2+x^2}}=\dfrac{xd}{\sqrt{d^2+x^2}}$
$PM=\sqrt{d^2-MQ^2}=d\sqrt{1-\dfrac{x^2}{d^2+x^2}}=\dfrac{d^2}{\sqrt{d^2+x^2}}$
Since $PMP'\sim MXQ'$
$p:q+x=PM:MX=d^2/\sqrt{d^2+x^2}:x^2/\sqrt{d^2+x^2}=d^2:x^2$
$⇔d^2(q+x)=px^2$
$⇔px^2-d^2x-d^2q=0$
$x=(d^2+d\sqrt{d^2+4pq})/2p $
Similarly, since $PNP'\sim NQ'Y$
$p:q-y=PN:NY=d^2:y^2 $
$py^2+d^2y-d^2q=0 $
$y=(-d^2+d\sqrt{d^2+4pq})/2p$
Then
$(X-x)(X-y)=X^2-\sqrt{d^2+4pq}/p*X+qd^2/p$.
but $(X-x)(X+y)=X^2+\dfrac{d^2}pX-\dfrac{qd^2}p$. x and y are solutions of this equation.

A: HINTS:
Direct ( BFI :) ) method
Let radius of circle be $ r$
Transversal through circle center
$$ \frac{y-r}{x-p} = \frac{2r}{p+q} $$
Central circle Equation
$$ x^2+y^2 =r^2$$
Points of intersection $$ ( N,M)= (x_1,y_1), (x_2,y_2) $$
Form Left slant line  Equation  L in which put  $ \rightarrow y=0 $
Form Right  slant line   Equation R  in which put$ \rightarrow y=0 $
(Next verify the problem beauty etc. in hindsight.)


text:
Q: std::cin sometimes hangs, sometimes repeats forever after invalid input In this case, when the line marked hang point receives invalid input, eg. abc, it repeats the inner do-while loop and hangs upon reaching that line again.
// figure 1
std::string s;
do {
    do {
        std::cout<<"s = ";
        std::getline(std::cin, s);
    } while (s == "");
    double d;
    std::cout<<"d = ";
    do {
        std::cin.clear();
        std::cin>>d; // hang point
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    } while (std::cin.fail());
} while (s != "exit");

In this case the program skips over that line and repeats the do-while loop forever.
// figure 2
double d;
do {
    std::cout<<"d = ";
    std::cin.clear();
    std::cin>>d; // skip point
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
} while (std::cin.fail());

Why?
Originally I was going to ask why figure 1 hangs, and in the process of trying to simplify the example I came up with figure 2, and found that it didn't hang, but repeated forever. I don't understand why either figure 1 or figure 2 do what they do.
Edit: I've been causing cin to fail by entering alphabetical data at the prompt that I wrote for myself. eg.
s = something
d = 3
s = something
d = a

A: Figure2: You have to call cin.clear() before cin.ignore(). Otherwise, cin.ignore won't do anything because cin is still in an error state.
double d;
do {
    if (std::cin.fail()) {
        std::cin.clear();
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    }
    std::cout<<"d = ";
    std::cin>>d;
} while (std::cin.fail());

A: My impression is that you're resetting the flags, but the cin buffer is still full. So when it re-enters the loop, 'd' is automatically reassigned the letter value (say, the 'abc' you entered at the terminal) automatically. Thus the fail flag will then be reset, and the cycle repeats all over again.
Here's the fixed version (with a few stylistic changes, sorry about that):
#include <string>
#include <iostream>

int main(){
    std::string s="";
    std::string dummy="";
    while ( s!="exit"){
        s="";
        while (s==""){
            std::cout<<"s = ";
            std::getline(std::cin, s);
        }
        double d;
        std::cout<<"d = ";
        do {
            if (std::cin.fail()){
                std::cin.clear();
                std::getline(std::cin, dummy);
                std::cout << "d = ";
            }
            std::cin>>d;
            std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        } while (std::cin.fail());
    }
}


text:
Q: Is it necessary to check an optional argument before passing it to another optional argument? I have the following question concerning the usage of optional argument. Let's say I have the following routine aaa defined in module m_aaa
MODULE m_aaa
SUBROUTINE aaa(a, b)
  INTEGER           :: a
  INTEGER, OPTIONAL :: b
END SUBROUTINE
END MODULE

now I have a second routine that uses the module m_aaa. Is it possible to pass the optional argument like this
! Variant 1:
SUBROUTINE bbb(c, d)
  USE m_aaa
  INTEGER           :: c
  INTEGER, OPTIONAL :: d
  CALL aaa(c,d)
END SUBROUTINE

or is it necessary to check the presence of the optional argument d like this:
! Variant 2:
SUBROUTINE bbb(c, d)
  USE m_aaa
  INTEGER           :: c
  INTEGER, OPTIONAL :: d
  IF (PRESENT(d)) THEN
    CALL aaa(c,d)
  ELSE
    CALL aaa(c)
  ENDIF
END SUBROUTINE

Thanks for your help.

A: It is not necessary to check to presence of an optional dummy argument before passing it as an actual argument to another optional dummy argument.
This is allowed by 12.5.2.12 paragraph 4 (ISO/IEC 1539-1 (Draft 7 June 2010) aka Fortran 2008) regarding optional actual arguments that are not present:

Except as noted in the list above, it may be supplied as an actual argument corresponding to an optional dummy
  argument, which is then also considered not to be present.


text:
Q: Exoplayer Analytics, Accurate way of getting analytics Is there any accurate way of getting analytics from Exoplayer ? I want to get player analytics which can track total tracking time, exclude seeked track and all ?

A: Analytics on ExoPlayer depends on the ExoPlayer version s well. Some basic analytics can be done via ExoPlayer's EventListener Callbacks itself. To get accurate data analytical data add event listener as per your need: available listeners are

*

*EventListener: Provides ExoPlayer's general event callbacks

*AudioRendererEventListener(deprecated now with V2.9.+). So better
use AudioListener.

*VideoRendererEventListener (deprecated now with V2.9.+). So better
use VideoListener.

*AnalyticsListener: Available With ExoPlayer V2.9.+ it has most of
the available ExoPlayer callbacks. So it can be best suited as per
you need.

In all you can use available callbacks provided by Exoplayer and get the required analytical data like, total tracking time, seek event data, bandwidth, bitrate, etc.

A: This can be done by hooking up to the event callbacks ExoPlayer gives you and measuring these things yourself. You then need to send them to your backend and store/aggregate the data there over time.
An alternative would be to use a Video Analytics Solution that handles all of these things for you automatically like Bitmovin Analytics or Mux Data.
(Disclosure: I work for Bitmovin)


text:
Q: Refactor Big Blob Factory with SimpleInjector The Situation
I recently refactored my main Big Blob domain type into a facade for it's various aspects. So far the facade and the individual aspect services are working like a charm but creating the whole thing and wiring everything together is done in a Big Blob Factory for the type with Poor Man's Dependency Injection. It's really annoying having to put the whole thing together by hand so I feel that I have traded a Big Blob Domain type for a Big Blog Domain type factory :-/.
I'm trying to follow the SOLID Principles and so far the connection of the domain with my view layer is really working pretty well thanks to the QueryHandler and CommandHandler abstractions and my favorite Dependency Injection Container (SimpleInjector to the rescue).
Now I wonder how I can make use of the SimpleInjector to do the work my larger than life factory is doing by hand.
Some Sample Code to Illustrate My Case
Note that the actual IUser is created by a separate factory elsewhere and being handed in as a property of a Command/Query parameter object, so in my book it is not to be treated as a service (e.g. handed in by the DI container) but rather as data.
Before the refactoring:

class BigDomainBlob : IDomainService
{
    public BigDomainBlob(Config config)
    {
        // Set up all the big blog business with the help of the
        // given configuration ...
    }

    // Lots of code interleaving the various aspects of the domain
}

interface IUser : System.Security.Principal.IPrincipal
{
    // Session information, ip address, etc.
}

class BigDomainBlobFactory : IFactory<IUser, IDomainService>
{
    // To this point the DI container can help me autowire the
    // factory's dependencies
    public BigDomainBlobFactory(/* ... */)
    {
        // Injecting persistence strategies and client specific
        // plugins to customize the service creation
    }

    public IDomainService Create(IUser user)
    {
        return new BigDomainBlob(new BigDomainBlob.Config
        {
            // Plenty of configuration code to tailor
            // the service to the needs of the given user
        });
    }
}

After the refactoring:
class NeatDomainFacade : IDomainService
{
    private readonly IDataHandlingService service1;
    private readonly IMetaDataService service2;

    public NeatDomainFacade(
        IDataHandlingService service1,
        IMetaDataService service2)
    {
        this.service1 = service1;
        this.service2 = service2;
    }

    // Forwarding the IDomainService functionality
    // to the different aspects of the domain
}

class NeatDomainFacadeFactory : IFactory<IUser, IDomainService>
{
    // To this point the DI container can still help me autowire the
    // factory's dependencies
    public NeatDomainFacadeFactory(/* ... */)
    {
        // Injecting persistence strategies and client specific
        // plugins to customize the service creation
    }

    // I still have to tailor every aspect of the domain to the
    // specific needs of a user by hand so the factory is going nuts
    public IDomainService Create(IUser user)
    {
        // From here on I'm on my own hand wiring everything together ...

        // ...
        // Lots of code to set up user role, tailor SQL queries, etc.
        // ...

        // Handwiring my aspect dependencies and handing them in
        // to my fresh domain service
        var handWiredServiceForDataHandling = new Internal.DataService(
            someServiceDependency,
            anotherServiceDependency,
            new Internal.DataService.Config
            {
                SomeUserSpecificDbQueryString = "..."
            });

        var handWiredServiceThatAlsoUsesDataHandling = new Internal.MetaDataService(
            handWiredServiceForDataHandling,
            yetAnotherServiceDependency,
            new Internal.MetaDataService.Config
            {
                CustomizedMetaDataRetrievalString = "..."
            });

        // Even more code to hand wire and configure other dependencies ...

        // Finally handing in the service dependencies and creating the domain service
        return NeatDomainFacade(
            handWiredServiceForDataHandling,
            handWiredServiceThatAlsoUsesDataHandling);
    }
}

The Question
So you see: all the different aspects not only need other services but also some data configuration to customize their behavior for the user so all of them have to be configured at a stage where the user information is available - meaning I can't configure them at startup time.
I thought I got my head around the dependency injection way by now but I just don't see how I am to achieve this with the help of auto wiring.
I'm successfully injecting and using the factory to create the domain service in my QueryHandlers/CommandHandlers and like I said: the rest of the application architecture seems to work out pretty well - I hardly ever have to touch the composition root, just put the dependencies into the constructor and done. If only I could solve this pita domain service creation :-)
Help very much appreciated!
Edit:
I did the refactoring steven suggested in his answer but now I'm faced with a lifestyle issue. While hand wiring I created every dependency exactly once for every instance of the IDomainService and reused these for cross-dependencies. Some code:
public IDomainService Create(IUser user)
{
    // All dependencies are created exactly once and are
    // being reused throughout this method
    var serviceA = new ServiceA();
    var serviceB = new ServiceB(serviceA);
    var serviceC = new ServiceC(serviceA, serviceB)

    return new DomainService(serviceA, serviceB, serviceC);
}

That's not the case anymore with the default Lifestyle.Transient where every service would get a fresh instance of a requested dependency. Is it possible to get the SimpleInjector to simulate my hand-wiring behavior?
Thanks again!
Edit2:
I went with the SimpleInjector LifetimeScope like this:
public class CompositionRoot
{
    public static Container container;

    public sealed class DomainServiceFactory : IFactory<IDomainService>
    {
        public IDomainService Create()
        {
            var container = CompositionRoot.container;
            using (container.BeginLifetimeScope())
            {
                return container.GetInstance<IDomainService>();
            }
        }
    }

    public static void Setup(Container container)
    {
        CompositionRoot.container = container;

        container.Register<IDomainService, NeatDomainFacade>();
        container.Register<IFactory<IDomainService>, DomainServiceFactory>();
        container.RegisterLifetimeScope<ServiceA>();
        container.RegisterLifetimeScope<ServiceB>();
        container.RegisterLifetimeScope<ServiceC>();
    }
}

Now I can request the IFactory<IDomainService> and the lifetime scope is kicking in for the dependencies. Finally free of hand wiring :-)

A: I think the problem is here that you are building up the object graphs using the contextual information for the user.
So instead of doing that, I suggest the following:

*

*Prevent passing in user information through commands and through your NeatDomainFacadeFactory.Create method, but instead inject an IUserContext service that allows retrieving the IUser after the object graph is built.

*Inject extra services that use the IUserContext to retrieve the proper information that is needed objects at runtime.

So instead of creating a service instance for one particular user, create an instance that can be used for whatever user you are running, and only make decisions based on the user when you actually send runtim data through the object graph (so after construction).
You might need some aditional refactoring to get this working though.


text:
Q: Redirect to internal page in MVC I have a web site written in ASP.NET MVC 4.5
I have a controller called Products with views about each product.
I want with one of our products that when a user goes to www.website.com/ProductName redirects to www.website.com/Products/ProductName.
I am thinking right now this two approaches:

*

*Create a Controller called like ProductName and use RedirectToRoute()

*Modify the RouteConfig.cs file and add one.

What is your the best approach and why? Is there another?

A: I'm with @rjovic, definitely go with the second approach and add a new route.
The first approach would require creating a new controller for every product, which seems to go against good design principles; why have a separate class for multiple products that behave the same way?  Routes are designed for exactly this kind of scenario: mapping a user-friendly URL scheme to the appropriate handlers in your application logic.
There are two possible approaches to designing the route in this case:

*

*Match any URLs like /{ProductName}.  The problem is this is a greedy scheme, so you'd want to put this near the end of the route lists, so that it would only be used in case no other schemes are matched.

*Match only the URLs like /{ProductName} that match an actual product.  So you'd have to pre-load the list of product names, and construct a constraint that would look like (for example) "[product1|product2|product3]".

A: It looks as though all you are doing here is some redirection. You might want to look at using the IIS Url Rewrite module and create a redirect rule such as
<rewrite>
  <rules>
    <rule name="Redirect to Products/ProductName">
      <match url="^ProductName" />
      <action type="Redirect" url="Products/ProductName" />
    </rule>
  </rules>
</rewrite>

There's plenty of information on http://learn.iis.net/page.aspx/461/creating-rewrite-rules-for-the-url-rewrite-module/

A: www.website.com/products/productname would be more RESTful. Having your products at the root level of your website is only asking for trouble in the long run when you want to add another section of your site. i.e. www.website.com/about-us - is about-us a product, or it's own page?
Create a ProductsController and have a default action that takes a string that's a product name.


text:
Q: Turbolinks loading content before css/images I'm using Turbolinks in my laravel App, the problem I'm encountering now is when I switch view, the content is loaded before the CSS and images and it causes an awkward display of HTML before quickly switching to full view with is bad for UX. How can I fix this, probably by ensuring turbolinks only switches once it has loaded all CSS and images first?
====EDIT====
I've been able to uncover this much
We are routing from there to the login page:
@extends('./layouts/base')
@section('meta')
@section('title', 'Become a Tuper Seller')
  <link rel = "stylesheet" href = " {{ asset('fonts/material-icon/css/material-design-iconic-font.min.css')}} ">
@endsection
@section('body')
<link rel = "stylesheet" href = " {{ mix('css/auth.css')}} ">

Create A Consumer Account

                        <form method="POST" class="register-form" id="register-form">
                        @csrf

                                <input type="text" name="username" id="name" placeholder="Your Name" value = "{{ old('username')}}"/>

                            @error("username")

 {{ $message }}

                            @enderror

                                <input type="email" name="email" value = "{{ old('email')}}" id="email" placeholder="Your Email"/>

                            @error('email')

 {{ $message }}

                            @enderror

                                <input type="number" value = "{{ old('telephone') }}"name="telephone" id="telephone" placeholder="Telephone"/>

                            @error("telephone")

 {{ $message }}

                            @enderror

                                <input type="password" name="password" value = "{{ old('password') }}"id="pass" placeholder="Password"/>

                            @error('password')

 {{ $message }}

                            @enderror

                                <input type="password" value = "{{ old('password_confirmation')}}" name="password_confirmation" id="re_pass" placeholder="Repeat your password"/>

                                <input type="checkbox" name="agree-term" id="agree-term" class="agree-term" />
                                I agree all statements in  Terms of service

                                <input type="submit" name="signup" id="signup" class="form-submit" value="Register"/>

                        </form>

                        I want to be a seller

@endsection

I've noticed that replacing the mix(auth.css) in the login page with inline style tags and pasting the mix file fixes this error but this is not a suitable way of accomplishing this.

A: Well ive found a pretty neat solution. Since the css lag is caused by the link tag and since it works well when i paste the required css into style tags, i can replace by link tag with

This way it dumps the css as content instead of hyper referencing it which erradicates the dumbass delay. Also the mix helper wont work here if mix.version() is set in your webpack.mix.js because of the cache hashing.
But i dont imagine it will be a problem since there will be no cache of the css.


text:
Q: Ajax call SPRING MVC - url not found error I make an ajax call to populate dynamically a select tag on user's option.
function updateSelect(){
    var ddlTool = $('#selectTool');
    var ddlAction = $('#selectAction');
        ddlTool.on('change',function(){
            //append the placeholder
            ddlAction.html('<option value="NONE">Select action</option>')
            var option = ddlTool.val();
            $.ajax({
                url: "/eMuse/loadActions",
                    data : {id:option},
                success : function (response){
                    debugger;
                    for(var i = 0; i < response.length; i++){
                        ddlAction.append('option value="' + response[i].value + '">'+
                                response[i].text + '</option>');
                    }
                }
            });
    });
}

In Controller i have this method:
    @RequestMapping(value = "/loadActions", method = RequestMethod.GET, produces ="application/json")
    public @ResponseBody List<DropDownListItem> loadActionsGET(@RequestParam("id") long id) {

        // load actions by selected tool
        List<ActionViewModel> actions = StudentModelMapper
                .mapListActionDTOToListActionVM(actionService
                        .getActionsByIdTool(id));
        List<DropDownListItem> items = new ArrayList<DropDownListItem>();
        for (ActionViewModel a : actions) {
            items.add(new DropDownListItem(String.valueOf(a.getIdAction()), a
                    .getName()));
        }

        return items;

    }

If i run :

http://localhost:8080/eMuse/loadActions?id=1
  i also get the NOT FOUND error

In my web.xml file i have map the servlet like this:
<servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>*.html</url-pattern>
</servlet-mapping>

If i replace the url-pattern *.html with /* then I am able to run the link above, but everything else falls apart.
Can anybody help me?

A: You have set the request mapping to be /loadActions
However you have told spring to only be responsible for urls with this pattern :
<url-pattern>*.html</url-pattern>

You probably want to change the url pattern, to /*, or change that specific request mapping to /loadActions.html


text:
Q: How do I stop a pip install if there are package dependency conflicts? I did pip install tensorflow-gpu==1.12.3 because my GPU can only support CUDA 9, while the latest tensorflow-gpu==1.14.0 requires a minimum of CUDA 10. One of the package dependencies is tensorboard.
I want to do pip install tensorflow. However, the latest version warns that a newer version of tensorboard must be installed, then automatically proceeded to uninstall the existing version and install the newer one. Is there a way to have pip halt or at least ask for confirmation instead of proceeding on its own in such a situation? I'm trying to figure out which is a compatible version of tensorflow that doesn't require newer versions of package dependencies shared with tensorflow-gpu.
Edit
ok just to clarify, this isn't a tensorflow-specific question, I'm just using it as an example because I just happen to be doing that right now.
To generalise: I installed an older version of package A, which has a dependency on an older version of package B. I want to install package C, which also has a dependency on package B. However, the latest version of C requires the latest version of B. When I try to install C, it automatically uninstalled the older B and installed the newest version. How do I stop it from doing that?
Right now my only workaround is to install a version of C, wait for it to automatically uninstall something, then interrupt the installation of C, and reinstall the version of the dependency package that was uninstalled. Then I step down to the next older version C, and repeat. Basically, a trial and error process.
Is there a more proper and elegant solution? I'm fine with it giving a warning that C requires a newer version of B and then terminating at that point, or prompting for a confirmation before proceeding to uninstall, instead of doing it automatically without asking.
I'm using PyCharm's venv, so alternatively I'm also fine if there's a way to revert the latest change to the environment i.e. uninstall C and whatever new dependency packages that's installed, reverting to the list of installed packages before I executed pip install C.
Hopefully that doesn't sound too convoluted.

A: I have never done any work with tensorflow so I can't help you with that part, but I can suggest you using virtual environments when testing out stuff and not risking breaking system Python or upgrading packages you want at specific version.
python -m venv env to create virtual environment called env. source env/bin/activate to make the virtual environment active and deactivate to leave it.
Regarding the overwriting old packages, I haven't found options for promting installing new version nor an option to ignore requirements for a certain package. This is probably because developers can specify which version of dependencies are required and thus if pip finds outdated package, the package you wish to instal would probably not be usable with it.
However, you might try installing the newest version of tensorflow and let it install requirements it needs and then simply uninstall them using pip uninstall PACKAGE-NAME and install the version you wish with pip install PACKAGE-NAME==x.x.x.
Also, here is a guide that explains installation of tensorflow with CUDA 9. It seems that they are using version 1.8 for CUDA 9.2 and 1.7 for CUDA 9.1.


text:
Q: Saving a really simple tensorFlow model I am in the process of creating a really simple tensor flow network as part of a Django/ React native web app, I have managed to create a training set which works and produces the following output when run with plt:
Training output
However, as im a total noob when it comes to neural networks and Tensor Flow im finding saving this trained set challenging, I have tried saving using saver() and had a look at session but neither has really worked so far. What I want is to save this trained model so that i can use it in my application to match User entered questions(represented by integers) and pre-set answers. Also, I'm aware that the data is super basic and can easily be done by hardcoding the responses, this project is more about learning rather than getting reults in the most effecient way possible. Any feedback is really appreciated, source code listed below!
machine_learn.py
def loss(self, predicted_y, desired_y):
    return tf.reduce_mean(tf.square(predicted_y - desired_y))

def train(self, model, inputs, outputs, learning_rate):
    with tf.GradientTape() as t:
        current_loss = self.loss(model(inputs), outputs)

    dQ = t.gradient(current_loss, model.Q)
    model.Q.assign_sub(learning_rate * dQ)

def train_network(self, value_set):
    model = TrainingModel(value_set)
    desired_list = [4.00, 3.00, 2.00, 1.00]
    num_examples = 10000
    desired_ans = desired_list[0]
    inputs = tf.random_normal(shape=[num_examples])
    Qs = []
    epochs = range(150)
    for _ in epochs:
        Qs.append(model.Q.numpy())
        current_loss = self.loss(model.Q, desired_list)
        self.train(model, inputs, desired_list, 0.1)
        print(current_loss)
    plt.plot(epochs, Qs, 'r')
    plt.plot([desired_ans] * len(epochs), 'r--')
    plt.legend(['Q', 'true q'])

    plt.show()

training_model.py
class TrainingModel(object):

def __init__(self, questions):
    self.questions = questions
    self.Q = tfe.Variable(questions)

def __call__(self, inputs):
    return self.Q

A: I agree with Prune's comments but as a fellow noobie who's had a lot of trouble finding a useful tutorial for saver() take a look at the example programs here:
Useful example code.
The save and restore code should be what you're looking for.  I'd also encourage you to check out the tensorboard examples, it will show you how to graph variables without having to use the plt library.  Hope this helps!


text:
Q: Как собрать новый объект из свойств объектов лежащих в массиве? У меня есть JSON файл в котором массив с объективами.
http://bulk.openweathermap.org/sample/ (первый файл)
Мне нужно из этого массива выбрать свойства id у каждого объекта и записать его в отдельный массив для дальнейшей работы. (идеальным будет просто файлик с массивом id-шек)
Вот как это пытался сделать я. Делалось это в консоли браузера сам массив (ids) был вставлен в html.
function ids1 (let i = 0; i < 209579; i++) {
    function (i) {
        ids.forEach(function(obj) {console.log(ids[i].id)})
    }
   }

A:

const src = [
  {id: 1, data: 'data'},
  {id: 2, data: 'data'},
  {id: 3, data: 'data'},
  {id: 4, data: 'data'},
];

let dest = src.map(item => item.id);

console.log(dest);


text:
Q: AngularJS: как вынести html модального окна в отдельный файл? Есть одностраничное веб-приложение. Вся дополнительная информация подгружается в виде модальных окон jqxwindow.
Я к этой системе пытаюсь приладить AngularJS. Изначально подружил jqxwindow с Angular, просто прописав весь код jqxwindow прямо в index.php и создав контроллер создания окна так, как написано в доке jqwidgets.
Затем создал контроллер getInfo, который получает данные с сервера, и директиву greet, которая подставляет в div внутри модального окна таблицу с данными.
После того, как все заработало, попытался вынести код модального окна в отдельный файл, создал директиву, на этом все поломалось.
При клике, который вызывает событие создания окна, в консоли появляется ошибка:

TypeError: $scope.jqxWindowSettings.apply is not a function

index.php:

                Всего

jqx-window-template:
<jqx-window jqx-settings="jqxWindowSettings">

    Modal Window

        <jqx-button data-ng-click="Ok()" style="margin-right: 10px">Ok</jqx-button>
        <jqx-button data-ng-click="Cancel()">Cancel</jqx-button>

</jqx-window>

info-description.html:

        ID
        IMEI
        Model
        Наш
        Телефон

        {{answer.id}}
        {{answer.imeiNumber}}
        {{answer.model}}
        {{answer.own ? 'Наш' : 'Не наш'}}
        {{answer.phone}}

И наконец, файл с Ангуляром:
var arm = angular.module("arm", ["jqwidgets"]);

  arm.controller("armController", function ($scope) {
    $scope.jqxWindowSettings = {
      maxHeight: 1000, maxWidth: 1000, minHeight: 350, minWidth: 350, height: 200, width: 200,
      resizable: true, isModal: false, autoOpen: false, collapsed: true, modalOpacity: 0
    };
    // show button click handler.
    $scope.showWindow = function () {
      $scope.jqxWindowSettings.apply('open');
    };
    // Ok button click handler.
    $scope.Ok = function () {
      $scope.jqxWindowSettings.apply('close');
    };
    // cancel button click handler.
    $scope.Cancel = function () {
      $scope.jqxWindowSettings.apply('close');
    };
  });

  arm.controller('getInfo', function ($scope, $http) {
    $http.get('tablets/new-tablets-request.php').success(function (data) {
      $scope.newInfo = data;
      console.log($scope.newInfo);
    });
  });

  arm.directive("greet", function () {
    return {
      controller: "getInfo",
      restrict: 'A',
      templateUrl: 'tablets/info-description.html',
      scope: {
      },

      link: function (scope, element, attributes) {
      }
    }
  });

arm.directive("showNewWindow", function () {
  return {
    controller: "armController",
    restrict: 'A',
    templateUrl: 'tablets/jqx-window-template.html',
    scope: {},

    link: function (scope, element, attributes) {
    }
  }
});

A: Решение нашел сам.
Кусок файла с Ангуляром.
Было:
arm.controller("armController", function ($scope) {
    $scope.jqxWindowSettings = {
      maxHeight: 1000, maxWidth: 1000, minHeight: 350, minWidth: 350, height: 200, width: 200,
      resizable: true, isModal: false, autoOpen: false, collapsed: true, modalOpacity: 0
    };
    // show button click handler.
    $scope.showWindow = function () {
      $scope.jqxWindowSettings.apply('open');
    };
    // Ok button click handler.
    $scope.Ok = function () {
      $scope.jqxWindowSettings.apply('close');
    };
    // cancel button click handler.
    $scope.Cancel = function () {
      $scope.jqxWindowSettings.apply('close');
    };
  });

Стало:
arm.controller("armController", function ($scope,$rootScope) {
    $scope.jqxWindowSettings = {
      maxHeight: 1000,
      maxWidth: 1000,
      minHeight: 350,
      minWidth: 350,
      height: 200,
      width: 200,
      resizable: true,
      isModal: false,
      autoOpen: false,
      collapsed: true,
      modalOpacity: 0
    };
    // show button click handler.
    $scope.showWindow = function () {
      $rootScope.jqxWindowSettings.apply('open');
    };
    // Ok button click handler.
    $scope.Ok = function () {
      $rootScope.jqxWindowSettings.apply('close');
    };
    // cancel button click handler.
    $scope.Cancel = function () {
      $rootScope.jqxWindowSettings.apply('close');
    };
  });


text:
Q: Calling a process from a while loop I am trying to delete and rebuild an encrypted password file.  I am able to create the file and add usernames and encrypted passwords if I run the commands manually on the server within a command window.  But I get nothing if I try to run this code from within my C# web api controller.  The delete line works, but the first Process.Start line fails, and it never makes it to my while loop.
            System.IO.StreamReader pass2 = new System.IO.StreamReader(pass);

            File.Delete("C:\\inetpub\\wwwroot\\password\passMD5.txt");

            Process.Start("C:\\inetpub\\htpasswd.exe -bc C:\\inetpub\\wwwroot\\password\\passMD5.txt sm88555 sm88999");

            while ((line = pass2.ReadLine()) != null)
            {
                un = line.Substring(0, 6);
                pw = line.Substring(7, 6);
                Process.Start("C:\\inetpub\\htpasswd.exe -b C:\\inetpub\\wwwroot\\password\\passMD5.txt " + un + " " + pw);
            }

            pass2.Close();


text:
Q: How can I use JS to append a query string parameter to all outbound urls? This problem may seem simple enough, but some of the links on my page are embedded in a video iframe, which is not hosted by me. All outbound links are the same however, even the video one, is there a way to force anyone clicking ANY link all all to go to the same url, modifying it only by appending the initial query sting?
Basically the page is sub.mysite.com and all links on it go to mysite.com - What I need is for anyone landing on sub.mysite.com?x=landing to be taken to mysite.com/landing if they click on any link going out of sub.mysite.com, including the video one. Is this at all possible?
I'm thinking something like:
var urlParams;
(window.onpopstate = function () {
    var match,
        pl     = /\+/g,  // Regex for replacing addition symbol with a space
        search = /([^&=]+)=?([^&]*)/g,
        decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
        query  = window.location.search.substring(1);

    urlParams = {};
    while (match = search.exec(query))
       urlParams[decode(match[1])] = decode(match[2]);
})();

Then something like:
var anchors = document.getElementsByTagName('a');
for(var i = 0; i < anchors.length; i++) {
  var a = anchors[i];
  if(a.href) {
    a.addEventListener('mousedown', function(e) {
      this.href = 'mysite.com/' + x;
    }, false);
  }
}

But not sure if this would work for the iframe. Is there some blunt way to force redirect absolutely every outbound link? Maybe with some php to help? or an htaccess dynamic rule?


text:
Q: Faster version of strsplit in R I have a data such as sequence of string where text and number type alternate: e.g. VID22CAS05, TEL21XSE12 and I need to check the length of items after parsing, e.g. VID22CAS05 -> VID 22 CAS 05 => length of 4.
data <- c("VID22CAS05", "TEL21XSE12")

string_lengths<-purrr::map(data, function(x){
    x_sep <- trimws(x = gsub("(\\d+|[A-Za-z]+)", "\\1 ", x), which = "both")
    length <- strsplit(x_sep, " ")[[1]]
})

This works fine but the problem is that this is very slow for huge dataset.
Is there any way, how to speed this up?

A: Will this do?
lengths(gregexpr('\\d+|[a-zA-Z]+', data))
# [1] 4 4

A: I have put this together, included a solution based on strsplit and added another one using package stringi. Then I evaluate the performance using random data and microbenchmark, getting the following result.
require(stringi)
require(microbenchmark)

set.seed(42)
n <- 100000L

data <- stri_rand_shuffle(stri_paste(
    stri_rand_strings(n, sample(5:11, 5, replace = TRUE), "[A-Z]"),
    stri_rand_strings(n, sample(5:11, 5, replace = TRUE), "[0-9]")))

microbenchmark(lengths(gregexpr("\\d+|[a-zA-Z]+", data)),
               unlist(lapply(strsplit(data, "\\d+|[A-Z]+"), length)),
               nchar(gsub("\\d+|[A-Z]+", "_", data)),
               stri_count_regex(data, "\\d+|[a-zA-Z]+"),
               times = 10L)
#> Unit: milliseconds
#>                                                     expr      min       lq
#>              lengths(gregexpr("\\\\d+|[a-zA-Z]+", data)) 509.1273 562.6491
#>  unlist(lapply(strsplit(data, "\\\\d+|[A-Z]+"), length)) 499.3535 505.2245
#>                  nchar(gsub("\\\\d+|[A-Z]+", "_", data)) 248.5850 249.4832
#>               stri_count_regex(data, "\\\\d+|[a-zA-Z]+")  84.0736  84.7188
#>       mean   median       uq      max neval
#>  604.38020 607.2948 633.2371 677.1071    10
#>  516.07114 513.0919 515.4636 557.8389    10
#>  250.19865 250.0769 250.9425 252.5554    10
#>   85.40322  85.1071  86.5041  87.0498    10

So, using stri_count_regex from the stringi package seems to be the fastest. Please note that I adjusted the very nice and compact answer from @akrun so that it matches the results from the other approaches.
Created on 2022-12-21 with reprex v2.0.2

A: How about rethinking the problem, when we know text and number type alternate? Counting the occurrence of digits only and inferring the character count could speed things up further.
library(stringr)

str_count(data, "\\d+")*2

Output:
[1] 4 4 6

Data:
data<- c("VID22CAS05", "TEL21XSE12", "TEL21XSE12XSE12")

A: A base R option with gsub and nchar
nchar(gsub("\\D+", "", data))
[1] 4 4


text:
Q: Open a PDF and add pages to it in an Android app? I generate a PDF document from user input. This document is then displayed and "signed" by the user.
I need to grab this signature and append it to the document. I'm generating the PDF using Android API and displaying using an external library, but I need a way to re-open the document after signing and modifying it.
It's mandatory to generate the PDF before signing it, so the user can review it.

A: if the pdf file is saved to your storage after creating and updating it then try to read the file again otherwise you need to store the document first