text:
Q: R: grouping/splitting a dataset by categories in combination with apply.weekly() Intro
I am not an R expert yet so please excuse another question which I probably should be embarassed of to ask. In another question I asked on stackoverflow I got some very helpful comments on how to aggregate unregularly daily data of an xts object to weekly values by the
apply.weekly() function. Unfortunately I didn't find a function like tapply(), ddply(), by() or aggregate() which allows to split up by categories which works together with the apply.weekly() function.
My Data
This is my example dataset. I already posted in the other question. For illustration purposes I am taking the liberty to also post it here:
example <- as.data.frame(structure(c(" 1", " 2", " 1", " 2", " 1", " 1", " 2", " 1", " 2",
" 1", " 2", " 3", " 1", " 1", " 2", " 2", " 3", " 1", " 2", " 2",
" 1", " 2", " 1", " 1", " 2", NA, " 2", NA, NA, " 1", " 3", " 1",
" 3", " 3", " 2", " 3", " 3", " 3", " 2", " 2", " 2", " 3", " 3",
" 3", " 2", " 2", " 3", " 3", " 3", " 3", " 1", " 2", " 1", " 2",
" 2", " 1", " 2", " 1", " 2", " 2", " 2", " 3", " 1", " 1", " 2",
" 2", " 3", " 3", " 2", " 2", " 1", " 2", " 1", " 1", " 2", NA,
" 2", NA, NA, " 1", " 3", " 2", " 3", " 2", " 0", " 3", " 3",
" 3", " 2", " 0", " 2", " 3", " 3", " 3", " 0", " 2", " 2", " 3",
" 3", " 0", "12", " 5", " 9", "14", " 5", "tra", "tra", "man",
"inf", "agc", "07-2011", "07-2011", "07-2011", "07-2011", "07-2011"
), .indexCLASS = c("POSIXlt", "POSIXt"), .indexTZ = "", class = c("xts",
"zoo"), .indexFORMAT = "%U-%Y", index = structure(c(1297642226,
1297672737, 1297741204, 1297748893, 1297749513), tzone = "", tclass = c("POSIXlt",
"POSIXt")), .Dim = c(5L, 23L), .Dimnames = list(NULL, c("rev_sit",
"prof_sit", "emp_nr_sit", "inv_sit", "ord_home_sit", "ord_abr_sit",
"emp_cost_sit", "usage_cost_sit", "tax_cost_sit", "gov_cost_sit",
"rev_exp", "prof_exp", "emp_nr_exp", "inv_exp", "ord_home_exp",
"ord_abr_exp", "emp_cost_exp", "usage_cost_exp", "tax_cost_exp",
"gov_cost_exp", "land", "nace", "index"))))

The columns
"rev_sit", "prof_sit", "emp_nr_sit", "inv_sit", "ord_home_sit", "ord_abr_sit", "emp_cost_sit", "usage_cost_sit", "tax_cost_sit", "gov_cost_sit","rev_exp", "prof_exp", "emp_nr_exp", "inv_exp", "ord_home_exp","ord_abr_exp", "emp_cost_exp", "usage_cost_exp","tax_cost_exp","gov_cost_exp",
refer to questions in a survey. There were three answering possibilities codes as "1", "2", and "3".
The columns
"land", "nace"
are categories with 16 and 8 unique factors respectively.
My goal
My goal is to count the occurrence of "1", "2", and "3" each by week for each combination of the category factors in "nace" and "land". My idea was to create binary vectors for each answering possibility {1,2,3} beforehand (example_1,example_2,example_2) and then apply something like:
apply.weekly(example_1, function(d){ddply(d,list(example$nace,example$land),sum)})

But this doesn't work neither with ddply, aggregate, by etc.
My goal
My unprofessional work around initially was not to create a time series, just a date vector example$date with the given time column coded as weekly via %V an then to use i.e:
tapply(example_1[,5], list(example$date,example$nace,example$land),sum)

which I would of course than have to do for every out of the above displayed twenty questions. I then get i.e. for example_1:
week1, nace1.land1, nace1.land2, nace1.land3, ..., nace1.land16, nace2.land1,..,nace8.land16
week2, nace1.land1, nace1.land2, nace1.land3, ..., nace1.land16, nace2.land1,..,nace8.land16
...
...
weekn, nace1.land1, nace1.land2, nace1.land3, ..., nace1.land16, nace2.land1,..,nace8.land16
The same I would have to do for 2 (example_2) and 3 (example_3) and this for each of the 20 questions to produce all in all 16*8*3*20=7680 columns. This extreme and additionally with this method the product is not a time series and thus it is not ordered correctly by week.
Summary
So can anyone teach me or give me a hint how to use the function apply.weekly() in combination with functions the sort of tapply(), ddply(), by(), split(), unstack() etc. or any other method to achieve grouping like described above. Every hint is really appreciated. I am so frustrated already thinking about to abandon my R experiment and changing back to stata where so many things are much more intuitive with collapse() and by() etc... But don't understand me wrong: I am keen to learn so please help me!

