text:
Q: Add Confirm Password field in wp-login.php Password Reset page I'm working on a WordPress website and I'd like to modify the password reset screen /wp-login.php?action=rp. Currently, the password reset screen generates a new password for the user and I want to add a Confirm Password field and make it a required field.
I think I've found the relevant code in the wp-login.php file and it looks like there is a confirm password option but I don't know how to get it to appear.
<form name="resetpassform" id="resetpassform" action="<?php echo esc_url( network_site_url( 'wp-login.php?action=resetpass', 'login_post' ) ); ?>" method="post" autocomplete="off">
<input type="hidden" id="user_login" value="<?php echo esc_attr( $rp_login ); ?>" autocomplete="off" />

        <?php _e( 'New password' ) ?>

            <input type="password" data-reveal="1" data-pw="<?php echo esc_attr( wp_generate_password( 16 ) ); ?>" name="pass1" id="pass1" class="input" size="20" value="" autocomplete="off" aria-describedby="pass-strength-result" />

<?php _e( 'Strength indicator' ); ?>

    <?php _e( 'Confirm new password' ) ?>

    <input type="password" name="pass2" id="pass2" class="input" size="20" value="" autocomplete="off" />

<?php echo wp_get_password_hint(); ?>

<?php
/**
 * Fires following the 'Strength indicator' meter in the user password reset form.
 *
 * @since 3.9.0
 *
 * @param WP_User $user User object of the user whose password is being reset.
 */
do_action( 'resetpass_form', $user );
?>
<input type="hidden" name="rp_key" value="<?php echo esc_attr( $rp_key ); ?>" />

<input type="submit" name="wp-submit" id="wp-submit" class="button button-primary button-large" value="<?php esc_attr_e('Reset Password'); ?>" />

</form>

A: It's tempting to unhide the pass2 input but that's not enough.
In the file /wp-admin/js/user-profile.js the bindPass1() binds it to pass1  that makes writing to it not possible. The pass2 input is then hidden in bindPasswordForm() with $('.user-pass2-wrap').hide();
We can instead add our own input field to validate the password.
First we add it via the resetpass_form action:
add_action( 'resetpass_form', function( $user )
{ ?>

        <?php _e( 'Confirm new password' ) ?>

        <input type="password" name="wpse-pass2" id="wpse-pass2" class="input"
               size="20" value="" autocomplete="off" />

 <?php
} );

Then we use the validate_password_reset hook to validate it:
add_action( 'validate_password_reset', function( $errors )
{
    if ( isset( $_POST['pass1'] ) && $_POST['pass1'] != $_POST['wpse-pass2'] )
        $errors->add( 'password_reset_mismatch', __( 'The passwords do not match.' ) );
} );

This is just using similar code as we have in the wp-login.php file.
This is how it looks in Icelandic, when there's a mismatch:

Plugin
Create the plugin under:
/wp-content/plugins/wpse-confirm-password/wpse-confirm-password.php

and add the following code into that file:
<?php
/**
 * Plugin Name: Confirm New Login Password
 * Plugin URI:  http://wordpress.stackexchange.com/a/262607/26350
 */

add_action( 'resetpass_form', function( $user )
{ ?>

        <?php _e( 'Confirm new password' ) ?>

        <input type="password" name="wpse-pass2" id="wpse-pass2" class="input"
               size="20" value="" autocomplete="off" />

 <?php
} );

add_action( 'validate_password_reset', function( $errors )
{
    if ( isset( $_POST['pass1'] ) && $_POST['pass1'] != $_POST['wpse-pass2'] )
        $errors->add( 'password_reset_mismatch', __( 'The passwords do not match.' ) );
} );

Then activate the plugin from the backend as usual.

A: In addition to the very useful Plugin CODE @birgire added in his answer, it may also be useful to hide the Password Text (as you type in the password field) on the password reset page. Since with this CODE we will have Confirm Password field anyway, it doesn't make sense to show the password as you type.
The reason WordPress core doesn't add a Confirm Password field is mainly because WordPress already shows the password text as you type it. Confirm Password field is the replacement for that feature and can be very useful (more secure) when the user is typing in front of someone else.
So, I suggest you add the following CODE in addition to birgire's Plugin CODE:
add_action( 'login_enqueue_scripts', function ()
{
    if ( ! wp_script_is( 'jquery', 'done' ) ) {
        wp_enqueue_script( 'jquery' );
    }
    // this line basically hides the password text
    wp_add_inline_script( 'jquery-migrate', 'jQuery(document).ready(function(){ jQuery( "#pass1" ).data( "reveal", 0 ); });' );
}, 1 );

Of course, in this case WordPress will not auto generate the password for you, because obviously auto generating password & then hiding the password text doesn't make sense, as users will not be able to see it & type it in the Confirm Password field.
Anyways, if you want to use this, then the final Plugin CODE will become:
<?php
/**
 * Plugin Name: Confirm New Login Password
 * Plugin URI:  https://wordpress.stackexchange.com/a/262851/110572
 */

add_action( 'resetpass_form', function( $user )
{ ?>

        <?php _e( 'Confirm new password' ) ?>

        <input type="password" name="wpse-pass2" id="wpse-pass2" class="input"
               size="20" value="" autocomplete="off" />

 <?php
} );

add_action( 'validate_password_reset', function( $errors )
{
    if ( isset( $_POST['pass1'] ) && $_POST['pass1'] != $_POST['wpse-pass2'] )
        $errors->add( 'password_reset_mismatch', __( 'The passwords do not match.' ) );
} );

add_action( 'login_enqueue_scripts', function ()
{
    if ( ! wp_script_is( 'jquery', 'done' ) ) {
        wp_enqueue_script( 'jquery' );
    }
    wp_add_inline_script( 'jquery-migrate', 'jQuery(document).ready(function(){ jQuery( "#pass1" ).data( "reveal", 0 ); });' );
}, 1 );


text:
Q: firebase C++ sdk on ios firebase::App::Create returns nullptr The below "helpful" messages are logged by the underlying objective-c sdk:
ERROR: Unable to configure Firebase services: Neither name nor options can be nil.
<Notice>: [2017.07.28-02.15.27:187][585] Created Firebase App: 0x0
<Notice>: [Firebase/Core][I-COR000012] Could not locate configuration file: 'GoogleService-Info.plist'.

Of course, I am passing the app name and the options to the C++ api (and none of them are nullptr):
firebase::AppOptions AppOptions;
const char* app_id = ...
AppOptions.set_app_id(app_id);
const char* project_id = ...
AppOptions.set_project_id(project_id);
const char* api_key = ...
AppOptions.set_api_key(api_key);
const char* gcm_sender_id = ...
AppOptions.set_messaging_sender_id(gcm_sender_id);
const char* database_url = ...
AppOptions.set_database_url(database_url);
const char* storage_bucket = ...
AppOptions.set_storage_bucket(storage_bucket);
firebase::App* AppPtr = firebase::App::Create(AppOptions, app_id);
Log("Created Firebase App %p", AppPtr);

A: Hi Firebase engineer here,
We currently do not expose all required options in the firebase::AppOptions interface.  The configuration file (plist on iOS / json on Android) specify a number of configuration values that are required by the API but not specified by developers during App initialization.  Therefore - at the moment - we require the config file (plist on iOS) to be included in the application in order to initialize the underlying Obj-C SDK.
I'm sure you've already look at it, but our setup flow is documented here:
https://firebase.google.com/docs/cpp/setup
Cheers,
Stewart

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to get image from outside web path i have a php script that generates a array with info
Array ( [0] => /mnt/sdb1/files/Copains-16-55-47.jpg
        [1] => /mnt/sdb1/files/Copains-16-55-41.jpg )

now i wanna view this images with
<img src="<?php echo $files[0] ?>"  >
<img src="<?php echo $files[1] ?>"  >

the page don't show the images
in  the source of the page

where is my fault ?? the path /mnt/sdb1/files has the
drwxrwxrwx 2 nobody nogroup 4096 aug 25 16:52 files

A: This is probably a path problem. Most web servers, for security reasons, will never allow any access to files outside of the document path (eg /var/www/html )
You could sym-link /mnt/sdb1/files -> /var/www/html/files and re-write the HTML to
You also may need to tell Apache to allow sym-links.

