text:
Q: OpenCV saving video to file I think my question is pretty basic, but I'm writing this code in OpenCV to simply capture video data from the webcam and save it to file. Now the problem is that the file gets made at the desired destination, it initially is about 286 bytes in size. Then when I assign the first frame to the pointer, the size increases to 414 bytes. However, when I run the whole code, the size of the saved video remains 414 bytes. Of course, as a result my media player cannot play the file and says " is not in a format that QuickTime Player understands." and the same happens with the VLC player.
Here is my code for the same:
#include <opencv2/opencv.hpp>
#include <opencv2/highgui/highgui.hpp>

int main( int argc, char** argv ) {
CvCapture* capture;

capture = cvCreateCameraCapture(0);

assert( capture != NULL );

IplImage* bgr_frame = cvQueryFrame( capture );

CvSize size = cvSize(
                     (int)cvGetCaptureProperty( capture,
                                               CV_CAP_PROP_FRAME_WIDTH),
                     (int)cvGetCaptureProperty( capture,
                                               CV_CAP_PROP_FRAME_HEIGHT)
                     );

cvNamedWindow( "Webcam", CV_WINDOW_AUTOSIZE );

CvVideoWriter *writer = cvCreateVideoWriter(    "/Users/user/Desktop/OpenCV_trial/OpenCV_trial/vidtry.AVI",
                                            CV_FOURCC('D','I','V','X'),
                                            30,
                                            size
                                            );

while( (bgr_frame = cvQueryFrame( capture )) != NULL )
{
    cvWriteFrame(writer, bgr_frame );
    cvShowImage( "Webcam", bgr_frame );
    char c = cvWaitKey( 33 );
    if( c == 27 ) break;
}
cvReleaseVideoWriter( &writer );
cvReleaseCapture( &capture );
cvDestroyWindow( "Webcam" );
return( 0 );
}

I don't know why this is happening. I am using the mac OSX Lion and running Xcode.
Has anyone faced this problem before? If so, how could I solve it?
Thank you!
-Yash

A: Hi I think I found the answer to the question.
As Velthune had suggested, it seems to be a codec issue and the MAC OS can run only a few of them. Here is the link for all the ones that work:
List of QuickTime codecs supported by the mac os port
Not all of the codecs listed there work though. Out of all the ones that I tried only the WRLE seemed to work.
Thanks a lot Velthune.
-Yash

A: Have you try to open your file with another player? VLC for instance..
This because Quicktime and .avi do not get along very well.
Take a look on apple documentation.
Otherwise try to change the video codec, this is the opencv reference.

A: Actually I too was trying to do same. But its that i tried in Visual C++ (Express Edition) in windows 7. But in this case we need to add extra header as "#include "stdafx.h" and also make sure the link to save the file exists. For example the code i modified was as:
#include "stdafx.h"
#include <opencv2/opencv.hpp>
#include <opencv2/highgui/highgui.hpp>

int main( int argc, char** argv ) {
CvCapture* capture;

capture = cvCreateCameraCapture(0);

assert( capture != NULL );

IplImage* bgr_frame = cvQueryFrame( capture );

CvSize size = cvSize(
                     (int)cvGetCaptureProperty( capture,
                                               CV_CAP_PROP_FRAME_WIDTH),
                     (int)cvGetCaptureProperty( capture,
                                               CV_CAP_PROP_FRAME_HEIGHT)
                     );

cvNamedWindow( "Webcam", CV_WINDOW_AUTOSIZE );

CvVideoWriter *writer = cvCreateVideoWriter("D:/vidtry.AVI",CV_FOURCC('D','I','V','X'),15,size);

while( (bgr_frame = cvQueryFrame( capture )) != NULL )
{
    cvWriteFrame(writer, bgr_frame );
    cvShowImage( "Webcam", bgr_frame );
    char c = cvWaitKey( 33 );
    if( c == 27 ) break;
}
cvReleaseVideoWriter( &writer );
cvReleaseCapture( &capture );
cvDestroyWindow( "Webcam" );
return( 0 );
}


text:
Q: how to compare two percentages to prove for statistical significance I have problem to compare the two percentages and to get the statistical significance for these two different percentage. I just want to approve whether these two percentages are significant or not significant using Microsoft Excel or SPSS. I attach with the image of my data.

Hopefully your help may lead me to correct method. Thank you.

A: Assuming you have the underlying numbers (as @gung asks), this is a classic case for a $\chi^2$ test. This is a basic test of association, and will give you a p-value to assess statistical significance. Just beware that $\chi^2$ tests are sensitive to sample size, so if you have a large sample, even small, non-substantive differences may come up as significant. I like to pair my $\chi^2$ tests with an effect size, which gets more at whether the difference is important. To calculate the effect size for a cross tab, use Cohen's w, which is easily created by calculating the standardized $\chi^2$ statistic - this is just calculating $\chi^2$ where the cell values are the overall table proportions (where the cell value is $N_{cell}/N_{table}$) (reference:  Cohen, J. (1992). Statistical Power Analysis. Current Directions in Psychological Science, 1(3), 98–101).
SPSS does it easily in its crosstab function. I think you have to hand calculate the $\chi^2$ statistic in Excel and then use one of its distribution formulas to get the p-value.
This link gives you more details on it, or you could refer to any introductory statistics text. This link and this link give you how to do it in SPSS.

redpajama_set_name: RedPajamaStackExchange


text:
Q: setBackgroundImage on TabBar does not work when tapping items I can set the background once, but after that it never changes again. I've seen all examples on stackoverflow. The code examples look always the same. I've set the delegate. The images are all ok. I've set them one after the other as default image and the will show. But after the app finished launching nothing happens with the background anymore.
Here's my code:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    [self customizeInterface];

    // Override point for customization after application launch.
    self.tabController = (UITabBarController *)self.window.rootViewController;
    self.tabController.delegate = self;
...
}

- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController
{
    int tabitem = self.tabController.selectedIndex;
    NSLog(@"tabitem: %i", tabitem);
    [self switchTabBarImage:tabitem];
    //[[tabController objectAtIndex:tabitem] popToRootViewControllerAnimated:YES];
}

- (void)switchTabBarImage:(int)selectedIndex
{
    NSLog(@"selected: %i", selectedIndex);
    if (selectedIndex == 0) {
        NSLog(@"0");
        UIImage *tabBarBackground = [UIImage imageNamed:@"tabbar-1.png"];
        [[UITabBar appearance] setBackgroundImage:tabBarBackground];
    }
    if (selectedIndex == 1) {
        NSLog(@"1");
        UIImage *tabBarBackground = [UIImage imageNamed:@"tabbar-2.png"];
        [[UITabBar appearance] setBackgroundImage:tabBarBackground];
    }
    if (selectedIndex == 2) {
        NSLog(@"2");
        UIImage *tabBarBackground = [UIImage imageNamed:@"tabbar-3.png"];
        [[UITabBar appearance] setBackgroundImage:tabBarBackground];
    }
    if (selectedIndex == 3) {
        NSLog(@"3");
        UIImage *tabBarBackground = [UIImage imageNamed:@"tabbar-4.png"];
        [[UITabBar appearance] setBackgroundImage:tabBarBackground];
    }
}

- (void)customizeInterface
{

    UIImage *tabBarBackground = [UIImage imageNamed:@"tabbar-1.png"];
    [[UITabBar appearance] setBackgroundImage:tabBarBackground];

    UIImage *selectionIndicator = [UIImage imageNamed:@"tabbar-icon-clean.png"];
    [[UITabBar appearance] setSelectionIndicatorImage:selectionIndicator];

}

The debugger shows:
2012-11-13 02:42:06.147 soundapp[9060:c07] tabitem: 1
2012-11-13 02:42:06.148 soundapp[9060:c07] selected: 1
2012-11-13 02:42:06.148 soundapp[9060:c07] 1
2012-11-13 02:42:07.739 soundapp[9060:c07] tabitem: 2
2012-11-13 02:42:07.739 soundapp[9060:c07] selected: 2
2012-11-13 02:42:07.740 soundapp[9060:c07] 2

I'm searching nor for hours and can't figure out why it works only once. Does anybody see a mistake in my code?

A: After another hour i've found the solution somewhere else on the web (http://felipecypriano.com/2012/02/27/how-to-customize-uitabbar-on-ios-5/)
- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController
{
    int tabitem = self.tabController.selectedIndex;
    NSLog(@"tabitem: %i", tabitem);
    [self switchTabBarImage:tabitem];
    //[[tabController objectAtIndex:tabitem] popToRootViewControllerAnimated:YES];
}

- (void)switchTabBarImage:(int)selectedIndex
{

    switch (selectedIndex) {
        case 0:
            [[[self tabController] tabBar] setBackgroundImage:[UIImage imageNamed:@"tabbar-1.png"]];
            break;
        case 1:
            [[[self tabController] tabBar] setBackgroundImage:[UIImage imageNamed:@"tabbar-2.png"]];
            break;
        case 2:
            [[[self tabController] tabBar] setBackgroundImage:[UIImage imageNamed:@"tabbar-3.png"]];
            break;
        case 3:
            [[[self tabController] tabBar] setBackgroundImage:[UIImage imageNamed:@"tabbar-4.png"]];
            break;
    }
}

- (void)customizeInterface
{

    UIImage *tabBarBackground = [UIImage imageNamed:@"tabbar-1.png"];
    [[UITabBar appearance] setBackgroundImage:tabBarBackground];

    UIImage *selectionIndicator = [UIImage imageNamed:@"tabbar-icon-clean.png"];
    [[UITabBar appearance] setSelectionIndicatorImage:selectionIndicator];

}

I don't really understand why there are two different ways to change the background. It's confusing that these two different code lines work only in different places. I don't get that. But now it works.


text:
Q: What other "timer" libs can I use besides ScheduledExecutorService? What are my choices to do this?
Will creating many scheduled tasks require more than one thread? I would want to only use one thread to handle all these scheduled tasks.
Currently, I am using this:
    // send first message, first message is right away
sendMessage();

// prepare the timer to send second message, 2nd message sends 35 seconds after 1st
final ScheduledFuture<?> future2 = ses.scheduleAtFixedRate(
    sendMessage(),
    initDelay,
    EXE_LENGTH * EXE_LENGTH,
    TimeUnit.SECONDS
);

// kill the process for future2 30 seconds after 2nd message is sent
ses.schedule(new Runnable()
{
    @Override
    public void run()
    {
        future2.cancel(true);
    }
}, initDelay, TimeUnit.SECONDS);

// prepare the timer to send the third message, 3rd message sends 35 seconds after task for 2nd message is killed
final ScheduledFuture<?> future3 = ses.scheduleAtFixedRate(
    sendMessage(),
    initDelay + 2L,
    EXE_LENGTH * EXE_LENGTH,
    TimeUnit.SECONDS
);

// kill the process for future3 30 seconds after 3rd message is sent
ses.schedule(new Runnable()
{
    @Override
    public void run()
    {
        future3.cancel(true);
    }
}, initDelay, TimeUnit.SECONDS);

// shutdown the whole scheduler after the 3rd process is killed
ses.schedule(new Runnable()
{
    @Override
    public void run() {
        shutdown(challengeId);
    }
}, initDelay+2L, TimeUnit.SECONDS);

I'm not too knowledgeable about threads, but I believe this create multiple threads to handle a few tasks.


text:
Q: Refinement of an Open Cover This seems rather simple, but just curious about the following definition (pulled from Lee, but definitely standard):

Given an open cover $\mathcal{U}$ of $X$, another open cover $\mathcal{V}$ is called a refinement of $\mathcal{U}$ if for each $V\in \mathcal{V}$ there exists some $U\in \mathcal{U}$ such that $V\subset U$.

