text:
Q: Python FBProphet ValueError: Must pass 2-d input I'm experiencing an error I can't figure out a solution for. I have 5,000 records I feeding through Prophet but get a ValueError: Must pass 2-d input . shape=(124, 56, 16) error. Any easy fixes, or explanations on what I need to change? Thanks!
import pandas as pd
import os
from fbprophet import Prophet

# Read in File
df1 = pd.read_csv('C:\\Users\\capnb\\Documents\\Sales10.csv')

#Create Loop to Forecast Multiple SKUs
def get_prediction(df):
    prediction = {}
    df1 = df.rename(columns={'date': 'ds','quantity ordered': 'y', 'UID': 'item'})
    list_items = df1.item.unique()

    for item in list_items:
        item_df = df1.loc[df1['item'] == item]
        # set the uncertainty interval to 95% (the Prophet default is 80%)
        my_model = Prophet(yearly_seasonality= True, seasonality_prior_scale=1.0)
        my_model.fit(item_df)
        future_dates = my_model.make_future_dataframe(periods=12, freq='M')
        forecast = my_model.predict(future_dates)
        prediction[item] = forecast
    return prediction

# Save predictions to dictionary
df2 = get_prediction(df1)
df3 = pd.DataFrame.from_dict(df2,orient='index')

def flatten(dict_of_df):
    # insert column 'item'
    for key, value in dict_of_df.items():
        value['item'] = key

    # return vertically concatenated dataframe with all the items
    return pd.concat(dict_of_df.values())
df4 = flatten(df2)

df4.to_csv ('C:\\Users\\capnb\\Desktop\\export_dataframe8.csv', index = False, header=True)

print (df4)


text:
Q: MATLAB "filter" function in C/C++ I've been tasked with recoding a MATLAB script into C or C++, and I'm having a little difficulty wrapping my head around this filter function (filter(a, b, x)). Does anyone know of a simple way to do this, or an existing C library that accomplishes the same thing?
Thanks!

A: Just implement the filter function as described here. This resembles just a tapped delay-line filter, where b and a are coefficients and x is the input data:
a[1]y[n] = b[1]x[n]+b[2]x[n-1]+...+b[N]x[n-B+1]-a[2]y[n-1]-...-a[N]y[n-N+1]

You only have to take care about not-yet-existing indices, which are denoted by the square brackets. a and b are vectors of length N.

redpajama_set_name: RedPajamaStackExchange


text:
Q: AJAX POST request in Spring-MVC does not works I am learning Spring MVC and I have stuck at how to send a simple string value from client using AJAX and print it at JAVA server (controller). I have written below code for doing this. But when I click button to send string, error.... response is popped-up in my browser and the browser console displays POST http://localhost:8090/addUser 404 (). It has been a day since I am trying to solve this issue. Can someone please tell what can be the problem? Or please tell a working alternative solution for sending data from client using AJAX and printing/saving it on JAVA server (Spring-MVC).
UserController.java
@Controller
public class UserController {

    @RequestMapping(value = "/addUser", method = RequestMethod.POST, consumes=MediaType.APPLICATION_JSON_VALUE, produces=MediaType.APPLICATION_JSON_VALUE)
    public JSONArray addUser(@ModelAttribute("UserTest") JSONArray name) {
        System.out.println(name.toString());
        return name;
    }
}

AJAX Request:
<script>
    function addUser() {
        var json = '{"uname":"John", "Age":42}';
            obj = JSON.parse(json);
            $.ajax({
                    url : "/addUser",
                    data : obj,
                    type : "POST",
                    async: false,
                    contentType: "application/json",
                    success : function(response) {
                             alert( response );
                    },
                    error : function() {
                        alert("error...."); //this is being popped-up in my browser
                    }
            });
       }
</script>

A:
POST http://localhost:8090/addUser 404 ()

Your request is going to http://localhost:8090/addUser, which is not correct. Your request url should have your application and included.
http://localhost:8090/<app_name>/addUser

AFAIK, your request url should have application name included. Now, to achieve this, you are suppose to change your ajax url
 url : "/<app_name>/addUser"

A: The URL for the ajax call is not correct. It should be like
Url:YourApplicationContextPath/ControllerName/addUser


text:
Q: Multiple user owning a directory in Linux I have 2 users www-data & ubun who needs to own a particular directory /opt/sw/vam
How can I set the access accordingly?
I did this -
sudo chown -R www-data:www-data /opt/sw/vam and now ubun cannot access the folders..
How do I give both the users permission..

A: Either create a group they can share, give that group the perms they need, and set it as the group for the directory or use ACLs as Barmar suggested. I've personally never used ACLs and since groups are more natural in *nix, I would go with the group method. But ACLs would work.
You could to this by:
sudo groupadd [group name]
sudo usermod -a -G [group name] www-data
sudo usermod -a -G [group name] ubun
sudo chown -R [whichever]:[group name] /opt/sw/vam

Then you need to give set the group permissions like you have the user permissions now. Probably everything, so sudo chmod -R g+a /opt/sw/vam.
The [whichever] can refer to either user, since it won't matter because they will both be in the group and get the permissions given to the group.


text:
Q: A question on magic square A magic square of order $N$ is an $N\times N$ matrix with positive integral entries such that the elements of every row, every collumn and the two diagonals all add up to the same number.
If a magic square is filled with numbers in AP starting with $a \in \mathbb{N}$ and common difference $d \in \mathbb{N}$ what is the value of this common sum?
I am thinking that it is just a sum of the AP given? I mean $$\frac{N}{2}[2a+(N-1)d]$$ Am I right?

A: Let $s$ be the common sum. Then each row sums to $s$, and there are $N$ rows, so the sum of all the numbers in the square is $Ns$. That is,
$$\frac{N^2}2\Big(2a+(N^2-1)d\Big)=Ns\;,$$
and $$s=\frac{N}2\Big(2a+(N^2-1)d\Big)\;.$$
(Note that you miscounted the number of terms in the sequence when you wrote down your expression for the sum.)


text:
Q: Save a resource received from API to a file I don't know if this is possible, so I am not really sure how to word this question. I am completely new to resources in PHP... Please forgive me if this sounds silly - I am all ears on suggestions on how to better this question.
I have been given code that makes an API call to a soap client. When it does this, an object is returned and part of that object is resources.
$myService = (object)array(
   'stuff' => MyCode::getClient('stuff_I_want_access_to')
);

When I print out 'stuff', I get something like this (some parts have been omitted as they aren't required for this question):
MyCode Object
(
    [_headers:protected] => Array
        (
        )

    [_stream_context] => Resource id #14
)

The issue with this particular code is that when I need to use it (which is often multiple times a day), I have to make these API calls for every command. This can take anywhere from 2-15 minutes depending on server load. To mitigate this wait time, I would like to save the objects returned from the API in some way so I can easily reference it later without making the API calls over again.
The issue I am running into is saving the resource. So far, anything I have tried does save all the keys, but it does not save the "Resource ID #14".Instead, it saves something like this:
[_stream_context] => 0

Is it possible to save resources? I am guessing that the Resource is really a pointer, but I don't know how that works.


text:
Q: Squid is not caching I have been trying to install Squid version 3.1.20 on Ubuntu version 12.10 by entering sudo apt-get install squid, but the problem is the squid I installed it is not caching. I tried to browse to the same websites many times it keep showing me TCP_MISS all the times. As I understand it should show TCP_HIT.
The configuration is very simple. I just added the below statements into the squid configuration file.
acl allow_network src 172.16.0.0/16

http_access allow allow_network

Please help me to fix the problem.

A: First off, Squid 3 is installed by:
sudo apt-get install squid3
Then, you have to add your acl, which you have done, good.
Then you need to create your cache_dirs by running:
sudo squid3 -z
Then you need to start the service:
sudo service squid3 start
After that, you might need to tweek your config a bitty, look at: allow_cache and always_direct, you really don't want the latter! Have a read of this: http://wiki.squid-cache.org/SquidFaq/ConfiguringSquid#Can_I_make_Squid_proxy_only.2C_without_caching_anything.3F for what NOT to do. I tend to use cache allow all


text:
Q: Change WCF Service binding to https at runtime We have an application that is deployed to many clients, some of which use http others https.  When setting up our application the web.config is automatically populated with the WCF endpoints, bindings, etc.  We would like to change over the binding to https upon application startup - without modifying the .config file.  Is this possible?  For example our .config file looks like (this is a snippet):
  <service behaviorConfiguration="Figment.Services.Business.ObjectInfo.ObjectInfoServiceBehavior" name="Figment.Services.Business.ObjectInfo.ObjectInfoService">
    <endpoint address="" binding="basicHttpBinding" bindingNamespace="http://Figment.com/webservices/" contract="Figment.Business.Core.ObjectInfo.IObjectInfoService" />
    <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
  </service>

From what I have read it is possible to have an http and https binding at the same time, but we do not want this - if it is https then force it over to use https.
The change should be done in c# on service startup and be permanent while the service is running.

A: I know it is an old question, but I have had the same problem and found no answer on the SO. As it took me a couple days of digging to solve the problem, I think it is worth posting it here.
You generally have 3 options here:
1) Configure your service host completely in code (ignoring *.config) as per here
2) Make a script to modify *.config or use other config as per here
3) Use both *.config and programmatic binding configuration
Option (3) is tricky as you have to modify your service host after it has been created but before it would be open (something like host.State == Created). This because modification of bindings of an already open host has no effect. More details here.
To get (3) work you have to use custom host factory. Sample markup:
<%@ ServiceHost
    Language="C#"
    Debug="true"
    CodeBehind="MyService.svc.cs"
    Service="Namespace.MyService, MyService"
    Factory="Namespace.MyWcfHostFactory, MyService"
%>

MyWcfHostFactory should inherit ServiceHostFactory and extend/override CreateServiceHost method.
I am using DI framework (Autofac) which simplifies things a bit. So MyWcfHostFactory just inherits AutofacHostFactory. Startup code (called from either Global.asax Application_Start or static constructor of MyWcfHostFactory):
var builder = new ContainerBuilder();

// Register your service implementations.
builder.RegisterType< Namespace.MyService>();

// Set the dependency resolver.
var container = builder.Build();
AutofacHostFactory.Container = container;
AutofacHostFactory.HostConfigurationAction = (host => PerformHostConfiguration(host));

In PerformHostConfiguration you can overwrite or modify bindings. Code below takes 1st registered endpoint and replaces its binding with https one:
/// <summary> This is used as a delegate to perform wcf host configuration - set Behaviors, global error handlers, auth, etc </summary>
private static void PerformHostConfiguration(ServiceHostBase host) {
    var serviceEndpoint = host.Description.Endpoints.First();
    serviceEndpoint.Binding = new BasicHttpBinding {
        ReaderQuotas = {MaxArrayLength = int.MaxValue},
        MaxBufferSize = int.MaxValue,
        MaxReceivedMessageSize = int.MaxValue,
        Security = new BasicHttpSecurity {
            Mode = BasicHttpSecurityMode.Transport, //main setting for https
        },
    };
}


text:
Q: Ttrigger extra parameter According to the jQuery manual you can send extra parameters (as an array) when calling a trigger. I am using this at the moment:
$('#page0').trigger('click', [true]);

How would I pick up whether the paramter has come through or not when using this?
$('ul.pages li a').click(function() {
  // Do stuff if true has been passed as an extra parameter
});

A: $('ul.pages li a').click(function(event, param) {
  if (param) {
    // Do stuff if true has been passed as an extra parameter
  }
});

If the click event was triggered normally, param will be undefined and body of the if statement won't execute.

A: You could also use the arguments array without specifying a permanent function prototype (arguments[0] is the event itself):
$('.post-text').click(function() {
    if(arguments[1]===true) {
        // do something
    }
});

$('.post-text').trigger('click',[true]);