A: thank you very much for all your help. I was busy with some other stuff in the meanwhile but now I was working on my problem again, and with the help of your great comments I have found a solution:
I gave up working directly with time series, postponing this step to the end of my analysis. Therefore I take the date vector and transform it into weeks:
library(ISOweek)
d$index <- ISOweek(d$date)
(i do this with ISOweek since I am using Windows)
then I use a combination of tapply and lapply. The following function calculates the number of positive answers in the survey (coded by 1) for every calendar week (d$index = t[[22]]) and every combination of the two categorical columns t[[21]], t[[22]]. In the same step the whole thing is transformed into a data frame:
groupweeksums <- function(x,t){as.data.frame(tapply((x==1)*1,list(t[[23]],t[[21]],t[[22]]), function(d)sum(d,na.rm=TRUE)))}
==>x stands for the specific column, t for the data frame (i didn't know how to do that otherwise because at one point i have to address a column at the other the data frame and I wanted to avoid lots of typing) ; if d is the data frame then:
df <- groupweeksums(d,d)
in order that I don't have to repeat this procedure for all of my 20 questions is use lapply:
df <- as.data.frame(lapply(df[,1:20],function(d)groupweeksums(d,euwifo)))
This gives me a beautiful data frame with all I need for further analysis. Thanks for your help, with your helpful comments I came closer and closer to the solution!!!
P.S. I will also post this answer to the other question I posted on stackoverflow which was connected to this one. I hope this is no problem or against any rules here.

A: I would add a "week" column, as you suggest, but convert the data to a tall format before processing -- you can convert it back to a time series afterwards, if needed.
library(reshape2)
d <- melt(example, id.vars=c("land", "nace", "index"))
# You apparently want one of the followings
dcast( d, land + nace + index ~ value, length )
dcast( d, land + nace + index + variable ~ value, length )
dcast( d, land + nace + index ~ variable + value, length )

Equivalently, you could use ddply:
library(plyr)
d <- melt(example, id.vars=c("land", "nace", "index"))
ddply( d,
  c("land", "nace", "index", "value"),
  summarize,
  number=length(value)  # The argument "value" does not play any role
)

Your index column contains the number of the week in the current year (%Y-%U): this will only work if all the dates are within the same calendar year. It may be safer to use an actual date instead of the week number, for instance, the Sunday at the start of the current week -- it also makes it easier to turn the result into a time series.
week_start <- function(u) as.Date(u) - as.numeric(format(u, "%u"))
example$index <- weekstart( as.POSIXct(rownames(example)) )
# The following may also work.
example$index <- format( as.POSIXct(rownames(example)), "%G-%V" )


text:
Q: Getting form inputs in the controller after validation I am new to Laravel world and I have a problem which I can't solve so far.
My question is:
How to access the submitted values in the controller's create() function after the validation fails?
Here is what I have:

*

*PostsController, defined as resource in the routes.php

*In the controller I have usual methods create() and store() etc.

Here is some code:
//PostsController
public function create()
{
    //Here I need to get the inputs
    return view('posts.create');
}

public function store(Requests\PostsRequest $request)
{
    //store actions
}

I have created PostsRequest class which has some rules like:
public function rules(){
    $rules = [
        'category_id'=>'required',
        'name'=>'required|min:3',
        'description'=>'required'
    ];
    return $rules;
}

If everything is fine the entry has been stored to the DB, but when the validation fails, it's loaded the create() with some validation messages.
I need to load ancestors of the selected category in the form and this should happen by knowing the submitted value of the category_id element.
What I've tried so far:

*

*Tried to add parameter in the create like so:
public function create(Requests\PostsRequest $request){...}

But it went to infinite loop. I understand why because of the resource definition of the controller and it "think" that it's store method.

*Tried to print facade Input::all() but it's empty

*Tried to make:
public function create(){
    $request = new \Request();
    //print $request
}

But it doesn't work, neither I think it's the right way.
So any idea how to get these values in the controller would be highly appreciated.

A: You should be able to get the data with Input::old()
In your views you can do
<input type="text" name="name" value="{{ old('name') }}" />

which would give the value from name if it was sent.
Also see this recent question/answer;
Laravel 5 - Validation error on form doesn't re-enter user input

A: If you use {!! Form::open() !!} (or Form::model) everything will be loaded again (after redirect back). Laravel automatically capture the "Input::old" values.
From source: FormBuilder.php (illuminate/html package - Version 5.0)
/**
 * Get the value that should be assigned to the field.
 *
 * @param  string  $name
 * @param  string  $value
 * @return string
 */
public function getValueAttribute($name, $value = null)
{
    if (is_null($name)) return $value;

    if ( ! is_null($this->old($name)))
    {
        return $this->old($name);
    }

    if ( ! is_null($value)) return $value;

    if (isset($this->model))
    {
        return $this->getModelValueAttribute($name);
    }
}

If you don't want to use illuminate/html, just add at your  value attribute:
Input::old('input_name')

If you want to get the Request. Just add to your create method.
public function create(Request $request){
   $data = $request->all(); //or whatever you want..
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Save file changes if you forgot to use sudo I am using Nano.
Sometimes I make changes to a file and then after attempting to save I realize that I need sudo permissions. Then I need to close the file, reopen it as sudo and make my changes again...
Is there a way to save anyways? I remember a colleague closed the file without saving and then executed "sudo !!" or something and then it saved the changes.
How does it work?

A: The command sudo !! in shells such as zsh or bash that implement csh-style history expansion would re-execute the most recent command but prefix it with sudo.  If the most recent command was opening a text editor, then this will be done as the root user.  You could then go on and re-do the changes and save.  However, the changes that you introduced the first time around would be lost.
Assuming you are using the nano editor as a non-root user, and you find yourself needing to save the current file as root.  You may then do so by filtering the current buffer's contents through sudo tee some/file/path.  That command would run tee as root and would overwrite or create the file at some/file/path.
From the nano editor, you could invoke this filter by pressing ^R^X, i.e., Ctrl+R+Ctrl+X, and then type
|sudo tee some/file/path

(The initial | signals to nano that you want to pass the current document to that command.)
If sudo needs to prompt you for your password, it will do so.  This will mess up the display a bit, but you may redraw the screen by pressing ^L (Ctrl+L).
Note that care must be taken to specify the correct pathname of the file that you want to write to, as it would irreversibly overwrite that file with the contents of the editor's buffer.  Since you write as root, permissions will not stop you from destroying data. This is therefore a sort of "hack" that may possibly be good to know about, but that you don't want to rely on.
The ability to filter text from nano to an external command like this was added in release 2.9.8 (2018).

A: Try this...
:w !sudo tee %

Explanation...

*

*:w – writes the contents of buffer

*!sudo – pipes it to the stdin of sudo

*tee % – sudo executes tee to write to "%" file

*% – Vim expands "%" to current file name

A: sudo !! will recall last command (!!) with sudo. You'll have to remade the change anyway (supposing last command was the editing).
Depending on file size and sensivity (confidentials informations, clear text password, etc ...), you may save file in a temporary location, and re import it from sudo.
sample code from a vi session :
:w /tmp/file.txt
sudo vi /some/path/file.txt
:%d (this will delete all content of file.txt under sudo)
:r /tmp/file.txt (this will include from /tmp/file.txt )
:x (exit vi)
rm -f /tmp/file.txt (delete file)

note that /tmp/file.txt is exposed.

A: The general solution is "write the modified file to somewhere permitted, exit the editor, copy/move the file to the Right Place".
If you set up the VISUAL and EDITOR environment variables to the full path of your favorite editor (use, e.g. type -p nano)  , you can use the sudoedit command. Read man sudoedit.
sudoedit uses its root powers to make a temporary copy of the file you're editing, lets you ($USER) edit the copy. When you finish editing, and the temporary file has been changed, sudoedit copies the temporary file to the file you wanted to edit.


text:
Q: Accessing outer object from the nested one Question about C++ standard and appropriate design pattern
I have an object which has several non-POD objects as members, and from within those objects I need to access the outer one.
For example it can be an object which "listens" to several different events, whereas listening means implementing some interface. You can't just inherit this interface directly by your main class, because you can't inherit the same base class multiple times. But even if you could - you may want to avoid this, since you don't want to expose this interface, it's just implementation details of your object.
I mean something like this:
class MyClass
{
    // ...
    struct Listener1 :public IEventListener {
        virtual void OnEvent() { /* need to access MyClass */ }
    } m_Evt1;

    struct Listener2 :public IEventListener {
        virtual void OnEvent() { /* need to access MyClass */ }
    } m_Evt2;
};

One obvious way to give access to the outer class is to have a member of pointer/reference to it in every inner object. But this requires writing some code (initialization of the pointer/reference), and compilers don't like when you use this in base member initialization, plus there's an actual code generated for this and object layout is inflated in memory.
There is also another possibility: using offsetof-like trick. The memory offset of the inner object wrt outer class is known at compile-time. Hence vice-versa also holds, i.e. we can subtract that offset from this of the inner object to get the pointer to the outer class. Wrap it with nice C++ accessor method and - voila.
#define IMPLEMENT_GET_PARENT_OBJ(parent_class, this_var) \
parent_class& get_ParentObj() { return * (parent_class*) (((PBYTE) this) + 1 - (PBYTE) (&((parent_class*) 1)->this_var)); }

class MyClass
{
    // ...
    struct Listener1 :public IEventListener {
        IMPLEMENT_GET_PARENT_OBJ(MyClass, m_Evt1)
        virtual void OnEvent() { get_ParentObj().OnEvent1(); }
    } m_Evt1;

    struct Listener2 :public IEventListener {
        IMPLEMENT_GET_PARENT_OBJ(MyClass, m_Evt2)
        virtual void OnEvent() { get_ParentObj().OnEvent2(); }
    } m_Evt2;

    void OnEvent1();
    void OnEvent2();
};

One can argue that if you declare such objects of inner type outside of the MyClass - then obviously the get_ParentObj() is broken, and you get the undefined behavior. Also you may technically get the reference to the outer class from the c'tor of the inner one, and invoke its methods even before it's constructed.
I know there are zillions of ways to solve this and make it fool-proof, such as creating inner objects dynamically and giving them a weak reference to the outer class, and etc.
But this is an overkill in my scenario. Assuming you don't shoot yourself in the foot on purpose there seems to be no problem.  And speaking practically it just works, without any memory waste or unneeded extra code.
Is it considered a good practice? And if not - why?


text:
Q: Creating objects with cypher using neo4j ogm I have started using neo4j-ogm 2.1.0 and I have a basic question.
I understand that we can persist or query objects to/from a graph with a fixed, declarative domain model.
My requirement is to do this using cypher instead, so that I don't have to worry about dynamic types which may not be declared in my domain model. I have already referred to
Neo4j-Ogm for dynamic domain object model.
My question is, can I do something like:
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
String cypher = "CREATE (n:MyNode{name:"my name"}) RETURN n";
try {
    session.execute(cypher);
}

A: If you do not care about modelling domain objects and simply want an API to execute Cypher statements from Java then you can either use the Bolt Driver (requires Neo4j 3.0 and above; refer to the manual for usage) or by using the HTTP Endpoint with a client (like this one).
If you want a mix of both then you can continue to use the Neo4j OGM and just call the query or queryForObject methods on Session to call your dynamic cypher.


text:
Q: Java socket client: waiting for the response patiently I have created a server via sockets with the help of quickserver.org. The server runs solidly.
Now I had to write the client that sends a request (just a string value) to the server for an instruction and waits for its response (xml as string). This works fine when the triggered process by the request on server is not very time consuming. Unfortunately the client connection breaks as far as the server needs a long time for the process and that leads for a connection break and the client doesn't get anything back.
Here is the client code:
public String sendAndReceive(String message) throws IOException {
    PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(this.socket.getOutputStream()));
    BufferedReader reader = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
    printWriter.print(message);
    printWriter.flush();
    this.socket.shutdownOutput();
    String line = null;
    StringBuilder xmlResponse = new StringBuilder();
    while ((line = reader.readLine()) != null)
    {
        xmlResponse.append(line);
    }
    printWriter.close();
    reader.close();
    this.socket.close();
    return xmlResponse.toString();
  }

This method sends the request and waits for the response afterwards. I am not sure about the while loop but all examples I have found on web are praising this construction. On my point of view reader.readline() can be null because the server needs more time for the response and therefore the method ends without getting the response.
How is the best practice for socket clients waiting for the response patiently? What I am doing wrong?
Kind regards,
Hilderich

A: You are probably getting timeout.
You can use Socket.setSoTimeout(int timeout) to change timeout (in milliseconds).


text:
Q: Can Kalman Filtering be done hierarchically - estimated from multiple time series with the same parameters? I have a large number of of noisy time series recordings (trials), for which I wish to estimate the state transition model underlying them using the Kalman filter. The process generating the time series is the same in every trial, and so I want to be able to pool information from all of the trials, rather than fitting individual filters to every trial.
I thought this should be a fairly common application of the Kalman filter, but
unfortunately I haven't been able to find any literature on how this might be done. I suspect I've either fundamentally misunderstood something about how Kalman filters work, and so what I require can't be done, or I just don't know the terminology for what I'm looking for.
So, can anyone tell me if it is possible to fit the Kalman filter in this way, and if so, what this method is called?

A: If the parameters can be assumed to have the same value across all trials, the total likelihood (assuming independence between trials) is just the product of the likelihood for each trial.  So just write a function that computes this product (or the sum of the logs) taking the unknown parameter values as a vector first argument.  If you're happy with maximum likelihood estimates, then maximise this function numerically.  In R, the functions you need are optim and KalmanLike (or perhaps Kfilter0 in the astsa package).


text:
Q: Favicon requested on every route change
I think it's strange that a route change would trigger a request for the favicon.
Is this intended or what is going on here?

A: I had the same problem and I believe the problem started with the Chrome 49.0.2623.87. I hope it is going to be fixed in the coming updates. For now, I am using the script below, which can be found here.
var favIcon = "favicon.ico";
var docHead = document.getElementsByTagName('head')[0];
var newLink = document.createElement('link');
newLink.rel = 'shortcut icon';
newLink.href = 'data:image/png;base64,'+favIcon;
docHead.appendChild(newLink);

It will not stop the favicon requests, so for a short period of time you still will see the default favicon from chrome, but I believe there is not much to be done about that.

A: I found a solution on Github. Quoting @Doeke:

Try reordering the favicon link tags. For me, putting the 16x16 link before 32x32 fixed this issue. As for why this works... I have no idea.

For me, it meant putting the only favicon <link> on my page right at the top of <head>, after <meta charset>.

A: Try to serve favicon.ico from your server or add route for that. I was experienced such error when using express catch-all app.get('*') method which redirected all requests to index.html (even for favicon)

A:
Change the <link> tag as mentioned below in Step 6, or follow the comments.

Embedding the icon inline as a Data URL will do the magic!

What is a Data URL?
Data URLs allow content creators to embed small files inline in documents.

STEPS:

*

*Convert favicon image to Data URI from this link: Converter

*Upload the .ico file from the public folder.

*Next, select output format as: Data URI -- data:content/type;base64

*Next change the <link> tag's href with the generated output!

*

Replace this line(<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />) in public > index.html.

*

TO this line ↓↓

<link
  rel="icon"
  href="data:image/x-icon;base64,[encoded data, 5160 characters]"
/>

Now whenever this href is parsed, the DATA URL is loaded, instead of the .ico file. Hence, no new requests will be sent to the server as the data is embedded inline!

A: Change the favicon request by the following line of code in your index.html page
<link rel="icon" href="data:image/vnd.microsoft.icon;base64,<data>">

here, <data> is the base64 data of your favicon.
refer https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs
This trick stops the user's browser from sending an automatic HTTP request for the favicon.

A: For me, while using Next 13, replacing
<head> with <Head> (note case) seems to fix the issue.


text:
Q: Range Based For Loop in C++ : How it is working? std::vector<int> v = {0, 1, 2, 3, 4, 5};
for (auto i : v)
{
   // access by value, the type of i is int
   std::cout << i << ' ';
}
std::cout << '\n';

I found this as part of another question
How to navigate through a vector using iterators? (C++)
I would like to know how  the following works ?
for (auto i : v)

will navigate the entire vector, I need this information because I want to implement a custom vector class. In order to create custom vector class, do I need to create the begin(), end() functions and iterator member variable in it?


text:
Q: Change Tax according to vendor product on shipping I am trying to add tax functionality according to vendor product and vendors have allowed different shipping address.
I have added the functionality for vendor to select specific tax location and on checkout using this code get tax but unable to update tax after order completed. I am using Dokan multi vendor plugin.
Simply want to add tax on allowed shipping address by vendor.
function filter_woocommerce_calc_tax( $taxes, $price, $rates, $price_includes_tax, $suppress_rounding) {
     global $woocommerce;
     global $wpdb;
     $subTotal=$woocommerce->cart->subtotal;
     $table = $wpdb->prefix.'tax_state_by_vendor';
     $cart = WC()->cart->get_cart();
     $reqTaxStat=0;
     $reqTaxStat = $wpdb->get_row("select tax_rate_id from wpyp_woocommerce_tax_rates WHERE tax_rate_country = '".$_REQUEST['s_country']."' and tax_rate_state = '". $_REQUEST['s_state']."'");
     $Qunatity=1;

     $productDetails = array();
        $i = 0;
        foreach( $cart as $key => $cart_item ){
            $Qunatity += $cart_item['quantity'];
            $post_obj    = get_post( $cart_item['product_id'] ); // The WP_Post object
            $productDetails[$i]['product_id'] = $cart_item['product_id'];
            $productDetails[$i]['vendor_id'] = $post_obj->post_author;
            $taxes = $wpdb->get_row("select tax_id from $table WHERE vendor_id = ".$post_obj->post_author);
            $productDetails[$i]['vendor_tax_states'] = $taxes->tax_id;
            $taxDetails = $wpdb->get_results("select wrt.tax_rate,wrt.tax_rate_country,wrt.tax_rate_state from wpyp_tax_state_by_vendor tv left join wpyp_woocommerce_tax_rates wrt on find_in_set(wrt.tax_rate_id, tv.tax_id) > 0
            WHERE tv.vendor_id = ".$post_obj->post_author);

            $productDetails[$i]['vendor_tax_details'] = array();
            foreach($taxDetails as $tkeys => $tval){
                $productDetails[$i]['vendor_tax_details'][$tkeys]['tax_price'] = $tval->tax_rate;
                $productDetails[$i]['vendor_tax_details'][$tkeys]['tax_country'] = $tval->tax_rate_country;
                $productDetails[$i]['vendor_tax_details'][$tkeys]['tax_state'] = $tval->tax_rate_state;
            }
            $productDetails[$i]['product_total_rpice'] = get_post_meta($cart_item['product_id'] , '_price', true);
            $i++;
        }
     $totalTax = 0;

     if(!empty($productDetails)){
        foreach($productDetails as $pkey => $pval){
            foreach($pval['vendor_tax_details'] as $taxD){
                if(($_REQUEST['s_country'] == $taxD['tax_country']) && ($_REQUEST['s_state'] == $taxD['tax_state'])){
                     $totalTax += $pval['product_total_rpice'] * $taxD['tax_price'] / 100;
                }
            }
        }
     }
     if(isset($totalTax)){
    // echo $Qunatity;
     // print_r(array($reqTaxStat->tax_rate_id => $totalTax));die;
        return array($reqTaxStat->tax_rate_id => $totalTax * 100 / count($cart));
     }

    return taxes;
}

add_filter( 'woocommerce_calc_tax', 'filter_woocommerce_calc_tax', 10, 5);

Can anybody help me how will I add tax according to vendor allowed product.


text:
Q: How can I get rid of this c warning? Here sock_client is an socket:
LaunchThread(proxy_handlereq, sock_client);

static void LaunchThread(int (*func)(), void *parg)
{
#ifdef WINDOWS
    LPDWORD         tid;
    CreateThread(NULL, 0L, (void *)func, parg, 0L, &tid);
#else
    pthread_t               pth;
    pthread_create(&pth, NULL, func, parg);
#endif
}

I'm getting the following warning: warning: cast to pointer from integer of different size
How can I pass it as the 2nd parameter of LaunchThread?

A: Try this:
LaunchThread(proxy_handlereq, (void*)sock_client);

Edit:
Ok, now I see:  sock_client is just the integer number of the port.
And you want to pass this number to the other thread, right?
(Depending on the pointer size on your system) you can get rid of the
warning by this dirty cast:
LaunchThread(proxy_handlereq, (void*)(0xFFFFFFFFFFFFFFFF & sock_client);

But actually I would recommend, that you create a data structure with
all the information, that you want to pass to the other thread, e.g.:
struct MyData {
    int socket_no;
    const char* host_name;
    ...
};

Then create an instance of this and pass a pointer to the instance to
your LaunchThread function.

Edit2:
You can see some sample code in this question:
Multiple arguments to function called by pthread_create()?

A: If sock_client is a socket, you need to invoke LaunchThread as:
LaunchThread(proxy_handlereq, &sock_client);

because both CreateThread and pthread_create expect a pointer to the argument to pass on to func().


text:
Q: how to call a generic parameterized method bounded JAVA? I would like to know how I can call a bounded parameterized method.
For example, I have the following method :
  public static<R extends Reader & Runnable> R foo(R r) {
         r.run();
         return r;
  }

I would like to know how to call this method.
I try the following code :
    private static class Test extends Reader implements Runnable {
        ...........
    }

    private static <T extends extends & Runnable> T getInstance() {
        return (T) new Test();
    }

    public static void main(String[] args) {
        foo(getInstance());
    }

But I have the following exception :

Exception in thread "main" java.lang.ClassCastException: class ent.Main$Test cannot be cast to class java.lang.Runnable (ent.Main$Test is in unnamed module of loader 'app'; java.lang.Runnable is in module java.base of loader 'bootstrap')

And I can not find the solution.
Can someone have an idea?
Thank you in advance !

A: This:
private static <T extends Reader & Runnable> T getInstance() {

means that the method can return something that can be cast to any class which both extends Reader and implements Runnable. However, there is only one such value that you can return safely from this:
return null;

Anything else could result in a ClassCastException. In particular, return new Test(); will only succeed if you happen to have invoked is in a context expecting to receive a Test.
In general, you can't safely return a non-null T from a method if T does not feature in the formal parameters. See the documentation of Error Prone's TypeParameterUnusedInFormals check for more detail.
If you want to return an instance of Test from getInstance(), drop the generics and make the return type Test.
private static Test getInstance() {
    return new Test();
}


text:
Q: Get specific records in an ordered data by time but doesn't have primary key for association Ok, the title isn't enough to explain the problem. I have the following data which gives the time and length of iron bars. There is no primary key that identifies each iron bar. However, the data is ordered by time and whenever the length is zero we know that the values after it belong to the same iron bar. The time is when the measurement is recorded, and length is the measurement. Here is the script to create the data:
DECLARE @data TABLE ([time] DATETIME, [length] FLOAT)

INSERT INTO @data
VALUES ('2023-01-15 01:00:10', 0), ('2023-01-15 02:23:15', 0), ('2023-01-15 02:23:16', 0.3334), ('2023-01-15 02:23:23', 1.11), ('2023-01-15 02:23:50', 2.225), ('2023-01-15 02:24:00', 5), ('2023-01-15 02:24:13', 5.334), ('2023-01-15 02:24:23', 5.9), ('2023-01-15 02:24:35', 6.125), ('2023-01-15 02:25:30', 6.334), ('2023-01-15 02:26:33', 7.996), ('2023-01-15 02:27:31', 10.3), ('2023-01-15 02:27:32', 0), ('2023-01-15 02:28:28', 0), ('2023-01-15 02:29:22', 0), ('2023-01-15 02:30:14', 0.66669), ('2023-01-15 02:30:15', 1.669), ('2023-01-15 02:30:25', 2.334), ('2023-01-15 02:30:30', 3), ('2023-01-15 02:30:35', 5.669), ('2023-01-15 02:30:56', 6.669), ('2023-01-15 02:31:15', 7.332), ('2023-01-15 02:31:30', 8), ('2023-01-15 02:31:40', 9.5), ('2023-01-15 02:31:44', 9.9), ('2023-01-15 02:31:55', 10), ('2023-01-15 02:32:15', 10.4), ('2023-01-15 02:32:20', 0), ('2023-01-15 02:32:30', 0.5), ('2023-01-15 02:32:44', 1), ('2023-01-15 02:32:54', 1.334)

What I'm trying to get from this data are the records when the length becomes 0, 5, 7 and 10. Usually, the length is not a whole number and has a fraction. In that case I'll take the first length close to the whole number. For example, If I have the following lengths: 4.9, 5.33, 5.5, 5.7, then I'll take the value 5.33 because it is the least number higher than 5. The same applies for the remaining lengths.
Number 0 indicates a new Iron bar, but it also can be recorded more than once for the same Bar. Here is a screenshot of the data above:
3 iron bars with lengths
And this is the data I'm trying to get:
enter image description here
I tried the following but this leads to data to get scrambled. Just added this since stackoverflow requests it but obviously not what I'm looking for.
SELECT MIN([time]), FLOOR([length])
FROM @data
WHERE FLOOR([length]) IN (0, 5, 7, 10)
GROUP BY FLOOR([length])

Thanks.

A: Cool question, appeared much more complicated then it seems to be :)
;with candidates as (
    select
        *
    from @data
    where floor([length]) in (0, 5, 7, 10)
)
, candidatesWithPrevLength as (
    select
        *
        , lag([length]) over (order by [time]) as lengthPrevious
    from candidates
), candidatesWithGroupStarts as (
    select
        *
        , case when [length] < lengthPrevious or lengthPrevious is null then 1 else null end as 'groupStart'
    from candidatesWithPrevLength
), groups as (
    select
        [time]
        , lead([time]) over (order by [time]) as validUntil
        , row_number() over (order by [time]) as groupId
    from candidatesWithGroupStarts
    where groupStart = 1
), candidatesInGroups as (
    select
        c.*
        , g.groupId
    from candidates c, groups g
    where c.[time] >= g.[time] and (c.[time] < g.validUntil or g.validUntil is null)
), candidatesInGroupsWithOrders as (
    select
        *
        , row_number() over (partition by groupId, floor([length]) order by [time]) as OrderNo
    from candidatesInGroups
)
select [time], [length] from candidatesInGroupsWithOrders where orderno = 1

Surprisingly, I had to use a bunch of SQL mechanisms to achieve this goal: CTE-s, join, window functions
Will try to describe the idea in brief:

*

*find candidate bars (ones who match initial conditions)

*calculate groups of candidates (based on 0-to-10 length checks)

*split all candidates into groups

*select needed bars from these groups

That's just a possible option. Definitely, a bit "dirty". Not sure how it will work with huge amounts of data. Definitely could be simplified and optimized. But it works and could be a good "starting point"


text:
Q: ng-click change parent class I'm attempting to build a simple slide out menu, I have it working fine using the menu button.

{{filter.filter_type}}

CSS
.side-menu {
  left: -25%;
  position: absolute;
  transition: all 0.2s linear 0s;
  width: 25%;
  background: #000;
}

.side-menu.show_menu {
    left:0%;
}

When I press the menu-button div it works fine (i.e it adds the class), however I also want to be able to close the menu when an item inside it is picked, I have tried the above but nothing is happening.
I thought originally it had to do with the fact that its calling another function too, but I even removed that and there's still the same issue. Am I misunderstanding how ng-click works?

A: ng-repeat directive create new scope - child to scope where your show_menu exists. So by clicking on menu item (some filter I think) you is changing show_menu in that child scope actually. But ng-class watches for show_menu in parent scope, which was not changed.
For more information read here: https://github.com/angular/angular.js/wiki/Understanding-Scopes
PS: You can write ng-class:

which much more concise and clearly, I think.


text:
Q: Deriving a lower bound for a probability involving a random variable $X$ with the Gamma distribution. Question
Let $X$ have the $Gamma(\alpha, \beta)$ density.
I.e. $$f_X(x) = \frac{1}{\gamma(\alpha)\beta^\alpha}x^{\alpha-1}e^{-\frac{x}{\beta}}$$
when $x >0$ and $0$ elsewhere.
The moment generating function of $X$ is $M(t) = \frac{1}{(1-\beta t)^\alpha}, t < \frac{1}{\beta}.$
(*) Accept that $P(X \ge r) \le e^{-rt}M(t)$ for every $r$ and all t, $0 < t < \frac{1}{\beta}$.
Derive a lower bound (depending only on $\alpha$) for $P(X \ge 2\alpha\beta)$
Answer
Using (*) and letting $r = 2\alpha\beta$ we have
$$P(X \ge 2\alpha\beta) \le e^{-2\alpha\beta t} \frac{1}{(1-\beta t)^\alpha}$$
$$\iff P(X \ge 2\alpha\beta) \le \frac{(e^{-2\beta t})^\alpha}{(1-\beta t)^\alpha}$$
$$\iff P(X \ge 2\alpha\beta) \le \bigg(\frac{e^{-2\beta t}}{(1-\beta t)}\bigg)^\alpha$$
But all I have now is an upper bound, and not only that, it is dependent on $\beta$ and $t$ as well as $\alpha$. Am I completely off track here? Anyone know how to solve this problem?

A: Directly using the distribution function:
$$P(X \geq 2\alpha \beta)= 1 - P(X < 2\alpha \beta)=1 - F(2\alpha \beta)\\=1-\frac{1}{\Gamma(\alpha)\beta^\alpha}\int_0^{2\alpha\beta}s^{\alpha-1}e^{-\frac{s}{\beta}}\, ds.$$
Let $u = s/\beta$.
Then
$$P(X \geq 2\alpha \beta)= 1- \frac{1}{\Gamma(\alpha)}\int_0^{2\alpha}u^{\alpha-1}e^{-u}\, du>0.$$ So equality here gives a lower bound that depends only on $\alpha$.
For an upper bound, you can use Markov's inequality.
$$P(X \geq 2\alpha \beta) \leq \frac{E(X)}{2\alpha\beta} = \frac{\alpha \beta}{2\alpha\beta}=\frac1{2}.$$


text:
Q: How to overlay Tikz picture over an equation? How do I properly overlay a Tikzpicture over a numbered equation? I want to have arrows pointing to different places in the equation to explain their origin.
\begin{equation}
    2\left[\frac{2k_{F}}{\left(\frac{2\pi}{Na}\right)}\right]=n(Na)
\end{equation}

I have tried doing
\begin{equation}
\begin{tikzpicture}
   \node at (0,0)
        {\[
            2\left[\frac{2k_{F}}{\left(\frac{2\pi}{Na}\right)}\right]=n(Na)
        \]};
\end{tikzpicture}
\end{equation}

but the number becomes misaligned with the rest of the equation.


text:
Q: mongodb full text search, have a spellchecker or a way to implement? I have a index full text on my collection of mongoidb and i want to know if exist a way to find a result even if the word is misspelled,  for example:
{id:1,
description: "The world is yours"
},{
id:2
description: "Hello my friend"}

if i search for the word 'wordl' the result would be:
{id:1,
    description: "The world is yours"
   }

is it that possible?

A: MongoDB does not support Fuzzy Search at this time. One way to do it is using string/sounding similarity algorithms, like soundex.
I've created a simple example in PHP to show how to do it with soundex:
$dbName = 'soundex';
$client = new MongoClient("mongodb://127.0.0.1", array('db' => $db));
$db     = $client->$dbName;

$phrases = array(
    'This, is the last of earth. I am content.',
    'Take a step forward, lads. It will be easier that way.',
    'Adieu, mes amis. Je vais à la gloire. (Farewell, my friends. I go to glory.)',
    'I will die like a true-blue rebel. Don\'t waste any time in mourning - organize.'
);

// just for the example, so we can reuse the script several times
$db->phrases->drop();

foreach ($phrases as $phrase) {
    // remove all non characters/whitespaces
    $phrase = preg_replace('/[^a-z\s]/i', ' ', $phrase);

    // remove multiple whitespaces and whitespaces at the beginning/end of the phrase
    $phrase = preg_replace('/\s\s+/', ' ', trim($phrase));

    // split the phrase into unique words
    $words = array_unique(explode(' ', $phrase));

    $soundex = array();

    foreach ($words as $word) {
        $soundex[] = soundex($word);
    }

    $soundex = array_unique($soundex);

    $db->phrases->insert(array(
        'phrase'  => $phrase,
        'soundex' => $soundex
    ));
}

// search for some words

$searches = array(
    'earht',    // earth, phrase 1
    'eaasierr', // easier, phrase 2
    'faerwel',  // farewell, phrase 3
    'reebell'   // rebel, phrase 4
);

foreach ($searches as $search) {
    $cursor = $db->phrases->find(array(
        'soundex' => array(
            '$in' => array(soundex($search))
        )
    ));

    if ($cursor->count()) {
        foreach ($cursor as $doc) {
            echo "Search result for '$search':\n";
            echo $doc['phrase'] . "\n\n";
        }
    } else {
        echo "No results for '$search'\n\n";
        echo soundex($search);
    }
}

This example will output:
Search result for 'earht':
This is the last of earth I am content

Search result for 'eaasierr':
Take a step forward lads It will be easier that way

Search result for 'faerwel':
Adieu mes amis Je vais la gloire Farewell my friends I go to glory

Search result for 'reebell':
I will die like a true blue rebel Don t waste any time in mourning organize

It's just a simple example without removing stop words. You also have to remember to create an index on the soundex values.
Learn more about soundex: http://php.net/soundex
Hope that helps to get an idea of how to do a fuzzy search with MongoDB.


text:
Q: Java8 java.util.Date conversion to java.time.ZonedDateTime I am getting the following exception while trying to convert java.util.Date to java.time.LocalDate.
java.time.DateTimeException: Unable to obtain ZonedDateTime from TemporalAccessor: 2014-08-19T05:28:16.768Z of type java.time.Instant

The code is as follow:
public static Date getNearestQuarterStartDate(Date calculateFromDate){

    int[] quaterStartMonths={1,4,7,10};
    Date startDate=null;

    ZonedDateTime d=ZonedDateTime.from(calculateFromDate.toInstant());
    int frmDateMonth=d.getMonth().getValue();

Is there something wrong in the way I am using the ZonedDateTime class?
As per documentation, this should convert a java.util.Date object to ZonedDateTime. The date format above is standard Date?
Do I have to fallback on Joda time?
If someone could provide some suggestion, it would be great.

A: To obtain a ZonedDateTime from a Date you can use:
calculateFromDate.toInstant().atZone(ZoneId.systemDefault())

You can then call the toLocalDate method if you need a LocalDate. See also: Convert java.util.Date to java.time.LocalDate

A: To transform an Instant to a ZonedDateTime, ZonedDateTime offers the method ZonedDateTime.ofInstant(Instant, ZoneId). So
So, assuming you want a ZonedDateTime in the default timezone, your code should be
ZonedDateTime d = ZonedDateTime.ofInstant(calculateFromDate.toInstant(),
                                          ZoneId.systemDefault());

A: The Answer by assylias and the Answer by JB Nizet are both correct:

*

*Call the new conversion method added to the legacy class, java.util.Date::toInstant.

*Call Instant::atZone, passing a ZoneId, resulting in a ZonedDateTime.

But your code example is aimed at quarters. For that, read on.
Quarters
No need to roll-your-own handling of quarters. Use a class already written and tested.
org.threeten.extra.YearQuarter
The java.time classes are extended by the ThreeTen-Extra project. Among the many handy classes provided in that library you will find Quarter and YearQuarter.
First get your ZonedDateTime.
ZonedId z = ZoneID.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = myJavaUtilDate.toInstant().atZone( z ) ;

Determine the year-quarter for that particular date.
YearQuarter yq = YearQuarter.from( zdt ) ;

Next we need the start date of that quarter.
LocalDate quarterStart = yq.atDay( 1 ) ;

While I do not necessarily recommend doing so, you could use a single line of code rather than implement a method.
LocalDate quarterStart =                    // Represent a date-only, without time-of-day and without time zone.
    YearQuarter                             // Represent a specific quarter using the ThreeTen-Extra class `org.threeten.extra.YearQuarter`.
    .from(                                  // Given a moment, determine its year-quarter.
        myJavaUtilDate                      // Terrible legacy class `java.util.Date` represents a moment in UTC as a count of milliseconds since the epoch of 1970-01-01T00:00:00Z. Avoid using this class if at all possible.
        .toInstant()                        // New method on old class to convert from legacy to modern. `Instant` represents a moment in UTC as a count of nanoseconds since the epoch of 1970-01-01T00:00:00Z.
        .atZone(                            // Adjust from UTC to the wall-clock time used by the people of a particular region (a time zone). Same moment, same point on the timeline, different wall-clock time.
            ZoneID.of( "Africa/Tunis" )     // Specify a time zone using proper `Continent/Region` format. Never use 2-4 letter pseudo-zone such as `PST` or `EST` or `IST`.
        )                                   // Returns a `ZonedDateTime` object.
    )                                       // Returns a `YearQuarter` object.
    .atDay( 1 )                             // Returns a `LocalDate` object, the first day of the quarter.
;

By the way, if you can phase out your use of java.util.Date altogether, do so. It is a terrible class, along with its siblings such as Calendar. Use Date only where you must, when you are interfacing with old code not yet updated to java.time.

About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?

*

*Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later  - Part of the standard Java API with a bundled implementation.

*

*Java 9 adds some minor features and fixes.

*Java SE 6 and Java SE 7

*

*Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.

*Android

*

*Later versions of Android bundle implementations of the java.time classes.

*For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

A: The answer didn't work for me on Java 10 storing util.Date in UTC.
Date.toInstant() seems to convert the EpochMillis into the local time zone of the server.
ZDT.ofInstant(instant, zoneId) and instant.atZone(zoneId) seem to just tag on a TZ on the instant, but it's already messed up with.
I couldn't find a way to prevent Date.toInstant() from messing with the UTC time with the system time zone.
The only way I found to work around this was to go through the sql.Timestamp class:
new java.sql.Timestamp(date.getTime()).toLocalDateTime()
                                      .atZone(ZoneId.of("UTC"))
                                      .withZoneSameInstant(desiredTZ)


text:
Q: Cuál es el mejor tipo de dato para almacenar nombres, direcciones, entre otros Estoy aprendiendo sobre SQL y me ha surgido una duda, en búsqueda de tener creados de manera correcta los tipos de dato.
Me gustaría saber que tipo de dato recomiendan para almacenar:

*

*Nombres

*Direcciones

*Teléfonos

*Correos Electrónicos

*Fechas

*Imágenes

*Números enteros

*Números con decimal

Si tienen algún artículo que hable de esto, también estaría agradecido.

A: Según mi experiencia y limitándome al listado que diste serían de la siguiente forma:

*

*Nombres -> Varchar(longitud)

*Direcciones -> Varchar(longitud)

*Teléfonos -> Varchar o Int, aunque en realidad setear un teléfono como número es un tanto innecesario ya que nunca usarás una operación
  matemática (me refiero a sumar, restar, etc) con un teléfono.

*Correos -> Varchar(longitud)

*Fechas -> Date o Datetime, dependiendo lo que requieras y la versión de SQL que estés utilizando.

*Imágenes -> Varchar(longitud)

*Números enteros -> Int o BigInt dependiendo el límite del número a ingresar.

*Números con decimal -> Decimal

Podría ser útil también el tipo BIT que funciona como un true/false, aunque en la base se almacena como 0 y 1.
Los tipos de datos que específique estan pensados para SQL 2008, creo que añadieron más tipo de datos para versiones posteriores pero ignoro cuales son.
Te dejo el artículo Tipos de datos (Transact-SQL) (en español) para que te interiorices más

A: Según yo utilizo esos datos, los defino de la siguiente forma:

*

*Nombres (string)

*Direcciones (string)

*Teléfonos (string)

*Correos Electrónicos (string)

*Fechas (string)

*Imágenes (string (Si le pasas una URL))

*Números enteros (int)

*Números con decimal (float)

Espero que te pueda servir de ayuda!

A: Si el motor de base de datos que se vaya a utilizar tiene un tipo de dato nativo para almacenar fechas, usarlo para almacenar las fechas.
Hay que determinar si para ese motor de base de datos las fechas son solo el año-mes-día o si se incluye el componente de hora-minuto-segundo.
Es importante anotar que una cosa es cómo una base de datos almacena un valor de tipo FECHA y otra muy diferente como se visualiza en pantalla o se imprime esa fecha.
En el caso de Oracle, (SQL y el lenguage PL/SQL) existe el tipo de dato DATE (tanto para columnas como para variables) con el cual se almacena una fecha con la hora-minuto-segundo.
El usar un tipo de dato "STRING" para almacenar y manejar fechas es inconveniente  ya que existen un sinúmero de maneras de escribir una cadena (o string) que represente una fecha, que depende fundamentalmente del país y y con los cuales se producen errores al momento de ordenar, buscar y comparar fechas.
Ejemplo:
Si una fecha es 10 de agosto de 2018, entonces hay estas alternativas:

*

*Para Estados Unidos y otros países es "08/10/2018" (el mes primero)

*En Europa es común escribirla como "10/08/2018"    (el día primero)

*O escribir el mes con un texto como "30-agosto-2018"

Ejemplo de error al usar strings para representar una fecha:
Si hay 2 cadenas que representan una fecha almacenada como día/mes/año:

*

*"04/01/2017" (para el 04 de enero de 2017)

*

*"03/02/2018" (para el 03 de marzo de 2018)

Se hace una comparación de los 2 strings y cuál será menor?
La respuesta es que por comparación de strings el menor es "03/02/2018" lo cual es errado!! ya que desde el punto de vista que el string representa una fecha la cual es MAYOR que la fecha "04/01/2017".
Si definitivamente hay que usar texto (o strings) para almacenar una fecha la recomendación es usar la norma ISO 8601, con la cual el string SIEMPRE es:

Para año-mes-dia es "AAAAMMDD" o "AAAA-MM-DD"      y con
  hora-minuto-segundo es "AAAAMMDDTHHMMSS" ó "AAAA-MM-DDTHH:MM:SS" ó
  "AAAA-MM-DD HH:MM:SS"

Los años son de 4 dígitos
Los meses son de 2 dígitos, de 01 al 12
Los días son de 2 dígitos, de 01 al último día correspondiente mes (28,29, 30,31).
Las horas son en formato militar de las 00 a las 23
Los minutos son de 2 dígitos, de 00 al 59
Los segundos son de 2 dígitos, del 00 al 59

A: Creo que tu pregunta es por el lado de la BD mas no por el lenguaje, por ende seria lo recomendado asi:

*

*Nombres nvarchar (cant)

*Direcciones nvarchar (cant)

*Teléfonos nvarchar (cant)

*Correos Electrónicos nvarchar (cant)

*Fechas date()

*Imágenes nvarchar (Si le pasas una URL)

*Imágenes binary(Si le pasas una URL)

*Números enteros int(cant)

*Números con decimal decimal()

// con los numero, solo si vas a hacer operaciones matematicas es
  recomendable ponerlos en tipo int de lo contrario en char

Espero que te servir !, me cunetas...

A: En SQL en general, para los nombres, direcciones, teléfonos, correos electrónicos yo usaría String o VARCHAR. Omitiendo lo obvio como en nombres y direcciones, el caso de los teléfonos siempre hay personas que diseñan sus bases de datos con NUMERIC o INT pero siempre existe el problema con los teléfonos con ceros al inicio e inclusive con números de identificación (DNI o cedula). Para el caso de los emails o correos electrónicos te recomiendo VARCHAR de igual manera que con los nombres o direcciones, controlando el registro de que sean solo emails, desde tu aplicación o programa, y no desde tu BD, es una tarea menos para la BD y la aplicación o programa la puede controlar desde que se registra en el formulario.
Para el caso de las fechas a menos que necesites enteramente la fecha con hora utiliza DATETIME pero si solo es necesario para tu registro en BD la fecha utiliza tipo DATE. Manejar luego consultas en SQL con datos tipo DATETIME es complicado y necesitas siempre convertidores o parsear la data en tu programa.
Esto en base a la experiencia. Saludos


text:
Q: webpack config proxy request body logging Webpack dev server proxy config documentation seen here:
https://webpack.js.org/configuration/dev-server/#devserver-proxy
says it uses http-proxy-middleware:
https://github.com/chimurai/http-proxy-middleware#http-proxy-events
Using the onProxyRes function documented in the above link I do the following:
function onProxyRes(proxyRes, req, res) {
    proxyRes.headers['x-added'] = 'foobar';     // add new header to response
    delete proxyRes.headers['x-removed'];       // remove header from response
    console.log(req.headers)                    // log headers
    console.log(req.body)                  // undefined
    console.log(proxyReq.body)             // undefined
}

My problem, although everything else works great - I cannot log the Request Body - it returns undefined
Anyone know how to read the request body for debugging purposes? Do I somehow need to use the npm body-parser module? If so, how? thx

A: I solved a similar problem using body-parser.
I was trying to modify the request body before sending it to server, and it caused the request to hang maybe because, altering the body, the Content-Length of the request was no more matching (causing it to be truncated).
The solution was "resizing" Content-Length before writing the new request body:
var bodyParser = require('body-parser');

devServer: {
    before: function (app, server) {
        app.use(bodyParser.json());
    },
    onProxyReq: function (proxyReq, req, res) {
        req.body = {
            ...req.body,
            myProperty: "myPropertyValue"
        };

        const body = JSON.stringify(req.body);

        proxyReq.setHeader('Content-Length', Buffer.byteLength(body));

        proxyReq.write(body);
    }
}

Not sure, but in your case it could be that the request has been truncated by adding/removing headers, causing it to hang.

A: I tried logging the request with the express body-parser module but it caused the requests to hang. Using the body module to log the request body fixed it.
const anyBody = require('body/any')
onProxyReq(proxyReq, req, res) {
    anyBody(req, res, function (err, body) {
        if (err) console.error(err)
        console.log(body)
    })
})

Note that I also used this same approach inside express as follows:
app.use((req, res, next) => {
    anyBody(req, res, function (err, body) {
        if (err) console.error(err)
        console.log(body)
    })
    next()
})


text:
Q: code not working for bigger range of numbers So my problem is that I wrote this code that takes two numbers and writes all numbers between those numbers (including the given two numbers). The code works for the numbers 4 and 7, it prints out "4 5 6 7" but when the 2nd number is a little bigger than the first number for example for the numbers 6 and 14 the code does nothing. If someone could explain to me why it is like this and how could I solve this problem I would-be so happy.

function calculate() {
  var start = document.getElementById("number1").value;
  var end = document.getElementById("number2").value;
  var answer = "";
  for (var i = start; i <= end; i++) {
    answer = answer + i + " ";
  }
  document.getElementById("answer2").innerHTML = answer;
}
<input type="number" id="number1">
<input type="number" id="number2">
<button onclick="calculate()">Pokaż</button>

A: The value property returns a string representing the value of the value attribute of a text field.
To compare start and end you need to convert them into numbers (e.g. with the Number primitive wrapper), else the string 6 will be (alphabetically) greater than the string 14.

function calculate() {
  var start = Number(document.getElementById("number1").value);
  var end = Number(document.getElementById("number2").value);
  var answer = "";
  for (var i = start; i <= end; i++) {
    answer = answer + i + " ";
  }
  document.getElementById("answer2").innerHTML = answer;
}
<input type="number" id="number1">
<input type="number" id="number2">
<button onclick="calculate()">Pokaż</button>

A: That's the alternative solution with parseInt in for

function calculate() {
  var start = document.getElementById("number1").value;
  var end = document.getElementById("number2").value;
  var answer = "";
  for (var i = parseInt(start); i <= parseInt(end); i++) {
    answer = answer + i + " ";
  }
  document.getElementById("answer2").innerHTML = answer;
}
<input type="number" id="number1">
<input type="number" id="number2">
<button onclick="calculate()">Pokaż</button>


text:
Q: I Can't See the Highlighted State of My Custom When I Push it To Get a New View I am reading many posts about UIViewController managing but I can't find the solution to my problem. I am making an iPhone game. I have three screens (menu, game play and scores) constructed into the Interface Builder and from three UIViewController classes. Into the main menu I have two custom buttons that allow to go to the game play screen or to the scores screen. Actually I am using the next method to navigate but when I use it, even it changes the screen and takes me to the game play, I can't see the highlighted state of the custom button. Must I change the views like this? How can I show the custom state of my buttons? How can I show an animation while the views are changing?
- (IBAction)gotoPlayViewController:(id)sender {

 //Navigation logic may go here.
 PlayViewController *playViewController = [[PlayViewController alloc] initWithNibName:@"PlayViewController" bundle:nil];

 self.view = playViewController.view;

 [playViewController release];
}

Thanks for readding.

A: You want to use UINavigationController, don't you?

The UINavigationController class implements a specialized view controller that manages the navigation of hierarchical content. This class is not intended for subclassing. Instead, you use instances of it as-is in situations where you want your application's user interface to reflect the hierarchical nature of your content. This navigation interface makes it possible to present your data efficiently and also makes it easier for the user to navigate that content.

Here is a nice tutorial.
Here is the class reference.

UINavigationController also provides a very easy way to add the slide transition you want.

Have fun!


text:
Q: Matplotlib step plot rotation I'm trying to rotate correctly the matplotlib step plot. First I swapped the x and y axes and reversed the y axis. I made the step plot again. However, the direction of the step line (blue color) was not as desired in the right picture and the red colored stepping line is the superimposed rotated image of the left picture. Here is my code
import numpy as np
import matplotlib.pyplot as plt

x = np.arange(14)
y = np.sin(x / 2)

fig, (ax, bx) = plt.subplots(nrows=1, ncols=2, figsize=(11.5, 5.5))
fig.subplots_adjust(left=0.08, bottom=0.13, top=0.98, right=0.97, wspace=0.2, hspace=0.0)

ax.step(x, y, where='mid', c='r')
ax.plot(x, y, 'o--', color='grey', alpha=0.3)

bx.invert_yaxis()
bx.step(y, x, where='pre', c='b')
bx.plot(y, x, 'o--', color='grey', alpha=0.3)

plt.show()

I am trying to make red colored step plot as shown in the right picture. How can I do this?

A: The desired step-style can be obtained by shifting a little bit the second coordinates and using where=pre.
def plot_step_invert_mid(x, y, *args, **kwargs):
    y_new = np.insert(y, 0, y[0])
    y_new = 0.5 * (y_new[1:] + y_new[:-1])
    x_new = np.append(x, x[-1])
    y_new = np.append(y_new, y[-1])
    plt.step(x_new, y_new, where="pre", *args, **kwargs)

fig, (ax, bx) = plt.subplots(nrows=1, ncols=2, figsize=(11.5, 5.5))
fig.subplots_adjust(left=0.08, bottom=0.13, top=0.98, right=0.97, wspace=0.2, hspace=0.0)

ax.step(x, y, where="mid", c='r')
ax.plot(x, y, 'o--', color='grey', alpha=0.3)

bx.invert_yaxis()
plot_step_invert_mid(y, x)
bx.plot(y, x, 'o--', color='grey', alpha=0.3)

A: I suggest you to interpolate your original curve with scipy.interpolate.interp1d rather then use the matplotlib.pyplot.step method of plotting. This because interp1d generates a new vector that you can manipulate as you wish.
In the code below:

*

*x and y are the original curve vectors (length 14)

*xx and yy are the original curve interpolated vectors (length N)

In order to rotate the plot you can simply swap x with y and xx with yy in plt.plot:
import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import interp1d

x = np.arange(14)
y = np.sin(x/2)

N = 1000
xx = np.linspace(0, 13, N)
yy = interp1d(x, y, kind = 'nearest')(xx)

fig, (ax, bx) = plt.subplots(nrows = 1, ncols = 2, figsize = (11.5, 5.5))
fig.subplots_adjust(left = 0.08, bottom = 0.13, top = 0.98, right = 0.97, wspace = 0.2, hspace = 0.0)

ax.plot(xx, yy, 'r')
ax.plot(x, y, 'o--', color = 'grey', alpha = 0.3)

bx.invert_yaxis()
bx.plot(yy, xx, 'r')
bx.plot(y, x, 'o--', color = 'grey', alpha = 0.3)

plt.show()


text:
Q: ASP.NET MVC 2 routing problems with string I want to add a simple route to my webapp, but it just doesn't work and i don't know why
code in global.asax.cs:
routes.MapRoute(
            "BrowseGenre",
            "{controller}/{action}/{genre}",
            new {controller = "Store", action = "Browse", genre = UrlParameter.Optional}
        );

code in StoreController.cs:
    // GET: /Store/Browse
    public ActionResult Browse(string genreName)
    {

        var genreModel = storeDB.Genres.Include("Albums").Single(g => g.Name == genreName);
        //....

genreName is always null
the actionlinks are generated correctly (like domain.com/Store/Browse/Jazz

A: The action parameter should be called genre instead of genreName (the same way it uis called in your route):
public ActionResult Browse(string genre)

A: change your anonymous type from
 new {controller = "Store", action = "Browse", genre = UrlParameter.Optional}

to
 new {controller = "Store", action = "Browse", genreName = UrlParameter.Optional}

OR
change the argument name in action from "genreName" to "genre" so that name of the member in the anonymous type matches the name of the argument in your action method.


text:
Q: How to pass exit code to a function in bash? let's say I have this logging function in bash .
function report {
    echo "Log message: [$@]  time:  " `date` >> reports.txt
}

And I call it each time I need like this.
report running python
python3 script.py
report python script ended

Now, I would also like to the log message the exist code from script.py
I could obviously do this using report python script ended with $? exit code
but is there a way not to explicitly pass the argument like that, and instead fetch it from withing the function report?
I tried
...
echo "Log message: [$@]  time:  " `date`  with exit code $? >> reports.txt
...

but I always get 0 even if the script failed.

A: $? isn't reset until you run another command, so you should be able to capture it as the first action of report:
report () {
    status=$?
    ...
    printf 'Log message: [%s] time: %s with exit code %d\n' "$1" "$(date)" "$status"
}

Note that you should pass the log message as a single argument, rather than as an arbitrary sequence of words.
report "running python"
python3 script.py
report "python script ended"

It might be cleaner, though, to have the exit status be passed directly as an argument, for example, python3 script.py; status=$?; ...; report "python script ended" "$status". This frees you from having to make sure that report is called immediately after the command whose status you want to log. (This also allows you to ignore status if it doesn't apply, as with the call prior to script.py.)


text:
Q: Probleme to reload a ReactLeaflet map I got a problem with my map. A react-leaflet map.
It's displayed when I load my website on it. But other way, like on click on a link, it doesn't.
I just load the tiles at the top left, one by one when I scroll.
Did someone have this problem before? Or did someone have an idea?
An Example :
http://www.noelshack.com/2019-02-1-1546872914-capture.png
import React, { Component } from 'react';
import { Map, Marker, Popup, TileLayer } from 'react-leaflet';
import 'leaflet/dist/leaflet.css';
import './local_leaflet.css';

const mapState = {
  lat: 49.4431,
  lng: 1.0993,
  zoom: 10,
  visible: true,
  url: 'https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png',
};

export default () => (

    <Map center={[mapState.lat, mapState.lng]} zoom={mapState.zoom}>
      <TileLayer url={mapState.url} />
    </Map>

);

I already try componentDidMount, componentDidUpdate, componentWillUnmount ... and nothing worked.

A: I resolve my prob.
I put a key in my MAP render, like this :
  render ()
  {
    return (

        <Map key={this.state.keyMAP} center={[this.mapState.lat, this.mapState.lng]} zoom={this.mapState.zoom}>
          <TileLayer url={this.mapState.url} />
        </Map>

    );
  }

It's a random key which is in my state. Random, like this.
state = {
   keyMAP: Math.random(),
};

Hope it'll help someone else ! :)


text:
Q: Thread id not showing in logs My applications listens to messages on a queue and then publishes results to Tibco subject. We have written a message listener which is called via "onMessage" method of "MessageListener"
Problem i am facing is that all the threads in logs show same thread name i.e. "TIBCO EMS Session Dispatcher (21367271)". And its making it very difficult to track which thread is doing what.
My log4j expression is "%d{HH:mm:ss,SSS} %-5p %c{1} [%t] - %m%n" .
What change do i need to make to get proper thread id?
EDIT:
I want to be able to differentiate between log messages printed for processing of different messages. At present i can't do that with thread name.

A: You are free to set the name of the thread as you like.  You could do:
private static AtomicInteger count = new AtomicInteger(0);

public void onMessage(Message message)
{
  String oldName = Thread.currentThread().getName();
  Thread.currentThread.setName("my-thread-" + count.getAndIncrement())

  try
  {
    // ... existing code ...
  }
  finally
  {
    Thread.currentThread().setName(oldName);
  }
}

An alternate to the atomic integer for uniquely identifying the thread would be to use the identity hash code:
Thread.currentThread.setName("my-thread-" + System.identityHashCode());


text:
Q: Dynamic SQL versus using the model We started using COGNOS about 3 years ago.  We have used COGNOS 8 and are now on COGNOS 10.  We are constantly being told that using dynamic SQL queries instead of using the COGNOS model is extremely bad in that it causes performance issues and that it is not recommended by IBM.  We have never had a problem that was specific to dynamic SQL and they perform just as good as reports that use the model.
Are there any performance issues or drawbacks that are specific to dynamic SQL queries?  Is it really recommended by IBM that they not be used?
I understand that the model is great for at-hoc reporting and for users who do not know SQL.  But for developers, the dynamic SQL seems to be a better option especially if they do not have any control over the COGNOS model.  (We have to request and document needed changes the model)
Appreciate your comments/feedback.

A: Manually building your queries with Dynamic SQL may we worse for many reasons (extensability, maintainability, reusability), but performance wise it is only limited by your own SQL query writing abilities.  This means in some cases it will be faster than using the Cognos model.  There are no speed disadvantages to using dynamic SQL.
That being said, you are missing alot of the benefits of Cognos if you are not leveraging the model.  Your ability to maintain consistency, make broad changes without rewriting reports, and quickly produce new reports will be severely diminished with Dynamic SQL.
If your environment is small, dynamic sql may meet your needs.  Especially for odd one-off reports that use tables and relationships that have little to do with your other reports.  Or if there is a specific way you want to force indexes to be used, this may be achieved with dynamic sql.
Edit:  It is important to note that criteria established in Report Studio Filters will not be passed into your Dynamic SQL queries until after the data has been retrieved.  For large data sets this can be extremely inefficient.  In order to pass criteria into your Dynamic SQL from your prompts, use #prompt('yourPromptVariableNamehere')# or #promptmany('yourMultiSelectPromptVariablehere')#.  A rule of thumb is this, run your Dynamic SQL query outside of cognos and see how much data is being returned.  If you have a giant sales query that at a minimum needs to be filtered on date or branch, put a Prompt in the prompt page to force the user to select a specific date/period/date range/branch/etc. into your prompts, and add the criteria into your Dynamic SQL Statement with the prompt/promptmany syntax.  Prompts can still be used as regular filters inside your Report Studio queries, but all of that criteria is filtered AFTER the result set is returned from the database if you are using Dynamic Queries without prompt/promptmany.

A: When it comes to performance, when you introduce dynamic SQL, it wont be able to use the caching abilities that Cognos offers (system wise).
On the other hand, its obvious that you can tune the SQL better than the machine.
I wouldn't say dynamic SQL can cause performance issues in general.
IBM doesn't recommend dynamic SQL because only with a proper model, build with framework manager, you can use all the features of Cognos.


text:
Q: Undefined offset: $result = db2_getsub( array('campaigns_id' => $this_id) );

if (!is_null($result))
    {
          $numsub = 0;
    while ( $row = $result->fetch_object() )
        {
            $numsub = $numsub +1;
            array_push($arrFornavn, $row->sub_name);
                    array_push($arrEtternavn, $row->sub_code);
                    }
          $formcountfld=$numsub;
                }
        else
        {
        $numsub=1;
        $formcountfld=1;
        }

            $i = 1;

            if (1==1) {

                for ($i = 1; $i <= $numsub; $i++)
                {
        ?>

              <input type="text" id="fornavn_<?= $i ?>" name="fornavn_<?= $i ?>" value="<?= $arrFornavn[$i-1] ?>" />

              <input type="text" id="etternavn_<?= $i ?>" name="etternavn_<?= $i ?>" value="<?= $arrEtternavn[$i-1] ?>" />

          <?php

                    }

            } else {

        ?>

I am getting an error as Notice: Undefined offset: 0  can anybody help .thanks in advance looking forward for an answer.

A: It means you are trying to access a value that does not exist, which in your case is $arrEtternavn[0].
Small example:
$array = array();
$array[1] = 'one';
$array[2] = 'two';
$array[4] = 'four';

echo $array[0]; // This will give a notice, $array[0] does not exist.
echo $array[1]; // 'one'
echo $array[2]; // 'two'
echo $array[3]; // This will give a notice, $array[3] does not exist.
echo $array[4]; // 'four'

A very easy fix would me something like this:
value="<?= isset($arrEtternavn[$i-1]) ? $arrEtternavn[$i-1] : '' ?>"

This is a short elseif-> (condition) ? if_True : if_False
Edit: I'd like to add that a notice isnt a very bad thing. No notices would be the best thing, but it should not keep you awake at night.

A: My guess would be this... In the case where $result is empty you are setting $numsub = 1 in your else clause. However, in this case you have not added anything to the array. Your later loop however defines the continuing condition as $numsub <= 1, so will execute and try to print out array index 0, which because $result was NULL doesn't contain because the array is empty.
Changing your for loop to be
for ($i = 0; $i < $numsub; $i++) // Notice now strictly less than
{

          <input type="text" id="fornavn_<?= $i+1 ?>" name="fornavn_<?= $i+1 ?>"
                                              ^^^^                       ^^^^
                 value="<?= $arrFornavn[$i] ?>" />
                                        ^^^

          <input type="text" id="etternavn_<?= $i+1 ?>" name="etternavn_<?= $i+1 ?>"
                                               ^^^^                       ^^^^
                  value="<?= $arrEtternavn[$i] ?>" />
                                           ^^^

As Martijn suggests, you can always use isset() to find out if an array index exists.  From the logic you've implemented I think you're trying to assure that the array index in that loop is in fact guaranteed to be set, so I'm guess its the small logic error described above that causing the problem.
Hope it helps...


text:
Q: replacing multiple line with singe word using perl [root@localhost test]# perl -e 'undef $/;while (<>) {s/\<|[a-zA-Z]|\>|\//one/gs;print}' file

oneoneoneoneoneoneoneoneoneoneoneone

oneoneoneoneoneoneoneoneoneoneoneone

oneoneoneoneoneoneoneoneoneoneoneone

I need only one need to get print
[root@localhost test]# cat file.input
                   <tag>X</tag>
                   <tag>Y</tag>
                   <tag>Z</tag>

[root@localhost test]# cat file.output
                    one

[root@localhost test]#

A: Here is some explanation:
 <                             # Opening tag
 ( \w+ )                       # (1), tag name
 \s*                           # Whitespaces: tab,space,newlines, etc..
 > [^>]*? </ \1 \s* >          # Some text then Closing tag
 (?:                           # Cluster group
      \s*                           # Whitespaces: tab,space,newlines, etc..
      <                             # Repeat as above, with tag name
      \1                            #    ""
      \s*                           #    ""
      > [^>]*? </ \1 \s* >          #    ""
 )*                            # End cluster, do 0 to many times


text:
Q: Is there a transcript of Uhura's conversation with the Klingons? In Star Trek Into Darkness, there is a scene on Kronos where Uhura leaves the shuttle to converse with the Klingons. What was the conversation about? Is there a transcript?

A: You can see a copy of the transcript, along with the English and German translations, at this link.
The link is to a Google+ post containing a scan of the transcript which was released by Marc Okrand (the creator of the Klingon language) through the annual qepHom (a meeting of Klingon speakers) in Germany. The scan also includes an explanation of the new vocabulary used in the dialogue. It's as official as it gets.
From the link above:

Uhura:
jIvuylaH. jIve'. jIyI'. ghach jIvvo' naH. DaH pIghvamDaq So''eghtaH. 'ej Dojmey wID - vInDa'ma' peq.
  I am here to help you. With respect. There is a criminal hiding in these ruins. He has killed many of our people.
Klingon:
toH, Hey Humanpu'. qatlh DISaH?
  Why should I care about a human killing humans?
Uhura:
potlhmo' batlh, vIqawba'. 'ej chIvo' neH chIw vum'e'. Qob lIb bam SoH chuDlI' je.
  Because you care about honor. And this man has none. You and your people are in danger.

A:
Uhura: "I am here to help you. With Respect. There is a criminal hiding in these ruins. He has killed many of our people."
Klingon: "Why should I care about a human killing humans?"
Uhura: "Because you care about honor. And this man has none. You and your people are in danger."

(From the subtitles.)


text:
Q: OpenCV parallel splitting I have a three channel image and want to split it with the function split.
void function(Mat modifiedImage, Mat originalImage, int rows, int cols)
{

   Mat channels[3];
   cv::split(originalImage, channels);

   Mat blue = channels[0];
   Mat green = channels[1];
   Mat red = channels[2];

}

I heard that the split function can be used in a parallel mode. How can I do this?


text:
Q: jsf 1.2 two scopes in the same managed-bean is it possible to have the same Bean with two different scopes in JSF 1.2??
What I mean is:
<managed-bean>
    <managed-bean-name>beanOne</managed-bean-name>
    <managed-bean-class>files.bean.BeanOne</managed-bean-class>
    <managed-bean-scope>session</managed-bean-scope>
    <managed-property>
            <property-name>someConfiguration</property-name>
            <value>#{configurationBean}</value>
    </managed-property>
</managed-bean>

<managed-bean>
    <managed-bean-name>beanOne</managed-bean-name>
    <managed-bean-class>files.bean.BeanOne</managed-bean-class>
    <managed-bean-scope>request</managed-bean-scope>
    <managed-property>
            <property-name>someParam</property-name>
            <value>#{param.value}</value>
    </managed-property>
</managed-bean>

Obviously, this solution doesn't work but it's what I want to do without having the same BeanOne two times with different names!
Thanks!! ;)

A: Its not possible to have same bean with two different scopes. In your case, please give a different name to your other bean and have two different beans (one in request scope and the other in session scope)
To know more you can refer to some good posts by BalusC
Link1 & Link2


text:
Q: How to get the current String Value from array in objective C I am new in iOS and I am facing problem regarding to get current value of string from array.
My code is like this
loginStatusHS = [[NSString alloc] initWithBytes: [myNSMDatalatetudeFromServer mutableBytes] length:[myNSMDatalatetudeFromServer length] encoding:NSUTF8StringEncoding];
    NSLog(@"loginStatus =%@",loginStatusHS);
    NSError *parseError = nil;
    NSDictionary *xmlDictionary = [XMLReader dictionaryForXMLString:loginStatusHS error:&parseError];
    NSLog(@"JSON DICTIONARY = %@",xmlDictionary);
    recordResultHS = [xmlDictionary[@"success"] integerValue];
    NSLog(@"Success: %ld",(long)recordResultHS);
    NSDictionary* Address=[xmlDictionary objectForKey:@"soap:Envelope"];
    NSLog(@"Address Dict = %@",Address);
    NSDictionary *new =[Address objectForKey:@"soap:Body"];
    NSLog(@"NEW DICT =%@",new);
    NSDictionary *LoginResponse=[new objectForKey:@"HS_GetResponse"];
    NSLog(@"Login Response DICT =%@",LoginResponse);
    NSDictionary *LoginResult=[LoginResponse objectForKey:@"HS_GetResult"];
    NSLog(@"Login Result =%@",LoginResult);
    if(LoginResult.count>0)
    {
        NSLog(@"Login Result = %@",LoginResult);
        NSLog(@"Login Result Dict =%@",LoginResult);
        NSString *teststr =[[NSString alloc] init];
        teststr =[LoginResult objectForKey:@"text"];
        NSLog(@"Test String Value =%@",teststr);
        NSString *string = [LoginResult valueForKey:@"text"];
        NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
        responseletetudedict = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        NSLog(@"Latetude Dictionary =%@",responseletetudedict);
        idlatetudearray=[[NSMutableArray alloc]init];
        idlatetudearray=[responseletetudedict valueForKey:@"City"];

        NameHSArray=[[NSMutableArray alloc] init];
        NameHSArray=[responseletetudedict valueForKey:@"Name"];
        AddressHSArray=[[NSMutableArray alloc] init];
        AddressHSArray=[responseletetudedict valueForKey:@"Address"];
        FacilitiesHSArray=[[NSMutableArray alloc] init];
        FacilitiesHSArray=[responseletetudedict valueForKey:@"Facilities"];
        PhoneNoHSArray=[[NSMutableArray alloc] init];
        PhoneNoHSArray=[responseletetudedict valueForKey:@"Phoneno"];
        FaxnoHSArray=[[NSMutableArray alloc] init];
        FaxnoHSArray=[responseletetudedict valueForKey:@"Faxno"];
        LatitudeHSArray=[[NSMutableArray alloc] init];
        LatitudeHSArray=[responseletetudedict valueForKey:@"Latitude"];
        LongitudeHSArray=[[NSMutableArray alloc] init];
        LongitudeHSArray=[responseletetudedict valueForKey:@"Longitude"];
        TypeHSArray=[[NSMutableArray alloc] init];
        TypeHSArray=[responseletetudedict valueForKey:@"Type"];

        for (int i=0; i<NameHSArray.count; i++) {
            double LatitudeDouble = [LatitudeHSArray[i] doubleValue];
            double LongitudeDouble = [LongitudeHSArray[i] doubleValue];
            CLLocationCoordinate2D position = CLLocationCoordinate2DMake(LatitudeDouble, LongitudeDouble);
            GMSMarker *marker = [GMSMarker markerWithPosition:position];
            marker.title = NameHSArray[i];
            marker.snippet=AddressHSArray[i];
            userData = [[NSArray alloc] initWithObjects:NameHSArray[i], AddressHSArray[i],FacilitiesHSArray[i], PhoneNoHSArray[i],FaxnoHSArray[i], TypeHSArray[i], nil];
            marker.userData = userData;

            if([TypeHSArray[i] isEqualToString:@"ESIC"])
            {
                marker.icon = [UIImage imageNamed:@"mapicon2.png"];
            }
            else
            {
                marker.icon = [UIImage imageNamed:@"mapicon1.png"];
            }
            GMSCameraUpdate *zoomCamera = [GMSCameraUpdate zoomIn];
            [mapView animateWithCameraUpdate:zoomCamera];

            marker.map = mapView;

        }

Add in the Image when I click on Nobel Hospital I call the delegate
  - (void)mapView:(GMSMapView *)mapView didTapInfoWindowOfMarker:(GMSMarker *)marker {
    // your click action

    StringAddress =  marker.snippet;
    StringName = marker.title;

    NSLog(@"Address=%@",StringAddress);
    NSLog(@"Name= %@",StringName);

    lblNamepopup.text=StringName;
    lblAddresspopup.text=StringAddress;

    NSLog(@"User Data Array = %@",userData);

    viewpopup.hidden=NO;
    viewpopup.transform = CGAffineTransformMakeScale(0.01, 0.01);
    [UIView animateWithDuration:0.2 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
        viewpopup.transform = CGAffineTransformIdentity;
    } completion:^(BOOL finished){
        // do something once the animation finishes, put it here
    }];
}

Hear in this delegate I need to get the current name of string address.But hear I am getting the Last value means the string get override. How can I get the value which I have click from array. Thanks in Advance!

A: You can get index as follow
-(void)mapView:(GMSMapView *)mapView didTapInfoWindowOfMarker:(GMSMarker *)marker
{
    NSInteger index = [NameHSArray indexOfObject:marker.title];
    NSLog(@"%ld",(long)index);
}

--- EDIT ---
You can also use

*

*i found some reference from library.

*Note that userData should not hold any strong references to any Maps

*objects, otherwise a loop may be created (preventing ARC from releasing
objects).

NOTE :-
You can pass data through snippet but snippet show data into info window. so you creates a custom info window and show data as you want.
like this,
NSArray * userData = [NSArray alloc] initWithObjects:FacilitiesHSArray[i], PhoneNoHSArray[i],FaxnoHSArray[i], nil];
NSString *userDataString = [userData componentsJoinedByString:@";"];
marker.snippet = userDataString;

retrive
like this,
 NSString *userDataString = marker.snippet;
 NSArray *array = [userDataString componentsSeparatedByString:@";"];
 NSLog(@"%@",array);

You can Do Like this
- (void)mapView:(GMSMapView *)mapView didTapInfoWindowOfMarker:(GMSMarker *)marker {
    // your click action

    StringAddress =  marker.snippet;
    StringName = marker.title;

    NSInteger indexCheck = [NameHSArray indexOfObject:marker.title];
    NSLog(@"Curret Index =%ld",(long)indexCheck);

    StringName=[NSString stringWithFormat:@"%@",[NameHSArray objectAtIndex:indexCheck]];
    StringAddress=[NSString stringWithFormat:@"%@",[AddressHSArray objectAtIndex:indexCheck]];
    StringPhoneNo=[NSString stringWithFormat:@"%@",[PhoneNoHSArray objectAtIndex:indexCheck]];

    NSLog(@"Address=%@",StringAddress);
    NSLog(@"Name= %@",StringName);
    NSLog(@"Phone No =%@",StringPhoneNo);

    lblNamepopup.text=StringName;
    lblAddresspopup.text=StringAddress;
}


text:
Q: Convert RAW images to BMP format I received a .raw frame format (here is a sample) which contains the raw pixel values of a frame. And I've been told I can convert it to an image (.bmp or .png) using FFMpeg using following command. However, when trying, it doesn't work.
dd bs=16 dumpB4EncodeHLSAfterEncodeBuf1200IP_TS/dumpedYuv/image-1140.raw |  ffmpeg -f rawvideo -video_size 2160 2160 -pixel_format nv12 -i - yuv.bmp

What is the problem? Is there any ways to avoid use of dd and purely do it from FFmpeg?
Here is the error:
dd: unrecognized operand 'frame.raw'
Try 'dd --help' for more information.
ffmpeg version 3.4.8-0ubuntu0.2 Copyright (c) 2000-2020 the FFmpeg developers
  built with gcc 7 (Ubuntu 7.5.0-3ubuntu1~18.04)
  configuration: --prefix=/usr --extra-version=0ubuntu0.2 --toolchain=hardened --libdir=/usr/lib/x86_64-linux-gnu --incdir=/usr/include/x86_64-linux-gnu --enable-gpl --disable-stripping --enable-avresample --enable-avisynth --enable-gnutls --enable-ladspa --enable-libass --enable-libbluray --enable-libbs2b --enable-libcaca --enable-libcdio --enable-libflite --enable-libfontconfig --enable-libfreetype --enable-libfribidi --enable-libgme --enable-libgsm --enable-libmp3lame --enable-libmysofa --enable-libopenjpeg --enable-libopenmpt --enable-libopus --enable-libpulse --enable-librubberband --enable-librsvg --enable-libshine --enable-libsnappy --enable-libsoxr --enable-libspeex --enable-libssh --enable-libtheora --enable-libtwolame --enable-libvorbis --enable-libvpx --enable-libwavpack --enable-libwebp --enable-libx265 --enable-libxml2 --enable-libxvid --enable-libzmq --enable-libzvbi --enable-omx --enable-openal --enable-opengl --enable-sdl2 --enable-libdc1394 --enable-libdrm --enable-libiec61883 --enable-chromaprint --enable-frei0r --enable-libopencv --enable-libx264 --enable-shared
  libavutil      55. 78.100 / 55. 78.100
  libavcodec     57.107.100 / 57.107.100
  libavformat    57. 83.100 / 57. 83.100
  libavdevice    57. 10.100 / 57. 10.100
  libavfilter     6.107.100 /  6.107.100
  libavresample   3.  7.  0 /  3.  7.  0
  libswscale      4.  8.100 /  4.  8.100
  libswresample   2.  9.100 /  2.  9.100
  libpostproc    54.  7.100 / 54.  7.100
pipe:: Invalid data found when processing input

And if I use ffmpeg directly:
ffmpeg -video_size 2160x2160 -pixel_format nv12 -i frame.raw yuv.bmp

I will get this error:
ffmpeg version 3.4.8-0ubuntu0.2 Copyright (c) 2000-2020 the FFmpeg developers
  built with gcc 7 (Ubuntu 7.5.0-3ubuntu1~18.04)
  configuration: --prefix=/usr --extra-version=0ubuntu0.2 --toolchain=hardened --libdir=/usr/lib/x86_64-linux-gnu --incdir=/usr/include/x86_64-linux-gnu --enable-gpl --disable-stripping --enable-avresample --enable-avisynth --enable-gnutls --enable-ladspa --enable-libass --enable-libbluray --enable-libbs2b --enable-libcaca --enable-libcdio --enable-libflite --enable-libfontconfig --enable-libfreetype --enable-libfribidi --enable-libgme --enable-libgsm --enable-libmp3lame --enable-libmysofa --enable-libopenjpeg --enable-libopenmpt --enable-libopus --enable-libpulse --enable-librubberband --enable-librsvg --enable-libshine --enable-libsnappy --enable-libsoxr --enable-libspeex --enable-libssh --enable-libtheora --enable-libtwolame --enable-libvorbis --enable-libvpx --enable-libwavpack --enable-libwebp --enable-libx265 --enable-libxml2 --enable-libxvid --enable-libzmq --enable-libzvbi --enable-omx --enable-openal --enable-opengl --enable-sdl2 --enable-libdc1394 --enable-libdrm --enable-libiec61883 --enable-chromaprint --enable-frei0r --enable-libopencv --enable-libx264 --enable-shared
  libavutil      55. 78.100 / 55. 78.100
  libavcodec     57.107.100 / 57.107.100
  libavformat    57. 83.100 / 57. 83.100
  libavdevice    57. 10.100 / 57. 10.100
  libavfilter     6.107.100 /  6.107.100
  libavresample   3.  7.  0 /  3.  7.  0
  libswscale      4.  8.100 /  4.  8.100
  libswresample   2.  9.100 /  2.  9.100
  libpostproc    54.  7.100 / 54.  7.100
[image2 @ 0x5605e52bb4c0] Format image2 detected only with low score of 5, misdetection possible!
Input #0, image2, from 'frame.raw':
  Duration: 00:00:00.04, start: 0.000000, bitrate: 1244160 kb/s
    Stream #0:0: Video: rawvideo (NV12 / 0x3231564E), nv12, 2160x2160, 25 tbr, 25 tbn, 25 tbc
Stream mapping:
  Stream #0:0 -> #0:0 (rawvideo (native) -> bmp (native))
Press [q] to stop, [?] for help
[rawvideo @ 0x5605e52bea00] Invalid buffer size, packet size 6220800 < expected frame_size 6998400
Error while decoding stream #0:0: Invalid argument
Finishing stream 0:0 without any data written to it.
Output #0, image2, to 'yuv.bmp':
  Metadata:
    encoder         : Lavf57.83.100
    Stream #0:0: Video: bmp, bgr24, 2160x2160, q=2-31, 200 kb/s, 25 fps, 25 tbn, 25 tbc
    Metadata:
      encoder         : Lavc57.107.100 bmp
frame=    0 fps=0.0 q=0.0 Lsize=N/A time=00:00:00.00 bitrate=N/A speed=   0x
video:0kB audio:0kB subtitle:0kB other streams:0kB global headers:0kB muxing overhead: unknown
Output file is empty, nothing was encoded (check -ss / -t / -frames parameters if used)
Conversion failed!

A: Updated Answer
Now that we know the correct size and format, we can do the conversion easily with ImageMagick:
magick -depth 8 -size 1920x1080 rgb:frame.raw result.png

Or, as you wanted, with ffmpeg:
ffmpeg -y -f rawvideo -s 1920x1080 -pix_fmt rgb24 -i frame.raw  image.bmp

Original Answer
You raw file is either not NV12 or not 2160x2160. NV12 uses 1.5 bytes per pixel, which would mean you should have
2160 * 2160 * 1.5 = 6,998,400 bytes

but you actually have 6,220,800 so there is something wrong with your information - either the file is incomplete, or it is not that format or it is not that size.
If it was NV12, the first 2160x2160 bytes would be the greyscale (or Luminance/Y) channel, but even if we get the first 2160x2160 bytes as greyscale and ignore any trailing colour information, it is still wrong:
head -c $((2160*2160)) frame.raw | magick -depth 8 -size 2160x2160 gray:- image.bmp

Please check and identify the provenance and characteristics of your raw data.


text:
Q: New nodes in Docker swarm don't expose service ports I have a Docker swarm with three nodes to which I added two more nodes. All nodes have the same OS (Ubuntu) and the same Docker version (19.03.6). Everything seems to be alright, all nodes are up, the networks span all nodes, when I scale a service to 4 replicas one of them is put on one of the new nodes.
However, while the service responds when using the IP adresses of the first three nodes, it cannot be accessed on the new ones.
Some observations:

*

*Creating the service with scale=3 is fast, scaling to 4/5 (creating containers on the new nodes) takes half a minute or so

*Exposing container ports on the new hosts directly works properly

*Just now, after removing, re-adding, and then scaling the service, it works better, one of the new nodes replies, the other one only sometimes.

*iptables look identical on all nodes.

What could be the cause of this? How can I debug it?


text:
Q: Error running .jar on a Mac I have 2 files, Project.jar and JavaFile.java, saved in a folder called Project.  I compiled them both successfully using Mac's Terminal as per below:
 javac -cp Project.jar JavaFile.java

However, after trying to run the program, which is supposed to receive 2 arguments, using
 java -cp Project.jar JavaFile argument1 argument2

I get the following error message:
Exception in thread "main" java.lang.NoClassDefFoundError: JavaFile
Caused by: java.lang.ClassNotFoundException: JavaFile
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)

I'm very new to Java and any help would be much appreciated.
Thanks!

A: Ok, so I figured it out... I need to use colon in order to separate the elements:
javac -cp "Project.jar:" JavaFile.java

java -cp "Project.jar:" JavaFile


text:
Q: PHP/MySQL printing 0 inside of int value When I try to enter in an ID field to tag my individual posts (post-id:1932, etc.), the value always prints as 0, instead of the database's value.
The query takes the $_REQUEST's topic variable (generated from clicking a link).
Here is my code:
 <?php

 require_once 'connect.php';

 $topic = $_REQUEST['topic'];

 // Build the SELECT statement
 $select_posts =
 "SELECT p.topic, p.title, p.pic_id, p.snippet, p.content, p.author_id, p.date FROM posts p WHERE p.topic =  '" . $topic . "' OR p.topic='Admin' ORDER BY p.date DESC";

 // Run the Query
 $result = mysql_query($select_posts);

 ?>

 <?php
   $post_count=0;
   while ($post_count<10 && $posts = mysql_fetch_array($result)) {
       $posts_row = sprintf(
           '<entry>
               <headline>%s</headline>
                    <pic><img class=inlinepic src=/Sustenance/assets/post-pics/%d.jpg></pic>
                    <snippet class=on id="%d snippet">%s</snippet>
                    <readmore id="readmore%d" class=on onclick=readmore("%d")>Read More</readmore>
                    <content id="%d" class="less">%s
                        <readmore class=on onclick=readless(%d)>Show Less</readmore>
                    </content>
                    <byline>
                        <by>by</by>
                        <author>%s</author>
                    </byline>
            </entry>',
       $posts['topic'], $posts['title'], $posts['pic_id'], $posts['post_id'], $posts['snippet'], $posts['post_id'], $posts['post_id'], $posts['post_id'], $posts['content'], $posts['post_id'], $posts['author_id']);
       echo $posts_row;
       $post_count++;
  }
 ?>

What I find odd is the 'pic_id' prints properly and pulls in the correct picture, but even when I tried to reuse the pic_id in the $divid it doesn't work. I've tried replacing the $divid with $posts['id'], using all the different integer type specifiers in the PHP Manual, and even using inline php.
Do I have a syntax error? Why does it keep printing out 0?
EDIT: I have posted the query as per requested
EDIT 2: Removed the $divid variable.

A: You do have to put the line
$divid=$posts['post_id'];

inside your while loop. The way it is now it tries to get a value of $posts['post_id'] already before it is assigned for the first time in the loop head and therefore is 0 and never changes (since it's never reassigned).


text:
Q: SQL query number of students per school I have a table of students and schools. How do I select the total students per school?
I'm sure this is a very simple query, however I'm not sure how to proceed on from this:
SELECT tblSchools.name
FROM tblStudentDetails
INNER JOIN tblSchools
   ON tblStudentDetails.schoolId = tblSchools.id

A: Group by the school and use count() to count the students
SELECT s.name, count(d.id) as students_count
FROM tblSchools s
INNER JOIN tblStudentDetails d ON d.schoolId = s.id
GROUP BY s.name

A: I want to add on to the accepted answer as well. Working for a school district and continuously having to pull counts of students there are a few additional things to keep in mind. What students are you looking for?

*

*Do you want active students, inactive students, or active and inactive students.

*Do you want to include students that have been no showed (were going to come to your school, but ended up not coming for even a day, this is recorded in most student information systems.

*Is the student attending multiple schools, in which case you want to exclude them from counting in their second or third school.

I've built the script with the idea of a normalized school district database, where things are broken out by school year, and enrollment.
Often a basic script for me looks a little like this.
SELECT s.SCHOOL_NAME, COUNT(stu.STUDENT_GU) AS STUDENT_COUNT
FROM STUDENT stu
JOIN STUDENT_YEAR sy ON sy.STUDENT_ID = stu.STUDENT_ID
JOIN SCHOOL_YEAR scy ON scy.SCHOOL_YEAR_ID = sy.SCHOOL_YEAR_ID
JOIN SCHOOL s ON s.SCHOOL_ID = scy.SCHOOL_ID
JOIN YEAR y ON y.YEAR_ID = sy.YEAR_ID
WHERE y.SCHOOL_YEAR = 2017
AND (sy.CONCURRENT IS NULL OR sy.CONCURRENT OR != 'Not Concurrent')
AND sy.ENTER_DATE IS NOT NULL
AND sy.STATUS IS NULL
GROUP BY s.SCHOOL_NAME

Because each school year is a new year, students, and schools usually have a table for the basic data that doesn't change. But also tables that are school year specific. In my example STUDENT_YEAR and SCHOOL_YEAR is where we get into the specifics regarding which kids we are actually getting, and where they currently are. I utilize the YEAR table to identify which school year I want to look at.
The STUDENT_YEAR table is where we store the students concurrency flag, enter date, and so within that table I can use in the WHERE clause a way to filter out Inactive Students, Concurrent Students, and ensure each student is counted only once.
If those year values aren't included, at least in my database, I would get all students ever enrolled for every year we've got stored.