text:
Q: Getting error while inserting image into word document using apache poi     run.addPicture(pic, XWPFDocument.PICTURE_TYPE_PNG, screenshot_name, Units.toEMU(350), Units.toEMU(350));
showing error at this line? any solution?

java.lang.NoSuchMethodError: 'org.apache.poi.xwpf.usermodel.XWPFPicture org.apache.poi.xwpf.usermodel.XWPFRun.addPicture(java.io.InputStream, int, java.lang.String, int, int)' getting this error can i get any response regarding this????


text:
Q: How to set margin on view programmatically? I am new to android development and I am trying to add margins to my view but I have not been able to get it to work.
Here's my code:
ConstraintLayout layout = new ConstraintLayout(this);

    final float scale = getResources().getDisplayMetrics().density;
    layout.setMinHeight((int)(100*scale));
    layout.setMaxHeight((int)(100*scale));

    CircleImageView icon = new CircleImageView(this);
    icon.setImageResource(image);
    icon.setBorderWidth(3);

    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams((int)(90*scale), (int)(90*scale));
    icon.setLayoutParams(layoutParams);

    ViewGroup.MarginLayoutParams marginParams = new ViewGroup.MarginLayoutParams(icon.getLayoutParams());
    marginParams.setMargins(100, 0, 0, 0);
    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(marginParams);
    icon.setLayoutParams(params);

    layout.addView(icon);

Why isn't this working? Thanks!

A: You should do like this:
LayoutParams param = new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT);
param.setMargins(left, top, right, bottom);
view.setLayoutParams(param);

A: After you have created the icon, you should first generate an id for it:
icon.setId(View.generateViewId());

Then, remove the setMargins line and add these lines below layout.addView(icon):
ConstraintSet set = new ConstraintSet();
set.clone(layout);

set.constrainWidth(icon.getId(), (int)(90*scale));
set.constrainHeight(icon.getId(), (int)(90*scale));

set.connect(icon.getId(), ConstraintSet.TOP, ConstraintSet.PARENT_ID, ConstraintSet.TOP, 0);
set.connect(icon.getId(), ConstraintSet.START, ConstraintSet.PARENT_ID, ConstraintSet.START, 100);

set.applyTo(layout);

I haven't tested it but it should be a step in the right direction.
Let me know how it goes.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Assign an html id to a sass variable as value I am pretty new to web development, so if you don't understand the explanation of my question, pls let me know.
In my html File I have multiple divs with the same classname which are also defined by an unique id.

Now I want to hand the id over to my sass file, and assign the id as a value to a variable. So at the end I want have the id name as my timer length. Like so:
$timer_length: 130

This way I want to manage the timer length of multiple individual timers.
I don't know if this is even possible. Maybe there is a simple way to do this.

A: You can try something like this not sure about this will help you or not.
If you know how many individuals are then you can give them a dynamic name something like example_1 where example_ and 1 is static with that you can fetch a specific individual's id then you can use with the help of JavaScript as @Noam said in the comments.

var dynamic_number = 2;
var elm_name = "example_" +dynamic_number;
console.log(elm_name);
var elements = document.getElementsByName( elm_name );
var value = elements[0].getAttribute( 'id' );
alert("Time for individule " + dynamic_number +" is: "+ value);

A: There is an attr property that you can use in css, but according to CanIUse, it's currently only supported for the content attribute.
You may need to use JavaScript to do what you want.
Since you seems to use your IDs as a data, I suggest you to use data-[...].
Here is an example with your IDs as data-length to set up div length :

let examples = document.getElementsByClassName("example");
for (let i = 0; i < examples.length; i++) {
  examples[i].style.width = examples[i].dataset.length+"px";
}
.example{
  height:10px;
  background-color:orange;
  margin-bottom:10px;
}


text:
Q: In deriving the catenary equation, how does integrating $\frac{dy'}{\sqrt{1+(y')^2}}=\frac1a dx$ yield $\sinh^{-1}(y')=\frac{x}{a}$? Watch, consider and refer the following you tube video named " Catenary equation derivation".
Catenary equation derivation
At time $00:17:07$, author of this video integrates both sides of the equation $$\frac{dy'}{\sqrt{1+(y')^2}} = \frac1a dx \tag{1}$$
and arrived at the following step
$$ \sinh^{-1} {(y')}=\dfrac{x}{a}\tag{2}$$
Now I understood the R.H.S. of equation $(2)$, but I don't understand how did the author(math professor) of video integrate L.H.S of equation $(1)$ and arrived at L.H.S. of equation $(2)$.
Would any member of this math stack exchange, what are the steps involved in this integration of equation $(1)$?

A: You want to evaluate $\int \frac{1}{\sqrt{1+x^2}}dx,$ so substitute $x=\sinh(u),$ $dx=\cosh(u)du$ and we have
$$\int \frac{1}{\sqrt{1+x^2}}dx=\int\frac{\cosh(u)}{\sqrt{1+\sinh^2(u)}}du=\int\frac{\cosh(u)}{\cosh(u)}du$$
$$=\int 1\ du=u+C=\sinh^{-1}\left(x\right)+C$$
using the hyperbolic identity $\cosh^2(u)=1+\sinh^2(u)$.
See also hyperbolic functions.


text:
Q: Three.js have one particle exactly? I would like to add just one particle and be able to move it around. However, all I could find it how to do it with a Particle System. I tried adding a particle to the scene as one would do a mesh, but it didn't render. Only when I used a particle system did it render.
Here is what I tried:
particle_material = new THREE.ParticleBasicMaterial({ color: 0x0000ff, size: 2000 });
        particle = new THREE.Particle(particle_material);
        particle.position.x = 0;
        particle.position.y = 0;
        particle.position.z = 0;

        scene.add(particle);

A: THREE.Particle is supported by CanvasRenderer and THREE.ParticleSystem is supported by WebGLRenderer.
You may want to consider using THREE.Sprite. See http://threejs.org/examples/webgl_sprites.html.
three.js r.60


text:
Q: Подскажите хорошее решение для многопоточной обработки txt Eсть txt, допустим 1000 строк. Нужно при помощи threading, например, в 50 потоков обработать (взять строку, передать в функцию, удалить строку). На ум пришло поместить весь файл в список, и через list.remove() удалять обработанные строки. Но дело в том, что потоки видимо мешают друг другу, из 1000 итемов в списке обрабатывается ~700 и скрипт гоняет пустой список, не завершаясь (хотя проверка на длину списка есть). Создавать копию txt и удалять из нее строки- я думаю костыль.
Вопрос: как по дзену Python нужно реализовать этот скрипт?


text:
Q: Move rows to bottom in a TableView which uses CoreData In my app  I have a folder-file (one-to-many relationship).So when I open my app, my firstViewController contains all files and when clicked on each folder, it opens a tableViewController displaying files in that folder.
Now here whenever I swipe any row, it is moved to bottom row and the table is update accordingly, the next swiped row will go and sit above the first swiped row.
Eg, at present if my table contains
0 1 2 3
A B C D

After swiping A
0 1 2   3
B C D **A**

after swiping B
0 1   2 3
C D **B A**

and so on,
To do this functionality, I should update the NSOrderedSet also
which is shown below
for (int i = 0; i < [self.folder.file count]; i++)
        {
            File *file =  [self.folder.file objectAtIndex:i];
            if(file.completedStatus == false)
            {
                m_position = i;
                m_finalIndexPath = [NSIndexPath indexPathForRow:i inSection:0];
            }
        }

        file.completedStatus = YES;

        id obj = [self.folder. file objectAtIndex:row];

        NSMutableOrderedSet *files = [self.folder.file mutableCopy];
        [files removeObjectAtIndex:row];
        [files insertObject:obj atIndex:m_position];

        NSIndexPath *currentIndexPath = [NSIndexPath indexPathForRow:row inSection:0];
        [m_tableView moveRowAtIndexPath:currentIndexPath toIndexPath:m_finalIndexPath];
        self.folder.file = files;
         }
         [self.managedObjectContext save:nil];
         [m_tableView reloadData];

This works fine in this View, and here self.folder, is particular folder on which the user clicks
Now I have another ViewController called TestViewController where I have some of the file objects irrespective of in which ever folder they are present . I have populated the table of this TestViewController with these files, Now here also, when I swipe the cells, they will change the color but not move their position as above
Eg
0 1 2 3
A C B D

after swiping A and B

  0   1   2   3
**A** C **B** D

Now here A can belong to folder 1 and B can belong to folder 2,
when I close(dismiss) this TestViewController, What should happen is that
a) it shows me the fileViewController by default
b) the color of file A should change and it should move to a position by checking whether there are any swiped cells already. If yes, it should be placed above it or else at the bottom.
c) similarly for color B.
Regards
Ranjit.

A: Ranjit,
About your question I cannot understand what you are asking here. So, please provide some other details.
To know the folder a specific file belongs to, this is quite simple to achieve.
If you have set up an inverse relationship between a file and a folder, simply access that relationship.
For example, if the inverse relationship is called toFolder, you can retrieve the current folder like
Folder* currentFolder = currentFile.toFolder; // or access it through KVC

To create an inverse relationship take a look here: Core data structure use multiple entities or not?


text:
Q: getting syntax and unexpected token(s) error, anyone know why? I have a header class that refuses to cooperate, I've ironed a bunch of errors but cannot for the life of me get these two. Any ideas?
#pragma once
#include <iostream>
#include <string>
#include <conio.h>

using namespace std;
#ifndef EndageredSpecies
#define EndageredSpecies
using namespace std;
class EndageredSpecies
{
public:
    EndageredSpecies;
    EndageredSpecies(string newName, newLevel, newReason);
    void setName(string newName);
    void setLevel(string newLevel);
    void setReason(string newReason);
    string getName();
    string getLevel();
    string getReason();
    void print();
private:
    std::string name;
    std::string level;
    std::string reason;
};

void do_something()
{
    cout << "Doing something";
}
#endif

Errors are:
C2059 syntax error: ')' - line 13
C2238 sunexpected tokens preceding ';'- line 13
(Line 13 is 'EndageredSpecies(string newName, newLevel, newReason);')

A: What your code looks like to the compiler (note I have not processed the include statements as that, while more accurate, would make quite a mess):
#pragma once
#include <iostream>
#include <string>
#include <conio.h>

using namespace std;
using namespace std;
class
{
public:
    ;
    (string newName, newLevel, newReason);
    void setName(string newName);
    void setLevel(string newLevel);
    void setReason(string newReason);
    string getName();
    string getLevel();
    string getReason();
    void print();
private:
    std::string name;
    std::string level;
    std::string reason;
};

void do_something()
{
    cout << "Doing something";
}

Why is this?
#define EndageredSpecies

tells the preprocessor to replace EndageredSpecies wherever it finds it with whatever is on the line after #define EndageredSpecies, absolutely nothing in this case, so
class EndageredSpecies

is now
class

etc...
You have to be VERY careful with a #define macro. They are amazingly simple in execution. They have no brains whatsoever. If they see the token they've been told to replace, they replace it. Period. I once made the mistake of defining int strlen; to contain the length of a string.
Big Mistake.
It turned out the strlen function was implemented as a macro. int strlen; became int <whole function body here>;. I think I burned most of an afternoon figuring that out.
Do not fear the macro, but you have to use it very carefully.
What you really want is more like
#pragma once
#ifndef UNIQUE_AND_NEVER_REPEATED_IDENTIFIER
#define UNIQUE_AND_NEVER_REPEATED_IDENTIFIER
// note how this is above the includes. Don't want to re-include them

#include <iostream>
#include <string>
#include <conio.h>

// do not use using namespace std; in a header. It's a very nasty surprise
// to other programmers.
class EndageredSpecies
{
public:
    EndageredSpecies(); // added brackets
    EndageredSpecies(std::string newName, // added std namespace
                     std::string newLevel,
                     std::string newReason);
    void setName(std::string newName);
    void setLevel(std::string newLevel);
    void setReason(std::string newReason);
    std::string getName();
    std::string getLevel();
    std::string getReason();
    void print();
private:
    std::string name;
    std::string level;
    std::string reason;
};

void do_something()
{
    std::cout << "Doing something";
}
#endif

An Aside:
#pragma once

and
#ifndef EndageredSpecies
#define EndageredSpecies
#endif

are two ways to make an include guard. You can use both, but typically you don't need to.
#pragma once

