text:
Q: How to force users to use strong password on my form in WordPress I would like to add a regex into my uncanny form in wordpress to force users to have strong password before sending the form, is not activated and available by default with the extension.
I've try to add custom js into elementor and the js is well recognized because display error message work
$.validator.addMethod("strongPassword", function(value, element) {
  return this.optional(element) || /^(?=.*[A-Z].*[A-Z])(?=.*[!@#$&*])(?=.*[0-9].*[0-9])(?=.*[a-z].*[a-z].*[a-z]).{8}$/.test(value);
}, "Le mot de passe doit comporter au moins une majuscule, une minuscule, un chiffre et un caractère spéciallle.");

$(document).ready(function() {
  $('#uncanny-learndash-codes-registration_form').validate({
    rules: {
      "uncanny-learndash-codes-user_pass": {
        required: true,
        minlength: 8,
        strongPassword: true
      },
      "uncanny-learndash-codes-user_pass_confirm": {
        required: true,
        minlength: 8,
        equalTo: "#uncanny-learndash-codes-user_pass"
      }
    },
    messages: {
      "uncanny-learndash-codes-user_pass": {
        required: "Veuillez entrer un mot de passe.",
        minlength: "Le mot de passe doit comporter au moins 8 caractères.",
        strongPassword: "Le mot de passe doit comporter au moins une majuscule, une minuscule, un chiffre et un caractère spécial."
      },
      "uncanny-learndash-codes-user_pass_confirm": {
        required: "Veuillez confirmer votre mot de passe.",
        minlength: "Le mot de passe doit comporter au moins 8 caractères.",
        equalTo: "Les mots de passe ne correspondent pas."
      }
    }
  });
});

but when I try this code it says no match between password and that I don't have the required strongPassword when I try with this Password "M0tDeP@sse!"
here's the php form
<?php

namespace uncanny_learndash_codes;

$atts = $GLOBALS['atts'];
if (SharedFunctionality::ulc_filter_has_var('registered')) { ?>

<?php esc_html_e('Bravo, votre compte est bien enregistré, bienvenue chez Zenmon Drops ', 'uncanny-learndash-codes') ?>

<?php
} else {
    $default = array(
        'redirect'      => '',
        'code_optional' => 'no',
        'auto_login'    => 'yes',
        'role'          => 'subscriber',
    );
    if (is_multisite()) {
        $options = get_blog_option(get_current_blog_id(), 'uncanny-codes-custom-registration-atts', $default);
    } else {
        $options = get_option('uncanny-codes-custom-registration-atts', $default);
    }
?>

    <form id="uncanny-learndash-codes-registration_form" class="uncanny-learndash-codes-registration uncanny-learndash-codes" action="" method="POST">
        <fieldset>

                    <?php echo esc_html__('Prénom', 'uncanny-learndash-codes'); ?>

                    <input name="uncanny-learndash-codes-user_first" id="uncanny-learndash-codes-user_first" required="required" value="<?php if (SharedFunctionality::ulc_filter_has_var('uncanny-learndash-codes-user_first', INPUT_POST)) {
                                                                                echo sanitize_text_field(SharedFunctionality::ulc_filter_input('uncanny-learndash-codes-user_first', INPUT_POST));
                                                                                } ?>" type="text" />

                    <?php echo esc_html__('Nom', 'uncanny-learndash-codes'); ?>

                    <input name="uncanny-learndash-codes-user_last" id="uncanny-learndash-codes-user_last" required="required" value="<?php if (SharedFunctionality::ulc_filter_has_var('uncanny-learndash-codes-user_last', INPUT_POST)) {
                                                                                echo sanitize_text_field(SharedFunctionality::ulc_filter_input('uncanny-learndash-codes-user_last', INPUT_POST));
                                                                                } ?>" type="text" />

                    <?php echo esc_html__('E-mail', 'uncanny-learndash-codes'); ?>

                    <input name="uncanny-learndash-codes-user_email" id="uncanny-learndash-codes-user_email" required="required" value="<?php if (SharedFunctionality::ulc_filter_has_var('uncanny-learndash-codes-user_email', INPUT_POST)) {
                                                                                echo sanitize_text_field(SharedFunctionality::ulc_filter_input('uncanny-learndash-codes-user_email', INPUT_POST));
                                                                                } ?>" class="required" type="email" />

                    <?php echo esc_html__('Mot de passe : il doit obligatoirement comporter au minimum 8 caractères mélangeant les majuscules, les minuscules, des chiffres et des caractères spéciaux.', 'uncanny-learndash-codes'); ?>

                    <input name="uncanny-learndash-codes-user_pass" id="password" required="required" minlength="8" class="required" type="password" />

                    <?php echo esc_html__('Confirmer mot de passe : ', 'uncanny-learndash-codes'); ?>

                    <input name="uncanny-learndash-codes-user_pass_confirm" id="password_again" required="required" minlength="8" class="required" type="password" />

                    <?php echo esc_html__('Votre code ici : ', 'uncanny-learndash-codes'); ?>

                    <input name="uncanny-learndash-codes-code_registration" id="code_registration" <?php if ('no' === $options['code_optional']) { ?>required="required" class="required" <?php } ?> value="<?php if (SharedFunctionality::ulc_filter_has_var('uncanny-learndash-codes-code_registration', INPUT_POST)) {
                                                                                echo sanitize_text_field(SharedFunctionality::ulc_filter_input('uncanny-learndash-codes-code_registration', INPUT_POST));
                                                                                } ?>" type="text" />

                <?php
                if (!empty($term_conditions)) {
                ?>

                        <?php echo esc_html__('Terms & Conditions', 'uncanny-learndash-codes'); ?>

                        <input name="uo_codes_terms_conditions" id="terms_conditions" required="required" class="required" value="<?php if (SharedFunctionality::ulc_filter_has_var('uo_codes_terms_conditions', INPUT_POST)) {
                                                                                echo sanitize_email(SharedFunctionality::ulc_filter_input('uo_codes_terms_conditions', INPUT_POST));
                                                                                } ?>" type="checkbox" /><?php echo $term_conditions; ?>

                <?php } ?>

                        <input type="hidden" name="_uo_nonce" value="<?php echo wp_create_nonce(Config::get_project_name()); ?>" />
                        <input type="hidden" name="redirect_to" value="<?php echo $atts['redirect']; ?>" />
                        <input type="hidden" name="key" value="<?php echo crypt(get_the_ID(), 'uncanny-learndash-codes'); ?>" />

                    <input type="submit" class="btn btn-default" value="<?php echo esc_html__('Je crée mon compte', 'uncanny-learndash-codes'); ?>" />

        </fieldset>
    </form>

<?php } ?>

is it something wrong with my code ?
if someone wants to try here's the page
https://zenmondrops.com/zenmonregister/


text:
Q: Jquery Confirm (Library) in a form submit I am using Jquery Confirm Library and using like this
$('#GoToLead').on('click', function (e) {
                console.log('from on click');
                e.preventDefault();

                $('<input type="hidden" name="StartDate" />').val($('#StartDate').val()).appendTo('#theForm');
                $('<input type="hidden" name="EndDate" />').val($('#EndDate').val()).appendTo('#theForm');
                $('<input type="hidden" name="City" />').val($('#City').val()).appendTo('#theForm');
                $('<input type="hidden" name="AbbrName" />').val($('#AbbrName').val()).appendTo('#theForm');
                $('<input type="hidden" name="ZipCode" />').val($('#ZipCode').val()).appendTo('#theForm');
                $('<input type="hidden" name="FirstName" />').val($('#FirstName').val()).appendTo('#theForm');
                $('<input type="hidden" name="LastName" />').val($('#LastName').val()).appendTo('#theForm');
                $('<input type="hidden" name="EmailAddress" />').val($('#EmailAddress').val()).appendTo('#theForm');
                $('<input type="hidden" name="GroupNumber" />').val($('#GroupNumber').val()).appendTo('#theForm');

                var buttonid = this.id;

                callAssignGroupModal(buttonid);

                //alert("data = " + $('#theForm').serialize());
            });

        });

        function callAssignGroupModal() {

            $("#GoToLead").confirm({
                confirm: function (buttonid) {
                    //var token = $("input[name='__RequestVerificationToken']").val();

                    var buttonclickedId = buttonid;

                    var formData = $('#theForm').val();

                    $("form").submit();
                },

                confirmButton: "Continue",
                confirmButtonClass: "btn-primary",
                cancelButton: "Cancel",
                cancelButtonClass: "btn-default",
                dialogClass: "modal-dialog modal-lg",
                post: false,
                text: "Are you sure you want to assign the Group Number of all these leads?",
                title: "Confirm assign the Group number to leads"

            });

I am trying to achieve two things here

*

*It takes two clicks to make a confirm and proceed the list to the data.

*The pop-up box is displayed at bottom of the page.

any help is much appreciated. thanks in advance

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there a maps API that will show closest residential locations? (google places?) I have a mobile app where I need try and predictably guess which residential location the user is standing in front of. (Not businesses)
I see the google places api, but it doesn't look like it does residential?
http://code.google.com/apis/maps/documentation/places/#PlaceSearches
I tried searching with a lat an long in a neighborhood, and it brought up all sorts of results that were close by, like parks and schools, but not residential.
Am I missing something? Is there something out there that will let me see what homes are close to a lat,long point?

A: The Places API probably won't work for you since it's querying a databases of places or businesses, not residential addresses.  You might want to consider reverse geocoding to the closest address from that point on the map instead: http://code.google.com/apis/maps/documentation/geocoding/#ReverseGeocoding


text:
Q: Download a file into my working directory I would like to download a file directly into my working directory
I can do this to a temp directory:
download.file("http://www.abc.com/abc.zip",temp)
but what do I have to replace temp with to get it to download to the working directory?

A: The second argument of download.file() is destfile and it must be specified. I don't have a Windows machine to test this on, but both of these work on my linux box and I can't see why at least the second won't work on Windows too:
download.file("http://www.abc.com/abc.zip", "./abc.zip")
download.file("http://www.abc.com/abc.zip", "abc.zip")

The second of those indicates that if you just give a filename, the file will be download to the current working directory and saved under the stated name.

A: If your url is in a variable, you can use basename to get the "filename" part out of it:
u <- "http://www.abc.com/abc.zip"
basename(u) # "abc.zip"

# downloads to current directory:
download.file(u, basename(u))

# downloads to subdirectory "foo":
download.file(u, file.path("foo", basename(u)))


text:
Q: Node.js - PostgreSQL - could not determine data type of parameter $1 error I'm trying to create a PostgreSQL prepared statement using node.js pg npm package. However, I keep getting an error:

could not determine data type of parameter $1

 function promiseQuery(sql, values) {
    return new Promise(function(resolve, reject) {
        pool.query('select $1 from workers', ['name'], function(err, result) {
            if (err) {console.log(err); reject(err)}
            else resolve(result.rows);
        })
    });
}

In the db the name field is set to type text not null.
I also tries pg-promise, but with no success either.

A: In the query select name from workers, from the point of view of the SQL syntax name is an identifier, and identifiers can never be passed as $N parameters, they must appear verbatim in the command. Otherwise the query cannot be prepared.
$N parameters can only appear in the query at positions where literals (constants) would be.
You'd have the same error if trying something similar with the PREPARE SQL command, outside of any client-side library:
PREPARE p as SELECT $1 FROM pg_class;
ERROR:  could not determine data type of parameter $1

The solution is to build the query in javascript with string replacement techniques for column names or table names, before submitting it to the database.
pg-promise does support injection of identifiers into a query with a specific syntax. From its documentation:
db.query('SELECT $1:name FROM $2:name', ['*', 'table']);
//=> SELECT * FROM "table"

A: Extending on the answer by Daniel Vérité...
You cannot combine Prepared Statements with dynamic column names, you'd have to generate the query on the client-side.
Using pg-promise syntax for SQL Names, you can properly escape your query like this:
db.any('SELECT $1~ FROM table', [colName])
// OR:
db.any('SELECT $1:name FROM table', [colName])
// OR:
db.any('SELECT ${colName~} FROM table', {colName})
// OR:
db.any('SELECT ${colName:name} FROM table', {colName})
// Etc, other variable syntax, like $[], $//, $<>, $()

And if you want to do it for a list of columns, then the simplest way to do it is like this:
const colNames = ['one', 'two', 'three'];

db.any('SELECT $1~ FROM table', [colNames])
// etc, the same variations as above, all will generate:
// SELECT "one","two","three" FROM table

or from all object properties:
const data = {
    one: 123,
    two: true,
    three: 'text'
};
db.any('SELECT $1~ FROM table', [data])
// etc, the same variations as above, all will generate:
// SELECT "one","two","three" FROM table

All these methods will properly escape the query, making sure SQL injection is not possible.


text:
Q: Email Validator Problems- Putting it all together I'm very new to PHP coding.
I've done tons of research to try and help me. As you can imagine I've gotten tons of material for help. The problem is when I'm trying to put it all together.
Specifically here is my problem. I've come across:
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo "e-Mail is Valid";
} else {
    echo "Invalid e-Mail";
}

