text:
Q: The actual value of $\phi$ I was reading into the Golden Ratio, and saw that Wikipedia, along with many other more reliable sites, said that the Golden Ratio was equal to $\frac {\sqrt{5}+1}{2}=1.618033\ldots$.
But when I asked my friends that, they said the Golden Ratio was equal to $0.618033\ldots$ or $\phi-1$.
I'm confused at the moment, because the Internet says $\phi=1.618\ldots$ but my friends said $0.618\ldots$. So which value is the correct value?
Note: My friends also claimed that $\frac {1-0.618\ldots}{0.618\ldots}=0.618\ldots$. This seems very interesting.
Doing some basic math, I find that $0.618\ldots=\frac {2}{\sqrt{5}+1}$. While $\phi=\frac {\sqrt{5}+1}{2}$, which is the reciprocal of the other value.

A: According to Wikipedia:
In mathematics, two quantities are in the golden ratio if their ratio is the same as the ratio of their sum to the larger of the two quantities.
Hence we need:
$$\frac{a+b}{a}=\frac{a}{b}=\phi>1$$
$$1+\frac{b}{a}=\frac{a}{b}=\phi>1$$
Notice
$$\frac{a}{b}=\phi$$
Substitute this in and solve to get:
$$\phi=\frac{1 \pm \sqrt{5}}{2}$$
But one of this is negative and as a result of the definition of the golden ration can't be the actual golden ratio.
Thus if we take this definition you are correct.
Furthermore the golden ratio is one solution to:
$$x^2-x-1=0$$
Dividing both sides by $x$ we have:
$$x-1-\frac{1}{x}=0$$
So it shouldn't really be that much of surprise that:
$$\phi-1=\frac{1}{\phi}$$
From where:
$$\frac{1-(\phi-1)}{(\phi-1)}=\phi-1$$
Follows.

A: Both are right depending on how the source defines it.   I usually encounter it as the larger number though.
And yes, $(1.618033\ldots)^{-1} = (0.618033\ldots)$ is the interesting property of the golden ration.
$$\begin{align}
\phi =&~ \dfrac{\surd 5~+1}{2}
\\[2ex] \phi^{-1} =&~\dfrac{2}{(\surd 5+1)}\cdot\dfrac{(\surd 5 -1)}{(\surd 5-1)}
\\[1ex] =&~ \dfrac{\surd5~-1}{2}
\\[1ex]  =&~ \phi-1
\end{align}$$

A: the formal definition of the golden ratio is :

the golden ration $\varphi$ is the positive solution of $$ x^2=x+1$$ and is $$ \varphi=\frac{1+\sqrt5}{2}$$

and so the other solution (the negative one) is :
$$
-\varphi^{-1}=\frac{-1+\sqrt5}{2}=1-\varphi
$$
which explain the confusion

A: The golden ratio is any two nonzero numbers $x$ and $y$ which satisfy the equation $\frac xy=\frac {x+y}{x}$ Defining the ratio $\phi=\frac xy>0$ the equation gives: $\phi=1+\frac 1\phi$. You can then multiply by $\phi$ to obtain $\phi^2=\phi +1$ or $\phi^2-\phi-1=0$. Using the quadratic formula gives a positive solution $\frac {1+\sqrt5}{2}\approx1.618$
It is however a ratio so inverting it ($\frac 1\phi=\frac yx\approx 0.618$) just depends on which two quantities you're comparing. In other words, its a ratio of two quantities so they're both correct. It just depends on the order taken. Think of me asking you to give me the ratio of boys to girls at a school. You could give me $\frac{\text{num.boys}}{\text{num.girls}}$ or $\frac{\text{num.girls}}{\text{num.boys}}$


text:
Q: Keep protect server from stress test or from V-Users I am worried about the trespassers on my site , so my question is that how to keep my server protected from stress test .
I am an Performance tester, so we have a separate server Production Like Server . There we used to do all kind of "Performance testing"  like Stress, Load,and  Endurance Test etc . So here by I want to know how to block a trespasser from putting load on my Live server (Rather than genuine users ) from a particular IP , or how to block the V-USERS(Virtual Users) (LoadRunner/Jmeter/or any other load testing tool) .
We have the servers : IIS 2012 / Famrwork 4.5
Kindly let me know if the question is not clear to you .

A: This is really more of a firewall rule configuration question.  Once you understand what your natural load looks like then consider a rule which automatically blocks IP addresses which are beyond 3/4 standard deviations in traffic.  Bots and performance tests are fairly easy to identify because of the small number of IP addresses generating large amounts of request traffic.
Odds are if you pulled your HTTP request logs today and did a count of requests by IP you would then find quickly that some of the IP addresses fall very quickly to the top of the number of requests.  Examine the user agent strings carefully.  You will likely find patterns.  Use WhoIS to look up the networks that this large users by IP address are a part of.   Engage firewall rules to block or frustrate (random blocking with a 503 for up to 30 minutes at a time, demand captcha, etc...) the appropriate IP addresses.
I know some sites which block all cloud providers because of bots.  I know others which block whole country subnets because of abuse.  I also know some companies that corral the bots and load testers with 503's & Captchas with a great deal of success.  DDOS are much harder as these typically involve hundreds/if not thousands or tens of thousands of hosts.  The requests, however, tend to be substantially similar.  If you can ID them early and you have a CDN, then the web application firewall at your CDN can be a savior to keep the load off of your origin servers

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to remove two sprites in COCOS2d v3.x in ios I'm working with the cocos2d 3.x and Xcode 5.1.1.I'm doing a game like candy crush here
i save the sprites in a array while loading,I compare the touched sprite, previous sprite and swap that sprites,now i want to remove these two sprites?
By the following line i removed the last touched sprite..
    [self removeChild:startSprite cleanup:YES];

A: As LearnCocos2D says, you would call this to remove the sprite from the scene (this is more for the benefit of others since you know this):
[sprite removeFromParent];

Or as you have it you could also remove the child via its parent (this is more for the benefit of others since you know this):
[self removeChild:sprite cleanup:YES];

To remove it from your array you could simply do this:
[array removeObject:sprite];

Or if you only knew the array index the sprite was in the array you could use:
[array removeObjectAtIndex:index];

Note that your array must be an NSMutableArray to use these remove methods.


text: Q: Connecting two laptops as each other external monitors In my working room I have to laptops, one with Windows and another with Ubuntu, and one extarnal screen. Depending on my needs i connect external screent to one of laptops via HDMI. Now I am in my family house and I don't have access to external screen and i would like to use screen of one laptop for another laptop. Once Ubuntu should be host, and once Windows. Is there easy and convienient way to do this?