is not part of Standard C++, so you can't count on it being supported. Any pragma that a compiler does not support it is allowed to silently discard, leading to confusion, disaster, and possibly no useful error messages. That said, most compilers these days implement once. once likely has not been Standardized because it has severe failure cases in complicated build environments. Don't do anything sneaky and it works just fine.
#ifndef EndageredSpecies
#define EndageredSpecies
#endif

Works all the time everywhere. It's problems are the likes of what the asker has experienced.
Do not repeat a include guard identifier. Ever. For any reason.
Name include guards so that they will be next to impossible to repeat unless you are crazy. Sadly Norman Bates nailed it: We all go a little mad sometimes. To protect against temporary madness, make it as obvious as possible so when you are not mad later, you can see that the used identifier does not make sense where it is being used and change it.
You typically only want one or the other type of include guard, but there can be advantages to using both. If #pragma once is not supported or fails, you don't get the nasty surprise. If it is supported, there are often performance benefits from not having to look at the included file at all.


text:
Q: ssl not displaying in first visit in codeigniter website i have ssl installed in my codeigniter website which is live and also I have enabled forced https option, my host is hostinger, SSL issuer: Let's Encrypt Authority X3.
the problem here is when the user first visit the website its showing without SSL "not secure", then if u go to another page its showing SSL and then if u go to homepage again the SSL is present, the problem is in the first visit using the searchbar of the browser, everytime when u use the searchbar of the browser this happens, any device and browser its like this.
The live URL is below is my config.php:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

$config['base_url'] = '';
$config['index_page'] = '';
$config['uri_protocol'] = 'REQUEST_URI';
$config['url_suffix'] = '';
$config['language'] = 'english';
$config['charset'] = 'UTF-8';
$config['enable_hooks'] = FALSE;
$config['subclass_prefix'] = 'MY_';
$config['composer_autoload'] = FALSE;
$config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-';
$config['enable_query_strings'] = FALSE;
$config['controller_trigger'] = 'c';
$config['function_trigger'] = 'm';
$config['directory_trigger'] = 'd';
$config['allow_get_array'] = TRUE;
$config['log_threshold'] = 0;
$config['log_path'] = '';
$config['log_file_extension'] = '';
$config['log_file_permissions'] = 0644;
$config['log_date_format'] = 'Y-m-d H:i:s';
$config['error_views_path'] = '';
$config['cache_path'] = '';
$config['cache_query_string'] = FALSE;
$config['encryption_key'] = '';
$config['sess_driver'] = 'files';
$config['sess_cookie_name'] = 'ci_session';
$config['sess_expiration'] = 7200;
$config['sess_save_path'] = NULL;
$config['sess_match_ip'] = FALSE;
$config['sess_time_to_update'] = 300;
$config['sess_regenerate_destroy'] = FALSE;
$config['cookie_prefix']    = '';
$config['cookie_domain']    = '';
$config['cookie_path']      = '/';
$config['cookie_secure']    = FALSE;
$config['cookie_httponly']  = FALSE;
$config['standardize_newlines'] = FALSE;
$config['global_xss_filtering'] = FALSE;
$config['csrf_protection'] = FALSE;
$config['csrf_token_name'] = 'csrf_test_name';
$config['csrf_cookie_name'] = 'csrf_cookie_name';
$config['csrf_expire'] = 7200;
$config['csrf_regenerate'] = TRUE;
$config['csrf_exclude_uris'] = array();
$config['compress_output'] = FALSE;
$config['time_reference'] = 'local';
$config['rewrite_short_tags'] = FALSE;
$config['proxy_ips'] = '';

this is my htaccess code:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]

can anyone please tell me what could be wrong here, thanks in advance

A: Set redirection in .htaccess
RewriteCond %{HTTPS} off
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]


text:
Q: Zend Framework 2 Session Full example of how to use Zend Framework 2 Session in Controllers, and display the session variable to the view (.phtml).

A: I guess the links below would be a good starting point.
Links:
Using Sessions in Zend Framework 2
Using Sessions In Zend Framework 2 – Part 1
Session Container
update:
in your view action inside a controller add them in the ViewModel.
        //session
        $session = new Container('somecontainer');
        $poster = $session->somename;//$session->somename holds data set from another action

        $view = new ViewModel(array(
            'poster' => $poster,

        ));
        return $view;

and inside the view depending on the type of the variable you use it
echo $poster;//will echo the session message.


text:
Q: -[NSURL _CFURLRequest]: unrecognized selector sent to instance i am using JSONKit in my program to parse google places api but my app crashes with the following error
-[NSURL _CFURLRequest]: unrecognized selector sent to instance
     NSString* URL = [NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/place/search/json?location=28.632808,77.218276&radius=500&types=atm&sensor=false&key=AIzaSyDHft2g5IDshIpXS17uOtZzkqGGgj-p1RQ"];

NSError* error = nil;
NSURLResponse* response = nil;

NSURLRequest *URLReq = [NSURL URLWithString:URL];
//[request setURL:URL];
//[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
//[request setTimeoutInterval:30];

NSData* data = [NSURLConnection sendSynchronousRequest:URLReq returningResponse:&response error:&error];

if (error)
{
    NSLog(@"Error performing request %@", URL);
    NSLog(@"%@", [error localizedDescription]);
    return;
}

NSDictionary *json = [data objectFromJSONData];

NSArray *places = [json objectForKey:@"results"];

NSLog(@"Google Data: %@", places);

A: You're setting up your "NSURLRequest" incorrectly and should be using requestWithURL: instead.
Instead of
NSURLRequest *URLReq = [NSURL URLWithString:URL];

do
NSURLRequest * urlReq = [NSURLRequest requestWithURL: [NSURL URLWithString: URL]];

Also, a quick FYI:  Objective C convention is to use lowercase letters for variables and ivars.  Use capital letters for your class names. In other words, change "URLReq" to "urlReq" and "URL" to "url" (or even better than that, something more specific like "googlePlaceURL").


text:
Q: How to use a command's return value with pipe as a variable in batch file I want to extract a file in in windows, right after search for it, like this:
7z [args] | ls | grep filename

In my windows batch script, its:
7z [args] | dir /B | findstr filename

the search alone works perfectly like in linux, but i just cant pass it forward to a variable, or straight to 7z as an input.
I tried

*

*pipe from the left

*pipe from the right

*for /f "delims=" %%a in ('dir /B ^| findstr onboard.zip') do @set Value=%%a
But all my solutions crashed with error.
My idea to pass the found file to any variable, OR give it straight forward to the extracting tool.
Do you have any working solution/workaround for this?
Thanks in advance!

A: After 1.5 days i realized that DIR have built in search, that can solve my problem without the pipe:
dir /b *filename

but still really interested in your - pipe included - solution :)

A: I am not quite sure of what you want. Does 7z produce a list of filenames?
for /f "usebackq tokens=*" %f in (`7z [args]`) do (if exist "%f" echo found file "%f")

If this is used inside a batch script, the percent characters must be doubled.


text:
Q: Remove corner of image with css I'm looking to remove the corner of an image using CSS. I currently achieved this by adjusting the image, but I would rather learn how to do this properly.
Here is the page with the image shopped to what I wanted to achieve. The idea is to use the full image with CSS doing the snipping of the corner
http://goos3d.ie/home-2/

A: You have a few option to archive this effect:
Clip Path
Use CSS clip-path to cutt of the edges. This technique works like a mask in Photoshop. Unfortunately this property is relatively new and needs to be shimed in older browsers
Image Mask
You could create another image which works as mask and place it on top of your image:

.image {
    position: relative;
    overflow: hidden;
}

.image-mask {
    bottom: 0;
    left: 0;
    position: absolute;
    right: 0;
    top: 0;
}

DIV Elements
Use for DIV elements to create a corner and position them on top of you image:

.image {
    position: relative;
    overflow: hidden;
}

.image-corner {
    background-repeat: no-repeat;
    heigth: CORNER_HEIGHT;
    position: absolute;
    width: CORNER_WIDTH;
}

.image-corner-top-left {
    background-image: url('/path/to/corner-top-left');
    left: 0;
    top: 0;
}

.image-corner-top-right {
    background-image: url('/path/to/corner-top-right');
    right: 0;
    top: 0;
}

.image-corner-bottom-left {
    background-image: url('/path/to/corner-bottom-left');
    bottom: 0;
    left: 0;
}

.image-corner-bottom-right {
    background-image: url('/path/to/corner-bottom-right');
    bottom: 0;
    right: 0;
}

A: The astronaut picture that you are seeing does not involve any clipping of the image..The image is still there but parts of the image is hidden using css rules
Take a look at the image from the source url..Yes it is still there but parts of it is hidden on the website

Now you can simply replicate this behaviour using css
to get some "clipping" with using css only

* Add a background image to a div background:url("....")

* Postion the image using background-position rule
See snippet below

#astro {
  width: 500px;
  height: 500px;
  border: solid;
  background: url("http://goos3d.ie/wp-content/uploads/2016/11/goos3d-moon-large2.png");
  background-repeat: no-repeat;
  background-size: cover;
  background-position: -400px 0px
}

A: Two easy steps:
First You need to apply the following styling to the container
 that has the background image:
.vc_parallax-content-moving-fade
{
    border-bottom-right-radius: 100% !important;
    overflow: hidden;
}

Second The orange button will be hidden because of the above styling, so you need to put the orange button immediately before the container that has the background image.
Then give it the following styling:
.vc_btn3
{
    z-index: 9999;
    right: 0;
    position: absolute;
    top: 300px;
}


text:
Q: TSQL: Ranking records by using different columns I have a table with persons and their expenses and some other columns. What I need is to create two new columns: ranking1 and ranking2. These rankings are "calculated" by using some columns and by using aggregates.
ranking1: if total of person expenses exceeds 1000 then ranking 1 else ranking 0
ranking2: (if Col1 = 1 then 0 else 5) + (if Col2 = 1 then 0 else 7) + (if Col3 = 1 then 5 else 10)

What I need is to have the original table (unaltered) with these two new columns that give me the ranking for each person.
My query:
select Col1, Col2, Col3
       ((CASE Col1 = 1 THEN 0 ELSE 5 END) +
        (CASE WHEN Col2 = 1 THEN 0 ELSE 7 END) +
        (CASE WHEN Col3 = 1 THEN 5 WHEN Col3 = 2 THEN 2 ELSE 10 END)) as ranking, tmp.Expenses    from table t
left join (select id, Person,
          (case when temp.expenses > 1000 then 1 else 0 end) as UserExpenses
           from (select id, Person, sum(Expenses) as expenses
           from table
           group by id, Person) temp) tmp
on t.Person = tmp.Person and t.id = tmp.id
order by ranking desc, tmp.UserExpenses desc

I am dubious about if this query will give me what I want, that is the original unaltered table with two new columns as ranking. Especially I am dubious about left join, is it the right join? Thanks in advance

A: Your query should bring you right results. Below is a little bit simplified version of your query:
select  Col1,
        Col2,
        Col3
        (CASE WHEN Col1 = 1 THEN 0 ELSE 5 END) +
        (CASE WHEN Col2 = 1 THEN 0 ELSE 7 END) +
        (CASE WHEN Col3 = 1 THEN 5 WHEN Col3 = 2 THEN 2 ELSE 10 END) as ranking,
        (case when temp.expenses > 1000 then 1 else 0 end) as Expenses
from [table] t
OUTER APPLY (select id,
                    Person,
                    sum(Expenses) as expenses
            from [table]
            where t.Person = Person and t.id = id
            group by id, Person
            ) temp
order by ranking desc, temp.expenses desc


text:
Q: Virtualbox: WARNING! Diff between built and installed module After I signed Virtualbox for secure-boot on Debian I typed dkms status.
I've got that message :WARNING! Diff between built and installed module.
Is that because I signed the module ?


text:
Q: SUM All ROW of Table Column [HTML, JavaScript] So I have this code to generate an invoice :

.table-data_2{
        padding: 0;
        margin: 0 auto 1.5em auto;
    border-top: 0px solid #C1DAD7;
        border-left: 0px solid #C1DAD7;
        border-collapse:collapse;
    font-size:12px;
        font-family: verdana,arial,sans-serif;
        color:#545454;
    border: 0;
}
.td-data_1 {
 font: normal 11px "Trebuchet MS", Verdana, Arial, Helvetica, sans-serif;
 border-right: 1px solid #C1DAD7;
 border-bottom: 1px solid #C1DAD7;
 padding: 3px 6px 3px 6px;
 color: #4f6b72;
 border: 2;
 text-align: left;
}