text:
Q: Размер шрифта в зависимости от разрешения TextBox Пользователь может изменять размер формы. В соответствии с этим изменяется и размер TextBox. Можно ли сделать, чтобы шрифт текста в TextBox увеличивался/уменьшался в зависимости от размеров TextBox?

A: Вешаем обработчик на SizeChanged текстбокса.
Код обработчика
private void ResizeFont(object sender, System.EventArgs e)
{
    TextTextBox.Font = new System.Drawing.Font(TextTextBox.Font.FontFamily, TextTextBox.Size.Height * 25 / 100);
}


text:
Q: Evaluating limit of $\lim_{x \to 0^+} x \ln(x)$ Problem.
Evaluate the limit $$\lim_{x \to 0^+} x \ln(x)$$
I split the limit up in a product of $x$ and $\ln(x)$ and get $0 \cdot -\infty$ which sounds a bit shady...Can I simply say that this is obviously $0$ because $0 \cdot a = 0, \forall a \in \mathbb{R}$...?

A: Hint:
$$
\lim_{x \to 0^+} x\ln(x) =\lim_{x \to 0^+} \frac{\ln(x)}{1/x}
$$

A: Another way to think about it: let $x=e^{-t}$; then the limit becomes:
$$\lim_{t\to \infty}\;\; -t \, e^{-t}$$
Maybe that's clearer.

A: As shown in this answer, for all $x\in\mathbb{R}$,
$$
x\lt1+x\le e^x\tag{1}
$$
If $u\gt0$, applying $(1)$ to $u/2$ and squaring gives
$$
u^2/4\lt e^u\tag{2}
$$
Multiplying $(2)$ by $\dfrac4{ue^u}$ yields
$$
0\lt\frac{u}{e^u}\lt\frac4u\tag{3}
$$
Thus, applying $(3)$ and the Squeeze Theorem,
$$
\begin{align}
\lim_{x\to0^+}x\log(x)
&=\lim_{x\to0^+}\log(x)e^{\log(x)}\\
&=\lim_{u\to\infty}-ue^{-u}\\
&=-\lim_{u\to\infty}\frac{u}{e^u}\\[3pt]
&=0\tag{4}
\end{align}
$$

