text:
Q: Stomp over Websocket: Connection is established but messages are not received on the channel. Probably more related to Javascript I implement chat using WebSocket and SockJs in the client and spring-websocket on the server, I have established a connection but when I send a message it never gets to the server - or it appears so based on the lack of log from handling method. It looks like the client (and the coder :P) is at fault here but I cannot spot the mistake.
Client:
import Stomp from 'stompjs';
...
function connect() {
    var socket = new WebSocket('ws://localhost:8080/chat', "v10.stomp");
    stompClient = Stomp.over(socket);
    stompClient.connect({}, function(frame) {
        setConnected(true);
        console.log('Connected: ' + frame);
        stompClient.subscribe('/topic/greeting', function(messageOutput) {
            console.log(messageOutput.body);
            showMessageOutput(JSON.parse(messageOutput.body));
        });
    });
}

function sendMessage() {
    let message = JSON.stringify({"from":"User1", "messageBody":"Connected", "to":''});
    console.log(message);
    stompClient.send("app/greeting", {}, message); // tried to change destination to topic/greeting - with no positive results
}
...

Clients package.json dependencies:
"devDependencies": {
    "css-loader": "^6.7.2",
    "postcss-loader": "^7.0.2",
    "sass": "^1.56.1",
    "sass-loader": "^13.2.0",
    "style-loader": "^3.3.1",
    "webpack": "^5.75.0",
    "webpack-cli": "^5.0.1",
    "webpack-dev-server": "^4.11.1"
  },
  "main": "webpack.config.js",
  "description": "",
  "dependencies": {
    "bootstrap": "^5.2.3",
    "html-webpack-plugin": "^5.5.0",
    "jquery": "^3.6.1",
    "net": "^1.0.2",
    "sockjs-client": "^1.6.1",
    "stomp-websocket": "^2.3.4-next",
    "stompjs": "^2.3.3",
    "websocket": "^1.0.34"
  }

Server:
@RequiredArgsConstructor
@Controller
@Slf4j
class WebSocketController {

    private static final Map<String, String> userToSessionMap = new ConcurrentHashMap<>();
    SimpMessagingTemplate simpMessagingTemplate;

    @MessageMapping("/greeting")
    public void addUserAndNotifyOthers(@Header("simpSessionId") String sessionId, @Payload Message initialMessage) {
        userToSessionMap.put(initialMessage.getFrom(), sessionId);
        log.warn(initialMessage.toString()); // THIS LOG IS NEVER DISPLAYED
        simpMessagingTemplate.convertAndSend("topic/greeting", initialMessage);
    }
...
}

@Data
@AllArgsConstructor
public class Message {
    String to;
    String from;
    String messageBody;
}

@Configuration
@EnableWebSocketMessageBroker
public class WebsocketConfiguration implements WebSocketMessageBrokerConfigurer {

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/chat").setAllowedOrigins("http://localhost:5000");
        registry.addEndpoint("/chat").setAllowedOrigins("http://localhost:5000").withSockJS();
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        registry.enableSimpleBroker("/topic", "/queue");
        registry.setApplicationDestinationPrefixes("/app");
    }
}

LOGS
Web Socket Opened... stomp.js:134:104
>>> CONNECT
accept-version:1.1,1.0
heart-beat:10000,10000

� stomp.js:134:104
<<< CONNECTED
version:1.1
heart-beat:0,0

� stomp.js:134:104
connected to server undefined stomp.js:134:104
Connected: CONNECTED
heart-beat:0,0
version:1.1

index.js:32:17
>>> SUBSCRIBE
id:sub-0
destination:/topic/greeting

� stomp.js:134:104
SENDING:  {"from":"User1","messageBody":"Connected","to":""} index.js:54:13
>>> SEND
destination:topic/greeting
content-length:50

{"from":"User1","messageBody":"Connected","to":""}�
// END OF LOGS: I never get Received log


text:
Q: cakephp and paypal - how do I check if a user on my site is using a valid paypal email address? Firstly I know that there is a lot of documentation on the paypal website but it's all very confusing and not necessarily related specifically to cakephp.
I've never built an app using paypal before and I'm a bit green with cakephp too! So I'm really confused and in need of a kindly soul to provide a little direction.
I'm trying to build a site where users can sign up and create a profile with me. They will then be able to receive payments from 3rd parties straight into their paypal accounts (with a little commission going to me)
I understand I need to use the Adaptive Payments API and that what I want to do is possible somehow - haven't quite figured it out just yet. However, the first thing I need to do is when the user signs up to my site I want to connect up their email address with their paypal account to make sure that they do actually have a paypal account. IE when someone clicks sign up, my app connects with paypal and links their profile on my site with their paypal account.
Can someone suggest how I might go about doing this?
Eternally grateful
Sarah :)
ps I've seen this cakephp plugin mentioned a fair bit - would it be of any use to me? http://bakery.cakephp.org/articles/aniljmk/2010/08/19/paypal-gateway-integration-complete-solution

A: Good luck with your adventures into Cake!
But, the very first thing I'd do before you go any further...get used to your framework of choice.  If Cake really is the framework you're going to use then get to know it, use it, love it, hate it, figure out how it's doing what it's doing.
Read the book, all of it.  Too often a question on SO about Cake is plainly answered in Cake's documentation.
Don't fight the framework!  Another thing I see all too often are people breaking Cake's "automagic" for seemingly no reason.  I know that certain applications are going to be built using an existing database but if you're building a new application don't try to mold Cake into your own flavor.  Instead make sure you're using the conventions Cake has set out, your life will be significantly less stressed out.
After you're familiar with things like, skinny controllers and fat models, creating and using controller components, view helpers, view elements and model behaviors then you should move on to working with PayPal payment authorization.  Being a self-taught programmer I can tell you right now that until you get the framework under your belt you are biting off more then you can chew.
All of that being said...
I have limited use with the PayPal API so I'm not sure this is going to be of assistance and might not be what you're looking for but apparently PayPal has an API operation called AddressVerify that might help you do what you're wanting to do.
I hope this proves useful, if you have any other questions or need to clarify how AddressVerify doesn't solve your problem let me know and I'll take another stab at it.

A: I have used Paypal in my Cake app before, but just to receive payments, nothing fancy. This is the first time I hear about the Adaptive Payment API. From what I just read, it seems pretty complicated. And if you are not completely comfortable with Cake yet, this is gonna be a very difficult task.
If you just want to learn, I'd suggest horn your CakePHP skill first, then come back to this later. But if you need this for business purpose, getting someone who has done this would be the best way to do.

redpajama_set_name: RedPajamaStackExchange


text:
Q: RATE() is returning "#NUM!" I am trying to calculate the rate of an annuity that costs $100,000 and pays $50,000 per year for 23 years. I am entering this into Excel as:
=RATE(23, 50000, -100000)

but this results in:
#NUM!

What am I doing wrong? The cell is a percentage, and I am entering the numbers in manually. I am using Excel (Mac) 2007.

A:
If the successive results of RATE do not converge to within 0.0000001 after 20 iterations, RATE returns the #NUM! error value.

Without including a guess for the Guess it is assumed to be 10 percent and that is nowhere near the actual rate that would be required to equate $100k now to $50k pa for 23 years.
Try:
=RATE(23,50000,-100000,,,0.4)

and then either:
=RATE(23,50000,-100000,,,0.45)

or
=RATE(23,50000,-100000,,,0.6)


text:
Q: glBindVertexBuffer vs glBindBuffer I see that I can bind a vertex buffer using glBindBuffer(GL_ARRAY_BUFFER, vbo);.  This works, and I can also bind an element array using glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);.  When using these everything draws as desired.
In reading the OpenGL 4.4 specification in section 10.3.1 I find mention of glBindVertexBuffer.  It looks like this permits binding multiple vertex buffers and then having them all rendered at once.  Is this correct?  Also, how does it differ from using glBindBuffer?  Can you use an element array buffer when binding vertex buffers with this?

A: Actually, the point of glBindVertexBuffer (...) is entirely different.
The idea when it was introduced in GL_ARB_vertex_attrib_binding was to separate the fixed mapping that has always existed between vertex buffer and pointer and replace it with a more flexible system that allows you to setup a format for a vertex attribute, a binding location for the vertex buffer/attribute to use and then simply swap out the buffer bound to that location.
You will not simply be replacing a call to glBindBuffer (...) with this new function, you have at least two other functions you need to call to setup a generic vertex attribute to be able to take advantage of glBindVertexBuffer (...):

*

*glVertexAttribFormat (...) - This is effectively the same thing as glVertexAttribPointer (...) except it does not setup a pointer, it merely establishes how the buffer that will be paired with this attribute is to be interpreted.

*glVertexAttribBinding (...) - This associates the generic attribute location with a new type of binding location (vertex buffer binding) so that you can use glBindVertexBuffer (...) to bind your VBO to a location this attribute will use.

*glVertexBindingDivisor (...) - This is a replacement for glVertexAttribDivisor(). This replacement respects the binding association between the Vertex Attribute index and the Binding Slot index made by glVertexAttribBinding(...). This is worth pointing out because it's name is somewhat out of form with the other two functions listed above, while the older glVertexAttribDivisor() appears more in-form, but is the wrong function to use.

To put this into perspective, I have included some pseudo-code from the extension specification that shows how glVertexAttribPointer (...) works in relation to this new API addition.
The commands:
void glVertexAttribPointer (GLuint index, GLint size, GLenum type,
                            GLboolean normalized, GLsizei stride,
                            const GLvoid *pointer);
void glVertexAttribIPointer (GLuint index, GLint size, GLenum type,
                             GLsizei stride, const GLvoid *pointer);
void glVertexAttribLPointer (GLuint index, GLint size, GLenum type,
                             GLsizei stride, const GLvoid *pointer);

Control vertex attribute state, a vertex buffer binding, and the mapping between a vertex attribute and a vertex buffer binding.
They are equivalent to (assuming no errors are generated):
if (no buffer is bound to GL_ARRAY_BUFFER and pointer != NULL)
{
    generate GL_INVALID_OPERATION;
}
glVertexAttrib*Format (index, size, type, {normalized, }, 0);
glVertexAttribBinding (index, index);
if (stride != 0) {
    effectiveStride = stride;
} else {
    compute effectiveStride based on size/type;
}
GL_VERTEX_ATTRIB_ARRAY_STRIDE[index] = stride;
// GL_VERTEX_BINDING_STRIDE will be set to effectiveStride
// by glBindVertexBuffer.
glBindVertexBuffer (index, <buffer bound to GL_ARRAY_BUFFER>,
                 (GLchar *)pointer - (GLchar *)NULL, effectiveStride);

It is a little difficult to wrap your head around at first, but what it boils down to is very similar to the separation of sampler state from Texture Objects when Sampler Objects were introduced in GL 3.3. You can continue using the old API, but this alternative solution gives you some more flexibility.
Regarding element array buffers, no. This new part of the API has nothing to do with that, because Vertex Array Objects actually manage the one-and-only element array buffer binding.

A: Not really. glBindVertexBuffers
is used for binding multiple vertex buffers. As for glBindVertexBuffer, it is used for binding a buffer to a vertex buffer. You may have to call it many times to bind multiple vertex buffers.
You can check their documentation here:
http://www.opengl.org/sdk/docs/man/xhtml/glBindVertexBuffers.xml


