text:
Q: Cant use this query in php even though it works inline on my database I am trying to handle if either NULL or a datetime object is passed to my handler while still writing NULL to the database and not just 00000000
I can get it to work if I parse the stop_date first and then depending on what it is, send it through 2 entirely different queries, but I want to be able to do it in one query either way
if(strtolower($stop_date) != 'null'){
            $stop = date("Y-m-d H:i:s", strtotime($stop_date));
            if($stop <= date('Y-m-d H:i:s')){
                die('No stop date was entered for this appointment. Recurring appointments must have a stop date or marked "NULL" if they do not have a stop date');
            }
        }
        else{
            $stop = NULL;
        }
        $db->query("
        UPDATE appt_recurring
        SET hc_id = :hc_id, note = :note, appt_type_id = :appt_type_id, start_date = :start_date, end_date = :end_date,
        stop_date = (
            CASE
                WHEN
                    ".$stop." != NULL
                THEN
                    :stop_date
                ELSE
                    $stop
            END
        ),
        frequency = :frequency, frequency_type = :frequency_type, frequency_data = :frequency_data
        WHERE id = :id
        ");

        $db->bind(':id', $id );
        $db->bind(':hc_id', $hc_id );
        $db->bind(':note', $note );
        $db->bind(':appt_type_id', $appt_type_id );
        $db->bind(':start_date', $start_date->format('Y-m-d H:i:s'));
        $db->bind(':end_date', $end_date->format('Y-m-d H:i:s'));
        if(strtolower($stop_date) != 'null'){
            $db->bind(':stop_date', $stop);
        }
        $db->bind(':frequency', $frequency );
        $db->bind(':frequency_type', $frequency_type );
        $db->bind(':frequency_data', $frequency_data );

This provides nothing but syntax errors and in some cases with some tweaking a parameter error. Please help!

A: A few things jump out. For starters WHEN ".$stop." != NULL should be WHEN                     ".$stop." IS NOT NULL. And as @Jonnix highlighted, evaluating like that on the value being assigned makes no sense. The SQL would read as WHEN != NULL. Just a note for if you are evaluating a null state field in the future.
Really there should be no need for logic like that in the update statement.
You should simply assign a null value to the variable you will bind to the end_date.
Can you not force a null by using:
$db->bind(':end_date', NULL);

If you can't get that working you need to be sure the column allows null values (DESC appt_recurring;).
So, in summary, aim for one if to check this, not one up top and one later.

if(strtolower($stop_date) != 'null'){
  $stop = date("Y-m-d H:i:s", strtotime($stop_date));
  if($stop <= date('Y-m-d H:i:s')){
    die('No stop date was entered for this appointment. Recurring appointments must have a stop date or marked "NULL" if they do not have a stop date');
  }
  $endDate = $stop->format('Y-m-d H:i:s');
} else {
  $endDate = NULL;
}

...

$db->bind(':end_date', $endDate);


text:
Q: Best approach to make sure only one value set to 1 the other values set automatically to 0 in a column SQL I am designing a simple image gallery that the user can set for album primary picture lets say similar to Facebook that user  will be able to select the cover of the album from the pictures.
I believe that to achieve this I will need to add another bool column to Images table to call it IsCoverPicture. Then I will set this value for specific image to true. But later if they would like to change the cover image?
The way I do it is to set all value first to false and then set the new selected value to true.
Here I just wonder whether this is the correct way of doing this or is there any specific store procedure or anything by using Entity Framework that would handle this for me automatically when I set a new true value for the new  cover picture it would take care of the rest for me and go and set the rest false?

A: First solution: Change your album table to contain pictures and the cover. This way only one picture can be set to be the cover of the album.
Another idea is to add a unique constraint on album column and the new boolean column. Your image table will contains at least these two columns: AlbumId and IsCover. Simply add a unique constraint on these two columns:
Unique constraint on multiple columns

A: I suggest you normalise your schema. You need a table Cover with columns PictureId and AlbumId something like this.
CREATE TABLE Cover (
  AlbumId INT,
  PictureId INT,
  PRIMARY KEY (AlbumId,PictureId)
)

With your current schema, to change the cover image you need to update two rows, and a single delete can leave you with no cover image. With a normalised schema update anomalies cannot occur.
If you declare the foreign key constraints then you will also be protected from the delete problem.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Wordpress mysql service error ERROR: Failed to start "mysql": cannot start service: Process exited with status 3 I'm hoping someone can help me, i've been working on a website using wordpress for the past 3 months on my mac, only when i tried to access it this past weekend the mysql service won't run and i keep getting the error
ERROR: Failed to start "mysql": cannot start service: Process exited with status 3

Can anyone help me get my site up and running again?
This is the first tie using Wordpress so i'm not really sure what I'm doing.
Any help would be greatly appreciated
i've managed to run mysql in safe mode and this is the code it gives
Last login: Mon Jul 13 22:23:09 on ttys001
Lukes-iMac:~ lukejackson$/Users/lukejackson/.bitnami/stackman/machines/wordpress/volumes/root/mysql/bin/mysqld_safe ; exit;
/Users/lukejackson/.bitnami/stackman/machines/wordpress/volumes/root/mysql/bin/my_print_defaults: line 12: /Users/lukejackson/.bitnami/stackman/machines/wordpress/volumes/root/mysql/bin/my_print_defaults.bin: cannot execute binary file
/Users/lukejackson/.bitnami/stackman/machines/wordpress/volumes/root/mysql/bin/my_print_defaults: line 12: /Users/lukejackson/.bitnami/stackman/machines/wordpress/volumes/root/mysql/bin/my_print_defaults.bin: Undefined error: 0
/Users/lukejackson/.bitnami/stackman/machines/wordpress/volumes/root/mysql/bin/my_print_defaults: line 12: /Users/lukejackson/.bitnami/stackman/machines/wordpress/volumes/root/mysql/bin/my_print_defaults.bin: cannot execute binary file
/Users/lukejackson/.bitnami/stackman/machines/wordpress/volumes/root/mysql/bin/my_print_defaults: line 12: /Users/lukejackson/.bitnami/stackman/machines/wordpress/volumes/root/mysql/bin/my_print_defaults.bin: Undefined error: 0
/Users/lukejackson/.bitnami/stackman/machines/wordpress/volumes/root/mysql/bin/mysqld_safe: line 674: /opt/bitnami/mysql/data/Lukes-iMac.err: No such file or directory
Logging to '/opt/bitnami/mysql/data/Lukes-iMac.err'.2020-07-13T21:43:10.6NZ mysqld_safe Starting mysqld daemon with databases from /opt/bitnami/mysql/data/Users/lukejackson/.bitnami/stackman/machines/wordpress/volumes/root/mysql/bin/mysqld_safe: line 144: /opt/bitnami/mysql/data/Lukes-iMac.err: No such file or directory
/Users/lukejackson/.bitnami/stackman/machines/wordpress/volumes/root/mysql/bin/mysqld_safe: line 199: /opt/bitnami/mysql/data/Lukes-iMac.err: No such file or directory
/Users/lukejackson/.bitnami/stackman/machines/wordpress/volumes/root/mysql/bin/mysqld_safe: line 937: /opt/bitnami/mysql/data/Lukes-iMac.err: No such file or directory
2020-07-13T21:43:10.6NZ mysqld_safe mysqld from pid file /opt/bitnami/mysql/data/Lukes-iMac.pid ended
/Users/lukejackson/.bitnami/stackman/machines/wordpress/volumes/root/mysql/bin/mysqld_safe: line 144: /opt/bitnami/mysql/data/Lukes-iMac.err: No such file or directory
logout
Saving session...
...copying shared history...
...saving history...truncating history files...
...completed.

[Process completed]

A: Your local database server is failing to start up, and it's being started with enough layers between you and it that any reporting it's doing on why is being hidden.  To attempt to start it while being able to see what it's complaining about, try the methodology here: start MySQL server from command line on Mac OS Lion

A: Bitnami Engineer here.
Thank you for using our solution. Please note that the OS X VM solution is a VM we build and configure with the application. You need to open the Console of the VM when running any command, can you try to open the console and run the start command?
sudo /opt/bitnami/ctlscript.sh start

You can use the ctlscript.sh file to stop the services and get the status as well. If the database can't be started, you can take a look at the database's log file (/opt/bitnami/mysql/data/mysqld.log) to get more information
sudo tail -n 30 /opt/bitnami/mysql/data/mysqld.log


text:
Q: A question on completeness for quantified temporal logics Quantified temporal logics have the Barcan formulas and its converses for both G (it will always be the case that) and H (it has always been the case that), so that both $\forall x G \alpha \rightarrow G \forall x \alpha$/$G \forall x \alpha \rightarrow \forall x G \alpha$ and $\forall x H \alpha \rightarrow H \forall x \alpha$/$H \forall x \alpha \rightarrow \forall x H \alpha$ are theorems.
Are there known completeness results for quantified temporal logics extending or as strong as the one for lattices with axioms $G \alpha \rightarrow F \alpha$/$H \alpha \rightarrow P \alpha$ and $G \alpha \rightarrow GG \alpha$/$H \alpha \rightarrow HH \alpha$ and $FG \alpha \rightarrow GF \alpha$/$PH \alpha \rightarrow HP \alpha$?


text:
Q: Android app closes after running few days (2days) I'm am developing an app that suppose to run forever once the app is installed. I don't get any exceptions or crashes. Only error I'm able to find is as mentioned below
Fatal signal 6 (SIGABRT), code -6 (SI_TKILL) in tid 30752 (llay.myapp), pid 30752 (llay.myapp)
2021-08-21 00:14:47.663 29579-29579/? A/DEBUG: * * * * * * * * * * * * * * * *
2021-08-21 00:14:47.664 29579-29579/? A/DEBUG: Build fingerprint: 'Amlogic/faraday/faraday:9/PPR1.180610.011/20191021:userdebug/test-keys'
2021-08-21 00:14:47.664 29579-29579/? A/DEBUG: Revision: '0'
2021-08-21 00:14:47.664 29579-29579/? A/DEBUG: ABI: 'arm'
2021-08-21 00:14:47.664 29579-29579/? A/DEBUG: pid: 30752, tid: 30752, name: llay.myapp  >>> com.foo.myapp <<<
2021-08-21 00:14:47.664 29579-29579/? A/DEBUG: signal 6 (SIGABRT), code -6 (SI_TKILL), fault addr --------
2021-08-21 00:14:47.664 29579-29579/? A/DEBUG: Abort message: 'java_vm_ext.cc:662] JNI ERROR (app bug): weak global reference table overflow (max=51200)weak global reference table dump:'
2021-08-21 00:14:47.664 29579-29579/? A/DEBUG:     r0  00000000  r1  00007820  r2  00000006  r3  af663918
2021-08-21 00:14:47.664 29579-29579/? A/DEBUG:     r4  00007820  r5  00007820  r6  bbdd51a4  r7  0000010c
2021-08-21 00:14:47.664 29579-29579/? A/DEBUG:     r8  0000000b  r9  bbdd5211  r10 000008b4  r11 bbdd5210
2021-08-21 00:14:47.664 29579-29579/? A/DEBUG:     ip  00000041  sp  bbdd5190  lr  af5f20e5  pc  af5e9e72
2021-08-21 00:14:47.672 29579-29579/? A/DEBUG: backtrace:
2021-08-21 00:14:47.672 29579-29579/? A/DEBUG:     #00 pc 0001ce72  /system/lib/libc.so (abort+62)
2021-08-21 00:14:47.672 29579-29579/? A/DEBUG:     #01 pc 00356e7f  /system/lib/libart.so (art::Runtime::Abort(char const*)+798)
2021-08-21 00:14:47.672 29579-29579/? A/DEBUG:     #02 pc 000071c7  /system/lib/libbase.so (android::base::LogMessage::~LogMessage()+502)
2021-08-21 00:14:47.672 29579-29579/? A/DEBUG:     #03 pc 00236f6b  /system/lib/libart.so (art::JavaVMExt::AddWeakGlobalRef(art::Thread*, art::ObjPtr<art::mirror::Object>)+198)
2021-08-21 00:14:47.672 29579-29579/? A/DEBUG:     #04 pc 002b0d41  /system/lib/libart.so (art::JNI::NewWeakGlobalRef(_JNIEnv*, _jobject*)+432)
2021-08-21 00:14:47.672 29579-29579/? A/DEBUG:     #05 pc 014c1b25  /system/app/webview/webview.apk (offset 0x780000)

A: You have to run a foreground service in android with a permanent notification.
Please do check my blog to get an idea about foreground service - https://medium.com/@kunal31/services-in-android-for-beginners-c3114810f430


text:
Q: Why is $X(T)$ under $\mathbb Q^{M}$ $\sim X(T)-X(0)+\tilde{X}(0)$ under $\mathbb Q^ {N}$ under the following assumptions? Assume we have equivalent probability measures $\mathbb Q^{M}$ and $\mathbb Q^{N}$ and further assume that $$ \tilde{X}(T)-\tilde{X}(0) \text{ under }\mathbb Q^{M} \sim X(T)-X(0) \text{ under }\mathbb Q^{N}\; \; (*),$$
where $\tilde{X}(t):=X(t)\exp(\int_{t}^{T}\gamma(s)ds)$,
Clearly, it holds that $\tilde{X}(T) = X(T)$, and then it is stated:
$$X(T)\text{ under }\mathbb Q^{M}\sim X(T)-X(0)+\tilde{X}(0)\text{ under }\mathbb Q^ {N}$$
but unfortunately, I do not see why this is the case.
Comments/My thoughts: Using the fact that $X(T)=\tilde{X}(T)$ it is clear that $X(T)\sim\tilde{X}(T)\text{ under }\mathbb Q^{N}\text{ and }\mathbb Q^{M}$ and further from $(*)$, we obtain:
we have $X(T)-\tilde{X}(0)\text{ under }\mathbb Q^{M} \sim X(T)-X(0)\text{ under }\mathbb Q^{N}$.
If $\tilde{X}(0)$ were deterministic, i.e. has a trivial distribution under $\mathbb Q^{M}$ and $\mathbb Q^{N}$, then we can simply "add" $\tilde{X}(0)$ to both sides, but in general we cannot do this? Am I right, or what exactly am I missing here?


text:
Q: What's the relationship between Banach space and inner product space I know that Banach space is a special Hilbert space. Inner product space is a special normed space. Hilbert space is a complete inner product space. Banach space is a complete normed space. I'm wondering what is the relationship between Banach space and inner product space.

A: Every inner product induces a norm, so an inner product space is a normed vector space. Banach spaces are complete, normed vector spaces. So, the relation between inner product spaces and Banach spaces is that they're both normed vector spaces.
However, (1) an inner product space might lack the completeness that a Banach space possesses and (2) a Banach space norm need not be induced by an inner product. The norm needs to satisfy the parallelogram law for this to be the case (see https://en.wikipedia.org/wiki/Parallelogram_law#Normed_vector_spaces_satisfying_the_parallelogram_law).

A: A Banach space is a complete metric space, so that it has a distance function $d(x,y)$ and every Cauchy sequence converges to an element of the space.
A Hilbert space is a complete vector space, with an inner product $<x,y>$ or $x \cdot y$, that defines angles:
$$
cos(\theta) = \dfrac{\langle x,y\rangle}{||x|| ||y||}
$$
which defines the norm as
$$
||x|| = \sqrt{\langle x,x\rangle}.
$$
and distance as
$$
||x-y|| = \sqrt{\langle x-y,x-y \rangle}.
$$
So in a Banach space, you can talk about distance and convergence but not direction, while a Hilbert space has all of those. You need a Hilbert space for generalizing things like orthogonality, characterizing solutions to minimum distance problems (by way of the parallelogram equality), projection for statistics like OLS, and often useful results in approximation.
For example, consider the difference between $\mathbb{R}^N$ with the norm
$$
||x|| = \sup_{i} |x_i|
$$
and the Euclidean norm
$$
||x|| = \sqrt{\sum_{i=1}^N x_i^2} = \sqrt{x\cdot x}.
$$
You can think of the first as a Banach space but not a Hilbert space, and the second as a Hilbert space.  Imagine what you lose by analyzing $\mathbb{R}^N$ without angles.


text:
Q: Add a second checkbox in WooCommerce registration form How could I add a second checkbox in the registration form for WooCommerce users?
On the 'my account' page of WooCommerce it gives you the option to log in or register (that's where I need help).
I already have a checkbox established to accept the privacy policy (just below the user, e-mail and password boxes).
This is the hook that I have achieved thanks to this article
add_action( 'woocommerce_register_form', function () {

  woocommerce_form_field( 'politica_privacidad_registro', array(
      'type'          => 'checkbox',
      'class'         => array('form-row rgpd'),
      'label_class'   => array('woocommerce-form__label woocommerce-form__label-for-checkbox checkbox'),
      'input_class'   => array('woocommerce-form__input woocommerce-form__input-checkbox input-checkbox'),
      'required'      => true,
      'label'         => 'He leído y acepto la política de privacidad',
      ));
}, 10);

add_filter( 'woocommerce_registration_errors', function ( $errores, $usuario, $email ) {
    if ( ! (int) isset( $_POST['politica_privacidad_registro'] ) ) {
        $errores->add( 'politica_privacidad_registro_error', 'Tienes que aceptar nuestra política de privacidad' );
    }
return $errores;
}, 10, 3);

But I need another checkbox so that they accept another necessary requirement on the web (age verification).
That mandatory age verification checkbox to register, of course, would be accompanied by a small phrase.
I have tried with some hook in the functions.php, but it happens that if you accept the privacy checkbox you could already register even if you do not accept the second mandatory checkbox.
This is the code that best suited what I needed to this post
// To add the form
function add_age_verification() {
    ?>

    <?php _e( 'age verification', 'woocommerce' ); ?> *
    <input type="checkbox" class="woocommerce-form__input woocommerce-form__input-checkbox" name="age_verification" id="reg_age_verification" value="<?php if ( ! empty( $_POST['age_verification'] ) ) esc_attr_e( $_POST['age_verification'] ); ?>" />

    <?php
}
  // to validate the form
function validate_age_verification( $errors, $username, $email ) {
    if ( isset( $_POST['age_verification'] ) && empty( $_POST['age_verification'] ) ) {
        $errors->add( 'age_verification_error', __( 'Error: First name is required!', 'woocommerce' ) );
    }
    return $errors;
}

 // to save the form into user meta age_verification
function age_verification_save( $customer_id ) {
    if ( isset( $_POST['age_verification'] ) ) {
        update_user_meta( $customer_id, 'age_verification', sanitize_text_field( $_POST['age_verification'] ) );
   }
}

add_action( 'woocommerce_register_form', 'add_age_verification' );
add_filter( 'woocommerce_registration_errors', 'validate_age_verification', 10, 3 );
add_action( 'woocommerce_created_customer', 'age_verification_save' );

Aside from the incompatibility of hooks, also this second checkbox with the tests that I have carried out appears the phrase in a line and the check box below. It must all go together on one line.
How could I do it and have both hooks work without creating incompatibilities?

A: Your code contains some minor mistakes

*

*woocommerce_created_customer missing from the privacy policy

*reg_age_verification & age_verification are used interchangeably

*Regarding the display of the fields, this can be done by adding/modifying CSS selectors: form-row-first, form-row-last & form-row-wide. Furthermore, it is a matter of CSS adjustments, depending on the theme you use

So you get:
// Add fields to register page
function action_woocommerce_register_form() {
    // First checkbox
    woocommerce_form_field( 'politica_privacidad_registro', array(
        'type'          => 'checkbox',
        'class'         => array( 'woocommerce-form-row woocommerce-form-row--wide form-row form-row-wide' ),
        'label_class'   => array( 'woocommerce-form__label woocommerce-form__label-for-checkbox checkbox' ),
        'input_class'   => array( 'woocommerce-form__input woocommerce-form__input-checkbox input-checkbox' ),
        'required'      => true,
        'label'         => __( 'He leído y acepto la política de privacidad', 'woocommerce' ),
    ));

    // Second checkbox
    woocommerce_form_field( 'age_verification', array(
        'type'          => 'checkbox',
        'class'         => array( 'woocommerce-form-row woocommerce-form-row--wide form-row form-row-wide' ),
        'label_class'   => array( 'woocommerce-form__label woocommerce-form__label-for-checkbox checkbox' ),
        'input_class'   => array( 'woocommerce-form__input woocommerce-form__input-checkbox input-checkbox' ),
        'required'      => true,
        'label'         => __( 'Age verification', 'woocommerce'),
    ));
}
add_action( 'woocommerce_register_form', 'action_woocommerce_register_form' );

// Validation
function filter_woocommerce_registration_errors( $errors, $username, $email ) {
    // Privacy NOT isset
    if ( ! (int) isset( $_POST['politica_privacidad_registro'] ) ) {
        $errors->add( 'politica_privacidad_registro_error', __( 'Tienes que aceptar nuestra política de privacidad.', 'woocommerce' ) );
    }

    // Age NOT isset
    if ( ! (int) isset( $_POST['age_verification'] ) ) {
        $errors->add( 'age_verification_error', __( 'Age is required.', 'woocommerce' ) );
    }

    return $errors;
}
add_filter( 'woocommerce_registration_errors', 'filter_woocommerce_registration_errors', 10, 3 );

// Save fields
function action_woocommerce_created_customer( $customer_id, $new_customer_data, $password_generated ) {
    // Privacy isset
    if ( isset( $_POST['politica_privacidad_registro'] ) ) {
        update_user_meta( $customer_id, 'politica_privacidad_registro', sanitize_text_field( $_POST['politica_privacidad_registro'] ) );
    }

    // Age isset
    if ( isset( $_POST['age_verification'] ) ) {
        update_user_meta( $customer_id, 'age_verification', sanitize_text_field( $_POST['age_verification'] ) );
    }
}
add_action( 'woocommerce_created_customer', 'action_woocommerce_created_customer', 10 , 3 );


text:
Q: Jenkins Groovy: how to extract specific number from parameter in method? I am quite new in Groovy and trying to extract find the best way to write a method that will extract the 3rd number in branch name which is passed as a parameter.
Standard gitBranchName looks like this release-1.2.3
Below is my method and I am wondering what to do with newestTagNumber:
#!/usr/bin/env groovy

def call(gitRepoName, gitBranchName) {
withCredentials([
    string(credentialsId: 'jenkinsuser', variable: 'USER'),
    string(credentialsId: 'jenkinssecret', variable: 'SECRET')]) {
    def commitHash = sh(
      script: 'git rev-parse --short HEAD',
      /*script: 'git rev-parse --symbolic-full-name @{-1} && git rev-parse --abbrev-ref @{-1}' */
      returnStdout: true).trim()
    def repoUrl = "bitbucket.org/cos/${gitRepoName}"

    /* newestTagNumber - this is 3rd number taken from gitBranchName */
    def newestTagNumber = <what_to_add_here?>

    /* nextTagNumber - incremented by 1 */
    def nextTagNumber = newestTagNumber + 1

    sh """
      git config user.email "example@example.com"
      git config user.name "jenkins"
      git tag -a release-${nextTagNumber}.t -m 'Create tag release-${nextTagNumber}.t'
    """
    sh('git push --tags https://${JT_USER}:${JT_SECRET}@' + repoUrl)
  }
}

This is how it will probably work using Regex, but is there a prettier way to do it in Groovy?
[\d]*(\d$)

Thank you guys!

A: You can simply split the String by "." and get the last digit.
def parts = gitBranchName.split("\\.")
def newestTagNumber = parts[parts.size()-1]

If you are sure you will always get the branch name in this format with 3 decimal points(release-1.2.3) here is a one-liner.
def newestTagNumber = gitBranchName.split("\\.")[2]

A: @ycr solution is right, but I found even better option if you always want to change the last number (which is my case):
def newestTagNumber = gitBranchName.split("\\.").last()

Thanks!


text:
Q: Authorize scopes after renewing credentials and app access to google account Here is my problem.
I'm developping a web app using google app engine in JAVA.
I've searched the web and saw a lot of different answers to my problem, giving various solutions but none of them worked for me I still get:
{
  "code" : 403,
  "errors" : [ {
    "domain" : "global",
    "message" : "Insufficient Permission",
    "reason" : "insufficientPermissions"
  } ],
  "message" : "Insufficient Permission"
}

I'm trying to send a mail from my account to other email adresses (from me to me as a test).
I've implemented successfully the sheets API but remembered I had to go first through a consent Screen but now I really don't know how to popup this screen again to validate scopes permanently, Let me explain myself.
I have two credentials files.

*

*for retrieving users infos to confirm sign in through Google, here I use an openID connect URL and there I user get the consent screen.

*use Sheets API and Gmail API as "me" to first retrieve datas from my spreadsheets and send mail from my email adress. As told before I've validated the Sheets API but can't get Gmail to work with the same credentials.

I've tested various scopes add another credential file without any success. Please tell me if you need some code.
EDIT
Just deleted my Sheets API credentials also removed my app fto be linked to my account and now I cannot get the consent screen to popup. and I get:
com.google.api.client.auth.oauth2.TokenResponseException: 400 Bad Request
{
  "error" : "invalid_grant",
  "error_description" : "Token has been expired or revoked."
}

I'm using this code to get credentials
private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws IOException {
    // Load client secrets.
    InputStreamReader in = new InputStreamReader(new FileInputStream(new File("WEB-INF/credentials.json")));
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, in);

    // Build flow and trigger user authorization request.
    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
            HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
            .setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH)))
            .setAccessType("offline")
            .build();
    LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build();
    return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
}