A: $$\lim_{x\to 0} x\log x=\lim_{x\to 0}\frac{\log x}{\frac1x}\stackrel{l\,'H}=\lim_{x\to 0}\frac{\frac1x}{-\frac1{x^2}}=\ldots$$

A: Set $t=\frac{1}{x}$, then
$$\lim_{x \to 0^+} x \ln(x)=\lim_{t\rightarrow +\infty}\frac{\log(\frac{1}{t})}{t}=\lim_{t\rightarrow +\infty}\frac{-\log(t)}{t}=0.$$


text:
Q: The definition of a vector space: closure under scalar multiplication I'm have problem proving: Law for Scalar Multiplication :
Vector spaces possess a collection of specific characteristics and properties. Use the definitions in the attached "Definitions" to complete this task.
Define the elements belonging to $\mathbb{R}^2$ as $\{(a, b) | a, b \in \mathbb{ R}\}$. Combining elements within this set under the operations of vector addition and scalar multiplication should use the following notation:
Vector Addition Example: $(–2, 10) + (–5, 0) = (–2 – 5, 10 + 0) = (–7, 10)$
Scalar Multiplication Example: $–10 × (1, –7) = (–10 × 1, –10 × –7) = (–10, 70)$, where –10 is a scalar.
Under these definitions for the operations, it can be rigorously proven that R2 is a vector space.
Prove Closure under Scalar Multiplication - **i need help with this law **
Can someone put it in a proof form?

A: If you're asking if vector spaces are closed under multiplication by a scalar, then yes, it is true. If you're asking why, it's because it's written in the definition of a vector space that it must be true ; there is nothing to prove here. It's true because we assume it is when we speak of a vector space.
EDIT : So if I understand this correctly, you need to show that $\mathbb R^2$ is a vector space and you need help showing that $\mathbb R^2$ is closed under scalar multiplication. Scalar multiplication is defined for $\lambda \in \mathbb R$ and $(a,b) \in \mathbb R^2$ via
$$
\lambda \cdot (a,b) \overset{def}= (\lambda a, \lambda b)
$$
where $\lambda a$ is the usual multiplication of real numbers. What you want to show is that
$$
\forall \lambda,a,b \in \mathbb R, \quad \lambda \cdot (a,b) \in \mathbb R^2.
$$
Is it obvious now?
Hope that helps,

A: If $V$ is a vector space over the field $\mathbf F$, then it must satisfy two properties, namely closure under addition and closure under multiplication.
For closure under multiplication, we demand that if $u \in V$, $a \in \mathbf F$, then $a \mathbf F \in V$. Note that the 'multiplication' needs to be defined beforehand.
Specifically to your example, perhaps you are having trouble with what's meant by closure. According to the definition, you want to prove that $S:\{(a,b)|a,b \in \mathscr R\}$ is a vector space.
You have actually done it. You have shown it is closed under addition as well as multiplication.
Let's take your example,$–10 \times (1, –7) = (–10 \times 1, –10 \times –7) = (–10, 70)$, the original vector$(1,-7) \in S$,right? Also$(-10,70) \in S$ because let $a=-10,b=70$, then you see $(-10,70)$ satisfy the requirement $a,b \in R$. Thus you have proved closure under multiplication.
Edit: I will try to prove the statement

$\mathbb R^2$ is a vector space over the field $\mathbb R$

Proof:
if $ a,b \in \mathbb R$, then $(a,b) \in \mathbb R^2$. Let $k \in \mathbb R$ be a scalar, then $k(a,b)=(ka,kb)$. As $k,a,b \in \mathbb R$, $ka,kb \in \mathbb R$, thus $(ka,kb) \in \mathbb R^2$. Therefore scalar multiplication on $\mathbb R^2$ is closed.

A: Take the examples of all directed arrows (every possible length and every possible angle) originating from a single point.
Now in this set vector addition is like addition of forces in physics: parallelogram law. In this set internally there is addition. Also there is an external operation. Any vector can be "scaled up/down" by any real number. This real number is not part of the set of arrows. But it makes sense to  talk of 3.75 times a force. SImply a force directed in the same way but with with strength 3.75 times the original. This is depicted as an arrow of that length in the same direction.
In general any set where we can add them among themselves, and multiply by an external scalar usually the set of real numbers subject to some expected conditions is called a vector space.


text:
Q: Calculating the entropy rate of ADCs Formally, the entropy of a normal distribution is:-
$$ \frac{1}{2} \log(2 \pi e \sigma^2) $$
So if you're sampling a random (normally distributed) signal, that would seem to be the rate of entropy generation. I take it that if the logarithm is base 2, then the entropy would be in units of bits. So a process with a standard deviation of 1V creates 2.05 bits of entropy /sample.
My problem is with the rate calculation.  I thought that the entropy rate would be governed by the precision of the samples.  A 16 bit ADC must by definition create more sample data than an 8 bit ADC if they both cover the same voltage range. Intuitively more precision suggests more data. More data suggests more entropy.
My question is why does the entropy formula above take no account of sample precision?

Note. I suspect that this is not the appropriate formula for ADCs.

Edit. It's not. I think that I can manage to formulate the min.entropy for a normal distribution.  Min. entropy is used in cryptography and randomness extraction and would be good enough.  I get:-
$$ H_{min}  = -log_2 \left[ 2 \Phi \left(\frac{V_s - \mu}{\delta} \right) - 1 \right] $$
where \$ V_s \$ is half of the minimum ADC voltage step, as:-
$$ V_s = \frac{V_{range}}{2^{N+1}} $$
for an \$ N \$ bit ADC digitising a range of \$ V_{range} \$ volts. And generally, for any distribution such as a (asymmetrical) log normal that you might get sampling a diode's avalanche noise:-
$$ H_{min} = -log_2 \left[ CDF(v'_{max}) - CDF(v'_{min}) \right] $$
where \$ v'_{max}, v'_{min} \$ are the two quantized  max. min. boundaries of the smallest ADC step based on \$ V_s = \frac{V_{range}}{2^{N}} \$ and which bound the mode.
Thus I think that I had totally the wrong equation...

A: That's the continuous (differential) entropy; not the entropy of the discrete random variable that your ADC output is!
You could (and seeing your profile page, you'll probably have a lot of fun doing that) look into what is called rate distortion in the field that concerns itself with information entropy, information theory. Essentially, an ADC doesn't "let through" all the entropy entering it, and there's ways of measuring that.
But in this specific case, things are simpler.
Remember: The entropy of a discrete source \$X\$ is the expectation of information
$$H(X) = E(I(X))$$
and since your ADC output \$X\$ has very finitely many, countable amounts of output states, the expectation is just a sum of probability of an output \$x\$ times the information of that output:
\begin{align}
H(X) &= E(I(X))\\
&= \sum_{x} P(X=x) \cdot I(X=x)\\
&= \sum_{x} P(X=x) \cdot \left(-\log_2(P(X=x))\right)\\
&= -\sum_{x} P(X=x) \log_2(P(X=x))
\end{align}
Now, first observation: \$H(X)\$ of an \$N\$-bit ADC has an upper bound: you can't ever get more than \$N\$ bits of info out of that ADC. And: you get exactly \$H(X)=N\$ if you use the discrete uniform distribution for the values over the \$2^N\$ ADC steps (try it! set \$P(X=x) = \frac1{2^N}\$ in the formula above, and remember that you sum over \$2^N\$ different possible output states).
So, we can intuitively conclude that the digitized normal distribution yields fewer bits of entropy than the digitized uniform distribution.
Practically, that means something immensely simple: Instead of using, say, one 16-bit ADC to digitize your normally distributed phenomenon, use sixteen 1-bit ADCs to observe 16 analog normally distributed entities, and only measure whether the observed value is smaller or larger than the mean value of the normal distribution. That "sign bit" is uniformly distributed over \$\{-1, +1\}\$, and thus, you get one full bit out of every 1-bit ADC, summing to 16 total bits. If your noise source is white (that means: one sample isn't correlated to the next), then you can just sample 16 times as fast as your 16-bit ADC with your 1-bit ADC, and get the full 16 bit of entropy in the same time you would have done one 16-bit analog-to-digital conversion¹.
How many bits of entropy does the quantized normal distribution have?
But you had a very important question: How many bits do you get when you digitize a normal distribution?
First thing to realize:

The normal distribution has tails, and you will have to truncate them; meaning that all the values above the largest ADC step will be mapped to the largest value, and all the values below the smallest to the smallest value.
So, what probability do the ADC steps then get?
I'll do the following model:

*

*As shown above, the sign of our \$\mathcal N(0,1)\$ distributed variable is stochastically independent from the absolute value. So, I'll just calculate the values for the ADC bins \$\ge0\$; the negative ones will be symmetrically identical.

*Our model ADC covers \$[-1,1]\$ analog units; it has \$N+1\$ bits. Meaning that I'll cover \$[0,1]\$ with \$N\$ bits below.

*The smallest non-negative ADC bin thus covers analog values \$v_0=[0,2^{-N}[\$; the one after that \$v_1=[2^{-N},2\cdot 2^{-N}[\$. The \$i\$th bin (counting from 1, \$i<2^N-1\$) covers $$v_i=[i\cdot 2^{-N},(i+1)\cdot 2^{-N}[$$.

*Most interesting, however, is the last bin: it covers $$v_{2^N-1}=[
(2^N-1)\cdot 2^{-N},\infty[=[1-2^{-N},\infty[$$.

So, to get the entropy, i.e. the expected information, we'll need to calculate the individual bin's information, and average these, i.e. weigh each bin's information with its probability. What is the probability of each bin?
\begin{align}
P(X\in v_i|X>0) &= \int\limits_{i\cdot 2^{-N}}^{(i+1)\cdot 2^{-N}} f_X(x)\,\mathrm dx && {0\le i<2^N-1}\\
&= 2\left(F_X\left((i+1)\cdot 2^{-N}\right)-F_X\left(i\cdot 2^{-N}\right)\right) &&|\text{ standard normal}\\
&= 2\Phi\left((i+1)\cdot 2^{-N}\right)-2\Phi\left(i\cdot 2^{-N}\right)\\[1.5em]
P(X\in v_{2^N-1}|X>0) &=\Phi(\infty)-2\Phi\left(1- 2^{-N}\right)\\
&= 1-2\Phi\left(1- 2^{-N}\right)
\end{align}
So, let's plot the information of a 5-bit ADC (which means 4 bits represent the positive values):

Summing up the $\P\$ from above, we see that we only get 3.47 bits.
Let's actually do an experiment: Does my ADC pay?
We'll simply plot entropy that we get over ADC bits that we pay for.

As you can see, you get diminishing returns for added cost; so don't use a high-resolution ADC to digitize a strongly truncated normal distribution
Scaling the ADC range
As was rather intuitive from the previous sections, the problem is that the boundary bin accumulates too much probability mass.
What if we scaled the ADC range, to cover \$[-a\sigma, a\sigma]\$ instead of just \$[-\sigma, \sigma]\$?

Which confirms our suspicion that there's a maximum entropy you'll get when you "kinda" make your normal distribution look relatively uniform:

source code
The scripts used to generate above figures can be found on Github.

¹ in fact, you must take a close look at the architecture of your ADC: ADCs are typically not meant to digitize white noise, and thus, many ADC architectures strive to "color" the white noise e.g. by shifting the noise energy to higher frequencies when measuring the output value successively; an introduction to the Delta-Sigma ADC is a must-read here! And I'm certain you'll enjoy that :)


text:
Q: Arduino MPU6050 Sensor Not Working with Code from Arduino's Website I keep getting the following in the serial monitor over and over:
AcX = -1 | AcY = -1 | AcZ = -1 | Tmp = 36.53 | GyX = -1 | GyY = -1 | GyZ = -1
I am using the following code that I got off http://playground.arduino.cc/Main/MPU-6050#sketch:
// MPU-6050 Short Example Sketch
// By Arduino User JohnChi
// August 17, 2014
// Public Domain
#include<Wire.h>
const int MPU=0x68;  // I2C address of the MPU-6050
int16_t AcX,AcY,AcZ,Tmp,GyX,GyY,GyZ;
void setup(){
  Wire.begin();
  Wire.beginTransmission(MPU);
  Wire.write(0x6B);  // PWR_MGMT_1 register
  Wire.write(0);     // set to zero (wakes up the MPU-6050)
  Wire.endTransmission(true);
  Serial.begin(9600);
}
void loop(){
  Wire.beginTransmission(MPU);
  Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
  Wire.endTransmission(false);
  Wire.requestFrom(MPU,14,true);  // request a total of 14 registers
  AcX=Wire.read()<<8|Wire.read();  // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
  AcY=Wire.read()<<8|Wire.read();  // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
  AcZ=Wire.read()<<8|Wire.read();  // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
  Tmp=Wire.read()<<8|Wire.read();  // 0x41 (TEMP_OUT_H) & 0x42 (TEMP_OUT_L)
  GyX=Wire.read()<<8|Wire.read();  // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
  GyY=Wire.read()<<8|Wire.read();  // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
  GyZ=Wire.read()<<8|Wire.read();  // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)
  Serial.print("AcX = "); Serial.print(AcX);
  Serial.print(" | AcY = "); Serial.print(AcY);
  Serial.print(" | AcZ = "); Serial.print(AcZ);
  Serial.print(" | Tmp = "); Serial.print(Tmp/340.00+36.53);  //equation for temperature in degrees C from datasheet
  Serial.print(" | GyX = "); Serial.print(GyX);
  Serial.print(" | GyY = "); Serial.print(GyY);
  Serial.print(" | GyZ = "); Serial.println(GyZ);
  delay(333);
}

This is the wiring I am using: http://jamesmpoe.com/roboticswiki/images/4/45/MPU6050-Arduino-Uno-Connections.jpg
I do not know what is wrong.
Thank you for your help.

A: First of all, I'd set the clock to the X gyroscope oscillator instead of the internal oscillator (as it is suggested on the MPU6050 datasheet), hence
Wire.beginTransmission(MPU);
Wire.write(0x6B);  // PWR_MGMT_1 register
Wire.write(1);     // set to one to turn on the Xgyro oscillator
Wire.endTransmission(true);

In my project, however, I wrote a lot more initializations... I suggest you to

*

*Write some functions to write/read bit(s), byte(s) and word(s) on the I2C interface, because you'll need them

*Write functions to get and set the important parts of the registers in the MPU6050

*Write more complex functions.

Examples:
// I2C interface
bool i2c_writeBytes(uint8_t devAddr, uint8_t regAddr, uint8_t length, uint8_t* data)
{
    Wire.beginTransmission(devAddr);
    Wire.write((uint8_t) regAddr); // send address

    for (uint8_t i = 0; i < length; i++)
    {
        Wire.write((uint8_t) data[i]);
    }
    return (Wire.endTransmission() == 0);
}

// Simple function
int16_t mpu6050_getAccelerationX() {
    i2c_readBytes(MPU6050_ADDRESS, MPU6050_RA_ACCEL_XOUT_H, 2, rwBuffer);
    return (((int16_t)rwBuffer[0]) << 8) | rwBuffer[1];
}

// Complex function
void mpu6050_initialize()
{
    mpu6050_reset();
    delay(100);
    mpu6050_setClockSource(MPU6050_CLOCK_PLL_XGYRO);
    mpu6050_setSleepEnabled(false);
    mpu6050_setWakeCycleEnabled(false);
    mpu6050_switchSPIEnabled(false);
    mpu6050_setI2CMasterModeEnabled(false);
    mpu6050_setFIFOEnabled(false);
    delay(100);

    mpu6050_setRate(7); // 1kHz scan freq
    mpu6050_setDLPFMode(MPU6050_DLPF_BW_256);
    mpu6050_setFullScaleGyroRange(MPU6050_GYRO_FS_250);
    mpu6050_setFullScaleAccelRange(MPU6050_ACCEL_FS_2);
    mpu6050_setInterruptMode(MPU6050_INTMODE_ACTIVEHIGH);
    mpu6050_setInterruptDrive(MPU6050_INTDRV_PUSHPULL);
    mpu6050_setInterruptLatch(MPU6050_INTLATCH_WAITCLEAR);
    mpu6050_setInterruptLatchClear(MPU6050_INTCLEAR_ANYREAD);
    mpu6050_setFSyncInterruptEnabled(0);
    mpu6050_setI2CBypassEnabled(0);
    mpu6050_setClockOutputEnabled(0);
    mpu6050_setIntEnabled(MPU6050_INTERRUPT_MASK_DATA_RDY_BIT); // Interrupt when data ready
}

A useful resource is the MPU6050 registers map (you can find it here).

A: It was a soldering error.
It works perfectly with the code above.


text:
Q: meta name viewport doesn't work correctly I tried all these meta tags on my website but no one of them worked:
<meta name="viewport" width="device-width">

<meta name="viewport" content="width=device-width, initial-scale=1.0" />

<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">

But when I add @-ms-viewport{ width: device-width; } to style.css it works, but the width is not 100% on my iPhone and Samsung tab, users still need to scroll horizentally.
My main content width is 1070px.

A: i dont know your page, but i got a similar problem some days ago.
The problem was, that padding-commands made divs bigger than they should have been and this resulted in a horizontal scrolling.
Maybe you could check for your padding elements and maybe remove them (use margin on other elements instead).


text:
Q: Argo Event webhook authentication with Github I'm trying to integrate the GitHub repo with the Argo Event Source webhook as an example (link). When the configured from the Github event returns an error.

'Invalid Authorization Header'.

Code:
apiVersion: argoproj.io/v1alpha1
kind: EventSource
metadata:
  name: ci-pipeline-webhook
spec:
  service:
    ports:
      - port: 12000
        targetPort: 12000
  webhook:
    start-pipeline:
      port: "12000"
      endpoint: /start-pipeline
      method: POST
      authSecret:
        name: my-webhook-token
        key: my-token

A: If you want to use a secure GitHub webhook as an event source, you will need to use the GitHub event source type. GitHub webhooks send a special authorization header, X-Hub-Signature/X-Hub-Signature-256, that includes as hashed value of the webhook secret. The "regular" webhook event source expects a standard Bearer token with an authorization header in the form of "Authorization: Bearer <webhook-secret>".
You can read more about GitHub webhook delivery headers here. You can then compare that to the Argo Events webhook event source authentication documentation here.
There are basically two options when creating the GitHub webhook event source.

*

*Provide GitHub API credentials in a Kubernetes secret so Argo Events can make the API call to GitHub to create the webhook on your behalf.

*Omit the GitHub API credentials in the EventSource spec and create the webhook yourself either manually or through whichever means you normally create a webhook (Terraform, scripted API calls, etc).

Here is an example for the second option:
apiVersion: argoproj.io/v1alpha1
kind: EventSource
metadata:
  name: github-events
  namespace: my-namespace
spec:
  service:
    ports:
      - name: http
        port: 12000
        targetPort: 12000
  github:
    default:
      owner: my-github-org-or-username
      repository: my-github-repo-name
      webhook:
        url: https://my-argo-events-server-fqdn
        endpoint: /push
        port: "12000"
        method: POST
      events:
        - "*"
      webhookSecret:
        name: my-secret-name
        key: my-secret-key
      insecure: false
      active: true
      contentType: "json"


text:
Q: Saxon HE vs Saxon PE: File URI Resolution My question is a very easy one. I just want to know if buying the professional version of Saxon will help with file URI resolution, since the professional version has the EXPath extension.
I'm asking this because no matter how hard I try, (passing command line parameters, using file:///C|/path/to/text.csv, etc.) Saxon-HE refuses to let my stylesheets load a raw text file using unparsed-text('file:///C:/path/to/text.csv'), and will only resolve the file if it comes from one of the network drives that are mounted, unparsed-text('file://example.com/Dept/path/to/text.csv').
I have to ask this because the Saxon documentation explicitly states that unparsed-text() is NOT dependant on any custom URI resolver classes being used.

A: The simple answer to your simple question is no. There are many benefits to the commercial Saxon editions but they aren't magic fairy dust: if you are using a URI that can't be dereferenced in Saxon-HE, then you need to work out what you are doing wrong rather than hoping that different software will work it out for you.
I would suggest trying it first on the simplest possible case. Create a file called c:/test.txt, and then try referencing it as unparsed-text('file:///c:/test.txt'). Come back to us and tell us whether that works.

A: The answer is to always check your raw text's encoding BEFORE you attempt to parse it in UTF-8 though XSLT. :^)


text:
Q: git command to check for code changes in the git repo and use of it in the Batch file I am writing a batch file for Build auto server, which checks for any changes in the git repository and if there is it will pull the changes from the repo to my workspace and build the files. However I am not sure of which commands to use or the correct method to use it .

A: On linux put git pull origin master && yourBuildCommandsHere in a bash script and create a cronjob that runs this script every x minutes.
On windows you can schedule the script with AT commands.. http://www.computerhope.com/at.htm


text:
Q: Background Image not responsive in mobile I have used a bootstrap 4 template then edited it to fit my design. It is almost completely fully responsive except for one aspect. I have a background image as a main header image. It is responsive except when on mobile. I was wondering how I can make it fill the mobil screen while also shrinking to show the image.

header.masthead {
  padding-top: 10rem;
  padding-bottom: calc(10rem - 56px);
  background-image: url(../img/fg-heads-nologo.png);
  background-position: center center;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover
}

header.masthead hr {
  margin-top: 30px;
  margin-bottom: 30px
}

header.masthead h1 {
  font-size: 2rem
}

header.masthead p {
  font-weight: 300
}

@media (min-width:768px) {
  header.masthead p {
    font-size: 1.15rem;
  }
}

@media (min-width:992px) {
  header.masthead {
    height: 100vh;
    min-height: 650px;
    padding-top: 0;
    padding-bottom: 0
  }
  header.masthead h1 {
    font-size: 3rem
  }
}

@media (min-width:1200px) {
  header.masthead h1 {
    font-size: 4rem
  }
}

Thanks!

A: Use below properties in your CSS
background-size:contain;
background-position:center;

A: Try this->

#image {
    float:left;
    width:100%;
    height:400px;
    background: url('https://salemnet.vo.llnwd.net/media/cms/CW/faith/36525-Jesus-Jesussitting-painting-thinkstock.1200w.tn.jpg') no-repeat center center fixed;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}


text: Q: Can a cell in ui-grid be rendered in two rows if content is too large? Can angularjs grid be configured such that if content fits it just shows one row, but if content is big it expands to two rows maximum?


text:
Q: Intellij IDEA - IvyCache does not recognize dependencies
*

*Intellij Ultimate - 12.1

*JDK 1.7.0_10 (Sun/Oracle)

*IvyIDEA - 1.0.8
They seem to be the latest version of the plugins/IDEs. When I import a new project from eclipse, IDEA does not recognize my libraries (Eclipse nicely detected and added these libraries to my classpath).
I added IvyIDEA as a facet and supplied the ivy.xml, ivy-settings.xml and the build.properties then did a Tools -> Resolve for all modules which prints me the following (when I enable IvyIDEA logging at info level)
---------------------------------------------------------------------
|                  |            modules            ||   artifacts   |
|       conf       | number| search|dwnlded|evicted|| number|dwnlded|
---------------------------------------------------------------------
|      runtime     |   55  |   49  |   0   |   8   ||  157  |   0   |
|    war-runtime   |   47  |   41  |   0   |   7   ||  140  |   0   |
|     build-war    |   47  |   41  |   0   |   7   ||  140  |   0   |
|    build-main    |   47  |   41  |   0   |   7   ||  140  |   0   |
| build-tests-unit |   52  |   46  |   0   |   7   ||  152  |   0   |
|build-tests-integr|   50  |   44  |   0   |   7   ||  148  |   0   |
---------------------------------------------------------------------

No problems detected during resolve for module
But after this nothing happens i.e, no libraries are added to my project. What am I missing and how do I go about debugging this?


text:
Q: Tmux clear history in bash vi mode I just recently switched to using bash vi mode with set -o vi setting in my .bash_profile.  But this leads a problem
I had a tmux mapping that would run the clear-history command when I pressed <ctrl>+k.  This was the relevant mapping
bind -n C-k clear-history

This does not work in bash vi mode, probably because vi mode takes precedence.  How do I resolve or work around this issue?

A: You could change the key, this is what I use:
# reset & clear history
bind r send-keys -R \; send-keys C-l \; clear-history

You have to press ctrl+b+r
k can indeed be used but if you also move across panels (ctrl + hkjl), it may become confusing.
In any case this work by just using ctrl+k
bind -n C-k send-keys C-l \; run-shell "sleep .3s; tmux clear-history"

Without using the sleep:
bind -n C-k send-keys -R \; send-keys C-l \; clear-history

A: From this question, I have the following tmux mapping:
bind-key -n C-k send-keys -R \; send-keys Escape C-l a \; clear-history

There are many variants of this (each with pros and cons, and for different use cases); see the linked question.


text:
Q: UITabBarController height decreases everytime it's loaded When I first load my application and log in. Everything is fine.
However when I log out, then log back in. The height of my view has been decreased. Here's a screenshot of the bug:

I havn't been able to find the cause of this. Making this quite a difficult question to ask help with as I can't specify the precise section of code causing the issue. But I'll try.
The problematic setup is like so:
I have a containerViewController, with 2 childViewControllers, a menu and a UITabBarController. The UITabBarController has 2 UIViewControllers.
To better explain it, here's a visual representation.
_______________________

App Start ->

NavigationController(rootViewController LandingPageVC)

   LandingPageVC -> push -> SignInVC(this is where I login from)

   SignInVC -> push -> ContainerViewController(this has my UITabBarController and my menu)

   ContainerViewController (sets up my menuTabBarController and menu)

        menuTabBarController (this tabBarController is used to switch out my content from the menu)

        SidePanelViewController (this is my menu)

   ContainerViewController -> push(signing out) -> LandingPageVC

_______________________

Here's how I push the containerViewController when a successful login is called.
let mainTableViewController = ContainerViewController()
mainTableViewController.navigationItem.setHidesBackButton(true, animated: false)
navigationController!.pushViewController(mainTableViewController, animated: true)
menuEnabled = true

here's the function called from the containerViewController I use to log out.
func signOut() {

    // Set up the landing page as the main viewcontroller again.
    let mainTableViewController = LandingPageVC()
    mainTableViewController.navigationItem.setHidesBackButton(true, animated: false)
    mainTableViewController.skipView = false
    self.navigationController!.pushViewController(mainTableViewController, animated: true)

    // Disable menu access
    menuEnabled = false
}

by printing the height of ContainerViewController and menuTabBarController, I found that it is the UITabBarController's height that's decreasing and not the ContainerViewController.
Here's the code that has to do with the UITabBarController
import UIKit
import QuartzCore

let menuTabBarController = UITabBarController()

var menuButton = UIBarButtonItem()

var menuEnabled = false

class ContainerViewController: UIViewController, CenterViewControllerDelegate, SidePanelViewControllerDelegate, UIGestureRecognizerDelegate {

    func needsSignOut(sender: SidePanelViewController) {
        // toggling left panel
        self.toggleLeftPanel()
        // signing out
        self.signOut()
    }

  var centerViewController: UITabBarController!

  var leftViewController: SidePanelViewController?

  let centerPanelExpandedOffset: CGFloat = 60

  override func viewDidLoad() {
    super.viewDidLoad()

    menuTabBarController.tabBar.hidden = true

    menuButton = UIBarButtonItem(title: "", style: UIBarButtonItemStyle.Plain, target: self, action: "toggleLeftPanel")
    if let font = UIFont(name: "FontAwesome", size: 20) {
        menuButton.setTitleTextAttributes([NSFontAttributeName: font], forState: UIControlState.Normal)
    }
    self.navigationItem.leftBarButtonItem = menuButton

    //let tabBarController = UITabBarController()
    let suggestionsVC = SuggestionsViewController()
    let testVC = detaiLSuggestion_VC()
    let controllers = [suggestionsVC,testVC]

    menuTabBarController.setViewControllers(controllers, animated: false)

    centerViewController = menuTabBarController
    view.addSubview(menuTabBarController.view)
    addChildViewController(menuTabBarController)

    //centerNavigationController.didMoveToParentViewController(self)
  }

  // MARK: CenterViewController delegate methods

  func toggleLeftPanel() {

    let notAlreadyExpanded = (currentState != .LeftPanelExpanded)

    if notAlreadyExpanded {
        addLeftPanelViewController()
    }

    animateLeftPanel(shouldExpand: notAlreadyExpanded)

  }

  func collapseSidePanels() {
    switch (currentState) {
    case .LeftPanelExpanded:
      toggleLeftPanel()
    default:
      break
    }
  }

  func addLeftPanelViewController() {
    if (leftViewController == nil) {
        leftViewController = SidePanelViewController()
        leftViewController!.delegate = self

        addChildSidePanelController(leftViewController!)
    }
  }

  func addChildSidePanelController(sidePanelController: SidePanelViewController) {

    view.insertSubview(sidePanelController.view, atIndex: 0)

    addChildViewController(sidePanelController)
    sidePanelController.didMoveToParentViewController(self)
  }

  func animateLeftPanel(#shouldExpand: Bool) {
    if (shouldExpand) {
      currentState = .LeftPanelExpanded

        animateCenterPanelXPosition(targetPosition: CGRectGetWidth(centerViewController.view.frame) - centerPanelExpandedOffset)
    } else {
      animateCenterPanelXPosition(targetPosition: 0) { finished in
        self.currentState = .BothCollapsed

        self.leftViewController!.view.removeFromSuperview()
        self.leftViewController = nil;
      }
    }
  }

  func animateCenterPanelXPosition(#targetPosition: CGFloat, completion: ((Bool) -> Void)! = nil) {
    UIView.animateWithDuration(0.5, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0, options: .CurveEaseInOut, animations: {
        self.centerViewController.view.frame.origin.x = targetPosition
      }, completion: completion)
  }

Any help deducing where this is coming from or how I can go about fixing it would be greatly appreciated! And again I apologize for the dumb of code. I'll update it further if I am able to rule out parts of it.

A: rdelmar found a solution for me in chat.
The problem was fixed by specifying the menuTabBarController.view.frame like so:
menuTabBarController.view.frame = self.view.frame


text:
Q: Positioning of a table (tabularx) I need to put a table in the right side of the page, how can I do it? (it should looks like in the picture). Here is code which I have right now.
\documentclass{article}
\usepackage{ucs}
\usepackage[utf8x]{inputenc}
\usepackage[russian]{babel}
\usepackage[T1,T2A]{fontenc}
\usepackage{tabularx}
\begin{document}

\begin{flushright}
{\large {\textsc{Типова форма № П-4}}} \\
{\large {\textsc{ЗАТВЕРДЖЕННО}}} \\
{\large {\textsc{наказом Держкостату України}}} \\
{\large {\textsc{від 5 грудня 2008 р. N 489}}} \\
\end{flushright}

\begin{tabularx}{\textwidth}{ | X | X | }
\hline
ЄДРПОУ  & 21672519 \\ \hline
Дата складання &  15.01.2016 \\  \hline
\end{tabularx}

\end{document}

A: See, if the following is what you looking for:

\documentclass{article}
\usepackage{ucs}
\usepackage[utf8x]{inputenc}
\usepackage[russian]{babel}
\usepackage[T1,T2A]{fontenc}
\usepackage{tabularx}

\usepackage[margin=30mm,showframe]{geometry}

\begin{document}

\hfill\begin{minipage}{0.5\textwidth}
    \raggedleft
{    \large\scshape
Типова форма № П-4\\
ЗАТВЕРДЖЕННО\\
наказом Держкостату України\\
від 5 грудня 2008 р. N 489
}

\medskip
\begin{tabularx}{\textwidth}{ | X | X | }
    \hline
ЄДРПОУ          &   21672519    \\
    \hline
Дата складання  &  15.01.2016   \\
    \hline
\end{tabularx}
    \end{minipage}
\end{document}


text:
Q: tagging points in 3D matrix - there must be a more elegant solution to this I have two datasets with X,Y,Z coordinates, dfA and dFB, and I want to add a column with a variable from dfB to dfA if the distance between the points is less than some value d.
here's an example of the data that I'm trying to work with (in reality dfA and dfB will have over 1000 rows each):
dfA<-data.frame(matrix(ncol=5, nrow=40))
names(dfA) <- c("ID","G","x","y", "z")

dfA$ID<-round(runif(40, min=10, max=50),0)
dfA$G<-round(runif(40, min=0.5, max=15),3)
dfA$x<-round(runif(40, min=0, max=100),1)
dfA$y<-round(runif(40, min=0, max=100),1)
dfA$z<-round(runif(40, min=0, max=100),1)

dfB<-data.frame(matrix(ncol=5, nrow=20))
names(dfB) <- c("ID","TPH","x","y", "z")

dfB$ID<-round(runif(20, min=100, max=200),0)
dfB$TPH<-round(runif(20, min=100, max=1000),0)
dfB$x<-round(runif(20, min=0, max=100),1)
dfB$y<-round(runif(20, min=0, max=100),1)
dfB$z<-round(runif(20, min=0, max=100),1)

so what I would like to get is a dfB$TPH value for each dfA$ID if the points are at some minimum distance. Ideally I'd also like to get the dfB$ID and the distance between those points.
this is what I have figured out but I'm hoping there is a more elegant solution to this...
library(flexclust)
d<-as.data.frame(dist2(dfA[,3:5],dfB[,3:5]))
colnames(d)<-dfB$ID
dfD<- as.data.table(d)

library(data.table)

dfD<-dfD[, MAX := colnames(.SD)[max.col(.SD, ties.method="first")]]
dfD<-dfD[, MIN2 := colnames(.SD)[which.min(.SD)], by = 1:nrow(dfD)]
dfD<-cbind(dfA["ID"],dfD)
View(dfD)

dfD<-cbind(dfA,dfD)
dfD$di<-0
dfD$TPH<-0
n.smp<-nrow(dfD)

for (i in 1:n.smp){
  j<-dfD[i,"MIN2"]
  dfD[i,"di"]<-dfD[i,j]
  xx<-dfB$TPH[dfB$ID == j]
  dfD[i,"TPH"]<-xx
}

at this point I can filter out the points in dfA without close enough dfB points but this seems clunky and I'm not looking forward to doing this on my real data.
Any advice?
Many Thanks


text:
Q: Filtering listbox using textbox, while the listbox is filled using File Names I am unable to find a solution to this on here as it is filled in differently from how other questions similair to this have asked.
Basically, I'd like to filter a listbox with Dvd Names in it.
How Listbox is filled:
private void AdminShop_Load(object sender, EventArgs e)
    {
        string[] files = Directory.GetFiles("C:\\DvDShop\\DvdNames\\");

        foreach (string file in files)
        {
            lbxDvd.Items.Add(System.IO.Path.GetFileNameWithoutExtension(file));
        }

    }

So far in textChanged,when I input any text in the textbox, the listbox turns blank, but when I delete anything in the textbox, it fills back up again with all the entries. I feel like I am missing a simple issue here.
TextChanged:
private void txtSearch_TextChanged(object sender, EventArgs e)
    {
        string[] files = Directory.GetFiles("C:\\DvDShop\\DvdNames\\");

        if (String.IsNullOrEmpty(txtSearch.Text.Trim()) == false)
        {
            lbxDvd.Items.Clear();
            foreach (string file in files)
            {
                if (file.StartsWith(txtSearch.Text.Trim()))
                {
                    lbxDvd.Items.Add(System.IO.Path.GetFileNameWithoutExtension(file));
                }
            }

        }
        else if (txtSearch.Text.Trim() == "")
        {
            lbxDvd.Items.Clear();

            foreach (string file in files)
            {
                lbxDvd.Items.Add(System.IO.Path.GetFileNameWithoutExtension(file));
            }
        }
    }

Any help with my small issue would be appreciated!

A: You are using the full path to check if it Starts With it, try this code:
private void txtSearch_TextChanged(object sender, EventArgs e)
{
    string[] files = Directory.GetFiles("C:\\DvDShop\\DvdNames\\");

    if (String.IsNullOrEmpty(txtSearch.Text.Trim()) == false)
    {
        lbxDvd.Items.Clear();
        foreach (string file in files)
        {
            string filename = System.IO.Path.GetFileNameWithoutExtension(file);
            if (filename.StartsWith(txtSearch.Text.Trim()))
            {
                lbxDvd.Items.Add(System.IO.Path.GetFileNameWithoutExtension(file));
            }
        }

    }
    else if (txtSearch.Text.Trim() == "")
    {
        lbxDvd.Items.Clear();

        foreach (string file in files)
        {
            lbxDvd.Items.Add(System.IO.Path.GetFileNameWithoutExtension(file));
        }
    }
}

A: You are checking against Directory.GetFiles() which returns full path. Rather get the filename and check like
        foreach (string file in files)
        {
          string filename = System.IO.Path.GetFileNameWithoutExtension(file);
            if (filename.StartsWith(txtSearch.Text.Trim()))
            {
                lbxDvd.Items.Add(filename);
            }
        }


text:
Q: Need to place Figcaption below responsive Image I have used some code from stackoverflow oct 13 by Mark e Haas. The aim is to have two images side by side with a fig caption below them and for the images to respond to the screen size.
The image sizing is working inthe sense that te images stay on the screen as the size shrinks. The issue is with the  I have tried amending various parameters but the caption always appears on the left of the image not below it. Before i start invetigating using a grid to place the image in is it possible to have the  place itself below the Image preferably in the middle.
Code is below.


text:
Q: Prove that the adjoint of a densely defined operator is closed I'd like to prove that the adjoint of a densely defined linear operator is closed.
Let $H$ be a Hilbert space, and $T: D(T)\rightarrow H$ a densely defined linear operator ($D(T)$ is a dense subspace of $H$). The domain of the adjoint is defined as $D(T^{\ast}):=\left\{x \in H: \exists y\in H \mbox{ with } \langle x,Tz \rangle=\langle y, z \rangle\; \forall z \in H\right\}$ and $T^{\ast}x=y$.
Let $\{x_{n}\}_{n \in \mathbb{N}}\subset D(T^{\ast})$ be a convergent sequence with $\lim_{n \to \infty}x_{n}=x$ and $\lim_{n \to \infty}T^{\ast}x_{n}=y$. For $T^{\ast}$ to be closed I need to show:

*

*$x \in D(T^{\ast})$

*$T^{\ast}x=y$
1.)
$$
\begin{align}
\langle x, Tz \rangle
&=
\langle \lim_{n \to \infty}x_{n}, Tz \rangle\\
&=
\lim_{n \to \infty}\langle x_{n}, Tz \rangle\\
&=
\lim_{n \to \infty}\langle T^{\ast}x_{n}, z \rangle\\
&=
\langle\lim_{n \to \infty} T^{\ast}x_{n}, z \rangle\\
&=
\langle y, z \rangle\\
\end{align}
$$
and therefore $x \in D(T^{\ast})$.
2.)
Given 1.), the continuity of $\langle \cdot, \cdot \rangle$ and the definition of the adjoint we can show
$$
\begin{align}
\langle y, z \rangle
&=
\langle \lim_{n \to \infty}T^{\ast}x_{n}, z \rangle\\
&=
\lim_{n \to \infty} \langle T^{\ast}x_{n}, z \rangle\\
&=
\lim_{n \to \infty} \langle x_{n}, Tz \rangle\\
&=
\langle \lim_{n \to \infty}x_{n}, Tz \rangle\\
&=
\langle x, Tz \rangle\\
&=
\langle T^{\ast}x, z \rangle\\
\end{align}
$$
for all $z \in H$ and hence $y=T^{\ast}x$.
Is this proof correct?


text:
Q: Configure git pre-commit hook with pylint and pytest I want to add a pre-commit hook in git for windows such commit just succeed if all test pass and pylint does not return any warning. I execute those in the command line this way:
py.test
pylint mypackage

After some research I have come up with the following pre-commit bash file (only for the py.test part):
#!/bin/sh
py.test
RESULT=$?
git stash pop -q
[ $? -ne 0 ] && exit 1
[ $RESULT -ne 0 ] && exit 1
exit 0

It effectively aborts the commit and prints a No stash found message at the end. The problem is that when I solve the failing test, the commit does not succeed and it still prints No stash found.
How could I solve this, including also pylint checks?


text:
Q: ORA-24805:LOB type mismatch Let there be table A(text_1 varchar2(4000 CHAR), text_2 varchar(4000 CHAR))
And here is the select for this:
SELECT sys.dbms_crypto.hash(empty_clob() || text_1 || text_2, 2)  from A;

I am getting error 24805. I am expecting casting text_1 and text_2 to  CLOB , and connecting to each other. After that I need to get hash_code using function below. This code will also be part of PL/SQL block ( part of insert statement in function).
If I will use this:
SELECT sys.dbms_crypto.hash(to_clob('') || text_1 || text_2, 2)  from A;

Everything is ok now. So, what was the problem?
 create table A(text_1 varchar2(4000 CHAR), text_2 varchar2(4000 CHAR));
 insert into A(text_1,text_2)values ('test1','test2');
 commit;

Here is an example of creating data for A.

A: You can use TO_CLOB for concatenate your char based columns. Then use CONCAT which seems can work with CLOB. Try below.
SELECT DBMS_CRYPTO.HASH(CONCAT(TO_CLOB (TEXT_1) , TO_CLOB (TEXT_2)), 2)  FROM A;

A: Please try below query,
SELECT sys.dbms_crypto.hash(to_clob(text_1 || text_2), 2)  from A;


text:
Q: Pro-finite completion of topological spaces Let $X$ be a topological space. Then if $\Omega(X)$ denotes the set of equivalence relations $\sim$ on $X$ such that $X/\sim$ is a finite set, the pro-finite completion of $X$ is defined to be the limit
$$\hat{X}:=\text{lim}_{\sim\in \Omega(X)} X/_\sim.$$
By the work of Hoechster, we know that profinite $T_0$-topological spaces are spectral. I'm having a some trouble seeing which properties of $X$ transfer to $\hat{X}$. For instance, if $X$ is $T_0$, does it follow that $\hat{X}$ is $T_0$? If $X$ is a loop space, i.e. there exists some $Y$ such that $X\cong \Omega Y$, does it follow that $\hat{X}$ is a loop space, i.e. that there exists a $Z$ such that $\hat{X}\cong \Omega Z$? Can we tell when a topological space is the completion of a CW-complex?

A: The profinite completion of a topological space is typically a horribly pathological sort of space.  Let me first describe it more concretely.  The points of $\hat{X}$ are naturally in bijection with ultrafilters on $X$: given ${\sim}\in\Omega(X)$ and an ultrafilter $F$, exactly one equivalence class of $\sim$ will be in $F$.  It is not hard to show that the choices of equivalence classes which are compatible and thus give an element of $\hat{X}$ are exactly those which come from an ultrafilter in this way.  The natural inclusion $X\to\hat{X}$ is then just the inclusion of the principal ultrafilters.  The topology on $\hat{X}$ also has a simple description when you identify $\hat{X}$ as the set of ultrafilters on $X$: it is the topology generated by sets of the form $S_U=\{F\in\hat{X}:U\in F\}$ where $U\subseteq X$ is open.  Note that restricted to principal ultrafilters, this is just the given topology on $X$, so the natural inclusion $X\to\hat{X}$ is an embedding.
Now, let $B$ be the Boolean algebra generated by the open subsets of $X$.  For pretty much any space of interest, $B$ is going to be a proper subalgebra of the full power set $\mathcal{P}(X)$.  (For instance, if $X=\mathbb{R}$, it is easy to see that $B$ has cardinality $2^{\aleph_0}$ whereas $\mathcal{P}(X)$ has cardinality $2^{2^{\aleph_0}}$.)  This means that there are distinct ultrafilters on $\mathcal{P}(X)$ which have the same intersection with $B$.  That is, there are distinct ultrafilters on $X$ which contain the same open sets.  That means there are points of $\hat{X}$ which are in exactly the same open sets in its topology, so $\hat{X}$ is not $T_0$.
So, $\hat{X}$ will usually not be $T_0$, even for very nice spaces.  Here is another example of how $\hat{X}$ can be bad: suppose $x\in X$ is any non-isolated point.  Then there is some nonprincipal ultrafilter $F\in\hat{X}$ which converges to $x$.  This means that every closed set which is in $F$ contains $x$, or in other words that every closed subset of $\hat{X}$ which contains $F$ also contains the principal ultrafilter $F_x$ at $x$.  In particular, this shows $\hat{X}$ is never $T_1$ if $X$ is not discrete.
However, when $X$ is compact Hausdorff, at least the homotopy type of $\hat{X}$ is well-behaved: $\hat{X}$ deformation-retracts to $X$.  If $X$ is compact Hausdorff, then every ultrafilter on $\hat{X}$ has a unique limit in $X$; let $L:\hat{X}\to X$ be the map which takes each ultrafilter to its limit.  Define $$H:\hat{X}\times[0,1]\to\hat{X}$$ by $H(F,t)=F$ for all $t<1$ and $H(F,1)=L(F)$ (here we identify $X$ as a subset of $\hat{X}$ in the natural way, so that $L(F)\in\hat{X}$).  I claim $H$ is continuous, and so is a deformation retraction from $\hat{X}$ to $X$.  It is clear $H$ is continuous on $\hat{X}\times[0,1)$.  For continuity at $t=1$, suppose $F\in\hat{X}$ and $U\subseteq X$ is open such that $H(F,1)\in S_U$; we must find a neighborhood $V$ of $(F,1)$ such that $H(G,t)\in S_U$ for all $(G,t)\in V$.  Note first that $H(F,1)=L(F)\in S_U$ just means that $L(F)\in U$ (thinking of $L(F)$ as a point of $X$ rather than a principal ultrafilter).  Since $X$ is regular, there is an open neighborhood $W$ of $L(F)$ whose closure contained in $U$.  Since $F$ converges to $L(F)$, we have $W\in F$.  Moreover, for any $G\in\hat{X}$ such that $W\in G$, we have $L(G)\in\overline{W}\subseteq U$.  It follows $H(G,t)\in S_U$ for any $(G,t)\in S_W\times[0,1]$, so we can take $V=S_W\times[0,1]$ as the desired open set.


text:
Q: How do you get maximal speed out of SSE? What are the best settings for stuff like MXCSR? Which rounding mode is fastest? On what processors? Is it faster to enable signalling NaNs so I get informed when a computation results in a nan, or does this cause slowdowns in non-NaN computations?
In summary, how do you get the maximum of speed out of tight inner SSE loops?
Any related x87 floating-point speed advice also welcome.

A: Use Flush-to-zero and Denormals-are-zero modes: they are intended for speed at a precision cost that you probably won't notice.
I doubt that different rounding modes have different costs. Round-to-nearest is hardest in theory, but in a hardware implementation, I would guess the additional transistors to do it in the same number of cycles are probably there anyway, and are just unused for directed rounding.
Signaling NaNs do not slow down non-NaN computations.
Set the control flags word only once before your computation: changing it during the computation will dwarf any savings you achieve.

A: If you computation is likely to encounter denormals, and accuracy of very small values is not important to your computation, then by all means turn on FZ and DAZ (once, at the start of your computation; don't touch the MXCSR more than necessary).  They won't make any difference if your computation doesn't involve denormal values, but if it does, the difference can be quite significant.
None of the other MXCSR bits have any effect on performance at all.
The only x87-related performance advice is: don't use the x87 unit. Do your computations in SSE instead whenever possible.


text:
Q: Python sendto() not working on 3.1 (works on 2.6) For some reason, the following seems to work perfectly on my ubuntu machine running python 2.6 and returns an error on my windows xp box running python 3.1
from socket import socket, AF_INET, SOCK_DGRAM
data = 'UDP Test Data'
port = 12345
hostname = '192.168.0.1'
udp = socket(AF_INET,SOCK_DGRAM)
udp.sendto(data, (hostname, port))

Below is the error that the python 3.1 throws:
Traceback (most recent call last):
  File "sendto.py", line 6, in <module>
    udp.sendto(data, (hostname, port))
TypeError: sendto() takes exactly 3 arguments (2 given)

I have consulted the documentation for python 3.1 and the sendto() only requires two parameters. Any ideas as to what may be causing this?

A: In Python 3, the string (first) argument must be of type bytes or buffer, not str.  You'll get that error message if you supply the optional flags parameter.  Change data to:
data = b'UDP Test Data'
You might want to file a bug report about that at the python.org bug tracker.  [EDIT: already filed as noted by Dav]
...
>>> data = 'UDP Test Data'
>>> udp.sendto(data, (hostname, port))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: sendto() takes exactly 3 arguments (2 given)
>>> udp.sendto(data, 0, (hostname, port))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: sendto() argument 1 must be bytes or buffer, not str
>>> data = b'UDP Test Data'
>>> udp.sendto(data, 0, (hostname, port))
13
>>> udp.sendto(data, (hostname, port))
13

A: Related issue on the Python bugtracker:
http://bugs.python.org/issue5421


text:
Q: How can I set selected model with list? In my controller I set the items in the ViewBag:
List<ShopItemModel> items = new List<ShopItemModel>();
/* populate my items */
ViewBag.Items = items;

So on the cshtml i run thru the list, but how do I connect it so on postback sets the argument of the Post method in the controller?
The CSHTML:
@model Models.ShopItemModel

Webshop

@foreach( var item in ViewBag.Items)
{
    using (Html.BeginForm())
    {

@item.Name

        @Html.LabelFor(model => model.Name, new { Name = item.Name })

        <input type="submit" value="Buy" />
    }
}

The post version of the method in the controller:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(ShopItemModel m)
{
    return View();
}

But how do I fix this binding? So I fetch the selected item from the list?

A: In your view:
using (Html.BeginForm())
{
    for (int i = 0; i < Model.Count; i++)
    {
       @Html.LabelFor(model => model[i].Name)
    }
}

This will produce html controls like this:
<input name="ShopItemModel[3].Name"  ...

If you're using this in a form, in your controller, iterate over the POSTed model data:
foreach (var item in model)
{
    ... do something to each item
}

You can use a foreach loop in the view rather than a for loop, example here


text:
Q: Evalute $\lim\limits_{n\to\infty}\int _{0}^{1}\frac{nf(x)}{1+n^2x^2}\,dx$ Suppose $f\colon [0, 1] \to \mathbb{R}$ is a continuous function, Find the following limit:
$$\lim\limits_{n\to\infty}\int _{0}^{1}\frac{nf(x)}{1+n^2x^2}\,dx$$
I know the  answer is equal   $\frac{\pi}{2}f(0) $, but I don't prove that.
Any ideas or insight would be greatly appreciated.

A: With the change $y=nx$ you get $$\int _{0}^{1}\frac{nf(x)}{1+n^2x^2}\,dx = \int _{0}^{n}\frac{f(\frac{y}{n})}{1+y^2}\,dx.$$ Now Lebesgue theorem should allow you to conclude.

A: I get that the limit is
$\frac12 (1+\pi \coth(\pi))f(0)
$.
Since this disagrees with
what is presumably the correct answer,
I would like to know
where and what my error is.
Thanks.
$\begin{array}\\
\lim\limits_{n\to\infty}\int _{0}^{1}\frac{nf(x)}{1+n^2x^2}\,dx
&=\lim\limits_{n\to\infty}\frac1{n}\sum_{k=0}^{n-1}\frac{nf(k/n)}{1+n^2(k/n)^2}
\qquad\text{(the error is probably here, but I'm not sure why)}\\
&=\lim\limits_{n\to\infty}\sum_{k=0}^{n-1}\frac{f(k/n)}{1+k^2}\\
&=\lim\limits_{n\to\infty}\sum_{0\le k\lt n^a}\frac{f(k/n)}{1+k^2}
+\lim\limits_{n\to\infty}\sum_{n^a\ge k\le n-1}\frac{f(k/n)}{1+k^2}
\qquad\text{where }\frac12 < a <1\\
&=\lim\limits_{n\to\infty}\sum_{0\le k\lt n^a}\frac{f(k/n)}{1+k^2}
\qquad\text{since }\lim\limits_{n\to\infty}\sum_{n^a\le k\le n-1}\frac{f(k/n)}{1+k^2}=0\\
&=f(0)\lim\limits_{n\to\infty}\sum_{0\le k\lt n^a}\frac{1}{1+k^2}\\
&=f(0)\sum_{k=0}^{\infty}\frac{1}{1+k^2}\\
&=\frac12 (1+\pi \coth(\pi))f(0)
\qquad\text{(according to Wolfy)}\\
&\approx 2.076674f(0)
\end{array}
$


text:
Q: Non-English characters are not imported using SSIS or Visual Studio Deploy I'm having problems with importing data into a SQL Server 2008 database.
If I execute the following statement in SSMS, it works fine.
INSERT INTO
    [dbo].[ObjectiveRatingTranslation]
(
    [ObjectiveRatingId]
,   [TranslationId]
,   [Abbreviation]
,   [RateName]
,   [Description]
,   [CreatedBy]
,   [CreatedOn]
,   [ModifiedBy]
,   [ModifiedOn]
)
VALUES
(
    3
,   29
,   N'O / T'
,   N'På målet'
,   N'Målet har slutförts i enlighet med detta förväntningar. Uppfyller de slutprodukter som definieras. Det förväntas att de flesta mål bör vara Topplista på denna nivå.'
,   0
,   '2012-03-27T11:49:43.2300000'
,   0
,   '2012-03-27T11:49:43.2300000'
)

If I have this statement in  a script file that is being executed by VS 2010, Database, Deploy.  The data gets imported as
P� m�let | M�let har slutf�rts i enlighet med detta f�rv�ntningar. Uppfyller de slutprodukter som definieras. Det f�rv�ntas att de flesta m�l b�r vara Topplista p� denna niv�.

Same type of problem happens with SSIS on import to. I'm sure there must be some kind of setting that can be changed, but I"m not sure what.

A: The data types of the columns you are inserting the text into should be set to nvarchar.


text:
Q: UUID with additional string as prefix in primary key Spring Boot I had an idea to implement UUID as my primary key in the SQL database with spring boot technology. Currently, I have a dilemma on how to implement a custom fixed string with UUID as my primary key. Here is an example:
This is a classic UUID:
08d88683-20fc-4884-a523-8f39a06d037f

But I wanted to my UUID looks something like this:
USER-08d88683-20fc-4884-a523-8f39a06d037f

How could I achieve that with Spring boot and Hibernate?
Here is my user model:
@Data
@Entity
@Table( name = "users",
        uniqueConstraints = {
                @UniqueConstraint(columnNames = "username"),
                @UniqueConstraint(columnNames = "email")
        })
@NoArgsConstructor
public class User {
    @Id
    @GeneratedValue(generator = "uuid2")
    @GenericGenerator(name = "uuid2", strategy = "uuid2")
    @Column(name = "id", updatable = false, nullable = false, columnDefinition = "VARCHAR(36)")
    @Type(type = "uuid-char")
    private UUID id;

    @NotBlank
    @Size(max = 20)
    private String username;

    @NotBlank
    @Size(max = 50)
    @Email
    private String email;

    @NotBlank
    @Size(max = 120)
    private String password;

    @ManyToMany(fetch = FetchType.LAZY)
    @JoinTable( name = "user_roles",
            joinColumns = @JoinColumn(name = "user_id"),
            inverseJoinColumns = @JoinColumn(name = "role_id"))
    private Set<Role> roles = new HashSet<>();

    public User(String username, String email, String password) {
        this.username = username;
        this.email = email;
        this.password = password;
    }
}

A: The best way to implement custom id generator in Hibernate.
Using the following class you can create Custom Generator:
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.id.IdentifierGenerator;
import java.io.Serializable;
import java.util.UUID;

public class CustomUserIdGenerator implements IdentifierGenerator {
    @Override
    public Serializable generate(SharedSessionContractImplementor sharedSessionContractImplementor, Object o) throws HibernateException {
        return "USER-"+ UUID.randomUUID();
    }
}

And then you can use the above created class as the generator strategy in entity class for the GenricGenerator
@Id
@GenericGenerator(name = "string_based_custom_sequence", strategy = "com.package.CustomUserIdGenerator")
@GeneratedValue(generator = "string_based_custom_sequence")
private UUID id;


text:
Q: Median Concentration implies mean concentrarion I want to prove that if X is such that
$$P[|X-m_X|\geq t] \leq c_1 e^{-c_2t^2},$$
for $c_1, c_2$ positive constants, $t\geq 0$, then it holds that $$P[|X-E[X]|\geq t] \leq c_3 e^{-c_4t^2},$$ with $c_3=1+2c_1$ and $c_4=c_2/4$.
There is a proof of reverse direction here.

A: First, note that we may re-write the problem using auxiliary variable $Y=X-m_X$. Hence, we need to show,
$$ P[|Y|\geq t] \leq c_1 e^{-c_2t^2} \Rightarrow P[|Y-E[Y]|\geq t] \leq c_3 e^{-c_4t^2}.$$
A proof may be obtained using the properties of sub-Gaussian random variables. It can be shown that if $P[|Y|\geq t] \leq c_1 e^{-c_2t^2} $ then there exist finite $c_3,c_4$ such that $E[\exp(c_4Y^2)]\leq c_3$ (You may find the proof in Proposition 2.5.2 of R.Vershynin (2018) book).  Hence,
$$P[|Y|\geq t] \leq c_1 e^{-c_2t^2} \Rightarrow \exists c_3,c_4>0,\quad E[\exp(c_4Y^2)]\leq c_3.$$
By Markov inequality we may write
$$P[|Y-E[Y]|\geq t] = P\left[\exp(c_4|Y-E[Y]|^2)\geq \exp(c_4t^2)\right] \leq e^{-c_4t^2}E\left[\exp(c_4|Y-E[Y]|^2)\right].$$
Then it can be easily seen that:
$$e^{-c_4t^2}E\left[\exp(c_4|Y-E[Y]|^2)\right] \leq e^{-c_4t^2}E\left[\exp(c_4|Y|^2)\right],$$
which gives
$$P[|Y-E[Y]|\geq t]\leq e^{-c_4t^2}E\left[\exp(c_4|Y|^2)\right]\leq c_3 e^{-c_4t^2}.$$
Vershynin, Roman, High-dimensional probability. An introduction with applications in data science, Cambridge Series in Statistical and Probabilistic Mathematics 47. Cambridge: Cambridge University Press (ISBN 978-1-108-41519-4/hbk; 978-1-108-23159-6/ebook). xiv, 284 p. (2018). ZBL1430.60005.


text:
Q: Why does a large static array give a seg-fault but dynamic doesn't? (C++) The following code gives me a segmentation fault:
bool primeNums[100000000]; // index corresponds to number, t = prime, f = not prime

for (int i = 0; i < 100000000; ++i)
{
    primeNums[i] = false;
}

However, if I change the array declaration to be dynamic:
bool *primeNums = new bool[100000000];

I don't get a seg-fault.  I have a general idea of why this is: in the first example, the memory's being put on the stack while in the dynamic case it's being put on the heap.
Could you explain this in more detail?

A: bool primeNums[100000000];

used out all your stack space, therefore, you will get segmentation fault since there is not enough stack space to allocate a static array with huge size.
dynamic array is allocated on the heap, therefore, not that easy to get segmentation fault. Dynamic arrays are created using new in C++, it will call operator new to allocate memory then call constructor to initialize the allocated memory.
More information about how operator new works is quoted from the standard below [new.delete.single]:

Required behavior:
Return a nonnull pointer to suitably aligned storage (3.7.3), or else throw a bad_alloc exception. This requirement is binding on a replacement version of this function.
Default behavior:
— Executes a loop: Within the loop, the function first attempts to allocate the requested storage. Whether the attempt involves a call to the Standard C library function malloc is unspecified.
— Returns a pointer to the allocated storage if the attempt is successful. Otherwise, if the last argument to set_new_handler() was a null pointer, throw bad_alloc.
— Otherwise, the function calls the current new_handler (18.4.2.2). If the called function returns, the loop repeats.
— The loop terminates when an attempt to allocate the requested storage is successful or when a called new_handler function does not return.

So using dynamic array with new, when there is not enough space, it will throw bad_alloc by default, in this case, you will see an exception not a segmentation fault, when your array size is huge, it is better to use dynamic array or standard containers such as vectors.

A: bool primeNums[100000000];

This declaration allocates memory in the stack space. The stack space is a memory block allocated when your application is launched. It is usually in the range of a few kilobyes or megabytes (it depends on the language implementation, compiler, os, and other factors).
This space is used to store local and static variables so you have to be gentle and don't overuse it. Because this is a stack, all allocations are continuos (no empty space between allocations).
bool *primeNums = new bool[100000000];

In this case the memory is allocated is the heap. This is space free where large new chucks of memory can be allocated.

A: Some compilers or operating systems limit the size of the stack.  On windows the default is 1 MB but it can be changed.

A: in the first case you allocate memory on stack:
bool primeNums[100000000]; // put 100000000 bools on stack

for (int i = 0; i < 100000000; ++i)
{
    primeNums[i] = false;
}

however this is allocation on heap:
bool *primeNums = new bool[100000000]; // put 100000000 bools in the heap

and since stack is (very) limited this is the reason for segfault


text:
Q: React Native Animated If function const OFFSET = useRef(new Animated.Value(0)).current;
const LOGO_ANIM_INTERPOLATE = OFFSET.interpolate({
inputRange: [-100,0],
outputRange: [ WINDOW_WIDTH/2-35,0],
extrapolate: 'clamp',
})

if (LOGO_ANIM_INTERPOLATE === WINDOW_WIDTH/2-35) {
alert('OK');
} else {
}

-----------

OnScroll in ScrollView

onScroll={
Animated.event(
[{nativeEvent: {
contentOffset: {
y: OFFSET,
},
},
}],
{ useNativeDriver: false },
)}

--------

An object move to the right accordingly Scroll y-offset.
If object get x-position = WINDOW_WIDTH/2-35 I want alert('OK');
IF function not working! Why?


text:
Q: Can I call the Graph API within Azure functions? I am new to azure functions.
I created a ReactApp and used the graph API to get information about users registered in Azure ADB2C.
At this time, a client credential flow was used, but user information could not be obtained due to a CORS error.

Previous Idea(CORS error): ReactApp↔graphAPI↔Azure ADB2C

So I thought of using Azure functions.
First, ReactApp calls azure functions as an API.
Next, call the graphAPI in the azure functions.
At this point, we want to use the client credential flow.
Then, the user data of Azure ADB2C can be obtained because the graphAPI was used.
This user data is returned to Azure functions so that it can be used in ReactApp.

My Idea: ReactApp↔Azure functions ↔ graph API ↔ Azure ADB2C

Is this feasible?
If it is possible and you have a sample, please let me know.
Thanks for reading.

A: •   Yes, you can surely do the same as per what you have stated in your post.  You can surely deploy a react app in Azure functions and trigger a graph API query from the function to an Azure AD B2C tenant. To do so, you will have to first deploy an Azure Static Web app in Azure, then build and deploy it through a workflow in Github by creating a repository there, then create an Azure function API for the react app deployed. This Azure function service provides serverless APIs which allows you to focus on your TypeScript code and not have to configure a full back-end web server.
•   Once done, then connect the react client app to Azure function API. The Azure static web app resource deployed earlier provides a proxy between the react client and the Azure function API. Hence, while deploying the above, I would suggest you to please follow the below Microsoft documentation link and its subsequent article series for the said above resources.
https://learn.microsoft.com/en-us/azure/developer/javascript/how-to/with-web-app/static-web-app-with-swa-cli/introduction
Please follow the series of documentation articles stated above till the end of connecting the react client to Azure function API. Once done, then register an application in Azure AD B2C for authentication purposes and copy the application's required credentials like the client ID, tenant ID, tenant name and client secret for inserting these details in the HTTP trigger function API created earlier. Also, give the registered application in Azure AD B2C the required application permissions of 'User.ReadWrite.All' for the Microsoft Graph API. Ensure that you are adding the 'Microsoft.Identity.Client', 'Microsoft.Graph.Auth' and 'Microsoft.Graph.Beta' nuget packages to your Azure function solution created earlier. Then modify the constant parameters and variables in the Azure solution code file as in the below snapshot: -

•   Once the above has been done successfully, you can then test the deployed solution through 'Postman' application API as well as by redirecting to the react app page there by triggering a HTTP response in the function API which will ensure that you read the logged in Azure AD B2C user in the react app. For detailed information on the above-mentioned configuration, I would suggest you to please go through the video link below as it perfectly describes your condition in detail: -

https://www.youtube.com/watch?v=4uJHSwA-TZE


text:
Q: C++: Can not read the value inside a spesific memory address of my program using a different program I'm currently learning c++ and i decided that i want to give it a shot and try to write a simple program that can read the values of other programs that are stored in memory (and later on be able to modify these values).
To test it i wrote a program that does a simple addition, i then run my other program and I'm trying to read in real time the value of the first program using its address in the memory.
The code will help you to understand better what i mean.
The "target" program that i want to read the value from:
#include <iostream>
#include <windows.h>
#include <conio.h>

using namespace std;

int main()
{
    int userValue=0;
    int total=0;
    int* t;
    SetWindowText(NULL, "Memory");

    while(1)
    {
    cin >> userValue;
    total += userValue;
    t = &total;
    cout << *t << endl;
    cout <<"Pointer: " << &t <<" Total: " << &total;
    }

    getch();
    return 0;
}

And the program that reads the value from the first one:
#include <windows.h>
#include <iostream>

using namespace std;

int main()
{
    DWORD address = 0x28FEF0;
    int value = 0;
    DWORD pid;
    HWND hwnd;
        hwnd = FindWindow(NULL,"Memory");
    if(!hwnd)
    {
    cout <<"Window not found!\n";
    cin.get();
    }
    else
    {
    GetWindowThreadProcessId(hwnd,&pid);
    HANDLE phandle = OpenProcess(PROCESS_VM_READ,0,pid);
        if(!phandle)
        {
        cout <<"Could not get handle!\n";
        cin.get();
        }
        else
        {
        while(1)
        {
        ReadProcessMemory(phandle,(void*)address,&value,sizeof(value),0);
        cout << value << "\n";

        Sleep(1000);
        }
        return 0;
        }
    }
}

The code from the second one was taken from a forum (after googling) and it works fine if i use it with any other program, but it doesn't want to work at all with my program.
I tried changing the address to both the pointer t and the actual integer total, but nothing worked.
I feel like I've done something wrong in the first program rather than the second one.
I'm using Code:Blocks with GCC compiler.
Thanks in advance for any help!
Oh, and Merry Christmas!

A: &t = the address of the pointer that points to total
&total = the address of the actual "total value"
In your first program you should output "&total"
In your second program you should use ReadProcessMemory to read the address which is output from the first program.
If it doesn't work, you must run the second program as administrator to get permissions.  If you still have trouble, call GetLastError() after each Windows API call, check the return value of ReadProcessMemory() and utilize the last argument of ReadProcessMemory() for error checking.


text:
Q: Using JSON.net to deserialize an object I'm having trouble deserialising a JSON string into an object using JSON.net.
I'm calling the serialisation with:
Payload payload = JsonConvert.DeserializeObject<Payload>(string);

However, the resulting Payload object is null. Any ideas why?
My class:
public class Payload
{
    public Payload()
    { }

    public string Action { get; set; }
    public Payload.Bill[] Bills { get; set; }
    public string ResourceType { get; set; }
    public string Signature { get; set; }

    public class Bill
    {
        public Bill()
        { }

        public string Amount { get; set; }

        public string Id { get; set; }
        public string MerchantId { get; set; }
        public DateTimeOffset? PaidAt { get; set; }
        public string SourceId { get; set; }
        public string SourceType { get; set; }
        public string Status { get; set; }
        public string Uri { get; set; }
        public string UserId { get; set; }
    }
}

My JSON string:
{
  "payload": {
    "bills": [
      {
        "id": "xxxx",
        "status": "withdrawn",
        "uri": "xxxx",
        "amount": "5.19",
        "amount_minus_fees": "5.14",
        "source_type": "subscription",
        "source_id": "xxx",
        "payout_id": "xxx"
      }
    ],
    "resource_type": "bill",
    "action": "withdrawn",
    "signature": "xxx"
  }
}

A: The resulting payload object is null because the json string structure does not match with your Payload class. You need additional wrapper class to deserialize it successfully:
public class PayloadWrapper
{
    public PayloadWrapper()
    {
        Payload = new Payload();
    }

    public Payload Payload { get; set; }
}

and the deserialization logic:
PayloadWrapper wrap = JsonConvert.DeserializeObject<PayloadWrapper>(jsonStr);

To avoid creating another wrapper class, you can use LINQ to JSON:
JObject obj = JObject.Parse(jsonStr);
Payload payload = obj["payload"].ToObject<Payload>();

where jsonStr variable is the json string you posted. Also I noticed that some of the properties in the json string do not match with the property names of the Payload class, like resource_type in the json string and ResourceType in the class. Add JsonProperty attribute to them for successful deserialization.

A: try below one
The type parameter for DeserializeObject has to be List<Payload> instead of string. it would be JsonConvert.DeserializeObject<List<Payload>>(json).


text:
Q: Bash script printing a variable value after a newline character I have bash script which calls another script(some_script). some_script expects some input from the user. I have used printf statement for this purpose.
But the problem is the variable value is not being accepted by the target script. I think this is because '\' is being taken as an escape character in the script
The statement somewhat looks like this
 printf 'yes\n$var1\n$var2\n$var3' | some_script

If i directly replace the variable with values it runs perfectly but i want the script to take the values from the variables. How do i achieve this?

A: There is a difference between " and '. Try
printf "yes\n$var1\n$var2\n$var3" | some_script

because with ' the variables won't get substituted.

A: Yes, \ is a character that has to be escaped.
Use \\n.
For more details we would need more details on how your script works.


text:
Q: Update password from table So i have a project, that have a simple login system. There is a "users" table, that have "username" and "password" ecnrypted with SHA1.
And i have a simple form, that will change the password of the account that is logged in. But it is not working. Here is what i got:
<?php
include('connect.php');
if(isset($_POST['change']))
{
$nova_password = $_POST["nova_password"];
session_start();
$utilizador = $_SESSION['username'];
    if (empty($nova_password)) {
    $nopassword = 'Insira uma nova password!
';
    echo $nopassword;
    }
    if(!empty($nova_password))
    {
    $query = mysql_query("update users set password=SHA1('$nova_password') where username='$utilizador'");
    $sucesso = 'Password Alterada com Sucesso!';
    echo $sucesso;
    }
} //END IF
?>

When i go to the page, it says:"A session had already been started - ignoring session_start()".
This error appear before i click the button.

A: You have already started a session? Try removing session_start(); under $nova_password
Edit: Do this
$query = mysql_query("update users set password=SHA1('$nova_password') where username='$utilizador'");

// Destroy session and send them to login form
session_destroy();
header("Location: http://yourdomain.com/login.php");
exit();

But If you'd like to echo a message first you could use header( "refresh:seconds;url=wherever.php" );. But yes make sure no headers have been sent yet. Else you could use <meta http-equiv="refresh" content="seconds;url=url">
Or you could turn on output buffering ob_start(). Then it don't matter.

A: Substitute session_start() line with this:
if(!isset($_SESSION))
    session_start();


text:
Q: htaccess re-write for subfolders? Maybe someone can point me in the right direction with what I'm trying to do.
I'm trying to re-write so that all subfolders will re-direct to one folder while keeping the first subfolder info, along with the rest of the URL.
Example:
http://www.example.com/billy/profile/info.php
http://www.example.com/mike/profile/info.php
http://www.example.com/sarah/profile/info.php
http://www.example.com/mark/profile/info.php
where it would redirect to:
http://www.example.com/home/profile/info.php?user_name=$1
where I can get the user name and redirect to the correct page.

A: You can use this code in your DOCUMENT_ROOT/.htaccess file:
RewriteEngine On
RewriteBase /

RewriteRule ^(?!home/)([^/]+)/(profile/info\.php)$ home/$2?user_name=$1 [L,QSA,NC]


text:
Q: Audio player with listview i have audio files when i'm play another file then previous file play continuously.
so if you have solution please let me know.
here is my main.java
public class MusicAndroidActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    buttonPlay = (Button) findViewById(R.id.play);
    music = (ListView)findViewById(R.id.music);
  //  music.setAdapter(new ArrayAdapter<String>(this,, str));

    music.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view,int position, long id) {

            switch (position){

                case 0:
                    MediaPlayer mp = MediaPlayer.create(getApplicationContext(),R.raw.hosannatamil);
                    mp.start();
                    mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                        public void onCompletion(MediaPlayer mp) {
                            mp.release();
                        }
                    });
                    break;

                case 1:
                    MediaPlayer mp1 = MediaPlayer.create(getApplicationContext(),R.raw.one_less);
                    mp1.start();
                    mp1.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                        public void onCompletion(MediaPlayer mp) {
                            mp.release();
                        }
                    });
                    break;
                case 2:
                    MediaPlayer mp2 = MediaPlayer.create(getApplicationContext(),R.raw.words);
                    mp2.start();
                    mp2.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                        public void onCompletion(MediaPlayer mp) {
                            mp.release();
                        }
                    });
                    break;

            }
}
    });
}

A: You need to manually call MediaPlayer.stop() if you want to stop the playback.
If you want to start the same MediaPlayer again you have to call .prepare() before that.
For more information read the reference page and look at the state diagram there.

A:     if(mediaPlayer.isPlaying())
{
    //stop or pause your media player mediaPlayer.stop(); or mediaPlayer.pause();
    mediaPlayer.pause();
}
else
{
    mediaPlayer.start();
}

Put this Condition inside switch statements before mediaPlayer.start() also create a global reference of Media Player instead of creating three references like MediaPlayer mediaPlayer instead of MediaPlayer mp,mp1,mp2 etc,because you can create media Player object in the same reference as one condition must be true all the time,also put a default condition in the switch statement!


text:
Q: Ray-plane intersection to find the Z of the intersecting point I have a rectangle in 3d space (p1, p2, p3, p4) and when the mouse rolls over it I need to calculate the exact Z of the point on the rect, given the mouse coordinates (x, y).
Would a Ray-plane intersection find the Z of the intersecting point?
Thanks

A: You might try a ray / plane intersection. Check: Object/Object intersection.


text:
Q: license key for php script I have a script, and I sell it to some people. I need a way to make sure that my script won't work on any website that not in my clients list.

*

*First of all, I am using IonCube to encrypt my PHP code.

*I have all my clients in my server database.

*Each Client has a domain name, email, name, phone.

What is the best method to avoid making people from stealing my script?
I read about making a license key in the script, so any script without license won't work. However, there are many ways to generate a license key without taking my permission right?
All I need is to not activate any script in any domain name, unless I have it in my clients list.

A: Your question is very interesting because way too many php developers wonder the same thing. How can I protect my product from being stolen and copied?
Some of the comment talk about not being greedy, but the truth is that many people program for a living, so it isn't a matter of just some software you built as a hobby, it is your work and you deserve to get paid for it, just like any other profession.
Sadly, PHP is a language that is very hard to protect, but I will give you a few pointers:
1) Don't trust encryption: I have seen way too many tools for un-encrypting code, even some tools that I used to trust like Zend Guard, are also vulnerable. The most advanced tools I have seen can reveal your code in minutes.
EDIT: Another thing I forgot to mention about encryption. It will require the server to have certain special modules installed in order for your code to work and this is a deal-breaker for all the people who use shared hosting and can't install the unencryption module.
2) Try obfuscation: Even though your code will be still readable, if the obfuscator does a good job at mixing variables, adding nonsense and making functions within functions, the code itself will become almost non-modificable, so it will be useless to try to modify it.
3) Take advantage of obfuscation to insert domain-lock code within your software itself: Instead of a license file, just sell the software to a certain customer with some domain verification code within the software itself, that approach combined with obfuscation, will make it very hard to figure out what to change to make it work in some other domain, so you will probably achieve your goal.
4) Make a great software: This is the most important part, build an outstanding software that people will be willing to pay for, create a proper website for it, get the word out there.
I hope I have helped you.

