text:
Q: Is there a way to block and notify of connected USB devices? I just read the following news about how connected USB devices can act as keyboards or network cards, etc. and so for example input what they like or change sites to scam sites.
http://www.bbc.com/news/technology-28701124
If the operating system initially blocked USB devices when connected until a notification stating what it does is confirmed, then it would be less of a worry.
Is there a way to do this?
(Windows 7 or 8)

A: You can use Intel ME to block unknown USB devices and get reports on system logs.
To configure this you can use "Intel Small Business Advantages" or take a look at their samples and code something yourself. You may have a way to do it from the UEFI, depending on your motherboard.
You could also disable unused USB ports.


text:
Q: Text Recognition in Images in Swift Im new to swift and I was trying to make an app that can parse the from on a screenshot. I have the following code so far, and I wasnt able to figure out proper way to call the recognize function in my ContentView, any help is appreciated:
`
struct ContentView: View {
    @State var selectedItems: PhotosPickerItem?
    @State var selectedPhotoData: Data?

    func recogText(selData: Data?)
    {
        if let selData = selData, let image = UIImage(data: selData){
            guard let cgImage = image.cgImage else {return}
            let handler = VNImageRequestHandler(cgImage: cgImage)
            let request = VNDetectTextRectanglesRequest { request, error in
                guard let observations = request.results as? [VNRecognizedTextObservation],
                      error == nil else {return}
                let text = observations.compactMap({
                    $0.topCandidates(1).first?.string
                    }).joined(separator: ", ")
                print(text.count)
            }

            do {
                try handler.perform([request])
            }
            catch {
                print("Unable to perform the requests: \(error).")
            }
        }
    }

    var body: some View {
        VStack{

            //Icon
            mainImage()

            //Button
            PhotosPicker(selection: $selectedItems, matching: .images) {
                Label("Select a photo", systemImage: "photo")
            }
            .tint(.blue)
            .controlSize(.large)
            .buttonStyle(.borderedProminent)
            .onChange(of: selectedItems) { newItem in
                Task {
                    if let data = try? await newItem?.loadTransferable(type: Data.self) {
                        selectedPhotoData = data
                        let _ = recogText(selData: data)
                    }
                }

            }
        }
    }
}

`
Expected a print of the parsed text but no output was found

A: Hello here is an example function that might help you. Of course you have to replace the TestImage with yours. This might work for you and you need to import Vision
func recogText() {
    let textRecognitionRequest = VNRecognizeTextRequest { (request, error) in
        // Insert code to process the text recognition results here
        guard let observations = request.results as? [VNRecognizedTextObservation] else { return }

        for observation in observations {
            let topCandidate = observation.topCandidates(1).first
            if let recognizedText = topCandidate?.string {
                print(recognizedText)
            }
        }
    }

    textRecognitionRequest.recognitionLevel = .accurate

    let image = UIImage(named: "TestImage")
    let imageRequestHandler = VNImageRequestHandler(cgImage: (image?.cgImage!)!, options: [:])

    do {
        try imageRequestHandler.perform([textRecognitionRequest])
    } catch {
        print(error)
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: don't understand python's behaviour of three dimensional lists (references to sublists are the same) I don't understand why the following code behaves the way it does.
import numpy as np

nbr_arrays = 4
nbr_fields_per_array = 3
nbr_subfields_per_field = 2

# pre-allocate zeros list
zeros = np.zeros(nbr_subfields_per_field)

data = []
for array in range(nbr_arrays):

    # pre-allocate the subarray
    empty_array = []
    for empty_array_index in range(nbr_fields_per_array):
        empty_array.append(zeros)

    # append pre subarray to data
    data.append(empty_array)

    # fill up data
    for j in range(nbr_fields_per_array):
        for k in range(nbr_subfields_per_field):
            data[array][j][k] = j*k*array

The generated output data reads now:
[[array([ 0.,  6.]), array([ 0.,  6.]), array([ 0.,  6.])],
 [array([ 0.,  6.]), array([ 0.,  6.]), array([ 0.,  6.])],
 [array([ 0.,  6.]), array([ 0.,  6.]), array([ 0.,  6.])],
 [array([ 0.,  6.]), array([ 0.,  6.]), array([ 0.,  6.])]]

Even zeros reads completely differently:
array([ 0.,  6.])

If I look at the identify of the different lists, this is what I get:
id(data[0][0])
Out[72]: 45790208

id(data[1][0])
Out[66]: 45790208

id(data[2][0])
Out[67]: 45790208

id(data[3][0])
Out[68]: 45790208

id(zeros)
Out[69]: 45790208

why are all the references the same? and why does zero suddenly contain non-zero values?
I'd really appreciate it if somebody could explain me what exactly is happening here, and how I have to modify my code to see the expected behaviour (output).
EDIT:
not using zeros but using [[0]*nbr_subfields_per_field for x in range(nbr_fields_per_array)] instead gives me the expected result. but why? why doesn't the original code work?
Modified code that works:
data = []
for array in range(nbr_arrays):
    empty_array = [[0]*nbr_subfields_per_field for x in range(nbr_fields_per_array)]

    ''' this is causing the weird behaviour
    empty_array = []
    for empty_array_index in range(nbr_fields_per_array):
        empty_array.append(zeros)
    '''

    data.append(empty_array)

    for j in range(nbr_fields_per_array):
        for k in range(nbr_subfields_per_field):
            data[array][j][k] = j*k*array

A:
# pre-allocate zeros list
zeros = np.zeros(nbr_subfields_per_field)

This creates a single object.

for empty_array_index in range(nbr_fields_per_array):
    empty_array.append(zeros)

This keeps appending the same object.
Stop pre-allocating.

A: Numpy can set up multidimensional arrays for you, if you want. Since you're going to initialize the whole array immediately after creating it, the empty method seems like the most appropriate:
data = np.empty((nbr_arrays, nbr_fields_per_array, nbr_subfields_per_field))


text:
Q: Is it possible to figure out the parameter type and return type of a lambda? Given a lambda, is it possible to figure out it's parameter type and return type? If yes, how?
Basically, I want lambda_traits which can be used in following ways:
auto lambda = [](int i) { return long(i*10); };

lambda_traits<decltype(lambda)>::param_type  i; //i should be int
lambda_traits<decltype(lambda)>::return_type l; //l should be long

The motivation behind is that I want to use lambda_traits in a function template which accepts a lambda as argument, and I need to know it's parameter type and return type inside the function:
template<typename TLambda>
void f(TLambda lambda)
{
   typedef typename lambda_traits<TLambda>::param_type  P;
   typedef typename lambda_traits<TLambda>::return_type R;

   std::function<R(P)> fun = lambda; //I want to do this!
   //...
}

For the time being, we can assume that the lambda takes exactly one argument.
Initially, I tried to work with std::function as:
template<typename T>
A<T> f(std::function<bool(T)> fun)
{
   return A<T>(fun);
}

f([](int){return true;}); //error

But it obviously would give error. So I changed it to TLambda version of the function template and want to construct the std::function object inside the function (as shown above).

A: The specialization method shown in @KennyTMs answer can be extended to cover all cases, including variadic and mutable lambdas:
template <typename T>
struct closure_traits : closure_traits<decltype(&T::operator())> {};

#define REM_CTOR(...) __VA_ARGS__
#define SPEC(cv, var, is_var)                                              \
template <typename C, typename R, typename... Args>                        \
struct closure_traits<R (C::*) (Args... REM_CTOR var) cv>                  \
{                                                                          \
    using arity = std::integral_constant<std::size_t, sizeof...(Args) >;   \
    using is_variadic = std::integral_constant<bool, is_var>;              \
    using is_const    = std::is_const<int cv>;                             \
                                                                           \
    using result_type = R;                                                 \
                                                                           \
    template <std::size_t i>                                               \
    using arg = typename std::tuple_element<i, std::tuple<Args...>>::type; \
};

SPEC(const, (,...), 1)
SPEC(const, (), 0)
SPEC(, (,...), 1)
SPEC(, (), 0)

Demo.
Note that the arity is not adjusted for variadic operator()s. Instead one can also consider is_variadic.

A: Funny, I've just written a function_traits implementation based on  Specializing a template on a lambda in C++0x  which can give the parameter types. The trick, as described in the answer in that question, is to use the decltype of the lambda's operator().
template <typename T>
struct function_traits
    : public function_traits<decltype(&T::operator())>
{};
// For generic types, directly use the result of the signature of its 'operator()'

template <typename ClassType, typename ReturnType, typename... Args>
struct function_traits<ReturnType(ClassType::*)(Args...) const>
// we specialize for pointers to member function
{
    enum { arity = sizeof...(Args) };
    // arity is the number of arguments.

    typedef ReturnType result_type;

    template <size_t i>
    struct arg
    {
        typedef typename std::tuple_element<i, std::tuple<Args...>>::type type;
        // the i-th argument is equivalent to the i-th tuple element of a tuple
        // composed of those arguments.
    };
};

// test code below:
int main()
{
    auto lambda = [](int i) { return long(i*10); };

    typedef function_traits<decltype(lambda)> traits;

    static_assert(std::is_same<long, traits::result_type>::value, "err");
    static_assert(std::is_same<int, traits::arg<0>::type>::value, "err");

    return 0;
}

Note that this solution does not work for generic lambda like [](auto x) {}.

A: Though I'm not sure this is strictly standard conforming,
ideone compiled the following code:
template< class > struct mem_type;

template< class C, class T > struct mem_type< T C::* > {
  typedef T type;
};

template< class T > struct lambda_func_type {
  typedef typename mem_type< decltype( &T::operator() ) >::type type;
};

int main() {
  auto l = [](int i) { return long(i); };
  typedef lambda_func_type< decltype(l) >::type T;
  static_assert( std::is_same< T, long( int )const >::value, "" );
}

However, this provides only the function type, so the result and parameter
types have to be extracted from it.
If you can use boost::function_traits, result_type and arg1_type
will meet the purpose.
Since ideone seems not to provide boost in C++11 mode, I couldn't post
the actual code, sorry.

A: The answer provided by @KennyTMs works great, however if a lambda has no parameters, using the index arg<0> does not compile. If anyone else was having this problem, I have a simple solution (simpler than using SFINAE related solutions, that is).
Just add void to the end of the tuple in the arg struct after the variadic argument types. i.e.
template <size_t i>
    struct arg
    {
        typedef typename std::tuple_element<i, std::tuple<Args...,void>>::type type;
    };

since the arity isn't dependent on the actual number of template parameters, the actual won't be incorrect, and if it's 0 then at least arg<0> will still exist and you can do with it what you will. If you already plan to not exceed the index arg<arity-1> then it shouldn't interfere with your current implementation.

A: If you're looking for a complete solution for all types in C++ that can be invoked, a lot of these answers work but miss some of the corner cases, like

*

*A reference to a lambda

*Functions and function pointers

Here's a complete solution to my knowledge (except for generic lambdas) - let me know in the comments if anything is missing:
template <typename>
struct closure_traits;

template <typename FunctionT> // overloaded operator () (e.g. std::function)
struct closure_traits
    : closure_traits<decltype(&std::remove_reference_t<FunctionT>::operator())>
{
};

template <typename ReturnTypeT, typename... Args> // Free functions
struct closure_traits<ReturnTypeT(Args...)>
{
    using arguments = std::tuple<Args...>;

    static constexpr std::size_t arity = std::tuple_size<arguments>::value;

    template <std::size_t N>
    using argument_type = typename std::tuple_element<N, arguments>::type;

    using return_type = ReturnTypeT;
};

template <typename ReturnTypeT, typename... Args> // Function pointers
struct closure_traits<ReturnTypeT (*)(Args...)>
    : closure_traits<ReturnTypeT(Args...)>
{
};

// member functions
template <typename ReturnTypeT, typename ClassTypeT, typename... Args>
struct closure_traits<ReturnTypeT (ClassTypeT::*)(Args...)>
    : closure_traits<ReturnTypeT(Args...)>
{
    using class_type = ClassTypeT;
};

// const member functions (and lambda's operator() gets redirected here)
template <typename ReturnTypeT, typename ClassTypeT, typename... Args>
struct closure_traits<ReturnTypeT (ClassTypeT::*)(Args...) const>
    : closure_traits<ReturnTypeT (ClassTypeT::*)(Args...)>
{
};

Disclaimer: the std::remove_reference was inspired by this code.


text:
Q: Store python requests session in persistent storage I'm using python requests library. My application performs simple get request from a site and prints results.
The site requires authorization with ntlm. Fortunately I can rely on HttpNtlmAuth, which works fine.
session = requests.Session()
session.auth = HttpNtlmAuth(domain + "\\" + username,
                            password,
                            session)

But if application is executed several times - each time I need to ask for username and password. It is very uncomfortable. Storing credentials is undesirable.
Could I store session object itself and reuse it several times? From server point of view - it should be fine.
Is there a way to pickle and unpickle session?

A: If you use the dill package, you should be able to pickle the session where pickle itself fails.
>>> import dill as pickle
>>> pickled = pickle.dumps(session)
>>> restored = pickle.loads(pickled)

Get dill here: https://github.com/uqfoundation/dill
Actually, dill also makes it easy to store your python session across restarts, so you
could pickle your entire python session like this:
>>> pickle.dump_session('session.pkl')

Then restart python, and pick up where you left off.
Python 2.7.8 (default, Jul 13 2014, 02:29:54)
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import dill as pickle
>>> pickle.load_session('session.pkl')
>>> restored
<requests.sessions.Session object at 0x10c012690>


text:
Q: Lift of finite group action on circle to double cover Suppose we have a finite group G acting on the circle.
The circle has a double cover, corresponding to the subgroup $2\mathbb{Z}$ of the fundamental group $\mathbb{Z}$ of the circle. We can lift the group action to the double cover, obtaining an an action of some central extension $\tilde{G}$ of G by $\mathbb{Z}_2$. My question is: when is $\tilde{G}$ a direct product $\tilde{G}\simeq G\times\mathbb{Z}_2$?

A: For each $g \in G$ you have given me a diffeomorphism $\rho_g: S^1 \to S^1$. Now choose a lift $\overline \rho_g: S^1 \to S^1$ so that $\rho_g(z) = [\overline \rho_g(z^2)]$, that is, $\overline \rho_g$ is a double cover of $\rho_g$.
This gives you a 2-cocycle in $H^2(G; \Bbb Z/2)$, by $f(g,h) = \overline \rho_g \overline \rho_h (\overline \rho_{gh})^{-1}$. By the assumption that the $\overline \rho_g$ double-cover $\rho_g$, and the fact that $\rho_g$ is a group action, this expression reduces (in the quotient) to the identity. It follows that this expression is either the identity or the antipodal map, which we can think of as being an element of $\Bbb Z/2$. It is straightforward to check that this is indeed a cocycle.
Your central extension is trivial iff this group cohomology class is zero.
In many circumstances you can guarantee that this group cohomology class is zero simply because that cohomology group is zero. This is true automatically for any group of odd order (for which an extension with fiber $\Bbb Z/2$ automatically splits as a product, central or no). Sometimes you may find that this group is zero by some explicit calculation
Assuming $G$ is finite, the universal coefficient theorem gives a homological condition that is necessary and sufficeient for $H^2(G;\Bbb Z/2)$ to be zero is as follows.
You require both
i) $G^{\text{ab}}$ has no 2-torsion.
ii) The Schur multiplier, which may be calculated explicitly from a presentation due to work of Hopf, is odd order.
If $G$ has finitely generated homology groups, (but is not necessarily finite), then the first condition is unchanged but the second condition is replaced by: "The Schur multiplier is finite of odd order"; finiteness is no longer automatic.
For general $G$ you must write the conditions less explicitly: $\text{Ext}(G^{\text{ab}}, \Bbb Z/2) = 0$ and $\text{Hom}(H_2(G;\Bbb Z), \Bbb Z/2) = 0$.