A: Check URL in your location:
[YOUR_URL_ON_THIS_SCRIPT]/mnt/sdb1/files/Copains-16-55-47.jpg
If you dont show image.
It`s relative path problem.


text:
Q: Getting 403 error when calling Microsoft Forms API I'm trying to use API to list all forms, get all forms' questions and responses, I'm following this
to setup the permissions, I can get the access token from
'https://login.microsoftonline.com/tenantId/oauth2/v2.0/token'
But I'm getting 403 error when using the token to list the forms.
Does anyone know what's going wrong here, or is there any way I can list the forms?
Thanks


text:
Q: How can I create a 4-D plot with points with different sizes for the fourth dimension? Python or Matlab I would like to create a 4-D plot with points with different sizes for the fourth dimension. The first three dimensions are years, regions, and types of land covers. The fourth dimension contains the area for each specific land cover for regions in different years. I want to create a 4-D plot with three axes using years, regions, and types of land covers. I want to show the fourth dimension with points with different sizes corresponding to their area for each specific land cover for different regions and years. Python or Matlab preferred. Thanks in advance!!
I found a few references for creating a 4-D plot with different colors for the fourth dimension, but I want to creat a plot with points with different sizes instead of different colors.


text:
Q: How does OpenGL differentiate binding points in VAO from ones defined with glBindBufferBase? I am writing a particle simulation which uses OpenGL >= 4.3 and came upon a "problem" (or rather the lack of one), which confuses me.
For the compute shader part, I use various GL_SHADER_STORAGE_BUFFERs which are bound to binding points via glBindBufferBase().
One of these GL_SHADER_STORAGE_BUFFERs is also used in the vertex shader to supply normals needed for rendering.
The binding in both the compute and vertex shader GLSL (these are called shaders 1 below) looks like this:
OpenGL part:
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 1, normals_ssbo);

GLSL part:
...
layout(std430, binding = 1) buffer normals_ssbo
{
    vec4 normals[];
};
...

The interesting part is that in a seperate shader program with a different vertex shader (below called shader 2), the binding point 1 is (re-)used like this:
GLSL:
layout(location = 1) in vec4 Normal;

but in this case, the normals come from a different buffer object and the binding is done using a VAO, like this:
OpenGL:
glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, 0, 0);

As you can see, the binding point and the layout of the data (both are vec4) are the same, but the actual buffer objects differ.
Now to my questions:
Why does the VAO of shader 2, which is created and used after setting up shaders 1 (which use glBindBufferBase for binding), seamingly overwrite (?) the binding point, but shaders 1 still remember the SSBO binding and work fine without calling glBindBufferBase again before using them?
How does OpenGL know which of those two buffer objects the binding point (which in both cases is 1) should use?  Are binding points created via VAO and glBindBufferBase simply completely seperate things?   If that's the case, why does something like this NOT work:
layout(std430, binding = 1) buffer normals_ssbo
{
    vec4 normals[];
};
layout(location = 1) in vec4 Normal;

A:
Are binding points created via VAO and glBindBufferBase simply completely seperate things?

Yes, they are. That's why they're set by two different functions.

If that's the case, why does something like this NOT work:

Two possibilities present themselves. You implemented it incorrectly on the rendering side, or your driver has a bug. Which is which cannot be determined without seeing your actual code.


text:
Q: How to disable the error log file in cakephp here I try to disable the error log and debug log files, even when the core is enabled.
I tried the following code.
Configure::write('Error', array(
  'handler' => 'ErrorHandler::handleError',
  'level' => 0,
  'trace' => false
));

but it only disables debug log.
is there any other way to disable error log and debug log file?

A: try adding
another parameter as 'log' and set it to true
Or you can use constant LOG_DEBUG in your core.php and set it to true.
The details of which are given here http://book.cakephp.org/2.0/en/development/configuration.html


text:
Q: How to retrieve Performance MAX campaigns Google Ads into Google Big Query I am using a third-party tool that use the Adwords Reporting https://developers.google.com/adwords/api/docs/appendix/reports/all-reports to retrieve data.
At the moment all the "Performance Max" campaigns are lost from the Adwords Reporting and I need to retrieve them to include their costs.
With the migration from Adwords to Ads, also, I need to find a solution before April 2022.
I only need to move that data into my Google BigQuery project.
At the moment the solution using the BigQuery Data Transfer is NOT OK because use the same v201809 reporting of Adwords ( https://cloud.google.com/bigquery-transfer/docs/adwords-transfer?hl=en-GB )
.
Also the Google Ads Script don't support Google Ads but only report name of Adwords v201809 ( https://developers.google.com/google-ads/scripts/docs/solutions/bigquery-exporter )
Do you have a suggestion to help me?
Thanks

A: You have several options and the solutions depends on level in which you want to report data. On campaign level you can fetch data about impressions, clicks and cost from Google Analytics API if you have connected ads and analytics accounts.
If you want more granular information you can create report in google ads and schedule downloads of this report, for example everyday. Only problem is that performance max campaigns combine multiple types of ads, so on some dimensions you can get no data, for example campaign spend 50 eur yesterday, but in report with product id this campaign spent only 25. I combine this two sources, it isn't ideal, but better than total blindness now days.

A: Remember: Do not select an AdGroup when querying Performance Max campaigns, as no campaigns will be returned.
https://developers.google.com/google-ads/api/docs/performance-max/reporting
Solution --> I use two different GAQL :

*

*one FROM ad_group for the details needed with the ad_groups resource

*another FROM campaign without any ad_group in the SELECT


text:
Q: Find common element in a column by aggregating another column I need some help in R. I want to find which brand appears in every ID. My data contains three tab delimited fields, lets call them ID (which identify a person), time, brand:
ID time brand
01 1111 BMW
01 1112 BMW
01 1113 Audi
01 1114 Mercedes
02 1115 Audi
02 1115 Cadillac
02 1116 BMW
03 1117 Acura
03 1117 Audi
03 1117 BMW
03 1118 Mercedes
.......

According to the data, therefore, the brands that is common to all IDs are BMW and Audi. Time field is not always unique. However since I have many more records, I can't be sure if there is a common brand to all the IDs. In which case I want to get a rank of what brand appears in most ID.
I have many unique IDs and brands, so I can't use the explanations here
How to find common elements from multiple vectors?
I would like to know how to do it in R. Thank you.

A: data = read.table(text = "ID time brand
        01 1111 BMW
        01 1112 BMW
        01 1113 Audi
        01 1114 Mercedes
        02 1115 Audi
        02 1115 Cadillac
        02 1116 BMW
        03 1117 Acura
        03 1117 Audi
        03 1117 BMW
        03 1118 Mercedes", header = TRUE)

require("data.table")
DT <- as.data.table(data)

# Count instances of brand
DT[, count := .N, by="brand"]

# Keep the brand that appears more times by ID
result = DT[, list(max_count = max(count), time), by="brand,ID"]
result

# Drop max_count column by reference in case you want to
set(result, j=c("max_count"), value=NULL)

print(result)
#       brand ID time
# 1:      BMW  1 1111
# 2:      BMW  1 1112
# 3:     Audi  1 1113
# 4: Mercedes  1 1114
# 5:     Audi  2 1115
# 6: Cadillac  2 1115
# 7:      BMW  2 1116
# 8:    Acura  3 1117
# 9:     Audi  3 1117
# 10:      BMW  3 1117
# 11: Mercedes  3 1118

A: You could use a table and find those brands that appear in each ID.
> tab <- table(dat$ID, dat$brand)
> names(which(apply(tab, 2, function(x) !any(x == 0))))
## [1] "Audi" "BMW"

For those brands that do not appear in each ID,
> A <- apply(tab, 2, sum)
> A[A < nrow(tab)]
## Acura Cadillac Mercedes
##     1        1        2

And to sort them most to least
> sort(A[A < nrow(tab)], decreasing = TRUE)
## Mercedes    Acura Cadillac
##        2        1        1


text: Q: Using Intel's App Framework with Android 2.3.3 This is not a question related to a specific issue. I want to know if anyone has tried writing an Android Cordova application with Intel's App Framework. This is because I tried writing an application and it fails in certain occasions. But when I write for higher versions of Android like 3.0 it works. It is strange. I want to know why it happens like that. Is it a known issue? Will someone help we with this? (Any explanation regarding this)


text:
Q: print to file bash usernames and account status I would like to create a script that would loop through /etc/passwd and print all usernames and account status.
while read line; do
print username to field1 in user.txt
print status active/disabled in field2 in user.txt
done</etc/passwd

A: while IFS=: read user status placeholder; do
    [[ $status == x ]] && active=active || active=inactive
    echo "$user $active" >> user.txt
done < /etc/passwd
cat user.txt

But if the second column is x the user have an encrypted password, that not stands for active or inactive...
See
man 5 passwd

You should look
account expiration date

in
man 5 shadow


text:
Q: jquery validation for asp.net web forms when javascript in browser is disable? I use Jquery validation in my project ( asp.net web forms)  but if user disable java script in browser , server side validation still work ? or i must use validation controls (asp.net) ?
how do i do for secure validation with Jquery when java script is disable in browser ?

A: Jquery is written in JavaScript. So if JavaScript is disabled , Jquery validation or any other Jquery functionality won't work.
You can use  block to convey message to user to enbale Javascript in browser if it is disabled.
 block runs if Javascript is disabled.
<nocript>

Please enable Javascript

A: You seem to be a little confused about a couple of concepts here. As m hasan said, JQuery uses JavaScript (is written in if you prefer) which is a client scripting language, and as such, can be disabled on the client's machine (browser).
Server side validation works independently of the client, so the user disabling technology on their system should have no bearing on whether server side validation functions correctly or not.
If a user disables JavaScript in their browser, then you can't use JQuery. One option is to use the  blocks, as suggested by m hasan above (or below, depending on where this comment ends up).
From a security point of view, you should never rely solely on client side validation tools (such as JavaScript / JQuery). They should be seen more as aids to the user interface. All critical validation should always take place on the server.


text:
Q: Installing C++ on eclipse under one condition What if you have the Eclipse IDE already installed on your computer, but the condition is that you have the JAVA eclipse installed but you also want to add the C++ Eclipse feature to your existing Eclipse IDE?

A: In Eclipse, select:
    Help -> Install new software
In the Install dialog, under "Work with:" select Mars - http://download.eclipse.org/release/mars (or whatever Eclipse version you're on)
Then select:
    Programming Languages -> C/C++ Development Tools
Select "Next >" and continue through the remaining questions. Restart Eclipse and you should have CDT installed.


text:
Q: Distribution of difference between independent Poisson random variables I'm working on a problem in which the random variable is the difference between two random variables.  We know from math that the mean will be the difference of the means, and that the variance will be the sum of the variances.  I know that for a Poisson distributions the sum of two independent variables will be another Poisson distribution with mean the sum of the means, and this will be identical to the variance.
Therefore I can treat the difference between Poisson distributed random variables the same way. However, a Poisson distribution has only positive values, and I know that the difference between the random variables will have some value that turns out to be negative. What am I missing?

A: Here are two Poisson distributions:

Here is the associated Skellam Distribution (which is the solution to your problem):

Indeed, the distribution is defined for negative values.  Moreover, the mean of the Skellam distribution is the difference of the means of the two Poisson distributions (even if that value is negative) and the variance of the Skellam distribution is the (positive) sum of the variances of the Poisson distributions.


text:
Q: Uploading File in AngularJS without submit button What is the best practices in angularjs when submitting file without a submit button.
Here is my sample code.
<form method="post" enctype="multipart/form-data" action="">
   <input type="file" name="file">
</form>

I already tried using onchange, very useful also but what i want is after selecting a file it will make an ajax call (without submit button).

A: i have used ngpload module for it.
ngpload
please refer the document from the link this will definitely help you a lot


text:
Q: Mark method as not testable in ABAP Can I mark methods as not testable for ABAP Unit tests so that the method is marked as fully tested in the ABAP Unit test coverage explorer?

A: Still, in my understanding there are methods which cannot be easily unit tested.
For example it could be a method which uses some BAPI to change the statuses of the objects (f.ex. change status of maintenence order) and requires the existence of such object in the DB. IT gets even worse when this method is just a public method that contains couple of private methods calling different BAPIs. In this case one would have to mock the entire business process (creating objects, setting statuses etc.) which would mean that ultimatelly one would have to write tests to tests ;) )


text:
Q: Ionic 2 Android Build Prod Warning while verifying jar signing I am getting an error while building my Ionic application, it occurs on a new app (which I started from the scratch couple of days ago). None of my old apps have this issue. The issue does not occur in any of older apps i.e., apps that are 4-5 months old.

WARNING: META-INF/android.arch.lifecycle_runtime.version not protected by signature. Unauthorized modifications to this JAR entry
     will not be detected. Delete or move the entry outside of META-INF/.

and it continues for 4-5 more files.
My environment info:
cli packages: (/usr/local/lib/node_modules)
@ionic/cli-utils  : 1.19.0
ionic (Ionic CLI) : 3.19.0

global packages:
cordova (Cordova CLI) : 7.1.0

local packages:
@ionic/app-scripts : 3.1.6
Cordova Platforms  : android 6.3.0 ios 4.5.4
Ionic Framework    : ionic-angular 3.9.2

System:
Node  : v8.9.1
npm   : 5.6.0
OS    : macOS High Sierra
Xcode : Xcode 9.2 Build version 9C40b

Environment Variables:
ANDROID_HOME : not set

Misc:
backend : pro

Is this of any security concern or am I missing something?
Thanks in advance.

A: [TEMP FIX]: As all the file contains are version nos, for now I have removed those META files from my final apk before verification e.g., used

sudo zip -d apkfilename.apk META-INF/android.arch.lifecycle_runtime

did the same for the rest of the six files!


text:
Q: Как изменить сортировку коментариев У меня есть код вывода комментариев (отзывов) он выводит список всех комментариев с пагинацией но выводит так что самые новые комментарии находятся на последней странице. Как поменять сортировку что бы самые новые были на первой странице?
Я пробывал сюда wp_list_comments(['reply_text' => 'Ответить', 'callback' => 'raba_comment', 'avatar_size' => 32,]); добавить 'orderby' => 'comment_date' но ничего не изменилось(
<?php
//http://verstaka.net/wordpress/shablon-kommentariev-wordpress.html
    if (comments_open()) {
        if (get_comments_number() == 0) {
            echo 'Еще нет отзывов и комментариев, будьте первым!';
        } else {
            echo '
';
            wp_list_comments(['reply_text' => 'Ответить', 'callback' => 'raba_comment', 'avatar_size' => 32,]);
            echo '
';
        }
        //пагинация комментариев
        echo  get_the_comments_pagination(rabaPaginationCommentsArgs());
        //форма отправки
        comment_form(comment_form_args());
    } else {
        echo '
Обсуждения закрыты для данной записи
';
    }
    ?>

    <?php if ( post_password_required() )
{ return; }
?>


text:
Q: How can I create the same thing using recyclerview or list view in android studio? The list I wanna create
I wanna create the same list and when I click it it expands and shows more content
I tried recyclerview with cardview as item or row but didn't work so can I create recyclerview or listview like the same as the Image?
(Note)
I'm talk about the list not the tabs
any ideas please :)
The list I wanna create

A: Create a Viewpager with tablayout, create fragments and then connect them to your viewpager


text:
Q: How secure is the https connection if the client not passes certificate We have a web server running on linux machine where we configured 'SSLVerifyClient' as 'require' in ssl.conf file.
Does this needs client who is utilizing the service from web browser(like firefox or chrome) needs a certificate.
If yes, then it is not possible to distribute client certificate to every user as there can be some thousands of users, how to overcome this problem.
If no, then how the data passed over network is secure? I know that certificate helps in encrypting data so that no one who don't have certificate can read data.
Please help me in clarifying my doubts

A: If you don't use client certificate, the https connection is still safe:

*

*Only the client and the server can read/write the content

*The identity of the server is assured by a certificate authority

Client certificate only give you client authentication in the beginning of the connection.  To encrypt the data, the public key of the server is used in the beginning (See public key encryption).
If you identify the client with cookies set after login/password submit, it is still safe: you have identify the client.

A: When SSLVerifyClient is set to require, the client MUST pass a client certificate. You would generate these via OpenSSL, and sign them with a certificate authority that you install via SSLCACertificateFile.
How you distribute those certificates is an issue you'll have to solve yourself.


text:
Q: Mongoose: Array attribute inside a collection is returned empty by Model.find() even though it has data in the database I'm trying to create a test query for one of my databases using Mongoose. For this, I have created some data in a JSON file and have imported it into MongoDB. Here's the data:
{
    "name": "SSS",
    "discordid": "61231237",
    "prefix": "!",
    "servers": [
        {
            "name": "DMG TTT",
            "type": "garrysmod",
            "host": "66.151.244.2",
            "vchannelid": "616413849679036530",
            "tchannelid": "616414488916393984"
        },
        {
            "name": "DMG Potpourri",
            "type": "garrysmod",
            "host": "192.223.27.68",
            "vchannelid": "616415352271667232",
            "tchannelid": "616415277713981441"
        }
    ]
}

As you can see, the servers attribute is an array that has 2 objects inside it. However, when I query the database using Mongoose using this code:
Guild.find({ name: "SSS" }).exec((err, data) => { console.log(JSON.stringify(data)) })

The following is returned in console:
[{"servers":[],"_id":"5d675d80dd57df7e7d88e491","name":"SSS","discordid":"61231237","prefix":"!"}]

Notice that the servers array is returned as empty, even though it has data inside of it. Looking through some solutions, it was suggested that I try JSON.stringify, but it made no difference with or without it. Why does this happen?
EDIT: Here is the model file:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;

//Discord Guild schema
const guildSchema = Schema({
    name: String,
    discordid: String,
    prefix: String,
    servers: [{
        name: String,
        type: String,
        host: String,
        vchannelid: String,
        tchannelid: String
    }]
})

module.exports = mongoose.model("Guild", guildSchema)

and here is the same query done thought the MongoDB CLI:
> db.guilds.find()
{ "_id" : ObjectId("5d675d80dd57df7e7d88e491"), "name" : "SSS", "discordid" : "61231237", "prefix" : "!", "servers" : [ { "name" : "DMG TTT", "type" : "garrysmod", "host" : "66.151.244.2", "vchannelid" : "616413849679036530", "tchannelid" : "616414488916393984" }, { "name" : "DMG Potpourri", "type" : "garrysmod", "host" : "192.223.27.68", "vchannelid" : "616415352271667232", "tchannelid" : "616415277713981441" } ] }

A: Try the following approach ,
Your guildModel ,
const guildSchema = Schema({
    name: {type: String},
    discordid: {type: String},
    prefix: {type: String},
    servers: [{
        name: {type: String},
        type: {type: String},
        host: {type: String},
        vchannelid: {type: String},
        tchannelid: {type: String}
    }]
})

First save the JSON object in your database as below-
Your Controller File , Make sure the format is as same as below .
var guildModel = require('../models/guild.model');

req.body =  [{
        "name": "SSS",
        "discordid": "61231237",
        "prefix": "!",
        "servers": [
        {
            "name": "DMG TTT",
            "type": "garrysmod",
            "host": "66.151.244.2",
            "vchannelid": "616413849679036530",
            "tchannelid": "616414488916393984"
        },
        {
            "name": "DMG Potpourri",
            "type": "garrysmod",
            "host": "192.223.27.68",
            "vchannelid": "616415352271667232",
            "tchannelid": "616415277713981441"
        }
        ],

    }];
    var guild = new guildModel(req.body[0]);
    guild.save((err , userSaved)=>{
                if(err){
                    res.status(400).send(err);
                }
                else{
                    console.log("userSaved =========> " , userSaved);
                    res.json({user: userSaved});
                }
            });

then apply the below code to retrieve the data from the database .
guildModel.find({name : "SSS"})
        .exec((err , found )=>{
            if (err){
                res.send(err)
        }else{
                res.send(found);
            }
         });


text:
Q: Get the clicked list item with a click event on the ul tag (parent) I have this:

Home

Credits

About

and I want to get the clicked item list href value with an event listener on the ul tag, something like this:
    $('.tabs').click(function () {
        let getClickedItem =
    })

A: You can access the target property on the event object:

$('.tabs').click((event) => {
  console.log(event.target);
});

Home

Credits

About

This will however give the element that was clicked which in this case would most definitelly be the anchor tags.
You say you want the list item that is clicked. You could just attach the event listener directly to those:

$('.tabs li').click(function () {
  console.log('click', this);
});

Home

Credits

About

A: Put this code and out console, this should be thing you are looking for:
$(function(){
            $(".tabs li a").click(function(e){
                e.preventDefault();
                console.log($(this).attr('href'));
            })
        })


text:
Q: Matplotlib animation.save only works when called from __main__ I have written a function which in principle does this:
def make_animation():
    nframes = 30
    arr = np.random.rand(30, 2, 2) * 255
    data = xr.DataArray(arr, [('time', np.arange(30)), ('x', [1, 2]), ('y', [0, 1])])
    fig, ax = plt.subplots()
    quad = data.isel(time=0).plot.imshow(origin='lower',
                                     vmin=np.nanmin(data.values),
                                     vmax=np.nanmax(data.values))

    def update(i):
        ti = data.isel(time=i)
        quad.set_array(ti.data)
        return quad

    anim = animation.FuncAnimation(fig, update,
                               frames=len(data.time), blit=False,
                               interval=50)
    anim.save('some_path', writer='ffmpeg', fps=2)

It works like a charm if I call this from __main__ for any number of nframes. However, if I import this function into another module it writes the output file, but doesn't "fill" it when frames is too high. (Too high already means 50 frames, or so). This is the last log message:
 matplotlib.animation: MovieWriter.grab_frame: Grabbing frame.

I've tried to set the save_count parameter to the length of the time axis already, but it didn't change anything. Any idea how to fix this?


text:
Q: Ansible hostvars undefined I have a very simple play which saves vars and looks them up in hostvars.
- name: Set hostvars
  hosts: localhost
  vars:
    var_one: "I am a"
    var_two: "test"
  tasks:
    - debug: var=hostvars['localhost']['var_one']
    - debug: var=hostvars['localhost']['var_two']

However, when I run this play the vars aren't defined:
PLAY [Set hostvars] ************************************************************

TASK [setup] *******************************************************************
ok: [localhost]

TASK [debug] *******************************************************************
ok: [localhost] => {
    "hostvars['localhost']['var_one']": "VARIABLE IS NOT DEFINED!"
}

TASK [debug] *******************************************************************
ok: [localhost] => {
    "hostvars['localhost']['var_two']": "VARIABLE IS NOT DEFINED!"
}

How can I save these vars in hostvars?

A: You can set host facts runtime using set_fact module:
---
- name: Set hostvars
  hosts: localhost
  tasks:
    - set_fact: var_one="I am a"
    - set_fact: var_two="test"
    - debug: var=hostvars['localhost']['var_one']
    - debug: var=hostvars['localhost']['var_two']

Quoting the documentation:
These variables will survive between plays during an Ansible run, but will not be saved across executions even if you use a fact cache.

A: This is where the difference between facts (variables bound to Ansible target hosts) and regular variables can be seen.
Variables are internally stored in vars structure, so you can access them with:
tasks:
  - debug: var=vars['var_one']
  - debug: var=vars['var_two']

Facts, on the other hand are stored in hostvars.

In either case, unless you were referring to a variable name with a dynamic name, or a fact bound to another host than the one executing the task, you can simply use the variable/fact name by using its name:
tasks:
  - debug: var=var_one
  - debug: var=var_two

A: Try using

msg=

instead of var=. As per help of debug module
var - A variable name to debug. Mutually exclusive with the 'msg' option.

- name: Set hostvars
  hosts: localhost
  vars:
    var_one: I am a
    var_two: est
  tasks:
    - debug: msg=hostvars['localhost']['var_one']
    - debug: msg=hostvars['localhost']['var_two']
...

PLAY [Set hostvars] ************************************************************

TASK [setup] *******************************************************************
ok: [localhost]

TASK [debug] *******************************************************************
ok: [localhost] => {
    "msg": "hostvars['localhost']['var_one']"
}

TASK [debug] *******************************************************************
ok: [localhost] => {
    "msg": "hostvars['localhost']['var_two']"
}

PLAY RECAP *********************************************************************
localhost                  : ok=3    changed=0    unreachable=0    failed=0


text:
Q: DevExpress chart control I want to replace my Winforms chart control with DevExpress chart control so i moved the code to my new chart:
DevExpress.XtraCharts.Series se = new DevExpress.XtraCharts.Series();
chartControl1.Series.Add(se);

This is my timer that read real time data:
private void chartTimer_Tick(object sender, EventArgs e)
        {
                //Old code

                //if (seriesBps.Points.Count() > 300)
                    //seriesBps.Points.RemoveAt(0);
                //seriesBps.Points.Add(wf.BitsPerSecond * 0.000001);

                DevExpress.XtraCharts.SeriesPoint point = new DevExpress.XtraCharts.SeriesPoint(wf.BitsPerSecond * 0.000001);
                se.Points.Add(point);

                 //Old cod
                //chart1.ResetAutoValues();
            }
        }

My problem is that i cannot see any points over my chart control graph although i can see that this chart moved the x Axis valus.

A: In Devexpress when you are plotting you need to provide 2 values per SeriesPoint your code should look like this :
assuming ChartControl1 is your control and se is your series name from chart
private void chartTimer_Tick(object sender, EventArgs e)
{
  ChartControl1.Series["SeriesNameHere"].Points.Add(new SeriesPoint("AnyOtherValueHere",wf.BitsPerSecond * 0.000001)) ;
}

Replace AnyOtherValueHere with any thing you like to see in the SwiftChart, this way your chart will view 2 values on 2 axis each time you tick event is triggerd


text:
Q: Android studio okhttp and Retrofit failed gradle execution Seems I added this line
compile 'com.squareup.okhttp:okhttp:2.4.0'

I got this error: Failed to complete gradle execution
I allready have retrofit installed.
Android Studio 1.2.2
Any idea?

A: Maybe it's the missing space after compile?
Try it like this: compile 'com.squareup.okhttp:okhttp:2.4.0'

A: From OkHttp site

You'll also need Okio, which OkHttp uses for fast I/O and resizable buffers. Download the latest JAR.


text:
Q: Call ToJson Method For T Class I'm new on Dart & Flutter. I have to post data to internet.
I would to use a common class method for this.
In other hand i need to convert my object to JSON.
But how can do it with T class or is there other elegant way?
Could you give me an opinion?
Future<ReturnModel> postData<T>(T model) async {
  final response = await http.post(
      Uri.parse('https://localhost/SomeAddress'),
      headers: <String, String>{
        'Content-Type': 'application/json; charset=UTF-8',
      },

      //**
      IDE gives error here of course.
      Because it is not know type of T.
      How can i get over this?
      **//
      body: jsonEncode(model.toJson())
  );

  if (response.statusCode == StatusCode.OK) {
    return ReturnModel.fromJson(jsonDecode(response.body));
  } else {
    throw Exception('Bir hata oluştu.');
  }
}

A: body: jsonEncode(((model) as dynamic).toJson())


text:
Q: Displaying Max, Min, Avg across bar chart Tableau I have a bar chart with X axis as discrete date value and Y axis as number of records.
eg: x axis (Filtered Date)- 1st Oct, 2nd Oct, 3rd Oct etc
    y axis (Number of Records)- 30, 4, 3 etc
Now, I have to create a table to get Max, Min and Avg. Value of the 'Number of Record'.
I have written a Calculated Field as MAX([Number of Records]) to get the maximum of Number of Records in this case 30 but I always get a value of 1.
How do I define the values to get max, min and avg. ?
Thanks,

A: Number of Records is an automatically calculated field that tableau generates when importing a datasource.  You can right click on it and see the definition of the calculation: 1.
As you currently have your field defined, tableau will look for the maximum value of the column.  It will always be 1 because that is the only value in that field for every record.
It sounds like you are actually trying to calculate the maxiuum of the sum of the number of records for your aggregation level (in your case date).  You should be able to easily accomplish this using Level of Detail (LOD) expressions, or table calculations.  Something like the following:
WINDOW_MAX(SUM([Number of Records]))


text:
Q: Keep Input Date Jquery I am choosing a date with submit. What I want to do is keeping this date on the form when I am redirected to another web page.
https://jsfiddle.net/92gd7v26/
I tried this but it's not working:
$name7=$_SESSION['date'];
$name8=$_SESSION['date2'];
$name9=$_SESSION['date3'];

<script>// <![CDATA[
$( function() { $( "#datepicker" ).datepicker(); $( "#datepicker2" ).datepicker(); $( "#datepicker3" ).datepicker();

    $('#datepicker').datepicker({
        inline: true,
        showOtherMonths: true,

    })
    $("#datepicker").datepicker("setDate",   $name7);
    $("#datepicker2").datepicker("setDate",  $name8);
    $("#datepicker3").datepicker("setDate",  $name9);
} );
// ]]></script>

I don't know what's wrong. I am able to get the "date" values from $name7,$name8 and $name9. But when I try to put them on .datepicker("setDate") I am not getting the values I sent..


text:
Q: Website logos for twitter, youtube etc I am trying to modify some website code that I have got from a template. In the css file i have a number of lines of code which look as follows - and i assume these are the logos to be referenced;
/*********************************************************************************/
/* Icons                                                                         */
/* Powered by Font Awesome by Dave Gandy | http://fontawesome.io                 */
/* Licensed under the SIL OFL 1.1 (font), MIT (CSS)                              */
/*********************************************************************************/
.fa {
    text-decoration: none;
}

    .fa.solo {
    }

        .fa.solo span {
            display: none;
        }

    .fa:before {
        display:inline-block;
        font-family: FontAwesome;
        font-size: 1.25em;
        text-decoration: none;
        font-style: normal;
        font-weight: normal;
        line-height: 1;
        -webkit-font-smoothing:antialiased;
        -moz-osx-font-smoothing:grayscale;
    }

    .fa-lg{font-size:1.3333333333333333em;line-height:.75em;vertical-align:-15%}
    .fa-2x{font-size:2em}
    .fa-3x{font-size:3em}
    .fa-4x{font-size:4em}
    .fa-5x{font-size:5em}
    .fa-apple:before{content:"\f179"}
    .fa-windows:before{content:"\f17a"}
    .fa-android:before{content:"\f17b"}
    .fa-linux:before{content:"\f17c"}
    .fa-dribbble:before{content:"\f17d"}
    .fa-skype:before{content:"\f17e"}
    .fa-foursquare:before{content:"\f180"}
    .fa-trello:before{content:"\f181"}
    .fa-female:before{content:"\f182"}
    .fa-male:before{content:"\f183"}
    .fa-gittip:before{content:"\f184"}
    .fa-sun-o:before{content:"\f185"}
    .fa-moon-o:before{content:"\f186"}
    .fa-archive:before{content:"\f187"}
    .fa-bug:before{content:"\f188"}

The issue i am having is that the logos do not appear on the webpage. Does the slash indicate that in the current directory there should be image f181,f182 and so on or do these values represent something else.
Thanks for your help.

A: I got the answer. These codes are from font awesome family. Down load the font awesome and link to your webpage. It will work for you.
Download Font Awesome


text:
Q: Can I use the LEFT (string) operator in ExecuteSQL()? In QGIS I can use the LEFT operator on a dataset like this:
LEFT( "Name2",3) ='031'

What is the syntax for using this expression with ogr in python? Isn't this the right syntax?
a=water.ExecuteSQL("select left('Name2',3)='031' from 'benlux_w_min' ")
'ERROR 1: SQL Expression Parsing Error: syntax error`

