text:
Q: greuests alternative - python I am developing a program that downloads multiple pages, and I used grequests to minimize the download time and also because it supports requests session since the program requires a login. grequests is based on gevent which gave me a hard time when compiling the program (py2exe, bbfreeze). Is there any alternative that can use requests sessions ? Or are there any tips on compiling a program with gevent ?
I can't use pyinstaller: I have to use esky which allows updates.

A: Sure, there are plenty of alternatives. There's absolutely no reason you have to use gevent—or greenlets at all—to download multiple pages.
If you're trying to handle thousands of connections, that's one thing, but normally a parallel downloader only wants 4-16 simultaneous connections, and any modern OS can run 4-16 threads just fine. Here's an example using Python 3.2+. If you're using 2.x or 3.1, download the futures backport from PyPI—it's pure Python, so you should have no trouble building and packaging it.
import concurrent.futures
import requests

def get_url(url, other, args):
    # your existing requests-based code here

urls = [your, list, of, page, urls, here]

with concurrent.futures.ThreadPoolExecutor() as pool:
    pool.map(get_url, urls)

If you have some simple post-processing to do after each of the downloads on the main thread, the example in the docs shows how to do exactly that.
If you've heard that "threads are bad in Python because of the GIL", you've heard wrong. Threads that do CPU-bound work in Python are bad because of the GIL. Threads that do I/O-bound work, like downloading a web page, are perfectly fine. And that's exactly the same restriction as when using greenlets, like your existing grequests code, which works.

As I said, this isn't the only alternative. For example, curl (with any of its various Python bindings) is a pain to get the hang of in the first place compared to requests—but once you do, having it multiplex multiple downloads for you isn't much harder than doing one at a time. But threading is the easiest alternative, especially if you've already written code around greenlets.

* In 2.x and 3.1, it can be a problem to have a single thread doing significant CPU work while background threads are doing I/O. In 3.2+, it works the way it should.


text:
Q: How to initialize char * in c++ class? (sizeof() always gives 8) I'm facing some troubles with code for my school. The problem is that I have a char pointer named "contenido" like this:
class Archivo {
 public:
  Archivo(const char *filename, int banderas);
  Archivo(const char *filename, int banderas, mode_t modo);
  ~Archivo();
  size_t lee(size_t nbytes);
  size_t escribe(const void *buffer, size_t nbytes);
  char *get_contenido();
  void cerrar();

 protected:
  string nombreArchivo;
  int fd;

  //Problematic char pointer
  char *contenido;
};

The code is supposed to be a class implementation of the c functions read(), write() and open(), the specific method where i need to set a new size for my char pointer is size_t lee(size_t nbytes); that i implemented like this:
size_t Archivo::lee(size_t nbytes) {
  contenido = new char[nbytes];
  cout << "contenido: " << sizeof(contenido) << endl;
  nbytes = read(fd, contenido, sizeof(contenido));
  return nbytes;
}

In this method, I should receive a new size for "contenido" that in this case, it works as my buffer for the read() function but unfortunately, it doesn't matter which value I use it always returns "8" in the call of sizeof(contenido). I have tried using malloc() in the constructor, using malloc() and then realloc() and as you may see using new char[size_t] but in every single case I receive the same result of "8". I researched about this and in most cases the suggestion was to use std::vector but in this specific case it's necessary to use char * due to the request of my professor. I hope you can help me and thanks in advance.

A: sizeof(contenido) evaluates to the size of a pointer, which is 8 on your platform.
To restore the contents of a string, you need to use the length of the string as argument to read.
size_t Archivo::lee(size_t nbytes) {
  contenido = new char[nbytes];
  cout << "contenido: " << sizeof(contenido) << endl;
  nbytes = read(fd, contenido, nbytes);
  return nbytes;
}

If contenido is supposed to be a null terminated string, you probably need to allocate one more byte for it and make sure to add the terminating null character.
size_t Archivo::lee(size_t nbytes) {
  contenido = new char[nbytes+1];
  cout << "contenido: " << sizeof(contenido) << endl;
  nbytes = read(fd, contenido, nbytpes);
  contenido[nbytes] = '\0';
  return nbytes;
}

A: You are calling the sizeof() operator on a pointer, therefore you get the size of the pointer and not the size of content it's pointing to. Pointer in memory is usually like another regular variable (int for example) except it contains an address instead of an actual value. You always get the number 8 probably because your machine is 64 bit, so a pointer should be able to hold any address in the 64 bit space. (8 bytes = 64 bit)
If you want to get the size in bytes of the content (the memory you allocated), you should take the size of char (the type the content is made of) using sizeof() and then multiply that by the number of chars allocated, like so:
sizeof(char)*nbytes

redpajama_set_name: RedPajamaStackExchange


text:
Q: Extract hard link files with tar I am trying to get list of all files in tar folder show them all on a page with links to download files.
On click on single files it will be downloaded. This all is working fine except the hard link files
command I use to extract single file is
tar --extract --file=abc.tar.xz abc.file

but if the file is hard link then it gives me error, is there a way to get hard link file ?

A: The problem is in how tar stores files.  So, for example
$ echo hello > a
$ ln a b
$ tar cf foo.tar a b
$ tar tf foo.tar
a
b