text:
Q: How to handle various units in a single attribute / feature using Pandas? I have a dataset, on which i am working on Data Cleaning part, where one of the attribute or feature is having the values with various units. for example some of the values are as follow.
1 kg; 6 LB; 900 gms; 32 oz; etc.
If i use the standard scaler then it will not be fair as the values and their units are different, so cannot treat them as is.
Please do suggest how to handle such data.

A: I will recommend to change the different value to same unit first of all. For example, you can make all the value to kg or whatever suits best for you, and then perform the standard scale.

A: Thanks All, I did some research and found that i need to convert the various units into standard units and which follow internation norms referred to SI Units https://www.nist.gov/pml/weights-and-measures/metric-si/si-units , and same suggestion has given by @sharmajee499.
Moving ahead with this approach.. though this is going to be a lot of manual code, but seems there is no direct short and easy way.
Please do post if have any better solution.


text:
Q: null value passed from a iphone view to another When I pass a string to another view  I have a null values.
My code is:
In  view AddBarView.m, where I have the string:
nameAdded = nameField.text;   //nameAdded is defined as NSString in AddBarView.h
NSLog(@"namefrom addbarview: %@", nameAdded);  OK it works here , NsLog return the textfild

Now in other view  AddLocationController.m
@synthesize nameAdded;
- (void)addViewControllerDidFinish:(AddBarView *)controller
{
    AddBarView *controllerAdd;
    NSLog(@"namefrom addbarview: %@", controller.nameAdded);  //here

    [self dismissModalViewControllerAnimated:YES];
}

the NSLog return a (null) value. Where is my fault?
tx in advance!

A: You need to allocate memory to nameAdded string as follows and initialize it with nameField.
nameAdded=[[NSString alloc] initWithFormat:@"%@",nameField.text];

edited
Put the below line in the init method.
nameAdded=[NSString stringWithFormat:@"%@",nameField.text];

A: See my this post I gave a Tutorial here for how to pass a NSString from one ViewController class to another iOS - Passing variable to view controller

A: nameAdded = nameField.text;   you had only retain the value. If you edit the nameField.text later,  nameAdded's value will be changed, too.
you should make a copy to keep the value.  nameAdded = [nameField.text copy];
Check that  in AddBarView's viewDidUnload function whether  you has released nameAdded or not.
 Otherwise, the two nameAdded variables are same object? please print their address.

A: Actually you are allocating and initializing the class that holds the textField. So it will always return you NULL value as the textField also allocated and initialized. If the class 'AddBarView' called before the class that access it, you could simply pass it to the class. Instead 'AddBarView' called after the class that access it, you may want to store the textField value in a Global String!!


text:
Q: returning message: "; ", statusText: "OK" in breeze odata query using angular i am new to breeze and odata..
im trying to fetch data from odata api using breeze in angular...
heres my code:
//adding authorization to the header
        var authObj = localStorageService.get('authorizationData');
        var token = 'Bearer ' + authObj.token;
        var oldClient = OData.defaultHttpClient;

        var myClient = {
            request: function (request, success, error) {
                request.headers.Authorization = token;
                return oldClient.request(request, success, error);
            }
        };

        OData.defaultHttpClient = myClient;

        baseService.getBreezeAdapter;

        breeze.NamingConvention.camelCase.setAsDefault();
        var manager = baseService.newManager();

        var query = new breeze.EntityQuery()
                        .from('Customers');

        function fetchData() {
            manager.executeQuery(query)
                .then(function (data) {
                    console.log(data)
                })
                .catch(function (fail) {
                    console.log(fail)
                })
                .finally(function (response) {

                });
        };

when i look into fiddler.. there was no error..its working fine..
but after the query it falls down to catch which is fail.. it returns an error message
"; ", but it said that the statustext is ok and it has the data in its body element..
here is the actual error
{message: "; ", statusText: "OK", status: 200, url: "http://xxxxxx.net/odata/Customers", body: Object…}

can someone can explain to me why its returning an error ";"


text:
Q: htaccess - redirect http to https but only for certain domains I have two domains pointing to the same place but I only want one of these to redirect all http requests to https.
http://www.thisisme.com should stay as it is
http://thisisme.mydomain.com needs to redirect to https://thisisme.mydomain.com
As an extra rule I need to make sure that http://thisisme.mydomain.com/health_check.php does not redirect.
Here's what I have so far.
<IfModule mod_rewrite.c>
    Options +FollowSymlinks
    RewriteEngine On

    # Don't redirect /heath_check.php to https
    RewriteCond %{REQUEST_URI} !(health_check\.php)$

    #This line needs looking at! Should only redirect any xxx.mydomain.com requests to https
    RewriteCond %{HTTP_HOST} mydomain\.com

    RewriteCond %{HTTP:X-Forwarded-Proto} =http
    RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R,L]

    # block hidden directories
    RewriteRule "(^|/)\." - [F]

    # This makes the url look pretty for codeigniter...
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ ./index.php/$1 [L,QSA]
</IfModule>

EDIT!
I actually need to do the opposite if the requested domain is not mydomain.com - it needs to redirect to http is https is requested

A: To exclude www.thisisme.com ,put the following condition right bellow RewriteEngine on line or above the http=>https rule :
RewriteCond %{HTTP_HOST} !^(www\.)?thisisme\.com$ [NC]


text:
Q: Is there an online LIBXML2 XML parser available or a way to parse XML with libxml2 standalone? We are currently on a module trying to parse XML using LIBXML2 component and have found an issue related to it when a XML containing a namespace containing non-ASCII character such as this é.
Sample XML file:
< ?xml version="1.0" encoding="UTF-8"?>
<SOAP:Envelope xmlns:SOAP="http://schemas.xmlsoap.org/soap/envelope/">
  <SOAP:Body>
    <Helloé xmlns="http://schemas/Helloé">
      <ns0:Helloé xmlns:ns0="http://schemas/Helloé" />
    </Helloé>
  </SOAP:Body>
</SOAP:Envelope>

We were able to check and confirm that this is supported by the DOM parser by testing it with a small test program. When we have tried to check for the validity of this scenario provided, by the W3School XML online parser we are getting the following error:

We have tested it through the other online sources too, as like this even which says the same - the same error message.
Can anyone please let us know if there is a way to identify an online tool/resource where we can pinpoint this to libxml2?
Or a sample program that can test this?

A: Simply run the file through libxml2's xmllint on the command line:
$ xmllint --noout so.xml
so.xml:4: namespace error : xmlns: 'http://schemas/Helloé' is not a valid URI
    <Helloé xmlns="http://schemas/Helloé">
                                           ^
so.xml:5: namespace error : xmlns:ns0: 'http://schemas/Helloé' is not a valid URI
      <ns0:Helloé xmlns:ns0="http://schemas/Helloé" />
                                                     ^

Also, replacing é with the correct UTF-8 percent-escape works. Just change the URI to http://schemas/Hello%C3%A9.