But I have no idea how to implement it. As it stands now the validator checks the fields before the user has time to imput them..... I'm desperate
I'm sure the solution is really simple, but I've spent hours on this and am really desperate for this problem to be solved already.
Here's a link to the page
Here is the code for the page:
<!DOCTYPE html>

<meta charset='utf-8'>
<title>AWalsh Photography - Contact Me</title>
<link href="style/main_page.css" rel="stylesheet" type="text/css" />

 Contact Andrew walsh Photography

      <form id="email_form" name="email_form" method="post">

    First Name:

    <input type="text" name="fname_input" id="fname_input" />

    Last Name:

    <input type="text" name="lname_input" id="lname_input" />

    Your Email:

    <input type="text" name="email_input" id="email_input" />

    Re-enter Email:

    <input type="text" name="email_conf" id="email_conf" />

    Message

    <textarea rows="8" cols="45" id="message_input" name="message_input"></textarea>

    <input id="submit"type="submit" value="submit" name="submit"/>

    </form>

<?php

if($_POST['email_imput'] == $_POST['email_conf']){
    //stuff to do on success
    echo '
Success!!
';
} else {
    //stuff to do on failure
    echo '
Sorry, The emails you entered do not match
';
}

    $email_imput = $_POST['email_imput'];

if (filter_var($email_imput, FILTER_VALIDATE_EMAIL)) {
    echo $email_imput . ' is a valid email address.';
} else {
    echo $email_imput . ' is not a valid email address.';
}

$message_imput = $_POST['message_imput'];

$msg = "Email address: $email_imput \n" . "Message: $message_imput";

$to = 'myemail@gmail.com ';

$subject = 'AWP_email';

