text:
Q: Do countable unital rings with uncountably many distinct right ideals have uncountably many maximal right ideals? Suppose we are given a countable unital ring $R$ with uncountably many distinct right ideals. Does it follow from this that $R$ has uncountably many maximal right ideals?

A: No.
Take $R= \mathbb Q[X_0,X_1,...,X_n,...]/\langle X_iX_j\mid i,j\in \mathbb N\rangle=\mathbb Q[x_0,x_1,...,x_n,...]$
The only maximal  ideal (actually only prime ideal !) is
$\langle x_0,x_1,...,x_n,...\rangle$ but $R$ has  a family of distinct ideals indexed by the uncountably many subsets $P\subset \mathbb N$, namely $$ I_P=\langle   x_i\mid i\in P\rangle=\operatorname {vect}_\mathbb Q (x_i\mid i\in P)$$
Edit
I hadn't seen Mariano's answer when I posted mine a few minutes later, but our rings are actually isomorphic : if his $V$ has basis $(v_i)_{i\in \mathbb N}$ over $\mathbb Q$ we have an isomorphism (of $\mathbb Q$-algebras even)
$$ \mathbb Q\oplus V \stackrel {\cong}{\to} \mathbb Q[x_0,x_1,...,x_n,...]:(q,\sum q_iv_i)\mapsto q+\sum q_ix_i$$

A: Let $V$ be a $\mathbb Q$-vector space of countable dimension and let $R=\mathbb Q\oplus V$ with commutative multiplication such that the injection $\mathbb Q\to R$ is a map of rings, multiplication between $\mathbb Q$ and $V$ is the obvious one, and $v\cdot w=0$ for all $v$, $w\in V$.
Every subspace of $V$ is an ideal of $R$, so there are uncountably many of these, yet $R$ is local.


text:
Q: Visual Studio C++ Headers I need to create structure like this:
// file main.h:
#pragma once

#ifndef _MAIN_H
#define _MAIN_H

#include <iostream>

#include "first.h"
#include "second.h"

#endif
// -----------------

// file first.h:
#pragma once

#ifndef _FIRST_H
#define _FIRST_H

#include "main.h" // because of using SomeFunction() in first.cpp

int SomeVar; // used in first.cpp

#endif
// -----------------

// file second.h:
#pragma once

#ifndef _SECOND_H
#define _SECOND_H

#include "main.h" // because of using SomeVar in second.cpp

int SomeFunction(); // implemented in second.cpp

#endif
// -----------------

By logic, if main.h will be compiled first, then each of this headers will be included only once and all variables/functions will be defined normally.
For example, this configuration compiled normally in IAR C++ Compiler, if set up in options "preinclude file" (not precompiled) to main.h.
But, in Visual Studio 2010 same structure causes linker errors like:
1>second.obj : error LNK2005: "int SomeVar" (?SomeVar@@3HA) already defined in first.obj
1>second.obj : error LNK2005: "int SomeFunction" (?SomeFunction@@3HA) already defined in first.obj

I think because of including files in alphabetic order. Apparently pragma- and define-guards are ignored by linker.
Errors can be fixed by additional header and external variables definitions, but this is hard and wrong way.
Question is: What should i do?

A: int SomeVar; // used in first.cpp

Variables should never be defined in headers. They should be declared with extern:
extern int SomeVar; // used in first.cpp

Then you can actually define them in "first.cpp" with int SomeVar;.

Also, "first.h" does not need to include "main.h". Headers should only include files if the definitions in that header absolutely need the contents of those files. The definitions in "first.h" do not need anything in "main.h". Therefore, it should not include it.
If "first.cpp" needs to include something from "second.h", then it is the responsibility of "first.cpp" to include it.

A: In the header file use extern keyword as:
//first.h
extern int SomeVar; //extern tells the compiler that definition is elsewhere

Then in .cpp file define it and use it:
//first.cpp
int SomeVar; //definition is here

As for SomeFunction, have you defined it header file itself? Re-check it. :-)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Problem with get_the_excerpt when using an add_action('the_content') containing script tags Because of the add_action I'm doing on get_content(), where I'm appending social media icons to the end of the post, it appears that calls to get_the_excerpt() are picking up the part of the javascript and appending it to the end of the text returned from get_the_excerpt(). I suppose this is caused by the fact that the "" tags are being stripped out (due to the fact get_the_excerpt() filters them out) as a partial answer.
However, why is this being picked up by get_the_excerpt() in the first place?
It results in the text:

Here is the excerpt.document.write('')...

if((get_option('myTest_facebook_like') || get_option('myTest_plus1') || get_option('myTest_tweet')) && !get_option('myTest_share_title')){
    add_action('the_content', 'myTest_get_social', 10);
}

