text:
Q: oData and EF4 - different result for the same query I am running the following query...
(from txRx in TxRxes
where txRx.Serial == "someSerial"
select txRx).Single().TxRxModes.Count()

When I run this on the database using EF4 in LinqPad, I get the correct result of 1 back. When I run exactly the same query on the same database through oData (using the same underlying context) I get 0.
Why?

A: The Single forces the query before it to execute in OData (technically it's WCF Data Services). So the query sent to the server is just the selection of a txRx with the specified serial. The difference from EF is, that EF will lazy load navigation properties (in your case the TxRxModes) and thus when you access it to count it, it works.
WCF Data Services doesn't perform lazy load, since it could be very expensive (HTTP request to a remote server), and thus the TxRxModes is just an empty collection.
To work around this, you should be able to modify your code to preload the navigation property in question (so eager loading):
(from txRx in TxRxes.Expand("TxRxModes")
where txRx.Serial == "someSerial"
select txRx).Single().TxRxModes.Count()

Note the additional Expand call which causes the query to pull not just the txRx but also all its related TxRxModes from the server (in one query).


text:
Q: how to traversing through vector using iterator and accessing element value? I started to use iterators for traversing through a vector. Usually, I would use this to go through a vector:
for( int i=0; i< vector.size(); i++){
    cout<<vector[i];
}

I learned if I want to use iterators I would have to do something like this:
vector<int>::iterator col;
for(col = vector.begin(); col != vector.end(); col++){
    cout << *col;
}

But, if I want to access the value at which the iterator is pointing, how would I do that?
I tried to do this:
 int temp = *col;

but this gives an error

Assigning to 'int' from incompatible type 'std::__1::vector<int, std::__1::allocator<int> >'

I am trying this because I have a 2d vector and I'm trying to find the sum of individual columns.

A: The code you showed is correct ... for a 1D vector. But, you say you are actually using a 2D vector, in which case the outer vector's elements are themselves vectors, and so dereferencing an iterator for the outer vector gives you a reference to an inner vector.  That is exactly what the error message is complaining about - you are trying to assign an inner vector to an int, which will obviously not work. You would have to iterate that inner vector separately, same as you would have to do when using indexes instead of iterators, eg:
std::vector<std::vector<int> > rows_vec;
...
/*
for(size_t row_idx = 0; row_idx < rows_vec.size(); ++row_idx){
    std::vector<int> &row_vec = rows_vec[row_idx];
    int sum_cols = 0;
    for(size_t col_iter = 0; col_idx < row_vec.size(); ++col_idx){
        sum_cols += row_vec[col_idx];
    }
    // use sum_cols as needed...
}
*/
std::vector<std::vector<int> >::iterator row_iter;
for(row_iter = rows_vec.begin(); row_iter != rows_vec.end(); ++row_iter){
    std::vector<int> &row_vec = *row_iter;
    std::vector<int>::iterator col_iter;
    int sum_cols = 0;
    for(col_iter = row_vec.begin(); col_iter != row_vec.end(); ++col_iter){
        sum_cols += *col_iter;
    }
    // use sum_cols as needed...
}

If you are using C++11 or later, this can be greatly simplified using range-based for loops:
std::vector<std::vector<int>> rows_vec;
...
for(auto &row_vec : rows_vec){
    int sum_cols = 0;
    for(int col_val : row_vec){
        sum_cols += col_val;
    }
    // use sum_cols as needed...
}

Which could be simplified more by using the standard std::accumulate() algorithm, eg:
std::vector<std::vector<int>> rows_vec;
...
for(auto &row_vec : rows_vec){
    int sum_cols = std::accumulate(row_vec.begin(), row_vec.end(), 0);
    // use sum_cols as needed...
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Counting the number of response codes in JMeter 4.0 I run some load tests (all endpoints) and we do have a known issue in our code: if multiple POST requests are sent in the same time we do get a duplicate error based on a timestamp field in our database.
All I want to do is to count timeouts (based on the message received "Service is not available. Request timeout") in a variable and accept this as a normal behavior (don't fail the tests).
For now I've added a Response Assertion for this (in order to keep the tests running) but I cannot tell if or how many timeout actually happen.
How can I count this?
Thank you

A: If you just need to find out the count based on the response message then you can save the performance results in a csv file using simple data writer (configure for csv only) and then filter csv based on the response message to get the required count. Or you can use Display only "errors" option to get all the errors and then filter out based on the expected error message.
If you need to find out at the runtime then you can use aggregate report listener and use "Errors" checkbox to get the count of failure but this will include other failures also.
But, if you need to get the count at the run time to use it later then it is a different case. I am assuming that it is not the case.
Thanks,

A: I would recommend doing this as follows:

*

*Add JSR223 Listener to your Test Plan

*Put the following code into "Script" area:
if (prev.getResponseDataAsString().contains('Service is not available. Request timeout')) {
    prev.setSampleLabel('False negative')
}

That's it, if sampler will contain  Service is not available. Request timeout in the response body - JMeter will change its title to False negative.

You can even mark it as passed by adding prev.setSuccessful(false) line to your script. See Apache Groovy - Why and How You Should Use It article fore more information on what else you can do with Groovy in JMeter tests


text:
Q: I want to bring the file from S3 to Elasticsearch I want to bring the file from S3 to Elasticsearch
Help me
thanks!

A: You could have described in a little more details your use case, but with the little information you have given, here is what I would suggest.
Logstash provides the s3 input plugin which you can use to source data from an S3 bucket. Data from the files inside that bucket can then be sent to Elasticsearch using the Logstash elasticsearch output plugin
The Logstash configuration file would look like this:
input {
  s3 {
    "access_key_id" => "1234"
    "secret_access_key" => "secret"
    "bucket" => "my-bucket"
  }
}
output {
  elasticsearch {
    hosts => "http://localhost:9200"
    index => "my-index"
  }
}

Another idea since you are in the AWS ecosystem would be to create a lambda that sources data from an S3 bucket and sends it directly to Elasticsearch. Here is an example on how to set this up: https://github.com/miztiik/serverless-s3-to-elasticsearch-ingester


text:
Q: Client error: `POST https://api.mailgun.net/v3/sandbox75c537762edc4d29becf4de26ec1738b.mailgun.org/messages.mime` resulted in a `400 BAD REQUEST Estoy implementando Mailgun en Laravel. hice toda la configuración y desde localhost me funciona perfecto, pero cuando hago deploy en Heroku me sale el siguiente error:

Client error: POST
  https://api.mailgun.net/v3/sandbox75c537762edc4d29becf4de26ec1738b.mailgun.org/messages.mime
  resulted in a 400 BAD REQUEST response: { "message": "Sandbox
  subdomains are for test purposes only. Please add your own domain or
  add the address to authoriz (truncated...)

Estoy usando mi propio dominio, no se que estará fallando, pero en localhost los correos se envían sin problema.
archivo .env
MAIL_DRIVER=mailgun
MAIL_HOST=smtp.mailgun.org
MAIL_PORT=587
MAIL_USERNAME=postmaster@email.Mydomain.co
MAIL_PASSWORD=1567---ca----b3f74f23fe
MAIL_ENCRYPTION=tls
MAILGUN_DOMAIN=email.Mydomain.co
MAILGUN_SECRET=key-03be65a7c90-----f51d---83e4

Services
    'mailgun' => [
    'domain' => env('MAILGUN_DOMAIN'),
    'secret' => env('MAILGUN_SECRET'),
],

A: Al parecer es un problema que no actualiza los cambios realizados en el archivo .env --> investigaré más sobre este tema.
Lo resolví de la siguiente manera por si alguien tiene el mismo problema:
Reemplacé las lineas del archivo services.php:
estaban originalmente así:
'mailgun' => [
    'domain' => env('MAILGUN_DOMAIN'),
    'secret' => env('MAILGUN_SECRET'),
],

las reemplacé por:
'mailgun' => [
    'domain' => ('email.Mydomain.co'),
    'secret' => ('key-03be65a7c90-----f51d---83e4'),
],

No se por qué, pero según la documentación es como dicen las minas originales, sin embargo, al reemplazarlas funciona.


text:
Q: retriving web.config appsettings on html page I wanna use appsettings value from web.config file on html page in javascript or jquery. The content from my web.config file is:
<configuration>
 <appSettings>
   <add key="ServiceURL" value="http://localhost:16917/Service1.svc"></add>
 </appSettings>
</configuration>

I have tried with
var serviceUrl='<%=ConfigurationManager.AppSettings["ServiceURL"].ToString() %>'
alert(serviceUrl);

Instead of showing value from webconfig it is showing  <%=ConfigurationManager.AppSettings["ServiceURL"].ToString() %> on alert.
Can anybody help me please.

A: I think you are missing closing tag '>'
<configuration>
 <appSettings>
   <add key="ServiceURL" value="http://localhost:16917/Service1.svc"> </add>
 </appSettings>
</configuration>

A: 1. Change WebConfig UI
<pages pageBaseType="Main.Web.ViewPage">

*Create an abstract class that implement from the WebViewPage.

public abstract class ViewPage<T> : WebViewPage<T>
    {
        public ViewPage()
        {
        }

        public JSSettings UISession
        {
            get
            {
                var appSettingsFileBasedSettings = new JSSettings()
                {
                    SessionTimeoutMinutes = ConfigurationManager.AppSettings["SessionTimeoutMinutes"]
                };
                return appSettingsFileBasedSettings;
            }
        }
    }

*In the html page just do something like.

<script type="text/javascript">
        var show = {
            Settings : @Html.Raw(Json.Encode(this.UISession))
            };

        console.log(show);
</script>

Hope it help.

A: This should work:
var test = {
    ServiceURL: <%=ConfigurationManager.AppSettings["ServiceURL"] %>
}

A: You can't do that with static HTML file, at least not in any good way.
Instead, use the power of ASP.NET and work with a Web Form, where you have Code Behind.
In the code behind, send the value from the server to the client as JS variable:
protected void Page_Load(object sender, EventArgs e)
{
    Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), "ServiceURL_JS",
        string.Format("var serviceUrl = \"{0}\"; ",
        ConfigurationManager.AppSettings["ServiceURL"]), true
    );
}

Now you can access the variable serviceUrl in the client side JS.


text:
Q: R and S3 generic functions I am having trouble creating an S3 print method for a function I have.
Within the function I have two variables, one returns a single number, and the other returns a data frame with multiple rows and multiple columns.
Within my function I have the following:
rate = A/B
kout = list(rate, C)
class(kout) = 'kfoldOut'
return(kout)

in the above A and B are numeric and C is a data.frame with 2 rows and 50 columns. I then create my print method as follows.
print.kfoldOut = function(x) {
cat("Rate:", x$rate)
print(x$C)
}

When I run my function e.g.
z = func(x,y)

and then
print(z)

I get Rate: NULL
I can return Rate and C directly within my function and everything looks good, but cannot get the print method working.
EDIT: The output of dput(z), note I have removed values for ease of view.

structure(list(0.312169312169312, structure(list(C = c(0,
0), X1 = c(1, 0), X2 = c(1, 0), .... X18.9 = c(1, 0), X19.8 = c(0, 0)), .Names = c("C",
"X1", "X2", "X3", .... "X19.8"), row.names = c("trueV", "testing_rd2"
), class = "data.frame")), class = "kfoldOut")


text:
Q: What does "model-based" mean for multivariate statistics? What does "model-based" mean for multivariate statistics?
E.g. mvabund– an R package for model-based analysis of multivariate abundance data.
How is "non-model-based multivariate statistics" then?
Thanks!

A: According to the world-renowned statistician Peter McCullagh (of generalized linear models fame), a statistical model can be defined as "a set of probability distributions on the sample space" (2002, p. 1225). Therefore, regardless of being multivariate or univariate, I would define a model-based statistics as a set of statistical statements, which includes corresponding assumptions or facts in regard to data probability distributions, as well as specification of relationship between variables, representing (modeling) the data. Thus, a non-model-based multivariate (or univariate) statistics is the one, lacking some elements, comprising statistical model, for example, distribution assumptions. This is, of course, my own simplistic approach to the topic. Much more detailed and formal treatise on the subject can be found the above-referenced paper by McCullagh.
References
McCullagh P. (2002). What is a statistical model? Annals of Statistics, 30(5), 1225-1310. Retrieved from https://galton.uchicago.edu/~pmcc/pubs/AOS023.pdf

A: Multivariate abundance data (for ecology: observations as rows and species as columns) is usually analyzed using an algorithmic approach. For example, a summarizing distance measure (eg. Bray Curtis) is used for each observation. This matrix of distances is then analyzed using an algorithm. PERMANOVA, for example, uses permutations of the data in a Bray Curtis matrix to create a null distribution, and then test the F-ratio against a distribution of F-ratios to determine significance (Anderson 2001). This does not fit a statistical model.
Model based analyses of multivariate data have been more recently advocated for (see Warton et al. 2014) due to the challenges of distance based multivariate approaches confounding dispersion and location effects (Warton et al 2012). A model based approach "involves specifying a statistical model for the observed multivariate abundance data". I highly recommend reading all of the cited publications, they are excellent.
Anderson, M. J. 2001. A new method for non-parametric multivariate analysis of variance. Austral Ecology:32–46.
Warton, D. I., S. D. Foster, G. De'ath, J. Stoklosa, and P. K. Dunstan. 2014. Model-based thinking for community ecology. Plant Ecology.
Warton, D. I., S. T. Wright, and Y. Wang. 2012. Distance-based multivariate analyses confound location and dispersion effects. Methods in Ecology and Evolution 3:89–101.


text:
Q: wordpress bootstrap submenu always visible in mobile view I am using wordpress and The responsive menubar is having issues. The sub-menu links are always visible in the mobile responsive view. The operative site is Here
I have checked for this issue in Google but didnt find the proper answer anywhere. Can anyone solve here please?

A: You override bootstraps css within your custom media-query in your style.css - see .dropdown-menu at line 138: display: block is the problem!
  .dropdown-menu {
    background-color: transparent;
    border: medium none;
    border-radius: 0;
    box-shadow: none;
    display: block;
    float: none;
    padding: 10px 0;
    position: static;
}

Removing display: block should resolve the problem.

A: Default css queries of bootstrap are bypassed by your style.css. Look at the class dropdown-menu and remove display-block in your media query of max-width: 767px. This will solve your problem.


text:
Q: No usable version of libssl was found Aborted (core dumped) (Powershell on ubuntu 21.04) I have installed powershell on ubuntu 21.04:
$ sudo snap install powershell --classic
snap "powershell" is already installed, see 'snap help refresh'

But when I try to run it I get:
$ powershell
PowerShell 7.1.4
Copyright (c) Microsoft Corporation.

https://aka.ms/powershell
Type 'help' to get help.

No usable version of libssl was found
Aborted (core dumped)

Also tried:
$ sudo apt-get install libssl1.0
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
Note, selecting 'libssl1.0-dev' for regex 'libssl1.0'
Note, selecting 'libssl1.0.0' for regex 'libssl1.0'
Note, selecting 'libssl1.0.2' for regex 'libssl1.0'
0 upgraded, 0 newly installed, 0 to remove and 2 not upgraded.

Still same error. This worked before with ubuntu 20.10.
Also related - but not solved:
https://ubuntuforums.org/showthread.php?t=2465105
Any suggestions?


text:
Q: Java: array initialize in shorthand cannot assign to an object Integer i1 = 1;
Integer i2 = 2;

Number arr1[] = {i1, i2};

as we already know, {i1, i2} is shorthand for new Number[]{i1, i2}
but when declare in this way:
Object o = {i1, i2};   //error

I got a compile error:
Type mismatch: cannot convert from Integer[] to Object
On the other hand,
Object arr1 = new Number[]{i1, i2};

Isn't it means, that the array can be convert to Object.
And if I write in this way:
Number arr2[] = {i1, i2};
Object obj = arr2;

It's also okay.
So, the problem i want to consult is, why did I got the compile error.
Or the eclipse gave me an mistake error message ,for '{i1, i2}' in the expression 'Object o = {i1, i2};' is not an array?

A: Shorthand array initializers are only valid when initializing an array. Number arr1[] = {i1, i2}; declares and initializes an array of Number. Object o just declares a single object, not an array. You could write Object o = new Number[] { i1, i2 }; (e.g., not shorthand) and it would work.

A: {..} is a syntactic sugar for declaring an array type and initializing it.
In your Object o = {i1, i2}, you didn't specify that it is an array type (because you omitted []), so the compiler does not even know that it is an array i.e. it treats that it is a single object and throws error.
Object o = {i1, i2}; // This is NOT an array type

Object[] o = {i1, i2}; //This represents an array

But, once you have got an array object created (i.e., either with new operator specifying the size or by using the above syntactic sugar), you will have an array object which you can assign it to an Object type as shown below:
Number arr1[] = {i1, i2};//arr1 created & initialized
Object obj1 = arr1;//arr1 can now be assigned to Object type

Number arr2[] = new Number[2];//arr2 created (initialized values to null)
Object obj2 = arr2;//arr2 can now be assigned to Object type


text:
Q: Getting isometric grid coordinates from standard X,Y coordinates I'm currently trying to add sprites to an isometric Tiled TMX map using Objects in cocos2d. The problem is the X and Y metadata from TMX object are in standard 2d format (pixels x, pixels y), instead of isometric grid X and Y format. Usually you would just divide them by the tile size, but isometric needs some sort of transform.
For example on a 64x32 isometric tilemap of size 40 tiles by 40 tiles an object at (20,21)'s coordinates come out as (640,584)
So the question really is what formula gets (20,21) from (640,584)?

A: Straight from cocos2d's CCTMXLayer source code:
-(CGPoint) positionForIsoAt:(CGPoint)pos
{
    CGPoint xy = {
        mapTileSize_.width /2 * ( layerSize_.width + pos.x - pos.y - 1),
        mapTileSize_.height /2 * (( layerSize_.height * 2 - pos.x - pos.y) - 2),
    };
    return xy;
}

A: Wikipedia's isometric projection article is your friend here. In the maths section:
cx   | 1  0  0 |  | c' 0 -s' |  ax
cy = | 0  c  s |  | 0  1  0  |  ay
cz   | 0 -s  c |  | s' 0  c' |  az

Where c is the vector you get by rotating a through some angle alpha (first matrix) and then beta (second matrix), s = sin(alpha), c = cos(alpha), s' = sin(beta), c' = cos(beta). You then project that onto 2d by pre-multiplying c:
vx   | 1 0 0 |  cx
vy = | 0 1 0 |  cy
vz   | 0 0 1 |  cz

Combining all these matrix transforms into one:
vx   | c'  0  -s' |  ax
vy = | ss' c  sc' |  ay
vz   | 0   0   0  |  az

To get the transform in numbers, use your own values of alpha and beta to generate the coefficients.


text:
Q: parallel.invoke behaving differently in Winform and Console Application I recently built a prototype c# console application to read in measurements from four instruments in parallel(On the same TimeStamp), I used the parallel.invoke command to do so, The results were quite good every single time. Later i tried to implement the same concept in Winforms using backgroundworker. So in my DoWork i call this parallel.invoke to run the four functions to get readings, but the results are returned after so long and they are not on the same time stamp, I did try it without background worker but i have the same results. Any one has idea why parallel.invoke is behaving so?. That it works fine in console application and not in winform?. Also is there is a way to make sure that multiple async procces execution is run in parallel?. I am having a hard time understanding this, Please help me out here. Any comments would be appreciated!
Update : Sorry for the confusion , I did this before with parallel Invoke
             later i changed it to task but the behaviour is the same.
Console Application:
public static void funcc()
{
    for (int i = 0; i < 5; i++)
    {
        rawData3 = fmio.IO.Read(4 * numReadings);
        RawData3.Add(rawData3);
    }
}

public static void funcd()
{
    for (int i = 0; i < 5; i++)
    {
        rawData4 = fmio.IO.Read(4 * numReadings);
        RawData4.Add(rawData4);
    }
}

static void Main(string[] args)
{
    //Parallel.Invoke(() => { funcb(); }, () => { funcc(); }, () => { funca(); }, () => { funcd(); });

    var factory = new TaskFactory(TaskCreationOptions.LongRunning, TaskContinuationOptions.None);

    Task t1 = factory.StartNew(funca);
    Task t2 = factory.StartNew(funcb);
    Task t3 = factory.StartNew(funcc);
    Task t4 = factory.StartNew(funcd);

    t1.Wait();
    t2.Wait();
    t3.Wait();
    t4.Wait();

    WriteToFile(); // Writes Result to the file
}

In my Gui Application I am am doing this in backgroundWorker I have the same readings functions as defined above that i am using in my GUI Application:
public static void funca()
{
    for (int i = 0; i < 5; i++)
    {
        rawData = fmio.IO.Read(4 * numReadings); // Getting Data in Byte Array
        RawData1.Add(rawData);                   // Putting it in ArrayList
    }
}

public static void funcb()
{
    for (int i = 0; i < 5; i++)
    {
        rawData2 = fmio.IO.Read(4 * numReadings);
        RawData2.Add(rawData2);
    }
}

private void btn_StartMeasurement_Click(object sender, EventArgs e)
{
    if (!bwObj.IsBusy)
    {
        bw_Obj.RunWorkerAsync();
    }
}

private void bw_Obj_DoWork_1(object sender, DoWorkEventArgs e)
{
    //Parallel.Invoke(() => { funcb(); }, () => { funcc(); }, () => { funca(); }, () => { funcd(); });

    var factoryA = new TaskFactory(TaskCreationOptions.LongRunning, TaskContinuationOptions.None);
    var time = System.Diagnostics.Stopwatch.StartNew();
    Task t1 = factoryA.StartNew(() => funca(Globls.numReadings, DMM));
    Task t2 = factoryA.StartNew(() => funcb(Globls.numReadings, DMM2));
    Task t3 = factoryA.StartNew(() => funcc(Globls.numReadings, DMM3));
    Task t4 = factoryA.StartNew(() => funcd(Globls.numReadings, DMM4));

    t1.Wait();
    t2.Wait();
    t3.Wait();
    t4.Wait();

    WriteToFile();
}

A: I'd handle the issue like this: extract the working parallel-reading code in its own static class, then call it from both the console application and the winforms application, and see what happens. You should find yourself with something that either goes both ways, or doesn't work at all (since you're calling the same code).

A: This could be implemented many ways. If you're looking for executing what's in the bw_Obj_DoWork_1 section in parallel then I'd consider changing the btn_StartMeasurement_Click and dropping the BackgroundWorker.
private void btn_StartMeasurement_Click(object sender, EventArgs e)
{
    Task[] tasks = new Task[]
        {
            Task.Factory.StartNew(funca),
            Task.Factory.StartNew(funcb),
            Task.Factory.StartNew(funcc),
            Task.Factory.StartNew(funcd)
        };
    Task writeTask = Task.Factory.ContinueWhenAll(tasks, (t) => writeToFile());
}

Or, you could create a method, I'll call it executeAndWrite, and use Threads or Tasks in btn_StartMeasurement_Click to start them:
private void btn_StartMeasurement_Click(object sender, EventArgs e)
{
    new Thread(executeAndWrite).Start();
}

private void executeAndWrite()
{
    Parallel.Invoke(funca, funcb, funcc, funcd);
    writeToFile();
}

I'd personally go with this option.


text:
Q: Woo-commerce 3.0 single product price is not changing properly I made a new post type named "sub_products" containing the meta tag "unit_price".
After assigning a new field for every Woocommerce product containing a list of all the "sub_products" posts, the goal was to update every product price based on the selected "sub_products" meta "unit_price".
function kulcskron_edit_post( $p1, $p2 )
{
  if ( !is_admin() )
    return;

  if ( get_post_type() != 'product' )
    return;

  $sub_product_ids = $p2->get_meta( 'sub_products' );

  if ( empty($sub_product_ids) )
    return;

  $product_regular_price = 0;
  foreach ( $sub_product_ids as $id )
    $product_regular_price += get_post_meta( $id, 'unit_price', true );

  if ( $p1 == $product_regular_price )
    return;

  $p2->set_regular_price( $product_regular_price );
  $p2->save();
}
add_action( 'woocommerce_product_get_price', 'kulcskron_edit_post', 10, 2 );

I tried every possible hook to make this work:
add_action( 'the_post', 'kulcskron_edit_post', 9, 1 );
add_action( 'edit_post', 'kulcskron_edit_post', 10, 2 );
add_action( 'pre_get_posts', 'kulcskron_edit_post' );
add_action( 'save_post', 'kulcskron_edit_post' );

This code updates the price but in a strange way:
Admin single product edit view: The price is not updated right away, just after I revisit the edit screen.
Admin product listing view: Every price is 0.
Front-end product page view: The displayed price is 0.
How do I update the product price based on the assigned "sub_products" "unit_price" post meta when a single product is saved in admin view?

A: You may use the hook "woocommefrce_get_price_html" it should work

A: I managed to solve the price update problem.
I used the save_post action:

save_post is an action triggered whenever a post or page is created or updated, which could be from an import, post/page edit form, xmlrpc, or post by email.

The final code:
function kulcskron_update_product( $product_obj )
{
  if ( !is_admin() )
    return;

  if ( get_post_type() != 'product' )
    return;

  $product = wc_get_product( $product_obj );
  if ( !$product->meta_exists( 'sub_products' ) )
    return;

  $sub_product_ids = $product->get_meta( 'sub_products' );
  if ( empty($sub_product_ids) )
    return;

  _update_product_price( $product_obj, $sub_product_ids );

}
add_action( 'save_post', 'kulcskron_update_product' );

And for the sake of completeness here is the rest of code:
function _update_product_price( $product_obj, $sub_product_ids )
{
  $product = wc_get_product( $product_obj );

  $product_regular_price = 0;
  foreach ( $sub_product_ids as $id )
    $product_regular_price += get_post_meta( $id, 'kulcskron_unit_price', true );

  $product->set_regular_price( $product_regular_price );
  $product->set_price( $product_regular_price );
  $product->save();
}

This way basically everything can be edited and updated. Example:
function _update_product_stock( $product_obj, $sub_product_ids )
{
  $product = wc_get_product( $product_obj );

  $sub_product_stocks = array();
  foreach ( $sub_product_ids as $id )
    $sub_product_stocks[] = get_post_meta( $id, 'kulcskron_free_stock_quantity', true );

  $product->set_manage_stock( true );
  $product->set_stock_quantity( min($sub_product_stocks) );
  $product->save();
}

I would love to post a link to all the methods to edit a product but I have no rep for that.
But sadly this is not all...
In order to fully update the price, we need to filter the price HTML to return the newly updated price.
function kulcskron_price_html( $priceHtml, $product )
{
  $symbol = get_woocommerce_currency_symbol();
  $price = $product->get_regular_price();
  $html = ''. $price .' '. $symbol .'';
  return $html;
};
add_filter( 'woocommerce_get_price_html', 'kulcskron_price_html', 10, 2 );

A little backstory. We need to sync all the products from an external database through an XML file. But there is a catch, the XML file only contains product parts and they are not displayed, searched, filtered and certainly can't be ordered individually. None of the Woocommerce build in functionality meet these requirements.
In order to solve this, I registered a new post type and imported all the product parts into this newly created post type. After that, I registered a new field for every WC Product with the Advanced Custom Fields plugin.
It looks like this:
Newly registered custom post type with the custom fields
The code above makes easy to update the WC Products (e.g. Prices) based on the selected Sub products.


text:
Q: Minimizing Function with vector valued input in MATLAB I want to minimize a function like below:

Here, n can be 5,10,50 etc. I want to use Matlab and want to use Gradient Descent and Quasi-Newton Method with BFGS update to solve this problem along with backtracking line search. I am a novice in Matlab. Can anyone help, please? I can find a solution for a similar problem in that link: https://www.mathworks.com/help/optim/ug/unconstrained-nonlinear-optimization-algorithms.html .
But, I really don't know how to create a vector-valued function in Matlab (in my case input x can be an n-dimensional vector).

A: You will have to make quite a leap to get where you want to be -- may I suggest to go through some basic tutorial first in order to digest basic MATLAB syntax and concepts?  Another useful read is the very basic example to unconstrained optimization in the documentation.  However, the answer to your question touches only basic syntax, so we can go through it quickly nevertheless.
The absolute minimum to invoke the unconstraint nonlinear optimization algorithms of the Optimization Toolbox is the formulation of an objective function.  That function is supposed to return the function value f of your function at any given point x, and in your case it reads
function f = objfun(x)
    f = sum(100 * (x(2:end) - x(1:end-1).^2).^2 + (1 - x(1:end-1)).^2);
end

Notice that

*

*we select the indiviual components of the x vector by matrix indexing, and that

*the .^ notation effects that the operand is to be squared elementwise.
For simplicity, save this function to a file objfun.m in your current working directory, so that you have it available from the command window.
Now all you have to do is to call the appropriate optimization algorithm, say, the quasi Newton method, from the command window:
n = 10; % Use n variables
options = optimoptions(@fminunc,'Algorithm','quasi-newton'); % Use QM method
x0 = rand(n,1); % Random starting guess
[x,fval,exitflag] = fminunc(@objfun, x0, options); % Solve!
fprintf('Final objval=%.2e, exitflag=%d\n', fval, exitflag);

On my machine I see that the algorithm converges:

Local minimum found.
Optimization completed because the size of the gradient is less than
  the default value of the optimality tolerance.

Final objval=5.57e-11, exitflag=1


text:
Q: mysql too many indexe keys I working on database optimization where there is a bulk insert from .csv file (around 3800 records) at an interval of every 15 minutes.
For this, I'm running a mis.sql file through cron. This file contains Nine (09) mysql queries that performs duplicate removal from the table where bulk insert is targeted, Inner join Inserts, Deletes and Updates (ALTER, DELETE, INSERT & UPDATE).
Recently, a problem is being experienced with a query that runs just prior to the Bulk Insert query. The query is -
ALTER IGNORE TABLE pb ADD UNIQUE INDEX(hn, time);
ERROR 1069 (42000): Too many keys specified; max 64 keys allowed
On encountering above error, all the subsequent queries are being skipped. Then I checked table pb and found that there are 64 Unique Index Keys created with same cardinal value along with 02 Index Keys and 01 Primary Key.
While trying to remove one of the Unique Indexes, it's taking too much of time (almost 15 mins for 979,618 records), but at the end, it's not being removed.
Is there any solution to this problem?

A: The first thing: Why is there an ALTER TABLE command at all? New data should change the data not the database design. So while INSERT, UPDATE and DELETE are valid options in such a script ALTER TABLE doesn't belong there. Remove it.
As to deleting the index: That should only take a fraction of a second. There is nothing to build or rebuild, simply to remove.
DROP INDEX index_name ON tbl_name;

The only reason for this taking so long I can think of is that there isn't even a short time slice when no inserts, updates and deletes take place. So maybe you'll have to stop your job for a moment (or run it on an empty file), drop all those unnecessary indexes (only keep one), and start your job again.


text:
Q: Where is the 'this' pointer stored in computer memory? Where exactly is the 'this' pointer stored in memory? Is it allocated on the stack, in the heap, or in the data segment?
#include <iostream>
using namespace std;

class ClassA
{
    int a, b;

    public:
        void add()
        {
            a = 10;
            b = 20;
            cout << a << b << endl;
        }
};

int main()
{
    ClassA obj;
    obj.add();
    return 0;
}

In the above code I am calling the member function add() and the receiver object is passed implicitly as the 'this' pointer. Where is this stored in memory?

A: The easiest way is to think of this as being a hidden extra argument that is always passed automatically.
So, a fictional method like:
size_t String::length(void) const
{
  return strlen(m_string);
}

is actually more like this under the hood:
size_t String__length(const String *this)
{
  return strlen(this->m_string);
}

and a call like:
{
  String example("hello");
  cout << example.length();
}

becomes something like:
cout << String__length(&example);

Note that the above transformation is simplified, hopefully to make my point a bit clearer. No need to fill up the comments with "whaaa, where's the marshalling for method overloading, huh?"-type objection, please. :)
That transforms the question into "where are arguments stored?", and the answer is of course "it depends". :)
It's often on the stack, but it could be in registers too, or any other mechanism that the compiler considers is good for the target architecture.

A: Other answers have done a very good job explaining how a typical compiler implements this (by passing it as an implicit first parameter to the function).
I think it's also useful to see what the C++ ISO spec explicitly says about this.  According to the C++03 ISO spec, §9.3.2/1:

In the body of a nonstatic (9.3) member function, the keyword this is a non-lvalue expression whose value is the address of the object for which the function is called.

It's important to note that this is not a variable - it's an expression, much in the same way that the expression 1 + 2 * 3 is an expression.  The value of this expression is permitted to be stored pretty much anywhere.  The compiler might put it on the stack and pass it as an implicit parameter to a function, or it might put it in a register, and it conceivably could put it in the heap or in the data segment.  The C++ specification deliberately gives the implementation some flexibility here.
I think that the "language-lawyer" answer is "this is completely implementation-defined, and moreover this is technically not a pointer, but an expression that evaluates to a pointer."
Hope this helps!

A: this is usually passed as a hidden argument of the method (the only difference throughout different calling conventions is how).
If you call:
myClass.Method(1, 2, 3);

Compiler generates the following code:
Method(&myClass, 1, 2, 3);

Where the first parameter is actually the pointer to this.
Let's check the following code:
class MyClass
{
private:
    int a;

public:
    void __stdcall Method(int i)
    {
        a = i;
    }
};

int main(int argc, char *argv[])
{
    MyClass myClass;
    myClass.Method(5);

    return 0;
}

By using __stdcall I forced the compiler to pass all parameters through the stack. If you then start the debugger and inspect the assembly code, you'll find something like the following:
     myClass.Method(5);
00AA31BE  push        5
00AA31C0  lea         eax,[myClass]
00AA31C3  push        eax
00AA31C4  call        MyClass::Method (0AA1447h)

As you see, the parameter of the method is passed through the stack, then address of myClass is loaded to eax register and again pushed on the stack. In other words, this is treated as a regular parameter of this method.

A: this is an rvalue (you cannot take its address), so it doesn't
(necessarily) occupy memory at all.  Depending on the compiler
and the target architecture, it will often be in a register: i0
on a Sparc, ECX with MSVC on Intel, etc.  When the optimizer is
active, it can even move around. (I've seen it in different
registers with MSVC).

A: this behaves mostly like a function argument, and as such will be stored on the stack or - if the binary calling conventions of the architecture allow that - in a register.

A: this isn't stored at a well-defined location! The object that it points to is stored somewhere, and has a well-defined address, but the address itself does not have a specific home address. It is communicated around in the program. Not only that, but there can be many copies of that pointer.
In the following imaginary init function, the object registers itself to receive events and timer callbacks (using imaginary event source objects). So after the registration, there are two additional copies of this:
void foo_listener::init()
{
   g_usb_events.register(this); // register to receive USB events
   g_timer.register(this, 5);   // register for a 5 second timer
}

I a function activation chain, there will also be multiple copies of the this pointer. Suppose we have an object obj and call its foo function. That function calls the same object's bar function, and bar calls another function called update. Each function activation level has the this pointer. It's stored in a machine register, or in a memory location in the stack frame of the function activation.


text:
Q: How to return a string line by line in a function? I am reading a text file which contains integers separated by a new line. Like this.
5006179359870233335
13649319959095080120
17557656355642819359
15239379993672357891
3900144417965865322
12715826487550005702

From this file, I want to access each integer in a loop and compare it with another, in order to match those two. In function File_read() I can print the integers. But what I want is to get it integer by integer outside the function. For example in main method, if there is a integer called x, I want to check whether x equals one of the integers in my text file.
string File_read() {
    std::ifstream my_file("H:\\Sanduni_projects\\testing\\test.txt",
    std::ifstream::binary);
    if (my_file) {
        string line;

        for (int i = 0; i < 25; i++){
            getline(my_file, line);
            //cout << line << endl;
            return line;
        }

        if (my_file)
            std::cout << "all characters read successfully."<<endl;

        my_file.close();
    }
    return 0;
}

A: Never return unconditionally inside a loop.
You are returning unconditionally from inside the loop. This causes the caller to exit the loop and return from the function during the first iteration.
for (int i = 0; i < 25; i++){
    getline(my_file, line);
    return line; // <-- Return from function (rest of iterations unreachable). Bad.
}

No need to reinvent stuff
Use the standard library to read the numbers, e.g., into a container std::vector.
std::vector<unsigned long long> v{std::istream_iterator<unsigned long long>{my_file},
                                  std::istream_iterator<unsigned long long>{}};

Notice the value type of unsigned long long that is needed to fit the large numbers (you're pushing ~64 bits here).
Find a match
Use, e.g., std::find to find a possible match among the parsed numbers.
auto key = 15239379993672357891ull;

if (auto it = std::find(std::begin(v), std::end(v), key); it != std::end(v)) {
    std::cout << "Key found at line " << std::distance(std::begin(v), it) + 1 << std::endl;
}

Here, I'm using a C++1z if(init; condition) statement to limit the scope of the iterator it to inside the if statement. It's optional of course.
Live example

A: You are, currently, just returning the first number (as a std::string and not a number). If you remove the return statement in your loop you can, of course, print each of them. Here is a slightly modified version of your File_read function that will return a std::vector<unsigned long long> that contains all the numbers. Then  you can use this vector in, e.g., your main function to do your processing.
std::vector<unsigned long long> File_read()
{
    std::vector<unsigned long long> numbers;
    std::ifstream my_file("H:\\Sanduni_projects\\testing\\test.txt"); // Text files are not 'binany', i.e., removed std::ifstream::binary
    if (my_file)
    {
        std::string line;

        for (int i = 0; i < 25; i++)
        {
            std::getline(my_file, line);
            numbers.push_back(std::stoull(line));
        }

        if (my_file)
        {
            std::cout << "all characters read successfully." << std::endl;
        }

//        my_file.close(); // Do not do this manually
    }
    return numbers;
}

Usage example:
int main()
{
    unsigned long long x = /* some number */;

    // Read all the numbers
    std::vector<unsigned long long> vl = File_read();

    // Run through all the numbers
    for (unsigned long long y : vl)
    {
        // Check if any of the numbers are equal to x
        if (x == y)
        {
            // There is a match...
            // Do stuff
        }
    }
}

Update
The numbers cannot be held by in a long, however unsigned long long is sufficient.

A: std::vector<long> File_read(){
    vector<long> numbers;
    ifstream my_file("H:\\Sanduni_projects\\testing\\test.txt",
     std::ifstream::binary);
    if (my_file) {
        string line;

        for (int i = 0; i < frames_sec; i++){
            getline(my_file, line);
            numbers.push_back(std::stol(line));
        }

        if (my_file)
            std::cout << "all characters read successfully." << endl;
        else
            std::cout << "error: only " << my_file.gcount() << " could be read" << endl;
        my_file.close();

    }
    else{
        cout << "File can not be opened" << endl;
    }
    return numbers;
}

A: Although the someone gives the answers that works correctly, I want to share my code.
#include <memory>
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
#define MAX_SIZE 4096
class FileRead
{
public:
    FileRead(string path) :_file(path)
    {
        Reset();
    }
    void Reset()
    {
        memset(_buff, 0, MAX_SIZE);
    }
    string ReadLine()
    {
        if (!_file.is_open())
        {
            cout << "error open file" << endl;
            return "";
        }
        if (!_file.eof())
        {
            Reset();
            _file.getline(_buff,MAX_SIZE);
            return string(_buff);
        }
        else
        {
            cout << "read file finished." << endl;
            return "";
        }
    }

private:
    ifstream _file;
    string _line;
    char _buff[MAX_SIZE];
};

int _tmain(int argc, _TCHAR* argv[])
{
    FileRead fr("H:\\Sanduni_projects\\testing\\test.txt");
    string line;
    while (!(line = fr.ReadLine()).empty())
    {
        //do some compare..
    }
    return 0;
}

A: The other answers are correct about how return works, but there is something that acts how you thought return acted.
using string_coro = boost::coroutines::asymmetric_coroutine<std::string>

void File_read(string_coro::push_type & yield) {
    std::ifstream my_file("H:\\Sanduni_projects\\testing\\test.txt", std::ifstream::binary);
    if (my_file) {
        string line;

        for (int i = 0; i < 25; i++){
            getline(my_file, line);
            yield (line);
        }

        if (my_file)
            std::cout << "all characters read successfully." << std::endl;

        my_file.close();
    }
}

Which is used like this
string_coro::pull_type(File_read) strings;
for (const std::string & s : strings)
    std::cout << s << endl;


text:
Q: hash_file is computing same value for different files
Possible Duplicate:
What is a good way to check if an image is unique using PHP?

A user uploads an image (png, jpg, gif) via a form. I'm am using hash_file to check against the db to see if the image already has been uploaded but I am now noticing that it is not unique.
Is this a bug or should I be using something else to generate a unique ID for the files?
I guess the workaround would be md5(filesize($file) . $hash)?
UPDATE
From the logs... first set is using md5_file, second from hash_file with sha256...
HASH: SELECT SiteID FROM tbl_image_hashes WHERE SiteID = 0 AND Hash = 'd41d8cd98f00b204e9800998ecf8427e'
HASH: SELECT SiteID FROM tbl_image_hashes WHERE SiteID = 0 AND Hash = 'd41d8cd98f00b204e9800998ecf8427e'

HASH: SELECT SiteID FROM tbl_image_hashes WHERE SiteID = 0 AND Hash = 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'
HASH: SELECT SiteID FROM tbl_image_hashes WHERE SiteID = 0 AND Hash = 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'
HASH: SELECT SiteID FROM tbl_image_hashes WHERE SiteID = 0 AND Hash = 'e3b0c44298fc1c
20130117T231016: booru.pixymedia.us/utilities/batchExistingUpload.php
HASH: SELECT SiteID FROM tbl_image_hashes WHERE SiteID = 0 AND Hash = 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'
HASH: SELECT SiteID FROM tbl_image_hashes WHERE SiteID = 0 AND Hash = 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'
HASH: SELECT SiteID FROM tbl_image_hashes WHERE SiteID = 0 AND Hash = 'e3b0c44298fc1c

And no the SQL is right... I've uploaded 3,000 files successfully with this function...
This is the hash generating code:
$fileHash = hash_file("sha256",$FILE["tmp_name"]);

$FILE is basically $_FILE, it's just what the function parameter is named as

A: d41d...427e and e3b0...b855 are the MD5 and SHA256 sums of the empty string (e.g, md5("") and sha256("")). The fact that you've got these in your database indicates that there is something wrong with your code -- you may be hashing the wrong filename at some point.

A: The problem with working with the image data is that the same image can be represented in many ways. This is especially true of GIFs, where the colour table can be in any order and the result is the same.
You should probably work out a way to hash the image itself. You could do this by reading the colour of each pixel and generating some kind of hash from that. Alternatively, you could try using GD to load the image, and then let it "normalize" it by having it output the image with imagegd(), and then using that to check uniqueness.

A: If you are getting the same hash value for different files, then consider the possibilities:

*

*The hash is being generated incorrectly (=> check the input! <=); or,

*The hash used is not of sufficient quality (SHA-x is sufficient); or,

*The hash implementation is broken (doubtful, and not the case here); or,

*They files really do have the same content (determined to be false)

The odds of accidental SHA-x collisions are extremely small; here is a probability table, which doesn't do justice indicating exactly how unlikely this is. This article on 160-bit hashes has a more comparable scale at the bottom .. there is a higher chance of being hit by a meteor!
In any case, #1 is indeed the culprit.
Hint: hash("sha256", "")


text:
Q: On mobile; website background image is extremely blown up

#hero {
 background: #12151b url(../images/barbersupplies.jpg) no-repeat center center fixed;
 -webkit-background-size: cover !important;
 -moz-background-size: cover !important;
 background-size: cover !important;
 padding-top: 66px;
 padding-bottom: 90px;
 width: 100%;
 text-align: center;
 position: relative;
  }

I'm currently finishing up a friends website for haircuts (thebarbershock.com)
When I go to the website on mobile, the background images that look great on a desktop, end up being blown up and ugly on mobile.
I have tried playing around to fix this & do not know what could do it. When I change the image to background-size: contain; & background-size: auto 100% & it still shows zoomed in.
Any thoughts on what I can do to resolve it?


text:
Q: Multi Server Query generating Login failures My problem is that when using multi server queries using SSMS from SQL Server 2008 R2 against SQL Server 2008 R2, 2005 and 2000 I occasionally get error messages such as:
SQL Server 2008R2

Login failed for user 'DomainName\ADName'. Reason: Failed to open the
  explicitly specified database. [CLIENT: 21.12.0.0]
  Error: 18456, Severity: 14, State: 38.

SQL Server 2005

2013-10-10 15:55:34.28 logon     Login failed for user
  'DomainName\ADName'.
  Error: 18456, Severity: 14, State: 16.

SQL Server 2000

Login failed for user 'DomainName\ADName'. [CLIENT: 21.12.0.0]

Now my query works fine but given what my query does is search for errors in logs it is not ideal that it should also generate such errors.
My methodology may be flawed, what I have done is create a group under Local Server Groups and registered a few dozen servers of various versions. Then I right click on this group, select New Query to open a new batch window. Lastly I open my saved script and run it. In rough outline this is what it does
use master
go
determine version of SQL as like '%8.0%' or not
create temporary table based on version and pump results of xp_readerrorlog 0-6 into it
translate temporary table to another and insert to results temporary table
select on results table
drop temporary tables
go

I am a sysadmin on all machines. Two things I tried was the 'use master' statement at the top of the script and changing the registered servers to have a "Connect to database" of master. Neither of these has eliminated the problem. Does anyone have any further suggestions?


text:
Q: SPARK SQL CREATE VIEW I have noticed that there seems to be some max length of the create view statement.  Below is a SQL query I can run (select statement).  If I put a create view in front, it works as long as I limit the columns in the sub-query.  The view itself would only contain one column.  I have provided this for example.  I am running my sql through thrift server.  Is there any way to get around this issue?  Thanks in advance!
Working
select p from
(
select p
from
(select p,concat(
p1,',',p2,',',p3,',',p4,',',p5,',',p6,',',p7,',',p8,',',p9,',',p10,',',p11,',',p12,',',p13,',',p14,',',p15,',',p16,',',p17,',',p18,',',p19,',',p20,',',
p21,',',p22,',',p23,',',p24,',',p25,',',p26,',',p27,',',p28,',',p29,',',p30,',',p31,',',p32,',',p33,',',p34,',',p35,',',p36,',',p37,',',p38,',',p39,',',p40,',',
p41,',',p42,',',p43,',',p44,',',p45,',',p46,',',p47,',',p48,',',p49,',',p50,',',p51,',',p52,',',p53,',',p54,',',p55,',',p56,',',p57,',',p58,',',p59,',',p60,',',
p61,',',p62,',',p63,',',p64,',',p65,',',p66,',',p67,',',p68,',',p69,',',p70,',',p71,',',p72,',',p73,',',p74,',',p75,',',p76,',',p77,',',p78,',',p79,',',p80,',',
p81,',',p82,',',p83,',',p84,',',p85,',',p86,',',p87,',',p88,',',p89,',',p90,',',p91,',',p92,',',p93,',',p94,',',p95,',',p96,',',p97,',',p98,',',p99,',',p100,',',
p101,',',p102,',',p103,',',p104,',',p105,',',p106,',',p107,',',p108,',',p109,',',p110,',',p111,',',p112,',',p113,',',p114,',',p115,',',p116,',',p117,',',p118,',',p119,',',p120,',',
p121,',',p122,',',p123,',',p124,',',p125,',',p126,',',p127,',',p128,',',p129,',',p130,',',p131,',',p132,',',p133,',',p134,',',p135,',',p136,',',p137,',',p138,',',p139,',',p140,',',
p141,',',p142,',',p143,',',p144,',',p145,',',p146,',',p147,',',p148,',',p149,',',p150,',',p151,',',p152,',',p153,',',p154,',',p155,',',p156,',',p157,',',p158,',',p159,',',p160,',',
p161,',',p162,',',p163,',',p164,',',p165,',',p166,',',p167,',',p168,',',p169,',',p170,',',p171,',',p172,',',p173,',',p174,',',p175,',',p176,',',p177,',',p178,',',p179,',',p180,',',
p181,',',p182,',',p183,',',p184,',',p185,',',p186,',',p187,',',p188,',',p189,',',p190,',',p191,',',p192,',',p193,',',p194,',',p195,',',p196,',',p197,',',p198,',',p199,',',p200,',',
p201,',',p202,',',p203,',',p204,',',p205,',',p206,',',p207,',',p208,',',p209,',',p210,',',p211,',',p212,',',p213,',',p214,',',p215,',',p216,',',p217,',',p218,',',p219,',',p220,',',
p221,',',p222,',',p223,',',p224,',',p225,',',p226,',',p227,',',p228,',',p229,',',p230,',',p231,',',p232,',',p233,',',p234,',',p235,',',p236,',',p237,',',p238,',',p239,',',p240,',',
p241,',',p242,',',p243,',',p244,',',p245,',',p246,',',p247,',',p248,',',p249,',',p250,',',p251,',',p252,',',p253,',',p254,',',p255,',',p256,',',p257,',',p258,',',p259,',',p260,',',
p261,',',p262,',',p263,',',p264,',',p265,',',p266,',',p267,',',p268,',',p269,',',p270,',',p271,',',p272,',',p273,',',p274,',',p275,',',p276,',',p277,',',p278,',',p279) vector
from table1) a
) c

Not working
CREATE VIEW TEST AS
select p from
(
select p
from
(select p,concat(
p1,',',p2,',',p3,',',p4,',',p5,',',p6,',',p7,',',p8,',',p9,',',p10,',',p11,',',p12,',',p13,',',p14,',',p15,',',p16,',',p17,',',p18,',',p19,',',p20,',',
p21,',',p22,',',p23,',',p24,',',p25,',',p26,',',p27,',',p28,',',p29,',',p30,',',p31,',',p32,',',p33,',',p34,',',p35,',',p36,',',p37,',',p38,',',p39,',',p40,',',
p41,',',p42,',',p43,',',p44,',',p45,',',p46,',',p47,',',p48,',',p49,',',p50,',',p51,',',p52,',',p53,',',p54,',',p55,',',p56,',',p57,',',p58,',',p59,',',p60,',',
p61,',',p62,',',p63,',',p64,',',p65,',',p66,',',p67,',',p68,',',p69,',',p70,',',p71,',',p72,',',p73,',',p74,',',p75,',',p76,',',p77,',',p78,',',p79,',',p80,',',
p81,',',p82,',',p83,',',p84,',',p85,',',p86,',',p87,',',p88,',',p89,',',p90,',',p91,',',p92,',',p93,',',p94,',',p95,',',p96,',',p97,',',p98,',',p99,',',p100,',',
p101,',',p102,',',p103,',',p104,',',p105,',',p106,',',p107,',',p108,',',p109,',',p110,',',p111,',',p112,',',p113,',',p114,',',p115,',',p116,',',p117,',',p118,',',p119,',',p120,',',
p121,',',p122,',',p123,',',p124,',',p125,',',p126,',',p127,',',p128,',',p129,',',p130,',',p131,',',p132,',',p133,',',p134,',',p135,',',p136,',',p137,',',p138,',',p139,',',p140,',',
p141,',',p142,',',p143,',',p144,',',p145,',',p146,',',p147,',',p148,',',p149,',',p150,',',p151,',',p152,',',p153,',',p154,',',p155,',',p156,',',p157,',',p158,',',p159,',',p160,',',
p161,',',p162,',',p163,',',p164,',',p165,',',p166,',',p167,',',p168,',',p169,',',p170,',',p171,',',p172,',',p173,',',p174,',',p175,',',p176,',',p177,',',p178,',',p179,',',p180,',',
p181,',',p182,',',p183,',',p184,',',p185,',',p186,',',p187,',',p188,',',p189,',',p190,',',p191,',',p192,',',p193,',',p194,',',p195,',',p196,',',p197,',',p198,',',p199,',',p200,',',
p201,',',p202,',',p203,',',p204,',',p205,',',p206,',',p207,',',p208,',',p209,',',p210,',',p211,',',p212,',',p213,',',p214,',',p215,',',p216,',',p217,',',p218,',',p219,',',p220,',',
p221,',',p222,',',p223,',',p224,',',p225,',',p226,',',p227,',',p228,',',p229,',',p230,',',p231,',',p232,',',p233,',',p234,',',p235,',',p236,',',p237,',',p238,',',p239,',',p240,',',
p241,',',p242,',',p243,',',p244,',',p245,',',p246,',',p247,',',p248,',',p249,',',p250,',',p251,',',p252,',',p253,',',p254,',',p255,',',p256,',',p257,',',p258,',',p259,',',p260,',',
p261,',',p262,',',p263,',',p264,',',p265,',',p266,',',p267,',',p268,',',p269,',',p270,',',p271,',',p272,',',p273,',',p274,',',p275,',',p276,',',p277,',',p278,',',p279) vector
from table1) a
) c

WORKING
CREATE VIEW TEST AS
select p from
(
select p
from
(select p,concat(
p1,',',p2,',',p3,',',p4,',',p5,',',p6,',',p7,',',p8,',',p9,',',p10,',',p11,',',p12,',',p13,',',p14,',',p15,',',p16,',',p17,',',p18,',',p19,',',p20,',',
p21,',',p22,',',p23,',',p24,',',p25,',',p26,',',p27,',',p28,',',p29,',',p30,',',p31,',',p32,',',p33,',',p34,',',p35,',',p36,',',p37,',',p38,',',p39,',',p40,',',
p41,',',p42,',',p43,',',p44,',',p45,',',p46,',',p47,',',p48,',',p49,',',p50,',',p51,',',p52,',',p53,',',p54,',',p55,',',p56,',',p57,',',p58,',',p59,',',p60,',',
p61,',',p62,',',p63,',',p64,',',p65,',',p66,',',p67,',',p68,',',p69,',',p70,',',p71,',',p72,',',p73,',',p74,',',p75,',',p76,',',p77,',',p78,',',p79,',',p80,',',
p81,',',p82,',',p83,',',p84,',',p85,',',p86,',',p87,',',p88,',',p89,',',p90,',',p91,',',p92,',',p93,',',p94,',',p95,',',p96,',',p97,',',p98,',',p99,',',p100,',') vector
from table1) a
) c

A: Use JDBC driver included with Spark.  I can compile view now.  I am using SQL
Use SQL Squirrel instead with JDBC driver to connect and run queries. I was using the Microsoft SPARK ODBC driver. the JDBC one works fine.


text:
Q: MVC erro 404 método POST Esse é meu controller:
[HttpPost]
public ActionResult TestePost(int id1)
{
    ViewData["Teste"] = "O método POST funcionou, você digitou: " + id;

    return View("Index");
}

   [HttpGet]
    public ActionResult TesteGet(int id)
    {
        ViewData["Teste"] = "O método GET funcionou, você digitou: " + id;

        return View("Index");
    }

Abaixo minha view:
@using (Html.BeginForm("TesteGet", "Home", FormMethod.Get))
{
    <fieldset>
        <legend>Form tipo GET</legend>

        <input type="text" name="id" id="idGet" value="" />
        <input type="submit" name="enviar" value="enviar Get" placeholder="apenas numeros" />

    </fieldset>

}

@using (Html.BeginForm("TestePost", "Home", FormMethod.Post))
{
    <fieldset>
        <legend>Form tipo POST</legend>

        <input type="text" name="id1" id="idPost" value="" />
        <input type="submit" name="enviar" value="enviar Post" placeholder="apenas numeros"/>

    </fieldset>

}

@ViewData["Teste"]

Meu problema: Método GET funciona perfeitamente, método post não funciona.
Ressalto: Quando é localhost funciona perfeitamente POST e GET quando coloco na Locaweb dá esse erro.

A: Seu segundo form está com IDs diferentes do esperado pela Controller.
@using (Html.BeginForm("TestePost", "Home", FormMethod.Post))
{
    <fieldset>
        <legend>Form tipo POST</legend>

        <input type="text" name="id1" id="id1" value="" />
        <input type="submit" name="enviar" value="enviar Post" placeholder="apenas numeros"/>
    </fieldset>
}


text:
Q: application shutdown in emulator after running Everytime i try to run the app the app stops after de loadingActivity.
When it try to run the MainActivity it stops.
My logcat looks like this.
03-18 20:41:11.242 11729-11729/com.example.valueapp D/AndroidRuntime: Shutting down VM
03-18 20:41:11.243 11729-11729/com.example.valueapp E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.valueapp, PID: 11729
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.valueapp/com.example.valueapp.MainActivity}: java.lang.ClassCastException: androidx.appcompat.widget.AppCompatSpinner cannot be cast to android.widget.EditText
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
        at android.app.ActivityThread.access$800(ActivityThread.java:151)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5254)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
     Caused by: java.lang.ClassCastException: androidx.appcompat.widget.AppCompatSpinner cannot be cast to android.widget.EditText
        at com.example.valueapp.MainActivity.onCreate(MainActivity.java:27)
        at android.app.Activity.performCreate(Activity.java:5990)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
        at android.app.ActivityThread.access$800(ActivityThread.java:151)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5254)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

A: Try Project -> Clean
If this doesn't work you might actually cast something to an EditText somewhere.


text:
Q: how to permanantly install arduino ide 1.6.5? I downloaded the zip file arduino-nightly-linux32.tar.xz from here to my desktop.(YOU MAY NEED 64-bit. Ask your computer what it is: 32-bit or 64-bit):
I double clicked the arduino-nightly-linux.tar.xz icon and it opened a window that showed the .tar.xz file. I clicked the the extract button at the top of the window and extracted the contents of the arduino-nightly-linux.tar.xz archive to my desktop.
Once it was extracted, I could see and open the folder on my desktop (with all my other stuff), but could not run Arduino from there. I opened a terminal (Crtl+Alt+T)...
Note: capitalization matters in the terminal and depends on what YOUR machine calls the files/locations you are using...
I typed: cd Desktop and it gave me this prompt: jay@jay:~/Desktop$
I Typed on the line after the $ ls -- I click Enter and it LISTED every file and folder on my desktop.
I could see Arduino-nightly in the list (it was blue for some reason). If you DON'T see it in the list, you are in the WRONG directory and you need to "cd" to the directory it IS IN.
then I typed on the line after Desktop$ cd Arduino-nightly and it gave me this:
jay@jay:~/Desktop/arduino-nightly$
after the $ on that line, I typed ./arduino
but after doing steps mentioned above I programmed my arduino once after that I closed the application and now I cannot find it. each time when I want to open the arduino application I have to give command in terminal. how to permanantly install it?

A: Why not just install from the repositories?
sudo apt-get install arduino

Otherwise download the package, then in the directory of the download:
tar -xf arduino-1.6.5-r5-linux64.tar.xz
cd arduino-1.6.5-r5/
./arduino

To install it permamently (sort of) copy the contents of "arduino-1.6.5-r5" directory to somewhere (maybe $HOME/arduino") and  then copy the arduino.desktop file into $HOME/.local/share/application, edit it to contain the right pathes and you have it installed for your user "permanently".
#/usr/bin/env bash
# set variables for download
URL=https://www.arduino.cc/download.php?f=/arduino-nightly-linux64.tar.xz
DOWNLOAD="$HOME/Downloads/arduino-nightly.tar.xz"

# download file via wget from $URL to $DOWNLOAD
wget "$URL" -O "$DOWNLOAD"

# extract file to $HOME directory
tar xf "$DOWNLOAD" -C "$HOME"
# use sed to modify the provided arduino.desktop
# file and redirect the result into $HOME/.local.share/applications
# to be able to start from dash
# sed's replace command s/searchpattern/replacepattern/
# the slashes are replaced by '#' to not need to escape slashes in path
# replace placeholder "FULL_PATH" with install directory
sed "s#FULL_PATH#$HOME/arduino-nightly#" "$HOME/arduino-nightly/arduino.desktop" >"$HOME/.local/share/applications/arduino.desktop"

The script downloads the latest nightly build (website states hourly), extracts it to $HOME/arduino-nightly (that folder is in the tar, so I just used that) and copies the desktop file while modifying it. After logoff and logon you should be able to start it via the dash normally.


text:
Q: Determine if a subspace of $M_{22}$ I'm having a hard time trying to understand what it's asking. Seeing the transpose part is throwing me off.
Determine which of the following are subspace of $M_{22}$

The set of $2\times 2$ matrices such that $A = A^T$

A: $A=A^T$ are the symmetric matrices. Adding two symmetric matrices gives you another symmetric matrix, multiplying the symmetric matrix by a scalar gives you the symmetric matrix. Zero matrix is also the symmetric matrix. So the same sized symmetric matrices form a vector subspace.

A: First notice that a matrix satisfying $A=A^T$ is simply a symmetric matrix. Consider the set of the matrices with this property and follow the usual steps to check whether a set is a (linear) subspace:

*

*is the set non-empty / does it contain the zero vector (zero matrix)?

*does the sum of two matrices satisfying $A=A^T$ have this property as well?

*if a matrix $A$ satisfies $A=A^T$, does the scalar multiple $kA$ satisfy it as well?

If all the answers are yes, you have a subspace of $M_{22}$.

A: You need to show that $aA+bB$ belongs to the same set where $a,b\in \mathbb R$.


text:
Q: error: unknown type name 'intptr_t' I am receiving this error while compiling a C program in MinGW. As far as I know, I thought 'intptr_t' was a type in the C99 standard. Am I not including a file?

A: You need to include stdint.h.
Note that intptr_t and uintptr_t are indeed C99 types but they are optional.


text:
Q: NSMutableAttributedString adding multiple attributes hiding the text let text = "By accepting  you agree to our Terms of Service and Privacy Policy."
let attr = NSMutableAttributedString(string: text)

attr.setAttributes([.underlineStyle: 1, .foregroundColor: #colorLiteral(red: 0.7294117647, green: 0.6235294118, blue: 0.2823529412, alpha: 1).cgColor ],
                   range: (text as NSString).range(of: "Terms of Service"))

attr.setAttributes([.underlineStyle: 1, .foregroundColor: #colorLiteral(red: 0.7294117647, green: 0.6235294118, blue: 0.2823529412, alpha: 1).cgColor ],
                   range: (text as NSString).range(of: "Privacy Policy."))

This is the showing in terminal
-[__NSCFType set]: unrecognized selector sent to instance 0x6000039b2ca0

When adding single attribute it is working fine
Running Code on iOS Simulator 13.2.2, Xcode 11.2.1, Swift 5

A: Here is it you need to convert the cgColor to UIColor to use foregroundColor attribute
attr.setAttributes([.underlineStyle: 1, .foregroundColor: UIColor(red: 1, green: 0.556, blue: 0.232, alpha: 1)],
                      range: (text as NSString).range(of: "Terms of Service"))

 attr.setAttributes([.underlineStyle: 1, .foregroundColor: UIColor(red: 1, green: 0.556, blue: 0.232, alpha: 1) ],
                          range: (text as NSString).range(of: "Privacy Policy."))


text:
Q: SQL query with multiple same conditions I work with Sybase DB and trying to select data using few conditions:
The table name "alias".
a_id, a_data, a_type_id, a_value
------------------------------
    1,   666,       123, "value_1"
    2,   666,       456, "value_2"
    3,   777,       123, "value_4"
    4,   777,       456, "value_5"

I have few conditions:
1. a_type_id = 123 and a_value = "value_1" AND
2. a_type_id = 456 and a_value = "value_2"

So the result should be a_data = 666, in case the both conditions are achived.
The query should be like this, but it, of course, does not work, returns 0 results:
select a_data from alias where ( a_type_id = 123 AND a_value = "value_1" ) AND (a_type_id = 456 AND a_value = "value_2")

Expecting result a_data = 666.
Can someone advise something workaround? It is possible to have 2, 3 or more conditions like above.

A: Use aggregation and having:
select a_data
from t
where (a_type_id = 123 and a_value = 'value_1') or
      (a_type_id = 456 and a_value = 'value_2')
group by a_data
having count(*) = 2;

Note:  This assumes that type/value pairs are not duplicated in the original data for a given a_data value.  If they can be, then use:
having count(distinct a_type_id) = 2


text:
Q: How to disable tqdm's progressbar and keep only the text info in Pytorch Lightning (or in tqdm in general) I am working on Pytorchlightning and tqdm's progressbar is very buggy, it keep resizing back and forth from short to long, making reading the logging text so unpleasant, I realized that the progressbar is not really necessary and would like to keep only the info about the current epoch, current batch, accuracy, loss, etc.
From my searching it seems like you can disable whole tqdm display(progressbar and text), but how can I selectively disable only progressbar but not the text?

A: The tqdm way to disable the "meter" (while retaining display of stats) is to set ncols=0 and dynamic_ncols=False (see tqdm documentation).
The way to customize the default progress bar behavior in pytorch_lightning is to pass a custom ProgressBar in as a callback when building the Trainer.
Putting the two together, if you wanted to modify the progress bar during training you could do something like the following:
import pytorch_lightning as pl
from pytorch_lightning.callbacks import ProgressBar

class MeterlessProgressBar(ProgressBar):

    def init_train_tqdm(self):
        bar = super().init_train_tqdm()
        bar.dynamic_ncols = False
        bar.ncols = 0
        return bar

bar = MeterlessProgressBar()
trainer = pl.Trainer(callbacks=[bar])

You can separately customize for the sanity check, prediction, validation, and test by overriding: init_sanity_tqdm, init_predict_tqdm, init_validation_tqdm, and init_test_tqdm respectively. (If you want a quick and dirty way to do something to all progress bars, you could consider overriding the _update_bar method instead.)


text:
Q: PHP openssl_encrypt Reponse doesn't match CryptoJS AES Encryption PHP Encryption Logic
$secret_key = '###$$**@@@//!!!^^%%%';
$secret_iv = '$$##!!&&**!!**@@';

$encrypt_method = "AES-256-CBC";
$key = hash('sha256', $secret_key); // d7cc77e5a8db446cc11aaa510b5191852a0084ad09f7b33623137c78e09c8050
$iv = substr(hash('sha256', $secret_iv), 0, 16); // 36a50210c8b2f19e

$output = openssl_encrypt('testingDemo', $encrypt_method, $key, 0, $iv);
// response --> uRfctdzWekUYISdKHKW88Q==

JS Encryption Logic
const SECRET_KEY = '###$$**@@@//!!!^^%%%';
const SECRET_IV = '$$##!!&&**!!**@@';
const key = SHA256(SECRET_KEY); // d7cc77e5a8db446cc11aaa510b5191852a0084ad09f7b33623137c78e09c8050
const iv = SHA256(SECRET_IV).toString().substr(0, 16); // 36a50210c8b2f19e
console.log(iv, 'iv....');
const encrypted = AES.encrypt('testingDemo', key, { iv: enc.Hex.parse(iv) });
console.log(encrypted.toString(enc.Base64) // response --> vXyYVoSYagBbN0ihXVTgaA==

I don't know what I'm doing wrong. Please somebody help.
=============================
Update. The Working Code
JS Encryption Logic
export const tokenGenerator = (subdomain) => {
  const plainText = `${atob(process.env.REACT_APP_PREFIX)}${subdomain}${atob(process.env.REACT_APP_SUFFIX)}`;
  const key = SHA256(atob(process.env.REACT_APP_SECRET_KEY)).toString().substr(0, 32);
  const iv = SHA256(atob(process.env.REACT_APP_SECRET_IV)).toString().substr(0, 16);
  const encrypted = AES.encrypt(plainText, enc.Utf8.parse(key), { iv: enc.Utf8.parse(iv) });
  return btoa(enc.Base64.stringify(encrypted.ciphertext));
};

PHP Encryption Logic
$secret_key = '###$$**@@@//!!!^^%%%';
$secret_iv = '$$##!!&&**!!**@@';
$encrypt_method = "AES-256-CBC";
$key = hash('sha256', $secret_key);
$iv = substr(hash('sha256', $secret_iv), 0, 16);
$output = openssl_encrypt('testingDemo', $encrypt_method, $key, 0, $iv);


text:
Q: How to use Currency.js library in Adonis.js? I need to use some library to manage currencies (add, sum, floating point, etc.) in Adonis.js v4.
I found different libraries that should work (Diner.js, currency.js, money.js), but I am unable to use those libraries with Adonis.
For example with currency.js, I install it with npm
npm install --save currency.js

and then inside the controller I tried to use it with:
const currency = require('currency.js') //nada, but if I click on it it redirects me to the node modules folder
const currency = use('currency.js') //nada
const currency = require('currency.js/dist') //nada
const currency = require('currency.js/dist/currency.js') //nada

It always shows this error:
Cannot find module 'currency.js' Require stack: - /srv/app/app/Controllers/Http/Common/AccountTransactionController.js - /srv/app/node_modules/require-stack/src/index.js - /srv/app/node_modules/require-stack/index.js - /srv/app/node_modules/@adonisjs/fold/src/Ioc/index.js - /srv/app/node_modules/@adonisjs/fold/index.js - /srv/app/server.js
I tried with the other two libraries and it's the same.
Can you please help me import and use this/those library/libraries?


text:
Q: WinSCP synchronizing files (Remote to Local Directory) from Azure VM I am trying to follow this YouTube video instruction regards to "SFTP - Windows Script to Automate Synchronize Remote to Local Directory using WinSCP".
When I ran a batch file, I got this message:

I am not sure why it says "Cannot open file "C:\Windows\system32\SyncToLocalScript.txt".
I ran this batch file (SyncToLocalScript.bat) inside this folder (C:\Program Files (x86)\WinSCP.
"C:\Program Files (x86)\WinSCP\winscp.com" /script=SyncToLocalScript.txt
pause

I placed this text file (SyncToLocalScript.txt) inside C:\Windows\System32.
Here are details of code.
option batch abort
option confirm off
open sftp://ihcmirrdbuser:PasswordHere@ftpus.pointclickcare.com -
hostkey="ssh-rsa 1024 36:d1:fd:0e:c5:54:de:d7:3c:76:27:25:a3:4d:9f:64"
synchronize local F:\FTP /SQL2016/Logs
exit

After that, nothing is happening (files are not synchronizing but getting message as indicated earlier).
I got the HostKeyInformation from WinSCP application, and I copied the second line of Server host key fingerprints - where it starts after MD5 (please see below).

------------------------------------------------------------
Server host key fingerprints
SHA-256 = ssh-rsa 1024 yFTXpIc0fKp3JhQK5gIiauZ6GwPKE9pmJvcGSRo5nKs=
MD5 = ssh-rsa 1024 36:d1:fd:0e:c5:54:de:d7:3c:76:27:25:a3:4d:9f:64
------------------------------------------------------------

I am using Azure VM.
I am not sure whether it is anything to do with firewall or security issue with the VM.


text:
Q: How to create multiple arrays from one array? I have an array "values1" that has 104 items total, i need to create 1 array of 13 sub arrays and each sub array should have 8 values.
e.g if "values1" has item:
1,2,3,4,5 ..., 13,
14,15,15,... , 26,
27,28,29,...

and i need sub Arrays like this:
first subarray: 1,14,27, ....
second subarray: 2,15,18,...

and this is how i need to create 13 subArrays in one single array.
NSString *strFileContent = [NSString stringWithContentsOfFile:[[NSBundle mainBundle]
                                                               pathForResource: @"values" ofType: @"txt"] encoding:NSUTF8StringEncoding error:nil];
NSArray *values1 = [strFileContent componentsSeparatedByString:@"@@"];

A: NSString *strFileContent = [NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource: @"values" ofType: @"txt"] encoding:NSUTF8StringEncoding error:nil];
NSArray *values1 = [strFileContent componentsSeparatedByString:@"@@"];
NSMutableArray *graph1Values = [[NSMutableArray alloc]init];

for (int a=0; a<13; a++) {
NSMutableArray *newarray1 = [[NSMutableArray alloc] init];
for(int i=a; i<values1.count; i=i+13){
    [newarray1 addObject:[values1 objectAtIndex:i]];
}
    [graph1Values addObject:newarray1];
}

NSLog(@"%@",graph1Values);

A: Here's a tiny category for this:
NSArray+Split.h
#import <Foundation/Foundation.h>

@interface NSArray (Split)

-(NSArray *) splitIntoSubarrays:(NSInteger) count;

@end

NSArray+Split.m
#import "NSArray+Split.h"

@implementation NSArray (Split)

-(NSArray *) splitIntoSubarrays:(NSInteger) count
{
    NSMutableArray *arrayOfArrays = [[NSMutableArray alloc] init];

    for (NSInteger i = 0; i < self.count; i++)
    {
        if (i < count)
        {
            arrayOfArrays[i] = [[NSMutableArray alloc] init];
        }
        [arrayOfArrays[i % count] addObject:self[i]];
    }
    return arrayOfArrays;
}

@end

usage:
#import "NSArray+Split.h"

(...)

    NSArray *arrayOfArrays = [initialArray splitIntoSubarrays:13];


text:
Q: Having trouble plotting my data I'm pretty desperated. I ran into a problem when trying to plot my data.
The first circle plot works perfect, but I'm having problems with the second one plt.plot(x, y). When trying to plot it with the code below, I don't get any error messages, but the computation never goes into the elif loop - which it should considering the sill value is below 20000 and the x values go up to 95000. It keeps calculating the y-values with the if loop. I tried everything I could to fix it, but either I create new error messages, or I keep having the same problem.
Anyone got an idea how to fix the code or where the problem is located? Would really appreciate an answer.
import matplotlib.pyplot as plt
import numpy as np
b = 1.748
sill = 19506.208
x = np.linspace(0,95000,1000)
if (x < b).any():
    y = np.multiply(sill,( np.multiply(1.5,(x/b)) -
    (np.multiply(0.5,((x/b)**3.0)))))
elif (x > b).any():
    y = sill
plt.plot(Abstandsmatrix_Tage, Varianzmatrix_Tage, 'ro')
plt.plot(x,y)
plt.show()

A: you need to iterate over x when assigning your y values. or do it in a list comprehension:
import matplotlib.pyplot as plt
import numpy as np
b = 1.748
sill = 19506.208
x = np.linspace(0,95000,1000)

y = [np.multiply(sill,( np.multiply(1.5,(i/b)) - (np.multiply(0.5,((i/b)**3.0))))) if i < b else sill for i in x]

plt.plot(x,y)
plt.show()

However, with your example, only the first value of x is less than b, and that is 0, so you end up with:
y = [0.0, 19506.208, 19506.208, 19506.208, ... ]

So, maybe you mean if x < sill, instead of if x < b? If so:
y = [np.multiply(sill,( np.multiply(1.5,(i/b)) - (np.multiply(0.5,((i/b)**3.0))))) if i < sill else sill for i in x]


text:
Q: Re-install Mac mini Server My friend gave me Mac mini Server saying its Mavericks. When I switch it on I see 2 hard drives only and no operating system. I tried to use my Apple ID but it doesn't work. In disk utility I saw 1st hard drive has partition named "os" which I am not able to delete. How do I completely format both the hard drives and re-install Mavericks on that. I have a very slow internet and I don't have another mac, of course I have Linux and Windows dual boot machine.

A: In disk utility via safe mode, you should be able to format it completely by wiping the disk.
Then after wiping the disk, boot into a DVD or USB of OS X and reformat from there.

A: While we (and possibly you yourself as well) do not know what type of Mac Mini Server hardware you have, you can check this at the following Apple websites by using the serial number of your computer found at the underside:

*

*Check Your Service and Support Coverage

*Tech Specs (click on "Browse by product")

Respecting that you stated that you have a slow Internet connection, keep in mind that Mac OS X 10.7 Lion and later (Mavericks included) needs to be downloaded from the Internet, which is about 5 GB for each OS (plus 2 GB for the server extension in case of OS X 10.7 Lion).  The Mac Mini Server being a small computer, you can try to bring it to a friend to download it there, if they have a faster connection.

Nevertheless, here are some options for you:

For a Mac Mini Server (Mid 2010) or before, try one of the following options:

*

*Use the installation media which came with the Mac (e.g. Mac OS X Server 10.6) to install the OS again (if you do not have an optical drive with it, you will need to have a different Mac sharing its optical drive or try to clone the disc to a USB thumb drive)

*If a later version of Mac OS X is installed, you could use the built-in Recovery HD to install that version of Mac OS X the Recovery HD was created for (you will need to have obtained that version with your Apple ID or it will not work to authenticate the install).

For a Mac Mini Server (Mid 2011) or later, try the following option:
At startup, hold down Cmd+Alt+R to bypass any built-in recovery system and boot from the Internet Recovery (about 350-480 MB download).
This will give you the option to install the original OS which came with that Mac Mini Server.  Since that version is hardware-bound, no Apple ID is required to install it.

Once installed, you need to do the following to use Mavericks (or later):

*

*update the system to the latest version, then

*

*if you own Mavericks already, download it from the list of purchases from the App Store

*if you do not own it, you can download the latest version of OS X, which is Yosemite


text:
Q: android frame by frame animation on fragment I have an animation that works fine if I base my view on an Activity,
but if i want to base it on a fragment, i dont know what to do?,
here the code [working as activity]:
public class FramesAnimationActivity extends Activity {

    AnimationDrawable animation;

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

        animation = new AnimationDrawable();
        animation.addFrame(getResources().getDrawable(R.drawable.c_0), 100);
        animation.addFrame(getResources().getDrawable(R.drawable.c1), 100);
        animation.addFrame(getResources().getDrawable(R.drawable.c2), 100);
        animation.addFrame(getResources().getDrawable(R.drawable.c3), 100);
        animation.addFrame(getResources().getDrawable(R.drawable.c4), 100);
        animation.addFrame(getResources().getDrawable(R.drawable.c5), 100);
        animation.addFrame(getResources().getDrawable(R.drawable.c6), 100);
        animation.addFrame(getResources().getDrawable(R.drawable.c7), 100);

        animation.setOneShot(false);

        ImageView imageAnim =  (ImageView) findViewById(R.id.img);
        imageAnim.setBackgroundDrawable(animation);

        // run the start() method later on the UI thread
        imageAnim.post(new Starter());

    }

    class Starter implements Runnable {

        public void run() {
            animation.start();
        }

    }

}

But as Fragment, How to make it work?
public class HomeTab extends Fragment {
    /* (non-Javadoc)
     * @see android.support.v4.app.Fragment#onCreateView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle)
     */

    AnimationDrawable animation;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        if (container == null) {
            // We have different layouts, and in one of them this
            // fragment's containing frame doesn't exist.  The fragment
            // may still be created from its saved state, but there is
            // no reason to try to create its view hierarchy because it
            // won't be displayed.  Note this is not needed -- we could
            // just run the code below, where we would create and return
            // the view hierarchy; it would just never be used.
            return null;
        }

        animation = new AnimationDrawable();
        animation.addFrame(getResources().getDrawable(R.drawable.c_0), 100);
        animation.addFrame(getResources().getDrawable(R.drawable.c1), 100);
        animation.addFrame(getResources().getDrawable(R.drawable.c2), 100);
        animation.addFrame(getResources().getDrawable(R.drawable.c3), 100);
        animation.addFrame(getResources().getDrawable(R.drawable.c4), 100);
        animation.addFrame(getResources().getDrawable(R.drawable.c5), 100);
        animation.addFrame(getResources().getDrawable(R.drawable.c6), 100);
        animation.addFrame(getResources().getDrawable(R.drawable.c7), 100);

animation.setOneShot(false);

        ImageView imageAnim =  (ImageView) findViewById(R.id.img);
        imageAnim.setBackgroundDrawable(animation);

        // run the start() method later on the UI thread
        imageAnim.post(new Starter());

        return (LinearLayout)inflater.inflate(R.layout.tab_home_layout, container, false);
    }

    class Starter implements Runnable {

        public void run() {
            animation.start();
        }

    }

}

so I get an error in         ImageView imageAnim =  (ImageView) findViewById(R.id.img);
with the method findViewById(id) is undefined...
so how to adapt this to make it work on my fragment?
thanks!

A: First inflate your LinearLayout, then call the findViewById() method of the created view:
    LinearLayout ll = (LinearLayout)inflater.inflate(R.layout.tab_home_layout, container, false);
    ImageView imageAnim =  (ImageView) ll.findViewById(R.id.img);
    imageAnim.setBackgroundDrawable(animation);

    // run the start() method later on the UI thread
    imageAnim.post(new Starter());

    return ll;

A: For an animation drawable to work in a fragment call the methods of the animation inside onViewCreated method instead of the onCreateView method, like this.
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
      ImageView animationImageView = (ImageView) view.findViewById(R.id.imageViewSearchAnimation);
      animationImageView.setBackgroundResource(R.drawable.search_animation);
      animation = (AnimationDrawable) animationImageView.getBackground();
      animation.start();
      super.onViewCreated(view, savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {
      View view = inflater.inflate(R.layout.dialog_progress_search,
      container, false);
      return view;
}

@Override
public void onPause() {
      animation.stop();
      super.onPause();
}

@Override
public void onResume() {
      super.onResume();
      animation.start();
}


text:
Q: Transforming a right-skewed continuous response variable to an ordinal one: is this dumb? I am estimating task time-to-completion using a sample size of ~36k. ~34k points are complete, ~2k are not. The response variable for my sample is right-skewed. I want to use this data to predict how long it might take a task to be completed. However, my end-user does not care about the exact number of days, they want something classified as "easy", "medium", or "hard", where difficulty is related to time-to-completion in some way. I am considering splitting up my completed data into those categories based on quantiles (exactly by thirds using time-to-completion), binning all the incompletes into the "hard" category (because at this point they've been outstanding for so long that if they were to be completed they would all be hard), and turning this into an ordinal regression problem. Is this dumb? If it is dumb, is there a way to handle incompletes outside of survival analysis? I'm wary of using it because I read it's not great for prediction.

A: Survival analysis isn't likely to be any worse for prediction than your proposed ordinal-outcome regression.
In the clinical survival context, the frequently used semi-parametric Cox model can get that reputation because it uses an empirical baseline hazard/survival curve, which might not generalize well to other situations (particularly with many clinical survival data sets containing only a few hundred cases from one or a few institutions). With a data set of your size, you might be able to get a good and generalizable fully parametric model, if you make an appropriate choice of baseline hazard function (Weibull, log-normal, etc.). At the worst, a Cox model should readily distinguish groups of relative task difficulties based on their relative "hazards" of task completion.
For your application, survival analysis has the advantage that you don't have to pre-define times to completion that represent "easy," "medium," or "hard"; the analysis itself should demonstrate that distinction.Your pre-chosen quantiles might not be the most useful breakdown of task difficulty.
As kjetil b halvorsen notes, you could consider setting this up as an ordinal-outcome regression problem, but he also recommends grouping by difficulty after, not before, the analysis. I don't see any particular advantage of that approach over survival analysis.


text:
Q: how to check qr code values with all values from database im trying to check if the scanned qr code is equal with one of my sql posts.
if there is a match with one of my sql posts, this post should not be available for the next 4 days. I tried the following check this qr values:
public class Konto  extends AppCompatActivity implements ZXingScannerView.ResultHandler {
private TextView txtName;
private ImageButton btnLogout;
private String TAG = Locations.class.getSimpleName();

private ProgressDialog pDialog;
String qr_result;

// URL to get contacts JSON
private static String url = "yxxx";

ArrayList<HashMap<String, String>> contactList;

private SQLiteHandler db;
private SessionManager session;

private ZXingScannerView mScannerView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_konto
    );
    new GetContacts().execute();
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
        if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
            AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);
            alertBuilder.setCancelable(false);
            alertBuilder.setTitle("Permission necessary");
            alertBuilder.setMessage("Fine Location is necessary");
            alertBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {

                @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
                public void onClick(DialogInterface dialog, int which) {
                    ActivityCompat.requestPermissions(Konto.this, new String[]{Manifest.permission.CAMERA}, 1234);
                }
            });

            AlertDialog alert = alertBuilder.create();
            alert.show();
        } else {
            ActivityCompat.requestPermissions(Konto.this, new String[]{Manifest.permission.CAMERA}, 1234);
        }

    }
    ImageButton test = (ImageButton) findViewById(R.id.testforsql);
    test.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mScannerView = new ZXingScannerView(Konto.this);
            setContentView(mScannerView);
            mScannerView.setResultHandler(Konto.this);
            mScannerView.startCamera();

        }
    });

    txtName = (TextView) findViewById(R.id.kontoname);

    btnLogout = (ImageButton) findViewById(R.id.logoutbtn);

    // SqLite database handler
    db = new SQLiteHandler(getApplicationContext());

    // session manager
    session = new SessionManager(getApplicationContext());

    if (!session.isLoggedIn()) {
        logoutUser();
    }

    // Fetching user details from sqlite
    HashMap<String, String> user = db.getUserDetails();

    String name = user.get("name");
    String email = user.get("email");

    // Displaying the user details on the screen
    txtName.setText(name);

    // Logout button click event
    btnLogout.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            logoutUser();
        }
    });
    contactList = new ArrayList<>();

}

@Override
public void handleResult(Result result) {
    Log.w("handleResult", result.getText());
    AlertDialog.Builder builder = new AlertDialog.Builder(Konto.this);
    builder.setTitle("Scan Result");
    builder.setMessage(result.getText());
    AlertDialog alertDialog = builder.create();
    alertDialog.show();
    qr_result = result.getText();
    mScannerView.resumeCameraPreview(Konto.this);

}

/**
 * Logging out the user. Will set isLoggedIn flag to false in shared
 * preferences Clears the user data from sqlite users table
 */
private void logoutUser() {
    session.setLogin(false);

    db.deleteUsers();

    // Launching the login activity
    Intent intent = new Intent(Konto.this, LoginActivity.class);
    startActivity(intent);
    finish();
}

private class GetContacts extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Showing progress dialog
        pDialog = new ProgressDialog(Konto.this);
        pDialog.setMessage("Please wait...");
        pDialog.setCancelable(false);
        pDialog.show();

    }

    @Override
    protected Void doInBackground(Void... arg0) {
        HttpHandler sh = new HttpHandler();

        // Making a request to url and getting response
        String jsonStr = sh.makeServiceCall(url);

        Log.e(TAG, "Response from url: " + jsonStr);

        if (jsonStr != null) {
            try {
                JSONArray contacts = new JSONArray(jsonStr);

                // Getting JSON Array node

                // looping through All Contacts
                for (int i = 0; i < contacts.length(); i++) {
                    JSONObject c = contacts.getJSONObject(i);

                    String id = c.getString("id");
                    String name = c.getString("name");
                    String street = c.getString("street");
                    String postalcode = c.getString("postalcode");
                    String entry = c.getString("entry");
                    String opening = c.getString("opening");
                    String agegroup = c.getString("agegroup");
                    String imageurl = c.getString("imageurl");
                    String urlbtn = c.getString("urlbtn");
                    String Fsk = c.getString("Fsk");
                    String city = c.getString("city");
                    String lat = c.getString("lat");
                    String lng = c.getString("lng");
                    String bg = c.getString("background");
                    String qr = c.getString("qr");
                    HashMap<String, String> contact = new HashMap<>();

                    // adding each child node to HashMap key => value
                    contact.put("id", id);
                    contact.put("name", name);
                    contact.put("street", street);
                    contact.put("postalcode", postalcode);
                    contact.put("entry", entry);
                    contact.put("opening", opening);
                    contact.put("agegroup", agegroup);
                    contact.put("imageurl", imageurl);
                    contact.put("urlbtn", urlbtn);
                    contact.put("Fsk", Fsk);
                    contact.put("city", city);
                    contact.put("lat", lat);
                    contact.put("lng", lng);
                    contact.put("background", bg);
                    contact.put("qr",qr);
                    // adding contact to contact list
                    contactList.add(contact);

                }
            } catch (final JSONException e) {
                Log.e(TAG, "Json parsing error: " + e.getMessage());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),
                                "Json parsing error: " + e.getMessage(),
                                Toast.LENGTH_LONG)
                                .show();
                    }
                });

            }
        } else {
            Log.e(TAG, "Couldn't get json from server.");
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(),
                            "Couldn't get json from server. Check LogCat for possible errors!",
                            Toast.LENGTH_LONG)
                            .show();
                }
            });

        }

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        // Dismiss the progress dialog
        if (pDialog.isShowing())
            pDialog.dismiss();

        for (final HashMap<String, String> contact : contactList){
          contact.get("qr");
           if (qr_result.equals(contact.get("qr"))){
                Toast.makeText(getApplicationContext(),"QR Accepted",Toast.LENGTH_LONG).show();
            }else{
                Toast.makeText(getApplicationContext(),"NOt goog",Toast.LENGTH_LONG).show();
            }
        }
    }
}

}


text:
Q: Last visited pages in site I have one script where am trying to display in a website block The LATEST ARTICLES VISITED BY THE CURRENT USER.
The user can be anonymous or a member.
The articles are in table like [ id_art, intro, text]
So when the visitor X visit a page, i would like to put in the bloc the visited page.

A: Create a table on the form:
id, tstamp, art_id (key=[id, tstamp, art_id], index=[id, tstamp])

Whenever a user requests an article, add a row with article ID and timestamp. For the ID you can use the user ID for members or an auto-generated ID (persisted in a (session) cookie).
The list is then generated by extracting the latest N records in the table based on the (user/auto) id. (I.e., the actual list is generated by extracting N article titles and links based on a join on the IDs in the two tables.)
Credit goes to silvo for the following point (see comments):

... you should do some periodic upkeep on your table to make sure you don't keep entries that are too old and irrelevant

(Note: This is a generic solution. Nothing specific for Joomla / technology X / ... .)