text:
Q: How to retrieve data from SQL Server using pyodbc and Python? I have a SQL statement that retrieve data from SQL Server using pyodbc package.
The problem is that the query doesn't return all the data instead it return several records.
Example:
CREATE TABLE [dbo].[t1]
(
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [first] [nvarchar](50) NULL,
    [last] [nchar](50) NULL,
    [Rating] [int] NULL,

    CONSTRAINT [PK_t1]
        PRIMARY KEY CLUSTERED ([ID] ASC)
                WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
                      IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

Data:

SQL statement:
advanced_search_term_list =[]
     sql = (
             r"select ID, first, last, Rating "
             r"from dbo.t3 "
             r"where "
             r"(first LIKE CONCAT('%', ?, '%') OR ? IS NULL) AND "
             r"(last LIKE CONCAT('%', ?, '%') OR ? IS NULL) AND "
             r"(Rating = ? OR ? IS NULL)"
          )
    param1 = advanced_search_term_list[0]
    param2 = advanced_search_term_list[1]
    param3 = advanced_search_term_list[2]
    rows = cursor.execute(sql, [param1, param1, param2, param2, param3, param3]).fetchall()

    for row in rows:
              print(row.ID)
              print(row.first)
              print(row.last)
              print(row.Rating)

If the user runs this SQL statement without any user input, the expected output is all the rows.
But instead, it returns these rows only:

A: based on the comments of @Larnu i edit the sql statement by adding for the Rating field parameter = 0 like the below line :
r"(Rating = ? OR ? IS NULL OR ? = 0)"


text:
Q: Vector bundles on henselian schemes Let $X$ be a smooth and projective scheme over $\mathbf{Z}_p$.
We call $\mathfrak{X}$ the ringed space whose topological space is the topological space of the special fiber of $X$, and whose structure sheaf is the henselianization of the structure sheaf $\mathcal{O}^h$ of $X$ along $V(p\mathcal{O}_X)$.
(see for instance here)
$\mathcal{O}^h$ is a sheaf of Noetherian rings and so it's coherent. We say a sheaf of $\mathcal{O}^h$-modules on $\mathfrak{X}$ is a vector bundle if it is locally free of finite local ranks and call $\text{Vect}_{\mathfrak{X}}$ the category of vector bundles on $\mathfrak{X}$.
Reduction modulo $p$ gives a functor
$$\text{Vect}_{\mathfrak{X}}\to\text{Vect}_X$$

Is this an equivalence of categories? Is it essentially surjective?

Note that if $X$ was affine the functor is only essentially surjective, but it does induce bijections on isomorphism classes. This is a property of henselian pairs.

A: I am just posting my comment as an answer.  Reduction modulo $p$ defines a functor from the category of locally free $\mathcal{O}_{\mathfrak{X}}$-modules to the category of locally free sheaves on the closed fiber $X_0$.  This functor is not essentially surjective.  In fact, given an invertible sheaf $\mathcal{L}_0$ on $X_0$, already the obstruction to lift the invertible sheaf modulo $p^2$ is an element in $H^2(X_0,\mathcal{O}_{X_0})$.
For instance, given two smooth, proper, relative curves over $\mathbb{Z}_p$, say $C$ and $D$, such that the closed fibers $C_0$ and $D_0$ happen to be isomorphic, for the fiber product $X=C\times_{\text{Spec}\ \mathbb{Z}_p} D$, for the graph $\Gamma_0$ of the given isomorphism, for $\mathcal{L}_0:= \mathcal{O}_{X_0}(\Gamma_0)$, the obstruction class to lifting $\mathcal{L}_0$ modulo $p^2$ is essentially the "difference of the Kodaira-Spencer classes" of the two families.  There are many similar examples.


text:
Q: When/How does the Empire say Anakin Skywalker died? According to official Imperial records/propaganda, when & how did Anakin Skywalker die?
Given that the identity of Darth Vader is a secret in-universe, we also know that the galaxy at large believes Anakin Skywalker was a Jedi Knight who died during The Clone Wars. What is the "official" location and cause of death for Anakin Skywalker? Official pre-Empire records would have shown he was located on Coruscant when Order 66 was executed, so I imagine some doctoring would be needed to have him killed elsewhere along with the other Jedi. Or perhaps he was supposedly killed at the Jedi Temple massacre?
I'll accept any answer that shows an official location/time/cause of death as per Disney canon or Legends continuity (not Elseworlds/Tales, though).

A: I remember that in the Coruscant Nights Trilogy, Jax Pavan searches for how Anakin died. While all/most the other Jedi have pretty detailed descriptions of how they died, Anakin only has a sentence saying he died on Mustafar. I've been scouring the books for the quote, but I can only find this from "Patterns of Force":

[H]e (Jax) recalled one of the rumors of where and how Anakin was supposed to have died on Mustafar - thrown into the magma stream by...no one knew who.

A: Wookieepedia's article on Anakin cites the Legends novel Luke Skywalker and the Shadows of Mindor regarding the widely accepted story of Anakin's "death". This book was written by Matthew Stover (who also wrote the Revenge of the Sith novelization), so Stover's explanation is likely what Lucas had in mind. @Richard has helpfully provided a quote from the book:

"Kid, in the Clone Wars, everybody knew him. He was the greatest hero
  in the galaxy. When he died, it was like the end of the universe."
  Nick's gut twisted again at the memory. "It bloody well was the end of
  the Republic."
Luke stopped. He looked like something hurt. "When he … died?"
Nick came to a halt gratefully, bending over with hands on his knees
  while he tried to catch his breath. "Way I heard it, he was the last
  Jedi standing in the Temple Massacre—when Vader's Five Hundred First
  went in and killed all the Padawans."
"What?"
"That's where your father was killed: defending children in the Jedi
  Temple. He was not only the best of the Jedi, he was the last. Nobody
  ever told you the story?"
Luke's eyes were closed against some inexpressible pain. "That's … not
  the way I heard it."

This is may not be exactly the Empire's official story for Anakin's "death" since it portrays the stormtroopers in a bad light (killing mere Padawans). However, since this story is widely accepted (Nick is surprised that no one told it to Luke), it's likely that the Empire told everyone that Anakin was just one of many Jedi who died in the attack on the Jedi Temple by the 501st.


text:
Q: IE8 - window.open() - "No such interface supported" When I call window.open() from JavaScript, I get the error dialog with the message "Line: xxx Error: No such interface supported"
Google leads me to websites referring as far back as IE4 saying that I need to run regsrvr32 on several DLLs.
Is there a better solution?
EDIT: exact code requested

<button onclick="windowOpen();return false;">Hi There</button>

EDIT2:
The provided answers all go back to IE4/Win95 days.  I mean, seriously??  Regardless, I disabled Smooth scrolling in IE8 (!!!) and also attempted to register the controls listed in the kb article mentioned by Shoban, but got an error attempting to register shdocvw.dll (The module "shdocvw.dll" was loaded but the entry-point DllRegisterServer was not found.  Make sure that "shdocvw.dll" is a valid DLL or OCX file and then try again.)

A: First of all, try just the following and see if the problem goes away:
OPTION 1
Step 1: Fix IE
Copy and paste the following in the command prompt running as an admin, then press :
"%systemroot%\system32\regsvr32.exe" "C:\Program Files\Internet Explorer\ieproxy.dll"

If you are running 64 bit windows, try this:
"%systemroot%\system32\regsvr32.exe" "C:\Program Files> (x86)\Internet Explorer\ieproxy.dll"
OPTION 2
If the above doesn't work, try the following two steps.
Step 1: Re-register all DLLs
Open a command prompt as an admin. Type the following command:
FOR /R C:\ %G IN (*.dll) DO "%systemroot%\system32\regsvr32.exe" /s "%G"

You will probably get some error windows popping up at this point, just ignore them all and close them when the command prompt stops churning.
Step 2: Fix IE
Copy and paste the following in the command prompt running as an admin, then press :
"%systemroot%\system32\regsvr32.exe" "C:\Program Files\Internet Explorer\ieproxy.dll"

If you are running 64 bit windows, try this:
"%systemroot%\system32\regsvr32.exe" "C:\Program Files> (x86)\Internet Explorer\ieproxy.dll"
Sources:

*

*http://social.technet.microsoft.com/Forums/en-US/w7itproui/thread/99e4ab4f-165d-4691-90dd-ab41a05d26a2

*http://forums.techguy.org/all-other-software/568737-solved-internet-explorer-wont-start.html

A: Check if there are any toolbar installed. I had the same problem and this caused because I run fiddler http debugging proxy

A: On Win10 x64 with IE11 this solved my problem:
    regsvr32 "C:\Windows\SysWOW64\ieproxy.dll"


text:
Q: Comparing skin temperature to environment I have recorded animal skin temperatures (animals kept in fairly constant conditions) over a time period, and also the ambient humidity and temperature at the same time. What test(s) would I use to see if  ambient temp. and humidity may have affected the animals skin temp, and why?
And yes, Im very new to statistics :-(
Many thanks :-)

A: Linear regression is good for you. The animal skin temperatures will be response variable (dependent variable)and ambient humidity and temperature will be covariates (independent variables).
If you get the animal skin temperatures, the ambient humidity and temperature more than one time from the same animal (repeated measurement), you need to consider the correlation between measures. Maybe you can use AR(1) structure to deal with this correlation.
If your animals were in the different cages and one cage had multiple animals, maybe you need to treat the effect of cage as random.


text:
Q: Resolution of Microsoft.Net.Http.Headers assembly version 2.2.0 versus 6.0.0 depends on seemingly unrelated package references While trying to use HeaderNames.XFrameOptions, I found that it works in one of my projects and fails in another. Both are targeting .NET 6.
In my app, I need to work with the X-Frame-Options HTTP header. When possible, for maintainability reasons, I try to evade specifying constants for such standard strings myself, relying on standard constants instead. For this header's name, there is HeaderNames.XFrameOptions, available since ASP.NET Core 3.0.
By navigating to the class's implementation in VS, I found that the project where it works uses version 6.0.0.0 (.NET 6, x64) of the Microsoft.Net.Http.Headers assembly:

C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App\6.0.12\Microsoft.Net.Http.Headers.dll

The project where it does not work uses version 2.2.0.0 (.NET Standard 2.0, MSIL) of the assembly:

C:\Program Files\dotnet\sdk\NuGetFallbackFolder\microsoft.net.http.headers\2.2.0\lib\netstandard2.0\Microsoft.Net.Http.Headers.dll

The working project is the main project of my console app and the broken project is a library in the same solution, directly referenced by the console app.
When I looked into the broken project's obj\project.assets.json, I found that Microsoft.Net.Http.Headers is really used in version 2.2.0 and it is referenced by Microsoft.AspNetCore.Http.Extensions/2.2.0, which is also used in the broken project.
I used that info to reproduce the failure:
dotnet new globaljson --sdk-version 6.0.404 --roll-forward disable
dotnet new console -f net6.0
dotnet add package Microsoft.AspNetCore.Http.Extensions --version 2.2.0
echo "Console.WriteLine(Microsoft.Net.Http.Headers.HeaderNames.XFrameOptions);" > Program.cs
dotnet run

C:\Repos\playground\Program.cs(1,58): error CS0117: 'HeaderNames' does not contain a definition for 'XFrameOptions' [C:\Repos\playground\playground.csproj]
The build failed. Fix the build errors and run again.

I tried adding all the packages referenced by the working project to the repro project and it fixed it! By elimination and following the dependencies of the last remaining project, I found that the fix can be achieved by adding just a single package (AspNetCore.HealthChecks.UI.Client/6.0.5):
dotnet add package AspNetCore.HealthChecks.UI.Client --version 6.0.5
dotnet run

X-Frame-Options

I see that AspNetCore.HealthChecks.UI.Client references the Microsoft.Net.Http.Headers assembly version 6.0.0.0, but directly, as an assembly, not as a NuGet package. Sadly, the latest packaged version is 2.2.0.0.
How can I make HeaderNames.XFrameOptions work in both my projects at the same time? Is installing an irrelevant package like AspNetCore.HealthChecks.UI.Client the only solution? And is there a more straightforward way to diagnose such assembly resolution issues?


text:
Q: Convert a list of lists to array type in Python I have a matrix like this and want to convert it to  array for processing. How to do it
[[25  3  0  1  0  2  1]
 [ 1 21  0  0  0  0  0]
 [ 0  3 18  0  0  0  0]
 [ 1  0  0 35  2  0  0]
 [ 0  0  0  4 27  2  0]
 [ 0  0  0  0  1 27  0]
 [ 1  1  0  0  0  0 34]]

I understand that it should be of the form
[[25,  3,  0,  1,  0,  2,  1],
 [ 1, 21,  0,  0,  0,  0,  0],
 [ 0,  3, 18,  0,  0,  0,  0],
 [ 1,  0,  0, 35,  2,  0,  0],
 [ 0,  0,  0,  4, 27,  2,  0],
 [ 0,  0,  0,  0,  1, 27,  0],
 [ 1,  1,  0,  0,  0,  0, 34]]

Usually what i am doing is convert my array to the above form manually and calling
class = np.array([[28,  3,  0,  0,  5,  2,  1],
 [ 6, 25 , 0,  2,  2,  8,  0],
 [ 0 , 1 ,51 , 0,  0,  0,  0],
 [ 5 , 2 , 0 ,25, 12,  2,  2],
 [ 1 , 0 , 0,  2, 40,  6,  0],
 [ 0 , 0 , 0  ,0,  1, 48,  0],
 [ 2 , 1,  0  ,0 , 1,  1, 51]])

A: I am not sure what format you have when importing the matrix, here a solution for a string based matrix.
from ast import literal_eval

s = '''
[[25  3  0  1  0  2  1]
 [ 1 21  0  0  0  0  0]
 [ 0  3 18  0  0  0  0]
 [ 1  0  0 35  2  0  0]
 [ 0  0  0  4 27  2  0]
 [ 0  0  0  0  1 27  0]
 [ 1  1  0  0  0  0 34]]
'''
s = s.replace(" [","[").replace("[ ","[")
s = ", ".join(s.split())
ast.literal_eval(s)

# Out[12]:
# [[25, 3, 0, 1, 0, 2, 1],
#  [1, 21, 0, 0, 0, 0, 0],
#  [0, 3, 18, 0, 0, 0, 0],
#  [1, 0, 0, 35, 2, 0, 0],
#  [0, 0, 0, 4, 27, 2, 0],
#  [0, 0, 0, 0, 1, 27, 0],
#  [1, 1, 0, 0, 0, 0, 34]]

or in one line:
ast.literal_eval(", ".join(s.replace(" [","[").replace("[ ","[").split()))

A: Assuming that the matrix is stored on a string and it will always be integers, you can do:
import re
import numpy as np

my_list = """
[[25  3  0  1  0  2  1]
 [ 1 21  0  0  0  0  0]
 [ 0  3 18  0  0  0  0]
 [ 1  0  0 35  2  0  0]
 [ 0  0  0  4 27  2  0]
 [ 0  0  0  0  1 27  0]
 [ 1  1  0  0  0  0 34]]
"""

rows = []

for line in filter(len, map(str.strip, my_list.split("\n"))):
    rows.append([ int(v) for v in re.findall(r"\b[0-9]+\b", line) ])

np_rows = np.array(rows)

In that case,
>>> np_rows
array([[25,  3,  0,  1,  0,  2,  1],
       [ 1, 21,  0,  0,  0,  0,  0],
       [ 0,  3, 18,  0,  0,  0,  0],
       [ 1,  0,  0, 35,  2,  0,  0],
       [ 0,  0,  0,  4, 27,  2,  0],
       [ 0,  0,  0,  0,  1, 27,  0],
       [ 1,  1,  0,  0,  0,  0, 34]])


text:
Q: File locked / read-only On a networked computer, I have a file which is coming up as read-only because someone else has it open.  This is not true.  This is a file stored locally on the computer and it is not being used by anyone else.
I can login to the same computer using a different user, and the file opens up fine.  I just get the issue with a particular user account.
Other than deleting that account/profile and creating it again, how can I unlock this file?
Double clicking on this file gives me a message saying

The file is locked for editing by another user, or the file (or the folder in which it is located,) is marked as read-only, or you specified that you wanted to open this file read-only.

I don't think the folder is locked, because I can use other files in that folder fine, it's just 1 particular file which is causing this issue.  I know that only 1 user is using this file as the file is on his c: and the same file works fine if he logs off to allow another user to log in.

A: This doesn't sound like file locking to me. Many applications do not use shared-mode when opening a file, so if the file is open elsewhere (whether or not it is locked), the application will open it as read-only. If the application supports shared-mode, then it can be open in read-write at both locations.

A: You need to run a utility that tells you what is locking the file. Try running the utility here:
http://www.nirsoft.net/utils/opened_files_view.html
It should tell you what has locked the file. Kill that application (if it is possible) to get the file back. There are plenty of alternatives if that application isn't quite right for some reason.
If this fails to say, generally rebooting the PC and trying to access the file straight away will normally work.
If even this fails, it is likely that the disk itself has a problem. In that case, I recommend the use of Spinrite though I'm afraid it isn't free - it is, however, undoubtedly the best disk utility around, it will find and correct errors on disks that are otherwise unusable. You can also run it occasionally to help prevent disk issues.


text:
Q: ASP.Net viewstate questions on form postbacks Let's assume I have a very simple form, with a submit button and a dropdown list.  When I change the list entry and hit submit, at what stage in the postback processing does the viewstate reflect my changed list entry?
According to O'Reilly's Learning ASP.Net 3.5, there are two loads taking place-- one before form validation and another after (diagram on page 266 for those with a copy).
According to the diagram the viewstate is loaded during the first load stage, before the validation.  I assume my changed dropdown is reflected at this point?
Also, according to the diagram, posted data is processed twice, both before and after validation.  Could anyone elaborate a little more on this, and what form processing takes place at each point?
Thanks for the help.  It's a little misty, what takes place when and I'm trying to clear it up a bit.

A: The viewstate is loaded after page initialization but before page load. Validation takes place just before the event triggers for the button that caused the validation.

*

*ASP.NET Page Life Cycle Overview

*Understanding ASP.NET View State

*ASP.NET Validation in Depth


text:
Q: Wildfly 10.1 randomly throws WFLYEJB0241 in methods with LockType.READ I provide some http-API, the average load is about zero, but I can get several requests in a second.
Structure is:

*

*Servlet with only this annotation:
@WebServlet(urlPatterns = "/001")

it injects Stateless EJB (with @EJB annotation)

*Stateless EJB injects Singleton EJB and runs some of it's methods.
Singleton EJB holds sort of a cache (dataset is only 250MB, but when it is loaded in apache's DualHashBidiMap it takes couple of gigabytes, so I've changed Wildfly's maximum heap size to 4GB)
The dataset is static, it is populated on startup in a method
@PostConstruct
@Lock(LockType.WRITE)
void init() {}

all other methods are marked
@Lock(LockType.READ)

But randomly (once a day, sometimes once a week) I get
2017-10-04 13:50:04,793 ERROR [org.jboss.as.ejb3.invocation] (default task-112) WFLYEJB0034: EJB Invocation failed on component NameRewriter for method public java.lang.Integer ejbs.NameRewriter.parse((java.lang.String): javax.ejb.ConcurrentAccessTimeoutException: WFLYEJB0241: EJB 3.1 PFD2 4.8.5.5.1 concurrent access timeout on NameRewriter - could not obtain lock within 30000MILLISECONDS

Methods should be allowed to work concurrently, aren't whey? The most ridiculous thing - when timeouts start to appear, this can continue for several hours! All requests are not served.
My Singleton only fire BidiMap's containsKey , containsValue and get and that's all.
Configuration is:

*

*OS: Centos7.3

*Openjre8 141

*Wildfly 10.1.

I cannot catch the right moment to make a stack dump. Please suggest something to narrow the problem!
P.S. Average processing time for whole request to Stateless EJB is about 10-100 milliseconds. So, I do not understand how it can do something for 30 seconds (even if it was LockType.WRITE). And also I do not have ORM, just MongoDB, it doesn't look as offender.


text:
Q: MEF Framework - How to pass interface to constructor method of a class in MEF I am trying to implement MEF framework in my .Net core and .Net framework application. Here is my sample.
Project One class library:
[Export(typeof(IProductRepository))]

public class ProductRepository : IProductRepository
{

    public ProductRepository(ApplicationDBContext context)
    {
        this.context = context;
    }
}

Project Two class library:
[Export(typeof(IProductService))]

public class ProductService : IProductService
{

    public ProductService(IProductRepository _ProductRepository)
    {

    }
}

So here both project depends on interface injection on constructor, and in another class library i am implementing the MEF like
    [System.Composition.ImportMany]
    public static IProductService ProductService{ get; set; }

    [System.Composition.ImportMany]
    public static IProductRepository ProductRepository{ get; set; }

        var executableLocation = Assembly.GetEntryAssembly().Location;
        var assemblies = Directory
                    .GetFiles(executableLocation , "*.dll", SearchOption.TopDirectoryOnly)
                    .Select(AssemblyLoadContext.Default.LoadFromAssemblyPath)
                    .ToList();
        var configuration = new ContainerConfiguration().WithAssemblies(assemblies);
        using (var container = configuration.CreateContainer())
        {
            ProductRepository= container.GetExport<IProductRepository>();
            ProductService= container.GetExport<IProductService>();
        }

Here I am getting error 'No export was found for the contract 'IProductRepository"IProductService"'
My question is,
how to pass an interface to constructor of class using MEF framework?
how to pass an object to constructor of class using MEF framework?
How to implement MEF when multiple projects are involved?

A: After searching I have found the answer it will goes as,
The repository code should be like below
[Export(typeof(IProductRepository))]
public class ProductRepository : IProductRepository
{
    [ImportingConstructor]
    public ProductRepository(ApplicationDBContext context)
    {
        this.context = context;
    }
}

The service code should be like below
[Export(typeof(IProductService))]
public class ProductService : IProductService
{
    [Import(typeof(IProductRepository ))]
    private IProductRepository productRepository;

    [ImportingConstructor]
    public ProductService(IProductRepository _ProductRepository)
    {

    }
}

And using System.ComponentModel.Composition DLL implement the MEF container part as below
[Import(typeof(IProductService))]
public static IProductService ProductService { get; set; }

[Import(typeof(IProductRepository))]
public static IProductRepository ProductRepository { get; set; }

var catalog = new DirectoryCatalog(GlobalVariables.ApplicationAssemblyPath, "*.dll");
container = new CompositionContainer(catalog);

ProductRepository = container.GetExportedValue<IProductRepository>();
ProductService = container.GetExportedValue<IProductService>();

Hence from the ProductRepository, ProductService  we will get the instance


text:
Q: how to make a drowdown when icon clicked in angular html sass I'm having trouble creating an icon that when clicked appear a dropdown attached just next to the icon. Im using html/sass and typescript (angular):
This is how it should look:
image of how it should look and work
Ty ty very much

A: You can use the official angular material component for menus like yours.
Just change some styles as you need and that's it


text:
Q: Difference in adding a daemon vs non-daemon thread in a java shutdown hook I have seen this discussion in stackoverflow. But it is not clear to me if marking a thread as daemon in ShutdownHook is same as marking it as non-daemon?
Thread t = new Thread(this::someMethod, "shutdown_hook");
t.setDaemon(true);
Runtime.getRuntime().addShutdownHook(t);

Will the behavior be same if I don't do t.setDaemon(true); in the above code.
I am using java 8.

A: There is no difference, whether a shutdown hook Thread is daemon or not.
As the specification for Runtime.addShutdownHook says,

When the virtual machine begins its shutdown sequence it will start
  all registered shutdown hooks in some unspecified order and let them
  run concurrently. When all the hooks have finished it will then run
  all uninvoked finalizers if finalization-on-exit has been enabled.
  Finally, the virtual machine will halt. Note that daemon threads will
  continue to run during the shutdown sequence, as will non-daemon
  threads if shutdown was initiated by invoking the exit method.

and

Once the shutdown sequence has begun it can be stopped only by
  invoking the halt method

JDK implementation follows these rules. As we see in the source code,  runHooks starts hook threads and waits until all of them finish:
    for (Thread hook : threads) {
        hook.start();
    }
    for (Thread hook : threads) {
        while (true) {
            try {
                hook.join();
                break;
            } catch (InterruptedException ignored) {
            }
        }
    }


text:
Q: how to use java 8 stream in a loop and add results in a list I am using Java 8 stream in a loop, and the problem is that the final result is null. When I remove the loop, the final result is okay. And I guess the problem is with the collect part but I have no idea about what to use instead. So, could anyone help me with this? Thanks
public List<Book> updateBooks(String libraryId) {
    List<States> states = new ArrayList<>();
    states.add(States.AVAILABLE);
    states.add(States.BORROWED);
    states.add(States.BLOCKED);
    for (State state : states) {
      books = getBooks(libraryId,state.getValue());
      allBooks = books .getValues().stream().map(book -> {
        Book bookInfo = new Book();
        bookInfo.setId(book.getId());
        bookInfo.setTitle(book.getTitle());
        bookInfo.setState(book.getState());
        bookInfo.setLinks(book.getLinks());
        return pullRequestInfo;
      }).collect(Collectors.toList());
    }
    return allBooks;
  }

A: You don't need to combine a loop and a stream action, you can work wit only streams thanks to flatMap:
List<States> states = new ArrayList<>();
states.add(States.AVAILABLE);
states.add(States.BORROWED);
states.add(States.BLOCKED);
return states.stream()
        .flatMap(state -> getBooks(libraryId, state.getValue())
                .getValues()
                .stream()
        )
        .map(book -> {
            Book bookInfo = new Book();
            bookInfo.setId(book.getId());
            bookInfo.setTitle(book.getTitle());
            bookInfo.setState(book.getState());
            bookInfo.setLinks(book.getLinks());
            return bookInfo;
        })
        .collect(Collectors.toList());


text:
Q: How do you adjust for edge to edge screen without compromising minimum api level in Android Studio I am developing an app, however, I have noticed on phones that have edge-to-edge screens, the black notch at the top blocks out some of the features I've added in (for instance, information on the action bar).
I know there are simple fixes such as using
  <item name="android:windowLayoutInDisplayCutoutMode">
    shortEdges <!-- default, shortEdges, never -->
  </item>

within the activity style, however, I have noticed that the incision of this requires a minimum API level of 27, which is much higher than the minimum of 14 I have been trying to maintain, and I don't want to cut out that high of a percentage of the market.
Do any of you know how to deal with edge-to-edge screen layouts without compromising the minimum API level?

A: I would advise you to just use newer API, as since then new models with notch started showing up on market (thus Android introduced that API), keeping API 14 as min. You can still support older devices without calling non-existing methods from newer APIs. As you have here only one attribute in XML - these aren't resolved on older OS versions, but don't break nothing
PS. Note that before Android introduced this API there was some freshly introduced devices with notch and you don't have any option for proper handling layout on them (too old for API, device manufacturer didn't provide any API either). But most (all?) of them got update to API27, so your issue may occur only on never-updated devices with "experimental" notch


text:
Q: HighCharts polygon label - zoom capable I have a line chart with some background polygons that need labels, much like in this post. However, my chart uses the zoom capabilities of HighCharts.  The chart.events.render will draw new labels on zoom, but it doesn't remove the old ones, which do not zoom either. Using this.customLabel.destroy() doesn't seem to do the job. So I end up with excess labels in the wrong places.  How do I remove the old labels with each new render, or is there now a better way to label polygons?

A: Try this approach:
  chart: {
    events: {
      render() {
        const chart = this;
        if (chart.customLabel) {
          chart.customLabel.destroy()
        }
        chart.customLabel = chart.renderer.label('test label', Math.random() * 200 + chart.plotLeft, Math.random() * 200 + chart.plotTop)
          .css({
            color: '#FFFFFF'
          })
          .attr({
            fill: 'rgba(0, 0, 0, 0.75)',
            padding: 8,
            r: 5,
            zIndex: 6
          })
          .add();
      }
    }
  },

Demo: https://jsfiddle.net/BlackLabel/g1v4dwcn/ - resize the viewer in the jsfiddle to see the effect.
Edit by original poster: see comment about "two different SVG Elements"


text:
Q: Hide the tabbar when keyboard display I got one problem, when i type in editbox the keyboard pop up right.I need that the edit text box should view above of the keyboard.
i have added this in manifest file
android:windowSoftInputMode="stateHidden"

and what i am getting is

and this is what i need

could anybody help me out to hide the tabbar only @Thanks

A: Instead of that.... add the following inside the activity tag of your application manifest.
   android:windowSoftInputMode="adjustResize"

A: add this in your Manifest.xml,  android:windowSoftInputMode="stateVisible|adjustResize|adjustPan"

A: There is an option of disabling auto suggestion which pops out while typing your words.. In some case, you dont require it..
So try this,,
in your .xml file for EditText
android:inputType="textNoSuggestions"

or you can try out programatically like this...
editfield.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);

A: final View activityRootView = findViewById(R.id.RL_main_review);
    activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(
            new OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    int heightDiff = activityRootView.getRootView()
                            .getHeight() - activityRootView.getHeight();
                    if (heightDiff > 100) { // if more than 100 pixels, its
                                            // probably a keyboard...
                        tl_tab.setVisibility(TableLayout.GONE);

                    } else {
                        tl_tab.setVisibility(TableLayout.VISIBLE);

                    }
                }
            });


