text:
Q: Why does "F5 - Start Debugging" ignore breakpoints in PowerGUI? I'm not sure if I'm being a bit thick, but I have a simple script with three lines:
$iis = 90000
$name = "somesite"
Write-Host("Values are: $iis and $name")

If I set a breakpoint on any of these lines and hit the play button (F5 - start debugging) the script runs but the breakpoints are ignored.
If I start the script with F11 (step into) I can step through just fine, however hitting F5 to run to the next breakpoint again causes PowerGUI to ignore the breakpoints
The script I'm working on is substantial and I don't really want to have to F11 through every line of code.
Why would this be?

*

*I'm running PowerGUI 2.2.0.1358 on Windows 7 64-bit Ultimate Edition.

*I tried both the x64 and x32 versions of the PowerGUI script editor without success.

*I'm also running the PowerGUI Script Editor as Administrator (launched using right-click on PowerGUI Script Editor shortcut and Run As Administrator)

*My PowerShell execution policy is set to Unrestricted.

A: It looks like there's a problem with PowerShell and square brackets in folder and filenames.
Both PowerGUI and PowerShell ISE won't hit breakpoint if the script being debugged resides in a folder with [ or ] in the name.

A: I had this problem when the script that I was running was on a remote file share.
E.g. \\serverA\FileShare\script.ps1.
When I saved the script as c:\script\script.ps1 it was ok.

A: Powershell apparently also has an issue with spaces in the folder names. It did not like 'My Documents' but did for 'Documents'. Once I switched my path in PowerShell within ISE the debugger worked again.


text:
Q: User add Macro in Visual Studio does not work I want to add macro in my vcxproj file, or more precisely in user .props file, which is loaded from my vcxproj file.
I use this user macro for name of destination exe file (in vcxproj file):
<PropertyGroup Label="Globals">
    <TargetName>MajAcTest_$(MyVariable)_$(Platform)</TargetName>
</PropertyGroup>

And in prop file I have definition of this macro:
  <PropertyGroup Label="Configuration">
    <PlatformToolset Condition="'$(Configuration)'=='Debug'">v141</PlatformToolset>
    <PlatformToolset Condition="'$(Configuration)'=='Rel_2018'">v140</PlatformToolset>
    <PlatformToolset Condition="'$(Configuration)'=='Rel_2019'">v140</PlatformToolset>
    <PlatformToolset Condition="'$(Configuration)'=='Rel_2019'">v140</PlatformToolset>
    <PlatformToolset Condition="'$(Configuration)'=='Rel_2020'">v141</PlatformToolset>
    <PlatformToolset Condition="'$(Configuration)'=='Rel_2021'">v142</PlatformToolset>
    <PlatformToolset Condition="'$(Configuration)'=='Rel_2022'">v141</PlatformToolset>
  </PropertyGroup>

If I open project in Visual Studio (2017), in properties semms to be all rigth - name of file is, eg. "MajAcTest_Rel_2018_x64"

But if I build file, the name of file is without my variable (MajAcTest__x64)
Why? Please help.

A: After I test the program, I find that you could make the following changes:
<PropertyGroup Label="Globals">
    <TargetName>MajAcTest_$(Configuration)_$(Platform)</TargetName>
</PropertyGroup>

Also, you need to set the Sloutions Configurations as Rel_2018.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Load external js file with jQuery Looked for it everywhere, and found the answer but lost. anyone knows how to load an external .js file from another js file?
main_lobj1.onreadystatechange = function(){
  if (main_lobj1.readyState == 4) {if (main_lobj1.status == 200) {
    document.getElementById("middleDiv_m").innerHTML=main_lobj1.responseText;
  jQuery.getScript('jquery/tabs.js')
  }
}

innerHTML works and responce text is pasted. The problem is that JS is not working in that document. jQuery.getScript should be loading that external js file, but it doesnt

A: If you call an external script you want to base your script on you may want to take note that ajax-based jquery script are asynchronous by defealt.
Calling an external script asynchronousily will cause the rest of the rest being executed before the external script is loaded.
Today I ran into the same problem which was easily being solved by making a small adition to Sam Arul Raj's post:
$.ajax({
  type: "GET",
  url: "test.js",
  dataType: "script",
  async: false
});

A: This is the way you can do it to load an external js file to Jquery
$.ajax({
  type: "GET",
  url: "test.js",
  dataType: "script"
});

A: Exactly for this reason a function $.getScript() exist in jquery. You can use it simply in this way:
$.getScript("test.js", function( data, textStatus, jqxhr ) {
  // this is your callback.
});


text:
Q: Ejecutar dos funciones en setTimeout Muy buenas, tengo este código en el que pretendo que tras inactividad, se redirija a login.html
var nameTime;
function ini() {
    nameTime = setTimeout('location="login.html"',5000);
 }
function parar() {
  clearTimeout(nameTime);
    nameTime = setTimeout('location="login.html"',5000);
 }

Después
<body onload="ini()" onkeypress="parar()" onclick="parar()" onmousemove="parar()" >

Me gustaría poner algún tipo de aviso de que se ha redireccionado por inactividad, algo tipo toast o alert. Esto lo tengo ya, lo que no se es como hacer que el usuario vea algún tipo de mensaje cuando sea redireccionado

A: Lo que tendrías que hacer es que el setTimeout llamara a una función que mostrara el mensaje y, con otro timeout para dar al usuario tiempo a leerlo, redirija a la pantalla de login.
Algo así:

var nameTime;
function ini() {
  nameTime = setTimeout(redirigir, 5000);
}
function parar() {
  clearTimeout(nameTime);
  nameTime = setTimeout(redirigir, 5000);
}
function redirigir(){
  document.getElementById('message').style.display='inline';
  setTimeout('location="login.html"',1500);
}
body{
  padding: 10px;
}
#message{
  font-size: 20px;
  font-weight: bold;
  border: solid 1px #333333;
  padding: 15px;
  display:none;
}
<body onload="ini()" onkeypress="parar()" onclick="parar()" onmousemove="parar()" >
<div id="message">
  Va a ser redirigido a la pantalla de login por inactividad
</div>


text:
Q: ReactiveUI 6.5 ReactiveList.ItemChanged not triggering in UnitTest I have a ReactiveList with view models with a 'Selected' property. When I try to set this property from a unit-test, the subscription on ReactiveList.ItemChanged is not invoked. It works, however, when running the application and triggering the 'Selected' property from a check-box in the UI. Is there anything magic I have to do to make ReactiveList.ItemChanged work in a unit-test environment? I am using ReactiveUI 6.5 by the way.
WellsViewModels = new ReactiveList<WellViewModel> { ChangeTrackingEnabled = true };

var selectedWellsObservable =
    Observable.Merge(
        this.WhenAnyValue(vm => vm.WellSamplesFunc)
            .Select(_ => Enumerable.Empty<IPropertyModelingWell>()),
        WellsViewModels
            .ItemChanged
            .Where(x => x.PropertyName == nameof(WellViewModel.Selected))
            .Throttle(TimeSpan.FromMilliseconds(100), RxApp.MainThreadScheduler)
            .Select(_ => WellsViewModels.Where(vm => vm.Selected)
                                        .Select(vm => vm.Well).ToList())
    )
    .Publish()
    .RefCount();

selectedWellsObservable
    .Select(_ => ComputeAllCheckedState(WellsViewModels))
    .Subscribe(b => CheckAllWells = b) // <--- This is never invoked when unit-testing!?!

[Test]
public void CheckAllWells_UpdatedWhenWellsViewModelsSelectionChanges()
{
    new TestScheduler().With(scheduler =>
    {
        // Arrange
        ...
        ...

        // Act
        _viewModel.WellsViewModels[0].Selected = true;
        scheduler.AdvanceBy(TimeSpan.FromMilliseconds(200).Ticks);

        // Assert
        Assert.IsFalse(_viewModel.CheckAllWells.HasValue);
    });
}


text:
Q: TypeError: done() takes 1 positional argument but 2 were given In my following program I basicly want to create a edit field which, after I double click it, transforms into a label with the text I wrote in the edit field. Here is my code:
GUI.py:
from tkinter import *
import sys
import Classes
root = Tk()
root.wm_title("Schelling-Cup Alpha 1.0")
root.config(background = "#FFFFFF")

#VARIABLEN LADEN

playerlist = []

#BILDER WERDEN GELADEN

hintergrund = PhotoImage(file = "C:\\Users\\Jakub Pietraszko\\Desktop\\MarioKartProject\\Hintergrund2.png")
fotobutton1 = PhotoImage(file = "C:\\Users\\Jakub Pietraszko\\Desktop\\MarioKartProject\\Button_8Spieler_.png")
fotobutton2 = PhotoImage(file = "C:\\Users\\Jakub Pietraszko\\Desktop\\MarioKartProject\\Button_16Spieler_.png")

#FIRSTFRAME EDITED
firstFrame = Frame(root, width=400, height = 400)
firstFrame.grid(row = 0, column = 0, padx = 3, pady = 3)
x = Label(firstFrame, image = hintergrund)
x.grid(row = 0, column = 0)
def callback1():
    """Die Funktion für 8 Spieler, welche dann den entsprechenden Frame lädt."""
    Classes.EditToLabel(400, 400, firstFrame)
    pass
def callback2():
    """Die Funktion für 16 Spieler, welche dann den entsprechenden Frame lädt."""
    pass
B1 = Button(firstFrame, text = "Button1", bg = "#FFFFFF", width = 700, command = callback1)
B1.config(image = fotobutton1)
B1.place(x = 290, y = 250)
B2 = Button(firstFrame, text = "Button2", bg ="#FFFFFF", width = 700, command = callback2)
B2.config(image = fotobutton2)
B2.place(x = 290, y = 450)

#SECOUNDFRAME EDITED

secoundFrame = Frame(root, width = 400, height = 400)

root.mainloop() #GUI wird upgedated. Danach keine Elemente setzen

And here is my secound file, Classes.py:
from tkinter import *
import sys

x = 100
y = 100

class EditToLabel():
    def __init__(self, x_Koordinate, y_Koordinate, whichFrame):
        self.x_Koordinate = x_Koordinate
        self.y_Koordinate = y_Koordinate
        self.whichFrame = whichFrame

        global neuesEntry
        neuesEntry = Entry(whichFrame, width = 40)
        neuesEntry.place(x = x_Koordinate, y = y_Koordinate)

        neuesEntry.bind('<Double-Button-1>', self.done)
    def done(self):
        Eintrag = neuesEntry.get()
        neuesEntry.destroy()
        neuesLabel = Label(self.whichFrame, text = Eintrag, x = self.x_Koordinate, y = self.y_Koordinate)

Now the problem is, that I get and error and dont know exactly what to do. Following error message I get now:

Exception in Tkinter callback Traceback (most recent call last):
  File "C:...\Programs\Python\Python37\lib\tkinter__init__.py", line
  1705, in call
      return self.func(*args) TypeError: done() takes 1 positional argument but 2 were given

Does anybody know what I make wrong and could give me an example how to make it better and improve it?

A: When binding a method in Tkinter, the app sends information about the event as and argument to the function even if you dont use it.
Try:
def done(self, event = None):
    ...

Setting "event" as a default parametrer helps when you need to use self.done()
through other methods besides .bind().