text:
Q: Comparing the growth rates How can I go about comparing the growth rate of the following functions?
$$\sqrt n,\quad
10^n,\quad
n^{1.5},\quad
2^{\sqrt{\log n}},\quad
n^{5/3}.$$
I am looking for a more generic answer on how do we go about comparing growth rate of functions and a small example demonstrating it on this set of functions would be really helpful.Any links or references explaining the topic would also be very helpful.

A: Generically: exponentials beat positive powers; larger (positive) powers beat smaller (positive) powers; (positive) powers beat logarithms.
Among exponentials, you can always convert them all to the same base and compare exponents; larger exponents beat smaller ones. Same for logarithms.
So you know that $10^n$ will grow the fastest; with $2^{\log n}$ you have to be careful, because it looks exponential, but an exponential raised to a logarithm is actually not exponential:
$$2^{\log n} = e^{(\log n)(\log 2)} = (e^{\log n})^{\log 2} = n^{\log 2},$$
so this is actually just a power.
Among the powers, you have $n^{1/2}$, $n^{\log 2}$, $n^{1.5}$, and $n^{5/3}$. Comparing the exponents, we have
$$\frac{1}{2}\lt \log 2 \lt 1.5 \lt \frac{5}{3}$$
so that's the order of growth of the functions. So we have (with $\succ$ meaning "grows faster than")
$$10^n \succ n^{5/3} \succ n^{1/5} \succ 2^{\log n}=n^{\log 2} \succ \sqrt{n}.$$


text:
Q: depmixs4 list of state estimates I have fitted a time series of data to a Hidden Markov model using the fit(depmix()) functions in the package depmixs4. I want to obtain a time series of estimated states, where the estimate for state x is the mean value assigned to state x. Currently, I'm only getting a times series of values that say the index of the state (e.g. 1,3,5,2,5...).
This is my current code:
set.seed(9)
hmm9 <- depmix(volume ~ 1, data=data.frame(volume), nstates=9)
fitted_hmm9 <- fit(hmm9)
summary(fitted_hmm9)
state_ests9 <- posterior(fitted_hmm9)
state_ests9[,1]
The last part, state_ests9[,1], is the time series of state indices, while the actual expected values for states are stored somewhere in summary(fitted_hmm9).

A: By "estimated state" I assume you want the predicted response (i.e. "volume") according to each state. To get state-wise predicted values for responses, you can use the predict method, which however needs to be called on the response sub-model, which is somewhat hidden in the fitted depmix object.
In a fitted depmix object, there is a slot called "response", which is a list of lists, structured as
fitted_model@response[[state_id]][[response_id]]
In your case, I think "volume" is univariate, so that there is a single response and response_id is always 1. For a model with 9 states, state_id would vary from 1 to 9.
The following code (including randomly generated values for "volume" to make it reproducible) gives you what you want (I think):
set.seed(123)
volume <- rnorm(10000)

hmm9 <- depmix(volume ~ 1, data=data.frame(volume), nstates=9)

fitted_hmm9 <- fit(hmm9)

summary(fitted_hmm9)

state_ests9 <- posterior(fitted_hmm9)

state_ests9[,1]

# construct matrix for state-dependent predictions
pred_resp9 <- matrix(0.0,ncol=9,nrow=nrow(state_ests9))
# fill matrix column-wise by using the "predict" method of
# corresponding response model
for(i in 1:9) {
  pred_resp9[,i] <- predict(fitted_hmm9@response[[i]][[1]])
}
## use MAP state estimates to extract a single time-series
## with predictions
pred_resp9[cbind(1:nrow(pred_resp9),state_ests9[,1])]


text:
Q: Is it the chiral anomaly which is solely responsible for having instanton effects (and therefore, the $\theta-$term) in the QCD action? $\textbf{Fact 1}$ In principle, the QCD Lagrangian should contain a Lorentz invariant, gauge invariant, dimension-4 term $\sim\theta \text{Tr}[F^{\mu\nu}\tilde{F}_{\mu\nu}]$. This term, however, is usually neglected in classical physics because it is a total divergence, and therefore, cannot affect the equations of motion. However, when instanton effects are included, it turns out that the QCD action should be augmented by this term. This is explained, for example, in the book Quantum Field Theory by Mark Srednicki at the pages 598-599.
$\textbf{Fact 2}$ The part of the QCD Lagrangian with $u$ and $d$ quark, in the massless limit of $u$ and $d$, has a $U(1)$ axial anomaly $$\partial_\mu j^{\mu 5}=-\frac{g^2}{16\pi^2}\epsilon^{\alpha\beta\mu\nu}F_{\alpha\beta}^a F_{\mu\nu}^a\sim \text{Tr}[F\tilde{F}]$$ where $j^{\mu 5}=\bar{Q}\gamma^\mu\gamma^5 Q$ and $Q=\begin{pmatrix}u\\d\end{pmatrix}$. This anomaly term is exactly same in form as the term included in the QCD action by instanton effects.
Question This uncanny similarity strongly provokes me to guess that this anomaly is solely responsible for inducing the $\theta-$term $\sim\theta \text{Tr}[F^{\mu\nu}\tilde{F}_{\mu\nu}]$ to the QCD action. In other words, if the current $j^{\mu 5}$ were conserved or anomaly-free i.e., $\partial_\mu j^{\mu 5}=0$, the term $\sim \theta \text{Tr}[F^{\mu\nu}\tilde{F}_{\mu\nu}]$ to QCD action can always be dropped and instanton effects will not be present.
Is this the correct way to think about this striking correlation between fact 1 and fact 2? I'm doubtful because while discussing instantons of Yang-Mills action, in pages 590-599, Srednicki doesn't talk about anomalies at all.

