text:
Q: How to do code-review changes before submitting in Perforce? Is there a way to get code-reviews done by PEER before submitting the changes in Perforce?I heard p4 shelve is an option,is it right?is there a better way?
p4 [g-opts] shelve [files ...]

A: I would say that "p4 shelve" is the best way to do code review.  You might want to look at Swarm, which offers code review features that are based around shelving.
https://www.perforce.com/perforce/r16.1/manuals/cmdref/p4_shelve.html
https://www.perforce.com/perforce/r16.1/manuals/swarm/chapter.code_reviews.html


text:
Q: Adding a background image to UINavigationBar covers the title I have successfully added a background image to my UINavigationBar with the following code:
    UIImageView *barView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"subHeader_lg.png"]];
    [calculatorBar addSubview:barView];

    [barView release];

However, with this method, the title of the view is covered by the image.

If I navigate further into the app, and then back, the title appears on top of the background image like so:

Any ideas how I can get the title to appear on top from the beginning?
I have tried pushing the barView to the back, but that makes it hidden behind everything else.
EDIT:
It seems that the custom draw function is the accepted answer, but I am unable to get the draw function to be called. I have this code at the bottom of my appdelegate.m file
@implementation UINavigationBar (UINavigationBarCustomDraw)

- (void)drawRect:(CGRect)rect
{
    UIImage *image = [UIImage imageNamed: @"subHeader_lg.png"];
    [image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
}

@end

A: When you call "addSubview" it adds it above any view that have already been added, thus covering the title.
What you want is
[calculatorBar insertSubview:barView atIndex:0];
However, this won't make it "stick" on subsequent pushes, so use the methods described at http://www.developers-life.com/custom-uinavigationbar-with-image-and-back-button.html for a better solution.
Also in iOS 5, Apple has added a built in way to customize the nav bar see http://developer.apple.com/library/ios/#documentation/UIKit/Reference/UIAppearance_Protocol/Reference/Reference.html#//apple_ref/doc/uid/TP40010906

A: To set the background image on your navigation bar, use the following.
On iOS 5.x, use
[calculatorBar setBackgroundImage: barView.image forBarMetrics: 0];
On iOS 4.x use
calculatorBar.layer.contents = (id)barView.image.CGImage;

redpajama_set_name: RedPajamaStackExchange


text:
Q: error: package path is not valid. valid system image paths are:ository... null I have installed the command line tools of android, correctly configured all environment variables.
When I am creating a virtual device with this command:
avdmanager create avd -n test -k "system-images;android-23;google_apis;x86"

It gives the following error:
error: package path is not valid. valid system image paths are:ository... null

I have already installed the SDK tool : sdkmanager "system-images;android-23;google_apis;x86"
And accepted the licenses sdkmanager --licenses
But still it's showing the same error.
By the way, I am using it for react-native

A: I've resolved the issue by installing image first
like
sdkmanager --install "system-images;android-23;google_apis;x86"
and then it is possible to create the emulator

A: In order to resolve your issue, you need to first run the cmd sdkmanager --list. A list will be populated with installed & available modules make sure: you have installed

*

*Build-tools sdkmanager build-tools 30

*Platform-tools sdkmanager platform 30

*System image sdkmanager "system-images;android-30;google_apis;x86"

*System image sdkmanager "system-images;android-30;google_apis;x86_64"
After installing or making sure the above are installed you can go ahead on creating avd.

*Create an avd - avdmanager create avd -n TestAVD -k "system-images;android-30;google_apis;x86" --device "Pixel_4"

*List created avds emulator -list-avds

*Start Emulator or AVD emulator @TestAVD

A: It seem that avdmanager can not find the local image. Please try:

*

*cd YOUR_SDK_ROOT_DIRECTORY

*avdmanager create avd -n test -k "system-images;android-23;google_apis;x86"


text:
Q: Is it ok to use the destructor inside function of a class to reset values? In my lectures I don't see anyone using the destructor for reseting values to there starting parameters instead doing every variable manually in the function. Will using a destructor in a class function for reseting/deleting cause any issues
Small example of what I mean:
    class Test1{
        private:
            int *test;
            bool valid;
        public:
        Test1(int value,bool valid=false){
            test=new int(value); this->valid=valid;
        }
        ~Test1(){
            delete test; test=nullptr; valid=false;
        }

    void ResetStats(int NewValue){
        this->~Test1();
        test1=new int(NewValue);
        valid=false;
    }

    }

A: Calling a non-trivial destructor explicitly ends object's lifetime (why?).
Share the functionality between ResetStats and destructor by putting it in a separate private function:
// Both destructor and ResetStats call Reset
~Test1(){
    Reset(nullptr);
}
void ResetStats(int NewValue) {
    Reset(new int(NewValue));
}
// Shared functionality goes here
private Reset(int *ptr) {
    delete test;
    test=ptr;
    valid=false;
}

A: No. Destructors are to be called when objects are being destroyed, not when attempting to reset its state.
In order to reset values I would prefer a swap with a default constructed object, copy/move construction with a default constructed object, or move assignment to a default constructed object.
Test1 test;
// Do stuff
test.swap(Test());

Of course, one would have to implement a swap method, a copy constructor, or assignment. Lookup move semantics to implement these properly.
Consider classes that enforce RAII. In our example, test gets a file handle in its constructor. If you called the deconstructor for purposes of resetting values, then the object no longer has a file handle when you attempted to reset it, because it is obtained in the constructor and released in the deconstructor.
Deconstructors should be only be called when an object is being destroyed, imo.


text:
Q: StackOverflowException in solrnet We have the same requirement of passing huge data like http://bugsquash.blogspot.in/2010/12/customizing-solrnet.html, we tried the following.
1) Increased the requestHeaderSize to Int32.MaxValue - stackoverflow exception
2) Used PostSolrconnection  - got the StackOverflow exception.
3) Downloaded the source of solrnet and added as project reference - Stackoverflow exception
 Then even we changed to GET, we are getting the StackOverflow exception. The error is coming when we have more than 500 reference ids. If we have less values, it works.
This is how we are calling,
searchResults = solrPost.Query(new SolrMultipleCriteriaQuery(new[]
                {
                    query
                 }),
                      new SolrNet.Commands.Parameters.QueryOptions
                      {
                          Fields = new[] { "*", "score" },
                          Start = pageSize,
                          Rows = 40,
                          OrderBy = listSort
                      });

Any ideas?
EDIT:
We tried requesting solr using HttpRequest and identified as maxBooleanClause issue and then POST started working through HttpRequest. But using SolrNet the error is occurred and it is happening at serializing the query object. queryserializer.serialize(Query)

A: Wondering why step 2 didn't work which is the exact fix for the long Get request issue, i.e. to switch over to Post request.
Chances are there is an issue with the piece of code where you are initialising SolrNet to use PostSolrConnection instead of the default SolrConnection. Need to look at the bit of code which gets you the instance of solrPost object. Take another look at it and post it here.

A: Unfortunately the SolrNet didn't work due to stackoverflow error while serializing the query parameters. Alternate workaround is posted http://smartcoder.in/solrnetstackoverflow/


text:
Q: Find a certain value in Column and selections I just want to check whether there is anything wrong with my code. My code is trying to look for this value 1234 in column A and once it found it, it will select the value besides it if the condition was met. If there isn't 1234, then it will do nothing. Unfortunately, it does nothing even if 1234 was in column A. When I remove the Else statement, it was able to run as per normal. May I know what is wrong with it?
Sub testr1()

Dim vCell As Range
Dim otherrow As Long

otherrow = 1

    Do

        Set vCell = Sheets(Sheet1").Cells(otherrow, 1)

        If vCell = 1234 Then
            If Range("B5") = "B" Then
                Cells(otherrow, 2).Select
            End If
        Else
        'Do nothing if 1234 is N.A.
        Exit Do
        End If
        otherrow = otherrow + 1
   Loop

End Sub

A: Please take a look at this answer. It explains how to select cells and their offsets.
Apply what you've learnt from the above answer inside the for each loop where the comment says match found do something. You can remove that comment or just add your code below it in between the If and End If which indicate that there is a match.
Sub testr1()

    Dim myRange As Range

    ' change this to any range you like to check
    Set myRange = Range("A1:A100")

    Dim searchTerm As String
    ' specify your search term
    searchTerm = "1234"

    Dim cell As Range
    ' cell will be each cell in your range
    For Each cell In myRange
        ' checks whether the cell matches the searchTerm
        If StrComp(cell, searchTerm, vbTextCompare) = 0 Then
            ' match found do something

        End If
    Next
End Sub

This code iterates through all cells in the myRange variable. In the above example the range is set to A1 to A100 so the cell variable inside the loop will be the A1 for the first iteration, A2 for second, and so on until A100.
The StrComp() function compares each cell's value to your searchTerm which is 1234 in the example.
match found do something is where I am hoping you will apply the logic from the answer I provided the link to above.

your original but revised code
Sub testr1()

Dim vCell As Range
Dim otherrow As Long

otherrow = 1

    Do

        Set vCell = Sheets("Sheet1").Cells(otherrow, 1)

        If vCell = 1234 Then
            If Range("B5") = "B" Then
                Cells(otherrow, 2).Select
            End If
        End If
        otherrow = otherrow + 1
   Loop Until IsEmpty(vCell)

End Sub

Get rid of the else statement. The Exit Do exits your loop if 1234 is not found. So in case if the first cell doesn't equal 1234 you exiting the loop, and it doesnt move to the second row.
Also, you need to add a Boolean statement do your loop to prevent an infinite loop. I have added Loop Until isEmpty(vCell) to let the loop know that once there is an empty cell to terminate the loop. There are other, better approaches but if you do not want to modify your original code too much then this should be enough to avoid infinite looping.
What is your code actually doing?
I keep asking myself what you are trying to achieve with your code and I can't seem to give a good reason. Your revised code (the above one) will iterate through all the cells in column A until it finds an empty one. It will look for a match to your 1234 (which should really be used as a string not a stand-alone number - consider wrapping it in double quotes). Once a match is found it will check whether column B on the corresponding row has a value of B in it. If it does then it will select that cell.
Where the logic fails...
What is the point of iterating through the entire column since only the last 1234 and it's corresponding B will be selected? It makes no sense to me as it is. Try to better explain what you are trying to achieve.
Solution
Based on the latest comment I have edited the code to meet criteria
Sub testr1()

Dim vCell As Range
Dim otherrow As Long

otherrow = 1

    Do

        Set vCell = Sheets("Sheet1").Cells(otherrow, 1)

        If StrComp(vCell, "1234", vbTextCompare) = 0 Then
            If StrComp(vCell.Offset(0, 1), "B", vbTextCompare) = 0 Then
                vCell.Offset(0, 1).Select
                ' if all criterias are met then the cell will be highlighted in red
                vCell.Offset(0,1).Interior.Color = RGB(255, 0, 0)
            End If
        End If
        otherrow = otherrow + 1
   Loop Until IsEmpty(vCell)

End Sub

You need to use .Offset(0,1) property of the Range object (vCell) to select the corresponding cell ( one to the right )

A: Special thanks to @mehow on giving me an idea to make my code work
Sub testr1()
Dim vCell As Range
Dim otherrow As Long

otherrow = 1

    Do While otherrow <= Rows.Count

        Set vCell = Sheets("Sheet1").Cells(otherrow, 1)

         If vCell = 1234 Then
            If Range("B5") = "B" Then
                Cells(otherrow, 2).Select
            End If
        Exit Do
        End If
        otherrow = otherrow + 1

        Loop

End Sub


text:
Q: Undefined variable post_id in custom quick edit coloumn I am trying to add a custom coloumn to post quick edit and everything is almost working. Custom meta is saved and passed but if I click on quick edit the preview is blank.
This is the error it gives me:

Notice: Undefined variable: post_id in /home/etimueit/public_html/wp-content/themes/caru/functions.php on line 626

Here is my code.
function disponibilitaet_quickedit_custom_posts_columns( $posts_columns ) {
    $posts_columns['disponibilitaet_edit_time'] = __( 'Modifica Disponibilità', 'disponibilitaet' );
    return $posts_columns;
}
add_filter( 'manage_post_posts_columns', 'disponibilitaet_quickedit_custom_posts_columns' );`

function disponibilitaet_quickedit_custom_column_display( $column_name, $post_id ) {
    if ( 'disponibilitaet_edit_time' == $column_name ) {
        $dispo_registrata = get_post_meta( $post_id, 'disponibilitaet_edit_time', true );

        if ( $dispo_registrata ) {
            echo esc_html( $dispo_registrata );
        } else {
            esc_html_e( 'N/A', 'disponibilitaet' );
        }
    }
}
add_action( 'manage_post_posts_custom_column', 'disponibilitaet_quickedit_custom_column_display', 10, 2 );

function disponibilitaet_quickedit_fields( $column_name, $post_type ) {
    if ( 'disponibilitaet_edit_time' != $column_name )
        return;`
    //This is line 626

    $dispo_registrata = get_post_meta( $post_id, 'disponibilitaet_edit_time', true );
    ?>
    <fieldset class="inline-edit-col-right">

                <?php esc_html_e( 'Disponibilità', 'disponibilitaet' ); ?>

                <input type="text" name="disponibilitaet_edit_time" class="disponibilitaetedittime" value="<?php echo $dispo_registrata;?>">

    </fieldset>
    <?php
}
add_action( 'quick_edit_custom_box', 'disponibilitaet_quickedit_fields', 10, 2 );