The problem happens when you try to extract just one file
$ mkdir Y
$ cd Y
$ tar xvf ../foo.tar b
b
tar: b: Cannot hard link to `a': No such file or directory
tar: Exiting with failure status due to previous errors

What you need to do is look at the verbose content list shows
$ tar tvf foo.tar
-rw-r--r-- sweh/sweh         6 2016-06-13 10:43 a
hrw-r--r-- sweh/sweh         0 2016-06-13 10:43 b link to a

Now you can see that "b" has zero length, has type "h" (first character) and is flagged as " link to ".  This tells you the real file you need to extract.
In this case you may want to use the "O" option (send to stdout), so you'd end up doing tar Oxvf ../foo.tar a > b to create a file of the right name.


text:
Q: How to make a  in a VS form not post back to server I am creating a page in VS 2017 that uses bootstrap modal for a popup. When I place the  for the modal inside the asp.net form the modal opens and then closes right away.  When I place the button outside the form the modal works fine. I have tried using an asp.net button and OnclientClick but that doesn't work. I have tried onClick in the button, didn't work.  I tried type="button", didn't work. Is there anyway for a to stop the button from causing a submit. Here is the code.
 <form runat="server">
----some code

        <asp:Button ID="continue" runat="server" CssClass="btn btn-primary" text="Continue Login"/>
        <button class="btn btn-secondary ml-2" data-toggle="modal" data-target="#myModal">Request Account</button>

</form>

Modal Title

                   <button class="close" data-dismiss="modal">×</button>

Effective 22 May 08, access to the F-15 TADS site will require an approved DD Form 2875.

                    <button class="btn btn-secondary" data-dismiss="modal"></button>

A: I am surprised that you can still build web forms in VS2017!
Anyway, if you don't specify type attribute on a <button>, it will default to type=submit. That might be the reason why you saw the modal opened and closed right away.
To trigger the modal, a simple <button> with type=button should work. It doesn't need to be within the <form runat="server"></form>:
<button type="button" class="btn btn-secondary" data-toggle="modal"
    data-target="#myModal">
    Request Account
</button>

It should still work even the button is inside <form>, as long as it specifies type="button".


text:
Q: The "unexpected greater" PGA size allocated in rman channel Environment: RHEL 6.9、     Oracle 11.2.0.4
When we running some rman backup/restore jobs, we found the actual PGA size could greatly exceed the predefined limit value about PGA:

*

*Why the following each rman channel process memory allocated were almost all more than the _pga_max_size?

*Why the following total rman channel processes' memory allocated could be far more than the global pga_target?
SQL>
SQL>
SQL> SELECT a.ksppinm AS parameter, c.ksppstvl AS VALUE, a.ksppdesc AS description, b.ksppstdf AS "Default?"
  2  FROM x$ksppi a,  x$ksppcv b,  x$ksppsv c  WHERE a.indx = b.indx  AND a.indx = c.indx AND a.ksppinm IN
  3  ('pga_aggregate_target','_pga_max_size','_smm_max_size','_smm_px_max_size') ORDER BY a.ksppinm;

PARAMETER             VALUE              DESCRIPTION                                        Default?
--------------------- ------------------ -------------------------------------------------- ----------
_pga_max_size         209715200          Maximum size of the PGA memory for one process     TRUE
_smm_max_size         102400             maximum work area size in auto mode (serial)       TRUE
_smm_px_max_size      524288             maximum work area size in auto mode (global)       TRUE
pga_aggregate_target  1073741824         Target size for the aggregate PGA memory consumed  FALSE
                                         by the instance

SQL>
SQL> select component, current_size/1024/1024  "CURRENT_SIZE", min_size/1024/1024 "MIN_SIZE", max_size/1024/1024 "MAX_SIZE",
  2  user_specified_size/1024/1024 "USER_SPECIFIED_SIZE", last_oper_type "TYPE"  from  v$memory_dynamic_components where rownum < 100;

COMPONENT                                                        CURRENT_SIZE   MIN_SIZE   MAX_SIZE USER_SPECIFIED_SIZE TYPE
---------------------------------------------------------------- ------------ ---------- ---------- ------------------- -------------
shared pool                                                               656        528        656                   0 GROW
large pool                                                                416        416        416                   0 STATIC
java pool                                                                  64         64         64                   0 STATIC
streams pool                                                                0          0          0                   0 STATIC
SGA Target                                                               3072       3072       3072                   0 STATIC
DEFAULT buffer cache                                                     1888       1888       1904                   0 SHRINK
KEEP buffer cache                                                           0          0          0                   0 STATIC
RECYCLE buffer cache                                                        0          0          0                   0 STATIC
DEFAULT 2K buffer cache                                                     0          0          0                   0 STATIC
DEFAULT 4K buffer cache                                                     0          0          0                   0 STATIC
DEFAULT 8K buffer cache                                                     0          0          0                   0 STATIC
DEFAULT 16K buffer cache                                                    0          0          0                   0 STATIC
DEFAULT 32K buffer cache                                                    0          0          0                   0 STATIC
Shared IO Pool                                                              0          0          0                   0 STATIC
PGA Target                                                               1024       1024       1024                1024 STATIC
ASM Buffer Cache                                                            0          0          0                   0 STATIC

16 rows selected.

SQL>
SQL>
SQL> select sid, spid, s.program, event, pga_used_mem,pga_max_mem from v$process p, v$session s
  2  where addr = s.paddr and s.program like '%rman%'  order by pga_used_mem desc;

    SID SPID                     PROGRAM                                          EVENT                             PGA_USED_MEM PGA_MAX_MEM
------- ------------------------ ------------------------------------------------ --------------------------------- ------------ -----------
   1123 120921                   rman@JCHXRST (TNS V1-V3)                         Backup: MML read backup piece        542165387   562245814
   1057 120917                   rman@JCHXRST (TNS V1-V3)                         Backup: MML read backup piece        542127691   562245814
   1024 120915                   rman@JCHXRST (TNS V1-V3)                         Backup: MML read backup piece        541392107   562753046
    892 120907                   rman@JCHXRST (TNS V1-V3)                         SQL*Net message from client          106517430   113455286
   1090 120919                   rman@JCHXRST (TNS V1-V3)                         Backup: MML restore backup piece      21407539    24588470
    958 120914                   rman@JCHXRST (TNS V1-V3)                         SQL*Net message from client             980323     1913014

6 rows selected.

SQL>
SQL>

Updated:
It's just for the RMAN restore job !
And we just use the customized RMAN script with the default RMAN configuration:
RMAN> show all;

RMAN configuration parameters for database with db_unique_name SGPMDB are:
CONFIGURE RETENTION POLICY TO REDUNDANCY 1; # default
CONFIGURE BACKUP OPTIMIZATION OFF; # default
CONFIGURE DEFAULT DEVICE TYPE TO DISK; # default
CONFIGURE CONTROLFILE AUTOBACKUP OFF; # default
CONFIGURE CONTROLFILE AUTOBACKUP FORMAT FOR DEVICE TYPE DISK TO '%F'; # default
CONFIGURE DEVICE TYPE DISK PARALLELISM 1 BACKUP TYPE TO BACKUPSET; # default
CONFIGURE DATAFILE BACKUP COPIES FOR DEVICE TYPE DISK TO 1; # default
CONFIGURE ARCHIVELOG BACKUP COPIES FOR DEVICE TYPE DISK TO 1; # default
CONFIGURE MAXSETSIZE TO UNLIMITED; # default
CONFIGURE ENCRYPTION FOR DATABASE OFF; # default
CONFIGURE ENCRYPTION ALGORITHM 'AES128'; # default
CONFIGURE COMPRESSION ALGORITHM 'BASIC' AS OF RELEASE 'DEFAULT' OPTIMIZE FOR LOAD TRUE ; # default
CONFIGURE ARCHIVELOG DELETION POLICY TO NONE; # default
CONFIGURE SNAPSHOT CONTROLFILE NAME TO '+SGPMDB_ARC/snapcf_sgpmdb.f';

RMAN>

rman target / <<EOF
run {
allocate channel ch00 type 'sbt_tape';
allocate channel ch01 type 'sbt_tape';
allocate channel ch02 type 'sbt_tape';
allocate channel ch03 type 'sbt_tape';
SEND 'NB_ORA_SERV=jchxbak,NB_ORA_CLIENT=scyxdb3';
set until time "to_date('2020-08-22 15:12:58','YYYY-MM-DD HH24:MI:SS')";
SET NEWNAME FOR DATABASE to '+data/%U';
restore database ;
switch datafile all;
switch tempfile all;
release channel ch00;
release channel ch01;
release channel ch02;
release channel ch03;
}
exit;

A: == Partial answer as question require more context ==
== As i'm new here, i can't put that in the comments, so if reviewers could right the things ==
As it's Oracle 11, encryption cause can be casted out.
For point 1 & 2 could you precise if you're doing inconsistent backups (archive log, redo log, etc.) or consistent backups (cold backup, etc.) ?
As it concerns the PGA, that could be the result of your RMAN config (RMAN uses PLSQL package for backup and recover), i suggest to tune your buffers sizes and / or multiplexing level.
Update
Seeing that you've the default config, that means that your restore target disks (Tape backups / restores are more prone to target PGA). With disks, PGA load could come from Synchronous I/O with a high DBWR_IO_SLAVES. I suggest that you check these in your database config. If DBWR_IO_SLAVES is zero and you have asynchronous I/O, i suggest to reduce buffers size.


text:
Q: Transfer data and schema from one database to another one table at a time Hope you all can help me out with this situation.  My boss built up a brand new database and he wants several of the old tables in the new database.  My question is how do I transfer the data and schema over from the old database to the new database without deleting the tables in the old database?  Here is my two databases: WTS-SQL-DEV = this is the old database
: WTS-Business = is the new database
Additional info from comment:

I can access both databases on the same machine. I found a video on
  youtube how to transfer the table over and the structure. I was
  missing the data.

A: Two great answers already.
Another option is to right click the database, then go to Tasks > Export Data.
This will launch the import/export wizard.  You can define source/destination servers/databases and objects, and copy everything.
https://msdn.microsoft.com/en-us/library/ms140052.aspx

A: *

*Take a backup of the database

*

*On the new machine restore the database

A: You mentioned that the 2 databases are on the same machine, and that you figured out how to get the schema over
(I use Tasks - Create Scripts from the right-click context menu on the database, and generate the scripts by selecting the individual tables, and save to new query window.. then it's as simple as doing Use [new_db] on top of each created script, and the objects will be created in the new database, where [new_db] is your new database name.).
Since the tables have the same structure, to insert the data, once you create tables in new DB, it is an insert select statement. Enable identity insert if there is (as should be) an autogenerated primary key column. Insert the data. Then disable identity insert.
-- Note: Identity_Insert is required if there is an identity column present
-- Otherwise those two lines can be removed/commented out
Use [new_db]
Set IDENTITY_INSERT [table_name] On
Insert Into [table_name]
-- Note 2: Default schema is [dbo], but technically, it is [db].[schema].[table]
Select * From [old_db].[dbo].[table_name]
Set IDENTITY_INSERT [table_name] Off

Pretty straight-forward in your case, and no need to backup/restore the db. If the databases were on separate, non-linked servers, a backup/restore would be needed in order to get the old and new databases on the same machine... something that you already have in your particular case.


text:
Q: How count value of an attribute on different json pages using php I'm a beginner in php
I have this problem:
I need to plus up the total value of each sale of a json, but it is divided into pages! therefore, I must add the total sale of each page
Example:
- On page 1: I have 100 orders, each one costing 10 dollars, in the total of this page I will have a value of 1000.
- On page 2: I have 50 orders costing 10 dollars, therefore in the total of this page 500 reais
Now I need plus the total of these two pages
This is the api url.
$url = 'https://bling.com.br/Api/v2/pedidos/page=1/' . $outputType  . '/?'  . $dataEmissao;

$return = executeGetOrder($url, $apikey);

$obj = json_decode($return);
$subItem = $obj->return->orders;

$total = 0;

for($i = 0; $i < count($subItem); $i++) {
    $total += $subItem[$i]->orders->totalSale;
}

Important to remember that each page only shows 100 orders, sometimes I have the first page with 100 orders and the second page with.
Function executeGetOrder
function executeGetOrder($url, $apikey){
$curl_handle = curl_init();
curl_setopt($curl_handle, CURLOPT_URL, $url . '&apikey=' . $apikey);
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, TRUE);
$response = curl_exec($curl_handle);
curl_close($curl_handle);
return $response;

}

A: If you don't have the information of total number of pages you can do something like:
$page = 1;
$grandTotal = 0;

while ($return = executeGetOrder('https://bling.com.br/Api/v2/pedidos/page=' . $page . '/' . $outputType  . '/?'  . $dataEmissao, $apikey)) {
    $obj = json_decode($return);
    $subItem = $obj->return->orders;

    $total = 0;

    for ($i = 0; $i < count($subItem); $i++) {
        $total += $subItem[$i]->orders->totalSale;
    }

    $grandTotal += $total;
    $page ++;
}

And then it's important that when your executeGetOrder function sends an HTTP request and finds out that the page does not exist, then it will return false or null.

*

*Thought: you can add a condition to the loop in order to avoid unnecessary request most of the times when the last page has fewer orders than the rest. So for example, if you have 100 orders per page, you can add && $grandTotal % 100 == 0

If you know the total number of pages, then you better do a for loop: (avoiding unnecessary request):
$totalPages = ?;
$grandTotal = 0;

for ($page = 1; $page <= $totalPages; $page ++) {
    $return = executeGetOrder('https://bling.com.br/Api/v2/pedidos/page=' . $page . '/' . $outputType  . '/?'  . $dataEmissao, $apikey)
    $obj = json_decode($return);
    $subItem = $obj->return->orders;

    $total = 0;

    for ($i = 0; $i < count($subItem); $i++) {
        $total += $subItem[$i]->orders->totalSale;
    }

    $grandTotal += $total;
}

A: I did it, I made some changes
$page = 1;

$totalOrders = 0;

do {

$url = 'https://bling.com.br/Api/v2/pedidos/page=' . $page . '/' . $outputType . '/?' . $dataEmissao . '&apikey=' . $apikey;

$retorno = executeGetOrder($url);

$obj = json_decode($retorno);

if(!empty($obj->retorno->pedidos)) {

    $totalOrdersPage = count($obj->return->orders);

    $totalOrders += $totalOrdersPage;

    $page++;

    // Search each orders
    foreach ($obj->retorno->pedidos as $pedido) {
        // Add value total sales of the orders in $grandTotal
        $grandTotal += $orders->order->totalsale;
    }

} else {
    $totalOrdersPage = 0;
}

} while ($totalOrdersPage > 0);


text:
Q: java.sql.Types.ARRAY from simple select statement What I have:

*

*Table "CI", many columns in here, ci_id, description, ...

*Table "CI_REL", ci_id, parent_ci_id, child_ci_id

*CI_REL having multiple relations in them, to show that one record in CI has multiple parents, or multiple children records in CI

What I need:
Join the two tables, so I get one record of CI enriched with an Sql ARRAY (VARRAY?) for the parents and children in the record.
Example:
|id | description | children | parents |
|1  | root        | [2,3]    | null    |
|2  | child1      | [3]      | [1]     |
|3  | child2      | [2]      | [1]     |

Why do I need this?  I'm using Apache Nifi for Data Ingestion into Apache Solr, and need a multivalue field for children and parents.  Since the ExecuteSQL is interpreting the sql ResultSet, and acts on finding java.sql.Types.ARRAY in the way I need, I'd like to have a select, that actually returns this, somehow.  BTW: I don't have any possibility to use PL/SQL, hopefully this won't make an answer impossible...
Thanks!
Henning

A: You can use CAST( COLLECT( ... ) AS ... ) in a correlated sub-query generate your collections:
SQL Fiddle
Oracle 11g R2 Schema Setup:
CREATE TABLE CI ( id, description ) AS
SELECT 1, 'root' FROM DUAL UNION ALL
SELECT 2, 'child1' FROM DUAL UNION ALL
SELECT 3, 'child2' FROM DUAL;

CREATE TABLE CI_REL ( ci_id, child_ci_id, parent_ci_id ) AS
SELECT 1, 2, NULL FROM DUAL UNION ALL
SELECT 2, 3, 1    FROM DUAL UNION ALL
SELECT 3, NULL, 2 FROM DUAL;

CREATE TYPE NumberList IS TABLE OF Number(8,0);

Query 1:
SELECT c.*,
       ( SELECT CAST(
                  COLLECT(
                    DISTINCT child_ci_id
                    ORDER BY LEVEL
                  ) AS NumberList
                )
          FROM  CI_REL r
          WHERE child_ci_id IS NOT NULL
          START WITH r.ci_id = c.id
          CONNECT BY PRIOR child_ci_id = ci_id
       ) AS children,
       ( SELECT CAST(
                  COLLECT(
                    DISTINCT parent_ci_id
                    ORDER BY LEVEL
                  ) AS NumberList
                )
          FROM  CI_REL r
          WHERE parent_ci_id IS NOT NULL
          START WITH r.ci_id = c.id
          CONNECT BY PRIOR parent_ci_id = ci_id
        ) AS parents
FROM   CI c

Results:
| ID | DESCRIPTION | CHILDREN | PARENTS |
|----|-------------|----------|---------|
|  1 |        root |      2,3 |         |
|  2 |      child1 |        3 |       1 |
|  3 |      child2 |          |     2,1 |


text:
Q: Return to previous ViewController when using UITabBarController but not UINavigationController Im using a UITabBarController that I've created programatically to present UIViewControllers that I've created in Storyboard. I present these with
let storyboard = UIStoryboard(name: "Main", bundle: nil)

// create tab one
let tabOne = storyboard.instantiateViewController(withIdentifier: "feedVC")
let tabOneBarItem = UITabBarItem(title: "feed", image: UIImage(named: "feed_icon"), selectedImage: UIImage(named: "feed_icon_selected"))
        tabOne.tabBarItem = tabOneBarItem

self.viewControllers = [tabOne]

in one of the tabs where I don't show the TabBar, I have a cancel button in the top left. I prefer this to send the user back to the previous ViewController. But settle with a specific one. The code below works, but the TabBarController do not show... what is the most efficient way to implement a cancel/return button.
Should I use UINavigationController - or are there better alternatives?
@IBAction func cancelBtnWasPressed(_ sender: Any) {
    let returnVC = storyboard?.instantiateViewController(withIdentifier: "feedVC")

    present(returnVC!, animated: true, completion: nil)

}

A: I found the solution that worked for me.
Swift 4:
self.tabBarController?.selectedIndex = 0

This moves the view back to the first of the Tabs i the TabBarController

A: You have to dismiss the current one :
@IBAction func cancelBtnWasPressed(_ sender: Any) {
    self.dismiss(animated: true, completion: nil)
}


text:
Q: Display choosen image instead of default image first time user adds image cell in collectionview Swift 5 I am new to iOS development and coding on swift 5. I have a collection view that the user can add images to. There are two issues. First, I would like to not display any cells when the user first views the collection view. The second issue is that when the user adds the first image, it displays the default image/cell and not the selected image from image picker.
I have searched for this answer but haven't found anything to help resolve my issue. Thank you
I added minus 1 to numberOfItemsInSection function. When I run this it shows no cells in the collection view. But when I add an image/cell, the default image/cells appears and not the image the user chooses from photo library.
// collectionviewcell
class CollectionViewCell: UICollectionViewCell {

    @IBOutlet weak var img: UIImageView!

    var delegate: CollectionProtocol?
    var index: IndexPath?

    @IBOutlet weak var deleteBtn: UIButton!
    @IBAction func deleteBtn(_ sender: UIButton) {
        delegate?.deleteData(indx: (index?.row)!)
        print("photo deleted")
    }
}

// view controller
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return imgArr.count - 1
}

A: I needed to initialize the imageArray with an empty state.
So I updated it to:
let imageArray = UIImage
Also updated func numberOfItemsInSection to return numberOfRowsInSection


text:
Q: MariaDB GROUP_CONCAT LATERAL DERIVED I have two MariaDB instances running on two different machines
1. iMac (Late 2012, 32GB) OSX 10.13.3 (High-Sierra)
2. Brand-new Intel-Server with 4 cores (VMWare) 64GB exclusive Database-Server
On both machines MariaDB 10.3.4 is installed (latest Beta of MariaDB 10.3)
I have created two views whereas the second uses the first one as shown below.
First view
select
    `a`.`artikel` AS `artikel`,
    group_concat(
        distinct `b`.`reference` separator '/'
    ) AS `referenz`
from
    (
        `prod_welu_pdm`.`appadaptive_pdm_domain_model_stammdaten_artikelreference` `a`
    join `prod_welu_pdm`.`appadaptive_pdm_domain_model_klassifizierung_reference` `b` on
        (
            `a`.`reference` = `b`.`persistence_object_identifier`
        )
    )
group by
    `a`.`artikel`

Second View
select
    `a`.`persistence_object_identifier` AS `persistence_object_identifier`,
    `a`.`artikelnr` AS `artikelnr`,
    `a`.`bezeichnung` AS `bezeichnung`,
    `b`.`referenz` AS `referenz`
from
    (
        `prod_welu_pdm`.`appadaptive_pdm_domain_model_stammdaten_artikel` `a`
    left join `prod_welu_pdm`.`vwelupdmartikelreferences` `b` on
        (
            `a`.`persistence_object_identifier` = `b`.`artikel`
        )
    )

When I run the second view on my 6 years old iMac where MariaDB has a maximum of 5GB as buffer-pool-size, the query takes 200ms for 200 rows.
On the brand-new Intel-Server with 32GB buffer-pool-size the identical query takes
6 to 10 seconds.
The databases on both machines are absolutely identical concerning indexes, constraints and all the rest. The only visible difference is the result of the queries done with EXPLAIN
iMac: enter image description here
Intel-Server: enter image description here
What might cause such a different behaviour on two MariaDB instances with the same version?
enter image description here
Here the first EXPLAIN SELECT again as picture


text:
Q: What is difference between Password expires and Account expires ? Output of chage -l username command What is difference between Password expires and Account expires ? Output of "chage -l username" command in Linux. In both case account will be locked So why there are two different fields?

A: Password expiration means that user needs to change the password on next login. The user still be able to login after resetting the password.
In the case of account expiration, User account will be locked after certain days, Hence it is not able to login at all.

A: Check this out
https://security.stackexchange.com/questions/49684/difference-between-password-expiration-and-account-expiration

I think password expiration and account expiration are two differents means to achieve the same goal, that is to prevent someone to log in. However, they are used in different context and for different needs.
Password expiration is used when you want to force someone to renew their password at a specific interval (maybe 90 days) but you want the account to stay enabled. The user will be prompted to change his password and the next logon.
Account expiration should be used in another context. For example if you hire a contractor for 6 months and you want the account to be disabled at the end of the contract, you can set an account expiration at a fixed date and you won't have to be concerned about removing access to this contractor when the contract is finished since the account will be automatically disabled.

A: The difference is that when the password expires, you can't login using a password, but you can log in using SSH keys, for example.
In case the account has expired, you can't log in at all.

A: There are two different things here .
First , password expired -> when password gets expired then in the next login user must have to change/reset his password . after password expiry date , he will get reset password prompt as soon as he may try to login .
Also , password expired date is calculated using (last password change + max password age ) .
Second , Account expired -> when the account get expired then the password will be expired and also user will not receive any prompt to reset/change password . Now , only root user can help him to login . root user may extend the account expired date or create entire  new password with different password expiry information.
So , in short : when password expire , user by its own can reset it but when account expire the user can't change it and can't login at all .


text:
Q: how do i update my listView after deleting the data in firebase realtime database My app saves the data in a firebase realtime database and i retrived the data in a listView.Now i want to delete a particular data in a listView ,I used the removeValue().But the problem is i am not able to update the listView after deleting.It either clears the listView or it gets remain with only one item in a listView and when i reopen my app,then the items are properly updated.Please help.
This is my MainActivity.java
package com.example.manuj.todolist;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.firebase.database.ChildEventListener;
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.Query;
import com.google.firebase.database.ValueEventListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    ListView listView;
    TextView textView;
    Button button;

    String tasks;
    FirebaseDatabase db = FirebaseDatabase.getInstance();
    DatabaseReference rootRef = db.getReference();
    DatabaseReference dataRef = rootRef.child("Todo");
    ArrayList<String>arrayList=new ArrayList<>();
    ArrayAdapter arrayAdapter;

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

        button=findViewById(R.id.delButton);
        textView=findViewById(R.id.taskText);
        listView=findViewById(R.id.listView);

        arrayAdapter=new ArrayAdapter<String>(this,R.layout.list_items,R.id.taskText,arrayList);
        listView.setAdapter(arrayAdapter);

        dataRef.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                String value = dataSnapshot.getValue().toString();
                try {
                    JSONObject object = new JSONObject(value);
                    tasks = object.getString("Task");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                arrayList.add(tasks);
                arrayAdapter.notifyDataSetChanged();

            }

            @Override
            public void onChildChanged(DataSnapshot dataSnapshot, String s) {

            }

            @Override
            public void onChildRemoved(DataSnapshot dataSnapshot) {

            }

            @Override
            public void onChildMoved(DataSnapshot dataSnapshot, String s) {

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
                Toast.makeText(MainActivity.this,"sffad",Toast.LENGTH_SHORT).show();

            }

        });

        //Get the floating action button and set onClickLiter
        FloatingActionButton fab = findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent(MainActivity.this,CustomDialog.class);
                startActivity(intent);
            }
        });

    }

    public void deleteTask(View view) {

        int index=listView.getPositionForView(view);
        String str= (String) arrayAdapter.getItem(index++);

        DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
        Query taskQuery = ref.child("Todo").orderByChild("Task").equalTo(str);
        taskQuery.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for (DataSnapshot appleSnapshot: dataSnapshot.getChildren()) {
                    appleSnapshot.getRef().removeValue();
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                Log.e("TAG", "onCancelled", databaseError.toException());
            }
        });

        arrayAdapter.clear();
        arrayAdapter.addAll(arrayList);
        arrayAdapter.notifyDataSetChanged();

    }

}

A: After call of for loop of appleSnapshot.getRef().removeValue(); then remove that position item from arraylist , then call notifydatasetchanged and check like below
public void deleteTask(View view) {

    int index=listView.getPositionForView(view);
    String str= (String) arrayAdapter.getItem(index++);

    DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
    Query taskQuery = ref.child("Todo").orderByChild("Task").equalTo(str);
    taskQuery.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot appleSnapshot: dataSnapshot.getChildren()) {
                appleSnapshot.getRef().removeValue();
            }
            arrayList.remove(listView.getPositionForView(view)); // remove the item from list
            arrayAdapter.notifyDataSetChanged();// notify the changed
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            Log.e("TAG", "onCancelled", databaseError.toException());
        }
    });

}


text: Q: How can I turn on my computer and bypass the password with Android I am travelling overseas but would like to be able to remotely turn on and control my computer (Win7) from my Android (i9500 jtxx on 4.3 rooted) phone. My computer is currently password protected, and I would like for this to remain the case.


text:
Q: Needing assistance with Git, GitHub, and a DigitalOcean VPS for a version control solution Please let me know if the question needs to be reworded, and my apologies in advance for any confusion.
I am attempting to create a version control solution using Git, GitHub and my VPS on DigitalOcean. As it currently stands, I have always had a DEV directory and a PRODUCTION directory, both on my DO VPS.
In the past, when finishing changes on the DEV directory, I would copy changed files manually over to my PRODUCTION directory. (Each of these directories is served to a different URL via Apache).
My goal is to have a Git repo in my DEV directory (where I make changes) sync up to my GitHub repo (https://github.com/jmwii1981/hello_world), which I have working. Then (this is the part I can't figure out). I'd like to pull changes from GitHub to my working directory, and by 'pull' I mean that I'd like to use GitHub's built in services to sync my changes from GitHub to the PRODUCTION directory on my server, however, I cannot seem to figure this out to save my life as every bit of documentation I've found so far has it's own flavor or method which is not inline with what I'm trying to achieve in my workflow.
My specific workflow would work out as follows:
(1) Make changes to code on DEV directory.
(2) 'git add .', 'git commit -m "my message"', 'git push origin'
(3) Git adds my changes, I commit those changes with my update message, I push those commits to my origin's master branch on GitHub using my SSH key.
(4) GitHub receives my changes and syncs them to my PRODUCTION directory.
Is this possible? I would assume it is, but I don't have enough experience with Git to make this happen. Thanks in advance for your help, excuse my naivety on this matter. I appreciate any detailed steps as I'm new to Git tech. Thanks again!

A: GitHub cannot simply reach into your server and update the files, but what it can do is send messages when certain events happen. What you want to do is add a commit hook which sends your server a message. When your server receives the message, it should take all steps necessary to redeploy your application. (This may include stopping Apache, running git pull, and restarting Apache).
Git's commit hook feature allows you to run an arbitrary command or shell script on the server during a commit. Naturally GitHub doesn't give you all of that power; instead they have a set list of hooks which you can enable. The most general of these are called webhooks. When you set up webhooks GitHub will do an HTTP POST to a url of your choosing.


text:
Q: Optimizing this MySQL Query Table Schema
For the two tables, the CREATE queries are given below:
Table1:   (file_path_key, dir_path_key)
create table Table1(
             file_path_key varchar(500),
             dir_path_key varchar(500),
             primary key(file_path_key))
engine = innodb;

Table2: (file_path_key, hash_key)
create table Table2(
             file_path_key varchar(500) not null,
             hash_key bigint(20) not null,
             foreign key (file_path_key) references Table1(file_path_key) on update cascade on delete cascade)
engine = innodb;

Objective:
Given a file_path F and it's dir_path string D, I need to find all those
file names which have at least one hash in the set of hashes of F, but
don't have their directory names as D. If a file F1 shares multiple hashes
with F, then it should be repeated that many times.
Note that the file_path_key column in Table1 and the hash_key column in Table2 are indexed.
In this particular case, Table1 has around 350,000 entries and Table2 has 31,167,119 entries, which makes my current query slow:
create table temp
        as select hash_key from Table2
        where file_path_key = F;

select s1.file_path_key
        from Table1 as s1
        join Table2 as s2
        on s1.file_path_key join
        temp on temp.hash_key = s2.hash_key
        where s1.dir_path_key != D

How can I speed up this query?

A: I do not understand what is the purpose of temp table, but remember that such table, created with CREATE .. SELECT, does not have any indexes. So at the very least fix that statement to
CREATE TABLE temp (INDEX(hash_key)) ENGINE=InnoDB AS
SELECT hash_key FROM Table2 WHERE file_path_key = F;

Otherwise the other SELECT performs full join with temp, so it might be very slow.
I would also suggest using a numerical primary key (INT, BIGINT) in Table1 and reference it from Table2 rather than the text column. Eg:
create table Table1(
             id int not null auto_increment primary key,
             file_path_key varchar(500),
             dir_path_key varchar(500),
             unique key(file_path_key))
engine = innodb;

create table Table2(
             file_id int not null,
             hash_key bigint(20) not null,
             foreign key (file_id) references Table1(id)
            on update cascade on delete cascade) engine = innodb;

Queries joining the two tables may be a lot faster if integer columns are used in join predicate rather than text ones.


text:
Q: Map in Formik React I have made a custom component and I want to use Formik on these in map but I cannot figure it out how to use them in map like how to give erors and values in map
                  <LicenseFormControl id="utr-number"
                    error={errors.utrNumber}
                    formikValue={values.utrNumber}
                    handleChange={handleChange}
                    name="utrNumber"
                    touched={touched.utrNumber}
                    title="Have UTR number?"
                    tooltipTitle="Please provid"
                  />
                  <LicenseFormControl id="permises-permission"
                    error={errors.permisesPermission}
                    formikValue={values.permisesPermission}
                    handleChange={handleChange}
                    name="permisesPermission"
                    touched={touched.permisesPermission}
                    title="Have premises Permission?"
                    tooltipTitle="Please provide the premises "
                    setPermisesPermissionImage={setPermisesPermissionImage}
                    permisesPermissionImage={permisesPermissionImage}
                  />
                  <LicenseFormControl id="sign-memorendum"
                    error={errors.signMemorendum}
                    formikValue={values.signMemorendum}
                    handleChange={handleChange}
                    name="signMemorendum"
                    touched={touched.signMemorendum}
                    title="Please read and sign memorendum if you are agree"
                    tooltipTitle="You have to readenter code here"
                    setMemorendum={setMemorendum}enter code here
                    setShowContract={setShowContract}
                  />

is there any way to use it in map I am new it will be great pleasure if you help


text:
Q: Does the this function contain a local variable? The book I'm reading says that this function has a local variable. It also says that having a local variable for this function is important because it's recursive. Maybe I'm just blind or I don't understand how local variables work in assembly, but I don't see it.
.type factorial, @function
factorial:
    push %rbp               # Save old base pointer.
    mov  %rsp, %rbp         # Copy stack pointer to base pointer.
    mov  16(%rbp), %rax     # Save the argument in %rax.
    cmp  $1, %rax           # End of the factorial.
    je   end_factorial
    dec  %rax               # Decrement %rax.
    push %rax               # Push onto stack for next call to factorial.
    call factorial
    mov  16(%rbp), %rbx     # %rax has return value, so load arg into %rbx.
    imul %rbx, %rax         # Multiply that by result of last call to factorial.

end_factorial:
    # Restore stack pointer and base pointer to where they were
    # before function call.
    mov %rbp, %rsp
    pop %rbp
    ret

Can registers be considered local variables? I though local variables were implemented with something like sub $8, %rsp.

A: Local variables are not defined through their implementation, but by their semantics.
A definition
A variable is local, if every invocation of the function gets its own independent value for that variable, that's why you could say that the value of the variable is "local to the function".
Since this behavior can be achieved by using registers, that's a perfectly valid implementation.
Saving and restoring local variables
However, since certain registers are considered caller-saved, the values may have to be put on the stack before calling nested functions, otherwise the values would be lost. Upon returning to the original function from the nested call, the value can then be restored into the register from the stack.
As has already been mentioned, a accessing a register is much faster than accessing the stack. Thus, they are preferred to main memory whenever possible.
However, I do not know why it couldn't just do imul 16(%rbp), %rax without the additional move operation. After all, the imul instruction allows the source operand to be in-memory.

A: A register is a perfectly valid place to put a local variable. In fact, it is preferred to memory because access is much faster. I modified my LLVM demo page to compile this factorial algorithm at http://ellcc.org/demo/. For the x86-64 it comes up with
    .file   "/tmp/webcompile/_23578_0.c"
.text
.globl  fact
.align  16, 0x90
.type   fact,@function
fact:                                   # @fact
.cfi_startproc
# BB#0:                                 # %entry
movl    $1, %eax
cmpq    $2, %rdi
jl  .LBB0_2
.align  16, 0x90
.LBB0_1:                                # %if.end
                                     # =>This Inner Loop Header: Depth=1
imulq   %rdi, %rax
decq    %rdi
cmpq    $1, %rdi
jg  .LBB0_1
.LBB0_2:                                # %return
ret
.Ltmp0:
.size   fact, .Ltmp0-fact
.cfi_endproc

Notice that in this case the compiler gets rid of recursion and uses only registers to do the calculation.


text:
Q: Show / Hide Fields in Pentaho Report Based on User Input I'm trying to show / hide fields in a Pentaho report based upon user input.
For example, I would like to offer a checkbox to the user saying "Show Product Count" -- if the box is unchecked, it will not include that column in the report.
Is there a way to do this in Pentaho Report Designer, perhaps using Parameters?
Thanks for the help -Monica

A: Yes, you have half the answer.  Have a Yes/No Parameter "ShowProductCount"
Then on the conditional fields, go to the visible property, click the + formula icon and enter:
=IF([ShowProductCount]="Yes"; TRUE(); FALSE())
Simple! :)

A: There is more to this that the above answer. For example, if you don't want a field to show on the report, you pass the value mentioned above by Codek but the field will not show but the space for it will. The field has to be in a BAND and the band layout has to be set to ROW. Also, on the field you want to not display or display based on user selection, you have to set that field's style properties under size & position - invisible-consumes-space = false.


text:
Q: getElementsByTagName Stopped Working I'm trying to populate an HMTL page with XML data. This code used to work but I must have changed something because now nothing happens on the button clicks. Could it potentially be a problem with the server? And in that case what changed? The line where things appear to stop working is getElementsByTagName, all alerts before that line still work.
Here's the scripts:
<script type="text/javascript">
    function loadXMLDocTraditional() {

        var xhttp = new XMLHttpRequest();
          xhttp.onreadystatechange = function() {

            if (xhttp.readyState == 4 && xhttp.status == 200) {
                //alert("Xhttp.readyState = " + xhttp.readyState);

                var xmlDoc = xhttp.responseXML;
                //There is something wrong with this line
                var item = xmlDoc.getElementsByTagName("trad")[0].childNodes[0];
                document.getElementById("data").innerHTML = item.nodeValue;
            }
        };
        xhttp.open("GET", "data.xml", true);
        xhttp.send();
    }

    function loadXMLDocSimple() {

        var xhttp = new XMLHttpRequest();
          xhttp.onreadystatechange = function() {

            //alert("Xhttp.status = " + xhttp.status);
            if (xhttp.readyState == 4 && xhttp.status == 200) {

                var xmlDoc = xhttp.responseXML; //Using a variable doesn't work bc/ of the getElements method?
                var item = xmlDoc.getElementsByTagName("simp")[0].childNodes[0];
                document.getElementById("data").innerHTML = item.nodeValue;

            }
        };
        xhttp.open("GET", "data.xml", true);
        xhttp.send();
    }
</script>

And here's the XML:
<dictionary>
<word>
    <title>Ubiquitous</title>
    <trad>This is the traditional defintion ubiquitous</trad>
    <simp>This is the simplified defintion hopefully ubiquitous</simp>
</word>

<word>
    <title>Lithe</title>
    <trad>This is the traditional defintion of lithe</trad>
    <simp>This is the simplified defintion of lithe hopefully</simp>
</word>


text:
Q: edit link from google drive api While I get a file object from google drive api, I want to get the link to edit this file with google docs interface.
But as defined here, I only get the link to google docs if the drive.apps.readonly scope is set to readonly.
Is there any way to get this link for editing?

A: You should actually use drive.apps.readonly scope. "readonly" means that you cannot edit installed google apps, but you still can get list of these apps, and open any document for editing.


text:
Q: Runtime permission: Android (called twice if user deny permission) I have an issue with runtime permission alert dialog. This is my code:
button.setOnClickListener{
    requestPermissionLauncher.launch(android.Manifest.permission.CAMERA)
}

val requestPermissionLauncher =
        registerForActivityResult(
            ActivityResultContracts.RequestPermission()
        ) { isGranted: Boolean ->
            if (isGranted) {
                presenter.openCamera()
            } else {
                showMessage(getString(R.string.permission_needed))
            }
        }

If user click on "Camera" btn, the user see this dialog (as expected):

Then, if the user clicks on "While using the app" or "Only this time" -> all OK, there is no issue
But if the user clicks on "Don't allow" -> he sees an error message (as expected), but if the user clicks on "Camera" btn at second time -> permission alert dialog appears one more time. (and after second time this dialog never appears again)
Why does this alert dialog apper twice if the user deny permission at first time? It should be appear only once, and after second click user might see an error message right away

A: In short: Dialog appears twice because if the user clicks "Deny" at first time, next time system recommends to show a rationale dialog before asking for a permission, and shouldShowRequestPermissionRationale(android.Manifest.permission.CAMERA) returns true. You can check if this is true and simply don't show your permission dialog again. If you don't check manually this boolean, and if it's true, system will automatically show permission dialog once again.
KEEP IN MIND THAT IF USER CLICKS OUTSIDE OF THE PERMISSION DIALOG, IT'S TREATED THE SAME AS IF A USER CLICKED ON "DENY".
When a user denies permission for the second time, you're not allowed to show permission dialog again. The only way for user to allow permission is to go to the app info in system settings and manually allow a requested permission (THIS IS NOT RECOMMENDED).
From Documentation
Workflow for requesting permissions =>
...
Step 4. Check whether the user has already granted the runtime permission. If not, continue to the next step.
Step 5. Check whether your app should show a rationale to the user, explaining why your app needs the user to grant a permission.
...
Permission Graph from developer.android.com
Example:
if (checkSelfPermission(android.Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
        // Application can use camera
    } else if (shouldShowRequestPermissionRationale(android.Manifest.permission.CAMERA)) {
        /*
        This is the second time when system is about to show permission dialog.

        You can show your alert dialog here if you want to explain to user what are benefits if allow your requested permission (CAMERA in this case). Also, you can show
        permission dialog on "OK" click, and do nothing on "No, thank you".

        KEEP IN MIND THAT WITH THIS APPROACH YOU WILL SHOW ALERT DIALOG TO THE USER EVERY TIME YOU CHECK IF PERMISSION IS NOT GRANTED BUT
        shouldShowRequestPermissionRationale(android.Manifest.permission.CAMERA) RETURNS TRUE. THIS CAN BE ANNOYING TO THE USER AND YOU SHOULD
        AVOID THIS PART OF CODE. THIS IS JUST FOR TESTING PURPOSES.

        *** YOU SHOULD SHOW THIS ALERT DIALOG WHEN REGISTERING YOUR ACTIVITY FOR PERMISSION RESULT, IF PERMISSION IS NOT GRANTED!!!***
         */
        AlertDialog.Builder(this@YourActivity)
            .setMessage(
                "Your message"
            )
            .setPositiveButton(
                "OK"
            ) { _, _ ->
                // Show permission dialog
                requestPermissionLauncher.launch(android.Manifest.permission.CAMERA)
            }
            .setNegativeButton(
                "No, thank you"
            ) { _, _ -> }
            .create().show()

        /*
        IF YOU DON'T WANT TO SHOW ALERT_DIALOG FROM ABOVE, HERE YOU CAN SIMPLY SHOW PERMISSION DIALOG

        requestPermissionLauncher.launch(android.Manifest.permission.CAMERA)
         */
    } else {
        /*
        This part of code is active first time when you are going to request the permission, and last time (after second "Deny" by a user,
        or simply, when permission is not granted and shouldShowRequestPermissionRationale(android.Manifest.permission.CAMERA) returns false
         */
        requestPermissionLauncher.launch(android.Manifest.permission.CAMERA)
    }

As I mentioned at the beginning, you can navigate user to the app settings where permission can be allowed, but according to Google's documentation you should avoid that.
Message from documentation: "...respect the user's decision. Don't link to system settings in an effort to convince the user to change their decision."
Even if you want to navigate user you can do that with next block of code:
val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
val uri = Uri.fromParts("package", packageName, null)
intent.data = uri
startActivity(intent)


text:
Q: Django CBV - How to avoid repeating the get_context_data for every view just to get a custom title? I'm setting a {{ title }} for every page of my project. Sometimes this title is a static string such as Enter your Name and sometimes it's based on a relevant object on that page, such as Employee.first_name.
To create context['title'], I'm using get_context_data inside every class based view. But this seems to be resulting in me repeating a chunk of code every time, and I'm looking to reduce that somehow.
For example to write a custom title for each page, I'd have to write this:
def get_context_data(self, **kwargs):
    context = super(SomeView, self).get_context_data(**kwargs)
    context['title'] = 'Title for This page'
    return context

I feel like it'd be ideal to have a mixin that I somehow just pass in the variable for title and my context dictionary will automatically have context['title'] added based on the passed in variable.
Is this possible? Is there a way to create a mixin such that all I have to do is pass in a variable, and it'll give me a context just for the title instead of writing out that chunk of code for every single view?

A: Yes, it's possible and easy:
class YourTitleMixin(object):
    title = None # or your default title if you won't provide any

    def get_title(self):
        return self.title

    def get_context_data(self, **kwargs):
        context= super(YourTitleMixin, self).get_context_data(**kwargs)
        context['title'] = self.get_title()
        return context

And you use it:
def YourPageView(YourTitleMixin, DetailView):
    title = "Your Page Title" # you can either use this ...

    def get_title(self):
        return self.get_object().name # ... or that, if your title should be generated from some data

But is this necessary? Are you using your title only once in template? Do you share one template between views? Maybe you can do it purely in your templates? For example:
{# base.html #}
<html>
  <head>
    <title>{% block page_title %}My page{% endblock %}</title>
  </head>
</html>

{# detail.html #}
{% extends "base.html" %}
{% block title %}{{ article.name }} - {{ block.super }}{% endblock %}
{# will result in "article name - My Page". You don't need to use super if you don't want to #}

A: I usually solve this with a mixin:
class TitleMixin(object):
    """Pass a defined title to context"""

    title = None

    def get_title(self):
        return self.title

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['title'] = self.get_title()

        return context

In you views, you can then do:
class BlogIndex(TitleMixin, ListView):
    title = 'Blog entries'

class EntryDetail(TitleMixin, DetailView)
    def get_title(self): # for dynamic title, such as coming from a model field
        return self.object.title


text:
Q: Besides dim regularization, what are the advantages of Euclidean QFT? Initially, I saw Wick rotation as a useful trick to apply dimensional regularization, but then I learned about instantons and how they only exist in Euclidean Yang-Mills.
Also, I heard that path integrals are "more well-defined" in Euclidean spacetime.
What are the other advantages?

A: It is very good question!
Besides some technical advances, that you already presented in question, first of all, very important to realise statement:

The Osterwalder-Schrader reconstruction theorem states that correla-
tors in a reflection positive Euclidean QFT can be analytically continued
to give Wightman functions that are tempered distributions on Minkowski
space $R^{d−1,1}$.

See, for example, section 3 of Lorentzian methods in conformal field theory
Slava Rychkov. Nowadays, these ideas extensively studied in CFT, see also this. Main idea is very illustrative:

Unitary Lorentzian CFTs are related to reflection-positive Euclidean
CFTs by Wick rotation. This is the Osterwalder-Schrader reconstruction
theorem. Thus, in
principle, everything about a Lorentzian CFT is encoded in the usual CFT
data (operator dimensions and OPE coefficients) that can be studied in
Euclidean signature. However, many observables, and many constraints
on CFT data are deeply hidden in the Euclidean correlators.

Also, it's very important to realise, that Euclidean QFT are used in condensed matter physics. For example, it is useful tool for describing of critical phenomena.For introduction, one can consult
David Tong: Lectures on Statistical Field Theory.


text:
Q: Which is faster in SQLite in memory databases: no indexes, loading into an indexed table or building the index after load? I'm loading a big dataset, about 9Gb into a ":memory:" database using SQLite. Right now, I have a python script that loads the data from .csv files (doing some other stuff on a line by line basis). I then need to do some joins on two big tables. Will indexing the columns I'm joining on make a difference if the database is in-memory? If so, is it better to create the table with an index before loading data into it, or build an index just before the join? And finally, will it make a difference speed-wise if I specify types for the columns?

A: Indexing will help: searching through all records of a table
is still slower than looking up in an index with a binary search.
If you create the index before loading the data,
the index has to be updated for every inserted record.
In SQLite, column types do not matter except for
type affinity.
Having no column types declared will be as fast as having correct types;
you would get the added expense of type conversions only if you managed
to declare wrong types for the columns.


text:
Q: How can I accept user input differently from the same line in C++? I have an assignment for my intro C++ class to make a program that has a user select C, D, or E to process a check, deposit a check, or end the program respectively. The professor specified that if a user chooses C or D, he would like to accept both the selection and the amount of money in the same line. For example, if a user wants to deposit a check for $20, they would enter "D 20" in one line. I have it set up as such:
cout << "Enter the beginning balance:\n\n";
cin >> balance;

cout << "Commands:\n";
cout << "C - process a check\n";
cout << "D - process a deposit\n";
cout << "E - end the program\n\n";

while (choice != 'E')
{
    cout << "Enter a transaction:\n";
    cin >> choice >> amount;

Followed by a switch statement. The code itself works properly when entering C or D, but when I go to enter E to end the program, it will only work if I add a number to the end, because the line asking for input wants a char and a float. However, in the example output my professor showed, you could just enter E and it would terminate. Is there any way around this? How can I set it up so it accepts E differently from C and D?
EDIT: Here is the switch statement:
switch(choice)
{
    case 'C':cout << fixed << setprecision(2);
             cout << "Processing check for $" << amount << endl;
             balance = processCheck(amount, balance);
             cout << "Balance: $" << balance << endl;
             break;
    case 'D':cout << fixed << setprecision(2);
             cout << "Processing deposit for $" << amount << endl;
             balance = depositCheck(amount, balance);
             cout << "Balance: $" << balance << endl;
             break;
    case 'E':cout << "Processing end of month\n";
             cout << "Final balance: $" << balance << endl;
             break;
    default : cout << "Invalid choice\n";
}

A: Already answered in comments, but anyway:
Replace this code
cin >> choice >> amount;

by gradual and conditional input code:
cin >> choice;
if (choice == 'C' || choice == 'D')
    cin >> amount;


text:
Q: URL design in node.js routing I am currently trying to figure out how can I re-design an incoming url request in node.js and read the parameters from there.I am using restify.
In my router.js :
server.get('/myDomainName/myService/:location/:userId',myFunction);

I am getting the "location" and "userId" as parameter from here and further processing.
This is working perfectly. But I need to redesign the URL like ,
/myDomainName/myService?location={someLocation}&userId={someID}.

So, I have designed the URL like this :
/myDomainName/myService?location=:x&userId=:y

But when I am trying to read the value of x and y (console.log(request.params.x)) , they are undefined. I need to use that x and y value for further processing.
What I am doing wrong here for URL design ? How can I implement this ?
Thanks in advance.

A: Yo can set the url like:
/myDomainName/myService
and get the params from req.query.location and req.query.userId
This might help you: http://expressjs.com/api.html#req.query

A: Query string is not included in the route path, its available in req.query. Just ignore query string when designing the route path.


text:
Q: VMware vCenter Server Questions I plan on deploying a cluster of 2 physical servers running vSphere. The VMs in this cluster will be ran in fault tolerance mode. Can the vCenter server be ran as a appliance on the vSphere cluster, or does it require its own server separate from the cluster? Thanks!

A: We run ours in the cluster. We don't have too many issues.
See: http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=2003790 for vecenter installation best practices
and http://kb.vmware.com/selfservice/microsites/search.do?cmd=displayKC&docType=kc&docTypeID=DT_KB_1_1&externalId=10087 for special considerations related to running vcenter in a virtual machine.
If you have the resources on the two hosts, run vcenter as a VM. If you are tight on resources... you could push vcenter to a physical.

A: It runs as an appliance on one of your hosts. The only time when you wouldn't do this is if you were running hundreds of hosts and vCenter requires more and more RAM to function.


text:
Q: Does to good to do string concatination at SSRS report or its good to use SQL query for that? I am working on SSRS report and I have some column values to be concat while displaying in the report. So does to advisable to do that at report end or I have to do it at SQL query and bind that value directly to the report.
I am having 4 columns that I have to concat to single column while binding it to report.
there are three different ways to do that,

*

*Can do at SQL query to get combined column.

*Can create expression while binding dataset to tablix.

*Create a calculated field in dataset and bind that to my tablix.

from above three which one is advisable to get better performance.

A: This question is very broad but let me put it this way.
If you put business rules in the database then they can be consistently reused by many things beyond SSRS, for example, Excel, Power BI, data extracts
The downside is that it is often more technically difficult to consistently apply rules at a lower level like this. In other words you need a SQL Developer to do this properly rather than if you did the calc in SSRS, in which case you just need a SSRS developer.
So if you have a team full of SSRS developers, then it's going to be easier to create and maintain rules in SSRS, but the downside is these rules can't be reused by anything else.
Short answer: do it in a view in the database unless this is going to be difficult to maintain because your team doesn't have any SQL skills.


text:
Q: Using FOR loop for finding out the sum of variables? I have a data frame that has 6,497,651 observations of 6 variables that I got from the National Emissions Inventory website and it has the following variables:
fips    SCC       Pollutant     Emissions    type    year
09001   10100401  PM25          15.14        POINT   1999
09001   10100402  PM25          234.75       POINT   1999

Where fips is the county code, SCC is name of the source string, Pollutant is the type of pollutant (PM2.5 emission in this case), Emissions indicates the amount of the pollutant emitted in tons, type is the type of source where pollutant was emitted (road, non-road, point, etc) and year notes down years from 1999 to 2008.
Basically, I have to plot a simple line plot to showcase the change in the level of emissions according to each year. Now, the year 1999 alone has over a thousand observations; same goes for the rest of the years till 2008. The problem is not at all difficult since I can easily form a new data frame for each year with the sum of all the emissions recorded and then row bind all those subsetted data frames. But a more efficient and tidier way to accomplish this might be to use the FOR loop where I can calculate the sum of all the values under 'Emissions' according to each year and store all that information into a new data frame, but I am stuck on where to start. How do I enter the exact syntax that will calculate the sum of values according to each year? I should be having a data frame that looks something like this:
Year    Emissions

Where Emissions notes down the sum of values of all emissions in that specific year.

A: data.table package is probably the most efficient package to handle things like that. The syntax to calculate sum of emissions for every year would be like that (assuming your data is stored in dt):
library(data.table)
dt=data.table(dt)
dt[,.(Emissions=sum(Emissions)),by=year]

A: A dplyr/ggplot option.  We group by 'year', get the sum of 'Emissions' using summarise and plot with ggplot.
library(dplyr)
library(ggplot2)
df1 %>%
   group_by(year) %>%
   summarise(Emissions=sum(Emissions)) %>%
   ggplot(., aes(x=year, y=Emissions))+
   geom_line()

Or this can be done directly within ggplot
ggplot(df1, aes(x=year, y=Emissions)) +
                stat_summary(fun.y='sum', geom='line')


text:
Q: how to kill process handle? https://learn.microsoft.com/en-us/sysinternals/downloads/handle
It can be awkward using a translator. sorry
https://learn.microsoft.com/en-us/sysinternals/downloads/handle
I am trying to kill process' handle with cmd.
name of the program is winbaram.exe
The name of the handle you are trying to kill is \Sessions\1\BaseNamedObjects\Nexon.SingleInstance
I want to work like the picture with cmd.
enter image description here
How should I type the cmd command line?
set HANDLE_PATH=C:\handle
set PROCESS_NAME=winbaram.exe


text:
Q: How to remove spacing in contempo blogger theme and make the sidebar visible in screen above 1024 px How to remove spacing in contempo blogger theme and make the sidebar visible in screen above 1024 px, the tutorials given on the net do not work properly.

A: I think what exactly you are looking for is "to show sidebar in screen which are smaller then 1440px but greater then 1024px".
If that is the case here is the post that might help you in making the suitable changes in CSS of your site to make it look the way you want it to look : Link
So basically Override the default css with our own :
  @media screen and (max-width: 1024px) {
  .sidebar-container {
    bottom: 0;
    position: fixed;
    top: 0;
  }
  .sidebar-container {
    left: 0;
    right: auto;
  }
  .sidebar-container.sidebar-invisible {
    -webkit-transition-timing-function: cubic-bezier(0.4,0.0,0.6,1);
            transition-timing-function: cubic-bezier(0.4,0.0,0.6,1);
  }
  .sidebar-container.sidebar-invisible {
    -webkit-transform: translateX($(sidebar.width * -1));
        -ms-transform: translateX($(sidebar.width * -1));
            transform: translateX($(sidebar.width * -1));
  }
 .page_body{margin-left: 5%;margin-right: 5%;}

}

Followed by adjusting the margins:
@media screen and (max-width: 1439px) {
    .page_body{margin-left: 250px;}
}

A: This can be done using ONLY css. Edit it from your template html editor page. Link your site and I could help you. Right click > Inspect element or press F12 in your browser and start playing around with the HTML and CSS styles on elements in your page.


text:
Q: Embedding a JRE in a Swing application for Mac OS X I must ship a swing application with an embedded JRE. A zipped archive with application + JRE + .bat/.sh did the trick for Windows and Linux. Users download the zip, unzip it, and launch the application. Perfect.
But now, I must provide the same thing for Mac OS X. I have read / was told a lot of different things on that matter (forbidden to distribute a JRE on Mac, the contrary, there is always a JRE on Mac, etc...), so I'm really confused about what I can possibly do.
Does anybody already did such a thing? How did you solved the Mac application deployment? As a bonus, what is the best format to distribute my application in Mac (zip?)?

A: Have a look at the appbundler project on java.net.  It provides an Ant task that will package your application up as a normal Mac .app bundle, and can optionally include an embedded JRE.
The whole Java landscape on Mac is a bit of a mess at the moment as we're still in the transitional period where Java 6 releases are supplied and maintained by Apple and Java 7 releases come direct from Oracle.  The jarbundler project referred to by a_horse_with_no_name is for wrapping up a JAR as a .app bundle that will run on the Apple-supplied Java 6 that is included with Mac OS X 10.5/6/7, but not on Oracle Java 7, conversely appbundler targets Oracle Java 7 and its .app bundles won't run on Java 6.
If you want to target recent Macs running 10.7 or 10.8, and in particular if you want to distribute your app via the Mac App Store, then you should use appbundler and bundle a copy of the JRE.  If you don't want to distribute via the store then the embedded JRE is optional.  If your app can run on Java 6 then targetting Apple Java 6 with jarbundler will mean your app can run on older (<= 10.6) Macs.  But then anyone with a more recent Mac that has only Java 7 will be prompted to download and install Java 6 when they try and run your app.
It's fine to distribute the .app in a .zip archive, as long as everything in the Contents/MacOS directory (and the appropriate files in the embedded JRE if applicable) inside the app is marked with execute permission in the zip file.  If you're building with Ant you'll need to use <zipfileset>s with the right filemode.

A: The easiest approach uses the same JAR as any other platform, deployed via Java Web Start. I've never tried using it to install a JRE.
The best approach to provide a more Mac friendly experience requires you to wrap your JAR(s) in an application bundle, discussed in the article's cited here. The preferred delivery format is a compressed disk image, .dmg.
The article Java Deployment Options for Mac OS X compares both options. This game is an example that can be launched either way.
Addendum: For the curious, the Mac OS X Finder treats .jnlp files  as documents, opened with the JWS launcher by default. I keep a folder of some frequently used .jnlp files in a dock folder for quick access. The Java Preferences control panel permits managing cached applications. Choosing to install a shortcut creates a simple Mac Application bundle in the destination folder, and the included Info.plist can be edited just like any other. The decision to customize the .plist hinges on what features the application needs: screen menu bar, dock name and icon, JNI path, etc.

A: I think you can safely assume the JRE is already present on a Mac.
The best format (so I'm told - I'm not a Mac user myself) is a tar.gz (to preserve file attributes) of an "App" bundle.
You can use the "jarbundler" ( http://sourceforge.net/projects/jarbundler/ ) to create a proper Mac "bundle" that can be extracted without further ado. Make sure the Stub that is included in the bundle is marked as "executable" from within the Ant tar task.
I think there are some problems if more than one JRE is installed. In that case the correct Stub must be used to start the JRE version that your application needs. If I recall correctly this Stub is located at /System/Library/Frameworks/JavaVM.framework/Resources/MacOS/JavaApplicationStub
There is a page that indicates that there might be problems with Java7 and the jarbundler: http://informagen.com/JarBundler/


text:
Q: Can you declare an InputScope in a WebBrowser? I'm aware of the property InputScope in a TextBox, but is it possible to use in a WebBrowser? I actually just want to get rid of the autosuggestions, if that is possible without changing the InputScope.

A: You have to set the input scope for each input in the HTML. This way the specific keyboard for each input type will be displayed.
See HTML5 Input Types.
You can visit this page to try them.
Note that this will only work with Windows Phone 8 (IE10), because IE9, the browser in Windows Phone 7, doesn't implement it.

A: InputScope is available in XAML through System.Windows.Input in System.Windows.dll, so anywhere you use it whether it web / desktop / WP7 / WP8, it is available. See MSDN.
Although this tutorial for inputscope is for WP7, much of the theory applies to WP8
P.S. Where is your autocomplete / autosuggest code? If you post it we can possibly help you further, e.g. see this link for how to fiddle with autosuggest on android
EDIT: Ah in light of your comment; hopefully this answers your question in conjunction with the other answers supplied here is it possible to set inputscope from a webpage


text:
Q: Django filtering in views.py with a session variable I sessions up and running and currently I'm getting the variable 'context_number' set in the browser. In the view I would like to filter on this variable. So I have this in my views.py.
def allcontexts(request):
    allcontexts = Context.objects.all()
    return render(request, 'context_manager/context_manager.html',
    {
    'allcontexts':allcontexts,
    })

In order to filter I change the second row to the following
    allcontexts = Context.objects.filter(context_number=____)

In the blank I want to insert the context_number variable, so context_number[dbcolumn] = context_number[session variable]
I can't seem to figure out the correct syntax, any ideas?

A: You can access session variables using request.session.get() syntax:
allcontexts = Context.objects.filter(context_number=request.session.get("context_number"))


text:
Q: How to fix Unterminated expression in f-string; missing close brace in python? I want to use f string formatting instead of print. However, I get these errors:
Unterminated expression in f-string; missing close brace
Expected ')'
var="ab-c"
f"{var.replace("-","")}text123"

I tried to use single quote f'' and also double brackets but neither of them worked. Any idea about how to fix this?

A: Use single quotes:
var="ab-c"
f'{var.replace("-","")}text123'

# display abctext123

A: For f"{var.replace("-","")}text123", Python parses f"{var.replace(" as a complete string, which you can see has an opening { and opening (, but then the string is terminated.  It first expected a ) and eventually a }, hence the error you see.
To fix it, Python allows ' or " to enclose a string, so use one for the f-string and the other for inside the string:
f"{var.replace('-','')}text123"

or:
f'{var.replace("-","")}text123'

Triple quotes can also be used if internally you have both ' and "
f'''{var.replace("-",'')}text123'''

or:
f"""{var.replace("-",'')}text123"""

A: var = "ab-c"
f"{var.replace('-','')}text123"

always use a different quote character than the ones inside the f-string


text:
Q: Телеграм бот для добавления задач в Asana, с чего начать? Покопался в документации Asana, нашел реализацию слушателей (web-хуков) для событий в самой Asana, мне же нужно для теста создать бота в телеграм, который будет добавлять задачи, помогите пожалуйста с чего начать копать?

A: Пример кода бота с применением Asana API:
import os
import json
from flask import Flask, request
from asana import Client
from pyrogram import Client as TelegramClient

app = Flask(__name__)
telegram_client = TelegramClient("my_telegram_bot")
asana_client = Client.access_token("my_asana_access_token")

# function to handle incoming webhooks from Asana
@app.route("/webhook", methods=["POST"])
def handle_webhook():
    data = json.loads(request.data)
    task_name = data["data"]["name"]
    task_url = data["data"]["html_url"]

    # send message to Telegram channel with task name and url
    telegram_client.send_message("my_channel_username", f"New task added: {task_name}\n{task_url}")
    return "OK"

# function to handle commands from Telegram
@telegram_client.on_message(command="addtask")
def handle_add_task(client, message):
    task_name = message.text.split(" ", 1)[1]
    new_task = asana_client.tasks.create({"workspace": "my_workspace_id", "name": task_name})
    message.reply(f"Task added with id: {new_task['id']}")

if __name__ == "__main__":
    # start the Telegram bot
    telegram_client.run()
    # start the Flask app to handle webhooks
    app.run(port=int(os.environ.get("PORT", 5000)))

Это телеграм-бот для добавления задач. Что я тут сделал:
Импортировал os, json, Flask, asana, pyrogram.
Создал экземпляры классов Flask и TelegramClient, а также объект Asana, используя токен доступа.
Создал функцию handle_webhook() для обработки входящих webhooks из Asana. Эта функция использует метод POST и обрабатывает данные из webhook, извлекая имя задачи и URL. Затем она отправляет сообщение в Telegram канал с именем задачи и URL.
Заключительный шаг - добавил функцию handle_add_task() для обработки команд из Telegram. Эта функция вызывается, когда пользователь отправляет команду "/addtask" и имя задачи. Функция использует Asana API для создания новой задачи и отправляет ответ пользователю с ID новой задачи.


text:
Q: Delete a row from db after it has existed for 3 minutes. SQL CREATE EVENT delete_views
    ON SCHEDULE
      EVERY 1 SECOND_MICROSECOND
    DO BEGIN
      DELETE views WHERE date < DATE_SUB(NOW(), INTERVAL 3 MINUTE_SECOND);
    END;

I got this code above from another stackoverflow post and it does not work.
When I say it doesn't work I mean that there is an error that says there is a syntax error near WHERE date < DATE_SUB(NOW(), INTERVAL 3 MINUTE_SECOND)
(This is for a function so that it makes it so that people can not spam a post and get a bunch of views for it). But in otherwords, I want to have an event that repeats itself every second or microsecond (doesn't matter that much it just has to be a very short time) and it will delete a row that has existed for over 3 minutes in a table (views).
The table row contains the columns: user_id, video_id, date (current time stamp)

A: Don't delete rows, randomly through the day.  Just control access to the data through a view:
create view v_t as
    select t.*
    from t
    where t.date > now() - interval 3 minute;

Voila!  Only the most recent data is available.
You can then delete (if necessary) at your leisure, preferably in off-hours when the load on the database is minimal.


text:
Q: How can I find the generic name of a font in the .NET framework? I am searching for a way to go about finding the generic face name (Sans-Serif, Serif, Monospace, Cursive, Fantasy) for a given font using the .NET framework.  My language of preference is C#, but I've been writing source code for nearly 15 years, so if you can give me an example in any modern language, I can go about translating it, myself.
[Edit - Clarification]
I need a way to determine which of the generic font families (Sans-Serif, Serif, Monospace, Cursive, or Fantasy... and possibly even Symbol) any given System.Drawing.Font object belongs to.
As an example, if I create a font from the following line of code:
System.Drawing.Font font = new System.Drawing.Font( "Serif", 12f, System.Drawing.GraphicsUnit.Point );

The resulting font would likely be the 12-point "Times New Roman" font.  But I don't want "Times" or "New Roman" or even "Times New Roman", I need to know that it's in the "Serif" family.

A: You can go with linq
Here the new list of font of Microsoft you looking for.
Example:

*

*Sans-Serif or Serif = Microsoft Sans Serif

*Monospace = Batang

var font = FontFamily.Families
                     .Where(c => c.Name == "Microsoft Sans Serif")
                     .FirstOrDefault();

UPDATE:
Heres you're looking for the Generics font
http://msdn.microsoft.com/en-us/library/system.drawing.fontfamily.aspx
var font = FontFamily.GenericMonospace;

A: This is a typographic font classification that is not directly available from the Windows font api functions.  A possible backdoor is GetFontData(), it lets you access TrueType tables for the font directly.  Lots of info there, I'm however not aware of this exact kind of info being available.  You can have a look for yourself in the specification of the tables.

A:
A way to go about finding the generic face name for a given font.

Assuming you have a Font object, you can get the font family name like this:
Font font;
string familyName = font.FontFamily.Name;

*

*FontFamily documentation

*Constructing a font

To respond to your edit and comment: as far as I could find, no information on the font type is stored in a font. For example, I could design a font and classify it as Fantasy, while you classify the font as Sans-serif. Because there is no clear definition for what each class entails, it is not a property of the font.
There is a system-wide default monospace, sans-serif and serif font (through FontFamily) but that won't tell you whether any font has serifs. Using font.Style you can find out whether a font is cursive, underlined, etc. Through this answer you can find out whether a font is monospaced.


text:
Q: Proof: homogeneous second order differential equation This is an homogeneous second order differential equation
$Ay'' + By' + Cy = 0$
Its solution can be retrieved assuming $y = e^{rx}$: in this way, we will have
$y = e^{rx}$
$y' = re^{rx}$
$y'' = r^{2}e^{rx}$
replace:
$Ar^{2}e^{rx} + Bre^{rx} + Ce^{rx} = 0$
$(e^{rx}) (Ar^{2} + Br + C) = 0$
The last is a second degree equation. One can manifest a case in which the roots of this equation are real and coincident. If $r_1 = r_2$, a solution will be the function $y_1 = e^{rx}$ surely. At this point, we must build a linearly independent second solution: we take, for example, $y_2 = xe^{rx}$.
I should prove that $y_2 = xe^{rx}$ is a solution as well: how can I do?
Thank you in advance

A: The_lost is right in his comment, we show $xe^{rx}$ solves the equation
$Ay''(x) + By'(x) + Cy(x) = 0, \; A \ne 0, \tag 0$
by simple substitution (here I assume $A \ne 0$ to ensure (0) is a bona-fide second order equation); however, it helps to know something about $r$ first, to wit:
According to the quadratic formula, the roots of
$Ar^2 + Br + C = 0, \; A \ne 0, \tag 1$
are
$r_1, r_2 = \dfrac{-B \pm \sqrt{B^2 - 4AC}}{2A}; \tag 2$
we see that there is one root
$r = r_1 = r_2 = -\dfrac{B}{2A} \tag 3$
precisely when
$B^2 - 4AC = 0, \tag 4$
or, since $A \ne 0$,
$C = \dfrac{B^2}{4A}, \tag 5$
or
$\dfrac{C}{A} = \dfrac{B^2}{4A^2} = \left ( \dfrac{B}{2A} \right )^2; \tag 6$
for then,
$Ar^2 + Br + C = A \left (r^2 + \dfrac{B}{A} r + \dfrac{C}{A}  \right )$
$= A \left ( r^2 + \dfrac{B}{A} +  \left ( \dfrac{B}{2A} \right )^2 \right ) = A \left ( r + \dfrac{B}{2A} \right )^2; \tag 7$
now if
$y(x) = x e^{rx}, \tag 8$
we calculate:
$y'(x) = e^{rx} + rxe^{rx}; \tag 9$
$y''(x) = re^{rx} + re^{rx} + r^2xe^{rx} = r^2xe^{rx} + 2re^{rx}, \tag{10}$
whence, via (3),
$y''(x) + \dfrac{B}{A}y'(x) + \dfrac{C}{A} y(x) =  r^2xe^{rx} + 2re^{rx} + \dfrac{B}{A}(rxe^{rx} + e^{rx}) + \dfrac{C}{A} x e^{rx}$
$= \left (r^2  + \dfrac{B}{A}r  + \dfrac{C}{A} \right ) xe^{rx} + \left (2r + \dfrac{B}{A} \right )e^{rx}$
$= \left ( r + \dfrac{B}{2A} \right )^2 xe^{rx} + 2 \left (r + \dfrac{B}{2A} \right ) e^{rx} = 0; \tag{11}$
it then follows that
$Ay''(x) + By'(x) + Cy(x) = A \left (y''(x) + \dfrac{B}{A}y'(x) + \dfrac{C}{A} y(x) \right ) = 0 \tag{12}$
as well.

A: $$y_2 = x\exp(rx)$$
$$y_2' = (rx+1)\exp(rx)$$
$$y_2^" = (r^2x+2r)\exp(rx)$$
Substitute these into the original equation.
$$\exp(rx) (Ar^2x+2Ar+Brx+B+Cx)=0$$
$$\exp(rx) ((Ar^2+Br+C)x+2Ar+B)=0$$
For the $r$ that you found, we already know that $Ar^2+Br+c=0$.
Since this is a repeated root, the derivative also vanishes, that is $2Ar+B=0$.


text:
Q: How to read cookie expiration in dot net core? I see you can set the expiration using CookieOptions when appending a new cookie to the response. However, HttpContext.Request.Cookies returns an IRequestCookieCollection, which only seems to give you key/value pairs.
Is there a way to read the CookieOptions (specifically the Expiration) for request cookies?
I'm using .Net Core (1.0.0-preview2-003131)
NOTE: I need to read the expiration of an arbitrary cookie in request processing, not the expiration of the framework generated auth cookie.

A: I'm getting that by reacting to the event "OnValidatePrincipal"
app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
...
Events = new CookieAuthenticationEvents
{
OnValidatePrincipal = CookieAuthenticationEventHandler.ValidatePrincipalAsync
}
});

And then I can access, once the principal is validated, when the cookie will expire in my ValidatePrincipalAsync with the property context.Properties.ExpiresUtc
To be able to get that expires property later in my controller, I'm adding it in my HttpContext this way:
context.Request.HttpContext.Items.Add("ExpiresUTC", context.Properties.ExpiresUtc);

But I'm not really happy with that part, maybe someone can give you a better way to access it directly in the controller without having to get it from the OnValidatePrincipal.

A: No, HTTP does not include any details about cookies sent on requests, only their name and value. The auth cookie workaround only works because the expiration is also embedded in the value.


text:
Q: Embed the Google assistant in a Windows computer - device instance ID not generated while running the sample code I am trying to get Google Assistant installed on a Windows computer, following the instructions from Set Up Hardware and Network Access (Google Assistant SDK).
I have been able to complete all but the last step. I am at the point of running the sample code. https://developers.google.com/assistant/sdk/guides/service/python/embed/run-sample?refresh=1.
In this last step a 'device instance ID' should be generated, but that does not happen. See the screenshot:

The error message states that the client type needs to be specified as SDK_LIBRARY or SDK_SERVICE. However, when registering the model the '--client-type [SERVICE|LIBRARY]' option is not allowed (see Registration Tool Help).
How can I run the sample code ... so that it generates a 'device instance ID'?
My problem seems to be similar to an issue reported by another user. This user reported the issue however for the Raspberry Pi, while I am reporting it for a Windows computer. See Raspberry Pi and Google Voice client type

A: Navigate to the folder you downloaded the client secrets JSON file to, and paste in the following code:
googlesamples-assistant-devicetool --project-id PROJECT_ID register-model --model 'my-model-identifier' --type LIGHT --trait action.devices.traits.OnOff --manufacturer 'Assistant SDK developer' --product-name 'Assistant SDK light' --description 'Assistant SDK light device'

NB: Replace all details with the correct corresponding details.


text:
Q: ValueError: Number of features of the model must match the input. Model n_features is 10 and input n_features is 7 in Random Forest Im trying to build a prediction model and im getting the following error. How do i get this fixed?
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-11-cd63269e2c86> in <module>
      8
      9 # Make predictions on test data using the model trained on original data
---> 10 baseline_predictions = rf.predict(original_test_features)
     11
     12 # Performance metrics

~\AppData\Local\Continuum\anaconda3\lib\site-packages\sklearn\ensemble\forest.py in predict(self, X)
    691         check_is_fitted(self, 'estimators_')
    692         # Check data
--> 693         X = self._validate_X_predict(X)
    694
    695         # Assign chunk of trees to jobs

~\AppData\Local\Continuum\anaconda3\lib\site-packages\sklearn\ensemble\forest.py in _validate_X_predict(self, X)
    357                                  "call `fit` before exploiting the model.")
    358
--> 359         return self.estimators_[0]._validate_X_predict(X, check_input=True)
    360
    361     @property

~\AppData\Local\Continuum\anaconda3\lib\site-packages\sklearn\tree\tree.py in _validate_X_predict(self, X, check_input)
    400                              "match the input. Model n_features is %s and "
    401                              "input n_features is %s "
--> 402                              % (self.n_features_, n_features))
    403
    404         return X

ValueError: Number of features of the model must match the input. Model n_features is 10 and input n_features is 7

Here is the code that i use.....
# Find the original feature indices
original_feature_indices = [feature_list.index(feature) for feature in
                                      feature_list if feature not in
                                      ['feature1', 'feature2', 'feature3']]

# Create a test set of the original features
original_test_features = test_features[:, original_feature_indices]

# Make predictions on test data using the model trained on original data
baseline_predictions = rf.predict(original_test_features)

# Performance metrics
baseline_errors = abs(baseline_predictions - test_labels)

print('Metrics for Random Forest Trained on Original Data')
print('Average absolute error:', round(np.mean(baseline_errors), 2), 'degrees.')

# Calculate mean absolute percentage error (MAPE)
baseline_mape = 100 * np.mean((baseline_errors / test_labels))

# Calculate and display accuracy
baseline_accuracy = 100 - baseline_mape
print('Accuracy:', round(baseline_accuracy, 2), '%.')

Im trying to build a prediction model for a certain set of data with random forest classifier. However i am getting this error message stating that the number features of the model does not match the input.

A: your model has trained using dataset which have 10 features and,now your prediction set, which is original_test_features has only 7 features. That's why you get features mismatch error.check the original_test_features and make sure all features are match with model training set.


text:
Q: How do I make Sphinx stop ignoring spaces? I'm using Sphynx and ThinkingSphynx in my Rails project. Is there any way I can make Sphynx stop ignoring spaces so that "Foo " key would find me "Foo Bar" and wouldn't find me, for example,  "foo@bar.com"  ?

A: Sphinx is actually treating @ as a non-indexed character, same as ., so they become word separators. Thus, "foo@bar.com" is actually indexed as "foo bar com".
If you want "foo@bar.com" to be kept exactly as it is, then you should add @ and . to your charset_table value in config/thinking_sphinx.yml for each environment. My example here is the default set, plus the unicode values for those two characters at the end (40 is @, AD is .).
development:
  charset_table: 0..9, A..Z->a..z, _, a..z, U+410..U+42F->U+430..U+44F, U+430..U+44F, U+401->U+451, U+451, U+0040, U+00AD

An alternative is to add those characters to the ignore_chars option instead. This way, they're deleted in the indexed data, so "foo@bar.com" becomes "foobarcom":
development:
  ignore_chars: U+0040, U+00AD

Keep in mind that both of these settings will impact those characters everywhere in your indexed data, not just in email addresses (and no, you can't set them on a per-field basis).

A: I've added blend_chars option to indice and everything started working as needed:
set_property :blend_chars => 'U+20, @, .'

U+20 is actually a space.


text:
Q: Difficulty navigating through the various screens of my flutter app I need to scroll through my app screens. The Navigator is not enough for me because there are cases where I should go back to a screen that has never been created.
Just think of a 5-step process: if the application is stopped during the third step, the next time it starts it will resume from this and not from the first.
By doing this, if I wanted to go back from the third process, I couldn't do it because the third screen was created directly.
I've tried working with a PageView but that's not what I'm looking for. I have to somehow change the screens stack or launch multiple screens at the same time when the app starts.

A: You can use auto_route or go_router to push multiple pages at once. The setup varies between the two but the end result is the same - instead of pushing one page onto the navigator stack, you can push a whole list of them.
For example, if you know what page the user left off on, you can push them back to that screen when the app first opens:
AutoRouter.of(context).pushAll([
  PageOneRoute(),
  PageTwoRoute(),
  PageThreeRoute(),
])


text:
Q: Find Next in texteditor I am trying to code the search functionality in JTextArea.  I did it for find, but find next is where i am stuck.  The JOptionPane should not get closed until all the words are found in the JTextArea.
private void findActionPerformed(java.awt.event.ActionEvent evt) {
    findString = JOptionPane.showInputDialog(null, "Find What", "Find", JOptionPane.INFORMATION_MESSAGE);
    text = editorTextArea.getText();
    index = text.indexOf(findString, 0);
    editorTextArea.setCaretPosition(index);
    editorTextArea.setSelectionStart(index);
    editorTextArea.setSelectionEnd(index + findString.length());
}

A: Use non-modal JDialog and dispose it manually when you are done with the last find. For more details on JDialog check at http://docs.oracle.com/javase/tutorial/uiswing/components/dialog.html