text:
Q: Outer measure defined as infimum of a measure Let $\mathcal F$ be a $\sigma$-algebra on $\Omega$
 and let $\mu$: $\mathcal F \rightarrow [0,\infty]$ be a measure.
For each $X \subseteq \Omega$ define $\mu^*(X) := \inf\{\mu(A) : X \subseteq A,A\in\mathcal F\}$.
I'm trying to show that $\mu^*$ is an outer measure on $\Omega$, and that $\mathcal F$ is contained in $\mathcal F_{\mu^*}$ (the set of $\mu^*$ measurable sets).
So far for showing $\mu^*$ is an outer measure: 1) clearly $\mu^*(\emptyset)=0$. 2) If $A \subseteq B \subseteq \Omega$, then I want to say $\mu^*(A) \leq \mu(B) \leq\mu^*(B)$ but am unsure if this works.
Any help would be appreciated, thanks.

A: Regarding 2): You cannot claim that if $A \subseteq B$ then $\mu^*(A) \le \mu(B) \le \mu^*(B)$, because you need to have $B \in \mathcal F$ for the expression $\mu(B)$ to be meaningful.
However, you can still claim that $\mu^*(A) \le \mu^*(B)$. Here's a sketch of the proof: Consider all sets $C \in \mathcal F$ such that $B \subseteq C$. The outer measure of $B$ is exactly the infimum of the measures of those sets. But all those sets participate (maybe together with even more sets) in the definition of the outer measure of $A$...
(If you have a set of numbers, adding more numbers to it cannot increase its infimum.)
You also need to show countable subadditivity. Hint: Notice that if $X_n \subseteq A_n$ for every $n$ then also $\bigcup X_n \subseteq \bigcup A_n$. Select "covers" $A_n \supseteq  X_n$ which become tighter and tighter exponentially, and use the countable subadditivity of $\mu$.
Regarding $\mathcal F \subseteq \mathcal F_{\mu^*}$: This is easy, it follows from the definition of $\mu^*$. Edit: I forgot the definition of $\mathcal F_{\mu^*}$ when I wrote this, and it is less immediate than I imagined. You need to prove that given $M \in \mathcal F$, for all $X \subseteq \Omega$, we have $\mu^*(X) = \mu^*(X \cap M) + \mu^*(X \cap M^C)$. Hint: One way to prove equality is to prove inequality in both directions. One direction is easy and follows directly from the subadditivity of $\mu^*$. For the other direction, replace $X$ with a slightly bigger set which is in $\mathcal F$ (think about the definition of $\mu^*(X)$) and see that you get almost the inequality you need. Then, let "slightly" tend to 0.


text:
Q: Add Time To Javascript Game Timer If Condition Met EDIT:
I thought I'd try and add some clarity. Basically what I want is similar to Pole Position: cross the finish line and earn more time. Except in this case you match two numbers.