text:
Q: C# Absolute URI removes ".." from URL I have to upload a file via FTP to ftp://ftp.remoteServer.com
My root directory on remoteServer contains an "upload" and a "download" folder. I need to put my file in the "upload" directory.  But on log in, the server automatically puts me in the "download" folder.
I tried doing this:
string serverTarget = "ftp://ftp.remoteServer.com/";
serverTarget += "../upload/myfile.txt";
Uri target = new Uri(serverTarget);
FTPWebRequest ftp = (FTPWebRequest)FtpWebRequest.Create(target);

using(Stream requestStream = ftp.GetRequestStream()) {
    // Do upload here
}

This code fails with: (550) File unavailable (e.g., file not found, no access)
I debugged the code, and target.AbsoluteUri returns as ftp://ftp.remoteServer.com/upload instead of ftp://ftp.remoteServer.com/../upload  (missing the ..)
If I put ftp://ftp.remoteServer.com/../upload in a browser, I can log in and verify this is the correct place where I want to put my file.
How can I get the FTPWebRequest to go to the correct place?

A: I believe you can encode the dots as %2E to keep the dots in your URI.
So something like:
string serverTarget = "ftp://ftp.remoteServer.com/%2E%2E/upload/myfile.txt";

A: Try this:
string serverTarget = "../upload/myfile.txt";
Uri uri = new Uri(serverTarget, UriKind.Relative);