A simple where clause works just fine
In [53]: a=water.ExecuteSQL("select * from 'benlux_w_min' where 'Name2'='0310027' ")

In [54]: a.GetFeatureCount()
Out[54]: 367

A: In this case the query builder is something of a misnomer.  The interface you are looking for is QgsExpression.  ExecuteSQL will apply the sql expression through the layer providers SQL interface, such as for use with MSSQL or PostgreSQL.  I don't think TAB files support that.
QgsExpression is a simplified SQL-like interface for doing WHERE clauses on layers, and is well supported (though it doesn't support all SQL functions).
You can see a full example in the QGIS Python cookbook here.

A: Consider that your SQL query should be something like this:
a=water.ExecuteSQL("SELECT LEFT(Name2,3) AS foo FROM benlux_w_min WHERE foo='031'")

Then, if the LEFT function doesn't work and the provider is OGR, you can try also with SUBSTR:
a=water.ExecuteSQL("SELECT SUBSTR(Name2,1,3) AS foo FROM benlux_w_min WHERE foo='031'")

following the OGR SQL.


text:
Q: visual studio 2012 publishing issues I use visual studio to develop my website which works locally with user login. When I publish the website to a server and try to login I get this issue below: I cannot get past the login page. Anyone can please shed some light into what is going on?
[Win32Exception (0x80004005): The system cannot find the file specified]

[SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 52 - Unable to locate a Local Database Runtime installation. Verify that SQL Server Express is properly installed and that the Local Database Runtime feature is enabled.)]
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) +6749670
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +815
System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity, Boolean withFailover) +6775368
System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover) +219
System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout) +6777796
System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance) +6778255
System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData) +878
System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions) +1162
System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions) +72
System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) +6781425
System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) +103
System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection) +2105
System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection) +116
System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection) +1089
System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions) +6785863
System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1 retry) +233
System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry) +278
System.Data.SqlClient.SqlConnection.Open() +239
System.Data.SqlClient.SqlProviderServices.UsingConnection(SqlConnection sqlConnection, Action`1 act) +134
System.Data.SqlClient.SqlProviderServices.UsingMasterConnection(SqlConnection sqlConnection, Action`1 act) +3778055
System.Data.SqlClient.SqlProviderServices.GetDbProviderManifestToken(DbConnection connection) +10930518
System.Data.Common.DbProviderServices.GetProviderManifestToken(DbConnection connection) +91