if (filter_var($email_imput)){

mail($to, $subject, $msg, $email);
}
if (mail($to, $subject, $msg, $email)) {
   echo("
Message successfully sent! Thanks for submitting your message. We will reply to you as soon as possible
");
  } else {
   echo("
Sorry, There was an error in your imput. Please try again.
");
  }

?>
<?=$error;?>
<form method="post" action="">

 There was an error with your post

</form>

Any input would be amazing. Thank you.

A: You could add a hidden field into the form and check it's value when it's time to send the email.
if (isset($_POST["some_hidden_field"])) {
    // put form validation and sending email here
}
else {
    // print the form
}

A: You should first check whether the page has been submitted or not. You might want to try if ($_SERVER['METHOD'] == 'POST') before making any validations


text:
Q: Rails 4: How to use module from lib in initializer file? I use rails 4.1. I created a module in lib/ folder in Rails: lib/corelib.rb but when I try to use it in my custom initializer file config/initializers/load_data.rb with
include Corelib

it gives me an error:
.../config/initializers/load_data.rb:1:in `<top (required)>': uninitialized constant Corelib (NameError)

How do I use my module from lib/ folder in my initializer?

A: Apparently I've forgotten to add require before include:
require 'corelib'
include Corelib

on top of the file in load_data.rb fixes the issue.


text:
Q: Construct axis if you have drawn $y=x^2$ plot In the coordinate plane $xOy$ you have drawn parabola $y=x^2$. Now delete the coordinate axes. Using a straightedge and a compass reconstruct coordinate axes.

A: Hint: Draw any two parallel chords. Their midpoints determine a line parallel to the axis.

Can you continue?


text:
Q: When two std::map objects are identical I have two std::map objects that I populate with the same data but the order is different:
using TMap = std::map<int, std::wstring>;
using TSourceData = std::vector< std::pair<int, std::wstring> >;

TSourceData gen_source_data(int size)
{
    TSourceData result;
    result.reserve(size);

    for(int i = 0; i < size; ++i)
    {
        result.push_back( std::make_pair(i, std::to_wstring(i)) );
    }

    return result;
}

TMap fill_map(const TSourceData& source)
{
    TMap result;

    auto randomized = source;
    std::random_shuffle(randomized.begin(), randomized.end());

    for(const auto &e : randomized)
    {
        result[e.first] = e.second;
    }

    return result;
}

int main()
{
    auto source = gen_source_data(1000);

    auto m1 = fill_map(source);
    auto m2 = fill_map(source);

    std::wcout << (m1 == m2) << std::endl;
}

In VS2017 it seems to always print 1 so the two maps are equal no matter in what order they were filled. But is it guaranteed to be so? And if so, could you explain why?

A:
... so the two maps are equal no matter in what order they were filled. But is it guaranteed to be so?

Yes, because std::map is a  sorted associative container (usually implemented as a binary tree) its elements are guaranteed to be sorted (regardless of its implementation).

A: std::map is an associative container. The difference between a sequential container and an associative container is that:

*

*a sequential container lets you decide the position of the element

*an associative container itself determines the position of the element

Also since std::map is a sorted container, there can be only one possible order for all the keys, so in the absence of duplicates, insertion order for std::map doesn't matter. Similarly, the ordering inside std::unordered_map is determined by the hash of each key, and is again not dependent on the insertion order.
Notice that you shuffle a vector (a sequential container), then you copy the values into a map. It's impossible to "shuffle" a map, since you do not control the position of the elements there.


text:
Q: How many Pokemiles can Pokebank store before redeeming them? I forgot to check my Pokebank for months, is there a limit to Pokemiles I can store before redeeming and sending them to a game?

A: YES.
The maximum value of Pokemiles you can have at once on Pokebank without redeeming them is 65535.
This odd number is due to a 16-bit integer value used to store that number.
This means it's better to redeem them once in a while. However, Battle Points counter is capped too, and it can't exceed 9999 BPs.


text:
Q: Please help a noob out with installing Ubuntu So I am brand new to Linux. I have an older laptop that is collecting dust and am trying to install Ubuntu 12.04.3 onto it. It's a Dell Studio 1735 running Vista 64bit that I bought back in 08.
I have the iso on a usb drive, done with "UNetbootin". I formatted the drive to FAT32 before loading anything onto it.
From what I understand, I get to the boot menu, go to "boot from usb", and select "install ubuntu" from the UNetbootin menu. I get the menu, but if I click on any option in there (All option are listed twice for some reason) the Ubuntu screen (purple screen with red dots underneath "Ubuntu") will come up for about a minute or so, then it will bring me back to the UNetbootin screen. But the menu will be shrunken up and up in the corner, and underneath it will be some text.
"BusyBox v1.18.5 (Ubuntu 1:1.18.5-1ubuntu4.1) built-in shell (ash)
Enter 'help' for a list of built-in commands.
(initramfs) _"
I can input commands here, and the help menu will come up but I do not know what I'm doing. And from what I understand I shouldn't need to do any command prompt stuff to just get it to install. I took a video in case I'm not explaining this well enough: Link Here
Any help is really appreciated.

A: Download Ubuntu 13.10 64 bit version:
http://www.ubuntu.com/download/desktop/thank-you?release=latest&bits=64&distro=desktop&status=zeroc
Use Universal USB installer to create the pendrive:
http://www.pendrivelinux.com/universal-usb-installer-easy-as-1-2-3/
Use the following guide to install:
http://www.ubuntu.com/download/desktop/install-desktop-latest


text:
Q: How to make CQ5 use .htm extensions instead of .html? I am converting a huge site from MS CMS 2002 to Adobe CQ5. In the existing CMS all pages are referenced with .htm extension. When I create a new page in CQ5 it always has .html extension. Is there any way to force CQ5 to use .htm extension for pages?

A: A list of default extensions rendering the content can be modified in the configuration of an OSGi service called SlingServletResolver. In order to change it, open the following path:
/system/console/configMgr/org.apache.sling.servlets.resolver.SlingServletResolver

on your CQ installation and add htm to the last option (Default Extensions). You may also use sling:OsgiConfig nodes to have the service configured automatically.

A: In addition to the other answers a different approach is to create an internal redirect from your htm to the new html pages.  You can create a Sling mapping under /etc/map which will redirect htm requests to html.
Information on configuring the sling mapping can be found here http://sling.apache.org/documentation/the-sling-engine/mappings-for-resource-resolution.html under Root Level Mappings -> Mapping Entry Specification

A: Tomek has provided the best solution for this problem.  However, this solution will change the extension type for all the pages.  If you want another solution to target specific pages then here is the solution:
Override the head.jsp for /libs/foundation/components/page by copying this file to apps folder and there specify the content-type and content="text/htm.
 Now you have to refer to this component as a superResoucetype for every component or template wherever you want a htm or any other extension extension.


text:
Q: Boost Libraries: Taboo or useful? I've seen some c++ programmers swear by the boost library, and some twitch when I mention boost. However, boost contains a whole slew of useful functions and tools to employ when encountering common c++ related  issues. For the record, is the boost library a good thing, or something to stay away from programming professionally.

A: The boost library is very useful for many people, and provides a lot of functionality.
As to whether it is the right tool for the job is dependent on the project, and the programmer, and is very a subjective question to answer.
There is no correct answer to this question. Boost is neither intrinsically good or bad.


text:
Q: JPA, save relation without querying entities I have this Entity representing a relation between two other entities.
I'd like to save the relation without having to get Role and Privilege before saving.
I'd like something like .save(roleId, privilegeId) so I don't have to hit the database before saving the relation.
Is it possible and how ?
Thanks
@Entity
@Table(name = "security_role_privilege")
public class RolePrivilege implements Serializable {

  private static final long serialVersionUID = -4788066966268187121L;

  @EmbeddedId protected RolePrivilegeId id;

  @ManyToOne
  @JoinColumn(name = "role_id", insertable = false, updatable = false)
  protected Role role;

  @ManyToOne
  @JoinColumn(name = "privilege_id", insertable = false, updatable = false)
  protected Privilege privilege;

  protected RolePrivilege() {}

  public RolePrivilege(Role role, Privilege privilege) {
    super();
    this.role = role;
    this.privilege = privilege;
    this.id = new RolePrivilegeId(role.getId(), privilege.getId());
    this.privilege.getRolePrivileges().add(this);
    this.role.getRolePrivileges().add(this);
  }

  public RolePrivilegeId getId() {
    return this.id;
  }

  public Role getRole() {
    return this.role;
  }

  public Privilege getPrivilege() {
    return this.privilege;
  }
}

This is the Spring Data JPA Repository for this entity
@Repository
public interface RolePrivilegeRepository extends JpaRepository<RolePrivilege, RolePrivilegeId> {}

A: With a raw EntityManager you can use em.getReference(Class<T> clazz, Object primaryKey) to fetch only a reference to the entity you wish to link, without actually fetching the data for the entity.


text:
Q: How to hide custom product attribute from admin product detail page I created a custom product attribute which been used for a long time. Now the business need is, not to use it. I don't want to remove/delete it because I believe it will create a data integrity issue. So I created UpgradeData.php in My/Catalog/Setup directory.
I tried.
$eavSetup->updateAttribute(Product::ENTITY, $attrCode, 'visible', '0');
$eavSetup->updateAttribute(Product::ENTITY, $attrCode, 'is_visible_on_front', '0');

etc... And I didn't have any luck.
Any advice will be highly appreciated.
Thanks!

A: I found the solution. In case it helps someone...
$eavSetup->updateAttribute(Product::ENTITY, $attrCode, 'is_visible', '0');


text:
Q: List files/folders in google drive including sub folders and so on... with google drive api I have a google drive folder that has so many folders, then these folders also have other folders/files inside them and so on... I am using this code to list all the folders/files in the parent folder and I am putting the files/folders in a data frame like this:
import pickle
import os.path
import io
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from numpy import cumproduct
import pandas as pd
import gdown
from pyasn1.type.constraint import ContainedSubtypeConstraint
import requests
from googleapiclient.http import MediaIoBaseDownload
import httplib2

SCOPES = ['https://www.googleapis.com/auth/drive']

creds = None
if os.path.exists('token.pickle'):
    with open('token.pickle', 'rb') as token:
        creds = pickle.load(token)
if not creds or not creds.valid:
    if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
    else:
        flow = InstalledAppFlow.from_client_secrets_file(
                'test.json', SCOPES)
        creds = flow.run_local_server(port=0)
    with open('token.pickle', 'wb') as token:
        pickle.dump(creds, token)

service = build('drive', 'v3', credentials=creds)

folder_id='valid folder id'
query=f"parents = '{folder_id}'"

response=service.files().list(pageSize=1000, q=query).execute()
files=response.get('files')
nextPageToken=response.get('nextPageToken')

while nextPageToken:
    response=service.files().list(pageSize=1000, pageToken=nextPageToken, q=query).execute()
    files.extend(response.get('files'))
    nextPageToken=response.get('nextPageToken')

df = pd.DataFrame(files)
print(df)

This is the output I'm getting:
          kind            id               name                        mimeType
0        drive#file    valid id          Testfolder           application/vnd.google-apps.folder
.           .             .                   .                            .
.           .             .                   .                            .
.           .             .                   .                            .
2000   drive#file    valid id          Testfolder2000         application/vnd.google-apps.folder

How can I modify this code to also list all the files in sub folders?
Lets say that the parent folder name is root and I have files in this path: root/folder1/folder2/folder.../test.png. So, the output I want is to have all the files/folders in a dataframe.

A: This is working for me:
from getfilelistpy import getfilelist
from oauth2client.service_account import ServiceAccountCredentials

SCOPES = ['https://www.googleapis.com/auth/drive']

creds = ServiceAccountCredentials.from_json_keyfile_name(file.json, SCOPES)
resource = {
    #"oauth2": creds,
    "service_account": creds,
    "id": "{0}".format(folderId),
    "fields": "files(name,id)",
}

res = getfilelist.GetFileList(resource)
df = pd.json_normalize(res['fileList'], record_path=['files'])


text:
Q: get full string before first second third etc. split I have a file location and I need to check if it exists.
The way I wan't to do it is like this:
        Dim route As String = ("C:\testing1\testing2\testing3\testing4\testing5\TEXTBESTAND.txt")
        If System.IO.File.Exists(route) Then
            MsgBox("BESTAAT HET WERKT!")
        Else
            Dim subroute() As String = route.Split("\"c)
            Dim counting As Integer = route.Split("\"c).Length - 1
            For count2 As Integer = 0 To counting - 1

                Dim firstbackslash As Integer = route.IndexOf("\")
                Dim backslash As Integer = route.IndexOf("\", firstbackslash + 1)
                Dim firstPart As String = route.Substring(0, backslash)
                MsgBox(firstPart)

            Next

What I try  to accomplisch is that I fist check if folder "C:" exists then "C:\testing1" then "C:\testing1\testing2" etc.
But I cant find something like this on the internet nor with some messing around...

A: Don't use string mnaipulation to work with file or folder paths. use the Path class.
One option:
Private Function GetExistingSubPath(fullPath As String) As String
    If Directory.Exists(fullPath) OrElse File.Exists(fullPath) Then
        Return fullPath
    End If

    Dim subPath = Path.GetDirectoryName(fullPath)

    If subPath Is Nothing Then
        Return Nothing
    End If

    Return GetExistingSubPath(subPath)
End Function

Sample usage:
Dim fullPath = "C:\testing1\testing2\testing3\testing4\testing5\TEXTBESTAND.txt"
Dim existingSubPath = GetExistingSubPath(fullPath)

Console.WriteLine(existingSubPath)

A: Here is an algorithm that that will give you all the paths starting from the root and building up to the final path including the filename.  You can use this to check for each folder and create them as you go if they don't exist:
Sub Main()
    Dim route As String = ("C:\testing1\testing2\testing3\testing4\testing5\TEXTBESTAND.txt")

    Dim fi As New System.IO.FileInfo(route)
    If Not fi.Exists Then
        Dim fileName As String = Path.GetFileName(route)

        Dim di As DirectoryInfo = fi.Directory
        Dim pathStack As New Stack(Of String)()
        pathStack.Push(di.Name)
        While Not IsNothing(di.Parent)
            di = di.Parent
            pathStack.Push(di.Name)
        End While

        Dim curPath As String = ""
        While pathStack.Count > 0
            curPath = Path.Combine(curPath, pathStack.Pop)
            ' ... do something with "curPath" in here ...
            ' ... like check for existence and create it ...
            Console.WriteLine(curPath)
        End While

        curPath = Path.Combine(curPath, fileName)
        ' ... do something with "curPath" in here ...
        ' ... this is the full path including the file on the end ...
        Console.WriteLine(curPath)
    End If

    Console.Write("Press Enter to quit...")
    Console.ReadLine()
End Sub

Output:
C:\
C:\testing1
C:\testing1\testing2
C:\testing1\testing2\testing3
C:\testing1\testing2\testing3\testing4
C:\testing1\testing2\testing3\testing4\testing5
C:\testing1\testing2\testing3\testing4\testing5\TEXTBESTAND.txt
Press Enter to quit...

A:
What I try to accomplisch is that I fist check if folder "C:" exists then "C:\testing1" then "C:\testing1\testing2" etc.

Noooooooooooo!
That's not how to do it at all!  The file system is volatile: things can change between each of those checks. Moreover, file existence is only one of many things that can stop file access.
It's much better practice to try to access the file in question, and then handle the exception if it fails. Remember, because of the prior paragraph you have to be able to handle exceptions here anyway. .Exists() doesn't save you from writing that code. And each check is another round of disk access, which is about the slowest thing it's possible to do in a computer... even slower than unrolling the stack for an exception, which is the usual objection to this idea.

A: I fixed it, know I can check if multiple text files are at the locations I need, if there not I place the Textfiles at the location I need them. Then I can add something in it. (I need to put a Location of something else in it.)
        Dim een As String = "C:\testing1\testing2\testing7\testing1\testing1\text.txt"
        Dim twee As String = "C:\testing1\testing2\testing7\testing2\testing1\text.txt"
        Dim drie As String = "C:\testing1\testing2\testing7\testing3\testing1\text.txt"
        Dim vier As String = "C:\testing1\testing2\testing7\testing4\testing1\text.txt"

        Dim Files As String() = {een, twee, drie, vier}

        For Each route As String In Files
            If System.IO.File.Exists(route) Then
                MsgBox("BESTAAT HET WERKT!")
            Else
                Dim subroute() As String = route.Split("\"c)
                Dim counting As Integer = route.Split("\"c).Length - 1
                Dim tel As Integer = route.Substring(route.LastIndexOf("\") + 1).Count
                Dim bestandnaam As String = route.Substring(route.LastIndexOf("\") + 1)
                For count2 As Integer = 0 To route.Length - tel - 1

                    Dim firstbackslash As Integer = route.IndexOf("\", count2)
                    Dim backslash As Integer = route.IndexOf("\", count2)
                    Dim Mapnaam As String = route.Substring(0, backslash)
                    count2 = firstbackslash

                    If System.IO.Directory.Exists(Mapnaam) Then
                    Else
                        System.IO.Directory.CreateDirectory(Mapnaam)
                    End If
                Next
                If System.IO.File.Exists(route) Then
                Else
                    Dim objStreamWriter As System.IO.StreamWriter
                    objStreamWriter = New System.IO.StreamWriter(route)
                    Dim label As String
                    Select Case route
                        Case een
                            label = "een"
                        Case twee
                            label = "twee"
                        Case drie
                            label = "drie"
                        Case vier
                            label = "vier"
                    End Select
                    Dim value As String = InputBox("Route invullen naar " & label)

                    'Dim objStreamWriter As New System.IO.StreamWriter(route)

                    objStreamWriter.Write(value)
                    objStreamWriter.Close()
                    'Using sw As System.IO.StreamWriter = System.IO.File.AppendText(route)
                    '    sw.WriteLine(value)
                    'End Using
                End If

            End If

        Next route


text:
Q: reset root password for some of mysql instance I searched a lot in the net, but the results I found is how to reset MySQL root password. But I want to know how to reset MySQL root password for some of my other MySQL instances...
Below are details:
OS: Ubuntu 14.04.1 LTS
MySQL: 5.5.40
I have 5 instances of mysql, I know how to reset the root password of the main MySQL installation, but I do not know how to do it for some of the others MySQL instances.
Here is how I'm trying to login:
mysql --socket=/var/run/mysqld/mysqld3.sock -u UserName -p
whatever user or pass I'm typing it shows me access denied for UserName.... etc...
This is my first question here, so excuse me if something is not explained clear enough

A: I had the same problem and used mysqld_safe --mysqld=/usr/sbin/mysqld --basedir=/home/test/data/mysql --datadir=/home/test/data --skip-grant-tables. The point is to provide data and/or instalation dirs (don't know if both are needed). I also had to tell where mysqld was but this might be specific to my case only. After starting the instance I wanted reset root password to I did all the actions needed to make it happen, killed all mysqld processes and repeated everything for another MySQL instance.


text:
Q: How to keep my services and process open even after user long press and kill the app I want to periodically fetch data from server and put in database without opening the app so I want my service always open with or without activity knows about it.
So I want to keep my service always open. This means I want my service not bounded by activity but right now when I long press and exit from app, the service stops.
Can somebody knows how to solve it. Thanks
Many apps like WhatsApp Facebook do it. Even though we long press and swapped out the app, the service and process still not closed. I want similar functionality

A: You can use foreground process if you need it always alive. Or a better solution is to listen for system broadcasts and start your service based on those.
For example it will be a great idea to start your service synching when the user starts charging his device.
Also you might be interested reading about Manipulating Broadcast Receivers On Demand to manage the battery life even better.

A: When you create a Service, in its onStartCommand() method, return START_STICKY. That way, even when you remove your application from recent Apps list, the service is killed first and then restarts again. This is because removing an application from recent apps list destroys that process. As Service is part of the same process, it will also get killed. As we are returning START_STICKY, service will start itself again. You can read about this at link


text:
Q: IIS 7.5 wont load web service javascript Im having an issue getting my webservice javascript loaded via a script manager
I register a service using the following code:
PageScriptManager.Services.Add(new ServiceReference("~/Services/ClientScriptService.asmx"));

which in turn generates an html script block
<script src="Services/ClientScriptService.asmx/js" type="text/javascript"></script>

This has worked for ages but now I get a 404 error from Services/ClientScriptService.asmx/js when I load the site onto Windows Server 2008 R2 which is running iis 7.5
It works fine on my windows 7 box
any ideas how to fix this?

A: In iis manager, i changed the Managed Pipeline mode of the app pool to integrated and it all started working... but I dont understand why


text:
Q: Meteor/Cordova: is there a way to activate a atmosphere js package only on android? The amazing 255kb:cordova-keyboard package works perfectly, but because of some bug that I could not figure out it prevents me from building for iphone. How can I add a package only for android? Is this possible? I only need this package to handle some situations where users close the keyboard with the Android hardware back button.

A: You can use Meteor's dynamic imports together with platform detection.
function isAndroid() {
  return navigator.userAgent.toLowerCase().indexOf("android") > -1;
}

async function getAndroidLib() {
  if(isAndroid) {
    return await import('path/to/lib');
  }
  else {
    return {};
  }
}


text:
Q: Find: Use regex to get all files with specific directory name in path, but without another specific directory name in path I'm trying to use find to return all file names that have a specific directory in their path, but don't have another specific directory anywhere in the file path. Something like:
myRegex= <regex>
targetDir= <source directory>
find $targetDir -regex $myRegex -print

I know I might also be able to do this by piping one find command into another, but I would like to know how to do this with a single regular expression.
For example, I want every file that has the directory "good" in it's path, but doesn't have the directory "bad" anywhere in its path no matter the combination. Some examples:
/good/file_I_want.txt #Captured
/good/bad/file_I_dont_want.txt #Not captured

/dir1/good/file_I_want.txt #Captured
/dir2/good/bad/file_I_dont_want.txt #Not captured

/dir1/good/dir2/file_I_want.txt #Captured
/dir1/good/dir2/bad/file_I_want.txt #Not captured

/bad/dir1/good/file_I_dont_want.txt #Not captured

Keep in mind some file names might contain "good" or "bad", but I only want to account for directory names.
/good/bad.txt #Captured
/bad/good.txt #Not captured

My research suggests I should use a Negative Lookahead and a Negative Lookbehind. However, nothing I have tried has worked so far. Some help would be appreciated. Thanks.

A: As Inian said, you don't need -regex (which is non standard, and the syntax varies greatly between the implementations that do support -regex¹).
You can use -path for that, but you can also tell find not to enter directories called bad, which would be more efficient than discovering every file in them for later filtering them out with -path:
LC_ALL=C find . -name bad -prune -o -path '*/good/*.txt' -type f -print

(LC_ALL=C so find's * wildcard doesn't choke on filenames with sequence of bytes not forming valid characters in the locale).
Or for more than one folder name:
LC_ALL=C find . '(' -name bad -o -name worse ')' -prune -o \
  '(' -path '*/good/*' -o -path '*/better/*' ')' -name '*.txt' -type f -print

With zsh, you can also do:
set -o extendedglob # best in ~/.zshrc
print -rC1 -- (^bad/)#*.txt~^*/good/*(ND.)

print -rC1 -- (^(bad|worse)/)#*.txt~^*/(good|better)/*(ND.)

Or for the lists in arrays:
good=(good better best)
bad=(bad worse worst)
print -rC1 -- (^(${(~j[|])bad})/)#*.txt~^*/(${(~j[|])good})/*(ND.)

To not descend into dirs called bad, or (less efficient like with -path '*/good/*' ! -path '*/bad/*'):
print -rC1 -- **/*.txt~*/bad/*~^*/good/*(ND.)

In zsh -o extendedglob, ~ is the except (and-not) globbing operator while ^ is the negation operator and # is 0-or-more-of-the-preceding-thing like regexp *. ${(~j[|])array} joins the elements of the array with |, with that | being treated as a glob operator instead of a literal | with ~.
In zsh, you'd be able to use PCRE matching after set -o rematchpcre:
set -o rematchpcre
regex='^(?!.*/bad/).*/good/.*\.txt\Z'
print -rC1 -- **/*(ND.e['[[ $REPLY =~ $regex ]]'])

But that evaluation of shell code for every file (including those in bad directories) is likely to make it a lot slower than other solutions.
Also beware that PCRE (contrary to zsh globs) would choke on sequences of bytes that don't form valid characters in the locale, and doesn't support multi-byte charsets other than UTF-8. Fixing the locale to C like for find above would address both for this particular pattern.
If you'd rather [[ =~ ]] only does extended regexp matching like in bash, you can also instead just load the pcre module (zmodload zsh/pcre) and use [[ -pcre-match ]] instead of [[ =~ ]] to do PCRE matching.
Or you could do the filtering with grep -zP (assuming GNU grep or compatible):
regex='^(?!.*/bad/).*/good/.*\.txt\Z'
find . -type f -print0 |
  LC_ALL=C grep -zPe "$regex" |
  tr '\0' '\n'

(though find still discovers all files in all bad directories).
Replace tr '\0' '\n' with xargs -r0 cmd if you need to do anything with those files (other than printing them one per line).

¹ In any case, I don't know any find implementation that supports perl-like or vim-like regular expressions which you'd need for look-around operators.

A: You don't need a regex for this, you can use the -path predicate to exclude directories with a specific name at any level
find . -type f -path '*/good/*' '!' -path '*/bad/*'

A: While it's likely less-efficient (though I'm not certain!) and less "correct" than find's powerful filtering (for example naive grep here will not work for names containing newline chars, though these are extremely rare and normally represent an error), it's often much easier to stack a few instances of grep which successively filter the results using simpler matches and inverse matches -v
This takes more caution around substrings to ensure you're really finding a directory name, but generally will give a much easier syntax to understand and may do all that you need!
find ./ | grep "/good/" | grep -v "/bad/" | grep '\.txt$'


text:
Q: value is not assigned to variable in react native Im new to react native.
There are two files one is parent and another is child. From child file Im receiving callbacks in parent file.
In that callback , as attached in screenshot, I have value in this.positionId, but when I assign that to another variable is results as 'undefined'. Can anyone tell me why this is happening ?
Child js file contains panResponder :
componentWillMount: function() {
this._animatedValueX = 0;
this._animatedValueY = 0;
this.state.pan.x.addListener((value) => this._animatedValueX = value.value);
this.state.pan.y.addListener((value) => this._animatedValueY = value.value);
  this._panResponder = PanResponder.create({
    onMoveShouldSetResponderCapture: () => true, //Tell iOS that we are allowing the movement
    onMoveShouldSetPanResponderCapture: () => true, // Same here, tell iOS that we allow dragging
    onPanResponderGrant: (e, gestureState) => {
      this.state.pan.setOffset({x: this._animatedValueX, y: this._animatedValueY});
      this.state.pan.setValue({x: 0, y: 0}); //Initial value
    },
    onPanResponderMove: Animated.event([
      // null,
      // {
      //   dx: this.state.pan.x, dy: this.state.pan.y
      // }
    ]), // Creates a function to handle the movement and set offsets
    onPanResponderRelease: (e, gesture) => {
      this.state.pan.flattenOffset(); // Flatten the offset so it resets the default positioning
      this.props.releaseValues(e, gesture);
    }
  });
  },

as you can see the line this.props.releaseValues(e, gesture) gives the callback to parent controller.
Code of positionID component -->
addElements: function(){
return this.props.ElementsToBeAdded.map(function(element,key){
  return <DraggableView
      color={element}
      positionId={key}
      key={key}
      releaseValues={(e, gesture) => {
        if(((gesture.moveX > (currentX + currentWidht)) ||
            (gesture.moveX < currentX)) ||
            ((gesture.moveY > (currentY + currentHeight)) ||
            (gesture.moveY < currentY)))
        {
          _this.setState({positionID:this.positionId});
          _this.props.releaseValuesFirstView(e,gesture,0);
        }
        else {
          _this.props.releaseValuesFirstView(e,gesture,-1);
        }
      }
    } />
});
 },

A: The positionId is a prop to the DraggableView component. It is not available outside of the component. You can use key instead. Inside the DraggableView component, you can access it by this.props.positionId


text:
Q: How do I set the time out for page load? In the middle of download using selenium, I'm getting this error:

The HTTP request to the remote WebDriver server for URL
  http://localhost:57557/session/4aa4c28a-083-4477-b10d-1b35eff42b/url
  timed out after 60 seconds.

I've tried to set the timeouts I've found:
        var driver = new FirefoxDriver(myOptions));
        driver.Manage().Timeouts().PageLoad = TimeSpan.FromMinutes(40);
        driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromMinutes(40);

but neither seems to affect ths 60s timeout. How do I fix that?

A: You can try the following:
  driver = new FirefoxDriver(service, firefoxOptions,TimeSpan.FromMinutes(40));


text:
Q: How do I close any previous Bluetooth sockets after my app starts? In my app, I open and close a Bluetooth socket on the same device each session and listen for data. When I close one, I make sure to close the input and output streams and then socket in a cancel method. Still, for some people the app keeps trying to read from the device. I know because I read logs that are from run() in the listening thread, where there is a flag for listening that's set to false in cancel, and the listening thread will end when the socket is closed due to an IOException, but this never happens, so the socket must still be opened. I see logs of attempted reads every second of every day even though the person isn't using the app. This might be because the app crashes and the cancel method isn't called. Either way I can't guarantee the cancel method will be called. How do I close any Bluetooth sockets that were previously opened when I start up my app, if these were all opened in new threads created independently?
This guy had the same problem but I didn't see any solution:
Android bluetooth connection doesn't close after application crash
The accepted answer is no good because:

*

*The current users haven't had the UncaughtExceptionHandler run that code yet and they need to have any previous connections closed when the new version is released

*The UncaughtExceptionHandler must have a reference to the sockets, which it doesn't have. I want to be able to close any Bluetooth sockets when the app starts.

*The guy who made that question asked how to get information about the socket to store for when the app starts up and you want to close them, and got no response.
EDIT:
How I open the socket (removed logging code):
        try {
            tmp.connect();;
        } catch (IOException e) {
            isConnected = false;
                try {
                    tmp = (BluetoothSocket) device.getClass().getMethod("createRfcommSocket",
                            new Class[] {int.class}).invoke(device, 1);
                } catch (Exception e2) {
                    e2.printStackTrace();
                }
                try {
                    tmp.connect();
                    setConnected();
                } catch (IOException e1) {
                    e1.printStackTrace();
                    isConnected = false;
                    cancel();
                }

How I close the socket:
    public void cancel() {

        isConnected = false;
        listening = false;
        try {
            if (manageConnection.mmInStream != null) {
                manageConnection.mmInStream.close();
                manageConnection.mmInStream = null;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            if (manageConnection.mmOutStream != null) {
                manageConnection.mmOutStream.close();
                manageConnection.mmOutStream = null;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            mmSocket.close();
            mmSocket = null;
            manageConnection = null;
        } catch (IOException e) {
              // Logging code
        }
    }
}

Listening:
        while (listening == true) {
            try {

                synchronized (ListeningActivity.lock) {
                    buffer = new byte[mmInStream.available()];

                    mmInStream.read(buffer);
....

            } catch (IOException e) {
                // Code that calls cancel()


text:
Q: Is there a scenario where the iOS purchases are restored automatically? I have an app with non-consumable products and a restore purchase button to trigger the restoreCompletedTransactions() flow. This is working fine and the app has even been approved by Apple Review. However, during my tests, sometimes the restore purchase was triggered automatically when the app starts, without any interaction with my restore purchases button. Do you know if this is expected on any scenario? All tests were done either through TestFlight or with sandbox accounts. On all of them, the payload had a "is_sandbox":true.
Additional information about the devices used for testing:

*

*iPhone X, iOS 16.0

*iPad (8th gen), iPadOS 15.6.1


text:
Q: Type Arguments and Bounds in Scala I have the following example:
import scala.concurrent.Future
trait MyTrait[F[_]] {

  case class Test[X[_]](x: X[Int])

  def test[G[_]]: F[Test[G]]

}
class LocImpl extends MyTrait[Future] {

  import scala.concurrent.ExecutionContext.Implicits.global

  def test[Option]: Future[Test[Option]] = {
    Future { new Test[Option](Option(1)) }
  }
}

Which fails compilation due to the reason that:
Type argument Option does not have the same kind as its bound [_$2]

I'm binding the generic type on the test function to Option and binding the trait to Future. So what is the problem here?
https://scastie.scala-lang.org/35pqGtqnQIGvZpGl4BTlFg

A: For the reference, the beginning was here: Scala Higher Kinded Types for Traits and Method Parameters
Option in def func[Option]... is not scala.Option, you're just defining a new type parameter calling it Option, it's the same as def func[A]..., you just called A Option, which shadows scala.Option.
This is a difference def func[A] (definition site) vs. func[A] (call site) i.e. whether A is a new type or known type.
It's better to use scalacOptions += "-Xlint:type-parameter-shadow" to avoid shadowing known types.
What causes this type error in a pattern guard for matching list of tuples
Strange Error with String in Scala 2.12.7
Type parameters applied to Scala Function
And since def test[Option]... is the same as def test[A]..., errors are understandable. Test[Option] aka Test[A] doesn't make sense because of a disagreement in kind. Option(1) aka A(1) doesn't make sense either.
So it should be just
def test: Future[Test[Option]] = {
  Future { new Test[Option](Option(1)) }
}

without type parameter. But then you break overriding. You seem to want having G an abstract type (to be implemented in inheritors) rather than method's type parameter (when the method must be defined for arbitrary G)
trait MyTrait[F[_]] {

  case class Test[X[_]](x: X[Int])

  type G[_]

  def test: F[Test[G]]

}
class LocImpl extends MyTrait[Future] {

  import scala.concurrent.ExecutionContext.Implicits.global

  type G[A] = Option[A]

  def test: Future[Test[Option]] = {
    Future { new Test[Option](Option(1)) }
  }
}

https://scastie.scala-lang.org/DmytroMitin/rk82W02DQOiFAJ7mghHcAQ/1
It's similar to having G a type parameter of the type class
trait MyTrait[F[_], G[_]] {

  case class Test[X[_]](x: X[Int])

  def test: F[Test[G]]

}
class LocImpl extends MyTrait[Future, Option] {

  import scala.concurrent.ExecutionContext.Implicits.global

  def test: Future[Test[Option]] = {
    Future { new Test[Option](Option(1)) }
  }
}

https://scastie.scala-lang.org/DmytroMitin/rk82W02DQOiFAJ7mghHcAQ/2


text:
Q: With JSONDecoder in Swift 4, can missing keys use a default value instead of having to be optional properties? Swift 4 added the new Codable protocol. When I use JSONDecoder it seems to require all the non-optional properties of my Codable class to have keys in the JSON or it throws an error.
Making every property of my class optional seems like an unnecessary hassle since what I really want is to use the value in the json or a default value. (I don't want the property to be nil.)
Is there a way to do this?
class MyCodable: Codable {
    var name: String = "Default Appleseed"
}

func load(input: String) {
    do {
        if let data = input.data(using: .utf8) {
            let result = try JSONDecoder().decode(MyCodable.self, from: data)
            print("name: \(result.name)")
        }
    } catch  {
        print("error: \(error)")
        // `Error message: "Key not found when expecting non-optional type
        // String for coding key \"name\""`
    }
}