Why not the following definition:

Given an open cover $\mathcal{U}$ of $X$, another open cover $\mathcal{V}$ is called a refinement of $\mathcal{U}$ if for each $U\in \mathcal{U}$ there exists some $V\in \mathcal{V}$ such that $V\subset U$.

To me this second 'definition' seems more natural, is this important?  I guess these defintions are not equivalent but how bad is this definition of mine?

A: Your definition, while initially tempting, would make $\{X,\emptyset\}$ a refinement of every open cover! Basically, we need to be sure that every piece of a refinement is small relative to the original cover, and that's what the usual definition gets that yours doesn't. On the other hand, the usual definition does permit, say, $\{X\}$ as a refinement of the cover by all opens: roughly, a refinement doesn't have to be "fine" relative to the small parts of the original cover, but just relative to the big parts. It's a general principle that the small sets in an open cover (i.e. those contained in another element of the cover) are redundant and unimportant.


text:
Q: FIXED! Eclipse Mars Console Closes As Soon As It Opens I am new to java and don't relay know much but I know this is not meant to happen. I don't know how to explain it(besides saying it disappears as soon as it opens)  so I made a video which you can find here
Now that you know what is happening I was wondering if you would know how to fix it. It was a lot worse before, I don't know what I did to make it better.
I am on windows the code I'm using is just this
public class HelloWorld { //makes class
    public static void main(String[] args) { //Main part of program
        // Prints "Hello, World" to the terminal window.
        System.out.println("Hello, World");
    }
}
It is the hello world of Java nothing much
I just need to fix this nothing else is broken.
Ok, i look at the comments and I would like to thank you to all who answered and big thanks to @Priyamal for telling me the issue all I did was delete the workspace folder and reopen eclipse and it worked! Thaks a lot!


text:
Q: Function call within a for loop terminates the loop? I am experiencing a funny issue with JavaScript. I have a feeling this could have something to do with Closures, which, I admit, I am not really comfortable with.
Problem
It seems that calling a function from within results in a premature termination of the loop. I tried running the same loop without the function call and console.log() outputs the counter accurately suggesting the function call is breaking the loop.
Could someone suggest a possible fix? I have the code pasted here:
AbstractModel.prototype.deactivateContext   = function(context){

  for(i=0;i<this.asset.length;i++){
      if(this.asset[i].context == context){
        this.asset[i].deactivate();
        console.log(i);
        this.notify(this.asset[i],"REFRESHASSETS");
      }
  }
}

A: var is not optional
You proabbly have a global i in the other method. Declare your variables to the correct scope.
for (var i=0; i<this.asset.length; i++) {
     ^^^

A: Please declare i in the following function, like
AbstractModel.prototype.deactivateContext   = function(context){

  for(var i=0;i<this.asset.length;i++){
      if(this.asset[i].context == context){
        this.asset[i].deactivate();
        console.log(i);
        this.notify(this.asset[i],"REFRESHASSETS");
      }
  }
}

Looks like i is getting modified to a higher number in the notify function, when it returns from notify the for check is exiting.

A: Have you tried wrapping the call to the notify function in try catch. If you are saying that when you remove the call, output of counter prints as expected then the only explanation would be that your function is throwing an exception. Try this:
 for(i=0;i<this.asset.length;i++){
      if(this.asset[i].context == context){
        this.asset[i].deactivate();
        console.log(i);
        try {
          this.notify(this.asset[i],"REFRESHASSETS");
        } catch(e) {
           alert(e);
           console.log(e);
        }
      }
  }


text:
Q: Javascript regex issue with strings containing UTF-8 characters For some reason /(d+)/ (checks if there are any digits in the string) doesn't work if the string contains any UTF8 characters.
text = "ребёнок от 5 до 10 лет"
text.match(/(d+)/) >> null

text = "child 5 to 10 years"
text.match(/(d+)/) >> != null

There should be a fairly easy solution to this.

A: Please add \ to get \d, a digit shorthand class:

text = "ребёнок от 5 до 10 лет";
alert(text.match(/(\d+)/));


text:
Q: Why WPF UserControl's performance is so difference host into WPF application and win form application? This is my question:
I have 200,0000 Employee object(Id,Name,Job,Address) store at a database.
I read all Employee object to Empolyee[].
I create a window form application:

*

*I create a WPF UserControl(inside ListBox),name is "wpfUserControl1".

*I put "wpfUserControl1" into a window form.

*I set wpfUserControl1.listBox.ItemsSource = Employee[].

*Employee objects was displayed immediately.
// Performance is very good!
I create a WPF Application

*

*I create a MainWindow object.

*I put a ListBox to mainWindow.

*I set listBox.ItemsSource = Employee[].

*The speed of loading is very slow and occur outofmemeory exception.
// If i load 1000 objects, performance is too slow!
My doubt is :
Why same WPF UserControl was Hosted into WinFormApp and WpfApp ,it's performance difference is so big?

A: Could it perhaps have something to do with virtualizing? For instance, the WPF datagrid has virtualizing turned on by default, but if you place the datagrid inside a stackpanel and don't provide any width/height restrictions, then you effectively nullify virtualization since the stackpanel allows the datagrid to grow infinitely thus having to create DataGridRows for hundreds of thousands items.
I'm just guessing that the same effect might be happening with your usercontrol. In WinForms the hosting control propbably provides specific width/height restrictions and doesn't allow the usercontrol to grow infinitely. In WPF on the other hand, depending on how your WpfApp's MainWindow is defined, the usercontrol might grow infinitely.
Try setting a specific width/height for your usercontrol or mainwindow and see if the performance gets better...


text:
Q: Getting a "java.sql.SQLException: You can't operate on a closed Statement", with an open connection I have a program that makes several requests to a database, opening and closing connections to do what it needs to do. For each connection, it does a select that return 50 results and an update; it does this roughly 10 times per connection. After that, the connection is closed, and a new one is taken. But recently we have been having some random issues in which this SQL exception appears:
java.sql.SQLException: You can't operate on a closed Statement!!!
This error appears randomly. It first appeard mid-execution, and the only moment I managed to reproduce it, it happened at the initiation of the program (when I started it again after that, without making any change, it worked perfectly fine). I've looked around in the code but there's no chance that the connection closes before it can be used (the error occurs while inserting a parameter in a prepared statement). I'm already using c3p0 to manage the connection pool, so I don't know where else to look.
Someone has faced this error before? Any suggestions on where to look or how to reproduce it so I can test it properly?
Edit: Here is the problematic piece of code
    try{
        //send row to producer
        producer.processItem(fields);

        if (stmtLasProcessedTransaction == null) {
            stmtLasProcessedTransaction = getDbConnection().prepareStatement("UPDATE JTICKET_SUBSCRIBER SET LAST_PROCESSED_ROW = ? WHERE NAME = ? ");
            logger.trace("creating statement");
        }
        //update last processed transaction
        logger.trace("Setting the primary key to the prepared statement");
        stmtLasProcessedTransaction.setString(1, primaryKey);
        logger.trace("Setting the name to the prepared statement");
        stmtLasProcessedTransaction.setString(2, name);
        logger.trace("Attempting to execute the update on JTICKET_SUBSCRIBER in consumer {}",this.name);
        stmtLasProcessedTransaction.executeUpdate();
        logger.trace("Commiting execution");
        getDbConnection().commit();
        logger.trace("Update on JTICKET_SUBSCRIBER in consumer {} executed successfully",this.name);

        if (processedRows % 500 == 0) {
            logger.trace("resetting prepared statement");
            stmtLasProcessedTransaction.close();
            logger.trace("statement closed");
            stmtLasProcessedTransaction = null;
        }
        processedRows++;

    }catch(SQLException sqlException){
        logger.error("An SQL error ocurred while processing consumed item. Closing database connection and statement",sqlException);
        try{
            stmtLasProcessedTransaction.close();
            logger.info("Previous prepared statement of db consumer {} closed",this.name);
        }catch(Throwable throwable){
            logger.info("Couldn't properly close the prepared statement of db consumer {}",this.name);
        }finally{
            stmtLasProcessedTransaction=null;
        }

        try{
            databaseConnection.rollback();
            logger.info("Rollback of db connection of consumer {} done successfully",this.name);
            databaseConnection.close();
            logger.info("Previous connection of db consumer {} closed",this.name);
        }catch(Throwable throwable){
            logger.info("Couldn't rollback and/or close the connection of db consumer {}",this.name);
        }finally{
            databaseConnection=null;
        }
        throw sqlException;
    }catch(Exception exception){
        logger.error("An error ocurred while processing consumed item.", exception);
        throw exception;
    }

The prepared statement is a local variable, not a function one, so it can be re-used with every loop (this piece is part of a function that is called once for every result in a query that is done with a prepared statement to the same db connection). The error occurs when I'm trying to work on the prepared statement.
And the latest stack:

18/06/15 15:54:34.841 [ecbcbcmt] TRACE DatabaseConsumer - creating statement 18/06/15 15:54:34.850 [ecbcbcmt] ERROR DatabaseConsumer - An
    error ocurred while processing consumed item. java.sql.SQLException:
    You can't operate on a closed Statement!!!    at
    com.mchange.v2.sql.SqlUtils.toSQLException(SqlUtils.java:118)
    ~[mchange-commons-java-0.2.9.jar:0.2.9]   at
    com.mchange.v2.sql.SqlUtils.toSQLException(SqlUtils.java:77)
    ~[mchange-commons-java-0.2.9.jar:0.2.9]   at
    com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.setString(NewProxyPreparedStatement.java:488)
    ~[c3p0-0.9.5.jar:0.9.5]   at
    us.inswitch.jticket.subscriber.consumer.database.DatabaseConsumer.processRow(DatabaseConsumer.java:152)
    [bin/:na]     at
    us.inswitch.jticket.subscriber.consumer.database.DatabaseNumberConsumer.processRows(DatabaseNumberConsumer.java:73)
    [bin/:na]     at
    us.inswitch.jticket.subscriber.consumer.database.DatabaseConsumer.start(DatabaseConsumer.java:65)
    [bin/:na]     at
    us.inswitch.jticket.subscriber.consumer.Consumer.run(Consumer.java:35)
    [bin/:na]     at java.lang.Thread.run(Thread.java:662) [na:1.6.0_38-ea]
    Caused by: java.lang.NullPointerException: null   at
    com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.setString(NewProxyPreparedStatement.java:482)
    ~[c3p0-0.9.5.jar:0.9.5]   ... 5 common frames omitted 18/06/15
    15:54:34.852 [ecbcbcmt] WARN  DatabaseConsumer - An error ocurred
    while consuming table data. DatabaseConsumer will be restarted.
    java.sql.SQLException: You can't operate on a closed Statement!!!     at
    com.mchange.v2.sql.SqlUtils.toSQLException(SqlUtils.java:118)
    ~[mchange-commons-java-0.2.9.jar:0.2.9]   at
    com.mchange.v2.sql.SqlUtils.toSQLException(SqlUtils.java:77)
    ~[mchange-commons-java-0.2.9.jar:0.2.9]   at
    com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.setString(NewProxyPreparedStatement.java:488)
    ~[c3p0-0.9.5.jar:0.9.5]   at
    us.inswitch.jticket.subscriber.consumer.database.DatabaseConsumer.processRow(DatabaseConsumer.java:152)
    ~[bin/:na]    at
    us.inswitch.jticket.subscriber.consumer.database.DatabaseNumberConsumer.processRows(DatabaseNumberConsumer.java:73)
    ~[bin/:na]    at
    us.inswitch.jticket.subscriber.consumer.database.DatabaseConsumer.start(DatabaseConsumer.java:65)
    ~[bin/:na]    at
    us.inswitch.jticket.subscriber.consumer.Consumer.run(Consumer.java:35)
    [bin/:na]     at java.lang.Thread.run(Thread.java:662) [na:1.6.0_38-ea]
    Caused by: java.lang.NullPointerException: null   at
    com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.setString(NewProxyPreparedStatement.java:482)
    ~[c3p0-0.9.5.jar:0.9.5]   ... 5 common frames omitted

It's weird because it's completely random. We've had the program up and running for a while now, with all the connections working perfectly fine, and we get this kind of problem.

A: Use local variables, or otherwise use PreparedStatements carefully.
This avoids concurrent usage as in a web application.
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
    ...
    try (ResultSet rs = stmt.executeQuery()) {
        ...
    } // rs close
} // Does stm.close()