NO

 Q-Code

 Name, Spec, Size

 QTY

 Unit

 Currency

 Unit Price

 Total Price

     1
     Data Not Shown
     Data Not Shown
     2
     Data Not Shown
     Data Not Shown
     12000
     24000

     1
     Data Not Shown
     Data Not Shown
     2
     Data Not Shown
     Data Not Shown
     14000
     28000

    Sub total
    SUM TOTAL PRICE

    VAT
    10%

    TOTAL
    TOTAL + VAT

I want to generate sub total of total price that shown in my table (not from mysql database), and also how to generate value from sub total + vat?
Any help will be much appreciated.
Thanks,

A: That would be
$(document).ready(function () {
  var sumSubTotal = 0;
    $('.total_price').each(function() {
        sumSubTotal += parseInt($(this).text().trim(), 10) || 0;
    });
  $( "td:contains('SUM TOTAL')" ).text(sumSubTotal);
  $( "td:contains('10%')" ).text(sumSubTotal*0.1);
  $( "td:contains('TOTAL + VAT')" ).text((sumSubTotal*0.1)+sumSubTotal);

});

Example
https://jsfiddle.net/zzzrdcr5/1/

A: Try this:

$('document').ready(function() {
  var ttl = 0;
  $.each($('td.total_price'), function(key, value) {
    ttl += parseInt($(value).text()) || 0;
  });

  var vat = 10;
  var cVat = (ttl * vat) / 100;

  $('td.sub_total').html('' + ttl + '');
  $('td.vat').html('' + cVat + '');
  $('td.total').html('' + (ttl + cVat) + '');
});
.table-data_2{
        padding: 0;
        margin: 0 auto 1.5em auto;
    border-top: 0px solid #C1DAD7;
        border-left: 0px solid #C1DAD7;
        border-collapse:collapse;
    font-size:12px;
        font-family: verdana,arial,sans-serif;
        color:#545454;
    border: 0;
}
.td-data_1 {
 font: normal 11px "Trebuchet MS", Verdana, Arial, Helvetica, sans-serif;
 border-right: 1px solid #C1DAD7;
 border-bottom: 1px solid #C1DAD7;
 padding: 3px 6px 3px 6px;
 color: #4f6b72;
 border: 2;
 text-align: left;
}

NO

 Q-Code

 Name, Spec, Size

 QTY

 Unit

 Currency

 Unit Price

 Total Price

     1
     Data Not Shown
     Data Not Shown
     2
     Data Not Shown
     Data Not Shown
     12000
     24000

     1
     Data Not Shown
     Data Not Shown
     2
     Data Not Shown
     Data Not Shown
     14000
     28000

    Sub total
    SUM TOTAL PRICE

    VAT
    10%

    TOTAL
    TOTAL + VAT


text:
Q: Java heap - bigger than it needs to be My maths says the following Java program would need approx 8GB (2147483645 * 4 bytes) of RAM:
package foo;

public class Foo {
    public static void main(String[] args) throws Exception {
        int[] arr = new int[Integer.MAX_VALUE-2];
        Thread.sleep(500000L);
    }
}

This is backed up by observing the program when running:

But unless you set the max heap to around 12.5GB, the program fails to start:
$ java -Xmx12000m -cp ./ foo.Foo
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
        at foo.Foo.main(Foo.java:5)
$ java -Xmx12500m -cp ./ foo.Foo
//this works

Can understand the need for a bit of wiggle-room but why do we need so much?

A: Its because of the MinHeapFreeRatio default value (which is 40%). If you want to "need" less then you have to specify it: e.g. 5%
-XX:MinHeapFreeRatio=5
Also, you need to change memory allocated to the young generation as it plays a important role in memory allocation:

After total available memory, the second most influential factor affecting garbage collection performance is the proportion of the heap dedicated to the young generation.

try this:
java -Xmx9g -XX:MinHeapFreeRatio=1 -XX:MaxNewSize=256m -cp ./ foo.Foo

https://docs.oracle.com/javase/8/docs/technotes/guides/vm/gctuning/sizing.html


text:
Q: How to get top10(blue+green) frames from unsorted int[] arrays of blue and green? I have two arrays:-
int[] blueArray = new int[100];
int[] greenArray = new int[100];

greenArray and blueArray contain the a number between 0 and 255 to indicate the intensity of the respective color in each frame. So blueArray[0] has blue-value for frame-1 and blueArray[99] has blue-value for frame-100. Similar ordering applies for greenArray.
I wish to find out the top 10 frames with the highest cyan frames. So I am looking for the top  10 frame-ids that contain the highest sum of blue+green. I may not use additional data-structures and would like this top-10 list in O(n) time.
How can I accomplish this?

A: While not really fast, this is actually O(n):
for (j = 0; j < 10; j++)
  max = j
  for (i = j + 1; i < 10; i++)
    if (blueArray[i] + greenArray[i] > blueArray[i] + greenArray[i])
      max = i;
  swap(blueArray[j], blueArray[max])
  swap(greenArray[j], greenArray[max])

A: This is called partial sort.  Wikipedia provides a nice overview of the available algorithms.  The fact that you have to handle two arrays simultaneously shouldn't make a big difference, but it prevents you from using any existing implementation so you probably have to roll your own.


text:
Q: How to access the ASP.NET / IIS ContextId I've seen way too many times in my event logs this "ContextId" for a given ASP.NET request. I've recently started looking into ETW events that are pushed out by ASP.NET, and want to re-use this ContextID in my own events that I fire.
How can I do this?
System.Threading.Thread.CurrentContext doesn't seem to have it. It's always 0.

A: This is a poorly documented feature, but yes you can get it.
It sits on the HttpWorkerRequest RequestTraceIdentifier property.
http://msdn.microsoft.com/en-us/library/system.web.httpworkerrequest.requesttraceidentifier.aspx

A: You can get it from the HttpWorkerRequest.RequestTraceIdentifier property.  Note that obviously you need to have the IIS ETW (Event Tracing for Windows) feature enabled or this property will be Guid.Empty.  The following is how to get it from HttpContext:
var serviceProvider = (IServiceProvider)HttpContext.Current;
var workerReqest = (HttpWorkerRequest)serviceProvider.GetService(typeof(HttpWorkerRequest));
var requestId = workerReqest.RequestTraceIdentifier;

Reference: https://github.com/serilog/serilog/commit/b289dbcde3e0f7366d90daf66e00c94f4cc58de3#diff-4934d624fc1d467b08411d520972e840R48