function myTest_get_social($myTest_share = '') {
    global $post;

    if((get_option('myTest_plus1') == '' && get_option('myTest_facebook_like') ==  '' && get_option('myTest_tweet') ==  '') || in_category("dont-show-social", $post ) || get_post_meta($post->ID, '_noShare', true)) return $myTest_share;

    $myTest_share .= '
';

    $myTest_permalink   = is_front_page() ? get_bloginfo('siteurl') : get_permalink();

    if(get_option('myTest_plus1')){
        $myTest_share .='';
        global $post;
        if(get_post_meta($post->ID, '_myTest_plus1_href', true)){$myTest_share .= '';}
    }

A: Read this post. In your myTest_get_social() function, you need to check if the excerpt filter is active. If it is, just return the content and do nothing else:
 if(current_filter() === 'get_the_excerpt')
    return $myTest_share;

 // otherwise, do your stuff

A: You need to detect when will be filter applicated and skip changes if get_the_excerpt filter will be applicated also
 public function my_content($content) {
   global $wp_current_filter;
   // filter only post content not excerpt
   if (in_array('get_the_excerpt', $wp_current_filter)) return $content;
   return 'post content : ' . $content;
  }
 add_filter('the_content', 'my_content');

This issue come when $post->post_excerpt (excerpt) is empty. Wordpress try prepare excerpt from $post->content and call the_content filter.


text:
Q: How to secure RESTful Web Services (PROVIDER) I need secure Restfull services in the provider. I want that the user must have the authorization for use the REST service and I can generate use stadistic or simply dont allow call the REST services if isn´t a register developer.
I have been thinking about that the user send the email and password in the URL (http://autor.derf.com/api/search/email?=dsdfd@gmail.com&passwd=dasffsdf;) but isnt very safe.
Also I have read about oauth 2.0 but the documentation is very very bad for Java.
Are there any other way to have an RESTful api with authorization?
I want a Restfull API access by Iphone, Android, Windows Phone and web
Thanks in advance ;)

A: If you plan to write all the clients for the service yourself (iPhone, android etc) then sending email and password is a decent alternative, as long as the provider communicates over a secure transport layer (e.g SSL/HTTPS).
You can always add support for OAuth 1 or 2 later if you feel that you want to make your APIs public. (The whole idea with OAUth is to protect user's passwords, and also to get a more fine grained control over which APIs a client can use, and for how long).
But, in your case I would at least consider using basic authentication, in which a typical HTTP request looks somewhat like this:
GET /path/to/api HTTP/1.1
Host: www.example.com
Authorization: Basic aHR0cHdhdGNoOmY=

The hash after "Basic" is simply base64 encoded "username:password", or in your case "email:password". If anyone intercepts it, it is easy to simply un-encode to get the plain text user credentials. So HTTPS is a must.
» More information on basic authentication at wikipedia.


text:
Q: How to change the color of these bars? I'm using an Excel API for Javascript
    var dataRange = sheet.getRange(range);
      var chart = sheet.charts.add("ColumnClustered", dataRange, "Rows");
      chart.axes.valueAxis.minorUnit = 0.2;

      // chart.axes.valueAxis.format.font.

      //                12%
      //                +--+
      //                |  |
      // Acima da barra |  |
      chart.series.getItemAt(0).set({
        // format: { line: { color: 'black', weight: 10}},
        gapWidth: 2,
        dataLabels: {
          format: { font: { name: "Arial", size: 12, bold: false, color: "black" } }
        }
      });

      // chart.format.fill.setSolidColor("orange")

      chart.load('items')

      console.log(`>> ${chart.series.getItemAt(0)}`);

      chart.legend.visible = false;
      chart.dataLabels.format.font.size = 15;
      chart.dataLabels.format.font.color = "black";
      chart.axes.categoryAxis.format.fill.setSolidColor("white");
      chart.series.add();

      chart.axes.valueAxis.majorGridlines.visible = false;

A: Após muitos teste eu descobri como fazer:
chart.series.getItemAt(0).format.fill.setSolidColor("black")


text:
Q: Regarding Fisher information conditions If the condition
$$
\frac{d}{d\theta}\mathbb{E}\Big[\frac{\partial}{\partial\theta}logp_\theta(x)\Big] = \int_{x} \frac{\partial}{\partial\theta}\Big[\frac{\partial}{\partial\theta}logp_\theta(x)p_\theta(x)\Big]dx
$$
holds then $\mathbb{E}\Big[\Big(\frac{\partial}{\partial\theta}logp_{\theta}(x)\Big)^2\Big] = -\mathbb{E}\Big[\frac{\partial^2}{\partial\theta^2}logp_{\theta}(x)\Big]$. What is a parallel condition for PMFs?


text:
Q: Pipe filtered Android logcat to file Logcat obviously has a lot of rubbish so, I use the filters to exclude all rubbish when in AS.
However, I can't figure how to do this when I am piping logcat to a file:
adb logcat > test.txt

How can I filter them so I don't have thousands of unwanted lines in the file?
There are a LOT of filters. Excluding many, many tags.
I am on Windows 10.


text:
Q: How to use Phonegap SoftKeyboard Plugin for Android? I am developing an Android application using Phonegap. I need to make the softkeyboard appear programatically. I am using the SoftKeyboard plugin which is found here. Can anyone tell me how to properly include this plugin & make it work? I have tried the tutorial found on the Phonegap Wiki, but the plugin is not working.
[Update] I have added the plugin to the path
com/zenexity/SoftKeyBoardPlugin/SoftKeyBoard.java
Updated plugins.xml and included
<plugin name="SoftKeyBoard" value="com.zenexity.SoftKeyBoardPlugin.SoftKeyBoard"/>

Then in the www folder added softkeyboard.js, and  the following in index.html
plugins.SoftKeyBoard.show(function () {
    // success
},function () {
   // fail
});

But nothing happens, the keyboard is not displaying..

A: For the latest version of PhoneGap (Apache Cordova 2.1.0) I had to do the following:
Installed these plugin sources which reflected the project name change:
https://github.com/originalgremlin/phonegap-plugins/tree/master/Android/SoftKeyboard

*

*Copy softkeyboard.js to your javascript library directory.

*Copy SoftKeyBoard.java to src/org/apache/cordova/plugins/SoftKeyBoard.java

Put this in your HTML file, after including the cordova.js file:
<script src="/path/to/javascripts/softkeyboard.js"></script>

Add this to the bottom of the res/xml/config.xml plugins section:
<plugin name="SoftKeyBoard" value="org.apache.cordova.plugins.SoftKeyBoard" />

Now, assuming this HTML:
<button id="keyboard">Toggle Keyboard</button>

This jQuery should do something useful:
var softkeyboard = window.cordova.plugins.SoftKeyBoard;
$('#keyboard').toggle(softkeyboard.show, softkeyboard.hide);

A: Try it like this:
SoftKeyBoard.show(function () {
    // success
},function () {
   // fail
});

The code in the JS file does not put it in the "plugins" namespace.
Orjust use the PhoneGap plugins full namespace:
window.plugins.SoftKeyBoard.show(function () {
    // success
},function () {
   // fail
});

A: This is how I got SoftKeyBoard working in my application.
DroidGap Side

*

*create /src/com/phonegap/plugins/SoftKeyboard with provided file SoftKeyBoard.java inside

*add to /res/xml/plugins.xml:
< plugin name="SoftKeyBoard" value="com.phonegap.plugins.SoftKeyboard.SoftKeyBoard" />
/assets/www Side

*

*add provided file softkeyboard.js to /assets/www/js

*add to index.html in the head where your other javascripts are included after you have included the phonegap javascript:
< script type="text/javascript" charset="utf-8" src="js/softkeyboard.js"></script>
You can then call the following if you are on device or using something like Ripple:
window.plugins.SoftKeyBoard.show(function () {
  // success
},function () {
  // fail
});

or something like this if you want to make sure the namespace is available, which will prevent undefined problems:
((((window || {}).plugins || {}).SoftKeyBoard || {}).show || function(){})();

I think maybe where you went wrong was not including the js/softkeyboard.js in your head of index.html.
Hope this helps you

A: go through the link. here is the full project:--
SoftKeyboardPlugin by Simon McDonald

A: Cordova 3.0 + JQM 1.3.2: Changing "fullscreen" to "false" in config.xml fixed the "adjustPan" and prevented my inputs from being covered when the keyboard displayed. However, blur() would not close the keyboard and this plugin worked wonderfully.
For the almost latest version of phonegap:

*

*Add SoftKeyBoard.java to your app package in src

*Add softkeyboard.js to assets/www

*Update config.xml with:
<feature name="SoftKeyBoard"><param name="android-package" value="com.yourAppPackage" /></feature>

*Call your plugin: plugins.SoftKeyBoard.hide(function() {//success }, function() {//fail });


text:
Q: Codeigniter + NetBeans + XDebug : Debugger not working after redirect() I am working on a project that uses CodeIgniter. I use Netbeans as my IDE and I have Xdebug installed. I am using XAMPP for local development.
What Works: Xdebug is working fine for normal PHP code.
Problem: However, I am facing problems debugging my CodeIgniter project. Debugger stops on a redirect()
Problem Details: Start debugging project in netbeans. Debugger starts and we see homepage. On homepage, there is a link that corresponds to a method in homepage controller. Debugger reaches the method in controller to which the link points to. In this method there is a redirect. At the point of redirect debugger STOPS.
Relevant Code Snippet(s):
URL That is clicked (This is part of the header menu)
<a href="<?= base_url("somefunc/"); ?>">Click Me </a>

routes.php - Reroute for prettier url.
$route['somefunc'] = "foo/somefunc";

And in my Foo Controller (foo.php):
class Foo extends CI_Controller {
    public function somefunc()
    {
        redirect('/bar/otherfunc');  // DEBUGGER REACHES TILL HERE THEN STOPS WORKING
    }
}

As said above in the comment in function somefunc(), Xdebug stops working at the place where the redirect happens.
Additionally, the following information might be of some use:
config.php
$config['uri_protocol'] = 'AUTO'; // I have also tried PATH_INFO, QUERY_STRING, REQUEST_URI & ORIG_PATH_INFO.
$config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-';
$config['enable_query_strings'] = TRUE; // Have tried FALSE too.
$config['index_page'] = ''; // Tried index.php too.

xdebug settings in php.ini
zend_extension ="path\to\xampp\php\ext\php_xdebug.dll"
xdebug.remote_enable=on
xdebug.remote_handler=dbgp
xdebug.remote_host=localhost
xdebug.remote_port=9000

NOTE - I have already tried playing around with different suggestions that I have seen here as well as through google but to no avail. Can somebody please point me in the right direction?

A: Found a solution. Perhaps this might help someone else who has been struggling with this. Apparantly to allow smooth debugging, you need to include the option:
xdebug.remote_autostart=1

in your php.ini. These settings work for me now:
xdebug.remote_enable=on
xdebug.remote_handler=dbgp
xdebug.remote_host=localhost
xdebug.remote_port=9000
xdebug.remote_autostart=1

The last line is the option I found on (Xdebug Official Documentation). The relevant part of the documentation is mentioned below:
xdebug.remote_autostart
Type: boolean, Default value: 0
Normally you need to use a specific HTTP GET/POST variable to start remote debugging (see Remote Debugging). When this setting is set to 1, Xdebug will always attempt to start a remote debugging session and try to connect to a client, even if the GET/POST/COOKIE variable was not present.

A: I found the same problem, and fixed it by upgrading my version of xdebug.
There appears to have been a bug in the version I was using (xdebug 2.1.3), but it all works fine on xdebug 2.2.3.
Use this tool for custom installation instructions for your environment.
http://xdebug.org/wizard.php

A: Be aware that netbeans doenst work with $_SERVER['PATH_INFO'] and url like http://127.0.0.1/site/test.php/v1/v2/parametertoputonphpathinfo/v3, there is a bug of Mon Sep 09, 2013 8:54 am on netbeans board telling about it without response until now 2014:
http://forums.netbeans.org/topic56645.html
It make impossible debug frameworks using that sinatra way to routing requests.
Rewriting my simple Sinatra router to have a $_GET mode to debug and a better hook code.


text:
Q: Get the attribute value from inner tag of Div tag using jsoup i want extract the content  from webpage using jsoup. the values are in inner  tag How will  extract those values?
For example

        FRONT PAGE*

i want extract  the content  FRONT PAGE in  anchor tag * how will do this?

A: This will print the text of all the link tags with class toplevel-a
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class Main {

    public static void main(String[] args) throws Exception {
        String html =   "

" +
                            "" +
                                "
" +
                                    "
" +
                                        "
" +
                                            "FRONT PAGE*" +
                                        "
" +
                                    "
" +
                                "
" +
                            "";

        Document doc = Jsoup.parse(html);
        Elements els = doc.select("a.toplevel-a");
        for(Element el : els) {
            System.out.println(el.text());
        }
    }
}


text:
Q: Use Ghostscript to convert each page of a PDF to images and the output is still PDF I know that Adobe Acrobat Reader DC can select the Microsoft Print to PDF printer to output to a PDF file with Print As Image checked in the Advanced Print Setup dialog. However, I want to use a command to do this. I tried the following command, as a result it failed to convert each page to images (Note the output file is still PDF).
gs -o 0.999.watermask.compact.screen.pdf -sDEVICE=pdfwrite -dDetectDuplicateImages=true -dPDFSETTINGS=/screen 0.999.watermask.pdf

References

*

*7.4 PDF file output

*iText 7 iText 7 for Java represents the next level of SDKs for developers that want to take advantage of the benefits PDF can bring.

*itext-rups-7.1.14.jar iText RUPS iText® 7.1.14 ©2000-2020 iText Group NV (AGPL-version)

A: Your -switches include -dDetectDuplicateImages=true which under the circumstances should be superfluous and the device selection can be from one of four as pointed out by KenS.
gs -o 0.999.watermask.compact.screen.pdf -sDEVICE=pdfimage32 -dPDFSETTINGS=/screen 0.999.watermask.pdf

If you want to emulate MS Print As Image PDF on Windows you would find the result in some ways inferior (and often many times bigger). But for comparison it would be,
NOTE:- "%%printer%%... is for a batch file for a command line use "%printer%...
gswin64c.exe -sDEVICE=mswinpr2 -dNoCancel -o "%%printer%%Microsoft Print to PDF" -dPDFSETTINGS=/screen -f "0.999.watermask.pdf"


text:
Q: How do I push a new project to a shared Mercurial multi-repository? I have a local machine ("laptop") and a shared Mercurial repository on another machine ("server").
The shared repository is set up as a multi-repository as described in the Mercurial documentation using Apache, the hgwebdir.cgi script and Mercurial 1.4.
The setup works in the sense that I can browse the projects (repositories) in the web browser, I can clone and pull from the server, and I can push from the laptop when the project/repository already exists on the server.
But I cannot create a new project on the laptop (hg init, do stuff, hg commit) and push it to the shared multi-repository (hg push http://server/hg/my-new-project-name) - I get "abort: HTTP Error 404: Not Found", presumably because the directory/project repository does not exist yet.
How can I push a new project/directory structure to a Mercurial running elsewhere? I couldn't find anything in the documentation, how do you guys do it?

A: Update
I tried using Dropbox as described below, but couldn't make it sufficiently reliable, so I'm not recommending that option.
Original answer below, kept for context.
/update
I found one more option: Skipping both http and ssh altogether and using Dropbox for shared repos.
For the one-person-multiple-computers scenario, it looks like the simplest option of the lot, and you get backups as a nice side effect.
Here is a discussion on Hacker News

A: You cannot create new remote repositories over http with the built-in functionality.  Your options are to either:

*

*create with a ssh clone: `ssh clone local-repo ssh://you@remote//path/to/repo'

*log in to the remote repo and do a hg init where you want the repo.  After that you can push to the new empty repo

*Use a cheesy http-creation CGI like the one I wrote here: http://ry4an.org/unblog/UnBlog/2009-09-17


text:
Q: Order got deleted automatically after successful payment I am using Magento 2.3.3.
One order was automatically deleted after successful payment via authorize.net.
I didn't found order in database in quote table in reserve_order_id column and also not in sales_order table.
I also got confirmation email too.
Is anyone knows why this happened?
And I am using the mage-mojo server and mage-mojo told me request header was too large.
but I want to know that if the request header was large than why payment was successful and why order email was received ?
I have 1 observer
events.xml
<event name="checkout_submit_all_after">
    <observer name="add_terracycle_option_to_order" instance="Vendor\Modulename\Observer\Terracycle" />
</event>

Terracycle.php
<?php
namespace Vendor\Modulename\Observer;

use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;

class Terracycle implements ObserverInterface {

    protected $_cart;
    protected $_logger;

    public function __construct(
        \Magento\Quote\Api\CartRepositoryInterface $cart,
        \Psr\Log\LoggerInterface $logger
    ) {
        $this->_cart = $cart;
        $this->_logger = $logger;
    }
    public function execute(Observer $observer) {
        $order = $observer->getOrder();
        $quoteRepository = $this->_cart;
        /** @var \Magento\Quote\Model\Quote $quote */
        $quote = $quoteRepository->get($order->getQuoteId());
        $terracycle_value = $quote->getTerracycle();
        $order->setTerracycle($terracycle_value);
        $order->save();
        $message = "Order Id: " . $order->getId() . " | terracycle_value: " . $terracycle_value;
        $this->_logger->info($message);  //saved in var/log/system.log
    }
}

Is this possible to have some fault with this code ? because as I test this code it is working fine.

A: Same issue for me , random couple of orders are deleted , it send email , success payment and all working , but missing in all table and admin and customer too

A: Persistance Cart issue
Got issue , try following steps to reproduce issue
1) enable persistence cart
2) login as customer and add product to cart and go to checkout page , don't complete checkout , just logout with product in cart
3) now you are logged out as customer but add same product as Guest user go to checkout in same browser , use different email and all different address details and complete order with any payment method , check money order will also work
4) now check order number , missing order number in admin , but your both email (customer email and guestemail ) have success orderemail , and one of that order is missing in admin panel and everywhere in DB , but found mixed data in Quote table
Issue is , persistence cart data is mixed from previous persistence cart data
Temporary Solution
Disable Persistence Cart
I have check open issue in https://github.com/magento/magento2/issues/13229


text:
Q: Set background color of an PDF generated using libHaru So I am trying to set background color in C++ using libHaru for my new pdf.
I am having issues setting it. Searched through documentation and either was not there
or I missed it.
Anyone who knows how to set background color for pdf page?
Also any comments on libHaru? Would you recommend it etc would be awesome.
Thanks

A: There is no background color for a PDF page. If you want to make the page red, for example, you draw a rectangle that covers the page and fill it with red.


text:
Q: Using setter through decorators RecursionError I was looking at some link about Python.
https://medium.com/the-renaissance-developer/python-101-object-oriented-programming-part-1-7d5d06833f26
And there are decorators used in there to create(?) properties and a setter method for it. Below is the code:
class Vehicle:
    def __init__(self, number_of_wheels, type_of_tank, seating_capacity, maximum_velocity):
        self.number_of_wheels = number_of_wheels
        self.type_of_tank = type_of_tank
        self.seating_capacity = seating_capacity
        self.maximum_velocity = maximum_velocity

    @property
    def number_of_wheels(self):
        return self.number_of_wheels

    @number_of_wheels.setter
    def number_of_wheels(self, number):
        self.number_of_wheels = number

And this is the usage from the link as well.
tesla_model_s = Vehicle(4, 'electric', 5, 250)
print(tesla_model_s.number_of_wheels) # 4
tesla_model_s.number_of_wheels = 2 # setting number of wheels to 2
print(tesla_model_s.number_of_wheels) # 2

So, I was trying to understand why should I use it, instead of, you know, directly accessing class variable itself. I tried to run the code but I got RecursionError.
  File "C:/Users/Brandon/Desktop/Python/tryit.py", line 16, in number_of_wheels
    self.number_of_wheels = number
  [Previous line repeated 491 more times]
RecursionError: maximum recursion depth exceeded while calling a Python object

Finally my question is, how can this code work(what is wrong with it maybe?) and more importantly why should I use setter instead of accessing class variable directly?
ps. Any pointers like links to read or keywords for search are welcomed.

A: The property and attribute should not have the same name, otherwise, the setters and getters will keep calling themselves over and over. Conventionally, you would prepend a leading underscore to privatize (though it's not private) the attribute you're creating a property for.
class Vehicle(object):
    def __init__(self, number_of_wheels, type_of_tank, seating_capacity, maximum_velocity):
        self._number_of_wheels = number_of_wheels
        ...

    @property
    def number_of_wheels(self):
        return self._number_of_wheels

    @number_of_wheels.setter
    def number_of_wheels(self, number):
        self._number_of_wheels = number

Also remember to subclass object in Python 2, to make your class work with property.


text:
Q: Does webview create a separate surface like videoview does? I have a confusion and look forward to some comments on this. I was assuming that WebView creates a separate surface to draw and does not use the default surface of the activity to draw. But, in surfaceflinger dump, I dont see a new surface getting created when using webview.
When I do the similar experimnet of using videoview, I see a separate surface getting created.
Onwebview also, I wanted to play a video, so was assuming a separate surface would be created and thereby the surface resolution would be as per video resolution. But if it uses application's surface, then the max resolution of the video has to be of the UI resolution.
In chromium code, I see the code for separate surface but then in practical I could not see one getting created.
Can someone help me to clarify this.
Thank You.

A: If you look at VideoView inheritance graph you'll notice that it inherits from SurfaceView, while WebView does not, so WebView can only achieve that by creating an external SurfaceView.
While if you search for usages of ExternalVideoSurface in WebView part of Chromium code, you will notice that it is only enabled if "video hole" is enabled, which is intended to be used only for decoding encrypted videos, where WebView needs to do "hole punching". There is a System API-level setting in WebView that enables this behaviour, but it has its own limitations, and thus not recommended to be used in general.

A: I am also curious webview is not in sufaceflinger dump.
I think the reason is webview also render to the related activity native window, so there is not another surface in this situation.
But the situation seems differs in the lastest Android and Webview version by developer's option.


text:
Q: Firebase Realtime Database Configuring I'm trying to create in firebase a realtime database after a user sign in/log in for his profile.I made the authentification firebase,it's showing me that the user is in the firebase authetication.I tried a lot of tutorials but nothing works. How can I connect the authentication and the realtime database to make a user profile.
Rules:
  "rules": {
    ".read": "auth != null",
    "$user_id":{
       ".read": "auth.uid === $user_id",
       ".write": "auth.uid === $user_id"
    }
  }
}

User class:
   public String firstName;
    public String secondName;
    public String uid;
    public String email;
    public User(){

    }

    public User (String firstName, String secondName, String uid, String email) {
        this.firstName = firstName;
        this.secondName = secondName;
        this.uid=uid;
        this.email=email;
    }

    public User (String firstname, String secondname) {
    }

    public String getFirstName () {
        return firstName;
    }

    public String getSecondName () {
        return secondName;
    }

    public String getUid () {
        return uid;
    }

    public String getEmail () {
        return email;
    }

    public void setFirstName (String firstName) {
        this.firstName = firstName;
    }

    public void setSecondName (String secondName) {
        this.secondName = secondName;
    }

    public void setUid (String uid) {
        this.uid = uid;
    }

    public void setEmail (String email) {
        this.email = email;
    }
}

And the UserDetails class:
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.Button;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class UserDetails extends AppCompatActivity {
    private FirebaseAuth auth;
  private DatabaseReference reference;
  private FirebaseDatabase database;
  private FirebaseAuth.AuthStateListener authStateListener;
    private FirebaseUser user;
    private EditText firstName,secondName;
    private Button saveInfo;

    @Override
    protected void onCreate (Bundle savedInstanceState) {
        super.onCreate ( savedInstanceState );
        setContentView ( R.layout.activity_user_details );
        firstName=(EditText)findViewById ( R.id.firstname );
        secondName=(EditText)findViewById ( R.id.secondname );
        saveInfo=(Button)findViewById ( R.id.data );
        auth=FirebaseAuth.getInstance ();
        reference.addValueEventListener ( new ValueEventListener () {
            @Override
            public void onDataChange (@NonNull DataSnapshot dataSnapshot) {
                String firstname=dataSnapshot.getValue (User.class)
            }

            @Override
            public void onCancelled (@NonNull DatabaseError databaseError) {

            }
        } )

    }

}

I deleted some code at the DataSnapshot because it didn't work.What can I do? I used a lot of tutorials but nothing is written in the database. I want to be write in the database the userId,first name and the second name

A: The code reference.addValueEventListener reads from the database, while you're asking about writing.
To write to the database, you can do something like:
User user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
  DatabaseReference userRef = FirebaseDatabase.getInstance().getReference(user.getUid());
  userRef.child("firstname").setValue("Value of firstname field");
  userRef.child("secondname").setValue("Value of secondname field");
}

This creates a structure where the user data is stored under their UID, which is what your security rules enforce.

You can merge the two write operations in a single setValue() call with:
Map<String,Object> values = new HashMap<>();
values.put("firstname", "Value of firstname field");
values.put("secondname", "Value of secondname field");
userRef.setValue(values);

If you don't want to use maps of values, you can create a Java class to represent a user's properties. The simplest version of a class with these two JSON properties is:
class UserProperties {
  public string firstname;
  public string secondname;
}

And then initialize and write it with:
UserProperties userprops = new UserProperties();
userprops.firstname = "Value of firstname field";
userprops.secondname = "Value of secondname field";
userRef.setValue(userprops);


text:
Q: How to use volume's button to zoom in/out text in textview How to override and use volume buttons to zoom IN/OUT text inside in layout, similar as when you are writing/reading SMS ?

A: Please check this solution.
public class MainActivity extends AppCompatActivity {
    TextView txt;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        txt = (TextView) findViewById(R.id.OpenClose);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
            float x = txt.getScaleX();
            float y = txt.getScaleY();

            txt.setScaleX(x - 1);
            txt.setScaleY(y - 1);
            return true;
        } else if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
            float x = txt.getScaleX();
            float y = txt.getScaleY();

            txt.setScaleX(x + 1);
            txt.setScaleY(y + 1);
            return true;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }
}


text:
Q: Slider width and height without stretching I'm working on a website for a friend of mine. There's only one problem. The slider won't fit in the frame without stretching.
I've set it to 100% height, but it won't work out. (Its also responsive)
I want it to be a nice image in the original width and height (100x100, 200x200 etc) without stretching (200x500).
I hope you guys can help me out on this.
I'd tried alot and also asked some other people but they can't help me with this.
You can see the slider over here.
http://tinyurl.com/p36hz6u
Here's another version of the slider, but on this version the slider image gets cut off
http://tinyurl.com/nfjjvwu

A: If the images are background images, consider using the background-size:contain; which will allow the image to grow as large as visible/possible without stretching, and then you can position the background image wherever desired with background-position
If the slides have actual physical <img /> tags, I made a JSfiddle that demonstrates code that will contain an image within an element. In this example, the <div> tags represent a browser window and can be resized: http://jsfiddle.net/dds27w2y/

A: Firstly what I would do is to remove the: background-size: 100% 100% and add a background-position: center center.
Then I would add a background-color: white to the container. This would make it look nicer and it would be centered.


text:
Q: Django REST depth = 1 without quit the field form Model:
class StoreSettings(models.Model):
    slider_images = models.ManyToMany......

In Serializer I have this:
class SettingsSerializer(serializers.ModelSerializer):
    class Meta:
        model = StoreSettings
        fields = ('slider_images', )
        depth = 1

Adding depth = 1 The Multiple choice field is removed of the Django Rest form
I want to add depth = 1 but, with the form like It didn't happend
Thanks

A: Adding depth=1 means you want nested forms which Django REST framework doesn't support. Therefore it discards the field.


text:
Q: fB share button is not rendering This is the code i am using to display the Share button
    <!DOCTYPE html>

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

But the share button is not showing
any ideas?


text:
Q: Is it fine to remove all the language files for localizations I don't need in The Witcher 2? Is it alright to remove CookedPC/*.w2{strings,speech}, CookedPC/user_speech/* and so on for localizations I don't need? From what I saw this could save me nearly 5 GiB and would therefore offset the installation of REDkit a bit. It's not that I'm short on disk space, but I don't like wasting it either.
What steps are required (e.g. removing the registration for the localizations or using REDkit etc)?
I am using the GOG.com version (The Witcher 2 Enhanced Edition).

A: The answer appears to be: yes, it's possible.
Here's what I did. I hardlinked all the files into a different directory on the same volume, effectively duplicating the whole folder structure. After that I removed folders and files from the installation folder and tried running the game. The only difference is that the "Options" in the launcher don't show the pruned languages anymore.
For good measure I also launched the game and loaded a save game. All appears to work perfectly fine. No hiccups.
For reference: I removed all but the en locale.


text:
Q: Received Could not find a suitable TLS CA certificate bundle in Python I am trying to invoke a Particular API .
Received the below Error
OSError: Could not find a suitable TLS CA certificate bundle, invalid path: /etc/ssl/certs/ca-certificates.crt
I have set the HTTPS proxy also and set Environment variable to the below
os.environ['REQUESTS_CA_BUNDLE'] = os.path.join(
'/etc/ssl/certs/',
'ca-certificates.crt')

Please let me know how can i resolve the error .
Thanks in advance


text:
Q: Invalid hash - Stripe (Creating Source) Good day everyone so I'm creating a source on stripe with the payment method IDEAL using their library and I stumbled with this unusual error.
Fatal error: Uncaught exception 'Stripe\Error\InvalidRequest' with message 'Invalid hash' in /home/ubuntu/workspace/ideal/stripe-php-4.13.0/lib/ApiRequestor.php:110 from API request 'req_S1FAI6czFIggdC' in /home/ubuntu/workspace/ideal/stripe-php-4.13.0/lib/ApiRequestor.php on line 110
That error only appears when I tried to add this line of code under the owner object below (pls refer to my actual code below), that causes the error even its on the right place to add.
 "address" => "Test Adress"

Actual Code:
\Stripe\Stripe::setApiKey("test_key_here");

$source = \Stripe\Source::create(array(
  "type" => $type,
  "currency" => $currency,
  "amount" => $amount,
  "statement_descriptor" => $product,
  "owner" => array(
    "phone" => $phone,
    "email" => $email,
    "name" => $name,
    "address" => "Test Adress" //this causes the error
  ),
  "redirect" => array (
    "return_url" =>  $returnUrl
  ),
  "ideal" => array(
    "bank" => $bank
  )
));

A: The issue here is that address is not the street address, it's a hash that expects multiple sub-parameters (the line 1 and line 2, the city, etc.) as documented here: https://stripe.com/docs/api#create_source-owner-address
The code should be something like this:
$source = \Stripe\Source::create(array(
  "type" => $type,
  "currency" => $currency,
  "amount" => $amount,
  "statement_descriptor" => $product,
  "owner" => array(
    "phone" => $phone,
    "email" => $email,
    "name" => $name,
    "address" => array(
      "line1" => "Test line1",
      "city" => "My City",
      "postal_code" => "90210",
      "state" => "CA",
  ),
  "redirect" => array (
    "return_url" =>  $returnUrl
  ),
  "ideal" => array(
    "bank" => $bank
  )
));


text:
Q: Best way to transfer XML data between server and client sockets Server side:
PrintWriter outputStream = new PrintWriter(client.getOutputStream(),true);
BufferedReader inputStream = new BufferedReader(newInputStreamReader(client.getInputStream()));
outputStream.println("hello client");
System.out.println("server got: " + inputStream.readLine());
outputStream.println("to the client");

Client Side:
try{
    serverSocket = new Socket("machineName", 4444);
    out = new PrintWriter(serverSocket.getOutputStream(), true);
    in = new BufferedReader(new InputStreamReader(serverSocket.getInputStream()));
}
catch(Exception e){
    e.printStackTrace();
}

if ((fromServer = in.readLine()) != null) {
    System.out.println("Server: " + fromServer);
    fromUser = "I am the user";
    out.println(fromUser);
    System.out.println("Server: " + in.readLine());
}

 I am using this format for communicating between server and client sockets. Now I would like to send XML between client and server instead of strings. I have used DOM to parse XML data on server and client side.
Is there an efficient way to transfer XML between client and server instead of converting the XML to string and removing newline (because readLine reads one line at a time and XML start tag & end tag wont come in a single line in XML format) from XML data and sending it to client through Printwriter.
Thanks
P.S: This is not a homework question. I am learning java sockets for interviews.

A: Look into StAX api. It is designed for transferring XML data over the internet.

Streaming refers to a programming model in which XML infosets are
  transmitted and parsed serially at application runtime, often in real
  time, and often from dynamic sources whose contents are not precisely
  known beforehand.
  [...]
  Streaming models for XML processing are particularly useful when your
  application has strict memory limitations, as with a cellphone running
  the Java Platform, Micro Edition (Java ME platform), or when your
  application needs to process several requests simultaneously, as with
  an application server.

More in the docs: http://docs.oracle.com/javase/tutorial/jaxp/stax/why.html

A: You can convert your XML to compressed binary data by using Exificient

The EXI format is a very compact representation for the Extensible Markup Language (XML) Information Set that is intended to simultaneously optimize performance and the utilization of computational resources.

A: Actually, XML data is nothing more than string (but you can treat it as binary too). Your problem is sending many lines of xml string. If you don't want to use third party library, just do it by hand, here is a good place to start: https://stackoverflow.com/a/2441736/719212. This example uses the byte stream to send and receive xml data with parsing xml.


text:
Q: Attribute android:colorForeground not working in API 23 By setting android:colorForeground in the theme, the main text colours are calculated based on this setting, i.e. android:textColorPrimary and android:textColorSecondary.
I have tested this with API 23 and API 27. In API 23 it is not working and the text colours are based on white. In API 27 it is working as expected.

*

*Is this a known bug?

*Is there an easy workaround?

*How extended is the bug on different versions of the API?

Thank you very much.

A: As far as I can tell this is rather an issue of Android Studio. The Layout Editor is showing a color calculation behaviour for API 23, wich seems to be available from API 26 onwards.
The color requires an attribute primaryContentAlpha which is available for API 26.
I still have to find out, how the fallback behaves for lower API and if I can fix this by a support library.
See: Support library for text color behaviour of API 26?


text:
Q: Translating excel function to c# Math.pow not resulting in same values I'm trying to translate this function from excel to C#:
=10^(0.1*(-44.1224+3.32*(-97.060520104064452*LOG(0.89*(200/160)))))
excel gives me: 1.2467E-06
var value = Math.Pow(10, 0.1 * (-44.1224 + 3.32 * (-97.060520104064452 * Math.Log10(0.89 * (200 / 160)))));

C# gives me c#value = 0.0016543260792358536
Anybody has any ideas why I don't get the same value in excel and c#?

A: Because C# is rounding for you.
Change this:
200 / 160

To
200.0 / 160.0

Output locally:
1.24676291550131E-06

A: It's because 200/160 is being cast to an integer, which truncates your result. To fix the issue, you can do as Rob suggested and write the numerator or demoniator as a floating point number. See the / operator reference.


text:
Q: How to find where UIWebView is being included in my project another UIWebView question. I've started working on a project that is being rejected by Apple with the following error:

ITMS-90809: Deprecated API Usage - New apps that use UIWebView are no longer accepted. Instead, use WKWebView for improved security and reliability. Learn more (https://developer.apple.com/documentation/uikit/uiwebview).

I've successfully removed references to UIWebView on other projects, but I can't find where the reference is coming from in this case.
So far I've tried the following:

*

*Searched for references to UIWebView in the project, and confirmed that there are none.

*Searched for references in dependencies using grep -r UIWebView ., and confirmed that there are none (after updating dependencies for the ones I found).

*Updated all pods to the latest versions.

However when I inspect the binary by running nm MyProject.app/MyProject | grep UIWebView it returns U _OBJC_CLASS_$_UIWebView, i.e. the reference is still there, hence it is still being rejected by Apple.
Does anyone have any suggestions how I can locate where that reference is coming from?


text:
Q: how to automatically color a certain instance of text? I have made a website for a basketball association. It has a number of teams that each have their calendars. You can see it here for instance this is team "Heren C". As you can see in the calendar below there are some home games and some away games. We also have "Heren A", "Heren B", "Junioren", "Cadetten", and so on...
Now, these calendars are all tables and I would like to color (in this example) "Heren C" and make it bold. I want to do this for all our teams, so without actually going through each table and change these text instances.
Just to be sure I will mention that it's a Wordpress site and that each team is a different page, so it's loaded with the same template each time. Maybe that can help for the code.
Hope you guys can help!

A: You can use CSS3 Attribute Selectors
a[href*="heren-c"] {
  font-weight: bold;
}

the *= operator to make an attribute selector match elements that have an attribute which contains the specified value:

A: This isn't going to be possible purely in cross browser compliant CSS as there is nothing to hook into. Your best bet is going to be either Javascript or PHP search and replace, search for each term and replace with a term or similar so you have a hook for the CSS.
PHP would be the more fool proof method but Javascript may be a simpler implementation.

A: If jQuery is allowed (which could really simplify the job in your case), you could try something like this:
$('table tr td:nth-child(4)').each(function() {
    if($.trim($(this).text()) === 'Heren C') {
        $(this).css('font-weight', 'bold');
    }
});

I never used Wordpress, but I guess jQuery must be already loaded...


text:
Q: Wijmo Flexsheet Formula does not re-evaluate after referenced cell updated I am using wijmo 5 flexsheet with angularjs.
Problem is like this.
Cell B3 has a formula "=SUM(B1+B2)" . When I update the value of B1 or B2 cell B3 does not recalculated.
If I edit cell B3 like "=SUm(B1+B2)" value is updated. After I reedit B1 or B2 again B3 is not updated. It's like formula string is cached.
Any idea how to resolve the issue?

A: What's your Calculation option: If it is Automatically, it should update with the new value. Your option may be Manual?


text:
Q: How to run a Rails app in Docker on Heroku I'm moving a legacy rails app to run in docker. It works locally and on Virtualbox however pushing it to Heroku it fails.
If I bash into the container I can run rails c just fine. However it won't start up. Does anyone have any ideas?
2019-04-15T15:45:36.575923+00:00 heroku[web.1]: Starting process with command `/bin/bash -c \[\"rails\",\ \"server\",\ \"-b\",\ \"0.0.0.0\",\ \"-p\",\ \44429\]`
2019-04-15T15:45:38.700762+00:00 heroku[web.1]: State changed from starting to crashed
2019-04-15T15:45:38.616281+00:00 app[web.1]: /bin/bash: [rails,: command not found
2019-04-15T15:45:38.681262+00:00 heroku[web.1]: Process exited with status 127

Dockerfile
Here is my Dockerfile, I was originally thinking it was getting the error because it was using /bin/sh instead of /bin/bash. I added the line to set the SHELL to bash but it is still getting the error.
FROM ruby:2.3.8

ARG RAILS_SECRET_KEY
ARG RAILS_ENV=staging
ARG GITHUB_REPO_API_TOKEN
ARG POSTGRES_USER
ARG POSTGRES_PASSWORD
ARG POSTGRES_DB
ARG DATABASE_HOST
ARG FOG_PROVIDER
ARG FOG_REGION
ARG ASSET_FOG_DIRECTORY
ARG AWS_ACCESS_KEY_ID
ARG AWS_SECRET_ACCESS_KEY
ARG DONT_INIT
ARG PORT

# change bin/sh to /bin/bash
SHELL ["/bin/bash", "-c"]

# Most of these deps are for running JS tests. You can add whatever extra deps your project has (ffmpeg, imagemagick, etc)
RUN apt-get update

RUN apt-get update -yqq && apt-get install -yqq --no-install-recommends \
  nodejs \
  qt5-default \
  libqt5webkit5-dev \
  xvfb \
  postgresql \
  postgresql-contrib \
  imagemagick \
  openjdk-8-jdk

# cache the gemfile seperate
COPY Gemfile* /usr/src/app/

# required at CLI
ENV BUNDLE_GITHUB__COM=${GITHUB_REPO_API_TOKEN}:x-oauth-basic

# You'll need something here. For development, you don't need anything super secret.
ENV SECRET_KEY_BASE=${RAILS_SECRET_KEY}

# this tells container to cd into app directory
WORKDIR /usr/src/app

# so we don't have to reinstall all the gems when we add just one when we build a new container
ENV BUNDLE_PATH /gems

RUN bundle install

# copy app dir into /usr/src/app in container
COPY . /usr/src/app/

RUN DB_ADAPTER=nulldb bundle exec rake assets:precompile

# for the irritating times the server doesn't clean up when container shutsdown
ENTRYPOINT ["./docker-entrypoint.sh"]

CMD ["bundle", "exec", "rails", "server", "-b", "0.0.0.0", "-p", $PORT]

Update
Docker-entrypoint
#!/bin/bash
set -e

if [ -f tmp/pids/server.pid ]; then
  rm tmp/pids/server.pid
fi

exec "$@"

A: You may need to run your CMD command in shell form like
CMD bundle exec rails server -b 0.0.0.0 -p $PORT

Because it's going to be run as /bin/bash -c {CMD}, but /bin/bash -c ["bundle", "exec", "rails", "server", "-b", "0.0.0.0", "-p", $PORT] is not a valid command.
Also you may want (not required in this specific case) to set BUNDLE_BIN env variable along with BUNDLE_PATH
ENV BUNDLE_PATH=/gems \
    BUNDLE_BIN=/gems/bin \
    GEM_HOME=/gems
ENV PATH="${BUNDLE_BIN}:${PATH}"

It will allow command without bundle exec to work correctly too
CMD rails server -b 0.0.0.0 -p $PORT


text:
Q: How to iterate in google ocr textannotation object with php? I'm trying to get pages, paragraphs, blocks, etc
similar to the code below but in PHP.
https://cloud.google.com/vision/docs/fulltext-annotations
"""Returns document bounds given an image."""
client = vision.ImageAnnotatorClient()

bounds = []

with io.open(image_file, 'rb') as image_file:
    content = image_file.read()

image = types.Image(content=content)

response = client.document_text_detection(image=image)
document = response.full_text_annotation

# Collect specified feature bounds by enumerating all document features
for page in document.pages:
    for block in page.blocks:
        for paragraph in block.paragraphs:
            for word in paragraph.words:
                for symbol in word.symbols:
                    if (feature == FeatureType.SYMBOL):
                        bounds.append(symbol.bounding_box)

                if (feature == FeatureType.WORD):
                    bounds.append(word.bounding_box)

            if (feature == FeatureType.PARA):
                bounds.append(paragraph.bounding_box)

        if (feature == FeatureType.BLOCK):
            bounds.append(block.bounding_box)

# The list `bounds` contains the coordinates of the bounding boxes.

I was able to create this
require AUTOLOAD;
use Google\Cloud\Vision\VisionClient;
use Google\Cloud\Vision\V1\ImageAnnotatorClient;
use Google\Cloud\Vision\V1\TextAnnotation;

$path = 'img scr';

$imageAnnotator = new ImageAnnotatorClient();

$image = file_get_contents($path);
$response = $imageAnnotator->documentTextDetection($image);
$texts = $response->getFullTextAnnotation();

But I'm facing a hard time trying to iterate with the TextAnnotation object.
Either I got the message Cannot use object of type Google\Cloud\Vision\V1\TextAnnotation as array .Even if I try to force the object as array.
Here is the documentation from google for the object

A: To get the result from $response->getFullTextAnnotation(); try the following:
$response->getFullTextAnnotation()->getText();


text:
Q: Android - How to Create Sqlite database with Tables I need to create a database with 3 tables and I am doing this like below:
public class DatabaseUtils extends SQLiteOpenHelper {
      private final Context myContext;
      private SQLiteDatabase DataBase;

      // Database creation sql statement
      private static final String CREATE_TABLE_CS = "create table "+ TABLE_CS + "(" + COLUMN_CS + " TEXT NOT NULL, " + COLUMN_CE_CID + " INTEGER NOT NULL, "+ COLUMN_CE_PID +" INTEGER NOT NULL);";
      private static final String CREATE_TABLE_SS = "create table "+ TABLE_SS + "(" + COLUMN_SS + " TEXT NOT NULL, " + COLUMN_SUB_CID + " INTEGER NOT NULL, "+ COLUMN_SUB_PID +" INTEGER NOT NULL);";
      private static final String CREATE_TABLE_AS = "create table "+ TABLE_AS + "(" + COLUMN_AS + " TEXT NOT NULL, " + COLUMN_CID + " INTEGER NOT NULL, "+ COLUMN_AID +" INTEGER NOT NULL);";

      public DatabaseUtils(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        DATABASE_PATH =  Environment.getDataDirectory().getAbsolutePath() + "/" +"data/"+ context.getResources().getString(R.string.app_package);
        this.myContext = context;
      }

      @Override
      public void onCreate(SQLiteDatabase database) {
        database.execSQL(CREATE_TABLE_CS);
        database.execSQL(CREATE_TABLE_SS);
        database.execSQL(CREATE_TABLE_AS);
      }
      @Override
      public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.w(DatabaseUtils.class.getName(),"Upgrading database from version " + oldVersion + " to "+ newVersion + ", which will destroy all old data");
        //db.execSQL("DROP TABLE IF EXISTS " + TABLE_COMMENTS);
        onCreate(db);
      }
}

and in my Activity I am calling DatabaseUtils class in onCreate as below:
DatabaseUtils db = new DatabaseUtils(this);

but Database is not creating with the 3 tables. What am I doing wrong? BTW, I have all the string values correctly. Please help me how to create database.

A: I found the solution. DatabaseUtils' onCreate() is never called if i implement like below:
 DatabaseUtils db = new DatabaseUtils(this);

in myActivity's onCreate() method. I need to call getWritableDatabase() in myActivity as below:
DatabaseUtils db = new DatabaseUtils(this);
db.getWritableDatabase();

Then DatabaseUtils' onCreate() will be called and tables are created.

A: private void db_ini_create_table(android.database.sqlite.SQLiteDatabase db){
    String str_sql = "create table [possible_know_persions]         ("+
                                                                        "[id]                       INTEGER         PRIMARY KEY AUTOINCREMENT               NOT NULL,"+
                                                                        "[adate]                    DATETIME        DEFAULT (datetime('now','localtime'))   NOT NULL,"+
                                                                        "[current_userid]           INTEGER         DEFAULT 0 NOT NULL                              ,"+
                                                                        "[stranger_user_id]         INTEGER         DEFAULT 0 NOT NULL                              ,"+
                                                                        "[common_friend_count]      INTEGER         DEFAULT 0 NOT NULL                              ,"+
                                                                        "[common_game_count]        INTEGER         DEFAULT 0 NOT NULL                              ,"+
                                                                        "[user_account_type]        INTEGER         DEFAULT 0 NOT NULL                              ,"+
                                                                        "[verify_type]              INTEGER         NULL                                             "+
                                                                    ");";db.execSQL(str_sql);
    str_sql = "CREATE INDEX [possible_stranger_user_id]     on [possible_know_persions] ("+"[stranger_user_id] asc "+");";db.execSQL(str_sql);
}

this is a example for your reference


text:
Q: Activate external href onclick from link Let's say you have a link on your site and when you click that link it brings you to a different site. A site that you do not own and I would like it to have a "onclick" already activated maybe from a script that redirects to that link. Is this possible?

A: Simple answer NO. If possible it would be called 'mousejacking' :)

A: Setting window.location.href to a target link URL in javascript will, for most browsers, redirect the browser to the specified URL.
If you're specifically trying to make a link on your site redirect the user to a Google Search, read here.
There is almost no good reason to wrap an external site that you do not own in a frame. That kind of stuff is usually considered shady/malicious.


text:
Q: General Question(s) on Bloch's Theorem (Apologies for the long set-up, I wanted to make sure the question was properly motivated. Skip to the bottom for the actual question.)
Bloch's theorem is a foundational theorem in solid-state physics. It states, given a single-particle Hamiltonian $H = T + V$ with a periodic potential,
$$
V(\vec{r}+\vec{R}) = V(\vec{r}),
$$
the eigenstates of $H$ can always be chosen to satisfy
$$
\psi_{n\vec{k}}(\vec{r} + \vec{R}) = e^{i \vec{k} \cdot \vec{R}} \psi_{n\vec{k}}(\vec{r}) .
$$
Here, $\vec{R}$ refers to a vector in the Bravais lattice, which defines the periodicity of $V$. The theorem is easy to prove: it essentially follows from choosing eigenstates which are simultaneous eigenstates of the discrete translation operators. Alternatively, it follows by simply rewriting the Hamiltonian in Fourier space, where it is immediately seen that $V$ connects only states differing in momentum by a reciprocal lattice vector $\vec{K}$; therefore $H$ can be block diagonalized into sectors labeled by momenta $\vec{k}$ in the first Brillouin zone, each $\vec{k}$th sector containing all momentum eigenstates differing from $\vec{k}$ by a reciprocal lattice vector.
There are a number of statements which commonly follow the proof of Bloch's theorem (for example, see the discussion in Ashcroft and Mermin). First, it is claimed that the additional index $n$ used to resolve any degeneracies in the crystal momentum $\vec{k}$ is necessarily discrete. This is argued by considering the differential equation obeyed by the cell-periodic Bloch function $u_{n\vec{k}}(\vec{r}) = e^{-i\vec{k} \cdot \vec{r}} \psi_{n\vec{k}}(\vec{r})$:
$$
\left[ \frac{1}{2m} \left( -i \hbar \vec{\nabla} + \hbar \vec{k} \right)^2 + V(\vec{r}) \right] u_{n\vec{k}}(\vec{r}) = \varepsilon_{n\vec{k}} u_{n\vec{k}}(\vec{r})
$$
together with the boundary condition $u_{n\vec{k}}(\vec{r} + \vec{R}) = u_{n\vec{k}}(\vec{r})$. It is then claimed that since $u_{n\vec{k}}(\vec{r})$ satisfies this eigenvalue problem in a single unit cell, the spectrum of solutions for fixed $\vec{k}$ must be discrete, and the additional index $n$ used to label this spectrum can be chosen as a discrete index. The second statement commonly made is that for given $n$, the Bloch wavefunctions can always be chosen to be periodic in the Brillouin zone: $u_{n,\vec{k} + \vec{K}} = u_{n\vec{k}}$.
Both of these points are central to the theory of band structure. Together with the assumption that the eigenvalues $\varepsilon_{n\vec{k}}$ vary continuously with $\vec{k}$, the first point states that the spectrum of $H$ is organized into bands. The second point states that these bands are always periodic in the Brillouin zone.
Here are the questions, which I hope are sufficiently closely related to comprise one overall question:

*

*How can I see more precisely that the spectrum in $n$ is discrete for a fixed crystal momentum $\vec{k}$? In other words, given the above differential equation for the cell-periodic Bloch function, is there a way to show that the eigenvalue spectrum of the differential equation is discrete?

*While it's perfectly clear that I can take the crystal momenta to lie within the Brillouin zone, how can I see that each band must strictly be periodic in the Brillouin zone? For example, consider a one-dimensional problem for ease of visualizing the bands. Why can't the $n$th band start at some fixed energy $\varepsilon_{n, -\pi / a}$, increase monotonically with $k$, and end at $\varepsilon_{n,\pi / a} = \varepsilon_{n+1, -\pi / a}$, so that each band continuously wraps into the next one?

A:  Question 1
The functions
$
\newcommand{\bfr}{\mathbf{r}}
\newcommand{\bfR}{\mathbf{R}}
\newcommand{\bfk}{\mathbf{k}}
\newcommand{\bfK}{\mathbf{K}}
u_{n,\bfk}
$ are solutions to the third equation in the question. Everything in that equation, including $V$ and $u$, is assumed to be invariant under $\bfr\to \bfr+\bfR$ for lattice vectors $\bfR$. Therefore, for each value of $\bfk$, that equation defines an eigenvalue problem on a compact manifold (specifically a torus) consisting of points $\bfr$ modulo the vectors $\bfR$. Here's the key: for any given value of $\bfk$, the differential operator in that equation is self-adjoint and elliptic, and

*

*The eigenvalues$^\dagger$ of a self-adjoint elliptic differential operator on a compact manifold are discrete.

$^\dagger$  In physics, the word "eigenvalue" is often used loosely, referring also to elements of the continuous part of an operator's spectrum. That's how I'm using the word here, so the statement isn't just a tautology.
This is one of those general theorems in the phycisist's standard toolkit, with many applications. For a more precise statement and an outline of the proof, see theorem 1.46 on page 47 in

*

*Kottke (2016), "Linear Analysis on Manifolds: Notes for Math 7376, Spring 2016" (https://ckottke.ncf.edu/neu/7376_sp16/lacm.pdf).

The proof is not short, so I won't try to reproduce it here.
 Question 2
The condition $u_{n,\bfk+\bfK}=u_{n,\bfk}$ shown in the question might be a typo (?). The correct statement is that we can take
$$
\psi_{n,\bfk+\bfK}(\bfr)=\psi_{n,\bfk}(\bfr).
\tag{1}
$$
This is equation 8.50 in Ashcroft and Mermin's Solid State Physics, 1976. To see why equation (1) is valid, let
$$
\psi_{n,\bfk}(\bfr)=\exp(i\bfk\cdot\bfr)u_{n,\bfk}(\bfr)
\tag{2}
$$
be any solution of the original Schrödinger equation (not shown in the question), where $u_{n,\bfk}(\bfr)$ is invariant under $\bfr\to\bfr+\bfR$. We can obviously rewrite (2) as
$$
\psi_{n,\bfk}(\bfr)=\exp\big(i(\bfk+\bfK)\cdot\bfr\big)
\Big(\exp(-i\bfK\cdot\bfr)u_{n,\bfk}(\bfr)\Big).
\tag{3}
$$
The combination $\exp(-i\bfK\cdot\bfr)u_{n,\bfk}(\bfr)$ is still invariant under $\bfr\to \bfr+\bfR$, so given any complete basis of solutions (2) for each $\bfk$ in the first Brillouin zone, we can simply define the Bloch wavefunctions for the other Brillouin zones by
$$
\psi_{n,\bfk+\bfK}(\bfr)\equiv
 \exp\big(i(\bfk+\bfK)\cdot\bfr\big)
 u_{n,\bfk+\bfK}(\bfr)
\tag{4}
$$
for all $\bfk$ in the first Brillouin zone and for all reciporocal lattice vectors $\bfK$, with
$$
u_{n,\bfk+\bfK}(\bfr)
\equiv\exp(-i\bfK\cdot\bfr)u_{n,\bfk}(\bfr).
\tag{5}
$$
Equations (3)-(5) imply equation (1). To be consistent with how we defined $\psi_{n,\bfk+\bfK}$, we can also define
$$
\epsilon_{n,\bfk+\bfK}\equiv\epsilon_{n,\bfk}
\tag{6}
$$
for all $\bfk$ in the first Brillouin zone and for all reciporocal lattice vectors $\bfK$. We can take (1) and (6) to depend smoothly on $\bfk$ within the first Brillouin zone, but this does not imply that $\epsilon_{n,\bfk}$ is a smooth function of $\bfk$ when $\bfk$ crosses a zone boundary! Here's the key point:

*

*The choices (1) and (6) enforce periodicity in $\bfk$ instead of enforcing smoothness in $\bfk$ at the zone boundaries.

We can think of equations (1) and (6) as defining how the wavefunctions and bands are indexed in the other Brillouin zones, given a choice of indexing in the first Brillouin zone. With this definition, the index $n$ may jump when tracing a band smoothly (differentiably) across a zone boundary, as anticipated in the question. Alternatively, we could have used a different definition in which they are taken to vary smoothly with $\bfk$ across all zones, for each $n$, but that way of indexing things might not agree with the one defined by (1) and (6). Both ways of indexing things are legitimate, but they're not necessarily equivalent.
To see that they're not always equivalent, consider the case $V=0$. This is periodic with respect to any lattice, so choose an arbitrary lattice and consider equations (1) and (6). If we had indexed the bands to be smooth for all $\bfk$, then $\epsilon_{n,\bfk}$ would be a quadratic function of $\bfk$ that increases without bound as $|\bfk|$ increases. That's not consistent with (6), so this is a case where enforcing periodicity is not the same as enforcing smoothness.


text:
Q: Hibernate Criteria ordering and pagination not working I see a weird behavior when using criteria.addOrder(Order.asc("sortAttribute")) for sorting on non-unique attribute. The results returned are duplicate.
The same seems to work fine when the sortAttribute is a unique key in database.
resultObj = criteria.addOrder(order)
                        .setFirstResult(page.getPageNumber() * page.getPageSize())
                        .setMaxResults(page.getPageSize())
                        .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)
                        .list();

Also, I do have a join here between two entities. (Although I don't really see why this could be any reason for the unstable behavior)

A: Well, I think I found a solution to this issue. I did the following to obtain expected results:

*

*First sort on non unique key.

*Then sort on unique key.

This way the result was always in the proper order and ordering and pagination was ensured.
Hope this may help someone who comes across such an issue.


text:
Q: Polygonize Specific DN I am using QGIS 2.18.5.
I have a very large raster with DN values of interest (3) and others which I have no interest in at all (0,1,2). To prevent polygonising the entire raster which would take a number of hours, is it possible to selectively process values which match DN = '3'?

A: You can use the Raster Calculator to create a new raster containing only cells which have the value 3, leaving the rest as nodata by using the following expression:
"raster@1" / ("raster@1" = 3)

You can then polygonize the output which should dramatically decrease processing time.


text:
Q: How to optimize a nested for loop that uses `re.finditer`? I currently have a task of annotating substrings with labels in Python and am using Python's RegEx library to do that. I'll give an example of what I mean since it's hard to explain coherently:
label_dictionary = {'coca cola': 'company', 'united states': 'country'}
text = "Coca Cola is a company that has its headquarters in the United States."

for text in texts: # There are multiple strings.
    labels = ['O'] * len(text)

    for entity, label in label_dictionary.items():
        spans = [(match.start(), match.end()) for match in re.finditer(entity, text)]

        for span in spans:
            start, end = span

            labels[start] = label
            labels = labels[:start + 1] + ([label] * (end - start - 1)) + labels[end:]

Those of you who are familiar with natural language processing may have figured it out, but I'm trying to create a dataset for named entity recognition.
I want to get the start and end spans of each entity from the label_dictionary then mark those positions in the text with a label.
I'm wondering if I could use less for loops since that's where my code is taking so long, but am not sure if there's even a viable way to do this.
Any tips appreciated. Thanks.

A: If you have lots of entities in your label_dictionary, looping over all of them would get quite expensive. For example, if you have 10000 entities, you would search every text 10000 times for a substring.
Your can optimize this, by searching for all entities simultaneously using regular expressions.
For example, the regular expression Coca\ Cola|United\ States searches for both "Coca Cola" and "United States".
The following example combines all entities into one regular expression and prints the information you seem to need:
import re

label_dictionary = {'Coca Cola': 'company', 'United States': 'country'}
text = "Coca Cola is a company that has its headquarters in the United States."

regex = re.compile('|'.join(re.escape(entity) for entity in label_dictionary))

for m in re.finditer(regex, text):
    print('Span:', m.span())
    entity = m.group()
    print('Entity:', entity)
    print('Label:', label_dictionary[entity])

PS: It's a good idea to use re.escape because your entities might contain characters with a special meaning in regular expression (think e.g. of A* Company).


text:
Q: Which Elasticsearch Indices Need Optimisation? Let's say I'm facing an Elasticsearch database with a given set of indices and a hell lot of documents spread across them. When I call http://localhost:9200/_optimize it takes very long to run and the result proves that it was a necessary thing to do, the obvious hint being the fact that the database size was reduced by ~20%.
Now I want to optimise regularly per index rather than the entire database. For us this is interesting as the usual operations we do don't cover all indices at once. Just over time pretty much all indices are affected. How do I find out, which indices need optimisation?
What I found useful is looking for indices with deleted documents using http://localhost:9200/_stats/docs.
Are there any other checks I can do?
Maybe to emphasize this, this question isn't about when, why or how to optimise or how to avoid it.

A: Indices in ES are, basically, files on disk. Every time an index operation is performed, a document is appended to such a file or to a new segment file (depending on the refresh period). The optimization process merges smaller Lucene segments into larger segments.
When a delete operation or an update operation (an update = delete the old version of the document and reindex the new version of the document) is performed on an index the document isn't actually deleted, but marked for deletion. Whenever a merging operations kicks in then it's the time to actually delete the "marked as deleted" documents.
This is why looking at the number of deleted documents and then merging improves the disk allocation space. Usually, the optimize operation is not needed, it is performed automatically by ES. If you really want to do it, beware that it consumes IO and CPU cycles. One scenario when this can be useful is for those indices that are unlikely to change in the future (logs from the past for example). Doing this manually in other scenarios is not recommended.
"Which indices need optimisation?" - those that you know are unlikely to ever change (no writes to them anymore). Ideally, one index is good to have only one segment (searching an index with only one segment is performing better than searching an index composed of multiple segments).
Also, I suggest this reading about optimization.


text:
Q: Get distinct values from each table and each column with SQL Server I would like to loop through each table for a given database to get unique values for each char field.
My query might something like:
for each table:
    for each row in table:
       select distinct char_field
       from table
    loop
loop

How do I do this?

A: Try it like this
DECLARE cur CURSOR FOR
    SELECT 'SELECT DISTINCT ' + QUOTENAME(c.COLUMN_NAME) + 'AS ' + QUOTENAME(TABLE_CATALOG + '.' + TABLE_SCHEMA + '.' + TABLE_NAME) + ' FROM ' + QUOTENAME(TABLE_CATALOG) + '.' + QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)
    FROM INFORMATION_SCHEMA.COLUMNS AS c
    WHERE c.DATA_TYPE LIKE '%char%'

DECLARE @cmd VARCHAR(MAX);
OPEN cur;

FETCH NEXT FROM cur INTO @cmd;
WHILE @@FETCH_STATUS = 0
BEGIN
    PRINT @cmd
    EXEC(@cmd);
    FETCH NEXT FROM cur INTO @cmd;
END

CLOSE cur;
DEALLOCATE cur;

This process opens a cursor with all columns of all tables, where the data-type contains char. It will create a statement to select all distinct values and executes this one after the other.


text:
Q: Can you send data via an intent to an activity running in the background? I am making a simple online book store app. The two activities I want to share information between are activity A which is a recyclerView filled with books and activity B which displays more information about a book when said book is clicked in activity A. I want to add some functionality where when you click on the author name of a book in activity B, the application will send the authors name back to activity A and filter the books in such a way that only books from the chosen author are showed.
Filtering the data is an easy task to solve. However I do not know how to get the author name back to activity A. Is using an intent the right call here? Will the intent not start an entirely new A activity? Is it possible to send information to an activity running in the background and somehow receive it in onResume()? Is there something else I can use?
Similar questions did not seem helpful so I apologize for repeating this.
I don't see any reason to provide any code. Will do so if anyone asks.
EDIT: Solution of a follow up problem I received after using startactivityforresult()
I did not mention it above, but I am using a recycler view adapter class to get from activity A to activity B. This made it so that I was not able to change startActivity() to startactivityforresult().
My original piece of code was:
 mContext.startActivity(intent);

to solve the problem it was changed to the following:
((Activity) mContext).startActivityForResult(intent, 1);

A: Activity A to B,
Intent i = new Intent(A.this, B.class);
i.putExtra("book_id", 123);
startActivityForResult(i, 1);

// in Activity A

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (requestCode == 1) {
        if(resultCode == Activity.RESULT_OK){
            String result=data.getStringExtra("auther_name");
        }
        if (resultCode == Activity.RESULT_CANCELED) {
            //for no result
        }
    }
}//onActivityResult

Activity B to A,
Intent returnIntent = new Intent();
returnIntent.putExtra("auther_name", "name");
setResult(Activity.RESULT_OK,returnIntent);
finish();

Hope this works.


text:
Q: How can I make a table striped using elm-bootstrap 4.1.0? I have been trying several things and cannot work out how to style this Elm table with Bootstrap so it's striped.  I am trying to use elm-bootstrap and have installed rundis/elm-bootstrap 4.1.0
Bootstrap.Table is currently unused:
module Players.List exposing (..)

import Html exposing (..)
import Html.Attributes exposing (class)
import Msgs exposing (Msg)
import Models exposing (Player)
import RemoteData exposing (WebData)
import Bootstrap.Table as Table

view : WebData (List Player) -> Html Msg
view response =
div []
    [ nav
    , maybeList response
    ]

nav : Html Msg
nav =
div [ class "clearfix mb2 white bg-black" ]
    [ div [ class "left p2" ] [ text "Players" ] ]

maybeList : WebData (List Player) -> Html Msg
 maybeList response =
case response of
    RemoteData.NotAsked ->
        text ""

    RemoteData.Loading ->
        text "Loading..."

    RemoteData.Success players ->
        list players

    RemoteData.Failure error ->
        text (toString error)

list : List Player -> Html Msg
list players =
div [ class "col-md-4" ]
    [ table [ class "table table-striped" ]
        [ thead []
            [ tr []
                [ th [] [ text "Id" ]
                , th [] [ text "Initials" ]
                , th [] [ text "Time" ]
                , th [] [ text "Score" ]
                ]
            ]
        , tbody [] (List.map playerRow players)
        ]
    ]

playerRow : Player -> Html Msg
playerRow player =
tr []
    [ td [] [ text player.id ]
    , td [] [ text player.initials ]
    , td [] [ text (toString player.time) ]
    , td [] [ text (toString player.score) ]
    ]

As this should be ultra simple I'm clearly missing something here.  How can I make this table striped?

A: Your example uses HTML functions from Elm's HTML library but you're probably going to have a better time using the appropriate Bootstrap types and functions. For example, using the table options defined in the documentation, you could rewrite the view functions like this:
list : List Player -> Html msg
list players =
    Table.table
        { options = [ Table.striped ]
        , thead = Table.thead []
            [ Table.tr []
                [ Table.th [] [ text "Id" ]
                , Table.th [] [ text "Initials" ]
                , Table.th [] [ text "Time" ]
                , Table.th [] [ text "Score" ]
                ]
            ]
        , tbody = Table.tbody [] (List.map playerRow players)
        }

playerRow : Player -> Table.Row msg
playerRow player =
     Table.tr []
        [ Table.td [] [ text player.id ]
        , Table.td [] [ text player.initials ]
        , Table.td [] [ text (Debug.toString player.time) ]
        , Table.td [] [ text (Debug.toString player.score) ]
        ]

That will give you the right HTML but you may still need to import the Bootstrap styles. The documentation gives an example of including the stylesheet, which you could do in some wrapping function, for example:
import Bootstrap.Grid as Grid
import Bootstrap.Table as Table
import Bootstrap.CDN as CDN

view : Model -> Html Msg
view model =
    Grid.container []
        [ CDN.stylesheet -- creates an inline style node with the Bootstrap CSS
        , Grid.row []
            [ Grid.col []
                [ list model.players ]
            ]
        ]

Here is a slimmed down Ellie example to play with.


text:
Q: How to delete elements from multidimensional array where sum of values equals 0? I have a stack of 32 x 32 grayscale images in a multidimensional array masks as follows:
(2560, 1, 32, 32)

Some of these images contain a non-zero value if I sum their values.
I'd like to remove from the multidimensional array those elements whose sum of values equals zero.
This is how I'm approaching it:
for idx in range(masks.shape[0]):
    if np.sum(masks[idx]) == 0:
        masks = np.delete(masks, idx)

After the first iteration where a zero-sum element is found, masks changes from shape
(2560, 1, 32, 32)
to
(2621439,)
Why is this happening and how do I resolve it? What I desire is to only reduce the first dimension, e.g.
(2120, 1, 32, 32)

A: You get a one dimensional array because you didn't provide axis parameter for np.delete, according to docs:

If axis is None, obj is applied to the flattened array.

Besides it's not a good idea to loop through an array while deleting elements, which makes it hard to keep track of the index since the object's size is changing:
For your case:
masks = masks[masks.sum(axis=(1,2,3)) != 0]

should delete arrays whose sum of all values for axis 1,2,3 is zero.


text:
Q: Accidentally deleted gnome keyring from startup applications. How do I get it back? I was trying to delete Microsoft teams from the list of startup applications but I accidentally deleted something else from the list instead.
I think that the program I deleted from the list was SSH Key Agent - Gnome Keyring. I think this because of this website:
https://www.maketecheasier.com/manage-startup-applications-ubuntu/
In which there's a picture of the list of what seem to be the default startup programs.
I only just installed Ubuntu. My only remaining startup programs in the list are: "im-launch" and "NVIDIA X Server Settings". Did I in fact delete the Gnome Keyring? How do I get it back? When I press 'add' on the list of startup programs, it expects me to provide it with the location of the program that I want to run, but I don't know where the Gnome Keyring program is in the computer. I tried searching for it in usr/bin, but there are a few different files it could be.
Thanks for any help.

A: "SSH Key Agent" is autostarted by default in an Ubuntu desktop. Therefore, a .desktop launcher is installed in /etc/xdg/autostart/gnome-keyring-ssh.desktop. Such entries are disabled on a per user basis through settings in a copy in your local autostart folder. To enable the item again, delete your local user copy ~/.config/autostart/gnome-keyring-ssh.desktop. To see it appear, you need to quit and restart "Startup Applications" or "Gnome Tweaks" if you used the latter.


text:
Q: Can we compare two secret numbers? If you and I each have a secret number, is there a way we can find out whose is larger without either of us revealing our secret number?
Clearly a trusted third party could do the job, but I was wondering if there's some mathematical or cryptographic trick that could be used.
For practical examples, consider two people who want to compare salary, or age, or number of speeding tickets, etc.

A: Aye, this is Yao's Millionaires Problem!

A: Not mathematically rigorous, but perhaps more practical:
Let's assume we can narrow down the numbers to one of ten values.  Perhaps you're willing to round your salaries to the nearest 5K and you think they're between 50K and 95K, or you were both willing to announce that you had less than 10 speeding tickets.
Each of you should take half a deck of cards.  Pick one card to be your marker (perhaps an Ace - something easy to remember) and show the other person.  Now, as you together count up through the possible values, you take turns placing a card face down onto a common pile.  When you get to your number, you put your marker card down.  When you're done counting, you have 20 cards in the pile and whichever marker card is on top would indicate the person who has the higher number, but you can't look yet!
For example, if the first person has 2 speeding tickets (marker card in green), and the second has 4 (marker card in red), the pile would grow like this:

Now you each take turns holding the pile under the table while you put some of your remaining cards on the top of the pile and some underneath the pile.  After you've each done this, you don't know how deep in the deck your original pile of 20 cards is.  But it's somewhere, and the top marker card still indicates whose number is higher.
For the above example, the deck would now look something like this:

Then you can flip the cards off the top of the pile until you hit one of your marker cards.  If it's the marker of the person who was placing his card second on each number announcement, you should check the next card also, to see if you have a tie.  Immediately shuffle the deck.


text:
Q: Can resources in one Resource Group be used by another Resource Group? I am currently working on trying to manage and potentially split apart a Resource Group that currently contains basically every resource we have made in Azure. I am thinking the best split would be by Environment (Dev, Test, etc) combined with which App it is (OneApp, AnotherApp, etc) so like OneApp_Dev, OneApp_Test, etc.
There are a few resources (like a single SQL server instance) that are accessible by resources that would be moved apart from each other into many of the other new Resource Groups like an App vm that would go into each new Resource Group.
It is possible to have a Resource Group for shared resources and let each other Resource Group access that one? Or is that antithetical to the point of Resource Groups?

A: Yes, however pay attention in case you're using Managed Identity to make sure the identity will have access on the other resource too.
Also, pay attention to group resources in the same region to avoid network out traffic.


text:
Q: Is there a way to verify a common seed to a cumulative sequence of hashes with unknown repetitions between each value presented? I am writing a variant of the Cuckoo Cycle that uses an adjacency list for presenting solutions from two pairs of 8 bit coordinates, and I am not having any problems finding what I think should be an optimal solver for it, that uses two pairs of head/tail binary search trees to keep track of possible solution nodes, reject (branches) nodes and a binary tree that keeps a list of the candidate cycles as they are being assembled (as I understand it, binary search trees shorten the amount of processing for finding duplicates), but I need to refine the verifier function for solutions.
I see in Cuckoo that there is some process by which it modifies the edges with XOR functions and masks to identify a valid cycle, but I have two issues.
One is that each hash is generated from the previous hash, starting with the nonce, and proving that all offered node/edge pairs are valid derivatives from the nonce seems to me to require the verifier to repeat the hash function each time checking for a match until it gets a hit, which could be up to several thousand, in the worst case. Is there some property that can be used to shortcut this identification process, since unlike protection against DoS, we are providing the salt of the hash?
Second is that even if the presented cycle is perfectly valid, it is possible that one or more of the node/edge pairs in the cycle has a duplicate coordinate. The hashes are 32 bits long, and each coordinate is 8 bits. The answer to this probably has some relation to the previous question also, as having the seed for a hash function is a known security risk because of collisions. So obviously, as well as verifying the nodes are part of a cycle in the lowest possible values in the finite field, I need a way to be sure that a pair does not overlap with another possible, and branching pair.
I will be studying the verifier closer in the Cuckoo Cycle implementation to see if I can figure out how the algorithm ensures it is not approving a cycle that actually has a branch (and thus is invalid), but I thought I'd pop the question on this site in case someone knows better the ways of recognising hashes from a common seed, and if there is any way to recognise a 50% collision between a given coordinate and another one.

Note: After thinking about it for a while, I realised that I could solve the 'fake cycle' with one or more nodes having a branch by simply splitting the heads and tails into separate hashes, subsequent (odd then even), such as Murmur3 16 bit hashes.
And further thinking about it, I realised that Cuckoo Cycle is actually a special type of hash collision search that seeks only collisions that occur only once in the low order of the finite field. I am devising a new scheme called Hummingbird, which instead will not target the smallest numbers (which is also the same thing done by hashcash) but instead will target the most proximate hashes in a chain to the seed nonce. This will mean that attempts to insert branched nodes in the graph of the solution will be discovered in the verification. Which will probably take about 2-5 seconds depending on how deep. These solutions could be eliminated by specifying a maximum hash chain length as part of the consensus.

A: I just wanted to add that I answered my own question by realising that I am looking for, essentially, a hash collision, in my algorithm, and the simplest solution, with the least bit-twiddling was to make each coordinate a distinct hash in a hash chain (hash of nonce, then hash of hash, etc)
I didn't understand fully that Cuckoo Cycle is essentially a search for partial hash collisions, and when that dawned on me, I realised that the simple solution is to just make it into a search for hash collisions.
I have, from this realisation, moved very quickly forward to figuring out how my variation of Cuckoo can be much more simply implemented, as well as how to structure the B-tree based progressive search algorithm, the difficulty adjustment, and the rest.
I wasn't aware there was a stackexchange specialist site for math, or cryptography, or I would have posted it there instead. I studied FEC a few months ago and that opened the floodgates to a whole bunch of other ideas that led me to getting so worked up about Cuckoo Cycle. I believe I have generalised the Cuckoo Cycle into a generic, parameterisable graph theoretic proof of work and I will get back to finishing my implementation.
Thanks to everyone who submitted an answer, I will upvote as I deem correct, though I have zero or nearly zero rep, for what it's worth.


text:
Q: IS there a possibility to loop through dataframes? dflist = [DP, SMP, SMD, MP, MD, MSM, SAP, SAD,SAMA, SAM, AP,AD, ASM, AM,ASA]

for i, df in enumerate(dflist):
    # open an existing document
    doc = docx.Document()

    # add a table to the end and create a reference variable
    # extra row is so we can add the header row
    t = doc.add_table(dflist[i].shape[0]+1, dflist[i].shape[1])

    # add the header rows.
    for j in range(dflist[i].shape[-1]):
        t.cell(0,j).text = dflist[i].columns[j]

    # add the rest of the data frame
    for i in range(dflist[i].shape[0]):
        for j in range(dflist[i].shape[-1]):
            t.cell(i+1,j).text = str(dflist[i].values[i,j])

    # save the doc
    doc.save(fr'./test1[i].docx')

I am trying to iterate through the list of dataframes so that I create a word document for each of them.
However, I am getting the following error;
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-18-d61049a379a0> in <module>
     14     for i in range(dflist[i].shape[0]):
     15         for j in range(dflist[i].shape[-1]):
---> 16             t.cell(i+1,j).text = str(dflist[i].values[i,j])
     17
     18     # save the doc

IndexError: index 0 is out of bounds for axis 0 with size 0

What am I doing wrong?


text:
Q: Error messages on Android emulator bootup in Android Studio 2.2 I am using Android Studio 2.2 on a Windows 10 x64 platform. My virtual device is a Nexus 5 with API 22. When I boot up this virtual device in the emulator I get these messages on bootup. I also get the same errors with API's 23 and 24. Can someone help me with that these messages are and how to resolve these errors? Specifically "goldfish_audio_in" and ColorBuffer and glDrawElements() errors. I cannot debug any application because they keep crashing.
Hax is enabled
Hax ram_size 0x60000000
HAX is working and emulator runs in fast virt mode.
audio: Failed to create voice `goldfish_audio_in'
qemu-system-x86_64.exe: warning: opening audio input failed
emulator: Listening for console connections on port: 5554
emulator: Serial number of this emulator (for ADB): emulator-5554
ColorBuffer::bindFbo: FBO not complete: 0x8cdd
ColorBuffer::bindFbo: FBO not complete: 0x8cdd
draw: Could not glDrawElements() error=0x506
draw: Could not glDrawElements() error=0x506
draw: Could not glDrawElements() error=0x506
draw: Could not glDrawElements() error=0x506


text:
Q: Why does my MSYS2/MinGW64 setup link SDL2 without a -l directive, but not SDL2_ttf? I have MSYS2 and MinGW64 installed.  I also have Code::Blocks installed and have pointed it's toolchain configuration to the executables in MinGW64's bin. To keep things clean, I have only installed libraries using pacman from the MinGW64 shell.
$ pacman -Sl | grep SDL2
mingw32 mingw-w64-i686-SDL2 2.0.9-1
mingw32 mingw-w64-i686-SDL2_gfx 1.0.4-1
mingw32 mingw-w64-i686-SDL2_image 2.0.4-1
mingw32 mingw-w64-i686-SDL2_mixer 2.0.4-1
mingw32 mingw-w64-i686-SDL2_net 2.0.1-1
mingw32 mingw-w64-i686-SDL2_ttf 2.0.14-1
mingw64 mingw-w64-x86_64-SDL2 2.0.9-1 [installed]
mingw64 mingw-w64-x86_64-SDL2_gfx 1.0.4-1 [installed]
mingw64 mingw-w64-x86_64-SDL2_image 2.0.4-1 [installed]
mingw64 mingw-w64-x86_64-SDL2_mixer 2.0.4-1 [installed]
mingw64 mingw-w64-x86_64-SDL2_net 2.0.1-1 [installed]
mingw64 mingw-w64-x86_64-SDL2_ttf 2.0.14-1 [installed]

Using Code::Blocks, I can compile and link a sample that initializes SDL2, pops a window, and exits on an SDL_Quit event.  The sample project has NO additional compiler or linker configuration.  In fact, Code::Blocks global settings do not configure search directories, either.  I suppose GCC has INCLUDE and LIB already set in its default environment.
The problem occurs when I try to use SDL2_ttf.  I can include it, and Code::Blocks finds it well-enough to offer some code completion.  But builds fail on "Undefined reference to TTF_Init".
-------------- Build: Debug in TV Tennis (compiler: GNU GCC Compiler)---------------

g++.exe -LD:\msys64\mingw64\lib -o "bin\Debug\TV Tennis.exe" obj\Debug\main.o   -lmingw32 -lSDL2main -lSDL2.dll -luser32 -lgdi32 -lwinmm -ldxguid
obj\Debug\main.o: In function `SDL_main':
H:/Datacenter/Source/TVTennis/C++/TV Tennis/main.cpp:45: undefined reference to `TTF_Init'
H:/Datacenter/Source/TVTennis/C++/TV Tennis/main.cpp:59: undefined reference to `TTF_OpenFont'
H:/Datacenter/Source/TVTennis/C++/TV Tennis/main.cpp:109: undefined reference to `TTF_CloseFont'
H:/Datacenter/Source/TVTennis/C++/TV Tennis/main.cpp:110: undefined reference to `TTF_Quit'
collect2.exe: error: ld returned 1 exit status
Process terminated with status 1 (0 minute(s), 0 second(s))
5 error(s), 0 warning(s) (0 minute(s), 0 second(s))

If I add "-lSDL2_ttf" to the project's linker options, the problem goes away.
My question is, why do I get that automatic linking magic for SDL2, but not for SDL2_ttf?

A: I found out how SDL2 was "magically" linked in without any visible configuration or explicit directive.
When I created the Code::Blocks project, I specified it as an SDL2 project.  Code::Blocks then adds a bunch of libraries to the project by default via the project's *.cbp file (Code::Blocks Project).
<Compiler>
    <Add option="-Wall" />
    <Add directory="D:/msys64/mingw64/include" />
</Compiler>
<Linker>
    <Add library="mingw32" />
    <Add library="SDL2main" />
    <Add library="SDL2.dll" />
    <Add library="user32" />
    <Add library="gdi32" />
    <Add library="winmm" />
    <Add library="dxguid" />
    <Add directory="D:/msys64/mingw64/lib" />
</Linker>
<ExtraCommands>
    <Add after="XCOPY $(#sdl2)\bin\*.dll $(TARGET_OUTPUT_DIR) /D /Y" />
</ExtraCommands>

Honestly, this is why I hate starting with project templates; especially when I am new to a language, IDE, or library.  And in this case, I am new to all three.


text:
Q: Either Replace or Substitute in Excel I need to replace a character, "-", with ":" in all of our product names. It needs to work for the entire column A, not just a single cell, AND there are multiple "-"'s in some of the products, but I just need the first in each product. For example, we have product Spuhr-SP-3016 and product AI-0497. I need to replace only the first - in the Spuhr one and the - in the AI one. And again, this will need to be for thousands of products, not just a single cell but a range (A2:A3000, or all of column A if range doesn't work). Is there a formula using either Replace or Substitute?  All instructions I found demonstrate for one cell only instead of a range.

A: You can achieve this by using the FIND function in combination with LEFT and RIGHT
The FIND gets the first position of a "-" and you get the LEFT of that -1 so it ignores the "-".  Then get the length, LEN, minus the same position from the first FIND without the -1 to get the rest of the string. In between both functions just add the ".".
=LEFT(A1,FIND("-",A1)-1)&"."&RIGHT(A1,LEN(A1)-FIND("-",A1))