text:
Q: How to make conditional regex I want to create regex where the {{if gender == }} will be fixed and "Male", "Female", "Both" and "Unknown" will be dynamic values to be checked. I have tried something like this
/^\{\{if gender == "Male"|"Female"|"Both"|"Unknown"\}\}$/i

but this only checks {{if gender == "Male" and it's not good.
Also, I have tried something like this
/^\{\{if gender == ("Male"|"Female"|"Both"|"Unknown")\}\}$

but this only shows me a group.
What am I doing wrong?

A: You need to put parenthesis on the first part too and it works:
^(?:\{\{if gender ==) (?:"Male"|"Female"|"Both"|"Unknown")\}\}$

I am using ?: to make it Non-capturing group. Alternately, it can be used as follows:
^(\{\{if gender ==) ("Male"|"Female"|"Both"|"Unknown")\}\}$

Regex working link


text:
Q: Rails not detecting in windows 10 command prompt I tried rails -v but I am getting

'rails' is not recognized as an internal or external command,operable
  program or batch file.

I have done gem install rails --no-document and it installed Rails 5.0.1 but rails -v not working
I have set the environment variable to C:\RailsInstaller\Ruby2.3.0\bin\rails.bat
I have followed this guide http://installfest.railsbridge.org/installfest/windows
Thanks.

A: From my understanding, PATHEXT is missing .BAT from it. This is the environment variable responsible for knowing files to be executed without extensions .
To confirm, please do SET PATHEXT on a new command prompt and see the output, the result should be a semi-colon separated values that include .EXE, .BAT, .COM and perhaps .RB
If PATHEXT is empty or do not contain .BAT in it, that could explain why is not working.
This usually happens when windows versions do not match with that of rails. To solve, uninstall RubyInstaller and reboot the system and verify. I f variables are not restored, reinstall ruby. this should fix your problem.
Source: Ruby Documentations


text:
Q: Should I configure my URLs with a leading and/or trailing slash? Maybe too basic of a question but wanted to see if there is more to it than I am thinking.
When configuring URLs (baseUrls, like https://my.app or relative URLs like /path/to/resource) either as a static variable, in configuration files or environment variables etc., what should my 'slash strategy' be?
One of my coworkers mentioned that I should always configure base URLs with a trailing slash (https://my.app/) and paths with a leading and trailing slash (/path/to/resource/) because in most cases when you concatenate these, you may end up with double slashes (http://my.app//path/to/resource/) but most tools can handle that. If the claim that most tools can handle it is true, this could be an attractive approach since all you need to know is to always use slashes everywhere.
The other solutions could either be to follow and be consistent with either one of these approaches:

*

*No trailing slashes but always use leading ones (http://my.app, /path/to/resource)

*No leading slashes, but always use trailing ones (http://my.app/, path/to/resource/)

Is there a best strategy? Would the strategies be dependent on the tools being used (like libraries that can handle one but not the other?)

A: Always including a trailing slash on the base URL and omitting the leading slash on the relative URL would allow you to concatenate the two in a manner that matches the spec on combining a base URL with relative URL to derive a full URL (RFC1808, Section 4).
Doing it this way would allow you to have a consistent method that is also the least surprising.

A: Do not use bare strings to record URIs. Most languages have a type for them that handles joining absolute and relative paths automatically, ensuring you never need to sorry about doubled (or missing) slashes. Using this type will save you no end of problems,


text:
Q: Why does JavaScript force integer variables into string variables? I'm doing a project for school which is a website with many random little projects.
In one of these projects I've embedded a video that has a src link "...blah.../Ndub1" and if you change the "1" from the link to, for example "2", then you get the next video. Now I'm trying to write a javaScript script that will change that number to "number + 1" or to "number - 1" on a button click. Here's the source code of my website:

Number of episode: <input type="text" id="episodeInput"/>

<input type="radio" name="narutoSeason" id="naruto"> Naruto

<input type="radio" name="narutoSeason" id="narutoShippuden"> Naruto Shippuden

<button type="button" id="submitButton" onclick="narutoGetEpisodeGen()">Submit</button>

            <embed type="application/x-shockwave-flash" src="http://cdn.directvid.com/jwplayer/player.swf" style="undefined" name="embeddedVid" quality="high" allowfullscreen="true" allowscriptaccess="always" wmode="opaque" flashvars="autostart=&stretching=exactfit&type=video&skin=http://cdn.directvid.com/jwplayer/nemesis1.zip&file=http://www.animefun.com/dl/googDev.php?url=/112965806382805543465/Ndub1&plugins=timeslidertooltipplugin-2" height="480px" width="720px">

<button type="button" onClick="oneBack()">Previous</button>  <button type="button" onClick="oneForward()">Next</button>

So the main problem is that the part where I add or substract 1 from the number. First time I use the oneForward button it works normal, but the next time I use that button it just adds "1" to the number of episode I started with. Then the error keeps repeating if I use the same button, but stops occuring if I use the other button and from that point on it works normally.
To make my self extra clear I'll type some examples of what exactly I'm doing.
- Type in the input(id="episodeInput"): 3 > click on input(id="narutoShippuden") > click the button(id="submitButton") > observe how the function("narutoGetEpisode") did its job perfectly > click the button(onClick="oneForward") > observe the function working just fine (transformed the number from "3" to "4") > click the button(onClick="oneForward") again > observer how the link in embedded part transformed the number into "31" > click the button(onClick="oneForward") again > observer how the link in embedded part transformed the number into "311" > click the button(onClick="oneForward") again > observer how the link in embedded part transformed the number into "3111" > click the button(onClick="oneForward") again > observer how the link in embedded part transformed the number into "31111"  > click the button(onClick="oneBack") > observe the function working just fine (transformed the number from "31111" to "31110") > from here on, both buttons act just fine
- Type in the input(id="episodeInput"): 3 > click on input(id="narutoShippuden") > click the button(id="submitButton") > observe how the function("narutoGetEpisode") did its job perfectly > click the button(onClick="oneForward") > observe the function working just fine (transformed the number from "3" to "4") > click the button(onClick="oneBack") > observer how the link in embedded part transformed the number into "30" > click the button(onClick="oneForward") again > observe how the button did its job okay (transforms the number from "30" to "31") > click the button(onClick="oneForward") again > observe how the button did its job okay (transforms the number from "31" to "32") > click the button(onClick="oneBack") again > observe how the button did its job okay (transforms the number from "32" to "31") > from here on, both buttons act just fine
- Type in the input(id="episodeInput"): 3 > click on input(id="narutoShippuden") > click the button(id="submitButton") > observe how the function("narutoGetEpisode") did its job perfectly > click the button(onClick="oneBack") > observe the function working just fine (transformed the number from "3" to "2") > click the button(onClick="oneBack") > observe the function working just fine (transformed the number from "2" to "1") > from here on, both buttons act just fine

I also should mention that this happens in all three, Mozilla, Chrome and IE (all up to date).
So as I was brainstorming through this problem and searching the forums I tried many variants to fix the code, so now I'm going to type the things I tested and worked simmilarly wierd or worse:
To be clear I only cnanged the code in "script" tag in header, more precisely, only in these lines:
function oneForward() {
                var a, z, link;
                if (s == 0) {
                    z = eval(parseInt(e)+1);
                    a = "Ndub"+z.toString();
                    e += 1;
                }
                else {
                    z = eval(parseInt(e)+1);
                    a = "Nshipdub"+z.toString();
                    e += 1;
                }
                link = '<embed type="application/x-shockwave-flash" src="http://cdn.directvid.com/jwplayer/player.swf" style="undefined" name="embeddedVid" quality="high" allowfullscreen="true" allowscriptaccess="always" wmode="opaque" flashvars="autostart=&stretching=exactfit&type=video&skin=http://cdn.directvid.com/jwplayer/nemesis1.zip&file=http://www.animefun.com/dl/googDev.php?url=/112965806382805543465/' + a + '&plugins=timeslidertooltipplugin-2" height="480" width="720">';
                link2 = '<video width="720" height="480" controls><source id="videoEmbeddedVid" src="http://www.animefun.com/dl/googDev.php?url=/112965806382805543465/' + a + '&amp&autoplay=0" type="video/webm">Your browser does not support the video tag.</video>';
                document.getElementById('embeddedVideoDiv').innerHTML = link;
                document.getElementById('videoVidDiv').innerHTML = link2;
            }

            function oneBack() {
                var a, x, link;
                if (s == 0) {
                    x = eval(parseInt(e)-1);
                    a = "Ndub"+x.toString();
                    e -= 1;
                }
                else {
                    x = eval(parseInt(e)-1);
                    a = "Nshipdub"+x.toString();
                    e -= 1;
                }
                link = '<embed type="application/x-shockwave-flash" src="http://cdn.directvid.com/jwplayer/player.swf" style="undefined" name="embeddedVid" quality="high" allowfullscreen="true" allowscriptaccess="always" wmode="opaque" flashvars="autostart=&stretching=exactfit&type=video&skin=http://cdn.directvid.com/jwplayer/nemesis1.zip&file=http://www.animefun.com/dl/googDev.php?url=/112965806382805543465/' + a + '&plugins=timeslidertooltipplugin-2" height="480" width="720">';
                link2 = '<video width="720" height="480" controls><source id="videoEmbeddedVid" src="http://www.animefun.com/dl/googDev.php?url=/112965806382805543465/' + a + '&amp&autoplay=0" type="video/webm">Your browser does not support the video tag.</video>';
                document.getElementById('embeddedVideoDiv').innerHTML = link;
                document.getElementById('videoVidDiv').innerHTML = link2;

so I changed the
z = eval(parseInt(e)+1);
a = "Nshipdub"+z.toString();

to
z = (parseInt(e)+1);
a = "Nshipdub"+z.toString();

or
z = (e+1);
a = "Nshipdub"+z.toString();

or
a = "Nshipdub"+(e+1);

or
a = "Nshipdub"+(e*1+1);

or
a = "Nshipdub"+(parseInt(e)+1);

or
a = "Nshipdub"+(parseInt(e)*1+1);

or
a = "Nshipdub"+(parseInt(e)+1).toString();

and some others which I don't even remember any more. Anyway, all of them were no better.
I'd really appreciate some help with this and also an explanation why the above examples wont work, especially the ones with another variable, because I read the examples on forums saying that >"string" + 3+1"< equals to >"string + "3" + "1"< and that the >1+5 + "string"< equals to >6 + "string"<.

A: "Why does JavaScript force integer variables into string variables?"
Because, uh...
var e = "1";

You're defining it as a string?
e = document.getElementById('episodeInput').value

Twice?
Try:
var e = 1;

and:
e = parseInt(document.getElementById('episodeInput').value,10);


text:
Q: Does VS2010 C++ optimization do loop unrolling I have the following piece of simple code that is potentially going to be executed many hundreds of millions of times;
for (int i = 0; i < 8; i++)
    if (((p[i].X >= x) && (p[i].X <= x + d))
        &&((p[i].Y >= y) && (p[i].Y <= y + d))
        &&((p[i].Z >= z) && (p[i].Z <= z + d)))
      return 1;

Will the optimizer in the Visual C++ 2010 compiler unroll this loop for me, or am I better off to do it manually?  I've looked at other similar questions but don't see any specific results.  I

A: The real question is, what do you gain from unrolling ?
Unrolling shaves off one branch (if i >= 8 stop) for every "unroll".
Your loop body contains 6 branches already (if * 1, || * 2, && * 3); so is there much to gain in unrolling it ?
It might be interesting to see how the code is optimized; but I am quite unsure whether unrolling should be your primary focus, I'd be more worried about how the complex condition is handled!


text:
Q: Remove null value from nested list in R I have a nested list of data frames. In those data frames I have NA variables (vectors now?). I want to remove those elements.
EDIT: actually I have NULL instead of NA.
df.ls <- list(list(id = NULL, x = 3, works = NULL),
                 list(id = 2, x = 4, works = NULL),
              NULL)

I tried this code, but don't know how to tell which level should it use.
df.ls[sapply(df.ls, is.null)] <- NULL

A: For NULL values we can do
l1 <- lapply(df.ls, function(x) x[lengths(x) > 0])

For NAs we can do
l1 <- lapply(df.ls, function(x) x[!is.na(x)])
l1

#[[1]]
#[[1]]$x
#[1] 3

#[[2]]
#[[2]]$id
#[1] 2

#[[2]]$x
#[1] 4

#[[3]]
#list()

If you want to remove the empty list, you can do
l1[lengths(l1) >  0]

A: I am not sure what you are trying to do, since you say you have a list of data.frames but the example you provide is only a list of lists with elements of length one.
Lets assume you have a list of data.frames, which in turn contain vectors of length > 1, and you want to drop all columns that "only" contain NAs.
df.ls <- list(data.frame(id = c(NA,NA,NA),
                         x = c(NA,3,5),
                         works = c(4,5,NA)),
              data.frame(id = c("a","b","c"),
                         x = c(NA,3,5),
                         works = c(NA,NA,NA)),
              data.frame(id = c("e","d",NA),
                         x = c(NA,3,5),
                         works = c(4,5,NA)))

>   [[1]]
      id  x works
    1 NA NA     4
    2 NA  3     5
    3 NA  5    NA

    [[2]]
      id  x works
    1  a NA    NA
    2  b  3    NA
    3  c  5    NA

    [[3]]
        id  x works
    1    e NA     4
    2    d  3     5
    3 <NA>  5    NA

Then this approach will work:
    library(dplyr)
    library(purrr)
    non_empty_col <- function(x) {
        sum(is.na(x)) != length(x)
    }

    map(df.ls, ~ .x %>% select_if(non_empty_col))

Which returns your list of data.frames without columns that contain only NA.
[[1]]
   x works
1 NA     4
2  3     5
3  5    NA

[[2]]
  id  x
1  a NA
2  b  3
3  c  5

[[3]]
    id  x works
1    e NA     4
2    d  3     5
3 <NA>  5    NA

If you, however, prefer your list to have only complete cases in each data.frame (rows with no NAs), then the following code will work.
library(dplyr)
map(df.ls, ~ .x[complete.cases(.x), ])

Leaving you, in case of my example data, only with row 2 of data.frame 3.

A: To remove the NULL
discard(map(df.ls, ~ discard(.x, is.null)), is.null)
#[[1]]
#[[1]]$x
#[1] 3

#[[2]]
#[[2]]$id
#[1] 2

#[[2]]$x
#[1] 4

Or in base R with Filter and is.null
Filter(Negate(is.null), lapply(df.ls, function(x) Filter(Negate(is.null), x)))

Earlier version before the OP's update
library(purrr)
map(df.ls, ~ .x[!is.na(.x)])
#[[1]]
#[[1]]$x
#[1] 3

#[[2]]
#[[2]]$id
#[1] 2

#[[2]]$x
#[1] 4

#[[3]]
#list()


text:
Q: disable MTP udev rules for specific device so it can be mount as a USB Mass Storage device I have a problem with a specific device that is not an android / mobile device.
It is a media player with an internal hard drive that I am trying to connect as a mass storage device so I can copy movies/series too and from it.
I see the following when I connect it to my system
kernel: usb 1-4: new high-speed USB device number 7 using xhci_hcd
systemd[1]: Starting Cleanup of Temporary Directories...
systemd[1]: Started Cleanup of Temporary Directories.
mtp-probe[4978]: checking bus 1, device 7: "/sys/devices/pci0000:00/0000:00:14.0/usb1/1-4"
kernel: usb 1-4: can't set config #1, error -110
mtp-probe[4978]: bus: 1, device: 7 was not an MTP device
kernel: usb 1-4: USB disconnect, device number 7

lsusb shows me
Bus 001 Device 008: ID 174c:5106 ASMedia Technology Inc. ASM1051 SATA 3Gb/s bridge
Couldn't open device, some information will be missing
Device Descriptor:
  bLength                18
  bDescriptorType         1
  bcdUSB               2.10
  bDeviceClass            0
  bDeviceSubClass         0
  bDeviceProtocol         0
  bMaxPacketSize0        64
  idVendor           0x174c ASMedia Technology Inc.
  idProduct          0x5106 ASM1051 SATA 3Gb/s bridge
  bcdDevice            0.01
  iManufacturer           2
  iProduct                3
  iSerial                 1
  bNumConfigurations      1
  Configuration Descriptor:
    bLength                 9
    bDescriptorType         2
    wTotalLength           32
    bNumInterfaces          1
    bConfigurationValue     1
    iConfiguration          0
    bmAttributes         0xc0
      Self Powered
    MaxPower                0mA
    Interface Descriptor:
      bLength                 9
      bDescriptorType         4
      bInterfaceNumber        0
      bAlternateSetting       0
      bNumEndpoints           2
      bInterfaceClass         8 Mass Storage
      bInterfaceSubClass      6 SCSI
      bInterfaceProtocol     80 Bulk-Only
      iInterface              0
      Endpoint Descriptor:
        bLength                 7
        bDescriptorType         5
        bEndpointAddress     0x81  EP 1 IN
        bmAttributes            2
          Transfer Type            Bulk
          Synch Type               None
          Usage Type               Data
        wMaxPacketSize     0x0200  1x 512 bytes
        bInterval               0
      Endpoint Descriptor:
        bLength                 7
        bDescriptorType         5
        bEndpointAddress     0x02  EP 2 OUT
        bmAttributes            2
          Transfer Type            Bulk
          Synch Type               None
          Usage Type               Data
        wMaxPacketSize     0x0200  1x 512 bytes
        bInterval               0

My kernel and distro
uname -a
Linux aaron-pc 4.9.24-1-MANJARO #1 SMP PREEMPT Fri Apr 21 08:32:28 UTC 2017 x86_64 GNU/Linux

A: After much reading and testing.
I found out that this is related to a recent change in the default Udev rules to set a catch-all rule for devices to be handled by MTP if they don't match any other udev rules for USB devices.
Instead of my device being mounted as a USB mass storage device as it used to.
I found that I need to let udev know that this device should be managed a USB mass storage device instead of the MTP catch all rule
First I need my devices ID. Below it is the last one in the list
$ lsusb
Bus 002 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 001 Device 003: ID 8087:0a2a Intel Corp.
Bus 001 Device 002: ID 04f2:b51d Chicony Electronics Co., Ltd
Bus 001 Device 006: ID 04e8:6860 Samsung Electronics Co., Ltd Galaxy (MTP)
Bus 001 Device 005: ID 0b05:181b ASUSTek Computer, Inc.
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 001 Device 007: ID 174c:5106 ASMedia Technology Inc

I am sure there is more to this then what I have here, but this works for me. I take the device ID which 174c:5106 and replace it in the udev rules below.
$ cat /etc/udev/rules.d/90-myrules.rules
SUBSYSTEMS=="usb", ENV{MODALIAS}=="usb:174c:5106", ENV{MODALIAS}="usb-storage"

You will need to get udev to restart/reload to update the rules.
systemctl reload systemd-udevd.service

or
systemctl restart systemd-udevd

I now see the following in my system logs
journalctl -fe

kernel: usb 1-2: USB disconnect, device number 9
kernel: usb 1-2: new high-speed USB device number 10 using xhci_hcd
mtp-probe[9850]: checking bus 1, device 10: "/sys/devices/pci0000:00/0000:00:14.0/usb1/1-2"
mtp-probe[9850]: bus: 1, device: 10 was not an MTP device
kernel: usb-storage 1-2:1.0: USB Mass Storage device detected
kernel: scsi host3: usb-storage 1-2:1.0
kernel: usbcore: registered new interface driver usb-storage
kernel: usbcore: registered new interface driver uas
kernel: scsi 3:0:0:0: Direct-Access     ST310005 24AS             JC4B PQ: 0 ANSI: 0
kernel: sd 3:0:0:0: Attached scsi generic sg2 type 0
kernel: sd 3:0:0:0: [sdb] 1953525168 512-byte logical blocks: (1.00 TB/932 GiB)
kernel: sd 3:0:0:0: [sdb] Write Protect is off
kernel: sd 3:0:0:0: [sdb] Mode Sense: 23 00 00 00
kernel: sd 3:0:0:0: [sdb] No Caching mode page found
kernel: sd 3:0:0:0: [sdb] Assuming drive cache: write through
kernel:  sdb: sdb1
kernel: sd 3:0:0:0: [sdb] Attached SCSI disk

A: First copy the file /lib/udev/rules.d/69-libmtp.rules to /etc/udev/rules.d/69-libmtp.rules:
$ sudo cp /lib/udev/rules.d/69-libmtp.rules /etc/udev/rules.d/69-libmtp.rules

At the top of this file you can find:
# Some sensitive devices we surely don't wanna probe
ATTR{idVendor}=="0670", GOTO="libmtp_rules_end"
ATTR{idVendor}=="0471", ATTR{idProduct}=="083f", GOTO="libmtp_rules_end"

Then exclude the device from mtp-probe by adding next line after mentioned lines:
ATTR{idVendor}=="093a", ATTR{idProduct}=="2516", GOTO="libmtp_rules_end"

I found my USB device ID with lsusb shell command. It is 093a:2516

A: I'm experimenting peripherical disconnections using thinkpad dock (here)
Checking journalctl I found that last lines before disconnection shows mtp-probe device error, and I think the cause it could be the same exposed here but with my monitor.
How could I find my devices in order to exclude them for mtp-probe?
My lsusb:
Bus 002 Device 008: ID 17ef:1010 Lenovo Lenovo ThinkPad Dock
Bus 002 Device 002: ID 0bda:0316 Realtek Semiconductor Corp. USB3.0-CRW
Bus 002 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 001 Device 006: ID 138a:0097 Validity Sensors, Inc.
Bus 001 Device 005: ID 5986:2118 Acer, Inc Integrated Camera
Bus 001 Device 030: ID 046d:c084 Logitech, Inc. G203 Gaming Mouse
Bus 001 Device 029: ID 17ef:100f Lenovo Lenovo ThinkPad Dock
Bus 001 Device 028: ID 17ef:1010 Lenovo Lenovo ThinkPad Dock
Bus 001 Device 027: ID 04b4:1007 Cypress Semiconductor Corp.
Bus 001 Device 008: ID 2386:340e Raydium Corporation Raydium Touch System
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub


text:
Q: grep -v not working when piping from iwconfig but works when piping from cat on a file I am running iwconfig | grep -v "no wireless extensions" but can't get the -v option to work as expected. I want to exclude lines including "no wireless extensions", i.e., I want to display only the active/working wireless interface or whatever this should be called.
In the beginning I thought perhaps the command outputs to a stream different than the one piped to grep, so I tried cat myFile | grep -v myExclusionPattern. This works as expected, so I concluded -v does what I expect it does.
I then tried iwconfig | grep "no wireless extensions" and again the result is the expected - meaning the output of iwconfig is what is piped to grep.
So I am left with the question why specifically -v is not working when piping the results of iwconfig to grep.
Here is my output to iwconfig:
enp4s0    no wireless extensions.

docker0   no wireless extensions.

lo        no wireless extensions.

wlp5s0    IEEE 802.11  ESSID:"myEssid"
          Mode:Managed  Frequency:5.24 GHz  Access Point: 74:83:C2:75:86:2A
          Bit Rate=6 Mb/s   Tx-Power=30 dBm
          Retry short limit:7   RTS thr:off   Fragment thr:off
          Power Management:on
          Link Quality=59/70  Signal level=-51 dBm
          Rx invalid nwid:0  Rx invalid crypt:0  Rx invalid frag:0
          Tx excessive retries:0  Invalid misc:747   Missed beacon:0

Summarizing:

*

*grep -v works for me when I pipe to grep the output of a file with cat.

*I can't reproduce the same behavior as in (1) when piping the output of iwconfig to grep.

I read the following questions on grep -v, but am not able to find the answer to the above in any of them:

*

*Why "grep -q -v" only works with single line input?

*Pipe find into grep -v

*grep -v without output?

*grep -v -f alternative

A: iwconfig outputs to both standard output and to standard error, depending on whether it found or did not find any wireless extensions for an interface.  Piping only affects standard output.
Example removing the output sent to the standard error stream (only shows interfaces that have wireless extensions):
$ /usr/sbin/iwconfig 2>/dev/null
wlp4s0    IEEE 802.11  ESSID:off/any
          Mode:Managed  Access Point: Not-Associated   Tx-Power=22 dBm
          Retry short limit:7   RTS thr:off   Fragment thr:off
          Power Management:on

Example removing the output sent to the standard output stream (only shows interfaces where iwconfig failed to find wireless extensions):
$ /usr/sbin/iwconfig >/dev/null
lo        no wireless extensions.

enp0s31f6  no wireless extensions.

wwan0     no wireless extensions.

docker0   no wireless extensions.

br-ca679f9ee354  no wireless extensions.

veth232fd86  no wireless extensions.

vboxnet0  no wireless extensions.

A: I see no one mentioned this alternative, but I would consider using
iwconfig 2>&1 | grep -v "no wireless extensions" a solution as well (perhaps even more elegant ?)
Now both errors and regular output are sent to the same file descriptor (standard output), which is what is piped to grep, which can finally filter the whole data.


text:
Q: How to disable the sliding of menu of Action bar in xamarin forms? I am using MasterDetailPage and using Action Bar in it. I have disabled and hide logo, icon and back button of action bar. But when I try to swipe from left to right from left side a blank menu list opens. I don't know why it is happening. how I can disable this one for action bar. I don't want menu list that's why I disabled back button, icon.
How I can disable this sliding menu which is coming from left to right when I am swiping from left to right?

A: On the MasterDetailPage there is a Property called IsGestureEnabled.
Setting that to false should stop tracking the swipe gesture.


text:
Q: Change of variables with a continuous but not differentiable mapping Suppose that Y is a continuous random variable with a density function $f_{Y}(y)$. We transform $Y$ by the following mapping
\begin{equation} Y^{*} =  \left \{ \begin{array}{ll}
\alpha Y + \beta &  \text{ if } Y < y^{0} \\
 Y &  \text{ if } Y > y^{0}
\end{array} \right .
\end{equation}
where $\alpha$ and $\beta$ are known constants such that the mapping is continuous, but not differentiable at $Y = y^{0}$. How do I find the density function of $Y^{*}$?
My concern is how the non-differentiable point $Y=y^0$ affects the resulting density of $Y^∗$. My solution for the density of $Y^∗$ is the following:
$f_{Y^{*}}(y^{*}) = f_{Y}(y^{*}) I\{ Y^{*} > y^{0} \} +  \frac{1}{\alpha}f_{Y}\left (  \frac{y^{*} - \beta}{\alpha} \right) I\{ Y^{*} < \alpha y^{0} + \beta  \}. $

A: The transform leads to a cumulative distribution function that is non-differentiable in the point where you split the transformation.
The density function will have a jump discontinuity in that point. Possibly there are ways to still have the density defined in a way (e.g. use the directional continuity of the cumulative distribution function or an average as you did) but the discontinuity remains.
Below you see an example when we perform such transformation on the normal distribution


text:
Q: Stopping user input after certain entry? I am working on a very simple Java problem where I need to stop taking in data after a certain user value is entered. The user can still enter data after the value is entered, but once the value is entered, the output should not include that value or any data following that value. Also, I was trying to discount negative entries from being counted, but to no avail. Here is my code. Any help would be appreciated! Thank you!
import java.util.Scanner;

public class Sample
{
    public static void main (String[] args)
    {
        System.out.println("Please input any number, up to 10 entries. "
                + "Enter -1 to exit: ");
        Scanner read = new Scanner(System.in);
        int[] input_array = new int[10];
        int numOfEntries = 0;
        for(int i = 0; i < input_array.length; i++)
        {
            input_array[i] = read.nextInt();
            numOfEntries++;
            //only positive numbers
            if(input_array[i] >= 100 || input_array[i] < 0)
            {
                if(input_array[i] == 77) //certain value
                {
                    //entries before 77 is entered become the new array
                    numOfEntries = i;
                    int[] new_array = new int[numOfEntries];
                    for (int j = 0; j < numOfEntries; j++)
                    {
                        new_array[j] = input_array[i];
                    }
                    System.out.print(new_array[numOfEntries] + " ");
                }
                if(input_array[i] == -1) //exit loop
                {
                    break;
                }
                System.out.println("Please enter a positive
                number that is less than 100.");
            }
        }

        //final result
        System.out.println("Your entries are: ");
        for (int i = 0; i < numOfEntries; i++)
        {
            System.out.print(input_array[i] + " ");
        }

A: You should check like this to make sure everything correctly passes the conditions
//all this goes inside the for loop
    String input = read.nextInt();
    if (input == -1)
        break;
    if (input > 0)//is it negative?
    {
        if (input < 100)//is it greater than 100?
        {
           if (input == 77)//is it 77?
           {
               //your code
           }
           else//this will run when all conditions are passed
             input_array[i] = input;
        }
    }

A: No need to create a separate array,add into the initial array,only if it is a valid value.Check the below code,have made few modifications:
public static void main(String[] args) throws Exception {
        {
            System.out.println("Please input any number, up to 10 entries. " + "Enter -1 to exit: ");
            Scanner read = new Scanner(System.in);
            int[] input_array = new int[10];
            int numOfEntries = 0;
            int entry = 0, status = 0;
            for (int i = 0; i < input_array.length; i++) {
                entry = read.nextInt();
                // only positive numbers
                if (entry < 100 && entry >= 0) {
                    if (entry == 77) // certain value,change the value of 'status' here
                    {
                        status = 1;
                    }
                    if (status == 0) //if 'status' is not reset,then add the entry to array.
                    {
                        input_array[numOfEntries++] = entry;
                    }

                }  else if (entry == -1) // exit loop
                {
                    break;
                }else {//for negative and values which are greater than 100.
                    System.out.println("Please enter a positive number that is less than 100.");
                }
            }

            // final result
            System.out.println("Your entries are: ");
            for (int i = 0; i < numOfEntries; i++) {
                System.out.print(input_array[i] + " ");
            }
        }
    }

A: You dont need to add another array if you are not going to use it, So I have removed it and made some modification in your code. Please check the below code. Go through the comments. Hope you will understand.
import java.util.Scanner;

public class Sample {
    public static void main(String[] args) {
        System.out.println("Please input any number, up to 10 entries. "
                + "Enter -1 to exit: ");

        int[] input_array = new int[10]; //Input array - size 10
        int input = 0; // input variable
        boolean isInput77 = false; //Check input is 77 (certain value)
        int numOfEntries = 0; // Number of entries that passes your conditions
        Scanner read = new Scanner(System.in);

        for (int i = 0; i < 10; i++) {
            input = read.nextInt(); // input value assign to "input" variables
            if (input == -1){  // input is -1 break
                break;
            } else if (input == 77){ // input is 77 isInput77 is true
                isInput77 = true;
            } else if (!isInput77 && input < 100 && input >= 0) { // isInput77 is false and input is positive number that is less than 100 add to input_array
                input_array[numOfEntries] = input;
                numOfEntries++;
            } else if(input >= 100 || input < -1){ // input is negative or greater than or equal to 100
                System.out.println("Please enter a positive number that is less than 100.");
            }
        }

        System.out.println("Your entries are: ");
        for (int i = 0; i < numOfEntries; i++) { // Print only valuable entries
            System.out.print(input_array[i] + " ");
        }
    }
}


text:
Q: HTTPS support in elastic search Jest client I am trying to connect elasticsearch through HTTPS connection HTTPS/SSL support.
the code is as follows
// trust ALL certificates
        SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
            public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                return true;
            }
        }).build();

        // skip hostname checks
        HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;

        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
        SchemeIOSessionStrategy httpsIOSessionStrategy = new SSLIOSessionStrategy(sslContext, hostnameVerifier);

        JestClientFactory factory = new JestClientFactory();
        factory.setHttpClientConfig(new HttpClientConfig.Builder("https://localhost:9200")
                        .defaultSchemeForDiscoveredNodes("https") // required, otherwise uses http
                        .sslSocketFactory(sslSocketFactory) // this only affects sync calls
                        .httpsIOSessionStrategy(httpsIOSessionStrategy) // this only affects async calls
                        .build());

        JestClient client = factory.getObject();

        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(QueryBuilders.matchAllQuery());
         Search search = new Search.Builder(searchSourceBuilder.toString())
                .addIndex(INDEX)
                .addType(TYPE)
                .setParameter(Parameters.SIZE, 2)
                .setParameter(Parameters.SCROLL, "5m")
                .build();
             JestResult result = client.execute(search);

I am able to connect to using http connection. But when I try to connect using HTTPS connection ,I am getting following error

Pls let me know if you figure out this error. Is there any problem with the code?


text:
Q: User.Identity.Name is null when integrating ASP.NET Identity with OWIN auth to Azure AD B2C I am extending an existing MVC web application which uses ASP.NET Identity for authentication. It uses System.Web.HttpContext.Current.User.Identity.Name for getting the username of the currently logged on user.
When I switch to OWIN authentication using the sample code explained here the Name property is null, causing the existing application to throw an error. Is it possible to change the value of IIdentity.Name without invalidating the identity?

A: As described at the bottom of the referenced tutorial, you should access the user claims via the ClaimsPrincipal.Current object, such as:
// Controllers\HomeController.cs

[Authorize]
public ActionResult Claims()
{
    Claim displayName = ClaimsPrincipal.Current.FindFirst(ClaimsPrincipal.Current.Identities.First().NameClaimType);
    ViewBag.DisplayName = displayName != null ? displayName.Value : string.Empty;
    return View();
}


text:
Q: Can a Class clone property from a different class other than the parent class I have been working on a problem in MVC where I was facing code duplicity issue creating View-Models. I was wondering if there is a way to create a class whose properties can refer to properties defined in another class. I just need to write the property name or just the reference. I basically need all other stuff like Annotations should automatically come over to my new class definition.
Here is what I am looking for:
let say I have a Class A having some annotations.
Class A {

        [Required]
        [EmailAddress]
        [Display(Name = "Email ID")]
        public string EmailID { get; set; }
        [Required]

        [Required]
        [Display(Name = "Name")]
        public string FName { get; set; }
}

Now I need to write a new class B referring to some properties defined in class A.
Class B {
    public string EmailID; //should refer to class B so that I don't have to write annotations again
    public string newproperty;
}

A: You are expecting something that isn't there. There is only one way to indicate that some property of B is 'the same' as that of A, and that is inheritance.
If you make B derive from A, it inherits the property EmailID and its annotations.
Another option is to use annotations on interfaces, but those share the same problems as deriving in my opinion.
Else, you just have to copy/paste the annotation, since there isn't any obvious relationship except that they share the same name.


text:
Q: How to add a shortcut to open a new finder window to the Launchpad or dock What I want: A one-click action in the dock or launchpad that opens the downloads folder in a new finder window.
Note: the Downloads "fan" thing that is in the left side area of the dock is not what I want. When I click that it opens a weird list / grid / fan thing of the stuff in my downloads folder, and then I have to click some more to actually open a finder window. Nope. I want a one click icon in the dock or launchpad.
Additionally: the icon needs to be the Downloads folder icon, if at all possible.

A: Copy this script to a new ScriptEditor document.  Then export it as an application.
tell application "Finder"
    activate
    make new Finder window to path to downloads folder
end tell

Next, Open the "Get Info" window for the "Downloads" folder and also open the "Get Info" window for the new application you just exported. Select the icon of the downloads folder and "Edit/Copy" Select the icon of the new application and ""Edit/Paste".

Drag your new application down to your dock and you are good to go.

A: Another way to get what you're asking for, also done as an AppleScript application, but being able to customize the properties of the window.
In Script Editor, create a new document and add the following AppleScript code as an example:
set theTarget to (path to downloads folder as string)
tell application "Finder"
    set theWindow to make new Finder window to folder theTarget
    tell theWindow to set {current view, toolbar visible, bounds} to {list view, true, {0, 23, 1024, 512}}
    activate
end tell

You can modify the properties to your liking in the tell theWindow to set line of code  to whatever you'd like of the available properties.
To get the properties, you can open a Finder window to your downloads folder, arrange it how you'd like to appear every time and then use the following in a separate AppleScript document to get it's properties to use in the app that opens it:
tell application "Finder" to get properties of windows "Downloads"

The above command returns the following example output:

{class:Finder window, id:1004, name:"Downloads", position:{0, 23},
  bounds:{0, 23, 1024, 512}, index:1, zoomed:false, closeable:true,
  titled:true, floating:false, modal:false, resizable:true,
  zoomable:true, visible:true, collapsed:false, target:folder
  "Downloads" of folder "me" of folder "Users" of startup disk of
  application "Finder", current view:list view, icon view options:icon
  view options of Finder window id 1004 of application "Finder", list
  view options:list view options of Finder window id 1004 of application
  "Finder", column view options:column view options of Finder window id
  1004 of application "Finder", toolbar visible:true, statusbar
  visible:true, sidebar width:213}

Doing it this way, you get a new Finder window opened to your Downloads folder set exactly how you want it, based on available properties.
See wch1zpink's answer for assigning the Downloads folder icon to the AppleScript application's icon.


text:
Q: Change image in UIImageView based on UIPanGestureRecognizer translation value I have 8 images in the array and UIImageView that displays one image from the array at a time. I also have UIPanGestureRecognizer on UIImageView so when user moves their finger sideways on the image it changes (kind a like invisible scroller top of the image). I'm using pan gesture's translation value to change the image. This all works but not the way I want it to. The images change way too quickly, just short finger pan scrolls through the images. Is there a way to require longer pan to change the images? Or any other ways to make this "smoother" for the user?
.h
@interface FirstViewController : UIViewController
    @property (nonatomic, retain) IBOutlet UIImageView *imageView;
    - (IBAction)pan:(UIGestureRecognizer *)panGesture;

.m
@interface FirstViewController () {
    NSArray * imageArray;
    int _currentIndex;
}

@end

@implementation FirstViewController

- (IBAction)pan:(UIPanGestureRecognizer *)panGesture {
  //  NSLog(@"panned");
    CGPoint translation = [panGesture translationInView:self.view];
    [self.panLabel setText: NSStringFromCGPoint(translation)];
    NSLog(@"%@ translation", NSStringFromCGPoint(translation));

    if (translation.x<-1) {
        _currentIndex=(_currentIndex<=0)?0:_currentIndex-1;
        UIImage *img = [UIImage imageNamed:[imageArray objectAtIndex:_currentIndex]];
        [self.imageView setImage:img];
    }
    else if(translation.x>1){
        _currentIndex=(_currentIndex>=7)?7:_currentIndex+1;
        UIImage *img = [UIImage imageNamed:[imageArray objectAtIndex:_currentIndex]];
        [self.imageView setImage:img];
    }
    [panGesture setTranslation:CGPointZero inView:self.view];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    imageArray = [[NSArray alloc]
                  initWithObjects:@"image1.jpg", @"image2.jpg", @"image3.jpg", @"image4.jpg", @"image5.jpg", @"image6.jpg", @"image7.jpg", @"image8.jpg", nil];
}

A: You could modify your code to track X pan over time. This would allow you to set a variable for your pan amount. Modified code for this is below:
@interface FirstViewController () {
    NSArray * imageArray;
    int _currentIndex;

    CGFloat _currentPanXAmount;
    CGFloat _panThreshold;
}

@end

@implementation FirstViewController

- (IBAction)pan:(UIPanGestureRecognizer *)panGesture {
    CGPoint translation = [panGesture translationInView:self.view];

    _currentPanXAmount += translation.x;

    [self.panLabel setText: NSStringFromCGPoint(translation)];
    NSLog(@"%@ translation", NSStringFromCGPoint(translation));

    if (_currentPanXAmount < (-1 * _panThreshold)) {
        _currentIndex=(_currentIndex<=0)?0:_currentIndex-1;
        UIImage *img = [UIImage imageNamed:[imageArray objectAtIndex:_currentIndex]];
        [self.imageView setImage:img];
        _currentPanXAmount = 0.0;
    }
    else if(_currentPanXAmount > _panThreshold){
        _currentIndex=(_currentIndex>=7)?7:_currentIndex+1;
        UIImage *img = [UIImage imageNamed:[imageArray objectAtIndex:_currentIndex]];
        [self.imageView setImage:img];
        _currentPanXAmount = 0.0;
    }
    [panGesture setTranslation:CGPointZero inView:self.view];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    imageArray = [[NSArray alloc]
                  initWithObjects:@"image1.jpg", @"image2.jpg", @"image3.jpg", @"image4.jpg", @"image5.jpg", @"image6.jpg", @"image7.jpg", @"image8.jpg", nil];

    // Make this larger for slower transitions and smaller for faster transitions.
    _panThreshold = 10.0;
}


text:
Q: How to convert a function into string? Example function:
def my_function():if 9>8 print("Hello from a function") else print("Goodbye")

Expected Output:
String : """def my_function(): if 9>8 print("Hello from a function") else print("Goodbye")"""

Includes the reserved words (def,if,else) as well.

A: Use inspect.getsource()
As pointed out by @martineau (thx), your function had a SyntaxError. I reformatted your function and used a ternary to keep it single-line.
    import inspect

    def my_function(): print("Hello from a function") if 9>8 else print("Goodbye")

    print(inspect.getsource(my_function))

Output:

def my_function(): if 9>8 print("Hello from a function") else print("Goodbye")


text:
Q: Ошибка клонирования в GitHub При наборе:
$ git clone https://tarasula@bitbucket.org/tarasula/firstrepo.git

Выдает ошибку:

fatal: unable to access 'https://tarasula@bitbucket.org/tarasula/firstrepo.git': Could not resolve host: bitbucket.org

Подскажите кто сталкивался.
Спасибо

A: Проблема с DNS.
А интернет на этой машине есть, можете проверить?


text:
Q: Accept не работает со структурой подключенного клиента Когда клиент подключается к серверу и при этом в accept указана структура для заполнения информацией о клиенте, accept() выдает -1, хотя типы параметров учтены. Проблема пропадает когда передаю параметрами,заместь структуры, NULL,но при этом сервер не читает и не отсылает сообщения в ответ. Прошу помощи!
Вот код
'
#include <iostream>
#include <cstdlib>
#include<sys/socket.h>
#include<sys/types.h>
#include<arpa/inet.h>
#include<unistd.h>
#include<time.h>
#include<netdb.h>
#include<string.h>
using namespace std;
bool SetSocket(int &fd);
bool SetBind(int fd,sockaddr_in &sock);
bool StartListen(int fd);
bool SetAccept(int &fd,sockaddr_in &sock);
bool WhoIsClient(sockaddr_in &sock);

int main()
{
  int serv_socket;
  sockaddr_in serv;
  memset(&serv,0,sizeof(serv));
  serv.sin_addr.s_addr =htonl(INADDR_ANY);
  serv.sin_family = PF_INET;
  serv.sin_port = htons(1234);
 SetSocket(serv_socket);
 SetBind(serv_socket,serv);
 StartListen(serv_socket);
 SetAccept(serv_socket,serv);
 close(serv_socket);
 return 0;
}
bool SetSocket(int &fd)
{
 if( (fd = socket(AF_INET,SOCK_STREAM,0)) < 0 )
  {
    cerr<<"Can't open socket"<<endl;
    exit(EXIT_FAILURE);
  }
}
bool SetBind(int fd,sockaddr_in &sock)
{
 if( (bind(fd,(sockaddr*)&sock,sizeof(sock))) < 0 )
   {
    cerr<<"Can't bind the socket"<<endl;
    exit(EXIT_FAILURE);
   }
}
 bool StartListen(int fd)
{
 if ( listen(fd,10) < 0 )
   {
     cerr<<"Can't listen the port"<<endl;
     exit(EXIT_FAILURE);
   }
 }
 bool SetAccept(int &fd,sockaddr_in &sock)
{
 int client_connect;
 sockaddr_in client;
 char msg[40];
 //structures for get name of host
   if ((client_connect = accept(fd,(sockaddr*)&client,     (socklen_t*)sizeof(sockaddr)) < 0 ))
     cout<< "Can't accept the queue of clients"<<endl;
 while(true)
 {
     if ( (recv(fd,msg,39,0)) > 0 )
       {
         WhoIsClient(client);
         cout<<"Msg:"<<msg<<endl;
       }
     if (strcmp(msg,"bye") == 0)
         exit(EXIT_SUCCESS);
     memset(msg,0,40);
     //inputting the message for client
     cout<<"Input the message for client"<<endl;
    // cin.getline(msg,39);
     //end of get msg

     if ( send(client_connect,msg,40,0) < 0 )
         cerr<<"Fail!!! can't send the message"<<endl;
  }
  close(client_connect);
}
 bool WhoIsClient(sockaddr_in &sock)
{
 struct hostent *hp;
 cout<<"New connection"<<endl;
 cout<<"Time: "<<ctime(0)<<endl;
 cout<<"IP: "<<inet_ntoa(sock.sin_addr)<<endl;
 hp =gethostbyaddr((constvoid*)&sock.sin_addr,sizeof(sock.sin_addr),AF_INET);
 cout<<"Name of user: "<<hp->h_name<<endl;
}`

A: Я не знаю, как выглядит объявление функции accept, но, думаю, третий аргумент в ее вызове указан неверно
accept(fd,(sockaddr*)&client,     (socklen_t*)sizeof(sockaddr) )

Похоже, что требуется указатель на объект, содержащий размер передаваемого буфера. Поэтому по крайней мере следует написать
sockaddr_in client;
socklen_t size = sizeof(sockaddr);
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

if ((client_connect = accept(fd,(sockaddr*)&client,  &size ) < 0 ))
                                                     ^^^^^^

A: Третьим аргументом accept() д.б. адрес переменной типа socklen_t, содержащей правильное значение.
 socklen_t size = sizeof(client);
 if ((client_connect = accept(fd, (struct sockaddr *)&client,  &size )) < 0) ...

Обратите внимание на строки в man 2 accept

The addrlen argument is a value-result argument: the caller  must  initialize  it  to contain the size (in bytes) of the structure pointed to
         by addr; on return it will contain the actual size of the peer address.


text:
Q: Php regular expression to match a div

            Foo

           Bar

       Bar

I want find all object in id="a"
and out put is

    Foo

   Bar

Geat thanks.

A: SimpleHTMLDom is memory consuming solution. It may cause memory leaks.
I recommend using DOMDocument and DOMXPath.
Then you can fetch all div#a by this way:
$xpath->query('//div[@id = "a"]')

A: Seems the community has responded to this before as a bad idea.  Looks to be other, better ways.  Jquery, HTML parsers, etc.
A search on regex in SO
StackOverflow Thoughts on Regex and HTML
PHP/HTML Regex


text:
Q: How to access a MySQL database from a Lua script I am writing a Lua script using VS Code 1.73.1 on a Windows 11 PC. I would like to write some data from the script to a MySQL database that is located on another (Linux) PC that is on my local network.
I tried the following:

*

*add 'mysql = require "luasql.mysql"' to my code. This results in an error because the luasql.mysql module is not found.

*'luarocks install luasql-mysql' with the luasql-mysql-2.6.0-1.rockspec file downloaded from Https://github.com/lunarmodules/luasql. This fails because the Lua 5.4 interpreter is not found, and apparently I also have to install Git.

*Installed Git but now it cannot find mysql.h. According to Google I have to install a local version of MySql. I tried that but no mysql.h file

What can I do to get the luasql-mysql module working? (Preferrably without installing programs/utilities that I am probably never going to use again)
Thanks in advance


text:
Q: Base64 string decode and save as file This has been doing my head in and I hope someone can help. Please forgive me if it's a stupid question as I am very new to Go.
I have a struct that has base64 in it. the struct looks like this:
 type UploadedFile struct {
    PartnerId string
    FileName string
    UploadDateTime string
    FileChecksum string
    FileBase64 string
 }

I want to take that base64 string, decode it and then save it, sounds simple right and it probably is, but I am struck.
The code looks like this:
decoder := json.NewDecoder(r.Body)
uploadedFile := models.UploadedFile{}
err := decoder.Decode(&uploadedFile)
dec, _ := base64.StdEncoding.DecodeString(uploadedFile.FileBase64)

Where do I go from here? I have tried so many things and I just keep getting errors all over the file.
I have tried adapting code that people use for images, but I always crash and burn as the file isn't an image, it could be anything
Thanks in advance.

A: Update: I forgot to mention that, if you use f.Write make sure to also call f.Sync after you're done writing to ensure that all the contents you've written are actually stored. The example shows the updated code.
Not sure if your code example is incomplete, so this answer might be irrelevant but to save your decoded string bytes to a file you first need to open or create a file and then write the bytes into it. Something like this:
package main

import (
    "encoding/base64"
    "io"
    "os"
)

var b64 = `TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlz
IHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2Yg
dGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGlu
dWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRo
ZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4=`

func main() {
    dec, err := base64.StdEncoding.DecodeString(b64)
    if err != nil {
        panic(err)
    }

    f, err := os.Create("myfilename")
    if err != nil {
        panic(err)
    }
    defer f.Close()

    if _, err := f.Write(dec); err != nil {
        panic(err)
    }
    if err := f.Sync(); err != nil {
        panic(err)
    }
}

Run it here: https://play.golang.org/p/SZVquhZdXC


text:
Q: "Cannot resolve method" @AuthInterceptorOkHttpClient I am trying to integrate dagger-hilt on my project on android. I have implemented the libraries and steps in the link below.
However, I cannot access the @AuthInterceptorOkHttpClient annotation. I get the error "Cannot resolve method". For this I need to add another library. Can experienced friends help?
https://developer.android.com/training/dependency-injection/hilt-android?hl=ja_jp

A: AuthInterceptorOkHttpClient is custome interface.
@Qualifier
@Retention(AnnotationRetention.BINARY)
annotation class AuthInterceptorOkHttpClient

They give an example in cases where you need Hilt to provide different implementations of the same type as dependencies.


text:
Q: Django admin inline: Clone entry I`m using a GenericStackedInline in my django admin. I would like to have the option to duplicate the inline object when editing the parent object.
I can think of two ways of doing this:

*

*Using django-inline-actions to add a "clone" button. This did not work, because it does not show when using a fieldset in the GenericStackedInline

*Adding another checkbox next to "delete" checkbox with label "clone". When activating the checkbox and saving parent object, it should clone the inline object with new id. Is there an easy way to add another checkbox and add a action to handle cloning?

A: Ok, found a solution. I don`t really like it. Biggest flaw in my oppinion is, that I did not find a way to do clone in InlineClass, Mixin or formset. It's a bit clumsy that two classes / Mixins need to be combined to handle it.
Improvements or other solutions are very welcome.
Inline classes
class RgCloneInlineFormset(BaseGenericInlineFormSet):
    def add_fields(self, form, index):
        super().add_fields(form, index)
        form.fields["CLONE"] = forms.BooleanField(required=False)

class RgGenericStackedInlineWithClone(GenericStackedInline):
    template = "admin/edit_inline/stacked_with_clone.html"
    formset = RgCloneInlineFormset

class DetailpageElementInline(RgGenericStackedInlineWithClone, RgImagePreviewMixin):
    model = DetailpageElement
    extra = 0

Admin class
class CloneDetailpageElementInlineMixin():

    def save_formset(self, request, form, formset, change):
        # Save formset
        ret = super().save_formset(request, form, formset, change)

        # Do clone if nessesary
        detailpage_ids_to_clone = []

        for data in formset.cleaned_data:
            if isinstance(data.get("id"), DetailpageElement):
                if data.get("CLONE"):
                    detailpage_ids_to_clone.append(data.get("id").id)

        for detailpage_element in DetailpageElement.objects.filter(id__in=detailpage_ids_to_clone):
            detailpage_element.id = None
            detailpage_element.save()

        # Make sure function works like super function
        return ret

@admin.register(ArticleInt)
class ArticleIntAdmin(CloneDetailpageElementInlineMixin, ContentAdminBase):
    inlines = [
        inlines.DetailpageElementInline,
    ]

Template admin/edit_inline/stacked_with_clone.html
Just copied the stacked.html from django source code and added
{% if inline_admin_formset.has_add_permission and inline_admin_form.original %}{{ inline_admin_form.form.CLONE }} Clone{% endif %}


text:
Q: Recommend a Git GUI client for Ubuntu 11.10 the last thread made on this subject was 2009 so i'm hoping people can tell me what they are currently using.
I'm new to Linux and don't know much about the terminal and such yet, but I am able to use git via command line if needed.  Primarily I run windows 7 and have been using Git Extensions / Gitbash.
If anyone has any recommendations on something similar that is easy to install or at least has good instructions for Ubuntu please paste a link or write up a quick description.
Thanks!

A: I highly recommend gitg . It shows a clear revision tree and is much fancier than gitk.
$sudo apt-get install gitg
$cd path/to/gitrepo
$gitg

A: I don't use GUI for most Git operations but when I wanna see git tree or preview file edits then I use Giggle. Once I've tried to set up Meld as mergetool and difftool but then when want to see only git diff any_file with only a few diffs inside it was running whole Meld, that was annoying so I've forgotten about it and use only standard diff with vimdiff.

A: You could try qgit.
Most important features: browse revisions history, view patch content and changed files, graphically follow different development branches.
Download-Site: http://sourceforge.net/projects/qgit/
Website: http://digilander.libero.it/mcostalba/
or sudo apt-get install qgit

A: You can use Aptana it's a IDE but have a git GUI
http://aptana.com/

A: If you are used to GIT Extensions, you can try to run it on Ubuntu: http://jeremykentc.blogspot.co.il/2012/09/git-extensions-240-on-ubuntu-1204.html


text:
Q: Cross-sectional study design with no control group compares 2 treatment arms There is a trend among medical research that assesses cross sectional (singular point in time) treatment comparisons between 2 treated groups in retrospective data. In other words the  a person who took drug A and drug B, but no placebo group is included.
What is the literature like on these sort of designs and the obvious drawbacks on lacking a control group? I've seen methods like synthetic controls and front-door estimators that can provide useful estimation of certain treatment effects, under strong assumptions, but all of these methods are on data with multiple time points. Is there any method that works under a singular time point?


text:
Q: Interval Scheduling Algorithm or Activity Selection Algorithm I'm struggling with this question for so long.
There are n persons who want same room in a hotel. Each person wants to stay in the hotel for his own convenient time but only one person can stay at a time. Assume that room is available from 5AM to 11PM. Hotel manager takes 500 rupees from each person who is staying in that room. It does not matter how long a person stays in that room. We have to maximize the profit of the manager. Let us say that n =4 i.e. four persons want same room. Let us say that 1st person wants the room from 6AM to 8AM and 2nd person wants room from 7AM to 8AM, 3rd person wants room from 8AM to 12PM and 4th person wants room from 11AM to 1PM.

By observing above figure, we can easily see that manager can only allow maximum of two persons to stay (1st and 3rd or 1st and 4th or 2nd and 3rd or 2nd and 4th). So maximum profit he can get is 500+500 = 1000 rupees. So we have to implement an algorithm which can find maximum profit value. Assume that the persons want the room only b/w 5AM to 11PM and each person wants room in multiple of hours.
Input description:
{<1st person starting time>#<1st person ending time>,<2nd person starting time>#<2nd person ending time>,…………, # }
Output description:
Output should be maximum profit value.
For the example considered in the question, output is 2000.
Example:
Input: {6AM#8AM,11AM#1PM,7AM#3PM,7AM#10AM,10AM#12PM,2PM#4PM,1PM#4PM,8AM#9AM}
Output:
2000

A: This is Interval Scheduling Problem.
It can be solved by sorting the intervals by end time, and choosing greedily the earliest deadline first, remove all overlapping intervals and repeat.

A: Looks like a variant of the Activity Selection Problem.
Read this TopCoder Tutorial for an excellent explanation.

A: Below is the exact solution for your question:
<?php

// Timezone set
date_default_timezone_set("Asia/Kolkata");

// User - i/p
$input = "{6AM#8AM,11AM#1PM,7AM#3PM,7AM#10AM,10AM#12PM,2PM#4PM,1PM#4PM,8AM#9AM}";

// Processing i/p string to ARRAY

$input_array = [];  // Array given as i/p to "calculateprofit"-function
$processed_array = (explode(',', substr($input, 1, -1)));

foreach ($processed_array as $key => $value)
    $input_array[] = explode("#", $value);

// Function call and display o/p
$maximim_profit = calculateprofit($input_array);
echo "Input = ".$input;
echo "

Maximum Profit = ".$maximim_profit;

// Function to calculate - Maximum Profit
function calculateprofit($input){
    $room_charges = 500;
    $members_covered = [$input[0]];
    $last_member = 0;

    $finishing_time = array();

    foreach ($input as $key => $row)
        $finishing_time[$key] = date("H:i", strtotime($row[1]));

    array_multisort($finishing_time, SORT_ASC, $input);

    for($i=1; $i<sizeof($input); $i++){
        $current_coustmer = $input[$i];

        if(date("H:i", strtotime($current_coustmer[0])) >= date("H:i", strtotime($input[$last_member][1])) ){
            $members_covered[] = $input[$i];
            $last_member = $i;
        }

    }

    //  print_r($members_covered);

    return sizeof($members_covered)*$room_charges;
}

?>


text:
Q: Is there any tool replacement for SONAR for .net code quality and generate report from it? I have a Visual studio solution, which is designed using c# 4.0 .
I want to check the code quality for my solution and generate report out of it.
I tried the FxCop and i also got the report but i need the report something like this(from the image).
The rules compliance is 85% but in FxCop it only showed me the critical, error, etc.
I was not able to even deploy my project into SONAR because I had some timeout issue
coming for one of my project in the solution.
please someone help me.

Thanks in advance.
Regards,
Roopini

A: I don't know if there's an equivalent of SonarQube for .NET projects, but if you really want such reporting (which I can understand, obviously!), you should rather ask questions on how to resolve your installation issue for SonarQube instead of searching for something else. There are plenty of organizations where big .NET solutions are successfully analyzed with SonarQube and the C# plugins, so there's no reason why it can't work for you!
You can find useful material on the net to help you on this. For instance, a blog post written by John M Wright about "setting up SonarQube for C# projects". John periodically updates his post, so the information should still be very relevant.

A: Have you tried the tool NDepend? It generates interactive reports about .NET code quality and code rules compliance. Here are some sample reports.
NDepend is also a tool integrated in Visual Studio (2017, 2015, 2013, 2012, 2010) that proposes a range of interactive features (graph, dependency matrix, code metrics visualization, code diff...). Another point about NDepend is that code rules are actually C# LINQ queries, so it is pretty easy to customize a default code rule or create your own code rules.
NDepend also integrates in VS Team Services and you'll get all code quality data from your VSTS UI instead of being redirected to a server.
I read that you have time-out problems analyzing your code base, maybe it is because your code base is pretty large. NDepend is optimized and it can analyze a very large code base and create a report in a few dozens of seconds (it takes around a minute to analyze the whole .NET Fx).
A 14 days full featured trial is available.
Disclaimer: I work in the NDepend team

A: If you haven't already, I would suggest taking a look at my blog post on setting up SonarQube for C# projects: http://www.wrightfully.com/setting-up-sonar-analysis-for-c-projects/
The key to fixing your issue will be determining what the system is doing when the timeout occurs.  Take a look at your log files and see what the last lines were before it timed out.  It could be that your code is complex and just needs more time, in which case you can adjust the timeout values for whichever tool is running at the time.
Otherwise, I would suggest running whichever analysis tool (fxcop, gendarme, sytlecop, etc) was running when the timeout occurred outside of SonarQube.  That is, run the tool directly from the commandline to see if it still times out or provides any additional information on the console.
Also, assuming you're using the sonar-runner tool to execute the SonarQube analysis, you can add the -X argument to the commandline, which will run it with debug-level logging enabled. This will create a LOT more log messages which may shed some additional light on the issue.


text:
Q: Understanding Postfix-expression Evaluation in Java code using a stack I was given a snippet of code to decipher, explain and offer any recommendations for improvement. I was told it works and we can't run the code to test it. I pretty much understand it but just need to run it by someone to make sure what I do understand about it is correct and please get any help with explaining what I don't understand.I have been doing a ton of research and still have some questions.
The code is implementing used to read a postfix expression that only uses multiplication and addition. Then evaluate the expression while saving the results onto a stack. Then it prints out the results. Operands are pushed onto the stack and then when it reads an operator, it pops the top 2 operands from the stack performs the calculation and stores the result back into the stack.
The program assumes that the integers and operators are delimited by some kind of character like a blank space or something, but doesn't check the legality of the input at all.
 public static void main(String[] args)
{
    char[] a = args[0].toCharArray();
    int N =a.length;
    intStack s = new intStack();
    for (int i = 0; i<N; i++)
    {
        if (a[i]=='+')
        {
            s.push(s.pop() + s.pop());
        }
        if (a[i]=='*')
        {
            s.push(s.pop() * s.pop());
        }
        if ((a[i] >= '0') && (a[i] <= '9'))
        {
            s.push(0);
        }
        while ((a[i] >= '0') && (a[i] <= '9'))
        {
            s.push(10*s.pop() + (a[i++]-'0'));
        }
        Out.println(s.pop() + "");
    }
}

Post fix expression example: 2 3 5 + * = 16
I am confused when it comes to last if statement and the while loop.
So the first time it pushes a 0-9 number character it will store a # 0, then pop out that 0, multiple it by 10 and add it to the next number character (if there is one) that is converted into an int and push the result back into the stack?
If so, why is a 0 pushed onto the stack?
Shouldn't it convert the first 0-9 numbered character to an int datatype, push it onto the stack and then go to the while loop?
then in the While loop, read the the array and keep converting 0-9 numbered characters to int datatypes and pushing them on the stack until a character is read that is different?
I also don't see where it is incrementing int i in the while loop or breaking out of the while loop to advance to the next character?

A: The initial push of zero is a little confusing. The key to understanding what's going on there is to observe that i is not incremented. When the code sees, say, '4', which is a first digit in "42", the if statement pushes zero; then the loop immediately pops it, multiplies by ten, adds 4, and pushes back. i is advanced to the next character (i.e. 2), and then the loop pops 4, multiplies by ten, adds 2, and stores back 42 - the desired result.
There is an error in the code: when the expression ends in a number, you get an index out of bounds exception. For example, 42 is a valid postfix expression (having no operators is OK, right?) the inner loop would advance past the end of the string, causing an exception.


text:
Q: ajax filtering and infinite scroll (php & isotope) I am using the isotope plugin (http://isotope.metafizzy.co/) with the infinite ajax scroll plugin (https://github.com/webcreate/infinite-ajax-scroll).  The infinite scroll works great with the isotope filtering, however, I want to load more items into the container when a filter has been applied so that there are always 50 items being displayed.
I have the below code but am stuck at the point of loading the new items with ajax.
So every time a filter is selected, I calculate how many items are currently displayed out of 50.  I then need a way to get more items using ajax and calling the same page (index.php). I imagine I need to do something similar to the infinite ajax scroll plugin in order to get the next pages results.  I am not that experienced with JQuery and so am struggling to figure out exactly what their code is doing and how to implement something similar to this for my filtering.
I have tried using $.get but this loads the whole of the index.php page within the container instead of just getting the results.
I would be grateful for any help with this.
<?php

require_once('config/config.php');

$cat = (isset($_GET['cat']) ? urldecode($_GET['cat']) : '');
$type = (isset($_GET['type']) ? urldecode($_GET['type']) : '');

//get filter lists
$categories = StoreDiscounts::getCategories();
$types = StoreDiscounts::getDiscountTypes();

//get total number of discounts for search
$total_items = StoreDiscounts::countitems($cat, $type);
//pagination  - infinate scrolling
$pagelimit = 50; //items per page
$page = (int) (!isset($_GET['p'])) ? 1 : $_GET['p'];
$start = ($page * $pagelimit) - $pagelimit;
$limit = $pagelimit * $page;

if ($total_discounts > ($page * $limit)) {
    $next = ++$page;
}

//get items
$items = StoreDiscounts::getitems($cat, $type, $start, $limit);

?>
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <link rel="stylesheet" href="public/css/normalize.css">

    <link rel="stylesheet" href="public/css/style.css">

    <title>E-Store Offers.</title>

            Filters

Filters

[ Clear filters ]

Categories

                    <?
                    echo '
All
';
                    foreach ($categories as $category) {
                        $category_class = functions::sanitize($category);
                        echo '
' . $category . '
';
                    }
                    ?>

Type

                <?
                echo '
All
';
                foreach ($types as $type) {
                    $type_class = str_replace(' off', '', strtolower($discount_type));
                    echo '
' . $discount_type . '
';
                }
                ?>

            Return to Content

                <?php

                foreach ($items as $id => $item) {

                        echo "
";

$item[name]

$item[cat]

                        ";
                        echo "
$item[description]
";
                        echo "
\n";
                    }
                ?>

                <?php if (isset($next)): ?>

                  <?php
                  echo "Next";
                  ?>

                <?php endif?>

    FOOTER

Many thanks, Leah

A:         function loadMoreItems(getQuery) {
            $.get(getQuery, null, function(data) {
                container = $('#container', data).eq(0);
                if (container) {
                    var newItemsHTML = "";
                    newItemsHTML = $( container ).html();
                    var $newItems = $(newItemsHTML);
                    $('#container').isotope('insert', $newItems, true);
                }
            }, 'html');
        }


text:
Q: Android app keeps crashing on button click I have looked at other Qs and answers but cannot find anything wrong with my code?
I must be doing something wrong, so if anyone can help me out, it would be much appreciated.
I have checked the 1st and 2nd pages and the manifest.
package com.example.fmf;

import com.example.fmf.Search;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Spinner;
import android.view.View.OnClickListener;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button button = (Button) findViewById(R.id.go_button);

        button.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                   goMenu();
            }

        });
    }

    public void goMenu()
    {
      Intent myIntent = new Intent(this, Search.class);
      startActivity(myIntent);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

Page 2
package com.example.fmf;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.Spinner;
import android.support.v4.app.NavUtils;
import android.annotation.TargetApi;
import android.content.Intent;
import android.os.Build;

public class Search extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_search);
    // Show the Up button in the action bar.
    setupActionBar();
    }

    /**
     * Set up the {@link android.app.ActionBar}, if the API is available.
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    private void setupActionBar() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        getActionBar().setDisplayHomeAsUpEnabled(true);
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.search, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case android.R.id.home:
        // This ID represents the Home or Up button. In the case of this
        // activity, the Up button is shown. Use NavUtils to allow users
        // to navigate up one level in the application structure. For
        // more details, see the Navigation pattern on Android Design:
        //
        // http://developer.android.com/design/patterns/navigation.html#up-       vs-back
        //
        NavUtils.navigateUpFromSameTask(this);
        return true;
    }
    return super.onOptionsItemSelected(item);
}

Bundle extras = getIntent().getExtras();
 public final String ID_CITY = extras.getString("CITY_TH");

//retrieve list view value selected and store in variable restaurant
//Not sure how to do this...

}

Manifest

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".Search"
        android:label="@string/app_name"
        android:parentActivityName=".MainActivity" >
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value=".MainActivity" />
    </activity>
    <activity
        android:name=".Info"
        android:label="@string/app_name"
        android:parentActivityName=".Search" >
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value=".Search" />
        </activity>
    </application>

</manifest>

Sorry for the delay the log cat (Not sure how to post all of it)
11-27 15:40:05.118: D/AndroidRuntime(771): >>>>>> AndroidRuntime START com.android.internal.os.RuntimeInit <<<<<<
11-27 15:40:05.128: D/AndroidRuntime(771): CheckJNI is ON
11-27 15:40:05.158: D/dalvikvm(771): Trying to load lib libjavacore.so 0x0
11-27 15:40:05.168: D/dalvikvm(771): Added shared lib libjavacore.so 0x0
11-27 15:40:05.198: D/dalvikvm(771): Trying to load lib libnativehelper.so 0x0
11-27 15:40:05.198: D/dalvikvm(771): Added shared lib libnativehelper.so 0x0
11-27 15:40:05.278: E/cutils-trace(771): Error opening trace file: No such file or directory (2)
11-27 15:40:05.868: D/AlertService(549): Beginning updateAlertNotification
11-27 15:40:05.898: D/AndroidRuntime(771): Calling main entry com.android.commands.am.Am
11-27 15:40:05.918: D/dalvikvm(771): Note: class Landroid/app/ActivityManagerNative; has 163 unimplemented (abstract) methods
11-27 15:40:05.948: I/ActivityManager(286): Force stopping package com.example.fmf appid=10048 user=-1
11-27 15:40:05.959: I/ActivityManager(286): START u0 {act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10000000 cmp=com.example.fmf/.MainActivity} from pid 771
11-27 15:40:06.328: I/WindowManager(286): Screenshot max retries 4 of Token{419849f0 ActivityRecord{41984880 u0 com.android.launcher/com.android.launcher2.Launcher}} appWin=Window{419646b0 u0 com.android.launcher/com.android.launcher2.Launcher} drawState=4
11-27 15:40:06.328: W/WindowManager(286): Screenshot failure taking screenshot for (480x800) to layer 21000
11-27 15:40:06.338: D/AndroidRuntime(771): Shutting down VM
11-27 15:40:06.348: D/dalvikvm(771): GC_CONCURRENT freed 92K, 16% free 513K/608K, paused 1ms+0ms, total 11ms
11-27 15:40:06.358: D/AlertService(549): No fired or scheduled alerts
11-27 15:40:06.388: W/dalvikvm(783): PR_CAPBSET_DROP 0 failed: Invalid argument. Please make sure your kernel is compiled with file capabilities support enabled.
11-27 15:40:06.388: W/dalvikvm(783): PR_CAPBSET_DROP 1 failed: Invalid argument. Please make sure your kernel is compiled with file capabilities support enabled.

A: Without a stacktrace it can be hard to tell. From what I can see you have two possible culprites.
First
Bundle extras = getIntent().getExtras();
public final String ID_CITY = extras.getString("CITY_TH");

In your Search class you are trying to get data from bundle. But in your MainActivity.goMenu()  you are not passing in a bundle. This can cause a NULLPOINTEREXCEPTION
Second
setupActionBar();

Please try commenting that out in your Search.class and see what the results are. I can't see what your theme is from the manifest. So you may not even have an Action bar which can cause a crash. So if commenting out the line above works, add the following to your manifest:
Change:
android:theme="@style/AppTheme"

To:
android:theme="@android:style/Theme.Holo"

and see if that works.

A: The problem should be this:
button.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View arg0) {
               goMenu();
        }

    });
}

public void goMenu()
{
  Intent myIntent = new Intent(this, Search.class);
  startActivity(myIntent);
}

Just try to replace this:
button.setOnClickListener(new View.OnClickListener() {
       @Override
        public void onClick(View view) {
            Intent myIntent = new Intent(MainActivity.this,Search.class);
            MainActivity.this.startActivity(myIntent);

        }
    });

Hope it helps you.


text:
Q: Given an array with odd length, look at the first, last, and middle values in the array and return an array with those three values So for any given odd length array, I need to look at the first, middle and last value, and return an array with only hose 3 values but in ascending order.This is what I have, but it's only working with arrays of 3 elements, it's not working for other odd length arrays:
public int[] maxTriple(int[] nums) {

  int toSwap, indexOfSmallest = 0;
    int i, j, smallest;

    for( i = 0; i < nums.length; i ++ )
    {

        smallest = Integer.MAX_VALUE;

        for( j = i; j < nums.length; j ++ )
        {
            if( nums[ j ] < smallest )
            {
                smallest = nums[ j ];
                indexOfSmallest = j;
            }
        }

        toSwap = nums[ i ];
        nums[ i ] = smallest;
        nums[ indexOfSmallest ] = toSwap;
    }

    return nums;
}

A: You're getting the sorted array, so if you need just the first, middle and last values you can try it like this:
public int[] maxTriple(int[] nums) {

      int toSwap, indexOfSmallest = 0;
        int i, j, smallest;

        for( i = 0; i < nums.length; i ++ )
        {

            smallest = Integer.MAX_VALUE;

            for( j = i; j < nums.length; j ++ )
            {
                if( nums[ j ] < smallest )
                {
                    smallest = nums[ j ];
                    indexOfSmallest = j;
                }
            }

            toSwap = nums[ i ];
            nums[ i ] = smallest;
            nums[ indexOfSmallest ] = toSwap;
        }

        nums=new int[]{nums[0],nums[(nums.length/2)],nums[nums.length-1]};
        return nums;
    }

A: You're thinking about this too hard.  If the length of your array is less than 3 or even, return null.
Otherwise, get the first element, the last element, and the middle element and store them in a new array.  Sort the array with Arrays.sort() and return the new array.
public static void main(String[] args) throws Exception {
    System.out.println(Arrays.toString(maxTriple(new int[] {1, 4, 2, 4})));
    System.out.println(Arrays.toString(maxTriple(new int[] {1, 4, 2, 4, 5})));
    System.out.println(Arrays.toString(maxTriple(new int[] {75, 99, 4, 999, 4, 65, 23})));
}

public static int[] maxTriple(int[] nums) {
    if (nums.length < 3 || nums.length % 2 == 0) {
        return null;
    }

    int[] result = new int[3];
    result[0] = nums[0]; // First
    result[1] = nums[nums.length - 1]; // Last
    result[2] = nums[nums.length / 2]; // Middle
    Arrays.sort(result);

    return result;
}

Results:
null
[1, 2, 5]
[23, 75, 999]

A: I used another approach with ternary operators. I hope it can be useful...
public int maxTriple(int[] nums) {
    return (nums[0] > nums[nums.length/2]) ? (nums[0] > nums[nums.length-1] ?
            nums[0] : nums[nums.length-1]) : (nums[nums.length/2] > nums[nums.length-1]
                    ? nums[nums.length/2] : nums[nums.length-1]);
}

A: This code works fine:
public int[] maxTriple(int[] nums) {
    int[] myArray = new int[3];
    int length = nums.length;
    int middle = nums[(length + 1) / 2 - 1];
    int last = nums[length - 1];
    int first = nums[0];

    myArray[0] = nums[0];
    myArray[1] = nums[middle];
    myArray[2] = nums[last];
    return myArray;
}

A: What you are tyring to do is called selection sort. Here is the code for that:
int[] maxTriple(int[] nums, int size) {
    for (int i = 0; i < size - 1; i++) {
        for (int j = i; j < size; j++) {
            if (nums[j] < nums[i]) {

                int toSwap = nums[i];
                nums[i] = nums[j];
                nums[j] = toSwap;
            }
        }
    }
    return nums;
}


text:
Q: What is a condensate/ the act of condensating? We talked about the Bose-Einstein-Condensate (BEC) in our thermodynamics lecture and are discussing superconductivity in the condensed matter lecture where we also talked about a condensate wavefunction in order to describe charges in superconducters.
I also read in the same context about Cooper-Pairs condensating into the same state.
My only knowledge of condensation so far is that it is the transition from gas to liquid. As far as I understand, in the context of quantum mechanics, it has to do with multiple particles occupying the same state (BEC, Cooper-Pairs).
I never really thought about the meaning of "condensation", but am really curious to find out what it means.
Any explanation is appreciated.

A: Condensation is the phenomena in which a macroscopic number of bosons occupy the same microscopic quantum state. Usually, the number of bosons occupying a state with energy $E$ in a system held at a fixed temperature $T$ is given by the Bose-Einstein function
$$n(E) = \frac{1}{e^{E/T}-1}$$
However, another restriction is of course that all bosons in the system are at some state, therefore $\sum_E n(E) = N$ where $N$ is the total number of bosons. In the thermodynamic limit of large systems and continuous energy, the sum is replaced by an integral. This restriction introduces an energy shift to the system, if the number of bosons is conserved - the chemical potential $\mu(N,T)$, and the energies are calculated with respect to it.
As the temperature is lowered, more and more bosons shift to the low-energy states, but the general form of the Bose-Einstein function is respected. If the temperature, is lowered below a certain level, however, it might be that there are "too many" bosons to occupy the states, and so a large number of them condense into the state with the lowest energy.
In BCS superconductivity, the electrons (which are fermions) form Cooper pairs, and as each pair consist of two fermions, the pair itself is a boson. These pairs are then described by the Bose-Einstein statistic, and at low temperatures, depending on the geometry of the system, may condense such that almost all of them occupy the same quantum state.


text:
Q: How to show this inequality using the binomial theorem? I need a hint in proving this inequality for $ n \in \mathbb{Z}^+ $.
I am trying to show that
$$ \displaystyle \left(1 + \frac{1}{n}\right)^{n} < e $$ for any positive integer $n$ using the binomial theorem, and my definition of $e$ is $ e = \displaystyle \sum^{\infty}_{r=0} \frac{1}{r!} $.
So I have
$ \displaystyle {n \choose 0} + {n \choose 1}{\frac{1}{n}} + {n \choose 2}{\frac{1}{n^2}} + {n \choose 3}{\frac{1}{n^3}} .... {n \choose n}{\frac{1}{n^n}} < e$
$ \displaystyle 1 + 1 + \frac{(n-1)}{2n} + \frac{(n-1)(n-2)}{6n^2} + ...+\frac{1}{n^n} < 1 + \frac{1}{1!} + \frac{1}{2!} + \frac{1}{3!} + .... \frac{1}{r!}...$
$ \displaystyle  \frac{(n-1)}{2n} + \frac{(n-1)(n-2)}{6n^2} + ...  +\frac{1}{n^n} <  \frac{1}{2} + \frac{1}{6} + .... \frac{1}{r!}...$
I'm not sure where to go from here.


text:
Q: Change the style of an ListBox in WinRT I want to change the style of an ListBox, because in WinRT the ListBox have a light background after selecting an item. But I want that the ListBox is still with an transparent background after selecting an item. How can I do this? I don't want to change an ListBoxItem, because there everything is working fine.

A: Right click the ListBox, select Edit Template -> Edit a Copy.
Navigate to the Border inside <ControlTemplate TargetType="ListBox">.  Select the Background Property, click the Advanced Options square, select Reset.  You can now set the background to whatever you want.