but google documentation says:

Authorization information is stored on the file system, so subsequent
  executions will not prompt for authorization.

Where can I delete the stored file system?
Any help is greatly appreciated

A: After messing around hours and hours I've finally came with an unexplainable solution.
I remove my app from this page
then change my code to
return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");

to this
return new AuthorizationCodeInstalledApp(flow, receiver).authorize(null);

to make appear consent screen.
then I after validating my app I get a NullPointerException error so I change back the same line to this
return new AuthorizationCodeInstalledApp(flow, receiver).authorize("myemail@gmail.com");

and if it doesn't work (I guess that's a cache problem)
to this
return new AuthorizationCodeInstalledApp(flow, receiver).authorize("me");

don't ask me why but that did work.
Still any more detailed infos about this behaviour is welcome.


text:
Q: Transistors choice for buck boost converter using LM34936 I've been using TI's Webench online design tool for buck boost design purposes that uses LM34936.
The simplified schematic in LM324936's datasheet looks:

Webench design tool generated 4 different MOS transistors (CSD series):
M1 CSD16321Q5;
M2 CSD18511Q5A;
M3 CSD17303Q5;
M4 CSD17573Q5B;

My question is, could I use one just type of transistors instead of 4 different?
The output I'm trying to get is 12V, so what is the maximum Vds that could occur on MOS' drains?