The try-with-resources also closes when an exception is thrown.

A: The statement stmtLasProcessedTransaction.close(); is present at two places which is fishy!!
1. within try block in conditional if
2. within catch block
Better programming practice is to have only one close statement, that too in finally block
PS: You can have try-catch-finally within finally block as well


text:
Q: Remove main editor from wordpress edit page screen Anyone know of a way to remove the main editor from the page edit screen? And not just with css. I've added a few other meta boxes with the tinymce and they collide with the main one.
I have a class that removes other meta boxes from the edit screen, but I cant get rid of the main editor this way. I've tried to add 'divpostrich' and 'divpost' to the array in the class (but with no luck):
class removeMetas{
    public function __construct(){
        add_action('do_meta_boxes', array($this, 'removeMetaBoxes'), 10, 3);
    }

    public function removeMetaBoxes($type, $context, $post){
        /**
         * usages
         * remove_meta_box($id, $page, $context)
         * add_meta_box($id, $title, $callback, $page, $context = 'advanced', $priority = 'default')
         */
        $boxes = array( 'slugdiv', 'postexcerpt', 'passworddiv', 'categorydiv',
                        'tagsdiv', 'trackbacksdiv', 'commentstatusdiv', 'commentsdiv',
                        'authordiv', 'postcustom');

        foreach ($boxes as $box){
            foreach (array('link', 'post', 'page') as $page){
                foreach (array('normal', 'advanced', 'side') as $context){
                    remove_meta_box($box, $type, $context);
                }
            }
        }
    }
}

$removeMetas = new removeMetas();

I have also tried removing the 'divpostrich' with jquery. But cant figure out where to put the js for it to work. When I remove the 'postdivrich' in the browser with firebug - my remaining tinymce fields work perfect.
Any ideas?

A: What you are looking for is the global $_wp_post_type_features array.
Below is a quick example of how it can be used
function reset_editor()
{
     global $_wp_post_type_features;

     $post_type="page";
     $feature = "editor";
     if ( !isset($_wp_post_type_features[$post_type]) )
     {

     }
     elseif ( isset($_wp_post_type_features[$post_type][$feature]) )
     unset($_wp_post_type_features[$post_type][$feature]);
}

add_action("init","reset_editor");

A: There is built in WP support for this so you don't have to fiddle directly with the globals and ensure forwards compatibility if they ever change how features are handled. The WP Core code does pretty much the exact same logic as @user622018 answer however
function remove_editor() {
  remove_post_type_support('page', 'editor');
}
add_action('admin_init', 'remove_editor');

A: Add the following code to your functions.
function remove_editor_init() {
if ( is_admin() ) {
    $post_id = 0;
    if(isset($_GET['post'])) $post_id = $_GET['post'];
    $template_file = get_post_meta($post_id, '_wp_page_template', TRUE);
    if ($template_file == 'page-home.php') {
        remove_post_type_support('page', 'editor');
    }
}
}
add_action( 'init', 'remove_editor_init' );

A: Couldn't you just disable the TinyMCE editor, leaving the HTML editor, as your meta boxes are colliding with it? :)

A: To disable the editor you will need to edit your wp-config.php file and add this line to the top:
define('DISALLOW_FILE_EDIT', true);


text:
Q: Getting the i_th value of a vector merged into tibble I have a tibble that I want to add a column to. The tibble can be of any length n where it is the outcome of three variables:
x <- 1:5 # can be any sequence length
u <- 3L # can be any integer
data_length <- length(x)
h <- 3L # can be any integer

The function will take the above and spit out a tibble that is 45 long: data_length * u * h
Now I also have a vector nt that is made by nt <- seq(from = 1, to = length(x) + 1 - 1/u, by = 1/u) and in this case will give the following:
[1] 1.000000 1.333333 1.666667 2.000000 2.333333 2.666667 3.000000 3.333333 3.666667 4.000000
[11] 4.333333 4.666667 5.000000 5.333333 5.666667

I want to be able to make a tibble of the following:
nt  | x | h
-----------
1   | 1 | 1
1.3 | 0 | 1
1.6 | 0 | 1
2   | 2 | 1
2.3 | 0 | 1
... |...|...
5   | 5 | 1
... |...|...
1   | 1 | 3
1.3 | 0 | 3
1.6 | 0 | 3

A: You can try -
library(dplyr)

replicate(h, tibble(nt) %>%
  mutate(x = replace(nt, -seq(1, n(), u), 0)), simplify = FALSE) %>%
  bind_rows(.id = 'h')

# A tibble: 45 x 3
#    h         nt     x
#   <chr>  <dbl> <dbl>
# 1 1     1          1
# 2 1     1.3333     0
# 3 1     1.6667     0
# 4 1     2          2
# 5 1     2.3333     0
# 6 1     2.6667     0
# 7 1     3          3
# 8 1     3.3333     0
# 9 1     3.6667     0
#10 1     4          4
# … with 35 more rows


text:
Q: Rails partial gets double escaped when using link_to_function I have the following code.
   def add_resume_link(name, form)
     link_to_function name do |page|
       html = form.fields_for :resumes, @general_resume.resumes.build, :child_index => 'NEW_RECORD' do |form_parent|
               render :partial => 'resume_form', :locals=>{:form=>form_parent}
            end
       page << "$('resumes').insert({ bottom: '#{escape_javascript(html)}'.replace(/NEW_RECORD/g, id) });"
      end
    end

And on the resume_form i have somewhere:
 =add_skill_link("Add Skill", form, "resume_#{id}_skills")

and the function looks like:
  def add_skill_link(name, form, id)
    link_to_function name do |page|
      html = form.fields_for :skill_items, @general_resume.skill_items.build, :child_index => 'NEW_RECORD' do |form_parent|
        render :partial=>'skill_form', :locals=>{:form=>form_parent, :parent=>id}
      end
      page << "$('#{id}').insert({ bottom: '#{escape_javascript(html)}'.replace(/NEW_RECORD/g, new Date().getTime()) });"
    end
  end

So basically i have a javascript code which dynamically adds a piece of html (add_resume) and contains another javascript code which dynamically adds a select box to the page.
My problem is that the add_skill_link works fine if i use from the server side, i mean rendering from server side. And gets double escaped when using within the upper described way.
I tried to remove the escape_javascript from the add_skill_link bit still not good.
Any ideas?

A: Is this HAML?
=add_skill_link("Add Skill", form, "resume_#{id}_skills")

If so, you need to prevent HAML from escaping your output:
!=add_skill_link("Add Skill", form, "resume_#{id}_skills")

A: I observed that things get too messy, finally I got my solution from Ryan Bates example application, he has a railscast about nested models, and there I browsed the branches and i got a branch with a nice clean solution to this problem. link text