[ProviderIncompatibleException: The provider did not return a ProviderManifestToken string.]
System.Data.Common.DbProviderServices.GetProviderManifestToken(DbConnection connection) +10930589
System.Web.Providers.ModelHelper.CreateMetadataWorkspace(String providerName, DbConnection connection, String csdl, String ssdl, String msl) +168
System.Web.Providers.ModelHelper.CreateEntityConnection(ConnectionStringSettings setting, String csdl, String ssdl, String msl) +298
System.Web.Providers.ModelHelper.CreateMembershipEntities(ConnectionStringSettings setting) +51
System.Web.Providers.DefaultMembershipProvider.GetPasswordWithFormat(String userName, Boolean updateLastLoginActivityDate, Int32& status, String& password, Int32& format, String& salt, Int32& failedPasswordAttemptCount, Int32& failedPasswordAnswerAttemptCount, Boolean& isApproved, DateTime& lastLoginDate, DateTime& lastActivityDate) +211
System.Web.Providers.DefaultMembershipProvider.CheckPassword(String userName, String password, Boolean updateLastActivityDate, Boolean failIfNotApproved, String& salt, Int32& passwordFormat) +182
System.Web.Providers.DefaultMembershipProvider.ValidateUser(String username, String password) +198
System.Web.UI.WebControls.Login.AuthenticateUsingMembershipProvider(AuthenticateEventArgs e) +105
System.Web.UI.WebControls.Login.AttemptLogin() +160
System.Web.UI.WebControls.Login.OnBubbleEvent(Object source, EventArgs e) +105
System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args) +84
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3804