A: There's a reason Adobe, Microsoft, and others don't over actively pursue pirates (not saying they don't, just not at epic, absolutism levels) - they make most of their money from business to business sales and support. A simple license and support structure is typically enough to posture yourself for profit from legitimate businesses and parties who want your product.
Technical protection is a losing battle if you're going to give anyone the code. That's why SaaS is so popular.

A: The only true way to lock down script-based code that you give away, is to keep a core part of that code executing on a server you control -- and have the code you've given to your client 'call home' to your server on each execution. Then all you have to do is block access to this 'call home' script based on the requesting ip.
Also, in this 'call home' mechanism it is no good just performing a simple connection test or handshake because this can be worked around -- the script on your server has to do something integral to the system as a whole so that the client would have to rewrite that missing part in order to use your code elsewhere without you knowing. This could be some key calculation or data provision.
Obviously this is not ideal as many clients will not like a script calling a remote server, plus you'd have to make sure your network and server could handle the number of requests -- otherwise you'll slow or timeout your clients own systems.

A:
All I need is to not activate any script in any domain name, unless I have it in my clients list.

Ok you narrowed it enough.
create your openssl certificate, hardcode public part to checking code, when issuing license sign domain.name string with your private key, issue sign part as license, in your license:
$lic=<<<EOL
LICENSE CODE HERE - SIGNATURE of string contained domain name
EOL;

in your code to check license:
include 'license.php';
$cert=<<<EOK
PUBLIC KEY DATA HERE
EOK;
$pub_key=openssl_get_publickey($cert);
$ok = openssl_verify($_SERVER['SERVER_NAME'], $lic, $pub_key);
if ($ok !== 1) {die ('bad license!')}

O'c all should be encrypted as much as possible.
this probably vulnerable for special crafted libopenssl  binaries but I hope it will help you.
to avoid running of such code every you can add condition like this:
if (int(random()*100))==6) {check_license();}