A: The Voltage rating and  current ratings depends on each FET due to your Vin Max/Min Vgs and Vout.
If you reduce the range on input voltages, it is possible to have more common parts but \$Q_g\$ and \$Q_{gd}\$  increase with Vds and lower RdsOn which depends on these VI in/out ranges as a slower rise time also increases losses.


text:
Q: EF6 Query Criteria using object properties that aren't null I have a viewmodel class coming in from an MVC submission, and I want to get a result set from EF6 based upon values that the user has filled out, but ignore those items in the model that are null:
public class SearchFilterVM
{
    public int? ID { get; set; }
    public bool? Active { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string MiddleInitial { get; set; }
    public DateTime? DateOfBirth { get; set; }
    public string Phone { get; set; }
    public string Email { get; set; }
}

Essentially what I'm looking for is something like this psuedo-code:
var results = context.Members
    .Where(x => x.Active == vm.Active.Value)    // but only if vm prop is not null
    .Where(x => x.FirstName == vm.FirstName)    // but only if vm prop is not null
    .Where(x => x.LastName == vm.LastName)      // but only if vm prop is not null
    .ToList();

(e.g., if the filter model properties are null, ignore them altogether)
Naturally I don't want to use something like the above, as it would query based on the first criteria, then requery based on the second applicable criteria, etc. until completed (I'm working with 500k+ rows).
I can't think of a way to use LINQ query expressions for this either.
What I could do is build a parameterized SQL statement based on the presence of a value and append the criteria and finally pass it through EF6's RawSQLQuery, which would work performance-wise (and give me nice control over the order of indexed fields for better tuning), but I'm wondering if there's a "natural" way to accomplish the same thing via LINQ.

A: My Suggested Method
Remember that EF uses deferred execution and you don't actually execute any query until you materialise it with ToList() or iterating over it for example. That means you can do this:
var results = context.Members;

if(vm.Active.HasValue)
{
    results = results.Where(x => x.Active == vm.Active.Value);
}

if(!string.IsNullOrEmpty vm.FirstName))
{
    results = results.Where(x => x.FirstName == vm.FirstName);
}

//and so on until...

return results.ToList();

The Other Methods
I thought I'd add this extra as a freebie to understand why you may not want to use the techniques mentioned in the other answers. Lets say you did this:
string name = "bob";

var users = context.Users.Where(u => name == null || u.Name == name).ToList();

This looks pretty similar to my version and will give the same results, but the SQL query is quite different. You will end up with something like this:
DECLARE @p__linq__0 NVarChar(1000) = 'bob'
DECLARE @p__linq__1 NVarChar(1000) = 'bob'

SELECT
    [Extent1].[Id] AS [Id],
    [Extent1].[Name] AS [Name],
    /* snip */
    FROM [dbo].[Users] AS [Extent1]
    WHERE @p__linq__0 IS NULL OR [Extent1].[Name] = @p__linq__1

Note that the null check is now done in the database, and that you also sent the parameter in twice. OK, it's probably not going to be noticeably slower, but it's something you probably want to keep in mind for the future.

A: You could just check your VM variables for NULL inside where statements:
var results = context.Members
    .Where(x => vm.Active == null || x.Active == vm.Active.Value)    // but only if it's not null
    .Where(x => vm.FirstName == null || x.FirstName == vm.FirstName)    // but only if it's not null
    .Where(x => vm.LastName == null || x.LastName == vm.LastName)      // but only if it's not null
    .ToList();

In that case, for example, if vm.FirstName would be null, the first statement vm.FirstName == null would be true (and if not null, then it would actually check for first name equality) and so on for other conditions.


text:
Q: Rezising Linux Partition which contains the ubuntu OS in 14.04 LTS I was trying to extend my / partition using ubuntu live cd after installation done before 6 months. For installing a software i needed 9GB more space in my root partition. The size of the root partition was 24gb only. To find a safe solution i used my virtual box OS, and after booting from ubuntu installation disk and extending the root partition using GParted worked like a charm. So I chosen to take the risk for my ubuntu 14.04 LTS version which is my host. After booting to a live ubuntu 14.04 cd I was able to delete an ntfs partition which was above my / partition for ubuntu. the resizing of my 24gb space to 61gb also didnt gave any error. But when i rebooted it ended up with a grub rescue menu. I tried to find a solution but nothing worked at all.
I did this one also:
sudo mount /dev/sda7 /mnt
sudo mount -o bind /dev/ /mnt/dev
sudo grub-install --root-directory=/mnt /dev/sda
sudo chroot /mnt /bin/bash

# Now within the chroot
sudo update-grub
exit

# Now outside chroot
This also didnt helped. Pls help.

A: You should realize that partitions can be safely expanded only to the right side (i.e bottom part). Any attempt to resize it to the left firstly should have consumed a lot of time and secondly and inevitably destroy the grub. Instead of chrooting and installing the grub, i can suggest you a simpler method.
Live boot and open you /dev/sda7 partition in the file manager. Then, close it and open terminal and type the command.
sudo /media/ubuntu/disk-uuid/usr/sbin/grub-install /dev/sda --boot-directory=/media/ubuntu/disk-uuid/boot/

You don't need to do update-grub as your grub config files are already in the boot directory.
P.S- Note that you need to hit the tab key to get the uuid and then continue. I hope you know the right use of tab key before you proceed.


text:
Q: would rather have v3 than v3 or would rather have v3 than vinf What would be the correct structure for "would rather...than..." in past aspect?
1.) would rather have v3 than v3
    ex. He would rather have gone out than stayed.
2.) would rather have v3 than vinf
    ex. He would rather have gone out than stay.
I have tried to find some references but none exactly match the case.
For example, from the Cambridge website:

When we want to refer to the past we use would rather + have + -ed form (perfect infinitive without to):
She would rather have spent the money on a holiday. (The money wasn't spent on a holiday.)
I'd rather have seen it at the cinema than on DVD. (I saw the film on DVD.)

A: You first example (would rather have gone out than stayed) is the more normal. It maintains the parallelism, so that both sides of the comparison are in the same tense
If you use the infinitive stay, then what you are comparing is the past infinitive have gone out with a present infinitive stay. There's nothing ungrammatical about that, but it's rather unusual. I can think of some cases where it is more likely, for example:

He'd rather have gone out than be here to face his aunt now!

which means something like he wishes he had gone out .... (The reason I think this is more likely is that be here is something he is doing right now. One of the meanings of stay is the continuing state, including right now; but in contrasting it with go out, it is more natural to interpret it as his decision to stay, which presumably happened in the past.


text:
Q: How to manage multiple backend stacks for development? I am looking for the best/simplest way to manage a local development environment for multiple stacks. For example on one project I'm building a MEAN stack backend.
I was recommended to use docker, however I believe it would complicate the deployment process because shouldn't you have one container for mongo, one for express etc? As found in this question on stack.
How do developers manage multiple environments without VMs?
And in particular, what are best practices doing this on ubuntu?
Thanks a lot.

A: With Docker-Compose you can easily create multiple containers in one go. For development, the containers are usually configured to mount a local folder into the containers filesystem. This way you can easily work on your code and have live reloading. A sample docker-compse.yml could look like this:
version: '2' services:   node:
    build: ./node
    ports:
      - "3000:3000"
    volumes:
      - ./node:/src
      - /src/node_modules
    links:
     - mongo
    command: nodemon --legacy-watch /src/bin/www

  mongo:
    image: mongo

You can then just type
docker-compose up

And you Stack will be up in seconds.


text:
Q: preg_replace -- umlauts not processed on Server I have written a small function to replace umlauts and other special german charackters in a string.
The whole thing looks like that:
function replace_german_chars($str)
{
  return preg_replace(
    array("/\s+/", "@\x{00e4}@u", "@\x{00fc}@u", "@\x{00f6}@u", "@\x{00df}@u"),
    array("-", "ae", "ue", "oe", "ss"),
    $str);
}

That code is mainly influenced by this comment in the php manual.
However, it works as it should on my localhost (Mac OSX Yosmite), but not on the server. The function above just replaces the special chars with nothing.
Any Idea?
[UPDATE]
After gaining enough permission I could manage to insert the suggested »ini_sets«. Some of them seem to »survive« throughout the application life-cycle, some not. The use of mb_convert_encoding before this settings worked, but does not afterwards and returns ? for all the matches.
I really do not get the point of that. I is somehow strange, since it seems that there are actually multiple encodings in play, even if Drupal states that it internally handles everything in utf-8.
[UPDATE #2]
The journey goes on, setting mbstring.http_output=UTF-8 makes Drupal say: "Disable that"! Right now, I have no real Idea where all that might come from, so I dicided to post the http header of the page:
HTTP/1.1 200 OK
Server: nginx
Date: Wed, 25 Nov 2015 10:07:23 GMT
Content-Type: text/html; charset=utf-8
Connection: keep-alive
Vary: Accept-Encoding
Expires: Sun, 19 Nov 1978 05:00:00 GMT
Cache-Control: no-cache, must-revalidate, post-check=0, pre-check=0
Content-Language: de
Link: </node/10>; rel="shortlink",</startseite>; rel="canonical"
X-Generator: Drupal 7 (http://drupal.org)
X-Powered-By: PleskLin

Next to this, there is another thing that might the cause of the problem: The overall collation setting of the Database Server within phpMyAdmin. To keep things clear, here is an Image of that:

The Database Server itself is configured to use UTF-8

A: preg_replace() is expecting a utf-8 encoded string. It seems like you have set a different default encoding. Then, you need to convert $str:

string mb_convert_encoding ( string $str , string $to_encoding [, mixed $from_encoding = mb_internal_encoding() ] )
Converts the character encoding of string str to to_encoding from optionally from_encoding.

This function gets the internal character encoding as from_encoding by default. If it's not detected by default, set your encoding from one of the supported encodings.

Code
function replace_german_chars($str)
{
  return preg_replace(
    array("/\s+/", "@\x{00e4}@u", "@\x{00fc}@u", "@\x{00f6}@u", "@\x{00df}@u"),
    array("-", "ae", "ue", "oe", "ss"),
    mb_convert_encoding($str, 'UTF-8') );
}

rextester demo

A: The most probable solution to your question is unicode content.
You should use the following syntax in Apache configuration (in httpd.conf or .htaccess)
AddDefaultCharset utf-8

And in your php.ini set below Configuration
default_charset = "utf-8"
mbstring.internal_encoding=utf-8
mbstring.func_overload=6
mbstring.http_output=UTF-8
mbstring.encoding_translation=On


text:
Q: Angular 6 propriedade undefined no JSON Faço o consumo de uma API que me retorna um JSON. O retorno funciona perfeitamente, porém, quando eu tento acessar alguma propriedade desse JSON, ele me da como undefined. Já validei o JSON e está ok
JSON:
    [
  {
      "ratingDate": "2018-12-21",
      "rate1": 0,
      "rate2": 0,
      "rate3": 1,
      "rate4": 0,
      "rate5": 0,
      "detractor": 100,
      "promoter": 0,
      "nps": -100,
      "Reserva": 1,
      "Abertura": 0,
      "Finalizar": 0,
      "VeiculoSujo": 0,
      "Abastecimento": 0,
      "CheiroCigarro": 0,
      "VagaRuim": 1,
      "Outro": 0
  },
  {
      "ratingDate": "2018-12-22",
      "rate1": 1,
      "rate2": 0,
      "rate3": 0,
      "rate4": 0,
      "rate5": 4,
      "detractor": 20,
      "promoter": 80,
      "nps": 60,
      "Reserva": 0,
      "Abertura": 0,
      "Finalizar": 0,
      "VeiculoSujo": 1,
      "Abastecimento": 1,
      "CheiroCigarro": 1,
      "VagaRuim": 0,
      "Outro": 0
  },
  {
      "ratingDate": "2018-12-23",
      "rate1": 0,
      "rate2": 0,
      "rate3": 0,
      "rate4": 1,
      "rate5": 8,
      "detractor": 0,
      "promoter": 89,
      "nps": 89,
      "Reserva": 0,
      "Abertura": 0,
      "Finalizar": 0,
      "VeiculoSujo": 1,
      "Abastecimento": 0,
      "CheiroCigarro": 0,
      "VagaRuim": 0,
      "Outro": 0
  }
]

No meu service, tenho método simples para essa chamada:
  getNPS(){
    return this.http.get(API);
  }

No meu componente também é bem simples:
  public npsArray: any[]

  constructor(private npsService: NpsService) {
  }

  ngOnInit() {
    this.getNPS();
  }

  getNPS(){
    this.npsService.getNPS().subscribe((data: any[]) => {
      this.npsArray = data;
      console.log(this.npsArray);
    })
  }

}

No console.log me mostra o JSON certinho, porem se eu tento uma propriedade, por exemplo this.npsArray.VagaRuim, ele me da como undefined

A: Resolvi, pessoal!
No gfFor, coloquei assim:
{{item['key']}}

A: Tenta mapear o array passando um valor para ele!
public npmArrayMap: any;

getNPS(){
    this.npsService.getNPS().subscribe((data: any[]) => {
      this.npsArray = data;
      console.log(this.npsArray);
      //Passando valor para array com map
      var array = Object.keys(this.npsArray).map(key => ({
                type: key,
                value: this.npsArray[key]
      }));
      this.npmArrayMap = arr;
     console.log(npmArrayMap);
    })
 }

Assim voce também poderá acessá-lo com *ngFor
no HTML como no exemplo abaixo.
<ion-item *ngFor="let npm of npmArrayMap ">
  <p>{{ this.npmArrayMap.value.VeiculoSujo }} </p>
</ion-item>


text:
Q: next versus if in a .each loop? I have a text processing thing I'm doing in Ruby. Basically, I have to implement a simple state machine (with one character look-behind).
My code at the moment looks like this:
text.each{ |c|
  ...
  ...
  ...
  ...
  if @state!=:some_state
    next
  end
  #processing stuff for if in :some_state mode
  ...
  ...
  ...
  ...
  ...
}

Is this proper? Or should it rather be implemented like:
text.each{ |c|
  ...
  ...
  ...
  ...
  if @state==:some_state
    #processing stuff for if in :some_state mode
    ...
    ...
    ...
    ...
    ...
  end
}

Is there a right way or is it just preference? Which one blends more with "the ruby way" of doing things?

A: I think that the example you gave doesn't really capture situation where doing next makes a difference. Consider the situation where you have multiple "next-points" in your code:
text.each do |c|
  next if @state == :state1
  ...
  next if @state == :state2
  ...
  next if @state == :state3
  ...
end

and compare it with if-variant:
text.each do |c|
  unless @state == :state1
    ...
    unless @state == :state2
      ...
      unless @state == :state3
        ...
      end
    end
  end
end

Although the first could be viewed as spaghetti-style by some purists, IMHO it is more readable than the latter.

A: Do it the second way
Some schools of thought are opposed to things in various languages like next, retry, continue, and break, because they are just a little bit too much in the direction of the disrespected goto statement.
Those statements do have their use cases, but in general it's a bad idea to deliberately "spaghettify" the code when a structured downward-pointing construct will accomplish the same thing. Now if the condition called for skipping the entire loop body, in that case I might prefer the use of next.

A: Totally agree with @DigitalRoss and I have seen people using next if there is complicated piece of code after some condition is being evaluated i.e.
 next if @state!=:some_state
 # some long complicated code

on the other hand if there is a simple operation that needs to be performed on the basis of some condition then I would prefer
 if @state == :some_state
   #call_a_method_to_do_something
 end

 OR

 call_a_method if @state == :some_state

Having said that, its bad practice to write long complicated code. If your code is clean and well designed then you would never have to use next within your code.

A: i would go for:
text.each{ |c|
  ...
  ... Generic state processing
  ...
  case @state
    when :state_1 then code
    when :state_2 then code
  end
}

But if it's as on the first sample ( meaning just 1 state needs extra processing )
text.each{ |c|
  ...
  ... Generic state processing
  ...
  next unless @state == :state_1
  ...
  ... Code that process states other than :state_1
}

Going even further instead of hitting the instance variable, it sound nicer to ask the object if it's in the state we need like:
def processed?
  @state == :state_1
end

...
next unless processed? # sounds like natural language...
...

Reasoning a little bit further, I think one liners like 'next unless processed?' are good only when there are no more than 10 lines of code in the same indentation level, otherwise i rather do the other, so indentation will help me understand at first glance what's happening


text:
Q: Chernikov Groups and layer-finite groups A group $G$ is Chernikov if it has a subgroup of finite index that is a direct product of finitely many groups of $C_{p^\infty}$ for various primes $p$ (quasicyclic $p$-groups). The subgroup of finite index that is a direct product of finitely many groups of type $C_{p^\infty}$ is the minimal subgroup of finite index in $G$, so it is characteristic in $G$ (in particular, is normal). It is called the radicable part of $G$.
My question:
Let $G$ be a Chernikov group and denote by $N$ the radicable part of $G$. Suppose that $N$ is central in $G$. Then $G$ is layer-finite, that is, contains only finitely many elements of any order?

A: Fix some $n>0$. If $g \in G$ has order $n$ and $gh$ also has order $n$ with $h \in N$ then, since $N \le Z(G)$, we have $h^n=1$. But there are only finitely many elements of $N$ with $h^n=1$, so each coset of $N$ in $G$ contains only finitely many elements of order $N$. Hence so does $G$.


text:
Q: create a third list by combining values in two lists I have to two arrays (in my code below): "donlist" is a list of random donation amounts between $1 and $100, and "charlist" is a list of random charity numbers between 1 and 15. I need to create a third array using the total donations for each charity. So if charity #3 appears 8 times in "charlist", I have to get the sum of the corresponding floats from "donlist". I have absolutely no idea how to do this and have been trying to figure it out for the past 2-3 hours now. Does anyone know how to do it? Thank you.
import random
from array import *

counter = 0
donlist = []
charlist = []

while counter != 100:
    d = random.uniform(1.00,100.00)
    c = random.randint(1,15)
    counter +=1
    donlist.append(d)
    donlist = [round(elem,2) for elem in donlist]
    charlist.append(c)
    if counter == 100:
        break

Sample output:
Charity    Total Donations
1          802.65
2          1212.25
3          108.25
4          9324.12
5          534.98
6          6235.12
7          223.18
8          11.12
9          3345.68
10         856.68
11         7123.05
12         6125.86
13         1200.25
14         468.32
15         685.26

A: Use a dict, with the charity number as the key. You simply add the donation to the corresponding dict value. If the dict element doesn't exist yet, set it to zero as its initial value.
I'm using defaultdict: the lambda: 0 argument will guarantee a zero value if the key doesn't exist yet, otherwise you can just add to it.
Updating your script (with a few minor other alterations):
import random
from collections import defaultdict

donlist = []
charlist = []
totals = defaultdict(float)

counter = 0
while counter != 100:
    counter += 1
    d = random.uniform(1.00,100.00)
    c = random.randint(1,15)
    donlist.append(d)
    donlist = [round(elem,2) for elem in donlist]
    charlist.append(c)
    totals[c] += d

nb: I removed the array import, since you're only using lists in the code.

A: This seems a good example to use the zip function. It gets two lists as argument (in your case the donlist and charlist) and creates an iterator of these, so you can iterate one time adding the values from donlist in the right charity position. zip example:
for a, b in zip(range(1, 5), range(5, 10)):
    print(a, b)

will output
1 5
2 6
3 7
4 8

I strongly recommend generating the data lists before creating the third, so you can do
donlist = [ random.uniform(1.0, 100.0) for _ in range(0, 100) ]
charlist = [ random.randint(1, 15) for _ in range(0, 100) ]

This is a simple syntax to create a list from an iterator. You can read more about it here.
This way, you can guarantee that it works for cases when these lists are not generated during the calculation, for an example, where the user input the values.
After the lists generation / input you can just:
# this is the same as a list comprehension but for a dict
# https://docs.python.org/3/tutorial/datastructures.html#dictionaries
result = { char : 0 for char in range(1, 16) }
for don, char in zip(donlist, charlist):
    result[char] += don

In the end each charity N has it's donation value in result[N].

A: >>> l1 = [1,1,3,4] # charity list
>>> l2 = [5,6,7,8] # donation list
>>> zip(l1,l2)
[(1, 5), (1, 6), (3, 7), (4, 8)]

>>> from collections import defaultdict
>>> d = defaultdict(int)
>>> for k,v in zip(l1,l2):
...    d[k] += v
...
>>> d
defaultdict(<type 'int'>, {1: 11, 3: 7, 4: 8})

You can now index d by charity number and get the value of donation.


text:
Q: How to avoid calling refresh procedures all the time among the pages? I am new to AngularJS. I have the following scenerios
Menu Items -- Home  Page2 Page3  Page4
Remember,
Home Page has HomeController
Page2 has Page2Controller
Page3 has Page3Controller
Page4 has Page4Controller
Each page has it's own init() function to get the data from the server and populate the initial data.
At the beginning, I have to call a different procedure for each page to populate different values for each page.
Now the question I have is as follows:
Step 1:
 I have logged onto the apps and it populates the Home Page values.
Step 2:
 I have clicked Page2 to get the initial data.
The same is true for Page3 and Page4 as well.
At this point, all the pages have the initial values.
Step 3:
Now, I would like to go back ( say, click Home) to Home page.
Is there any way I can check the values of Home page?
If the Home page has values, I do not want to call the Init() function.
Is it possible to not call the Init() function?
The idea is that if I do not have to call the Init() function after the 1st call, the apps would be very faster.
I would really appreciate your input in this regard.
Thanks


text:
Q: How to remap mouse button to keyboard button I have a remote control with gyroscope. It has these buttons:
            home
settings    OK      back
            info

            zoom-in
            zoom-out

I need to test GUI without gyro, so I want to transform them into
        up
left    enter   right
        down

        home
        back

I had no problems with assigning left, up, down, home and back as they all had keyboard codes.
For example, I've replaced key 59    SETTINGS with key 59    DPAD_LEFT in Generic.kl (I'll create device-specific keylayout later)
However, original back button have code 273 (0x111). There were no such key in Generic.kl.
Adding key 0x111 DPAD_RIGHT or key 273   DPAD_RIGHT didn't work.
Just in case, here is getevent output for this key press:
/dev/input/event4: 0004 0004 00090002
/dev/input/event4: 0001 0111 00000001
/dev/input/event4: 0000 0000 00000000
/dev/input/event4: 0004 0004 00090002
/dev/input/event4: 0001 0111 00000000
/dev/input/event4: 0000 0000 00000000

So, how do I remap this key ?


text:
Q: Why is more than 3 GB of RAM not recognised when using AMD64? Why does Ubuntu 10.10 amd64 (Maverick Meerkat) not address more of 3 GB RAM?
My machine is a Toshiba P205-S6287 Intel Centrino Duo 64 bits processor and 4 GB RAM at 667 MHz.
According to the detailed specifications, the notebook runs a 64-bit Core 2 Duo T5300 processor and has a 945GM Express chipset.

A: This is due to the Mobile Intel 945GM Express in your laptop.
I own a Thinkpad T60, which uses the same chipset. It was one of the first northbridges from intel for the Core2Duo 64-bit CPUs. They failed in designing it.
The chipset can only theoretically address 4GB of RAM, yet also has to address other hardware (I/O memory). It reserves the upper 1GB memory range for that. The 64bit logical memory address support in the Linux kernel doesn't help, because the mainboard and northbridge only provide for a 32bit physical address bus to the CPU. And there is no workaround.
http://forums.lenovo.com/t5/T61-and-prior-T-series-ThinkPad/Thinkpad-s-and-N100-s-w-945PM-chipset-can-t-address-gt-3G-Ram/m-p/2730

There is a theoretical option in devising memory bank switching. Yet the kernel does not support it, nor would it make sense on the x86 architecture. The i810 memory controller of the 945GM is probably too lazy for that to make sense.

A: There are several possible reasons.
One is that you are, in fact, not running the amd64 build. Another is that your motherboard and/or BIOS are broken and not reporting the correct amount of RAM.
Another is that you have video memory and other hardware resources taking up space in the 3-4 GB area of memory, and your motherboard/BIOS is incapable of hoisting the shadowed RAM to higher addresses so that it can be accessed.
Figuring out which requires looking at your dmesg output.

A: My short answer is: likely because the BIOS designer was sloppy.
The long anwser is:
Although you have 4GB RAM installed, you can not expect to have 4GB of usable RAM available with the Intel 945GM chipset. This is a chipset limitation. You can tell this from the chipset's specification:
http://www.intel.com/content/www/us/en/intelligent-systems/navy-pier/mobile-945-express-chipset-datasheet.html
Quote from section 9.2: "The Memory Controller Hubs provides a maximum DRAM address decode space of 4 GB. The MCH does not remap APIC or PCI Express memory space. This means that as the amount of physical memory populated in the system reaches 4 GB, there will be physical memory
that exists yet is non-addressable and therefore unusable by the system."
The BIOS must reserve address ranges for several resources, i.e. the BIOS itself, PCI and PCI Express memory mapped space, internal graphics, APIC memory space and other memory windows for I/O access. All these address ranges have to lie within the 4GB address space and as such occupy address ranges that are not available to system memory any longer. You could say these resources "steal" physical RAM memory space.
That being said, if you have 4GB installed you can expect to have more than 3GB system memory available.
The amount of physical memory that is available to the system depends on how much effort the BIOS designer puts into arranging theses address ranges. For example, the BIOS could allocate the least amount needed for each resource. Or it could allow for disabling or limiting address allocation for PCI Express depending on your system's usage of PCI Express devices.
The BIOS designer of your system likely set the upper limit of usable RAM to a static maximum of 3GB even though you installed 4GB. This approach provides a static address window of 1GB to the BIOS designer and as such simplifies the BIOS designers task to allocate address ranges for the resources so they do not conflict with any other address range.

A: psusi is right.
I have the same situation here:
Although they call it "64-bit CPU" you can often not address 4 GB+ memory.
Most old motherboard do only have 32 bit for the addresses and from this pool the graphics card needs to get their addresses too.
= 4 GB - graphics card memory (1 GB) = 3 GB.
I fear there is no possibility to fix this by patching or upgrading firmware of anything.
If you are interested in detail I recommend: Physical Address Extension


text:
Q: Parrot OS no Wifi Applet/Can't COnnect So I've just installed Parrot Security OS On my Dell XPS 9370 Which is running the following wifi chipset 02:00.0 Network controller:
Qualcomm Atheros QCA6174 802.11ac Wireless Network Adapter (rev 32) However I'm unable to get wifi working at all on it. When I first login theres a popup which says wifi networks are available but clicking it does nothing. There doesn't seem to be a wifi applet either which shows available networks. I've tried downloading firmware online for the wifi chipset which hasn't solved the issue either.
Below are some syslogs which may indicate something to someone but not to me!
Jan 21 18:44:39 parrot kernel: [  355.053941] IPv6: ADDRCONF(NETDEV_UP): wlan0: link is not ready
Jan 21 18:44:39 parrot NetworkManager[835]: <info>  [1548096279.5974] device (wlan0): supplicant interface state: ready -> disabled
Jan 21 18:44:39 parrot NetworkManager[835]: <info>  [1548096279.6158] device (wlan0): supplicant interface state: disabled -> inactive
Jan 21 18:44:39 parrot wpa_supplicant[834]: wlan0: Reject scan trigger since one is already pending
Jan 21 18:47:46 parrot wpa_supplicant[834]: nl80211: deinit ifname=p2p-dev-wlan0 disabled_11b_rates=0
Jan 21 18:47:46 parrot NetworkManager[2293]: <info>  [1548096466.3396] wifi-nl80211: (wlan0): using nl80211 for WiFi device control
Jan 21 18:47:46 parrot wpa_supplicant[834]: nl80211: deinit ifname=wlan0 disabled_11b_rates=0
Jan 21 18:47:46 parrot NetworkManager[2293]: <info>  [1548096466.5779] device (wlan0): driver supports Access Point (AP) mode
Jan 21 18:47:46 parrot NetworkManager[2293]: <info>  [1548096466.5784] manager: (wlan0): new 802.11 WiFi device (/org/freedesktop/NetworkManager/Devices/3)
Jan 21 18:47:46 parrot NetworkManager[2293]: <info>  [1548096466.5796] device (wlan0): state change: unmanaged -> unavailable (reason 'managed', sys-iface-state: 'external')
Jan 21 18:47:46 parrot kernel: [  542.054412] IPv6: ADDRCONF(NETDEV_UP): wlan0: link is not ready
Jan 21 18:47:46 parrot NetworkManager[2293]: <info>  [1548096466.6670] device (wlan0): set-hw-addr: set MAC address to F6:E2:57:AC:D5:BD (scanning)
Jan 21 18:47:47 parrot kernel: [  542.887547] IPv6: ADDRCONF(NETDEV_UP): wlan0: link is not ready
Jan 21 18:47:47 parrot NetworkManager[2293]: <info>  [1548096467.4225] device (wlan0): supplicant interface state: init -> starting
Jan 21 18:47:47 parrot NetworkManager[2293]: <info>  [1548096467.5267] sup-iface[0x5612780340c0,wlan0]: supports 5 scan SSIDs
Jan 21 18:47:47 parrot NetworkManager[2293]: <info>  [1548096467.5289] device (wlan0): supplicant interface state: starting -> ready
Jan 21 18:47:47 parrot NetworkManager[2293]: <info>  [1548096467.5290] device (wlan0): state change: unavailable -> disconnected (reason 'supplicant-available', sys-iface-state: 'managed')
Jan 21 18:47:47 parrot kernel: [  543.003938] IPv6: ADDRCONF(NETDEV_UP): wlan0: link is not ready```

A: I know this is a little late in coming but I scoured the webs for the same issue and your thread gave me the lead I needed.
Under the menu System->Preferences->Hardware->Displays you can set the resolution. I had to play with it for a bit for my network manager to show up. Weird that parrot doesn't deal with hi-res well.


text:
Q: Update randomly selected item if it exists in RethinkDB I want to randomly select a single item from a collection of 0 to many items and if it exists, update a specific field. If the item does not exist, I'd like the function to perform no update and return null.
My current REQL code:
r.db('test').table('test')
.filter({
    something: true
}).sample(1).nth(0).default(null).update(function(thing) {
    return r.branch(
        thing.ne(null),
        thing.without('reserve'),
        null
    )
}, {
    returnChanges: true
});

This always returns the error: Expected type SELECTION but found DATUM I am not sure how to address this issue with REQL.

A: You probably want to write this:
r.db('test').table('test').filter({something: true}).sample(1).replace(function(thing) {
    return thing.without('reserve');
}, {returnChanges: true});

This will give you back a write summary object that you can use to determine whether or not a replacement actually occured.


text:
Q: Javascript function and variables scope Quick question, because one thing confused me today. Below is piece of JavaScript code:
var a = [1, 2, 3, 4];

function init() {

    console.log(a);

    if (false) {
        var a = [9, 8, 7];
    }
}

init();

This simple code logs "undefined" in JS console. I found that the reason for this is 5th line:
var a = [9, 8, 7];

Without word var inside that condition, it will log correct result [1, 2, 3, 4].
My question here is: why JavaScript interpreter takes into consideration piece of code which never will be executed?
Example to play with: http://jsfiddle.net/5DPCz/

A: You cannot declare variables in the middle of a function in JavaScript; all variables have function scope. Effectively, variable declarations are "hoisted" to the top of the function. Your function will only ever have access to the local variable a regardless of where in the function it is declared.
This is why JSLint (and most other linting tools) will advise you to move all variable declarations to the top of the function; that's where they're effectively written anyways.
Regardless of where in your function you place your var a, your code effectively executes this way:
var a = [1, 2, 3, 4];

function init() {
    var a;

    console.log(a);

    if (false) {
        a = [9, 8, 7];
    }
}

init();

A: Your example is equivalent to
var a = [1, 2, 3, 4];

function init() {
    var a;
    console.log(a);

    if (false) {
        a = [9, 8, 7];
    }
}

init();

Now you can see why it prints undefined.
The a that is local to the function has not been assigned a value at that point yet.
If you remove the var you turn it into
var a = [1, 2, 3, 4];

function init() {
    console.log(a);

    if (false) {
        a = [9, 8, 7];
    }
}

init();

So a in the function now refers to a from the global scope.


text:
Q: Map list of boolean observables into output that emits true whenever all inputs are true Say I have n Boolean Observables (O1, O2,...,On) that emit flags indicating, let's say, checkbox selection states.
For example, for n = 3, we would have something like this (T =true and F = false):
O1    - T ------------------- F ----------------------- T ------

O2    - F ------------ T ---------------------------------------

O3    - T -------------------------- F -------- T --------------

I want to get an output Boolean Observable (Oout) that emits true when all the latest emissions are true or false otherwise. Something like this:
O1    - T ------------------- F ----------------------- T ------

O2    - F ------------ T ---------------------------------------

O3    - T -------------------------- F -------- T --------------

================================================================

Oout  - F ------------ T ---- F ----------------------- T ------

Is there a fancy way to do this in RxJava (that is, without the need to create a custom observable and monitoring the state myself. I feel like a couple of operators can do the job)?

A: Static method Observable.combineLatest(List<Observable<T>> observables, FuncN<?> combineFunction) is the thing you are looking for.
You pass in a list of observables and a combine function, which determines the output, in your case just a for cycle will be sufficient to check if all of them are true.


text:
Q: Laravel 5 model method for a one-to-many where the many table uses the primary key more than two times I have one table called gen_nodes, which is a root table in that it has an id, fields for name and description, and each row is not dependent on another value.
I also have a table called gen_nodes_hierarchy which has three columns:
parent_node_id   (required)
child_node_id    (required)
group_node_id    (default NULL, optional)

Where the values in gen_nodes.id will reside.
To give an overview of use, these two tables are for defining complex taxonomic relationships including menu hierarchies.
I am new to this area of Laravel (5.5).  What is the proper way to set up the model(s) for these tables, and what properties need to be declared in each model to make this work?  Thanks.


text:
Q: copying the request header from request object to urlConnection object protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    URL url = new URL("http://localhost:8080/testy/Out");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setDoOutput(true);
    connection.setRequestMethod("POST");
    PrintWriter out = response.getWriter();
    for(Enumeration e = request.getHeaderNames(); e.hasMoreElements();) {
        Object o = e.nextElement();
        String value = request.getHeader(o.toString());
        out.println(o + "--is--" + value + "<br>");
        connection.setRequestProperty((String) o, value);
    }
    connection.connect();
}

i wrote the above code in a servlet to post form so some alternate locations than this servlet,but its not working.is it okay to use connection.setRequestProperty to set the header fields to what they are in the incoming request to servlet.

A: i think you are looking for
RequestDispatcher rd;
rd = getServletContext().getRequestDispatcher("pathToServlet");
rd.forward(request, response);

A: URLConnection is lazily executed. That is, it won't actually fire the HTTP request until you grab some information about the HTTP response. E.g.
int responseCode = httpUrlConnection.getResponseCode();

or
InputStream responseBody = urlConnection.getInputStream();

or
String statusHeader = urlConnection.getHeaderField(null);

The connection.connect(); is by the way entirely superfluous. It's already executed at the moment you called url.openConnection();. Also the connection.setRequestMethod("POST"); is entirely superflous, the connection.setDoOutput(true) already does that.
That said, if the target is actually located in the same webapp context hosted at the same machine, then there are much better ways to invoke it than creating a HTTP connection to it, such as forwarding or redirecting the request.


text: Q: Перетаскиваемый элемент без скролла Как сделать чтобы если элемент больше по ширине и высоте размеров экрана то скроллы не появлялись а было как у гугл-карт или яндекс-карт можно перетаскиванием двигать.Что-то связанное с draggable. Еще такую же реализацию видел у больших графиков d3.js


text:
Q: Pandas: Take an average of rows with matching values I've tried several ideas posted on the forums but none is quite working. I have a dataframe of product identifiers and prices. I have already narrowed the df to only where the same product has more than one price in the larger database. Now I want to create a new column that will be the average price of a given product. I.e.:
ID          Price
ABC1        101.45
XYZ2        88.12
ABC1        99.24
XYZ2        82.99
ABC1        105.00

The output I want is as such:
ID          Price          AvgPx
ABC1        101.45         101.897
XYZ2        88.12          85.556
ABC1        99.24          101.897
XYZ2        82.99          85.556
ABC1        105.00         101.897

I've tried various versions of groupby and for loops and nothing quite works. Thanks for your help!

A: While the other solutions offered work great, I would argue that using transform here leads to nice clean easy to read code:
df['AvgPx'] = df.groupby('ID')['Price'].transform('mean')

>>> df
     ID   Price       AvgPx
0  ABC1  101.45  101.896667
1  XYZ2   88.12   85.555000
2  ABC1   99.24  101.896667
3  XYZ2   82.99   85.555000
4  ABC1  105.00  101.896667

A: You can create an aggregate version of the dataframe, then use merge to join your original dataframe with your aggregate.
agg_df = df.groupby('ID', as_index=False)['Price'].mean().rename(columns={'Price': 'AvgPx'})

df = df.merge(agg_df)

ID   Price       AvgPx
0  ABC1  101.45  101.896667
1  ABC1   99.24  101.896667
2  ABC1  105.00  101.896667
3  XYZ2   88.12   85.555000
4  XYZ2   82.99   85.555000

A: You can do this:
avg = df.groupby('ID').Price.mean()
df.join(avg, on='ID', rsuffix='Avg')

It would be nicer to say df['AvgPx'] = avg.reindex(df.ID), but that doesn't work because reindex() requires a unique series.


text:
Q: Данные не сохраняются Написал простую прогу на C# с использованием элементов ADO.NET.
Из БД Access(формат "mdb") классом "OleDbDataAdapter" вытащил данные для определенной таблицы и "запихнул" в объект "DataGridView", создал BindingSource и BindingNavigator для управления записями. Возникла проблема с сохранением данных после измнения их в DataGridView – данные не хотят записываться в БД.
Привожу урывок кода:

...
private DataSet mainDS;
...
private void MakeTable(string tableName)
{
            //подключение и вытаскивание данных
            OleDbConnection cn = new OleDbConnection();
            cn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" + @"Data Source= D:\KP\main.mdb;";
            cn.Open();
            OleDbDataAdapter dAdapt = new OleDbDataAdapter("SELECT * FROM " + tableName, cn);
            mainDS = new DataSet("main");
            dAdapt.Fill(mainDS, tableName);
            cn.Close();
        //тут наверно и ошибка
        resGrid.DataSource = mainDS.Tables[tableName];
        resGrid.Refresh();
        bindingSource1.DataSource = resGrid.DataSource;
        bindingNavigator1.BindingSource = bindingSource1;

}

Помогите пожалуйста, очень нужно! Заранее спасибо!
Пы.Сы: добавил к bindingNavigator1 кнопку, которая выполняет код: "mainDS.AcceptChanges();" и все-равно не пашет -(
A: DataSet.AcceptChanges помечает датасет как неизменённый.
Чтобы сохранить данные, нужно вызвать у адаптера Update. При этом на все несохранённые изменения сгенерятся команы обновления БД. Соответственно, если AcceptChanges вызвать перед этим, в БД тоже ничего не сохранится.


text:
Q: Custom Layer not drawing using ArcObjects? I have a Customer layer which inherits BaseCustomLayer.
I add it to my MapControl via addLayer but the function public override void Draw(esriDrawPhase drawPhase, IDisplay Display, ITrackCancel trackCancel) is never hit.
The Custom Layer appears checked in the TOC.
I think I must be missing some initialization one-liner.

A: Here's a minimalist custom layer:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ESRI.ArcGIS.ADF.BaseClasses;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.Display;
using ESRI.ArcGIS.esriSystem;

namespace MapControlApplication1
{
    class CustLayer2: BaseCustomLayer
    {
        public override void Draw(esriDrawPhase drawPhase, IDisplay Display, ITrackCancel trackCancel)
        {
            System.Diagnostics.Debug.Print("drawing {0} {1}", drawPhase,  Environment.TickCount);
        }
    }
}

I created a new Project and choosing C#>ArcGIS>Extending ArcObjects>Mapcontrol Application, then added a new menuitem on the menu of MainForm with this:
private void testToolStripMenuItem_Click(object sender, EventArgs e)
{
    try
    {
        CustLayer2 layer = new CustLayer2();
        layer.Name = "cust layer2";
        axMapControl1.AddLayer(layer);
    }
    catch (Exception ex)
    {
        MessageBox.Show(this, ex.Message);
    }
}

When I run I see this output as I pan around the map:
drawing esriDPGeography 441416029
drawing esriDPGeography 441422207
drawing esriDPGeography 441433579


text:
Q: How to not run /etc/profile.d/custom.sh during Secure FTP login When I attempt to Secure FTP (using WinSCP) to my CentOS 6.4 box I'm prompted with a message that states:
Received too large (168438314 B) SFTP packet. Max supported packet size is 1024000 B.

This error is typically caused by message printed from startup script (like profile). The message may start with ""\n\n**""

Cannot initialize SFTP protocol. Is the host running an SFTP server

This appears to be caused by my /etc/profile.d/custom.sh script which gets run during login. Its setup to output a welcome message, as well as a system summary (CPU/Memory/Disk Usage).
I really need the custom.sh script to run when logging into the local console OR when logging in via SSH. However I don't want it to run when logging into Secure FTP (SFTP).
Is there some way to configure it not to run when logging in via Secure FTP?
Or alternatively if I can't stop it from running is there a way I can detect that its being run during a secure FTP login and not output anything. So in pseudo code something like:
If logged in via secure FTP then output nothing
Else if logged in via SSH or Local Console output message of the day (system stats).
Thanks!
Brad
UPDATE - There is documentation supporting this issue here: http://winscp.net/eng/docs/requirements#remote_environment
The suggestion is to detect if the session is interactive or not. I tried doing that by adding the following to the top of my custom.sh but its still not working:
if [ -z $PS1 ]; then
### if [ -v PS1 ]   # On Bash 4.2+ ...
    # non-interactive
    return
fi

Then the rest of my script runs outputting the MOTD.
Should SecureFTP be detected as non-interactive or interactive? If its non-interactive why isn't the code above existing the script when I attempt to login via Secure FTP?

A: Maybe standard method of checking the fd '0′ ?
if [ -t 0 ]; then
# do stuff
fi

A: Using /etc/profile.d for de facto dynamic MOTD needed only for interactive logins over SSH/console will generate such issues.
While the workaround in Danila Lander's answer may work, I suggest doing the right thing and using a proper solution for that.
Please see this question's answers for info on how to do it the right way on Ubuntu and Centos 7 servers.


text:
Q: On the meaning of set-valued mappings here one question that may look stupid. Why in general one insists on naming in a different way functions and set-valued functions just because one is single valued and the other is not? I mean, from topology, we define as function an object that maps one topological space $X$ into another one $Y$, we never require this mapping to be single-valued! Thanks!

A: I believe we have lifted some of your confusion in the comments, but let me illustrate how being "set-valued" and being "multivalued" have nothing in common. Let $A = \{1\}$ be a one-point set and let $B = \{1,A,\{A\}\}$. We are going to define four relations from $A$ to $B$. By definition these are subsets of the three-element set $A \times B$, and $a \in A$ is related to $b \in B$ if and only if $(a,b)$ belongs to the relation.
Let $R_1 = \{(1,1)\}$. This is just an ordinary function: the input $1$ has the unique output $1$. Moreover it isn't really "set-valued" if we consider $1$ to be an object that is somehow not really a set because we haven't specified what it contains.
Let $R_2 = \{(1,A)\}$. Again this is just an ordinary function: the input $1$ yields the output $A$ (a set). This is a "set-valued function".
Let $R_3 = \{(1,1),(1,A)\}$. This is a multivalued function because the input $1$ has precisely two outputs, namely $1$ and $A$. It isn't precisely set-valued because you don't consider $1$ to be a set.
Let $R_4 = \{(1,A),(1,\{A\})\}$. This is a "set-valued" multifunction.

A: Your question, as it stands, is confusing, but from your discussion with others in the comment sections, I think the problem is that you are yet to understand what the word function means in modern mathematics. In particular, I think you are imposing additional constraints on the usual definition, namely that you think a function must be one-to-one. But this is not necessary at all. Many functions are not injective (that's synonymous to one-to-one), and an example is the one you plucked from topology in your discussion in the comment under the OP.
So a function need not map different points to different images. There is absolutely no need for that in general. All that we require is that the same point must have no less and no more than one image.
In the language of sets, a function takes each point in a set (called the domain) to exactly one image point in a set (called the codomain). This does not mean two points in the domain cannot have the same image (we make no such restriction), so long as they both have just that one point as image.
I hope this clarifies some things. But I think you should read more about functions and really understand them. A definition means just what it says, no more or less.
PS. I thought I should give an example. Note that what we call a constant function is any function that takes all the points in the domain to the same one point in the codomain. This is a function because every point of the domain has precisely one image, even though in this case they all have the same image.


text:
Q: SSIS package fails when run by SQL Agent - "Invalid character value for cast specification" I have a SSIS package which reads data from .xml and .xlsx files and writes them to staging SQL Server database. The package is deployed to SSIS catalog on Microsoft SQL Server (Enterprise) instance. When the package is executed by SQL Agent job step it fails with the following error message:

SSIS Error Code DTS_E_OLEDBERROR. An OLE DB error has occurred. Error code: 0x80004005
An OLE DB record is available. Source: "Microsoft OLD DB Provider for SQL Server" Hresult: 0x80004005. Description: "Invalid character value for cast specification".

When the same package is run manually from Visual Studio it works just expected. There is no problem with feeding data to staging tables.
Any idea what can caused this issue?

A: I finally find an answer and will here share with you how to resolve it.
Even though the parameter Run64BitRuntime =false at Project Properties wchich I had deployed to SSIS catalog it looks like it was actually executed with 64bit mode as at Job Step properties at configuration tab you have option to run it with "32-bit runtime"
Job Step Properties


text:
Q: LINQ to SQL: how to select specific fields conditionally into DTOs (performance) LINQ to SQL is great however it backfires in performance in some cases. And with my case it backfires bigtime.
I have a StudentServiceDm that maps to a StudentService Table with 40 some fields. I have 10-20 millions of services in the table. The requirement from the client is that they need to export all services into excel from the application, while selecting only the fields they want at the time.
From my understanding, if i do
IQueryable<StudentServiceDm> serviceQuery = GetListQuery();
List<StudentServiceDto> dtos = serviceQuery.Select(m => new StudentServiceDto
{
    Id = m.Id,
    Name = m.Name,
}).ToList();

Then this translates into the SQL that selects only the fields I need
SELECT Id, Name FROM StudentService

Which saves performance by alot by decreasing the number of fields that need to be selected.
But in my case I need to allow the user to conditionally select fields like this, so I do this:
IQueryable<StudentServiceDm> serviceQuery = GetListQuery();

List<StudentServiceDto> dtos = serviceQuery.Select(m => new StudentServiceDto
            {
                Id = (options.ShowId) ? m.Id : null,
                Name = (options.ShowName) ? m.Name,
                StudentFirstName = (options.ShowFirstName) ? m.Student.FirstName : null,
                StudentLastName = (options.ShowLastName) ? m.Student.LastName : null,
                StudentServiceType = (options.ShowType) ? m.StudentServiceType.Name : null,
                StudentServiceSubType = (options.ShowSubType) ? m.StudentServiceSubType.Name : null,
                Date = (options.ShowDate) ? m.Date : null,
                // alot more assignments .....
            }).ToList();

However, this translates into the SQL query to something like this (according to SQL Profiler:
SELECT
    CASE WHEN (@p__linq__1 = 1) THEN [Project2].[Date] END AS [C1],
    CASE WHEN (@p__linq__2 = 1) THEN [Project2].[Name] END AS [C2],
    CASE WHEN (@p__linq__3 = 1) THEN [Project2].[StudentServiceTypeId] END AS [C3],
    CASE WHEN (@p__linq__4 = 1) THEN [Project2].[StudentServiceSubTypeId] END AS [C4],
    CASE WHEN (@p__linq__5 = 1) THEN [Project2].[Date] END AS [C5],
    // ..... more fields
    FROM * //

where it puts a condition on every field to check if it should retrieve ... and actually this query's performance is almost the same as if all fields were selected.
What I want to achieve is, if the user only chooses to select Name and Date, then the translated SQL should only be
SELECT Name, Date FROM StudentService

After some performance analysis, the performance difference between these 2 sets of statement is about 3-4 times.
Any expert opinion?

A: You can create Linq expressions at runtime that exactly correspond to what you'd type in inside a .Select() statement, it's just not very straightforward. I never did it for Linq to SQL specifically but I don't see why it wouldn't work. Something like How do I dynamically create an Expression<Func<MyClass, bool>> predicate? but of course I'd recommend reading the docs first to get familiar with expressions.

A: The only way to do what you are interested in doing is to create lots of different Select() sections, each corresponding to a different combination of fields. However, you will need to create an awful lot of different combinations (N!, where N is the number of fields), so it is not really practical or maintainable.
There is no other way to do this using L2S.
If performance is important for you in this aspect, I suggest creating the sql directly and using something like Dapper to retrieve the data. Then you can easily control exactly the fields that you want to include.


text:
Q: Problem displaying video in multiple windows with AVerMedia SDK I have a problem trying to display video in more than one window at the same time using the AVerSetVideoWindowMultiple function, using only one window at a time it can switch to the new window but if I try to make it display in two or more windowsat the same time gives me this error :

Can't get the number of devices. AVer Capture SDK

I'm using a CL314H1 video capture card and the code is in C# with .NET 4
stopStreaming(_hCaptureDeviceGlobal_0, m_bIsStartStreaming_0);

            IntPtr[] hWndPreviewPictureBox = new IntPtr[2];

            hWndPreviewPictureBox[0] = btnHD0.Handle;
            hWndPreviewPictureBox[1] = BigPicture.Handle;

            AVerCapAPI.AVerSetVideoWindowMultiple(_hCaptureDeviceGlobal_0, hWndPreviewPictureBox, (uint)2);

            if (!m_bHadSetVideoRenderer)
                AVerCapAPI.AVerSetVideoRenderer(_hCaptureDeviceGlobal_0, (uint)VIDEORENDERER.VIDEORENDERER_EVR);

            GCHandle gchThis = GCHandle.Alloc(this);
            AVerCapAPI.AVerSetEventCallback(_hCaptureDeviceGlobal_0, m_NotifyEventCallback, 0, GCHandle.ToIntPtr(gchThis));

            if (AVerCapAPI.AVerStartStreaming(_hCaptureDeviceGlobal_0) != (int)ERRORCODE.CAP_EC_SUCCESS)
            {
                string palabra = "Can't get the number of devices. AVer Capture SDK";
                MessageBox.Show(palabra);
                return;
            }

            RECT RectClient = new RECT();
            RectClient.Left = 0;
            RectClient.Top = 0;
            RectClient.Right = BigPicture.Width;
            RectClient.Bottom = BigPicture.Height;
            AVerCapAPI.AVerSetVideoWindowPositionMultiple(_hCaptureDeviceGlobal_0, (uint)1, RectClient);

            AVerCapAPI.AVerSetVideoWindowPosition(_hCaptureDeviceGlobal_0, RectClient);`


text:
Q: Plot intersection of row and colum values I feel like there is a simple solution to this that I am overlooking?
I have column headers with unique values and a single column (A) with rows of data. I am looking for a way to mark the cell in the corresponding column for the value found in the column A of the row. See screenshot for example. I don't care what it is marked with (X in screenshot example). A solution that would easily executable against 30+ columns and thousands of rows would be preferable.

A: Type the following in B2: =IF(B$1=$A2,"X","")
Drag this to the right and down.
But using vba would be better.


text:
Q: Phinx seeds won't run after upgrade to php7.0 I have a bunch of Phinx seeds which used to run fine
php vendor/bin/phinx seed:run

My seeds are located in var/www/html/db/seeds folder
I recently upgraded my VM to php 7.0 (Also upgraded to 16.04 LTS box), now I get the following output & error when I try to run phinx seeds:
ubuntu@ubuntu-xenial:/var/www/html$ sudo vendor/bin/phinx seed:run
Phinx by Rob Morgan - https://phinx.org. version 0.5.4

using config file ./phinx.yml
using config parser yaml
using migration path /var/www/html/db/migrations
using seed path /var/www/html/db/seeds
warning no environment specified, defaulting to: development
using adapter mysql
using database closecall

[InvalidArgumentException]
The seed class "" does not exist

To reiterate, seeds were running fine, upgraded to php 7.0 and now they're not.
Migrations still run completely fine, however.
I've removed all seeds bar one:
<?php

use Phinx\Seed\AbstractSeed;

class CategorySeeder extends AbstractSeed
{
    public function run()
    {
        $data = array(
            array(
                'name' => 'Confined Spaces'
            )
        );
    }
}

To debug with, still gives the same error.

A: Try:
php vendor/bin/phinx seed:run -s CategorySeeder


text:
Q: org.postgresql.util.PSQLException: FATAL: sorry, too many clients already I am trying to connect to a Postgresql database, I am getting the following Error:

Error:org.postgresql.util.PSQLException: FATAL: sorry, too many clients already

What does the error mean and how do I fix it?
My server.properties file is following:
serverPortData=9042
serverPortCommand=9078
trackConnectionURL=jdbc:postgresql://127.0.0.1:5432/vTrack?user=postgres password=postgres
dst=1
DatabaseName=vTrack
ServerName=127.0.0.1
User=postgres
Password=admin
MaxConnections=90
InitialConnections=80
PoolSize=100
MaxPoolSize=100
KeepAliveTime=100
TrackPoolSize=120
TrackMaxPoolSize=120
TrackKeepAliveTime=100
PortNumber=5432
Logging=1

A: No need to increase the MaxConnections & InitialConnections. Just close your connections after after doing your work.  For example if you are creating connection:
try {
     connection = DriverManager.getConnection(
                    "jdbc:postgresql://127.0.0.1/"+dbname,user,pass);

   } catch (SQLException e) {
    e.printStackTrace();
    return;
}

After doing your work close connection:
try {
    connection.commit();
    connection.close();
} catch (SQLException e) {
    e.printStackTrace();
}

A: We don't know what server.properties file is that, we neither know what SimocoPoolSize means (do you?)
Let's guess you are using some custom pool of database connections. Then, I guess the problem is that your pool is configured to open 100 or 120 connections, but you Postgresql server is configured to accept MaxConnections=90 . These seem conflictive settings. Try increasing MaxConnections=120.
But you should first understand your db layer infrastructure, know what pool are you using, if you really need so many open connections in the pool. And, specially, if you are gracefully returning the opened connections to the pool

A: The offending lines are the following:
MaxConnections=90
InitialConnections=80

You can increase the values to allow more connections.

A: You need to close all your connexions for example:
If you make an INSERT INTO statement you need to close the statement and your connexion in this way:
statement.close();
Connexion.close():

And if you make a SELECT statement you need to close the statement, the connexion and the resultset in this way:
resultset.close();
statement.close();
Connexion.close();

I did this and it worked

A: An explanation of the following error:
org.postgresql.util.PSQLException: FATAL: sorry, too many clients already.

Summary:
Your code opened up more than the allowed limit of connections to the postgresql database.  It ran something like this: Connection conn = myconn.Open(); inside a loop, and forgot to run conn.close();.  Just because your class is destroyed and garbage collected does not release the connection to the database.  The quickest fix to this is to make sure you have the following code with whatever class that creates a connection:
protected void finalize() throws Throwable
{
    try { your_connection.close(); }
    catch (SQLException e) {
        e.printStackTrace();
    }
    super.finalize();
}

Place that code in any class where you create a Connection.  Then when your class is garbage collected, your connection will be released.
Run this SQL to see postgresql max connections allowed:
show max_connections;

The default is 100.  PostgreSQL on good hardware can support a few hundred connections at a time.  If you want to have thousands, you should consider using connection pooling software to reduce the connection overhead.
Take a look at exactly who/what/when/where is holding open your connections:
SELECT * FROM pg_stat_activity;

The number of connections currently used is:
SELECT COUNT(*) from pg_stat_activity;

Debugging strategy

*

*You could give different usernames/passwords to the programs that might not be releasing the connections to find out which one it is, and then look in pg_stat_activity to find out which one is not cleaning up after itself.

*Do a full exception stack trace when the connections could not be created and follow the code back up to where you create a new Connection, make sure every code line where you create a connection ends with a connection.close();
How to set the max_connections higher:
max_connections in the postgresql.conf sets the maximum number of concurrent connections to the database server.

*

*First find your postgresql.conf file

*If you don't know where it is, query the database with the sql: SHOW config_file;

*Mine is in: /var/lib/pgsql/data/postgresql.conf

*Login as root and edit that file.

*Search for the string: "max_connections".

*You'll see a line that says max_connections=100.

*Set that number bigger, restart postgresql database.

What's the maximum max_connections?
Use this query:
select min_val, max_val from pg_settings where name='max_connections';

I get the value 8388607 so in theory that's the most you are allowed to have, but then a runaway process can eat up thousands of connections, and surprise, your database is unresponsive until reboot.  If you had a sensible max_connections like 100.  The offending program would be denied a new connection and the database is safu.

A: I had postgres and other apps up in docker. I was facing this problem when more than ten apps connected to postgres database. The solution was to increase postgres max_connection count. This is 100 by default. To increase this value, either find max_connection in the /var/lib/pgsql/data/postgresql.conf file and edit it. Another way is to add and run the docker-compose.yml document as follows.
version: '3'

services:
  taxi-postgresql:
    container_name: my-postgresql
    image: postgres:13.3
    volumes:
      - ./postgres-volume:/var/lib/postgresql/data
    environment:
      - POSTGRES_DB=taxi-postgresql
      - POSTGRES_USER=user
      - POSTGRES_PASSWORD=user
      - POSTGRES_HOST_AUTH_METHOD=trust
    command: postgres -c 'max_connections=1000'
    ports:
      - 127.0.0.1:5432:5432

A: The same error appears in our microservices deployment, and it is solved by increasing the below value in the Postgresql container:

num_init_children


text:
Q: Facebook open graph Identical objects displaying different I've created two custom action->object pairs in my app with identical structure (except each one has a own one custom property).
1) action: 'Rescue' -> object: 'Guardian'
Guardian have custom property 'stage' (string type)
2) action: 'Complete' -> object: 'Level'
Level have custom property 'level_type' (string type)
3) art (images) - both have 200x200 px
But they displays in different layout when i post them, and acts differently.
1) Complete a level story sample:

The description for level not displayed, and not shown on level title hover. The image looks small then for guardian (but they both same size)
2) Rescue a Guardian sample. It looks like it should.

I want 'Complete a level' story looks same as 'Rescue a Guardian'
Please advance, thanks!


text:
Q: Adaptive layout (mobile/desktop) in AngularJS - what is the preferred way to do it (example inside) What is the preferred way to handle adaptive (it's not about responsive) layout in AngularJS? What I need to do is to have a different layout with different shared components (shared directives and controllers) for desktop and mobile. I was thinking about using ui-router, here is what I have now:
index.html (main file):
<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>

    <link rel="stylesheet" href="style.css" />

Mobile

Desktop

desktop.html (wrapper for desktop content):

Desktop

mobile.html (wrapper for mobile content):

Mobile

user.html (shared content):

User name: {{name}}

app.js
var app = angular.module('plunker', ['ui.router']);

app.config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) {
  $stateProvider
    .state('mobile', {
      abstract: true,
      url: '/mobile',
      templateUrl: 'mobile.html'
    })
    .state('mobile.user', {
      url: '/user',
      templateUrl: 'user.html'
    })
    .state('desktop', {
      abstract: true,
      url: '/desktop',
      templateUrl: 'desktop.html'
    })
    .state('desktop.user', {
      url: '/user',
      templateUrl: 'user.html'
    })
}]);