let goodInput = "{\"name\": \"Jonny Appleseed\" }"
let badInput = "{}"
load(input: goodInput) // works, `name` is Jonny Applessed
load(input: badInput) // breaks, `name` required since property is non-optional

A: You can use a computed property that defaults to the desired value if the JSON key is not found.
class MyCodable: Decodable {
    var name: String { return _name ?? "Default Appleseed" }
    var age: Int?

    // this is the property that gets actually decoded/encoded
    private var _name: String?

    enum CodingKeys: String, CodingKey {
        case _name = "name"
        case age
    }
}

If you want to have the property read-write, you can also implement the setter:
var name: String {
    get { _name ?? "Default Appleseed" }
    set { _name = newValue }
}

This adds a little extra verbosity as you'll need to declare another property, and will require adding the CodingKeys enum (if not already there). The advantage is that you don't need to write custom decoding/encoding code, which can become tedious at some point.
Note that this solution only works if the value for the JSON key either holds a string or is not present. If the JSON might have the value under another form (e.g. it's an int), then you can try this solution.

A: Approach that I prefer is using so called DTOs - data transfer object.
It is a struct, that conforms to Codable and represents the desired object.
struct MyClassDTO: Codable {
    let items: [String]?
    let otherVar: Int?
}

Then you simply init the object that you want to use in the app with that DTO.
 class MyClass {
    let items: [String]
    var otherVar = 3
    init(_ dto: MyClassDTO) {
        items = dto.items ?? [String]()
        otherVar = dto.otherVar ?? 3
    }

    var dto: MyClassDTO {
        return MyClassDTO(items: items, otherVar: otherVar)
    }
}

This approach is also good since you can rename and change final object however you wish to.
It is clear and requires less code than manual decoding.
Moreover, with this approach you can separate networking layer from other app.

A: You can implement.
struct Source : Codable {

    let id : String?
    let name : String?

    enum CodingKeys: String, CodingKey {
        case id = "id"
        case name = "name"
    }

    init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        id = try values.decodeIfPresent(String.self, forKey: .id) ?? ""
        name = try values.decodeIfPresent(String.self, forKey: .name)
    }
}