A: Andy Evans' comment is correct.
Consider the URI: http://ftp.myserver.com/../. The .. means, "take me to the parent of this directory". But there is no parent! So when you derive the absolute URL, you're going to end up with http://ftp.myserver.com/ There is nothing else that the parser can do.
I think the problem is with the configuration of your FTP server. I assume that the directory structure looks something like:
ftproot
    upload
    download

It looks like the FTP service is automatically logging you to /ftproot/download. That is, the URI ftp.myserver.com gets mapped to /ftproot/download on the local file system. If that's the case, no amount of fiddling with the URI is going to get you anywhere. If the URI root is mapped to the download directory, there is no way you can, using the .. syntax, "go up one level and then down."
Are you able to upload using an FTP client such as Filezilla, or perhaps the Windows FTP command line tool? If so, what are the steps you take to do it? Can you make your code do the same thing?


text:
Q: Build a list with a while loop using DataFrame Say we're Amazon, and we receive a customer order in the form of this nested dict down here
order = {"order_id": 123, "requested": [{"product_id": 0, "quantity": 2}, {"product_id": 10, "quantity": 4}]}

Problem: Our boxes have a weight limit. Each box can only fit 1800g of product. Easy enough; I wrote code to perform that check. Where I'm stuck is this little tidbit: If the order can't fit in one box, we're supposed to split the order into multiple boxes until the whole order is shipped. To find weight and other info about each product, we reference this list of dicts:
product_info = [{"mass_g": 700, "product_name": "RBC A+ Adult", "product_id": 0}, {"mass_g": 700, "product_name": "RBC B+ Adult", "product_id": 1}, {"mass_g": 750, "product_name": "RBC AB+ Adult", "product_id": 2}, {"mass_g": 680, "product_name": "RBC O- Adult", "product_id": 3}, {"mass_g": 350, "product_name": "RBC A+ Child", "product_id": 4}, {"mass_g": 200, "product_name": "RBC AB+ Child", "product_id": 5}, {"mass_g": 120, "product_name": "PLT AB+", "product_id": 6}, {"mass_g": 80, "product_name": "PLT O+", "product_id": 7}, {"mass_g": 40, "product_name": "CRYO A+", "product_id": 8}, {"mass_g": 80, "product_name": "CRYO AB+", "product_id": 9}, {"mass_g": 300, "product_name": "FFP A+", "product_id": 10}, {"mass_g": 300, "product_name": "FFP B+", "product_id": 11}, {"mass_g": 300, "product_name": "FFP AB+", "product_id": 12}]

I compare the lists using DataFrame from the Pandas module. Here's my code so far:
import pandas as pd

def split_shipment(order, product_info):
    product_info_df = pd.DataFrame(product_info).set_index("product_id")
    order_df = pd.DataFrame(order["requested"]).set_index("product_id")
    order_weight = order_df.join(product_info_df)[['quantity', 'mass_g']].prod(1).sum()
    product_weights = order_df.join(product_info_df)[['quantity', 'mass_g']].to_numpy()
    shipment = [] #output will be a list of dicts containing order_id and quantities
    #for i in order:
        #shipment.append(product)
        #???
    print(shipment)

If we feed this code the order list at the top, expected output would be:
{"shipment_id": 0, "shipped": [{"product_id": 0, "quantity": 2}, {"product_id":10, "quantity":1}]}
{"shipment_id": 1, "shipped": [{"product_id":10, "quantity":3}]}

Please help, I am so stuck!

A: Not sure why you use pandas - you can do this using simple python with no imports whatsoever:
# ok, 1 import - but that is just for printing convenience ;)
from pprint import pprint

od = {"order_id": 123, "requested": [{"product_id": 0, "quantity": 2},
                                     {"product_id": 10, "quantity": 4}]}

# badly structured - we reformat it into a lookup dict based on product_id
pi = [{"mass_g": 700, "product_name": "RBC A+ Adult", "product_id": 0},
    {"mass_g": 700, "product_name": "RBC B+ Adult", "product_id": 1},
    {"mass_g": 750, "product_name": "RBC AB+ Adult", "product_id": 2},
    {"mass_g": 680, "product_name": "RBC O- Adult", "product_id": 3},
    {"mass_g": 350, "product_name": "RBC A+ Child", "product_id": 4},
    {"mass_g": 200, "product_name": "RBC AB+ Child", "product_id": 5},
    {"mass_g": 120, "product_name": "PLT AB+", "product_id": 6},
    {"mass_g": 80, "product_name": "PLT O+", "product_id": 7},
    {"mass_g": 40, "product_name": "CRYO A+", "product_id": 8},
    {"mass_g": 80, "product_name": "CRYO AB+", "product_id": 9},
    {"mass_g": 300, "product_name": "FFP A+", "product_id": 10},
    {"mass_g": 300, "product_name": "FFP B+", "product_id": 11},
    {"mass_g": 300, "product_name": "FFP AB+", "product_id": 12}]

# better usable lookup
bpi = {dic["product_id"]:dic for dic in pi }

# get a list of all products for scheduling for packing
products = [ bpi[k] for b in ([inner["product_id"]]*inner["quantity"]
                               for inner in od["requested"]) for k in b]

pprint(products)
print()

# packaging
max_w = 1800
# we start with one empty package and remember how much room is left
remaining = { 0 : max_w}
packages = [[]]

# now we schedule stuff, if needed we create a new empty package with appropriate room
# if one item does not fit any already prepared packages
for p in products:
    mass = p["mass_g"]
    done = False
    # look if it fits anywhere
    for i in remaining:
        if remaining[i] >= mass:
            packages[i].append(p)
            remaining[i] -= mass
            done = True
            break
    # does not fit, use new package
    if not done:
        remaining[i+1] = max_w - mass
        packages.append([p])

pprint(packages)

Output:
# order items
[{'mass_g': 700, 'product_id': 0, 'product_name': 'RBC A+ Adult'},
 {'mass_g': 700, 'product_id': 0, 'product_name': 'RBC A+ Adult'},
 {'mass_g': 300, 'product_id': 10, 'product_name': 'FFP A+'},
 {'mass_g': 300, 'product_id': 10, 'product_name': 'FFP A+'},
 {'mass_g': 300, 'product_id': 10, 'product_name': 'FFP A+'},
 {'mass_g': 300, 'product_id': 10, 'product_name': 'FFP A+'}]