A: Even assuming the presence of fermions (because in other case the anomaly doesn't exist), the $\theta$-term isn't related to chiral anomaly. It appears because of:

*

*non-trivial topology of the QCD gauge group, leading to the statement that there are topologically inequivalent vacua which can be parametrized by the winding number $n$

*Cluster decomposition principle, which requires the true vacuum be the sum over all non-trivial vacua with the weight $e^{in\theta}$
See also this question. By using the expression for the winding number $n$ in terms of the integral over the gauge configurations, the weight $e^{in\theta}$ can be written as the additional term in the effective action. The latter is $\theta$-term.
The axial anomaly mentioned in your question appears because of the different reason, namely, the absence of the renormalization scheme preserving both the gauge symmetry and global axial symmetry. Fundamentally it is formulated in terms of local equation. It appears in all gauge theories, independently on whether the $\theta$-vacuum exist. However, being integrated over the space-time, the anomaly equation
$$
\partial_{\mu}J^{\mu}_{5} \sim \text{tr}[F_{\mu\nu}\tilde{F}^{\mu\nu}]
$$
can be represented as
$$
n_{+} - n_{-} = \nu,
$$
where $n_{\pm}$ are number of zero left and right modes of the Dirac operator $D = \gamma_{\mu}(i\partial^{\mu} - g_{s}G^{\mu})$, and $\nu \sim \int \text{tr}[F_{\mu\nu}\tilde{F}^{\mu\nu}]$. Since the left hand-side is integer, the right hand-side also has to be integer. This is indeed the case because it can be represented as the difference of the winding numbers for $t = +\infty$ and $t = -\infty$.
See also the similar question.


text:
Q: Spring-pendulum The planar spring-pendulum is modeled by the set of equations
$$m\ddot{r}=mr\dotθ^2 + mg\cos\theta − k(r − L)$$
and,
$$r^2\ddot{\theta}= −2r\dot r\dotθ − gr\sin\theta$$
First we should define the angular momentum by $p_\theta = mr^2\dot\theta$ and the radial momentum by $p_r = m\dot r$ and rewrite the spring-pendulum system as a set of four first-order ODEs for $x = (r, \theta , p_r, p_\theta )$.
So I did like this, but I don't know if it's correct:
$$\dot r = p_r/m, ~\dot\theta=p_\theta/mr^2$$
and,
$$\dot p_r = mr\dot\theta^2 + mg\cos\theta - k(r-L)$$
and,
$$\dot p_\theta = m(-2r\dot r\dot\theta - gr\sin\theta)$$
Now I have to find the equilibrium solution(s), $x_{eq}$ , of the equations, i.e., those solutions for which $x$ is constant.
How do I find these solutions?

A: By the product rule,
$$
\dot p_θ=\frac{d}{dt}(mr^2\dotθ)=2mr\dot r\dotθ+mr^2\ddotθ=-mgr\sinθ
$$
With your definitions you should also eliminate all of $\dot r, \dotθ$ for $p_r, p_θ$ from the final form of the equations.

A: Actually, we should have  $\dot{p}=-mgr\sin\theta$ and then, put all the first order ODE to $0$, and then the equilibrium result should be
$$
r=\frac{mg}{K}+L;
$$
$$ \theta=n\pi;$$ and finally
$$ p_r=p_\theta=0$$


text:
Q: Get PHP echo data to be captilized So I've successfully managed to get a movie title and video title to display via the following code. My question is how do I force the first letters of the output to be captilized?
I know is CSS you would do something along the lines of {text-transform:capitalize;} but how do you implement this sort of thing in PHP?
<?php echo  $movtitle.' '.$vidtitle;?>

A: http://php.net/manual/en/function.ucwords.php
You could've googled that easily!

A: It sounds like you're looking for the ucwords() function in PHP.

A: If you want to upper case the first character of each word, use ucwords, or you can use ucfirst (for just the initial character in the string) or strtoupper to upper-case the entire string.
Incidentally, it's worth getting to know the various PHP string functions (and indeed array functions), as time invested in this now will pay dividends later.

A: <?php echo  ucwords($movtitle.' '.$vidtitle);?>


text:
Q: Asymmetric simple random walk. For an asymmetric simple random walk (the probability $p$ of a positive increment is not equal to the probability $q$ of a negative increment), it is true that the probability of ever reaching $+1$ is $p/q$ provided that $p < q$ (equivalently, $p < 1/2$). Apparently there is an easy argument which explains why, given this fact, the probability of ever reaching $n$, for a positive integer $n$ is $(p/q)^n$. I can't really determine what the argument is, though. I assume it will have to do with independence/Markov property of the random walk?

A: Let $P_n$ denote the probability of ever reaching $n$ and let $\tau_n$ denote the corresponding hitting-time of $n$. Then $P_{n+1}=P(\tau_{n+1}<\infty|\tau_{n}<\infty)P(\tau_{n}<\infty)$, since if $\tau_{n}=\infty$, you couldn't possibly reach $n+1$. By definition, this implies $P_{n+1}=P(\tau_{n+1}<\infty|\tau_n<\infty)P_n$. By the markovian property of hitting times, this is equivalent to $P_{n+1}=P(\tau_1<\infty)P_n$. In other words, after the walk hits $n$, it effectively restarts and now needs to hit $n+1$, which is distributionally equivalent to $\tau_1<\infty$.
From this it follows that $P_{n}=P_1^n$.

A: To ever reach $n$, you need to successfully move a net distance of $1$ to the right $n$ times. Each attempt to do so is independent, and they all have the same probability by the homogeneity in space, so the probability of ever reaching $n$ is $r^n$ where $r$ is the probability to ever move a net distance of $1$ to the right. If you take the result $r=\min \{ 1,p/q \}$ as a black box, then this gives your desired result.
Alternatively, you can derive it using a recurrence relation. Define $u_m(x)$ to be the probability to hit $n$ before hitting $m$ starting from $x$ between $m$ and $n$ inclusive. Then $u_m(n)=1,u_m(m)=0$, and for $m<x<n$ you have $u_m(x)=pu_m(x+1)+qu_m(x-1)$, which you can prove using the total probability formula. This recurrence relation with boundary conditions can be explicitly solved; the desired quantity is $\lim_{m \to -\infty} u_m(0)$.


text:
Q: What are static methods? How and when are they used? I am looking for information about static methods in C++.
I searched but honestly was not able to clearly understand a thing.
Are static functions those functions which contain static data members only?

A: Static methods of a class have no this pointer.  That means they cannot access instance member data.  Methods (static or otherwise) do not contain data members.  (They can declare variables on the stack or heap, however.)
Static methods are usually called with the class name (myClass::foo()) since you don't have to declare an instance of the class to use them, but can be called with the instance (myInstance.foo()) also.

A: Static methods in a C++ class, like those for a Java class, are methods that are available without having to actually instantiate an object or an instance of the class.
The only way to use the standard, non-static methods of a class is to create an object or instantiate an instance of the class.  Then when you use the methods you are operating on a particular object or instance of the class.
There are some restrictions on a static method.  For instance, you can not use the this pointer in a static method.  This is because a static method of a class is not associated with a particular, specific object.  It is instead a general method that is not tied to any particular object.
The way I think of a static method in a class is that when I do so I am creating a particular namespace, the class name, and then adding a function that can only be accessed by using that particular namespace.
A static variable within a class is created at application startup and can be accessed without having a particular instance of the class created.  A static variable is also shared by all instances of the class.
So for an example of the differences (off the cuff so there may be compile errors):
class myAclass {
public:
  myAclass();     // constructor
  void function1 (int iValueSet);   // a standard method
  static void functionStatic (int iValueSet);  // a static method
private:
  int iValue;                // an object specific variable
  static int iValueStatic;   // a class general variable shared by all instances of this class
};

int myAclass::iValueStatic = 0;  // init the class static variable

    myAclass::myAclass () : iValue (0)
{
}

void myAclass::function1 (int iValueSet)
{
   iValue = iValueSet;    // set the iValue for this particular object
   iValueStatic = iValueSet;  // set the shared iValueStatic for all instances
}

void myAclass::functionStatic (int iValueSet)
{
//    iValue = iValueSet;   // ERROR this is not allowed as iValue is not static
    iValueStatic = iValueSet;   // works since iValueStatic is static
}

And then how this class could be used:
myAclass jj;    // create an object instance

jj.function1(5);   // access the non-static method to change the object data

myAclass::functionStatic(8);  // set the static iValueStatic

And of course since struct is similar to class except that struct members are public by default, this works for struct as well.
One reason for using static functions and variables is to create an object factory for the class using the factory pattern.  Another use is with the Singleton Pattern.


text:
Q: SCVMM 2012 SP1 P2V Conversion I was wondering if anyone can help with this.
I have SCVMM 2012 SP1, and I want to do a P2V conversion of a 2008 R2 server with a number of hard drives, both interval as well as DAS.  I do not have one location on the host large enough, but do have enough space across both internal space as well as DAS.  Can the P2V wizard handle this scenario, or would I need to get involved with Powershell scripting for this?  I may want the C: and E: drives from the source server on the E: drive of the host, etc.

A: AFAIK, you can't select multiple host paths during the P2V. What you could do is to run the P2V twice (using different target guest names for each one). The first time selecting only one guest volume to convert and the second time selecting the other guest volume to convert, making sure to select the appropriate host path for each P2V. Then when both conversions are done simply delete the second P2V guest and add its volume to the first P2V. Removing/deleting a guest does not delete the virtual hard disk files so this should work for you.


text:
Q: Conditional statement in a for loop simple as i I found these lines of code in a library made to listen to touch events :
  for ( var i = elements.length; i; i-- ) {
    iterator( elements[ i - 1 ], elements );
  }

It surprised me for a second. I understand the code this way : i is an integer positive or null and the conditional statement is if i positive.
Do I understand right ? Does i return false when i==-1 ? Or did i miss something (like it's possible to write a for loop without a conditional statement) ?

A: The conditional is essentially if( i) proceedToNextIteration();
As numbers go, only zero is falsy and would fail the check. -1 would be true in the above condition.
For this reason, I'd rewrite that code as:
for( var i = elements.length-1; i >= 0; i--) {
    iterator( elements[i], elements);
}

It's much more explicit about its final condition.

A: This is the structure of the for statement in Javascript:
for ([initialization]; [condition]; [final-expression])
   statement

The statement you provided
    for ( var i = elements.length; i; i-- )
adheres to this syntax. This is same as
for(var i = 10; i!=0; i--)

Meaning loop from 10 (elements.length) to 1. Similar to looping from 1 to 10.
In Javascript, the condition i != 0 can be replaced with just i.
Meaning:
if(i != 0)

and
if (i)

are the same. That is what is done in the condition part.
Looping over elements of a list or array from max to 0 is helpful when removing items from it.


text:
Q: How to turn any program reading from standard input into a server using systemd? According to https://www.launchd.info/ (the cookbook section):

launchd makes it very easy to create servers. In fact, launchd can turn any program reading from standard input into a server.

Since systemd is more or less a clone of / heavily inspired by launchd, I suspect that the same functionality might be present there as well. However, a brief look through the docs and an equally brief google-ing later I came up empty handed.
Is this possible and if yes: how so?
Alternatives considered
There is of course good old (x)inetd which does exactly this. There is also websocketd which I found during this research, which seems handy. However, I'd rather not have to learn yet another config language for this.

A: Of course shortly after posting this question I googled some more and with inetd in the search terms I discovered this nicely written blog post, according to which you need a .socket file for everything socket related and the usual .service file, albeit with a twist (see the note at the end). Without further ado, here's the example from the blog post:
sshd.socket
[Unit]
Description=SSH Socket for Per-Connection Servers

[Socket]
ListenStream=22
Accept=yes

[Install]
WantedBy=sockets.target

sshd@.service
[Unit]
Description=SSH Per-Connection Server

[Service]
ExecStart=-/usr/sbin/sshd -i
StandardInput=socket

Worthy of note is the @ which I assume turns this into an instantiated service.
I haven't yet tried this, so buyer beware.


text:
Q: Get the first start time and last end time I have an initial query result in the first images.
select
    rpt_mem.Member_Full_Name as Member,
    rpt_mem.Email_Address as [Work Email],
    CONVERT(VARCHAR(10), Date_Time_Start, 101) as [Shift Start Date],
    MIN(CONVERT(VARCHAR(5), Date_Time_Start, 108)) as [Shift Start Time],
    CONVERT(VARCHAR(10), Date_Time_End, 101) as [Shift End Date],
    MAX(CONVERT(VARCHAR(5), Date_Time_End, 108)) as [Shift End Time]
from Schedule
where rpt_mem.Member_Full_Name = 'Member1'
AND CONVERT(VARCHAR(10), Date_Time_Start, 101) = '10/04/2020'

How can I modify the query to get only the first Shift Start Time and the last end time like the 2nd image

A: You need to group by only the date portion of Date_Time_Start and Date_Time_End.
declare @Schedule table (Member varchar(8), Date_Time_Start datetime2(0), Date_Time_End datetime2(0))

insert into @Schedule (Member, Date_Time_Start, Date_Time_End)
values
('Member 1', '10 Apr 2020 12:00:00', '10 Apr 2020 14:00')
, ('Member 1', '10 Apr 2020 17:00:00', '10 Apr 2020 18:00')

select
    , CONVERT(VARCHAR(10), convert(date,S.Date_Time_Start), 101) as [Shift Start Date]
    , CONVERT(VARCHAR(5), MIN(S.Date_Time_Start), 108) as [Shift Start Time]
    , CONVERT(VARCHAR(10), convert(date,S.Date_Time_Start), 101) as [Shift End Date]
    , CONVERT(VARCHAR(5), MAX(S.Date_Time_End), 108) as [Shift End Time]
from @Schedule S
where S.Member in ('Member 1')
--AND CONVERT(VARCHAR(10), Date_Time_Start, 101) = '10/04/2020'
-- Sargeable i.e. can make use of indexes.
AND S.Date_Time_Start >= '10 Apr 2020'
AND S.Date_Time_Start < '11 Apr 2020'
group by S.Member, convert(date,S.Date_Time_Start), convert(date,S.Date_Time_End);

Which returns:
Member      Shift Start Date    Shift Start Time    Shift End Date  Shift End Time
Member 1    04/10/2020          12:00               04/10/2020      18:00

Notes:

*

*You don't want to be converting your Date_Time_Start in your where clause because its non-sargeable. Instead use a window condition.

*You want to get in the habit of using a non-ambiguous date format.

*This query will allow you to run over multiple days and multiple members should you wish to. You'd just have to add any addition member information columns e.g. Email to the group by.

*If you setup test data using DDL/DML statements as shown you make it easier for people to answer your question.

A: You may also do -
select
    rpt_mem.Member_Full_Name as Member,
    rpt_mem.Email_Address as [Work Email],
    CONVERT(VARCHAR(10), MIN(Date_Time_Start), 101) as [Shift Start Date],
    CONVERT(VARCHAR(5), MIN(Date_Time_Start), 108) as [Shift Start Time],
    CONVERT(VARCHAR(10), MAX(Date_Time_End), 101) as [Shift End Date],
    CONVERT(VARCHAR(5), MAX(Date_Time_End), 108) as [Shift End Time]
from Schedule rpt_mem
where rpt_mem.Member_Full_Name = 'Member1'
AND CONVERT(VARCHAR(10), Date_Time_Start, 101) = '04/10/2020'
GROUP BY
 rpt_mem.Member_Full_Name,
 rpt_mem.Email_Address;

Here is a db fiddle link - https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=61da8cab5471d21818eb5b7fec8d509c


text:
Q: On.(click) not firing I have an on click function which fires an ajax call, the on click function does not fire, I have used:
.click(function(){

Which works but I need the buttons to be able to click more than once so I tried:

<button id='post' value='1' />Do</button>

I have also tried:
$(document).on('click', '#post', function(){})

Which also does not work and my console.log is always showing:
Uncaught Typeerror: $(...).on is not a function

A: Are you sure that is the only script referenced on your page? this sounds awefull lot like you have 1.7 < somewhere. I can't figure why else it would complain about .on() .
if you use chrome,
1) open dev tools
2) go to network tab
3) show filters
4) click js
5) look for jquery references there
Screen how to do (stackoverflow.com)

A: If you use an old jquery version (<1.7) you can use bind:
http://api.jquery.com/bind/

A: Check to make sure you have put your click script after you have referenced jQuery on the page, not before.


text:
Q: $scope.ons.navigator.pushPage not work in init method I am following init function in app.js
$scope.init = function ()
        {
            if(localStorage.getItem("id")!=null && localStorage.getItem("pass")!=null)
            {
                alert(localStorage.getItem("id")+" "+localStorage.getItem("pass"));
                var id=localStorage.getItem("id");
                var pass=localStorage.getItem("pass");
                $http({method: 'GET', url: site+'/login-web.php?txt_email='+id+'&txt_password='+pass}).
                success(function(data, status, headers, config)
                {
                    if(data=='error')
                        navigator.notification.alert("Wrong username or password.",null,"Attention.!","Try Again.!");
                    else
                    {
                        localStorage.setItem("id", id);
                        localStorage.setItem("pass", password);
                        alert("fire");
                        $scope.ons.navigator.pushPage('dashboard.html',{title : 'title'});
                    }

                }).
                error(function(data, status, headers, config)
                {
                    alert("Please check Mobile Data.");
                    // called asynchronously if an error occurs
                    // or server returns response with an error status.
                });
            }
        },