A: You can implement the init(from decoder: Decoder) method in your type instead of using the default implementation:
class MyCodable: Codable {
    var name: String = "Default Appleseed"

    required init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        if let name = try container.decodeIfPresent(String.self, forKey: .name) {
            self.name = name
        }
    }
}

You can also make name a constant property (if you want to):
class MyCodable: Codable {
    let name: String

    required init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        if let name = try container.decodeIfPresent(String.self, forKey: .name) {
            self.name = name
        } else {
            self.name = "Default Appleseed"
        }
    }
}

or
required init(from decoder: Decoder) throws {
    let container = try decoder.container(keyedBy: CodingKeys.self)
    self.name = try container.decodeIfPresent(String.self, forKey: .name) ?? "Default Appleseed"
}

Re your comment: With a custom extension
extension KeyedDecodingContainer {
    func decodeWrapper<T>(key: K, defaultValue: T) throws -> T
        where T : Decodable {
        return try decodeIfPresent(T.self, forKey: key) ?? defaultValue
    }
}

you could implement the init method as
required init(from decoder: Decoder) throws {
    let container = try decoder.container(keyedBy: CodingKeys.self)
    self.name = try container.decodeWrapper(key: .name, defaultValue: "Default Appleseed")
}

but that is not much shorter than
    self.name = try container.decodeIfPresent(String.self, forKey: .name) ?? "Default Appleseed"