but it depends on which part is should be protected.
also, in all parts of the code you should check md5summ of file that contain  license check code.

A: You can use http://www.ioncube.com to obfuscate your source code or http://www.phplicengine.com to license your php code remotely or locally.

A: My thoughts are that you can't successfully save code from to be nulled. I really don't like way the Non-Free apps are created, but I won't judge you. Best solution to protect code is sometimes not worth of it, because many people (read websites) have very restricted hosting, where they cant install ioncube... Best protection is to join many types of protections (ex. IonCube + injected licence connection to your data server in different places with different code+if site NEED to use some ssl, you can try to make some protection with to sell also ssl with public key check on your data server), or many, many, other ways, just be creative)
But however as I said, If you want very high protection, you will get loss of money for creating it, and loss of money of loosing your customers, because they use some cheap hosting...
You need to think about everything...
Forgot to say: Hosting on your server is best protection, but have disadvantages: you need to add possibility for 'templating' site, access to be created some plugins, and similar stuff... But sometimes Clients just don't like to keep all data on your hosted server.
I think I helped somehow...

A: There are some good comments from other posters to this. Depending on the edition of the ionCube Encoder that you're using the features that you need are there already (in Pro and Cerberus), including features to allow you to craft your own layers of licensing if you wish, though this shouldn't be necessary. Some basic steps give the biggest wins, and as others have said, it's not generally worth going over the top with a massive licensing infrastructure. Keep in mind too that a main benefit to licensing comes not so much from stopping those who are intent on cheating and not paying, but from keeping the paying customers in line.
Say that you have a fee for each domain where your software is used. If you mention this somewhere but do nothing to enforce it, then when an honest customers tries your scripts on a second domain and finds that it works, chances are that they'll simply use it without even realising that they should have paid. In contrast, if your software alerts them to the fact that a new license is needed, it's likely that they'll purchase for the second domain.
Realistically it's impossible to stop the most determined thieves, and as one poster eluded to it may even be beneficial in the long term to have cheaters using software for free rather than not at all, but licensing can definitely lock in revenue from the honest majority who are happy to purchase good software (plus support, bug fixes, upgrades etc.), and it's foolish not to do that.