text:
Q: Vectorized IF statement in R? x <- seq(0.1,10,0.1)
y <- if (x < 5) 1 else 2

This gives a warning (or error since R version 4.2.0) that the condition has length > 1.
I would want the if to operate on every single case instead of operating on the whole vector.
What do I have to change?

A: x <- seq(0.1,10,0.1)

> x
  [1]  0.1  0.2  0.3  0.4  0.5  0.6  0.7  0.8  0.9  1.0  1.1  1.2  1.3  1.4  1.5
 [16]  1.6  1.7  1.8  1.9  2.0  2.1  2.2  2.3  2.4  2.5  2.6  2.7  2.8  2.9  3.0
 [31]  3.1  3.2  3.3  3.4  3.5  3.6  3.7  3.8  3.9  4.0  4.1  4.2  4.3  4.4  4.5
 [46]  4.6  4.7  4.8  4.9  5.0  5.1  5.2  5.3  5.4  5.5  5.6  5.7  5.8  5.9  6.0
 [61]  6.1  6.2  6.3  6.4  6.5  6.6  6.7  6.8  6.9  7.0  7.1  7.2  7.3  7.4  7.5
 [76]  7.6  7.7  7.8  7.9  8.0  8.1  8.2  8.3  8.4  8.5  8.6  8.7  8.8  8.9  9.0
 [91]  9.1  9.2  9.3  9.4  9.5  9.6  9.7  9.8  9.9 10.0

> ifelse(x < 5, 1, 2)
  [1] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
 [38] 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
 [75] 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2

A: You could also just create a logical vector and 1 to it
x <- seq(0.1, 10, 0.1) # Your data set
(x >= 5) + 1
#  [1] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
# [92] 2 2 2 2 2 2 2 2 2

If would like to compare performance, it would be the fastest solution
set.seed(100)
x <- runif(1e6, 1, 10)

RL <- function(x) y <- ifelse(x < 5,1,2)
JM <- function(x) {y <- rep(2, length(x)); y[x < 5] <- 1}
DA <- function(x) y <- (x >= 5) + 1

library(microbenchmark)
microbenchmark(RL(x),
               JM(x),
               DA(x))

# Unit: milliseconds
#  expr       min        lq      mean    median        uq       max neval
# RL(x) 331.83448 366.52940 378.89182 374.99741 381.08659 609.21218   100
# JM(x)  38.72894  42.18745  44.36493  43.25086  44.09626  82.76168   100
# DA(x)  10.01644  11.96482  14.21593  13.17825  14.12930  53.76923   100

A: For completeness: In big vectors, you can use the indices to speed things up (we do that often in simulations, where functions typically run 1000 to 10000 times). But as long as it isn't necessary, just use ifelse. This reads a lot easier.
> set.seed(100)
> x <- runif(1000,1,10)

> system.time(replicate(10000,{
+     y <- ifelse(x < 5,1,2)
+ }))
   user  system elapsed
   2.56    0.08    2.64

> system.time(replicate(10000,{
+   y <- rep(2,length(x))
+   y[x < 5]<- 1
+ }))
   user  system elapsed
   0.48    0.00    0.48

A: y <- if (x < 5) 1 else 2 does not operate on the whole vector (the warning you receive tells you only the first element of the condition will be used).  You want ifelse:
y <- ifelse(x < 5, 1, 2)

ifelse operates on the whole logical vector, element-by-element.  if only accepts one logical value.  See ?"if" and ?ifelse

A: Following the above post you can even use and modify the elements of a vector satisfying the criteria. In my opinion if it's not more costly to compute faster one should always do it.
x = seq(0.1,10,0.1)
y <- rep(2,length(x))
y[x<5] <- x[x<5]*2

The code of the previous post is best to answer the question. But if I had to use the code above I would do:
x = seq(0.1,10,0.1)
y <- rep(2,length(x))
y[x<5] <- x[x<5]*0 +1

A: nzMean <- function(x) { mean(x[x!=-1],na.rm=TRUE)}

nzMin <- function(x) {min(x[x!=-1],na.rm=TRUE)}

nzMax <- function(x) { max(x[x!=-1],na.rm=TRUE)}

nzRange<-function(x) {nzMax(x)-nzMin(x)}

nzSD <- function(x) { SD(x[x!=-1],na.rm=TRUE)}

#following function works
nzN1<- function(x) {ifelse(x!=-1,(x-nzMin(x))/nzRange(x) ,x) }

#following is bad as it returns only 4 not 5 elements of vector
nzN2<- function(x) {ifelse(x!=-1,(x[x!=-1]-nzMin(x))/nzRange(x) ,x) }

#following is bad as it returns 5 elements of vector but not correct answer
nzN3<- function(x) {ifelse(x!=-1,(x[x!=-1]-nzMin(x))/nzRange(x) ,-1) }

y<-c(1,-1,-20,2,4)
a<-nzMean(y)
b<-nzMin(y)
c<-nzMax(y)
d<-nzRange(y)
# test the working function
z<-nzN1(y)

print(z)


text:
Q: Sub-additivity of a measure [sufficency of an argument] I don't know why the author of the book uses induction in order to show sub-aditivity of a measure $P$. Isn't it enough to observe that $ P(\bigcup E_n)=  P(\bigcup (E_n-(E_1 \cup \cdots \cup E_{n-1}))) = \sum P(E_n-(E_1 \cup \cdots \cup E_{n-1})) \le \sum P(E_n)$ because $A \subset B$ implies $P(A) \le P(B)$?

A: Just so that this does not appear as open, yes, this is sufficient.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can the systemd "start/stop job is running" timeout value be changed without rebuilding systemd? I read https://unix.stackexchange.com/a/328354 and it convinced me that systemd indeed has to be rebuilt for this value to be changed.
Is this the case or does anyone have another solution for this? (Other than programming such feature and patching systemd with that.)

A: Unless you are using an rc script like the asker in the question you linked, you can set DefaultTimeoutStopSec=10s in /etc/systemd/system.conf. You can change 10s to whatever timeout you want, of course.
If you write your services as systemd unit files, there is no need to recompile.


text:
Q: Converting between vectors I have two classes: A and B, and an implicit conversion from As to Bs. I also have a vector<A>, and I want to convert it to vector<B>. Is it possible to add a conversion that would allow me to implicitly or explicitly convert vector<A> to vector<B>?
I know I can use the technique described here, but is there some way to enable an implicit conversion between the two? Or an explicit conversion?

A: Generally you shouldn't do that, because vector<A> and vector<B> have different implementation (especially if vector is a template specialization like vector<bool>).
If you do not like copying vector, take a look from other perspective: you need that vector<A> will behave vector<B>: you need to convert interfaces not implementation.  Implementing adapter for vector<A> with overloaded operator* and operator-> which would act like B is what you need.

A: Indirectly, there is. It might not be what you are looking for,
but you could have your functions be templates that accept
iterator pairs as argument:
void doSomething( const B& );

template<typename Itr>
void foo1( Itr beg, Itr end )
{
    while( beg != end )
        doSomething(*beg++);
}

void foo2()
{
    vector<A> vec;
    foo1( vec.begin(), vec.end() );
}

A: One class that inherits vector< A > and another class that inherits vector< B > and implement constructor that takes the other class as a parameter.

A: I was hoping for a trick along the line of C#'s  along with C++'s template specialization. Something like this:
template<>                                                     // C++ specialization
vector<B>::operator vector<A>(this const vector<A> &vec) const // c# extension method
{
    return vector<C>(vec.begin(), vec.end());
}

Which would then allow me to simply state:
vector<A> va;
vector<B> vb = va;

Alas, this is not possible in C++, so I'll just add a global function:
vector<B> ConvertToB(const vector<A> &vec);

Thanks, everybody.


text:
Q: Line color in ggforce::geom_arc_bar Probably a simple one.
Is there a way to eliminate the bordering line in a ggforce::geom_arc_bar pie plot?
pie <- data.frame(
    state = c('eaten', 'eaten but said you didn\'t', 'cat took it',
              'for tonight', 'will decompose slowly'),
    focus = c(0.2, 0, 0, 0, 0),
    start = c(0, 1, 2, 3, 4),
    end = c(1, 2, 3, 4, 2*pi),
    amount = c(4,3, 1, 1.5, 6),
    stringsAsFactors = FALSE
)
ggplot(pie) +
    geom_arc_bar(aes(x0 = 0, y0 = 0, r0 = 0, r = 1, amount = amount,
                     fill = state, explode = focus), stat = 'pie') +
    scale_fill_brewer('', palette = 'Set1') +
    coord_fixed()

For example, in the plot above either eliminate the black border line or make its color the same as the fill color?
And another question, is it possible to eliminate the border line only from the perimeter of the pie? So only the demarkation of the slices stays?

A: You can add color = "transparent" or color = NA inside geom_arc_bar

Code
library(ggforce)
ggplot(pie) +
  geom_arc_bar(aes(x0 = 0, y0 = 0, r0 = 0, r = 1, amount = amount,
                   fill = state, explode = focus), stat = 'pie',
                   color = "transparent") +
  scale_fill_brewer('', palette = 'Set1') +
  coord_fixed()

A: ggplot uses two parameters in general for colours:
col =

and
fill =