A: I came across this question looking for the exact same thing. The answers I found were not very satisfying even though I was afraid that the solutions here would be the only option.
In my case, creating a custom decoder would require a ton of boilerplate that would be hard to maintain so I kept searching for other answers.
I ran into this article that shows an interesting way to overcome this in simple cases using a @propertyWrapper. The most important thing for me, was that it was reusable and required minimal refactoring of existing code.
The article assumes a case where you'd want a missing boolean property to default to false without failing but also shows other different variants.
You can read it in more detail but I'll show what I did for my use case.
In my case, I had an array that I wanted to be initialized as empty if the key was missing.
So, I declared the following @propertyWrapper and additional extensions:
@propertyWrapper
struct DefaultEmptyArray<T:Codable> {
    var wrappedValue: [T] = []
}

//codable extension to encode/decode the wrapped value
extension DefaultEmptyArray: Codable {

    func encode(to encoder: Encoder) throws {
        try wrappedValue.encode(to: encoder)
    }

    init(from decoder: Decoder) throws {
        let container = try decoder.singleValueContainer()
        wrappedValue = try container.decode([T].self)
    }

}

extension KeyedDecodingContainer {
    func decode<T:Decodable>(_ type: DefaultEmptyArray<T>.Type,
                forKey key: Key) throws -> DefaultEmptyArray<T> {
        try decodeIfPresent(type, forKey: key) ?? .init()
    }
}

The advantage of this method is that you can easily overcome the issue in existing code by simply adding the @propertyWrapper to the property. In my case:
@DefaultEmptyArray var items: [String] = []

Hope this helps someone dealing with the same issue.

UPDATE:
After posting this answer while continuing to look into the matter I found this other article but most importantly the respective library that contains some common easy to use @propertyWrappers for these kind of cases:
https://github.com/marksands/BetterCodable

A: If you don't want to implement your encoding and decoding methods, there is somewhat dirty solution around default values.
You can declare your new field as implicitly unwrapped optional and check if it's nil after decoding and set a default value.
I tested this only with PropertyListEncoder, but I think JSONDecoder works the same way.

A: If you think that writing your own version of init(from decoder: Decoder) is overwhelming, I would advice you to implement a method which will check the input before sending it to decoder. That way you'll have a place where you can check for fields absence and set your own default values.
For example:
final class CodableModel: Codable
{
    static func customDecode(_ obj: [String: Any]) -> CodableModel?
    {
        var validatedDict = obj
        let someField = validatedDict[CodingKeys.someField.stringValue] ?? false
        validatedDict[CodingKeys.someField.stringValue] = someField

        guard
            let data = try? JSONSerialization.data(withJSONObject: validatedDict, options: .prettyPrinted),
            let model = try? CodableModel.decoder.decode(CodableModel.self, from: data) else {
                return nil
        }

        return model
    }

    //your coding keys, properties, etc.
}

And in order to init an object from json, instead of:
do {
    let data = try JSONSerialization.data(withJSONObject: json, options: .prettyPrinted)
    let model = try CodableModel.decoder.decode(CodableModel.self, from: data)
} catch {
    assertionFailure(error.localizedDescription)
}

Init will look like this:
if let vuvVideoFile = PublicVideoFile.customDecode($0) {
    videos.append(vuvVideoFile)
}

In this particular situation I prefer to deal with optionals but if you have a different opinion, you can make your customDecode(:) method throwable


text:
Q: Variance in linear regression model Suppose a linear model has been fitted with design matrix X and there are estimates $\boldsymbol{\hat{\beta}}$ and $\hat{\sigma}^{2}$. For given covariates, $x_{*}$, the predicted response is $\hat{y}_{*} = x_{*}^{T}\boldsymbol{\hat{\beta}}$.
Here is the bit I don't get: why is $Var(x_{*}^{T}\boldsymbol{\hat{\beta}}) = x_{*}^{T}(X^{T}X)^{-1}x_{*}\sigma^{2}$? How do you show that?

A: Under the assumptions:

*

*Expected value of the errors equal to zero.

*Constant variance of the errors.

*Independence of the errors.

*Normality of the response.

You have
$\Sigma_{\epsilon}=E[(\epsilon-0)(\epsilon-0)^t]=E[\epsilon\epsilon^t]=\sigma^2I$
$E[\hat{Y}]=X\beta$
$\hat{Y}=X(X^tX)^{-1}X^tY=HY$, where $H^2=H$ and $H=H^t$.
$\hat{Y}=X(X^tX)^{-1}X^tY=X(X^tX)^{-1}X^t(X\beta+\epsilon)=(Y-\epsilon)+H\epsilon$
Than you have:
$\Sigma_{\hat{Y}}=E[(\hat{Y}-X\beta)(\hat{Y}-X\beta)^t]=E[(Y-\epsilon+H\epsilon-Y+\epsilon)(Y-\epsilon+H\epsilon-Y+\epsilon)^t]=
E[H\epsilon\epsilon^tH]=HE[\epsilon\epsilon^t]H=H\sigma^2I=X(X^tX)^{-1}X^t\sigma^2I$
.
If you take the elements of the diagonal of $\Sigma_{\hat{Y}}$, than you find the variance of each element of the vector $\hat{Y}$.


text:
Q: Is the order preserved when inserting into multiple tables in Postgres I have 3 tables created and there is no foreign key, so they are not related to each other.
In my program, I use JDBC to interact with DB. Now I have a query to insert into each of the table at once:
insert into table1 values (...);
insert into table2 values (...);
insert into table3 values (...);

Can I expect that the insert statements will be executed in order, and then completed in order?
In another word, can I expect table1 to have the inserted row first, then table2, and finally table3?

A: From your program's perspective the inserts will be executed in order.
From outside of your transaction, the inserts will appear simultaneously when your transaction is committed.


text:
Q: Limiting Access by Permission thanks for viewing this. I have a db that has users, roles & user_roles.
What I am trying to achieve is a login that will select users who have Admin or Associate permissions. The login then uses name and password to permit access.
My SQL syntax thus far is -
SELECT * FROM users
LEFT JOIN ON user_roles
ON user.id=user_roles.userid AND roleid IN (Administrator, Associate)
WHERE username = '$username' AND password = '$password'";

I am not sure where I am going wrong.
Thanks in advance for your help.

A: Try replacing "LEFT JOIN" by "INNER JOIN"