function disponibilitaet_quickedit_save_post( $post_id, $post ) {
    // if called by autosave, then bail here
    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
        return;

    // if this "post" post type?
    if ( $post->post_type != 'post' )
        return;

    // does this user have permissions?
    if ( ! current_user_can( 'edit_post', $post_id ) )
        return;

    // update!
    if ( isset( $_POST['disponibilitaet_edit_time'] ) ) {
        update_post_meta( $post_id, 'disponibilitaet_edit_time', $_POST['disponibilitaet_edit_time'] );
    }
}
add_action( 'save_post', 'disponibilitaet_quickedit_save_post', 10, 2 );

function disponibilitaet_quickedit_javascript() {
    $current_screen = get_current_screen();
    if ( $current_screen->id != 'edit-post' || $current_screen->post_type != 'post' )
        return;

    // Ensure jQuery library loads
    wp_enqueue_script( 'jquery' );
    ?>

    <?php
}
add_action( 'admin_print_footer_scripts-edit.php', 'disponibilitaet_quickedit_javascript' );

A: Sorry, I've had to change my answer after checking the WordPress Codex on adding custom editable data to the quick edit. So you'll have to remove the references to $post_id too (from the add_action arguments and from within your function).
It looks like the quick_edit_custom_box only takes 2 arguments: $column_name and $post_type. Then for getting and displaying the value, this has to be done using some more PHP and Javascript.
If you read further in to the WordPress Codex on the quick edit custom box and read further down to the section on 'Setting Existing Values', you'll see there's a fair bit more work required in order to do this.
I'd suggest reading the docs in a bit more detail as it's not quite as straight-forward as I first thought...

A: Here we are, finally found a solution, I leave it here so maybe it can help (maybe also future me XD ).
/**

*
 * Aggiungi Disponibilità nel Quick Edit
*/
function etdispo_quickedit_custom_posts_columns( $posts_columns ) {
    $posts_columns['et2018-quantita_birra'] = __( 'Disponibilità', 'etdispo' );
    return $posts_columns;
}
add_filter( 'manage_post_posts_columns', 'etdispo_quickedit_custom_posts_columns' );

function etdispo_quickedit_custom_column_display( $column_name, $post_id ) {
    if ( 'et2018-quantita_birra' == $column_name ) {
        $etdispo_regi = get_post_meta( $post_id, 'et2018-quantita_birra', true );

        if ( $etdispo_regi ) {
            echo esc_html( $etdispo_regi );
        } else {
            esc_html_e( 'N/A', 'etdispo' );
        }
    }
}
add_action( 'manage_post_posts_custom_column', 'etdispo_quickedit_custom_column_display', 10, 2 );

function etdispo_quickedit_fields( $column_name, $post_type, $post_id ) {
    if ( 'et2018-quantita_birra' != $column_name )
        return;

    $etdispo_regi = get_post_meta( $post_id, 'et2018-quantita_birra', true );
    ?>
    <fieldset class="inline-edit-col-right">

                <?php esc_html_e( 'Disponibilità', 'etdispo' ); ?>

                <input type="text" name="et2018-quantita_birra" class="etdispoedit" value="">

    </fieldset>
    <?php
}
add_action( 'quick_edit_custom_box', 'etdispo_quickedit_fields', 10, 3 );
function etdispo_quickedit_save_post( $post_id, $post ) {
    // if called by autosave, then bail here
    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
        return;

    // if this "post" post type?
    if ( $post->post_type != 'post' )
        return;

    // does this user have permissions?
    if ( ! current_user_can( 'edit_post', $post_id ) )
        return;

    // update!
    if ( isset( $_POST['et2018-quantita_birra'] ) ) {
        update_post_meta( $post_id, 'et2018-quantita_birra', $_POST['et2018-quantita_birra'] );
    }
}
add_action( 'save_post', 'etdispo_quickedit_save_post', 10, 2 );

function etdispo_quickedit_javascript() {
    $current_screen = get_current_screen();
    if ( $current_screen->id != 'edit-post' || $current_screen->post_type != 'post' )
        return;

    // Ensure jQuery library loads
    wp_enqueue_script( 'jquery' );
    ?>

    <?php
}
add_action( 'admin_print_footer_scripts-edit.php', 'etdispo_quickedit_javascript' );
/* Qui */
function etdispo_quickedit_set_data( $actions, $post ) {
    $found_value = get_post_meta( $post->ID, 'et2018-quantita_birra', true );

    if ( $found_value ) {
        if ( isset( $actions['inline hide-if-no-js'] ) ) {
            $new_attribute = sprintf( 'data-edit-dispo="%s"', esc_attr( $found_value ) );
            $actions['inline hide-if-no-js'] = str_replace( 'class=', "$new_attribute class=", $actions['inline hide-if-no-js'] );
        }
    }

    return $actions;
}
add_filter('post_row_actions', 'etdispo_quickedit_set_data', 10, 2);


text:
Q: mySQL "Too many connections" error influenced by number of mongrel instances? Recently I have started getting mySQL "too many connection" errors at times of high traffic.  My rails app runs on a mongrel cluster with 2 instances on a shared host.  Some recent changes that might be driving it:

*

*Traffic to my site has increased.  I
am now averaging about 4K pages a
day.

*Database size has increased.  My largest table has ~ 100K rows.
Some associations could return
several hundred instances in the
worst case, though most are far less.

*I have added some features that
increased the number and size of
database calls in some actions.

I have done a code review to reduce database calls, optimize SQL queries, add missing indexes, and use :include for eager loading.  However, many of my methods still make 5-10 separate SQL calls.  Most of my actions have a response time of around 100ms, but one of my most common actions averages 300-400ms, and some actions randomly peak at over 1000ms.
The logs are of little help, as the errors seem to occur randomly, or at least the pattern does not appear related to the actions being called or data being accessed.
Could I alleviate the error by adding additional mongrel instances?  Or are the mySQL connections limited by the server, and thus unrelated to the number of processes I divide my traffic across?
Is this most likely a problem with my coding, or should I be pressing my host for more capacity/less load on the shared server?

A: ActiveRecord has pooled database connections since Rails 2.2, and it's likely that that's what's causing your excess connections here. Try turning down the value of pool in your database.yml for that environment (it defaults to 5).
Docs can be found here.

A: Are you caching anything? It's an important part of alleviating application and database load. The Rails Guides have a section on caching.

A: Something is wrong. A Mongrel instance processes 1 request at a time so if you have 2 Mongrel instances then you should not be seeing more than 2 active MySQL connections (from the mongrels at least)
You could log or graph the output of SHOW STATUS LIKE 'Threads_connected' over time.
PS: this is not very many Mongrels. if you want to be able to service more than 2 simultaneous requests then you'll want more. ...if memory is tight, you can switch to Phusion Passenger and REE.


text:
Q: TypeError: this.list.push is not a function in ecmascript 6 When calling the add function of my GroceryList class, I get an error:

TypeError: this.list.push is not a function

Why is this?
class GroceryList {

      constructor() {
        this.list = {
            value: [],
            writable: false,
            enumerable: true
          };
      }

        add(item) {
        this.list.push(item);
      }

      getAll() {
        return this.list;
      }

      getItemIndex(value) {
        var index = this.list.length;
        while(--index > -1) {
          if(this.list[index] === value) {
            return index;
          }
        }
        return -1;
      }
    }

A: You are confusing

*

*A whole object
vs

*

*A list as an attribute of that object
The list object contains a list, but that does not mean it is a list. You should write list.value.push(x)

A: It seems you are trying to use a property descriptor. However, those descriptors only work with Object.defineProperty.
this.list = {
  value: [],
  writable: false,
  enumerable: true
};

literally assigns an object with the properties value, writable and enumerable to this.list.
What you seem to want is:
Object.definProperty(this, 'list', {
  value: [],
  writable: false,
  enumerable: true
});

Now this.list returns an array, but it's not possible to assign a new value to the property.


text:
Q: "Undefined Variable" while trying to read rows I'm trying to read a bunch of Rows and display them without the usual "ARRAY =>" crap but all I get is this error

Notice:  Undefined variable: data in C:\xampp\htdocs\sql.php on line 0

This is me code:
<?php virtual('/Connections/TDBS_local.php');
$query = "SELECT sub_category FROM sub_category WHERE main_category_id = 2 ";
$result = mysqli_query($TDBS_local, $query);
if ($result = mysqli_query($TDBS_local, $query)) {

/* fetch associative array */
if($row = mysqli_fetch_assoc($result)) {
    $data = unserialize($row['sub_category']);
}

/* free result set */
mysqli_free_result($result);
}

 print "
";
 print_r($data);
 print "
";
?>

Where am I going wrong?

A: Here is how to do it with pdo, mysqli, and mysql
MYSQLI
    $con=mysqli_connect("localhost","username","password","dbname");

    $sql="SELECT sub_category FROM sub_category WHERE main_category_id = 2";

    $result=mysqli_query($con,$sql);

    $new_array = array();

    while ($row = mysqli_fetch_array($result,MYSQLI_ASSOC)){
        $new_array[] = $row;
    }
    print_r($new_array);

    mysqli_free_result($result);

    mysqli_close($con);

MYSQL
mysql_connect("localhost","username","password");
mysql_select_db("dbname");

$result = mysql_query("SELECT sub_category FROM sub_category WHERE main_category_id = 2");
$new_array = array();
while ($row = mysql_fetch_array($result)) {
    $new_array[] = $row;
}
print_r($new_array);

PDO
$pdo = new PDO('mysql:host=localhost;dbname=dbname', 'username', 'password');

$statement = $pdo->query("SELECT sub_category FROM sub_category WHERE main_category_id = 2");
$new_array = array();
while ($row = $statement->fetch(PDO::FETCH_ASSOC)) {
    $new_array[] = $row;
}
print_r($new_array);

A: I think you have to use require or include instead of virtual:
<?php
require('Connections/TDBS_local.php');
$data = '';
$query = "SELECT sub_category FROM sub_category WHERE main_category_id = 2 ";
$result = mysqli_query($TDBS_local, $query);
if ($result = mysqli_query($TDBS_local, $query)) {

/* fetch associative array */
if($row = mysqli_fetch_assoc($result)) {
    $data = unserialize($row['sub_category']);
}

/* free result set */
mysqli_free_result($result);
}

 print "
";
 print_r($data);
 print "
";
?>