app.controller('UserCtrl', ['$scope', function($scope) {
  $scope.name = 'John';
}]);

Preview & edit:
http://plnkr.co/edit/gRnTJkMa7hTLnffOERMT?p=preview

*

*Is this a preferred way of doing adaptive layout?

*How can I (with this approach):

*

*Add a class to  in index.html based on mobile/desktop choice

*Dynamically load mobile.css or desktop.css

Best Regards,

A: I recently ran into same issues, that's why i landed here looking for some answers. According to my findings, looks like i have two different options:

*

*Use your approach

Facts

*

*Two partial different layouts, because header and footer and some other body tags are still shared. Otherwise you will have to apply data-ui-view on html

*This can be achieved only if you use ui-router, this isn't working with angular default router

*You will load all routes and configs, both from desktop and mobile, because you have a shared config file. This means that somehow you need to load all js files even if user is visiting only mobile version. Otherwise you will have to create a new config file for mobile version and use that one for mobile layout, or dynamic exclude some route based on detected device.

*You will be able to switch from mobile to desktop within your Single Page Application without any reload. Not sure if this is an advantage or not.

Good parts:
You are not going to apply any server logic and your are not going to make a separation of main index.html file served from server. This means that the entire logic lies on the client side.
Bad Parts:
You complicate the logic because you need to make a clear separation between devices and avoid loading unused js files if possible. If you are doing this, basically you are doing another SPA, because desktop version won't be available within your SPA.

