text:
Q: Is there a shortcut for collecting commits since the beginning of the branch? When doing an interactive rebase on a feature branch, I usually want to pull only the commits that are new in that branch into the rebase, which means I need to first check my log, count the commits, and specify git rebase HEAD~n --interactive where n is the number of commits.
Is there any shortcut command to just collect the commits I want?

A: If I understand your question correctly, you don't even have to worry about "commit counting" to rebase a feature branch onto a "main" branch.
Say you have a feature branch f1 created from master some time ago. If you later want to rebase f1 on master, assuming your current branch is f1, you simply have to run git rebase master.
Git knows when f1and master diverged and can thus know which commits must be rebased onto master.

A: You can use git merge <feature-branch> <origin branch>  This will give the latest SHA that is common for both branchs.  Then you will be able to do the interactive rebase from that commit.


text:
Q: Unable to connect Hive with MongoDB using mongo-hadoop connector I am trying to install and configure hive with mongo-hadoop-core 2.0.2, for the first time. I have installed hadoop 2.8.0, Hive 2.1.1 and MongoDB 3.4.6. and everything works fine when running individually.
My problem is, I am not able to connect MongoDB with Hive. I am using mongo-Hadoop connector for this as mentioned here https://github.com/mongodb/mongo-hadoop/wiki/Hive-Usage
The required jars are added to Hadoop and Hive lib. Even I add them in hive.sh or runtime from hive console.
 I am getting error while executing Create table query
My Query is
CREATE EXTERNAL TABLE testHive
(
    id STRING,
    name STRING
)
STORED BY 'com.mongodb.hadoop.hive.MongoStorageHandler'
WITH SERDEPROPERTIES('mongo.columns.mapping'='{"id":"_id","name":"name"}')
TBLPROPERTIES('mongo.uri'='mongodb://localhost:27017/hiveDb.testHive');

And I get the following error
FAILED: Execution Error, return code 1 from org.apache.hadoop.hive.ql.exec.DDLTask. com/mongodb/hadoop/io/BSONWritable
hive> ERROR hive.ql.exec.DDLTask - java.lang.NoClassDefFoundError: com/mongodb/hadoop/io/BSONWritable
    at com.mongodb.hadoop.hive.BSONSerDe.initialize(BSONSerDe.java:132)
    at org.apache.hadoop.hive.serde2.SerDeUtils.initializeSerDe(SerDeUtils.java:537)
    at org.apache.hadoop.hive.metastore.MetaStoreUtils.getDeserializer(MetaStoreUtils.java:424)
    at org.apache.hadoop.hive.metastore.MetaStoreUtils.getDeserializer(MetaStoreUtils.java:411)
    at org.apache.hadoop.hive.ql.metadata.Table.getDeserializerFromMetaStore(Table.java:279)
    at org.apache.hadoop.hive.ql.metadata.Table.getDeserializer(Table.java:261)

It shows that com/mongodb/hadoop/io/BSONWritable class is not in classpath but I have added the required(mongo-hadoop-core.jar) jar and class are present in the jar.
The version of jars I am using
mongo-hadoop-core 2.0.2,
mongo-hadoop-hive 2.0.2,
mongo-java-driver 3.0.2
Thanks

A: You need to register jars explicitly. In your Hive script, use ADD JAR commands to include these JARs (core, hive, and the Java driver), e.g., ADD JAR /path-to/mongo-hadoop-hive-<version>.jar;.
If you are running from Hive shell, use like this.
hive> ADD JAR /path-to/mongo-hadoop-hive-<version>.jar;
Then execute your query.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is !document.cookie reliable? I'm wondering if using the following Javascript code is reliable:
if (!document.cookie) {
    alert('Cookies are disabled.');
}

I've tested this in IE, Firefox and Chrome and it seems that when you disabled cookies, the document.cookie object becomes unavailable. Does anyone have any experience with this method working/not working?
Many Thanks
Stephen
Additional
I'm well aware that this method requires JavaScript to be enabled on the client. I'm also aware of other server-side/JavaScript solutions. Please can the discussion remain on topic.