text:
Q: How to keep the locale of the android app to locale.US? My android application depends on some library that behaves wrongly on changing the language of the phone to some arabic language. So I want my app locale to remain locale.US. For that, I searched and found the following code in MainApplication:
 public class MyApplication extends Application
 {

    @Override
    public void onConfigurationChanged(Configuration newConfig)
    {
        super.onConfigurationChanged(newConfig);

            Locale.setDefault(Locale.US);
            newConfig.locale = Locale.US;
            getBaseContext().getResources().updateConfiguration(newConfig, getBaseContext().getResources().getDisplayMetrics());

    }

    @Override
    public void onCreate()
    {

            locale = Locale.US;
            Locale.setDefault(locale);
            config.locale = locale;
            getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());

    }
}

This code creating problem on android L. When I change the language of the phone to arabic, the onConfigurationChanged function is called single times , but the activity keeps on getting created after opening the app. It looks like it is creating in a loop. So,

*

*Can I use Locale.setDefault(Locale.US) without getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics()); as it is working correctly.

*Is there any other way to specify the locale of the android app.

A: @Override
public void onConfigurationChanged(Configuration newConfig)
{
    super.onConfigurationChanged(newConfig); // call of super BEFORE setting the locale ??

        Locale.setDefault(Locale.US);
        newConfig.locale = Locale.US;
        getBaseContext().getResources().updateConfiguration(newConfig, getBaseContext().getResources().getDisplayMetrics());

}

You where close...
Just do it in the right order
    Locale.setDefault(Locale.US);
    newConfig.locale = Locale.US;
    super.onConfigurationChanged(newConfig);

And why are you using the "onChange" ?


text:
Q: How to execute click event of an asp.net button based upon the return value of OnClientClick event I am working on an asp.net web forms project. I have an asp.net button which has both OnClientClick and onClick events. The OnClientClick event executes the javascript function processHolidayDates() which in turn shows a Telerik's Ok/Cancel message box. When the Ok button is clicked it will return true and if the Cancel button is clicked it will return false. So, when false is returned, I don't want the button click event to execute the server side code. However, the moment the message box is displayed already the code behind under the btnCreate_Click is executed. When I add "return false;" at the OnClientClick as in   "OnClientClick="javascript:processHolidayDates(); return false " , the code behind is never executed even if I chose Ok in the message box. The following is my code on the aspx page
    <asp:button id="btnCreate" runat="server" Text="Create"  OnClientClick="javascript:processHolidayDates(); " onclick="btnCreate_Click"></asp:button>
function processStartAndEndDates() {

        var oConfirm = radconfirm('Hello', callBackFn, 400, 300, null, 'Test');
    return oConfirm ;

    }

A: You could change your OnClientClick to
OnClientClick="return processHolidayDates();"

So that you will return false (and cancel the postback) if the user cancels the window.

A: This should work:
OnClientClick="return processHolidayDates();"


text:
Q: Spark Standalone cluster master web UI inaccessible after an application finishes I have a spark application that finishes without error, but once it's done and saved all of its outputs and the process terminates, the Spark standalone cluster master process becomes a CPU hog, using 16 CPU's full time for hours, and the web UI becomes unresponsive. I have no idea what it could be doing, is there some complicated clean up step?
Some more details:
I've got a Spark standalone cluster (27 workers/nodes) that I've been successfully submitting jobs to for a while. I recently scaled up the size of my applications, the largest now takes 3.5 hours using  100 cores over 27 workers, and each worker has ~dozens of GB of shuffle read/write over the course of the job. Otherwise, the application is no different than the smaller jobs that have run successfully before.

A: This is a known issue with Spark's standalone cluster, and is caused by the massive event log created by large applications. You can read more at the issue tracking link below.
https://issues.apache.org/jira/browse/SPARK-12299
At the current time, the best work-around is to disable event logging for large jobs.


text:
Q: Redirect domain IIS to Apache IIS Server is listening Port 80 and Apache is listening 8080
I deployed website on apache.
Domain name is registered on IIS server. How can I redirect to a call from IIS to Apache server. Like if I type

www.abc.com

(on IIS), it will redirect call to website on Apache server (on port 8080)
How can I do that?

A: You need to setup a reverse proxy on IIS and point it to the apache server. Here is a blog post about how to set it up: http://blogs.iis.net/carlosag/archive/2010/04/01/setting-up-a-reverse-proxy-using-iis-url-rewrite-and-arr.aspx
It requires setting up URL Rewrite and Application Request Routing.
Excerpt from the blog post:

*

*The first thing you need to do is enable Proxy support in ARR.

*

*To do that just launch IIS Manager and click the server node in the tree view.

*Double click the "Application Request Routing Cache" icon

*Select the "Server Proxy Settings…" task in the Actions panel

*And Make sure that "Enable Proxy" checkbox is marked. What this will do is allow any request in the server that is rewritten to a server that is not the local machine will be routed to the right place automatically without any further configuration.

*Configure URL Rewrite to route the right folders and their requests to the right site. But rather than bothering you with UI steps I will show you the configuration and then explain step by step what each piece is doing.

*Note that for this post I will only take care of Company1, but you can imagine the same steps apply for Company2, and to test this you can just save the configuration file below as web.config and save it in your inetpub\wwwroot\  or in any other site root and you can test it.


text:
Q: How can I force the symfony entity-manager to recognize existing sub-entities? I'm using Fos_rest to do a webservice.
I recive an entity from an Angular App in JSON.
JSON example :
{"model":
   {
    "trademark":
      {"id":1,"name":"Alfa Romeo"},
    "type":
      {"id":1,"code":"car","name":"Car"},
    "name":"147"
    }
}

The entity is composed of two sub entities, called "trademark" and "type".
When receiving a POST, in controller does the following:
public function cpostAction(Request $request, $idTrademark)
   {
        $entity = new Model();
        $form = $this->createForm(ModeloType::class, $entity);
        $form->handleRequest($request);
        if ($form->isValid()) {
            $entity = $form->getData();
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();

            /*do things with the entity and return*/
        }
   }

The problem is given when doing Flush, since it recognizes "trademark" and "type" as new entities, since these already exist when owning an "id".
How can I force the entity manager to recognize the entities "trademark" and "type" from the database?
P.S:
Form Type:
class ModelType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('name')
                ->add('trademark', TrademarkType::class)
                ->add('type', TypeType::class)
                ->add('id');
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'AppBundle\Entity\Model',
            'csrf_protection' => false,
            'allow_extra_fields' => true,
        ));
    }
}

A: You should not do a find() : it does a database request. Prefer:
$em->getReference(Type::class, $entity->getType()->getId())

It does not a database query. The only problem is getReference does not check if the entity is still existing in the database. For me getReference should only be used to transform an id to the doctrine proxy object