A: The error is pretty self explanatory.
"error: 52 - Unable to locate a Local Database Runtime installation. Verify that SQL Server Express is properly installed and that the Local Database Runtime feature is enabled."
The connection string you are using is only valid for your development environment. Depending on how your production environment is setup you have to either make sure your local development environment matches that or adjust your connection string for your production environment accordingly.


text:
Q: Call a function only once while serial data evaluates to a specific number So my logic is kind of butts. But here's what I'm going for: I have a stream of serial data and some booleans to track. What I really want to do is: "While serial data is equal to [X], call a specific function only once."
Basically: Get incoming serial data to act a bit like buttons. I always falter on where to set the flag back to false for the individual arguments. Right now I just have a total reset, if nothing is coming in, reset it all.
Any help on where to set the booleans back to false for the individual arguments would be appreciated. I mostly just can't see it.
Eventually this thing will do something along the lines of "while serial is 2, get a random point on the screen, and draw a circle" But for now, just solving my bad logic.
import processing.serial.*;
Serial myPort;  // Create object from Serial class
int val;

boolean wasTwo = false;
boolean wasFour = false;
boolean wasSeven = false;

// /dev/cu.LightBlue-Bean
void setup()
{
    size(800, 800);
    printArray(Serial.list());
    String portName = Serial.list()[1];// /dev/cu.LightBlue-Bean
    myPort = new Serial(this, portName, 9600);
}

void draw(){
    background(0);

    if ( myPort.available() > 0) {  // If data is available,
        val = myPort.read();         // read it and store it in val
    }

    if(val != 0){

        if(!wasTwo && val == 2){
            print("2");
            wasTwo = true;
        }

        if(!wasFour && val == 4){
            print("4");
            wasFour = true;
        }

        if(!wasSeven && val == 7){
            print("7");
            wasSeven = true;
        }

    } else {
        wasTwo = false;
        wasFour = false;
        wasSeven = false;
    }

    if(wasTwo){
        red();
    }

    if(wasFour){
        green();
    }

    if(wasSeven){
        blue();
    }

}

void red(){
    fill(255,0,0);
    ellipse(200,200, 200, 200);

}

void green(){
    fill(0,200,0);
    ellipse(400,400, 200, 200);

}

void blue(){
    fill(0,0,255);
    ellipse(600,600, 200, 200);

}

A: You need to keep track of whether you've already seen the target value. You can do this with a boolean variable.
Then when you read the serial data, you check the value. If it's not the target value, then you simply set the boolean to false. If it is the target value, then you do another check: have you already seen the target value? If not, call your function and set the boolean to true. If so, then don't call the function.
Putting it all together, it might look like this:
boolean sawTarget = false;
int targetValue = 2;

void draw(){

   if ( myPort.available() > 0) {
      int serialValue = myPort.read();

      if(serialValue == targetValue){
          if(!sawTarget){
              doSomething();
          }
          sawTarget = true;
      }
      else{
          sawTarget = false;
      }
   }
}

Also note that this assumes the timing of your serial events is correct. Note that it's possible for your serial events to fire faster than 60 times per second, in which case you'd have a build-up of unprocessed events. In that case you might want to use a while() loop instead of your outermost if statement, or use the serialEvent() function instead.


text:
Q: Will I be able to install Windows 10 using just my OEM serial number I have a laptop that was originally on Windows 7 and still has the OEM windows sticker with serial number on the bottom. I've now reformatted completely removing windows and have installed Ubuntu instead.
Will I be able to install the free Windows 10 upgrade anyhow using my OEM windows serial number?

A: You will need to install windows 7 on the device and run "Get Windows 10 (GWX)" and reserve your copy
worked for me, i fished out a ancient 7 install media with key


text:
Q: Adsupportframework works on iOS5 simulator Why does Adsupportframework work on my iOS5 simulator? I thought if you enabled adsupportframework as a requirement on a iOS 5 simulator it would cause the simulator to crash. When I enable the social framework this cause my iOS 5 simulator to crash which it suppose to. This is kind of bugging me.

A: AdSupport framework is introduced in iOS6. To avoid crash in device with iOS5 or below, just make it optional framework. See image reference here:


text:
Q: Is there a way to add invalid phone numbers conditions in my code I have the following code in python(pandas), databricks. This is working fine but it is not filtering out the invalid phone numbers.
The code follows the pattern and filters out home and mobile phone numbers
import pandas as pd
import re
from pyspark.sql.functions import lit

df = Phonevalidation

# function to check the phone number pattern
def isValid(s):
  Pattern = re.compile("(0|44)?[7-9][0-9]{9}")
  if(Pattern.match(s)):
    return 'Mobile Number'
  else: return 'Home phone'

#UDF Register
PhType = udf(isValid)

df1 = Phonevalidation.withColumn('Phtype' ,PhType('Phonenumber') )
display(df1)

I am expecting to filter out invalid phone number with length >10 or <10 or numbers like 0000000 or 11111 to be tagged as invalid

A: The code you are currently using marks with 9 digits and leading zero or UK countrycode and then a initial 7, 8 or 9 as mobile number, but everything else (including malformated ones) as home number:
  Pattern = re.compile("(0|44)?[7-9][0-9]{9}")
  if(Pattern.match(s)):
    return 'Mobile Number'
  else: return 'Home phone'

If you are after US numbers, grep with regex for phone number might help.

I am expecting to filter out invalid phone number with length >10 or <10 or numbers like 0000000 or 11111 to be tagged as invalid

For the first part of your idea you can use as pattern like Pattern = re.compile("[0-9]{10}"), the 2nd part I would put into a pseudocode like
if (Pattern.match(s)):
   if (s != '0000000000' or s != '1111111111'):
      return: 'Fitting your criteria'
else: return 'Not valid'


text:
Q: VSCodium not importing modules in Python I wanted to make a voice assistant importing SpeechRecognition on Python;
I installed PyAudio and SpeechRecognition with the following commands: pip install PyAudio pip install SpeechRecognition on Linux, but when I try to import SpeechRecognition with import speech_recognition as sr, VSCodium doesn't import the module.
But then I tried to import other modules, and the same thing happens... what should I do?

A: I think its main reason is on Linux pip is for python 2 while pip3 is for python 3.
If you are using py3 using pip3 may help. Other reasons may include a virtual environment you are on.If vscodium does not automatically activate it or whatever extension you are using do not run in the virtual environment it may not find the packages you installed. you can try these commands:
Example:
pip3 install PyAudio
pip3 install SpeechRecognition
python3 main.py