text:
Q: pass value in global variable from client to server Lightswitch I have a two tier VisualStudio C# Lightswitch application that i'd like to pass a variable from the client to server.
Problem:
When i try running my application the global variable global.WorkOrder is always null.  I've tried commenting out all the class references on the server and hardcoded a constant string into global.WorkOrder on the client....but it remains null. Here's some code.
Client:
public partial class AddPart
{
    partial void Input_Changed()
    {
      UserCode.Globals global = new UserCode.Globals();
      global.WorkOrder = parts[7];

Server:
namespace LightSwitchApplication
{
    public partial class DataService
    {
        partial void Instances_Inserted(Instance entity)
        {
            UserCode.Globals global = new UserCode.Globals();
            InstanceInfo w = this.DataWorkspace.AUTOData.InstanceInfoes.AddNew();
            w.InfoContent = global.WorkOrder;

I've also created a Class1 that lives on the server in a UserGroup folder.  The class has been 'linked' on the client side.
Class:
namespace LightSwitchApplication.UserCode
{
    public class Globals
    {
            public string WorkOrder { get; set; }

The code compiles without errors but something isn't correct.  What am I doing wrong?  Sorry for the beginner question, and please let me know if you need more information to help. Thanks!

A: Turns out my global variable is working fine, I have another issue with a line of code that commits the record entry to my database.  I execute the commit on the client before the server is data is committed.  As soon as i commit the variable it becomes null.  This is more of a code structure thing with the two tier system that i need to figure out.


text:
Q: Dot product with Einstein summation convention (index notation) My professor, when proving:
$$a \cdot b = a_ib_i$$
wrote:
$$(a_i \hat{e}_i)\cdot(b_j \hat{e}_j) = (a_ib_j)(\hat{e}_i\hat{e}_j)$$

My doubt is:
Are we allowed to treat the dot product as ordinary multiplication once we have written everything in index notations? Does the same go for cross product?

*

*The confusion is mainly because we have moved $b_j$ from one bracket to another.
In my mind, We have moved $b_j$ across the dot. This feels wrong.

*By 'ordinary multiplication', I mean the kind of multiplication that we use in algebra to denote the product of two variables. We can move variables from one bracket to another there.

A: What you have in the right-hand side of
$(_̂_)⋅(_̂_)=(__)(̂_̂_)$
is not ordinary multiplication, because $̂_$ and $̂_$ are vectors. There you have to use the dot product.
Switching to the common notation we have:
$a=\sum_i a_i ̂_$
$b=\sum_j b_j ̂_j$
and
$$
a \cdot b= \sum_{i,j} a_i b_j (̂_ \cdot ̂_j)
$$
There we are using that the dot product is bilinear.


text:
Q: Problem related to Python insert() method I make a list of the first 10 square numbers. Here's how I might put the first 10 square numbers into a list:
    square=[]
    for i in range(1,10):
       square.insert(-1,i**2)
    print(square)

I expect the output of code to be
[1, 4, 9, 16, 25, 36, 49, 64, 81,]
but the actual output is
[4, 9, 16, 25, 36, 49, 64, 81, 1]
How I can fix this problem and please can you explain why my code isn't running

A: That's not the way to do it in Python, you should write something like this instead:
square = [i**2 for i in range(1,10)]

The reason why you get that result though is that inserting on -1st position will insert the number to the position before the last one in list, so you'll get [1], [2,1], [2,4,1] etc. as you iterate through the loop.

A: There may be typo in your code:
square.insert(-1, i**2)
may be:
square.insert(i, i**2)
See a working demo here.

A: Try this:
square=[]
num=10
for i in range(1,num):
    square.insert(num,i**2)
print(square)

The insert function exactly takes two arguments
list_name.insert(index, element)

now in the above code every element is trying to be inserted on 10th index whereas the list is empty so every element is filling the empty place before the 10th index. And if give -1 as an index then the increment for index will be -1,0,1,2,3,4,5... so that's why you got
>[4, 9, 16, 25, 36, 49, 64, 81, 1]

A: You can use the append function. It should look something like this:
square=[]
for i in range(1, 10):
    square.append(i**2)
print(square)

A: If you have to use insert, use len(square) rather than -1 as the index argument.
When you call insert(), it inserts the new element before the element at the given index. When the index is negative, it counts from the end. So square.insert(-1, newvalue) means to insert the new element before the last element, not after it.
The first time, the list is empty, so there's no last element to put it before, and it just appends to the list. But on all other iterations, it inserts before that element, so it stays at the end.
If you use len(square) as the index, that's after the last element, so inserting before it puts it at the end.
square=[]
for i in range(1,10):
   square.insert(len(square),i**2)
print(square)

I don't think there's any way to do it using a negative index.

A: You are inserting the order with -1. This should be:
square = []

for i in range(1, 10):
    square.insert(10, i**2)
print(square)

output:
[1, 4, 9, 16, 25, 36, 49, 64, 81]

A: Why don't you try:
square=[]
for i in range(1, 9):
    square.insert(i,i**2)
    print(square)

Your method does not work because you start from -1 which is equivalent to the end of your list and after that the insert() function cycles to the start of your list in order to fill it in.


text:
Q: Stringhandling, cut out part of string I have a string with values like -7.000, 10.000, 0.000, -212.000
Now i want to take away the .000 from the string and also the - in the front if there is one. My values always have to be positive.
So from this examples i has to give me 7, 10, 0, 212 back. How can i do that?
I could do  StringHandling.LEFT(myvalue,1).equals("-")?StringHandling.LEFT(myvalue,2):StringHandling.LEFT(myvalue,1) but then i have the Problem that when my values is 10.000 it just gonna give me 1

A: Why don't you just  parse the string as a number, then apply an 'absolute' operator?
String foo = "-50.000";
double bar = Double.parseDouble(foo);
int result = (int) abs(bar);
String yourResult = String.valueOf(result);

EDIT after OP comment:
To escape negative numbers, you can precede this code by a little:
   foo.replaceAll("-", "");

If you just want '378.890' to become '378' there's even simpler:
   String foo = "378.890";
   String[] bar = foo.split(".");
   String result = bar[0];

And if you need '0378.890' to become '378':
   String foo = "378.890";
   String[] bar= foo.split(".");
   String foobar = bar[0];
   int result = Integer.parseInt(foobar);
   result = abs(result); // If necessary (depends if you want to handle it at the string level or not)
   String finalResult = String.valueOf(result);

A: Use a simple String.substring() call:
String s = "-50.000";
String out = s.substring(s.charAt(0) == '-' ? 1 : 0, s.indexOf('.'));

If the input s starts with a minus sign -, it will be cut off, and also cuts off at the decimal point so there will be no trailing zeros.
This is the most efficient because it does only what is necessary for the required output. No unnecessary conversions and object creations.

A: You can use replaceAll() or replaceFirst() and regex like the one below:
\.[0-9]+

Example:
String test = "-700.999";
test = test.replaceFirst("-", "").replaceFirst("\\.[0-9]+", "");
System.out.println(test);

Output:
700

You can test this and other examples here.
Explanation:
replaceFirst("-", "") will delete first occurance of - with (as the replacement is empty value).
replaceFirst("\\.[0-9]+", "") will delete first occurance of dot followed by any number of digits. If there is a possibility that the number can be 700. and you want to remove the . as well, then you can replace + to * in this regex. * means 0 or more occurances while + means 1 ore more.
Further info
You can also shorten this solution that it will require one replaceAll() invokation with a little more complicated regex.

A: Try with regEx :
String yuStr =  "-7.000, 10.000, 0.000, -212.000";
System.out.println(yuStr.replaceAll("-|(\\d+)\\.\\d+", "$1"));

Output :
7, 10, 0, 212

A: In my opinion is not a matter of strings but more of numbers. Parsing it as a double and then dealing with its absolute value would take you where you want:
Math.abs(Double.valueOf(val).intValue())

A: Try this:
char[] splitChars = {',',' '};
string samplestring = "-7.000, 10.000, 0.000, -212.000 ";
string[] array = (samplestring.Split(splitChars, StringSplitOptions.RemoveEmptyEntries));
char[] splitChars1 = {'.','0'};
for(int i =0; i < array.Length; i++)
{
    array[i] = array[i].TrimStart('-').Replace(".000", "");
}

Or if its sure that you will always get .000, in the last then easiear way can be :
        char[] splitChars = {',',' '};
        string samplestring = "-7.000, 10.000, 0.000, -212.000 ";
        string output = samplestring.Replace("-", "");
        output = output.Replace(".000", "");

A: This can be done with simple maths:
String foo = "-1.99"; // example
double original = Double.parseDouble(foo);
double parsed = Math.floor(Math.abs(original)); // remove '-' if there is one, then round down


text:
Q: Lots of Failure Alerts on my DC I am receiving lots of Failure Audit logs on my DC, can you guide me - how should i identify the culprit.
Please see the below print-screen for more detail. The logon type is 3, that means it is a network logon. I have identify the Workstation from the log, but how should i prove who or which process is sending broadcast with logon authentication to my DC. The Anti-virus is also updated.
Note:- The Workstation is in Workgroup.

A: use tcp view http://technet.microsoft.com/en-us/sysinternals/bb897437.aspx on the workstation it will tell you the process that is talking to the dc.

A: As you said, your anti virus is updated, just perform virus scanning on all workstations or turn on IIS logging.
Refer the following link for error event: event id 4625
The thread can also be monitored by a third party tool.


text:
Q: Standalone Jar Execution From Batch File Below is my Jar structure. This is standalone jar.
MyApp.jar
--> .settings
--> com
--> lib
--> META-INF
--> resources
--> .classpath
--> .project

I am attempting to execute this jar file from bat file.
I have mentioned classpath and main class in MANIFEST.MF file under META-INF folder from MyApp.jar
Manifest-Version: 1.0
Class-Path: ./lib/jar1.jar ./lib/jar2.jar ./lib/jar3.jar
Main-Class: com.bank.Main

Inside my bat file:
java -jar D:\app\MyApp.jar
Is it correct way to lib folder inside jar?
But still i am facing ClassNotFoundException.

Exception in thread "main" java.lang.NoClassDefFoundError: javax/jms/JMSException

Anything i missed out Please advise me.

A: Put the lib folder outside of your current main jar [MyApp.jar] directory and execute it.
You have packaged the jar dependency inside your main jar. The intention of Class-Path is to add an external jar to the classpath, with the path relative to the location of the main jar.
Packaging a jar within a jar is not supported by standard Java classloaders. If you want, you can explode the inner jar into the main jar, though. Maven can do this for you.

A: Fat jar is not supported in Java by default. There are two options.

*

*You can define a custom class loader which has to load jars inside lib directory programmatically.

*You can manually merge all packages of jars inside lib directory to make a one jar and run it. Refer  [https://dzone.com/articles/java-8-how-to-create-executable-fatjar-without-ide ]


text:
Q: Show daily data from current week, Postgresql I am trying to fetch data from the current week and not from the last 7 days. My query is:
select
        order_datetime_tz::date AS date,
        orders

    FROM
         order_fact f
        where order_datetime_tz < current_date
        and order_datetime_tz >= date_trunc('week',current_date) - interval '1 week'

However this returns me the last 7 days..
Any idea on that?
Thanks!!

A: The beginning of the current week is date_trunc('week',current_date), so you just want to query dates later later than that:
select
    order_datetime_tz::date AS date,
    orders

FROM
    order_fact f
    where order_datetime_tz >= date_trunc('week',current_date)


text: Q: Non-rigid indecomposable summands of simple-minded collections in bounded derived category of hereditary algebras Let $\Lambda$ be a hereditary algebra over an algebraically closed field $k$. Let $S$ be one of the indecomposable summands of one simple-minded collection in $D^b(\Lambda)$. Is it true that $S$ is necessarily rigid? This is true when $\Lambda$ is of finite type. What about tame and wild types?


text:
Q: Should a base PHP database class create multiple connections? I have written a data class for handling MySQL queries and then all other classes such as login, products extend this class to make use of the database. As a result, each page load creates 2 or more DB connections due to something similar to the following:
$login, parent::__construct(); // check login via db
$products, parent::__construct(); // fetch products from db

Is there a way around this such as adding some code in the constructor to verify whether an existing DB connection has already been established?
A fellow developer I work with writes in procedural style and simply uses a single global $_db object for all queries and, this seems a lot more efficient as it only creates 1 DB connection.

A: For many smaller applications, I make my database instance global to the whole application, along with configuration and other application-wide classes, such as logging.  This is not necessarily the preferred method, as it couples code to expect things named certain ways, and could possibly cause conflicts down the road.  However, for small utility applications it is convenient.
For anything larger, I usually utilize my DB from an ORM anyway, so it becomes a non issue.

A: Michael's example of creating a static class and how to use it helped resolve the problem.
https://stackoverflow.com/a/26981461/541091


text:
Q: Interesting tiling with a lot of symmetrical shapes I have such an interesting observation: if I take a square grid and rotate it over itself by atan(3/4) , it forms a structure which has four axes of reflection symmetry:

The resulting structure is really mesmerizing, I see a lot of symmetric shapes in it: octagons, stars, rhombuses. And all of them appear inside this structure in different sizes, namely scaled by an integer factor:

Also looking at minimal periods, I notice that exactly the same structure I can create from rhombus grids, put over itself at 90 degrees. Namely rhombuses which have height of double of its width.
And the same structure, only with one additional square grid over it, I can create from a parallelogramm. Once I have made a question about this parallelogram (Very special geometric shape - parallelogram (No name yet?))
The relation between all shapes which spawn these grids:

To spawn it from parallelogram I copy-reflect the parallelogram grid and then copy-rotate the whole by 90 degrees:

Question:

*

*How this particular structure is classified, or named?

*Do you know of any articles about it or any applications?

To be exact, I made up two structures, but since they are almost the same, I hope this does not add much confusion.

A: Such kind of things are called multi-grids. The kind of multi-grids you drew are called singular. Non-singular or regular multi-grids, where no three different lines intersect, provide a general method for constructing non-periodic tilings of the plane. They were used (maybe itroduced?) by N. de Bruijn in his paper Algebraic theory of Penrose tilings. Later on de Bruijn's student Beenker used tetra-grids to describe Ammann-Beenker tilings -take a look at references therein.
The multi-grids method for constructing non-periodic tilings of the plane is generalized by the projection method (also cut-and-project method) and is related to the mathematical theory of quasi-crystals. Such method consists in projecting a stripe of a higher dimensional lattice onto a totally irrational subspace.
The relation between projection tilings and the inflational structure was studied by Harriss and Lamb.


text:
Q: Why is the container div used in this particular way? I see it used like this all the time For a simple use case example check out below:

<meta charset="utf-8">

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

<title>A Question for The Stackflow Community</title>
<link rel="stylesheet" type="text/css" href="css/global.css">

DUDE YOU NEED TO BUY THIS STUFF!!

        <button id="home">HOME</button>

I know that browsers offer some native relationship with the container div, or at least they can. But I see this use case alot in code, where the container div is created then closed. No special CSS is being used for it within the global.css file in this example. As you can see, no style tags are being used to add anything special either. So what I am asking is, why do this? What purpose does it serve?
As a sidenote, the body tag is outside of the container tag, whereas I would assume the inverse to be true, at least to follow what is expected as clean semantic markup. Any knowledge or feedback from the community is truly appreciated. A good answer deserves a good upvote for sure. Thank you!
-Cheers,
Branden Dnae

A: too vague to pinpoint an exact answer, however overall the probable effect is to have the content outside of the container (typically) pinned atop the container (or at least pinned in front, even if hidden), ala position:fixed; either 100% of the time, like a banner/header, or perhaps only upon user interaction...so think like a lightbox.


text:
Q: Parallel generating of triangular graph distance matrix in R I have an array of n graphs and I have to generate a triangular n x n matrix with the distance between the graphs.
I made the non-parallel program, meaning I have the function that calculates the no. of vertices for every pair of 2 graphs of size n1 and n2, No_MaxCommonSubgraph(graph1,graph2,n1,n2)
and I have 2 nesting for, and that construct the matrix. It works ok.
I transformed the first for into foreach, and I have
foreach(i <- 1:n-1)
    for(j in i:n){
       nn <- No_MaxCommonSubgraph(graph1,graph2,n1,n2)
       mat[i,j] <- max(n1,n2)-nn ##this should construct the matrix
}

The problem is that when I get out of foreach, the matrix mat has all values NA.
I tried to write the matrix file into foreach, after the for j, line by line, but it writes the lines in different order, as the lines are calculated by the cores. And sometimes write a line inside another line.
I use a Linux comp. with 12 cores and I may use another comp. with 8 cores.
For graph size 8, I have 11117 graphs and I have to go till size 9 or 10.
I'm new into R.

A: The use of foreach:
 m2 <-foreach(i=1:(len-1), .combine='rbind', .multicombine=TRUE) %dopar% {
        f_foreach(erg, i, len)}

so

*

*use %dopar% in foreach

*function "f_foreach()" returns a vector and by using ".combine='rbind'" in foreach it combines the vectors to form the matrix m2 as result of foreach.

*inside f_foreach() is the second for


text:
Q: Change key in array based first element array multidimensional How to change key of array into first element array ?
I preferred using array_map.
Now I have a common array.
If I have an array like this :
[
 0 => [
    'barang_id' => '7389'
    'spec' => 'KCH8AT-DM'
    'heat_no' => '7B4784'
    'coil_no' => '0210'
    'size' => '17.9'
    'weight' => '2014'
    'container' => 'TCLU6265556'
]
 1 => [
    'barang_id' => '7390'
    'spec' => 'KCH8AT-DM'
    'heat_no' => '7B4784'
    'coil_no' => '0050'
    'size' => '17.9'
    'weight' => '2006'
    'container' => 'TCLU6265556'
 ]
]

I need like this. The value of first element array is going to be key of array.
[
 7389 => [
    'barang_id' => '7389'
    'spec' => 'KCH8AT-DM'
    'heat_no' => '7B4784'
    'coil_no' => '0210'
    'size' => '17.9'
    'weight' => '2014'
    'container' => 'TCLU6265556'
]
 7390 => [
    'barang_id' => '7390'
    'spec' => 'KCH8AT-DM'
    'heat_no' => '7B4784'
    'coil_no' => '0050'
    'size' => '17.9'
    'weight' => '2006'
    'container' => 'TCLU6265556'
 ]
]

Please advise

A: I thought with this solution using array_map
$a = [['id' => 1233, 'name' => 'test1'], ['id' => 1313, 'name' => 'test2'], ['id' => 13123, 'name' => 'test3']];

$result = [];
array_map(
    function ($item, $key) use (&$result) {
        $result[$item['id']] = $item;
        return $item; // you can ignore this
    }, $a, array_keys($a)
);

now result contains what you want, check this image:

Or you could use it like this (without the $result thing) but you should unset the old key, look at the image:

A: if you have only 2 values you can create a new array:
$newarray[7389] = $oldarray[0];
$newarray[7390] = $oldarray[1];

or if you have multiple values you can do:
$newarray =[];
foreach($oldarray as $value) {
$newarray[$value['barang_id']] = $value

}

demo:https://ideone.com/mm2T7T

A: You cannot use array_map, because array_map will not pass the keys to the callback. But array_walk would work:
$reindexed = [];
array_walk($data, function($v, $k) use (&$reindexed) {
    $reindexed[$v['barang_id']] = $v;
});

This has no advantage over a plain old foreach though.


text:
Q: eZpublish contact form (collection) Our eZpublish 4.3 contact form is randomly sending emails to the ezpublish site admin email address instead of the correct form address.
The contact form is a standard 'information collection' ezpublish form, the user choose from a select box a department to contact then type his/her message and hit send.
The site is running on a Debian 7 box with PHP 5.6 installed via apt-get (as an apache module). eZpublish 4.3 need PHP 5.3 so we have compiled a PHP 5.3 from source and put it in /opt/php53 and it's run with php-fpm.
Sometimes the email is sent to the correct department email address, but sometimes it is sent to the site admin address.
My question is how can I debug what is going on? I can't find anything in apache logs. I tried looking in ezpublish log file but can't find anything of value there either.
What could be going wrong?

A: Probably something wrong with one of the values of your selectbox. Replicate in development and use xdebug or other debugging technique to show the Post values in form PHP controller. If those are wrong then your template or content is probably wrong.
Edit 2 :  look at the HTML to check select values instead.

A: Hierarchy for email_receiver is like this:
membership_coordinator_email_address

attribute in your feedbackform class if its not set, mail will send to:

...\settings\siteaccess\YOUR_SITE_NAME\site.ini.append.php

[InformationCollectionSettings]EmailReceiver=example@mail.com

if its not set, mail will send to:

...\settings\override\site.ini.append.php

[MailSettings]AdminEmail=admin_example@mail.com

For more information check tutorial on official site (maybe you messed something with ur feedbackform): http://share.ez.no/learn/ez-publish/how-to-create-ez-publish-forms


text:
Q: Creating an array of arrays without duplicates to add values I have an array of objects with number values that I am trying to loop over to get a result of and ARRAY of ARRAYS. Ive found examples of using for loop where the output is an ARRAY of OBJECTS. But I am having trouble looping over and adding the number values to create an array for each month value with the second value being a total of all the values listed for that month.
var input = [
  {month: "Jan", value: 3},
  {month: "Jan", value: 3.5},
  {month: "Feb", value: 2.1},
  {month: "Mar", value: 6},
  {month: "Apr", value: 4.3},
  {month: "May", value: 5.5},
  {month: "Jun", value: 7},
  {month: "Jun", value: 9},
  {month: "Jul", value: 7},
  {month: "Jul", value: 9},
  {month: "Jul", value: 7},
  {month: "Aug", value: 9},
  {month: "Sep", value: 9},
  {month: "Sep", value: 9},
  {month: "Oct", value: 8},
  {month: "Oct", value: 5},
  {month: "Oct", value: 3},
  {month: "Nov", value: 12},
  {month: "Nov", value: 19.5},
];

var result = [];

for (var i = 0; i < input.length; i++) {
  var data = input[i];
  var found = false;
  console.log(result[1][1], "help");
  for (var j = 0; j < result.length; j++) {
    if (result[j].month === data.month) {
      found = true;

      result[j][1] += data.value;
      break;
    }
  }
  if (!found) {
    result.push([data.month, data.value]);
  }
}

Currently returns an array of arrays but it is not adding the values instead it is making an array for each object.
My expected output would be:
[["Jan", 6.5],["Feb", 2.1],["Mar", 6],["Jun", 16]...etc]

A: An alternate approach using month as keys in an Object.

var input = [
  { month: "Jan", value: 3 },
  { month: "Jan", value: 3.5 },
  { month: "Feb", value: 2.1 },
  { month: "Mar", value: 6 },
  { month: "Apr", value: 4.3 },
  { month: "May", value: 5.5 },
  { month: "Jun", value: 7 },
  { month: "Jun", value: 9 },
  { month: "Jul", value: 7 },
  { month: "Jul", value: 9 },
  { month: "Jul", value: 7 },
  { month: "Aug", value: 9 },
  { month: "Sep", value: 9 },
  { month: "Sep", value: 9 },
  { month: "Oct", value: 8 },
  { month: "Oct", value: 5 },
  { month: "Oct", value: 3 },
  { month: "Nov", value: 12 },
  { month: "Nov", value: 19.5 },
];

const totalMonthObj = {};
for (monthObj of input) {
  if (totalMonthObj[monthObj.month]) {
    totalMonthObj[monthObj.month].value += monthObj.value;
  } else {
    totalMonthObj[monthObj.month] = monthObj;
  }
}
console.log(Object.values(totalMonthObj).map(({month,value})=>[month,value]));

A: You can use array.reduce:
const result = input.reduce((r, item) => {
  const { month, value } = item;
  const existing = r.find((x) => x[0] === month);
  if (existing) {
    existing[1] += value;
  } else {
    r.push([month, value]);
  }
  return r;
}, []);

Output:
console.log(JSON.stringify(result));

[["Jan",6.5],["Feb",2.1],["Mar",6],["Apr",4.3],["May",5.5],["Jun",16],["Jul",23],["Aug",9],["Sep",18],["Oct",16],["Nov",31.5]]

A: just pass the months array to the function and it will return your expectation
function filterMonth(arr){

    let data = [];

    for (let index = 0; index < arr.length; index++) {
        let findIndex = data.findIndex(item => item[0] === arr[index].month)

        if (findIndex === -1){
            data.push([arr[index].month,arr[index].value])
        }
    }

    return data
}

NOTE** this function will only work if the given array is just like yours

A: Arrays don't have .month attributes associated with them. Look in your code below.

var input = [
  {month: "Jan", value: 3},
  {month: "Jan", value: 3.5},
  {month: "Feb", value: 2.1},
  {month: "Mar", value: 6},
  {month: "Apr", value: 4.3},
  {month: "May", value: 5.5},
  {month: "Jun", value: 7},
  {month: "Jun", value: 9},
  {month: "Jul", value: 7},
  {month: "Jul", value: 9},
  {month: "Jul", value: 7},
  {month: "Aug", value: 9},
  {month: "Sep", value: 9},
  {month: "Sep", value: 9},
  {month: "Oct", value: 8},
  {month: "Oct", value: 5},
  {month: "Oct", value: 3},
  {month: "Nov", value: 12},
  {month: "Nov", value: 19.5},
];

// your code with error correction

result = []

for (var i = 0; i < input.length; i++)
{
  var data = input[i]; // this is redundant but we can keep it
  var found = false;
  for (var j = 0; j < result.length; j++)
  {

    /* ----------------------------------------------------------
       ------------------------- HERE ------------------------
    ---------------------------------------------------------- */

    //if (result[j].month === data.month)
    // your if statement was never hit, because result[j] is an array
    // and doesn't have a month attribute, so it should return null,
    // thus never hitting your if statement
    if (result[j][0] === data.month)
    {
      found = true;
      result[j][1] += data.value;
      break;
    }
  }
  if (!found) {
    result.push([data.month, data.value]);
  }
}

console.log(result)


text:
Q: Select only email from a message- Open Refine I have columns with several cells like this:
"Hi my email is mail@mail.com feel free to email me!"

"Hey, this is my email: mail2@mail.com"

I want to create a new column from there with this cells:
"mail@mail.com"

"mail2@mail.com"

Thank you!

A: You can search the for mail adresses with regex (take a look here). An easy example for such a regex would be /\b\S+@\S+\.\S+\b/
To use it in OpenRefine:

*

*Click on column

*"Edit column"

*"Add column based on this column…"

*set "New column name"

*set "Expression" with something like value.find(/\b\S+@\S+\.\S+\b/)[0]

*Ok


text:
Q: Query on INFORMATION_SCHEMA.JOBS_BY_PROJECT throwing dml_stats error I have recently started seeing an error when i simply run
SELECT * FROM  region-eu.INFORMATION_SCHEMA.JOBS_BY_PROJECT
Field name dml_stats does not exist in STRUCT<...
Excluding field dml_stats doesn't seem to work either.
Anyone else spotted this?
Cheers.

A: There are already 2 issues reported in the public issue tracker.

*

*https://issuetracker.google.com/issues/193159258

*https://issuetracker.google.com/issues/193437397
This seems to be a bug on the Google side. Hopefully, they will fix it soon.


text:
Q: Cordova Version for Android Kitkat App I want to build a Cordova Application.
Which Cordova Version should i install to build an application for Android Kitkat Version ?
Is it 4.0   or    5.0

A: You can use latest cordova version, and yo can specify target-platform in your config.xml as so that application built will support all the android versions
<preference name="target-device" value="universal" />
<preference name="android-minSdkVersion" value="7" />   //android: MIN SDK version supported on the target device. MAX version is blank by default.


text:
Q: Use of undefined constant CURLOPT_POST - assumed 'CURLOPT_POST' I am making a cURL request via Kohana 3.2 but I get the following error when it tries to access CURLOPT_POST constant:
Use of undefined constant CURLOPT_POST - assumed 'CURLOPT_POST'

From Kohana 3.2 system/classes/kohana/request/client/curl.php
public function _set_curl_request_method(Request $request, array $options)
{
    switch ($request->method()) {
        case Request::POST:
            $options[CURLOPT_POST] = TRUE;
            break;
        case Request::PUT:
            $options[CURLOPT_PUT] = TRUE;
            break;
        default:
            $options[CURLOPT_CUSTOMREQUEST] = $request->method();
            break;
    }
    return $options;
}

My application code:
$request = Request::factory($uri);
$request->query('key', $key);
$request->post($params);
$request->method(Request::POST);

// fails here
$response = $request->execute();

I have tested that curl is active as an extension using:
if (in_array  ('curl', get_loaded_extensions()))
{
    echo '1';
}
else
{
    echo '0';
}

What is the problem here? I am using Windows 7, PHP 5.4.12, and Apache 2.4.

A: I noticed extension=php_curl.dll was commented out in C:\wamp\bin\php\php5.4.12\php.ini but active via C:\wamp\bin\apache\Apache2.4.4\bin\php.ini.
I found that uncommenting the line in C:\wamp\bin\php\php5.4.12\php.ini fixed my issue.

A: First, let's check php-curl has been installed on your server by
aptitude search php-curl

or
    aptitude search php5.6-curl
if that hasn't been installed yet, let's install it by
sudo apt-get install php5.6-curl


text:
Q: Decoding response with mixed UTF-8 encoding in Python I'm downloading data from a website using aiohttp and I'm getting a bytes object as a response but I'm having an hard time decoding it.
This is an example of the reponse I get
b'\\r\\nLocalit\xc3\xa0' # Località
b'\\u003cdiv\\u003e12/09/2019\\u003c/div\\u003e\\r\\n' #
12/09/2019

From what I understand it has normal unicode for text and escaped unicode for the html tags and line feed.
If I try to decode it using "str(content, "utf-8")" I still have the html tags in this format
\u003cdiv \u003e12/09/2019\u003c/div\u003e\r\n

Should I just do a manual .replace("\u003", "<") for every tag or is there a more elegant solution?

A: You could use the 'unicode-escape' codec to convert the unicode part, then reencode transparently to bytes (latin-1 is convenient for this, as is provides a 1-to-1 correspondance between bytes and chars), then decode as 'utf-8':
b = b'\\u003cdiv\\u003e12/09/2019\\u003c/div\\u003e\\r\\n\\r\\nLocalit\xc3\xa0'
b.decode('unicode-escape').encode('latin1').decode('utf8')
# '
12/09/2019
\r\n\r\nLocalità'


text:
Q: fullBackup: User 10193 does not have android.permission.BACKUP When I run backup command(bu) from my android app, the following error messages ware displayed.
I don't know why this error message shown.
Would you tell me how to avoid the error?
=== my app code ===
String cmd = "/system/bin/bu " + 2 + " backup -apk -noshared -all -nosystem";
Process process = Runtime.getRuntime().exec(cmd);
===

=== error message ===
D/AndroidRuntime(23189): Calling main entry com.android.commands.bu.Backup
D/bu      (23189): Beginning: 2
E/bu      (23189): Error running backup/restore
E/bu      (23189): java.lang.SecurityException: fullBackup: User 10193 does not have   android.permission.BACKUP.
E/bu      (23189):  at android.os.Parcel.readException(Parcel.java:1327)
E/bu      (23189):  at android.os.Parcel.readException(Parcel.java:1281)
E/bu      (23189):  at android.app.backup.IBackupManager$Stub$Proxy.fullBackup(IBackupManager.java:628)
E/bu      (23189):  at com.android.commands.bu.Backup.doFullBackup(Backup.java:110)
E/bu      (23189):  at com.android.commands.bu.Backup.run(Backup.java:56)
E/bu      (23189):  at com.android.commands.bu.Backup.main(Backup.java:38)
E/bu      (23189):  at com.android.internal.os.RuntimeInit.finishInit(Native Method)
E/bu      (23189):  at com.android.internal.os.RuntimeInit.main(RuntimeInit.java:262)
E/bu      (23189):  at dalvik.system.NativeStart.main(Native Method)
D/bu      (23189): Finished.
D/AndroidRuntime(23189): Shutting down VM

A: I had the same exception error.
The problem is that I was connected to ADB as the application (run-as application).
Just execute "ADB -d shell" (-e if emulated device)  and then the backup commands.
Hope it helps someone.


text:
Q: Comparing two rows in the same table SQL We are having trouble solving a part of an exercise in a SQL-course, here is a part of the dataset:
The query we are looking for should: Find the diseases that can be treated with hydrocortisone but not with etanercept.
Any ideas?

A: Group by DiseaseName and set the condition in the HAVING clause:
select DiseaseName
from tablename
where DrugName in ('hydrocortisone', 'etanercept')
group by DiseaseName
having count(case when DrugName = 'etanercept' then 1 end) = 0

In Mysql the difference would be the having clause:
having sum(DrugName = 'etanercept') = 0

And in Potgresql:
having sum((DrugName = 'etanercept')::int) = 0

Another way with NOT EXISTS:
select DISTINCT t.DiseaseName
from tablename t
where t.DrugName = 'hydrocortisone'
and not exists (select 1 from tablename where DiseaseName = t.DiseaseName and DrugName = 'etanercept')

A: You can use below query:
SELECT "diseasename" FROM TABLE1
GROUP BY  "diseasename"
HAVING MIN("DRUGNAME") = MAX("DRUGNAME") AND MAX("DRUGNAME") = 'hydrocortisone';


text:
Q: Same business entity for identical tables? I got a legacy database which have about 10 identical tables (only name differs).
Is it possible to be able to use the same business entity for all tables without having to create several classes/mapping files?

A: You can create a base class with all the properties, but you still need to map them all.
For that, you can either use copy&paste, XML entities (see examle at  http://nhibernate.info/doc/nh/en/index.html#inheritance-tableperconcreate-polymorphism), or a code-based mapping method (Fluent or ConfORM). They usually make reuse easier.

A: You can use the entity-name feature if you are using NHibernate v2.1 or higher. It is poorly documented but I am actively using the feature.  It has gotten hard to find the documentation on it but look here:
Section 5.3 in
http://docs.jboss.org/hibernate/core/3.2/reference/en/html/mapping.html#mapping-entityname
A couple of things to be aware of.  You must now use entity-name instead of class name to refer to the objects.  In general it is not an entirely transparent change moving from class names to entity names.
Session actions now require two parameters, for example:
_session.Save("MyEntity", myobject)
The entity-name controls what table the data goes into.
Some HQL queries do not work right anymore, sometimes you must use Criteria instead.
If you need a set of sample code I may be able post some, but far too busy at the moment.  I suggest you look at the limited info you can find and set it up for a very simple object and multiple tables to learn how it all works.  It does work.


text:
Q: what's the difference between these blocks of code? So I went over this block of code several times in a book that I'm reading:
int[][] someArray = new int[size][];
for(int i=0; i<size; i++)
   someArray[i] = new int[size];

I don't see any difference between that and the following declaration:
int[][] someArray = new int[size][size];

Did I miss anything here? Is there any reason why I should use the long block of code above?
Thanks,

A: You can create ragged or jagged arrays with the first construct

A: As said by parapura you can create what's called a ragged array. Essentially you can make something triangular shaped and such (might resemble stairs or a christmas tree or whatever you want it to be). So it can be like (using random numbers)
1 2 3
1 2
4 4 5 6 2 3 5
4 5 1
2 2 5 2
where the lengths of the sub arrays are different sizes. In your example though they are both the same size so both ways do exactly the same thing.
One reason this could be done is to save space in memory instead of zero filling empty slots.

A: No difference here. The first one is useful when we want to create arrays having different sizes.

A: When in doubt take a look at the bytecode -- especially for something like this that is just a few lines of code.
Apparently the compiler has a special construct for creating the second form.
first form (without the loop):
public static void main(java.lang.String[]);
  Code:
   0:   iconst_3
   1:   anewarray       #2; //class "[I"
   4:   astore_1
   5:   return
second form:
0:   iconst_3
1:   iconst_3
2:   multianewarray  #2,  2; //class "[[I"
6:   astore_1
7:   return
==================
One way to look at it is that there is a LOT of wasted time in the loop when you know you are going to have a "square" array anyways.  Imagine if you were at Google and you needed a two-dimensional array with size=10000000.  The first form would be dramatically slower.


text:
Q: How to Add 7 Authors' Name? Hi I have a two columns table with ACM SIG Proceedings template http://www.acm.org/sigs/publications/proceedings-templates
Here is my code for six authors, my problem is I have a 7-th author, I am not sure how to add it nicely, is it possible to squeeze the second rows(maybe smaller font size) to allow 4 authors?
\documentclass[9pt]{sig-alternate}

\begin{document}
\title{Paper title}

\numberofauthors{6}

\author{

% 1st. author
\alignauthor
Author Name\\
       \affaddr{This is Author School Name}\\
       \email{AuthorEmail@gmail.com}
% 2nd. author
\alignauthor
Author Name\\
       \affaddr{This is Author School Name}\\
       \email{AuthorEmail@gmail.com}
% 3rd. author
\alignauthor
Author Name\\
       \affaddr{This is Author School Name}\\
       \email{AuthorEmail@gmail.com}
\and  % use '\and' if you need 'another row' of author names
% 4th. author
\alignauthor
Author Name\\
       \affaddr{This is Author School Name}\\
       \email{AuthorEmail@gmail.com}
% 5th. author
\alignauthor
Author Name\\
       \affaddr{This is Author School Name}\\
       \email{AuthorEmail@gmail.com}
% 6th. author
\alignauthor
Author Name\\
       \affaddr{This is Author School Name}\\
       \email{AuthorEmail@gmail.com}
}

\maketitle

\end{document}

A: Put \and after the sixth author to create another row.
\documentclass[9pt]{sig-alternate}

\begin{document}
\title{Paper title}

\numberofauthors{7}

\author{
% 1st. author
\alignauthor
Author Name\\
       \affaddr{This is Author School Name}\\
       \email{AuthorEmail@gmail.com}
% 2nd. author
\alignauthor
Author Name\\
       \affaddr{This is Author School Name}\\
       \email{AuthorEmail@gmail.com}
% 3rd. author
\alignauthor
Author Name\\
       \affaddr{This is Author School Name}\\
       \email{AuthorEmail@gmail.com}
\and  % use '\and' if you need 'another row' of author names
% 4th. author
\alignauthor
Author Name\\
       \affaddr{This is Author School Name}\\
       \email{AuthorEmail@gmail.com}
% 5th. author
\alignauthor
Author Name\\
       \affaddr{This is Author School Name}\\
       \email{AuthorEmail@gmail.com}
% 6th. author
\alignauthor
Author Name\\
       \affaddr{This is Author School Name}\\
       \email{AuthorEmail@gmail.com}
\and
% 7th. author
\alignauthor
Author Name\\
       \affaddr{This is Author School Name}\\
       \email{AuthorEmail@gmail.com}
}

\maketitle

\end{document}

I will advise against squeezing the fourth author into the second row for then it will look cramped. Other options would be to put \and after the second and fifth authors or after third and fifth authors. Note that displaying more than six authors after the title is discouraged as posted in this ACM page.


text:
Q: C# Connect to WiFi network by Windows Runtime Api. LocalSystem vs NetworkService I'm writing simple C# (tried .Net Core 3.1 and .Net 5 with Framework Moniker) console app (will work as a service) for controlling wifi adapters (turn on/off, disconnect, connect).
It works well when running from Visual Studio, works well when running from .exe but "Connect" method does not work when running program as a Network Service.
Sample code for connecting to a network:
    {
        static async Task Main(string[] args)
        {
            var access = await WiFiAdapter.RequestAccessAsync();
            if (access != WiFiAccessStatus.Allowed)
            {
                // No access
            }

            var adapters = await WiFiAdapter.FindAllAdaptersAsync();
            var firstAdapter = adapters.First();

            await firstAdapter.ScanAsync();
            var wifiNetwork = firstAdapter.NetworkReport.AvailableNetworks.Single(x => x.Ssid == "Wifi_Network_Name");

            var credential = new PasswordCredential {Password = "Wifi_Network_Password"};
            var connectResult = await firstAdapter.ConnectAsync(wifiNetwork, WiFiReconnectionKind.Manual, credential);

            Console.ReadKey();
        }
    }

If I run this program as "nt authority\network service" then firstAdapter.ConnectAsync returns UnspecifiedFailure (https://learn.microsoft.com/en-us/uwp/api/windows.devices.wifi.wificonnectionstatus?view=winrt-19041).
Works well when run as Local System.
I'm using this Windows Runtime API:
https://learn.microsoft.com/en-us/uwp/api/windows.devices.wifi?view=winrt-19041
For .Net Core I'm using Microsoft.Windows.SDK.Contacts 10.0.19041.1
For .Net 5.0 I'm using Target Framework Moniker: net5.0-windows10.0.19041.0
I guess there is something going on with Network Service privileges or access permissions but can't google anything useful.
Any help or advice would be much appreciated :)


text:
Q: add/remove dll reference c# I'm developing a desktop application. For that I'm creating class libraries. At the development time I have to rebuild the class library multiple times for functional testing and update reference to DLL. But once I add a reference to a DLL, then add some code to a class file and rebuild it, and add a reference to the newly built DLL, it's not updating the reference. It refers to the old DLL only.

A: That's the expected behavior for what you are doing. By manually adding the reference DLL, you are simply copying the compiled file at that time, so further compiles will not update the copied DLL.
What you want is to add a project reference to the working project.
How to: Add a Reference to a Visual Studio Project in a Web Site

A: If you are building on the same machine, when you add a reference to a DLL it will by default remember where that DLL was and pick up newer versions as they appear and the project is built.
Sometimes it can get confused, so a Rebuild All can solve the problem, or dropping and readding the reference.


text:
Q: How to AND multiple setQuery in elasticsearch using java? I am trying to create query for search filter using elasticsearch. I created query that shows results based on search term, price range and brand list. Results shown for searchterm and price range is right but when brand list is provided all results  related to selected brand is shown.
I want results for searchterm AND price AND brands
This is my query
BoolQueryBuilder query = QueryBuilders.boolQuery();
for (String key : brands) {
    query.must(QueryBuilders.matchQuery("brand", key));
}

SearchResponse searchresponse = client
        .prepareSearch("product")
        .setTypes("product")
        .setQuery(
                QueryBuilders.matchPhraseQuery("name", pSearchTerm))
        .setPostFilter(
                QueryBuilders.rangeQuery("unit_price").from(min)
                        .to(max))
        .setQuery(query).setExplain(true)
        .execute().actionGet();

what am i doing wrong here?

A: You have two setQuery() calls so the second one is overriding the first one. You need to combine all your constraints into one query like this:
// brand list
BoolQueryBuilder query = QueryBuilders.boolQuery();
for (String key : brands) {
    query.must(QueryBuilders.matchQuery("brand", key));
}

// search term
query.must(QueryBuilders.matchPhraseQuery("name", pSearchTerm));

// price range
query.filter(QueryBuilders.rangeQuery("unit_price").from(min).to(max));

SearchResponse searchresponse = client
    .prepareSearch("product")
    .setTypes("product")
    .setQuery(query)
    .setExplain(true)
    .execute().actionGet();


text:
Q: nspredicate escaping url When using an NSPredicate for an NSFetchRequest and searching for a URL is there a need to escape "/"?
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(url == %@) , aURL];

A: Do this as i assume aURL is string:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(url == %@") , aURL];

Also try like this:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ANY url  like '%@'" , aURL];


text:
Q: Agregar SUM(X) de variaas tablas SQL SERVER Mi problema es el siguiente
Tengo tres tabla una llamada
PTO_PRESUPUESTO,
V_EJE_CDP,
V_EJE_RP
Estoy tratando de agregar la sumatoria por Rubro(codigo) de V_EJE_CDP Y V_EJE_RP  a la tabla PTO_PRESUPUESTO,
Al momento de hacerlo con V_EJE_CDP me da los resultados esperados, cuando intento hacerle el SUM a V_EJE_RP la sumatoria de V_EJE_RP se altera, voy a colocar una imagen con los datos.

Espero me entiendan.
Gracias de ante mano


text:
Q: Split a differential $(k+1)- form$ into two parts In the proof of Poincare's lemma, it's said every differential $(k+1)-form $ ${\omega} \in\Omega^{k+1}(U\times\mathbb{R})$ ($U$ is an open set in $\mathbb{R}^n$) could be uniquely written as $$\omega=\sum f_I(x,t)dx_I+\sum g_J(x,t)dt\wedge dx_J .\quad (*)$$ Here $I=(i_1,\cdots,i_{k+1}),J=(j_1,\cdots,j_k),\ 1\le i_1<i_2<\cdots<i_{k+1}\le n, 1\le j_1<j_2<\cdots <j_k\le n.$
Question: I wonder where the second part in $(*)$ comes from, and what's the meaning of symbol $dt$ here. Any help would be appreciated.

A: In this notation, we are writing the coordinates in $U\subseteq\Bbb R^n$
as $x_1,\ldots,x_n$ and in $\Bbb R$ as $t$ so that the coordinates
on $U\times \Bbb R$ are $x_1,\ldots,x_n,t$. So $dx_1,\ldots,dx_n,dt$
are the basic $1$-forms.
A typical $3$-form might then be say
$$t\,dx_1\wedge dx_3-x_1^2dx_2\wedge dx_3+dt\wedge(\sin t\,dx_2-e^{x_2}\,dx_3).$$


text:
Q: Can Spring JPA Auditing audit the User Entity itself? Here is what I am trying to implement in Spring Boot-
public class User extends  AbstractAuditable<User, Long>{
    Long userId;
    String userNAme;
    String password
}

When I try to run the test and have  UserRepository injected, the context fails to load with he following reason -
Caused by: java.lang.IllegalArgumentException: This class [class com.example.User] does not define an IdClass


text:
Q: how to Calculate distance base on lat long mongodb {
    "_id": ObjectID("5e576bf5d72a185fcf11e03f"),
    "location": {
        "latitude": 27.6648,
        "longitude": 81.5158,
        "city": "Florida",
        "state": "Florida",
        "country": "United State"
    },
    "description": "This is for test",
    "distance" : "100" //Miles
}

How can get the record that calculate the minium distance between coordinates tried difference way didn't get success


text:
Q: How come I can copy a vector of structs if there is no overloaded assignment operator? Why does my MS visual c++ compiler allow me to copy and assign a vector of a struct that has no copy and assign operators?
struct Reading
{
    int hour;
    double temperature;
    Reading(int h, double temp)
        :hour(h), temperature(temp){}
};

//========================================================

int main()
{
    vector<Reading> readings;

    readings = get_readings(readings);//This is OK!!

    keep_window_open();

}

A: Because the default copy constructors and assignment operators simply copy every field in your struct.
See section "When do I need to write a copy constructor?" in
http://www.cplusplus.com/articles/y8hv0pDG/

A: Structs and classes have default copy constructors and assignment operators.
Default constructors and destructors are also generated.
For constructors they are generated if no other constructor is generated.
Operation of copy ctor and assignment operator is a simple memcpy (shallow copy) which is dangerous in some cases.

A: There are default copy/assignment constructors generated in most circumstances.
This code demonstrates this (I added some constexpr and a bad operator== for demo purposes):
struct Reading
{
  int hour;
  double temperature;
  constexpr Reading(int h, double temp)
      :hour(h), temperature(temp){}
};

constexpr bool operator==(const Reading& r1, const Reading& r2)
{
  return r1.hour == r2.hour && r1.temperature == r2.temperature;
}

int main()
{
  constexpr Reading r1(42, 4.2);
  constexpr Reading r2 = r1; // compiler will generate a default copy constructor here
  static_assert(r1 == r2, "not equal");
}

A: From cplusplus.com: Copy constructors, assignment operators, and exception safe assignment

When do I need to write a copy constructor?
First, you should understand that if you do not declare a copy
  constructor, the compiler gives you one implicitly. The implicit copy
  constructor does a member-wise copy of the source object.
When do I need to write an assignment operator?
First, you should understand that if you do not declare an assignment
  operator, the compiler gives you one implicitly. The implicit
  assignment operator does member-wise assignment of each data member
  from the source object.


text:
Q: Square v1 API for adding card to customer(New/Existing) There is a Square v2 endpoint to create a card for a customer as described in the link, https://developer.squareup.com/docs/api/connect/v2#endpoint-customers-createcustomercard
I will not be able to use the same API for applications in v1 version. I tried and faced the below error,
{
    "errors": [{
        "category": "INVALID_REQUEST_ERROR",
        "code": "V1_APPLICATION",
        "detail": "This application does not support accessing Connect API v2 endpoints. To access these endpoints, register a new application with Square at connect.squareup.com."
    }]
}

If I need to add a card to a customer like the one mentioned for v2 API, which endpoint of v1 should I rely on?

A: There are no endpoints in V1 that allow adding a card to a customer's profile. This functionality only exists in V2. If you are receiving that error, then unfortunately, your application was created before V2, and the only way to use V2 endpoints would be to create a new application (which just means updating your access token and secrets appropriately).


text:
Q: Socket.io клиент Android заранее извиняюсь за возможно нубский вопрос, новичок в java)
и по socket.io нету нормальных туториалов. С гуглом попытался начать осваивать и вроде что-то получилось(Приложение хотя бы запускается xD)
но когда жму кнопку на форме и выполняется Connect то краш с ошибкой
java.lang.NullPointerException: Attempt to invoke virtual method 'io.socket.client.Socket io.socket.client.Socket.connect()' on a null object reference

Вот что получилось) можете объяснить что не так?
public class LoginActivity extends AppCompatActivity {
    private Socket mSocket;
    {
    try {
        mSocket = IO.socket("192.168.100.3:8080");
    } catch (URISyntaxException e) {}
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
    }

    public void Connect(View v){
        mSocket.connect();
    };
}

A: Согласно комменту, после того, как в catch блоке была выведена в консоль ошибка, выяснилось, что в адресе не хватало схемы, т.е. http://. Именно в этом была ошибка


text:
Q: module 'matplotlib.pyplot' has no attribute 'yaxis' I know this isn't reproducable but I'm not sure enough what is happening to make it that way.  I'll update and re-answer if someone can explain.
ax = plt.plot( 'spending_billions', 'poverty_rates', data=pv_rates_df, marker='o', color='blue', linewidth=2, label = 'Black Poverty Rate')
plt.title("Black Poverty and Cash Reparations", fontsize=12, fontweight=0, color='Black')
plt.xlabel("Spending in Billions")
plt.ylabel("SPM Black Poverty Rates")
plt.yticks(np.arange(0, 22, 2))
plt.yaxis.set_major_formatter(mtick.PercentFormatter())
plt.legend()

I get this error.  module 'matplotlib.pyplot' has no attribute 'yaxis'
Any suggestions?

A: As the error message says, yaxis does not exist on your plt object.
If you use pandas.DataFrame.plot, the return value is in fact matplotlib.axes.Axes, as your variable naming suggests. It seems however that you're using matplotlib.pyplot.plot, which returns a list of matplotlib.lines.Line2D objects.
yaxis is an attribute of matplotlib.axes.Axes. To get your current matplotlib.axes.Axes instance, you can use matplotlib.gca() (get current axes). So the following works:
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker

plt.scatter(range(5), range(5), s=3)
plt.gca().yaxis.set_major_formatter(ticker.PercentFormatter())
plt.show()


text:
Q: Difference between calling classmethod or regular method from another classmethod I have been lurking SO a long time and it happens that now it's my first time to ask a question since I couldn't find answer anywhere. I really hope that the title is not that confusing, I don't know how else to name it.
I am working on a Matrix class which I need for my college project (LUP decomposition, matrix inverse, solving linear equations...). Basic matrix operations, operator overloading, some helper methods, nothing too fancy.
As I was writing the code I came up with something that bothers me. I have a private method _makeMatrix. That method creates intended Matrix object. Then, I have classmethods like createFromList and createFromFile and similar, basically methods that allow a different way to create Matrix object. All of these methods call _makeMatrix to actually create Matrix object.
So, my question is, what is the difference between these two, except that in second case I can call _makeMatrix without creating object (which I obviously don't want to because _makeMatrix is intended to be private):
def _makeMatrix(r):
    # some code that creates Matrix object m
    return m

@classmethod
def createFromList(cls, matxList)
    # code that makes matxList suitable for passing to _makeMatrix()
    r = matxList
    return Matrix._makeMatrix(r)

and
@classmethod
def _makeMatrix(cls, r):
    # some code that creates Matrix object m
    return m

@classmethod
def createFromList(cls, matxList)
    # code that makes matxList suitable for passing to _makeMatrix()
    r = matxList
    return cls._makeMatrix(r)

What are the exact differences between these two and are there any benefits/drawbacks of using one or another approach?

A: The proper decorator for this example should be staticmethod. Here's why:
class MyClass:
    @classmethod
    def foo(cls, arg):
        # Here I can reference the class to work on things related to it
        # even if it is being accessed by an object of this class
        pass

    @staticmethod
    def bar(arg):
        # This one behaves as a pure function unaware of the class it is
        # located on; even if it is accessed by an object of this class
        pass

    def baz(arg):
        # This one is tricky. Because it has no "self", it should crash
        # when accessed by an object of the class but not on the class
        # itself!
        pass

Testing:
x = MyClass()
x.foo(10) # OK, but `cls` is unused
x.bar(10) # OK!
x.baz(10) # Crash!!

MyClass.foo(10) # Ok, but `cls` is unused
MyClass.bar(10) # OK!
MyClass.baz(10) # OK!

So, whenever you need a "pure" function inside a class, i.e. a function which doesn't need any information from the class it is inserted this should be a staticmethod. If you don't want to instantiate an object but require some information from the class, you want classmethod.


text:
Q: Action Script Set Focus I have a KeyboardEvent.KEY_DOWN event listener on frame 10 and on the first frame a button which when clicked takes you to frame 10, if you add gotoAndPlay(10); on the top of frame 1 the event listener works fine, if you click the button to get to frame 10 you have to click somewhere in the frame before the event listener works..
Any ideas?
D.

A: You can use the stages focus property to set the keyboard focus to an interactive object.
stage.focus = stage;

A: In addition to TandemAdam's suggestion of shifting focus, you can register your events at the stage level. For example, call stage.addEventListener(...).
EDIT: Posted this right before I read your comment, Dean Bayley. It seems like you're already doing what I suggested, and in that case I can't reproduce your problem--it works fine on my machine.


text:
Q: C# - Sorting using Extension Method I want to sort a list of person say
List<Person> persons=new List<Person>();
persons.Add(new Person("Jon","Bernald",45000.89));
persons.Add(new Person("Mark","Drake",346.89));
persons.Add(new Person("Bill","Watts",456.899));

based on
public enum CompareOptions
 {
    ByFirstName,
    ByLastName,
    BySalary
 }

 public enum SortOrder
 {
   Ascending,
   Descending
 }

using lambda expression what is the way to go for sorting?
    public static List<Person> SortPeople(this List<Person> lst,
   CompareOptions opt1,SortOrder ord)

        {
           lst.Sort((p,op1,op2)=>{ how to apply lambda expression here});
        }

A: Do you really need the enums? I don't think that encapsulating your search logic in a method is much clearer or more DRY than just using linq methods:
persons.OrderBy( p => p.FirstName );
persons.OrderByDescending( p => p.Salary);

etc.

A: To get this to work in a lambda, the expression needs to form a Comparison<T> signature.  This would take 2 "Person" instances.  You could do this like:
public static void SortPeople(
    this List<Person> lst, CompareOptions opt1,SortOrder ord)
{
    lst.Sort((left, right) =>
             {
                 int result;
                 // left and right are the two Person instances
                 if (opt1 == CompareOptions.Salary)
                 {
                     result = left.Salary.CompareTo(right.Salary);
                 }
                 else
                 {
                     string compStr1, compStr2;
                     if (opt1 == CompareOptions.FirstName)
                     {
                          compStr1 = left.FirstName;
                          compStr2 = right.FirstName;
                     }
                     else
                     {
                          compStr1 = left.LastName;
                          compStr2 = right.LastName;
                     }
                     result = compStr1.CompareTo(compStr2);
                 }
                 if (ord == SortOrder.Descending)
                     result *= -1;
                 return result;
             });
}

A: using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication2
{
     class Program
    {
    static void Main(string[] args)
    {
        List<Person> persons = new List<Person>();
        persons.Add(new Person("Jon", "Bernald", 45000.89));
        persons.Add(new Person("Mark", "Drake", 346.89));
        persons.Add(new Person("Bill", "Watts", 456.899));

        persons.SortPeople(CompareOptions.ByFirstName, SortOrder.Ascending);

        persons.ForEach(p => Console.WriteLine(p.ToString()));

        persons.SortPeople(CompareOptions.ByFirstName, SortOrder.Descending);

        persons.ForEach(p => Console.WriteLine(p.ToString()));

        persons.SortPeople(CompareOptions.ByLastName, SortOrder.Ascending);

        persons.ForEach(p => Console.WriteLine(p.ToString()));

        persons.SortPeople(CompareOptions.ByLastName, SortOrder.Descending);

        persons.ForEach(p => Console.WriteLine(p.ToString()));

        persons.SortPeople(CompareOptions.BySalary, SortOrder.Ascending);

        persons.ForEach(p => Console.WriteLine(p.ToString()));

        persons.SortPeople(CompareOptions.BySalary, SortOrder.Descending);

        persons.ForEach(p => Console.WriteLine(p.ToString()));

        Console.ReadLine();
    }
}

public static class Extensions
{
    public static void SortPeople(this List<Person> lst, CompareOptions opt1,SortOrder ord){
        lst.Sort((Person p1, Person p2) =>
            {
                switch (opt1)
                {
                    case CompareOptions.ByFirstName:
                        return ord == SortOrder.Ascending ? p1.FirstName.CompareTo(p2.FirstName) : p2.FirstName.CompareTo(p1.FirstName);
                    case CompareOptions.ByLastName:
                        return ord == SortOrder.Ascending ? p1.LastName.CompareTo(p2.LastName) : p2.LastName.CompareTo(p1.LastName);
                    case CompareOptions.BySalary:
                        return ord == SortOrder.Ascending ? p1.Salary.CompareTo(p2.Salary) : p2.Salary.CompareTo(p1.Salary);
                    default:
                        return 0;
                }
            });
    }
}

public class Person
{
    public double Salary { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public Person(string first, string last, double salary)
    {
        this.Salary = salary;
        this.FirstName = first;
        this.LastName = last;
    }

    public override string ToString()
    {
        return string.Format("{0} {1} has a salary of {2}", this.FirstName, this.LastName, this.Salary);
    }
}

public enum CompareOptions { ByFirstName, ByLastName, BySalary }
public enum SortOrder { Ascending, Descending }

}

A: It looks like you are attempting to call the Sort method on List<T> which takes a Comparison<T> delegate.  This will require a bit of work because you first have to define a compatible comparison function.
First step is to write a comparison function based on the CompareOptions value
private static Comparison<Person> Create(CompareOptions opt) {
  switch (opt) {
    case CompareOptions.ByFirstName: (x,y) => x.FirstName.CompareTo(y.FirstName);
    case CompareOptions.ByLastName: (x,y) => x.LastName.CompareTo(y.LastName);
    case CompareOptions.BySalary: (x,y) => x.Salary - y.Salary;
    default: throw new Exception();
  }
}

By default this function will sort in ascending order.  If you want it to be descending simply negate the value.  So now writing SortPeople can be done by the following
public static List<Person> SortPeople(
   this List<Person> list,
   CompareOptions opt1,
   SortOrder ord) )
   var original = Create(opt1);
   var comp = original;
   if( ord == SortOrder.Descending ) {
     comp = (x,y) => -(orig(x,y));
   }
   list.Sort(comp);
}

EDIT
Version which is done 100% in a lambda
public static List<Person> SortPeople(
   this List<Person> list,
   CompareOptions opt1,
   SortOrder ord) )

   list.Sort( (x,y) => {
     int comp = 0;
     switch (opt) {
       case CompareOptions.ByFirstName: comp = x.FirstName.CompareTo(y.FirstName);
       case CompareOptions.ByLastName: comp = x.LastName.CompareTo(y.LastName);
       case CompareOptions.BySalary: comp = x.Salary.CompareTo(y.Salary);
       default: throw new Exception();
     }
     if ( ord == SortOrder.Descending ) {
       comp = -comp;
     }
     return comp;
   });
}


text:
Q: C# with MySql and Unicode characters My problem is when using C# and MySQL database to save some records by sending parameters.
Although i have already set the charset as Utf-8 and i can see the unicode characters correctly, the problem i get when trying to insert unicode characters is that it only saves half of the string.
The really weird this is that this happens only with unicode strings such as Greek words and only when i send the query with parameters.
Ie. if my query as seen in C# is:
string query = "INSERT INTO tablename VALUES (NULL, @somestring)";

and i set the @somestring parameters value as "TESTING". This would work just fine.
If i try to set the value as unicode string "ΤΕΣΤΙΝΓ", the query executes fine with no errors but only saves half the characters in the database, ie. it only saves "ΤΕΣΤ".
On the other hand if i remove the parameters and adjust the query to be as:
string somestring = "ΤΕΣΤΙΝΓ";
string query = "INSERT INTO tablename VALUES (NULL,'" + somestring + "')";

the query again works just fine AND saves the whole word/sentence in the database.
Hope i explained it correctly and you can understand my situation.
Thanks

A: The length of how you declare the parameter @somestring is too short in c#.
UTF-8 takes upto 3 bytes per character so you'd need length to be 21 not 7 for example to fit testing and varieties thereof
Saying that, I've not used c# to call MySQL (only SQL Server) but I'm sure this is the problem