You assigned fill (internal), but didnt deal with col (outline).
the following should work, where I assign col=NA
ggplot(pie) +
  geom_arc_bar(aes(x0 = 0, y0 = 0, r0 = 0, r = 1, amount = amount,
                   fill = state, explode = focus), col=NA,stat = 'pie') +
  scale_fill_brewer('', palette = 'Set1') +
  coord_fixed()

EDIT: So to answer the second quesiton - I really don't know if this is possible (I am not overly familiar with ggforce)
In light of this, I ask forgiveness in advance of this very 'hacky' solution to your problem. But I felt it was better to offer something for others to improve on.
To explain: keep hte original outline, but then plot a new outline the same colour as each segment using the geom_arc0 function"
geom_arc0(aes(x0 = 0, y0 = 0, r = 1, start = start, end = end,
              colour = factor(state)), data = pie, ncp = 50)

in context:
ggplot(pie) +
  geom_arc_bar(aes(x0 = 0, y0 = 0, r0 = 0, r = 1, amount = amount,
                   fill = state, explode = focus), col="black",stat = 'pie') +
  geom_arc0(aes(x0 = 0, y0 = 0, r = 1, start = start, end = end,
                colour = factor(state)), data = pie, ncp = 50)
  scale_fill_brewer('', palette = 'Set1') +
  coord_fixed()

It may look a bit dodgy - if you increase the ncp parameter it adds more points to the outline (thus getting closer to a perfect circle) - i was limited to ncp=2000.
Again apologies that it is so hacky.


text:
Q: error with loading screen assetmanager libgdx java I currently have 2 classes, an Assets class and a loading screen class:
Assets class:
public class Assets {

    public static AssetManager manager = new AssetManager();

    public static void queueLoading() {
        (..)
        manager.load("sound/startScreen.mp3", Music.class);
        (..)

        while(!manager.update())
        {
            System.out.println("Loaded: " + manager.getProgress() *100 + "%");
        }
    }
    public static boolean isLoaded() {
        if(manager.getProgress() >= 1)
            return true;
        return false;
        //return manager.update();
    }
}

Loading screen::
public class LoadingScreen implements Screen{
    final Game1 game;
    Sprite LdScreen;
    OrthographicCamera camera;

    public LoadingScreen(Game1 gam){
        game=gam;

        camera = new OrthographicCamera();
        camera.setToOrtho(false, 1920, 1080);

    }

    public void show() {
        Texture LdscreenTexture = new Texture(Gdx.files.internal("data/Background.png"));
        LdScreen =  new Sprite (LdscreenTexture);
    }

    @Override
    public void render(float delta) {
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        camera.update();
        game.batch.setProjectionMatrix(camera.combined);
        game.batch.begin();
        game.batch.draw(LdScreen, 0,0);
        game.batch.end();
        Assets.manager.update();
        if(Assets.manager.update() == true){
            game.setScreen(new MainMenuScreen(game));
            System.out.print("test");
        }
}

The problem is this doesn't work, when I run it immediately Assets.manager.update returns true and I get an error saying that the assets are not found for MainMenuScreen, clear as they have not been loaded. And when i comment out game.setScreen(new MainMenuScreen(game)); I get the 'test' written to the console but I don't get the progress to the console from my Assets class. This leads me to think that when I run I the Asset.smanager.update always returns true, and it isn't loading the assets at all.
I have looked at tutorials and the wiki, but I have not found them to be useful. Any ideas?


text:
Q: Pass table name to @Table annotation of entity at runtime Hibernate I have a next problem: I ve got a several tables in database, and  somehow i need to make a query from one of them, but only in runtime i will know the name of needed table, so is any possibility to pass table name to @Table annotation of entity in runtime? All of these tables have absolutely identical schema. The only distinction - is name (BILLING_DATA_2016_1, BILLING_DATA_2015_12 etc.). Do somebody have an idea how can i pass the name of table dynamically? Or may be some hack with Queries and Inheritance?

A: You can try HibernateInterceptor. Place the {BILLING_DATA_PLACEHOLDER} string into your @Table annotation and just replace it on fly
public class HibernateInterceptor extends EmptyInterceptor {
@Override
    public String onPrepareStatement(String sql) {
          String prepedStatement = super.onPrepareStatement(sql);
          prepedStatement = prepedStatement.replaceAll("{BILLING_DATA_PLACEHOLDER}", theRealSchemaName);
          return prepedStatement;
    }
}

Have not tried though


text:
Q: Bridge Construction Problem - Buckling Bridge A 100 ft. bridge expands 1 in. during the heat of the day. Since the ends of the bridge are embedded in rock, the bridge buckles upward and forms an arc for which the original bridge is a chord. What is the approximate distance moved by the center of the bridge?
Starting points?

A: In my mind's eye, the bridge is across a horizontal span:

The bridge originally spanned a gap of length $L$ from $P$ to $Q$, but after growing to $L+\delta L$, it has now buckled into the arc $PSQ$ with center at $O$. From right triangle $ROQ$ with hypotenuse $OQ$ of length $r$ and $\angle ROQ=\theta$, we see that $RQ=\frac L2=r\sin\theta$ and $RO=r\cos\theta$, so the bridge has buckled from $R$ to $S$, a distance of $\delta y=r-r\cos\theta$.
The bridge now spans arc $PSQ$ of length $2r\theta=L+\delta L$. Thus
$$r=\frac{L+\delta L}{2\theta}=\frac L{2\sin\theta}$$
Solving for $\theta$,
$$\theta=\frac{L+\delta L}L\sin\theta=\sin\theta+\frac{\delta L}L\sin\theta\approx\sin\theta+\frac16\sin^3\theta$$
Using the first two terms of the series for $\arcsin$ in this last equation. Then we get
$$\sin\theta\approx\sqrt{\frac{6\delta L}L}$$ So
$$\begin{align}\delta y & =r(1-\cos\theta)=2r\sin^2\frac{\theta}2=\frac{L\sin^2\frac{\theta}2}{\sin\theta}=\frac{4L\cos^2\frac{\theta}2\sin^2\frac{\theta}2}{4\sin\theta\cos^2\frac{\theta}2} \\
 & =\frac{L\sin\theta}{4\cos^2\frac{\theta}2}\approx\frac{L\sin\theta}4\approx\frac{\sqrt6}4\sqrt{L\delta L}=\frac{\sqrt6}4\sqrt{(100)\left(\frac1{12}\right)} \\
 & \approx1.76777 ft\end{align}$$
This is my first attempt at posting an image. I hope it doesn't look too bad. You can get the first two term of the $\arcsin$ series from trigonometry and algebra alone, but it's a tough slog.
You knew in advance the answer had to look something like this from the variational principle. The length of the bridge is
$$L+\delta L\approx L+\frac{\partial L}{\partial y}\delta y+\frac12\frac{\partial^2L}{\partial y^2}(\delta y)^2$$
We know that $\frac{\partial L}{\partial y}=0$ because the shortest path between two points is a straight line, so we get $\delta y\approx k\sqrt{\delta L}$. To get consistent units, we must multiply the right hand side by the square root of a length, and the only length visible in the problem is $L$, so we have $\delta y\approx\kappa\sqrt{L\delta L}$, and we find our numerical constant $\kappa=\frac{\sqrt6}4$.

A: DRAW A SKETCH.  The  vertical line is the original, the arc is the expanded bridge.  You have some right triangles and an arc-how do the lengths compare?  You wind up comparing $\cos \theta$ to $1$ for small $\theta$.  You want the distance along the $x$ axis between the line and the arc.

A: First we have to calculate the force due to temparature effects:
$
Force = E * Δl / l
$
Reference: http://www.setareh.arch.vt.edu/safas/007_fdmtl_29_stress_due_to_temperature_change.html
Then apply the theory of buckling where nice formulas will appear:
http://www.arpnjournals.com/jeas/research_papers/rp_2007/jeas_0207_35.pdf
*
See that we are missing E (the Young's modulus of the beam) and I (the area moment of inertia of the beam's cross section).
*
I recommend to change the tag to "physics".

A: The two equations seems to be simple:
$r\theta = 2r*sin{\theta /2}+1/(254*30)$
$2r*sin{\theta /2}=100$
The move of the center is:
$d=r-r*cos\theta$
Let me know if this suffice...


text:
Q: GHCi can't resolve names in two versions of the same package I'm trying to use Parsec's OperatorTable with the following:
table :: Ex.OperatorTable String () Identity Expr
table = [[]]

cabal build and cabal run work, but loading Main into GHCi gives me this weird error:
Parser.hs:127:33:
    Couldn't match type 'Identity'
                  with 'transformers-0.3.0.0:Data.Functor.Identity.Identity'
    NB: 'Identity'
          is defined in 'Data.Functor.Identity'
              in package 'transformers-0.4.3.0'
        'transformers-0.3.0.0:Data.Functor.Identity.Identity'
          is defined in 'Data.Functor.Identity'
              in package 'transformers-0.3.0.0'
    Expected type: Ex.OperatorTable
                     String () transformers-0.3.0.0:Data.Functor.Identity.Identity Expr
      Actual type: Ex.OperatorTable String () Identity Expr
    In the first argument of 'Ex.buildExpressionParser', namely 'table'
    In the expression: Ex.buildExpressionParser table factor

So I deleted ~/.cabal and .cabal-sandbox and reinstalled mtl, both globally and in a new sandbox Same error.
ghc-pkg list | grep trans gives:
transformers-0.3.0.0
transformers-0.4.3.0

so I tried ghc-pkg unregister transformers-0.3.0.0 but got a scary-looking warning message about how a bunch of other packages would break:
ghc-pkg: unregistering transformers-0.3.0.0 would break the following
packages: regex-posix-0.95.2 regex-compat-0.95.1 regex-base-0.93.2
parsec-3.1.5 network-2.4.2.3 mtl-2.1.3.1 fgl-5.5.0.1 HTTP-4000.2.10
ghc-7.8.3 haskeline-0.7.1.2 (use --force to override)

Didn't proceed.
Also tried ghci -package transformers-0.4.3.0 and got the same error.
What do I do now? :\
My .cabal file contains transformers <= 0.4.3.0. I'm on GHC 7.8.3 on OS X 10.10.2.


text:
Q: Coinflip Embed Command Discord.py? How would I go about making a coinflip embed command.
What I want it to do is make a discord embed saying Coinflip | (Bot Name) as the header, then the field is "(User who used the command) the coin landed on (what it lands on)! and then the thumbnail is a picture of a coin flipped on tails or heads.

A: Method
You can import choice from random, and use the number 1 and 0 to make determine your coinflip by doing something like if random.choice(number) == 1:.
Example
import random
from random import choice

determine_flip = [1, 0]

@bot.commands()
async def coinflip(ctx):
    if random.choice(determine_flip) == 1:
        embed = discord.Embed(title="Coinflip | (Bot Name)", description=f"{ctx.author.mention} Flipped coin, we got **Heads**!")
        await ctx.send(embed=embed)