text:
Q: Position changing after rotation processing I am working on a tic-tac-toe game in my computer science class using processing-java. In my program, on the far right side I have a status bar that states which player's turn it is, who won, and who lost. This status bar is also placed vertically, so in my code I am rotating it and although it is rotating properly, it is causing another problem. The status bar appears in a certain area on the game screen, but after one X or O is placed, it moves spots and I am unsure of how to fix this. After another piece is placed, it moves a second time, then a third and then finalizes its place in an area I do not want it to be. This is my code regarding the text and rotation.
void updateStatus(String status) { // function to update the status message
  fill(0);
  rect(statusX, sbh, width, height-1);
  stroke(#FFFFFF);
  strokeWeight(4);
  line(statusX, sbh, statusX, screenH); // Status line
  fill(255);

  String fullStatus = "It is player "+status+"'s turn";
  //String fullStatus = "It is player X's turn";
  float statusTxtX = width*15/16, statusTxtY = height*2.5/7;

  pushMatrix();
  translate(statusTxtX, statusTxtY);
  rotate(HALF_PI);
  textSize(55);
  textFont(mainFont);
  text(fullStatus, 0, 0);
  //textDraw(status, mainFont, height, 255, CENTER, CENTER, statusX, height*3/12, width, height*1/2);
  popMatrix();
}

A: The problem is with text-aligns. There is one in the placing() function and one in the textDraw() function. When you disable those the text stays in the same location. However, this will mess up the X's and O's, so you'll need to do some work on tracing where what text-align is set.
As a more general tip (since you're learning): put your first focus on functionality. You could for example build TicTacToe using println() and the numpad as input. When the game mechanics work you can add a nice user interface. Doing both at the same time often makes messy code that is prone to errors that are hard to debug. I bumped into that wall plenty of times myself ;)


text:
Q: How to efficiently rename variables using sas I got a SAS dataset DATA which contains 100 variables. Unfortunately, this dataset dont contain the name of each variable. It just name the variable as VAR1 - Var100. I got a seperate file which list the name of each variable Name (one name per cell). I donot want to rename it one by one so the following code is not an option.
data lib.test (rename = (var1= truename1 var2 = truename2 ...) ;
   set lib.test;
run;

Following Reeze's suggestions, I try to implement the following solution http://stackoverflow.com/questions/29006915/rename-variable-regardless-of-its-name-in-sas.
proc sql;
   /* Write the individual rename assignments */
   select strip(name) || " = " || substr("ABCDEFGHIJKLMNOPQRSTUVWXYZ", varnum , 1)

   /* Store them in a macro variable and separate them by spaces */
   into :vars separated by " "

   /* Use a sas dictionary table to find metadata about the dataset */
   from sashelp.vcolumn
   where libname = "LIB"
     and memname = "TEST"
     and 1 <= varnum <= 100;
quit;

proc datasets lib=lib nolist nodetails;
   modify test;
   rename &vars.;
quit;

Now, instead of using a,b,c,d ... to rename my variable, I want to use the name on datasetName as new names. Dataset Name looks like the following (I can transpose it if it is easier to use). The order of Name is the same as variable sequence in dataset lib.test. How can I change the code above to achieve this?
Name
name1
anc
sjsjd
mdmd

A: You can convert your NAME dataset to have both the old and new names and then use that to generate the rename pairs.
data name_pairs;
  set name ;
  old_name = cats('VAR',_n_);
run;

proc sql noprint ;
  select catx('=',old_name,name)
    into :vars separated by ' '
    from name_pairs
  ;
quit;

You can then use the macro variable VARS in your rename statement.


text:
Q: Error uploading file using MSGraph in onedrive business account I use Microsoft graph to create a web application that uploads files to OneDrive.
File upload uses upload session.
https://learn.microsoft.com/ja-jp/graph/api/driveitem-createuploadsession?view=graph-rest-1.0
uploading a file fails if the upload destination account is a Business account.
The error that occurs is
{" error ": {" innerError ": {" code ":" invalidToken "}," code ":" unauthenticated "," message ":" This access token is not valid on this endpoint. "}}.
However, it will succeed if the upload destination is a personal account
By the way, the simple upload will succeed in both business and personal.
Do you know if there are any measures?
The following is the upload procedure.
(1)
POST /me/drive/root:/sample.txt:/createUploadSession
Authorization: Bearer {bearer token}
Content-Type: application/json
{
  "item": {
    "@microsoft.graph.conflictBehavior": "rename",
    "name": "sample.txt"
  }
}

(2)response
HTTP/1.1 200 OK
Content-Type: application/json

{
  "uploadUrl": "https://our-tenant-my.sharepoint.com/personal/our_tenant_onmicrosoft_com/_api/v2.0/drive/items/aaaa/uploadSession?guid='example'&path='example'&overwrite=False&rename=True&dc=0&tempauth=example",
  "expirationDateTime": "2019-05-24T05:07:08.728Z"
}

(3)
Upload bytes to the upload session
PUT https://our-tenant-my.sharepoint.com/personal/our_tenant_onmicrosoft_com/_api/v2.0/drive/items/aaaa/uploadSession?guid='example'&path='example'&overwrite=False&rename=True&dc=0&tempauth=example

(4) return error
HTTP/1.1 401
{"error":{"innerError":{"code":"invalidToken"},"code":"unauthenticated","message":"This access token is not valid on this endpoint."}}

By the way, in case of a personal account, uploadUrl of the response is
https://api.onedrive.com/rup/example/more~~~

Will be back.
I can upload with this path.
UploadUrl is different in the personal account and the business account, is this related to this error?
Is there a way to solve this problem?

A: When using PUT don't send the token it's not accepted there.

Including the Authorization header when issuing the PUT call may result in a HTTP 401 Unauthorized response.
The Authorization header and bearer token should only be sent when issuing the POST during the first step. It should be not be included when issueing the PUT.

A: This problem has been resolved.
The reason is that the HTTP client of the web application has rearranged the query parameter of the URL.
I used faraday of Ruby on Rails, so I changed this.


text:
Q: Positioning of Pgfplot axis labels I'm trying to adjust the position of my axes labels and I'm having some trouble:
\documentclass{article}
\usepackage{float}
\usepackage{pgfplots}
\usepackage{graphicx}
\begin{document}
\begin{figure}[H]
\centering
\begin{tikzpicture}
\begin{axis}[
    axis lines=middle,
    axis line style={->},
    x label style={at={(current axis.right of origin)},anchor=north, below=5mm},
    y label style={at={(current axis.above origin)},rotate=90,anchor=south east},
    xlabel={$u$ unemployment},
    ylabel={$\pi$ inflation}]
\addplot[black,samples=100,domain=0:1] {120*(1-x)^(1/3)-1};
\end{axis}
\end{tikzpicture}
\end{figure}
\end{document}

It may be that I don't understand the label style stuff, but I want the y label to be rotated and on the left of the y-axis (so it doesn't intersect with the ticks) and I want the x label to be below the x-axis (so it also doesn't run into ticks).  Also, is there a way to center the labels in those positions?

A: You can control the position of labels accurately with
at={(axis description cs:0.5,-0.03)}

The start of the axis is 0 and the end is 1.
\documentclass{article}
\usepackage{pgfplots}
\begin{document}
\begin{tikzpicture}
\begin{axis}[
    axis lines=middle,
    axis line style={->},
    x label style={at={(axis description cs:0.5,-0.1)},anchor=north},
    y label style={at={(axis description cs:-0.1,.5)},rotate=90,anchor=south},
    xlabel={$u$ unemployment},
    ylabel={$\pi$ inflation}]
\addplot[black,samples=100,domain=0:1] {120*(1-x)^(1/3)-1};
\end{axis}
\end{tikzpicture}
\end{document}

A: You can use the xlabel near ticks and ylabel near ticks styles. These will automatically place the labels outside the ticks, whereas with Harish's solution you have to manually change the position to accommodate larger ticklabels. They are described in section 4.9.3 Labels of the manual, and are defined as
\pgfplotsset{
  /pgfplots/xlabel near ticks/.style={
     /pgfplots/every axis x label/.style={
        at={(ticklabel cs:0.5)},anchor=near ticklabel
     }
  },
  /pgfplots/ylabel near ticks/.style={
     /pgfplots/every axis y label/.style={
        at={(ticklabel cs:0.5)},rotate=90,anchor=near ticklabel}
     }
  }

Code example:
\documentclass{article}
\usepackage{pgfplots}
\begin{document}
\begin{tikzpicture}
\begin{axis}[
    axis lines=middle,
    axis line style={->},
    ylabel near ticks,
    xlabel near ticks,
    xlabel={$u$ unemployment},
    ylabel={$\pi$ inflation}]
\addplot[black,samples=100,domain=0:1] {120*(1-x)^(1/3)-1};
\end{axis}
\end{tikzpicture}
\end{document}


text:
Q: Loading external .class files with Javassist I have a directory called 'TestDir' which contains several external .class files that i would like to load and modify at runtime with JAssist.
I understand this is how you are supposed to load external classes with javassist:
    ClassPool pool = ClassPool.getDefault();

    pool.insertClassPath("C:\\Users\\MainPC\\Documents\\TestDir");
    CtClass clazz = pool.getCtClass("TestClass");

This works without throwing any exceptions, however the moment try to call any methods of 'clazz', like for example:
    System.out.println(clazz.getGenericSignature());

I receive the following exception:
Exception in thread "main" java.lang.RuntimeException: cannot find TestClass: TestDir.TestClass found in TestClass.class
at javassist.CtClassType.getClassFile3(CtClassType.java:211)
at javassist.CtClassType.getClassFile2(CtClassType.java:178)
at javassist.CtClassType.getGenericSignature(CtClassType.java:379)
at ReflectionTests.main(ReflectionTests.java:33)

Can someone explain to me why this happens?

A: I did something like this javassist, and as far as I remember, the package name is part of the class file. That means, your code needs to be changed to:
ClassPool pool = ClassPool.getDefault();

pool.insertClassPath("C:\\Users\\MainPC\\Documents");
CtClass clazz = pool.getCtClass("TestDir/TestClass");


text:
Q: Can't connect SSH with paramiko to a Google Compute Engine instance I found a lot of similar questions here in SO, but any of them helped me, even this problem seems to be simple.
I'm trying to connect to a remote Google Compute Engine instance through SSH (I want to use SFTP) using paramiko. Below is my code:
        client = paramiko.SSHClient()
        client.load_system_host_keys()
        client.connect('External_IP_Get_In_GCE_panel', username='myuser')
        stdin, stdout, stderr = client.exec_command('ls')
        for line in stdout:
            print('... ' + line.strip('\n'))
        client.close()

With this code, I have the error

PasswordRequiredException: Private key file is encrypted

When I tried client.connect('External_IP_Get_In_GCE_panel', username='myuser', password='') the error is:

BadAuthenticationType: ('Bad authentication type', [u'publickey']) (allowed_types=[u'publickey'])

My SSH key to access Google Compute engine has no password. I can use the gcloud compute ssh instance-name and also access SFTP throug Filezilla without problems.
As I said, I tried a lot of alternatives found here in SO, but any of them helped me. Below are 3 other versions of the code:
Using key
    key = paramiko.RSAKey(data=base64.b64decode(b"""AAAAB3Nza..."""))
    client = paramiko.SSHClient()
    client.get_host_keys().add('External_IP_Get_In_GCE_panel', 'ssh-rsa', key)
    client.connect('External_IP_Get_In_GCE_panel', username='myuser', password='')
    # I got the key using ssh-keyscan `External_IP_Get_In_GCE_panel`in my local machine

Using another lib
    key = paramiko.RSAKey(data=decodebytes(keydata))
    cnopts = pysftp.CnOpts()
    cnopts.hostkeys.add('External_IP_Get_In_GCE_panel', 'ssh-rsa', key)

    with pysftp.Connection('External_IP_Get_In_GCE_panel', username='myuser', cnopts=cnopts) as sftp:
        with sftp.cd('../directory'):
            sftp.get('remote_file')'''

Using the ssh key file
    self.client = paramiko.SSHClient()
    self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    self.client.connect(hostname="External_IP_Get_In_GCE_panel", username="myuser", key_filename=os.path.expanduser('~/.ssh/ssh_key_file'), password='') # also tried ssh_key_file.pub

In all this versions (and some others) I tried to use password='', password=None and not send password argument. The results is always the same erros above.
Any tip about what I'm doing wrong?

A: The key is encrypted, you need a password (and presumably non-empty so) to decrypt the private key, i.e.
key = paramiko.RSAKey(data=base64.b64decode(b"""AAAAB3Nza..."""), password='my key password')

The server there only allows public key authentication, so giving password to client.connect does not make any sense.


text:
Q: Get Outlook AppointmentItem using GlobalAppointmentID I am developing a calendar for my firm that synchronizes with Outlook Calendar.
Atm I can:

*

*import appointments from Outlook and show them in my calendar

*update my appointments when Outlook appointments get updated

*create Outlook appointments when appointments get created in my calendar

The only issue I have is updating/deleting Outlook appointments when my appointments update/delete.
I have the GlobalAppointmentID of the corresponding appointments but I can't seem to search on that ID.
I tried:
using Microsoft.Office.Interop;

private void GetAppointment(string myGlobalAppointmentID)
{
Outlook.Application oApp = new Outlook.Application();

Outlook.NameSpace mapiNamespace = oApp.GetNamespace("MAPI");

Outlook.MAPIFolder calendarFolder = mapiNamespace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderCalendar);
Outlook.Items outlookCalendarItems = calendarFolder.Items;

Outlook.AppointmentItem appointmentItem = (Outlook.AppointmentItem)outlookCalendarItems.Find("[GlobalAppointmentID] = '{0}'", myGlobalAppointmentID));

//update or delete appointmentItem here (which I know how to do)
}

I keep getting 'Condition is not valid' Exception.
Apparently Outlook does not allow to search on binary properties (such as GlobalAppointmentID).
I use the same outlookCalendarItems.Find() and calendarFolder.Items.Restrict() without problems in other instances.
I tried using Redemption but I couldn't get it to work either.
Does anybody have experience or a suggestion?

A: Yes, OOM won't let you search on binary properties (as well as recipients or attachments), but Redemption (I am its author) should work. The following script (VBA) worked just fine for me:
  set Session = CreateObject("Redemption.RDOSession")
  Session.MAPIOBJECT = Application.Session.MAPIOBJECT
  set Folder = Session.GetDefaultFolder(olFolderCalendar)
  set appt = Folder.Items.Find("GlobalAppointmentID = '040000008200E00074C5B7101A82E00800000000D0FECEE58FEAD70100000000000000001000000041C887A3FA12694F8A0402FEFFAD0BBB'")
  MsgBox appt.Subject

A: The Outlook object model doesn't support searching for binary properties such as GlobalAppointmentId (any other PT_BINARY property) with Items.Find/Items.FindNext/Items.Restrict.
The only workaround is to loop through all item in the Calendar folder (which is inefficient) or search using Extended MAPI (or using third-party wrappers such as Redemption.

A: What I ended up doing after looking further:
I added a text UserProperty where I put the GlobalAppointmentID("GAID") in.
You can Filter on those.
And it seems to do the trick.
private void AddGAIDIfNeeded(Outlook.AppointmentItem app)
        {
            bool GAIDexists = false;
            if (app.UserProperties.Count != 0)
            {
                foreach (UserProperty item in app.UserProperties)
                {
                    if (item.Name == "GAID")
                    {
                        GAIDexists = true;
                        break;
                    }
                }
            }

            if (GAIDexists == false)
            {
                app.UserProperties.Add("GAID", Outlook.OlUserPropertyType.olText);
                app.UserProperties["GAID"].Value = app.GlobalAppointmentID;
                app.Save();
            }
        }

And to find a specific AppointmentItem:
private void DeleteOutlookAppointmentByGAID(string globalAppointmentID)
        {
            Outlook.Application oApp = new Outlook.Application();
            Outlook.NameSpace mapiNamespace = oApp.GetNamespace("MAPI");
            Outlook.MAPIFolder calendarFolder = mapiNamespace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderCalendar);
            Outlook.Items outlookCalendarItems = calendarFolder.Items;

            try
            {
                Outlook.AppointmentItem appointmentItem = null;
                appointmentItem = outlookCalendarItems.Find(String.Format("[GAID] = '{0}'", globalAppointmentID));

                if (appointmentItem != null)
                {
                    appointmentItem.Delete();
                }
            }
            catch (Exception ex)
            {
                classExecptionLogging.LogErrorToFolder(ex);
            }

        }


text:
Q: Error in building wheel for osqp because "No module named cmake' " I'm trying to install the cvxpy package in my virtual environment of PyCharm. I typed C:\Users\<Username>\PycharmProjects\<projectName>\venv\Scripts>pip install cvxpy, and got:
Collecting cvxpy
  Using cached cvxpy-1.2.1-cp311-cp311-win_amd64.whl
Collecting ecos>=2
  Using cached ecos-2.0.10-cp311-cp311-win_amd64.whl
Collecting osqp>=0.4.1
  Using cached osqp-0.6.2.post5.tar.gz (226 kB)
  Installing build dependencies ... done
  Getting requirements to build wheel ... done
  Preparing metadata (pyproject.toml) ... done
Requirement already satisfied: numpy>=1.15 in c:\users\<Username>\PycharmProjects\<projectName>\venv\lib\site-packages (from cvxpy) (1.23.4)
Collecting scs>=1.1.6
  Using cached scs-3.2.0-cp311-cp311-win_amd64.whl
Requirement already satisfied: scipy>=1.1.0 in c:\users\<Username>\PycharmProjects\<projectName>\venv\lib\site-packages (from cvxpy) (1.9.3)
Collecting qdldl
  Using cached qdldl-0.1.5.post2-cp311-cp311-win_amd64.whl
Building wheels for collected packages: osqp
  Building wheel for osqp (pyproject.toml) ... error
  ERROR: Command errored out with exit status 1:
   command: 'C:\Users\<Username>\PycharmProjects\<projectName>\venv\Scripts\python.exe' 'C:\Users\<Username>\PycharmProjects\<projectName>\venv\Lib\site-packages\pip\_vendor\pep517\in_process\_in_process.py' build_wheel 'C:\Users\<Username>\AppD
ata\Local\Temp\tmptb8bjomi'
       cwd: C:\Users\<Username>\AppData\Local\Temp\pip-install-6glakjuq\osqp_f4f485f728cb41eb9bd04d39cf2e5c81
  Complete output (82 lines):
  Disabling LONG
  Remove long integers for numpy compatibility. See:
   - https://github.com/numpy/numpy/issues/5906
   - https://github.com/ContinuumIO/anaconda-issues/issues/3823
  You can reenable long integers by passing: --osqp --long argument.

  running bdist_wheel
  running build
  running build_py
  running egg_info
  writing src\osqp.egg-info\PKG-INFO
  writing dependency_links to src\osqp.egg-info\dependency_links.txt
  writing requirements to src\osqp.egg-info\requires.txt
  writing top-level names to src\osqp.egg-info\top_level.txt
  listing git files failed - pretending there aren't any
  reading manifest file 'src\osqp.egg-info\SOURCES.txt'
  reading manifest template 'MANIFEST.in'
  adding license file 'LICENSE'
  running build_ext
  Traceback (most recent call last):
    File "<frozen runpy>", line 198, in _run_module_as_main
    File "<frozen runpy>", line 88, in _run_code
    File "C:\Users\<Username>\PycharmProjects\<projectName>\venv\Scripts\cmake.exe\__main__.py", line 4, in <module>
  ModuleNotFoundError: No module named 'cmake'
.
.
.
  subprocess.CalledProcessError: Command '['cmake', '--version']' returned non-zero exit status 1.
  ----------------------------------------

  ERROR: Failed building wheel for osqp

Trying C:\Users\<Username>>pip install cvxpy does successfuly install cvxpy, but then cvxpy isn't in my virtual environment. I tried uninstalling cmake and then installing cvxpy - didn't work. I uninstalled and reinstalled cmake and didn't work.
cmake version is the latest, ver 3.24.1, obtained from running pip install cmake
python version is 3.11.0, pip version is 21.3.1.

A: Update: this has been resolved by uninstalling python version 3.11.0 and installing python version 3.10.7. This page  suggested that OSQP developers have validated the build wheels properly for 3.10. So maybe they havn't done that for 3.11 yet.

A: I just downloaded the zip file for "cvxpy" package from https://github.com/cvxpy/cvxpy, unzipped the file and went to where the "setup.py" file is, and ran the command "python setup.py install" to successfully install "cvxpy". I am using python 3.11.


text:
Q: How to add cover art to MP4? I'm trying to find an effective way to update the metadata for my MP4 files that I plan to put on a DLNA server. First thing, I want to have the video files have a cover art.
I'm specifically using 640x360 JPG files to be the cover art.
I might also want to add some other tags, like media type or update the Title.  Please let me know what can be done.
If code suggestions are available, please know I have the file name details in a variable %file% to handle things. The JPG has the same name as the source MP4 file, so it's easy enough to get the file type and remove the extension, which is what I've done so far.
My goal is to be able to simply drop the MP4 file on the following batch file and know its filename and full path, the JPG file, and attach it to the orgininal MP4 file. Apparently ffmpeg.exe won't write to the file it pulled from, so I have it go to a temp file and then use MOVE to replace the old file with the fixed file.
@ECHO OFF
set arg=%1
set file=%arg:~1,-5%
ffmpeg -i "%file%.mp4" -i "%file%.jpg" -acodec copy -vcodec copy -map 0 -map 1:0 "%file%WIP.mp4"
move /Y "%file%WIP.mp4" "%file".mp4"

This code did not seem to work. It doesn't show up in Windows as the cover art, so I'd say it failed.

A: Can would do a try, by to change the argument and the position of -map 0 -map 1:0 to immediately after name file input -map 1 -map 0 along command line, so, this work to me...
Sorry my limited English.
@echo off & cd "%~dp0" && setlocal enableextensions enabledelayedexpansion

for %%i in (%*) do (

     set "_arg=%%i"

     set "_file=!_arg:~1,-5!"

     if exist "!_file!.mp4" ffmpeg -i "!_file!.mp4" -i "!_file!.jpg"--map 1 -map 0  -acodec copy -vcodec copy "!_file!WIP.mp4" && move /Y "!_file!WIP.mp4" "!_file!".mp4"

     shift

    )


text:
Q: Hibernate distributing cache between multiple applications Is it possible to distribute Java Hibernate cache between multiple applications without implementing some external infrastructure? I have separate hibernate context file in every application, maybe merging it into one somehow will do the trick. All apps are deployed on the same server (jboss).

A: Cacheonix provides a distributed Hibernate cache plugin: https://github.com/cacheonix/cacheonix-core


text:
Q: How display percent values on a stacked bar plot using ggplot in R I've produced this graph (on the attached photo) using ggplot2.
My code goes like this:
ggplot(data, aes(fill=condition, y=value, x=period)) +
geom_bar(position="fill", stat="identity")+
xlab("Période") +  ylab("Pourcentage") +
ggtitle("Répartition des français et étrangers")+
scale_y_continuous(labels = scales::percent)+
scale_fill_brewer(palette = "OrRd")

Result looks like this
I just need to display the values on the bars. However, adding geom_text is not straightforward.
I would appreciate it if you could provide some ideas.

A: Without knowing the data:
Try:   geom_text(aes(label = paste0(value*100,"%")), position = position_stack(vjust = 0.5), size = 2)
ggplot(data, aes(fill=condition, y=value, x=period)) +
  geom_bar(position="fill", stat="identity")+
  geom_text(aes(label = paste0(value*100,"%")),
            position = position_stack(vjust = 0.5), size = 2)
  xlab("Période") +  ylab("Pourcentage") +
  ggtitle("Répartition des français et étrangers")+
  scale_y_continuous(labels = scales::percent)+
  scale_fill_brewer(palette = "OrRd")


text:
Q: Capybara trim down the link and getting ActionController::RoutingError: I have a link in my ruby on rails project which redirects the user here: https://blah.com/files/form/anonymous/api/library/142270db-..., but when running the command
bundle exec rpsec spec/features/*

When I simulate the click of the link I get:
 ActionController::RoutingError:

No route matches [GET] "/files/form/anonymous/api/library/142270db-...
Why is Capybara triming down the link and then getting a routing error?

A: Since you don't mention a specific driver, I assume you're using the racktest driver.  It ignores the host name and assumes all URLs point to your app since that's all it can access.


text:
Q: Differentiation of $f(x)=2x(2+3x^2)^3$ The question:

Differentiate $f(x)=2x(2+3x^2)^3$.

How do I approach this problem? Do I only have to use the product rule...? I have the answer but I don't know how to get there.
Here is my attempt to this problem:
$$\frac{df}{dx}=(2)(2+3x^2)^3 + (2x)(6x)(3)(2+3x^2)^2 = \\ =(2+3x^2)^2 [(2)(2+3x^2) + (2x)(6x)(3)] = \\ = (2+3x^2)^2 [(4+6x^2) + 36x^2] = \\ = (2+3x^2)^2 (42x^2+4)$$

A: You get the right answer:
$$(2+3x^2)^2 (42x^2+4)=(2+3x^2)^2 \cdot 2 \cdot (21x^2+2)$$


text:
Q: OCR of Chinese characters with probability I have a collection of Chinese character images (with single characters, not text). I need a way to OCR them, i.e. to map them to Unicode.
However, a crucial fact is that many of the images are a bit blurred, or quite small. Thus, the algorithm (or library, or online service) should not just return one Unicode value, but some kind of probability vector which estimates the probability that the given image represents which character.
For example, the image

could have the following distribution:

*

*咳 95%

*骇 4%

*该 1%

I'd rather not train a neural network myself, since I'm sure that all OCR models are probabilistic underneath. All I'm looking for is an OCR solution that exposes the probabilities for single characters.


text:
Q: equation number is not appearing for my set of equations I wanted to number the following set of equations as a single equation but the equations number does not appear. Any help would be appreciated.
{\footnotesize
\begin{equation}\label{demomodel}
\begin{array}{lcl}
H'=\underbrace{\mu \frac{(H+F)^i}{K^i+(H+F)^i}h(M_I)}_{\text{new healthy ticks}}-\underbrace{\beta_1 M_I \frac{H}{H+H_I+F}}_{\text{infected ticks}}-\underbrace{(d_1+\delta_1) H}_{\text{death}} -\underbrace{\gamma_1 (M_I+M_S) H}_{\text{death due to ticks}}
 -\underbrace{H\left(\sigma_1-\sigma_2 \left(\frac{F}{H+F}\right)\right)}_{\text{transition term}},\\
 %next eq
F'=\underbrace{H\left(\sigma_1-\sigma_2 \left(\frac{F}{H+F}\right)\right)}_{\text{transition term}}-\underbrace{\beta_1 M_I \frac{F}{H+H_I+F}}_{\text{infected ticks}}-\underbrace{(p+d_2+\delta_2) F}_{\text{death}} -\underbrace{\gamma_2 (M_I+M_S) F}_{\text{death due to ticks}}, \\
%next eq
H'_I=\underbrace{\beta_1 M_I \frac{H+F}{H+H_I+F}}_{\text{infected ticks}}-\underbrace{(d_3+\delta_3) H_I}_{\text{death}}-\underbrace{\gamma_3 (M_I+M_S)H_I}_{\text{death due to ticks}}, \\
%next eq
M'_I=\underbrace{rM_I\left(1-\frac{M_I+M_S}{\alpha (H+H_I+F)}\right)}_{\text{logistic growth of ticks}}+\underbrace{\beta_2 M_S\frac{H_I}{H+H_I+F}}_{\substack{\text{virus-free ticks to}\\ \text{virus-carrying ticks}}}-\underbrace{\beta_3 M_I \frac{H+F}{H+H_I+F}}_{\substack{\text{virus-carrying ticks lose }\\\text{virus to uninfected host}}}
-\underbrace{\delta_4 M_I}_{\substack{\text{death due}\\ \text{ to virus}}}, \\
%next eq
M'_S=\underbrace{rM_S\left(1-\frac{M_I+M_S}{\alpha (H+H_I+F)}\right)}_{\text{logistic growth of ticks}}-\underbrace{\beta_2 M_S \frac{H_I}{H+H_I+F}\nonumber}_{\substack{\text{virus-free ticks to}\\ \text{ virus-carrying ticks}}}+\underbrace{\beta_3 M_I \frac{H+F}{H+H_I+F}}_{\substack{\text{virus-carrying ticks lose}\\\text{virus to uninfected host}}}
-\underbrace{\delta_5 M_S}_{\substack{\text{death due}\\ \text{to virus}}}.
\end{array}
\end{equation}
}

A: You have \nonumber which prevents the equation number. You could also consider using \raisetag to position it by one of the shorter lines. If you wrap the first line then it more or less fits without extending into the margins,

\documentclass{article}

\usepackage{mathtools}

\begin{document}

\noindent X\dotfill X

{\footnotesize
\begin{gather}\label{demomodel}
\hspace*{-1cm}\begin{aligned}
H'&=\underbrace{\mu \frac{(H+F)^i}{K^i+(H+F)^i}h(M_I)}_{\text{new healthy ticks}}-\underbrace{\beta_1 M_I \frac{H}{H+H_I+F}}_{\text{infected ticks}}-\underbrace{(d_1+\delta_1) H}_{\text{death}} -\underbrace{\gamma_1 (M_I+M_S) H}_{\text{death due to ticks}}
 -\underbrace{H\left(\sigma_1-\sigma_2 \left(\frac{F}{H+F}\right)\right)}_{\text{transition term}},\\
 %next eq
F'&=\underbrace{H\left(\sigma_1-\sigma_2 \left(\frac{F}{H+F}\right)\right)}_{\text{transition term}}-\underbrace{\beta_1 M_I \frac{F}{H+H_I+F}}_{\text{infected ticks}}-\underbrace{(p+d_2+\delta_2) F}_{\text{death}} -\underbrace{\gamma_2 (M_I+M_S) F}_{\text{death due to ticks}}, \\
%next eq
H'_I&=\underbrace{\beta_1 M_I \frac{H+F}{H+H_I+F}}_{\text{infected ticks}}-\underbrace{(d_3+\delta_3) H_I}_{\text{death}}-\underbrace{\gamma_3 (M_I+M_S)H_I}_{\text{death due to ticks}}, \\
%next eq
M'_I&=\underbrace{rM_I\left(1-\frac{M_I+M_S}{\alpha (H+H_I+F)}\right)}_{\text{logistic growth of ticks}}+\underbrace{\beta_2 M_S\frac{H_I}{H+H_I+F}}_{\substack{\text{virus-free ticks to}\\ \text{virus-carrying ticks}}}-\underbrace{\beta_3 M_I \frac{H+F}{H+H_I+F}}_{\substack{\text{virus-carrying ticks lose }\\\text{virus to uninfected host}}}
-\underbrace{\delta_4 M_I}_{\substack{\text{death due}\\ \text{ to virus}}}, \\
%next eq
M'_S&=\underbrace{rM_S\left(1-\frac{M_I+M_S}{\alpha (H+H_I+F)}\right)}_{\text{logistic growth of ticks}}-\underbrace{\beta_2 M_S \frac{H_I}{H+H_I+F}}_{\substack{\text{virus-free ticks to}\\ \text{ virus-carrying ticks}}}+\underbrace{\beta_3 M_I \frac{H+F}{H+H_I+F}}_{\substack{\text{virus-carrying ticks lose}\\\text{virus to uninfected host}}}
-\underbrace{\delta_5 M_S}_{\substack{\text{death due}\\ \text{to virus}}}.
\end{aligned}\hspace*{-1cm}
\raisetag{110pt}
\end{gather}
}

\bigskip

{\footnotesize
\begin{gather}\label{demomodel}
\begin{aligned}
H'&=\begin{multlined}[t]\underbrace{\mu \frac{(H+F)^i}{K^i+(H+F)^i}h(M_I)}_{\text{new healthy ticks}}-\underbrace{\beta_1 M_I \frac{H}{H+H_I+F}}_{\text{infected ticks}}-\underbrace{(d_1+\delta_1) H}_{\text{death}} -\underbrace{\gamma_1 (M_I+M_S) H}_{\text{death due to ticks}}
 \\{}-\underbrace{H\left(\sigma_1-\sigma_2 \left(\frac{F}{H+F}\right)\right)}_{\text{transition term}},\end{multlined}\\
 %next eq
F'&=\underbrace{H\left(\sigma_1-\sigma_2 \left(\frac{F}{H+F}\right)\right)}_{\text{transition term}}-\underbrace{\beta_1 M_I \frac{F}{H+H_I+F}}_{\text{infected ticks}}-\underbrace{(p+d_2+\delta_2) F}_{\text{death}} -\underbrace{\gamma_2 (M_I+M_S) F}_{\text{death due to ticks}}, \\
%next eq
H'_I&=\underbrace{\beta_1 M_I \frac{H+F}{H+H_I+F}}_{\text{infected ticks}}-\underbrace{(d_3+\delta_3) H_I}_{\text{death}}-\underbrace{\gamma_3 (M_I+M_S)H_I}_{\text{death due to ticks}}, \\
%next eq
M'_I&=\underbrace{rM_I\left(1-\frac{M_I+M_S}{\alpha (H+H_I+F)}\right)}_{\text{logistic growth of ticks}}+\underbrace{\beta_2 M_S\frac{H_I}{H+H_I+F}}_{\substack{\text{virus-free ticks to}\\ \text{virus-carrying ticks}}}-\underbrace{\beta_3 M_I \frac{H+F}{H+H_I+F}}_{\substack{\text{virus-carrying ticks lose }\\\text{virus to uninfected host}}}
-\underbrace{\delta_4 M_I}_{\substack{\text{death due}\\ \text{ to virus}}}, \\
%next eq
M'_S&=\underbrace{rM_S\left(1-\frac{M_I+M_S}{\alpha (H+H_I+F)}\right)}_{\text{logistic growth of ticks}}-\underbrace{\beta_2 M_S \frac{H_I}{H+H_I+F}}_{\substack{\text{virus-free ticks to}\\ \text{ virus-carrying ticks}}}+\underbrace{\beta_3 M_I \frac{H+F}{H+H_I+F}}_{\substack{\text{virus-carrying ticks lose}\\\text{virus to uninfected host}}}
-\underbrace{\delta_5 M_S}_{\substack{\text{death due}\\ \text{to virus}}}.
\end{aligned}
\raisetag{100pt}
\end{gather}
}
\end{document}

A: The basic approach taken in this answer is very similar to the one in David Carlisle's answer, i.e., it gets rid of the \nonumber directive and replaces the array environment with a split environment.
The answer given here differs from David's in that it (a) doesn't use \footnotesize, uses three additional line breaks, and uses (typographic) struts to place the second arguments of the \underbrace directives on the same height, thereby (hopefully) making it much more likely that the readers of your piece will feel tempted to actually read all that extra explanatory material.

\documentclass{article}
\usepackage{mathtools,mleftright}
\mleftright
% define 3 typographic struts:
\newcommand\strutA{\vphantom{\frac{(H)^i}{(F)^i}}}
\newcommand\strutB{\vphantom{\left(\frac{F}{F}\right)}}
\newcommand\strutC{\vphantom{\frac{H}{H_I}}}

\begin{document}
\hrule % just to illustrate width of textblock

\begin{equation}\label{demomodel}
\addtolength\jot{4pt} % for a more open "look"
\begin{split}
H'&={\underbrace{\mu \frac{(H+F)^i}{K^i+(H+F)^i}h(M_I)}_{\text{new healthy ticks}}}
   -{\underbrace{\beta_1 M_I \frac{H}{H+H_I+F}\strutA}_{\text{infected ticks}}}
   -{\underbrace{(d_1+\delta_1) H\strutA}_{\text{death}}} \\[-2pt]
   &\qquad
   -{\underbrace{\gamma_1 (M_I+M_S) H\strutB}_{\text{death due to ticks}}}
   -{\underbrace{H\left(\sigma_1-\sigma_2 \left(\frac{F}{H+F}\right)\right)}_{\text{transition term\vphantom{d}}}} \\
%next eq
F'&={\underbrace{H\left(\sigma_1-\sigma_2 \left(\frac{F}{H+F}\right)\right)}_{\text{transition term}}}
   -{\underbrace{\beta_1 M_I \frac{F}{H+H_I+F}\strutB}_{\text{infected ticks}}}
   -{\underbrace{(p+d_2+\delta_2) F\strutB}_{\text{death}}} \\[-2pt]
   &\qquad
   -{\underbrace{\gamma_2 (M_I+M_S) F}_{\text{death due to ticks}}} \\
%next eq
H'_I &={\underbrace{\beta_1 M_I \frac{H+F}{H+H_I+F}}_{\text{infected ticks}}}
   -{\underbrace{(d_3+\delta_3) H_I\strutC}_{\text{death}}}
   -{\underbrace{\gamma_3 (M_I+M_S)H_I\strutC}_{\text{death due to ticks}}} \\
%next eq
M'_I &={\underbrace{rM_I\left(1-\frac{M_I+M_S}{\alpha (H+H_I+F)}\right)}_{\text{logistic growth of ticks}}}
   +{\underbrace{\beta_2 M_S\frac{H_I}{H+H_I+F}\strutB}_{\substack{\text{virus-free ticks to\vphantom{g}}\\ \text{virus-carrying ticks}}}}\\[-2pt]
   &\qquad
   -{\underbrace{\beta_3 M_I \frac{H+F}{H+H_I+F}}_{\substack{\text{virus-carrying ticks lose}\\ \text{virus to uninfected host}}}}
   -{\underbrace{\delta_4 M_I\strutC}_{\substack{\text{death due\vphantom{g}}\\ \text{to virus\vphantom{f}}}}} \\
%next eq
M'_S &={\underbrace{rM_S\left(1-\frac{M_I+M_S}{\alpha(H+H_I+F)}\right)}_{\text{logistic growth of ticks}}}
   -{\underbrace{\beta_2 M_S \frac{H_I}{H+H_I+F}\strutB}_{\substack{\text{virus-free ticks to\vphantom{g}}\\ \text{ virus-carrying ticks}}}}\\[-2pt]
   &\qquad
   +{\underbrace{\beta_3 M_I \frac{H+F}{H+H_I+F}}_{\substack{\text{virus-carrying ticks lose}\\ \text{virus to uninfected host}}}} \,
   -{\underbrace{\delta_5 M_S\strutC}_{\substack{\text{death due\vphantom{g}}\\ \text{to virus}}}}
\end{split}
\end{equation}

\end{document}

A: The lines are too long even with \footnotesize.
Here's a way to split the longer ones with multlined; between equations I added some vertical space to better separate them. You can choose between \small or \footnotesize; or even neither.
Note that using \footnotesize or \small before the display will produce bad vertical spacing in the surrounding material, so I opted to use the size changing commands inside the display with the \mbox trick.
I also introduced a \ubracetext command to ease input. The second argument is split at \\ and each item is wrapped by \text automatically.
\documentclass{article}
\usepackage{amsmath,mathtools}

\newcommand{\ubracetext}[2]{{\underbrace{#1}_{\ubracetextprocess{#2}}}}

\ExplSyntaxOn
\NewDocumentCommand{\ubracetextprocess}{m}
 {
  \seq_set_split:Nnn \l_tmpa_seq { \\ } { #1 }
  \seq_set_map:NNn \l_tmpb_seq \l_tmpa_seq { \text{\vphantom{Ay}##1} }
  \substack{ \seq_use:Nn \l_tmpb_seq { \\ } }
 }
\ExplSyntaxOff

\begin{document}

\begin{equation}\label{demomodel}
\mbox{%
  %\footnotesize
  \small
  $\begin{aligned}
H'
&= \begin{multlined}[t]
   \ubracetext{\mu \frac{(H+F)^i}{K^i+(H+F)^i}h(M_I)}{new healthy ticks}
  -\ubracetext{\beta_1 M_I \frac{H}{H+H_I+F}}{infected ticks}
  -\ubracetext{(d_1+\delta_1) H}{death}
  \\
  -\ubracetext{\gamma_1 (M_I+M_S) H}{death due to ticks}
  -\ubracetext{H\left(\sigma_1-\sigma_2 \left(\frac{F}{H+F}\right)\right)}{transition term},
  \end{multlined}
\\[2ex]
F'
&= \begin{multlined}[t]
   \ubracetext{H\left(\sigma_1-\sigma_2 \left(\frac{F}{H+F}\right)\right)}{transition term}
  -\ubracetext{\beta_1 M_I \frac{F}{H+H_I+F}}{infected ticks}
  \\
  -\ubracetext{(p+d_2+\delta_2) F}{death}
  -\ubracetext{\gamma_2 (M_I+M_S) F}{death due to ticks},
  \end{multlined}
\\[2ex]
H'_I
&= \ubracetext{\beta_1 M_I \frac{H+F}{H+H_I+F}}{infected ticks}
  -\ubracetext{(d_3+\delta_3) H_I}{death}
  -\ubracetext{\gamma_3 (M_I+M_S)H_I}{death due to ticks},
\\[2ex]
M'_I
&= \begin{multlined}[t]
   \ubracetext{rM_I\left(1-\frac{M_I+M_S}{\alpha (H+H_I+F)}\right)}{logistic growth of ticks}
  +\ubracetext{\beta_2 M_S\frac{H_I}{H+H_I+F}}{virus-free ticks to \\ virus-carrying ticks}
  \\
  -\ubracetext{\beta_3 M_I \frac{H+F}{H+H_I+F}}{virus-carrying ticks lose \\ virus to uninfected host}
  -\ubracetext{\delta_4 M_I}{death due \\ to virus},
  \end{multlined}
\\[2ex]
M'_S
&= \begin{multlined}[t]
   \ubracetext{rM_S\left(1-\frac{M_I+M_S}{\alpha (H+H_I+F)}\right)}{logistic growth of ticks}
  -\ubracetext{\beta_2 M_S \frac{H_I}{H+H_I+F}}{virus-free ticks to \\ virus-carrying ticks}
  \\
  +\ubracetext{\beta_3 M_I \frac{H+F}{H+H_I+F}}{virus-carrying ticks lose \\ virus to uninfected host}
  -\ubracetext{\delta_5 M_S}{death due \\ to virus}.
  \end{multlined}
\end{aligned}$}% end of the \mbox
\end{equation}

\end{document}


text:
Q: Using SevenZipSharp to compress in multi volumes? I want to use SevenZipsharp to compress a file in volumes, for example to compress a file of 100 mb into 10 files of 10 mb each. We can do the same using 7zip.exe -volume parameter so...
For example, when I compress in multi volumes using 7Zip I get these structure of files:
File.7z.001
File.7z.002
File.7z.003
etc...

The files are not independient, Are not a amount of 7zip files with the same size, is one compressed file in various volumes, I mean to extract the entire content we need the first file "File.7z.001"
I want to make the same thing using SevenZipSharp (if possible).
I've made this snippet in vb.net (but no matter if the answer are in C# code), I need to implement the multi-volume option, I need help:
   Imports SevenZip

   Dim dll As String = "7z.dll"

   Private Function SevenZipSharp_Compress(ByVal Input_DirOrFile As String, _
                                      Optional ByVal OutputFileName As String = Nothing, _
                                      Optional ByVal Format As OutArchiveFormat = OutArchiveFormat.SevenZip, _
                                      Optional ByVal CompressionMode As CompressionMode = CompressionMode.Create, _
                                      Optional ByVal CompressionMethod As CompressionMethod = CompressionMethod.Lzma, _
                                      Optional ByVal CompressionLevel As CompressionLevel = CompressionLevel.Normal, _
                                      Optional ByVal Password As String = Nothing) As Boolean
       Try
           ' Set library path
           SevenZipExtractor.SetLibraryPath(dll)

       ' Create compressor and specify the file or folder to compress
       Dim Compressor As SevenZipCompressor = New SevenZipCompressor()

       ' Set compression parameters
       Compressor.CompressionLevel = CompressionLevel ' Archiving compression level.
       Compressor.CompressionMethod = CompressionMethod ' Append files to compressed file or overwrite the compressed file.
       Compressor.ArchiveFormat = Format ' Compression file format
       Compressor.CompressionMode = CompressionMode ' Compression mode
       Compressor.DirectoryStructure = True ' Preserve the directory structure.
       Compressor.IncludeEmptyDirectories = True ' Include empty directories to archives.
       Compressor.ScanOnlyWritable = False ' Compress files only open for writing.
       Compressor.EncryptHeaders = False ' Encrypt 7-Zip archive headers
       Compressor.TempFolderPath = System.IO.Path.GetTempPath() ' Temporary folder path
       Compressor.FastCompression = False ' Compress as fast as possible, without calling events.
       Compressor.PreserveDirectoryRoot = True ' Preserve the directory root for CompressDirectory.
       Compressor.ZipEncryptionMethod = ZipEncryptionMethod.ZipCrypto ' Encryption method for zip archives.
       Compressor.DefaultItemName = "File.7z" ' Item name used when an item to be compressed has no name, for example, when you compress a MemoryStream instance

       ' Get File extension
       Dim CompressedFileExtension As String = Nothing
       Select Case Compressor.ArchiveFormat
           Case OutArchiveFormat.SevenZip : CompressedFileExtension = ".7z"
           Case OutArchiveFormat.BZip2 : CompressedFileExtension = ".bz"
           Case OutArchiveFormat.GZip : CompressedFileExtension = ".gzip"
           Case OutArchiveFormat.Tar : CompressedFileExtension = ".tar"
           Case OutArchiveFormat.XZ : CompressedFileExtension = ".xz"
           Case OutArchiveFormat.Zip : CompressedFileExtension = ".zip"
       End Select

       ' Add Progress Handler
       'AddHandler Compressor.Compressing, AddressOf SevenZipSharp_Compress_Progress

       ' Removes the end slash ("\") if given for a directory
       If Input_DirOrFile.EndsWith("\") Then Input_DirOrFile = Input_DirOrFile.Substring(0, Input_DirOrFile.Length - 1)

       ' Generate the OutputFileName if any is given.
       If OutputFileName Is Nothing Then _
           OutputFileName = (My.Computer.FileSystem.GetFileInfo(Input_DirOrFile).DirectoryName & "\" & (Input_DirOrFile.Split("\").Last) & CompressedFileExtension).Replace("\\", "\")

       ' Check if given argument is Dir or File ...then start the compression
       If IO.Directory.Exists(Input_DirOrFile) Then ' Is a Dir
           If Not Password Is Nothing Then
               Compressor.CompressDirectory(Input_DirOrFile, OutputFileName, True, Password)
           Else
               Compressor.CompressDirectory(Input_DirOrFile, OutputFileName, True)
           End If
       ElseIf IO.File.Exists(Input_DirOrFile) Then ' Is a File
           If Not Password Is Nothing Then
               Compressor.CompressFilesEncrypted(OutputFileName, Password, Input_DirOrFile)
           Else
               Compressor.CompressFiles(OutputFileName, Input_DirOrFile)
           End If
       End If

   Catch ex As Exception
       'Return False ' File not compressed
       Throw New Exception(ex.Message)
   End Try

   Return True ' File compressed

   End Function

Usage of the snippet:
   SevenZipSharp_Compress("C:\File or folder", _
                           "Optional: Output dir", _
                           OutArchiveFormat.SevenZip, _
                           CompressionMode.Create, _
                           CompressionMethod.Lzma, _
                           CompressionLevel.Ultra, _
                           "Optional: Password")

A: On your Compressor object, set VolumeSize to the desired size of the output file(s) in bytes.  Using the sample code below, with the source directory full of about 72MB of mp3 files, the compressor created 8 output files named zipped.7z.001, zipped.7z.002, etc.
Looking at the current source for the SevenZipExtractor class, it looks like the multi-volume compression is only available if you are using OutArchiveFormat.SevenZip as your ArchiveFormat.
string dll = @"C:\Users\WarrenG\Desktop\7z.dll";
string source = @"C:\Users\WarrenG\Desktop\source";
string output = @"C:\Users\WarrenG\Desktop\output\zipped.7z";

SevenZipExtractor.SetLibraryPath(dll);
SevenZipCompressor compressor = new SevenZipCompressor();
compressor.ArchiveFormat = OutArchiveFormat.SevenZip;
compressor.CompressionMode = CompressionMode.Create;
compressor.TempFolderPath = System.IO.Path.GetTempPath();
compressor.VolumeSize = 10000000;   // output file size in bytes
compressor.CompressDirectory(source, output);


text:
Q: jQuery find() returning undefined I have a pretty typical form with some inputs and a submit button, however when I try to use jQuery's find() method, I get some annyingly inconsistent results. The are as follows:
$("#frmContact").find(":submit") -> undefined is not a function
$("#frmContact").find(".btn") -> works
$("#frmContact").find(".btn.secondary") -> undefined is not a function
$("#frmContact").find("input[type=submit]") -> works
$("#frmContact input:submit") -> undefined is not a function
$("input[type=submit]", "#frmContact") -> undefined is not a function
$("form").find("input") -> works
$("form").find("input[type=submit]") -> undefined is not a function

What's going on here and how do I fix this?
I'm using jQuery 1.11 after upgrading from 1.9 hoping that it will fix the issue. There's also Angular on the page and I'm calling this code from the console after everything is loaded.
My form, just in case you need it is as follows [EDIT] updated to show actual HTML output with Angular classes and directives:
<form ng-submit="saveContact($event, '/applicants/update_contact?id=1593')" class="ng-pristine ng-valid" _lpchecked="1" id="frmContact">

Applicant Contact Information

   <field id="email" type="text" model="applicant.email" label="Email address" class="ng-isolate-scope">

        Email address
        <input type="text" ng-model="model" class="ng-pristine ng-valid">

   </field>

     <input type="submit" value="Save" class="btn secondary">

</form>

My JavaScript libraries are loaded in this order:

*

*jQuery 11

*jQuery UI

*Angular

*My app.js

Scripts are loaded at the bottom of the page.

A: AngularJS comes with JQLite, a lightweight smaller verison of jQuery, which is the one you are using here and that gives you unexpected results.
In order for Angular to works with the full jQuery, you need to make sure that you load jQuery before Angular. So watch your


text:
Q: How to interpret query process GB in Bigquery? I am using a free trial of Google bigquery. This is the query that I am using.
select * from `test`.events where subject_id = 124 and id = 256064 and time >= '2166-01-15T14:00:00' and time <='2166-01-15T14:15:00' and id_1 in (3655,223762,223761,678,211,220045,8368,8441,225310,8555,8440)

This query is expected to return at most 300 records and not more than that.
However I see a message like this as below

But the table on which this query operates is really huge. Does this indicate the table size? However, I ran this query multiple times a day
Due to this, it resulted in error below

Quota exceeded: Your project exceeded quota for free query bytes scanned. For more information, see https://cloud.google.com/bigquery/troubleshooting-errors

How long do I have to wait for this error to go-away? Is the daily limit 1TB? If yes, then I didn't not use close to 400 GB.
How to view my daily usage?
If I can edit quota, can you let me know which option should I be editing?
Can you help me with the above questions?

A: According to the official documentation
"BigQuery charges for queries by using one metric: the number of bytes processed (also referred to as bytes read)", regardless of how large the output size is. What this means is that if you do a count(*) on a 1TB table, you will supposedly be charged $5, even though the final output is very minimal.
Note that due to storage optimizations that BigQuery is doing internally, the bytes processed might not equal to the actual raw table size when you created it.
For the error you're seeing, browse the Google Console to "IAM & admin" then "Quotas", where you can then search for quotas specific to the BigQuery service.
Hope this helps!
Flavien


text:
Q: Замена значений в SQL Нужно вставить/заменить в колонку часть значения из другой колонки. Например, есть значение одной колонки "Duplicata B02341543". В другую колонку нужно вставить только "B02341543". Для каждой строки слово "Duplicata" сохраняется, а, значение "B02341543" меняется.
A: update table set field2=substring(field1,10,len(field1))

A: UPDATE <YourTable> SET <updatedField> = SomeOperation(<someField>)

A: UPDATE table_name SET filed2 = SUBSTR(filed1,11);

11 - это длина слова "Duplicata" и пробел.


text:
Q: Many to one relation, select only rows which ancestor met all criteria First I will show You architecture of tables.
 Table "public.questionare"
      Column        |          Type         |
--------------------+-----------------------+
 id                 | integer               |

Table "public.questionareacceptance"
         Column          |          Type         |
-------------------------+-----------------------+
 id                      | integer               |
 questionare_id          | integer               |
 accept_id               | integer               |
 impact_id               | integer               |

Table questionareacceptance contains:
id  | questionare_id | accept_id|       impact_id  |
----+----------------+----------+------------------+
1   |1               |1         |                  |
2   |1               |1         | 1                |
3   |1               |1         | 1                |
4   |2               |          | 1                |
5   |3               |1         | 1                |
6   |4               |1         | 1                |
7   |4               |1         | 1                |

What I am trying to get is a list of questionare ID where in each questionareacceptance fields accept_id and impact_id are not NULL
My query looks like:
SELECT q.id AS quest,
    qa.id AS accepted
FROM questionare q,
    questionareacceptance qa
WHERE q.id = qa.questionare_id
    AND qa.accept_id IS NOT NULL
    AND qa.impact_id IS NOT NULL;

But the result is as fallows:
      quest         |          accepted     |
--------------------+-----------------------+
 1                  |1                      |
 1                  |2                      |
 1                  |3                      |
 2                  |4                      |
 3                  |5                      |
 4                  |6                      |
 4                  |7                      |

But the result that should be returned are only 3 and 4 others have impact_id or accept_id null.
Can anyone point me where I am doing the mistake?

A: your query could be written with not exists:
select
    q.id as quest, qa.id as accepted
from questionare as q
    inner join questionareacceptance as qa on qa.questionare_id = q.id
where
    not exists (
        select *
        from questionareacceptance as tqa
        where
           tqa.questionare_id = q.id and
           (tqa.accept_id is null or tqa.impact_id is null)
    )

but I think faster one would using window functions:
with cte as (
    select
        q.id as quest, qa.id as accepted,
        sum(case when qa.accept_id is not null and qa.impact_id is not null then 1 else 0 end) over(partition by q.id) as cnt1,
        count(*) over(partition by q.id) as cnt2
    from questionare as q
        inner join questionareacceptance as qa on qa.questionare_id = q.id
)
select quest, accepted
from cte
where cnt1 = cnt2

actually looks like you don't need join at all:
with cte as (
    select
        qa.questionare_id as quest, qa.id as accepted,
        sum(case when qa.accept_id is not null and qa.impact_id is not null then 1 else 0 end) over(partition by qa.questionare_id) as cnt1,
        count(*) over(partition by qa.questionare_id) as cnt2
    from questionareacceptance as qa
)
select quest, accepted
from cte
where cnt1 = cnt2;

sql fiddle demo


text:
Q: Is there a formula in excel or VBA to count groups of values? For instance if I had a column with the an "X" in groups of 1, 2, 3 or 4 IF column B, 8 rows had xx xxx xx xxxx xx xxxx xx xxx. I need to find how many groups of two X, three x and four x. The result of the above would be xx = 4, xxx = 2 and 4 = 2. I've tried VBA but the count is never correct.
Here is an image of the H column with the word "TRUE". I am trying to count how many time they are consecutive twice, three time or four up to six consecutive "True"

A: If I understand you correctly, maybe something like this ?
Sub test()
Dim rg As Range
Dim ocr1, ocr2, ocr3, ocr4, ocr5, ocr6, ocr7

Set rg = Range("H1")
If rg = "" Then Set rg = rg.End(xlDown)

    Do
        If rg.Offset(1, 0) <> "" Then
            Select Case Range(rg, rg.End(xlDown)).Rows.Count
                Case 2: ocr2 = ocr2 + 1
                Case 3: ocr3 = ocr3 + 1
                Case 4: ocr4 = ocr4 + 1
                Case 5: ocr5 = ocr5 + 1
                Case 6: ocr6 = ocr6 + 1
                Case 7: ocr7 = ocr7 + 1
            End Select
            Set rg = rg.End(xlDown).End(xlDown)
        Else
            ocr1 = ocr1 + 1
            Set rg = rg.End(xlDown)
        End If
    Loop Until rg.Row = Rows.Count

Debug.Print "no consecutive occurence = " & ocr1
Debug.Print "two consecutive occurence = " & ocr2
Debug.Print "three consecutive occurence = " & ocr3
Debug.Print "four consecutive occurence = " & ocr4
Debug.Print "five consecutive occurence = " & ocr5
Debug.Print "six consecutive occurence = " & ocr6
Debug.Print "seven consecutive occurence = " & ocr7

End Sub

The goal is to get how many times it occur for each consecutive rows with a value.
the rg variable is the cell to start.
If the rg is empty then it do end(xldown) and set this cell as the rg.
Then it do the loop
First it check if the cell below the rg is empty then it means there is no consecutive occurence, so it add 1 to the ocr1 variable then set the rg to the next rg with value
If the cell below the rg is not empty, then it use a case on how many rows is the range with consecutive occurence. Each is assign to each own variable.
If there are two consecutive rows with value, then it add 1 to the ocr2.
If there are three consecutive rows with value, then it add 1 to the ocr3.
and so on.
Then it set the rg to the next rg with value
Since I don't how many consecutive rows with value at max, I just made it to 7. If you know there is a limit (means, you know that the consecutive rows with value won't exceed from 4) then just delete the case 5 to case 7.
Run the sub where the sheet as seen in your picture is active
Again, that if I understand you correctly.


text:
Q: Diagrams and xy-pic package I want to reproduce the shape of the following diagram :

And the closest thing I could manage with the xy package was :
$$
\xymatrix{
     &B \ar[r]  & H  \ar[r] & B   \ar[rd]  \\
    E'_{n+1} \ar[ru] \ar[r]   &  & E'_{n}    \ar[r] &   E_n  \ar[r]  &  E_{n+1} }
$$

which gives

Is it possible to do so with this package?

A: Make a seven-column matrix:
\documentclass{article}
\usepackage{amsmath}

\usepackage[all,cmtip]{xy}

\begin{document}

\[
\xymatrix@C-1pc{
  & B' \ar[rr]^{t_i} && H \ar[rr]^i && B \ar[dr]^{\tilde{v}} \\
  E'_{n+1} \ar[ur]^{t_{\tilde{w}}} \ar[rr]_{t_{j_n}} &&
  E'_n \ar[rr]_{\bar{u}} && E_n \ar[rr]_{j_n} && E_{n+1}
}
\]

\end{document}

The instruction @C-1pc reduces the space between columns.

With the missing arrows:
\documentclass{article}
\usepackage{amsmath}

\usepackage[all,cmtip]{xy}

\begin{document}

\[
\xymatrix@C-1pc{
  & B' \ar[rr]^{t_i} && H \ar[rr]^i \ar[dr]^v && B \ar[dr]^{\tilde{v}} \\
  E'_{n+1} \ar[ur]^{t_{\tilde{w}}} \ar[rr]_{t_{j_n}} &&
  E'_n \ar[rr]_{\bar{u}} \ar[ur]^{t_w} && E_n \ar[rr]_{j_n} && E_{n+1}
}
\]

\end{document}

With tikz-cd:
\documentclass{article}
\usepackage{amsmath}

\usepackage{tikz-cd}

\begin{document}

\[
\begin{tikzcd}[column sep=small]
  & B' \arrow[rr,"t_i"] && H \arrow[rr,"i"] \arrow[dr,"v"] &&
    B \arrow[dr,"\tilde{v}"] \\
  E'_{n+1} \arrow[ur,"t_{\tilde{w}}"] \arrow[rr,"t_{j_n}"'] &&
  E'_n \arrow[rr,"\bar{u}"'] \arrow[ur,"t_w"] && E_n \arrow[rr,"j_n"'] &&
    E_{n+1}
\end{tikzcd}
\]

\end{document}

Labels are by default typeset on the left of the arrow (think to rivers), but with "<label>"' (note the apostrophe) the label goes on the other side. Alternatively, precede the label with the keyword swap.


text:
Q: How to columnate a list in python? I have a pandas Series, sufficiently small so I can read all items (about 80), but too big for the size of the screen.
Is there some python command ou ipython (notebook) magic command or pandas function to columnate that list or Series so I can read it entirely without scrolling down and up?
I'm basically looking for the equivalent of the column command in bash.
For example, I have a Series like this:
A      76
B      56
C      42
D      31
E      31
F      25
G      24

And let's say that my screen is so small that I need to scroll down to see after the B row. What I'd like is something like this:
A    76        C    42        E    31        G    24
B    56        D    31        F    25

A: The following non-numpy/pandas solution might give you some inspiration:
import itertools

rows =  [("A", 76),  ("B", 56), ("C", 42), ("D", 31), ("E", 31), ("F", 25), ("G", 24)]

def print_multi_cols(lrows, split_at=5, space_each=4):
    for row in itertools.izip(*itertools.izip_longest(*[iter(lrows)]*split_at, fillvalue=(" ", " "))):
        for col in row:
            print " ".join(["%-*s" % (space_each, item) for item in col]),
        print

print_multi_cols(rows, 2)
print_multi_cols(rows, 3)

This gives the following output:
A     76      C     42      E     31      G     24
B     56      D     31      F     25

A     76      D     31      G     24
B     56      E     31
C     42      F     25

You would need to convert your series before this could be used. Tested using Python 2.7.
Or for a bit more control over the justification, it could be modified as follows:
import itertools

rows =  [("A", 9),  ("B", 56), ("C", 42), ("D", 31), ("E", 31), ("F", 25), ("G", 999)]

def print_multi_cols(lrows, split_at=5, space_each=4, left_justify=None):
    if not left_justify:
        left_justify = [True] * len(lrows[0])

    for row in itertools.izip(*itertools.izip_longest(*[iter(lrows)]*split_at, fillvalue=(" ", " "))):
        for col in row:
            print " ".join([("%-*s " if left else "%*s ") % (space_each, item) for item, left in itertools.izip(col, left_justify)]),
        print
    print

print_multi_cols(rows, split_at=5, space_each=3, left_justify=[True, False])

Giving:
A      9  F     25
B     56  G    999
C     42
D     31
E     31

A: Using the idea of a show function (with some loops, but since data that can be shown that way is small, it should be fine).
def show(series, cols=6):
    rows = int(np.ceil(len(series)/float(cols)))
    indices = series.index

    ind_loop = 0
    for row in range(rows):
        ind = indices[ind_loop:ind_loop+cols]
        dat = series[ind]
        comb = zip(ind, dat)
        print_str = ""
        for num in range(len(dat)):
            print_str += "{{{0}: <10}} ".format(num)

        print(print_str.format(*comb))
        ind_loop += cols

ser = pd.Series(range(20))
show(ser, cols=6)

(0, 0)     (1, 1)     (2, 2)     (3, 3)     (4, 4)     (5, 5)
(6, 6)     (7, 7)     (8, 8)     (9, 9)     (10, 10)   (11, 11)
(12, 12)   (13, 13)   (14, 14)   (15, 15)   (16, 16)   (17, 17)
(18, 18)   (19, 19)

You could adjust the print to show something like index : value if you like.


text:
Q: Backtracking in a grid Let's say there's a 2D grid of 1s and 0s, for example -
0 1 0 0
0 0 1 0
0 0 0 1
1 0 0 0

The grid is "collapsed" to form a smaller grid of 1 fewer row and 1 fewer column, so the above example would be "collapsed" to form a grid of 3 rows and 3 columns.
The new values are determined by the following rule -
new_grid[i][j] is dependent on
  i) old_grid[i][j],
 ii) old_grid[i][j+1],
iii) old_grid[i+1][j]
 iv) old_grid[i+1][j+1]

If exactly one of the above values are 1, then new_grid[i][j] will be 1, else 0.

So for the example grid, out of [0][0], [0][1], [1][0] and [1][1], only [0][1] is 1, so [0][0] in the new grid will be 1. Similarly, out of [0][1], [0][2], [1][1] and [1][2], both [0][1] and [1][2] are 1, so [0][1] in new_grid will be 0.
The input is given in the form of new_grid values. I have to find out the number of possible configurations of old_grid, such that new_grid is possible through the collapsing rules provided.

My approach
The backtracking solution that I have currently thought of goes like this -

*

*Identify imaginary 2X2 boxes for each 1-valued cell in the old grid which would correspond to the appropriate cell in the new grid.

*All of these boxes will contain exactly one cell with value 1, so put 1 in a random cell in each box.

*Recursively check if putting 1s in the random cells ensures that each box still retains exactly one cell with value 1.

*If a grid configuration is finally obtained where every box contains exactly one cell with value 1, check if the configuration can be "collapsed" to get the new grid.

*If not, then repeat the process with a different cell with the value 1.
If there are some cells in the old grid which don't come under any "box", then they are what I have termed as "doesn't-matter" cells.

For example -
1 1
0 0

For the above new_grid, the old_grid can be -
1 0 1
0 0 0
0 0 0

or
1 0 1
0 0 0
1 1 1

The last row's cells are "doesn't-matter" cells since they don't come under any 2X2 box and they can all be 1s or 0s to be valid configurations (I am thinking that is the extent to which we can flexibly manipulate them, although I am not sure).
My question is this - This algorithm is quite possibly exponential in growth and it will take a lot of time for a grid of say, 50X10.
Is there any other way to solve this question? Or is there any clever algorithm to not go through every possible configuration in order to count them?

A: Hmm, so I have thought of a 2x3 newGrid like so:
newGrid: 0 1 0
         0 0 0

Which would need to be produced by either one of these 3x4 oldGrids:
Each _ can be 1 or 0
oldGrid 1: _ 0 1 _
           _ 0 0 _
           _ _ _ _

oldGrid 2: _ 1 0 _
           _ 0 0 _
           _ _ _ _

oldGrid 3: _ 0 0 _
           _ 1 0 _
           _ _ _ _

oldGrid 4: _ 0 0 _
           _ 0 1 _
           _ _ _ _

And all the remaining 8 spots can be populated in 2^8 ways.
So the answer would be 4 * 2^8
However, imagine if newGrid had more than one 1:
newGrid: 1 1 0
         0 0 0

Which will have these 8 oldGrids:
oldGrid 1: 1 0 _ _
           0 0 _ _
           _ _ _ _

oldGrid 2: 0 1 _ _
           0 0 _ _
           _ _ _ _

oldGrid 3: 0 0 _ _
           1 0 _ _
           _ _ _ _

oldGrid 4: 0 0 _ _
           0 1 _ _
           _ _ _ _

oldGrid 5: _ 1 0 _
           _ 0 0 _
           _ _ _ _

oldGrid 6: _ 0 1 _
           _ 0 0 _
           _ _ _ _

oldGrid 7: _ 0 0 _
           _ 1 0 _
           _ _ _ _

oldGrid 8: _ 0 0 _
           _ 0 1 _
           _ _ _ _

from oldGrid 1 I would have produced 2^8 combinations. But notice how some of those will be the same solutions produced by oldGrid 6. It's those that look like this:
oldGrid 1.1: 1 0 1 _
             0 0 0 _
             _ _ _ _

And it has 2^6 solutions.
So oldGrid 1 has 2^8 - 2^6 solutions that don't conflict with oldGrid 6.
And oldGrid 6 has 2^6 solutions that don't conflict with oldGrid 1.
And together they have (2^8 - 2^6) + (2^8 - 2^6) + 2^6 solutions.
1 and 6, 1 and 8, 2 and 5, 3 and 6, 3 and 8, 4 and 7 have conflicting solution spaces, each one with 2^6.
Which I think means the number of solutions are 8 * 2^8 - 6 * 2^6.
And that is:
numberOfSolutions = numberOf1s * 4 * 2^(oldGridSize-4) - overlappingSolutionsCount
overlappingSolutionsCount = numberOfOverlappingPairs * 2^(oldGridSize-4-overlapAreaSize)

How to calculate the overlap
function countOverlappingSolutions(newGrid: an MxN matrix) {
    result = 0
    oldGridSize = (M+1) * (N+1)
    for each pair of 1s in the newGrid:
        let manhattanDistance = manhattan distance between the 1s in the pair
        let overlapAreaSize = 0

        if the 1s are in the same row or column
            if manhattanDistance == 1:
                overlapSize = 2
        else if manhattanDistance == 2
            overlapAreaSize = 1

        result += 2^(oldGridSize -4 -overlapAreaSize)

    return result
}

The final algorithm:
let newGrid be a MxN matrix
let numberOf1s = number of 1s in newGrid
let oldGridSize = (M+1) * (N+1)

result = numberOf1s * 4 * 2^(oldGridSize - 4) - countOverlappingSolutions(newGrid)

I couldn't make the effort to write python code but I hope the solution is correct and/or shows the way


text:
Q: SQLite: Selecting multiple counts from one column I am running a query with SQLite and am relatively new to this. Glance of my dataset:
  ColA       ColB
 Atlanta     mild
 Atlanta    moderate
 Miami       high
 Houston    moderate
 Houston    moderate
 Miami       mild
 Atlanta    moderate

I want group the results by Col A and then show 3 more columns (mild, moderate, high) and their counts -- Here is what I'm looking for:
 ColA    mild    moderate    high
Atlanta   1        2          0
Houston   0        2          0
Miami     1        0          1

I know how I can select just one of the columns (say, mild), but not sure how to select the others. Thanks!

A: You can pivot with conditional aggregation:
select
    colA,
    sum(case when ColB = 'mild' then 1 else 0 end) mild,
    sum(case when ColB = 'moderate' then 1 else 0 end) moderate,
    sum(case when ColB = 'high' then 1 else 0 end) high
from mytable
group by colA

Demo on DB Fiddle:

ColA    | mild | moderate | high
:------ | :--- | :------- | :---
Atlanta | 1    | 2        | 0
Houston | 0    | 2        | 0
Miami   | 1    | 0        | 1

A: Sqlite 3.30 added support for FILTER clauses to aggregate functions. When available I think it makes for a cleaner, easier to understand query than the CASE you have to use in older versions (In particular, you can use count() instead of sum() which better conveys what you're actually trying to calculate).
SELECT ColA
     , count(ColB) FILTER (WHERE ColB = 'mild') AS Mild
     , count(ColB) FILTER (WHERE ColB = 'moderate') AS Moderate
     , count(ColB) FILTER (WHERE ColB = 'high') AS High
FROM cities
GROUP BY ColA
ORDER BY ColA;

ColA        Mild        Moderate    High
----------  ----------  ----------  ----------
Atlanta     1           2           0
Houston     0           2           0
Miami       1           0           1


text:
Q: Sybase - how do I return the first value that exists from a condition in SQL? Say I'm trying to return some results where a column in a table matches a condition I set. But I only want to return the first result from a list of possible values in the condition. Is there a quick and easy way to do that? I'm thinking that I can use coalesce somehow, but not sure how I can structure it.
Something like:
select identifier,purpose from table
where identifier = 'letters'
and purpose = coalesce('A','B','C')
group by purpose

So in the table, if A purpose isn't there, then I only want the B purpose to show up. if it isn't there, then I want the C to show up, if none of them are there, then I would ideally like a null or no results to be returned. I'd rather not make several case statements where if A is null then look to B, then if B is null to look to C. Is there a quick way syntactically to do so?
Edit: I also want this to work if I have multiple identifiers I list, such as:
select identifier,purpose from table
where identifier in ('letters1', 'letters2')
and purpose = coalesce('A','B','C')
group by purpose

where I return two results if they exist - one purpose for each identifier, with the purpose in the order of importance for A first, then B, then C, or null if none exist.
Unforunately my reasoning for caolesce doesn't work above, as none of the variables are null so my query will just try to return all purposes of 'A' without the fallback that I intend my query to do. I want to try and avoid using temp tables if possible.

A: Sybase ASE does not have support for the row_number() function (else this would be fairly simple), so one option would be to use a #temp table to simulate (to some extent) row_number() functionality.

Some sample data:
create table mytab
(identifier     varchar(30)
,purpose        varchar(30)
)
go

insert mytab values ('letters1','A')
insert mytab values ('letters1','B')
insert mytab values ('letters1','C')

insert mytab values ('letters2','A')
insert mytab values ('letters2','B')
insert mytab values ('letters2','C')
go

The #temp table is created with an identity column plus a 2nd column to hold the items you wish to prioritize; priority is determined by the order in which the rows are inserted into the #temp table.
create table #priority
(id        smallint    identity
,purpose   varchar(30))
go

insert #priority (purpose)
select 'A'                  -- first  priority
union all
select 'B'                  -- second priority
union all
select 'C'                  -- last   priority
go

select * from #priority order by id
go

 id     purpose
 ------ -------
      1 A
      2 B
      3 C

We'll use a derived table to find the highest priority purpose (ie, minimal id value).  We then join this minimal id back to #priority to generate the final result set:
select  dt.identifier,
        p.purpose

from    (-- join mytab with #priority, keeping only the minimal priority id of the rows that exist:

         select m.identifier,
                min(p.id)       as min_id

         from   mytab m

         join   #priority p
         on     p.purpose = m.purpose

         group by m.identifier) dt

-- join back to #priority to convert min(id) into the actual purpose:

join    #priority p
on      p.id = dt.min_id

order by 1
go

Some test runs with different set of mytab data:
/* contents of mytab:

insert mytab values ('letters1','A')
insert mytab values ('letters1','B')
insert mytab values ('letters1','C')

insert mytab values ('letters2','A')
insert mytab values ('letters2','B')
insert mytab values ('letters2','C')
*/

 identifier purpose
 ---------- -------
 letters1         A
 letters2         A

/* contents of mytab:

--insert mytab values ('letters1','A')
--insert mytab values ('letters1','B')
insert mytab values ('letters1','C')

--insert mytab values ('letters2','A')
insert mytab values ('letters2','B')
insert mytab values ('letters2','C')
*/

 identifier purpose
 ---------- -------
 letters1         C
 letters2         B

Returning NULL if a row does not exist is not going to be easy since generating a NULL requires existence of a row ... somewhere ... with which to associate the NULL.
One idea would be to expand on the #temp table idea by creating another #temp table (eg, #identifiers) with the list of desired identifier values you wish to search on. You could then make use of a left (outer) join from #identifiers to mytab to ensure you always generate a result record for each identifier.


text:
Q: Create Matrix from a DataFrame I have a dataframe with several columns, including Department and ICA. I need to create a matrix where the rows are the departments, and the columns are ICA values (they range from bad-acceptable-good).
So position r,c would be a number that shows how many observations of ICA were recorded for each department.
For example, if Amazonas is row 1 and Acceptable is column 3, position (1,3) would be the number of acceptable observations for Amazonas.
Thanks!

A: You can get values from your DataFrame using integer-based indexing with the DataFrame.iloc method. This seems to do what you need.
For example, if df is your DataFrame, then df.iloc[0, 2] will give you the value at the first row and third column.


text: Q: Can every random variable be written as a Borel-measurable function of a uniformly distributed random variable? I am trying to find a proof for the claim that every random variable can be written as a Borel-measurable function of a uniformly distributed random variable. Can anyone point it out to me? Thanks