*Share the same app but from server based on domain you can serve different html file. For example: yoursite.com will serve index.html which will eventually load desktop version and m.yourside.com will serve mobile.html which will eventually load mobile version.

Facts:

*

*This is more like a hard separation and implies server logic to make a separation

*When switching from mobile and desktop, a reload will take place.

*Now, you can't use the same config or other changes from app.js that refers to your desktop version, so it might need to change some files to not refer anymore to libraries that are used for desktop

*This approach looks more like a new angularJs app within same project (folder structure/ application folder) with same name maybe and lots of shared components and services, but less dependencies and cleaner.

To me, this sounds more like a logic separation consider that you do not need to server all those js files on your mobile version, maybe you won't use all the features of desktop version to mobile version. The only difference i see here at presentation level, different routing maybe, config file, controllers and views. Still same models and share services and big componentes.
In order to make a decision you need to think on both situations each with good and bad parts. Right now i don't know yet which decision to make, i will investigate maybe a day or two.
Good day and good luck.
Andrei

A: var isMobile = window.orientation > -1;
var orientationVariable = isMobile ? 'Mobile' : 'DeskTop';
if (orientationVariable == 'Mobile'){
    $urlRouterProvider.otherwise("/mobile/main");
    $stateProvider
         .state('mobile', {
             abstract: true,
             url: '/mobile',
             controller: 'appCtrl',
             templateUrl: '../app/tpl/mobile-main.html'
         })
      .state('mobile.main', {
            url: '/main',
            controller: 'appCtrl',
            templateUrl: '../app/tpl/app-mobile.html'
        })}else if(orientationVariable == 'DeskTop') {

    $urlRouterProvider.otherwise("/desktop/main");

    $stateProvider.state('desktop', {
            abstract: true,
            url: '/desktop',
            controller: 'appCtrl',
            templateUrl: '../app/tpl/desktop.html',
        })
         .state('desktop.main', {
             url: '/main',
             controller: 'appCtrl',
             templateUrl: '../app/tpl/desktop.main.html',
         })}


text:
Q: CGAL handle to iterator comparison I've read up on forums that CGAL iterator/circulator are type-castable to corresponding handles implicitly. I should be able to use iterators/circulators "as if they were handles". Why then I get an error if I try to compare them? Here is an example:
typedef CGAL::Constrained_Delaunay_triangulation_2<K, Tds> CDT;
typedef CDT::Vertex_handle Vertex_handle;
typedef CDT::Vertex_iterator Vertex_iterator;
...
CDT cdt;
Vertex_handle va = cdt.insert(Point(0,0));
for(Vertex_iterator i=cdt.vertices_begin();...) {
  va=i;  /* Compiles Ok */
  if(va==i) { ... } /* Pages of Error messages */
}

This example is adapted from CGAL Delaunay meshing demo

A: The solution was simple...
for(Vertex_iterator i=cdt.vertices_begin();...)
{
  va=i; /* Implicit dereferencing */
  /* Implicit deref. doesn't work, so use explicit dereferencing */
  if(va==Vertex_handle(i)) { ... }
}