    else:
        embed = discord.Embed(title="Coinflip | (Bot Name)", description=f"{ctx.author.mention} Flipped coin, we got **Tails**!")
        await ctx.send(embed=embed)

Conclusion
I hope this helped, good luck on your Discord Bot, If you're new to discord.py then you can get help from my community and improve your bot and even solve your problems.
Have a nice day!
Join Senarc if you need help. ;)

A: async def _coinflipl(ctx):
    responses = ['heads.',
                 'tails.']
    await ctx.send(f"{random.choice(responses)}") ```


text:
Q: What is my mistake when creating this grouped barplot in R and how do i resolve this? This is my dataframe data

dput(data4)

structure(list(`number of goals scored` = c(311, 271),
               `number of fouls commited` = c(2147, 2246)),
               row.names = c("Hometeam", "AwayTeam"),
               class = "data.frame")

This is the my barplot code and the error i get when creating the grouped barplot
barplot(data4,
        main = 'total num of goals and fouls commited',
        xlab = 'Teams',ylab = 'frequency',
        col = c('red','yellow'),
        legend.text = rownames(data4),
        beside = TRUE)

Error in barplot.default(data4, main = "total num of goals and fouls commited",  :    'height' must be a vector or a matrix

A: See if this is what you wanted:
barplot(as.matrix(data4[,1:2]),
    main = 'total num of goals and fouls commited',
    xlab = 'Teams',ylab = 'frequency',
    col = c('red','yellow'),
    legend.text = rownames(data4),
    beside = TRUE)

barplot is asking for a matrix in the 1st argument. So give it a matrix intead of a data.frame.


text:
Q: Get and Read from XML in C# I have log files where the name of the file is today's date. and I need to get the errors to attributes in these files if they are between the start and stop times currently kept in the variable. how can i achieve this?
<ErrorLogs>
  <Logs Hour_Date="9:34/1_6_2021" ID="1">
    <ErrorGUI>checkbox</ErrorGUI>
    <ErrorType>uplink fail</ErrorType>
    <ProgramPage>Failures Page</ProgramPage>
    <ErrorStartTime>9:34:20</ErrorStartTime>
  </Logs>
<ErrorLogs>

A: As @JonSkeet mentioned you need to deserialize from XML to object classes. Deserialize the XML as ErrorLogs.
[XmlRoot("ErrorLogs")]
public class ErrorLogs
{
    [XmlElement("Logs")]
    public List<Log> Logs { get; set; }
}

public class Log
{
    [XmlAttribute("Hour_Date")]
    public string HourDate { get; set; }

    [XmlAttribute("ID")]
    public string ID { get; set; }

    [XmlElement("ErrorGUI")]
    public string ErrorGUI { get; set; }

    [XmlElement("ErrorType")]
    public string ErrorType { get; set; }

    [XmlElement("ProgramPage")]
    public string ProgramPage { get; set; }

    [XmlIgnore]
    public TimeSpan ErrorStartTime { get { return TimeSpan.Parse(_ErrorStartTime); } }

    [XmlElement("ErrorStartTime")]
    public string _ErrorStartTime { get; set; }
}

Next, working with System.Linq to filter data by date range.
using System.Xml;
using System.Xml.Serialization;
using System.Collections.Generic;
using System.IO;
using System.Linq;

XmlSerializer serializer = new XmlSerializer(typeof(ErrorLogs));

ErrorLogs errorLogs = (ErrorLogs)serializer.Deserialize(new StringReader(xml));

TimeSpan startTs = new TimeSpan(8, 0, 0); // Your Start Time
TimeSpan endTs = new TimeSpan(10, 0, 0); // Your End Time

var result = errorLogs.Logs
    .Where(x => startTs <= x.ErrorStartTime
            && x.ErrorStartTime <= endTs)
    .ToList();

Demo @ .NET Fiddle

A: Try following :
using System;
using System.Linq;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Linq;
using System.Globalization;

namespace ConsoleApp2
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            List<ErrorLog> errors = new List<ErrorLog>();

            TimeSpan startTime = new TimeSpan(8, 0, 0);
            TimeSpan endTime = new TimeSpan(19, 0, 0);
            //create a loop to read all files
            List<ErrorLog> results = ErrorLog.GetErrors(FILENAME, startTime, endTime);
            if (results != null)
            {
                errors.AddRange(results);
            }
        }
    }
    public class ErrorLog
    {
        public string errorGui { get; set; }
        public string errorType { get; set; }
        public string programPage { get; set; }
        public TimeSpan errorStartTime { get; set; }
        public DateTime date { get; set; }
        public int ID { get; set; }

        static string dateFormat = "H:mm/M_d_yyyy";
        static string timeFormat = "h:mm:ss";

        public static List<ErrorLog> GetErrors(string filename, TimeSpan start, TimeSpan end)
        {
            List<ErrorLog> errors = null;
            XDocument doc = XDocument.Load(filename);
            List<XElement> logs = doc.Descendants("Logs").ToList();

            foreach(XElement log in logs)
            {
                string errorStartTime = (string)log.Element("ErrorStartTime");
                TimeSpan time = DateTime.ParseExact(errorStartTime, timeFormat, CultureInfo.InvariantCulture).TimeOfDay;

                if (time >= start && time <= end)
                {
                    ErrorLog error = new ErrorLog();
                    error.ID = (int)log.Attribute("ID");
                    error.errorGui = (string)log.Element("ErrorGui");
                    error.errorType = (string)log.Element("ErrorType");
                    error.programPage = (string)log.Element("ProgramPage");
                    error.errorStartTime = time;
                    string strDate = (string)log.Attribute("Hour_Date");
                    error.date = DateTime.ParseExact(strDate, dateFormat, CultureInfo.InvariantCulture);
                    if (errors == null) errors = new List<ErrorLog>();
                    errors.Add(error);

                }
            }

            return errors;
        }
    }

}


text:
Q: ADMU3011E: Server launched but failed initialization when set generic VM args I was facing a Java.lang.OutOfMemoryError: Java heap space in the Websphere console.
To resolve that I have put the following generic VM args
-Xms512m –Xmx1024m -XX:PermSize=512m -XX:MaxPermSize=512m
But after that I cannot start the server, it is showing
ADMU3011E: Server launched but failed initialization.
I cannot open the WAS Admin Console to revert the chnages back.
What can I do in this case?

A: Referring to the valuable comments, I came to the following solution:
Go to
${PROFILE_HOME}/config/cells/${CELL}/nodes/${NODE}/servers/${SERVER}
and modify server.xml
Removed generic JVM arguments
-Xms512m –Xmx1024m -XX:PermSize=512m -XX:MaxPermSize=512m
Then started the server again.


text:
Q: What is the difference between side effect and referential transparency? What is the difference between these terms?

*

*a function has no side effect

*a function is referential transparent

A: A function that is referentially transparent definitely has no side effects. However, a function that has no side effects is not always referentially transparent.
Examples:
int x = 0;

int referentiallyTransparent(int y)
{
    return y + 1;
}

int hasNoSideEffects(int y)
{
    return x + y;
}

The function hasNoSideEffects has no side effects. Which means that calling hasNoSideEffects(y) does not affect the state of the program. However, the value it returns is affected by the state of the program and does not solely depend on the input variable y and thus a call hasNoSideEffects(y) cannot always be replaced by the value it reduces to.


text:
Q: How to use drop down menu to change PHP object variable? The title may not be the best way to word this question, so please let me know if I can improve it.
What I am trying to do is use a drop down menu to change the value of a PHP object.
In the example below, I want $selected to be assigned as the "value" of the the menu option selected.
  $selected = $_GET['program_select'];

Here is the drop down menu:
  <select id="programs_select" name="programs_select">
    <option>Select a Different Month</option>
    <?
     foreach($pagedata->programs as $programs){
    ?>
    <option value="<?=$programs->id?>"><?=$programs->title?></option>
    <?
    }
    ?>
  </select>

How can I send this value to the server and reload the page using the selected value?
For example, if the 2nd option is selected and it's id is 2 the result would be:
$selected = 2;

FYI, this is being used to dynamically generate the output data for a thumbnail menu.  The "program" being displayed would be determined by the value in the option selected.

A:   <select id="programs_select" name="programs_select" onchange="ihavechanges(this.options[this.selectedIndex].value)">
    <option>Select a Different Month</option>
    <?
     foreach($pagedata->programs as $programs){
    ?>
    <option value="<?=$programs->id?>"><?=$programs->title?></option>
    <?
    }
    ?>
  </select>

A: <select id="programs_select" name="programs_select">
    <option>Select a Different Month</option>
    <?
    $selected = $_GET['program_select'];
    foreach($pagedata->programs as $programs){
        $seld = ($selected == $program-id) ? 'selected' : '';
        echo '<option value="'.$programs->id.'" '.$seld.'>'.$programs->title.'</option>';
    }
    ?>
</select>

A: You are using GET in the php side. So, if you just want to know how to pass the value to your php file, then put your select tag into a form and add a submit button.
<form id="your_id" name="your_id" method="get" action="your_controller/your_function_name">
 <select id="programs_select" name="programs_select">
    <option>Select a Different Month</option>
    <?
     foreach($pagedata->programs as $programs){
    ?>
    <option value="<?=$programs->id?>"><?=$programs->title?></option>
    <?
    }
    ?>
  </select>
  <input type="submit" id="submit" name="submit" value="GO">
</form>

In your controller, echo something based on the value.

$selected = $_GET['program_select'];

However, if your want to change the contents in the same page without refresh. You may need ajax call to do that, and I recommend the jQuery ajax api (http://api.jquery.com/jQuery.ajax/).
$("select#programs_select").live('change', function(){
        var id = $("select#programs_select").val();
                $.ajax({
                type: "GET",
                url: "your_controller/the_funstion_name?programs_select=" + id,
                data: "",
                contentType: "application/json; charset=utf-8",
                            success: function(msg) {
                $("#your_thumbnail_menu_id").html(msg);
                },
                error: function() {
                alert("Error! Ajax failed");
                }
            });

        });

In your controller side, echo the html you need at last.
e.g:
$selected = $_GET['program_select'];
$html = "

your menu  $selected
";
$html .="
which depends on the id you got!

";
echo $html;


text:
Q: Is there a way to display the real time clock in a UEFI menu? I want to display a real-time clock in [YY/MM/DD, hh:mm:ss, time zone] format. How do we do the real-time update at each second on the page?
I am new to UEFI. I am referring to a page in which we press F2 or Esc to reach a menu when we boot a computer. In that menu, we can check the CPU temperature, configure IP address, etc in different pages. Here is an example,
https://github.com/tianocore/edk2/blob/master/NetworkPkg/Ip4Dxe/Ip4Config2Nv.c
Let's say I am looking at this Ip4Dxe page in the UEFI menu and I want to add a real-time clock on the first line of the page.
To fetch the time, I use gRT->getTime(&Time, NULL). I can then display the Time variable on the page. However, I have no idea how to make it update automatically in real-time. Do we have some RuntimeServices to support this?


text:
Q: How to localize UI files in PySide I created an application which loads its UI dynamically from UI files (added to resources of application. I have't translate in with poyside-uic, loading as is. now I want lo localize application, but do not understand how.
I tried to generate TS file using pyside-lupdate widge1.ui widget2.ui ... -ts my.ts and got document with multiple context nodes and linguist does not shows all records (only about 7 records and I do not understand which exact).
So, my question: how to translate dynamically loaded UI files?

A: Found it. Quite simple, but not always obvious.

*

*Execute pyside-lupdate file1.ui file2.ui .... fileN.ui -ts translations\ru_RU.ts. Got a TS file after that with multiple contexts (it is ok, I was wrong)

*Open TS with linguist. Ensure that option 'Context' checked in menu "View->View"

*...

*PROFIT!!!


text:
Q: How to download network image in Flutter I am building a simple wallpaper app with Api by watching tutorials on YouTube. But in the last stage, I can't save the image from the URL in the android simulator. Can you guys help me with how can I do this work?
import 'package:flutter/material.dart';
class ImageView extends StatefulWidget {
  final String imageUrl;
  ImageView({@required this.imageUrl});
  @override
  _ImageViewState createState() => _ImageViewState();}
class _ImageViewState extends State<ImageView> {
  @override
Widget build(BuildContext context) {
return Scaffold(
  body: Stack(
    children: [
      Hero(
        tag: widget.imageUrl,
        child: Container(
          height: MediaQuery.of(context).size.height,
          width: MediaQuery.of(context).size.width,
          child: Image.network(
            widget.imageUrl,
            fit: BoxFit.cover,
          ),
        ),
      ),

//the buttons is here
      Container(
        alignment: Alignment.bottomCenter,
        height: MediaQuery.of(context).size.height,
        width: MediaQuery.of(context).size.width,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.end,
          children: [
            //wallpaper download button
            GestureDetector(
              onTap: () {},
              child: Stack(
                children: [
                  Container(
                      height: 55,
                      width: MediaQuery.of(context).size.width / 2,
                      decoration: BoxDecoration(
                        color: Color(0xff1c1b1b).withOpacity(0.8),
                        borderRadius: BorderRadius.circular(30),
                      )),
                  Container(
                      padding:
                          EdgeInsets.symmetric(horizontal: 8, vertical: 8),
                      width: MediaQuery.of(context).size.width / 2,
                      height: 55,
                      decoration: BoxDecoration(
                          border: Border.all(
                            color: Colors.white,
                            width: 1,
                          ),
                          borderRadius: BorderRadius.circular(30),
                          gradient: LinearGradient(colors: [
                            Colors.blueGrey[100],
                            Colors.grey[900],
                          ])),
                      child: Column(
                        children: [
                          Text(
                            'Set Wallpaper',
                            style: TextStyle(
                              fontSize: 16,
                              color: Colors.white,
                            ),
                          ),
                          SizedBox(height: 5),
                          Text(
                            'Image wil be save in gallery',
                            style: TextStyle(
                              fontSize: 10,
                              color: Colors.white,
                            ),
                          )
                        ],
                      )),
                ],
              ),
            ),
            SizedBox(height: 16),
            //for closeing the showing wallpaper
            GestureDetector(
              onTap: () => Navigator.pop(context),
              child: Text(
                'Cancel',
                style: TextStyle(
                  color: Colors.amber,
                ),
              ),
            ),
            SizedBox(height: 50)
          ],
        ),
      )
    ],
   ),
  );
 }
}

A: You can copy paste run full code below
Step 1: To save image to gallery, add <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> to AndroidManifest.xml
Step 2: Request permission with permission_handler
Step 3: Download file with flutter_cache_manager's DefaultCacheManager().getSingleFile(widget.imageUrl)
Step 4: Save to gallery with image_gallery_saver's ImageGallerySaver.saveFile(file.path)
Step 5: Directly set wall paper with wallpaper_manager's  WallpaperManager.setWallpaperFromFile(file.path, WallpaperManager.HOME_SCREEN)
code snippet
_requestPermission() async {
    Map<Permission, PermissionStatus> statuses = await [
      Permission.storage,
    ].request();

    final info = statuses[Permission.storage].toString();
    print(info);
  }
...
GestureDetector(
          onTap: () async {
            File file = await DefaultCacheManager()
                .getSingleFile(widget.imageUrl);
            print(file.path);
            final result = await ImageGallerySaver.saveFile(file.path);
            print("gallerysaver result $result");

            String resultWall =
                await WallpaperManager.setWallpaperFromFile(
                    file.path, WallpaperManager.HOME_SCREEN);

            print("resultWall $resultWall");
          },

working demo

full code
import 'dart:io';

import 'package:permission_handler/permission_handler.dart';
import 'package:flutter/material.dart';
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
import 'package:wallpaper_manager/wallpaper_manager.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';

class ImageView extends StatefulWidget {
  final String imageUrl;
  ImageView({@required this.imageUrl});
  @override
  _ImageViewState createState() => _ImageViewState();
}

class _ImageViewState extends State<ImageView> {
  @override
  void initState() {
    super.initState();

    _requestPermission();
  }

  _requestPermission() async {
    Map<Permission, PermissionStatus> statuses = await [
      Permission.storage,
    ].request();

    final info = statuses[Permission.storage].toString();
    print(info);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: [
          Hero(
            tag: widget.imageUrl,
            child: Container(
              height: MediaQuery.of(context).size.height,
              width: MediaQuery.of(context).size.width,
              child: Image.network(
                widget.imageUrl,
                fit: BoxFit.cover,
              ),
            ),
          ),

//the buttons is here
          Container(
            alignment: Alignment.bottomCenter,
            height: MediaQuery.of(context).size.height,
            width: MediaQuery.of(context).size.width,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                //wallpaper download button
                GestureDetector(
                  onTap: () async {
                    File file = await DefaultCacheManager()
                        .getSingleFile(widget.imageUrl);
                    print(file.path);
                    final result = await ImageGallerySaver.saveFile(file.path);
                    print("gallerysaver result $result");

                    String resultWall =
                        await WallpaperManager.setWallpaperFromFile(
                            file.path, WallpaperManager.HOME_SCREEN);

                    print("resultWall $resultWall");
                  },
                  child: Stack(
                    children: [
                      Container(
                          height: 55,
                          width: MediaQuery.of(context).size.width / 2,
                          decoration: BoxDecoration(
                            color: Color(0xff1c1b1b).withOpacity(0.8),
                            borderRadius: BorderRadius.circular(30),
                          )),
                      Container(
                          padding:
                              EdgeInsets.symmetric(horizontal: 8, vertical: 8),
                          width: MediaQuery.of(context).size.width / 2,
                          height: 55,
                          decoration: BoxDecoration(
                              border: Border.all(
                                color: Colors.white,
                                width: 1,
                              ),
                              borderRadius: BorderRadius.circular(30),
                              gradient: LinearGradient(colors: [
                                Colors.blueGrey[100],
                                Colors.grey[900],
                              ])),
                          child: Column(
                            children: [
                              Text(
                                'Set Wallpaper',
                                style: TextStyle(
                                  fontSize: 16,
                                  color: Colors.white,
                                ),
                              ),
                              SizedBox(height: 5),
                              Text(
                                'Image wil be save in gallery',
                                style: TextStyle(
                                  fontSize: 10,
                                  color: Colors.white,
                                ),
                              )
                            ],
                          )),
                    ],
                  ),
                ),
                SizedBox(height: 16),
                //for closeing the showing wallpaper
                GestureDetector(
                  onTap: () => Navigator.pop(context),
                  child: Text(
                    'Cancel',
                    style: TextStyle(
                      color: Colors.amber,
                    ),
                  ),
                ),
                SizedBox(height: 50)
              ],
            ),
          )
        ],
      ),
    );
  }
}

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: Center(
            child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
              ElevatedButton(
                  onPressed: () {
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                          builder: (context) => ImageView(
                              imageUrl: "https://picsum.photos/250?image=9")),
                    );
                  },
                  child: Text('To set wall paper')),
            ])));
  }
}


text:
Q: How can I get Android Wifi Scan Results into a list? I know how to get a <List> of Android Wifi Scans but I can not figure out the best way to make a list adapter out of them. I would like to just bind SSID and BSSID from a <List> of scans to text1 and text2.
Samples of what I have been doing
wifi.startScan();
        // get list of the results in object format ( like an array )
        List<ScanResult> results = wifi.getScanResults();`

        // loop that goes through list
        for (ScanResult result : results) {
            Toast.makeText(this, result.SSID + " " + result.level,
                    Toast.LENGTH_SHORT).show();

And:
private void fillDataFromDb() {
        Cursor scanCursor = Db.fetchAllScans();
        startManagingCursor(scanCursor);`

        // Create an array to specify the fields we want to display in the list
        // (only TITLE)
        String[] from = new String[] { WifiDbAdapter.KEY_BSSID,
                WifiDbAdapter.KEY_SSID };

        // and an array of the fields we want to bind those fields to (in this
        // case just text1)
        int[] to = new int[] { R.id.text1, R.id.text2 };

        // Now create a simple cursor adapter and set it to display
        SimpleCursorAdapter scansdb = new SimpleCursorAdapter(this,
                R.layout.scan_row, scanCursor, from, to);
        setListAdapter(scansdb);
    }

A: Try this code
public class WiFiDemo extends Activity implements OnClickListener
 {
    WifiManager wifi;
    ListView lv;
    TextView textStatus;
    Button buttonScan;
    int size = 0;
    List<ScanResult> results;

    String ITEM_KEY = "key";
    ArrayList<HashMap<String, String>> arraylist = new ArrayList<HashMap<String, String>>();
    SimpleAdapter adapter;

    /* Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        textStatus = (TextView) findViewById(R.id.textStatus);
        buttonScan = (Button) findViewById(R.id.buttonScan);
        buttonScan.setOnClickListener(this);
        lv = (ListView)findViewById(R.id.list);

        wifi = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        if (wifi.isWifiEnabled() == false)
        {
            Toast.makeText(getApplicationContext(), "wifi is disabled..making it enabled", Toast.LENGTH_LONG).show();
            wifi.setWifiEnabled(true);
        }
        this.adapter = new SimpleAdapter(WiFiDemo.this, arraylist, R.layout.row, new String[] { ITEM_KEY }, new int[] { R.id.list_value });
        lv.setAdapter(this.adapter);

        registerReceiver(new BroadcastReceiver()
        {
            @Override
            public void onReceive(Context c, Intent intent)
            {
               results = wifi.getScanResults();
               size = results.size();
            }
        }, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
    }

    public void onClick(View view)
    {
        arraylist.clear();
        wifi.startScan();

        Toast.makeText(this, "Scanning...." + size, Toast.LENGTH_SHORT).show();
        try
        {
            size = size - 1;
            while (size >= 0)
            {
                HashMap<String, String> item = new HashMap<String, String>();
                item.put(ITEM_KEY, results.get(size).SSID + "  " + results.get(size).capabilities);

                arraylist.add(item);
                size--;
                adapter.notifyDataSetChanged();
            }
        }
        catch (Exception e)
        { }
    }
}

WiFiDemo.xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="16dp"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_vertical"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/textStatus"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Status" />

        <Button
            android:id="@+id/buttonScan"
            android:layout_width="wrap_content"
            android:layout_height="40dp"
            android:text="Scan" />
    </LinearLayout>

    <ListView
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="20dp"></ListView>
</LinearLayout>

For ListView- row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="8dp">

    <TextView
        android:id="@+id/list_value"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="14dp" />
</LinearLayout>

Add these permission in AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

A: Wrap an ArrayAdapter around your List<ScanResult>. Override getView() to populate your rows with the ScanResult data. Here is a free excerpt from one of my books that covers how to create custom ArrayAdapters like this.

A: Find a complete working example below:
The code by @Android is very good but has few issues, namely:

*

*Populating to ListView code needs to be moved to onReceive of BroadCastReceiver where only the result will be available. In the case result is obtained at 2nd attempt.

*BroadCastReceiver needs to be unregistered after the results are obtained.

*size = size -1 seems unnecessary.

Find below the modified code of @Android as a working example:
WifiScanner.java which is the Main Activity
package com.arjunandroid.wifiscanner;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class WifiScanner extends Activity implements View.OnClickListener{

    WifiManager wifi;
    ListView lv;
    Button buttonScan;
    int size = 0;
    List<ScanResult> results;

    String ITEM_KEY = "key";
    ArrayList<String> arraylist = new ArrayList<>();
    ArrayAdapter adapter;

    /* Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        getActionBar().setTitle("Widhwan Setup Wizard");

        setContentView(R.layout.activity_wifi_scanner);

        buttonScan = (Button) findViewById(R.id.scan);
        buttonScan.setOnClickListener(this);
        lv = (ListView)findViewById(R.id.wifilist);

        wifi = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        if (wifi.isWifiEnabled() == false)
        {
            Toast.makeText(getApplicationContext(), "wifi is disabled..making it enabled", Toast.LENGTH_LONG).show();
            wifi.setWifiEnabled(true);
        }
        this.adapter =  new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,arraylist);
        lv.setAdapter(this.adapter);

        scanWifiNetworks();
    }

    public void onClick(View view)
    {
        scanWifiNetworks();
    }

    private void scanWifiNetworks(){

        arraylist.clear();
        registerReceiver(wifi_receiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));

        wifi.startScan();

        Log.d("WifScanner", "scanWifiNetworks");

        Toast.makeText(this, "Scanning....", Toast.LENGTH_SHORT).show();

    }

    BroadcastReceiver wifi_receiver= new BroadcastReceiver()
    {

        @Override
        public void onReceive(Context c, Intent intent)
        {
            Log.d("WifScanner", "onReceive");
            results = wifi.getScanResults();
            size = results.size();
            unregisterReceiver(this);

            try
            {
                while (size >= 0)
                {
                    size--;
                    arraylist.add(results.get(size).SSID);
                    adapter.notifyDataSetChanged();
                }
            }
            catch (Exception e)
            {
                Log.w("WifScanner", "Exception: "+e);

            }

        }
    };

}

activity_wifi_scanner.xml which is the layout file for the Activity
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:padding="10dp"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ListView
        android:id="@+id/wifilist"
        android:layout_width="match_parent"
        android:layout_height="312dp"
        android:layout_weight="0.97" />

    <Button
        android:id="@+id/scan"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_gravity="bottom"
        android:layout_margin="15dp"
        android:background="@android:color/holo_green_light"
        android:text="Scan Again" />
</LinearLayout>

Also as mentioned above, do not forget to add Wifi permissions in the AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />

A: In addition for the accepted answer you'll need the following permissions into your AndroidManifest to get it working:
 <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
 <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />

A: refer below link for getting ScanResult with redundant ssid removed from the list
duplicate SSID in scanning wifi result


text:
Q: How to place boxed text next to an image of the same height? I'd like to mimic the following style: having an image of an author next to a textbox of the same height.

However, my attempt is humorously unsettling:

It appears that the aspect-ratio of my face has changed, and it is one-line offset from the textbox, dipping down into the abstract line. Here, I'm attempting to scale the image to the height of the textbox, but I'd actually like to scale the textbox to have the height of the image (without changing the aspect ratio):
\noindent\fbox{%
    \parbox{\textwidth}{%
        \begin{wrapfigure}{r}{0.2\textwidth}
            \begin{center}
                \includegraphics[width=0.18\textwidth]{boylan.jpg}
            \end{center}
        \end{wrapfigure}
        \textbf{Lyam K. Boylan} is an undergraduate student studying physics and pure mathematics at the
University of Victoria with primary interests in the set theoretic foundations of the universe.
    }%
}

A: With use of valign instruction defined in the adjustbox package, and text and image inserted in tabularx:

\documentclass{article}
\usepackage[export]{adjustbox}  % it load  graphicx too
\usepackage{tabularx}

\begin{document}
\noindent\begin{tabularx}{\linewidth}{ |X|c @{} }
    \cline{1-1}
\textbf{Lyam K. Boylan} is an undergraduate student studying physics and pure mathematics at the \emph{}University of Victoria with primary interests in the set theoretic foundations of the universe.
    &   \includegraphics[width=0.2\linewidth,valign=t]{example-image-a}  \\
    \cline{1-1}
\end{tabularx}  \\
\begin{tabularx}{\linewidth}{@{} c|X| }
    \cline{2-2}
\includegraphics[width=0.2\linewidth,valign=t]{example-image-b}
    &   \textbf{Lyam K. Boylan} is an undergraduate student studying physics and pure mathematics at the \emph{}University of Victoria with primary interests in the set theoretic foundations of the universe.\\
    \cline{2-2}
\end{tabularx}
\end{document}

A: One posibility: \raisebox
\documentclass{article}
\usepackage{graphicx}
\usepackage{wrapfig}

\begin{document}

    \noindent\fbox{%
        \parbox{\textwidth}{%
            \begin{wrapfigure}[4]{r}{0.3\textwidth}

                    \raisebox{-11mm}[0pt][0pt]{ \includegraphics[width=0.18\textwidth]{example-image}}

            \end{wrapfigure}
            \textbf{Lyam K. Boylan} is an undergraduate student studying physics and pure mathematics at the
            University of Victoria with primary interests in the set theoretic foundations of the universe.
        }%
    }

\end{document}


text:
Q: In PHP number with 19 digit changes in to exponential number In PHP i have define a variable with 19 digit long number and then print it. But it changes into exponential NUmber which is not acceptable in API Use. I need it as NUMBER. Here is an example of Problem.
$a = 1435483000000072013;
echo $a;

adn it returns 1.4354830000001E+18
Also, I have tried following function but it return wrong number
function output($x) {
    $f = sprintf('%0.08f', $x);
    $f = rtrim($f,'0');
    $f = rtrim($f,'.');
    return $f;
}
echo output(1435483000000072013);

this returns me 1435483000000071936 Number changes
So what is solution for this??

A: Champ, PHP doesn't have strictly typed variables, but it still has to decide whether your number is an int, a float or a double when it stores the information. And your number is larger than INT_MAX, so it's not going to fit into an integer format. That means the system has to bump it up to at least a float, which is where you're getting the exponential format from.
See NoGray's solution for how to fix it. Your number is still being stored, it's just being represented differently because your number is too big.

A: You can use number_format with an empty string for the thousands separator
e.g.
$a = 1435483000000072013;
echo number_format($a, 0, '.', '');

A: $a = 1.435483000000072013;
printf("%.18f",$a);


text:
Q: How do I reuse the code from this function cleanly? The following function is used within a module to query network devices and is called from multiple scripts I use. The arguments it takes are a nested dictionary (the device IP and creds etc) and a string (the command to run on the device):
def query_devices(hosts, cmd):

    results = {
        'success' : [],
        'failed' : [],
    }

    for host in hosts:
        device = hosts[host]
        try:
            swp = ConnectHandler(device_type=device['dev_type'],
                                 ip=device['ip'],
                                 username=device['user'],
                                 password=device['pwd'],
                                 secret=device['secret'])
            swp.enable()
            results[host] = swp.send_command(cmd)
            results['success'].append(host)
            swp.disconnect()
        except (NetMikoTimeoutException, NetMikoAuthenticationException) as e:
            results['failed'].append(host)
            results[host] = e

    return results

I want to reuse all of the code to update a device and the only changes would be:

*

*The function would take the same dictionary but the cmd argument would now be a list of commands.

*The following line:
results[host] = swp.send_command(cmd)

would be replaced by:
results[host] = swp.send_config_set(cmd)

I could obviously just replicate the function making those two changes and as it is in a module I reuse, I am only having to do it once but I am still basically repeating a lot of the same code.
Is there a better way to do this as I seem to come across the same issue quite often in my code.

A: You could just add a check on the changed line:
...
if isinstance(cmd, str):
    results[host] = swp.send_command(cmd)
else:
    results[host] = swp.send_config_set(cmd)
...

The rest of the function can stay the same and now you can simply call it with either a string or a list of strings...

A: You could use the unpacking operator to always make cmds an iterable (a tuple, actually) even if it is a single value.  That way you could always call send_config_set.  Here is a super simplified example to illustrate the concept.
def query_devices(hosts, *cmds):
    for one_cmd in cmds:
        print(one_cmd)

print('query_devices("hosts", "cmd_1")')
query_devices("hosts", "cmd_1")

print('\nquery_devices("hosts", "cmd_1", "cmd_2", "cmd_3")')
query_devices("hosts", "cmd_1", "cmd_2", "cmd_3")

print('\nquery_devices("hosts", *["cmd_1", "cmd_2", "cmd_3"])')
query_devices("hosts", *["cmd_1", "cmd_2", "cmd_3"])

Output:
query_devices("hosts", "cmd_1")
cmd_1

query_devices("hosts", "cmd_1", "cmd_2", "cmd_3")
cmd_1
cmd_2
cmd_3

query_devices("hosts", *["cmd_1", "cmd_2", "cmd_3"])
cmd_1
cmd_2
cmd_3


text:
Q: HTTP Response Format incorrect? I was looking at creating WebServers with C++.
I followed this tutorial by Sloan Kelly, and referenced this answer here.
I wrote (improperly adapted) the following code (showing the sending part only):
std::stringstream make_response;
make_response << "HTTP/1.1 200 OK\r\n";
make_response << "Cache-Control: no-cache, private\r\n";
make_response << "Content-Type: text/html\r\n";
make_response << "Content-Length: 88\r\n";
make_response << "\r\n";
make_response << "Hello!";
std::string finished_response = make_response.str();

send(client, finished_response.c_str(), finished_response.length()+1, 0);

What is the problem here? When I connect to 127.0.0.1:8000, the screen is entirely blank.
I know that the request reaches me, as I have printed it in the console:
C:\Users\Jaideep Shekhar\OneDrive\Documents\Projects\ProjectC++\Library\v0.1\main>webserver.exe
Listening for incoming connections...
Client connected!
Client says: GET / HTTP/1.1
Host: 127.0.0.1:8000
Connection: keep-alive
Cache-Control: max-age=0
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.75 Safari/537.36
Sec-Fetch-Mode: navigate
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3
Sec-Fetch-Site: cross-site
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9

@_M
Client disconnected.

You can copy the whole source code from here and open up your terminal:
g++ webserver.cpp -o webserver.exe -lws2_32 && webserver.exe

Note that this code is for Windows OS.
Edit: Thanks to a comment, I solved the problem (see code below). Any improvements or problems in the code are welcome to be pointed out.
Edit2: How would I send images? I am opening the file opened with std::ios::binary, but it is not being recieved by the browser.
Thanks!

A: Okay, looks like the format and headers were all correct after all. I made a mistake in responding that I am sending 88 bytes of content, while I sent 5.
In fact, to avoid these issues, I have now put the HTML in its separate file.
The relevant part looks like this now:
// Transfer the whole HTML to a std::string
std::fstream grab_content("home.html");
std::stringstream make_content;
make_content << grab_content.rdbuf();
std::string finished_content;
finished_content = make_content.str();

// Create the HTTP Response
std::stringstream make_response;
make_response << "HTTP/1.1 200 OK\r\n";
make_response << "Cache-Control: no-cache, private\r\n";
make_response << "Content-Type: text/html\r\n";
make_response << "Content-Length: " << finished_content.length() << "\r\n";
make_response << "\r\n";
make_response << finished_content;
// Transfer it to a std::string to send
std::string finished_response = make_response.str();

// Send the HTTP Response
send(client, finished_response.c_str(), finished_response.length(), 0);  // flag = 0


text: Q: Mapping Im(z)>0 to a shifted circle - Möbius transformation I want to map $Im(z)>0$ to $|z-i|<1$ using a Möbius transformation. I have a simple question regarding that. I know I can choose 3 points on the domain boundary and map them to the circle, but it is quite tedious. Can I know which point will be mapped to the center of the circle $|z-i|=1$? I can then use the preservation of symmetry to find the transformation. I saw somewhere that I can say $f(i)=i$ in this case, but I have no idea why it is ensured $i$ will go to the center of the circle and not any other points inside the $Im(z)>0$ domain.


text:
Q: Dynamically duplicated forms disappear on CodeIgniter reload I have the following code that needs to be duplicated:
<form method="post">

            Name
            <input type="text" id="Name[1]" name="Name[]" />

            Email
            <input type="text" id="Email[1]" name="Email[]" />

    <input type="button" class="confirm add-field-row" value="Add" />
    <input type="button" class="danger delete-field-row" value="Delete" />
    <input type="submit" />

The duplicated / dynamically added elements will have the same names of Name[] and Email[] but their ID's will be incremented.
The JavaScript is below, based from Josiah Ruddell's form duplication script.
var template = $('#field-row-container #field-row-1').clone();
window.addForm = function () {
        var parent = $(this).closest('.dynamic-rows').attr('id');
    var fieldRowCount = countRows(parent) + 1;
    var newFieldRow = template.clone().find(':input').each(function () {
        var newId = this.id.substring(0, this.id.length - 3) + "[" + fieldRowCount + "]";

        $(this).prev().attr('for', newId); // update label for
        this.id = newId; // update id and name (assume the same)
        $(this).closest('.field-row').addClass('new-row');
    }).end()
        .attr('id', 'field-row-' + fieldRowCount)
        .appendTo('#field-row-container');
}
$('.add-field-row').click(addForm);

Whenever I submit the form to CodeIgniter and if there is a validation error, once the controller reloads the multi-part form, the dynamically added elements disappear as well as the values in the initial fields.
How do I go around this problem? I'm at a loss on how to solve this...
Other notes that might help:

*

*This is a component multi-part form with only one form controller

*I have multiple instances of this - Addresses, Education Degrees and such

*I use CodeIgniter's form_validation library to check server-side each array of posts

A: When the page with the form on reloads after the controllers redirects back to it after failing validation, it will only reload the original page, with no DOM manipulations applied.
I would perform the POST request which submits the form via ajax, so you can handle the response without leaving the page. Something like this:
$.post('/locationOfController.php', $('#yourForm').serialize(), function(response){
  if(response.valid){
    window.location.href = '/somewhereAfterFormPosted.php';
  } else {
    $('#yourForm').append("
"+response.error+"
");
  }
}, 'json');

and change the controller to return a JSON object based on whether validation passed or not. To match up with my example above, you would return something like below when an error occurs:
{valid: false, error: 'Please fill out the whole form'}

Try something like that as a basic example. You could do much more, such as returning several errors if multiple fields are invalid.


text:
Q: php wrap specific strings in different tags I get from server some text which looks like
Title ||
text text text
text text text

Title ||
text text text
text text text
text text text
text text text

and I need to add different tags and make it looks like

Title

text text text

text text text

Title

text text text

text text text

text text text

This is my code below
$receipt_ingredients = "Title ||
                    text text text
                    text text text

                    Title ||
                    text text text
                    text text text
                    text text text
                    text text text";

$receipt_ingredients = preg_replace('/^(.*?)\s*[|]{2}/m', '
$1
', $receipt_ingredients);

$receipt_ingredients = '
'.str_replace(array("\r","\n\n","\n"),array('',"\n","
\n
"),trim($receipt_ingredients,"\n\r")).'
';

echo $receipt_ingredients;

but I get structure which looks like

Title

text text text

text text text

Title

text text text

text text text

text text text

text text text

How to get the structure I need?

A: Try using explode(). First explode by empty line, after that by || and by newline char in the end.
First create a mapping array, something like :
$exploded = array('blocks' => array(
0 => array(
    'title' => '',
    'text' => ''
),
1 => array(
    'title' => '',
    'text' => ''
)
));

// Explode and fill array
$exploded = array();
$blocks = explode('\r\n \r\n', $receipt_ingredients); // NOTE you have to check the newline char coming from the db and use that

foreach ( $blocks as $block ) {
    $parts = explode('||', $block);
    $block_array = array(
        'title' => $parts[0],
        'text' => count($parts) > 1 ? $parts[1] : ''
    );

    // You could also simply echo so you do not have to reiterate the array again

    $exploded[] = $block_array;
}

This is one approach, usually I use this one in such situations.


text:
Q: How to build routes only to action and to controller with id? I'm trying to build two routes only to action and to controller with id, keeping the default.
I have to access:

*

*www.mysite.com/MyController/MyAction/{OptionalId}

*www.mysite.com/MyController/{OptionalId}

*www.mysite.com/MyActionFromHomeController

I was able to create routes to work with first and the third point, but not for the second. Current code:
public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "OnlyActionToHomeController",
            url: "{action}",
            defaults: new { controller = "Home" },
            constraints: new { noConflictingControllerExists = new NoConflictingControllerExists() }
        );

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
}

public class NoConflictingControllerExists : IRouteConstraint
{
    private static readonly Dictionary<string, bool> _cache = new Dictionary<string, bool>(StringComparer.OrdinalIgnoreCase);

    public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
    {
        var path = httpContext.Request.Path;

        if (path == "/" || String.IsNullOrEmpty(path))
            return false;

        if (_cache.ContainsKey(path))
            return _cache[path];

        IController ctrl;

        try
        {
            var ctrlFactory = ControllerBuilder.Current.GetControllerFactory();
            ctrl = ctrlFactory.CreateController(httpContext.Request.RequestContext, values["action"] as string);
        }
        catch
        {
            _cache.Add(path, true);
            return true;
        }

        var res = ctrl == null;
        _cache.Add(path, res);

        return res;
    }
}

A: I did!
public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "OnlyController",
            url: "{controller}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
            constraints: new { id = @"\d+" } // define the id parameter needs to be integer
        );

        routes.MapRoute(
            name: "OnlyActionToHomeController",
            url: "{action}",
            defaults: new { controller = "Home" },
            constraints: new { noConflictingControllerExists = new NoConflictingControllerExists() }
        );

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
}

public class NoConflictingControllerExists : IRouteConstraint
{
    private static readonly Dictionary<string, bool> _cache = new Dictionary<string, bool>(StringComparer.OrdinalIgnoreCase);

    public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
    {
        var path = httpContext.Request.Path;

        if (path == "/" || String.IsNullOrEmpty(path))
            return false;

        if (_cache.ContainsKey(path))
            return _cache[path];

        IController ctrl;

        try
        {
            var ctrlFactory = ControllerBuilder.Current.GetControllerFactory();
            ctrl = ctrlFactory.CreateController(httpContext.Request.RequestContext, values["action"] as string);
        }
        catch
        {
            _cache.Add(path, true);
            return true;
        }

        var res = ctrl == null;
        _cache.Add(path, res);

        return res;
    }
}


text:
Q: How come console prints only 1 unique address of integer variable when using address-of operator? I am a university student currently studying computer science and programming and while reading chapter 2 of c++ primer by Stanley B. Lippmann a question popped up into my mind and that is, if computer memory is divided into tiny storage locations called Bytes (8 bits) and each Byte of memory is assigned a unique address, and an integer variable uses up 4 Bytes of memory, shouldn't my console, when using the address-of operator print out 4 unique addresses instead of 1?
I doubt that the textbook is incorrect and that their is a flaw in my understanding of computer memory. As a result, I would like a positive clarification of this question I am facing. Thanks in advance people :)

A:
shouldn't my console, when using the address-of operator print out 4 unique addresses instead of 1?

No.
The address of an object is the address of its starting byte. A 4-byte int has a unique address, the address of its first byte, but it occupies the next three bytes as well. Those next three bytes have different addresses, but they are not the address of the int.

A: Each variable is located in memory somewhere, so each variable gets an address you can get with the address-of operator.
That each byte in a multi-byte variable also have their addresses doesn't matter, the address-of operator gives you a pointer to the variable.
Some "graphics" to hopefully explain it...
Lets say we have an int variable named i, and that the type int takes four bytes (32 bits, this is the usual for int). Then you have something like

+---+---+---+---+
|   |   |   |   |
+---+---+---+---+

Some place is reserved for the four bytes, where doesn't matter the compiler will handle all that for you.
Now if you use the address-of operator to get a pointer to the variable i i.e. you do &i, then you have something like

+---+---+---+---+
|   |   |   |   |
+---+---+---+---+
^
|
&i

The expression &i points to the memory position where the byte-sequence of the variable begins. It can't possible give you multiple pointers, one for each byte, that's really impossible, and not needed as well.

A: Yes an integer type requires four bytes. All four bytes are allocated as one block of memory for your integer, where each block has a unique address. This unique address is simply the first byte's address of the block.


text:
Q: Jenkins and Slack (Jenkins Slack app cannot be used in a script) We want to post messages from Jenkins builds in 2 scenarios:

*

*Post build Step and

*From a python script

Unfortunately, the Jenkins CI app made by Slack ONLY works from Jenkins:
https://my.slack.com/services/new/jenkins-ci
So I can't use that app's credentials in a random python script.
And my own token cannot be used by the Jenkins Plugin, since it ONLY wants the integration token of the Jenkins CI app.
So this is forcing me to use 2 Jenkins CI apps: One from https://my.slack.com/services/new/jenkins-ci to work with the Jenkins Slack Plugin, and my own custom app just to get the token to use in jenkins scripts.
Is there a way to simply use a single Jenkins Slack app for both the Jenkins Plugin AND random scripts?


text:
Q: Validity of using more queries on one try catch? Is valid to use e.g. two query in one try-catch block?
try
{
   $query1 = prepare("SELECT * FROM tbl1...");
   $query2 = prepare("SELECT * FROM tbl2...");
   $query1 = execute();
   $query2 = execute();
}catch (PDOException $e)
{
   print "Error!: " . $e->getMessage();
   return false;
}

OR, it should be:
try
{
   $query1 = prepare("SELECT * FROM tbl1...");
   $query1 = execute();
}catch (PDOException $e)
{
   print "Error!: " . $e->getMessage();
   return false;
}

try
{
   $query2 = prepare("SELECT * FROM tbl2...");
   $query2 = execute();
}catch (PDOException $e)
{
   print "Error!: " . $e->getMessage();
   return false;
}

If both method are accepted and in use are there any differenc between them? (Speed?)
Because I have to do more query in the index but I dont want to separet all

A: Both method are accepted but the first one is more readable. One try catch for the same group of functions is enough.
If one of your calls fails it will stop the bloc execution and go directly to the catch, so putting all in the same try works.
I suspect that in the second way, the compiler might recognize the code in the two catchs as being identical and optimize it as the first one but this should be tried out.

A: If you need different behaviors according to which command failed then you'll need to wrap each (pair) of commands in their own try/catch block.
If all you are worried about is some error happening from any line, then you can wrap all the commands together and handle all exceptions as the same.

A: Both are perfectly valid. As others have stated it's all about the use case.
The only thing I want to add to it is that you may also want to use a transaction. That way you can rollback if for example if the second query fails. Note this is also depended on the use case.

A: It kind of differs in what's your propuse. If one query is dependant of each other, so they should be in on try-catch. If not, if you don't need data from the other and if you think page can go along without the information of the first try-catch, then you can continue your queries.
At least I think this way.

A: I'd say use a single try-catch block as much as possible. If your second query depends on the success of your first query, the second won't be executed if the first throws an exception.
A series of try-catch blocks doesn't make for very readable code, to my eye. A sizable try-catch is OK, as long as you're not going all pokemon-style (gotta catch 'em all)... By that I mean that it's ok to perform 5 queries inside a single try-block, but when you're processing the result of each query in that same block, you're taking things too far.
If you're wondering which is the most efficient approach: catch-blocks are triggered by an instance of the Exception class being thrown. The code inside the catch block is expected to deal with that error, so the script needn't fail completely, and normal service can be resumed.
If you use several try-catch blocks, odds are that snippet of code might throw several Exception instances (PDOException in this case). However "minor" the overhead is, creating a new instance isn't free. If, at the end of the ride you still want to present the user with the data of the queries that were successful and show a notice that some data wasn't retrieved successfully, you need multiple try-catches, if you want to show either everything, or nothing, use 1 try-catch block, and use Exception instance to work out what query failed and present the user with the appropriate error message (or just tell them it's all gone wrong)


text:
Q: Visualization of force-driven large graph: python and graphviz I am working on community detection algorithms, and I am currently trying to visualize the results of Louvain algorithm (https://arxiv.org/abs/0803.0476) on a graph of 70K nodes and 8M edges.
I plotted a smaller graph before (20K nodes, 650K edges) with igraph by taking inspiration from How to plot Community-based graph using igraph for python, and it took almost 30 minutes. Plotting 70K nodes and 8M edges takes 8 hours.
To plot the current graph, due to performance, I moved to sfdp (e.g.,
sfdp foo.dot -Goutputorder="edgesfirst" -Goverlap=false -Tpdf -O). However, I am not able to achieve a good layout to highlight distinct communities by distantiating them. I tried to tune both K at graph level, and len and/or weight at edge level (by setting high values for intra-communities edges, e.g., 1000; and low values for inter-community edges, e.g., 1). sfdp seems to ignore weights. Still, as an extension of fdp, it should not.
Examples on a small graph
igraph + fruchterman_reingold layout

sfdp

Am I missing something? How can I highlight community differences as done in the above link?


text:
Q: Given positive real numbers a and b, prove that $\frac{2}{\frac{a}{x}+\frac{b}{y}} \leq ax + by, x>0, y>0$ I am working through Problem Solving through Problems by Larsons. I am stuck on question 1.8.5b) which is as follows:
"
Given positive real numbers $a$ and $b$ such that $a + b = 1$, prove that
$$\frac{2}{\frac{a}{x}+\frac{b}{y}} \leq ax + by, \ x>0, y>0$$
"
It appears to me that this question has a typo. Given any $a$ and $b$, choose $x = 1$, $y = 1$. Then:
$$\frac{2}{\frac{a}{1}+\frac{b}{1}} \leq a + b \Leftrightarrow  \frac{2}{a+b} \leq a + b \Leftrightarrow \frac{2}{1} \leq 1 \Rightarrow \Leftarrow Contradiction$$
My long-shot hypothesis is that the "$2$" is supposed to be a "$1$". I think that I actually proved this version of the problem (it was how I first realized that something seemed weird in the problem -- won't get into that proof here). However, I am hugely unsure about all of this. It seems very bizarre to me that Problem Solving would have this sort of error, and I suspect that I am just getting something very simple wrong somewhere. Anyone agree with my reasoning or know where I went wrong? Thank you!
Edit: Thought I would drop a link to the original text where the problem appears as above: https://math.la.asu.edu/~ifulman/spring13/mat194/problem-solving.pdf

A: You are right, the problem is wrong. Actually we have
$$
\left( \frac{a}{x}+\frac{b}{y} \right) \left( ax+by \right) =a^2+b^2+ab\left( \frac{y}{x}+\frac{x}{y} \right) \ge a^2+b^2+2ab=\left( a+b \right) ^2=1
$$
which indicates
$$
\frac{1}{\frac{a}{x}+\frac{b}{y}}\le ax+by
$$

A: Note
$$\frac{1}{\frac{a}{x}+\frac{b}{y}} \leq ax + by\tag1$$
is equivalent to
$$ (ax+by)(\frac{a}{x}+\frac{b}{y})\ge1 $$
or
$$ a^2+b^2+ab(\frac{x}{y}+\frac{y}{x})\ge1. \tag2$$
Since
$$ \frac{x}{y}+\frac{y}{x}\ge 2 $$
one has
$$ a^2+b^2+ab(\frac{x}{y}+\frac{y}{x})\ge a^2+b^2+2ab=(a+b)^2=1 $$
which says (2) is true. So (1) is true.

A: This is just Cauchy-Schwarz:
$$1=(a+b)^2=\left(\sqrt{ax} \sqrt{\frac ax} + \sqrt{by} \sqrt{\frac by}\right)^2 \le (ax+by)\left(\frac ax + \frac by\right)$$

A: Actually,
you can get an identity
rather than just
an inequality.
I'll start like FFjet.
$\begin{array}\\
\left( \frac{a}{x}+\frac{b}{y} \right) \left( ax+by \right)
&=a^2+b^2+ab\left( \frac{y}{x}+\frac{x}{y} \right)\\
&=a^2+b^2+2ab +ab\left( \frac{y}{x}-2+\frac{x}{y} \right)\\
&=(a+b)^2+ ab\left( \sqrt{\frac{y}{x}}-\sqrt{\frac{x}{y}} \right)^2\\
&=(a+b)^2+ \frac{ab}{xy}\left(y-x\right)^2\\
&\ge (a+b)^2
\qquad\text{with equality } \iff x=y\\
\end{array}
$
So it doesn't depend on
what $a+b$ is.


text:
Q: Recursively removing fields of type `never` from a type in TypeScript In TypeScript, if an object type contains a field whose type is never, you can't really instantiate an object of the type. Example:
type x = { a: string; b: never };
const xx: x = { a: "asd" }; // property 'b' is missing

I figured it might be useful (actually I mostly thought it would be a fun challenge) to be able to remove all fields that cannot be assigned to, and my solution is:
/** Recursively decays all fields that are of type `never` from `T`.
 * @example DecayNever<number> // yields number
 * @example DecayNever<{ x: number; y: string; z: never }> // yields { x: number; y: string }
 * @example DecayNever<{ x: number; y: { z: never } }> // yields { x: number }
 * @example DecayNever<{ x: number; y: { z: never, w: string } }> // yields { x: number, y: { w: string } }
 * @example DecayNever<{ a: { b: { c: never } } }> // yields never
 */
export type DecayNever<T> = T extends Record<string | number | symbol, unknown>
    ? FilteredKeys<{ [K in keyof T]: DecayNever<T[K]> }> extends never
        ? never
        : Pick<DecayNeverType<T>, FilteredKeys<DecayNeverType<T>>>
    : T;

type DecayNeverType<T> = { [K in keyof T]: DecayNever<T[K]> };

/** Returns a union of all keys of `T` where `T[K]` is not `never` */
type FilteredKeys<T> = { [K in keyof T]: T[K] extends never ? never : K }[keyof T];

type t_1 = DecayNever<number>;
type t_2 = DecayNever<{ x: number; y: string; z: never }>;
type t_3 = DecayNever<{ x: number; y: { z: never } }>;
type t_4 = DecayNever<{ x: number; y: { z: never, w: string } }>;
type t_5 = DecayNever<{ a: { b: { c: never } } }>;

playground link
This does seems to work, though it is very, well, wonky. I'm surprised there isn't a built-in method to do this, but is there a better way to do this? It feels very inelegant, and the check to ensure FilteredKeys<...> is not never is because Pick<T, never> results in the {} type (which I think is somewhat similar to any?).