A: Here's how I'd write the query:
$stmt = $pdo->prepare("
SELECT (u.password = :password) AS password_is_correct,
  (r.roleid IS NOT NULL) AS role_is_authorized
FROM users u
LEFT JOIN ON user_roles r
  ON u.id=r.userid AND r.roleid IN (Administrator, Associate)
WHERE u.username = :username");

$stmt->execute(array(":password"=>$password, ":username"=>$username));

This allows you to distinguish between the three conditions: (1) username does not exist, (2) password is wrong, or (3) role is not authorized.
PS: Should "Administrator" and "Associate" be quoted or something?  The way you're using them, they look like identifiers rather than values.


text:
Q: Messy graph when plotting fitted values from flexmix I am trying to plot 3 regression lines for 3 components in the data estimated via flexmix package.
However, when I try to plot predicted values for the first component, the result is a messy graph with lines connecting to each other.

These are my codes:
m_1 <- flexmix(x ~ y + z, data=set2, cluster=clstr)
yhat <-fitted(m_1)
plot(x, y, options=...)
lines(x, yhat[,1], options=...)

Online I found some hints about > order() with no result
reorder <- order(yhat[,1])

lines(x[reorder], yhat[,1][reorder], options=...)

It results in a continuous line that looks like a time series with high volatility.
The other two components are working fine. Any idea on how to solve this?

A: The solution is here I think :
http://pages.mtu.edu/~shanem/psy5220/daily/Day19/Mixture_of_regressions.html


text:
Q: CordovaWebView inside a Fragment returns NullPointerException I'm trying to implement the CordovaWebView (2.2.0) inside a fragment but it's returning an error when trying to inflate the layout.
My xml:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
         android:layout_width="fill_parent"
         android:layout_height="fill_parent">

<org.apache.cordova.CordovaWebView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:id = "@+id/mainView"/>

</FrameLayout>

My onCreateView:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {

    View v = inflater.inflate(R.layout.cordovawebview, container); // <--- the error occurs here!

    return v;
}

Error:

10-25 15:52:02.839: ERROR/AndroidRuntime(2878): FATAL
  EXCEPTION: main
      android.view.InflateException: Binary XML file line #21: Error inflating class org.apache.cordova.CordovaWebView
  NullPointerException CordovaWebView.java line 691

int id = getResources().getIdentifier("config", "xml", this.cordova.getActivity().getPackageName());

It seems that the resource is null here.
I have already checked it and the config.xml file is in the xml folder.
I can implement it in a FragmentActivity but I need it in a Fragment.
Any ideas?
Thanks in advance.

A: @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {

    View v = inflater.inflate(R.layout.cordovawebview, container, false); // <--- add false parameter
    CordovaWebView webView = (CordovaWebView)v.findViewById(R.id.mainView);

    return v;
}

A: CordovaWebViews need to be created on the activity the fragment is on as well as the fragment itself. You can create your own ContextWrapper and supply it to your inflater to handle doing this for you.
Here is a step by step guide on how to do just that: https://github.com/Adobe-Marketing-Cloud/app-sample-android-phonegap/wiki/Embed-Webview-in-Android-Fragment


text:
Q: How to remove elements different than numbers of a Scipy Sparse Matrix? I have a COO sparse matrix in which every element is a dictionary. I want to filter that matrix by some conditions, nevertheless when I try to multiply the matrix by the filter I get an exception TypeError: no supported conversion for types: (dtype('O'),). Is it possible to avoid this issue?
from scipy.sparse import coo_matrix
import numpy as np

row = np.array([0, 0, 1, 2, 2, 2])
col = np.array([0, 2, 2, 0, 1, 2])
data = [{"x": 1}, {"y": -1}, {"x": -1}, {"x": 2}, {"t": -2}, {"z": 2}]
matrix = coo_matrix((data, (row, col)), shape=(3, 3))

matrix.multiply(np.array([0, 1, 0])) # Raises exception

A: It is possible to filter a coo_matrix, nevertheless it isn't straightforward. First you must create your filter mask with `True/False' values and then use it to index the matrix's column, rows and data vectors.
In [22]: mask = [True, False, False, True, False, False]

In [23]: matrix.data[mask]
Out[23]: array([{'x': 1}, {'x': 2}], dtype=object)

In [24]: matrix.col[mask]
Out[24]: array([0, 0], dtype=int32)

In [25]: matrix.col[row]
Out[25]: array([0, 0, 2, 2, 2, 2], dtype=int32)

In [26]: matrix.col[mask]
Out[26]: array([0, 0], dtype=int32)


text:
Q: How to increment or add storage (up to 500Gb) to new AWS instance? I want to create new instance in the AWS cloud. The standard space is 8Gb which is not enough for my purpose.
I have my application in the /var/www-directory where files from users get uploaded. I need the additional space for these files. After the user uploaded the file i will move them to my S3 storage.
How can i increment the storage limit of a new instance or add new volume (EBS) mounted as /dev/sdb at /var?


text:
Q: Distributed make for several computers on same file system Is there a make equivalent to distribute task among several computer, all operating on the same filesystem? (without having to
example : instead of calling directly the compile command, juste raise it and then one computer available execute it ? (without rsh like dmake)

A: You could try ElectricAccelerator, a distributed, high-performance reimplementation of GNU make.  It uses lightweight automatic virtualization to handle filesharing between participating computers, as well as some clever technology to ensure correct parallel builds even if your dependencies are incomplete.  It's a commercial product, but you can download and try ElectricAccelerator Huddle, the freemium variant.
Alternatively you could try something like distcc, which can distribute gcc (and gcc-like) compile commands to remote systems, in conjuction with good-old gmake -j.
Disclaimer: I'm the chief architect of ElectricAccelerator


text:
Q: Why can't i delete my todo item using filter? I'm trying to make the function to delete my todo item but when click on the delete button, nothing happens, is there anything wrong with my codes, plsease help me! Thank you so much!
import React, { useState } from "react";

function App() {
  const [value, setValue] = useState("");
  const [todos, setTodos] = useState([]);

  // you can use the submit itself, no need for an extra addTodo function
  handleSubmit = (e) => {
    console.log("x");
    e.preventDefault();
    setTodos([...todos, value]);
    setValue("");
  };

  deleteTodo = (id) => {
    console.log("delete")
    const removedArr = [...todos].filter(todo => todo.id !== id);

    setTodos(removedArr);
  }

  return (

      <form onSubmit={handleSubmit}>
        <input
          onChange={(e) => setValue(e.target.value)}
          type="text"
          placeholder="add todo"
        />
        <button type="submit">Add</button>
      </form>
      {todos.map((todoValue) => (

        {todoValue} <button deleteTodo={()=>deleteTodo(id)}>x</button>

      ))}

  );
}
export default App;

Link codesandbox: https://codesandbox.io/s/tender-cdn-cy3w4?file=/src/App.js:0-933

A: see this code
import React, { useState } from "react";

function App() {
  const [value, setValue] = useState("");
  const [todos, setTodos] = useState([]);

  // you can use the submit itself, no need for an extra addTodo function
  handleSubmit = (e) => {
    console.log("x");
    e.preventDefault();
    setTodos([...todos, value]);
    setValue("");
  };
  deleteTodo = (id) => {
    console.log("delete");
    console.log(id);
    const removedArr = [...todos].filter((todo) => todo !== id);

    setTodos(removedArr);
  };
  return (

      <input
        onChange={(e) => setValue(e.target.value)}
        type="text"
        placeholder="add todo"
      />
      <button type="submit" onClick={handleSubmit}>
        Add
      </button>

      {todos.map((todoValue) => (

          {todoValue} <button onClick={() => deleteTodo(todoValue)}>x</button>

      ))}

  );
}
export default App;

**Work Demo**
https://codesandbox.io/s/wonderful-estrela-k5xvu?file=/src/App.js:0-932

A: There is two mistakes in your code :

*

*button should call the deleteTodo function when user clicks on that button i.e onClick() function

*id is undefined.
Please refer to this sandbox code example.
I corrected your code and now it is working .Link to sandbox
Following the code written inside sandbox.
import React, { useState } from "react";

function App() {
  const [value, setValue] = useState("");
  const [todos, setTodos] = useState([]);

  // you can use the submit itself, no need for an extra addTodo function
  const handleSubmit = (e) => {
    console.log("x");
    e.preventDefault();
    setTodos([...todos, value]);
    setValue("");
  };

  const deleteTodo = (index) => {
    console.log("delete");
    const removedArr = [...todos].filter((todo, i) => index !== i);

    setTodos(removedArr);
  };

  return (

      <form onSubmit={handleSubmit}>
        <input
          onChange={(e) => setValue(e.target.value)}
          type="text"
          placeholder="add todo"
        />
        <button type="submit">Add</button>
      </form>
      {todos.map((todoValue, index) => (

          {todoValue} <button onClick={() => deleteTodo(index)}>x</button>

      ))}

  );
}
export default App;

A: you should use onClick in button and your list does not have id so use todo instead of todo.id:
      deleteTodo = (id) => {
     const removedArr = [...todos].filter(todo => todo !== id);
        setTodos(removedArr);
      }

      return (

          <form onSubmit={handleSubmit}>
            <input
              onChange={(e) => setValue(e.target.value)}
              type="text"
              placeholder="add todo"
            />
            <button type="submit">Add</button>
          </form>
          {todos.map((todoValue) => (

            {todoValue} <button onClick={()=>deleteTodo(todoValue)}>x</button>

          ))}

      );
    }
    export default App;


text:
Q: Running LibreOffice soffice.exe on Windows from PHP exec() stuck I am having issues converting Word documents to PDF using soffice.exe in LibreOffice 5.4.6 - running on Windows Server 2012 R2 via IIS.
After changing directory into the relevant LibreOffice program directory in PHP (chdir), the command I am calling in PHP is:
$cmd = "soffice.exe --headless -convert-to pdf -outdir ".sys_get_temp_dir()." ".$workingdoc;
exec($cmd);

Where $workingdoc is the full path to the .docx Word file.
sys_get_temp_dir() on my system translates to C:\Windows\Temp
If I echo out the $cmd variable to a browser, then copy-paste that output into a cmd.exe Command Prompt interactively on the server, a PDF gets produced without issue.
For example, an echoed out $cmd that I copy-paste into a cmd.exe prompt might be:
soffice.exe --headless -convert-to pdf -outdir C:\Windows\TEMP C:\Windows\Temp\pdD125.docx

However, running this $cmd variable from PHP via exec() in the same user context as what I interactively initiated the cmd.exe from just hangs. I can see soffice.exe in Task Manager with RAM usage hovering between 10-20MB. Additionally, in my C:\Windows\Temp folder, I get multiple empty folders continuously created every second whilst soffice.exe remains running, all with a name in the format of lu*.tmp
For example, one of the many folders that get produced are lu1124fq1pud.tmp
The PDF does not get created, and the only way to allow the PHP script to finish and stop the lu folders being created (besides PHP timeouts) is to force end the soffice.exe task in Task Manager.
So, why does the soffice.exe command work when called from cmd.exe, but not via PHP, even though through both methods they are launched in the same user context?

A: It turns out this is a known issue as reported here. In short, it appears to be a user permissions issue.
I solved my issue by first creating a temporary LibreOffice user profile folder in the system's temp directory (don't make the directory, allow the soffice.exe to initialise it):
$tempLibreOfficeProfile = sys_get_temp_dir()."\\LibreOfficeProfile".rand(100000, 999999);

Then add an env parameter to the soffice.exe command:
$cmd = 'soffice "-env:UserInstallation=file:///'.str_replace("\\", "/", $tempLibreOfficeProfile).'" --headless --convert-to pdf -outdir "'.sys_get_temp_dir().'" '.$workingDoc;
exec($cmd);

Make sure to clean up your temporary profile folder once finished to not clog up your temp, for example:
exec('rmdir /S /Q "'.$tempLibreOfficeProfile.'"');


text:
Q: Get total sum for each month in DAX I have a tabular mode analysis server connected to a sql server database. I want to get the total x per month, and I have the total x per day. So for example, I have a table DailyEvent with the first 2 columns like this, and I want the column "MonthXCount":
TimeID   XCount MonthXCount
20160429  3          11
20160430  8          11
20160501  4           4

So the total XCount for April is 11, so for every day in April I want 11. The total X count for may is 4 (so far).
What I have now is a MonthToDate total I think, calculated as:
=TOTALMTD(SUM('DailyEvent'[XCount]),'DailyEvent'[TimeID])

But I want to then have a column that puts the last value of the month in for every day of the month.
The end goal is to have a XCount by month graph in PowerBI, so I might not need to add the column here... I might be able to just tell PowerBi to graph the last day of the month, but I'm not sure how to do that and thought this would be easier.

A: SqlConnection sqlConnection1 = new SqlConnection("Your Connection String");
SqlCommand cmd = new SqlCommand();
SqlDataReader reader;

cmd.CommandText = "begin transaction t
    update table dailyevent
    set monthxcount = (select top(1) monthxcount
                            from dailyevent
                            where MONTH(timeID) = 4
                            order by monthxcount desc)
    where MONTH(timeID) = 4

    --commit only if the rows affected corresponds to the number of rows found for the month of april.

    commit";
cmd.CommandType = CommandType.Text;
cmd.Connection = sqlConnection1;

sqlConnection1.Open();

reader = cmd.ExecuteReader();
// Data is accessible through the DataReader object here.

sqlConnection1.Close();

A: Do you have a Calendar Table in your model connected to your data table?
If yes, let's say the Calendar Table is called DimDate and that it contains a column called YearMonth, then the formula would be:
Month Sales := SUMX(
                    VALUES(DimDate[YearMonth]),
                    SUM(DailyEvent[XCount])
                    )

If you don't have a Calendar Table, then you can create a calculated column in your table called YearMonth with this formula:
=LEFT(DailyEvent[TimeID], 6)

Then calculate the sum of Month Sales with:
Month Sales := SUMX(
                    VALUES(DailyEvent[YearMonth]),
                    SUM(DailyEvent[XCount])
                    )

Hope this helps!
A note with respect to the formula you were using:
Time intelligence functions, such as TOTALMTD, require Calendar Tables. Therefore, be sure to add one to your data model before using them.
Edit:
Another solution could be to create a date column:
     = DATE(
            LEFT(DailyEvent[TimeID], 4),
            MID(DailyEvent[TimeID], 5, 2),
            1)

Then drop that column in the X-axis of the graph and the XCount column in the Y-axis.

A: You could use a measure calculation in Power BI, or in SSAS model, if there is a calendar table, make sure it is marked as date table otherwise the time logic will not work. I used the following query (DAX) it calculates the Month To Date
MtD :=CALCULATE(SUM('DailyEvent'[XCount]),DATESMTD('DateTabe'[calendarDate]))

If however there is no calendar or you are working with the be-spoke calendar, this may help
Running Totals Whitout a Traditional Calendar Table


text:
Q: How to drag files into an app's Dock icon in macOS Sierra? Up until the macOS Sierra update, I was able to do the following, which I used quite a lot:

*

*Start writing an email in Outlook for Mac or in Mail.app.

*Select a file in Finder that I want to attach to the email.

*Drag the file to Mail.app (or Outlook) Dock icon.

*Hover over the Dock icon until the icon flashes a couple of times and then shows the open application windows. You can press the Space bar to speed up the process of showing the application windows.

*Drop the file into the email window that I opened in the first step.

This has worked fine for years, up until the macOS Sierra update. With Sierra, the app icon in the Dock flashes once or twice and then nothing happens at all.
The settings described in this question also no longer seem to be in Sierra - I can't find them in the Finder Preferences. It looks like this has been moved to Preferences > Accessibility > Mouse & Trackpad, although it does not help.
Dragging files into other application windows (this does not only affect Finder and email) has become a lot more difficult due to this.
Is this a known bug, or is there a workaround that allows to use the above process again for this use case?