A: You can check which pip you are using through pip --version, and which python you are using through where python(cmd) or get-command python(PowerShell). Make sure pip matches up with the python interpreter you are using.
If it's not, you can try to reopen the terminal with the shortcut 'Ctrl+Shift+`'. And then to check the pip version again.
If it still not matches up with the interpreter. That's maybe this environment hasn't installed the pip in this environment.


text:
Q: How to send xml via post to wcf service I got a code which post xml to wcf service. Here is the full code
1) WCF Service Interface
[OperationContract]
[WebInvoke(Method = "POST",
    UriTemplate = "GetData",
    RequestFormat = WebMessageFormat.Xml,
    BodyStyle = WebMessageBodyStyle.Bare)]
string GetData(DataRequest parameter);

2) WCF Service Implementation
public string GetData(DataRequest parameter)
{
    //Do stuff
    return "your data here";
}

3) Data Contract in your WCF service (In this case it's DataRequest)
[DataContract(Namespace = "YourNamespaceHere")]
public class DataRequest
{
    [DataMember]
    public string ID{ get; set; }
    [DataMember]
    public string Data{ get; set; }
}

4) Client sending the data must have the data constructed properly! (C# console app in this case)
static void Main(string[] args)
{
    ASCIIEncoding encoding = new ASCIIEncoding();
    string SampleXml = "<DataRequest xmlns=\"YourNamespaceHere\">" +
                                    "<ID>" +
                                    yourIDVariable +
                                    "</ID>" +
                                    "<Data>" +
                                    yourDataVariable +
                                    "</Data>" +
                                "</DataRequest>";

    string postData = SampleXml.ToString();
    byte[] data = encoding.GetBytes(postData);

    string url = "http://localhost:62810/MyService.svc/GetData";

    string strResult = string.Empty;

    // declare httpwebrequet wrt url defined above
    HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(url);
    // set method as post
    webrequest.Method = "POST";
    // set content type
    webrequest.ContentType = "application/xml";
    // set content length
    webrequest.ContentLength = data.Length;
    // get stream data out of webrequest object
    Stream newStream = webrequest.GetRequestStream();
    newStream.Write(data, 0, data.Length);
    newStream.Close();

    //Gets the response
    WebResponse response = webrequest.GetResponse();
    //Writes the Response
    Stream responseStream = response.GetResponseStream();

    StreamReader sr = new StreamReader(responseStream);
    string s = sr.ReadToEnd();

    return s;
}

My question is that if GetData() function expect two or more parameter then how could I supply value to GetData()
public string GetData(string xml1,string xml2)
{
     //Do stuff return "your data here";
}

so please guide me how to pass two xml data to GetData() function ?

A: First of all you can't have a service with WebMessageBodyStyle.Bare and a method that takes two parameters. You'll need to change to a WrappedRequest as a minimum:
[OperationContract]
[WebInvoke(Method = "POST",
     UriTemplate = "GetData",
     RequestFormat = WebMessageFormat.Xml,
     BodyStyle = WebMessageBodyStyle.WrappedRequest)]
string GetData(DataRequest xml1, string xml2);

With that out of the way let's see what the wire format needs to be for this webHttp binding.
The root element needs to be named as the name of the operation, GetData. Next are a sequence of child elements, for each parameter one. The default name of those elements equals the name of your variable, so in the example it would be xml1 and xml2. Those defaults can be influenced by decorating the parameter with a [MessageParameter(Name="Bar")] attribute.
Applying above ground rules would require that your HTTP Post body looks similar to this:
<GetData>    <!-- Operation -->
    <xml1>   <!-- parameter one -->
    </xml1>
    <xml2>   <!-- parameter two -->
    </xml2>
</GetData>

Unfortunately this is not it. The service and it's contracts have namespace. Without any decoration the namespace is the ugly http://tempuri.org/ which I replaced on the IService interface with
 [ServiceContract(Namespace="http://service.stackoverflow.com")]

In your first example the DataRequest type had a namespace. In my test I decorated the type with
 [DataContract(Namespace="http://data.stackoverflow.com")]

Now we need to add those namespaces (with namespace aliases) to our basic xml payload:
<GetData xmlns="http://service.stackoverflow.com"> <!-- Operation with default namespace  -->
    <xml1 xmlns:a="http://data.stackoverflow.com">   <!-- namespace on type -->
      <a:ID>42</a:ID> <!-- members are in the type namespace, use the alias -->
      <a:Data>FuBar</a:Data>
    </xml1>
    <xml2>   <!-- parameter two, no explicit namespace so is in the default one -->
       BlahBlah
    </xml2>
</GetData>

Posting that payload to the service at Service1.svc/GetData does invoke the service with the parameters having the deserialized data.
To answer your question exactly given your example code change at the Service:
[ServiceContract(Namespace="http://service.stackoverflow.com")]
public interface IService1
{
    [OperationContract]
    [WebInvoke(Method = "POST",
      UriTemplate = "GetData",
        RequestFormat = WebMessageFormat.Xml,
        BodyStyle = WebMessageBodyStyle.WrappedRequest)]
    string GetData([MessageParameter(Name="Bar")] DataRequest xml1, string xml2);
}

and at the client:
var yourIDVariable = "foo";
var yourDataVariable = "bar";
string SampleXml = "<xml1 xmlns:a=\"http://data.stackoverflow.com\">" +
                                "<a:ID>" +
                                yourIDVariable +
                                "</a:ID>" +
                                "<a:Data>" +
                                yourDataVariable +
                                "</a:Data>" +
                            "</xml1>";

string xml2 = "some data";
string wrapper = "<GetData xmlns=\"http://service.stackoverflow.com\">{0}<xml2>{1}</xml2></GetData>";
string postData = String.Format(wrapper, SampleXml, xml2);

When dealing with WCF service call and diagnosing serialization issues it is extremely convenient to enable WCF message logging in the config of system.serviceModel:
<diagnostics>
  <endToEndTracing activityTracing="true" messageFlowTracing="true" propagateActivity="true"/>
  <messageLogging
     logKnownPii="true"
     logEntireMessage="true"
     logMalformedMessages="true"
     logMessagesAtServiceLevel="true"
     logMessagesAtTransportLevel="true"
     maxMessagesToLog="30000"
     maxSizeOfMessageToLog="20000"/>
</diagnostics>

and the suitable listener:
<system.diagnostics>
   <sources>
     <source name="System.ServiceModel.MessageLogging">
       <listeners>
             <add name="messages"
             type="System.Diagnostics.XmlWriterTraceListener"
             initializeData="messages.svclog" />
        </listeners>
     </source>
  </sources>
  <trace autoflush="true"></trace>
</system.diagnostics>

Which gives you the exact payload in the Service Trace Viewer:


text:
Q: jQuery .focus() not working in Safari (desktop) on search field I have a search field that is hidden, and when a user clicks on the search icon, it opens and I want to bring focus to the search input immediately so the user does not have to click twice. It works perfect in Chrome, but not in Safari (desktop). I saw some other suggestions that wrapping it in a timeout will work, but still no dice. Any thoughts?
jQuery:
$search       = $('.header--search-container');
$searchInput  = $('.header--search-input input[type=search]');

  $search.click(function(){
    $searchInput.toggleClass('search-active');
    setTimeout(function(){
      $('header .header--search-input .search-field').focus();
    }, 1);
  });

HTML (Don't really think its needed but just so you can see... Also redacted is the  element) :

      <form role="search" method="get" class="search-form" action="http://example.com/">

         Search for:
         <input type="search" class="search-field" placeholder="Search …" value="" name="s" />

        <input type="submit" class="search-submit" value="Search" />
       </form>

          <svg>
           .. redacted for legibility on stack overflow ..
          </svg>

A: Adding a higher setTimeout value works.
  $search.click(function(){
    $searchInput.toggleClass('search-active');
    setTimeout(function(){
      $('header .header--search-input .search-field').focus();
    }, 500);
  });


text:
Q: LaTeX causes Anki to crash I'm attempting to use LaTeX along with anki to enhance the typsetting system in anki.
The issue I run into that some cards simply crash the anki application for no apparent reason.
Here is how I customized my card type to enable LaTeX:
[latex]{{Front}}[/latex]

And
{{FrontSide}}

{{Source}}

[latex]{{Back}}[/latex]

Cards like this work well:
Cards like this however crash the applictaion:


text:
Q: SSDP/UDP Multicast on fresh installation not working I have a freshly setup CentOS 8 Stream host.
I need to receive SSDP messages.
The problem is, as soon as firewalld is enabled, socat does not print anything.
socat UDP4-RECVFROM:1900,ip-add-membership=239.255.255.250:0.0.0.0,fork,reuseaddr -

As soon as i disable firewalld, i see ssdp messages.
I tried to allow it with:  iptables -A INPUT -d 239.255.255.250/32 -p udp -m udp --dport 1900 -j ACCEPT but that does not work.
[root@docker-1 ~]# iptables -L -n
Chain INPUT (policy ACCEPT)
target     prot opt source               destination
ACCEPT     udp  --  0.0.0.0/0            239.255.255.250      udp dpt:1900
ACCEPT     udp  --  0.0.0.0/0            0.0.0.0/0            match-set upnp dst,dst
ACCEPT     udp  --  0.0.0.0/0            0.0.0.0/0            udp spt:1900
ACCEPT     udp  --  0.0.0.0/0            0.0.0.0/0            udp dpt:1900

Chain FORWARD (policy DROP)
target     prot opt source               destination
DOCKER-ISOLATION-STAGE-1  all  --  0.0.0.0/0            0.0.0.0/0
ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0            ctstate RELATED,ESTABLISHED
DOCKER     all  --  0.0.0.0/0            0.0.0.0/0
ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0
ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0
DOCKER-USER  all  --  0.0.0.0/0            0.0.0.0/0
ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0            ctstate RELATED,ESTABLISHED
DOCKER     all  --  0.0.0.0/0            0.0.0.0/0
ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0
ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination
SET        udp  --  0.0.0.0/0            239.255.255.250      udp dpt:1900 add-set upnp src,src exist

Chain DOCKER (2 references)
target     prot opt source               destination

Chain DOCKER-ISOLATION-STAGE-1 (1 references)
target     prot opt source               destination
RETURN     all  --  0.0.0.0/0            0.0.0.0/0

Chain DOCKER-ISOLATION-STAGE-2 (0 references)
target     prot opt source               destination
RETURN     all  --  0.0.0.0/0            0.0.0.0/0

Chain DOCKER-USER (1 references)
target     prot opt source               destination
RETURN     all  --  0.0.0.0/0            0.0.0.0/0

Why does this with firewalld enabled not work?
The provided solution/iptables rule did not work either:

*

*Fedora firewall with UPnP?

*https://serverfault.com/q/250797/569434


text:
Q: OpenGL alpha value makes texture whiter? I'm trying to load a texture with RGBA values but the alpha values just seem to make the texture more white, not adjust the transparency.  I've heard about this problem with 3D scenes, but I'm just using OpenGL for 2D. Is there anyway I can fix this?
I'm initializing OpenGL with
glViewport(0, 0, winWidth, winHeight);
glDisable(GL_TEXTURE_2D);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glDisable(GL_DEPTH_TEST);
glClearColor(0, 0, 0, 0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0, winWidth, 0, winHeight); // set origin to bottom left corner
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glColor3f(1, 1, 1);

Screenshot:

That washed out dotty image should be semitransparent. The black bits are supposed to be completely transparent. As you can see, there's an image behind it that isn't showing through.
The code to generate that texture is rather lengthy, so I'll describe what I did. It's a 40*30*4 array of type unsigned char. Every 4th char is set to 128 (should be 50% transparent, right?).
I then pass it into this function, loads the data into a texture:
void Texture::Load(unsigned char* data, GLenum format) {
    glEnable(GL_TEXTURE_2D);
        glBindTexture(GL_TEXTURE_2D, _texID);
        glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, _w, _h, format, GL_UNSIGNED_BYTE, data);
    glDisable(GL_TEXTURE_2D);
}

And...I think I just found the problem.  Was initializing the full-sized texture with this code:
glEnable(GL_TEXTURE_2D);
    glBindTexture(GL_TEXTURE_2D, _texID);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, tw, th, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, NULL);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
glDisable(GL_TEXTURE_2D);

But I guess glTexImage2D needs to be GL_RGBA too? I can't use two different internal formats? Or at least not ones of different sizes (3 bytes vs 4 bytes)? GL_BGR works fine even when its initialized like this...

A: In the interest of others, I post my solution here.
The problem was that although my Load function was correct,
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, _w, _h, GL_RGBA, GL_UNSIGNED_BYTE, data);

I was passing GL_RGB to this function
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, tw, th, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, NULL);

Which also needs to specify the correct number of bytes (four).  From my understanding you can't use a different number of bytes for a SubImage, although I think you can use a different format if it does have the same number of bytes (i.e. mixing GL_RGB and GL_BGA is okay, but not GL_RGB and GL_RGBA).

A: Are there any overlapping primitives in your scene?
You are aware that you're calling the 3-parameter version of glColor, which sets the alpha to 1.0, right?
It could be helpful if you could post a screenshot, or otherwise describe what happens, say, when you draw two primitives with identical colors and differing alphas. In fact, any code demostrating the problem could help.
Edit:
I'd imagine that using TexImage with GL_RGB (for internalformat, the 3rd parameter) creates a 3-component texture with no alpha or alpha values implicitly initialized to 1, no matter what kind of pixel data you supply.
GL_BGR is not a valid value for this parameter, perhaps it is tricking your implementation into using a full 4-byte internal format? (Or a 2-byte one, as per GL_LUMINANCE_ALPHA) Or do you mean passing GL_BGR to your Texture::Load() function, which should not really be different from passing GL_RGB?

A: I think this should work, but it assumes the image has an alpha channel.  If you try and load an image without an alpha channel you will get an exception or your application might crash.  For non-alpha channel images use GL_RGB instead of GL_RGBA on the second parameter, right before setting the GL_UNSIGNED_BYTE.
void Texture::Load(unsigned char* data) {
  glEnable(GL_TEXTURE_2D);
    glBindTexture(GL_TEXTURE_2D, _texID);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, tw, th, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
  glDisable(GL_TEXTURE_2D);
}


text:
Q: Not receiving APNS messages from Azure after upgrade to Swift 3.0 After updating my application to Swift 3 (what an experience that was! ) - I knew I had to rework the Notification code due to the changes in iOS10.
Using this helpful resource - I was able to recode and I am getting a valid connection
https://github.com/ashishkakkad8/Notifications10Swift/blob/master/Notifications10Swift/AppDelegate.swift
I also amended the Capabilties for the project, adding 1) Notifications, and 2) Background Modes / Remote Notifications.
However, when I send a test message thru the Azure 'test-send' feature, I don't receive it.
Here's the relevant code from my AppDelegate:
var window: UIWindow?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    // Register for remote notifications
    if #available(iOS 10.0, *) {
        let center  = UNUserNotificationCenter.current()
        center.delegate = self
        center.requestAuthorization(options: [.sound, .alert, .badge]) { (granted, error) in
            if error == nil{
                UIApplication.shared.registerForRemoteNotifications()
            }
        }
    }
    else {
        UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.sound, .alert, .badge], categories: nil))
        UIApplication.shared.registerForRemoteNotifications()
    }
}

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data)
{
    let hub: SBNotificationHub = SBNotificationHub.init(connectionString: APISettings.Instance.notificationHubEndpoint, notificationHubPath: APISettings.Instance.notificationHubName)

    hub.registerNative(withDeviceToken: deviceToken, tags: nil) { (error) -> Void in

        if (error != nil){
            print("Error registering for notifications: %@", error)
        } else {
            print("Registration ok")
        }
    }
}

func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error)
{
    print("Error = ",error.localizedDescription)
}

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    print(userInfo)
}

// MARK: UNUserNotificationCenter Delegate // >= iOS 10

@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    print("User Info = ",notification.request.content.userInfo)
    completionHandler([.alert, .badge, .sound])
}

@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
    print("User Info = ",response.notification.request.content.userInfo)
    completionHandler()
}

Any help would be greatly appreciated.

A: Try to call this function on didFinishLaunchingWithOptions and clean >Run your app
func registerNotification()
{
UIApplication.sharedApplication()
        let application = UIApplication.sharedApplication()
if application.respondsToSelector(#selector(UIApplication.registerUserNotificationSettings(_:)))
{
        let settings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)

        application.registerUserNotificationSettings(settings)
        application.registerForRemoteNotifications()

    }

}

func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings) {
    if notificationSettings.types != .None {
        application.registerForRemoteNotifications()
    }
}


text:
Q: private method inside spring mvc controller is thread safe As i understand spring mvc controllers are thread safe by default (like servlets). But  I just want to know any private helper methods inside the controllers are thread safe ?
I have two mapping in the controller class eg: /test and test/success. Every time user invokes this url I want to check the user status and activation time in the database using a service method ( two different calls ). So I have decided to create a one private helper method to check the status.
So could anyone know that my private method is thread safe ?

A: All request are handled by one instance of your controller (singleton because it's a spring managed bean). So you need to make sure to not store any state (in a field) related to one request.
So:
@Controller
@RequestMapping("/foo")
public class Foo {
    @Autowired
    private Something something;

    @RequestMapping("/list")
    public String foo() {
       something.someMethod();
       bar();
       return "view"
    }

    private void bar() {
        // something
    }
}

is OK, but:
@Controller
@RequestMapping("/foo")
public class Foo {

    private User theUser; // problem is ALL request share this field

    @RequestMapping("/foo/{userId}")
    public String foo(@PathVariable final Integer userId) {
       if (theUser.getId().equals(userId)) {
           // something
       } else {
           theUser = ...
       }
       return "view"
    }
}

is not.
NB: not tested (typed just here so it can even hurts your compiler)


text:
Q: Appium shows InspectorMoved
I do have latest version of Inspector installed but it still says inspectorMoved, maybe inspector is not synced with Appium.
How can I solve it?

A: The Inspector is now separated.
You can get it from here https://github.com/appium/appium-inspector/releases


text:
Q: Why is ESLint trying to run on its own config file when using Typescript? I have .eslintignore right next to eslintrc.js
The ignore is simply this:
.eslintrc.js
dist/*
node_modules/*
out-tsc/*

However when I go into eslintrc.js I get this error:
Parsing error: ESLint was configured to run on `<tsconfigRootDir>/.eslintrc.js` using `parserOptions.project`: <tsconfigRootDir>/../../../../../../users/dstein/repositories/social-experiment/packages/site/tsconfig.json
However, that TSConfig does not include this file. Either:
- Change ESLint's list of included files to not include this file
- Change that TSConfig to include this file
- Create a new TSConfig that includes this file and include it in your parserOptions.project
See the typescript-eslint docs for more info: https://typescript-eslint.io/linting/troubleshooting#i-get-errors-telling-me-eslint-was-configured-to-run--however-that-tsconfig-does-not--none-of-those-tsconfigs-include-this-file

The article it links to unsurprisingly says to use .eslintignore if you don't want to lint the file the error is on. Meanwhile, my TS config does not say to include any js files.
{
  "compilerOptions": {
    "target": "es2018",
    "module": "esnext",
    "moduleResolution": "node",
    "noEmitOnError": true,
    "lib": ["es2017", "dom"],
    "strict": true,
    "esModuleInterop": false,
    "allowSyntheticDefaultImports": true,
    "experimentalDecorators": true,
    "importHelpers": true,
    "outDir": "out-tsc",
    "sourceMap": true,
    "inlineSources": true,
    "rootDir": "./",
    "incremental": true
  },
  "include": ["**/*.ts"],
}

Really bewildered why TS Config saying to only include ts files would have ESLint it was configured to run using parserOptions.project
The ESLint config is fairly straightforward (I will remove all the rules to save some reading here):
module.exports = {
  root: true,
  parser: '@typescript-eslint/parser',
  parserOptions: {
    tsconfigRootDir: __dirname,
    project: ['./tsconfig.json'],
  },
  plugins: ['@typescript-eslint'],
  env: {
    es6: true,
    browser: true,
  },
  extends: [
    '@open-wc',
    'eslint:recommended',
    'plugin:import/recommended',
    'prettier',
  ],
  rules: {},
};


text:
Q: How to rollback macOS Sierra Developer Beta back to El Capitan (without time machine) I can't reinstall El Capitan from AppStore because of this:

and CmdR only suggest to reinstall macOS Sierra.

A: macOS is not designed to be downgradable, and as such you cannot downgrade it through an installer like this. You will need to create a bootable install disk (Apple support), e.g. by running
sudo /Applications/Install\ OS\ X\ El\ Capitan.app/Contents/Resources/createinstallmedia --volume /Volumes/MyVolume --applicationpath /Applications/Install\ OS\ X\ El\ Capitan.app

to install on a drive called MyVolume. Running this will lose you all your content, so you will need to have a backup if you want to retain your files. Otherwise, wait Sierra out…

A: The preferred way is to do a Restore from Time Machine.  Your next option is to do a clean install OS X from USB or other install media; meaning wipe the HDD and install.

A: Best way to downgrade to El Capitan:

*

*Make a new partition

*Reboot and hold down Command R to start Internet Recovery .
This will clean install El Capitan.

*After installation, remove the partition of Sierra.

See official documentation of Apple about Internet Recovery
Done.

A: Ok so i just bought this macbook pro and i am really good with computers. However, this is my first mac. So the person i bought it from didnt know how to reboot it so i went online.
Command+R brings up the 4 option menu. I erased the hard drive and when i went to reinstall i wasnt able to install el capitan using my icloud id that i have for my ipad. It said temporarily not available.
So i got pissed and shut down the computer as everything i had read had not worked. After shutting it down i turned it back on and a folder with a question mark came on and couldnt get anywhere. Shut it down again.
Restarted it while holding down command+R and the internet system recovery began. Had to connect to wifi. BAMCIS it was that easy to get it to factory settings. It installed OS X LION and i then upgraded to Sierra. Only to realize that Serato Scratch live was not compatible with Sierra as i am running SL1 lol.
Anyways had to go back to OS X LION so same process erase hard drive. Shut down computer. Command+R to start internet system recovery go back to OS X Lion. Pretty simple method if you want to go back without a hastle or got a laptop off someone and are getting the temporarily not available message. Hope this helps.

A: this may seem like a bit of a hack, but you could try to use Unibeast to create a fresh OS X El Capitan installation disk, and boot your mac from it to install.
Here is a step-by-step guide on creating this disk :
http://www.tonymacx86.com/threads/unibeast-install-os-x-el-capitan-on-any-supported-intel-based-pc.172672/
This is basically intended for Intel-based PCs but it works like a charm on the Mac to perform rollbacks.


text:
Q: Mouse cursor appears during Games from 2 days this problem happening. during game-play(windowed or full-screen) suddenly mouse cursor appears(with a sound notification but nothing shows on the notification area) on the screen and the pointer moving  as i move my mouse. i didn't installed any software from couple of days...  just installed windows updates (1803 and other ms updates ).
note: when the cursor reaches the top of the screen it comes from bottom it like a loop or something like that... like the snake game.
should i just reinstall the windows? or i can trust on you guys ?
adding the video clip of my problem ... please sees this :video clip of my problem
this is happens in task manager, and this sound coming. video2


text:
Q: How to construct an output which consists an array of objects? lets say I have a sample data like this,
const questions_chklist =
  { credit_broker_checklist:
    [ { id: '1', title: 'Are any identified risks to the customer given equal prominence?', question_id: 'wmBHr' }
    , { id: '2', title: 'Content has been approved by an authorised individual',            question_id: 'sPYvu' }
    , { id: '3', title: 'Does it clearly name your company or the ?',                       question_id: '64bBL' }
    ]
  , test_checklist_checklist:
    [ { id: '1', title: 'new questionn 1',     question_id: '0VsnL' }
    , { id: '2', title: 'new question 02',     question_id: 'c9jrW' }
    , { id: '3', title: 'New question 03',     question_id: 'fbJON' }
    , { id: '4', title: 'new question 412234', question_id: 'AbcDE' }
    ]
  , new_list_checklist: [ ]
  }

Now I am trying to create an object like this,
{ credit_broker_checklist:
  [ { answer: '', comments: '', question_id: 'wmBHr' }
  , { answer: '', comments: '', question_id: 'sPYvu' }
  , { answer: '', comments: '', question_id: '64bBL' }
  ]
, test_checklist_checklist:
  [ { answer: '', comments: '', question_id: '0VsnL' }
  , { answer: '', comments: '', question_id: 'c9jrW' }
  , { answer: '', comments: '', question_id: 'fbJON' }
  , { answer: '', comments: '', question_id: 'AbcDE' }
  ]
, new_list_checklist: [ ]
}

Currently , I don't know how to generate an object so I am generating like this,

const questions_chklist =
  { credit_broker_checklist:
    [ { id: '1', title: 'Are any identified risks to the customer given equal prominence?', question_id: 'wmBHr' }
    , { id: '2', title: 'Content has been approved by an authorised individual',            question_id: 'sPYvu' }
    , { id: '3', title: 'Does it clearly name your company or the ?',                       question_id: '64bBL' }
    ]
  , test_checklist_checklist:
    [ { id: '1', title: 'new questionn 1',     question_id: '0VsnL' }
    , { id: '2', title: 'new question 02',     question_id: 'c9jrW' }
    , { id: '3', title: 'New question 03',     question_id: 'fbJON' }
    , { id: '4', title: 'new question 412234', question_id: 'AbcDE' }
    ]
  , new_list_checklist: [ ]
  }

let jsonObj = []
for (var key in questions_chklist)
  {
  if (questions_chklist.hasOwnProperty(key))
    {
    let option_count = questions_chklist[key].length;
    for (let i = 0; i < option_count; i++)
      {
      let item            = {}
      item ["answer"]     = "";
      item ["comments"]   = "";
      item["question_id"] = questions_chklist[key][i].question_id
      jsonObj.push(item);
      }
    }
  }

console.log( jsonObj )
.as-console-wrapper { max-height: 100% !important; top: 0 }

Its simply creating an array of several objects,
[
  {
    answer: '',
    comments: '',
    question_id: 'wmBHr'
  },
  {
    answer: '',
    comments: '',
    question_id: 'sPYvu'
  },
...
....

A: If you want your jsonObj output to be an object, don't initialize it as an array. What you did was loop through each property's value and push the items in the jsonObj array.
Here's your code a bit adjusted to output what you need, if I understood your issue correctly.

let questions_chklist = {
    "credit_broker_checklist": [
        {
            "id": "1",
            "title": "Are any identified risks to the customer given equal prominence?",
            "question_id": "wmBHr"
        },
        {
            "id": "2",
            "title": "Content has been approved by an authorised individual",
            "question_id": "sPYvu"
        },
        {
            "id": "3",
            "title": "Does it clearly name your company or the ?",
            "question_id": "64bBL"
        }],
    "test_checklist_checklist": [
        {
            "id": "1",
            "title": "new questionn 1",
            "question_id": "0VsnL"
        },
        {
            "id": "2",
            "title": "new question 02",
            "question_id": "c9jrW"
        },
        {
            "id": "3",
            "title": "New question 03",
            "question_id": "fbJON"
        },
        {
            "id": "4",
            "title": "new question 412234",
            "question_id": "AbcDE"
        }
    ],
    "new_list_checklist": []
}

let jsonObj = {}
for (var key in questions_chklist) {
    if (questions_chklist.hasOwnProperty(key)) {
       jsonObj[key] = [];
       let option_count = questions_chklist[key].length;
       for (let i = 0; i < option_count; i++) {
          let item = {}
          item ["answer"] = "";
          item ["comments"] = "";
          item["question_id"] = questions_chklist[key][i].question_id
          jsonObj[key].push(item);
       }
   }
}
console.log(jsonObj)

A: So you just want to retain the question_id from the original, and then add empty answer and comment properties.
You can turn your original object to an array of pairs with Object.entries, do the mapping, and then turn that back to an object with Object.fromEntries:

const questions_chklist = { credit_broker_checklist: [ { id: '1', title: 'Are any identified risks to the customer given equal prominence?', question_id: 'wmBHr' }, { id: '2', title: 'Content has been approved by an authorised individual', question_id: 'sPYvu' } , { id: '3', title: 'Does it clearly name your company or the ?', question_id: '64bBL' } ] , test_checklist_checklist: [ { id: '1', title: 'new questionn 1', question_id: '0VsnL' } , { id: '2', title: 'new question 02', question_id: 'c9jrW' } , { id: '3', title: 'New question 03', question_id: 'fbJON' } , { id: '4', title: 'new question 412234', question_id: 'AbcDE' } ] , new_list_checklist: [ ] }

let result = Object.fromEntries(
    Object.entries(questions_chklist).map(([name, questions]) =>
        [name, questions.map(({question_id}) => ({
             answer: "",
             comment: "",
             question_id
        }))]
    )
);

console.log(result);


text:
Q: facet api: textbox filter I'm looking to a way to add a textbox filter for searches of facet api in Drupal7. My site has three content type (A,B,C) that is used in searches.
I see that I can activate some filters in Admin -> configuration -> search and metadata -> Search API (edit one and then filters tab), but I can't see one of text. Is there a text field for filter in facet api?
Currently, I use Facet API and Drupal search, but the problem is that if I filter for content A and after I search something ("Andrew" for example) it resets the filter and search in all contents. I would like to filter and if I search something, search on the filtered content, not in a new search.
I have searched on Google, but I don't get a solution. The same problem is reported here, with a temporal solution, but I wnat to know if there is a better solution:

*

*https://www.drupal.org/node/1381524

*https://tech-tamer.com/drupal-7-refining-a-faceted-search-with-an-exposed-filter-solved/

A: Maybe You can deal with urls , reconstruct url from parameters to automatically check facets :
/**
 * Implements hook_facetapi_searcher_info().
 *
 * @see hook_facetapi_searcher_info_alter()
 */
function MYMODULE_facetapi_searcher_info_alter(array &$searcher_info)
{
    foreach ($searcher_info as $key => $value) {
        if ($value['url processor'] == 'pretty_paths') {
            $searcher_info[$key]['url processor'] = 'mymodule_urlprocessor';
        }
    }
}

/**
 * Implements hook_facetapi_url_processors().
 *
 * @see hook_facetapi_url_processors()
 */
function MYMODULE_facetapi_url_processors()
{
    return array(
        'mymodule_urlprocessor' => array(
            'handler' => array(
                'label' => t('My URL processor'),
                'class' => 'FacetapiUrlProcessorMyModule',
            ),
        ),
    );
}

class FacetapiUrlProcessorMyModule extends FacetapiUrlProcessorPrettyPaths {

 // overrides methods to construct url
}


text:
Q: asp.net specific embedded flash file doesn't work on the server I want to show a flash file on my site. I use next code to embed flash into web page:
<object height="344" width="425">
  <embed src="/flash/1.swf" type="application/x-shockwave-flash" height="344" width="425">
</object>

All works fine locally.

But when I load this page on the web server (IIS 7.0) flash loads but does't work (in all browsers).

Also I know that only this particular flash file doesn't work. Others flash files work fine.
Any ideas?


text:
Q: Mongoose Model Undefined in Pre Middleware I am trying to construct an application that acts as a URL shortener like bitly. I have hit a snag, however, and would very much appreciate your help. I was in the process of testing my Link model with mocha and was running into errors in one of my pre middleware functions. In this function I attempt to get a count of all the entries that have a shortened url that matches the one that I just generated, so that I don't double up on my shortened links. In order to do this I am trying to call the Mongoose's count function on my model, but I am getting the TypeError: "cannot read property 'count' of undefined". I have tried to search for why this is happening but have been unable to come up with anything.
If you could help me figure out why this is happening or what a better method would be for generating the shortened links, I would very much appreciate it. Thanks!
You can find my code for my Link model below:
'use strict';

let mongoose = require('mongoose'),
    config = require('../../config/config'),
    schema = mongoose.Schema;

let LinkSchema = new schema({
    originalLink: {
        type: String,
        trim: true,
        validate: [
            function(link) {
                let urlReg = new RegExp("(http|ftp|https)://[\w-]+" +
                    "(\.[\w-]+)+([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?");
                return urlReg.test(link);
            }, 'The URL entered is not valid'
        ],
        required: 'URL to shorten is required'
    },
    shortenedLink: String
});

LinkSchema.pre('save', function(next) {
    let shortLink;
    let count;
    while (true) {
        console.log(`slink: ${shortLink}, count: ${count}`);
        shortLink = this.generateShortenedLink(this.originalLink);
        mongoose.model['Link'].count({shortenedLink : shortLink}, (err, n) => {
            if (err) {
                console.log(err);
                next();
            }
            count = n;
        });
        if (count === 0) {
            break;
        }
    }

    this.shortenedLink = shortLink;

    next();
});

LinkSchema.methods.generateShortenedLink = function(link) {
    let text = "";
    let possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

    for (let i = 0; i < 8; i++ )
        text += possible.charAt(Math.floor(Math.random() * possible.length));

    return config.appUrl + text;
};

mongoose.model('Link', LinkSchema);

A: mongoose.model is a function, and you're using it as if it were an object.
Try this instead:
mongoose.model('Link').count(...);