text:
Q: Filtrado desde un tercer JOIN en Base de Datos Estoy intentando hacer un JOIN con las siguientes tres tablas.
Primero entrada-salida con cliente a través de un LEFT JOIN.
A su vez, igual con la tabla pago, con un LEFT JOIN.
Les muestro las tablas, su estructura y sus registros.
Todo esto con MYSQL
CLIENTE
CREATE TABLE `cliente` (
  `id_cliente` int(11) NOT NULL,
  `nombre_cliente` varchar(60) NOT NULL,
  `apellido_cliente` varchar(60) NOT NULL,
  `sexo_cliente` varchar(10) NOT NULL,
  `email_cliente` varchar(60) NOT NULL,
  `fecha_nacimiento_cliente` date NOT NULL,
  `telefono_cliente` varchar(15) NOT NULL,
  `estado_cliente` tinyint(4) NOT NULL DEFAULT 1,
  `gimnasio_cliente` int(11) NOT NULL,
  `url_imagen_cliente` varchar(100) NOT NULL,
  `fecha_creacion_cliente` date DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

INSERT INTO `cliente` (`id_cliente`, `nombre_cliente`, `apellido_cliente`, `sexo_cliente`, `email_cliente`, `fecha_nacimiento_cliente`, `telefono_cliente`, `estado_cliente`, `gimnasio_cliente`, `url_imagen_cliente`, `fecha_creacion_cliente`) VALUES
    (20, 'Eliseo', 'VM', '', 'eliseo-01@gmail.com', '2021-12-31', '9981505702', 1, 65, '127162643_10159108904568217_5842463868241141841_n.jpg', NULL),
    (21, 'Juana', 'Perez', '', 'eliseo-01@gmail.com', '2020-11-14', '9981505702', 1, 64, '122678745_2762713470669451_2203428614279550983_o.jpg', NULL),
    (22, 'Pepe', 'Luna', '', 'eliseo-01@gmail.com', '2020-11-10', '9981505702', 1, 72, 'Sin título111.png', NULL),
    (23, 'Alex', 'Mejilla', '', 'eliseo-01@gmail.com', '2020-11-03', '9981505702', 1, 66, 'Sin título111.png', NULL),
    (26, 'Carlos', 'V', '', 'eliseo-01@gmail.com', '2020-11-10', '9981505702', 1, 66, '122678745_2762713470669451_2203428614279550983_o.jpg', NULL),
    (27, 'Itzel', 'Portillo', '', 'eliseo-01@gmail.com', '2020-11-14', '9981505702', 1, 66, 'Sin título111.png', NULL),
    (28, 'Lucia', 'Juarez', '', 'eliseo-01@gmail.com', '1994-07-19', '9981505702', 1, 68, '123140339_1519457401589137_5102889472902390156_n.jpg', NULL),
    (29, 'Omar', 'Chaparro', '', 'eliseo-01@gmail.com', '2020-11-03', '9981505702', 1, 67, '20190609_112611.jpg', NULL),
    (30, 'Astrid', 'Lopez', '', 'eliseo-01@gmail.com', '1994-07-19', '9981505702', 1, 72, '122708132_1000704930432221_3500663975623121294_o.jpg', NULL),
    (31, 'Fanny', 'Galan', '', 'ultima@ultima.com', '2020-11-02', '9981505702', 1, 66, '123049280_184397109906000_7453044576460053003_o.jpg', NULL),
    (32, 'Federico', 'Quico', '', 'juan@juan.com', '2020-11-02', '9981-5057-02', 1, 66, '118988454_322259409191532_9047549356402945931_o.jpg', NULL),
    (33, 'Ariel', 'XX', '', 'eliseo-01@gmail.com', '2020-11-03', '9981505702', 1, 67, '108031076_10208153574434112_6700955287415195789_o.jpg', NULL),
    (34, 'Lucia', 'Alamilla', '', 'eliseo-01@gmail.com', '2020-11-02', '9981-5057-02', 1, 73, '108031076_10208153574434112_6700955287415195789_o.jpg', NULL),
    (35, 'Beatriz', 'Juarez', '', 'eliseo-01@gmail.com', '2020-11-18', '9981-5057-02', 1, 64, '113242783_10208175112172542_1332820974758870271_o.jpg', NULL),
    (36, 'Ana', 'Dell', '', 'eliseo-01@gmail.com', '1994-07-19', '9981505702', 1, 71, '127162643_10159108904568217_5842463868241141841_n.jpg', NULL),
    (39, 'Logi Logi', 'Logi', '', 'logi@logi.com', '2021-01-20', '9981505050', 1, 76, 'aprender-ingles.jpg', NULL),
    (40, 'Fede', 'Perez', '', 'logi@logi.com', '2021-01-27', '9981505050', 1, 64, 'unnamed.jpg', NULL),
    (42, 'Microsoft', 'Corporation', '', 'eliseo-01@gmail.com', '2021-02-24', '9981505050', 1, 76, 'platzi.jpg', NULL),
    (44, 'Alma', 'China', '', 'logi@logi.com', '2021-01-20', '9981505050', 1, 76, 'eb7710e28b66bc1bfa26e60c0426cf0e.jpg', NULL),
    (45, 'Propiedad', 'propiedad', '', 'logi@logi.com', '2021-01-20', '9981505050', 1, 65, 'unnamed.jpg', NULL),
    (46, 'Guadalupe', 'Tijuana', '', 'eliseo-01@gmail.com', '2021-01-20', '9981505050', 1, 65, 'brackets-linguales-preguntas-frecuentes.jpg', NULL),
    (47, 'Luz', 'Nieto', '', 'eliseo-01@gmail.com', '2021-01-20', '9981505050', 1, 65, 'maxresdefault.jpg', NULL),
    (48, 'Nvidia', 'Nvidia', '', 'nvidia@nvidia.com', '2021-02-24', '9981505050', 1, 64, 'platzi.jpg', NULL),
    (49, 'Luis', 'Paca', '', '', '2021-03-24', '', 1, 64, 'pantalla-muy-larga-gaming-1024x576.jpg', NULL),
    (50, 'Pepe', 'Juarez', '', 'juarez@alave.com.mx', '2020-09-09', '9981505702', 1, 76, '', NULL),
    (51, 'Pepita', 'Nana', '', '', '2020-05-20', '9981505702', 1, 79, '', NULL),
    (52, 'Pepe', 'Mujica', '', 'paragua@paraguay.com', '2021-04-24', '9981505702', 1, 64, '1366_200350.jpg', NULL),
    (53, 'Clark', 'Kent', '', 'superman@superman.com', '2021-04-12', '9981505702', 1, 64, 'aprender-ingles.jpg', '2021-04-18'),
    (54, 'Venom', 'Simbionte', 'otro', 'simbionte@simbionte.com', '2021-06-10', '9981', 1, 64, '123049280_184397109906000_7453044576460053003_o.jpg', '2021-06-10'),
    (55, 'Peter', 'Parker', '', 'spiderman@spiderman.com', '2021-06-09', '9981', 1, 64, 'Captura de pantalla 2021-06-10 090108.png', '2021-06-10'),
    (56, 'Benito', 'Juarez', '', 'benito@benito.com', '2021-06-20', '9981', 1, 64, 'Captura de pantalla 2021-06-10 090108.png', '2021-06-10'),
    (57, 'Prueba', 'Prueba', '', 'prueba@prueba.com', '2021-06-25', '9981', 1, 64, '56848056_1210196885824870_5863649069448036352_n.jpg', '2021-06-11'),
    (58, 'Prueba2', 'Prueba2', '', 'prueba2@prueba2.com.mx', '2021-06-25', '9981', 1, 64, '56848056_1210196885824870_5863649069448036352_n.jpg', '2021-06-11'),
    (59, 'Prueba3', 'Prueba3', '', 'prueba3@prueba3.com.mx', '2021-06-17', '9981', 1, 64, '193064032_336448634560516_2941969823588855552_n.jpg', '2021-06-11'),
    (60, 'Prueba4', 'Prueba4', 'mujer', 'prueba4@prueba4.com.mx', '2021-06-17', '9981', 0, 64, 'Unidad de imagen T3.jpeg', '2021-06-11'),
    (61, 'Loki', 'Loki', 'otro', 'loki@loki.com.mx', '2021-06-25', '9981', 0, 64, 'Mensaje en la impresora.jpeg', '2021-06-11');

ENTRADA-SALIDA
CREATE TABLE `entrada_salida` (
  `id_entrada_salida` int(11) NOT NULL,
  `cliente_entrada_salida` int(11) NOT NULL,
  `fecha_entrada_salida` date NOT NULL,
  `hora_entrada_salida` time NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

INSERT INTO `entrada_salida` (`id_entrada_salida`, `cliente_entrada_salida`, `fecha_entrada_salida`, `hora_entrada_salida`) VALUES
(43, 20, '2021-01-03', '17:03:27'),
(44, 20, '2021-01-03', '17:03:31'),
(46, 21, '2021-01-03', '17:03:40'),
(47, 21, '2021-01-03', '17:03:44'),
(48, 47, '2021-01-08', '20:37:32'),
(49, 47, '2021-01-08', '20:39:16'),
(52, 46, '2021-01-08', '20:39:45'),
(53, 46, '2021-01-08', '20:40:36'),
(54, 46, '2021-01-08', '20:40:37'),
(55, 46, '2021-01-08', '20:40:39'),
(56, 46, '2021-01-08', '20:42:10'),
(57, 46, '2021-01-08', '20:42:11'),
(58, 46, '2021-01-08', '20:42:12'),
(59, 46, '2021-01-08', '20:42:19'),
(60, 46, '2021-01-08', '20:42:20'),
(61, 46, '2021-01-08', '20:42:20'),
(62, 46, '2021-01-08', '20:42:30'),
(63, 20, '2021-01-08', '20:52:18'),
(64, 20, '2021-01-08', '20:53:11'),
(65, 20, '2021-01-08', '20:54:38'),
(66, 20, '2021-01-08', '20:58:21'),
(67, 20, '2021-01-08', '21:00:22'),
(68, 21, '2021-01-08', '21:01:19'),
(69, 21, '2021-01-08', '21:02:26'),
(70, 45, '2021-01-09', '14:41:09'),
(71, 22, '2021-01-12', '21:23:18'),
(72, 22, '2021-01-12', '21:23:57'),
(73, 48, '2021-01-12', '21:27:23'),
(74, 48, '2021-01-12', '21:27:26'),
(75, 48, '2021-01-13', '21:50:07'),
(76, 48, '2021-01-13', '21:50:24'),
(77, 34, '2021-01-16', '22:12:42'),
(78, 21, '2021-01-19', '23:08:00'),
(80, 21, '2021-02-04', '22:09:35'),
(81, 21, '2021-02-04', '22:11:15'),
(82, 21, '2021-03-09', '21:34:34'),
(83, 35, '2021-03-09', '22:00:08'),
(84, 21, '2021-03-14', '21:23:11'),
(85, 20, '2021-04-18', '12:57:35'),
(86, 53, '2021-06-09', '11:44:00'),
(87, 53, '2021-06-09', '11:45:49'),
(88, 53, '2021-06-14', '12:00:41'),
(89, 59, '2021-06-14', '12:07:03'),
(90, 58, '2021-06-14', '12:07:21'),
(91, 57, '2021-06-14', '12:08:01'),
(92, 56, '2021-06-14', '12:08:20'),
(93, 55, '2021-06-14', '12:09:59'),
(94, 54, '2021-06-14', '12:10:16'),
(95, 52, '2021-06-14', '12:10:38'),
(96, 49, '2021-06-14', '12:10:52'),
(97, 48, '2021-06-14', '12:11:07'),
(98, 40, '2021-06-14', '12:11:10'),
(99, 56, '2021-06-14', '12:11:30'),
(100, 21, '2021-06-14', '12:13:21'),
(101, 53, '2021-06-14', '12:13:34'),
(102, 53, '2021-06-15', '12:30:03');

PAGO
CREATE TABLE `pago` (
  `id_pago` int(11) NOT NULL,
  `nombre_cliente_pago` int(11) NOT NULL,
  `cobertura_pago` date DEFAULT NULL,
  `pago` decimal(9,2) DEFAULT NULL,
  `fecha_creacion_pago` date DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

INSERT INTO `pago` (`id_pago`, `nombre_cliente_pago`, `cobertura_pago`, `pago`, `fecha_creacion_pago`) VALUES
(1, 20, NULL, NULL, NULL),
(4, 23, NULL, NULL, NULL),
(5, 26, NULL, NULL, NULL),
(6, 27, NULL, NULL, NULL),
(7, 28, NULL, NULL, NULL),
(8, 29, NULL, NULL, NULL),
(9, 30, NULL, NULL, NULL),
(10, 31, NULL, NULL, NULL),
(11, 32, NULL, NULL, NULL),
(12, 33, NULL, NULL, NULL),
(13, 34, NULL, NULL, NULL),
(15, 36, NULL, NULL, NULL),
(16, 39, NULL, NULL, NULL),
(17, 53, '1971-01-27', '490.00', NULL),
(18, 42, NULL, NULL, NULL),
(19, 44, NULL, NULL, NULL),
(20, 45, NULL, NULL, NULL),
(21, 46, NULL, NULL, NULL),
(22, 47, NULL, NULL, NULL),
(23, 48, NULL, NULL, NULL),
(24, 49, NULL, NULL, NULL),
(25, 50, NULL, NULL, NULL),
(26, 51, NULL, NULL, NULL),
(27, 52, NULL, NULL, NULL),
(28, 53, NULL, NULL, NULL),
(29, 53, '2021-04-08', '300.00', '2021-04-02'),
(31, 30, '2021-04-02', '1234.00', '2021-04-24'),
(32, 30, '2021-04-03', '900.00', '2021-04-24'),
(33, 20, '2021-04-04', '900.50', '2021-04-25'),
(34, 54, NULL, NULL, NULL),
(35, 55, NULL, NULL, NULL),
(36, 56, NULL, NULL, NULL),
(37, 56, '2021-06-15', '300.00', '2021-06-11'),
(38, 57, NULL, NULL, NULL),
(39, 58, NULL, NULL, NULL),
(40, 59, NULL, NULL, NULL),
(41, 60, NULL, NULL, NULL),
(42, 56, '2021-06-16', '123.00', '2021-06-18');

Las tres tablas anteriormente mencionadas, hago la unión con la siguiente consulta.
SELECT
    es.id_entrada_salida AS 'id_entrada_salida',
    es.fecha_entrada_salida AS 'f_entrada_salida',
    es.hora_entrada_salida AS 'h_entrada_salida',

    c.id_cliente AS 'id_cliente',
    c.nombre_cliente AS 'nombre_cliente',
    c.apellido_cliente AS 'apellido_cliente',
    c.gimnasio_cliente AS 'gimnasio_cliente',

    IFNULL(p.id_pago, 'Sin datos') AS 'id_pago',
    IFNULL(p.nombre_cliente_pago, 'Sin datos') AS 'id_cliente_en_el_pago',
    IFNULL(p.cobertura_pago, 'Sin datos') AS 'cobertura_pago',
    IFNULL(p.pago, 'Sin datos') AS 'pago',
    IFNULL(p.fecha_creacion_pago, 'Sin datos') AS 'fecha_pago'

FROM entrada_salida es
LEFT JOIN cliente c
ON es.cliente_entrada_salida = c.id_cliente
LEFT JOIN pago p
ON c.id_cliente = p.nombre_cliente_pago
WHERE c.gimnasio_cliente = 64

ORDER BY
    es.id_entrada_salida
DESC;

Lo cual me da como resultado lo siguiente:

El detalle aquí, es que quiero mostrar SOLO el ultimo pago (de la tabla pago) del id_cliente y no me muestre los 3 pagos que tiene.
En este caso, muestra del id_entrada_salida (102) los tres pagos que tiene (1971-01-27, Sin datos, 2021-04-08).
Esto del id_entrada_salida para que no se repita (dependiendo del pago) utilicé un GROUP BY es.id_entrada_salida después del WHERE y antes de ORDER BY.
Ya que se repetía dependiendo del numero de pagos del cliente.
Lo cual me da como resultado lo siguiente.

Ahora no se me repiten los id_entrada_salida pero me muestra solo el primer pago del cliente (1971-01-27) y no el ultimo (2021-04-08) como se muestra en la imagen anterior.
Espero y haberme explicado bien, también poner toda la información posible y los detalles del problema en el cual quiero expresar bien este problema que tengo.
Hice un esfuerzo en solucionar el problema yo mismo, en investigar y leer, pero por el momento estoy bloqueado con este detalle de la consulta en la base de datos.
De antemano, muchas gracias por leer todo esto.

A: Creo que la solución está en agrupar por cllientes y no buscar todas las fechas sino solo la última max().
SELECT
es.id_entrada_salida AS 'id_entrada_salida',
es.fecha_entrada_salida AS 'f_entrada_salida',
es.hora_entrada_salida AS 'h_entrada_salida',

c.id_cliente AS 'id_cliente',
c.nombre_cliente AS 'nombre_cliente',
c.apellido_cliente AS 'apellido_cliente',
c.gimnasio_cliente AS 'gimnasio_cliente',

IFNULL(p.id_pago, 'Sin datos') AS 'id_pago',
IFNULL(p.nombre_cliente_pago, 'Sin datos') AS 'id_cliente_en_el_pago',
IFNULL(max(p.cobertura_pago), 'Sin datos') AS 'cobertura_pago',
IFNULL(p.pago, 'Sin datos') AS 'pago',
IFNULL(p.fecha_creacion_pago, 'Sin datos') AS 'fecha_pago'

FROM entrada_salida es
JOIN cliente c ON es.cliente_entrada_salida = c.id_cliente
JOIN pago p ON c.id_cliente = p.nombre_cliente_pago
WHERE c.gimnasio_cliente = 64

GROUP BY nombre_cliente_pago
ASC;

Aquí muestra solo el último pago para los que tienen uno o más pagos.


text:
Q: how to find wordpress files on linux installed from bitnami super frustrated by this problem. I am trying to learn wordpress development and I have been trying for hours to find the files I need such as functions.php but alas I can not find the files
Does anyone know where functions.php and other wordpress files would be on linux installed from bitnami?
I have found /opt/lampp/var/mysql but I can not access it with the permissions it has.
I have tried changing the permissions using chmod but I still can not get into it.

A: it's under apps/wordpress/
The following is from their readme file.
apache2/: Apache Web server.
        varnish/: Varnish Cache
    php/: PHP Scripting Language.
    mysql/: MySQL Database.
    apps/
      wordpress/: WordPress application folder
        conf/: WordPress Apache configuration files
        htdocs/: WordPress PHP application files
      phpMyAdmin/: phpMyAdmin application folder (optional)


text:
Q: Convert the map key and value pair as two fields in a struct in golang I am trying to convert a map's key value pair into a struct's two fields that I have, but facing some issue while doing it.

type A struct{
Name string
Value float64
}

type B struct {
    ListOfMetrics []*A
}

func (n *A) UnmarshalYAML(unmarshal func(interface{}) error) error {
    type origA struct {
        Metrics     map[string]float64 `protobuf:"bytes,2,opt,name=metric" json:"metrics"`
        ListOfMetrics []*A
    }
    var oN origA
    err := unmarshal(&oN)
    if err != nil {
        return err
    }
    var Dp []*A
    for metric, value := range oN.Metrics {
        fmt.Println(metric, value)
        n := A{}
        n.Metric = metric
        n.Value = value
        Dp = append(Dp, &n)

    }
    oN.ListOfMetrics = Dp
    var m *B
    m.ListOfMetrics = oN.ListOfMetrics
    return nil

Basically I am trying to get the Metrics field of map[string]float64 into a struct of Metric name string and Metric value float64, which needs to be stored as a list of metric name and values. Can anyone please help?

A: Your method UnmarshalYAML is defined for A, but A is just a pair.
For me.. make sense put it in B
Also your logic seems complex. You create a local variable with your content and there is no way to recover it from outside (without an extra effort)
I wrote a small example using json as base, can be a starting point
https://go.dev/play/p/13lDeu3BkwQ


text:
Q: Extract middle part of string Teradata I am stuck trying to figure out why my REGEX expression in Teradata works sometimes but not always: i am trying to extract part of the string in the middle that has a pattern: it starts with ABC and is followed by 3 or 4 digits.
select RegExp_Substr('X886782E-ABC2036-VACCINE COVID', '[ABC]+[0-9]+')

My logic works most of the time, but not always: it does not always recogize part of the string that starts with ABC and is followed by 3-4 digits.

A: With Cary Stoveland's help, either of these line of code will help extract middle part of the string that starts with ABC and is followed by 3-4 digits:
select RegExp_Substr('X886782E-ABC2036-VACCINE COVID', 'ABC[0-9]+')
select RegExp_Substr('X886782E-ABC2036-VACCINE COVID', 'ABC\d+')
select RegExp_Substr('X886782E-ABC2036-VACCINE COVID', '\bABC[0-9]+')
select RegExp_Substr('X886782E-ABC2036-VACCINE COVID', '(?<=-)ABC[0-9]+')


text:
Q: Hover and onclick functionality issue in jquery I want to have onclick and hover functionality simultaneously but if you have clicked somewhere then hover should not work until I click somewhere else. I have tried alot but I didn't find any working code. Kindly help
 canvas.addEventListener('mousedown', function(evt) {
    }, false);
canvas.onmousemove = function(evt) {

 };

A: Well, I am not quite sure what you need and why you need it. But, in that short piece of code you wrote I saw the word "canvas" and thought "what the heck, that could be fun!". I have not much experience with the canvas element since earlier, so I realize there may be better ways of writing this code.
But, I hope what I wrote in the below example is at least close to what you were looking for. Otherwise, go nuts and change and adapt the way you like... and while you do that, try to learn something of it.

var Canvas = function() {
  this.$canvas = $('canvas');
  this.$currPos = $('#currPos');
  this.$currClick = $('#currClick');
  this.$clickInfo = $('#clickInfo');

  this.canvsWidth = 150;
  this.cavasHeight = 150;
  this.ctx = ctx = this.$canvas[0].getContext('2d');
  this.rect = this.$canvas[0].getBoundingClientRect();
  this.squares = [];
  this.sqm = 50;

  this.tracker = 0;
  this.latestHover = {};

  this._events();
  this._prepare();
};

Canvas.prototype._events = function() {
  var self = this;

  this.$canvas.on('mousemove', function(e) {
    var posX = e.clientX - self.rect.left,
        posY = e.clientY - self.rect.top,
        newX = Math.floor(posX / self.sqm),
        newY = Math.floor(posY / self.sqm);

    if($.isEmptyObject(self.latestHover) || (self.latestHover.x !== newX || self.latestHover.y !== newY)) {
      self.latestHover.x = newX;
      self.latestHover.y = newY;

     self.squares.map(function(k, v) {
      let obj = self.squares[v];
      if(!obj.fixedBackground) obj.reverseBackgroundColor();
     });

      var square = self.findObject(newX, newY)[0];
      if(square) {
        square.setBackgroundColor('#ff0000');

        self.$currPos.html(newX +'x'+ newY);
        self._redraw();
      }

    }
  });

  this.$canvas.on('click', function() {
    if(self.tracker === 2) {
      return self._reset();
    }

    if(!($.isEmptyObject(self.latestHover))) {
      var x = self.latestHover.x,
          y = self.latestHover.y;

      var square = self.findObject(x, y)[0];
          square.setFixedBackground();

      self.$currClick.html(x +'x'+ y);
      self.setTracker();
    }
  });

};

Canvas.prototype._prepare = function() {
  for(var row = 0; row < 3; row++) {
    for(var col = 0; col < 3; col++) {
      this.squares.push(new Square(row, col, this.ctx, this.sqm));
    }
  }
};

Canvas.prototype._redraw = function() {
  var self = this;

  this.ctx.clearRect(0, 0, this.canvasWidth, this.canvasHeight);

  this.squares.filter(function(k, v) {
    self.squares[v].draw();
  });
};

Canvas.prototype.setTracker = function() {
  this.tracker++;

  if(this.tracker === 2) this.$clickInfo.html('Click one more time to start over');
};

Canvas.prototype.findObject = function(x, y) {
  var self = this;

  return square = self.squares.filter(function(k, v) {
      var obj = self.squares[v];
      if(obj.posX === x && obj.posY === y) return obj;
    });
};

Canvas.prototype._reset = function() {
  var self = this;

  this.squares.map(function(k, v) {
    let obj = self.squares[v];
        obj.reverseBackgroundColor();
        obj.unsetFixedBackground();
  });

  this.$currClick.html('');
  this.$clickInfo.html('');
  this.tracker = 0;
  this._redraw();
};

var Square = function(x, y, ctx, sqm) {
  this.ctx = ctx;
  this.sqm = sqm;
  this.posX = x;
  this.posY = y;
  this.background = '#fff';
  this.strokeThickness = 1;
  this.fixedBackground = false;

  this.draw();
};

Square.prototype.setBackgroundColor = function(color) {
  return this.background = color;
};

Square.prototype.reverseBackgroundColor = function() {
  return this.background = '#fff';
};

Square.prototype.setFixedBackground = function() {
  return this.fixedBackground = true;
};

Square.prototype.unsetFixedBackground = function() {
  return this.fixedBackground = false;
};

Square.prototype.draw = function() {
  this.ctx.fillStyle = this.background;
  this.ctx.fillRect(this.posX * this.sqm, this.posY * this.sqm, this.sqm, this.sqm);
  this.ctx.strokeRect(this.posX * this.sqm, this.posY * this.sqm, this.sqm, this.sqm);
};

window.Canvas = new Canvas();
canvas {
  border: 1px solid #ccc;
}

<canvas width="150" height="150"></canvas>

  Current position:

  Last click:


text:
Q: Attaching Informix .dat and .idx files We are trying to duplicate one of our informix database on a test server, but without Informix expertise in house we can only guess what we need to do.  I am learning this stuff on the fly myself and nowhere near the expertise level needed to operate Informix efficiently or even inefficiently.  Anyhow...
We managed to copy the .dat and .idx files from the live server somewhere.  Installed Linux and the latest Informix Dynamic Server on it and have it up and running.
Now what should we do with the .dat and idx files from the live server?  Do we copy it somewhere and it will recognize it automatically?
Or is there an equivalent way like you can do attach DB from MS SQLServer to register the database files in the new database?
At my rope end...

A: You've asked a pretty complicated question without realizing it. Informix is architected as a shared everything database engine, meaning all resources available to the instance are available to every database in that instance. This means that more than one database can store data in any given dbspace, .dat or .idx file in your case. Most DBA's know better than to do that but it's something to be aware of. Given this knowledge you now know that the .dat and .idx files do not belong to a database but belong the instance. The dbspaces and files were created to contain your databases data but they technically belong to the instance. It's worth noting that the .dat and .idx files are known to the database by the logical dbspace name.
Armed with this background info and assuming that the production and development servers are running the same OS and that your hardware is relatively the same, not a combination of PARISC, Itanium or x86/x64, I'll throw a couple of options out for you.

*

*Create the dbspaces that you need in the new instance and use onunload and onload
to copy the database from production to development.

*Use ontape or onbar to backup the entire production instance and
restore it over your development instance.

Option 1 requires that you know what the dbspaces are named and how large they are. Use onstat -d on the production instance to find this out. BTW, the numbers listed in onstat -d are in pages, I believe that Linux is a 2K page.
Option 2 simply requires that the paths for the data files are the same on both servers. This means that the ROOTDBS needs to be the same in both instances. That can be found by executing onstat -c | grep ROOTDBS
There's a lot that has been left out but I hope that this gives you the info that you need to move forward with your task.

A: The .dat and .idx files are associated with C-ISAM, or, when organized in a directory called dbase.dbs (where dbase is the name of your database), the .dat and .idx files are associated with Informix Standard Engine, aka Informix SE.  SE uses C-ISAM to manage its storage.  SE is rather different from (and much simpler than) Informix Dynamic Server (IDS).  It is not impossible that the .dat and .idx files are associated with IDS; it is just extremely unlikely.
From the information available, it sounds as though your production server is running SE.  To get the data from SE to IDS, you will probably want to use DB-Export at the SE end and DB-Import at the Linux/IDS end.  Certainly, that is the simplest way to do it.
There are other possible solutions - C-ISAM datablade being one such - but they are more expensive and probably not warranted.  There are other possible loading solutions, such as HPL (High-Performance Loader).
For more information about Informix, either use the various web sites already referenced (http://www.informix.com is a link to the Informix section of IBM's web site), or use the International Informix User Group (IIUG) web site.  There are mailing lists available (which require you to belong, but membership is free) for discussing Informix in detail.

A: Those Informix-SE datafiles (.DAT) and their associated index files (.IDX) are useless unless you also have all the associated catalog files, such as SYSTABLES.DAT SYSTABLES.IDX, SYSCOLUMNS, SYSINDEXES, etc.
Then you also have to worry about which version of Informix-SE created them, as some have a 2K or 4K index file node size.
Your best approach is to obtain all the .DAT and .IDX files from the source db, plus the correct standard engine, installed on the same hardware and operating system it came from.
Long story short, on the source machine, run "dbexport" to unload all the data to ascii files, and run "dbschema" to generate all the table schemas and indexes. It also wouldn't hurt to run a "bcheck" on all the files before unloading them to ascii flat files.

A: I don't have any Informix-specific advice but for situations like this you can usually find the answer by looking up how to move a database (a common admin task, and usually well described in the manual) and just skipping the steps that would remove the old database.
Also, be careful of problems caused by different system architectures; some DBs fail spectacularly if you move them from a big-endian system (such as Solaris) to a little-endian system (such as x86 Linux)  Again, the manual section on moving a DB would cover any extra steps that are needed.


text:
Q: reactjs mobx without decorators not working I am trying to incorporate mobx with react. Since I spawned my application using create-react-app, I can't use decorators given by mobx.
Given that we can use mobx without decorators as per this documentation: https://mobxjs.github.io/mobx/best/decorators.html
Here's a component that I created:
import React, { Component } from 'react';
import observer from 'mobx-react';

export const TestComponent = observer(class TestComponent extends Component {

  render() {
     return
Just a test component!

  }

});

Here's a simple calling of the above component:
import React, { Component } from 'react';

import './App.css';

import Auth from './Auth'
import { TestComponent } from './Test'

import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';

import AppBar from 'material-ui/AppBar';
import  authStore  from './stores/Store'

class App extends Component {

    constructor(props) {
        super(props);
        this.state = {
        }
    }

    render() {
    return (

            <MuiThemeProvider>

                    <TestComponent store={authStore} />

            </MuiThemeProvider>

    );
  }
}

export default App;

Now when I run the above component, I get error: Uncaught TypeError: (0 , _mobxReact2.default) is not a function(…) nothing get displays in console.
What am I doing wrong here?

A: Please use import {observer} from 'mobx-react';
N.B. note that decorators can be used with create-react-app by using custom-react-scripts, as explained here)


text:
Q: Android Layout design tips For a school project, I try to implement a design for an Android application.
Image 1:

Image 2:

As you can see, I have a list with some items. When the user clicks on an item, a little detailpage appear under the clicked item. Actually, I'm not sure if I should use a ListView in my example.
Creating a ListView with all items works for me. But for the detail information, I don't know what to do.
Are there some tips & tricks for designing this page?
Thanks in advance!

A: Use ExpandableListView see references here

A: You could use custom BaseAdapter, on getViewTypeCount() return 2 and depending on click, changing the clicked list element type, invalidate list, and on getView() generate view depending on itemType. No animation though.


text:
Q: Non blocking read and blocking write on Posix PIPE I'm writing Client-Server application using posix FIFO to communicate. Both client and server are single thread and single process application.
The server is design to handle multiple clients. Each client has own pair of named pipe, one to send messages from Server to this Client and the other to send messages from Client to the Server.
The idea is quite simple, Server loops through all Client to Server pipes and check if there is something to read there.
My first implemenentation was sth like:
/* SERVER */
int desc = open(pipeName, O_RDONLY | O_NDELAY); //1
assert(desc > 0); //just simplyfing error handling
int read = read(desc, buffer, BUFSIZE); //2
if(read > 0)
  do_stuff();
close(desc); //3

/* CLIENT */
int desc = open(pipeName, O_WRONLY) //4
assert(desc > 0); //just simplyfing error handling
int read = write(desc, buffer, BUFSIZE) //5
close(desc); //6

As far as I know this code is invalid.
There are race conditions and for example an order of calls like: 1, 2, 4, 3, 5, 6 - will probably cause SIGPIPE.
The problem is that nonblocking read open is always successful even if there is no writer on the other side of PIPE.
That means that if Client will block on open() then server do nonblocking open (which will unlock Client) and then read() which will return 0 because at the moment nothing will be in PIPE and close() afterwards, then when control will go back to client which want to do write() on opened PIPE it will cause SIGPIPE as the reader is no longer available (server already closed the pipe).
For now i see two solutions:

*

*Handle SIGPIPE in Client with "tryAgain()" - this looks really bad, if i do such thing there is no guarantee that it will work at any moment - it will depend on possibility of good command processing order...

*Keep reading PIPE open all the time in Server (open it once and close when connection will be considered finished) - it is inconvenient in my application architecture but of course possible. I guess it will fix the problem but I'm not sure about that.

Here are my questions:

*

*Is any of those two approaches correct way to do that?

*Is there any other way to handle that scenario?

*Do you think second solution will work correctly?

*What would you choose and why?

Thanks for every answer.

A: I'm having a lot of trouble understanding your question.  Things
Client will block on open()  <== nothing blocks on open
Use select or epoll to determine which file descriptors are readable and writeable.
Then, just call read on those.
You will be notified that the client closed the pipe as a read event you'll need to handle and not write if it is closed.
http://linux.die.net/man/4/epoll
https://banu.com/blog/2/how-to-use-epoll-a-complete-example-in-c/


text:
Q: Having trouble fixing my title in Wordpress I'm using this code in order to display what page the user is.
<title><?php
    global $page, $paged;
    wp_title( '|', true, 'right' );
    bloginfo( 'name' );
    $site_description = get_bloginfo( 'description', 'display' );
    if ( $site_description && ( is_front_page() ) )
        echo " | $site_description";
    if ( $paged >= 2 || $page >= 2 )
        echo ' | ' . sprintf( __( 'Page %s' ), x( $paged, $page ) );
?></title>

When clicking on the navigation it seem to be working properly and it also displays the correct title. But when I click on the pagination, the website shows only a blank page.
I'm using WP-PageNavi plugin to display the pagination.
When I hovered on the tab an error appeared:

A: Please check the second last line in your code block.
You have "x( $paged, $page ) );"
I think you should remove the "x", character.
EDIT: in fact, the correct (and accepted) solution is to replace "x" with "max" (see comment below)


text:
Q: Prove that the tangent bundle to a smooth manifold has a canonical orientation I'm having some trouble understanding the tangent space to a point on the tangent bundle.
I have to prove for homework that the tangent bundle to a smooth manifold has a canonical orientation, even if the manifold is not orientable.
My idea is that, given bases $(v^1,\ldots,v^n)$ and $(w^1,\ldots,w^n)$ for $T_pM$ at some point $p$, these will induce two different bases $(\hat{v^1},\ldots,\hat{v^n},\ldots)$ and $(\hat{w^1},\ldots,\hat{w^n},\ldots)$ of $T_{(p,v)}TM$ for some $v \in T_pM$, where the second half of the basis is the same (because the second half of the coordinates for $TM$ are in some sense the same no matter what domain of what chart you're in, since the map is always $v\frac{\partial}{\partial x^i} \mapsto v$), and then I can use the fact that the second half is the same to show that the orientation of the two bases is the same, and hopefully it will be compatible with the smooth structure. Unfortunately, I really can't conceptualize at all what the induced basis would be like, cause I feel like I don't really have any intuition about what $T_{(p,v)}TM$ is like. Can anyone help me understand/tell me if my approach is a good one? Thanks

A: I really don't think one can consider the orientation of the tangent bundle $TM$ canonical. What it's true is that $TM$ is always orientable. The easiest way is to exhibit a positive atlas. To do that, let $\varphi_i:U_i\to V_i\subset M$ be a familly of parametrizations of the manifold $M$, where the $U_i$'s are open in, say, $\mathbb R^n$ and $V_i$ are open in $M$ and cover $M$. Then the mappings
$$
\varPhi_i:U_i\times\mathbb R^n\to TV_i\subset TM_i:(x,u)\mapsto(\varphi_i(x),d_x\varphi_i(u))
$$
give a positive atlas of $TM$. The point is to check the jacobian determinants of the changes $H=\varPhi_j^{-1}\circ\varPhi_i$ are positive. To that end, denote $h=\varphi_j^{-1}\circ\varphi_i$, which is a diffeo. A little computation shows that
$H(x,u)=(h(x),d_xh(u))$, hence $$JH(x,u)=\begin{pmatrix}Jh(x)&0\\*&Jh(x)\end{pmatrix}.$$ (Notice that the first component of $H$ does not depend on $u$ and the second component $d_xh(u)$ of $H$ is linear with respect to $u$, hence its derivative with respect to $u$ is $d_xh$.) Consequently $\det JH(x,u)=(\det Jh(x))^2>0$.


text:
Q: Prove that the derivative of a vector with constant module is perpendicular I am told to prove that the derivative of a vector with constant module is perpendicular to the vector. Here is my approach, though I'm not sure about if it's correct or not:
Let $A(t)$ be a constant vector with $|A(t)|=C$, where C is a constant. Then,
$|A(t)|=\sqrt{x(t)^2+y(t)^2+z(t)^2}=C$, and therefore, $|A(t)|'=(\sqrt{x(t)^2+y(t)^2+z(t)^2})'=0$, thus:
$(x(t)^2+y(t)^2+z(t)^2)'=0$. Since all terms are $>=0$, we can deduce $x'(t)=y'(t)=z'(t)=0$ (I think here's what I'm doing wrong).
Now we can say $A(t)·A'(t)=x(t)x'(t)+y(t)y'(t)+z(t)z'(t)=0$, and therefore they are perpendicular.
I think this is wrong because of  $x'(t)=y'(t)=z'(t)=0$, which would imply the derivative is the vector 0, which has no sense. But I haven't got a better approach.


text:
Q: Spring-Data @Query with Collection params Below is my repository method
List<Shipment> findByProductCategoriesBetweenQuarter( Set<Category> categories, Quarter from, Quarter to)

where Category is an Entity and Quarter is @Embeddable as below
class Quarter {
 int year;
 Quarters q; //Enum
}

I would like to create a custom Repository impl with @Query with a below representational query
@Query("select s from Shipment s where Category in (categories) and Quarter between (from, to)")

Looks like @Query works pretty well with primitives, couldn't find an example which could help me implement the case above.
so couple of question here
1. Is it possible at all
2. If possible, requesting some reference.
PS: Cant do QueryDSL now.

A: JPA will store Enum ordinal as int in the database tables.
So you can do the following.
@Query("select s from Shipment s where Category in (categories) and Quarter between (from.ordinal(), to.ordinal())")


text:
Q: datarow values comparision with c# I have a sql database with a table that contains my grading scales and comment e.g
debut        end        comment
5  ----       10   --      x
0  ----        4   ---     y

I have managed to iterate through the rows of my table with a foreach loop.
I want to supply a value, maybe with a text box control, then the program should check the range in my gradingScale table where the value follows and outputs a corresponding comment
for example
int number;
number=4

comment=y;

A: Not sure what you're looking for - and you didn't mention what database you're using - so here I'm just guess that you might be looking for something like this:
DECLARE @Number INT
SET @Number = 4

SELECT comment
FROM dbo.gradingScale
WHERE @Number BETWEEN debut AND end

Of course, you could also wrap this inside a stored procedure (if your database supports that):
CREATE PROCEDURE dbo.GetComment (@Number INT)
AS
   SELECT comment
   FROM dbo.gradingScale
   WHERE @Number BETWEEN debut AND end

These code samples are for Microsoft SQL Server 2005 and up (T-SQL).

A: Hard to make out what you want exactly, but here's an example implementation (You don't say how or in what form your Sql results are returned, so I've provided a DTO/List implementation:
static void SO6648999()
{
    List<test> sample = new List<test>
        {
        new test {  debut = 0,
                    end = 4,
                    comment = "y"},
        new test {  debut = 5,
                    end = 10,
                    comment = "x"}
        };
    int number = 4;
    string comment = sample.Single(x => number >= x.debut && number <= x.end).comment;
}

class test
{
    public int debut;
    public int end;
    public string comment;
}

A: If I understand correctly, your database list ranges, each associated with a comment. In your example 0 to 4 map to x, while 5 to 10 map to y.
In that case, a very simple approach would be, assuming that your ranges are not overlapping, to sort your table by ascending debut, and then iterate over the rows until you find one which start is <= to your value.

A: I believe you are referring to DataTable
You can use a Select on the DataTable and filter out the records by providing an expression. It works similar to a where clause in Sql.
dt1.Select("end = 4")// assuming column holding int value

end is the column name of the value you are searching and this will return the datarow (array) satisfying the condition.


text:
Q: How to clear AWS RDS Aurora MySQL local storage? I got a warning message about running out of AWS RDS local storage.

The free storage capacity for DB Instance: {MY INSTANCE NAME} is low
at 2% of the provisioned storage [Provisioned Storage: 157.36 GB, Free
Storage: 3.35 GB]. You may want to increase the provisioned storage to
address this issue.

According to the AWS document, local storage depends on instance type and can be increased by scale up : https://aws.amazon.com/premiumsupport/knowledge-center/aurora-mysql-local-storage/?nc1=h_ls
But, I would like to clear the local storage instead of scaling up the instance because only one instance of the read cluster has insufficient local storage.
I restarted Aurora instance but the local storage is still almost full.
How can I clear local storage?
It's MySQL version is 5.6.

A: I asked to AWS about this issue and got answers.
It was a bug on oscar5.6.mysql_aurora.1.23.2 version.
Because of the bug, the size of the log file continued to increase.
The bug was solved on 2.10.2 version.
I upgraded the Aurora MySQL cluster from oscar5.6.mysql_aurora.1.23.2 to aurora-mysql:5.7.mysql_aurora.2.10.2.
Then, I created new instances on the same cluster and deleted old instances. - BingbngKim


text:
Q: How do you construct a definition query to return only those features in the current month without hard coding the date? I have a feature class containing a date field within a 9.3.1 File Geodatabase. There are "duplicate" features contained within this layer, one feature for each month over the past few months.
However, the final dataset may contain dates for the last few years.
| Feature 1 | '2012-05-01' |
| Feature 1 | '2012-04-13' |
| Feature 1 | '2012-03-23' |
| Feature 1 | '2011-03-23' |
| Feature 2 | '2012-05-12' |
| Feature 2 | '2012-04-14' |
| Feature 2 | '2012-03-30' |
| Feature 2 | '2011-03-30' |
... and so on

I want to apply a definition query such that the map will only display features for the current month and year and I do not want to update the definition query each month.
I have attempted to use a combination of date, CURRENT_DATE, EXTRACT, and CONCAT but without much success. Ultimately I think I need a definition query that looks something like this but with the hard-coded dates removed.
DateField >= date '2012-05-01' AND DateField <= date '2012-05-31'

CURRENT_DATE returns the current date and can replace the second component to give:
DateField >= date '2012-05-01' AND DateField <= CURRENT_DATE

However I cannot seem to format the first component such that it always starts at the beginning of the current month. I attempted to format the date string via the CONCAT but I am unable to form valid SQL and I am not sure what the error is. Ignoring the CURRENT_DATE and EXTRACT methods for now gives me this invalid SQL:
DateField >= date CONCAT(CONCAT(CONCAT('2012', '-'), CONCAT('05', '-')), '01')

Ultimately the year and month would be replace by the current year and month using EXTRACT and CURRENT_DATE. However the "simplified" SQL above fails with a generic "An invalid SQL statement was used." error. I know I am doing something wrong but I am not sure what it is.
So, how do you construct a definition query to return only those features in the current month without hard coding the date in ArcMap 9.3.1 in a 9.3.1 File Geodatabase?

A: Based on this, you can also do:
EXTRACT(MONTH from DateField) = EXTRACT(MONTH from CURRENT_DATE) AND EXTRACT(YEAR from DateField) = EXTRACT(YEAR from CURRENT_DATE)

Or a shorter solution that would also work is:
DateField >= CURRENT_DATE - EXTRACT(DAY FROM CURRENT_DATE)

A: The following will do what you want, providing that your date field is of "date" data type:
EXTRACT(MONTH FROM "your_date_field" ) = EXTRACT(MONTH FROM CURRENT_DATE)


text:
Q: IF condition for INSERT AND UPDATE in SQL I have a table called EMPLOYEE and created a new table EMPLOYEE_SALARY_CHANGE (to track employee salary changes)
here is EMPLOYEE table
ID | Employee_Salary | Active
1        500 -> 700       1
2          600            1
3         2100            1

500->700 means the employee_salary is changed from 500 to 700.
Here is EMPLOYEE_SALARY_CHANGE table
ID | Employee_Salary | Active
1          500            0
1          700            1
2          600            1
3         2100            1

when employee salary is changed from 500 to 700, I have to insert a new row in EMPLOYEE_SALARY_CHANGE
and update existing one's active to 0.
IF (EMPLOYEE.EMPLOYEE_SALARY != EMPLOYEE_SALARY_CHANGE.EMPLOYEE_SALARY,
INSERT EMPLOYEE_SALARY_CHANGE INTO (EMPLOYEE.ID,EMPLOYEE.EMPLOYEE_SALARY,1) UNION
UPDATE EMPLOYEE_SALARY_CHANGE SET ACTIVE = 0 WHERE EMPLOYEE.EMPLOYEE_SALARY = EMPLOYEE_SALARY_CHANGE.EMPLOYEE_SALARY))

but there is something wrong. Do you think it is better to use php or can be handled in sql?

A: One method uses union all:
select id, substring_index(employee_salary, ' -> ', 1) + 0 as employee_salary,
       (employee_salary not like '% -> %') as active
from t
union all
select id, substring_index(employee_salary, ' -> ', -1) + 0, 1
from t
where employee_salary like '% -> %';

A: Normally you would use a trigger to handle the upsert . For example
drop table if exists employee,employee_salary_change;
create table employee
(ID  int, Employee_Salary int, Active int);
insert into employee values
(1      ,    500   ,     1),
(2      ,    600   ,     1),
(3      ,    2100  ,     1);

create table EMPLOYEE_SALARY_CHANGE(
ID int, Employee_Salary int, Active int);
insert into employee_salary_change values
(1   ,       500   ,         1),
(2   ,       600   ,         1),
(3   ,      2100   ,         1);

drop trigger if exists t;
delimiter $$
create trigger t after update on employee
for each row
begin
    update employee_salary_change
        set active = 0 where id = new.id;
    insert into employee_salary_change values (new.id,new.employee_salary,new.active);
end $$

delimiter ;
update employee
    set employee_salary = 700 where id = 1;
select * from employee;
+------+-----------------+--------+
| ID   | Employee_Salary | Active |
+------+-----------------+--------+
|    1 |             700 |      1 |
|    2 |             600 |      1 |
|    3 |            2100 |      1 |
+------+-----------------+--------+

select * from employee_salary_change;

+------+-----------------+--------+
| ID   | Employee_Salary | Active |
+------+-----------------+--------+
|    1 |             500 |      0 |
|    2 |             600 |      1 |
|    3 |            2100 |      1 |
|    1 |             700 |      1 |
+------+-----------------+--------+

I assume your employee_salary_change table is simplified for the purpose of the question so I haven't tested to see if same salary already exists.


text:
Q: How to properly format Date in yyyy-mm-dd? I have a column in my table of Date type in MYSQL and inserting the date format of 25-March-2019 hh:mm:ss returns an error telling me incorrect data value.
So I have my code written like this:
 String startdt=request.getParameter("startdate");
    String enddate=request.getParameter("enddate");
    SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd");
    Date Startdate=dateFormat.parse(startdt);
    Date Enddate=dateFormat.parse(enddate);

And I am passing Startdate and Enddate to a function that inserts into my table column.
Is there a way I can have Startdate and Enddate above just return in yyyy-mm-dd without the time so I can insert to my db without error?

A: tl;dr
myPreparedStatement
.setObject(
    LocalDate.parse( "2019-01-23" )
) ;

DATE in MySQL is date-only
The DATE type in MySQL is a date-only value, without time-of-day and without time zone.
Excerpting from MySQL 8.0 documentation:

The DATE type is used for values with a date part but no time part. MySQL retrieves and displays DATE values in 'YYYY-MM-DD' format. The supported range is '1000-01-01' to '9999-12-31'.

Use a date-only type in Java for data coming from a date-only type in your database. The java.util.Date class you are trying to use is not a date, it is a moment in UTC, a date with time-of-day and offset-from-UTC of zero, all tracked as a count of milliseconds from the first moment of 1970 in UTC. The misnaming of that class is only the first of many poor design choices made by those programmers. Move on to java.time classes instead. Stop using Date.
MM = month number, not name
Your format of "yyyy-MM-dd" is for a numeric month, not the string of month name shown in your example value of 25-March-2019.
Avoid legacy date-time classes
The SimpleDateFormat and Date classes are terrible, a wretched mess of bad design. They were supplanted years ago with the adoption of JSR 310, implemented in the java.time classes.
Smart objects, not dumb strings
Exchange objects with your database where possible, not text.
As of JDBC 4.2, we can directly exchanged java.time objects with the database. For a date-only value, as with SQL-standard DATE type, use the java.time.LocalDate class.
Apparently, your text inputs for date values is YYYY-MM-DD which is standard ISO 8601 format. The java.time classes use ISO 8601 formats by default. So no need to specify a formatting pattern.
LocalDate localDate = LocalDate.parse( "2019-01-23" ) ;
myPreparedStatement.setObject( … , localDate ) ;

Retrieval.
LocalDate localDate = myResultSet.getObject( … , LocalDate.class ) ;

localDate.toString(): 2019-01-23

If you want to produce a string representing the value of that LocalDate object in a different textual format, use the DateTimeFormatter class. Search Stack Overflow for more info as it, like the rest of your Question, has been covered many times already on Stack Overflow. Do search Stack Overflow before posting.
Tip: Generally best to use a PreparedStatement in your JDBC work. One major benefit is thwarting SQL Injection security attacks.

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: Java 7 and ThreeTen Backport
    DateTimeFormatter formatter
            = DateTimeFormatter.ofPattern("d-MMMM-uuuu HH:mm:ss", Locale.ENGLISH);
    String dateFromHtmlForm = "25-March-2019 22:43:55";
    LocalDateTime dateTime = LocalDateTime.parse(dateFromHtmlForm, formatter);
    // We are discarding the time of day and only saving the date
    java.sql.Date dateToSave = DateTimeUtils.toSqlDate(dateTime.toLocalDate());

    String insertSql = "insert into your_table (your_date_column) values (?);";
    try (PreparedStatement insertStatement
            = yourDatabaseConnection.prepareStatement(insertSql)) {
        insertStatement.setDate(1, dateToSave);
        int rowsInserted = insertStatement.executeUpdate();
    }

As has already been said, pass date objects to MySQL, not strings. In Java 8 and later these would have been LocalDate objects, but in Java 7 we will need to make do with the poorly designed java.sql.Date class. It's still better than strings. And the conversion from LocalDate is straightforward.
On Java 7 we can use java.time through the backport, ThreeTen Backport (ThreeTen for JSR-310). My imports are:
import org.threeten.bp.DateTimeUtils;
import org.threeten.bp.LocalDateTime;
import org.threeten.bp.format.DateTimeFormatter;

Why would we want to use an external library for this? There are pros and cons, of course. Advantages include:

*

*java.time is so much nicer to work with than the old-fashoined Date and SimpleDateFormat and gives clearer code.

*It's future-proof: once you move to Java 8 or later, all you need to do is change your import statements (and discard the library and retest).

Links

*

*Oracle tutorial: Date Time explaining how to use java.time.

*Java Specification Request (JSR) 310, where java.time was first described.

*ThreeTen Backport project, the backport of java.time to Java 6 and 7.

*ThreeTenABP, Android edition of ThreeTen Backport

*Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.


text:
Q: Read webpage - avoid diamond / question mark for non-standard chars I'm trying to read a webpage that contains a registered trademark symbol in the content, i.e. ®.  However, when I use quickwatch and look at sb in the below example, I see a diamond with a question mark instead of ®.  The same issue occurs if I serialize sb and display it in another webpage via javascript.  Is this just how this char will appear in my quickwatch window, or am I reading/decoding the page incorrectly?  The code is as follows:
    const int bufSize = 4096;
    const int maxBytesToGet = 5000000;
    byte[] buf = new byte[bufSize];
    StringBuilder sb = new StringBuilder(bufSize);

    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
    {

        using (Stream responseStream = response.GetResponseStream())
        {
            while ((bytesToGet = responseStream.Read(buf, 0, buf.Length)) != 0)
            {
                sb.Append(Encoding.UTF8.GetString(buf, 0, bytesToGet));
                if (sb.Length > maxBytesToGet) break;
            }
        }
    }

A: You're assuming the response is UTF8.  You need to look at the response headers to see what the encoding actually is.  It's also easier to use a StreamReader instead of Encoding.GetString.
string responseText;

using (var response = (HttpWebResponse)request.GetResponse())
{
    using (Stream responseStream = response.GetResponseStream())
    {
        var encoding = Encoding.GetEncoding(response.CharacterSet);
        using(var reader = new StreamReader(responseStream, encoding))
        {
            responseText = reader.ReadToEnd();
        }
    }
}


text:
Q: Finding a function's parameters in Python I want to be able to ask a class's __init__ method what it's parameters are.  The straightforward approach is the following:
cls.__init__.__func__.__code__.co_varnames[:code.co_argcount]

However, that won't work if the class has any decorators.  It will give the parameter list for the function returned by the decorator.  I want to get down to the original __init__ method and get those original parameters.  In the case of a decorator, the decorator function is going to be found in the closure of the function returned by the decorator:
cls.__init__.__func__.__closure__[0]

However, it is more complicated if there are other things in the closure, which decorators may do from time to time:
def Something(test):
    def decorator(func):
        def newfunc(self):
            stuff = test
            return func(self)
        return newfunc
    return decorator

def test():
    class Test(object):
        @Something(4)
        def something(self):
            print Test
    return Test

test().something.__func__.__closure__
(<cell at 0xb7ce7584: int object at 0x81b208c>, <cell at 0xb7ce7614: function object at 0xb7ce6994>)

And then I have to decide if I want to the parameters from decorator or the parameters from the original function.  The function returned by the decorator could have *args and **kwargs for its parameters.  What if there are multiple decorators and I have to decide which is the one I care about?
So what is the best way to find a function's parameters even when the function may be decorated?  Also, what is the best way to go down a chain of decorators back to the decorated function?
Update:
Here is effectively how I am doing this right now (names have been changed to protect the identity of the accused):
import abc
import collections

IGNORED_PARAMS = ("self",)
DEFAULT_PARAM_MAPPING = {}
DEFAULT_DEFAULT_PARAMS = {}

class DICT_MAPPING_Placeholder(object):
    def __get__(self, obj, type):
        DICT_MAPPING = {}
        for key in type.PARAMS:
            DICT_MAPPING[key] = None
        for cls in type.mro():
            if "__init__" in cls.__dict__:
                cls.DICT_MAPPING = DICT_MAPPING
                break
        return DICT_MAPPING

class PARAM_MAPPING_Placeholder(object):
    def __get__(self, obj, type):
        for cls in type.mro():
            if "__init__" in cls.__dict__:
                cls.PARAM_MAPPING = DEFAULT_PARAM_MAPPING
                break
        return DEFAULT_PARAM_MAPPING

class DEFAULT_PARAMS_Placeholder(object):
    def __get__(self, obj, type):
        for cls in type.mro():
            if "__init__" in cls.__dict__:
                cls.DEFAULT_PARAMS = DEFAULT_DEFAULT_PARAMS
                break
        return DEFAULT_DEFAULT_PARAMS

class PARAMS_Placeholder(object):
    def __get__(self, obj, type):
        func = type.__init__.__func__
        # unwrap decorators here
        code = func.__code__
        keys = list(code.co_varnames[:code.co_argcount])
        for name in IGNORED_PARAMS:
            try: keys.remove(name)
            except ValueError: pass
        for cls in type.mro():
            if "__init__" in cls.__dict__:
                cls.PARAMS = tuple(keys)
                break
        return tuple(keys)

class BaseMeta(abc.ABCMeta):
    def __init__(self, name, bases, dict):
        super(BaseMeta, self).__init__(name, bases, dict)
        if "__init__" not in dict:
            return
        if "PARAMS" not in dict:
            self.PARAMS = PARAMS_Placeholder()
        if "DEFAULT_PARAMS" not in dict:
            self.DEFAULT_PARAMS = DEFAULT_PARAMS_Placeholder()
        if "PARAM_MAPPING" not in dict:
            self.PARAM_MAPPING = PARAM_MAPPING_Placeholder()
        if "DICT_MAPPING" not in dict:
            self.DICT_MAPPING = DICT_MAPPING_Placeholder()

class Base(collections.Mapping):
    __metaclass__ = BaseMeta
    """
    Dict-like class that uses its __init__ params for default keys.

    Override PARAMS, DEFAULT_PARAMS, PARAM_MAPPING, and DICT_MAPPING
    in the subclass definition to give non-default behavior.

    """
    def __init__(self):
        pass
    def __nonzero__(self):
        """Handle bool casting instead of __len__."""
        return True
    def __getitem__(self, key):
        action = self.DICT_MAPPING[key]
        if action is None:
            return getattr(self, key)
        try:
            return action(self)
        except AttributeError:
            return getattr(self, action)
    def __iter__(self):
        return iter(self.DICT_MAPPING)
    def __len__(self):
        return len(self.DICT_MAPPING)

print Base.PARAMS
# ()
print dict(Base())
# {}

At this point Base reports uninteresting values for the four contants and the dict version of instances is empty.  However, if you subclass you can override any of the four, or you can include other parameters to the __init__:
class Sub1(Base):
    def __init__(self, one, two):
        super(Sub1, self).__init__()
        self.one = one
        self.two = two

Sub1.PARAMS
# ("one", "two")
dict(Sub1(1,2))
# {"one": 1, "two": 2}

class Sub2(Base):
    PARAMS = ("first", "second")
    def __init__(self, one, two):
        super(Sub2, self).__init__()
        self.first = one
        self.second = two

Sub2.PARAMS
# ("first", "second")
dict(Sub2(1,2))
# {"first": 1, "second": 2}

A: Consider this decorator:
def rickroll(old_function):
    return lambda junk, junk1, junk2: "Never Going To Give You Up"

class Foo(object):
    @rickroll
    def bar(self, p1, p2):
        return p1 * p2

print Foo().bar(1, 2)

In it, the rickroll decorator takes the bar method, discards it, replaces it with a new function that ignores its differently-named (and possibly numbered!) parameters and instead returns a line from a classic song.
There are no further references to the original function, and the garbage collector can come and remove it any time it likes.
In such a case, I cannot see how you could find the parameter names p1 and p2. In my understanding, even the Python interpreter itself has no idea what they used to be called.


text:
Q: This comment has not yet been published to Facebook I am using FB:Comments on my page using XFBML. When I post a comment, an error comes up with the message "This comment has not yet been published to Facebook"
This is the code that I am using apart from the fb:comments tag

A: It looks this problem comes with ".info" domains.
Or it might be that this happens with top level domains with 4 or more letters, like .info, .name or .mobi, though I haven't investigated into all of them.

A: What attributes do you have set on the fb:comments tag? I believe all that's doing is the facebook connect/login side of things. Have you got the correct OG tags in place? You could also add in code to subscribe to the add comment event and see what's going on:

you may also need the channel file as detailed here https://developers.facebook.com/docs/reference/javascript/

A: I'm having the same problem. If I use the example page (http://developers.facebook.com/docs/reference/plugins/comments/) the comment gets posted on my wall, whereas doing the same in the comment box of my app does not, unless I pint them to a Facebook URL.
This works:
   <fb:comments   href="http://www.facebook.com/any-url/" ></fb:comments>

This doesn't if I do it from my app, but it works if I do it from my site (which doesn't really help for the purpose I need it to)
<fb:comments   href="http://www.mysite.com/any-other-url/" ></fb:comments>


text:
Q: SDL2 in Raspberry Pi 3B+ has no mouse events I have an application that works well with SDL 1.2 on Ubuntu 16.04. I migrated the code to use SDL 2.0 and it works without problems on linux/windows x86/x86_64. However, on Raspberry OS Buster i click and nothing happens.
I use a Buster lite loop-mounted image to cross-compile on Ubuntu 16.04, and a regular (non-lite, with X11) image for deployment.
Prior to switching to 2.0, these were the dependencies of SDL (in the chroot):
# objdump -x /usr/lib/arm-linux-gnueabihf/libSDL-1.2.so.0.11.4 | grep NEED
  NEEDED               libasound.so.2
  NEEDED               libm.so.6
  NEEDED               libdl.so.2
  NEEDED               libpulse-simple.so.0
  NEEDED               libpulse.so.0
  NEEDED               libX11.so.6
  NEEDED               libXext.so.6
  NEEDED               libXrandr.so.2
  NEEDED               libXrender.so.1
  NEEDED               libbcm_host.so
  NEEDED               libvcos.so
  NEEDED               libvchiq_arm.so
  NEEDED               libcaca.so.0
  NEEDED               libpthread.so.0
  NEEDED               libc.so.6
  NEEDED               ld-linux-armhf.so.3

I then replaced SDL 1.2 with 2.0, now they're slightly different:
# objdump -x /usr/lib/arm-linux-gnueabihf/libSDL2-2.0.so.0.9.0 | grep NEED
  NEEDED               libasound.so.2
  NEEDED               libm.so.6
  NEEDED               libdl.so.2
  NEEDED               libpulse-simple.so.0
  NEEDED               libpulse.so.0
  NEEDED               libsndio.so.7.0
  NEEDED               libbcm_host.so
  NEEDED               libX11.so.6
  NEEDED               libXext.so.6
  NEEDED               libXcursor.so.1
  NEEDED               libXinerama.so.1
  NEEDED               libXi.so.6
  NEEDED               libXrandr.so.2
  NEEDED               libXss.so.1
  NEEDED               libXxf86vm.so.1
  NEEDED               libwayland-egl.so.1
  NEEDED               libwayland-client.so.0
  NEEDED               libwayland-cursor.so.0
  NEEDED               libxkbcommon.so.0
  NEEDED               libpthread.so.0
  NEEDED               librt.so.1
  NEEDED               libc.so.6
  NEEDED               ld-linux-armhf.so.3

I have libudev-dev installed, but these are packaged versions, i'm not compiling anything yet. I don't see libudev.so mentioned above, but if 1.2 worked... I do have it though:
# find /usr/lib/ -type f -name "libudev*so*"
  /usr/lib/arm-linux-gnueabihf/libudev.so.1.6.13
  /usr/lib/arm-linux-gnueabihf/libudev.so.0.13.0

# apt list --installed | grep -i udev
  libudev-dev/oldstable,now 241-7~deb10u8+rpi1 armhf [installed,automatic]
  libudev0/oldstable,now 175-7.2 armhf [installed]
  libudev1/oldstable,now 241-7~deb10u8+rpi1 armhf [installed]
  udev/oldstable,now 241-7~deb10u8+rpi1 armhf [installed]

Considering these are packaged versions, i shouldn't be having this problem. SDL's ./confgure --help does list
--enable-libudev        enable libudev support [[default=yes]]

...so I assume it's a dependency. Must i cross-compile SDL 2.0 for armhf to get events to work? If so, is there a way to see which configuration flags were used?
Yes, the user is in the input group:
pi@raspberrypi:~ $ groups
pi adm dialout cdrom sudo audio video plugdev games users input netdev lpadmin gpio i2c spi

Strange how Buster lite (i.e. headless) has dependencies on libX11.so.
Edit1
Both checkkeys and testhittesting work when compiled on the pi.

Edit2
I debugged the application side-by-side on a x86_64 host and the armhf one, the code fails on a line like this:
if((child = dynamic_cast<Parent*>(parent)) != 0)

with child and parent being pointers to their respective structures. On armhf, this dynamic_cast always returns 0. Specifically it's a bunch of ifs trying to determine the object type to process an SDL event -- the events are being processed, just not handled properly.
I wrote this small program to test dynamic_cast on armhf but it seems to work (or my example code is wrong):
#include <iostream>

/* compiling with g++ armDynamicCast.cpp -std=c++11 -o armDynamicCast.x86_64
   results in:
      Parent age(0)
      Child1 age(0) name(name1)
      Child2 age(0) name(name2)
      pc1 not cast to cc1
      pc2 cast to cc1
  compiling with /usr/bin/arm-linux-gnueabihf-g++ armDynamicCast.cpp -std=c++11 -o armDynamicCast.armhf
  results in:
    Parent age(0)
    Child1 age(0) name(name1)
    Child2 age(0) name(name2)
    pc1 not cast to cc1
    pc2 cast to cc1
  so arm-linux-gnueabihf-g++ supports dynamic_cast
*/

struct Parent {
  int age;
  public:
  Parent() {
    age = 0;
  }

  virtual ~Parent() = default;

};

struct Child1 : Parent {
  std::string name;
  public:
  Child1() {
    name = "name1";
  }

};

struct Child2 : Parent {
  public:
  std::string name;
  Child2() {
    name = "name2";
  }

};

int main() {
  Parent p;
  Child1 c1; Child1* pc1 = &c1;
  Child2 c2; Child2* pc2 = &c2;
  std::cout << "Parent age(" << p.age << ")"                          << std::endl;
  std::cout << "Child1 age(" << c1.age << ") name(" << c1.name << ")" << std::endl;
  std::cout << "Child2 age(" << c2.age << ") name(" << c2.name << ")" << std::endl;

  Parent* fakeP1 = &c1;
  Parent* fakeP2 = &c2;
  Parent* fakePX = &c2;

  Child1* cc1 = dynamic_cast<Child1*>(fakePX);
  if(NULL != cc1) {
    std::cout << "pc1 cast to cc1" << std::endl;
  }
  else {
    std::cout << "pc1 not cast to cc1" << std::endl;
  }
  Child2* cc2 = dynamic_cast<Child2*>(fakePX);
  if(NULL != cc2) {
    std::cout << "pc2 cast to cc1" << std::endl;
  }
  else {
    std::cout << "pc2 not cast to cc1" << std::endl;
  }
  return 0;
}

I'm at a loss.
This Android-related answer seems to suggest moving destructors around. I couldn't duplicate the issue though.
This  suggests avoiding dynamic_cast by having specific method. A bit laborious (i have about 100 occurrences of dynamic_cast) but then again so is migrating from SDL 1.2.