I have wanted to get better at Javascript and jQuery so I thought creating a game would be a great way to go about it.
The gist of the game is that you are given a number and the goal is to match that number.  I have everything working, including that when the goal is matched it adds to score. What I want now is to also add 30 seconds back to the time when the goal is matched.
I got it to add 30 seconds to the innerHTML but not the countdown. So if you were at 15 it would flash 45 then go back to 14.
I found the answer here and thought that I could change the
if (seconds == 0) {
        isRunning = true;
        seconds += 2;

to my condition and change it to seconds += 30; however nothing happens.
Here is my code. I am open to Jquery solutions as well if that is what you prefer to share.
var isWaiting = false;
var isRunning = false;
var seconds = 120;
var countdownTimer;
var finalCountdown = false;
var goalDiv = document.getElementById("goal").innerHTML;
var totalDiv = document.getElementById("total").innerHTML;

function GameTimer() {
    var minutes = Math.round((seconds - 30) / 60);
    var remainingSeconds = seconds % 120;

    document.getElementById('timerID').innerHTML = remainingSeconds;
    if (goalDiv == totalDiv) {
        isRunning = true;
        seconds += 30;

        if (seconds == 0) {
        $.mobile.changePage("index.html#youlost",{transition: "slideup"});
            clearInterval(countdownTimer);
        } else {
            finalCountdown = true;
        }

    } else {
        isWaiting = true;
        seconds--;
    }
}
countdownTimer = setInterval(GameTimer, 1000);

A: It looks like you never update the value of totalDiv after you've initially set it.
var goalDiv = document.getElementById("goal").innerHTML;
var totalDiv = document.getElementById("total").innerHTML;

And then, your GameTimer() function just keeps checking the old value of the totalDiv over and over. So it will never increment the seconds counter.
You might want to change your code to recheck the value of totalDiv on each tick of the timer:
function GameTimer() {
    var minutes = Math.round((seconds - 30) / 60);   // also this does not make
    var remainingSeconds = seconds % 120;            //    much sense..

    var totalDiv = document.getElementById("total").innerHTML;

    document.getElementById('timerID').innerHTML = remainingSeconds;
    var totalDiv = document.getElementById("total").innerHTML;

    //...

Here's a JSFiddle that shows a working version (based on your sample code, with a modifications, based on what my understanding of what you're tring to do)
And another thing. This not right either..
 seconds += 30;
 if (seconds == 0) {         // this won't be 0 unless seconds was -30 before..
    $.mobile.changePage("index.html#youlost",{transition: "slideup"});
        clearInterval(countdownTimer);
 }

A: I figured it out.
First of all I wrote my own time .
var count = 120;
    function timer() {
            count--;
    $("#timerID").html(+count);
    }

Then....
1. I wrapped everything in a $(document).ready function.

*I put my setInterval in a global variable.

*My clearInterval pulls the variable and is inside my function and that checks the score for my condition.

*Then I add 30 seconds and recall the timer.
Maybe not the best strategy but it works.

redpajama_set_name: RedPajamaStackExchange


text:
Q: import org.powermock.api.mockito.PowerMockito not found? Please guide to fix this issue.
import org.mockito.Mockito;  works fine
import org.powermock.api.mockito.PowerMockito; org not found
import org.powermock.core.classloader.annotations.PrepareForTest; works fine
import org.powermock.modules.testng.PowerMockTestCase; works fine
import static org.junit.Assert.*;

A: I know the issue is fixed but if you're using Maven, you need to include this as well:powermock-api-mockito


text:
Q: ActiveRecord::RecordNotFound at /gigs/2/status Couldn't find Gig with 'id'= I added a route to the default restful routes in my app,so in my controller I have an action called status, it's verb is Patch, but I get the above error each time I try to update an attribute via the status action, Note: the default update action in the Restful route has no issues.
Routes.rb
Rails.application.routes.draw do

  devise_for :users
  resources :projects do
    resources :gigs, shallow: true do
        patch :status
    end
  end
end

Gigs Controller
class GigsController < ApplicationController
  before_action :set_gig, only: [:show, :edit, :update, :destroy,:status]

  def status
    respond_to do |format|
      if @gig.update(:done, true)
        format.html { redirect_to @gig, notice: 'Gig was successfully updated.' }
        format.json { render :show, status: :ok, location: @gig }
      else
        format.html { render :edit }
        format.json { render json: @gig.errors, status: :unprocessable_entity }
      end
    end
  end

  private

    def set_gig
      @gig = Gig.find(params[:id])
    end

    def gig_params
      params.require(:gig).permit(:name, :description, :done,:timeline)
    end
end

and here is the link I added to the index.html.erb to execute the update
 <%= link_to 'Mark as Done', gig_status_path(gig), method: :patch %>

Here is the log
Started PATCH "/gigs/2/status" for 127.0.0.1 at 2018-04-07 12:26:20 +0100
Processing by GigsController#status as HTML
  Parameters: {"authenticity_token"=>"iNYFcsiwtNnCAC9goTGtfrqHFnBKufpgQ+61/pwZLVV6Nw82MBTART5ozVQUVsk74UFiWDknWrtoqYLN9D/2YQ==", "gig_id"=>"2"}
  [1m[36mGig Load (0.0ms)[0m  [1m[34mSELECT  "gigs".* FROM "gigs" WHERE "gigs"."id" = $1 LIMIT $2[0m  [["id", nil], ["LIMIT", 1]]
Completed 404 Not Found in 0ms (ActiveRecord: 0.0ms)

ActiveRecord::RecordNotFound - Couldn't find Gig with 'id'=:
  app/controllers/gigs_controller.rb:93:in `set_gig'

Started POST "/__better_errors/df8ad027b952f89c/variables" for 127.0.0.1 at 2018-04-07 12:26:20 +0100

A: You can check URI Pattern by using command rake routes for status action.
         Prefix Verb   URI Pattern                              Controller#Action
     gig_status PATCH  /gigs/:gig_id/status(.:format)           gigs#status
   project_gigs GET    /projects/:project_id/gigs(.:format)     gigs#index
                POST   /projects/:project_id/gigs(.:format)     gigs#create
new_project_gig GET    /projects/:project_id/gigs/new(.:format) gigs#new
       edit_gig GET    /gigs/:id/edit(.:format)                 gigs#edit
            gig GET    /gigs/:id(.:format)                      gigs#show
                PATCH  /gigs/:id(.:format)                      gigs#update
                PUT    /gigs/:id(.:format)                      gigs#update

so you need to use gig_id in case of status action
Modify method set_gig as follows:
   def set_gig
      @gig = Gig.find(params[:gig_id])
    end


text:
Q: R: change columns names of multiple tables I read in multiple .csv and now want to change all their column names in a loop. I could only find out how to change the names of a single table:
colnames(w01_10temp) <- c("date", "time", "temp", "na")

I also nee .csv files in R. Before I had:
filenames <- list.files(path=getwd())
numfiles <- length(filenames)
for (all_temp in c(1:numfiles)) {
filenames[all_temp] <- paste(filenames[all_temp],sep="")
assign(gsub([.]ASC$","temp",filenames[all_temp]),read.delim2(filenames[all_temp], fileEncoding="ISO-8859-15", skip = 4))    }

So I tried putting the lapply in the loop, without success:
for (all_temp in lapply(filenames,myReadTable)) {
  filenames[all_temp] <- paste(filenames[all_temp],sep="")
  }

A: Write a wrapper function:
myReadTable<-function(file){
 read.table(file,...)->x
 names(x)<-c("date","time","temp","na")
 return(x)
}

And then lapply it over the file name vector to get a list of data frames (this is much more manageable than using global variables).
lapply(c('fileA.csv','fileB.csv','fileC.csv'),myReadTable)


text:
Q: why error with if (xmlHttp.readyState == 4) I earlier asked a question about a xmlHttp.send() code that wasn't working. I thought I had fixed all of it, but now I've got another problem.
In the handleServerResponse() function, the code errors out in the if (xmlHttp.readyState == 4) and if (xmlHttp.readyState == 200). Why is it doing that? An example php code is under the JavaScript.
var xmlHttp = createXmlHttpRequestObject();

        function createXmlHttpRequestObject(){
            var xmlHttp;

            if(window.ActiveXObject){
                try{
                   xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
                }catch(e){
                    xmlHttp = false;
                }
            }else{
                try{
                   xmlHttp = new XMLHttpRequest();
                }catch(e){
                    xmlHttp = false;
                }
            }

            if(!xmlHttp){
                alert("cant create that object hos");

            }else{
                return xmlHttp;
            }
        }

function newuser() {

            if (xmlHttp.readyState == 0 || xmlHttp.readyState == 4) {
                name = encodeURIComponent(document.getElementById("name").value);

                queryString = "name=" + name;
                xmlHttp.open("GET", "code/php/core.php?" + queryString, true);
                xmlHttp.onreadystatechange = handleServerRespons;
                xmlHttp.send();
           }else{
               setTimeout('newuser()', 1000)
           }
    }

    function handleServerRespons(){

        if (xmlHttp.readyState == 4){

            if (xmlHttp.readyState == 200){
                alert('1234545');
                xmlResponse = xmlHttp.responseXML;
                xmlDocumentElement=xmlResponse.documentElement;
                message = xmlDocumentElement.firstChild.data;

                alert(message);

                }
            }
        }

php code:
         $name = $_GET['name'];

                      header('Content-Type: text/xml');
                      echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>';
                      echo '<response>';
                      echo $name;
                      echo '</response>';

A: instead of using a variable (xmlHttp) you must use this in an onreadystatechange event callback
so your function will be:
function handleServerRespons() {
  if ( this.readyState === 4 && this.status === 200 ) { // and also use "status" here not "readyState"
    xmlResponse = this.responseXML;
    xmlDocumentElement=xmlResponse.documentElement;
    message = xmlDocumentElement.firstChild.data;
    alert( message );
  }
}

or wrap your code with (function(){...})(); like below
(function() {
  // all your code goes here, so you can use that 'xmlHttp' instead of 'this'
})();

A: xmlHttp.readyState can't be 200. you should use xmlHttp.status.

A: xmlHttp.readyState has status of the XMLHttpRequest The XMLHttpRequest Object
xmlHttp.status will be available when xmlHttp.readyState is 3 or 4. When available xmlHttp.status should represent the HTTP status code.


text: Q: Channel brandingSettings image YT API deprecated I have a question related to YT API brandingSettings.image which is now deprecated. I used it to retrieve the channel banner image brandingSettings.getImage().getBannerImageUrl(). Is there any other way to retrieve the banner image for channel using YT API?


text:
Q: Difference between using withStateHandler and withState + withHandler Does withStateHandler has some benefit over using withState and withHandler together?
Why should I use withStateHandler at all when I can get same functionality with withState and withHandler?

A: withStateHandler has little benefits like less code and fewer function imports, but that won't do a lot of performance increment, practically they do the same thing in the same way if you do not worry about the size of your code splitting or something like this


text:
Q: Hibernate Delete, child violation I am yet again stuck with trying to delete data with Hibernate..
I am at point where I am starting to just stack annotation, hoping something would work... so far nothing has.
I need to delete old calculation when starting new for same time period.
I have the following query
@Modifying
@QueryHints(value = @QueryHint(name = HINT_FETCH_SIZE, value = "10"))
@Query(value = "DELETE FROM Group a WHERE a.c_date BETWEEN :dateA AND :dateB")
void deleteOld(@Param("dateA") LocalDate dateA, @Param("dateB") LocalDate dateB);

which uses entity Group, which has (on top of normal String, LocalDate and long types) attribute
    @OneToMany(cascade=CascadeType.ALL, mappedBy = "owner", orphanRemoval = true)
    @JsonManagedReference
    @OnDelete(action = OnDeleteAction.CASCADE)
    private List<Instrument> instruments = new ArrayList<>();

But I still get  violated - child record found every time I try to run delete method.
I keep finding more and more annotations like this, from threads where people have the same kind of problems, but I would love to understand why is this a problem. From what I read Cascade and orphanRemoval should be all I need, but it sure does not seem to be.
Hibernate: 5.2.17.Final
Please help me to understand, why is this happening ?

A: The @OnDelete will delete records using a ON DELETE rule on the database, when using Hibernate to generate the schema. If you manage your own schema this will have no effect.
The @QueryHints you have specified doesn't really make sense here, for an DELETE query that is. Nothing will be fetched.
The fact that you are using an @Query basically bypasses the configuration in the @OneToMany, simply due to the fact that you write a query and apparently know what you are doing. So the mapping isn't taken into account.
If you want to delete the childs as then you have 3 options:

*

*Add an additional query and first remove the childs, then the parents

*Add an ON DELETE rule to your database, to automatically remove the childs

*Retrieve the Group and remove using EntityManager.remove which will take the @OneToMany mappings into account as now Hibernate needs to manage the dependencies between the entities.


text:
Q: Remove rows from R dataset based on matching I did a word learning experiment with 54 participants. The design was such that each participant would be learning 12 cognate words and 12 non-cognate words. However, I had to remove some observations from the dataset, ending up with 1591 cognate observations and 1816 non-cognate observations.
Now, I want to calculate the correlation between scores for cognates and non-cognates. This means that I will have to reduce the 1816 non-cognate observations to 1591, because correlations are always performed with equal samples.
I could just remove rows 1592-1816, but that would not be ideal, because I would loose all non-cognates for the later participants (the data are sorted by participant number).
What I'd rather do, is loop through all the participants, and for each participant remove as many 'surplus' non-cognates so that the number of cognates and non-cognates becomes equal for that participant.
This is an example of the data for 2 participants (note that words are tested at multiple points in time, ideally this would also be taken into account when removing data):
structure(list(Participant = structure(c(2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L,
3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L,
3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L,
3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L,
3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L), .Label = c("1",
"2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13",
"14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24",
"25", "26", "27", "28", "29", "30", "31", "34", "35", "36", "37",
"38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48",
"49", "50", "51", "52", "54", "55", "56", "57"), class = "factor"),
    Word = structure(c(5L, 77L, 23L, 40L, 30L, 8L, 73L, 28L,
    48L, 44L, 58L, 69L, 50L, 57L, 45L, 6L, 56L, 53L, 63L, 65L,
    77L, 5L, 40L, 23L, 30L, 8L, 28L, 73L, 48L, 58L, 44L, 50L,
    69L, 57L, 45L, 56L, 6L, 63L, 53L, 65L, 23L, 30L, 40L, 5L,
    8L, 77L, 73L, 48L, 28L, 57L, 69L, 58L, 50L, 45L, 44L, 53L,
    65L, 6L, 63L, 56L, 5L, 40L, 8L, 77L, 30L, 23L, 28L, 48L,
    73L, 57L, 45L, 50L, 69L, 58L, 44L, 63L, 53L, 56L, 6L, 16L,
    13L, 81L, 82L, 52L, 1L, 12L, 75L, 55L, 78L, 70L, 66L, 80L,
    83L, 64L, 68L, 25L, 47L, 11L, 26L, 4L, 19L, 36L, 13L, 16L,
    82L, 81L, 52L, 1L, 75L, 12L, 78L, 55L, 70L, 80L, 66L, 64L,
    83L, 68L, 25L, 11L, 47L, 4L, 26L, 19L, 36L, 13L, 16L, 1L,
    82L, 52L, 81L, 78L, 12L, 75L, 55L, 70L, 80L, 66L, 64L, 83L,
    68L, 25L, 4L, 11L, 47L, 36L, 19L, 26L), .Label = c("aambeeld",
    "bezem", "brandblusser", "broodrooster", "buis", "citruspers",
    "dienblad", "dobber", "dweil", "emmer", "garde", "gesp",
    "gieter", "gum", "heggenschaar", "hengel", "hes", "kaars",
    "kapstok", "keppel", "kist", "klapper", "klos", "knikker",
    "knuffel", "kooi", "kous", "kraag", "kroon", "kruiwagen",
    "kruk", "kurk", "kussen", "kwast", "lantaarn", "lessenaar",
    "mijter", "onderzetter", "pak", "passer", "peddel", "pet",
    "pruik", "puntenslijper", "rammelaar", "reddingsvest", "rietje",
    "rits", "romper", "sambabal", "schort", "schroef", "servet",
    "skelter", "slab", "slang", "slinger", "speen", "speldje",
    "spijker", "spuit", "staf", "stamper", "stelt", "stofzuiger",
    "stokpaard", "stolp", "tamboerijn", "tol", "tooi", "toverstaf",
    "tuinbroek", "tulband", "vergiet", "veter", "vijl", "vijzel",
    "waaier", "wafelijzer", "wip", "zaag", "zeis", "zwemvleugel"
    ), class = "factor"), Cognate = structure(c(2L, 2L, 2L, 2L,
    2L, 2L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L,
    1L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L,
    2L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L,
    2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L,
    2L, 2L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L,
    1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L,
    1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 2L,
    2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L,
    2L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L,
    1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("Cognate",
    "Non-cognate"), class = "factor"), TestingMoment = structure(c(1L,
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
    1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
    2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L,
    3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 4L,
    4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L,
    4L, 4L, 4L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L,
    2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
    2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L,
    3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L), .Label = c("Main2",
    "Main4", "Post", "FollowUp"), class = "factor"), Score = c(0,
    1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0.71, 1, 1, 0.86,
    1, 1, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1,
    1, 0.86, 1, 0, 0, 0, 0, 1, 0, 0.43, 1, 1, 0, 0, 0, 0, 1,
    1, 0.86, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0.75, 0, 0, 0, 0.57,
    0, 0, 0, 0.45, 1, 1, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1,
    1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1,
    0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 0.8,
    1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0,
    0, 0)), .Names = c("Participant", "Word", "Cognate", "TestingMoment",
"Score"), row.names = c(97L, 98L, 99L, 100L, 101L, 102L, 103L,
104L, 105L, 109L, 110L, 111L, 112L, 113L, 114L, 115L, 116L, 117L,
118L, 120L, 121L, 122L, 123L, 124L, 125L, 126L, 127L, 128L, 130L,
133L, 134L, 135L, 136L, 137L, 138L, 139L, 140L, 141L, 142L, 144L,
145L, 146L, 147L, 148L, 149L, 150L, 152L, 154L, 155L, 157L, 158L,
159L, 160L, 161L, 162L, 163L, 164L, 165L, 166L, 168L, 169L, 170L,
171L, 172L, 173L, 174L, 175L, 178L, 180L, 181L, 182L, 183L, 184L,
185L, 186L, 188L, 189L, 190L, 191L, 193L, 194L, 195L, 196L, 197L,
198L, 199L, 200L, 201L, 202L, 204L, 205L, 206L, 207L, 208L, 209L,
210L, 211L, 212L, 213L, 214L, 215L, 216L, 217L, 218L, 219L, 220L,
221L, 222L, 223L, 224L, 225L, 226L, 228L, 229L, 230L, 231L, 232L,
233L, 234L, 235L, 236L, 237L, 238L, 239L, 240L, 241L, 242L, 243L,
244L, 245L, 246L, 247L, 248L, 250L, 251L, 252L, 253L, 254L, 255L,
256L, 257L, 258L, 259L, 260L, 261L, 262L, 263L, 264L), class = "data.frame")

What is the best way to go?

A: A somewhat smaller answer.
df2    = df     ## Preserve original data
for(Part in levels(df2$Participant)) {
    Tab    = table(df2$Cognate[df2$Participant == Part])
    if(Tab[1] == Tab[2]) { next }
    Big   = ifelse(Tab[1] > Tab[2], 1, 2)
    Small = ifelse(Tab[1] < Tab[2], 1, 2)

    Rem1   = sample(Tab[Big], Tab[Big] - Tab[Small])
    Remove = which(df2$Participant == Part &  df2$Cognate == levels(df2$Cognate)[Big])[Rem1]
    df2 = df2[-Remove,]
}
table(df2$Cognate)

A: Here's my answer, it's big and weird but it loops through each user, check if Cognate or Non-cognate is more frequent and remove until it gets equal (remember to assign your data to data variable):
final_data <- NULL
for (ptcp in unique(data$Participant)) {

  # subset to chose each participant
  new_data <- data[which(data$Participant==ptcp), ]

  # Check if Non-cognate and Cognate are equal
  if ( length(which(new_data$Cognate=="Non-cognate")) == length(which(new_data$Cognate=="Cognate")) ) break

  # Check if have more Non-cognate than Cognate
  if ( length(which(new_data$Cognate=="Non-cognate")) > length(which(new_data$Cognate=="Cognate")) ) {
    # Loop while they are not equal
    while (length(which(new_data$Cognate=="Non-cognate")) > length(which(new_data$Cognate=="Cognate"))) {

      # Removes the first row of "non-cognate
      id <- which(new_data$Cognate=="Non-cognate")
      new_data <- new_data[-id[1],]

    }

    # Check if have more Cognate than Non-cognate
  } else if ( length(which(new_data$Cognate=="Cognate")) > length(which(new_data$Cognate=="Non-cognate")) ) {
    # Loop while they are not equal
    while (length(which(new_data$Cognate=="Cognate")) > length(which(new_data$Cognate=="Non-cognate"))) {

      # Removes the first row of "non-cognate
      id <- which(new_data$Cognate=="Cognate")
      new_data <- new_data[-id[1],]

    }

  }

  # Combine each user to final_data
  final_data <- rbind(final_data, new_data)

}


text:
Q: DMN neural network with poor validation results -- only 50% I have this problem with my Neural Network. I'm trying to implement what's called a DMN (Dynamic Memory Network) for the babi data set. A paper about the DMN model can be found here: http://arxiv.org/abs/1506.07285 Another paper about DMNs can be found here: https://yerevann.github.io/2016/02/05/implementing-dynamic-memory-networks/
Here's my problem. btw I'm using PyTorch.
I split the training and testing data into parts for training, testing, and validation. I use 1000 parts for training, 500 parts for testing and 500 parts for validation. I run into a problem. I can train successfully but when I go to the validation step I never get a score above 50% accuracy. With the babi data set it is documented that you should be able to get 100% accuracy with the first test set. (There are 20 test sets in all). I can get 100% accuracy during training, but only 50% in validation. My question to you is what part of the program would be responsible for this kind of behavior? In other words, can you tell me why I'm always getting 50% ?? Thanks for your time. I'm limiting my experiments to the first babi test for now.
I thought I had this all figured out but my problem has cropped up again. I really don't have a clue what it is. Here is a link to the code. If you could take a look I would be most grateful. https://github.com/radiodee1/awesome-chatbot/blob/master/model/babi_iv.py
Some code is included below.
class WrapMemRNN(nn.Module):
    def __init__(self,vocab_size, embed_dim,  hidden_size, n_layers, dropout=0.3, do_babi=True, bad_token_lst=[], freeze_embedding=False, embedding=None, print_to_screen=False):
        super(WrapMemRNN, self).__init__()
        self.hidden_size = hidden_size
        self.n_layers = n_layers
        self.do_babi = do_babi
        self.print_to_screen = print_to_screen
        self.bad_token_lst = bad_token_lst
        self.embedding = embedding
        self.freeze_embedding = freeze_embedding
        self.teacher_forcing_ratio = hparams['teacher_forcing_ratio']

        gru_dropout = dropout * 0

        self.model_1_enc = Encoder(vocab_size, embed_dim, hidden_size, n_layers, dropout=dropout,embedding=embedding, bidirectional=False)
        self.model_2_enc = Encoder(vocab_size, embed_dim, hidden_size, n_layers, dropout=gru_dropout, embedding=embedding, bidirectional=False)
        self.model_3_mem_a = MemRNN(hidden_size, dropout=gru_dropout)
        self.model_3_mem_b = MemRNN(hidden_size, dropout=gru_dropout)
        self.model_4_att = EpisodicAttn(hidden_size, dropout=gru_dropout)
        self.model_5_ans = AnswerModule(vocab_size, hidden_size,dropout=dropout)

        self.input_var = None  # for input
        self.q_var = None  # for question
        self.answer_var = None  # for answer
        self.q_q = None  # extra question
        self.inp_c = None  # extra input
        self.inp_c_seq = None
        self.all_mem = None
        self.last_mem = None  # output of mem unit
        self.prediction = None  # final single word prediction
        self.memory_hops = hparams['babi_memory_hops']

        self.reset_parameters()

        if self.freeze_embedding or self.embedding is not None:
            self.new_freeze_embedding()
        #self.criterion = nn.CrossEntropyLoss()

        pass

    def reset_parameters(self):
        #print('reset')
        stdv = 1.0 / math.sqrt(self.hidden_size)
        for weight in self.parameters():
            #print('here...')
            weight.data.uniform_(-stdv, stdv)
            if len(weight.size()) > 1:
                init.xavier_normal_(weight)

    def forward(self, input_variable, question_variable, target_variable, criterion=None):

        self.new_input_module(input_variable, question_variable)
        self.new_episodic_module()
        outputs,  ans = self.new_answer_module_simple()

        return outputs, None, ans, None

    def new_freeze_embedding(self):
        self.model_1_enc.embed.weight.requires_grad = False
        self.model_2_enc.embed.weight.requires_grad = False
        print('freeze embedding')
        pass

    def new_input_module(self, input_variable, question_variable):

        prev_h1 = []

        for ii in input_variable:

            ii = self.prune_tensor(ii, 2)

            out1, hidden1 = self.model_1_enc(ii, None)

            prev_h1.append(hidden1)

        self.inp_c_seq = prev_h1
        self.inp_c = prev_h1[-1]

        prev_h2 = []

        for ii in question_variable:
            ii = self.prune_tensor(ii, 2)

            out2, hidden2 = self.model_2_enc(ii, None)
            prev_h2.append(hidden2)

        self.q_q = hidden2[:,-1,:]

        return

    def new_episodic_module(self):
        if True:

            mem_list = []

            sequences = self.inp_c_seq

            for i in range(len(sequences)):

                m_list = [self.q_q.clone()]

                #print(sequences[i].size(),'seq')

                for iter in range(self.memory_hops):

                    x = self.new_attention_step(sequences[i], None, m_list[iter], self.q_q)

                    if self.print_to_screen and not self.training:
                        print(x,'x -- after', len(x), sequences[i].size())

                    e, _ = self.new_episode_small_step(sequences[i], x.permute(1,0), None)

                    assert len(sequences[i].size()) == 3
                    #print(e.size(),'e')
                    ee = e[:, 0, -1]#.permute(2,1,0)

                    _, out = self.model_3_mem_a(ee.unsqueeze(0), self.prune_tensor(m_list[iter], 3))

                    m_list.append(out)

                mem_list.append(m_list[self.memory_hops])

            mm_list = torch.cat(mem_list, dim=1)

            self.last_mem = mm_list

            #print(self.last_mem.size(),'lm')

        return None

    def new_episode_small_step(self, ct, g, prev_h):

        assert len(ct.size()) == 3
        bat, sen, emb = ct.size()
        #print(ct.size(),'ct')
        #print(sen,'sen', g.size())
        last = [prev_h]

        ep = []
        for iii in range(sen):

            c = ct[0,iii,:].unsqueeze(0)

            if prev_h is not None:
                prev_h = self.prune_tensor(prev_h, 3)

            out, gru = self.model_3_mem_b(c, last[iii] )

            last.append(out)

            g = g.squeeze(0)
            gru = gru.squeeze(0).permute(1,0)

            #if not self.training: print(g.size(),'g', iii)
            #ggg = g[:, iii]
            ggg = g[iii]
            h = torch.mul(ggg , gru)#  + torch.mul((1 - g[iii]) , prev_h.permute(1,0))

            index = -1 #-1 # -2
            if last[iii + index] is not None:
                #print(last[iii].size(),'last -',ggg.size(), ggg, sen)
                if False: h = h + torch.mul((1 - ggg), last[iii + index])

            #print(h.size(),'hsize')
            if iii == sen - 1 : ep.append(h.unsqueeze(1))

        h = torch.cat(ep, dim=1)

        #print(h.size(),ep[0].size(),'h',sen, gru.size())

        return h, gru

    def new_attention_step(self, ct, prev_g, mem, q_q):

        q_q = self.prune_tensor(q_q,3)
        mem = self.prune_tensor(mem,3)

        assert len(ct.size()) == 3
        bat, sen, emb = ct.size()

        #print(sen,'len sen')

        att = []
        for iii in range(sen):
            c = ct[0,iii,:]

            concat_list = [
                c.unsqueeze(0),
                mem.squeeze(0),
                q_q.squeeze(0),
                (c * q_q).squeeze(0),
                (c * mem).squeeze(0),
                (torch.abs(c - q_q) ).squeeze(0),
                (torch.abs(c - mem) ).squeeze(0)
            ]
            #for ii in concat_list: print(ii.size())
            #print(sen,'sen')
            #exit()
            #z = F.sigmoid(z)
            concat_list = torch.cat(concat_list, dim=1)
            #print(concat_list.size(),'cl')
            att.append(concat_list)

        att = torch.cat(att, dim=0)
        #z = torch.cat(att, dim=0)
        z = self.model_4_att(att)
        z = F.sigmoid(z)
        #z =  F.softmax(z, dim=1) #F.sigmoid(z)
        #print(z.size(),'z')
        return z

    def prune_tensor(self, input, size):
        if len(input.size()) < size:
            input = input.unsqueeze(0)
        if len(input.size()) > size:
            input = input.squeeze(0)
        return input

    def new_answer_module_simple(self):
        #outputs

        ansx = self.model_5_ans(self.last_mem, None)

        #ansx = F.softmax(ansx, dim=0)

        if self.print_to_screen:
            print(ansx, 'ansx printed')
            print(ansx.size(), 'ansx')
            vocab, sen = ansx.size()
            aa = torch.argmax(ansx, dim=0)
            print(aa.size(),'aa')
            for i in range(sen):
                zz = aa[i]
                z = ansx[:, i]
                a = torch.argmax(z, dim=0)
                print(a.item(), zz.item())
            print('----')
        #ans = torch.argmax(ansx,dim=1)#[0]

        return [None], ansx

        pass


text:
Q: Object reference not set, ERROR when adding a new webpart I wanted to try tag cloud in a SharePoint server I maintain, I grabbed Nuage from www.codeplex.com and when I try to install , I get the below error
C:>stsadm -o addsolution -filename TagCloud.Sharepoint.Solution.wsp
Object reference not set to an instance of an object.
TagCloud.Sharepoint.Solution.wsp: The Solution installation failed

A: To determine if this is a permission issues, try this stsadm command to enumerate your sites:
stsadm -o enumsites -url http://<YOUR URL>

If you get a login failed message, then you will need to run your stsadm command with a user account that has necessary permissions. The farm account is a good bet.

A: Did you tried Installing it as Farm Admin sometime you get this error when you are running it as non farm Admin. Also make sure the Timer Job is running

A: Also be sure you have access to the sharepoint content database, because addsolution does work there too.


text: Q: Equalize heights of scattered 3D distributions (Python) I am working with 3D numpy arrays containing sparse data that consists of isolated distributions in random locations that are roughly Gaussian in shape (representing particle light intensities in 3D space), but with some variation in width and intensity. I am wondering what method or filter I should use to essentially "normalize" this data- that is, to try and roughly equalize the intensities/amplitudes of these distributions while otherwise largely preserving their widths, such that these isolated distributions end up with roughly the same characteristics.


text:
Q: How can I access specific iOS app's directory with Objective C? I'm trying to write an app for jailbroken iOS devices that can load files from another app. But  appstore apps are stored in folders with seemingly random characters that vary per device. How can I figure out the directory for X app on the device? On iOS 8, achieving this seems harder due to the way the app filesystem is structured.

A: iOS 7 and below
AppStore apps are installed in /var/mobile/Applications inside directory with random name. App's directories (documents, library etc) and *.app directory are both inside it. To determine which app it is you need to parse Info.plist file inside *.app directory where app name and bundle identifier are stored.
iOS 8
Apple completely changed the way AppStore apps are stored in filesystem. Everything we need now is in /var/mobile/Containers directory - at this point every directory I mention further down the text is contained inside that directory. All bundles (anything that contains application code) are stored in Bundle directory. There you will find apps, plugins and may be some other stuff.
For example, OpenVPN application contains two bundles with application code - OpenVPN.app with application executable and OpenVPNPlugin.vpnplugin which implements OpenVPN protocol as iOS VPN plugin. OpenVPN.app is in Applications directory and OpenVPNPlugin.vpnplugin is in VPNPlugin. For some reason OpenVPNPlugin.vpnplugin is also stored in Applications but it looks like it's a temporary measure for compatibility reasons.
All application data now stored in Data directory. Applications, plugins store their data inside that directory.
Apps directories (documents, library etc) now stored in Data/Application inside directory with random name. To determine which app directories it is you need to parse Data/Application/xx-xx-xx/.com.apple.mobile_container_manager.metadata.plist. Inside it you will find MCMMetadataIdentifier key that contains app's bundle identifier.
There are also Data/PluginKitPlugin and Data/VPNPlugin directories on my device. Again, parse Data/PluginKitPlugin/xx-xx-xx/.com.apple.mobile_container_manager.metadata.plist and Data/VPNPlugin/xx-xx-xx/.com.apple.mobile_container_manager.metadata.plist respectively. Inside it you will find MCMMetadataIdentifier key that contains plugin's bundle identifier. In case of PluginKitPlugin, to determine to which app it belongs you need to go to *.app. It seems PluginKitPlugin bundles are stored in *.app/PlugIns. Parse it's Info.plist to determine plugin's bundle identifier. As an example you can look at how Evernote is stored.
And finally there is Shared directory. It seems it contains app's documents that can be shared between different apps. Again, inside Shared you will find directory with random name. To determine which app shared that documents parse the .com.apple.mobile_container_manager.metadata.plist. MCMMetadataIdentifier will contain group. string concatenated with app's bundle identifier.
iOS 8 Update
Since iOS 8.4 Apple once again changed things. Now there are no .com.apple.mobile_container_manager.metadata.plist files. Instead you need to parse /var/mobile/Library/MobileInstallation/LastLaunchServicesMap.plist. It holds information about all installed applications (even system ones) since iOS 8 so you actually don't need .com.apple.mobile_container_manager.metadata.plist at all.
The plist has a very simple structure. First is dictionary with two main keys

*

*System - dictionary of system applications (including Cydia ones)

*User - dictionary of user applications (AppStore, enterprise, developer apps etc)

Those dictionaries use bundle identifier as key and dictionary with application info as value. For example:

*

*Path - path to application bundle directory

*Container - path to application directories (documents, library etc)

iOS 9 Update
It looks like both .com.apple.mobile_container_manager.metadata.plist and /var/mobile/Library/MobileInstallation/LastLaunchServicesMap.plist are too unreliable. The former is once again present in iOS 9 - don't know what happened in 8.4, maybe a bug. The latter is not always up-to-date. In fact, most of the time it contains old information. Especially for application sandbox path. Looks like it does change periodically as many times I found that the plist gives me the wrong path.
There is a much more reliable solution that doesn't require fiddling with plists or anything - LSApplicationWorkspace from MobileCoreServices framework. It has method - (id)allInstalledApplications that returns an array of LSApplicationProxy objects that will give you all the information you might find in LastLaunchServicesMap.plist. And, if I remember correctly, it works even without jailbreak.


text:
Q: Selecting/Filtering nested collections in L2E Consider 3 entities. Group, Box and Message. Each Group contains Boxes and each Box contains Messages.
what's the neatest way to retrieve Messages inside a Group with custom conditions in Linq To Entitis using lambda expressions?
For example, I want to select messages submitted yesterday in a certain group (thus, the resultr should be IEnumerable<Message>). How can I make the fewest calls to db and filter out results in my db-query?
Update
Got a downvote for not showing my code. That's because I don't have any. Question is simple enough. not a homework. Didn't expect that!

A: Assuming you have foreign keys in your database and Navigation properties in your model because of this, the following code should do the trick:
var messages = context.Groups
                      .SelectMany(g => g.Boxes
                                        .SelectMany(b => b.Messages
                                                          .Where(m => m.Date ==
                                                                      yourDate)
                                                   )
                                 );

A: You just need to put join query between them
from g in group
join b in boxes on g.id = b.groupid
join m in messages on b.id = m.boxid
where m.Date = your date
select m


text:
Q: Can I use getters/settings with this in javascript? Does using this.property still trigger the getter? class MyClass {
    constructor () {
         this._value = 1
    }

    increase (e) {
        this.value = this.value + 1;
    }

    get value () {return this._value;}

    set value(value) {
         this._value = value;
    }
}

does this not work? I want increase() to trigger both the getter and setter (since its getting and setting the value)


text:
Q: Create a Progress Bar (without %) between two Activities, until load the content of the Second Activity I have a Main Activity with a button, pressing that button opens a second Activity. This second Activity loads a large amount of data from Firebase to a RecyclerView that takes some time. When I clicked on the Main Activity button, I wanted to open a page with a Progress Bar (without showing the percentage) and only when the second Activity was completely loaded did the Progress Bar close and show the content of the second Activity. What is the best way to do this? Any idea? Thanks.

A: When you switch the second activitiy in onCreate method, if you implement the progress bar programmatically set it to infinite after instantiate it and add it to view hierarcy. Then when your data is done in the background just hide using View.GONE attribute Assuming you use Java and vertical linear layout.
ProgressBar progressBar = new ProgressBar(this);
progressBar.setIndeterminate(true);
yourLinearLayout.addView(progressBar);
...
// Once your data has been loaded hide the progress bar
progressBar.setVisibility(View.GONE);
// Or remove it
yourLinearLayout.removeView(progressBar);

A: Use ProgressBar in xml layout file(in the fragment/activity where you need to display), like this
    <RelativeLayout
        android:id="@+id/progressLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/white">

        <ProgressBar
            android:id="@+id/progressBar"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true" />
   </RelativeLayout>

and in the associated activity file, set the visibility to GONE.
do this where you called a method to load data.
progressLayout.visibility = View.GONE

if you can add that part of the code to your question, then it will be easier to help.


text:
Q: Why is my cache manifest still not working? I watch in chorme's console,there is nothing output,and no application cache
    why is this happen?thanks

and here is my html:
<html manifest="http://www.test.com/test.manifest">

here is the content of test.manifest file:
CACHE MANIFEST
# VERSION v1.0.120927-1430
CACHE:
http://www.test.info/js/smiles.js
# pic
http://www.test.info/imgs/user_32.gif
http://www.test.info/imgs/user_48.gif
http://www.test.info/smiles/christree.gif
http://www.test.info/smiles/horse2.gif
NETWORK:
*

that is my js code to print the logs:
function logEvent(a) {
    console.log(a.type);
    if (a.type == "updateready" || a.type == "cached") {
        applicationCache.swapCache();
    }
    if (a.lengthComputable) {
        console.log("total:" + a.total + "  loaded:" + a.loaded);
    }
    if (a.type == "error") {
        applicationCache.update();
    }
}
if(window.applicationCache){
    window.applicationCache.addEventListener("checking", logEvent, false);
    window.applicationCache.addEventListener("noupdate", logEvent, false);
    window.applicationCache.addEventListener("progress", logEvent, false);
    window.applicationCache.addEventListener("downloading", logEvent, false);
    window.applicationCache.addEventListener("cached", logEvent, false);
    window.applicationCache.addEventListener("updateready", logEvent, false);
    window.applicationCache.addEventListener("obsolete", logEvent, false);
    window.applicationCache.addEventListener("error", logEvent, false);
}

I watch in chorme's console,there is nothing output,and no application cache
    why is this happen?thanks

A: Your screenshots shows www.mmbang.com, but your HTML and manifest relates to www.test.com. If that's your original configuration this would never work because the manifest has to have the same origin as the website.


text:
Q: How change webpack dependency for axios. NormalModuleReplacementPlugin doesn't work I'm doing a bundle for Electron app with Webpack 5.
I need Node version of Axios library in my bundle, as I use nodeIntegration.
Axios takes XHR adapter by default for Electron app:
if (typeof XMLHttpRequest !== 'undefined') {
  // For browsers use XHR adapter
  adapter = require('./adapters/xhr');
} else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') {
  // For node use HTTP adapter
  adapter = require('./adapters/http');
}

So I use Webpack plugin to force Axios use Node version.
But in bundle I still got XHR version of adapter.
config.plugins!.push(
  new webpack.NormalModuleReplacementPlugin(
    /axios/,
    function (_resource) {
      if (_resource.request.indexOf('xhr') >= 0) {
        _resource.request = _resource.request.replace('xhr', 'http');
      }
    }
  )
);


text:
Q: Detecting a cycle in a directed graph I read a discussion here, at SO about finding a cycle in a directed graph. Now, the OP claims that we need to validate two things:

*

*There's a back edge from u to v

*v is in the recursion-stack

Why do we need the second test? Could you give an example to demonstrate it's necessity?

A: Well, you probably got confused between the definition of a back-edge in a directed graph and a back-edge in an undirected graph. Yes, they are different.
While in undirected graph back edges are edges from the current vertex to an-already-visited vertex. (as OP from your link mentioned).
In directed graph the definition for back edge is different. A back edge in a directed graph is an edge from current vertex to a GREY vertex (the DFS for this vertex has started but not yet finished), meaning it is still in the recursion stack.
So if you take the definition of a back edge as it is in a directed graph then yes, it is enough for detecting a cycle.
But if you take the definition of a back edge as it is in an undirected graph then you will need also to make sure that v is in the recursion stack in order to detect a cycle.
See this and this for more information and examples.
Example:
Consider the DFS visit order to be A -> B -> C.
In this example, the edge <A,C> is a back edge in the undericted graph (as C was already visited).
But it is not a back edge in this directed graph - C was already visited but is not in the recursion stack, meaning it is not a cycle.

A: Only the fact that we already visited v is not sufficient. It allows us to go from u to v, but not from v to u.
Simple graphical counterexample:

Numbers are traversal order. We have a back edge from 4 to 3, but we don't have any cycles.

A: The second test is needed when it is a cross edge, not a back edge. A cross edge refers to an edge that goes from one vertex to an already visited one regardless of position. A back edge refers to an edge that points to an ancestor of the starting vertex, one that is still in the recursive stack. In terms of how the question was asked, the OP refers to a back edge as an edge that points to another already visited edge, but a more accurate explanation would be a cross edge. Knowing it is a back edge is sufficient because it implies the second step. Those steps are required when the first is a cross edge because the second proves the cross edge is a back edge. In a directed graph, a cross edge does not always mean that a loop occurs. Here is an example:
vertices a,b,c,d
a->b
a->c
b->d
d->c

Depending on the order that this is processed, d->c can be considered a cross edge, therefore step number 2 would be required to detect a loop. Unfortunately, back edge and cross edge are mixed up quite often causing confusion like this. Heres a link to another description of the difference between the two, Depth-First Search.


text:
Q: Объясните, пожалуйста, что не так с изменением размера? Я пытаюсь масштабировать видеофайл из библиотеки scikit-video, но не могу разобраться в ошибке:
Traceback (most recent call last)
<ipython-input-10-9ed9b2a0d1f2> in <module>()
----> 1 src_video_example, tar_video_example = load_video_examples(vid_src=1)

1 frames
/scaleatt/video/utils/load_video_data.py in load_video_examples(vid_src, video_loaded)
     21     if vid_src == 1:
     22         src_video_example = skvideo.io.vread(skvideo.datasets.bigbuckbunny())
---> 23         src_video_example = scale_utils.scale_cv2(src_video_example, 1024, 1024)
     24
     25         tar_video_example = skvideo.io.vread(skvideo.datasets.bikes())

/scaleatt/video/scaling/scale_utils.py in scale_cv2(xin, trows, tcols, alg)
     38
     39 def scale_cv2(xin, trows, tcols, alg=cv2.INTER_CUBIC):
---> 40     res = cv2.resize(xin, (tcols, trows), interpolation=alg)
     41     return res

error: OpenCV(4.1.2) /io/opencv/modules/imgproc/src/resize.cpp:3363: error: (-215:Assertion failed) !dsize.empty() in function 'resize'


text:
Q: Wait() and Notify() concepts - Java Multithreading class Q {
  volatile boolean valueSet = false;
  volatile int n;

  synchronized int get () {
    if ( !valueSet ) {
      try {
        wait();
      } catch ( InterruptedException e ) {
        System.out.println( "InterruptedException caught" );
      }
    }

    System.out.println( "Got: " + n );
    valueSet = false;
    notify();
    return n;
  }

  synchronized void put ( int n ) {
    if ( valueSet ) {
      try {
        wait();
      } catch ( InterruptedException e ) {
        System.out.println( "InterruptedException caught" );
      }
    }

    this.n = n;
    valueSet = true;
    System.out.println( "Put: " + n );
    notify();
  }
}

class Producer
    implements Runnable {
  Q q;
  Producer ( Q q ) {
    this.q = q;
    new Thread( this, "Producer" ).start();
  }

  public void run () {
    int i = 0;
    while ( true ) {
      q.put( i++ );
    }
  }

}

class Consumer
    implements Runnable {
  Q q;
  Consumer ( Q q ) {
    this.q = q;
    new Thread( this, "Consumer" ).start();
  }

  public void run () {
    while ( true ) {
      q.get();
    }
  }

}

class PCFixed {
  public static void main ( String args[] ) {
    Q q = new Q();
    new Producer( q );
    new Consumer( q );
    System.out.println( "Press Control-C to stop." );
  }
}

I'm unable to understand how this works. Take this flow for instance. Producer enters put method and calls notify(). What if wait() has not been called by the consumer yet? Also, once the producer calls notify(), how can the consumer enter the method get() when the producer has not let go of the monitor yet? Please help me out here.

A: I'm assuming that the class at the top is Q, it's missing some code. Anyway, the general idea is that the boolean valueSet and the wait()/notify() calls work in tandem.
If the consumer has already begun to wait, he has acquired the lock to the Q instance through the synchronized get() method and then releases it while he waits.
If the consumer has not begun to wait yet, the producer may have the lock to the Q instance because the put() method is synchronized on that same lock. Once the producer exits the lock, he will have called notify() as well as set the valueSet boolean to true.
The consumer's next call to get() will read the boolean value before attempting to wait, notice that something's there, take the contents of n and do whatever work is needed. If the value had not been set, meaning that nothing had come in in the consumer's absence, he would wait() on the lock for new work and the next notify() will wake him up.
Update
In your scenario in the comments, you're essentially asking about the exact same situation but in reverse. The same logic applies.
The consumer is currently waiting and the producer calls notify(). The producer currently has the lock and will continue to hold the lock for the duration of the method. All notify() does is let one other thread currently waiting on the lock know that, when the lock is released, it can try to take the lock and resume execution. In this case, there is only one other thread, but if there were multiple threads then it would select only one (to wake everyone, notifyAll() should be called).

*

*The producer exits the method, releasing the lock.

*The consumer wakes up and takes the lock.

At this point, it's ambiguous as to whether the producer has already come around and is currently waiting on the lock or if it has not entered the method yet. The same tandem of the boolean flag and wait()/notify() applies to this as well.
Before the consumer releases the lock by exiting the method, it will both set the boolean flag to false and call notify().
If the producer is currently already waiting on the lock, calling notify() will let it know that it can wake up and continue when the lock is released.
If the producer is not waiting through a wait() call, it must be outside the method (possibly waiting to enter the method and acquire the lock that way). When the consumer exits the method and releases the lock, the producer acquires it and checks the boolean flag. It's been set to false, therefore the producer does not attempt to call wait() and just drops its value off, sets the boolean flag and calls notify().

A: *

*What if wait() has not been called by the consumer yet?

*

*The message will be lost

*Once the producer calls notify(), how can the consumer enter the method get() when the producer has not let go of the monitor yet?

*

*It will deadlock - block until it the monitor is realeased.

A: I'll try to understand how this works. For example, the Producer has entered the put() method and saw that the monitor is free and he can execute the putting action. At the time he's doing his job here comes the Consumer and tries to execute the get() action. But he fails since the monitor is already taken by the Producer, so he calls wait() meaning he is blocked at that line of code waiting for some other thread to call notify(). The trick here is that he never again calls get() before he's been notified that the monitor is free again, means he won't execute any more empty cycles. So, when the Producer has finished his work, he calls notify() and the Consumer resumes where he left off. I know it's a bit hard to understand at first and a bit hard to explain too, but when you do you'll see that these are really simple and powerful things. Good luck!


text:
Q: Monitoring webservice in production environment
Possible Duplicate:
What tool do you use to monitor your servers?

We are running a .net webservice and need to periodically test that the services are still up and running.  It will be easy enough to roll our own solution for this, but I'm just wondering what pre-existing tools are around for this purpose.
Thanks

A: Why don't you run a PowerShell script when the service(s) fail?

*

*You can google a PowerShell e-mail script and you should find plenty.

*Configure the service(s) to "Run a program" upon failure. This can be done in the Recovery tab of the Service's properties.


text:
Q: how to create Mschart in VB6? How can i retrieve data from database and display in chart format using MSChart in visual basic6.(Not in VB .NET).??? pls pls.... send me d answer...

A: Have a look at the following example code:
Display Data on a Chart Using MSChart control: Demo.
It's compatible with VB5 and 6
There is a nice tutorial on handling the difficulties (and getting started) with the chart control in VB6 here: Microsoft Chart - A How To Guide For Handling The VB 6 Charting Beast


text:
Q: Gdb and external functions So I have the following code
(gdb) list
#include<stdio.h>
#include<string.h>

int main()
{
char str_a[20];

strcpy(str_a,"Hello World!\n");
printf(str_a);
}

But when I disassemble it with gdb, strcpy isn't referenced. Instead the inside of the function strcpy is shown.
(gdb) disassemble main
Dump of assembler code for function main:
0x00000000004004fd <+0>:     push   rbp
0x00000000004004fe <+1>:     mov    rbp,rsp
0x0000000000400501 <+4>:     sub    rsp,0x20
0x0000000000400505 <+8>:     lea    rax,[rbp-0x20]
0x0000000000400509 <+12>:    movabs rdx,0x6f57206f6c6c6548
0x0000000000400513 <+22>:    mov    QWORD PTR [rax],rdx
0x0000000000400516 <+25>:    mov    DWORD PTR [rax+0x8],0x21646c72
0x000000000040051d <+32>:    mov    WORD PTR [rax+0xc],0xa
0x0000000000400523 <+38>:    lea    rax,[rbp-0x20]
0x0000000000400527 <+42>:    mov    rdi,rax
0x000000000040052a <+45>:    mov    eax,0x0
0x000000000040052f <+50>:    call   0x4003e0 <printf@plt>
0x0000000000400534 <+55>:    leave
0x0000000000400535 <+56>:    ret
End of assembler dump.

How can I get GDB to reference strcpy the way it references printf?
I'm compiling with "gcc -g"

A: Try compiling your program with -fno-builtin.
In your gcc, strcpy is a builtin function. See also 6.56 Other Built-in Functions Provided by GCC.


text:
Q: Why is the else function still running even when the conditions are not met? sorry for the constant pings but got to finish this project by Monday and its gone absolutely horribly! For this section of the code, when the employee details have been inputted, I want the system to search the employee list file for any existing employees with the same ID. If there is, I want the system to ask the employee if they want to create a new employee regardless and if they click the confirm button, the employee will be created with a different ID. If no employee has been found which has the same ID then a new employee will automatically be created.
The problem is that even when an employee is detected, it will first run through the expected code, but will then run through the code designated for when an employee is not detected.
def add_emp():
    empSurname = txtSurnameS.get()
    empForename = txtForenameS.get()
    empPhone = txtPhoneS.get()
    empGender = comboGenderS.get()
    empDOB = txtDOBS.get()
    empEmail = txtEmailS.get()
    empHouseNum = txtHouseNumS.get()
    empStreetName = txtStreetNameS.get()
    empTC = txtTcS.get()
    empCounty = txtCountyS.get()
    empPostcode = txtPostcodeS.get()
    empPassword = txtPasswordS.get()

    txtSurnameS.delete(0,END)
    txtForenameS.delete(0,END)
    txtPhoneS.delete(0,END)
    comboGenderS.delete(0,END)
    txtDOBS.delete(0,END)
    txtEmailS.delete(0,END)
    txtHouseNumS.delete(0,END)
    txtStreetNameS.delete(0,END)
    txtTcS.delete(0,END)
    txtCountyS.delete(0,END)
    txtPostcodeS.delete(0,END)
    txtPasswordS.delete(0,END)

    CAPL = empSurname.upper()
    CAPF = empForename.upper()

    with open("employees.txt", "r") as empList:
        for i in empList:
            fields = i.split(", ")
            if len(fields) < 2:
                continue
            oldID = fields[0]
            if oldID[:4] == CAPL[:3]+CAPF[:1]:
                exEmp = "Employee with name", empForename, " ", empSurname, "already exists, do you still wish to create account?"
                lblConfirm=Label(login_frame3,text=exEmp,font=("Calibri", 16), bg="white", fg="black", width = 135, height = 5)
                lblConfirm.grid(row=8, column=1, columnspan = 8, rowspan = 2)
                def confirm():
                    for i in employeeList:
                        counts=1
                        if i[:4] == CAPL[:3] + CAPF[:1]:
                            counts = counts + 1
                    empIDs = CAPL[:3] + CAPF[:1] + str("{:02d}".format(counts))
                    empList.close()
                    newEmp = classFunctions.Employee(empIDs, empSurname, empForename, empGender, empPhone, empDOB, empEmail, empHouseNum, empStreetName, empPostcode, empTC, empCounty, empPassword)
                btnConfirm=Button(login_frame3,command=confirm,text="Confirm", width=15, font=("Calibri", 16, "bold"), fg="white", bg="black")
                btnConfirm.grid(row=11, column=1)
        else:
            CAPL = empSurname.upper()
            CAPF = empForename.upper()

            employeeList = open("employees.txt", "r")
            count = 1stack
            for i in employeeList:
                if i[:4] == CAPL[:3] + CAPF[:1]:
                    count = count + 1
            empIDs = CAPL[:3] + CAPF[:1] + str("{:02d}".format(count))
            newEmp = classFunctions.Employee(empIDs, empSurname, empForename, empGender, empPhone, empDOB, empEmail, empHouseNum, empStreetName, empPostcode, empTC, empCounty, empPassword)
            empList.close()
            show_frame(login_frame)

addBtn=Button(login_frame3,command=add_emp,text="Add Emp", width=15, font=("Calibri", 16, "bold"), fg="white", bg="black")
addBtn.grid(row=7, column=1)
btnClose=Button(login_frame3,command=lambda:show_frame(login_frame),text="Cancel", width=15, font=("Calibri", 16, "bold"), fg="white", bg="black")
btnClose.grid(row=7, column=2)

This problem did not occur until I added the confirm subroutine in. Any help would be appreciated!


text:
Q: Process csv file from upload I have a gin application that receives a post request containing a csv file which I want to read without saving it. I'm stuck here trying to read from the post request with the following error message: cannot use file (variable of type *multipart.FileHeader) as io.Reader value in argument to csv.NewReader: missing method Read
file, err := c.FormFile("file")
if err != nil {
    errList["Invalid_body"] = "Unable to get request"
    c.JSON(http.StatusUnprocessableEntity, gin.H{
        "status": http.StatusUnprocessableEntity,
        "error":  errList,
    })
}

r := csv.NewReader(file) // <= Error message

records, err := r.ReadAll()

for _, record := range records {
    fmt.Println(record)
}

Is there a good example that I could use?

A: first read the file and header
csvPartFile, csvHeader, openErr := r.FormFile("file")
if openErr != nil {
    // handle error
}

then  read the lines from the file
csvLines, readErr := csv.NewReader(csvPartFile).ReadAll()
if readErr != nil {
  //handle error
}

you can go through the lines looping through the records
for _, line := range csvLines {
        fmt.Println(line)
    }

A: As other answers have mentioned, you should Open() it first.
The latest version of gin.Context.FromFile(string) seems to return only two values.
This worked for me:
func (c *gin.Context) {
    file_ptr, err := c.FormFile("file")
    if err != nil {
        log.Println(err.Error())
        c.Status(http.StatusUnprocessableEntity)
        return
    }
    log.Println(file_ptr.Filename)
    file, err := file_ptr.Open()
    if err != nil {
        log.Println(err.Error())
        c.Status(http.StatusUnprocessableEntity)
        return
    }
    defer file.Close()
    records, err := csv.NewReader(file).ReadAll()
    if err != nil {
        log.Println(err.Error())
        c.Status(http.StatusUnprocessableEntity)
        return
    }
    for _, line := range records {
        fmt.Println(line)
    }
}


text:
Q: Android App > Widget (AppWidgetProvider) > How to make a toggle button? I want to create a very simple widget. 1x1 cell. A button with text underneath. See image below, the 'clock' icon/text is how i want it aligned.. 'hello' is my effort so far.. It would be very nice to have a toggleButton, so with two states, after a click it should freeze the 'pressed' state. After another click it should return to the normale state.
My wishes:
- I want to create a Widget:
- 1x1 Cell
- A togglebutton (offcourse two states: normal & pressed, pressed must be freezed after click)
- Text underneath
- Toggle button has got a background, ratio must be 4:4 all the time. perfect circle.
- The text must also change to another string when the button is freezed in 'pressed' state
Since toggleButtons are not supported in widgets im looking for a quality answer. Im strugling with alignment of text, toggleButton in widget, background: keeping the ratio 4:4 instead of stretching... so what is the best approuch? how do other widgets build it?
See image:
http://i.stack.imgur.com/HnAS3.jpg
my code so far:
http://paste2.org/p/2414784
Help would be deeply appreciated!

A: edit: Similar SO question with code sample, kudos Mortalus:
Making a Toggle Button in an AppWidget
Tutorial for creating toggle-buttons in an Activity:
http://www.edumobile.org/android/android-programming-tutorials/create-a-toggle-button/
And a great tutorial about creating AppWidgets:
http://blog.doityourselfandroid.com/2011/05/24/developing-android-home-screenwidgets/
I take it you got 40dp from the widget guidelines, an excellent resource:
http://developer.android.com/guide/practices/ui_guidelines/widget_design.html
I noticed your image seems constrained horizontally, and stretched vertically, which seems to match these lines of your Button:
android:layout_width="match_parent"
android:layout_height="wrap_content"

You can try setting both to wrap_content (or, conversely, to match_parent) to even them out.
As far as alignment, a bit more info is available here:
http://developer.android.com/guide/topics/appwidgets/index.html#AddingMargins


text:
Q: Why does this custom formatter annotation in Spring MVC not work using Spring Boot? I am using Spring Boot and Thymeleaf.
I wanted to create a formatter annotation that formats an attribute of an object on printing it in the html file.
I wrote a sample project where a formatter annotation is supposed to add 10 to an Integer value.
This is my class: :
public class NumberObject {

@AddTenAnnotation
public Integer intFifty = 50;
}

Here is the html-file: :
<html >
<meta charset="UTF-8">
<body>
<label th:text=${numberObj.intFifty}></label>
</body>
</html>

I created
-a Formatter:
   public class AddTenIntegerFormatter implements Formatter<Integer> {

    @Override
    public Integer parse(String text, Locale locale) throws ParseException {
        return null;
    }

    @Override
    public String print(Integer a, Locale l) {
        int newVal = a +10;
        return String.valueOf(newVal);
    }
}

-an annotation:
@Target(value = { ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface AddTenAnnotation {
}

-an annotation factory:
public class IntegerAnnotationFactory implements AnnotationFormatterFactory<AddTenAnnotation> {

    public Set<Class<?>> getFieldTypes() {
        Set<Class<?>> fieldTypes = new HashSet<Class<?>>(1, 1);
        fieldTypes.add(Integer.class);
        return fieldTypes;
    }

    public Parser<?> getParser(AddTenAnnotation annotation, Class<?> fieldType) {
        return new AddTenIntegerFormatter();
    }

    public Printer<?> getPrinter(AddTenAnnotation annotation, Class<?> fieldType) {
        return new AddTenIntegerFormatter();
    }
}

and implemented a WebMvcConfigurer where I registered the annotation factory.
It is inside of the main-SpringBoot-class:
    @SpringBootApplication
    public class FormatterTestApplication {

    public static void main(String[] args) {
        SpringApplication.run(FormatterTestApplication.class, args);
    }

    @Configuration
    @EnableWebMvc
    public class WebMvcConfig implements WebMvcConfigurer {

        @Override
        public void addFormatters(FormatterRegistry registry) {

            registry.addFormatterForFieldAnnotation(new IntegerAnnotationFactory());
        }
    }
}

What I've tried:
I looked at several tutorials/ sample projects like spring-mvc-showcase/ stack overflow questions.
I tried to adjust them to my needs but it didn't work.
Maybe I overlooked something (rather new to spring)?
I already debugged it:
-addFormatters() of WebMvcConfigurer is called, getFieldTypes() of the annotation factory is called
-no methods of the Formatter class are called when I display the html-file.
So my questions would be
a) what could I do to make the annotation work ? Am I missing something ?
b)is there a preferred/ different way to create a custom formatter annotation in Spring Boot ? I could not find one ...
Thanks a lot for your help :)


text:
Q: How to get all the syllables of a word in Python? I am looking to split the word into its syllables. I am trying to build a speech-to-text system but focused on transcribing medical terms.
Consider a doctor/pharmacist who instead of typing out the medicine dosage would just speak into the microphone and a digital prescription would be generated automatically.
I want to avoid ML/DL based approaches since I wanted the system to work in real-time. Therefore I wanted to tackle this problem via a dictionary-based approach. I have scraped the rxlist.com to get all the possible medicine names.
Currently, I am using the webspeech API (https://www.google.com/intl/en/chrome/demos/speech.html). This works well but often messes up the medicine names.

*

*Panadol twice a day for three days would become panel twice a day for three days

It works sometimes (super unstable). Also, it is important to consider that panadol is a relatively simple term. Consider Vicodin (changed to why couldn't), Abacavir Sulfate, etc.
Here is the approach I thought could perhaps work.

*

*Maintain a dictionary of all medicines.

*Once the detections are there (I append all the detections instead of just using the last output), compare the string distance from each medicine (could be huge, so sorting is important here) and replace the word with minimum error.

*If nothing matches (maintain a threshold of error in step 2), check the syllables of prediction and that of medicine name and replace the one with the lowest error.

So I now have the list, I was hoping if I could find a library/dictionary API which could give me the syllables of medicine names. Typing How to pronounce vicodin on Google gets the Learn to Pronounce panel which has: vai·kuh·dn. I would want something similar, now I could scrape it off of Google, but I don't get the results for all the medicine names.
Any help would be appreciated.
Thanks.

A: You can use a library called pyphen. It's pretty easy to use. To install it run the following command in your terminal:
pip install pyphen

After this, find out the syllables in a string:
import pyphen
a = pyphen.Pyphen(lang='en')
print(a.inserted('vicodin'))

I hope you find this useful


text:
Q: Cloudformation template to create multiple SQS I am trying to create 2 SQS using a single cloudformation template. I want to apply same Queue policy to both the queues. Currently I have the below template to create 1 queue and its corresponding dlq. Do I have to write all the resources twice or can I reuse the same queue policy for Queue2?
Resources:
  Queue1:
    Type: AWS::SQS::Queue
    Properties:
      RedrivePolicy:
        deadLetterTargetArn: !GetAtt   DeadLetterQueue.Arn
        maxReceiveCount: 10
      QueueName: queue1
      MessageRetentionPeriod: 604800
      VisibilityTimeout: 150
      ReceiveMessageWaitTimeSeconds: 0

  DeadLetterQueue1:
    Type: AWS::SQS::Queue
    Properties:
      QueueName: queue1-dlq
      MessageRetentionPeriod: 1209600

  QueuePolicy:
    Type: AWS::SQS::QueuePolicy
    Properties:
      PolicyDocument:
        Version: 2012-10-17
        Statement:
          - Sid: allow-service-to-read-and-write-messages
            Effect: Allow
            Principal:
              AWS:
                - !Sub arn:aws:iam::${AWS::AccountId}:role/User
            Resource: !GetAtt Queue1.Arn
            Action:
              - SQS:ChangeMessageVisibility
              - SQS:DeleteMessage
              - SQS:GetQueueUrl
              - SQS:ReceiveMessage
              - SQS:SendMessage
      Queues:
        - !Ref Queue1

  DeadLetterQueuePolicy:
    Type: AWS::SQS::QueuePolicy
    Properties:
      PolicyDocument:
        Version: 2012-10-17
        Statement:
          - Sid: allow-service-to-read-messages
            Effect: Allow
            Principal:
              AWS:
                - !Sub arn:aws:iam::${AWS::AccountId}:role/User
            Resource: !GetAtt DeadLetterQueue1.Arn
            Action:
              - SQS:ChangeMessageVisibility
              - SQS:DeleteMessage
              - SQS:GetQueueUrl
              - SQS:ReceiveMessage
          - Sid: allow-queue-to-send-messages
            Effect: Allow
            Principal: '*'
            Resource: !GetAtt DeadLetterQueue1.Arn
            Action:
              - SQS:SendMessage
            Condition:
              ArnEquals:
                "aws:SourceArn": !Ref Queue1
      Queues:
        - !Ref DeadLetterQueue1

Outputs:
  SourceQueueURL:
    Description: URL of source queue
    Value:
      Ref: Queue1
  SourceQueueARN:
    Value: !GetAtt Queue1.Arn
    Description: Arn of created SQS
  DeadLetterQueueURL:
    Description: URL of dead-letter queue
    Value:
      Ref: DeadLetterQueue1
  DeadLetterQueueARN:
    Value: !GetAtt DeadLetterQueue1.Arn
    Description: Arn of created SQS

Tried with just 1 queue and its working fine

A: You have to create the policy separately for the second queue as it will have different !GetAtt DeadLetterQueue1.Arn. If you do not want to do this, you can extract the policy to a different template and use that template as a nested stack in your template with queue.


text:
Q: Swift - Converting UIImage to jpegData - [Metal] 9072 by 12198 iosurface is too large for GPU I'm trying to convert images picked from the users camera roll into jpegData for me to upload to a server.
I'm doing the following to covert to Data:
let imageData: Data? = uiImage.jpegData(compressionQuality: 0)
This works fine when converting screenshots. But when I attempt to convert an image taken using the device's camera. It gives me the following error:
[Metal] 9072 by 12198 iosurface is too large for GPU
It still converts it into data, but the data then just contains a blank image. Not the selected image.
I'm at a loss with where to go with this one, I've tried converting HEIC preloaded onto the device's bundle and it works fine. But when using ones selected from the camera roll, I get the stated error.
Any help would be appreciated. This is the sample code I'm using to test the issue. (I'm aware it's quite pointless in this form)
    func convertImage(image: Image?) -> Image? {   //1
        let key = "\(String.random(length: 15))"

        let uiImage: UIImage = image.asUIImage()
        let imageData: Data? = uiImage.jpegData(compressionQuality: 0)

        guard let imageData = imageData else { return nil }

        let encodedImage = imageData.base64EncodedString()

        let fileManager = FileManager.default
        let documentsPath = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first
        let localImageUrl = (documentsPath?.appendingPathComponent(key))
        guard let localImageUrl = localImageUrl else {
            return nil
        }
        try! encodedImage.write(to: localImageUrl, atomically: true, encoding: String.Encoding.utf8)

        guard let fileContents = try? String(contentsOf: localImageUrl) else {
            return nil
        }

        let dataDecoded : Data = Data(base64Encoded: fileContents, options: .ignoreUnknownCharacters)!
        let decodedimage = UIImage(data: dataDecoded)

        return (Image(uiImage: decodedimage ?? UIImage(named: "placeholder")!))
    }

import SwiftUI

struct UploadTesting: View {
    @ObservedObject var crViewModel = ChatroomsViewModel()

    @State var showImagePicker = false
    @State var selectedImage: Image? = nil

    @State var convertedImage: Image?
    var body: some View {
        VStack {
            Button("Select") {
                showImagePicker.toggle()
            }

            selectedImage?.resizable().scaledToFit().frame(width: 300, height: 300)

            Button("Convert") {

                convertedImage = crViewModel.convertImage(image: selectedImage)
            }

            convertedImage?.resizable().scaledToFit().frame(width: 200, height: 200).background(Color.red)
        }
        .sheet(isPresented: $showImagePicker) {
            ImagePicker(image: $selectedImage)
        }

    }
}

Video of issue: https://streamable.com/h0uqly


text:
Q: How to calculate $E(x)$ and $V(x)$ when $g(x)\sim f(g(x))$ Let assume that we are interested in a variable $x$.
We know that e.g. $g(x)=x^2$, $g(x) \sim Uniform(a,b)$ or any other distribution.
From that I can calculate $E(g(x)) = (a+b)/2$ and $V(g(x))=(b-a)/12$ .
Is there a way to calculate the $E(x)$ and $V(x)$?
I tried to do some research but I do not know how to phrase the question in one phrase or word to search


text:
Q: Laravel - Validate quantity field on server side for product which have different quantities I have a form that has a drop-down to select a product from different product listings, upon selection an AJAX request is sent to fetch the quantity of that particular product and max attribute is set for the quantity HTML element.

This is a form repeater (not any plugin) which creates a dynamic element on the fly when add new item is pressed and then another drop-down for product listing appears with its quantity HTML element (empty input element).

I am validating it on client-side by setting max attribute of quantity element, but how can I validate this on server-side for each product with respect to its quantity in the database.
If the user somehow opens developer tools in chrome and change the max attribute and submit the form my whole application will crash/create ambiguities.
I am using Laravel 5.7
This is how I am trying to achieve that.
$validated = $request->validate([
        'misc_equipment.*' => 'nullable|distinct',
        'misc_quantity.*' => 'required|numeric',
    ], [
        'misc_equipment.*.distinct' => 'This misc equipment has a duplicate value.'
    ]);

I just want to check that quantity from DB for that product


text:
Q: XSLT: Fill table based on common attribute value under different elements I've been trying to create a table with XSLT based on identical attribute values in XML file. I'm struggling with linking the elements based on identical attributes and looping through the XML file retrieving the necessary data.
The XML file i have:
<?xml version="1.0" encoding="UTF-8"?>
<LandXML>
  <Survey>
    <GPSSetup id="Setup1" stationName="Ref1">
    </GPSSetup>
    <GPSSetup id="Setup2" stationName="Ref2">
    </GPSSetup>
    <GPSSetup id="Setup3" stationName="Ref3">
    </GPSSetup>
    ...
  </Survey>
  <Survey>
    <GPSSetup id="id1" name="0001">
    </GPSSetup>
    <GPSSetup id="id2" name="0002">
    </GPSSetup>
    <GPSSetup id="id3" name="0003">
    </GPSSetup>
    ...
    <GPSVector setupID_a="Ref1">
      <TargetPoint pntRef="0001"></TargetPoint>
    </GPSVector>
    <GPSVector setupID_a="Ref1">
      <TargetPoint pntRef="0002"></TargetPoint>
    </GPSVector>
    <GPSVector setupID_a="Ref2">
      <TargetPoint pntRef="0003"></TargetPoint>
    </GPSVector>
    ...
  </Survey>
  <HexagonLandXML>
    <Point uniqueID="0001">
      <Coordinates n="1234"></Coordinates>
    </Point>
    <Point uniqueID="name2">
      <Coordinates n="1225"></Coordinates>
    </Point>
    <Point uniqueID="name3">
      <Coordinates n="1335"></Coordinates>
    </Point>
  </HexagonLandXML>
</LandXML>

I want to output a html file where under every "stationName" value that is found in the XML, a table is created where the corresponding "pntRef" and "n" values are shown.
The output i would like to achieve:
Ref1:
0001   1234
0002   1225

Ref2:
0003   1335

The XSLT file i have made so far:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"
            xmlns:l="http://www.landxml.org/schema/LandXML-1.2"
            xmlns:h="http://xml.hexagon.com/schema/HeXML-1.7"
            xmlns:msxsl="urn:schemas-microsoft-com:xslt"
            exclude-result-prefixes="h l"
            extension-element-prefixes="h l msxsl">
<xsl:output method="html" indent="no" encoding="utf-8"/>
<xsl:variable name="fileExt" select="'html'"/>

<xsl:template match="/">

      <xsl:apply-templates select="//l:LandXML/l:Survey[1]/l:GPSSetup">
      </xsl:apply-templates>

</xsl:template>

<xsl:key name="keyLGPSVector" match="l:GPSVector" use="@setupID_A"/>
<xsl:key name="keyH" match="h:Point" use="@uniqueID"/>

<xsl:template match="//l:LandXML/l:Survey[1]/l:GPSSetup">
  <xsl:variable name="Survey1L" select="."/>
  <xsl:variable name="Survey1LID" select="key('keyLGPSVector', $Survey1L/@id)"/>
  <xsl:variable name="PointH" select="key('keyH', $Survey1L/@id)"/>

  <xsl:for-each select=".">

    <xsl:value-of select="@stationName"/>

                Number
                n [m]

            <xsl:for-each select="$Survey1LID">
                <xsl:if test="$Survey1LID/@setupID_A = $Survey1L/@id">

                    <xsl:value-of select="current()/l:TargetPoint/@pntRef"/>
                    <xsl:value-of select="$PointH/h:Coordinates/@n"/>

                </xsl:if>
            </xsl:for-each>

</xsl:for-each>

With this i can achieve that the correct "pntRef" values are shown under each "Ref()" heading, but i cannot get the "n" value. From reading this forum i understand that for-each is probably not the best element to be used in this case.
Sorry if the editing is wrong or non-transparent, this is my first post.

A: You don't need the <xsl:for-each select=".">, you can remove that as inside a template there is only one context node anyway.
Then I think you should move the <xsl:variable name="PointH" select="key('keyH', $Survey1L/@id)"/> inside of the second for-each, but as <xsl:variable name="PointH" select="key('keyH', TargetPoint/@pntRef)"/>.
If you still have problems then consider to edit your XML and XSLT samples to be minimal but complete and consistent, currently your XML sample doesn't show any namespaces but your XSLT assumes at least two.

A: I think this is what you need; see comments for explanations:  XSLT Fiddle
Code:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:math="http://www.w3.org/2005/xpath-functions/math"
    xmlns:map="http://www.w3.org/2005/xpath-functions/map"
    xmlns:array="http://www.w3.org/2005/xpath-functions/array"
    exclude-result-prefixes="xs math map array"
    version="3.0">

    <xsl:template match="/">

                 <xsl:apply-templates select="/LandXML/Survey/GPSSetup[./@stationName]" />

    </xsl:template>

    <xsl:template match="/LandXML/Survey/GPSSetup">
        <xsl:variable name="stationName" select="./@stationName" />

            <xsl:value-of select="$stationName"/>

                    Number
                    n [m]

                 <xsl:apply-templates select="../../Survey/GPSVector[@setupID_a = $stationName]/TargetPoint" />

    </xsl:template>

    <xsl:template match="/LandXML/Survey/GPSVector/TargetPoint">
        <xsl:variable name="pntRef" select="./@pntRef" />
         <xsl:apply-templates select="../../../HexagonLandXML/Point[@uniqueID = $pntRef]/Coordinates" />
    </xsl:template>

    <xsl:template match="/LandXML/HexagonLandXML/Point/Coordinates">

            <xsl:value-of select="../@uniqueID" />
            <xsl:value-of select="./@n" />

    </xsl:template>

</xsl:stylesheet>

Explanation

*

*The template <xsl:template match="/LandXML/HexagonLandXML/Point/Coordinates"> creates the rows with the uniqueID and n values; but does not work out where these should be placed.

*The code <xsl:apply-templates select="../../../HexagonLandXML/Point[@uniqueID = $pntRef]/Coordinates" /> pulls back those results from the above template where the uniqueID value matches the current template's pntRef value; so we only display the relevant rows for each pntRef.  NB: I've used a relative XPath in my select (../../../HexagonLandXML/Point[@uniqueID = $pntRef]/Coordinates; but could equally have used an absolute one (/LandXML/HexagonLandXML/Point[@uniqueID = $pntRef]/Coordinates).  The relative one works from the current template's match's context whilst the absolute one works from the source document's root element.  The latter is probably simpler to understand; but the former may be useful if there were any relation inferred from the XML's structure (though I don't think that's the case here).

*We repeat the above trick of using apply-templates to filter another template's matches when finding those TargetPoints which are related to the other template's stations.

*For the template which creates an entry per station we don't need to filter on the values; we simply extract all matches as they occur.


text:
Q: what should callerContext param be for Fresco's prefetchToBitmapCache? In order to implement image pre-fetching, we get the ImagePipeline and call prefetchToBitmapCache on it. however, both the API Javadoc (http://frescolib.org/javadoc/reference/com/facebook/imagepipeline/core/ImagePipeline.html#prefetchToBitmapCache(com.facebook.imagepipeline.request.ImageRequest, java.lang.Object) and the plain doc (http://frescolib.org/docs/using-image-pipeline.html#) are incorrect. specifically , they leave out the description and example for what the second method parameter is. I am talking about the Object callerContext . which since its an object isn't an android Context. I'm guessing that because the type is an object, not a Context. Could the documentation be updated and/or someone explain what the caller context is supposed to be?
Thank you!

A: So I posted this question a while back on the fresco github (https://github.com/facebook/fresco/issues/609) and I was told the documentation would be updated. I'm posting my results here since it is likely others might look here. I still haven't seen any updates to frescolib.org or anywhere else. I decided to figure it out myself. Basically, if you're using SimpleDraweeView and its respective ImageRequest (which the prefetch call needs) , then you would notice that setting the uri on the view creates a DraweeController with a null callerContext. I figured that might be what is needed here. Sure enough, I made the call to prefetchToBitmapCache(draweeController, null) and its prefetched! I know that because I waited for a bit and turned off the data. also this call was only active on a select imageview. the other did not load. I can't be sure this is the right way to do it, ntil they come out with the right documentation. but like i said it works.


text:
Q: Jquery click funtion is not working when mobile view I have jquery click funtion which is to close custom modal. It's working perfectly except when I'm on mobile view (I use different type of browser but still not working when it's on mobile view)
I wonder why it's not working when mobile view.

$(document).ready(function() {
  $(".cus-close").click(function() {
    $(".custom-modal").css('display', 'none');
  });
});

      Add success


text:
Q: TypeError: can only concatenate str (not "relativedelta") to str i'm trying to get next month from selected date. if i using datetime.date.today() its ok. but i need working with request date. how can i solve it.Thanks
date = request.form['date']
print(date) // 2022-11-05
// nextmonth = datetime.date.today() + relativedelta.relativedelta(months=1)
nextmonth = date + relativedelta.relativedelta(months=1)

A: You have to convert str to date and then use relativedelta.relativedelta.
Not sure what format the date is, I am assuming it is YYYY-MM-DD.
You can change the day and month format as per what you want.
import datetime
from dateutil import relativedelta
date = '2022-11-05'
date = datetime.datetime.strptime(date, '%Y-%m-%d').date()
nextmonth = date + relativedelta.relativedelta(months=1)

That should give you 2022-12-05.


text:
Q: Trouble with rotational kinematics I'm having a bit of trouble with the following homework problem:

My thinking is there are only three forces acting on the laundry: the force due to centripetal acceleration, the force due to gravity, and the normal force, which is orthogonal to the plane tangent to the circle where the center of the laundry's mass touches the dryer. ( The question says the dryer's drum is smooth, so I'm taking that to mean we are ignoring the force due to friction between the drum and the laundry. )
So, I drew the following free-body diagram:

Next, I applied Newton's Second Law in the i-direction:
$$ F\ =\ m\ \frac{v^2}{R} $$
$$ -N\ cos\ (\ \theta\ )\ +\ \frac{m\ v^2cos\ (\ \theta\ )}{R}\ =\ 0 $$
$$ \frac{m\ v^2cos\ (\ \theta\ )}{R}\ =\ N\ cos\ (\ \theta\ ) $$
$$ m\ v^2cos\ (\ \theta\ )\ =\ N\ cos\ (\ \theta\ )\ R $$
$$ m\ v^2\ =\ N\ R $$
$$ \frac{m\ v^2}{R}\ =\ N $$
Then, I applied Newton's Second Law in the j-direction:
$$ N\ sin(\ \theta\ )\ -\ \frac{m\ v^2\ sin\ (\ \theta\ )}{R}\ -\ mg\ =\ 0 $$
$$ \frac{m\ v^2\ sin(\ \theta\ )}{R}\ -\ \frac{m\ v^2\ sin\ (\ \theta\ )}{R}\ -\ mg\ =\ 0 $$
$$ -\ mg\ =\ 0 $$
Which--is not entirely useful ( nor is it probably true ).
I've done this question a few times now and can't seem to spot my mistake--either in approach, algebra, or both. Any help in spotting my mistake in algebra, approach, or both would be greatly appreciated.

A: There are three forces acting which then change to two.
The frictional force will not contribute to the net force towards the centre of rotation which produces the centripetal acceleration as it is tangential to the drum.
The other two forces on the washing are the normal reaction and the weight.
Draw some free body diagrams as the washing moves from the bottom.
You need the condiion when the normal reaction becomes zero.

A:
I guess that your free body diagram is not correct.
I came up with the equation $m\omega^2r=N+gcos\theta$.
Substitute $N=0$ and given radius, at the $\theta=70.5$


text:
Q: Getting a 'KeyError" while trying to access a Custom Dataset I am trying to learn PyTorch and make use of a custom dataset. Code Credit - https://github.com/vineeth2309/Custom-Dataset-and-Dataloader-in-Torch.
However, when I run the code I get a 'KeyError'.
import glob
import cv2
import numpy as np
import torch
from torch.utils.data import Dataset, DataLoader

class CustomDataset(Dataset):
    def __init__(self):
        self.imgs_path = "Dog_Cat_Dataset/"
        file_list = glob.glob(self.imgs_path + "*")
        print(file_list)
        self.data = []
        for class_path in file_list:
            class_name = class_path.split("/")[-1]
            for img_path in glob.glob(class_path + "/*.jpeg"):
                self.data.append([img_path, class_name])
        print(self.data)
        self.class_map = {"dogs" : 0, "cats": 1}
        self.img_dim = (416, 416)

    def __len__(self):
        return len(self.data)

    def __getitem__(self, idx):
        img_path, class_name = self.data[idx]
        img = cv2.imread(img_path)
        img = cv2.resize(img, self.img_dim)
        class_id = self.class_map[class_name]
        img_tensor = torch.from_numpy(img)
        img_tensor = img_tensor.permute(2, 0, 1)
        class_id = torch.tensor([class_id])
        return img_tensor, class_id

if __name__ == "__main__":
    dataset = CustomDataset()
    print (dataset)
    data_loader = DataLoader(dataset, batch_size=4, shuffle=True)
    print (data_loader)
    for imgs, labels in data_loader:
        print("Batch of images has shape: ",imgs.shape)
        print("Batch of labels has shape: ", labels.shape)

Stack-Trace :
C:\Users\parag\anaconda3\envs\tf-gpu\python.exe C:/Users/parag/PycharmProjects/Custom-Dataset-and-Dataloader-in-Torch/Main.py
['Dog_Cat_Dataset\\cats', 'Dog_Cat_Dataset\\dogs']
[['Dog_Cat_Dataset\\cats\\1.jpeg', 'Dog_Cat_Dataset\\cats'], ['Dog_Cat_Dataset\\cats\\2.jpeg', 'Dog_Cat_Dataset\\cats'], ['Dog_Cat_Dataset\\cats\\3.jpeg', 'Dog_Cat_Dataset\\cats'], ['Dog_Cat_Dataset\\cats\\4.jpeg', 'Dog_Cat_Dataset\\cats'], ['Dog_Cat_Dataset\\cats\\5.jpeg', 'Dog_Cat_Dataset\\cats'], ['Dog_Cat_Dataset\\dogs\\1.jpeg', 'Dog_Cat_Dataset\\dogs'], ['Dog_Cat_Dataset\\dogs\\2.jpeg', 'Dog_Cat_Dataset\\dogs'], ['Dog_Cat_Dataset\\dogs\\3.jpeg', 'Dog_Cat_Dataset\\dogs'], ['Dog_Cat_Dataset\\dogs\\4.jpeg', 'Dog_Cat_Dataset\\dogs'], ['Dog_Cat_Dataset\\dogs\\5.jpeg', 'Dog_Cat_Dataset\\dogs']]
<__main__.CustomDataset object at 0x00000254C0568FD0>
<torch.utils.data.dataloader.DataLoader object at 0x00000254C250A7F0>
Traceback (most recent call last):
  File "C:\Users\parag\PycharmProjects\Custom-Dataset-and-Dataloader-in-Torch\Main.py", line 40, in <module>
    for imgs, labels in data_loader.dataset:
  File "C:\Users\parag\PycharmProjects\Custom-Dataset-and-Dataloader-in-Torch\Main.py", line 29, in __getitem__
    class_id = self.class_map[class_name]
KeyError: 'Dog_Cat_Dataset\\cats'

Process finished with exit code 1

[My Folder Structure][1]
I have tried, but not able to resolve the error. Could someone please help me with this?
[1]: https://i.stack.imgur.com/1giJw.png

A: You've used forward slash when it should be backslash:
    for class_path in file_list:
        class_name = class_path.split("\\")[-1]
        for img_path in glob.glob(class_path + "\*.jpeg"):
            self.data.append([img_path, class_name])

I'm guessing you're running on windows when the example is from linux.


text:
Q: Blockchain currency on disconnected nodes Good afternoon!  I have a conceptual question regarding maintaining blockchain currency on disconnected nodes...
What happens to transaction currency (as in, the blockchain kept current) in situations where (for example) a large network is disconnected from the public network for an extended period of time (or blocked)?  Let's use the example of a country disconnecting itself from the public internet (for all intents and purposes; yes I know that's almost impossible but go with me), but business utilizing blockchain transactions still continues inside the country.
How is blockchain currency (re)established once that country (network of nodes) is reconnected to the public network?  Are transactions verified/sync'd with the public network based on a verifiable transaction time, or what?
Thanks!
Steve

A: After resync:

*

*The transactions realized in bigger network will be marked as proper

*The transactions realized in smaller network will have been marked as invalid and will be ignored

External systems usually are protected from problems related to network fragmentation. External system require connection to many nodes in different locations (countries). If payment isn't visible in all locations it isn't accepted at all.
Moreover some cryptocurrencies are protected from network fragmentation. The node which finds that lost connection to nodes in different location will stop accepting new transactions.