# packaging
[[{'mass_g': 700, 'product_id': 0, 'product_name': 'RBC A+ Adult'},
  {'mass_g': 700, 'product_id': 0, 'product_name': 'RBC A+ Adult'},
  {'mass_g': 300, 'product_id': 10, 'product_name': 'FFP A+'}],
 [{'mass_g': 300, 'product_id': 10, 'product_name': 'FFP A+'},
  {'mass_g': 300, 'product_id': 10, 'product_name': 'FFP A+'},
  {'mass_g': 300, 'product_id': 10, 'product_name': 'FFP A+'}]]

You can regroup your data if you want a shorter output.


text:
Q: What does text before selectors in css mean? Apologies for the beginner css question but it's rather difficult to find an answer for this.
I'm looking at the duckett book for html and css and it has a couple of selector syntax confusing to me.
table.one{}
input#web{}

I thought that the .x indicates that x is a class selector and similarly that #x indicates that x is an id selector but why did the author choose to put text before these? He didn't give an explanation as far as I can tell.

A: table.one matches all table elements which have class one.
input#web matches the input element which has id web.
This kind of selector is called "Type selector". You can read these resources:

*

*CSS2.1 spec

*Selectors Level 3

*Selectors Level 4

*MDN article

A: *

*table.one{}
'[element type].[css class name]{}

*input#web{}
'[element type]#[id attribute]{}

When an element type is specified, that means that definition will only work for that element type.
table.myCss{} for the  Element, when class='myCss' then apply the css. Don't apply this CSS to  or any other element type.
Here is a link to the official specifications page for CSS3. http://www.w3.org/TR/css3-selectors/

A: The use of table and input in front of their respective classes / IDs reference the type of element in the markup. For example:
table.one {
  ..
}

References a table with class "one" (in code:
). This way, if the author has another element with class "one" (example:
), the div is not affected by the rule of table.one.
Same idea for input#web, except the selector is targeted towards input tags with ID of "web" (<input id="web">)
Some additional reading from W3 may be of some help (it's from CSS2, but the main points are still present): http://www.w3.org/TR/CSS2/selector.html
DEMO: http://jsfiddle.net/uWkYL/

A: Let me break it down:
table.one means, look for a tag with the name table, which also has the class one
input#web similarly means: look for an element with the name input and the id of web
In some cases, these selectors might not be necessary, especially on IDs, since they are supposed to be unique, as opposed to classes, which are reasuable. The usage of element names with classes, however, can help you make different elements look different than others, for example, if you want to center text and a div, you might only want to use one class for both, but since
 elements are block level, they can't be center like text by default.
div.center {
    margin-left: auto;
    margin-right: auto;
}
p.center {
    text-align: center;
}

A: <input class="x" ... >

So now we have:
.x {} // To select both

input.x {} // To select just the input with class "x"

div.x {} // To select just the div with class "x"

This could be used to just make it more clear for what element the styles are for. Or to limit the elements affected.
Similarly we can do this with element ids.
<input id="a" ... >

So we can write simply #a. Or we can write input#a. Currently these are equivalent.
With the div we would have either #b or div#b.


text:
Q: Java Google chrome decrypt I am trying to decrypt chromes encrypted field, but i get the following exception :-
Exception in thread "main" java.lang.AbstractMethodError: com.sun.jna.Structure.getFieldOrder()Ljava/util/List;
at com.sun.jna.Structure.fieldOrder(Structure.java:868)
at com.sun.jna.Structure.getFields(Structure.java:894)
at com.sun.jna.Structure.deriveLayout(Structure.java:1042)
at com.sun.jna.Structure.calculateSize(Structure.java:966)
at com.sun.jna.Structure.calculateSize(Structure.java:933)
at com.sun.jna.Structure.allocateMemory(Structure.java:360)
at com.sun.jna.Structure.<init>(Structure.java:184)
at com.sun.jna.Structure.<init>(Structure.java:172)
at com.sun.jna.Structure.<init>(Structure.java:159)
at com.sun.jna.Structure.<init>(Structure.java:151)
at com.sun.jna.platform.win32.WinCrypt$DATA_BLOB.<init>(WinCrypt.java:42)
at com.sun.jna.platform.win32.Crypt32Util.cryptUnprotectData(Crypt32Util.java:121)
at com.sun.jna.platform.win32.Crypt32Util.cryptUnprotectData(Crypt32Util.java:103)
at com.sun.jna.platform.win32.Crypt32Util.cryptUnprotectData(Crypt32Util.java:90)
at JPasswordManager.ChromeManager.main(ChromeManager.java:8)

Here is a snippet from my chrome class (Edit here is a sample code note - password field can be some other encrypted field i just quickly set it to that...):-
public static void main(String[] args)
{
  try
  {
    Class.forName("org.sqlite.JDBC");
    connection = DriverManager.getConnection("jdbc:sqlite:\\Users\\Standard User\\AppData\\Local\\Google\\Chrome\\User Data\\Default\\Login Data");
    resultSet = statement.executeQuery("SELECT username_value, password_value FROM logins"); // some encrypted field

    while (resultSet.next())
    {
        byte[] encryptedData = resultSet.getBytes(1);
        byte[] decryptedData = Crypt32Util.cryptUnprotectData(encryptedData);  // exception over here

        StringBuilder decryptedString = new StringBuilder();

        for (byte b : decryptedData)
        {
           decryptedString .append((char) b);
        }

        System.out.println("decrypted = [" + decryptedString + "]");
   }
 }

 catch(Exception e)
 {
    e.printStackTrace();
 }

}

i have also tried converting to hexString and then decrypting, that too did not work in case if you are intrested in knowing how i had converted to hex then here is a method that i coded
public static String ToHexString(byte[] bytes)
{
    StringBuilder sb = new StringBuilder();
    Formatter formatter = new Formatter(sb);
    for (byte b : bytes)
    {
        formatter.format("%02x", b);
    }
    return sb.toString();
}

i used to pass encryptedData variable through this method and then try to cryptUnprotect the data but still it did not work..


text:
Q: Android 8 samsung admob not showing ads I have an application with admob.
It works on all devices, but it doesn't show ads on android 8 samsung devices.
It also works samsung's other versions and other brands all versions including android 8.
I get following error.
2018-10-12 21:21:47.508 13284-31190/? E/Ads: Error waiting for future.
    java.util.concurrent.ExecutionException: java.util.concurrent.TimeoutException
        at com.google.android.gms.ads.internal.util.future.af.get(:com.google.android.gms@14366015@14.3.66 (040300-213742215):18)
        at com.google.android.gms.ads.internal.util.future.g.a(:com.google.android.gms@14366015@14.3.66 (040300-213742215):11)
        at com.google.android.gms.ads.internal.request.service.c.a(:com.google.android.gms@14366015@14.3.66 (040300-213742215):62)
        at com.google.android.gms.ads.internal.request.service.c.a(:com.google.android.gms@14366015@14.3.66 (040300-213742215):169)
        at com.google.android.gms.ads.internal.request.service.f.run(:com.google.android.gms@14366015@14.3.66 (040300-213742215):1)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:457)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
        at java.lang.Thread.run(Thread.java:764)
     Caused by: java.util.concurrent.TimeoutException
        at com.google.android.gms.ads.internal.util.future.m.run(Unknown Source:2)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:457)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:301

For ads, I use following version:
implementation 'com.google.android.gms:play-services-ads:17.0.0'

Manifest File
<?xml version="1.1" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.package.app">

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

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

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".DepartmentCoursesActivity" />
        <activity android:name=".ExamDetailActivity" />
        <activity android:name=".AddLessonActivity" />
        <activity android:name=".LoginActivity" />
        <activity android:name=".CourseExamListActivity" />
        <activity android:name=".ImageZoomActivity"></activity>

        <!-- Sample AdMob App ID: ca-app-pub-3940256099942544~3347511713 -->
        <meta-data
            android:name="com.google.android.gms.ads.APPLICATION_ID"
            android:value="[MY_AD_ID]"/>
    </application>

</manifest>

And also there is following log, it may be related
2018-10-12 21:21:46.618 1764-1764/? E/ServiceUtils: [#MLP#] Unable to get package name: android.content.pm.PackageManager$NameNotFoundException: com.samsung.ipservice (com.samsung.ipservice)
        at android.app.ApplicationPackageManager.getPackageInfoAsUser (ApplicationPackageManager.java:301)
        at android.app.ApplicationPackageManager.getPackageInfo (ApplicationPackageManager.java:272)
        at com.samsung.mlp.platform.utils.ServiceUtils.isPackageAvailable (ServiceUtils.java:55)
        at com.samsung.mlp.platform.framework.ItemFetchTask.buildImageSelectionSchema (ItemFetchTask.java:147)
        at com.samsung.mlp.platform.framework.ItemFetchTask.buildMediaSelectionSchema (ItemFetchTask.java:129)
        at com.samsung.mlp.platform.framework.ItemFetchTask.<init> (ItemFetchTask.java:107)
        at com.samsung.mlp.platform.framework.LPServiceController.setupExecutors (LPServiceController.java:200)
        at com.samsung.mlp.platform.framework.LPServiceController.<init> (LPServiceController.java:179)
        at com.samsung.mlp.platform.framework.LPServiceController.getInstance (LPServiceController.java:168)
        at com.samsung.mlp.platform.LPService.onBind (LPService.java:49)
        at android.app.ActivityThread.handleBindService (ActivityThread.java:3571)
        at android.app.ActivityThread.-wrap2 (null:0)
        at android.app.ActivityThread$H.handleMessage (ActivityThread.java:1791)
        at android.os.Handler.dispatchMessage (Handler.java:105)
        at android.os.Looper.loop (Looper.java:164)
        at android.app.ActivityThread.main (ActivityThread.java:6944)
        at java.lang.reflect.Method.invoke (Method.java:-2)
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run (Zygote.java:327)
        at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1374)

A: Add below code in manifest file
<meta-data android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />

 <activity
        android:name="com.google.android.gms.ads.AdActivity"
        android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"
        android:theme="@android:style/Theme.Translucent" />

Hope this will work...!


text:
Q: what does 'div' in my css code mean? For a long time I was having trouble displaying a button to the right of my input box. On some computers it worked but on other computers and in different resolutions it would be hidden under the input box, so the user couldn't even see it.
My code was something like (using simple_form in Rails):
<%= simple_form_for @review, :url => search_index_path, :method => :post, :html => {:class => 'form-inline'} do |f| %>

etc...etc...
With the help of Stackoverflow my css changed many times - spent days at it - and finally ended up like, which works perfectly:
.form-inline div {
display: inline-block;
margin-top: 5px;
 }

I'm just curious what that 'div' means? For example,
.form-inline {
display: inline-block;
margin-top: 5px;
 }

doesn't work. I thought 'div' is what you put in the markup code, like
whatever
, not in the css. Just curious...