A: The only reliable way to me in this scenario (check if cookies are disabled, you don't mind about the javascript issues, and need a client-side solution) is to use a set function for a test cookie, then a get function to read it back. If the test cookie can't be read back, cookies are off.
You can write your own implementation of it reading a great resource from quirksmode, use a jQuery plugin or an out-of-box solution.

A: In XHTML documents, there is no document.cookie at all (up to Firefox 2 or forever on if you send the document as application/xml). I had to learn painfully, that it can be set on document, however:
document.cookie = "foo";

This is valid JS, and the browser shrugs its shoulders and sets the property cookie of the variable document. But the special magic to transform this in an HTTP header doesn't get called.
To put it in a nutshell: No, you can't be sure, that the absence of document.cookie is always identical with disabled cookies, and vice versa.

A: Try setting a value on the server, and reading it on the client. If cookies are enabled, you should be able to read the same value. If not, they are disabled. Note that the site might have httpOnly enabled.

A: Opera 7.10 will not understand document.cookie, so it is not reliable.
Try using this one instead:
<script type="text/javascript">
var cookieEnabled=(navigator.cookieEnabled)? true : false

//if not IE4+ nor NS6+
if (typeof navigator.cookieEnabled=="undefined" && !cookieEnabled){
document.cookie="testcookie"
cookieEnabled=(document.cookie.indexOf("testcookie")!=-1)? true : false
}

//if (cookieEnabled) //if cookies are enabled on client's browser
//do whatever

</script>

It is compatible with most browsers and the ones which will not work with it are not used anymore. I have tested it with Internet Explorer 8.0, Firefox 3.6, Google Chrome 4.0, Opera 10.10 both within HTML and XHTML. While using HTML version with Internet Explorer 8.0 I had to confirm execution of the script.

A: var gotCookie = (navigator.cookieEnabled) ? true : false;

if(typeof navigator.cookieEnabled == 'undefined' && !gotCookie) {
    document.cookie = 'test';
    gotCookie       = (document.cookie.indexOf('test') != -1) ? true : false;
    }

if gotCookie == true, then you've gotCookie :)
note:
when there's no cookie set, document.cookie seems to be unavailable even if cookie is enabled in the browser. that's why we set it with document.cookie = 'test', then check it on the next line. of course, assuming that js is enabled.


text:
Q: Do these two observations suffice to show that a finite boolean ring must be of the form $\mathbb{Z}_2\times\cdots\times\mathbb{Z}_2$?
Question: If $R$ is a finite boolean ring, then show $R \cong \mathbb Z_2 \times \mathbb Z_2 \times \cdots\times \mathbb Z_2$.

I know that

*

*$\mathrm{char}(R) =2$

*$R$ has $2^k$ elements for some $k$  (this is because, if $p\neq 2$ is a prime with $p\mid|R|$, then there exists a non-zero $x \in R$ s.t. $px=0$ and $p $ is odd $\implies x=0$, contradiction).
Does this suffice to answer my question?

A: Once you know that $R$ has characteristic $2$, it will be a vector space (an algebra, really) over the field $F$ with $2$ elements, of dimension $d$, say. So $R$ has $2^d$ elements.
For each $a \in R$, consider the linear map $T_a : R \to R$ given by $u \to au$. Note that $a \mapsto T_a$ gives a morphism of rings from $R$ to $\operatorname{End}(R)$ (these are the endomorphisms of $R$ as a vector space over $F$). This morphism is injective because $T_a(a) = a$, so its kernel is $0$. If $S$ is its image, then $R$ is isomorphic to $S$.
Since $S$ is commutative, and all of its elements are roots of $x^2-x$, the elements of $S$ can be simultaneously diagonalized, with $0$ and $1$ on the diagonal. There are $2^d$ matrices like this, and $R \cong S$ has $2^d$ elements, so $S$ is the whole ring of diagonal matrices. Choose the (canonical) basis $T_{a_{1}}, \dots, T_{a_{d}}$ such that all $T_{a_{i}}$ have only one $1$ on the diagonal (which corresponds to $T_{a_i}(a_i) = a_i^2=a_i$).
Then with respect to the basis ${a_{1}}, \dots, {a_{d}}$ the ring $R$ has the form you require, because $a_i a_j = 0$ for $i \ne j$.
I guess this is just a version for this case of Stone's representation theorem.

A: No, it does not suffice, because (for example) the finite field with $2^k$ elements, $\mathbb{F}_{2^k}$, satisfies both of the properties listed, and this is not isomorphic to $(\mathbb{Z}/2\mathbb{Z})^k$ when $k>1$ because in $\mathbb{F}_{2^k}$, the zero ideal is prime.
Another counterexample would be $\mathbb{F}_2[x]/(x^k)$. We can see that this is not isomorphic to $(\mathbb{Z}/2\mathbb{Z})^k$ when $k>1$ because any element of $(\mathbb{Z}/2\mathbb{Z})^k$ is idempotent, while this is not true of $\mathbb{F}_2[x]/(x^k)$.


text:
Q: Registering Touch on UI in Unity I'm needing to have some funcitonality ignored, if I have happen to touch my UI. However, I am struggling to detect if I am actually touching it or not.
My UI makes use of the native UI inside Unity. My thought behind it was to simply check the layers and if I touched anything on that layer, I'd stop any functionality from happening.
So I wrote this to test it:
    void Update () {
    if (Input.touchCount > 0 && Input.GetTouch (0).phase == TouchPhase.Began)
    {
        Ray ray = Camera.main.ScreenPointToRay( Input.GetTouch(0).position );
        RaycastHit hit;

        if ( Physics.Raycast(ray, out hit,  Mathf.Infinity, mask))
        {
            Debug.Log("hit ui");
        }
    }
}

However, when I press the button on my UI (it's comprised of a Canvas, Panel and a single button to test), nothing happens. However, if I place a cube in the scene and assign that to the UI layer, the debug log appears.
Why is that?

A: I guess the key here is: EventSystems.EventSystem.current.IsPointerOverGameObject()
It should return true whether you are hovering UI. Try implementing it like this:
using UnityEngine.EventSystems;
...
if (Input.touchCount > 0 && Input.GetTouch (0).phase == TouchPhase.Began)
{
    if(EventSystems.EventSystem.current.IsPointerOverGameObject()) {
          Debug.Log("UI hit!");
    }
}

A: For a 2d elements you need to use Physics.Raycast2d instead of Physics.Raycast and make sure that your UI element have a Collider2D
RaycastHit2D hit = Physics2D.Raycast(worldPoint,Vector2.zero);

        //If something was hit, the RaycastHit2D.collider will not be null.
        if ( hit.collider != null )
        {
            Debug.Log( hit.collider.name );
        }


text:
Q: Actions on Google always defaults to Mountain View, CA on simulator I am trying to follow the below sample available on GitHub that explains how permissions work using the Node JS SDK:
https://github.com/actions-on-google/dialogflow-name-psychic-nodejs
I am noticing few strange things:

*

*When tested on the web simulator, the location always defaults to    Mountain View, CA. Is that on purpose because the Google HQ is located there?

*When I invoke the same action on Google Home mini (I am logged into my Google account)
2.1 I did not hear the reason why the permission was requested. From the    logs, I can see that the request_location_permission action gets    called but the conv.ask API call is not getting triggered.
Code Snippet below:
app.intent('request_location_permission', (conv) => {
  // If the request comes from a phone, we can't use coarse location.
  conv.data.requestedPermission =
    conv.surface.capabilities.has('actions.capability.SCREEN_OUTPUT')
    ? 'DEVICE_PRECISE_LOCATION'
    : 'DEVICE_COARSE_LOCATION';

  if (!conv.user.storage.location) {
    console.log('**inside the if condition');
    return conv.ask(new Permission({
      context: responses.permissionReason,
      permissions: conv.data.requestedPermission,
    }));
  }
  showLocationOnScreen(conv);
});

2.2 It ALWAYS defaults to permission denied (inside the  handle_permission intent)
Here's the sequence of events on Google Home mini:
User-> Talk to my test app
Google Home-> bla..bla bla
User-> location
Google Home-> I can't read your mind
App Quits.

But, what expected is that after I say "location", Google Home should ask for location permission, instead it reads out the error message.
Can anyone please shed some light on this.


text:
Q: How can I use different authentication methods for different MQTT endpoints? [Mosquitto] I have a Mosquitto MQTT Broker, configured for Websockets on one port, and mqtt over another.
I have a custom authentication plugin, and it works well. What I want, however, is that only clients connecting over websockets use my plugin, and clients connecting over mqtt protocol use the default TLS authentication.
I am hoping there is some simple setting I have overlooked that I can add to the configuration file, but any/all solutions are welcome. Many thanks.

A: From the mosquitto.conf man page

per_listener_settings [ true | false ]
If true, then authentication and access control settings will be controlled on a per-listener basis. The following options are
affected:
password_file, acl_file, psk_file, allow_anonymous, allow_zero_length_clientid, auth_plugin, auth_opt_*, auto_id_prefix.

Note that if set to true, then a durable client (i.e. with clean session set to false) that has disconnected will use the ACL settings
defined for the listener that it was most recently connected to.
The default behaviour is for this to be set to false, which maintains the settings behaviour from previous versions of mosquitto.
Reloaded on reload signal.

If you set this to true then you can include listerner specific settings under each listener entry in the config file and they will each have their own acl/user settings.


text:
Q: Reload UIPreviewActions after 3D Touch peek I have a tableView and on a 3D touch its cells display the View Controller behind it along with a UIPreviewAction that will share a URL that the "peeked" View Controller fetches.
The problem is that the server doesn't always come back with the URL before the UIPreviewActions are initialised and I don't want to give the option to share if the URL doesn't exist (certain pages don't have a URL).
Is there any way to reload the UIPreviewActions after the View Controller has loaded?


text:
Q: MVP - Getting Data from the View to the Presenter I'm trying to get some practice implementing the MVP pattern in a simple C# WinForms application. On the left of the view is a tree view with a list of the files saved by the application; on the right of the view is a DataGridView for displaying whichever file is clicked in the tree view, or for typing into to save as a new file. The files are simply Dictionary objects written to disk with BinaryFormatter.
I created an interface for the view:
public interface IMappingsView
{
    event EventHandler SaveMapping;
    event EventHandler NewMapping;
    event EventHandler<DeleteArgs> DeleteMapping;
    event EventHandler PasteData;
    event EventHandler NodeClicked;
}

The delete button on the view has the following click event handler:
private void buttonDeleteMapping_Click(object sender, EventArgs e)
{
    var node = treeView1.SelectedNode.Text;
    var args = new DeleteArgs(Path.Combine(RootDir,node));

    if (DeleteMapping != null)
    {
        DeleteMapping(this, args);
        dataGridView1.Rows.Clear();
        RefreshTreeView();
    }
}

What is the best way to to pass information from the view to the presenter? I feel as though needing custom event arguments for every scenario is very wrong.

A: Make the data you want available available via the interface as a property.
Assuming you have a firstName and lastName field that you want exposed...
public interface IMappingsView
{
    event EventHandler SaveMapping;
    event EventHandler NewMapping;
    event EventHandler<DeleteArgs> DeleteMapping;
    event EventHandler PasteData;
    event EventHandler NodeClicked;
    string FirstName {get;set;}
    string LastName {get;set;}
}

Then in your form that implements the interface,
string FirstName {
    get {
        return textFirstName.Text;
    }
    set {
        textFirstName.Text = value;
    }
}

as an example.


text:
Q: How do I replace the a portion of the string with special characters I would like to replace a certain portion of the string with "\\_\\_\\_\\_\\_"
(e.g. String str = "Hello World")

If I do str.replaceAll("World", "\\_\\_\\_\\_\\_");
I don't see the "\" character in my replaced string, I would expect it to show me "Hello \_\_\_\_\_"

A: You need:
str = str.replaceAll("World", "\\\\_\\\\_\\\\_\\\\_\\\\_");

See it.
\ is the escape character in Java strings. So to mean a literal \ you need to escape it with another \ as \\.
\ is the escape char for the regex engine as-well. So a \\ in Java string will be sent to regex engine as \ which is not treated literally but instead will be used to escape the following character.
To pass \\ to regex engine you need to have \\\\ in the Java string.

Since you are replacing a string (not pattern) with another string, there is really no need for regex, you can use the replace method of the String class as:
input = input.replace("World", "\\_\\_\\_\\_\\_");

See it.

A: You need to use 4 backslashes to insert a single one.
The point is: in literal java strings the backslash is an escape character so the literal string "\" is a single backslash. But in regular expressions, the backslash is also an escape character. The regular expression \ matches a single backslash. This regular expression as a Java string, becomes "\\".
So try something like this:
String str = "hello world";
System.out.println(str.replace("world","\\\\_\\\\_\\\\_\\\\"));

A: Have a look at this post.


text:
Q: Installing an old version of Foundation Is there any way to easily install a Foundation version, other that the latest one? Instructions for "manual" install start with
git clone https://github.com/zurb/foundation-sites-template projectname

Ideally, I'd like to be able to do something like
git clone https://github.com/zurb/foundation-sites-template/tree/v6.1.2 projectname

but there is no such v6.1.2 tag
EDIT:
I have found a workaround - I run
git clone https://github.com/zurb/foundation-sites-template projectname

And then I edit the dependencies in bower.json and proceed with the rest of the installation. At least it works for my purposes, as I mainly need the scss stuff, not the whole project. And I still have to hunt for the correct versions of scss/app.scss and scss/_settings.scss as the ones getting downloaded are for the latest version.
Would be nice if there was a fully automated way of installing a version other than the latest.

A: There is actualy NO TAG for the Zurb-Foundation TEMPLATE project on github (https://github.com/zurb/foundation-sites-template):

Maybe you could switch to the actual Site project if it is what you are looking for.
EDIT:
I suggest making a ps1 or .bat script that would do the following
git clone https://github.com/zurb/foundation-zurb-template projectname
cd projectname
cp C://bower.json bower.json -f
npm install
bower install

You could also fork the template project on Github and edit it's bower.json so it's always up to date and there is no need to use the cp command
Or make a git repo of the variables you are using and do something like
git clone https://github.com/zurb/foundation-zurb-template projectname
git clone https://github.com/you/foundation-version foundation-version
cd projectname
cp ../foundation-version/bower.json bower.json -f
npm install
bower install


text:
Q: Hypothesis testing on multiple regression coefficients In the simple linear regression setting, in order to determine
whether there is a relationship between the response and the predictor we
can simply check whether $\beta_1=0$. In multiple regression, it is to check $\beta_1 = \beta_2 = \cdots = \beta_p=0$ for hypothesis testing.
Why do we set these coefficients to zero? What is the motivation/physical meaning for this?

A: Here's the full model:
$$ y_i = \beta_0 + \beta_1 x_{i,1} + \cdots + \beta_p x_{i,p} + \epsilon_i$$
where all the $\epsilon_i$s are independent and identically distributed as $\mathcal{N}(0,\sigma^2)$. If you set all the $\beta$s to zero, it simplifies the model to
$$ y_i = \beta_0 + \epsilon_i$$
which means that your data is just normally distributed, or
$$Y_i \sim \mathcal{N}(\beta_0, \sigma^2)$$
and none of the $x$s can help you predict it.

A: Primarily null hypothesis might be that adding these P variables does not reduce residual variation, meaning does not explain variation in the response variable.
But this null vector hypothesis is not only one, often parameter restrictions are put only to the subset of variables.
One can have model A which is larger than model B, having more variables. Null hypothesis might be that model B is adequate for the explaining variation in the response variable and then it is natural that you have zero restrictions on the remaining P-S variables which are in model A.


text:
Q: How can I add a class in codeigniter? I am working with Enom API and this API uses its own Interface (not Codeigniters) as shown below:
<?php
require_once( dirname(__FILE__) . '/class.EnomInterface.php' );

Class EnomService extends EnomInterface{

function checkDomain($sld, $tld, $spinner = false, $allowDash = true, $word1 = '', $word2 = '', $word3 = ''){
$this->_setCommand('Check');

$this->addParam('SLD', $sld);
if( strstr($tld, ',') )
{
  $this->addParam('TLDList', $tld);
}
else
{
  $this->addParam('TLD', $tld);
}

if( $spinner && !strstr($tld, ',') )
{
    $this->addParam('DomainSpinner', '1');
    $this->addParam('AllowDash', $allowDash ? '1' : '0');
    if('' != $word1)
        $this->addParam('Word1', $word1);
    if('' != $word2)
        $this->addParam('Word2', $word2);
    if('' != $word3)
        $this->addParam('Word3', $word3);
}

if( !$this->process() || '0' != $this->response['ErrCount'] )
{
  return $this->_returnError();
}

$result = array();

if($spinner)
{
    $i = 1;
    while( isset($this->response['SuggestedName' . $i]) )
    {
        $result[$this->response['SuggestedName' . $i]] = true;
        $i++;
    }
}

if( !isset($this->response['DomainCount']) || '1' == $this->response['DomainCount'] )
{
  $result["$sld.$tld"] = ('210' == $this->response['RRPCode']) ? true : false;
  return $result;
}

for($i=1; $i<=$this->response['DomainCount']; $i++)
{
  $result[ $this->response[('Domain'.$i)] ] = ('210' == $this->response[('RRPCode'.$i)]) ? true : false;
}

return $result;
}
}

This has more functions but I guess you guys get the point.
Anyway, I am trying to load it like this:
$this->load->library('Enom/class.EnomService');

And the classes are in:
libraries/Enom/class.EnomService.php
libraries/Enom/class.EnomInterface.php

What it tells me it has an internal server error.
Could somebody please help me with this implementation?
PS: I am new to Codeigniter.. :)
Thanks!
EDIT:
As a conclusion, ENOM and other API's use many Interfaces and variables between them wich may cause conflict with the loader class of the codeigniter.
I managed to solve this issue was not implementing it through the loader class but directly through the require and include variables.
It turned out something like this:
require_once('application/libraries/enom/class.EnomService.php');
$enom = new EnomService($registrar_username, $registrar_password, false, true);
$enom->debug = true;

Instead of:
$this->load->library('Enom/class.EnomService');

If anyone needs any further explenation I would me more than glad to help.
Thanks to everyone who helped on the way, Specially Phill.

A: Just include the class file, like EnomService does to get the EnomInterface, and you should be able to use EnomService as Enom documents.
include APPPATH.'libraries/Enom/class.EnomService.php';

$enom = new EnomService('username', '********', false, true);
$enom->debug = true;

$result = $enom->checkDomain('systurn', 'com', true);

var_dump($result);

APPPATH refers to the application directory in CodeIgniter.


text:
Q: Windows App - Facebook Login Windows Store SID for testing I'm new on developing an application on Windows. I want to integrate a Facebook login button for my user to login. However, when I create the app in Facebook Developer console, it ask for the Windows Store SID. My app is still in developing and what I should put there? Please help me. If you can, please provide a step by step solution to me. Thank you.

A: WebAuthenticationBroker.GetCurrentApplicationCallbackUri().ToString(); gets SID


text:
Q: Adding API method to App Engine causes NullPointerException I'm using the local App Engine and I have a working Endpoint, but when I add the following API, the API Explorer (https://developers.google.com/apis-explorer/?base=http://localhost:8888/_ah/api#p/) doesn't load while the JavaScript console has an unhandled exception.
@ApiMethod(name = "getClientByPublicId")
public Client getClientByPublicId(@Named("publicId") String publicId) {
    EntityManager mgr = getEntityManager();
    Client client = null;
    client = mgr.find(Client.class, publicId);
    mgr.close();

    return client;
}

Within the Chrome JavaScript console, it doesn't give anything useful because it's minimized
Uncaught java.lang.NullPointerException
(anonymous function)
(anonymous function)
h
(anonymous function)
F.(anonymous function).z.(anonymous function).z.(anonymous function)
_.T.K.__cb
h
c

The whole API Explorer page comes up blank.
I've ran this in debug mode and set a breakpoint within the added API, but it isn't triggered.
If I load the discovery document at http://localhost:8888/_ah/api/discovery/v1/apis/clientendpoint/v1/rest, it fails with the following response.
{
  "error" : {
    "message" : ""
  }
}

If I remove this new API it all works fine, albeit without having the new API.
Anyone know what is causing this?
Update
I stumbled across Google APis Explorer didn't found my available ApiMethod from my app-engine app and it sounds like there may be a path collision, which I don't understand yet but I'm going to try to work on this idea now.
If this may be the issue, the related API is
@ApiMethod(name = "getClient")
public Client getClient(@Named("id") Long id) {
    EntityManager mgr = getEntityManager();
    Client client = null;
    try {
        client = mgr.find(Client.class, id);
    } finally {
        mgr.close();
    }
    return client;
}

I'll give this a shot and answer my question, unless someone knows different.

A: After finding Google APis Explorer didn't found my available ApiMethod from my app-engine app I learned that you must include a new path.
For example, I was able to alter the ApiMethod to
@ApiMethod(
    name = "getClientByPublicId",
    path = "client/publicId/{publicId}",
    httpMethod = "GET"
)

Works great now.


text:
Q: Every subset of a finite set is finite (hopefully this would be the last time) I am so sorry for posting about it more than one time but this is my 4th revision for this proof and I want some feedback..
Note : $[n]$ is $\{1,2,3,4,\ldots,n\}$, a finite set
Prop: Every subset of a finite set is finite
Proof: Let $A,B$ sets and suppose $B$ is a finite set.
Also let $A \subseteq B$
If $A = \varnothing$, then it is finite
If $B = \varnothing$, then also $A = \varnothing$, which is finite.
So we suppose $A \neq \varnothing$ and $B \neq \varnothing$. Then there exstis a bijection $f: B \to [n]$
Since $A \subseteq B$, the inclusion mapping $I : A \to B$ defined on $f(a) = a$ for $a \in A$ exists.
Note $I(a_1) = a_1$ and $I(a_2)=a_2$ and if we suppose $I(a_1)=I(a_2)$, then $a_1 = a_2$, and therefore $I$ is an injection.
Then we can have $f \circ I: A \to [n]$, which is injective.
We need to prove that there is a bijection between the set $A$ and subset of $[n]$
So, let $p(n)$ be the statement that "If $A \subseteq [n]$, $A$ has a bijection with $[m]$ for some $m \in Z_{\ge0}$ such that $m \le n$"
Base case $(n=1)$ : If $A \subseteq [1]$, since we suppose $A \neq \varnothing$, $A$ has a bijection with $[1]$
Induction part : Now let $k \in N$ and suppose $p(k)$ holds. Now we want to prove that $p(k+1)$, that is, "If $A \subseteq [k+1]$, $A$ has a bijection with $[m]$ for some $m \in Z_{\ge0}$ such that $m \le k+1$"
Then if $A $ has $k+1 $ elements, it is done. It has a bijection with $[k+1]$.
If $A \subseteq [k]$, by the induction hypothesis, $A$ has a bijection with $[m]$ for $m \le k$.
Hence every subset of finite set is finite.

A: Would this be easier? An infinite set $S$ trivially has infinitely many subsets (take e.g. the singletons $\left\{ s \right\}$, $s \in S$). By a simple combinatorial argument a finite set $F$ has $2^{\#F}< \infty$ subsets.
Assume that $A \subset F$ is infinite, with $F$ a finite set. Then there are infinitely many $B \subset A \subset F$, which is a contradiction.


text:
Q: Select parent page and all its child page but exclude one specific child page Hi everyone hope all is good. I need some suggestion.
I need to select parent page and all its child page but exclude one specific child page. can you please tell me how can i exclude specific child ?
```// Store Only Show For the Registered Users
function woocommerce_store_private_redirect() {
global $post;
if (
    ! is_user_logged_in()
    && (is_woocommerce() || is_cart() || is_checkout() || is_product_category() || is_product_tag() || is_product() || is_tree(64) )
) {
    // feel free to customize the following line to suit your needs
    wp_redirect( site_url('mein-konto/') );
    exit;
}
}
add_action('template_redirect', 'woocommerce_store_private_redirect');

function is_tree($pid) {      // $pid = The ID of the page we're looking for pages underneath
global $post;         // load details about this page

$pages = get_posts([
'post_type' => 'page',
'posts_per_page' => -1,
'post_parent' => $pid, // the parent id you want the children from
'post__not_in' => [4419] // the id you want to exclude
]);

if(is_page()&& $pages)
           return true;   // we're at the page or at a sub page
else
           return false;  // we're elsewhere
};

A: There are some issues in your code, e.g. $pages will always return an array, even where there are no results in which an empty array is returned, so if ( is_page() && $pages ) return true; does not necessarily mean that "we're at the page or at a sub page". Instead, it means, "as long as it's a Page (post type page), then we return true".
Nonetheless, try the following which works even if the page in question has a grandchild:
// This function checks whether the current Page has the specified ID ($pid), or
// that the current Page is a direct or indirect child of $pid.
function is_tree( $pid ) {
    // ID of the specific child page that you want to exclude.
    $cid = 4419;

    // Bail early if we're not on a Page.
    if ( ! is_page() ) {
        return false;
    }

    $page_id = get_queried_object_id();
    $pid     = (int) $pid;

    // We're on the parent page.
    if ( $pid === $page_id ) {
        return true;
    }

    // We're on the **excluded child page**, so return false.
    if ( (int) $cid === $page_id ) {
        return false;
    }

    $pages = get_pages( array( 'child_of' => $pid ) );

    // Check if we're on one of the other child pages.
    return in_array( $page_id, wp_list_pluck( $pages, 'ID' ) );
}


text:
Q: The vscode first page main window does not appear While setting zoom, too large a number was entered by mistake, causing the screen to become excessively large and the vscode execution window to disappear.No matter how hard you try, you can't return to the default setting.Help - Removing and reinstalling the vscode leaves the enlarged window and does not disappear.
I want the first page of vscode (main page) to appear.
I tried to find the settings page, but there was no way. The Run window does not appear.


text: Q: How do I perform google authentication with Selenium? I have read many stackoverflow responses about this, but they seem very outdated. In order to do end to end testing on my application, I need to login through google SSO which is the login method the application uses. How can I perform this task with selenium because I keep getting the following.


text:
Q: Date formatting to MM/DD/YYYY in LWC datatable How do we format the date in datatable like MM/DD/YYYY in LWC data table.
In my datatable column type is defined as date,  value display in table as
Jan 10, 2020. Expecting in MM/DD/YYYY format.
{ label: "Start Date", fieldName: "Program_Start_Date__c", type: "date" },
I gone through the LWC data table Documentation:
Displays a date and time based on the locale using lightning-formatted-date-time.
Displaying Date and Time Using Type Attributes.  Type Attribute: day, era, hour, hour12, minute, month, second, timeZone, timeZoneName, weekday, year
typeAttributes: {
 day: 'numeric',
month: 'short',
year: 'numeric',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
hour12: true
}

Still not works, Can anyone Please help me on this.

A: lightning-datatable internally uses lightning-formatted-date to output date field.
To output, the date in MM/DD/YYYY format set the type attribute to
typeAttributes: {
    day: "numeric",
    month: "numeric",
    year: "numeric"
}


text:
Q: Forming a local martingale with continuous increasing process If $M_t$ is continuous martingale, we know that there exists quadratic variation process which is continuous and increasing. I am interested to know if the converse is also true. To make it precise

Let $ \{A_t, \mathcal{F_t}; 0\leq t < \infty\}$ be continuous, increasing process starting at 0 a.s. Let $\{B_t, \mathcal{F_t}; 0\leq t < \infty\}$ be standard Brownian motion. Is it true that $M_t := B_{A_t}$ is a local martingale with quadratic variation $A_t$?

I was trying to use time change for Brownian motion. However I am not successful in getting the right formulation with stopping times.


text:
Q: Java Eclipse Project to MySQL Database communication issue? Hello!
I'm writing a Java program which inserts lines from a given Text-File into a MySQL Database.  My code works fine for smaller text files (< 1KB), however for larger TextFiles (> 1MB), I'm getting the following Runtime Error:

This error typically occurs about 30,000 words in (about 250 KB).  I'm not sure why this is happening or how to get around it.
Code below:
My InsertRecord classfile:

This specific program is writing to a Table named "Lexicon", and a
  Database named "WordGuess".

import java.sql.DriverManager;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import FileManager.MetaTextFile;

public class InsertRecord {

    private static final String DB_DRIVER = "com.mysql.jdbc.Driver";
    private static final String DB_CONNECTION = "jdbc:mysql://localhost:8889/";
    private static final String DB_USER = "root";
    private static final String DB_PASSWORD = "root";

    public static void insertRecord(String db, String tbl) throws SQLException, IOException {

        Connection dbConnection = null;
        PreparedStatement preparedStatement = null;

        MetaTextFile txt = new MetaTextFile(tbl);
        txt.putFileIntoArray(tbl);
        String[] FileArray = txt.getArray();

        for (int i=0; i<FileArray.length; i++){
            String insert_statement = "INSERT INTO " + tbl + " VALUE (NULL, "
                    + "'" + FileArray[i] + "'" + ")";

            try {
                dbConnection = getDBConnection(db);
                preparedStatement = dbConnection.prepareStatement(insert_statement);

                // execute create SQL statement
                preparedStatement.executeUpdate();

            } catch (SQLException e) {

                System.out.println(e.getMessage());

            } finally {

                if (preparedStatement != null) {
                    preparedStatement.close();
                }

                if (dbConnection != null) {
                    dbConnection.close();
                }

            }
        }

    }

    private static Connection getDBConnection(String db) {

        Connection dbConnection = null;

        try {

            Class.forName(DB_DRIVER);

        } catch (ClassNotFoundException e) {

            System.out.println(e.getMessage());

        }

        try {

            dbConnection = DriverManager.getConnection(
                            DB_CONNECTION + db, DB_USER,DB_PASSWORD);
            return dbConnection;

        } catch (SQLException e) {

            System.out.println(e.getMessage());

        }

        return dbConnection;

    }
}


text:
Q: I need to to login in java using this sql to check if account is active I need SQL query or anyhow i can fix this so before user can login the sql path will check if status is active or blocked if block can't login but active can. this my code is showing me that i have error in sql it worked very fine if i remove the status path.
DebuggerConnct(){
try{
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/studentdb1","root","");
        pst=con.prepareStatement("select * from studentstab where SrStudentId=? and password1=?,Status='Active'");
        }catch (ClassNotFoundException | SQLException e) {System.out.println(e);}}

public Boolean DebugUser(String SrStudentId,String password1){
try{
pst.setString(1, SrStudentId);pst.setString(2, password1);System.out.println(SrStudentId + password1);rs=pst.executeQuery()return rs.next();
}
catch (Exception e) {
    System.out.println("error while validating"+e);
    return false;}}

A: This SQL:
select * from studentstab where SrStudentId=? and password1=?,Status='Active'

seems invalid to me. How about replacing the , with AND which would make it SQL again?
select * from studentstab where SrStudentId=? and password1=? AND Status='Active'


text:
Q: How to rename column names based on pattern I'm needing to reformat the year columns according to a pattern. For example, 17/18 transformed to 2017-2018. In the full data set, the years go from 00/01 - 98-99 (2098-2099).
Here is the code to create a sample dataset:
id <- c(500,600,700)
a <- c(1,4,5)
b <- c(6,4,3)
c <- c(4,3,4)
d <- c(3,5,6)
test <- data.frame(id,a,b,c,d)
names(test) <- c("id","17/18","18/19","19/20","20/21")

Produces a dataframe like so:
    id  17/18 18/19 19/20 20/21
500 1     6     4     3
600 4     4     3     5
700 5     3     4     6

Desired outcome:
id  2017-2018 2018-2019 2019-2020 2020-2021
500 1         6         4         3
600 4         4         3         5
700 5         3         4         6

A: You can use regex to capture the digits and add prefix "20".
names(test)[-1] <- sub('(\\d+)/(\\d+)', '20\\1-20\\2', names(test)[-1])

test
#   id 2017-2018 2018-2019 2019-2020 2020-2021
#1 500         1         6         4         3
#2 600         4         4         3         5
#3 700         5         3         4         6

A: Given this input
x <- c("id","17/18","18/19","19/20","20/21")

You can split the second to last elements on "/" (which creates a list), use paste to add a prefixed "20" and collapse by "-"
x[-1] <- sapply(strsplit(x[-1], "/", fixed = TRUE), paste0, "20", collapse = "-")

Result
x
[1] "id"        "2017-2018" "2018-2019" "2019-2020" "2020-2021"

A: additional solution
colnames(test)[-1] <- names(test)[-1] %>%
  strsplit(split = "/") %>%
  map(~ str_c("20", .x)) %>%
  map_chr(~str_c(.x, collapse = "-"))


text:
Q: eclipse - show most recently visited tabs in the editor Is it possible to configure eclipse to order the tabs in the tab bar by most recent access time or something in those lines? The current behaviour is sort of not really comprehensible to me -- most of the time if I switch from tab1 (displaying file1) to e.g. tab2 (displaying file2) tab1 gets hidden in the >> thingy and some other tab, say tab42, which I haven't accessed in a long time, pops up in its place.

A: As @pabrantes pointed out my question is actually a duplicate of another so question, which I wasn't able to find on my own due to my inadequate question statement.
Long story short: you just need to set swt-mru-visible to true in the .MPartStack section of the CSS file for your current theme.


text:
Q: What is the difference between f(x) and x? What is the difference between f(x) and x?
For example:
Would
T$_1$(N) = O(f(N))
be any different than
T$_1$(N) = O(N)
?
Note: when I use "O" I am using it to indicate big-Oh notation.

A: For a simple example, let $f(x)=x^2$.  Then $T_1(N)=O(f(N))$ says $T_1(N)=O(N^2)$, which is different from $T_1(N)=O(N)$


text:
Q: MySQL "Advanced Where" Query I would like to know is there any possible way, whereby MySQL query can dynamically search whatever is there in the WHERE clause.
For example if the query is
Select *
from table
where item = 'Dell Optiplex 390'

It should search for rows having:
Dell Optiplex 390

Dell Desktop Optiplex 390

Dell Laptop Optiplex 390

Optiplex dual core 390

etc., etc.

A: For these sort of search capabilities I think you are looking for a matching algorithm. You can use the Levenshtein Distance Algorithm, there is a php function levenshtein that implement this algorithm if you are using php, to get the matching data and there is also Needleman–Wunsch algorithm, and if your data is in English only and one word column you can use Soundex Algorithm.
This is a start, you will find a lot of implementations out there for these algorithms in Mysql.

A: If you need to know that field consist any of you words.
Select *
from table
where item like '%Dell%' OR item like '%Optiplex%' or item like '%390%'

A: There was a good answer here which was deleted, I would modify that answer to:
Select * from table where
lower(item) like '%dell%optiplex%390%' or
lower(item) like '%optiplex%390%' or
lower(item) like '%dell%laptop%390%' or ...

A: Use the SQL LIKE clause with wild cards:
SELECT *
FROM table
WHERE item LIKE '%Dell%Optiplex390%';

Here's a good reference guide:

*

*MySQL Wildcard Filtering using LIKE.


text:
Q: When database Table is created in android application? I want to know the answer of this question because of, in one of my interview, interviewer asked to me this question.
When database Table is created..?
Option:-

*

*On application launch.

*when inserting data.

can any one explain me when the data base created?
I have always created table with specific row and column and inserted data, updating data for my application, but never think about this question.

A: This seems like an odd question to me, the answer should be whenever you create one, no? Straight from the documentation:
public class DictionaryOpenHelper extends SQLiteOpenHelper {

    private static final int DATABASE_VERSION = 2;
    private static final String DICTIONARY_TABLE_NAME = "dictionary";
    private static final String DICTIONARY_TABLE_CREATE =
                "CREATE TABLE " + DICTIONARY_TABLE_NAME + " (" +
                KEY_WORD + " TEXT, " +
                KEY_DEFINITION + " TEXT);";

    DictionaryOpenHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(DICTIONARY_TABLE_CREATE);
    }
}


text:
Q: C# IsPrime skips a prime number I am trying to fasten my isPrime function but when I add a condition that if the number is divisible by 2 just return false instead of doing the whole process to find if the number is prime or not, but when I do this, it skips me a number for example the 6th prime is 13, without the condition if it's divisble by 2 I get 13, but when I add it I get 17.
    static bool isPrime(long n)
    {
        bool prime = false;
        int div = 0;

        if (n % 2 == 0)
            return false;
        else

        for (long i = 1; i < n + 1; i++)

        {
            if (n % i == 0)
                div++;
            if (div == 2)
                prime = true;
            else
                prime = false;
        }
        return prime;
    }

A: You need to check for the special case of 2 first, it's even but prime.
As an additional optimization, you can improve the bounds you're looping up to; there's no need to go as high as n + 1.

A: If you want to speed up the solution you can do something like that:
static bool isPrime(long n) {
  // all integers less than 1 (1 is included) are not prime
  if (n <= 1)
    return false;

  // Error in your code: 2 is prime, even if other even numbers aren't
  if (n % 2 == 0)
    return (n == 2);

  // there's no need to loop up to n: sqrt(n) is quite enough
  long max = (long) (Math.Sqrt(n) + 0.1);

  // skip even numbers when looping: i +=2
  for (long i = 3; i <= max; i += 2) {
    // the early return the better
    if (n % i == 0)
      return false;
  }

  return true;
}

A: if (n % 2 == 0)
    return (n == 2);

Modulus operation is slow in most architectures if you compare it to bit level checking. You can choose to only check the least significant bit of each number and get the answer if it's even or odd number.
Just do a AND operation with 1 and the value. The result tells you if it's even.
Example:
100101011101 (the value to check)
000000000001 (bitmask to AND with)
000000000001 (the result after AND, still 1 ---> odd number (true in boolean))

So:
if(!(value & 1))
{
    //even
    return false;
};


text:
Q: Failing to capture mouse position and therefore pixel data Reposting question as clearer now.
What I have is a page with x number of images on. What I want to do is be able to click on any part of any image and make that particular color transparent in the image clicked on. Turning its Alpha to 0
So, images:

Below is what I'm trying, inspector tells me ImageData { width=300, height=300, data=Uint8ClampedArray}
When I click data=Uint8ClampedArray to see whats in there the browser (ff) freezes and asks if want to stop script.
So its getting caught in a loop and when I do finally see data=Uint8ClampedArray it shows 0=255, 1=255, 2=255 even though I clicked something red.
I think the problem is in the capturing the mouse position and the pixel clicked on.
// get mouse position

function findPos(obj) {
    var current_left = 0,
        current_top = 0;
    if (obj.offsetParent) {
        do {
            current_left += obj.offsetLeft;
            current_top += obj.offsetTop;
        } while (obj = obj.offsetParent);
        return {
            x: current_left,
            y: current_top
        };
    }
    return undefined;
}

// click
$('[id^=image]').click(function (e) {
    var after = $(this)[0];
    after.src = white2transparent(after);
})

function white2transparent(img) {
    var c = document.createElement('canvas');
    var w = img.width,
        h = img.height;

    c.width = w;
    c.height = h;

    // get the position
    var position = findPos(img);
    var x = img.pageX - position.x;
    var y = img.pageY - position.y;
    var coordinate = "x=" + x + ", y=" + y;

    var ctx = c.getContext('2d');

    ctx.width = w;
    ctx.height = h;
    ctx.drawImage(img, 0, 0, w, h);
    var imageData = ctx.getImageData(0, 0, w, h);

    // show rgb colors in inspector
    console.log(imageData);

    var pixel = imageData.data;

    var r = 0,
        g = 1,
        b = 2,
        a = 3;
    for (var p = 0; p < pixel.length; p += 4) {
        if (
        // this is where I need to return the RGB found and replace 220
        pixel[p + r] >= 220 &&
            pixel[p + g] >= 220 &&
            pixel[p + b] >= 220) {
            pixel[p + a] = 0;
        }
    }

    ctx.putImageData(imageData, 0, 0);

    return c.toDataURL('image/png');
}

This section is where I need to return the RGB of the clickde pixel and replace the 220 with each of the vealues
if (
    // this is where I need to return the RGB found and replace 220
      pixel[p+r] >= 220 &&
      pixel[p+g] >= 220 &&
      pixel[p+b] >= 220)

EDIT
When I try view co-ordinates in inspector using:
// show x + y
console.log("x=" + x + ", y=" + y);

It returns x=NaN, y=NaN

A: If you want to find the mouse position relative to the image, you should use the click event itself like so
$('[id^=image]').click(function (e) {
   // an array representing the relative x\y mouse coordinates within the image
   var relativeMousePosition=[e.pageX-$(this).offset().left,e.pageY-$(this).offset().top];

})


text:
Q: What's the minimum Em size for ttf fonts I'm trying to make a very small pixel font on fontforge, when I set my Em size to 8, the .ttf font generated would not open, giving me an error not a valid font file but changing Em to 16, the font opens fine.
I wonder if there is a minimum Em size for ttf fonts? Or it has something to do with fontforge?


text:
Q: Call actionPerformed of a JTextField using its object I have a javax.swing.JTextField named SearchBox with an actionPerformed Event.
public void SearchBoxActionPerformed(java.awt.event.ActionEvent evt){
     //TODO
}

What I want to do is to call the above method from another method in a different class by passing the JTextField object as an argument.
import javax.swing.JTextField;

public class Program {

    public static synchronized void QuickSearchResults(JTextField textBox) {
        /*
         * I want to call ActionPerformed method of textBox if it has any.
         */
    }
}

Please note that calling the method name directly is not an option. If
  I pass 3 different JTextField objects, the relevant ActionPerformed
  methods should be called.

Is there a way to achieve this? I already tried using,
textBox.getActions();
textBox.getActionListeners();

but it didn't go well, and now I'm back in square one.
Thanks in advice!

A: JTextField#postActionEvent will trigger the fields ActionListeners, which is what I assume you're trying to do
public class Program {

    public static synchronized void QuickSearchResults(JTextField textBox) {
        textBox.postActionEvent();
    }
}

A: I have found a way to achieve this, but it's certainly not the best.
public static synchronized void QuickSearchResults(JTextField textBox) {
    ActionListener actions[] = textBox.getActionListeners();
    for (ActionListener x : actions) {
        x.actionPerformed(null);
    }
}

In this case, only the ActionListeners are being called, but all of them which have been added to the JTextField using addActionListener(ActionListener l).
As I have said above, this may not be the best way, but solves the problem.

A: Use this code
public static synchronized void QuickSearchResults(JTextField textBox) {
    /*
     * I want to call ActionPerformed method of textBox if it has any.
     */
    textBox.addActionListener(e->{
        //Do what you want
    });
}


text:
Q: Android - Refresh data in an AlertDialog? So, if I create an AlertDialog like so:
AlertDialog.Builder b = new AlertDialog.Builder();
b.setItems(MyStringArray, MyListener);
b.create().show();

And then I want to update the items in the list, i.e. MyStringArray has changed to have more or fewer items. I can't seem to find a way to do this. So far, I've tried getting the ListView from the AlertDialog, but I can't seem to get .setAdapter to work. Is this the right approach, or is there a better way to do this?

A: I haven't tried this out myself, but from all the other apps I've built I'm pretty sure this will solve your problem.
Instead of using setItems, try using the setAdapter() method and pass in an ArrayAdapter that has been initialized with the data from your Array of String.  Then, when you know that the data has changed, you can use getListView() to get your View object and from there call getAdapter() so that now you're working directly with the dataset.  You can clear it, and re-initialize it if you like, or just add / remove the items as you like.  From the adapter object, if you call notifyDataSetChanged() it should trigger a re-draw using the new data set that you just supplied to the adapter.
Hope that helps you out.  Let me know if it doesn't.
DSC

A: If you are like me and you would like to use default adapter for example for multichoice items, then there is also a way.
Just as with any other adapter just update the string array object, get adapter from the dialog instance, cast it to appropriate adapter and invalidate it.
AlertDialog.Builder b = new AlertDialog.Builder();
b.setItems(MyStringArray, MyListener);
AlertDialog instance = b.create();
instance.show();

// Later when you need to update
MyStringArray[0] = "puf";
ListView list = instance.getListView();
// Now according to whether you used cursor or array for supplying items to the builder
// you have to cast adapter to either CursorAdapter or ArrayAdapter
ArrayAdapter adapter = (ArrayAdapter)list.getAdapter();
adapter.notifyDataSetChanged();

You can find out more here.

A: This is how I did it in Kotlin:
AlertDialog.Builder(context).apply {
   val actions = arrayListOf("aa", "bb")
   val onItemClickListener = DialogInterface.OnClickListener { dialog, which ->
       // code
   }
   val adapter = ArrayAdapter(requireContext(),
       android.R.layout.simple_list_item_1, actions)
   setAdapter(adapter, onItemClickListener)

   executeGetRequest() {
      actions.add("cc")
      adapter.notifyDataSetChanged()
   }
}.show()


text:
Q: docker-compose up rebuilds image after reboot I am working on my development machine and using a postgres database image into which I load a fairly large amount of data (takes ~15 minutes to load the whole thing). I have a secondary image which reads data from this database as part of my application. Since I don't intend to change anything in the database once I load the data into it, I don't want it to rebuild the image every time I run docker-compose up. To avoid that I always call
docker-compose build my_flask
docker-compose up
But it seems that after I reboot my computer, calling docker-compose up decides to rebuild the postgres image anyway, forcing me to sit through the lengthy loading process any time I reboot the computer. How can I stop this from happening?
docker-compose.yaml:
version: "3"

services:

  postgis:
    image: mdillon/postgis
    hostname: leni_prototype_postgis
    container_name: leni_prototype_postgis
    environment:
      - POSTGRES_PASSWORD=postgres
    networks:
      - mynetwork
    expose:
      - "5432"
      - "22"
    ports:
      - "5433:5432"
    volumes:
      - ./mnt/pg_init_data:/docker-entrypoint-initdb.d:z
    restart: always

  flask_server:
    build: ./flask/Docker/
    hostname: my_flask
    container_name: my_flask
    networks:
      - my-network
    expose:
      - "5005"
    ports:
      - "5005:5005"
    volumes:
      - ./flask/Docker/app/grass_data:/grass_data
      - /var/run/docker.sock:/var/run/docker.sock
    depends_on:
      - postgis
    restart: always

networks:
  my-network:
    driver: bridge

A: You need to persist the database data folder if you don't want it to be initialized each time:
    volumes:
      - ./mnt/pg_init_data:/docker-entrypoint-initdb.d:z
      - ./data:/var/lib/postgresql/data


text:
Q: Automatically updating a date field in visual basic So I'm trying to build an app for a builder to give new estimates to customers.
One of the features is that when he tries to create a new estimate, the quote date will get automatically get filled with the date of when the estimate is created.
And then a second date field is auto-filled to be 30 days later, so the builder can know when the quote expires. See below:

As you can see, the date fields in the Access table is not filled in.
However, it works when you change the date manually using the date picker and set it to something other than the default, see below:

now it shows up.
Here's the code I used to automatically set the dates of the date picker:
Private Sub Main_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        ' Adds today's date to the quote date as a defalut
        QuoteDateDateTimePicker.Value = Date.Today

        ' Creates automatic expiry date for quote in 30 days
        QuoteExpiryDateTimePicker.Value = Date.Today.AddDays(30D)

When I press the save button I expected the data would be added to the table.
Save button:
' Save Quote
Private Sub btnSaveEdit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSaveEdit.Click
    ' This causes the Total button to be clicked so that when
    ' users try to save the quote without pressing the "total"
    ' button it doesn't save an empty quote.
    btnTotal_Click(sender, e)

    ' Save quote
    QuotesBindingSource.EndEdit()
    If TotalTextBox.Text = "" Then
        MsgBox("Please enter a some estimates")
    End If
    QuotesTableAdapter.Update(QuotesDataSet.quotes)
    End Sub


text:
Q: open the image when clicking it i downloading images in an imageview from a json Server i need to open the image when clicking it and i send the position of the image to an activity that contain an imageview to Receive the sended photo but my problem is the imageView.setImageResource(list.get(ReceivedPosition)) take an intger and my list of photos from a custom obeject photos here the code
public class customfunny extends BaseAdapter {
Context c;
ArrayList<photos> sites;
public customfunny(Context c, ArrayList<photos> sites)
{
    this.c = c;
    this.sites = sites;
}
@Override
public int getCount() {
    return sites.size();
}
@Override
public Object getItem(int i) {
    return sites.get(i);
}
@Override
public long getItemId(int i) {
    return i;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
    if (view==null)
    {
        view = LayoutInflater.from(c).inflate(R.layout.funnyinflate,viewGroup,false);
    }
    ImageView imageView = (ImageView) view.findViewById(R.id.imageView1);
    photos site = (photos) this.getItem(i);
    Picasso.with(c).load(site.getImage()).into(imageView);
    return view;
}

}
pulbic class Funny extends AppCompactActivity{String url = "http://javawy.fulba.com/yphotos.php";
ProgressDialog dialog;
ArrayList<photos> list;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_funny);
    final GridView gridView = (GridView) findViewById(R.id.gridview);
    StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            try {
                JSONObject object = new JSONObject(response);
                JSONArray jsonArray = object.getJSONArray("photos");
                 list = new ArrayList<>();
                for (int i = 0;i<jsonArray.length();i++)
                {
                    JSONObject object1 = jsonArray.getJSONObject(i);
                    String pw = object1.getString("image");
                    photos posts = new photos(pw);
                    list.add(posts);
                }
                customfunny adapter = new customfunny(Funny.this,list);
                gridView.setAdapter(adapter);
                dialog.dismiss();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    dialog.dismiss();
                    Toast.makeText(Funny.this,"error",Toast.LENGTH_LONG).show();
                }
            });
    gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            Intent intent = new Intent(Funny.this,SelectedImage.class);
            intent.putExtra("one",i);
        }
    });
    dialog = new ProgressDialog(Funny.this);
    dialog.setTitle("downloading");
    dialog.setMessage("wait......");
    dialog.show();
    Volley.newRequestQueue(Funny.this).add(stringRequest);
}}

public class SelectedImage extends AppCompactActivity{ @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_selected_image);
    Intent i = getIntent();
    int position = i.getExtras().getInt("one");
    ImageView imageView = (ImageView) findViewById(R.id.result);
    imageView.setImageResource(new Funny().list.get(position));//compiler error
}}

A: Just pas the actual URL in the intent, and then use Picasa to download the image into view. Picasa internally has already cached the image. There is no reason you are recreating the Funny Class and Adapter.


text:
Q: Mad npm on windows 8 - tries to install weird packages in endless loop When I try to install whatever package using npm (node. 0.10.21 x64), npm downloads desired package (entries in node_modules exists but package is not functional) but it continues to download weird packages (not dependencies) and it seems that it gets stuck in some kind of endless loop. Below npm-debug.log from express install, but I cancelled it after a couple of minutes.
link to npm-debug.log (very long)


text:
Q: Laravel Cashier Stripe set capture_method to manual https://stripe.com/docs/payments/capture-later
In the stripe documentation above, they say that if you want to capture a payment hold to set the capture_method to manual and then when you're ready to finalize the charge, to send a capture request with the final amount.
I'm not seeing any documentation in the laravel cashier's implementation on how to do this.
however when I look in the code, I see that I can pass options that get merged in and I could set this I hope?
trait Billable
{
    /**
     * Make a "one off" charge on the customer for the given amount.
     *
     * @param  int  $amount
     * @param  string  $paymentMethod
     * @param  array  $options
     * @return \Laravel\Cashier\Payment
     *
     * @throws \Laravel\Cashier\Exceptions\PaymentActionRequired
     * @throws \Laravel\Cashier\Exceptions\PaymentFailure
     */
    public function charge($amount, $paymentMethod, array $options = [])
    {
        $options = array_merge([
            'confirmation_method' => 'automatic',
            'confirm' => true,
            'currency' => $this->preferredCurrency(),
        ], $options);

        $options['amount'] = $amount;
        $options['payment_method'] = $paymentMethod;

        if ($this->stripe_id) {
            $options['customer'] = $this->stripe_id;
        }

        $payment = new Payment(
            StripePaymentIntent::create($options, $this->stripeOptions())
        );

        $payment->validate();

        return $payment;
    }

...

    /**
     * Create a new SetupIntent instance.
     *
     * @param  array  $options
     * @return \Stripe\SetupIntent
     */
    public function createSetupIntent(array $options = [])
    {
        return StripeSetupIntent::create(
            $options, $this->stripeOptions()
        );
    }

but that seems to set the payment_method and not the capture_method... I feel like this would cause problems if both were set.
As I'm writing this, I think the answer is to use the createSetupIntent function with my desired parameters then save the response so I can reference the intent later and finalize the charge.
Has anyone done this? Rather has anyone reading this done it themselves? and if so, is this the right solution?

A: Although Laravel Cashier is amazing to start you on a subscription based model for your application, I always found Stripe's SDK way more useful, intuitive, and easy to use. Their documentation is amazing, I would suggest using the SDK itself.
Given that, you can continue to use Cashier for everything else and for this particular scenario you can make use of the SDK. For your case you'll have to create a PaymentIntent and like you said, set the capture_method to manual.
Here is an example using Stripe SDK (If you are using Cashier, you already have the package):
$stripe = new \Stripe\StripeClient(
  'YOUR_SECRET_KEY'
);

$stripe->paymentIntents->create([
  'amount' => 2000,
  'currency' => 'usd',
  'payment_method_types' => ['card'],
  'capture_method' => 'manual'
]);


text:
Q: Best VCS and hosting for a student group of 10? We are a student group consisting of ten people. For the next few months, we need to work on a big project together. Therefore, we thought it would be better if we use a VCS.
Many people in the group use git, but we need a web hosting that provides private repository and collaboration. As far as I know bitbucket provides free private repositories, but I wanted to ask if we have better alternatives.
It does not have to be git. We are open to learning new things.

A: Disclaimer: I am the CTO at Assembla
You should definitely use a VCS, your life and code will be that much better and easier to work in. That being said, Assembla is a hosted VCS system for Project Management.
Assembla offers a free offering for small groups, however if this is a Student project, we are open to offering a very large offering for free to students for private or public use.  Just contact me and I will set you up (goes for anyone with a .edu email address, later this process will be formalized and available on the site)
Assembla has lots to offer for project management and repositories, as well, it is fast to start and get using. We offer subversion, git, perforce, and hg repositories integrated with various tools including a ticketing and issue tracking tool.
Take a look at our blog, specifically these posts:
Looking for a Git Bug Tracker
Devlop Faster: Setup Your Git Fork and Merge Network


text:
Q: How to scan for user input of both strings and ints to put into a 2D array in c I am writing a program in C on 2D arrays where I am to get a user generated 2d array based off the amount of employees and products in the store. I am having trouble figuring out how to get the user input consisting of both names and numbers into the array.
  for (int r = 0; r < employees; r++)
{
   for (int c = 0;c < numProducts; c++)
    {
        arr[r][c] = getUserInput();
    }
}

A: So you can use a vector of pairs witch can contain strings and ints.
This sample program allows you to enter pairs node by node, and stores it in a vector of pairs (string and int):
Live sample
#include <iostream>
#include <vector>

int main()
{
    int num;
    std::string str;
    std::vector<std::pair<std::string, int>> nodes; //container

    std::cout << "Enter string and number" << std::endl;
    while(std::cin >> str)
    {
        if(str == "exit") //type exit to leave the input cycle
           break;
        std::cin >> num;
        nodes.push_back(std::make_pair(str, num));
    }

    for (const auto& p : nodes)  // print the products
    {
        std::cout << p.first << " " << p.second << std::endl;
    }
}

You now can incorporate it in what you need to do since your description of the problem doesn't allow me to understand exactly how you relate employees with products and names.
EDIT
So based on you coment I added a new solution maintaining std::pair it's very esasy to use and I'm sure no one will complain about it, so you need a container that has pairs (name, vector of values).
I separated the input of names and values because you you have an employee with several names it's harder to manage the input.
There is no number of employees and products, you can put as many as you need with as many product values as you need.
Live sample
#include <iostream>
#include <vector>
#include <sstream>

int main() {
    double temp_num;
    std::string str, name;
    std::vector<std::pair<std::string, std::vector<double>>> nodes;  //container
    std::vector<double> values;
    while(true){
        std::cout << "Enter employee name ('exit' to leave): ";
        getline(std::cin, str);  //employee name
        if (str == "exit") {
            break;
        }
        name = str;
        std::cout << "Enter values: ";
        getline(std::cin, str);  //values
        std::stringstream ss(str);
        while(ss >> temp_num)
            values.push_back(temp_num);
        nodes.push_back(std::make_pair(name, values));
    }
    std::cout << std::endl;
    for (const auto& p : nodes)  // print names and the products
    {
        std::cout <<"Name - " << p.first << ": ";
        for (const auto& vals : p.second) {
            std::cout <<"$"<< vals << " ";
        }
        std::cout << std::endl;
    }
}


text:
Q: Set Animation speed - ChartJS? I am trying to set the animation speed of a pie chart in chartJS.
I've tried the following:

*

*numSteps: Number

*animationSteps: Number

*Chart.defaults.global.animationSteps = Number
None of these have changed the speed. Any advice?
 var myNewChart;
    var data = [
        {
        value: 30,
        label: "hello",
        color: "#F7464A"
      }, {
        value: 50,
        color: "#E2EAE9"
      }, {
        value: 100,
        color: "#D4CCC5"
      }, {
        value: 40,
        color: "#949FB1"
      }, {
        value: 100,
        color: "#4D5360"
      },

    ];

    var options = {
      animation: true,
      animationEasing: 'easeInOutQuart',
      animationSteps: 80,
      multiTooltipTemplate: "<%= datasetLabel %> - <%= value %>"

    };

    var ctx = document.getElementById("myChart")
                                        .getContext("2d");

    myNewChart = new Chart(ctx).Doughnut(data, options);

A: Use Chart.defaults.global.animation.duration = 3000;

A: Use the animation object
options: {
        animation: {
            duration: 2000,
        },

I haven't see this documented anywhere, but it's incredibly helpful to not have to set the speed globally for every chart.


text:
Q: How to set Magento store config data programmatically? To get store config data, I would use this code:
$data = Mage::getStoreConfig('my/path/whatever');

Now, how could I save to that node? I tried Alans suggestions from Override Magento Config, but it did not work for me.
Thanks!

A: Empire Solution is right but do remember to clean cache after it. So use something like
$value = "100";
Mage::getModel('core/config')->saveConfig('my/path/whatever', $value);
Mage::getModel('core/config')->cleanCache();

A: Try following:
$value = "100";
Mage::getModel('core/config')->saveConfig('my/path/whatever', $value);

OR
$resource = $this->getResourceModel();
$resource->saveConfig(rtrim('my/path/whatever', '/'), 1, 'default', 0);

A: I have a cases when i need change configuration and get changed configuration in the same runnig script. So the expresion doese not work for me:
$value = "100";
Mage::getModel('core/config')->saveConfig('my/path/whatever', $value);
Mage::getModel('core/config')->cleanCache();

I looked at the Mage class and realized that $_config property is a static property and found Mage::reset() method. So fo my case work such expression:
$value = "300";
Mage::getModel('core/config')->saveConfig('my/test/config', $value);
Mage::getModel('core/config')->cleanCache();

Mage::reset();
Mage::app();

$changed_data = Mage::getStoreConfig('my/test/config');


text:
Q: VBA - Excel - Resetting var macro I hope you are doing well.
I wrote a macro for saving the active workbook with the date and hour. Everything work fine except the hour, date are not resetting after I re run the code.
Here is the code:
Sub SaveFile()

Dim fname As String
Dim fdate As String
Dim fhour As String
Dim name As String
Dim name2 As String
Dim path As String
Dim f_name As String
Dim f_date As String
Dim f_hour As String
Dim n_ame As String
Dim n_ame2 As String
Dim p_ath As String

On Error GoTo First
fdate = Format(Date, "yyyy") & " " & Format(Date, "mm") & " " & Format(Date, "dd")
fhour = Format(Time, "hh") & "h" & Format(Time, "mm")
name = Left(ThisWorkbook.name, (InStrRev(ThisWorkbook.name, "_", -1, vbTextCompare) - 1))
path = Application.ActiveWorkbook.path
fname = name & "_" & fdate & " - " & fhour
Application.ActiveWorkbook.SaveAs Filename:=path & "\" & fname, _
FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False

Exit Sub

First:

On Error GoTo -1
On Error GoTo Second
fdate = Format(Date, "yyyy") & " " & Format(Date, "mm") & " " & Format(Date, "dd")
fhour = Format(Time, "hh") & "h" & Format(Time, "mm")
name = Left(ThisWorkbook.name, (InStrRev(ThisWorkbook.name, "_", -1, vbTextCompare) - 1))
path = Application.ActiveWorkbook.path
fname = name & "_" & fdate & " - " & fhour
Application.ActiveWorkbook.SaveAs Filename:=path & "\" & fname, _
FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False

Exit Sub

Second:
f_date = Format(Date, "yyyy") & " " & Format(Date, "mm") & " " & Format(Date, "dd")
f_hour = Format(Time, "hh") & "h" & Format(Time, "mm")
n_ame = Left(ThisWorkbook.name, (InStrRev(ThisWorkbook.name, ".", -1, vbTextCompare) - 1))
path = Application.ActiveWorkbook.path
f_name = n_ame & "_" & f_date & " - " & f_hour
Application.ActiveWorkbook.SaveAs Filename:=path & "\" & f_name, _
FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False

End Sub

The macro currently save for the first time in the wanted format and for the next time will understand and left the correct number of characters to save in the proper wanted format.
I also set a "second chance" in case of too early enter pressed.
Currently if my workbook is name "Workook"
The macro will save it as "Workbook_2019 10 14 - 19h12" and not the current time and date values.
Thanks for your help
Naxos

A: Finally based on your advice I made the code simpler and everything work now.
I post it for the next users
Private Sub SaveFile()
Dim fname As String
Dim fdate As String
Dim fhour As String
Dim name As String
Dim name2 As String
Dim path As String
Dim f_name As String
Dim ppfdate As String
Dim ppfhour As String
Dim ppfname As String
Dim ppfname2 As String
Dim pppath As String

dateactuelle = Now()

On Error GoTo First
fdate = Format(dateactuelle, "yyyymmdd - h\hmm")
name = Left(ActiveWorkbook.name, (InStrRev(ActiveWorkbook.name, "_", -1, vbTextCompare) - 1))
path = Application.ActiveWorkbook.path
fname = name & "_v" & fdate

Application.ActiveWorkbook.SaveAs filename:=path & "\" & fname, _
FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
Exit Sub

First:
ppfdate = Format(dateactuelle, "yyyymmdd - h\hmm")
ppfname = Left(ActiveWorkbook.name, (InStrRev(ActiveWorkbook.name, ".", -1, vbTextCompare) - 1))
path = Application.ActiveWorkbook.path
f_name = ppfname & "_v" & ppfdate

Application.ActiveWorkbook.SaveAs filename:=path & "\" & f_name, _
FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
End Sub


text:
Q: x86 Assembly add and shift How do we write an code to multiply two 32 bit integers only using shift and add. I know how to do it with 16 bit integers but how can we do it for 32 bit integers, do we need two registers to hold the upper half and bottom half?

A: Assume that you are on i386 or above, just use eax,ebx,ecx,edx instead of ax,bx,cx,dx register.
you can use eax even if you are in real mode(16 bit).
If you want some code, here it is.
It uses other instructions like mov, and rol too tough.
(I didn't tested it.)
Multiply eax, ebx and save 32bit result to edx:
mov ecx, 32
xor edx, edx
next_binary_digit:
shl edx, 1
rol ebx, 1
text ebx, 1
jz add_done
add edx, eax
add_done:
loop next_binary_digit

If you want to use memory, it would be more complex because you may need to load value into register and shift, check carry, save back to memory.
Or.. do you want to stick to register size X yet want to multiply integer bigger than X?


text:
Q: JavaScript regular expression with text constants Here is a string: "cn=department9A,ou=subDepartment22,ou=subDepartment9A,o=system". I want to pass every string that match the template as follows: "cn=department9X,ou=subDepartment22,ou=subDepartment9X,o=system" where X - is any symbol (one or more).
Here is my code:
   var str = "cn=department9A,ou=subDepartment22,ou=subDepartment9A,o=system";
   var regexp = new RegExp("cn=department9+,ou=subDepartment22,ou=subDepartment9+,o=system", "ig");
   console.log(regexp.test(str)) //false . but should be true

Please, help me to build a proper regex. Thanks!

A: 9+ repeats the previous token that is 9 one or more times. Use  9[A-Za-z\d]+ instead if you mean alphanumeric characters as symbols.
Example:
> var str = "cn=department9A,ou=subDepartment22,ou=subDepartment9A,o=system";
undefined
> var regexp = new RegExp("cn=department9[A-Za-z\d]+,ou=subDepartment22,ou=subDepartment9[A-Za-z\d]+,o=system", "ig");
undefined
> console.log(regexp.test(str))
true

DEMO

A: Try this regex:
cn=department9[\S\w]+,ou=subDepartment22,ou=subDepartment9[\S\w]+,o=system

This regular expression will work for all the non-white space character or word at the given places
\S - Non white space character
\w - Word character


text:
Q: Spring Security: Handling user direct access to authentication-failure-url I am wondering how do we handle authentication when user directly accesses the authentication-failure-url ?
<security:form-login login-page="/login"
                         username-parameter="username"
                         password-parameter="password"
                         default-target-url="/member/"
                         authentication-failure-url="/invalidlogin"
                         />

I have this in my security-context.xml and /invalidlogin is a Controller for handling authentication failure, so I am wondering how do I handle direct accessing ? basically 2 case scenarios

*

*An authenticated user tries to access invalidlogin

*An unauthenticated user tries to access invalidlogin

Should I just put logic into my Controller for handling that or should I block user for accessing it directly?


text: Q: send google tag manager results to php page via ajax method GET i got a few variables on my site that i push on GTM they work perfect, now i need to get variables results from gtm and send it via ajax to a php page where afterwards i'll use it to an email with the results.


text:
Q: Two python class instances have a reference to each other I am having two python classes, let's call them A and B. A is responsible for handling the receiving and sending of messages of a certain format over the network. B is responsible for interpretation of the messages.
Now a and b are instances of classes A and B respectively. Consider the following scenario:

*

*a receives a message and calls some method of b for message interpretation

*b processes the message and wants to use some method of a to send a response

To achieve this I constructed two classes that have a reference to each other. This works fine but I would like to ask you if this a design flaw and should be avoided?
For illustration see the following minimal code example:
class A:

    def set_b(self, b):
        self.b = b

class B:

    def set_a(self, a):
        self.a = a

if __name__ == '__main__':

    a = A()
    b = B()

    b.set_a(a)
    a.set_b(b)

A: CPython added cyclic garbage collection some versions ago because cyclic dependencies are common enough to be an issue.  Still, you might be able to not create a cycle by having the methods of a that call a method of b pass self instead of depending on b already having a reference to a.
If you stick with the cycle, I would make the linkage as automatic as possible.  For instance:
class B:
    def __init__(self, a):
        self.a = a
        a.set_b(self)

a = A()
b = B(a)
# Both instances are fully initialized and ready to go.

If you forget to pass a to B, you get an immediate exception.


text:
Q: Access token refresh in iOS app extension We have an iOS app which communicates with a web-service.
It uses OAuth authentication (via AppAuth) with access_token and refresh_token. When short access_token expires, we need to refresh it using refresh_token.
We are now adding a Today Extension and want to make the extension communicate with a web-service too. But there is a problem – how to handle the renewal of the access/refresh token pair?
It seems like the main app might be sleeping when Today Extension is running, so sometimes there might be a situation when we want to refresh the access_token right from Today Extension. Since that invalidates the other refresh_token we have in the main app, it becomes very tricky to synchronize tokens back and forth.
Is there any established way to synchronize token refreshing?
Or maybe we should reconsider our approach somehow?
We use Keychain to store and share tokens right now, that part works great. But refreshing and syncing of tokens is something we are having a hard time figuring out.


text:
Q: getting null Value from firestore to recycleview I have made Notificatiion Activity that getting the data from Cloud Firestore. After I test the app. I got always null from database, I checked in the debug. I found the data is read from database, but not setting it in Notification.java. Here is my code:
NotificationActivity.java:
  @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_notifications);

        getSupportActionBar().setTitle(R.string.menu_notifications);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }

        initRecyclerView();
        getNotifications();
        Adview();
    }

    private void initRecyclerView() {
        Log.d(TAG, "initRecyclerView: init recyclerview.");
        mRecyclerView = findViewById(R.id.recyclerv_view);
        if (mNotificationsAdapter == null) {
            mNotificationsAdapter = new NotificationsAdapter(this, mNotifications);
        }
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.setAdapter(mNotificationsAdapter);
    }

    private void getNotifications() {
        SharedPreferences prefs = getSharedPreferences("TOKEN_PREF", MODE_PRIVATE);
        String token = prefs.getString("token", "");

        FirebaseFirestore db = FirebaseFirestore.getInstance();

        CollectionReference notificationsCollectionRef = db.collection("notifications").document(token).collection("messages");
        Query query = notificationsCollectionRef
                .orderBy("Date", Query.Direction.DESCENDING);
        query.get().addOnCompleteListener(task -> {

            if (task.isSuccessful()) {
                for (QueryDocumentSnapshot document : task.getResult()) {
                    Notifications notifications = document.toObject(Notifications.class);
                    mNotifications.add(notifications);
                }
                mNotificationsAdapter.notifyDataSetChanged();
            } else {
                Log.d(TAG,"Query Failed. Check Logs.");
            }
        });
    }

NotificationsAdapter.java:
class NotificationsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private static final String TAG = "NotificationsAdapter";
    private ArrayList<Notifications> mNotifications;
    private Context mContext;

    public NotificationsAdapter(Context context, ArrayList<Notifications> notifications) {
        mNotifications = notifications;
        mContext = context;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        RecyclerView.ViewHolder holder;
        View view = LayoutInflater.from(parent.getContext()).inflate(
                R.layout.notifications_listitem, parent, false);

        holder = new ViewHolder(view);

        return holder;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
        Log.d(TAG, "onBindViewHolder: called.");

        if (holder instanceof ViewHolder) {
            ((ViewHolder) holder).title.setText(mNotifications.get(position).getTitle());
            ((ViewHolder) holder).message.setText(mNotifications.get(position).getMessage());
            ((ViewHolder) holder).date_time.setText(mNotifications.get(position).getDate() + "\n" + mNotifications.get(position).getTime());
            ((ViewHolder) holder).parentLayout.setOnClickListener(view -> {
                Log.d(TAG, "onClick: clicked on: " + mNotifications.get(position).getTitle());

                Intent intent = new Intent(mContext, NotificationDetails.class);
                //  intent.putExtra("image_url", mImages.get(position));
                intent.putExtra("shop_name", mNotifications.get(position).getTitle());
                intent.putExtra("message", mNotifications.get(position).getMessage());
                mContext.startActivity(intent);
            });
        }
    }

    @Override
    public int getItemCount() {
        return mNotifications.size();
    }

       public class ViewHolder extends RecyclerView.ViewHolder {

        CircleImageView image;
        TextView title, message, date_time;
        RelativeLayout parentLayout;

        public ViewHolder(View itemView) {
            super(itemView);
            image = itemView.findViewById(R.id.shop_image);
            title = itemView.findViewById(R.id.title);
            message = itemView.findViewById(R.id.message);
            date_time = itemView.findViewById(R.id.date_time);
            parentLayout = itemView.findViewById(R.id.parent_layout);
        }
    }

Notifications.java
@IgnoreExtraProperties
public class Notifications {
    private String title;
    private String message;
    private String date;
    private String time;

    public Notifications() {
    }

    public Notifications(String title, String message, String date, String time) {
        this.title = title;
        this.message = message;
        this.date = date;
        this.time = time;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

    public String getTime() {
        return time;
    }

    public void setTime(String time) {
        this.time = time;
    }
}

A: Make sure your Firestore / firebase attributes and you java/Kotlin data class attributes are the same. I mean caps letters and everything.

A: Call the getNotification() method first.

A: I solved the issue by changing the variables in the model class to be starting with capital letter.


text:
Q: Adding the full name to the left hand side of 'List of Figures' and 'List of Tables' I'd like to add 'Figure X' and 'Table X' in my lists on Latex, and currents only 'X' is displayed (on the left hand side). See reference below.

Any pointers on how to make this simple change please?

A: Use the tocloft package; to read the manual texdoc tocloft.
\usepackage{tocloft}
\renewcommand{\cftfigpresnum}{Figure }% put Figure before figure number
\addtolength{\cftfignumwidth}{3em}% extra space for Figure (adjust to suit)
% and similarly for Tables, replacing fig above with tab
% and Figure with Table


text:
Q: x86 assembly, little endianness not being followed(or is it?) (Linux) I am new to assembly language programming and I wrote a small program to print the integer using sys_write system call. Here's my code :
section .data

N: dw 216
chr: dw ,0,0,0,0x0a

section .bss

section .text

  global _start

_start:
            xor ax, ax
            mov ax, word [N]
            mov cx, 10
            mov ebx,4

shift_while: div cx
             add dx, 0x0030
             mov word [chr+ebx],dx
             sub ebx, 2
             xor dx, dx
             cmp ax, 0
             jne shift_while
             call printchar

exit:        mov eax, 1
             mov ebx, 0
             int 80h

printchar:  pushad
            mov eax, 4
            mov ebx, 1
            mov ecx, chr
            mov edx, 8
            int 80h
            popad
            ret

I have hard coded 216, the number to be printed and I am getting the correct output. However what I am bemused by is the "mov word [chr+ebx],dx" instruction. dx contains 0x0032 in the first iteration so at the address [chr+ebx] this value should be stored as
32 00 (hex). But when I examined chr memory using gdb, it showed:
(gdb) x /5hx 0x80490d2
0x80490d2 <chr>:    0x0032  0x0031  0x0036  0x000a

what I expected was 0x3200 0x3100 0x3600 x0a00 and thought I'd have to do further memory manipulation to get the right result.
       Am I going wrong somewhere with this. Are there things I can't seem to see. I'd really appreciate a little help here. This is my first first post on stackoverflow.

A: gdb is helping you out here.
You asked for the h (halfword) format, on a little-endian platform, so it is decoding the memory as 16-bit little endian-values for you.
If you use the b format instead, you'll see something more like you expected.

A: It's just a representation thing - what you have in memory from a byte-wise perspective is
32 00 31 00 26 00 0a 00

but when you view this as 16 bit values it's
0032 0031 0026 000a

Similarly, if you viewed it as 32 bit values it would be:
00310032 000a0026

Such is the weirdness of little endianness. ;-)


text:
Q: elasticsearch python interlock ssl_context = create_ssl_context()
ssl_context.check_hostname = False
ssl_context.verify_mode = ssl.CERT_NONE

es = Elasticsearch(hosts=[{'host': 'localhost', 'port': 9200}],
                   scheme="https",
                   # to ensure that it does not use the default value `True`
                   verify_certs=False,
                   ssl_context=ssl_context,
                   basic_auth=("elastic", "elastic"))
es = Elasticsearch("https://127.0.0.1t:9200", ca_certs=False, basic_auth=("elastic", "elastic"))
es = Elasticsearch("https://127.0.0.1t:9200", basic_auth=("elastic", "elastic"))

I tried in many ways. No way.

"elastic_transport.TlsError: TLS error caused by: TlsError(TLS error caused by: SSLError([SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:997)))"

Environmental composition:
win10
elasticsearch-8.4.0
py3.10
pycharm


text:
Q: Why the text rendering is different between "default text" and "user typed text" in UWP TextBox control? You can see that the 2nd TextBox (user typed text) text is wider than the 1st TextBox text.

I found this in WinUI 3 but got the same result in UWP. I couldn't reproduce this in WPF.
This is the XAML.
<Grid HorizontalAlignment="Center" VerticalAlignment="Center">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto" />
        <ColumnDefinition Width="*" />
    </Grid.ColumnDefinitions>
    <TextBlock
        Grid.Row="0"
        Grid.Column="0"
        Text="Default text" />
    <TextBox
        Grid.Row="0"
        Grid.Column="1"
        Text="TestTestTestTestTestTestTestTestTestTest" />
    <TextBlock
        Grid.Row="1"
        Grid.Column="0"
        Text="Typed text" />
    <TextBox Grid.Row="1" Grid.Column="1" />
</Grid>

My question is in the title but I'd like to know if there is a way to make them identically.
UPDATE
Thanks @Niko Zhu ! I tried your suggestion and as you mentioned, this seems to be an IME? or Google Japanese Input problem.

A:
Why the text rendering is different between "default text" and "user typed text" in UWP TextBox control?

I could reproduce this problem with chinses keyboard input, and it looks IME problem that uppercase characters are larger than the default. Please use US keyboard to replace, it will solve the problem.


text:
Q: Convert uint[] to byte[] I'm working on cryptography algorithm and I need to convert initialization vector from uint[] to byte[]:
public byte[] IV { get; set; }

....

uint[] vector = new uint[256] { 0x95ae2518, 0x6fff22fc ...... };
int i=-1;
foreach (uint vec in vector)
{
   IV[++i] = Convert.ToByte(vec);
}

That's not working - it sais that uint is too large to be converted to byte.
So how do you convert from uint[] to byte[]?


text:
Q: Racket random function I'm having trouble with the random function. I have a function set up where:
(define random-abcd
  (cond [(equal? (random 4) 0) 'A]
        [(equal? (random 4) 1) 'B]
        [(equal? (random 4) 2) 'C]
        [else 'D]
        ))

However when I run this 'D comes out substantially more often than any of the other choices. It seems like whatever is in the code for [else ...] happens much more than the other choices meaning that it's not choosing  with equal probability. Is there any way around this?

A: The random function works fine, but your code is wrong. You want this instead:
(define random-abcd
  (let ([n (random 4)])
    (cond [(equal? n 0) 'A]
          [(equal? n 1) 'B]
          [(equal? n 2) 'C]
          [else 'D])))

In your original example, you generated a new random number for every comparison. This seems like it shouldn't affect the distribution, but it does.
In your original formulation, the second case required that the first case was false and the second case was true, giving an actual probability of 3/4 * 1/4, or 3/16. The third case had a probability of 13/16 * 1/4, or 13/64. All cases should have a probability of 1/4 for an equal distribution, and this error skewed your entire set of values.


text:
Q: How do I show grub when resuming from suspend? I have a Sony Vaio laptop, that came pre-installed with Windows 7. I resized the windows partition, then set up a dual boot scenario with Ubuntu.
I've noticed that when I run Windows and put the computer to sleep (i.e. shut the lid), and later resume it will sometimes show the grub menu. If I select the Windows 7 entry, it will resume as expected. If I select Ubuntu, then later restart, then select Windows, Windows will again resume from the last state.
The behaviour seems to be based on the amount of time it has been inactive. For example, if I shut the lid and the re-open straight away, it will return to Windows. On the other hand, if I shut the lid and come back some hours later, grub will be displayed.
On the other hand, with I put Ubuntu to sleep, it will always just go straight to Ubuntu.

*

*Is the behaviour I experience when running Windows - displaying grub, re-producible when running Ubuntu?

*Why does this occur on Windows?

*Can I disable the behaviour from Windows, or is it out of my control?

*How and where is the state saved - can I remove the state without rebooting back into windows and doing a hard reset, so that I can mount the disk?

A: You are experiencing this in Windows because you are resuming from Hibernate, not Suspend. When you leave Windows on suspend for a while while running Windows, it automatically hibernates. To change this on Windows, go to Control Panel->Power Options, select Change plan settings next to your active power plan, then select Change advanced power settings. Then expand the sleep node, followed by the  Hibernate after node. There is a setting for both on battery and plugged in.
If you want Ubuntu to Hibernate if it has been on a Suspend for a while (and therefore show grub on boot), please check this thread.
NOTE: Usually a system takes longer to resume from Hibernate than from Suspend.