A: I have just upgraded to Sierra and I am experiencing exactly the same problem, and not only with Outlook.
I hope this bug will be fixed in the next release of Sierra.
In the meantime, immediately after beggining dragging I press F9 to show Mission Control and select the target window.
Most times, this works.


text:
Q: How do I "get item" with an integer? I was wondering how I could do the "get item function" on an integer.
For example:
x='abcde'
print x[0:3]

That would print out abc
I was wondering how I would do that with integers.
I tried this:
x=12345
print x[0:3]

That doesn't work. Is there a way to do this for integers?

A: Try this:
x = 12345
print str(x)[0:3]

We convert the integer to a string, perform the string slicing and print it.
If you want to store it as a number:
new_x = int(str(x)[0:3])

You can omit the 0 in [0:3] and simply write this: [:3].


text:
Q: Play Framework Application and embedded Database packaging I implemented a server application with Play Framework.
I built native packages for different Operating Systems (Linux, Windows, Mac OS X) with SBT Native Packager.
This application requires a NoSQL Database. In particular, I am using MongoDB. Is there a way to embed MongoDB binary/package in my native package? Is this the best practice? Or do you suggest to install MongoDB and my Play application with two different packages?
If it is not possible / recommended to embed MongoDB in a package, do you suggest another DBMS (for instance Nitrite Database)? Thanks

A: This is not really best practise. Play has H2 in-memory DB embedded but this is only intended for development (because it is quicker than something that reads/writes to disk as well).
You really want to have your Mongo (or whatever other data store you decide to use) instance running in a different process, and packaged, deployed, stopped, started separately from your Play application.
You could probably figure out how to package it with your Play application and then have some script run during app startup to setup the database and load any existing data in -dbpath ie. whenever you redeploy/restart your application. But then you would have to stop/redeploy your Mongo binaries each time you redeploy a code change. You may update your application several times over a year but you are unlikely going to want to update your Mongo binaries as often. I could go on, but don't do it. It is best practise to manage your data stores separately from your applications.


text:
Q: Android Intent information passing I'm new to Android and have been looking around for an answer but can't seem to resolve my problem.  I have an intent that is passing information from one activity to another.  The activity receiving will display it when setContentView() is set to TextView.  If I try to use my xml file with setContentView() it will not display the String.
The Intent
public void clockin (View view){
    Intent intent = new Intent (getApplicationContext(), Mainmenu.class);
    String timedate = java.text.DateFormat.getDateTimeInstance().format(Calendar.getInstance90.getTime()0;
    intent.putExtra("TIME_DATE", timedate);
    startActivity(intent);

The Activity
public class Mainmenu extends Activity{
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        Bundle extras = getIntent().getExtras();
        if(extras!=null){
        String timedate = extras.getString("TIME_DATE");

        TextView textView = new TextView (this);
        text.View.setTextSize(20);
        text.View.setText(timedate);
        setContentView(R.layout.activity_mainmenu);}}

The xml
<TextView
     android:id="@+id/TIME_DATE"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:textSize="20sp"
     />

A: Android idiom for naming extras that would prevent your problem:
   Intent intent = new Intent (getApplicationContext(), Mainmenu.class);
   intent.putExtra(Mainmenu.EXTRA_DATE, timedate)

Activity:
    public class Mainmenu extends Activity {

      public final static String EXTRA_DATE="TIME_DATE":

      protected void onCreate(Bundle savedInstanceState){

          ....

          String timedate = extras.getString(EXTRA_DATE);

A: Your MainMenu should be
 public class Mainmenu extends Activity{
 protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    // setContentView(R.layout.activity_mainmenu);
    Bundle extras = getIntent().getExtras();
    if(extras!=null){
    String timedate = extras.getString("Time_Date");// key must match
    TextView textView = new TextView (this); // initialize textview
    textView.setTextSize(20);
    textView.setText(timedate);
    setContentView(textView);   // set textview as layout content
    }
    }

              or

activity_mainmenu.xml
 <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:textSize="20sp"
        android:text="TextView" />

</RelativeLayout>

MainMenu
     public class Mainmenu extends Activity{
     protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_mainmenu);
    Bundle extras = getIntent().getExtras();
    if(extras!=null){
    String timedate = extras.getString("Time_Date");
    TextView textView = (TextView) findViewById(R.id.textView1);
    textView.setText(timedate);
    }
    }

A: The name of the extra is case sensitive, viz:
String timedate = extras.getString("Time_Date");

A: In your second activity, try this:
Intent intent = getIntent();
String timedate = intent.getStringExtra("Time_Date");


text:
Q: JAVA regex to add white space between character and number I am trying to write a java regex to add white space between character and number. I tried few of them but its not working.
For example: This string "FR3456", I would like this to be converted to "FR 3456".
Any help will be appreciated.

A: You can add a space between non-digit and digit using Positive Lookbehind & Lookahead
System.out.println("FR3456".replaceAll("(?<=\\D)(?=\\d)"," "));

Here
\D  A non-digit: [^0-9]
\d  A digit: [0-9]

for more info have a look at Java Regex Pattern

Or use (?<=[^0-9])(?=[0-9])
Here is online demo
Pattern explanation:
  (?<=                     look behind to see if there is:
    [^0-9]                   any character except: '0' to '9'
  )                        end of look-behind
  (?=                      look ahead to see if there is:
    [0-9]                    any character of: '0' to '9'
  )                        end of look-ahead


text:
Q: effectively unlocking an SQLite database I have a program which frequently crashes (Zotero), leaving its SQLite database locked and inaccessible for use by the restarted program unless I reboot (which I really want to avoid). So this does not work (using the generic name, db.sqlite in place of the actual file in my case, zotero.sqlite):
sqlite3 db.sqlite
sqlite> .backup main backup.sqlite
Error: database is locked

Based on an answer here, I tried:
echo ".dump" | sqlite3 db.sqlite | sqlite3 db.sqlite2
mv db.sqlite2 db.sqlite

db.sqlite2 is 0KB so this obviously did not work. Inspired by another thread, I also tried
echo '.dump' | sqlite3 db.sqlite > db.dump
cat db.dump | sqlite3 db.sqlite2
mv db.sqlite2 db.sqlite

which leads to db.sqlite2 which is slightly smaller in filesize to db.sqlite, and Zotero (the file which requires the database) was not able to recognize its contents.
So this seems like a very brute force way of doing it, but worked:
cp -pv db.sqlite db.sqlite2
rm -f db.sqlite
mv db.sqlite2 db.sqlite

I wonder if there are any drawbacks to this solution and why the other methods are proposed before this one.

A: It may be that for transaction control zotero uses table based locking to prevent database inconsistencies during concurrent access. When one user uses the database it locks the tables so only they can use it and prevent them seeing the database in an inconsistent state. However when it crashes it's not releasing these locks.
In a well setup database upon crashing the transaction should be rolled back (undone) and locks released to prevent data being left in an inconsistent state or the tables being locked and you having to manually release them.
I've read on the internet that storing the database on a Network File System can interfere with SQLites locking mechanism, by changing the database location to a none network location you should be able to avoid these problems unless it's somewhere else.
If it is somewhere else I would recommend making a copy of your database and using the zotero database repair tool to try and identify any faults in set up etc that could cause this and repair them: https://www.zotero.org/utils/dbfix/
I hope this helps.


text:
Q: Добавить диапазон дат к каждому id Есть df с одним столбцом id. Мне необходимо к каждому id добавить диапазон дат. id много больше 100 тысяч. подробнее на фото. Для примера для двух id добавлены даты от 01.04.2022 до 03.04.2022.

A: Поскольку непонятно, сколько дат, покажу вариант с фиксированным набором дат. Если число дат будет разное, будет чуть сложнее всё:
import pandas as pd

df = pd.DataFrame({'id': range(10)})
dates = ['2022-01-01', '2022-01-02', '2022-01-03']
id_list = [id_ for id_ in df.id for _ in range(len(dates))]
dt_list = dates * df.shape[0]
df_new = pd.DataFrame({'id': id_list, 'dates': dt_list})

id
dates

0
0
2022-01-01

1
0
2022-01-02

2
0
2022-01-03

3
1
2022-01-01

...
...
...

Но суть будет в любом случае такая же - набрать значения в два списка и потом сделать из них новый датафрейм.


text:
Q: Options for Scala DataStreamReader Class 'format' Value Member I'm new to Scala and Spark but I'm working on "POCing" Structured Streaming and one of the available API class is DataStreamReader accessed by a sample code below:
val spark: SparkSession = ...
// Read text from socket
val socketDF = spark
  .readStream
  .format("socket")
  .option("host", "localhost")
  .option("port", 9999)
  .load()

.readStream returns DataStreamReader class and is furthered accessed with .format member and you can specify other parameters besides "socket" i.e. "text" or "parquet".  Information on these parameters are vague and not fully listed on Spark's Structured Steaming Programming Guide.  and I've tried looking at the DataStreamReader API but it doesn't tell you any of the available parameters.  Where can I find these information?

A: You have given all fields. There is no mistake there. You can refer this blog
First run the netcat server on different tab nc -lk 9999
In your spark shell,
    import org.apache.spark.sql.functions._
    import org.apache.spark.sql.SparkSession

    val spark = SparkSession
      .builder
      .appName("StructuredNetworkWordCount")
      .getOrCreate()

    import spark.implicits._

    val lines = spark.readStream
      .format("socket")
      .option("host", "localhost")
      .option("port", 9999)
      .load()

    val words = lines.as[String].flatMap(_.split(" "))

    val wordCounts = words.groupBy("value").count()

val query = wordCounts.writeStream
  .outputMode("complete")
  .format("console")
  .start()

query.awaitTermination()

When you type anything on netcat server, it will be consumed by spark..
nc -lk 9999
hi
this is first example of spark structtyred
streaing

-------------------------------------------
Batch: 0
-------------------------------------------
+-----+-----+
|value|count|
+-----+-----+
|   hi|    1|
+-----+-----+

-------------------------------------------
Batch: 1
-------------------------------------------
+-----------+-----+
|      value|count|
+-----------+-----+
|    example|    1|
|         is|    1|
|      spark|    1|
|         of|    1|
|         hi|    1|
|       this|    1|
|      first|    1|
|structtyred|    1|
+-----------+-----+

-------------------------------------------
Batch: 2
-------------------------------------------
+-----------+-----+
|      value|count|
+-----------+-----+
|   streaing|    1|
|    example|    1|
|         is|    1|
|      spark|    1|
|         of|    1|
|         hi|    1|
|       this|    1|
|      first|    1|
|structtyred|    1|
+-----------+-----+

A: does the spark structured streaming (2.2.1) support MySQL as the data source. Spark streaming supports custom receivers . Does the spark structured streaming has similar facility?