and i am fire init from
<body ng-controller="AppController" ng-init="init()">

I want to like this if i am login first time then i need to login and i store id and pass in localstorage and every time when application is load and init method is fire and i check id and pass from localstorage and fire server method to check id and pass if its right login is done automatically.
I am using phonegap + onsenui + angular js.
Problem is from init method
$scope.ons.navigator.pushPage('dashboard.html',{title : 'title'});

is not redirect to dashborad.

A: There is nothing wrong with $scope.ons.navigator.pushPage('dashboard.html',{title : 'title'});. But I think inside your <body> tag, there is no <ons-navigator> tag which is needed in order to use that function. Moreover, you need to call the function inside a setTimeout otherwise it will be called before the DOM element finishes rendering. Do as follows:
Here is what you need to add to ur controller:
app.factory('DataService', function($http) {
    var service = {
        requestData: function(url) {
            return $http.get(url).then(function(data, status, headers, config) {
                service.myData = data;
                return service.myData;
            });
        },
        myData: null,
    return service;
});

app.controller('AppController', function($scope, DataService)){
    $scope.init = function(){ setTimeout($scope.init_wait, 10); };

    $scope.init_wait = function () {
        if(localStorage.getItem("id")!=null && localStorage.getItem("pass")!=null){
            alert(localStorage.getItem("id")+" "+localStorage.getItem("pass"));
            var id=localStorage.getItem("id");
            var pass=localStorage.getItem("pass");
            var url = ite+'/login-web.php?txt_email='+id+'&txt_password='+pass;

            DataService.requestData(url).then(function(data, status, headers, config) {
                if(data=='error')
                    navigator.notification.alert("Wrong username or password.",null,"Attention.!","Try Again.!");
                else {
                    localStorage.setItem("id", id);
                    localStorage.setItem("pass", password);
                    alert("fire");
                    $scope.ons.navigator.pushPage('dashboard.html',{title : 'title'});
                }
            });
        }
    }
};

Here inside your HTML
<body ng-controller="AppController" ng-init="init()">
  <ons-navigator>
    <!--Your HTML-->
  </ons-navigator>
</body>


text:
Q: How to select the first suggested element using protractor? 1.Here is HTML code >

{{ profile.alias }}

2.here is my code :
element(by.id('ugcshare-textbox')).sendKeys('@mshinagi');
      browser.explore();
      element(by.id('alias-search-text')).get(0).click();
        browser.sleep(2000);
     element(by.id('share-submit')).click();

*Error : I am getting error as " TypeError: element(...).get is not a function "enter image description here
I want to select the first suggestion which is displayed in the image.Even though i am trying from the index but i was unsuccessful.Could someone please help me.

A: You could retrieve the entire list of items with a css selector instead of an id one and then get the first one from the list.
element.all(by.css('alias-search-profile-text')).get(0).click();


text:
Q: AWS Cognito userpool changed email address pointless validation code? i have set up a user pool using option 2 ( see docs here ) where i use the email address to sign in together with a password.
users are able to register and log in successfully.
users can successfully change the email address.
i then use this code to change the email address:
cognitoUser.updateAttributes(attributeList, function (err,
result) {....}
the confusion or problem is:
changing the email address automatically sends a validation code to the new email address. what do i need to do with this code as the email address is changed without validation and the user can use the new address to login without any problems.
is it necessary to validate the changed email address when the address seems to be automatically validated without using the validation code? if i don't have to use the validation code, is there any way of preventing it being sent to the user when they change the email address as they will probably be confused when they receive it seeing that the changed email address works?
thanks

A: Verification is needed when user will try to use forgot password. If email is not verified the code for reseting password will not be send.
You can prevent it from being sent from General settings > MFA and verifications under "Which attributes do you want to verify?"


text:
Q: Prove that every $n$-element set has the same number of subsets with even and odd cardinality without creating a bijection I need to prove that the number of even and odd subsets of a finite set if always equal. This is not a problem once we assume that $n$ is odd. Then, every "even" subset of the set defines in a unique way an "odd" subset and vice versa.
The problem starts once we assume that $n$ is even. The argument used in the previous case no longer works. I read some answers on Stack, but each of them, at this point, constructed a bijection which looked strange to me.  Is there a combinatorial or algebraical way to prove this theorem?

A: A bijection is a combinatorial way IMO. But there's a simple inductive argument. It's true for $n=1;$ suppose true for $n$ and take a set $S$ of size $n+1.$ Let $a$ be any element of $S$. Now $S- a$ is a set of size $n$, so has the same number of odd and even subsets. Therefore $S$ has the same number of odd subsets not containing $a$ as it has even subsets not containing $a.$ By adding $a$ to each subset, it also has the same number of even subsets containing $a$ as odd subsets containing $a.$ So in total it has the same number of odd and even subsets.

A: Give each size-$k$ subset a score of $(-1)^k$. The result you want is that the sum of all subsets' scores is $0$. But we can factorise that sum as $(1+(-1))^n$, since each element is either in or not in a subset, and multiplies the empty set's score of $1$ by $-1$ if it's included.

A: Here's my way of thinking... A set of cardinality $n$ will have $2^n$ subsets (why?)
Suppose that, for some $n$, the number of even and odd subsets is the same, i.e. $x$ for some $x$. Then $2x=2^n$.
Now suppose I introduce a new element, so we have a set of cardinality $n+1$. All the even subsets of the original $n$ items are still even subsets of our new slightly larger set - so we have $x$ even subsets AND all of the odd subsets of $n$ can be made into even subsets of $n+1$ by including our new element - and so we have another $x$ even subsets, giving $2x$ even subsets. However, we know that $2x=2^n=\frac{1}{2} \times 2^{n+1}$ and so exactly half of the subsets of our new set are even (implying the other half are odd). This is the inductive step in a proof by induction, you now just need to find an $n$ such that the base step holds (hint, $n=1$ might be worth a go).

A: The number of elements in $P(S)$ is $2^n$.  Suppose that $P_o(S) = 2^{n-1} = P_e(S)$ for all $1 \leq n \leq N$.  Then the sets are $P(S \cup a) = P(S) \cup (a \cup P(S))$.  Thus there are $2^{n-1} + \#\{ a \cup A : A \in P(S), |A| \text{ odd}\}$ even elements, and similarly for odd.  Proof by induction.


text: Q: name a series of formula automatically in excel Hi I created a formula involving an offset function in a cell and dragged it over covering more than a hundred cells, my problem is i need to define each formula in a name manager.  Is there a way I can do it automatically?


text:
Q: Unable to determine IP address from host name, The domain name does not exist A local website is set up on a server.
The website test.skien.kommune.no is mapped to 127.0.0.1
The site is configured in IIS and I have added a binding.
Everything worked for a week, but today I suddenly got this error message:
The following error was encountered while trying to retrieve the URL: http://test.skien.kommune.no/

    Unable to determine IP address from host name "test.skien.kommune.no"

The DNS server returned:

    Name Error: The domain name does not exist.

This means that the cache was not able to resolve the hostname presented in the URL. Check if the address is correct.

Your cache administrator is webmaster.

The hosts-file is configured '127.0.0.1        test.skien.kommune.no'
Why doesn't it use the local dns-mapping in the host-file?

A: Check for any VPN. if you have enabled any VPN in chrome then disable it.

A: Quoting @leo est omnia's answer, it might be possible that your browser would be treating your virtual host as a fully qualified domain when proxy server is ticked.
Adding to the answer,you also have these settings for the browser you are using, like for "Chrome":
settings => advanced settings => network => change proxy settings => connections => lan settings => uncheck use proxy server.
Also, if you have done some changes in your "httpd.conf" file, if you have given "\" backslash for directory path for the default path for your local  apache files, use "/" forward slash instead, apache reads it the linux type.

A: I found that the proxy settings were my problem.
In Windows "Control Panel" open "Internet Options" and go to the "Connections" tab. Click the "LAN settings" button.
If "Use a proxy server" is ticked, this may be your problem too. If there are periods in the local host domain, the proxy kicks in and treats the URL as a fully qualified domain name (which it won't be able to find).
To exclude it, click on "Advanced" and add it to the "Do not use proxy..." list.

A: This is the whole story
You should not use a proxy
Your proxy may have occurred through a browser extension, or you may have saved something in the system settings


text:
Q: Printing a floating point in assembly I have a question about printing a floating point number and difference between a double word and quad word data. Here is my example
section .data
number dq 2.0
form db '%.2f',0
section .text
extern printf
global main:
push rbp
mov rbp,rsp
push rdi
push rsi
push rbx

movq xmm0,[number]
push qword[number]
mov rdi,form
mov rax,1
call printf

pop rbx
pop rsi
pop rdi
mov rsp,rbp
pop rbp
ret

Output is :2.0 that is ok but here is a problem if a number is double word
section .data
number dd 2.0
form db '%.2f',0
section .text
extern printf
global main:
push rbp
mov rbp,rsp
push rdi
push rsi
push rbx

movd xmm0,[number]
push qword[number]
mov rdi,form
mov rax,1
call printf

pop rbx
pop rsi
pop rdi
mov rsp,rbp
pop rbp
ret

then output is 0.00, but when I check a xmm0 register I notice that in first case the content is something like this 8_float={0x0,0x2,...},v4_double={0x2,0x0...}, and in second case is 8_float={0x2,0x0,..},v4_double={0x0,0x0,..} so that mean that printf always check a v4_double? I try to printf a double with %lf, but it is the same result 0.00, do you have some idea I try even with different move like movsd,movups,movapd,.. but that does not help me. Do you have some idea?


text:
Q: How to correctly merge the value in the columns, in the case of using the widget type the Value map, with QGIS Trying to do work that was previously done in ArcGIS. There is a table when filling 4 columns, these values are added in the Sum column.

In QGIS, I decided to use the Value Map for fields

For the Sum field, I use the following expression

But as a result, I lose zeros
before number

Where did I go wrong and how do I get values with zeros when field type  is real and SUM field is string?


text:
Q: How can i get values from react native into my bridge swift class? Following docs i try to do something like this:
Everything work's but the value myprop don't get into my ComponentView
Native Code
//component.h

#import "React/RCTBridgeModule.h"
#import "React/RCTViewManager.h"
#import "React/RCTUIManager.h"

@interface component: RCTViewManager

@property (nonatomic, assign) NSString *myProp;

@end

//component.m

#import "component.h"

#import <Foundation/Foundation.h>

@interface RCT_EXTERN_MODULE(ComponentViewManager, RCTViewManager)

RCT_EXPORT_VIEW_PROPERTY(myProp, NSString)

@end

//ComponentViewManager.swift

import Foundation

@objc(ComponentViewManager)
class ComponentViewManager: RCTViewManager {

    override func view() -> UIView! {
        return ComponentView()
    }

    ....
}

//ComponentView
class ComponentView: UIView {

    //initWithFrame to init view from code
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.frame = frame
        setupView()
    }

    func setupView() {
        ...
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    public func setMyProp(_ myProp: NSString) {
        //DON'T GET Here :(
        self.myProp = myProp
    }
}

What i do wrong myProp value don't get in my view?
RN docs: https://facebook.github.io/react-native/docs/native-components-ios

A: Answering my own question :(, but i figured out how to solve and if could helps anyone.
you just to set one attribute with the same name of your prop that was registered into your .m and in your .h files.
//ComponentView

@objc var myProp = "" {
  didSet {
    //Here you can call any function and it will be called after the value get here
    doSomething()

  }
}


text:
Q: how to add tablet resolution support in Android Studio Using ConstraintLayout I saw this problem: on phones, the resolution of my widgets is normal and takes up almost all of the
screen space:

But when I switch to the resolution of the tablets, all the widgets become small and cannot be viewed on the screen:

How to make the resolution of widgets look normal on all resolutions and devices?

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TableLayout
        android:id="@+id/table_l"
        android:layout_width="297dp"
        android:layout_height="329dp"
        android:layout_weight="1"
        android:layout_x="57dp"
        android:layout_y="202dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1" />

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1" />

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1">

        </TableRow>
    </TableLayout>

    <Button
        android:id="@+id/st"
        android:layout_width="178dp"
        android:layout_height="wrap_content"
        android:layout_x="120dp"
        android:layout_y="112dp"
        android:text="start"
        app:layout_constraintBottom_toTopOf="@+id/table_l"
        app:layout_constraintEnd_toEndOf="@+id/table_l"
        app:layout_constraintHorizontal_bias="0.495"
        app:layout_constraintStart_toStartOf="@+id/table_l"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_weight="1"
        app:layout_constraintVertical_bias="0.647" />

    <TextView
        android:id="@+id/X_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="48dp"
        android:layout_x="118dp"
        android:layout_y="608dp"
        android:text="x:"
        android:textSize="30sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="@+id/O_text"
        app:layout_constraintStart_toStartOf="@+id/O_text"
        app:layout_constraintTop_toBottomOf="@+id/O_text" />

    <TextView
        android:id="@+id/O_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="36dp"
        android:layout_x="116dp"
        android:layout_y="661dp"
        android:text="o:"
        android:textSize="30sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="@+id/table_l"
        app:layout_constraintHorizontal_bias="0.153"
        app:layout_constraintStart_toStartOf="@+id/table_l"
        app:layout_constraintTop_toBottomOf="@+id/table_l"
        app:layout_constraintVertical_bias="0.0" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="27dp"
        android:layout_height="47dp"
        android:layout_marginTop="36dp"
        android:textSize="36sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.139"
        app:layout_constraintStart_toEndOf="@+id/O_text"
        app:layout_constraintTop_toBottomOf="@+id/table_l"
        app:layout_constraintVertical_bias="0.0" />

    <TextView
        android:id="@+id/textView4"
        android:layout_width="25dp"
        android:layout_height="45dp"
        android:layout_marginBottom="52dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.151"
        app:layout_constraintStart_toEndOf="@+id/X_text"
        app:layout_constraintTop_toBottomOf="@+id/textView3"
        app:layout_constraintVertical_bias="0.571" />

</androidx.constraintlayout.widget.ConstraintLayout>

A: You should create layout xml files for different screen size. For example; If your app running in Tablet(7 inch), you must create new layout as a layout-sw600dp.
Look at this link for more details.

A: You should stop using fixed sizes and x/y positions for layouts. There might be exceptions, but in general, all views should be able to dynamically resize themselves. That means, you almost never use fixed values for widths but instead wrap_content or match_parent. After 4 years of android development I also have to find one case where I ever needed the layout_x and layout_y XML tags.
Otherwise, this layout will be small on big screens and it won't fit on small screens.
For 90% of layouts, all you need is ConstraintLayout and maybe LinearLayout. RelativeLayouts have become mostly obsolete.
Explaining how to properly arrange your ui would be to exhaustive here. Instead, I recommend you to take the time to go through a tutorial like this google codelab on building a responsive UI with constraintlayouts. If done correctly, you can build one UI which looks good an smartphones and tablets.
But if you want to have an entirely different layout for tablets, then @Mustafa Yanık's approach is correct. Then you need to create a second layout in a different subfolder.


text:
Q: PHP code how to use if else My question is if Destination in Tokyo Discount 200 per Travelers who stays at least 5 nights.
    if($destination == "Barcelona")
    {
    $airFare = 875;
    $perNight = 85;
    }

    else if($destination == "Cairo")
    {
    $airFare = 950;
    $perNight = 98;
    }

    else if($destination == "Rome")
    {
    $airFare = 875;
    $perNight = 110;
    }

    else if($destination == "Santiago")
    {
    $airFare = 820;
    $perNight = 85;
    }

    elseif($destination == "Tokyo")
    {
    $airFare = 1575;
    $perNight = 240;
    }

    $tickets = $numTravelers * $airFare;
    $hotel = $numTravelers * $numNights * $perNight;
    $totalCost = $tickets + $hotel;

*I cannot change any code here just need to add it to get $200 discount who is going to Tokyo and staying 5 nights!
If I input 1 passenger for 5 nights to Tokyo the value must be $2575.
Also, I have to use Nested If or Compound Boolean Expression for this!
Thank you for all your helps!
This is my code how to I add up the question to get 200 discount in this code? Destination in Tokyo, At least saying 5 nights per travelers get 200 discount.

A: Try this code
 $subtotal=0;

elseif($destination == "Tokyo")
    {
    $airFare = 1575;
    $perNight = 240;
      if($numNights >= 5){
        $subtotal= ($perNight*numNights)-200;
      }else{
        $subtotal= ($perNight*numNights)-200;
      }
    }

$tickets = $numTravelers * $airFare;
    $hotel = $numTravelers * $numNights * $perNight;

change to:
$hotel = $numTravelers * $subtotal;

A: You should add another IF statement inside the code for Tokyo. Now, assuming you have declared the $discount = 200 and the $nights variables. Use this:
elseif($destination == "Tokyo")
    {
    $airFare = 1575;
    $perNight = 240;
if($nights >= 5){
    $total = ($airFare + $perNight) - $discount;
    }
    }

A: I try to modify your code as minimal as possible, and here it is:
EDITED to only stay 5 nights in Tokyo will get one time $200 discount

        if($destination == "Barcelona")
        {
            $airFare = 875;
            $perNight = 85;
        }

        else if($destination == "Cairo")
        {
            $airFare = 950;
            $perNight = 98;
        }

        else if($destination == "Rome")
        {
            $airFare = 875;
            $perNight = 110;
        }

        else if($destination == "Santiago")
        {
            $airFare = 820;
            $perNight = 85;
        }

        elseif($destination == "Tokyo")
        {
            $airFare = 1575;
            $perNight = 240;
        }

        $discount = ($destination == "Tokyo" && $numNight == 5)? 200 : 0; // condition is here
        $tickets = $numTravelers * $airFare;
        $hotel = $numTravelers * $numNights * $perNight;
        $totalCost = $tickets + $hotel - $discount;
    ?>

This is what I would suggest to you. You may find it very different:
Create a function rather then a lengthy elseif(s). Switch case may also be considered but I have found simply using array is more convenient to handle. Hope that helps
<?php
function getCost($destination, $numTravelers, $numNights) {

    // organize them in an array format
    $prices["Barcelona"] = ['airfare' => 875, 'perNight' => 85, 'discount' => 0];
    $prices["Cairo"] = ['airfare' => 950, 'perNight' => 98, 'discount' => 0];
    $prices["Rome"] = ['airfare' => 875, 'perNight' => 110, 'discount' => 0];
    $prices["Tokyo"] = ['airfare' => 875, 'perNight' => 110, 'discount' => 200];

    $min = 5; // minimum stay for discount

    // just get the value by providing the key (destination name)
    $tickets = $prices[$destination]['airfare'] * $numTravelers;
    $hotel = $numTravelers * $numNights * $prices[$destination]['perNight'];
    $total =  ($numNights = $min) ? $tickets + $hotel - $prices[$destination]['discount'] : $tickets + $hotel;
    // just for viewing the output
    echo 'Travel to ' . $destination . ' for ' . $numTravelers . ' people for ' . $numNights . ' nights cost: ' . $total . '<br>';
    return $total;
}

$cost1 = getCost('Tokyo', 3, 4);

$cost2 = getCost('Tokyo', 3, 5);
?>

OUTPUT
Travel to Tokyo for 3 people for 4 nights cost: 3945
Travel to Tokyo for 3 people for 5 nights cost: 4075


text:
Q: What is the difference between breakpoint and max-width, what is the best use case for them?  .about-wrapper {
       width: 100%;
       @media screen and(max-width: $large) {
         width: 600px;
         height: 338px;
         margin-left: -300px;
         margin-top: -190px;
    }
  }

vs
  .about-wrapper{
      width: 100%;
      @include breakpoint($large) {
         width: 600px;
         height: 338px;
         margin-left: -300px;
         margin-top: -190px;
    }
  }

Is there a proper way to use max-width?
Does one perform better than another? I am trying to understand the pros/cons of the two.

A: They are just SASS vs CSS way of writing things. @include breakpoint is compiled to css3 @media. In your case:
$large = 100px;

@include breakpoint($large) {
    ...
}

is compiled to:
@media (min-width: 100px) {
    ...
}

If you wanna set the breakpoint on max-width instead, do this:
$large = max-width 100px;

@include breakpoint($large) {
    ...
}

which will compile to:
@media (max-width: 100px) {
    ...
}

A: Breakpoint is a mixin from some SASS library. I bet you are using Breakpoint Sass. This mixin compiles to @media statements, so it's not that one is better than the other but different ways to manage media queries.


text:
Q: Return multiple vars: list/tuple I have a function which must return many values (statistics) for other function to interact with them. So I thought about returning them inside a list (array). But then I wondered: should I do so using a list (["foo", "bar"]) or using a tuple (("foo", "bar"))? what are the problems or differences there are when using one instead of the other??

A: If you do not need to edit the return value, use a tuple. The main difference is that lists can be edited.
See this: What's the difference between lists and tuples?

A: Use a tuple. In your application, it doesn't seem like you will want or need to change the list of results after.
Though, with many return values you might want to consider returning a dictionary with named values. That way is more flexible and extensible, as adding a new statistic doesn't requiring modifying every single time you use the function.


text:
Q: How to test the reception of Broadcast Receivers? I'm writing tests to verify the reception of the transmitting receivers but for some reason, the receiver is never registered or the intent is never sent.
I guess there should be a problem with the Context but, no luck yet finding it.
This is the BroadcastFactory.kt:
object BroadcastFactory {

    private lateinit var intent: Intent

    fun build(
        action: String,
        flag: Int? = null,
    ): BroadcastFactory {
        intent = Intent().apply {
            this.action = action
            this.flags = flag ?: 0
        }
        return this
    }

    fun send(
        context: Context
    ): Intent {
        context.sendBroadcast(intent)
        return intent
    }
}

And this is the test file BroadcastTest.kt:

@RunWith(AndroidJUnit4::class)
@SmallTest
class BroadcastTest {

    lateinit var intents: MutableList<Intent>
    lateinit var latch: CountDownLatch
    private lateinit var receiver: BroadcastReceiverTester

    inner class BroadcastReceiverTester : BroadcastReceiver() {

        override fun onReceive(p0: Context?, intent: Intent?) {
            intent?.let {
                intents.add(it)
                latch.countDown()
            }
        }
    }

    private val context: Context = getInstrumentation().targetContext

    @Before
    fun setUp() {
        intents = mutableListOf()
        latch = CountDownLatch(1)
        receiver = BroadcastReceiverTester()

        LocalBroadcastManager.getInstance(context).registerReceiver(
            receiver,
            IntentFilter.create(
                Constants.ACTION, "text/plain"
            )
        )

    }

    @Test
    fun testBroadcastReception() {
        BroadcastFactory
            .build(Constants.ACTION, Constants.FLAG)
            .send(context)

        // assert broadcast reception (NOT WORKING)
        latch.await(10, TimeUnit.SECONDS)
        assertThat(intents.size).isEqualTo(1)
    }

    @After
    fun tearDown() {
        LocalBroadcastManager.getInstance(context).unregisterReceiver(receiver)
    }

}

I'm using a CountDownLatch to wait 10 seconds for the receiver, plus, its value can be asserted. Besides, I set a list of Intents to check the number of registrations/receptions.
There is something I'm missing here? Different context provider? Robolectric runner?
Thanks

A: Is solved it by changing the receiver with this:
context.registerReceiver(
            receiver,
            IntentFilter(
                Constants.ACTION
            )
        )

Thanks to @selvin and @mike-m for the help!


text:
Q: How to resolve PIL unidentified image error in flask app I am taking a flask tutorial course at https://deeplizard.com, which seeks to predict cats and dogs. The code works well until the predict function is called. Here is a summary of the error message I get:
ERROR in app: Exception on /predict [POST]

PIL.UnidentifiedImageError: cannot identify image file <_io.BytesIO object at 0x0000023708CF4BE8>

Below are the backend and full error details. I would appreciate help with this error.
The backend code is from https://deeplizard.com/learn/video/XgzxH6G-ufA. Thank you.
import base64
import numpy as np
import io
from PIL import Image
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.models import Sequential, load_model
from tensorflow.keras.preprocessing.image import ImageDataGenerator, img_to_array
from flask import request
from flask import jsonify
from flask import Flask

app = Flask(__name__) #instance of flask class

def get_model():
    global model
    model = load_model('VGG16_cats_and_dogs.h5')
    print(" * Model loaded!")

def preprocess_image(image, target_size):

    if image.mode != "RGB":
        image = image.convert("RGB")
    image = image.resize(target_size)
    image = img_to_array(image)
    image = np.expand_dims(image, axis=0)
    return image

print(" * Loading Keras model...")
get_model()

@app.route("/predict", methods=["POST"])

def predict():
    message = request.get_json(force=True)
    encoded = message['image']
    decoded = base64.b64decode(encoded)
    image = Image.open(io.BytesIO(decoded))
    processed_image = preprocess_image(image, target_size=(224, 224))
    prediction = model.predict(processed_image).tolist()

    response = {
        'prediction': {
            'dog': prediction[0][0],
            'cat': prediction[0][1]
        }
    }
    return jsonify(response)

The error details are below:
[2021-02-23 08:43:26,191] ERROR in app: Exception on /predict [POST]
Traceback (most recent call last):
  File "C:\Users\Akua\Anaconda3\envs\tensorflow_gpu\lib\site-packages\flask\app.py", line 2447, in wsgi_app
    response = self.full_dispatch_request()
  File "C:\Users\Akua\Anaconda3\envs\tensorflow_gpu\lib\site-packages\flask\app.py", line 1952, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "C:\Users\Akua\Anaconda3\envs\tensorflow_gpu\lib\site-packages\flask\app.py", line 1821, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "C:\Users\Akua\Anaconda3\envs\tensorflow_gpu\lib\site-packages\flask\_compat.py", line 39, in reraise
    raise value
  File "C:\Users\Akua\Anaconda3\envs\tensorflow_gpu\lib\site-packages\flask\app.py", line 1950, in full_dispatch_request
    rv = self.dispatch_request()
  File "C:\Users\Akua\Anaconda3\envs\tensorflow_gpu\lib\site-packages\flask\app.py", line 1936, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "C:\Users\Akua\SDSMT G DRIVE\SDSMT Academics\COURSES\SUMMER 2019\Machine Learning - Discussions _ Coursera_files\Keras\Deep lizard\DogsAndCats\predict_app.py", line 67, in predict
    image = Image.open(io.BytesIO(decoded))
  File "C:\Users\Akua\Anaconda3\envs\tensorflow_gpu\lib\site-packages\PIL\Image.py", line 2959, in open
    "cannot identify image file %r" % (filename if filename else fp)
PIL.UnidentifiedImageError: cannot identify image file <_io.BytesIO object at 0x0000023708CF4BE8>


text:
Q: Get js classname inside super method of child in ES6 I have a parent class in JS that has some properties of which some are based on the class name of the child classes:
ParentClass.js
export default class ParentClass {

    constructor(className) {

        this.className = className;
        this.classNameLowerCase = className.toLowerCase();
    }
}

In a child class I extend the parent class and use super() for the constructor invocation where I will pass the class name of the child class.
ChildClass.js
import ParentClass from  "./ParentClass.js";

class ChildClass extends ParentClass {

    constructor() {
        super("ChildClass");
    }
}

As you can see the child class is called ChildClass and I also pass this name as a string in super(). I prefer to get the class name of the child class with a funtion (without havind to repeat myself). Without using super() I could use this.constructor.name to get the name of the class, but inside super() this is not allowed and neither anywhere before the parentclass constructor invocation.
How can I get the child class name to use as an argument inside super()?

A: One option is to put the functionality into the parent constructor - if no className is passed, check this.constructor.name:

class ParentClass {
    constructor(className) {
        if (!className) {
            className = this.constructor.name;
        }
        this.className = className;
        this.classNameLowerCase = className.toLowerCase();
    }
}

class ChildClass extends ParentClass {
    constructor() {
        super();
    }
}

const c = new ChildClass();
console.log(c.className);


text:
Q: Whatsapp sharing text and image is not working in ios If sending text to WhatsApp:
NSString *msg = @"Some Text";
NSString *urlWhats = [NSString stringWithFormat:@"whatsapp://send?text=%@",msg];
NSURL *whatsappURL = [NSURL URLWithString:[urlWhats stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
if ([[UIApplication sharedApplication] canOpenURL: whatsappURL]) {
  [[UIApplication sharedApplication] openURL: whatsappURL];
} else {
  UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"WhatsApp not installed." message:@"Your device has no WhatsApp installed." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
  [alert show];
}

If sending image to WhatsApp:
if ([[UIApplication sharedApplication] canOpenURL: [NSURL URLWithString:@"whatsapp://app"]]){

   UIImage* iconImage = [self captureScreen];// this will return a image
   NSString* savePath  = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/whatsAppTmp.wai"];

   [UIImageJPEGRepresentation(iconImage, 1.0) writeToFile:savePath atomically:YES];

   _documentInteractionController = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:savePath]];
   _documentInteractionController.UTI = @"net.whatsapp.image";
   _documentInteractionController.delegate = self;

   [_documentInteractionController presentOpenInMenuFromRect:CGRectMake(0, 0, 0, 0) inView:self.view animated: YES];
} else {
   UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"WhatsApp not installed." message:@"Your device has no WhatsApp installed." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
   [alert show];
}

Whatsapp is opened without any text for text sharing and image is also not getting shared. Please help me.

A: Did you add "LSApplicationQueriesSchemes" to you plist?

*

*Go to your project/Supporting Files/YourProjectName-Info.plist in
XCode project Explorer.

*Add a new key-value pair. Key :
LSApplicationQueriesSchemes Type : Array Add a new string item
"whatsapp"

Please try this and let me know if it is still not working.

A: note:- You can only share text or image, both sharing together in whatsApp is not working from whatsApp side
 /*
    //Share text
    NSString *textToShare = @"Enter your text to be shared";
    NSArray *objectsToShare = @[textToShare];

    UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:objectsToShare applicationActivities:nil];
    [self presentViewController:activityVC animated:YES completion:nil];
     */

    //Share Image
    UIImage * image = [UIImage imageNamed:@"images"];
    NSArray *objectsToShare = @[image];

    UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:objectsToShare applicationActivities:nil];
    [self presentViewController:activityVC animated:YES completion:nil];


text:
Q: How do I find the owner of the head in my hand? On Hypixel Skyblock, there is this item called the Raw Soulflow. I think the head looks cool, so I want to copy it.
But, after extensive searching, I can't seem to find out how!
Is there anyway to see the owner of the head in your hand in Minecraft? If you can't in vanilla, is there a mod that lets you?

A: Using a SkyBlock mod (or any mod that does this tbh), I use a special mod made for editing the official SB wiki - you can take the NBT of an item. Hovering over a Raw Soulflow and taking its NBT gives me this (copied to clipboard):
{
id: "minecraft:skull",
Count: 1b,
tag: {
    HideFlags: 254,
    SkullOwner: {
        Id: "0411d14d-f9fb-3395-b96f-b9fb16c47d16",
        Properties: {
            textures: [{
                Value: "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvODEzZmYwZmJjODE3MWEzMDYyYjZiZDVjYWNmN2FhMmVmZGZlOGRlMzk5NDYyYjJlMDMwYzlkYzljNjAifX19"
            }]
        }
    },
    display: {
        Lore: ["§7Hold and right-click to consume,", "§7gaining §3+1⸎ Soulflow§7!", "", "§a§lUNCOMMON"],
        Name: "§aRaw Soulflow"
    },
    ExtraAttributes: {
        id: "RAW_SOULFLOW"
    }
},
Damage: 3s}

The string found at tag -> SkullOwner -> Properties -> textures -> Value is a base64 string which in this case decodes to:
{"textures":{"SKIN":{"url":"http://textures.minecraft.net/texture/813ff0fbc8171a3062b6bd5cacf7aa2efdfe8de399462b2e030c9dc9c60"}}}

Viewing the url link gives you
which is the skin used for the soulflow item.

A: Without commands I think your only option is asking the mod developers.
It is not clear what the item is, it might be a regular block added by the mod with custom texture, and not a player head. If the block is indeed implemented as a player head, you have two options:
Place it somewhere (if possible) and then get its NBT with (replace with the actual coordinates):
/data get block 125 65 194

If it can't be placed, you can drop it on the ground and make sure there are no other items around and then:
/data get entity @e[type=item,sort=nearest,limit=1]


text:
Q: R Shiny: download the whole dataset with DT::renderDataTable I am using DT::renderDataTable and DT::datatable with extension 'Buttons' to allow user to download a table in R Shiny app.
With this script, the user can download data he sees on his screen (eg: User uses the selector to show 1 to 25 of 50 entries and clicks on donwload button: only the 1 to 25 rows will be downloaded)
Is there a way to modify the button behviours to allow user to download the whole dataset (50 rows)?
Thanks for your help!
Here is my current script:
output$mytable2  <- DT::renderDataTable(
                            DT::datatable(
                                { plots.dfs()[[2]] },

                                extensions = 'Buttons',

                                options = list(
                                    fixedColumns = TRUE,
                                    autoWidth = TRUE,
                                    ordering = TRUE,
                                    dom = 'Bliftsp',
                                    buttons = c('copy', 'csv', 'excel')
                                ),

                                class = "display"
                           ))

A: Use the server = FALSE argument to renderDataTable.
ref : rstudio.github.io/DT/server.html


text:
Q: why volley library not working on android 9(API 28) where as its working fine on android 8(API 27)? I am developing an app with volley library. Everything is working fine below android 9.0. But not in 9.0
I am using
implementation 'com.android.volley:volley:1.1.0'
targetSdkVersion 28
compileSdkVersion 28
minSdkVersion 24

gradle:3.2.1

A: Update :
Please add below line in manifests:
android:usesCleartextTraffic="true"

First, You check your Offline mode is check or Unchecked. if it's check then please go on setting and Unchecked.
Now change the below version :
compileSdkVersion 27
minSdkVersion 16
targetSdkVersion 27

implementation 'com.android.support:appcompat-v7:27.1.1'

implementation 'com.android.volley:volley:1.1.0'

Now Clean and Re-Build your Project.

A: Just add one line manifest file.
 android:usesCleartextTraffic="true"

A: From android 9 clear text traffic is prohibited. You will manually need to allow it adding below code to manifest.
android:networkSecurityConfig="@xml/network_security_config"

Also, create xml/network_security_config.xml and add below code to allow clear text traffic:
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <base-config cleartextTrafficPermitted="true">
        <trust-anchors>
            <certificates src="system" />
        </trust-anchors>
    </base-config>
</network-security-config>

A: I have same problem and resolved it when I use https not http.


text:
Q: Use POST method in RestSharp I want to use RestSharp to post data to my API here:
creat.php
My structure is like this:
read.php
In PostMan I use body option and raw input like this:
{
    "story_code" : "Amazing Pillow 2.0",
    "master_code" : "199",
    "created" : "2018-06-01 00:35:07"
}

And it works. In RestSharp I used this code but it returned Bad Request and the message: "Unable to create product. Data is incomplete."
var client = new RestClient("http://api.dastanito.ir");
var request = new RestRequest("/storiesmaster/creat.php", Method.POST);

request.AddParameter("story_code", "value");
request.AddParameter("master_code", "value2");

IRestResponse response = client.Execute(request);
var content = response.Content;

I even used AddQueryParameter but again bad request.
What function should I use?

A: Instead of .AddParameter you could use AddJsonBody to get something similar to what Postman sent which you already know works fine.
The code below works for example:
var client = new RestClient("http://api.dastanito.ir");
var request = new RestRequest("/storiesmaster/creat.php", Method.POST);

request.AddJsonBody(new
{
    story_code = "value",
    master_code = "value2"
});

IRestResponse response = client.Execute(request);
var content = response.Content; // {"message":" created."}

If you inspect the outgoing message with Fiddler, it looks like this:

{"story_code":"value","master_code":"value2"}

Whereas your message using AddParameter looks like this:

story_code=value&master_code=value2


text:
Q: iOS 7 When Rotating View in Tab Bar, Right Side of View is Not Clickable I have a very simple app consisting of a single view. Everything works fine, the app rotates and buttons on the right side of the screen are clickable. I'm using iOS 7 and Xcode 5.
If I go into the storyboard and select the view then do Editor > Embed In > Tab Bar Controller, now when the app rotates from portrait to landscape, the right side of the app is not clickable. It seems to be exactly 768 pixels from the left where it stops working, so it makes me think there's something in the app that didn't rotate. What could be wrong?
It's just a basic single view wizard app that I put some UI elements on it to test. The only thing that makes it stop working is embedding in the tab bar.
Here is the whole project: https://github.com/tomkincaid/rotate
Update: I had originally used the same iPhone storyboard for both iPhone and iPad and thought this might be the issue. However, I created a new iPad storyboard and it has the same issue.
Another Update: If I put the view inside a navigation controller, it works. So View works and Tab>Nav>View works, but Tab>View doesn't work.

A: Just put the following code in you TabBarViewController class.
- (void)viewDidLayoutSubviews
{
    // fix for iOS7 bug in UITabBarController
    self.selectedViewController.view.superview.frame = self.view.bounds;
}

A: To elaborate this answer, you can achieve the same result by editing the source code of the storyboard.
Replacing
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>

with
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>

for the view of the view controller that causes the problems.

A: I had the same problem. Putting the following code in my view controller's viewDidLoad fixed it:
self.view.autoresizesSubviews = YES;
self.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;

A: In the list of view controllers on the left hand side navigate to the views/view controllers affected, drag the view to underneath the first responder so that it is disassociated to the view controller's view.
Then go to the layout tab on the right hand side, select all 4 anchors and both sets of resizing arrows (horizontal + vertical).
Then drag the view back to where it was originally (just below the view controller).

A: I was also facing same issue and resolved it by adding following code inside app delegate's didFinishLaunchingWithOptions method.
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

window is the object of main interface .xib file.


text:
Q: Failed install of VirtualBox unable to uninstall, purge, or reinstall I'm trying to make the switch from Windows to GNU/linux. So far, I've installed Ubuntu, messed around with the command line a bit, and tried to install VirtualBox so I can run Windows 10 in a container and use it only for programs I can't run on linux or which run poorly on linux.
I've hit a snag.  I tried to install VirtualBox but ran into some trouble.  The install did not go successfully.  Now I'm trying to remove VirtualBox via this command:
sudo apt-get remove virtualbox

The result is as follows:
Reading package lists... Done
Building dependency tree
Reading state information... Done
Package 'virtualbox' is not installed, so not removed
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
1 not fully installed or removed.
After this operation, 0 B of additional disk space will be used.
debconf: DbDriver "config": /var/cache/debconf/config.dat is locked by another process: Resource temporarily unavailable
Setting up virtualbox-6.0 (6.0.24-139119~Ubuntu~eoan) ...
debconf: DbDriver "config": /var/cache/debconf/config.dat is locked by another process: Resource temporarily unavailable
dpkg: error processing package virtualbox-6.0 (--configure):
 installed virtualbox-6.0 package post-installation script subprocess returned error exit status 1
Errors were encountered while processing:
 virtualbox-6.0
E: Sub-process /usr/bin/dpkg returned an error code (1)

I've tried the clean, remove, reinstall commands. No dice. Any help? Total noob here.


text:
Q: При запуске приложения не видно картинки внутри кнопки Привет. Есть такой xaml код
`
<Button x:Name="goBack"  HorizontalAlignment="Left" Margin="10,10,0,0"VerticalAlignment="Top" Width="58" Height="50" FontSize="16" Cursor="Hand" Click="goBack_Click" Background="{x:Null}" BorderBrush="{x:Null}" Foreground="{x:Null}">
    <StackPanel Orientation="Horizontal">
        <Image Source="Img/back.png" Stretch="Uniform" Height="45" Width="50" />
    </StackPanel>
</Button>

`
В preview картинка отображается нормально, но при запуске ничего не видно и на клик, соответственно, не отвечает.
Почему? Вроде высоту и ширину везде указал.


text:
Q: SELF_SIGNED_CERT_IN_CHAIN error while using npm install Whenever I run npm install , I get an error
Error: SELF_SIGNED_CERT_IN_CHAIN.
How to resolve this error?

A: Even I used to get this error. Try following steps.
Steps to be followed to overcome this error:
1)  Run these three commands in a sequence.

*

*npm config set strict-ssl false

*npm update npm –g

*npm config set strict-ssl true
2)  Set properties proxy and https-proxy in the npm config using these commands:

*

*npm config set proxy="http://"proxy-name":8080"

*npm config set https-proxy="http://"proxy-name":8080"
Then try installing your packages using commands you tried.
Hope this helps.


text:
Q: vba using win32 api, showwindow function closes window #If VBA7 And Win64 Then
    Private Declare PtrSafe Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long
    Private Declare PtrSafe Function PostMessage Lib "user32" Alias "PostMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long
    Private Declare PtrSafe Function GetClassName Lib "user32" Alias "GetClassNameA" (ByVal hwnd As Long, ByVal lpClassName As String, ByVal nMaxCount As Long) As Long
    Private Declare PtrSafe Function ShowWindow Lib "user32" (ByVal hwnd As Long, ByVal nCmdShow As Long) As Long
#End If

Private Sub close_window()

Dim WinWnd As Long, Ret As String, RetVal As Long, lpClassName As String
'Ask for a Window title
'Ret = InputBox("Enter the exact window title:" + Chr$(13) + Chr$(10) + "Note: must be an exact match")
'Search the window
WinWnd = FindWindow(vbNullString, "somedocument.docx - Word")
If WinWnd = 0 Then MsgBox "Couldn't find the window ...": Exit Sub
'Show the window
ShowWindow WinWnd, SW_SHOWNORMAL
'Create a buffer
lpClassName = Space(256)
'retrieve the class name
RetVal = GetClassName(WinWnd, lpClassName, 256)

'Show the classname
MsgBox "Classname: " + Left$(lpClassName, RetVal)
'Post a message to the window to close itself

'PostMessage WinWnd, WM_CLOSE, 0&, 0&
End Sub

The purpose of the aforementioned code is to close a Word document. But, even if comment the PostMessage WinWnd, WM_CLOSE, 0&, 0&
as showed above, the word doc indeed closes whereas uncommenting the postmessage command, the window doesn't close. I have come to the conclusion (by commenting line by line the above code) that ShowWindow WinWnd, SW_SHOWNORMAL function closes the window(word document). Is this normal?

A: Following FaneDuru's suggestions here is the code that succesfully accomplishes the task:
#If VBA7 And Win64 Then
Private Declare PtrSafe Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As LongPtr
Private Declare PtrSafe Function PostMessage Lib "user32" Alias "PostMessageA" (ByVal hwnd As LongPtr, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long
Private Declare PtrSafe Function GetClassName Lib "user32" Alias "GetClassNameA" (ByVal hwnd As Long, ByVal lpClassName As String, ByVal nMaxCount As Long) As Long
Private Declare PtrSafe Function ShowWindow Lib "user32" (ByVal hwnd As LongPtr, ByVal nCmdShow As Long) As Long

#End If

Private Sub Form_Load()

Dim WinWnd As LongPtr, Ret As String, RetVal As Long, lpClassName As String
'Ask for a Window title
'Ret = InputBox("Enter the exact window title:" + Chr$(13) + Chr$(10) + "Note: must be an exact match")
'Search the window
 WinWnd = FindWindow(vbNullString, "some_document.docx - Word")
 If WinWnd = 0 Then MsgBox "Couldn't find the window ...": Exit Sub
 'Show the window
 ShowWindow WinWnd, SW_SHOWNORMAL
 'Create a buffer
 lpClassName = Space(256)
 'retrieve the class name
 'RetVal = GetClassName(WinWnd, lpClassName, 256)

 'Show the classname
 'MsgBox "Classname: " + Left$(lpClassName, RetVal)
 'Post a message to the window to close itself

 PostMessage WinWnd, WM_CLOSE, 0&, 0&
 End Sub


text:
Q: Variable not updating in addeventlistener after value change I have a variable set to false. I also have a addEventListener so when I click on the button, it should show me the variable's value (true or false).
I have another button that changes the variable's value to true. So when I press that button to change it to true, and then I check the variable's value with the addEventListener button, it should reflect as true. The problem is that it doesn't.
It should alert that the status is true after pressing the "Set Status" button. Why is the value not changing?
here is the code:
<button id="button">Set Status</button>
<br>
<button id="check-status">Check Status</button>

<script>
var status = false;

document.getElementById('check-status').addEventListener('click', function(event) {
    if(status === false) {
        alert('The status is false');
    } else {
        alert('The status is true');
    }
});

document.getElementById("button").onclick = function fun() {
    setStatusTrue();
}

function setStatusTrue() {
    var status = true;
}
</script>

Demo link: https://jsfiddle.net/xpLuh0ew/

A: You have messed up the scope of the variable. To set the status variable that is outside the function scope use:
function setStatusTrue() {
    status = true;
}

You can read more about scopes here


text:
Q: String.Split() using VbCrLf doesn't work but replacing VbCr with "" first then splitting on VbLf does work. Why? I have an embedded text file as a Resource. The content is:
Apple
Pear
Orange

I am trying to pull this into a List(Of String) but the Carriage Return and Line Feed characters are messing it up.
For example I try this:
Dim myNames As List(Of String) = My.Resources.TreeNames.Split(CChar(vbCrLf)).ToList

But the line feed character is being passed through:
"Apple"
vbLf & "Pear"
vbLf & "Orange"

so I try it using the environment variable:
Dim myNames As List(Of String) = My.Resources.TreeNames.Split(CChar(Environment.NewLine)).ToList

But that results in the exact same output.
So I try splitting it on the line feed character:
Dim myNames As List(Of String) = My.Resources.TreeNames.Split(CChar(vbLf)).ToList

And now the carriage return character is being passed through:
"Apple" & vbCr
"Pear" & vbCr
"Orange"

So the only way I got this to work is by first replacing the vbCr with nothing then splitting on the left over vbLf:
Dim myNames As List(Of String) = Replace(My.Resources.TreeNames, vbCr, "").Split(CChar(vbLf)).ToList

Can anyone explain why?  If I pull the file in directly to a string using this:
Dim myNames as String = My.Resources.TreeNames

I get:
"Apple" & vbCrLf & "Pear" & vbCrLf & "Orange"

Why is split not working properly?

A: See the Docs about CChar(<expression>):

Any valid Char or String expression; only first character of a String
is converted; value can be 0 through 65535 (unsigned)

So CChar(vbCrLf) returns just VbCr (\r - &H0D)
Since you're now splitting the source string on just VbCr, the Line Feed, VbLf (\n - &H0A), remains.
You need the overload of String.Split() that accepts an array of Strings or Chars:
Note that vbCrLf is a String Type, so are VbCr and VbLf
Dim res = My.Resources.TreeNames
' As an array of String
Dim myNames = res.Split({vbCrLf}, StringSplitOptions.RemoveEmptyEntries).ToList()
'Or
Dim myNames = res.Split({vbCr, VbLf}, StringSplitOptions.RemoveEmptyEntries).ToList()

Or as an array of Chars:
Dim myNames = res.Split(vbCrLf.ToCharArray(), StringSplitOptions.RemoveEmptyEntries).ToList()
' Or
Dim myNames = res.Split({ChrW(13), ChrW(10)}, StringSplitOptions.RemoveEmptyEntries).ToList()

StringSplitOptions.RemoveEmptyEntries is used to remove empty lines generated by splitting on multiple contiguous chars.
Without it, using your sample string - 3 items separated by Carriage Return + Line Feed - you would get an array of 5 elements instead of 3, including 2 empty elements.

A: I would not recommend using the VB constants. Instead, you should be using the Environment.NewLine property: https://learn.microsoft.com/en-us/dotnet/api/system.environment.newline
Per the documentation:

The property value of NewLine is a constant customized specifically
for the current platform and implementation of the .NET Framework.

Usage:
Dim myNames = My.Resources.TreeNames.Split(Environment.NewLine)

A: Of course, you could skip .Split altogether and just
Dim LinesList = File.ReadAllLines("txtFruit.txt").ToList

With Option Infer on hold your cursor over LinesList and you will see that it is a strongly typed List(Of String)


text:
Q: long polling using php mysql I found a script that uses php long polling. It uses the following code to see if the text file is changed and returns the content. This is received by the browser.
How can i change this to read a table and see if there are new events ?

$filename= dirname(__FILE__)."/data.txt";

$lastmodif = isset( $_GET['timestamp'])? $_GET['timestamp']: 0 ;
$currentmodif=filemtime($filename);

while ($currentmodif <= $lastmodif) {
usleep(10000);
clearstatcache();
$currentmodif =filemtime($filename);
}

$response = array();
$response['msg'] =Date("h:i:s")." ".file_get_contents($filename);
$response['timestamp']= $currentmodif;
echo json_encode($response);

How can i know if theres a new post ?


text:
Q: Can different tetrations have the same value? Suppose, we have two numbers
$a\uparrow \uparrow b$ and $c\uparrow \uparrow d$.
To avoid trivial cases, suppose $a,b,c,d>2$ and $(a,b)\ne (c,d)$.

Is there a quartupel $(a,b,c,d)$ with $a\uparrow\uparrow b=c\uparrow \uparrow d$ under the given conditions ?

In general, $b<d$ implies $a\uparrow \uparrow b<c\uparrow\uparrow d$, but if $a$
is large enough, $a\uparrow\uparrow b$ will exceed $c\uparrow \uparrow d$. So, this argument does not rule out the possibility of the equality.

A: No, that is not possible, not even if we allow one or more of $a,b,c,d$ to be $2$.
Suppose it was possible, assume without loss of generality that $a>c$, and consider the prime factorizations
$$ a = p_1^{\alpha_1} p_2^{\alpha_2} \cdots p_k^{\alpha_k} \\
c = p_1^{\gamma_1} p_2^{\gamma_2} \cdots p_k^{\gamma_k} $$
Because $a^{a\uparrow\uparrow (b-1)}=c^{c \uparrow\uparrow(d-1)}$ we must have that $\frac{\alpha_i}{\gamma_i}=\frac{c\uparrow\uparrow(d-1)}{a\uparrow\uparrow (b-1)} =: Q$ for every $i$.
The net exponent of $p_i$ in $\frac{c\uparrow\uparrow(d-1)}{a\uparrow\uparrow (b-1)}$ is $$\gamma_i(c\uparrow\uparrow(d-2))-\alpha_i(a\uparrow\uparrow(b-2))=\gamma_i\Bigl((c\uparrow\uparrow(d-2))-Q(a\uparrow\uparrow(b-2)\Bigr)$$
which has the same sign for every $i$, and since $a>c$, $Q$ must be an integer and $a=c^Q$.
But then $Q=\frac{c\uparrow\uparrow(d-1)}{a\uparrow\uparrow(b-1)}$ becomes
$$ Q = c^{c\uparrow\uparrow(d-2)-Q(a\uparrow\uparrow(b-2))}$$
Setting $R=\log_c Q$, this is
$$ R = c\uparrow\uparrow(d-2)-c^R(a\uparrow\uparrow(b-2)) $$
Now, $c\uparrow\uparrow(d-2)$ and $a\uparrow\uparrow(b-2)$ are both non-negative powers of $c$, so we have
$$ R = c^{\text{something}} - c^{R+\text{something}} $$
which must be positive (otherwise $Q=1$ and $a=c$) and is therefore a multiple of $c^{R+\text{something}}$. But for $R$ to be a multiple of $c^R$ when $c\ge 2$ is a contradiction!


text:
Q: Is it possible to decompile an Android .apk file? Are the users able to convert the apk file of my application back to the actual code?
If they do - is there any way to prevent this?

A: First, an apk file is just a modified jar file.  So the real question is can they decompile the dex files inside.  The answer is sort of.  There are already disassemblers, such as dedexer and smali.  You can expect these to only get better, and theoretically it should eventually be possible to decompile to actual Java source (at least sometimes).  See the previous question decompiling DEX into Java sourcecode.
What you should remember is obfuscation never works.  Choose a good license and do your best to enforce it through the law.  Don't waste time with unreliable technical measures.

A: Decompilation of APK file is possible. But it might be difficult to understand the code if it is  obfuscated.
Use Aapt (part of the Android SDK) or AXMLParser (from AndroGuard) to analyse and view info of an APK File

*

*Retrieves the content of the AndroidManifest.xml file

*Shows various information (e.g. permissions, activities, services, broadcast receivers, ...)

*Command:
Aapt
 aapt dump badging sampleApp.apk
 aapt dump permissions sampleApp.apk
 aapt dump xmltree sampleApp.apk

AXMLParser
 apkinfo sampleApp.apk

Use ApkTool or NinjaDroid to disassemble and view the resources of an APK File

*

*Disassembles the bytecode to smali/assembly

*Extracts the AndroidManifest.xml, the CERT.RSA file and everything in res folder (layout xml files, images, htmls used on webview etc..)

*Command:
ApkTool
apktool.bat d sampleApp.apk

java -jar apktool.jar -q decode -f sampleApp.apk -o myOutputDir

NinjaDroid
ninjadroid MyApk.apk --all --extract myOutputDir/

*NOTE: You can achieve something similar by using zip utility like 7-zip. But, these tools also extract the .smali files of all .class files.
Use dex2jar to decompile the DEX files of an APK File into Java code

*

*Generates the .jar file from a .apk file (note that the Java code of Android apps is usually obfuscated)

*Needs JD-GUI to view the source code from the output .jar file

*Command:
dex2jar sampleApp.apk

d2j-dex2jar.sh -f sampleApp.apk -o myOutputDir/sampleApp.jar

Use JD-GUI to view the .jar file

*

*Decompiles the .class files (obfuscated in a case of Android apps, but not in a case of other .jar files) and shows the corresponding Java code

A: I may also add, that nowadays it is possible to decompile Android application online, no software needed!
Here are 2 options for you:

*

*http://www.decompileandroid.com/

*http://www.javadecompilers.com/apk

A:
Are the users able to convert the apk file of my application back to the actual code?

yes.
People can use various tools to:

*

*analysis: your apk

*decode/hack your apk

*

*using FDex2 to dump out dex file

*

*then using dex2jar to convert to jar

*

*then using jadx to conver to java source code

If they do - is there any way to prevent this?

yes. Several (can combined) ways to prevent (certain degree) this:

*

*low level: code obfuscation

*

*using Android ProGuard

*high level: use android harden scenario

*

*such as

*Tecent Legu=腾讯乐固

*qihoo 360=360加固宝
More details can refer my Chinese tutorial: 安卓应用的安全和破解

A: Download this jadx tool https://sourceforge.net/projects/jadx/files/
Unzip it and than in lib folder run jadx-gui-0.6.1.jar file now browse your apk file.
It's done. Automatically apk will decompile and save it by pressing save button.
Hope it will work for you.
Thanks

A: Sometimes you get broken code, when using dex2jar/apktool, most notably in loops. To avoid this, use jadx, which decompiles dalvik bytecode into java source code, without creating a .jar/.class file first as dex2jar does (apktool uses dex2jar I think). It is also open-source and in active development. It even has a GUI, for GUI-fanatics. Try it!

A: Yes, there are tons of software available to decompile a .apk file.
Recently, I had compiled an ultimate list of 47 best APK decompilers on my website. I arranged them into 4 different sections.

*

*Open Source APK Decompilers

*Online APK Decompilers

*APK Decompiler for Windows, Mac or Linux

*APK Decompiler Apps

I hope this collection will be helpful to you.
Link: https://www.edopedia.com/blog/best-apk-decompilers/