text:
Q: How I can store line in PostgreSQL using Flask? I have a problem. I'm building an application using Flask, database in PostgreSQL and Leaflet. In the application the user can draw a line by clicking on the map all points are added to array and create a line( all code in js) . I created a columns in database in Flask using SQLAlchemy. I wonder how I can store this road as a line in database? Does such a type exists in SQLAlchemy ?
Function in js
function clickonMap(event){
        dict = event.latlng
        coordintates.push(Object.values(dict))
        if(mymap.hasLayer(polyline)){
            polyline.remove()
        }
        mark = L.marker(event.latlng,{icon: markerIcon}).addTo(mymap);
        markers.push(mark)
        polyline = L.polyline(coordintates,{color: 'red'}).addTo(mymap)

A: Minimal working code which uses modern fetch() to send data from browser to Flask, and it keep it on list. Later you can load it back and it also use fetch() to get it from Flask.
I use render_template_string instead of render_template only to make it simpler for test. Everyone can copy code to one file and test it.
from flask import Flask, request, render_template_string, jsonify

app = Flask(__name__)

@app.route('/')
def index():
    return render_template_string('''
<!DOCTYPE html>

 <link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css"
   integrity="sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/sMZMZ19scR4PsZChSR7A=="
   crossorigin=""/>

<button onclick="save();">Save</button>
<button onclick="clean();">Clean</button>
<button onclick="load();">Load</button>

''')

database = []

@app.route('/save', methods=['GET', 'POST'])
def save():
    data = request.json
    print('save:', data)
    database.append(data)
    return "OK"

@app.route('/load', methods=['GET', 'POST'])
def load():
    if database:
        data = database[-1]
    else:
        data = []
    print('load:', data)
    return jsonify(data)

if __name__ == '__main__':
    app.debug = True
    app.run() #debug=True


text:
Q: How to deal with non-rectangular sections of multiline inline text? How do you get a nice outline? This is similar to the question:
CSS/Javascript: How to draw minimal border around an inline element?
However, the accepted solution to that question results in jagged textboxes, as seen here:
http://jsfiddle.net/z9THQ/2/
/* p {
    text-align: justify;
} */
.wrapped {
   outline: 2px solid black;
   box-shadow: 0px 0px 0px 2px rgba(0,0,0,1);
}

.wrapped span {
    border: 1px solid white;
    background-color: white;
    position: relative;
    z-index: 1000;
}

Even with justified text, the right edge is still jagged; it should look like a single line, like in the image below.

A pure CSS solution would be ideal, but if Javascript is necessary, that would be fine too.
A related symptom which a solution would ideally solve is the fact that the :hover attribute is not activated by the region in between two lines of text. Ideally, the whole section should feel like a text-area, only it is non-rectangular since it is inline with other text.


text:
Q: Error 2003 with mysqldump Here is the command I enter:
mysqldump --host=ec2-107-20-94-121.compute-1.amazonaws.com --password=XXXXX --user=bill --single-transaction blink10 [products,productspriceNEW] > /data/blink10.sql
Here is what i get:
mysqldump: Got error: 2003: Can't connect to MySQL server on 'ec2-107-20-94-121.compute-1.amazonaws.com' (110) when trying to connect
Already checked port for mysql is open according to my firewall, where is the error coming from?

A: You probably need to authorize EC2 to accept incoming connections on 3306, in addition to configuring the firewall on your instance.
See for example http://bigtrapeze.com/2011/03/01/allow-remote-mysql-connections-to-an-aws-instance/
Alternatively, you could also open an ssh tunnel with port forwarding.
See http://www.howtogeek.com/howto/ubuntu/access-your-mysql-server-remotely-over-ssh/

A: Aren't you in a network behind a firewall that can intercept outgoing traffic (blocking port 3306) or maybe personal firewall ?


text:
Q: Can R create a barplot image with clickable bars to insert on a webpage? I know how to create a barplot, and how to stick it on a webpage; e.g, using hwriteImage in the hwriter package.
What I'd like is for each bar to be a region which highlights on mouseover, and where each bar has a different link when clicked. Similar to this map of the U.S. using the jQuery maphilight plugin, but for a barplot rather than a map.  I imagine R could calculate the coordinates of the regions around each bar, generate the HTML AREA tag etc and pass this to maphilight quite easily. Has it been done already? I searched but no luck so far.

A: Have a look here, which summarises a couple of methods: rggobi and iplots. rggobi looks pretty promising, though maybe the installation looks a bit involved. iplots is only good for scatter plots.
Some other options (I think these are strongest ones at the moment):
googleVis
The googleVis package interfaces with the google charts API: try demo(googleVis) and the third & fourth one are bar chart (there could be more). It has the advantage of being pretty simple to get started with, although these are not R graphics:
df=data.frame(country=c("US", "GB", "BR"), val1=c(10,13,14), val2=c(23,12,32))
Column <- gvisColumnChart(df)
plot(Column)

gridSVG
The gridSVG exports the current grid graphics to an .svg file that can be included into a webpage. Unlike googleVis, it's R graphics (so you can use grid/ggplot2 which are more familiar). It looks like you may have to know some Javascript to further embellish your plots though (e.g. to animate on mouse over, you use grid.garnish(...,onmouseover=...)).
There's some example code you can try here (The really awesome ones are here - usually clicking on the "SVG file" link will have the full interactivity/animation.) (This one is a scatterplot where the points highlight when you move your mouse over them).
As I said - have a look at the package pages, demos, examples, etc to see which suits you.


text:
Q: Cocoon gem, image upload with preview I have my nested form partial:

      <% if f.object.picture.present? %>
        <%= image_tag f.object.picture_url, :class=> "gallery-preview-image" %>
      <% else %>

      <% end %>

      <%= f.label :text %>

      <%= f.text_field :text %>
      <%= f.hidden_field :gallery_id, :value => @gallery.id %>

      <%= f.label :position %>

      <%= f.text_field :position %>
      <%= f.file_field :picture, :id => "upload-gallery-picture", :style => "display: none;" %>
      <%= f.hidden_field :picture_cache, :value => f.object.picture_cache %>
      <%= link_to t('seller_home.gallery.upload_picture').html_safe, "javascript:;", :id => "upload-gallery-picture-link", :onclick => "browseFiles(this);" %>

    <%= link_to_remove_association t('seller_home.gallery.remove').html_safe, f  %>

Also, for uploading image and for showing the image preview I've used the following script:

Now, You can see in the script each time I upload an image, the script filereader reads the file and shows its preview in gallery-preview-image.
The problem is that, the partial loads every time. So, for every nested field there is the same gallery-preview-image ID. Thus, if I upload any image to any form it will shows the preview to the top form.
What can I do?

A: You should use a class instead of an id. An id should be unique on a page. A class can be repeated.
So write
<%= f.file_field :picture, :class => "upload-gallery-picture", :style => "display: none;" %>

And adapt your javascript accordingly, so
use $(".upload-gallery-picture") instead.


text:
Q: Array not updating with objects correctly So my array of objects planetArray in the SolarSystem class is not updating with the objects it is assigned. Really just looking for a clue as to what is wrong with the way im doing it. This is a piece of coursework so im not looking for someone to completely rewrite my work, just some pointers as to the specific problem.
Below is the Automatic Test our lecturer uses:
/*This is the automatic test class for CS-110 coursework 2. The output of the student's program
 * under test should match the string TARGET_OUTPUT
 */
public class AutoTest {

    static final String TARGET_OUTPUT =
            "Our System\n"
            + "Planet Mercury has a mass of 0.055 Earths, is 0.387AU from its star, and orbits in 88.025 days\n"
            + "Planet Venus has a mass of 0.815 Earths, is 0.723AU from its star, and orbits in 224.629 days\n"
            + "Planet Earth has a mass of 1.0 Earths, is 1.0AU from its star, and orbits in 365.25 days\n"
            + "Planet Mars has a mass of 0.107 Earths, is 1.52AU from its star, and orbits in 1.874 years\n"
            + "Planet Jupiter has a mass of 317.8 Earths, is 5.2AU from its star, and orbits in 11.858 years\n"
            + "Planet Saturn has a mass of 95.2 Earths, is 9.58AU from its star, and orbits in 29.652 years\n"
            + "Planet Uranus has a mass of 14.5 Earths, is 19.2AU from its star, and orbits in 84.13 years\n"
            + "Planet Neptune has a mass of 17.1 Earths, is 30.05AU from its star, and orbits in 164.728 years\n";

    public static void main(String[] args) {
        SolarSystem ourSystem = new SolarSystem("Our System");

        //Add planets in our solar system
        ourSystem.addPlanet("Mercury", 0.0553, 0.387);
        ourSystem.addPlanet("Venus", 0.815, 0.723);
        ourSystem.addPlanet("Earth", 1.0, 1.0);
        ourSystem.addPlanet("Mars", 0.107, 1.52);
        ourSystem.addPlanet("Jupiter", 317.8, 5.20);
        ourSystem.addPlanet("Saturn", 95.2, 9.58);
        ourSystem.addPlanet("Uranus", 14.5, 19.20);
        ourSystem.addPlanet("Neptune", 17.1, 30.05);

        //Check the output
        if(ourSystem.toString().equals(TARGET_OUTPUT)){
            System.out.println("Pass!");
        } else {
            System.out.println("Fail!\n*****");
            System.out.println("Expected output:\n");
            System.out.println(TARGET_OUTPUT);
            System.out.println("\n\nActual output:\n");
            System.out.println(ourSystem);
        }

    }
}

This is my SolarSystem class:
public class SolarSystem{
    public static final int PLANET_MAX = 10;
    public static int planetCount = 0;
    String systemName;
    Planet[] planetArray = new Planet[PLANET_MAX];
    public SolarSystem(String name){
        systemName = name;
    }

    public void addPlanet(String planetName, double planetMass, double planetDistance){
        Planet newPlanet = new Planet(planetName, planetMass, planetDistance);
        newPlanet.calculatePeriod(planetDistance);
        planetArray[planetCount] = newPlanet;
        planetCount++;
    }

    public String toString(){
        String myString = systemName + "\n";
        for(int i = 0; i <= PLANET_MAX; i++){
            int count = 0;
            String name = planetArray[count].getPlanetName();
            double mass = planetArray[count].getPlanetMass();
            double distance = planetArray[count].getPlanetDistance();
            double period = planetArray[count].getPlanetPeriod();
            if(period < 1){
                myString = myString + "Planet " + name + " has a mass of " + mass + " Earths, is " + distance + " from its star and orbits in " + period + " days.\n";
            }
            else{
                myString = myString + "Planet" + name + "has a mass of" + mass + "Earths, is" + distance + "from its star and orbits in" + period + "years.\n";
            }
            count++;
        }
        return myString;
    }
}

This is my planet class
public class Planet{
    private String planetName;
    private double planetMass;
    private double planetDistance;
    private double planetPeriod;

    public Planet(String planetName, double planetMass, double planetDistance){
        this.planetName = planetName;
        this.planetMass = planetMass;
        this.planetDistance = planetDistance;
    }
    //sets the period for the current object
    public void calculatePeriod(double planetDistance){
        double period = Math.sqrt(planetDistance*planetDistance*planetDistance);
        setPlanetPeriod(period);
    }

    //accessors
    public String getPlanetName(){
        return planetName;
    }
    public double getPlanetMass(){
        return planetMass;
    }
    public double getPlanetDistance(){
        return planetDistance;
    }
    public double getPlanetPeriod(){
        return planetPeriod;
    }

    //mutators
    public void setPlanetName(String planetName){
        this.planetName = planetName;
    }
    public void setPlanetMass(double planetMass){
        this.planetMass = planetMass;
    }
    public void setPlanetDistance(double planetDistance){
        this.planetDistance = planetDistance;
    }
    public void setPlanetPeriod(double planetPeriod){
        this.planetPeriod = planetPeriod;
    }
}

My output shows the array filled with the value for mecury

A: It shows only mercury, because it stays 0, the first index. Moreover in the for loop it should be less than PLANET_MAX, since that is the number of elements (length). Otherwise you would get java.lang.arrayindexoutofboundsexception. Do it like:
public String toString(){
        String myString = systemName + "\n";
        for(int i = 0; i < PLANET_MAX; i++){ //< instead of <=
            String name = planetArray[i].getPlanetName();
            double mass = planetArray[i].getPlanetMass();
            double distance = planetArray[i].getPlanetDistance();
            double period = planetArray[i].getPlanetPeriod();


text:
Q: Apache jmeter - 2.10 - Null point exception while running an existing script The Jmeter script runs fine on apache-jmeter2.8. I upgraded recently to apache-jmeter-2.10 and I started getting Null Point exception.
I revert back to apache-jmeter2.8 and the script works fine.
        java.lang.NullPointerException
at org.apache.jorphan.util.JOrphanUtils.replaceAllChars(JOrphanUtils.java:264)
at org.apache.jmeter.protocol.http.sampler.HTTPSamplerBase.encodeSpaces(HTTPSamplerBase.java:1332)
at org.apache.jmeter.protocol.http.sampler.HTTPSamplerBase.followRedirects(HTTPSamplerBase.java:1404)
at org.apache.jmeter.protocol.http.sampler.HTTPSamplerBase.resultProcessing(HTTPSamplerBase.java:1482)
at org.apache.jmeter.protocol.http.sampler.HTTPAbstractImpl.resultProcessing(HTTPAbstractImpl.java:306)
at org.apache.jmeter.protocol.http.sampler.HTTPHC4Impl.sample(HTTPHC4Impl.java:381)
at org.apache.jmeter.protocol.http.sampler.HTTPSamplerProxy.sample(HTTPSamplerProxy.java:74)
at org.apache.jmeter.protocol.http.sampler.HTTPSamplerBase.sample(HTTPSamplerBase.java:1105)
at org.apache.jmeter.protocol.http.sampler.HTTPSamplerBase.sample(HTTPSamplerBase.java:1094)
at org.apache.jmeter.threads.JMeterThread.process_sampler(JMeterThread.java:429)
at org.apache.jmeter.threads.JMeterThread.run(JMeterThread.java:257)
at java.lang.Thread.run(Unknown Source)

The script is general login script and the failure happens when it is trying to post.
Let me know if you need more info.

A: You may be facing this known bug that has been fixed in nightly build:

*

*https://issues.apache.org/bugzilla/show_bug.cgi?id=55717
As a workaround, try changing http implementation to Java instead of HttpClient4 implementation.
If you want to give nightly build a try, see:
http://jmeter.apache.org/nightly.html

Read:

Installing JMeter runtime
Download the _bin and _lib files
Unpack the archives into the same directory structure
The other archives are not needed to run JMeter.

A: The above error has been addressed in 2.11 version. Download and use the latest version of jmeter 2.11 and check out your script.
No need to go for Nightly Build.


text:
Q: do I need a return after throwing exception (c++ and c#) I have a function that generate an exception. For example the following code:
void test()
{
    ifstream test("c:/afile.txt");
    if(!test)
    {
         throw exception("can not open file");
    }
    // other section of code that reads from file.
}

Do I need a return after throwing the exception?
What is the case in c#?

A: throw usually causes the function to terminate immediately, so you even if you do put any code after it (inside the same block), it won't execute. This goes for both C++ and C#. However, if you throw an exception inside a try block and the exception gets caught, execution will continue in the appropriate catch block, and if there is a finally block (C# only), it will be executed whether an exception is thrown or not. At any rate, any code immediately after the throw will never be executed.
(Note that having a throw directly inside a try/catch is usually a design problem - exceptions are designed for bubbling errors up across functions, not for error handling within a function.)

A: No, you don't need to return, because after the exception is thrown the code after that wont' be executed.

A: Strictly speaking throwing will NOT necessarily terminate the function immediately always.... as in this case,
try {

     throw new ApplicationException();

} catch (ApplicationException ex) {
    // if not re-thrown, function will continue as normal after the try/catch block

} catch (Exception ex) {

}

and then there is the Finally block - but after that it will exit.
So no, you do not have to return.

A: After you call throw the method will return immediately and no code following it will be executed. This is also true if any exceptions are thrown and not caught in a try / catch block.

A: If it's a void method you will never need a return instruction.
Then you can't put anything after the throw instruction it will never be used if something is throw
void test()
{
    ifstream test("c:/afile.txt");
    if(!test)
    {
         throw exception("can not open file");
         // If there is code here it will never be reach !
    }
    // other section of code that reads from file.
    //if you place code here it will be reach only if you don"t throw an exception, so only if test == true in your case
}


text:
Q: How Do I Create a Better Model? Disclaimer: I am a senior undergraduate student of Political Science with little proficiency in Data Science; please help me understand better and forgive any ensuing statistical illiteracy!
TL;DR: I created an OLS regression model using appropriate variable selection methods—wherein I reduced seventeen predictor variables to seven. Now, I am illustrating my OLS assumptions w.r.t to this model and asking for help in creating a better model.
Background Information
I employed OLS Regression in order to study the correlation between my dependent variable of Infant Mortality Rate (per 1000 live births) with respect to the following predictor variables: (1) Mothers received Antenatal care (%); (2) Mothers received Financial Assistance under JSY Scheme (%); (3) Average expenditure at a public health facility(Rs.); (4) Adult Female Literate (%); (5) Per capita NSDP (Rs.); (6) Households with Sanitation (%); (7) Households with Electricity (%).
I am studying this in the context of the Indian nation-state; therefore, my samples—or—N = 32 (the Indian States and UTs excluding those for whom no information was made available).
When I ran a linear multiple OLS Regression on this model (unweighted and not generalized), I obtained the following vital information:

*

*Residual Standard Error: 7.529 on 24 Degrees of Freedom

*Multiple R-squared: 0.7324

*Adjusted R-squared: 0.6543

*F-statistic: 9.384 on 7 and 24 DF

*p-value: 1.397e-05

Assumption Issues
Using the sjmisc and sjPlot packages, I ran the following code to test my OLS assumptions:
require(sjmisc)
require(sjPlot)
plot_model(Model1, type = "diag")

I am sharing the results of the assumptions.

Questions/Clarifications
Based on the assumption and regression results, do you all think that I am on the right track at all? From what I could gather, I can obviously see some issues of (1) non-normal distribution of residuals and (2) heteroscedasticity. However, do you all think that my assumptions of multicollinearity and non-normality of residuals and outliers (Q-Q) are alright?
More importantly, how do I fix these issues and attempt to create a better second model? Please consider that I am a relative beginner to the whole process, so forgive me for not knowing the proper direction. Is my preliminary regression model and result even decent? If so, how should I further improve (1) the normality of my residuals; (2) homoscedasticity; (3) regression results?
Lastly, are there any problems in the way I tested my OLS assumptions?
Thank you so much for your time. Have a great day!

A: For starters, good for you for checking the assumptions of your model. This should be a given, but unfortunately, this step is rarely reported. On the whole, your assumption checks do raise questions about whether OLS regression is appropriate for this data. You seem to have an issue with heteroscedasticity and positively-skewed residuals. This is not too surprising given the dependent variable you are looking at.
It is always possible that you could add other predictors that result in more well-behaved modelling. What is perhaps more reasonable is that you need a generalized linear model. Typically, predicting a rate variable is better done with a Poisson or Negative Binomial (in the case of over-dispersion) regression. There are some theoretical reasons why this is the case, but at the end of the day on the applied stats side, there is minimal difference between OLS regression (linear regression assuming a normal distribution) and generalized regression (linear regression assuming a different kind of distribution). In the case of generalized linear regression, you just need to choose a link function to help convert your linear predictors to whatever new distribution you're describing. You may just want to look at recommendations for predicting mortality rates and see what recommendations there are for modelling. I'm not familiar with the literature, but I'd assume the standard is something like a Poisson regression.
As far as testing the assumptions in alternative ways, this seems like a reasonable approach. Since you're using R, you could also consider using the "gvlma" package. This package lets you specify your normal linear regression using lm() and it tests all the assumptions for linear regression, including the assumption of the linear link function (a significant result there may support the need to move to a generalized linear model).


text:
Q: why can't I initialize a linked list like this? LinkedList.c
#include "stdio.h"
#include "stdlib.h"

struct ListNode
{
    int val;
    struct ListNode *next;
};

int main()
{
    int a[] = {1, 2, 3};
    struct ListNode *head = malloc(sizeof(struct ListNode));
    head->next = NULL;
    struct ListNode *rear = head;
    for (int i = 0; i < 3; i++)
    {
        struct ListNode s;
        s.val = a[i];
        s.next = rear->next;
        rear->next = &s;
        rear = &s;
    }
    struct ListNode *tmp = head;
    head = head->next;
    free(tmp);

    //display
    while (head != NULL)
    {
        printf("%d ",(*head).val);
        head = head->next;
    }

    return 0;
}

If I change the sentece  "struct ListNode s;" to "struct ListNode *s=malloc(sizeof(struct ListNode));" and use "->" but not ".", it will work.

A: As pointed out in comments, you're facing this because ListNode you create in your list creation loop is a local variable limited to loop scope. It only exists in that scope(for that particular iteration). You should use malloc for allocating ListNode and use free to de-allocate memory for your nodes when you're done with using the list. I did minor changes to your list creation loop:
for (int i = 0; i < 3; i++) {
    struct ListNode *s = malloc(sizeof(struct ListNode));
    s->val = a[i];
    s->next = rear->next;
    rear->next = s;
    rear = s;
}

When I ran this, I was able to see expected results:
src : $ gcc initializelinkedlist.c
src : $ ./a.out
1 2 3


text:
Q: Developing for Appstore using jailbroken iPhones HI,
I am new to development for the I phones and got the iphone from USA which is locked to at&t, i have successfully able to develop the apps on it, while it is not unlocked, now i want to unlock it so that i can use it with my local network and also wants to continue the development on it, so is it possible to continue the development on the jailblroken phones for the app store, and what problems may i encounter.

A: I have a first generation american iPhone that is jailbroken and works with my local network.
I had no problem deploying a self made app to my phone.
At the time writing I have iPhone OS 2.1.
I haven't yet gone through the process of submitting the application to AppStore.

A: As long as the application is developed using accepted Apple practices (using the official iPhone SDK, and not open-toolchain or something like that) and does not use any private APIs, you should not have any trouble submitting an application just because you tested it on a jailbroken (or carrier unlocked) phone.
To be 100% accurate, jailbreaking and carrier unlocking are against the developer agreement, but I can't really imagine the circumstances that would lead to you being caught.


text:
Q: Conversion between const wchar_t* and const char*, not allowed using qt I am trying to use the library simplexlsxwriter  with Qt, however when i try to compile I met the following error on several place in the code :
"cannot convert 'const TCHAR* {aka const wchar_t*}' to 'const char*' for argument '1' to 'size_t strlen(const char*)'"
The line in question is:
bool HasZipSuffix(const TCHAR *fn) {
    const TCHAR *ext = fn+_tcslen(fn);
}

In order to remove the error i tried the following:
bool HasZipSuffix(const TCHAR *fn) {
    const char* fn_cc = reinterpret_cast<const char*> (fn);
    const TCHAR *ext = fn+_tcslen(fn_cc );
}

It works, however it introduces a lot of errors (about 3720 issues) during compilations. I use mingw53_32 under Qt.
It is very strange since when i create a simple Makefile as follow:
ROOT_DIR := ./

CXXFLAGS=-MMD -MP -Wall
CXXFLAGS+= -I$(ROOT_DIR)

src = Zip/zip.cpp \
    Xlsx/Chartsheet.cpp \
    Xlsx/Workbook.cpp \
    Xlsx/Worksheet.cpp \
    Xlsx/XlsxHeaders.cpp \
    main.cpp

includes = Zip/zip.h \
    tchar.h \
    Xlsx/Chartsheet.h \
    Xlsx/SimpleXlsxDef.h \
    Xlsx/Workbook.h \
    Xlsx/Worksheet.h \
    Xlsx/XlsxHeaders.h

object=$(src:.cpp=.o)

%: %.o
    $(LINK.cpp) -o $@ $^ $(LDFLAGS)

main: $(object)

-include $(src:.cpp=.d)

The compilation encountered absolutely no difficulty and I obtain the desired binary. So my question is, why using Qt the conversion from  const wchar_t* to  const char* throw an error while using "raw" mingw compiler, it does not throw any error ?

A: Just add
DEFINES -= UNICODE

to the .pro file. qmake by default defines -DUNICODE, which clashes with the win32 library.


text:
Q: Newton's root finding method in MATLAB: quadratic vs cubic convergence So I have this example Newton's method for root finding with quadratic convergence below. It takes a function f, the derivative of f df, initial guess g, and tolerance tol. It outputs the # iterations it to reach nth root, the root estimate r, and the error approximation err.
function [it, r, err] = QuadraticN(f, df, g , tol)

   num_it = 20;
   it_max = num_it + 1;

   x(1)=(g + num_it)/2;   %set x at n = 1

    n = 1;
    r = 0; % root
    it = 0; % iteration #
    err =0; % error

% n = 1
r(1) = x(1)-f(x(1))/df(x(1)); % root at n = 1
err(1) = abs(x(1)-g); % error at n = 1

% n > 1
while (min(abs(f(x(n))))) && (abs(x(n)-it_max)>tol) && (it < num_it)

     x(n+1)=x(n)-f(x(n))/df(x(n)); % quadratic method

     it_max=x(n); % reset counter
     r= x(n); % set root to current at n

     err = f(x(n)); % set error to current
     it = n;  % keep track of iterations
     n=n+1;    % increment to next n

   end

end

Given this example, I am trying to implement a second version of the method that uses cubic convergence as opposed to quadratic and this is what I have (this is just the part of the function that would be changed to cubic, it takes the same inputs with the addition of ddf = the second derivative):
 r(1) = x(1)-df(x(1))/ddf(x(1)) + (sqrt((df(x(1)))^2 -
2*f(x(1))*ddf(x(1)))) / ddf(x(1));

err(1) = abs(x(1)-g); % error at n = 1

while (min(abs(ddf(x(n))))) && (abs(x(n)-it_max)>tol) && (it < num_it)

    cube = ((sqrt((df(x(n)))^2 - 2*f(x(n))*ddf(x(n)))) / ddf(x(n)));

    first = x(n) - df(x(n))/ddf(x(n));
    first = real(first); % is this right?

    x(n+1) = first + (cube);

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    %% FIX THIS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    %%%% check when to do plus or minus
   if( first > 0)
        x(n+1)=x(n)-df(x(n))/ddf(x(n)) + cube;
    else
        x(n+1)=x(n)-df(x(n))/ddf(x(n)) - cube;

   % end

I'm not sure if I am checking when to use +/- cube correctly. I know it will depend on the multiplicity but I'm not sure if using first (Newton's basic method). It is outputting some of the roots correctly, but for instance for the equation -x^3 + 8 with initial guess 2 I am getting -9.85985274E-01. Now I don't know if this is part of the problem above or if converting to real before calculating is. I am also getting negative errors. I am checking in the same way as I did with quadratic but I am not sure if this is right.


text:
Q: Python script stops working with BEX error I have a Python script running on Windows, which is basically RESTful interface client with multiple connections to SQL database. It has to be restarted with some period of time (for example, 15 minutes). For this purpose I wrapped the code inside the loop with function os.execl(). I run script from PowerShell using following format:
PS C:\test> python.exe .\script.pyc

Script itself (without disclosing implementation details):
import base64
import datetime
import glob
import logging
import os
import socket
import sys
import threading
import time
import pyodbc
import binascii
import configparser
import codecs
import requests
from collections import namedtuple
from binascii import unhexlify, b2a_base64

FORMAT = '%(asctime)-15s %(levelname)-10s %(message)s'
logging.basicConfig(format=FORMAT, level=logging.INFO)
log = logging.getLogger()

# some class declarations here

if __name__ == '__main__':

    # Initializing counter for time
    timeLast = time.time()

    while 1:
        timeCurrent = time.time()
        if ((timeCurrent - timeLast) > resetTime):
            timeLast = timeCurrent
            os.execl(sys.executable, sys.executable, * sys.argv)

        try:
            # Fetching data from DB
            # Processing data

        except Exception as e:
            log.error(repr(e))
            time.sleep(1)

# Wait for user input before exiting
sys.stdin.read()

However, after few days of running script stops working with following buffer overflow exception (BEX):

Faulting application python.exe, version 3.6.3150.1013, time stamp
  0x59d3c90d, faulting module ucrtbase.dll, version 10.0.10586.1171,
  time stamp 0x59ae5046, exception code 0xc0000417, fault offset
  0x000834c4, process id 0xecc, application start time
  0x01d351c6613b826e.

Also I noticed that PowerShell console window is not refreshing window content unless I put its window in focus and press arrow down. Maybe some different issue.
Environment:

*

*Windows Server Standard SP2 (32-bit)

*PowerShell 2.0

*Python 3.6.3

A: Seems issue is related to that fact that script is running inside PowerShell. It is not observed, while script is being run inside Python Shell.


text:
Q: Java Json parser I'm using tomcat 5 and JSON parser net/sf/json. I import json-lib2.4-jdk15.jar in my project and add it to `common/endorsed' dir in my tomcat. But when I start my servlet I have this exception:
java.lang.NoClassDefFoundError: net/sf/json/JSONException
net.sf.json.JSONSerializer.toJSON(JSONSerializer.java:108)
net.sf.json.JSONSerializer.toJSON(JSONSerializer.java:84)
com.britecs.atajer.bl.json.SubCategories.getSubCategory(SubCategories.java:37)
com.britecs.atajer.pl.json.SubCategoriesServlet.doGet(SubCategoriesServlet.java:23)
javax.servlet.http.HttpServlet.service(HttpServlet.java:689)
javax.servlet.http.HttpServlet.service(HttpServlet.java:802)

Can someone help me?

A: I'm not sure 'tomcat/common/endorsed' is the right directory to be using.  Have you tried installing your JAR file in tomcat/lib?


text:
Q: AlertDialog.Builder Below 19 How to make this alert to appear on apis below 19? Thanks.
AlertDialog.Builder mBuilder = new AlertDialog.Builder(this);
LayoutInflater inflater = this.getLayoutInflater();
View mView = inflater.inflate(R.layout.recover_password_dialog, null);
Button btnSend = (Button) mView.findViewById(R.id.btnRecuperar);
final EditText emailRecover = (EditText) mView.findViewById(R.id.emailRecover);
mBuilder.setView(mView);
btnSend.setOnClickListener(new View.OnClickListener() {

this is bugging my head.

A: May be you using
import android.support.v7.app.AlertDialog;

Try change it to
import android.app.AlertDialog;

A: I think you should be implementing this import for the AlertDialog class
import android.support.v7.app.AlertDialog;

Let me know if that helped

A: This is odd.
I had a function to present that dialog. working 100% on api 21 but not on 1.
What I did was delete the function and make OnClickListener on the EditText.
and on the code change this.
LayoutInflater inflater = login.this.getLayoutInflater();


text:
Q: alternate vertical timeline doesn't working I created a vertical timeline and inserted this code to make the contents alternate left and right, but something is not working, because the contents are all positioned on the left. Can you tell me where I went wrong?
https://modern.wedding-site.it/
thank you so much
.timeline_vertical > .ct-div-block > .ct-div-block {
  background: #fff;
  padding: 5%;
  width: 90%;
  margin-bottom: 30px;}
.timeline_vertical:before {
    position: absolute;
    left: 50%;
    top: 0;
    content: ' ';
    display: block;
    width: var(--line-width);
    height: 100%;
    background: var(--line-color);
    -webkit-transform: translateX(-50%);
            transform: translateX(-50%);}
.timeline_vertical > .ct-div-block {
    width: 50%;
    position: relative;}
.timeline_vertical > .ct-div-block::before {
    content: "";
    position: absolute;
    top: 0;
    width: var(--dot-size);
    height: var(--dot-size);
    border-radius: var(--dot-radius);
    border: var(--dot-border-width) solid var(--dot-border-color);
    background: var(--dot-background);
    z-index: 2;}
.timeline_vertical > .ct-div-block:nth-child(2n-1)::before {
  right: 0;
  -webkit-transform: translateX(50%);
          transform: translateX(50%);}
.timeline_vertical > .ct-div-block:nth-child(2n)::before {
  left: 0;
  -webkit-transform: translateX(-50%);
          transform: translateX(-50%);}
.timeline_vertical > .ct-div-block:nth-child(even) {
    -ms-flex-item-align: end;
        align-self: flex-end;
    -webkit-box-align: end;
        -ms-flex-align: end;
            align-items: flex-end;}
.timeline_vertical > .ct-div-block > .ct-text-block {
    position: absolute;
    top: -5px;
    right: -30px;
    -webkit-transform: translateX(100%);
            transform: translateX(100%);}
.timeline_vertical > .ct-div-block:nth-child(even) > .ct-text-block {
    left: -30px;
    top: -5px;
    right: auto;
    -webkit-transform: translateX(-100%);
            transform: translateX(-100%);}

A: It seems that the odd/even css rule got ignored because the parent is not the same (it has other parent between).
Change your code (or just add):
.oxy-dynamic-list .ct-div-block:nth-child(even) {
    -ms-flex-item-align: end;
    align-self: flex-end;
    -webkit-box-align: end;
    -ms-flex-align: end;
    align-items: flex-end;
}


text:
Q: Automatically suspend VMs after shutdown of Proxmox host I'm looking for a way to suspend my VMs after the Proxmox host do a restart. Using Hyper-V, its possible to define an action for each VM like suspend or restart, which should be done on the VM after host reboot. Proxmox by default shutdown the VM together with the host. I couldn't find any config option, only to let Proxmox automatically start a VM after shutdown.
I found this article: http://8086.support/content/13/75/en/how-do-i-configure-kvm-to-suspend_restore-virtual-machines-when-the-host-is-rebooted.html Seems exactly what I need, but the file /etc/sysconfig/libvirt-guests doesn't exist. This file is part of the libvirt-client package, which is not installed and so no part of Proxmox. So I'm not sure, if its a good idea to use Proxmox together with another management solution, which libvirt seems to be. According to this Entry, its even not possible.
Isn't there a native way from proxmox to suspend a VM after host shutdown?

A: Have you tried posting on the Proxmox forums? They're the expert of their product so I'd recommend it.
Even if there's not an easy "built in" way to configure that by default, it's still possible. Proxmox is Debian under the hood, so you could write a script to do what you want on shutdown/reboot.
The builtin pvesh allows you to interact with your PVE server from the commandline and do tons of different things (including suspend and start). It interacts with the PVE RESTful API. Info on pvesh is here and the full API docs are here.
Once you've written a script that will suspend or restart your VMs, you can then leverage SystemD to launch your script at the appropriate time. E.g. the CLI part of this


text:
Q: How To Add Storyboard Constraints For Equal Spaced Buttons I am trying to add two buttons to a view that also contains a table view. I want the two buttons to fill the width of the screen for different screen sizes (portrait only). There is a minimum width of say 100 units for the buttons to hold the text, but I would like them to be wider for larger screens. I would like the space between buttons to be at least 20 units and at least 20 units of space between the outside edges. This seems like it should be straight forward, but I can't make sense of the align and pin constraints in the Storyboard auto layout. So far, the tutorials I have seen are confusing and don't seem to cover the right amount of detail to help me. Please provide me with some guidance. Below is the layout before constraints are put in place.

And here is what the layout would look on a 4" iPhone:

I have already spent a day trying different combinations of constraints, but continue to have problems. Just when I think I have something that works, it won't build because it says I have conflicts.
I am trying to use the following tools (along with the align tools - not shown) to create the proper constraints. I have tried selecting one or both buttons and then using the editor to set the constraints, but each attempt looks bad. Even when I choose "Reset to Suggested Constraints", I get wacko results. Please help with suggestions on how to accomplish this seemingly basic task.

A: You must have:

*

*Leading for first button 20

*Trailing for second button 20

*horizontal spacing between buttons 20

*equal widths for both buttons

*width >= 150 for each button


text:
Q: Conditional Entropy of Lossy Channel Output I've seen the following claim in several sources, that all treat it as completely obvious, but am unable to prove it, probably due to lack of basic knowledge about probability and information theory, which at present I'm trying to learn on my own.
Claim:
Let $N\in\mathbb{N}$, $N>0$, and $X$ be a random variable in $\{0, 1\}^N$ (possibly further implicit assumptions are needed?). This random variable is transmitted through a lossy channel which has a probability $p_e$ of flipping any individual bit (the bits are treated as independent by this memoryless transmission). The result of the transmission is $Y$. Then the conditional (Shannon) entropy of $X$ given $Y$ is
$$
\begin{equation}
H(X|Y) = Nh(p_e) = N \left(-p_e \log(p_e) - (1-p_e)\log(1-p_e) \right),
\end{equation}
$$
where $h(p_e)$ is the Shannon entropy of a Bernoulli trial with parameter $p_e$.
My Attempt:
I tried to use the definition of conditional entropy:
$$
\begin{equation}
H(X|Y) = -\sum_{x,y\in\{0,1\}^N} p(x,y) \log\frac{p(x,y)}{p(y)}.
\end{equation}
$$
For $x,y\in\{0,1\}^N$ let $k$ be the Hamming distance between $x$ and $y$, i.e., the number of bits where $x$ and $y$ differ. Then $p(x,y)= p(x)\binom Nkp_e^k(1-p_e)^{N-k}$. However, if I try to plug this into the formula and somehow convert the sum into a sum over $k$ (which I'm not sure is correct in the first place), I get something like the entropy of a Binomial distribution, for which no simple formula is known. Clearly I'm doing something wrong. How would you prove the above claim (while possibly adding the "obvious" implicit assumptions)? Thanks in advance!

A: Denoting $X=(X_1, X_2, \ldots, X_N)$ and similary for $Y$, note that, since the channel is memoryless
$$
\mathbb{P}(X=(x_1,x_2,\ldots,x_N)|Y=(y_1,y_2,\ldots,y_N))=\prod_{i=1}^N \mathbb{P}(X_i=x_i|Y_i=y_i).
$$
From fundamental properties of the entropy, it follows that
$$
\begin{align}
H(X|Y)&=\sum_{i=1}^NH(X_i|Y_i)\\
&=N H(X_i|Y_i),
\end{align}
$$
You have probably seen the first equality as holding for unconditional entropy, you may want to work on showing why this also holds for conditional entropy. The second equality holds since the channel treats each bit the same. Now, you need to show that $H(X_i|Y_i)=h(p_e)$.

A: This summarizes the argument by Stelios (accepted answer) into a full proof.
Result: Let $N\in\mathbb{N}$, $N>0$ and $X$ be a random variable in $\{0,1\}^N$. Let $Y$ be the result of transmitting $X$ over a memoryless symmetric binary channel with error probability $p_e$. Then $$\begin{equation}H(X|Y) = N\end{equation}h(p_e)$$ where $h$ is the binary entropy function.
Proof.
Note that $$H(X_i|Y_i = 0) = - \left(\mathbb{P}(X_i=0|Y_i=0)\log\mathbb{P}(X_i=0|Y_i=0)  + \mathbb{P}(X_i=1|Y_i=0)\log\mathbb{P}(X_i=1|Y_i=0) \right).$$
By definition of the binary symmetric channel, $\mathbb{P}(X_i=0|Y_i=0) = 1 - p_e$ and $\mathbb{P}(X_i=1|Y_i=0) = p_e$, Hence $H(X_i|Y_i = 0) = h(p_e)$. By symmetry (or repeating the calculation), we find $H(X_i|Y_i = 1) = h(p_e).$
In summary, $$H(X_i|Y_i) = \sum_{y\in\{0, 1\}} p(Y_i=y) H(X_i|Y_i=y)=\sum_{y\in\{0, 1\}} p(Y_i=y) h(p_e) = h(p_e).$$
We turn to the sum property for conditional entropy. Since the channel is memoryless,
$$
\mathbb{P}(X=(x_1,x_2,\ldots,x_N)|Y=(y_1,y_2,\ldots,y_N))=\prod_{i=1}^N \mathbb{P}(X_i=x_i|Y_i=y_i).
$$
Consider the case of only four random variables $X_1, X_2, Y_1, Y_2$ such that $\mathbb{P}(X_1,X_2|Y_1,Y_2) = \mathbb{P}(X_1|Y_1)\mathbb{P}(X_2|Y_2)$. By (one) definition of conditional entropy
$$H(X_1,X_2|Y_1,Y_2) = \sum_{y_1, y_2}\mathbb{P}(Y_1=y_1, Y_2 = y_2)H(X_1, X_2|Y_1=y_1, Y_2 = y_2).$$
The second factor in the sum is the entropy of $X_1, X_2$ conditioned on $Y_1=y_1$ and $Y_2=y_2$. In particular, it is the (standard Shannon) entropy of the conditional probability distribution $$(x_1,x_2)\mapsto \mathbb{P}(X_1=x_1, X_2=x_2|Y_1=y_1,Y_2=y_2) = \mathbb{P}(X_1=x_1|Y_1=y_1) \mathbb{P}(X_2=x_2|Y_2=y_2),$$
i.e. the joint entropy of the two independent probability distributions $\mathbb{P}(X_1|Y_1=y_1)$ and $\mathbb{P}(X_2|Y_2=y_2)$. Hence
$$
\begin{align}
&H(X_1,X_2|Y_1,Y_2) \\&= \sum_{y_1, y_2}\mathbb{P}(Y_1=y_1, Y_2 = y_2)H(X_1, X_2|Y_1=y_1, Y_2 = y_2) \\&= \sum_{y_1, y_2}\mathbb{P}(Y_1=y_1, Y_2 = y_2)\left(H(X_1|Y_1=y_1) + H(X_2|Y_2=y_2)\right) \\&= \sum_{y_1}\left(\sum_{y_2}\mathbb{P}(Y_1=y_1, Y_2=y_2)\right)H(X_1|Y_1=y_1) + \sum_{y_2}\left(\sum_{y_1}\mathbb{P}(Y_1=y_1, Y_2=y_2)\right)H(X_2|Y_2=y_2) \\&=^{*} \sum_{y_1}\mathbb{P}(Y_1=y_1)H(X_1|Y_1=y_1) + \sum_{y_2}\mathbb{P}(Y_2=y_2)H(X_2|Y_2=y_2) \\&= H(X_1|Y_1) + H(X_2|Y_2),
\end{align}$$
where equality (*) follows from the definition of marginal distributions. This argument generalizes to $N$ pairs of random variables $(X_i, Y_i)$.
Combining everything, where $X=(X_1,\dots, X_N)$ and $Y = (Y_1, \dots, Y_N)$,
$$
\begin{equation}
H(X|Y)=\sum_{i=1}^NH(X_i|Y_i)=N H(X_i|Y_i)=Nh(p_e).
\end{equation}
$$


text:
Q: how can i cal the the controller function I am using ng-view in angularjs.
app.controller("onedetailsCtrl", ['$scope', '$rootScope', function($scope, $rootScope) {

    $rootScope.url = "Samples/one.html";

}])
app.config(['$routeProvider',
    function($routeProvider) {
        $routeProvider.
        when('/one', {
            templateUrl: 'sample/one.htm',
            controller: 'onedetailsCtrl'
        }).
        when('/two', {
            templateUrl: 'sample/two.htm',
            controller: 'deatailsController'
        }).
        otherwise({
            redirectTo: '/one'
        });
    }
]);

Here how can I call the controller function. I have tried below method also.
$scope.$on('$viewContentLoaded', function (event) {

$compile($('#auto'))($scope);

});
})

A: If u include the angular js script properly , it will take care of calling the controller function. U dont have to call it manually. If everthing is properly written including the syntax , angular will directly call onedetailsCtrl since if nothing is found , u are routing to page '/one'.

A: The controller linked to the route will automatically be linked upon route resolving. Therefor calling the linked route controller function can be invoked as following.
Route
when('/two', {
    templateUrl: 'sample/two.htm',
    controller: 'deatailsController'
}).

Controller
Add a controller $scopevalue that will be added on the view.
app.controller('deatailsController', function($scope) {
    alert('Hi deatailsController!');
    // add a scope value from inside the controller
    $scope.testValue = "Hello, this is the controller scope value";
}]);

View
On the HTML template sample/two.htm add following {{testValue}} to show the value binded to the scope object from inside the linked controller.


text:
Q: Ionic 3 App - Best way to work with non-ionic html components Ionic library offers a big collection of components and the documentation is great. So, if you need a button with a custom function called onClick, you quickly find the best way to do it by placing the button into a page.html (home.html in my case)
<button ion-button (click)="logEvent(this)"> Button</button>

and adding a function to the into a page.ts (home.ts in my case)
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  constructor(public navCtrl: NavController) {

  }

  logEvent(event) {
    console.log(event);
  }
}

But what is the best way to work with non-ionic elements such as a standard html checkbox element? Because Ionic 3 does not have a star rating element, I have to import a third-party solution for this element.
The rendering works well and the star rating looks like this

Now my problem is, I need to bind an onClick function to the inputs of the checkbox element. Having some minor experience in JavaScript, I tend to simply define a script section in the page.html and do some regular JavaScript binding. This, however, does not feel right, and, does not even seem to work.
I would appreciate if someone with experience could point out the most likely obvious way to do it as I could not google it. Obviously I am searching the wrong direction.
The checkbox element looks like this:

  <input type="checkbox" id="st1" value="1" />

  <input type="checkbox" id="st2" value="2" />

  <input type="checkbox" id="st3" value="3" />

  <input type="checkbox" id="st4" value="4" />

  <input type="checkbox" id="st5" value="5" />

A: I highly recommend using ionic2-rating component. I have used it one of my Ionic 3 / Angular 5 app and it is working perfectly fine.If you have any issues with it please let me know.
.html
<rating [(ngModel)]="rate"
        readOnly="false"
        max="5"
        emptyStarIconName="star-outline"
        halfStarIconName="star-half"
        starIconName="star"
        nullable="false"
        (ngModelChange)="onModelChange($event)">
</rating>


text:
Q: How long would it take Mustafa to do the job alone?
Murat and Mustafa can do a job together in fifteen days. After they
  have worked together for five days, Mustafa leaves the job. Murat
  completes the job in sixteen days. How long would it take Mustafa to
  do the job alone?

The answer is 40 days but I want the steps to solve this.

A: Let $\;x,y\;$ be the amount of days it takes to Murat, Mustafa respectively to complete the job alone. We're given that
$$15\left(\frac1x+\frac1y\right)=1$$
so that after 5 days they worked together they did one third of the job, and it then took Murat sixteen days to complete the two thirds that were still left:
$$\frac13+\frac{16}x=1\iff\frac x{16}=\frac32\implies x=24$$ and then
$$15\left(\frac1{24}+\frac1y\right)=1\implies\frac{15}y=\frac38\implies y=40$$

A: The classical way of solving this would be to find the speeds by which they both work (for convenience, in units of full jobs per day). Let's say Murat works at speed $v_1$ and Mustafa works at speed $v_2$. Then the fact that they finish in $15$ days if they cooperate means that $v_1 + v_2 = \frac1{15}$.
If they work together for five days, then a third of the work is done. That means Murat does two thirds of a job in $16$ days, or symbolically, that
$$
v_1 = \frac{2/3}{16} = \frac1{24}
$$
Now you should be able to do the rest.

A: Let $M$ be the fraction of the job that Murat can finish in one day.  Let $m$ be the fraction of the job that Mustafa can finish in one day. Then the statement that they can finish the job together in 15 days is:
$$M+m = \frac{1}{15}$$
After $5$ days then have finished
$$5(M+m) = \frac{5}{15} = \frac13$$
a third of the job.
Then we are told that for the remaining $\frac23$,
$$ 16M = \frac23 \implies M = \frac{2}{48} = \frac{1}{24} $$
So
$$
\frac{1}{24} + m = \frac{1}{15}\\
m = \frac{1}{15}-\frac{1}{24} = \frac{24-15}{24\cdot 15}=\frac{9}{360} = \frac{1}{40}
$$
So Mustapha finshes  $\frac{1}{40}$ each day.

A: Let $x$ be the rate of work/day of Murat and $y$ the rate of work/day of Mustafa, and $w$ the unknown amount of work, then you can model the given information as:
$$
15 (x + y) = w \\
5(x+y) + 16 x = w
$$
The final equation is
$$
d \, y = w
$$
where $d$ is the sought for number of days.
These are three equations with three unknowns $d$, $x$, $y$ and an unkown workload $w$, which itself does not matter (except it should not be zero).
Substracting the second from the first equation gives
$$
10 (x+y) - 16 x = 0 \iff \\
10 y = 6 x \iff \\
y = (3/5) x
$$
and using this in the first one:
$$
w = 15 x + 15 (3/5) x = 24 x \iff \\
x = w / 24
$$
Which leads to
$$
y = (3/5) (w/24) = (1/40) w
$$
Then using the last equation
$$
d (1/40) w = w \iff \\
d = 40
$$


text:
Q: Why does the Weierstrass theorem fail if a set is not compact? By Weierstrass theorem I mean that if
$f:\mathbb{R}^n \to \mathbb{R}$ is continuous and $C \subset \mathbb{R}^n$ is compact, then the theorem asserts that a solution
$x^*$ of
$$ \text{min} _{x\in C}f(x)$$
exists.
How does this theorem come to fail if
$C$ is either not closed, or it's not bounded, or $f$ isn't continuous?
Could someone show me with an example of each case?
For an unbounded set $C$ I would say if $C \in (-\infty,\infty)$ then $\text min f(x) = \emptyset$
But I can't think of anything for discontinuity or an open set?

A: For an unbounded set, $f(x)=x$ in $\mathbb{R}$.
For a non-closed set, $f(x)=1/x$ in $(0,1)$


text:
Q: it's possible to create a fake data field in a delphi dataset? I want to create a 'fake' data field in a DataSet (not ClientDataSet):

*

*the field should not be stored in the db

*it's not a calculated field (the user should be allowed to enter input data)

*the field has business logic meaning, so after the user updates its value it should update other fields (with the OnFieldChange event)

I know I can have a simple no-dbaware control, capture it's OnChange event and perform the calculations there (or call a DataModule function, where the DataSet resides) but I think it's more clean if I can reutilize the dataset automatic binding with db-ware controls and dataset events..
Also this way the unique connection between the Form (Presentation) and the DataModule (Model) it's the DataSet (less coupling)..
PD: I'm using fibplus, with I think the solution (if any) will be at the VCL level..
Thanks!

A: You could create an updatable view (with before insert/update/delete triggers) in your Interbase/Firebird database. This would look like a "virtual table" to the client (the select statement of the view's declaration can also contain "virtual fields") and it's totally up to you how you implement the triggers.

A: You can make a Calcfield writeable:
type
  TCalcStringField = class(TWideStringField)
    function GetCanModify: Boolean; override;
  end;

function TCalcStringField.GetCanModify: Boolean;
begin
  // Makes Calcfield editable
//if FieldNo > 0 then
    if DataSet.State <> dsSetKey then
      Result := not ReadOnly and DataSet.CanModify
    else
      Result := IsIndexField
//else
//  Result := False;
end;

Set Calculated to true, and in OnSetText of this Field you can then write the Text to any other place
procedure TformXX.XXOnSetText(Sender: TField; const Text: string);
begin
   ...
end;

A: Have you tried using an InternalCalc field? Your data aware controls will let you edit an InternalCalc field's value, and the value is stored in the dataset.
If you create an InternalCalc field in the dataset (TClientDataSet, TQuery, etc.) at design time, it's almost exactly what you're asking for.


text:
Q: How can I limit the BB DateTimePicker? I use a DateTimePicker in my app and I want it to allow to select only past dates, I use it to allow the user to select his date of birth and I would like it to start and end at a given year.

A: Well, a quick look at the DateTimePicker documentation shows that you use the setDateTime, setMaximumDate and setMinimumDate methods to set the timespans and initial date.

A: I managed to solve this the following way:
Calendar minDate = Calendar.getInstance();
minDate.set(Calendar.DAY_OF_MONTH, 1);
minDate.set(Calendar.MONTH, Calendar.JANUARY);
minDate.set(Calendar.YEAR, 1920);

_datePicker.setMinimumDate(minDate);


text:
Q: How can I get my Redux useSelector to update on store change? I'm using the Redux Toolkit and I'm struggling to find a way to update state within my store that also triggers a reassignment for useSelector.
const slice = createSlice({
  name: "state",
  initialState: [],
  reducers: {
    addToArray: (state, action) => {
      state.push(action.payload); // This updates the store but doesn't respect immutability?
   }
 }
});

I'm aware the above isn't entirely correct, and that something like
state = [...state, ...action.payload]
would be better, BUT for some reason I couldn't get it work correctly any other way. I'm simply trying to add an object to the array.
My component:
export default function App() {
   const array = useSelector(selectArray);

   return (
     {array.map((x) => {
        <div>{x.text}</div>
     })
   )
}

The issue is, whenever the dispatch is called, array doesn't update, which I'd like it to.

A: I think your issue is the way you push the new value into the array. That is not immutable and it appears the selector is detecting that the array hasn't changed, so it returns the previous value.
Try this:
const slice = createSlice({
  name: "state",
  initialState: [],
  reducers: {
    addToArray: (state, action) => {
      state = [ ...state, action.payload ];
   }
 }
});

This demo should simulate what happens when mutably changing state vs immutably changing state.

const state = {
  list: [1]
}

const addItemMutable = (item) => {
  const prevState = { ...state }
  state.list.push(item)

  // Using JSON.stringify for better readability in output.
  console.log(JSON.stringify(prevState.list), JSON.stringify(state.list))
  console.log(prevState.list === state.list)
}

const addItemImmutable = (item) => {
  const prevState = { ...state }
  state.list = [ ...state.list, item ]

  // Using JSON.stringify for better readability in output.
  console.log(JSON.stringify(prevState.list), JSON.stringify(state.list))
  console.log(prevState.list === state.list)
}

addItemMutable(2)
addItemImmutable(3)


text:
Q: How to get the response and logs of a Jenkins test without using the interface, from command line using curl? I am using curl command to build a job in Jenkins:
curl --user "admin:passwd" -X POST http://localhost:8080/job/jobname/build

How can I check if the test was successful or failed and how to get the logs of that build from command line only, preferably using curl?

A: If you have BlueOcean plugin installed, you can query its API. This usually returns JSON output that you might need to question further.
First, you need to find the build number triggered by your curl command. Then, you need to wait until your build is over. Then, you can question the result.
A good start is:
"curl -s ${your_jenkins}/blue/rest/organizations/jenkins/pipelines/${jobname}/runs/${buildbumber}/nodes/?limit=10000"


text:
Q: File.separator vs. File.pathSeparator File has the static Strings separator and pathSeparator. The separator is a "default name-separator character" and the pathSeparator is a "path-separator character".
What is the difference? Is there a time when one is preferable to the other?

A: java.io.File class contains four static separator variables. For better understanding, Let's understand with the help of some code

*

*separator: Platform dependent default name-separator character as String. For windows, it's '\' and for unix it's '/'

*separatorChar: Same as separator but it's char

*pathSeparator: Platform dependent variable for path-separator. For
example PATH or CLASSPATH variable list of paths separated by ':' in
Unix systems and ';' in Windows system

*pathSeparatorChar: Same as pathSeparator but it's char

Note that all of these are final variables and system dependent.
Here is the java program to print these separator variables.
FileSeparator.java
import java.io.File;

public class FileSeparator {

    public static void main(String[] args) {
        System.out.println("File.separator = "+File.separator);
        System.out.println("File.separatorChar = "+File.separatorChar);
        System.out.println("File.pathSeparator = "+File.pathSeparator);
        System.out.println("File.pathSeparatorChar = "+File.pathSeparatorChar);
    }

}

Output of above program on Unix system:
File.separator = /
File.separatorChar = /
File.pathSeparator = :
File.pathSeparatorChar = :

Output of the program on Windows system:
File.separator = \
File.separatorChar = \
File.pathSeparator = ;
File.pathSeparatorChar = ;

To make our program platform independent, we should always use these separators to create file path or read any system variables like PATH, CLASSPATH.
Here is the code snippet showing how to use separators correctly.
//no platform independence, good for Unix systems
File fileUnsafe = new File("tmp/abc.txt");
//platform independent and safe to use across Unix and Windows
File fileSafe = new File("tmp"+File.separator+"abc.txt");


text:
Q: Does winapi's bcrypt.h actually support bcrypt hashing? This may sound like a strange question, and it feels a bit bizarre that I actually have to ask this, but after spending a couple hours looking over the MSDN documentation for the bcrypt routines that were added in Vista, I've almost reached the conclusion that there is no actual bcrypt support!
According to Wikipedia:

bcrypt is an adaptive cryptographic hash function for passwords
  ... based on the Blowfish cipher ... Besides incorporating a
  salt to protect against rainbow table attacks, bcrypt is an adaptive
  hash: over time it can be made slower and slower so it remains
  resistant to specific brute-force search attacks against the hash and
  the salt.

However, from the documentation on MSDN, the "bcrypt" library is apparently actually a generic interface for encryption and hashing.  You have to obtain a handle to an "algorithm provider" via the BCryptOpenAlgorithmProvider function, which has several built-in algorithms to choose from.  But the word "blowfish" does not appear anywhere in the list.
So am I missing something?  Am I reading this wrong?  Or does Windows's "bcrypt" library not actually support bcrypt at all?

A: In the context of the MSDN, BCrypt is a shortform of "BestCrypt", but the PR name for it is:

Cryptography API: Next Generation (Cng)

It is implemented in bcrypt.dll.
BestCrypt/BCrypt/Cng is the successor to the older CryptoAPI.
Microsoft is slowly removing references to "BestCrypt" from their site, but you can still see it in some pages like:

SHA256Cng Class
This algorithm is for hashing only and does not provide any encryption or decryption. It uses the BCrypt (BestCrypt) layer CNG.

It's interesting (to me anyway) that the .NET framework generally can provide you three implementations for the each kind of crypto algorithm. For example, for SHA2 hashing, there is:

*

*SHA256Managed: an implementation written purely in managed code

*SHA256CryptoServiceProvider: a wrapper around the native Cryptographic Service Provider (CSP) implementation

*SHA256Cng: a wrapper around Cryptography Next Gen (Cng) implementation

Short version
No, bcrypt is short for bestcrypt. And, no, it doesn't support bcrypt (blowfish crypt) password hashing.

A: the BCrypt APIs are generic and support various cryptographic hash algorithms, but bcrypt is not one of them.  The B Prefix seems to be just a way to distinguish between the older APIs and the Next Generation.


text:
Q: Better understanding of timing and pipelining In this code, I'm just looping through the set of instructions a bunch of times. Without regard to how many times (100, 1000, 1000000), the timing using RDTSC shows (outputs) 6 clock cycles for the loop. I'm on a Coffee Lake I9-9900K
There are 13 instructions in the loop- I would have thought the minimum RDTSC delta would have been 13.
Would someone be able to educate me as to how this is seeming to run twice as fast as I expected it to? I'm clearly misunderstanding something basic, or I've made a ridiculous mistake.
Thank you!
    rng.SetFloatScale(2.0f / 8.0f);
00C010AE  vmovups     ymm4,ymmword ptr [__ymm@3e0000003e0000003e0000003e0000003e0000003e0000003e0000003e000000 (0C02160h)]

    Vec8f sum = 0;
    const size_t loopLen = 1000;

    auto start = __rdtsc();
00C010BB  rdtsc
00C010BD  mov         esi,eax
        sum += rng.NextScaledFloats();
00C010F0  vpslld      ymm0,ymm2,xmm5
00C010F4  vpxor       ymm1,ymm0,ymm2
00C010F8  vpsrld      ymm0,ymm1,xmm6
00C010FC  vpxor       ymm1,ymm0,ymm1
00C01100  vpslld      ymm0,ymm1,xmm7
00C01104  vpxor       ymm2,ymm0,ymm1
00C01108  vpand       ymm0,ymm2,ymmword ptr [__ymm@007fffff007fffff007fffff007fffff007fffff007fffff007fffff007fffff (0C02140h)]
00C01110  vpor        ymm0,ymm0,ymmword ptr [__ymm@4000000040000000400000004000000040000000400000004000000040000000 (0C021A0h)]
00C01118  vmovups     ymm1,ymm4
00C0111C  vfmsub213ps ymm1,ymm0,ymmword ptr [__ymm@3e8000003e8000003e8000003e8000003e8000003e8000003e8000003e800000 (0C02180h)]
00C01125  vaddps      ymm3,ymm1,ymm3
    for (size_t i = 0; i < loopLen; i++)
00C01129  sub         eax,1
00C0112C  jne         main+80h (0C010F0h)
    auto end = __rdtsc();
00C0112E  rdtsc
00C01130  mov         edi,eax
00C01132  mov         ecx,edx

    printf("\n\nAverage: %f\nAverage RDTSC: %ld\n", fsum, (end - start) / loopLen);


text:
Q: How to run a javascript function on all the rows When a cell is clicked the function is suppose to run.
Right now it is working only on the first row.
When i click on the button on a row i want that specific row to affect.
$(document).ready(function() {
  function loadHistory() {
    $('#btn').data('valType', 'more');
    $('#btn').click(function() {
      var id = $('#btn').data("valType")
    })
  }
})

A: In this case, use class selector, instead of id.
For example, yo have any list:

$(document).ready(function() {
  $('.delete').click(function(e) {
    $(this).parent().parent().remove();
  })
})

      Number
      Name
      Action

        1

        Chair

        <button class="delete">Delete</button>

        2

        Sofa

        <button class="delete">Delete</button>

        3

        Table

        <button class="delete">Delete</button>

A: Without the HTML code it is a bit more difficult to answer you, but I try.
Usually the ID is unique, so it's assigned to only one element, so try using the class selector.
Then another thing, I don't know if this is your case, if you go to create the other lines dynamically, the jQuery .click () function will not be able to manage the clicks on the elements created after loading the page. In this case use $.on('click', '.yourClass', function).
I hope I was helpful!