A: This div mean all div's elements in your elements with .form-inline class. They don't need to be children of .form-inline element. They just need to be in it.
Take this as an example:
<form class="form-inline">

a

b

Some text
d

</form>

c

divs "a", "b" and "d" will be formated. div "c" will be not.

A: .form-inline div selector means apply this rule to every div that is a descendent of any element with class form-inline.
So for example:
<my-elem class="form-inline">
   <another-type />

I'll get this CSS rule

   <something-else>

I'll get this CSS rule too

   </something-else>
</my-elem>

HTML element names in CSS are not prefixed like for example classes (with .dot) or IDs (with #hash).

A: It assigns that set of rules to any div inside the .form-inline element and not the .form-inline itself.

A: The div in your code is a part of selector in CSS.
In plain English it would mean select any element/tag that has a class of .form-inline and than select all div's which are the decendants of that element and apply the following rules.
display: inline-block;
margin-top: 5px;

In your case you are using a Descendant Selector
Descendant Selector
The space between the two simple selector is called a combinatory.
Selector Reference

A: There are a lot of css selectors that you can use. You can find all of them here:
http://www.w3.org/TR/CSS2/selector.html


text:
Q: List Items Vertical Align no working for IE 7 8 or 9 I did some research and tried some methods but nothing seems to work for IE.
I have a Vertical List Style Menu. Example would be

Home

Maritime Marinas

My CSS is
ul.menuleft {list-style-type: none; margin:0; padding:0;}
.menuleft li {
    width:248px;
    height:47px;
    background-image:url(images/left-menu-bg-off.png);
    background-repeat: no-repeat;
    margin: 0px;
    padding: 0px;
   line-height:47px;
    text-align: left;
    text-indent: 60px;

   }

.menuleft {text-decoration: none; font-family:Arial Narrow, Arial; color:#FFFFFF; text-shadow: 1px 1px 1px #052f5b; font-size:18px;}
.menuleft a:link {text-decoration: none; font-family:Arial Narrow, Arial; color:#FFFFFF; text-shadow: 1px 1px 1px #052f5b; font-size:18px;}
.menuleft a:visited {text-decoration: none; font-family:Arial Narrow, Arial; color:#FFFFFF; text-shadow: 1px 1px 1px #052f5b; font-size:18px;}
.menuleft a:hover {text-decoration: underline; font-family:Arial Narrow, Arial; color:#FFFFFF; text-shadow: 1px 1px 1px #052f5b; font-size:18px;}
.menuleft a:active {text-decoration: none; font-family:Arial Narrow, Arial; color:#FFFFFF; text-shadow: 1px 1px 1px #052f5b; font-size:18px;}

The text vertically centers perfect for Firefox, Safari and Chrome. But not IE 7 8 or 9 (also not Opera)
Please help. Thank you


text:
Q: C# create hierarchical GridView with Telerik UI for WinForms with SQL Query I tried to create a hierarchical GridView with Telerik UI for WinForms with two SQL queries for getting data.
I found this code example: http://www.telerik.com/help/winforms/gridview-hierarchical-grid-binding-to-hierarchical-data-programmatically.html
But they use a Northwind DataSet. (I will not connect to my SQL database via VS2008 SQL Connection Wizard.)
private void LoadUnboundData()
{
    using (radGridView1.DeferRefresh())
    {
        for (int i = 0; i < nwindDataSet.Employees.Count; i++)
        ...

How can I use my own dataselection via SQLDataReader?
I am working with Visual Studio 2008 using C# and a SQL Express 2012 Server with AdventureWorks database examples.
Suggestions are welcome
Best Regards

A: Here is an article describing how to use data reader: http://www.telerik.com/help/winforms/gridview-populating-with-data-binding-to-datareader.html

A: I am not positive if you'd like to do this "OnDemand" or preload everything at once. You can begin by referring to an answer I provided on the Telerik forum for an OnDemand load and alter it to fit your needs. The logic will use a datatable that you can load from any source like ODBC.
Link: https://www.telerik.com/forums/ondemand-hierarchical-datagrid#Cy41z5kzRUG-44fhLidpeQ
Code Example:
using System;
using System.Data;
using Telerik.WinControls.UI;

namespace example
{
    public partial class frmtest : Telerik.WinControls.UI.RadForm
    {
        private DataTable _parentData = new DataTable();

        public frmtest()
        {
            InitializeComponent();
        }

        private void frmtest_Load(object sender, EventArgs e)
        {
            _parentData = exampleParentDataTableLoad(); // Replace with call to populate a datatable from a query
            loadGridAndParentRecords();
        }

        private void loadGridAndParentRecords()
        {
            exampleRadGridView.DataSource = _parentData;
            var _childTemplate = CreateChildTemplate();
            exampleRadGridView.Templates.Add(_childTemplate);
            _childTemplate.HierarchyDataProvider = new GridViewEventDataProvider(_childTemplate);
            exampleRadGridView.RowSourceNeeded += ExampleRadGridView_RowSourceNeeded;
        }

        private GridViewTemplate CreateChildTemplate()
        {
            GridViewTemplate template = new GridViewTemplate();
            template.AutoSizeColumnsMode = GridViewAutoSizeColumnsMode.Fill;
            template.Columns.Add(new GridViewTextBoxColumn
            {
                Name = "Id",
                HeaderText = "ID"
            });
            template.Columns.Add(new GridViewTextBoxColumn
            {
                Name = "SampleNumber",
                HeaderText = "Sample Number"
            });
            template.Columns.Add(new GridViewTextBoxColumn
            {
                Name = "ParentId",
                HeaderText = "Parent Id"
            });

            return template;
        }

        private void ExampleRadGridView_RowSourceNeeded(object sender, Telerik.WinControls.UI.GridViewRowSourceNeededEventArgs e)
        {
            if (e.ParentRow != null)
            {
                if (e.ParentRow.DataBoundItem is DataRowView rowViewData)
                {
                    var _childDataTable = exampleChildTableLoad(); // Replace with call to populate a datatable from a query

                    var _dataRows = _childDataTable.Select($"ParentId = {rowViewData["Id"]}");

                    foreach (DataRow row in _dataRows)
                    {
                        GridViewRowInfo _newRowObj = e.Template.Rows.NewRow();
                        _newRowObj.Cells["Id"].Value = row["Id"];
                        _newRowObj.Cells["SampleNumber"].Value = row["SampleNumber"];
                        _newRowObj.Cells["ParentId"].Value = row["ParentId"];
                        e.SourceCollection.Add(_newRowObj);
                    }
                }
            }
        }

        private DataTable exampleParentDataTableLoad()
        {
            DataTable _return = new DataTable();
            _return.Columns.Add("Id", typeof(int));
            _return.Columns.Add("DisplayName", typeof(string));

            _return.Rows.Add(1, "Test1");
            _return.Rows.Add(2, "Test2");

            return _return;
        }

        private DataTable exampleChildTableLoad()
        {
            DataTable _return = new DataTable();
            _return.Columns.Add("Id", typeof(int));
            _return.Columns.Add("SampleNumber", typeof(string));
            _return.Columns.Add("ParentId", typeof(int));

            _return.Rows.Add(9999, "Test1", 2);
            _return.Rows.Add(9998, "Test2", 2);
            _return.Rows.Add(9997, "Test3", 2);
            _return.Rows.Add(9996, "Test4", 1);
            _return.Rows.Add(9995, "Test5", 1);
            _return.Rows.Add(9994, "Test6", 1);

            return _return;
        }
    }
}


text:
Q: Import data from existing word document to new one automatically all,
I would like to import data from an existing word document into a new word document automatically based on stored values inside variables.
Eg. var 1 - text 1, var 2 - text 2 etc
I want this variables that have stored text inside to be at one click away (multiple choice boxes)
I've done my research and all I could find is how to import from word to excel, yet I need em to be from word to word.
I'm leaving here what I have already found:
https://stackoverflow.com/questions/16919535/importing-specific-data-from-a-word-to-excel
Any hints would be of great help.
Thank you :)

A: Word has built in functions for what is known as "boiler plate." AutoText and Building Blocks.
See my page on these: Automated Boiler Plate in Word.
You can use the AutoTextList field and / or Building Blocks Gallery Content Control to easily choose and insert snippets of text into your document. Here is a sample template I've prepared comparing these. Either can let you insert pages of information if you have saved it as AutoText or a Building Block.

*

*Here is my writing on the Building Blocks Gallery Content Control.

*Here are two articles on the AutoTextList field:
AutoTextList in the Modern Age by Greg Maxey
How to add pop-up lists to any Word document so you can click your way through changes in seconds by Bill Coan.


text:
Q: Norm of linear operator -- verification This problem seems a bit too easy, so I wanted my answer to be checked.
Question:

Let $\Lambda:C[a,b]\to C[a,b]$ such that $\Lambda f=\int_a^xf(t)dt$ for all $f\in C[a,b]$. Let $\|f\|=^{\ \max}_{a\leq t\leq b}\|f(t)\|.$ Find $\|\Lambda\|$.

My attempt:
Let $f\in C[a,b]$ satisfy $\|f\|=1$. Then $f(t)\leq1$ for all $t\in[a,b]$. Now,
$$
\Lambda f=\int_a^xf(t)dt\leq\int_a^xdt=x-a,
$$
and the equality holds if $f(t)=1$ for all $t\in[a,b]$. Thus,
$$
\|\Lambda\|:=\sup\{\|\Lambda f\|:f\in C[a,b]\wedge \|f\|=1\}=x-a.
$$
Am I missing something, or is it just a simple exercise?

A: Your answer doesn't make sense as written, but has some good steps.  What is $x$?  Be careful to keep track of $x$ as an input from your domain, over which you take the maximum when computing the norm.  Even in the definition it should say $(\Lambda f)(x) = \int_a^x f(t)\,dt$; it is giving the value at a particular $x$.
It is correct that if $\|f\|\leq 1$, then $|(\Lambda f)(x)|\leq x-a\leq b-a$, which implies that $\|\Lambda f\|\leq b-a$, hence $\|\Lambda\|\leq b-a$.  With $f\equiv 1$ you get $\|\Lambda f\|=b-a$, yielding the other direction in the equality $\|\Lambda\|=b-a$.


text:
Q: Failed to create bulk Azure users from Portal I am trying to create bulk Azure users from Portal.
I created a CSV file like My csv file format
When I am trying to upload, I got this error Error1
I found this Document useful Bulk create users in the Azure Active Directory portal - Microsoft Entra | Microsoft Docs and got rid of the error.
File uploaded successfully
But bulk operation status is still pending. After some time, it failed with error like:
Error2
Did anyone face the same issue? Any suggestion is appreciated.
EDIT:
I am getting failure reason as below and status as bad request:
The domain portion of the userPrincipalName property is invalid. You must use one of the verified domain names in your organization.

A: The error usually occurs if you are trying to add users with unverified domain. Check whether the userPrincipalName property is valid or not.
You can check this MsDoc which states the same:

I tried to reproduce the same in my environment by creating a csv file of users with unverified domain like below:

I got the same error when I tried to upload CSV file like below:

Make sure whether the users are having the same domain in their _userPrincipalName_ property like below:

After modifying the _userPrincipalName_ property with verified domain, bulk users created successfully like below:


text:
Q: Appending function to Custom Event in Prototype JS I'm working with a 3rd party product where I am extending the UI with my own custom functionality. Within part of that I need to call an event after the UI has been updated with an AJAX call. Luckily the app fires a call to a Custom Event using the Prototype JS library after the call is complete, like this:
$(document.body).fire("ns:customevent");

If I add my own custom event with the same name then this works as expected
$(document).observe("ns:customevent", function(event) {
    //do custom stuff here
});

[I could not get $(document.body).observe() to work here but I don't think that really matters.]
My concern here is that there may be other parts of the app that have registered functions against that event, and I am (blindly) overwriting them with my own, which will lead to issues further down the line.
Does Prototype append custom functions even though they have the same name or does it in fact overwrite them? If it does overwrite them then how can I append my function to anything that is already existing? Is there anyway of viewing what
I would imagine something like this, but I hardly know Protoype and my JS is very rusty these days.
var ExistingCustomEvent = $(document.body).Events["ns:customevent"];
$(document).observe("ns:customevent", function(event) {
     ExistingCustomEvent();
    //do custom stuff here
});

I can't add my event handler or add in code to call my own function, I want to try avoiding the 3rd party library (if that would even be possible).
Thanks.

A: As an FYI for anyone else that stumbles upon this question, following the comment from Pointy it turns out that Prototype does append the functions to the custom event.
I verified this by trying the following and both alerts fired.
$(document).observe("ns:customevent", function(event) {
     alert("ALERT 1");
});
$(document).observe("ns:customevent", function(event) {
     alert("ALERT 2");
});

Great :)


text:
Q: Search Bar doesn't register input I created a MapView and a SearchBar in a .xib file. I loaded the xib file into a ViewController was testing it in the simulator. The MapView works as it should, but the SearchBar doesn't register any input. Whatever key I press on my keyboard, the SearchBar just shows my cursor and the placeholder text. I used the SearchBar in another project to see if it works there and it does. I can type whatever I want to in there.
I don't know why it doesn't work in my loaded .xib file. Doesn't it work in .xib? I also cleaned and rebuild everything and made sure that user interaction is enabled. I enabled it in code and Xcode.
Here are my attributes for the SearchBar from Xcode. I think everything is right but maybe it helps.

Any ideas?? Thanks in advance!
Edit:
I found out that I'm not only unable to make an input, but also can't add (or see) a scope bar to the SearchBar. Again, I could add it in another project but not in this current one. No matter if the scope bar is enabled or disabled, I can't see it when I click on the SearchBar.

A: It turns out that I had a problem in my SceneDelegate. I still don't understand why and how this error occurred but I somehow missed this in my SceneDelegate:
this.Window = new UIWindow(scene as UIWindowScene);

If you are experiencing the same issue or want to know why, here's another question I've found with the working solution


text:
Q: Saving the current Status of my ProgressBar I'm trying to save the Value in my ProgressBar so if I close the App (terminate it) and run it again, the same value is shown again. I tried this by using sharedpreferences but it's still not saving and I don't know how to solve it. I looked up everything I could find in the Internet but it's always kept very simplistic like "how to save a entertext into txt/xml" but that's not what I'm looking for.
protected void onPause(){
    super.onPause();
    fuelBar = (ProgressBar) findViewById(R.id.fuelProgressBar);
    SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
    incFuel = sharedPref.getInt(FUELBAR, fuelBar.getProgress());
    fuelBar.setProgress(incFuel);
}

public void onResume(){
    super.onResume();
    SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPref.edit();
    editor.putInt(FUELBAR, fuelBar.getProgress());
    editor.commit();
}

public void onStop(){
    super.onStop();
    fuelBar = (ProgressBar) findViewById(R.id.fuelProgressBar);
    SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
    incFuel = sharedPref.getInt(FUELBAR, fuelBar.getProgress());
    fuelBar.setProgress(incFuel);
}

In my onCreate I also have those Variables declared
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();

And in my MainActivity
int incFuel = 0;
final String FUELBAR = "fuelBar";

SharedPreferences sharedPref;
SharedPreferences.Editor editor;

I really have not a single clue what I'm missing and would highly appreciate some help.

A: I can see a few issues.

*

*Firstly, your onStop() is not needed, as the onPause and onResume are sufficient.

*Your onPause and onResume are in reverse. (onResume is called after activity loads, onPause occurs when the activity is closed)

*You also need to set the progress with the loaded value.
Below code should point you in the right direction.
protected void onPause(){
    super.onPause();
    SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPref.edit();
    editor.putInt(FUELBAR, fuelBar.getProgress());
    editor.commit();

}

public void onResume(){
    super.onResume();
    fuelBar = (ProgressBar) findViewById(R.id.fuelProgressBar);
    SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
    incFuel = sharedPref.getInt(FUELBAR, 0);
    fuelBar.setProgress(incFuel);
}

public void onStop(){
    super.onStop();
}


text:
Q: Spring: FactoryBean vs @Configuration I am failing to see the utility of FactoryBean for creating a bean...Why coudn't you create the respective bean in an Configuration class? What need is there for the FactoryBean ?
I know I'm missing something here but I can't figure out what exactly

A: Spring Configuration and FactoryBean classes have something similar but Configuration has not only option to produce beans for container.
@Configuration was created to implement in java everything that was possible to do in xml and even more.
With FactoryBean you can:
1. Create beans using some custom logic
And that is all.
Ref: https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/beans/factory/FactoryBean.html
With Configuration you can:
1. Declare beans without any creational logic.
2. Create beans for container using custom logic(the same as FactoryBean).
3. Declare static beans(see https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#beans-value-annotations)
4. Declare @ComponentScan
5. Declare @PropertySource
6. Import another configuration from java config using @Import
7. Import another configuration from xml using @ImportResource
8. Configuration class may be imported for testing usages(as test config)
....a lot of other usages
Ref: https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/annotation/Configuration.html
And the most significant difference is that @Configuration class is managed by Spring container and all its public methods are proxied.
FactoryBean is not managed by Spring container, it is just a tool to create beans for container.

NB: A bean that implements this interface cannot be used as a normal bean. A FactoryBean is defined in a bean style, but the object exposed for bean references (getObject()) is always the object that it creates.....FactoryBean is a programmatic contract. Implementations are not supposed to rely on annotation-driven injection or other reflective facilities.


text:
Q: casperjs: can't get jquery to use global variables I'm hoping this is a stupid question with an easy answer.
(I've googled for a day and a half without joy)
I am writing a casperjs script which changes a pulldown menu
I've dumbed down the test code to get to the crux of the problem
My test HTML is as follows:
    <html>
    <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    </head>
    <body style="background-color:powderblue;">
    <form>
    <select id="down">
      <option value="volvo">Volvo</option>
      <option value="saab">Saab</option>
      <option value="vw">VW</option>
      <option value="audi">Audi</option>
    </select>
    </form>
    </body>
    </html>

A working Casperjs script using jquery:
casper.start("http://192.168.0.14/test.html", function(){
   //change the pulldown selection
   casper.then(function () {
        this.evaluate(function(){
            $('#down').val('vw').change();
        });
   });

   casper.then(function(){
           this.capture("screen.png");
   });
});
casper.run();

Now I want to parameterise the code, and use variables instead of strings for the selector and the value.   But this code does not work:
var x1='#down';
var y1='vw';

casper.start("http://192.168.0.14/test.html", function(){
   //change the pulldown selection
   casper.then(function () {
        this.evaluate(function(){
            $(x1).val(y1).change();
        });
   });

   casper.then(function(){
           this.capture("screen.png");
   });
});
casper.run();

This shouldn't be difficult (and probably isn't) but all combinations of "window." or square bracket notations have failed me.
jquery is refusing to play nice.
Please help, I didn't think this would put me out of my depth, but it clearly has

A: Try this:-
    this.evaluate(function(x1, y1){
        $(x1).val(y1).change();
    }, x1, y1);

Anything inside evaluate is sandboxed and you will need to pass in any params you want to use inside


text:
Q: C# Bond: Can I have List of custom class in my bond struct? I know lists are supported in Bond, I'm just wondering if we can create class like
class Car
{
    string Model;
    string PlateNumber;

    // ...
}

Can I then have something like this in the bond file?
namespace MyNameSpace
{
    struct Gallery
    {
        0: required List<Cars> AllCars;
    }
}

If it's possible, can anyone please write an example of how the complete bond file should be like?
Also where I should add the class definition to be able to use it like that?
Edit: I need the Car to be a bond struct to be serialized as part of Gallery, so whenever I retrieve Gallery object, I should be able to access and modify the list of cars belongs to it.

A: Since you want Car to be a Bond struct, you can define it in the same .bond file as Gallery and then use it when defining the AllCars field. Here's an example gallery.bond:
namespace MyNameSpace;

struct Car
{
    0: string Model;
    1: string PlateNumber;
}

struct Gallery
{
    // Car needs to be defined/imported before Gallery so it's visible here
    0: required vector<Car> AllCars;
}

Note that Bond's vector field type maps to C#'s List. (Bond's list maps to LinkedList.)
The documentation for the gbc code generation tool talks, albeit briefly, about the types a field definition can have. If you end up needing recursive structs, you'll need to make use of forward declarations and nullable fields.
If you wanted, you could put Car is its own .bond file and then import that .bond file into the one with Gallery. There's an example showing how importing works, if you're interested.


text:
Q: RecyclerView embeded inside a Viewpager - how to enable swiping of viewpager only? My recyclerview items do not need to be swiped. there only for displaying information and clicking to go to a details page but no swipping.  So i'd like to disable swipping on the recyclerview so that the viewpager it is inside of can take the swipe and move to another tab.  The page is pretty simple its just a fragment of recyclerview items inside of a viewPager.
What i have tried so far is using the folling simplecallback:
 ItemTouchHelper.SimpleCallback simpleCallbackItemTouchHelper = new ItemTouchHelper.SimpleCallback(ItemTouchHelper.UP | ItemTouchHelper.DOWN, ItemTouchHelper.RIGHT){

        @Override
        public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {

        }

@Override
public int getSwipeDirs(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
   return 0; //i thought this would disable it but it didn't

}};

How can this be achieved ?

A: You may apply RecyclerView's TouchListener to null.


text:
Q: Case statement saying it appeared before I have these 2 case statements:
case SDLK_w && SDLK_a:
{
    ball.posX -= mers;
    ball.posY -= mers;
    break;
}

case SDLK_w && SDLK_d:
{
    ball.posX += mers;
    ball.posY -= mers;
    break;
}

The second SDLK_w gives me an error saying:

case label value has already appeared in this switch

It may be because case statements don't work with &&, but it only shows me an error at the second W key and not at the first one.
Any suggestions?

A: SDLK_w && SDLK_a is another way of writing 1 because they are both true.
SDLK_w && SDLK_d is also another way of writing 1.
Perhaps you meant this
case SDLK_w:
case SDLK_a: // two case statements in a row: both of them run the same code
{
    ball.posX -= mers;
    ball.posY -= mers;
    break;
}

case SDLK_w:
case SDLK_d:
{
    ball.posX += mers;
    ball.posY -= mers;
    break;
}

but it still doesn't make sense because SDLK_w has two cases.


text:
Q: How to add https-listener to WildFly's default-server? I'm following the tutorial from: https://github.com/jbosstm/quickstart/tree/master/XTS/ssl
Using jboss-cli successfully added the security-realm:
/core-service=management/security-realm=SSLRealm:add()
/core-service=management/security-realm=SSLRealm/server-identity=ssl:add( \
   keystore-path=./standalone/configuration/server.keystore, \
   keystore-password=client, \
   alias=client)

When I try to add an https-listener:
/subsystem=undertow/server=default-server/https-listener=https:add( \
    socket-binding="https", security-realm="SSLRealm" \
)

WildFly throws an exception:
{
  "outcome" => "failed",
  "failure-description" => "JBAS014750: Operation handler failed to complete",
  "rolled-back" => true
}

Any ideas how to add the https-listener?

A: Here is what worked for me on WildFly 8.1:
Add a realm:
[standalone@localhost:9990 /] /core-service=management/security-realm=WebSocketRealm:add()
{"outcome" => "success"}

Configure it:
[standalone@localhost:9990 /] /core-service=management/security-realm=WebSocketRealm/server-identity=ssl:add(keystore-path=websocket.keystore, keystore-relative-to=jboss.server.config.dir, keystore-password=websocket)
{
    "outcome" => "success",
    "response-headers" => {
        "operation-requires-reload" => true,
        "process-state" => "reload-required"
    }
}

Add a new listener:
[standalone@localhost:9990 /] /subsystem=undertow/server=default-server/https-listener=https:add(socket-binding=https, security-realm=WebSocketRealm)
{
    "outcome" => "success",
    "response-headers" => {"process-state" => "reload-required"}
}

And then restart:
[standalone@localhost:9990 /] reload

This added the following fragments to standalone/configuration/standalone.xml:
<security-realm name="WebSocketRealm">
            <server-identities>
                <ssl>
                    <keystore path="websocket.keystore" relative-to="jboss.server.config.dir" keystore-password="websocket"/>
                </ssl>
            </server-identities>
        </security-realm>

and
<https-listener name="https" socket-binding="https" security-realm="WebSocketRealm"/>

What version of WildFly are you using ?

A: I did this by adapting the standalone.xml. As far as I can remember the steps are:

*

*Adding a security realm for the ssl listener
<security-realm name="SSLRealm">
  <server-identities>
    <ssl protocol="TLS">
      <keystore path="keystore-name" relative-to="jboss.server.config.dir" keystore-password="password" alias="alias"/>
    </ssl>
  </server-identities>
  <authentication>
    <truststore path="truststorename" relative-to="jboss.server.config.dir" keystore-password="password"/>
  </authentication>
</security-realm>

*Adding the https-listener to the undertow configuration
<https-listener name="default-https" socket-binding="https" security-realm="SSLRealm" verify-client="REQUESTED"/>

*Adding the socket binding for the https-listener to the list of socket bindings
<socket-binding name="management-https" interface="management" port="${jboss.management.https.port:9993}"/>

I've not yet tried to add this listener using the management interface but the above approach worked perfectly.

A: In my case the keystore that was used in the security-realm was not present when I tried to add the https-listener. After I copied the keystore to the config directory and executed reload in the CLI, I could add the https-listener with the CLI.
Although the CLI does not print out a informative error message, the console tells you that wildfly cannot find the keystore.


text:
Q: What is the correct pom dependency for using jersey webservice? I am using Jersey version 2.12 and I am able to build my project but when I deploy and try to access I get java.lang.AbstractMethodError.
When I remove javax.ws.rs-api-2.0.1.jar jar from my webapp/war lib directory I am able to access the rest end points. Please help me with a correct configuration that I can use with Jersey 2.12 and Jersey multipart together.
Below is the full stacktrace
SEVERE: Servlet.service() for servlet [WebAgent] in context with path [/webagent] threw exception [Servlet execution threw an exception] with root cause
java.lang.AbstractMethodError: javax.ws.rs.core.UriBuilder.uri(Ljava/lang/String;)Ljavax/ws/rs/core/UriBuilder;
    at javax.ws.rs.core.UriBuilder.fromUri(UriBuilder.java:119)
    at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:651)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:847)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:314)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:724)

Below is my pom dependency list
    <dependencies>
    <dependency>
        <groupId>org.glassfish.jersey.core</groupId>
        <artifactId>jersey-common</artifactId>
        <version>2.12</version>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.core</groupId>
        <artifactId>jersey-server</artifactId>
        <version>2.12</version>
    </dependency>
    <dependency>
        <groupId>com.sun.jersey.contribs</groupId>
        <artifactId>jersey-multipart</artifactId>
        <version>1.18.1</version>
    </dependency>
    <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20140107</version>
    </dependency>
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.3.5</version>
    </dependency>
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpcore</artifactId>
        <version>4.3.2</version>
    </dependency>
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpmime</artifactId>
        <version>4.3.5</version>
    </dependency>
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient-cache</artifactId>
        <version>4.3.5</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>3.8.1</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.codehaus.groovy</groupId>
        <artifactId>groovy-all</artifactId>
        <version>2.2.1</version>
    </dependency>
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.16</version>
    </dependency>
    <dependency>
        <groupId>asm</groupId>
        <artifactId>asm</artifactId>
        <version>3.1</version>
    </dependency>
</dependencies>

Update mvn dependency:tree command output below
[INFO] [dependency:tree {execution: default-cli}]
[INFO] com.web:webagent:war:1.0-SNAPSHOT
[INFO] +- org.glassfish.jersey.core:jersey-common:jar:2.12:compile
[INFO] |  +- javax.ws.rs:javax.ws.rs-api:jar:2.0.1:compile
[INFO] |  +- javax.annotation:javax.annotation-api:jar:1.2:compile
[INFO] |  +- org.glassfish.jersey.bundles.repackaged:jersey-guava:jar:2.12:compile
[INFO] |  +- org.glassfish.hk2:hk2-api:jar:2.3.0-b10:compile
[INFO] |  |  +- org.glassfish.hk2:hk2-utils:jar:2.3.0-b10:compile
[INFO] |  |  \- org.glassfish.hk2.external:aopalliance-repackaged:jar:2.3.0-b10:compile
[INFO] |  +- org.glassfish.hk2.external:javax.inject:jar:2.3.0-b10:compile
[INFO] |  +- org.glassfish.hk2:hk2-locator:jar:2.3.0-b10:compile
[INFO] |  |  \- org.javassist:javassist:jar:3.18.1-GA:compile
[INFO] |  \- org.glassfish.hk2:osgi-resource-locator:jar:1.0.1:compile
[INFO] +- org.glassfish.jersey.core:jersey-server:jar:2.12:compile
[INFO] |  +- org.glassfish.jersey.core:jersey-client:jar:2.12:compile
[INFO] |  \- javax.validation:validation-api:jar:1.1.0.Final:compile
[INFO] +- com.sun.jersey.contribs:jersey-multipart:jar:1.18.1:compile
[INFO] |  +- org.jvnet.mimepull:mimepull:jar:1.9.3:compile
[INFO] |  \- com.sun.jersey:jersey-core:jar:1.18.1:compile
[INFO] +- org.json:json:jar:20140107:compile
[INFO] +- org.apache.httpcomponents:httpclient:jar:4.3.5:compile
[INFO] |  +- commons-logging:commons-logging:jar:1.1.3:compile
[INFO] |  \- commons-codec:commons-codec:jar:1.6:compile
[INFO] +- org.apache.httpcomponents:httpcore:jar:4.3.2:compile
[INFO] +- org.apache.httpcomponents:httpmime:jar:4.3.5:compile
[INFO] +- org.apache.httpcomponents:httpclient-cache:jar:4.3.5:compile
[INFO] +- junit:junit:jar:3.8.1:test
[INFO] +- org.codehaus.groovy:groovy-all:jar:2.2.1:compile
[INFO] +- log4j:log4j:jar:1.2.16:compile
[INFO] \- asm:asm:jar:3.1:compile
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESSFUL
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 11 minutes 39 seconds
[INFO] Finished at: Wed Oct 15 17:21:34 IST 2014
[INFO] Final Memory: 22M/315M

A: First things first: Don't mix jersey versions!
Example pom, which is use:
<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <jersey.version>2.12</jersey.version>
</properties>

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.glassfish.jersey</groupId>
            <artifactId>jersey-bom</artifactId>
            <version>${jersey.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

<dependencies>

    <dependency>
        <groupId>org.glassfish.jersey.core</groupId>
        <artifactId>jersey-server</artifactId>
    </dependency>

    <dependency>
        <groupId>javax.ws.rs</groupId>
        <artifactId>javax.ws.rs-api</artifactId>
        <version>2.0</version>
    </dependency>

    <dependency>
        <groupId>org.glassfish.jersey.bundles</groupId>
        <artifactId>jaxrs-ri</artifactId>
    </dependency>

    <dependency>
        <groupId>org.glassfish.jersey.containers</groupId>
        <artifactId>jersey-container-servlet</artifactId>
    </dependency>

    <dependency>
        <groupId>org.glassfish.jersey.media</groupId>
        <artifactId>jersey-media-json-processing</artifactId>
    </dependency>

    <dependency>
        <groupId>org.glassfish.jersey.media</groupId>
        <artifactId>jersey-media-json-jackson</artifactId>
    </dependency>

    <dependency>
        <groupId>org.glassfish.jersey.media</groupId>
        <artifactId>jersey-media-multipart</artifactId>
    </dependency>

    <dependency>
        <groupId>org.glassfish.jersey.media</groupId>
        <artifactId>jersey-media-moxy</artifactId>
    </dependency>

    <!-- ... -->

</dependencies>

Hope this helps, have a nice day.

A: Try to take the same version in all
    <dependency>
        <groupId>com.sun.jersey</groupId>
        <artifactId>jersey-server</artifactId>
        <version>${Jersey version}</version>
    </dependency>

    <dependency>
        <groupId>com.sun.jersey</groupId>
        <artifactId>jersey-servlet</artifactId>
        <version>${Jersey version}</version>
    </dependency>

    <dependency>
        <groupId>com.sun.jersey</groupId>
        <artifactId>jersey-json</artifactId>
        <version>${Jersey version}</version>
    </dependency>

    <dependency>
        <groupId>com.sun.jersey</groupId>
        <artifactId>jersey-client</artifactId>
        <version>${Jersey version}</version>
    </dependency>

    <dependency>
        <groupId>com.sun.jersey</groupId>
        <artifactId>jersey-core</artifactId>
        <version>${Jersey version}</version>
    </dependency>