text:
Q: SQL ISSUE- Help in query count + min Tables:
[dbo].[Dealer]
[number] [firstName] [surName]   [birthDate] [startWorkingDate] [ID]
Num Dealer|full name of Dealers| birthdate | date + time       | id number
[dbo].[Game]

[gameTypeName] [gameStartDateTime] [gameEndTime] [DealerInGame]
name of game  | date + time      | date + time| same numbers like [Dealer].[number]

What I want a query to do:
query that returns the dealer (employee number and full name), who participated in the smallest amount of games.
SELECT top 1 number,firstName +' '+ surName as 'full name' FROM Dealer
where  exists (SELECT gameTypeName,COUNT( gameTypeName)  FROM Game
GROUP BY gameTypeName)

The query only brings me the first one that has the smallest amount of games, but if there are 2 or more dealers with the same value then it doesn't show them all.
What's wrong?

A: I don't think, MySQL support the TOP operator as SQL Server does, but you can get the first record using LIMIT as below:
SELECT number,
       firstName +' '+ surName as 'full name'
FROM Dealer
where  exists (SELECT gameTypeName,COUNT( gameTypeName)
                 FROM Game
        GROUP BY gameTypeName)
LIMIT 1;

A: Join the two tables, use COUNT(), and then use ORDER BY and LIMIT 1. This is the MySQL syntax for it:
SELECT number, CONCAT(firstName, ' ', lastName) AS fullName
FROM Dealer AS d
JOIN Game AS g ON g.DealerInGame = d.number
GROUP BY d.number
ORDER BY COUNT(*)
LIMIT 1

A: You can do the join :
select d.number, CONCAT(d.firstName, ' ', d.lastName) as fullName
from Dealer d inner join (
           select DealerInGame
           from Game
           group by DealerInGame
           having count(*) <= 1
      ) g on g.DealerInGame = d.number;

A: If you want all of the dealers with the smallest number of games, you will need to take the smallest number of games played and then find all the dealers with that number of games.
WITH GameCount as (
    SELECT
        DealerInGame,
        Count(*) Games
    FROM Game
    )

SELECT
    d.firstName + ' ' + d.surName fullName,
    d.number
FROM GameCount g
    LEFT JOIN Dealer d on d.Number = g.DealerInGame
WHERE g.Games = (
    SELECT Min(Games)
    FROM GameCount)


text:
Q: How to call a method on an element within a list that is contained in a Kotlin Flow I am wondering if there's a better way to call a method on an element within a list that is contained in a Flow. Currently i'm doing this but i don't like calling map() twice:
override fun getEarnings(): Flow<List<Transaction>> {
    return transactionDao.getEarnings().map {
        it.map { transaction -> transaction.asDomainModel() }
    }
}

the getEarnings() method defined in the transactionsDao:
@Query("SELECT * FROM transactions WHERE is_income = 1")
fun getEarnings(): Flow<List<DatabaseTransaction>>

A: Small add on to philip's answer, In your particular case you can replace the lambda with a callable reference to make the code more concise. this can be done as
.mapIterable(Transaction::asDomainModel)

A: I've created this extension for the same purpose:
inline fun <T, R> Flow<Iterable<T>>.mapIterable(crossinline transform: (T) -> R): Flow<List<R>> =
    map { it.map(transform) }

Usage:
fun getEarnings(): Flow<List<Transaction>> {
    return transactionDao
        .getEarnings()
        .mapIterable { transaction ->
            transaction.asDomainModel()
        }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I organize my functions to get something like class.draw.line() instead of class.drawLine I often use functions that are nicely organized into calls such as pygame.draw.circle. I want to follow this structure in my class but do not know how do so. I tried using a nested class but it was limited to its own scope rather than its parent's, which was necessary for it to function.

*

*How do I properly implement this feature?

*Alternatively, is it a bad idea to attempt to mimic this except for certain scenarios? What should I be doing instead?

A: Try this:
| pygame/
|   __init__.py
|   draw/
|     __init__.py
|     circle.py
|     rectangle.py

Or, you could do it this way.
| pygame/
|   __init__.py
|   draw.py

draw.py

def circle(*args):
    """ Draws a circle using *args """
    pass

def rectangle(*args):
    #  and so on
    pass

your_project.py

from pygame.draw import circle, rectangle
circle(args)
rectangle(args)

#  or
from pygame import draw
draw.circle(args)
draw.rectangle(args)

#  or
import pygame
pygame.draw.circle(args)

You may want to read https://docs.python.org/3/reference/import.html#regular-packages as you're making your final decisions.


text:
Q: Why is my recursive function updating a list (calculating fibonacci of n) I'm trying to learn about dynamic programming.  I've gone through an example of how to find the Fibonacci number of an inputn, while caching the result of each "new" call as I go.
I understand the order in which the function recursively calls: fib(5) -> fib(4) -> fib(3) -> fib(2) -> fib(1) -> fib(0) -> fib(1) -> fib(2) "Cache found" -> fib(3) "Cache found" for n = 5
I'm struggling to understand how the final fib(2) and fib(3) calls have access to the updated cache, as each call only returns an integer, not the list, and I don't think I have the list declared as a global variable.
I originally expected the list to behave like the integer x in my code, so would welcome explanations for how the values have been passed back up.
Code:
def fib(n, cache, x):
    print(n, cache)
    print("x: ", x)
    x += 1
    if n == 0 or n == 1:
        return n

    if cache[n] == 0:
        cache[n] = fib(n-1, cache, x) + fib(n-2, cache, x)
    else:
        print("Cache called on", n)

    return cache[n]

def main():
    n = 5
    x = 0
    cache = [0 for _ in range(n+1)]
    print(fib(n, cache, x))
    print(cache)
    print("x: ", x)

if __name__ == "__main__":
    main()

Output:
5 [0, 0, 0, 0, 0, 0]
x:  0
4 [0, 0, 0, 0, 0, 0]
x:  1
3 [0, 0, 0, 0, 0, 0]
x:  2
2 [0, 0, 0, 0, 0, 0]
x:  3
1 [0, 0, 0, 0, 0, 0]
x:  4
0 [0, 0, 0, 0, 0, 0]
x:  4
1 [0, 0, 1, 0, 0, 0]
x:  3
2 [0, 0, 1, 2, 0, 0]
x:  2
Cache called on 2
3 [0, 0, 1, 2, 3, 0]
x:  1
Cache called on 3
5
[0, 0, 1, 2, 3, 5]
x:  0

A: You passed the original of cache, rather than a copy (newly-built object).  Thus, each instance of fib is working with the same object.  An update in one instance is immediately available to the others.  See also here.

A: In python function arguments are "passed-by-object" (or pass-by-object-reference). It means that if you pass the list (a mutable object) to a function then elements of the list can be modified. But if you will assign the list by a new list then the list will not change in the caller's scope.
def list_scope(l):
    print(l, "id: ", id(l))
    l = [3, 4,5]
    print(l, "id: ", id(l))

def main():
    l = [1, 2, 3]
    print("id: ", id(l))
    list_scope(l)
    print("id: ", id(l))

main()

Output:
id: 4510275784
[1, 2, 3] id:  4510275784
[3, 4, 5] id:  4509275592
id: 4510275784

The id for l in list_scope before assigning list [3, 4, 5] is same as the id in main. It changes once [3, 4, 5] is assigned, but remain same in main.


text:
Q: Activate GCP windows server VM failed I created a windows 2012 server VM in GCP with 1 internal IP and 1 ephemeral external IP,
I can ping the the google KMS server 35.190.247.13,
but when I try activate the windows with
cscript \windows\system32\slmgr.vbs /dlv
cscript \windows\system32\slmgr.vbs /skms 35.190.247.13:1688
cscript \windows\system32\slmgr.vbs /ato

the last step prompt error "The Software Licensing Service reported that the computer could not be activated. No Key Management Service (KMS) could be contacted. Please see the Application Event Log for additional information."
Do I need to enable google private access in my VPC subnet even though I have an external IP?

A: ping is based upon ICMP, which is not associated with any transport layer (that's why it is impossible to ping a specific port). The command to test tcp/1688 connectivity rather is:
powershell.exe Test-NetConnection 35.190.247.13 -Port 1688

If this doesn't work, you have to permit this destination in the firewall ruleset:
Address: 35.190.247.13
Port: 1688
Protocol: TCP

See Windows Licensing.


text:
Q: Stationary Solutions of stochastic differential equations When does the stationary density of an homogeneous Markov process exist?

A: It is hard to be brief here, but I will try.
One answer is: when the corresponding stationary Fokker-Planck equation (aka forward Kolmogorov equation) has a nonnegative integrable solution. The density is then obtained by normalization of that solution. This is not a very good answer because FP equations are often not so easy to analyze.
In fact, it is hard to guess what is the question you really wanted to ask. For example, one may say that your question is twofold:
1) when is there an invariant probability distribution?
2) If it exists, is it absolutely continuous w.r.t. Lebesgue?
Existence is guaranteed if the drift prevents the trajectories from going to infinity so that they spend a lot of time in a compact set. Some of the relevant keywords are: Lyapunov-Foster functions, Harris recurrence. Among weakest known conditions guaranteeing existence of invariant distributions are those due to Veretennikov.
Given part 1), absolute continuity of the stationary distributions can essentially be deduced from absolute continuity of transition probabilities. This part is easy if your equations are elliptic and not so easy if the noise excites only some directions.
The analysis can be quite nontrivial depending on how bad your equation is, as a look at a recent paper http://arxiv.org/abs/0712.3884 might convince you.


text:
Q: Sort by distinct Stream API I have a following JourneyType class
public class JourneyType {

    private String hostId;

}

and a method
public void getHotsId(List<JourneyType> journeyTypeList) {
    journeyTypeList.stream().map(p -> p.getHostId()).distinct().sorted().collect(Collectors.toList());
}

Filter class I have already did stream. So I would like to sort by hostId. I am stuck, any help?

A: To sort the stream of JourneyType by a getHostId() method result you can supply your own Comparator
List<JourneyType> res = journeyTypeList.stream()
  .sorted(Comparator.comparing(JourneyType::getHostId))
  .collect(Collectors.toList());

If your objective is just to sort the original collection it's easier to use Collections class:
Collections.sort(journeyTypeList, Comparator.comparing(JourneyType::getHostId));


text:
Q: How to reverse onClick event? I wanted to add inner shadow to a search box when the user clicks on it so I used this simple code :
function shadow()
{
document.getElementById("search2").style.boxShadow="inset 0px 0px 12px 0px rgba(0,0,0,0.75)";
}

And the markup :
<input type="search" onClick="shadow()">

So that when you click on the search box, the "search2" div gets an inner shadow and it works.
But I want to know how to reverse this (remove the inner shadow) when the user unclick the search box and click elsewhere.
Thanks

A: You should be using the onfocus and onblur events.

*

*onfocus - fires when the user is in the textbox

*onblur - fires when the user leaves the textbox

In the onblur event you add
document.getElementById("search2").style.boxShadow = "";

The click event only fires when the user clicks the element.

A: You can do this without using any JavaScript at all, using the CSS focus: pseudoselector.  In your CSS styles, use this:
#search2:focus {
    box-shadow: inset 0px 0px 12px 0px rgba(0,0,0,0.75);
}

The advantage here is that it's less code and it will still work even in browsers without JavaScript enabled.  Here's a jsFiddle:  http://jsfiddle.net/5g9an/
It couldn't be simpler.  Well, I can't think of a simpler method, anyhow.

A: Use blur event:
<input type="search" onClick="shadow()" onBlur="removeShadow()">

function removeShadow(){
  document.getElementById("search2").style.boxShadow="none";
}


text:
Q: How do I iterate three or more arrays in the same Swift loop? Iterating one array:
for item in myArray {
    print(item)
}

Iterating two arrays:
for (item1, item2) in zip(myArray1, myArray2) {
    print(item1, item2)
}

But what about three or more arrays?

A: You can use it this way, below is for 2 arrays
zip([11,12,12], [12,13,14]).forEach { (i1, i2) in
    print(i1, i2)
}

if array length are same them you can use this, easy way
for index in 0...firstArray.count {
    print(firstArray[index]) //First Array
    print(secondArray[index]) //Second Array
    print(thirdArray[index]) //Third Array
}

Alternative way to workaround will be like this,
for index in firstArray.enumerated() {
    print(firstArray[index]) //First Array
    print(secondArray[index]) //Second Array
    print(thirdArray[index]) //Third Array
}


text:
Q: Can somebody log in to my system as www-data? The Apache2 install creates a user and group named "www-data" apparently with no password, blank. It uses this user account to run under.
Doesn't this create a security problem because if the account has no password, then somebody could just log in to my system as www-data?

A: No. Because the default shell for www-data is /usr/sbin/nologin.
Here's how it looks on one of the (Debian) servers I operate:
getent passwd | grep www
www-data:x:33:33:www-data:/var/www:/usr/sbin/nologin

And here is what happens when you try to change into that user:
sudo su www-data
This account is currently not available.


text:
Q: Why does Azure B2C return idp_access_token which is not a jwt? I have setup Azure B2C to return a claim called idp_access_token and according to this Microsoft documentation
https://learn.microsoft.com/en-us/azure/active-directory-b2c/tokens-overview
it should be a valid JWT. However it is not a valid JWT.
Why is that?
"exp": 1588112929,
"nbf": 1588109329,
"ver": "1.0",
"iss": "https://xxx.b2clogin.com/903e0c59-0e1d-4769-8a57-0caba1f561da/v2.0/",
"sub": "f11eaa2e-0bad-400a-864f-57f9daa70720",
"aud": "8ab24fa8-a5f2-4f7d-a1ad-31f21d7fb627",
"nonce": "defaultNonce",
"iat": 1588109329,
"auth_time": 1588109329,
"idp_access_token": "PAQABAAAAAAAm-06blBE1TpVMil8KPQ41KrxufgbIw-NxMJGBuFrfjebtTsSNCwe_5MK208-HdCSx2GkqvSr7LV7ZZiKD9p4z7Zl-NawHeA4DJiPxlnmZB43ObtstvlmwyDoVzTFxSjdOkGvCv5_7A5JuGqct7VBbp1US7HmC2YeS9xVO6HlNiYWlNu90HQwk8A05fnzYwfhcshWQ5JvblgtbkwP6dlK4r_PM9erowtW0LuWkEeucdbU_DfnnM75nFbL4Bo4o_-j5nReC7wBpx_dhVC5gDItLuvuQUruju-3ANDSNsSzlNrp6RCv1HOZtMohVbRB6GYDYS0222u7_hf4by-bQca2SIxWvSZ1UKCPUmnQ0Ji4lYCrkCPlKTOPaUaf1D6yZHbWJtqYkOBY-8uuf7961GyDceW_szZhX80AUkEmK5t9yMd7jB38nV5lvHI13roMzr8N-jWdPSOcLCLxSWIvNG7Inp_5wGM2yYSCTjWUnCTMR8-UkXCETUIU16bw2FkTJc1K_eZhAYw2UyQIzYejd-9gQhZrHyTE0ogApg-Qm4bYnW0XCHGe4MZjDKNuVu49OEGTOxUrn7g0Zh9dn6k6FNma7O02ERUItq2bmpYSyqsRxIase4-9tn_zEhoV-lT1mdIHCDXPLwsH...some more comes here
 ...

More background information:

*

*I'm using "Sign up and sign in v2 (Preview)" user flow

*As identity provider of the flow I have selected an Open ID Connect IDP configured to use the Azure AD of the same Azure subscription in which the Azure AD B2C resided.

A: Because this is the AAD blob used to hit the user info endpoint. You get this as an access token if you don't specify a resource (v1 AAD endpoint), or scope (v2 endpoint) as part of the auth request.

A: In order to get valid "idp_access_token", you have to set "v2.0" in metaurl of OpenId Identity Provider Configurations.
As you can not edit metaurl for previous identity provider, create new one with "v2.0" in metaurl.
Your metaurl will be look like this,
https://login.microsoftonline.com/**tenant-name**.onmicrosoft.com/v2.0/.well-known/openid-configuration
Please replace "tenant-name" with your tenant.

A: I believe, this functionality of retrieving external IDP (identity provider) access_token would be extremely useful to relying parties(RP), if they (RP) want to then talk directly to the (external) IDP by providing this ( idp_access_token) token a bearer to do some operations.
Several Identity Brokers provide this feature; for example:

*

*Keycloak : https://www.keycloak.org/docs/latest/server_admin/#retrieving-external-idp-tokens

*Auth0 - https://auth0.com/docs/connections/calling-an-external-idp-api
I have some experience working with Keycloak and some of the Relying Parties I work with do use this feature in Keycloak -- to pull in some additional information about the authenticated user.
Well, there are some settings and configurations and permissions need to be done both at the IDP broker side (first leg) and at the second leg as well. I guess, that is beyond the scope of the question asked.


text:
Q: How to connect properly to an Optivote device through a local socket connection? Optivote IR8 is basically a voting system with a bunch of remote controllers, which can send IR signals to a receiver, which is connected to a computer through a USB port. And I'm trying to write my own little software for that with Flash.
Optivote receiver communicates with software through a virtual serial port. When I connect to that port through PuTTY, I can see signals whenever I press any button on the remote controllers.
Although, when I connect to that port through Serproxy (which relays a socket connection to a serial port connection), the remote controllers don't seem to work. I just get the same signal every half a second or so, over and over. I'm guessing the receiver is trying to make some kind of handshake this way.
The thing I can't figure out is what PuTTY does that Serproxy doesn't to make the serial port connection work. Maybe there's some proper way to tell the other end when I connect?
(I use Serproxy, because Flash applications cannot connect to a serial port directly, but supports socket connections)

A: I found I could not get serproxy to work, that was until I came across a new version
http://code.google.com/p/tinkerit/wiki/TinkerProxy


text:
Q: Codeigniter e .htaccess em subpasta no servidor Meu objetivo é fazer uma aplicação escrita em Codeigniter rodar no servidor em uma subpasta e não no domínio principal, exemplo: www.dominio.com.br/foo.
O erro é sobre redirecionamento, toda requisição está sendo redirecionada para a home (www.dominio.com.br).
Conteúdo do arquivo www.dominio.com.br/foo/.htaccess:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php/$1 [L]

Trecho do arquivo www.dominio.com.br/foo/application/config/config.php:
$config['base_url'] = 'http://www.dominio.com.br/foo/';
...
$config['index_page'] = '/index.php';

Adianto que já tentei utilizar o RewriteBase dessa forma...
RewriteEngine on
RewriteBase /foo/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php/$1 [L]

...mas tb não tive sucesso.
Confesso tb que alterei o .htaccess de tudo quanto é forma e sempre redireciona para a home.
Agradeço desde já!

A: Faltou definir o caminho correto para RewriteRule.
Note que você especificou RewriteBase, porém, RewriteRule continua apontando para a raíz.
Para resolver, faça isso: RewriteRule ^(.*)$ /foo/index.php/$1 [L]
Exemplo completo:
RewriteEngine on
RewriteBase /foo/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /foo/index.php/$1 [L]

Algumas observações

*

*O nome index.php é desnecessário caso DirectoryIndex já esteja apontando para o mesmo.

*Quando aplicar num diretório root, é boa prática especificar a base RewriteBase /.
Alternativa
Alternativamente, uma forma mais simplificada para as regras HTACCESS:
Para diretório raíz/root
RewriteEngine on
RewriteBase /
Options FollowSymLinks
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule (.+) /
DirectoryIndex index.php

Para um subfolder
RewriteEngine on
RewriteBase /foo/
Options FollowSymLinks
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule (.+) /foo/
DirectoryIndex index.php

A: Se você colocou seu CI com a estrutura padrão dentro da pasta FOO não tem porque ele não funcionar.
O que parece é que sua base para a escrita está em outra pasta.
Experimente esse padrão abaixo; dentro da sua pasta na memsa hierarquia do application.
'<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]
</IfModule>'

Isso deve funcionar!

A: Algumas considerações que talvez possam te ajudar:

*

*Se você utiliza a abordagem MVC, principalmente a VC, tendo um controller foo e nele a função index() chamando a view desejada, funcionaria da forma que você quer.

*O CodeIgniter permite trabalhar com as rotas de sua url pelo arquivo routes.php:
$route['bar'] = 'foo';  // rota foo para o controller bar

*As chamadas de views podem ser feitas também dentro de pastas: Ex: $this->load->view('pasta/arquivoPhp');
Obs: Costumo deixar o $config['base_url'] = ''; e $config['index_page'] = ''; vazios ou no $config['base_url'] = 'http://www.dominio.com.br/foo'; sem a última barra.

A: Costumo deixar meu application/config/config.php assim:
$config['base_url'] = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == "on") ? "https" : "http");
$config['base_url'].= "://" . (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : "");
$config['base_url'].= str_replace(basename($_SERVER['SCRIPT_NAME']),"",$_SERVER['SCRIPT_NAME']);

$config['index_page'] = '';

e o meu .htaccesss assim:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]

e não costumo ter nenhum problema em deixar em subpastas como no seu caso que precisa, que por sinal sempre deixo assim para fazer um testes.


text:
Q: Looking for an editor that supports editor-based notes/comments I'm relatively new to LaTeX and I'm currently looking for a suitable LaTeX editor. Right now I'm using Texmaker, which seems fine, but I'm really missing the possibility to write editor-based notes as opposed to only comments within the text itself.
Overleaf supports the type of notes that I'd like to use, but I'd prefer not to write everything online. Are there any other editors that support these types of editor-notes?
Here's a screenshot of one of these comments/notes in Overleaf:


text:
Q: Pull bulleted list from MySQL in php Trying to produce a bulleted list from text field in MySQL - I have the bullets in the DB field : I'm pulling data into the array $products, I need the string in array to be formatted as a bullet list in the products $Keyfindings2 results
<?php

/* This controller renders the category pages */

class CategoryController{
    public function handleRequest(){
    $cat = Category::find(array('id'=>$_GET['category']));

    if(empty($cat)){
        throw new Exception("There is no such category!");
    }

    // Fetch all the categories:
    $categories = Category::find();

    // Fetch all the products in this category:
    $products = Product::find(array('category'=>$_GET['category']));

    // $categories and $products are both arrays with objects

    $Keyfindings2 = explode('•', $products);
            echo "
\n";

                foreach( $Keyfindings2 as $item )
                    {
                        echo "
$item

\n";
                    }
                        echo "
";

    render('category',array(
        'title'         => 'Browsing '.$cat[0]->name,
        'categories'    => $categories,
        'products'      => $Keyfindings2

    ));
    }
}

?>

UPDATE: now getting 'undefined variable' in other part of code on line 1:
<li <?php echo ($active == $category->id ? 'data-theme="a"' : '') ?>>
<a href="?category=<?php echo $category->id?>" data-transition="fade">
<?php echo $category->name ?>
<?php echo $category->contains?>

A: You problem is quite simple: you are using explode on the wrong thing.
If your code/comments is right $products is an array and you explode it. You probably have your PHP error level too low because this produce a PHP warning: PHP Warning:  explode() expects parameter 2 to be string, array given in php shell code on line 1
So from there 2 solutions: either $products is an array of strings and you can do
function myExplode($product) {
    return explode('•', $product);
}
$Keyfindings2 = array_map('myExplode', $products);

or $products is an array of objects (as your code comment suggests) and you go with:
function myExplode($product) {
    // well actual the name of the field or method to call really depends on your
    // code and there is no way we can tell it with what we have on your post
    // so consider this an example
    return explode('•', $product->productFieldContainingList);
}
$Keyfindings2 = array_map('myExplode', $products);

With either solution the goal is the same: to apply explode on the correct data, not on an array containing that data.


text:
Q: Android Firebase OnDataChange not getting triggered So I'm trying to create a listener that will advertise the activity when a new entry is added to my database in Firebase like this:
public void dataListener() {
    Query lastQuery = mDatabase.child("id").orderByKey().limitToLast(1);
    lastQuery.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            Log.d("ChildAdded",dataSnapshot.getChildren().toString());
            getAddedUpdates(dataSnapshot);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            Log.d("ChildError",databaseError.toString());
        }
    });

I'm calling this dataListeneronCreate but nothing happens, and by that I mean, when I added a new entry on another phone this isn't triggered, even thought the data is being inserted (when i reload the app using a singleEeventListener in another method the data is received)

All fields are Text (Strings)

A: The location is wrong, you need to change this:
Query lastQuery = mDatabase.child("id").orderByKey().limitToLast(1);

into this:
 DatabaseReference ref=FirebaseDatabase.getInstance().getReference();
 Query lastQuery=ref.orderByKey().limitToLast(1);

the snapshot is at the root node then you will be able to order the keys and retrieve the last one.
The child("id") does not have any key under it, example:
id
 pushid
   name: peter

The child'("id") is equal to a randomid then you can do this:
Query lastQuery=ref.orderByChild("id").equalTo(key_here)


text:
Q: Normalization forms for a database so I'm pretty new to this, and I created a database model for an airport
[database Image]

Could anyone please help me understand what are the normalization forms of the tables? I'm pretty confused with that concept

A: i dont wan't to post a big answer but this link should explain things in a simple to understand way:
https://learn.microsoft.com/en-us/office/troubleshoot/access/database-normalization-description

Normalization is the process of organizing data in a database. This includes creating tables and establishing relationships between those tables according to rules designed both to protect the data and to make the database more flexible by eliminating redundancy and inconsistent dependency.


text:
Q: Combine multiple images using command line tool I'm trying to recombine multiple images into a single image using a command line tool like ImageMagick.
I have 30000 folders and In each folder there are nearly 50 images. The images are smaller tiles of a larger image that has been broken up into tiles. Each images is prefixed with their xy position
e.g.
folder1/01-imagename01-imagename
folder1/02-imagename
folder1/03-imagename
folder1/10-imagename
and so on
example here.
00-zzi.....=x0-y0-z2.jpg
01-zzi.....=x0-y1-z2.jpg
02-zzi.....=x0-y2-z2.jpg
03-zzi.....=x0-y3-z2.jpg

each tile image is 512x512 and typically is less than 50kb
I'm trying to figure out if there's any way that the image magick composite capability is the right tool, or any other suggestions.
Thanks!
Debian GNU/Linux 11
identify image output:
Image:
  Filename: 00-zzi3ZROdz3Lq8hTj7hy2ghoChBAv2D2-9bU_jPT-D4b_jXTraQfK81DEuQ=x0-y0-z2.jpg
  Format: JPEG (Joint Photographic Experts Group JFIF format)
  Mime type: image/jpeg
  Class: DirectClass
  Geometry: 512x512+0+0
  Units: Undefined
  Colorspace: sRGB
  Type: Grayscale
  Base type: Undefined
  Endianness: Undefined
  Depth: 8-bit
  Channel depth:
    red: 8-bit
    green: 8-bit
    blue: 8-bit
  Channel statistics:
    Pixels: 262144
    Red:
      min: 0  (0)
      max: 19 (0.0745098)
      mean: 3.06709 (0.0120278)
      standard deviation: 0.61571 (0.00241455)
      kurtosis: 28.6716
      skewness: 2.14642
      entropy: 0.251511
    Green:
      min: 0  (0)
      max: 19 (0.0745098)
      mean: 3.06709 (0.0120278)
      standard deviation: 0.61571 (0.00241455)
      kurtosis: 28.6716
      skewness: 2.14642
      entropy: 0.251511
    Blue:
      min: 0  (0)
      max: 19 (0.0745098)
      mean: 3.06709 (0.0120278)
      standard deviation: 0.61571 (0.00241455)
      kurtosis: 28.6716
      skewness: 2.14642
      entropy: 0.251511
  Image statistics:
    Overall:
      min: 0  (0)
      max: 19 (0.0745098)
      mean: 3.06709 (0.0120278)
      standard deviation: 0.61571 (0.00241455)
      kurtosis: 28.6717
      skewness: 2.14643
      entropy: 0.251511
  Colors: 18
  Histogram:
    560: (0,0,0) #000000 black
    2814: (1,1,1) #010101 srgb(1,1,1)
    15055: (2,2,2) #020202 srgb(2,2,2)
    212826: (3,3,3) #030303 grey1
    24467: (4,4,4) #040404 srgb(4,4,4)
    5004: (5,5,5) #050505 grey2
    896: (6,6,6) #060606 srgb(6,6,6)
    237: (7,7,7) #070707 srgb(7,7,7)
    113: (8,8,8) #080808 grey3
    72: (9,9,9) #090909 srgb(9,9,9)
    43: (10,10,10) #0A0A0A grey4
    24: (11,11,11) #0B0B0B srgb(11,11,11)
    14: (12,12,12) #0C0C0C srgb(12,12,12)
    7: (13,13,13) #0D0D0D grey5
    5: (14,14,14) #0E0E0E srgb(14,14,14)
    3: (15,15,15) #0F0F0F grey6
    1: (16,16,16) #101010 srgb(16,16,16)
    3: (19,19,19) #131313 srgb(19,19,19)
  Rendering intent: Perceptual
  Gamma: 0.454545
  Chromaticity:
    red primary: (0.64,0.33)
    green primary: (0.3,0.6)
    blue primary: (0.15,0.06)
    white point: (0.3127,0.329)
  Background color: white
  Border color: srgb(223,223,223)
  Matte color: grey74
  Transparent color: black
  Interlace: None
  Intensity: Undefined
  Compose: Over
  Page geometry: 512x512+0+0
  Dispose: Undefined
  Iterations: 0
  Compression: JPEG
  Quality: 90
  Orientation: Undefined
  Properties:
    date:create: 2022-09-07T00:51:18+00:00
    date:modify: 2022-09-07T00:51:18+00:00
    jpeg:colorspace: 2
    jpeg:sampling-factor: 2x2,1x1,1x1
    signature: ebb4af08227671b45fa62c44887f9b94a8a17d3a7d6c418c26be0e032b766359
  Artifacts:
    filename: 00-zzi3ZROdz3Lq8hTj7hy2ghoChBAv2D2-9bU_jPT-D4b_jXTraQfK81DEuQ=x0-y0-z2.jpg
    verbose: true
  Tainted: False
  Filesize: 3764B
  Number pixels: 262144
  Pixels per second: 67.2793MB
  User time: 0.000u
  Elapsed time: 0:01.003
  Version: ImageMagick 6.9.11-60 Q16 x86_64 2021-01-25 https://imagemagick.org

Hi Mark,
thank you for your help so far. I have been doing some testing and very nearly there! I had to change the get list of images code to use egrep due to it not finding the files, i have changed to:
row=( $(ls | egrep *-y${y}-z 2> /dev/null) )

The final hurdle, is that when attempting to process a smaller directory of 10 folders as a test of parallel processsing,
find "tiled_images" -type d -print ./processOne {}

It seems to not be printing the folder names after the command and showing:
find: paths must precede expression.

A: As I see it, there are two aspects to this:

*

*processing 30,000 directories

*processing one directory

IMHO, the best way to process 30,000 directories is in parallel, else you'll be there all day. So I would suggest to write the processing as a script that does one directory, passed as a single parameter, and then using a GNU Parallel job that processes all 30,000 directories, keeping all your CPU cores busy till all directories are done.
So, if your directories are under a top-level directory called "tiled_images", and you save the script in the next part of my answer as processOne.sh, you could do this:
find "tiled_images" -type d -print | parallel ./processOne {}

There are many options to GNU Parallel, here are a few of the most useful:

*

*parallel --eta ... will show you the "Estimated Time of Arrival" of job completion

*parallel --bar ... will show you a progress bar, and works with zenity

*parallel --j 4 ... will run just 4 jobs at a time

*parallel --j 50% ... will keep half your CPU cores busy

Now to the processing of a single directory, whose name is passed as parameter:
#!/bin/bash

# Expect one parameter - the directory name
[ $# -ne 2 ] || { >&2 echo "Usage: $0 DIRECTORY"; exit 1; }

d=$1

cd "$d" || { >&2 echo "ERROR: Directory $d does not exist"; exit 1; }

# Assume no more than 100 rows of tiles since fewer than 50 images altogether, and presumably more than 1 image per row
for ((y=0;y<100;y++)) ; do

   # Get list of images in this row
   row=( $(ls *-y${y}-z2.jpg 2> /dev/null) )

   # Break out of loop if no images
   [ -z "$row" ] && break

   # Formulate output filename for this row, being sure that it is zero-padded so the rows collate in correct order
   # Also, write to MPC, or Magick Pixel Cache format, which should be fastest to write and read later
   printf -v out "row-%02d.mpc" $y

   echo "Processing row: ${y}"
   echo "  concatenating: ${row[@]}"
   echo "  into: ${out}"
   magick "${row[@]}" +append "$out"
done

# Concatenate rows into result
magick row-*mpc -append result.jpg

# You should clean up here when it is tested
# rm *.mpc *.cache

You would then save this as processOne.sh and make it executable with:
chmod +x processOne.sh

Then test it on a single directory with:
./processOne SOME_DIRECTORY_CONTAINING_TILES

Note that +append concatenates images side-by-side, whereas -append (different sign) concatenates images above-and-below each other.

Note that you could speed this up by avoiding creation of intermediate files, but that might complicate things and make debugging harder. Just for reference, that would look something very much like this:
...
...

# Assume no more than 100 rows of tiles since fewer than 50 images altogether, and presumable more than 1 image per row
for ((y=0;y<100;y++)) ; do

   # Get list of images in this row
   row=( $(ls *-y${y}-z2.jpg 2> /dev/null) )

   # Break out of loop if no images
   [ -z "$row" ] && break

   # Append images to make a row and pass to outer `magick` command
   magick "${row[@]}" +append miff:-

done | magick miff:- -append result.jpg


text:
Q: Android: How to display two fragments with RecyclerView in one screen I have two fragments, each with its own respective RecyclerView list.
The RecyclerView from each of the fragments may contain many items. So, scrolling will mostly be necessary.
My problem is, how do I combine and display these two fragments into one screen using ScrollView, but at the same time, making the scrolling of the RecyclerViews behave as normally (non-sticky, follows the entire screen's scroll).
Thanks.
EDIT:
My layout file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.easyuni.courserecommender.ResultsActivity">

    <android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/drawer_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <include
                android:id="@+id/toolbar"
                layout="@layout/toolbar" />

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                android:layout_below="@+id/toolbar">

                <FrameLayout
                    android:id="@+id/fragment_container_results_career"
                    android:layout_width="match_parent"
                    android:layout_height="0dp"
                    android:layout_weight="1" />

                <View
                    android:id="@+id/divider"
                    android:layout_width="fill_parent"
                    android:layout_height="1dp"
                    android:layout_below="@+id/fragment_container_results_career"
                    android:layout_marginTop="8dp"
                    android:layout_marginBottom="8dp"
                    android:background="@color/divider" />

                <FrameLayout
                    android:id="@+id/fragment_container_results_courses"
                    android:layout_width="match_parent"
                    android:layout_height="0dp"
                    android:layout_weight="1" />

            </LinearLayout>

        </RelativeLayout>

        <android.support.design.widget.NavigationView
            android:id="@+id/navigation_view"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            app:itemIconTint="#333"
            app:itemTextColor="#333" />

    </android.support.v4.widget.DrawerLayout>

</RelativeLayout>

Screenshot:
(Notice the RecyclerView at the top and bottom scrolls individually)
https://drive.google.com/file/d/0B-glHmJbVcwiVU41WVRHU3g2bkE/view

A: You can do like this one -
In your activity's layout file, you should have two framelayout for containing your two fragment.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <FrameLayout
        android:id="@+id/first_fragment_container"
        android:layout_weight="1"
        android:layout_width="match_parent"
        android:layout_height="0dp">

    </FrameLayout>

    <FrameLayout
        android:id="@+id/second_fragment_container"
        android:layout_weight="1"
        android:layout_width="match_parent"
        android:layout_height="0dp">

    </FrameLayout>
</LinearLayout>

Then in your Activity's onCreate() method, you can use FragmentManager class to add Fragment to the FrameLayout.
 getSupportFragmentManager().beginTransaction().add(R.id.first_fragment_container, new YourFirstFragment()).commit();
        getSupportFragmentManager().beginTransaction().add(R.id.second_fragment_container, new YourSecondFragment()).commit();


text:
Q: How to configure config-file-provider files using configuration-as-code plugin in Jenkins I have been following this to configure config-file-provider files using the configuration-as-code plugin.
Provided below is a sample YAML code I have used.
unclassified:
 globalConfigFiles:
  configs:
  - custom:
      id: custom-test
      name: DummyCustom1
      comment: dummy custom 1
      content: dummy content 1

I want to know whether there is a way to give content as a file(or file path).
Any help on how to fix this issue would be appreciated.

A: That's not possible. It's not CasC specific, it's just config-file-provider plugin not offering it.


text:
Q: How to force users unregister service worker? I had a ReactJS webserver running with a domain. Recently, I've re-pointed DNS to a new server ip address but some users still see the old website though I've shutdown the old server already.
I've checked the browser network inspect and surprisingly the webpage was fetched from
Service Worker and the date was about 50 days ago.
At the moment, they aren't able to get any responses from new web server including any headers, etc. They just see old web page whether new/old web servers are running or not.
I used nginx to host both web servers.
How can I force users clear the browser cache automatically?
UPDATED: So I guess I figured out the reason exactly. My old website supported ServiceWorker while my new website doesn't. So now, I need to clear service worker of old website. What can I do here?


text:
Q: getting error "Object Reference not set to an instance of an object" Linq to SQL Database Insret a XML file As VarBinary i am getting error

Object Reference not set to an instance of an object

public static void SaveDashboardStream(string connectionString, MemoryStream ms)
{
  using (DashboardDBConDataContext db = new DashboardDBConDataContext(connectionString))
   {
     DBDashboard storedDashboard = (from t in db.Dashboards
                                               select t).FirstOrDefault();
     ms.Seek(0, SeekOrigin.Begin);
     storedDashboard.DashboardStream = new Binary(ms.ToArray());
     db.SubmitChanges();
  }
}

i am using above code in a function As
private void DashBoardGenerator_DashboardSaving(object sender, DashboardSavingEventArgs e)
{
  // Determines whether the user has called the Save command.
  if (e.Command == DashboardSaveCommand.Save)
  {
     try
     {
       using (MemoryStream saveStream = new MemoryStream())
       {
         Dashboard.SaveToXml(saveStream);
         DashboardSql.SaveDashboardStream(dashboardStorageConnectionString, saveStream);
       }
       e.Handled = true;
     }
     catch (Exception ex)
     {
      XtraMessageBox.Show(ex.Message, "Unable to Save Dashboard", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
  }
}

PLease guide if i am wrong anywhere ?

A: Probably storedDashboard seems to be null.
using (DashboardDBConDataContext db = new DashboardDBConDataContext(connectionString))
{
     DBDashboard storedDashboard = (from t in db.Dashboards
                                    select t).FirstOrDefault();

     //Always check for null when selecting First() or FirstOrDefault()
     if(storedDashboard == null) {
        storedDashboard = new DBDashboard();
     }

     ms.Seek(0, SeekOrigin.Begin);
     storedDashboard.DashboardStream = new Binary(ms.ToArray());
     db.SubmitChanges();
}


text:
Q: Density of sets whose image is dense This is probably easy, but I can't think of an answer. Assume $X$ is a Banach space and $A$ is a (not assumed closed) subspace of $X$. Let $T:X \to X$ be a bounded linear operator, which is also injective. If $T(A)$ is dense in $X$, does it follow that $A$ is dense in $X$?

A: No, not even if $X=\ell_2$.  Le $A$ be the closed span of $(e_n)_{n=2}^\infty$ and map $A$ to a proper dense subspace and $e_1$ to a vector not in that subspace.

A: Here's an explicit example for what Bill's answer proposes.
Let $T_1$ be the operator which maps $e_n$ to $4^{-n} e_{n-1}$ for $n \ge 2$ and maps $e_1$ to $0$.  That is, $T_1 \left(\sum_{n \ge 1} a_n e_n\right) = \sum_{n \ge 1} a_{n+1} 4^{-(n+1)} e_n$.  Note $T_1$ is injective on $A$, and $T_1 A$ is dense (it contains $c_{00}$).
Let $y = \sum_{n} 2^{-n} e_n$.  Note $y \notin T_1 A$.  Define $T$ by $T e_n = 4^{-n} e_{n-1}$ for $n \ge 2$ and $T e_1 = y$.  Now we still have that $TA = T_1 A$ is dense.  To see $T$ is injective, suppose $Tx = 0$.  Then we can write $x$ uniquely as $x = a_1 e_1 + u$ where $u \in A$.  Thus $T x = a_1 y + T_1 u$.  But $T_1 A$ is a vector space not containing $y$, so if $Tx=0$ we conclude that $a_1 = 0$ and $T_1 u = 0$.  But $T_1$ was injective on $A$ so $u = 0$.  Thus $x=0$.


text:
Q: is it possible to have a members of subclasses in superclass in c++ My goal here was, instead of placing all methods in ServerInterface(superclass), i wanted to place the methods in child classes to organize the code better.
class ServerInterface
{
public:
    Router* router = new Router();
    Client* client = new Client();
    ServerInterface() {

    } //Creates new Router and Client instance
};

class Router : public ServerInterface
{
public:
    Router() {}
    void randomRouterFunction() {}
};

class Client : public ServerInterface
{
public:
    Client() {}
    virtual void randomClientFunction() {};
};

class ProductionServer : public ServerInterface
{
public:
    ProductionServer() {}
};

int main() {
    ProductionServer* productionServer = new ProductionServer();
    productionServer->router->randomRouterFunction(); //causes it to not debug
    return 0;
}

In my situation I am only allowed to access to ProductionServer which has to inherit from ServerInterface in my code.
So instead of calling productionServer->randomRouterFunction() or productionServer->randomClientFunction(), i wanted to be able to call productionServer->Router->randomRouterFunction() etc
Even though intellisense tells me that it's all working fine, trying to run my code i recieve

main:289:20: error: 'class ProductionServer' has no member named
'router'
productionServer->router->randomRouterFunction();

Is this even feasible to accomplish? The reason for thinking it may not work is cause the superclass creates a member of Router which is the child class, and then the router child class creates another superclass since it inherits it, which then creats another router child class in the superclass.... and it would be an infinite loop? XD
ps. The randomFunction() could be any method, just used as an example.

A: The problem is with the design. You can compile this but when you create a ProductionServer it will instantiate a ServerInterface which will create a Router and a Client and those will both also instantiate a ServerInterface that will create a Router and a Client and so on - until you get a stack overflow.
In order to get this in some working condition, you need to add something that breaks that cycle so that it doesn't instantiate Routers and Clients endlessly.


text:
Q: Conditional fetching with NHibernate I need to eager load an object tree with NHibernate but I also wish to specify which objects to load.
The object tree is like this:
class A {
   double Date;
   IList<B> Bs;
}

class B {
   double Date;
   IList<C> Bs;
}

class C {
   double Date;
}

And what I want to do, is to eager load the whole tree, where A.Date > 2012, B.Date > 2012, C.Date > 2012 (basicly I want only a snapshot of the object tree according to my specified constraints).
Is that possible ?
I'm using NH 3.1 and Fluent.
Thanks!

A: Have you tried with NHibernate Filters ? http://nhibernate.info/doc/nh/en/index.html#objectstate-filters


text:
Q: Extract PKCS7 Container memory leak during receipt validation XCode detected memory leaks in one of my function:

The func is responsible for extracting PKCS7 container. Here the code of the func:
func extractPKCS7Container() throws -> UnsafeMutablePointer<PKCS7> {
    guard let receiptURL = Bundle.main.appStoreReceiptURL,
        let certificateURL = Bundle.main.url(forResource: "AppleIncRootCertificate", withExtension: "cer"),
        let receiptData = NSData(contentsOf: receiptURL),
        let certificateData = NSData(contentsOf: certificateURL) else {
            throw ReceiptError.couldNotFindReceipt
    }
    let bio = BIOWrapper(data: receiptData)
    let p7 = d2i_PKCS7_bio(bio.bio, nil)
    guard p7 != nil else {
        throw ReceiptError.emptyReceiptContents
    }
    OpenSSL_add_all_digests()

    let x509Store = X509StoreWrapper()
    let certificate = X509Wrapper(data: certificateData)
    x509Store.addCert(x509: certificate)
    let payload = BIOWrapper()
    guard PKCS7_verify(p7, nil, x509Store.store, nil, payload.bio, 0) == 1 else {
        throw ReceiptError.receiptNotSigned
    }
    return p7!
}

I also have supplementary classes:
class BIOWrapper {
    let bio = BIO_new(BIO_s_mem())
    init(data:NSData) {
        BIO_write(bio, data.bytes, Int32(data.length))
    }
    init() {}
    deinit {
        BIO_free(bio)
    }
}

class X509StoreWrapper {
    let store = X509_STORE_new()
    deinit {
        X509_STORE_free(store)
    }
    func addCert(x509:X509Wrapper) {
        X509_STORE_add_cert(store, x509.x509)
    }
}

class X509Wrapper {
    let x509 : UnsafeMutablePointer<X509>!
    init(data:NSData){
        let certBIO = BIOWrapper(data: data)
        x509 = d2i_X509_bio(certBIO.bio, nil)
    }
    deinit {
        X509_free(x509)
    }
}

All wrappers has init and deinit section. Other functions is from the build-in Crypto module... Frankly, I have no idea there the leak can be here. Could anyone help me?

A: You are allocating a PKCS7 object but it seems you are never calling PKCS7_free. For example, you would need to call it right before throw ReceiptError.receiptNotSigned.
Notice in the stack trace on the right there are stack frames missing. You can view them by clicking on the icon the looks like a square with a line above and below that. That way you know exactly which function call is responsible for the allocation (and thus likely what it is that leaked).


text:
Q: Flask-Session cookie works on other browsers for ip address & domain, but for chrome it only works on ip address I found a question with this same problem, except it was 7 years old, and they had the opposite issue, where chrome worked for their domain, but not IP. I need this application to work on the domain, not the ip, which is unfortunate.
If I Have some basic code like this:
Flask:
app = Flask(__name__)
from dotenv import load_dotenv
load_dotenv()
SECRET_KEY = os.getenv('FLASK_APP_SECRET_KEY')
SESSION_TYPE = 'filesystem'
app.config.from_object(__name__)
Session(app)
CORS(app)

@app.route('/give', methods = ['GET'])
@cross_origin(supports_credentials=True)
def user_make(id):
    session['Hi'] = 'There'
    return 'ye'

@app.route('/take', methods = ['GET'])
@cross_origin(supports_credentials=True)
def user_load(id):
    return session['Hi']

reactjs:
let data = new FormData()
return axios
      .get('12.34.56.78' + '/give', data, {
        headers: {
          "Content-Type": "multipart/form-data",
        },
      }).then(
return axios
      .take('12.34.56.78' + '/take', data, {
        headers: {
          "Content-Type": "multipart/form-data",
        },
      }))

On a server with ip='12.34.56.78' and domain 'example.com':
When using the domain or ip on safari, the output is

'there'

for both
however, on chrome,
for ip the output is

'there'

however, for domain, the output is

Key Error

edit:
Some more info:
This is on an AWS ec2 ubuntu server, which is running on port 80 for the frontend and 5000 for the backend. I connected the ip address to the domain name with AWS Route 53... just in case this is relevant. To access the frontend, one can go to the ip or the domain, whereas to access the backend, one must go to ip:5000
Any more info needed?
Is this fixable?
Thanks!

A: I think the problem is with how google chrome manage the cookies. It's the 'SameSite' attribute. Back on July 14th, 2020, Google started gradually rolling out a new browser policy with a few major changes. One that treats cookies as SameSite=Lax by default, if no SameSite attribute is specified. The other deprecates and removes the use of cookies with the SameSite=None attribute that did not include the Secure attribute. That means that any cookie that requests SameSite=None but is not marked Secure is now being rejected. This means that the front-end can't contact the back-end and the site is not working. To fix it, you just need to make sure that when your _SESSION_ID cookie is created it includes the SameSite=None and Secure attributes.
P.S.1: Based on the article of Caleb. Back-end is Ruby on Rails but i don't think this is an issue.
P.S.2: Before change anything, try other chrome-based browsers like Vivaldi, Comodo or even the new Microsoft Edge.


text:
Q: fft of a timeseries object in matlab how do I take the fft of a time series object in MATLAB ? I have tried using iddata( timeseries.data ,[],ts) , but gives me error saying   "The value of the "OutputData" property must be a double matrix or a cell array of such matrices."
Is there any another way i can do this .
I need to see the frequency spectrum of an unknown signal which is stored as a timeseries object z , in MATLAB . fs is my sampling frequency, length is total no. samples in my timeseries object.
this code gives me an error saying "vectors must be the same lengths".
fs=4.1650e+04
tsam=2.2676e-05
length=749701
frs=-fs/2:fs/len:fs/2
plot(frs,abs(fftshift(fft(z.data))))


text:
Q: disableOpenGesture hiding is not working Navigation Drawer react native We are using Navigation Drawer in our application to show side menu.
In a few of the screens we don't want to show this navigation drawer once user tried to do left/right gestures.
So, for that, we are trying to hide a particular screen - gestures/navigationdrawer -  but it's not working.
When the user swipes (left/right) the drawer still opens.

    const AppNavigator = StackNavigator(
      {
        // Drawer: { screen: Drawer },
        Register: {
          screen: Register,
          navigationOptions: ({ navigation }) => ({
            drawerLockMode: "locked-closed",
          })
        },
        TabHome: { screen: TabHome },
        Album: { screen: Album },
        offlineContent: { screen: offlineContent },
        changePassword: { screen: changePassword },
        Player: {screen: Player},
      },
      {
        initialRouteName: "TabHome",
        // header: null
      }
    );

We have tried both drawerLockMode:"locked-closed" and     disableOpenGesture: true
but nothing is working.
Note: I am using "react-navigation": "^3.0.9" version
Any suggestions to disable navigation drawer being opened by gestures?

A: can you try this code?
const AppNavigator = StackNavigator(
      {
        // Drawer: { screen: Drawer },
        Register: {
          screen: Register
        },
        TabHome: { screen: TabHome },
        Album: { screen: Album },
        offlineContent: { screen: offlineContent },
        changePassword: { screen: changePassword },
        Player: {screen: Player},
      },
      {
        initialRouteName: "TabHome",
        // header: null
      }
    );
AppNavigator.navigationOptions = ({ navigation }) => {
  const navigationOptions = {};
  if (getCurrentRouteName(navigation.state) === 'Register') {
    navigationOptions.drawerLockMode = 'locked-closed';
  }
  return navigationOptions;
};

OR If your react-navigation version is V2,
const Stack = createStackNavigator({
    Register: Register,
},
    {
        drawerLockMode: 'locked-closed'
    }
);

getCurrentRouteName function
getCurrentRouteName(navState) {

    if (navState.hasOwnProperty('index')) {
        this.getCurrentRouteName(navState.routes[navState.index])
    } else {
        console.log("Current Route Name:", navState.routeName)
        // can then save this to the state (I used redux)
        store.dispatch(setCurrentRouteName(navState.routeName))
    }

}


text:
Q: Using synchronized to suspend active Thread I'm trying to suspend (or pause) the active thread using wait() I have implemented this in my code already but when I run the code it doesn't output anything, I think it's because when it runs it starts on "suspend"  would appreciate any help solving this issue. Here is the relevant code and a link with everything just in case.
GreenhouseControls.java
public class GreenhouseControls extends Controller implements Serializable {
    ...
    private Boolean suspend = false;
    ...

    public void SuspendEvent() {
        suspend = true;
    }

    public void ResumeEvent() {
        suspend = false;
    }

    public Boolean getSuspend() {
        return suspend;
    }

    ...
}

Event.java
public abstract class Event implements Runnable {
  ...
  private boolean suspend;
  ...

public synchronized void isSuspended() {
    suspend = greenhouseControls.getSuspend();
    notifyAll();
  }

  public void run() {
    try {
      while (suspend = true) {
        try {
          synchronized(this) {
            wait();
          }
        }

        catch (InterruptedException e) {
          e.printStackTrace();
        }
      }

      Thread.sleep(delayTime);
    }

    catch (InterruptedException e) {
      e.printStackTrace();
    }

    try {
      this.action();
    }

    catch (GreenhouseControls.ControllerException e) {
      e.printStackTrace();
    }
  }

  ...
}

FansOff.java: there are other classes like this one each very similar to each other and they are the ones actually producing the output
public class FansOff extends Event {
   ...
   public void run() {
        try {
            boolean suspend = false;
            while (suspend = true) {
                try {
                    synchronized(this) {
                        wait();
                    }
                }

                catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            Thread.sleep(delayTime);
        }

        catch (InterruptedException e) {
            e.printStackTrace();
        }

        try {
            this.action();
            System.out.println(this.toString());
        }

        catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Full code: here.
Thanks in advance.


text:
Q: GoogleApiClient.Builder().addApi() for FCM I want to ensure devices have the Google Play services APK for Firebase Cloud Messaging.
Which API should i add in .addApi() and .addScope() method for FCM?
For example, if i want to use location service, i add this code in MainActivity:
GoogleApiClient mGoogleApiClient = new GoogleApiClient.Builder(this)
    .enableAutoManage(this /* FragmentActivity */,
                      this /* OnConnectionFailedListener */)
    .addApi(LocationServices.API)
    .build();

Also for check Google Drive, i use:
GoogleApiClient mGoogleApiClient = new GoogleApiClient.Builder(this)
    .enableAutoManage(this /* FragmentActivity */,
                      this /* OnConnectionFailedListener */)
    .addApi(Drive.API)
    .addScope(Drive.SCOPE_FILE)
    .build();

but i don't know the API and Scope value for FCM.

A: Just use GoogleApiAvailability.isGooglePlayServicesAvailable(). If this method returns SUCCESS it means that the Google Services API version that you specified in your build.gradle is supported on the device and that the device has the Firebase APIs; you are building your code against this version, which implies that the Firebase APIs that you are using in your code are supported in this version. The system does not need to provision access to the Firebase APIs, which is the purpose of addApi().
You do not need a GoogleApiClient to access the Firebase APIs/FCM.


text:
Q: how display input fields and required them when selected option with jquery i use a form such as this:
<form id="clac" action="#" method="post">
<select onchange="func_type()" name="t_person" id="t_person" class="t_person_class">
    <option value="0" selected>select persons</option>
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">three</option>
</select>

<input id="t_person_name1">

<input id="t_person_name2">

<input id="t_person_name3">

<input type="submit" value="okGo">
</form>

and use script such this for display some input fields when select an option:

in works fine, but how when a field display, then this field is required?

A: Try something like this:
Instead:
$.each($.viewMap, function() {
    this.hide('500');
});
$.viewMap[$(this).val()].show('500');

do:
$.each($.viewMap, function() {
    this.hide('500').prop('required',false);
});
$.viewMap[$(this).val()].show('500').prop('required',true);

View on jsFiddle


text:
Q: Autostart under random WM? I'm a long-time DE user, however there are some circumstances under which I prefer to use different tiling-based WMs instead of GNOME or KDE (I use GNOME mostly for last year or so).
I've got Fedora 22 Workstation installation, with GNOME installed. For most time on both of my machines I run GNOME. However, sometimes I prefer to run XMonad (for me this doesn't matter much actually - i3wm, xmonad, spectrwm - for all of those 3 I've got nice configurations that I can use).
On XMonad (any non-DE e.g.), I'd like to have some scripts & programs to run when the session starts. Is there any standard way to run them without altering /etc/X11/sessions scripts?
For example, having a user-defined session for GDM or something like standard autostart files or anything. I've used to run all this through ~/.Xsession or ~/.xinitrc, but GDM doesn't execute those.

A: Try placing a symbolic link to *.desktop file of desired application into the ~/.config/autostart/ folder.


text:
Q: R: efficiently grep characters in rows of large data.frame I have a data frame of character strings that is >1M rows long:
>head(df)
     A    B     C     D
1   S1   S2    U1    U2
2   S1   S2    S2    S1
3   S2   S1    S1    S2
4   S1   M2    U1    S2
5   S1   S1    M2    M1
6   M2   M2    M1    M2

I would like to identify all rows where a particular character is present (e.g., "U").
The solutions I have found so far are working, but they are very slow, for example:
matches <- apply(as.matrix(df), 1, function(x){ sum(grepl("U", x, perl=T)) > 0 })

Any idea how to improve this query?
Thanks!

A: EDIT: updates to address comments:
The following is also very fast (0.31 seconds, even faster than before):
rows <- which(
  rowSums(
    `dim<-`(grepl("U", as.matrix(df), fixed=TRUE), dim(df))
  ) > 0
)

And produces the same result as previous answers.  Using fixed=FALSE about doubles the time, but your example doesn't require that.
What we're doing here is cheating by applying grepl to a matrix, though really what we care about is turning df into a vector (which a matrix is), and as.matrix is one of the faster ways to do this.  Then we can just run one grepl command.  Finally, we use dim<- to turn the grepl vector result back into a matrix, and use rowSums to check which rows had matches.
Here are the reasons why this is much faster than your version:

*

*We call grepl once, instead of a million times as you do with apply since the function apply applies gets called once for each row; grepl is vectorized which means you want to minimize how many times you call it and take advantage of the vectorization

*We do the row match counts with rowSums instead of apply; rowSums is a much faster version of apply(x, 1, sum) (see docs for ?rowSums).

PREVIOUS ANSWER:
Here is a relatively straightforward solution that runs in 0.35 seconds on my system for a 1MM row by 4 column data frame:
rows <- which(rowSums(as.matrix(df) == "U") > 0)

To confirm
df[head(rows), ]

produces (every row has a U):
   a b c d
5  F B D U
8  R S U F
15 U L R P
20 U E E O
21 Y U D I
32 P F U H

And the data:
set.seed(1)
df <- as.data.frame(
  `names<-`(
    replicate(4, sample(LETTERS, 1e6, rep=T), simplify=F),
    letters[1:4]
  )
)

A: library(data.table)

df = fread("~/Rscripts/SO.csv")  # fast read
x = df[, lapply(.SD, function(x) x %like% "U")] # fast grep
y = x[, rowSums(x) > 0]
z = df[y,]

A: If you're just looking for the row index for characters, maybe try this.  It should be quite a bit faster than looping.
unique(row(df)[grep("U", unlist(df))])
# [1] 1 4

A: [This answered the original question, which was an exact match of characters in the matrix rather than a regular expression match]. Coerce to a matrix (which is the correct representation anyway??), compare each element to "U" (use %in% if there is more than one possible value of interest) to create a logical matrix, and compute the row sum; use that to subset the original
which(rowSums(as.matrix(df) == "U") > 0)

no need to explicitly loop (via apply or vapply); these are 'vectorized' calculations and fast (although the above implies creation of 2 new matrices, and so could be improved).


text:
Q: Can we declare multiple variables on one line in a UML class diagram? private int x1, x2, y1, y2;

Can the UML line be:
- x1,x2,y1,y2: int

Or do we have to make them on 4 separate lines?

A: You are referring to a UML Class Diagram.
That means that you are not referring to variables. You are referring to attributes.
UML Class Diagrams do not contain "lines". They are a graphical depiction of a UML class model. The model includes a list of attributes. The class diagram displays the set of attributes.
I have never seen an implementation of UML which displays multiple attributes on the same row of a class diagram.

A: The UML standard has examples for all noticeably different kinds of attributes. As you can see, there no possibility for several attributes in one line.

ClassA::name is an attribute with type String.
ClassA::shape is an attribute with type Rectangle.
ClassA::size is a public attribute of type Integer with multiplicity 0..1.
ClassA::area is a derived attribute with type Integer. It is marked as read-only.
ClassA::height is an attribute of type Integer with a default initial value of 5.
ClassA::width is an attribute of type Integer.
ClassB::id is an attribute that redefines ClassA::name.
ClassB::shape is an attribute that redefines ClassA::shape. It has type Square, a specialization of Rectangle.
ClassB shows size as an attribute inherited from ClassA, as signified by the prepended caret symbol (see 9.2.4).
ClassB::height is an attribute that redefines ClassA::height. It has a default of 7 for ClassB instances that overrides the ClassA default of 5.
ClassB::width is a derived attribute that redefines ClassA::width, which is not derived.

http://www.omg.org/spec/UML/2.5/Beta2/ - I strongly advice to use the 2.5 version, even if it is in beta2 version. I is absolutely the same as accepted 2.4.1 as for content (officially), but differs in the ways of explanation - is much easier.


text:
Q: How to show a function is a global maximum We have the functional $$F[y]=\int_0^\pi y+\frac12y^2-\frac12y''^2\,dx$$ where $y=y(x)$. There are also some boundary conditions - $$y(0)=-1,y'(0)=0,y(\pi)=\cosh\pi,y'(\pi)=\sinh\pi.$$ I found the function which extremises this by using the Euler-Lagrange equation, and I got $y(x)=\cosh x-\cos x -1$.
Then the question says to show that this is a global maximum, and says I may use the result $$\int_0^\pi\phi^2(x)\,dx\leq\int_0^\pi\phi'^2(x)\,dx$$ which is valid for any $\phi$ which satisfies $\phi(0)=\phi(\pi)=0$.

I am not sure how to mould my function into something which satisfies this, since if I change the function then its no longer the thing that maximises $F[y]$. I also considered using the second variation but this would only be able to prove it is a local maximum. I also calculated $$y+\frac12y^2-\frac12y''^2=-2\cosh x\cos x-\frac12$$but I don't know if this is helpful in any way. How can I use this result to show it is a global maximum?

A: Let $y_0$ solve the Euler–Lagrange equations, and let $\phi$ be such that $y_0+t\phi$ also satisfies the boundary conditions. Then we need to have $\phi(0)=\phi(1)=\phi'(0)=\phi'(1)=0$. Expand $F[y_0+t\phi]$:
$$ F[y_0+\phi] = F[y_0] + t\int_0^{\pi} (\phi + \phi y_0 - \phi''y_0'') \, dx + \frac{1}{2}t^2 \int_0^{\pi} (\phi^2 - \phi''^2) \, dx . $$
Now show that the coefficient of $t$ is zero (hint: where do the Euler–Lagrange equations come from?), and that the coefficient of $t^2$ is negative (hint: you need to use the provided inequality more than once).
Since this holds for arbitrary $t$ and $\phi$, what does this tell you about the functional applied to any function that satisfies the boundary conditions and is sufficiently well-behaved?

A: The second variation was a good thought, and you're correct that the typical method would only show local maximisation.  But in this case, the functional is simple enough that it'll work fine. I'll use $y$ to denote the solution you've already found, and let $\phi$ be some variation, such that $\phi(0) = \phi(\pi) = \phi'(0)=\phi'(\pi) = 0$.  We'll aim to show that $F[y+\epsilon \phi] - F[y] \leq 0$ for all such $\phi$, without the restriction that $\epsilon$ is small.  This would demonstrate that $y$ is indeed the global maximser.
$$\begin{align}
F[y^*+\epsilon \phi] - F[y^*]  &= \int_0^\pi \epsilon \phi+ \epsilon y \phi +\frac 12 \epsilon^2 \phi^2 - \epsilon y'' \phi'' - \frac 12 \epsilon^2 \phi''^2 \ dx \\
&= \epsilon \int_0^\pi (\phi + y \phi - y'' \phi'') \ dx + \frac 12\epsilon^2\int_0^\pi (\phi^2 - \phi''^2) \ dx
\end{align}$$
Integration by parts shows that the first integral is exactly zero, which shouldn't be surprising given how you derived the Euler-Lagrange equation in the first place.  Now since $\phi(0) = \phi(\pi) =0$, we know $\int_0^\pi \phi^2dx \leq \int_0^\pi \phi'^2dx $, and $\phi'(0) = \phi'(\pi) =0$, so $\int_0^\pi \phi'^2dx \leq \int_0^\pi \phi''^2dx $. Putting this into the above answer gives that $F[y+\epsilon \phi] - F[y] \leq 0$, as required.


text: Q: Suspend process to hard drive When I suspend a process via KSysGuard, I right click on the process, and hit 'suspend', I do not see any difference in RAM consumption. I am wondering if it is possible to make it so that suspended processes' RAM gets transferred to SWAP or something so that unused programs do not take up precious RAM. People might say, "Why don't you just close the program?" Well I don't want to close programs and have to re-open them later. It is very convenient to just suspend them and then continue them later when I need them. This seems like something that would be easily done. To my knoladge, SWAP is used when there is not enough RAM so unused stuff gets moved to the hard disk. I am running Kubuntu 14.04.


text:
Q: Filtering Shipping Options In Woocommerce Based on Date So, I have a complex Shipping issue I need to solve in woocommerce.
The three things I need to accomplish are:

*

*Filter shipping methods based on a datepicker.

*Reset the WC()->session->set('chosen_shipping_methods') with the lowest available shipping method after filtering based on the above date, AND THEN set the selected method as the $chosen_method.

*Filter shipping methods based on price.

So, out of these three, #1 and #3 have been simple. I am firing off a $('body').trigger('update_checkout'); when a date is picked, and that sends it to the WC_AJAX->update_order_review method. This then recalculates all the relevant data/methods, and returns the snippets.
However, after filtering my shipping methods and trying to set the cheapest as the first one, AND change the session to match, i'm having problems. It seems that I'm not able to change the session value early enough to be calculated into the correct totals ON THE FIRST TRY. On the second ajax request or page refresh, the session gets set to the correct method.
So, how far up the stack do i need to be to reset that session to get it to listen to that new value on the first try? I need to be able to access the $_POST data, the current available methods, AND be able to reset the session all in one place if possible, but if not, I can run the same code in two places to hopefully get the correct checkout totals and methods set.
Currently, I've been working in cart-shipping.php and i've overwritten one of the functions there to apply some custom filtering, as seen below.
This accomplishes #1 and #3, but I have trouble with the session here. If anybody knows any way to reliably reset that session here, that'd solve all my problems.
function woo_new_cart_shipping_html()
{
   global $woocommerce;

   $data_stream = extract_data_from_str( $_POST['post_data'] );

   $packages      = $woocommerce->shipping->get_packages();
   $chosen_method = isset( $woocommerce->session->chosen_shipping_methods[0] ) ? $woocommerce->session->chosen_shipping_methods[0] : '';

   foreach ( $packages as $i => $package )
   {
      $methods = apply_filters( 'woo_filter_available_methods_by_date',       $package['rates'], $data_stream );

       wc_get_template( 'cart/cart-shipping.php', array('package' => $package,
                                             'available_methods' =>           apply_filters( 'woo_sort_shipping_methods_by_cost', $methods ),
                                             'show_package_details' => ( sizeof( $packages ) > 1 ),
                                             'index' => $i,
                                             'chosen_method' =>      apply_filters( 'woo_set_lowest_shipping_method', $chosen_method, $methods, $data_stream ) ) );

   }
}


text:
Q: Append the specific column in another existing table using SQL QUERY I know it sounds easy when appending a entire row to new table, but this is different

Question 1, state to combine the Table 1 and Table 2 and keep duplicate value, to create a new table, I have used the following query:
CREATE TABLE EMP_TBL_3
(
    EMP_ID int,
    Name varchar(255),
    DOJ int
);

INSERT INTO EMP_TBL_3 (EMP_ID, Name, DOJ)
   SELECT * FROM EMP_TBL_1
   UNION ALL
   SELECT * FROM EMP_TBL_2;

Results:

Now the problem arise at 2nd question, saying: Take the D.O.B from EMP_BRTH_REC and combine them to EMP_TBL_3:
I have tried this query:
ALTER TABLE EMP_TBL_3
ADD DOB int;

SELECT * FROM EMP_TBL_3;

SELECT EMP_ID, Name, DOJ, DOB
FROM EMP_TBL_3
UNION ALL
SELECT EMP_TBL_3.EMP_ID, EMP_TBL_3.Name, EMP_TBL_3.DOJ, EMP_BRTH_REC.DOB
FROM EMP_BRTH_REC
LEFT JOIN EMP_TBL_3 ON EMP_BRTH_REC.EMP_ID = EMP_TBL_3.EMP_ID;

Results:

My desired output is:

How do I do that?

A: If i undertand propery, you just need to do this:
select EMP_TBL_3.EMP_ID, EMP_TBL_3.Name, EMP_TBL_3.DOJ, EMP_BRTH_REC.DOB
from EMP_BRTH_REC LEFT JOIN
     EMP_TBL_3
     on EMP_BRTH_REC.EMP_ID = EMP_TBL_3.EMP_ID;

A: You are twice inserting the records using UNION ALL. I would suggest you to truncate and reload data into Tbl3 as given below:
ALTER TABLE EMP_TBL_3
ADD DOB int;

TRUNCATE TABLE Emp_Tbl_3;

INSERT INTO Emp_Tbl_3(Emp_Id, Name, DOJ, DOB)
SELECT EMP_TBL_1.EMP_ID, EMP_TBL_1.Name, EMP_TBL_1.DOJ, EMP_BRTH_REC.DOB
from
EMP_BRTH_REC
LEFT JOIN EMP_TBL_1
on EMP_BRTH_REC.EMP_ID = EMP_TBL_1.EMP_ID
UNION ALL
SELECT EMP_TBL_2.EMP_ID, EMP_TBL_2.Name, EMP_TBL_2.DOJ, EMP_BRTH_REC.DOB
from
EMP_BRTH_REC
LEFT JOIN EMP_TBL_2
on EMP_BRTH_REC.EMP_ID = EMP_TBL_2.EMP_ID;


text:
Q: Cycle detected when computing super predicates in trait definitions. Rust compile-time error Consider the two traits
trait Super<T: ?Sized> {
    fn test(&self, p: Box<T>) -> Box<T>; // line not necessary to trigger the compilation error
}
trait Child: Super<dyn Child> {}

which yields the following at compile-time:
error[E0391]: cycle detected when computing the super predicates of `Child`
   --> src/main.rs:103:1
    |
    | trait Child: Super<dyn Child> {}
    | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    |
note: ...which requires computing the super traits of `Child`...
   --> src/main.rs:103:1
    |
    | trait Child: Super<dyn Child> {}
    | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    = note: ...which again requires computing the super predicates of `Child`, completing the cycle
note: cycle used when collecting item types in top-level module
   --> src/main.rs:103:1
    |
    | trait Child: Super<dyn Child> {}
    | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

When monomorphizing functions, it was my understanding, that the generics basically get filled in at compile time. This hopefully enabling all sorts of neat optimizations. So I expected something similar to happen for traits, but
trait Super {
    fn test(&self, p: Box<dyn Child>) -> Box<dyn Child>;
}
trait Child: Super {}

actually compiles. So not self-referential after all?
What is going on here? I know, that this error message has caused confusion in the past, but I don't think that applies here. I assume the compiler is being conservative and we could have gotten up to some shenanigans in Super?

A: This I believe is mainly a trait a coherence issue. After monomorphizing the generics, your traits look like this:
trait Super<dyn Child> {
    fn test(&self, p: Box<dyn Child>) -> Box<dyn Child>;
}
trait Child: Super<dyn Child> {}

What happens is when rustc tries to prove the validity of Super<dyn Child> it finds itself needing to evaluate the statement  Super<dyn Child> is valid if and only if Super<dyn Child> is valid, which is an error. On the other hand, in your other example, Child is valid if there exists a valid trait Super with no generic parameters. Because Super has no super traits it is well-formed, meaning both Child and Super are valid. The object safety of Child then follows a similar line of reasoning.
I was able to rewrite the Child trait in a way that does work with the given Super trait. However, before you use it, you should spend some time thinking about other ways to structure your code.
trait Super<T: ?Sized> {
    fn test(&self, p: Box<T>) -> Box<T>;
}
trait Inner {}
trait Marker: Super<dyn Inner> {}
trait Child: Marker {}

impl<T: Super<dyn Inner>> Marker for T {}

impl<T: Super<dyn Child>> Super<dyn Inner> for T {
    fn test(&self, _p: Box<dyn Inner>) -> Box<dyn Inner> {
        unreachable!()
    }
}

The idea here is to use a couple of marker traits for the bounds, and use blanket impls to break the cyclical dependency.
playground

A: I love the trick @Aiden4 showed in this answer. Breaking the cycle basically comes down to having an intermediate Marker type and the best would be some never type like empty enum.
You can still sidestep this by implementing Super<Marker> directly on your type, however stupid it may be. To guard against that Marker trait should be private which would at least prevent other crates from implementing Super<Marker> on their types
If I may be so bold, I'd like to suggest the following improvement:
    mod private {
        pub enum Marker {}
    }

    trait Super<T: ?Sized> {
        fn test(&self, p: Box<T>) -> Box<T>;
    }

    trait Child: Super<private::Marker> {}
    impl<T: Super<dyn Child>> Super<private::Marker> for T {
        // This method literally cannot be called because `Marker` cannot be constructed
        fn test(&self, _p: Box<private::Marker>) -> Box<private::Marker> {
            unreachable!()
        }
    }

The only downside to this pattern is that it's not obvious from Child trait declaration that Super<dyn Child> is it's supertrait

Another solution might be to move the type parameter from the trait declaration into method like this:
    trait Super {
        fn test<T: ?Sized>(&self, p: Box<T>) -> Box<T>;
    }

    trait Child: Super {}


text:
Q: Occasional incorrect values for generated columns in PostgreSQL 13 I have a PostgreSQL 13 server running in Google Cloud and one of our tables has a few generated columns and occasionally I find rows where the value saved in the generated column isn't up-to-date.
For example, if I run a query like:
SELECT * FROM [ table ]
WHERE [ column_name ] != [ generation_expression value ]

Where [ generation_expression value ] is the SQL statement copy-pasted directly from information_schema.columns for that table, I would expect to always find 0 results. Unfortunately, this is not the case.
When I find a row where the generated column isn't up-to-date, I can UPDATE a column in that row and then the generated column will automatically update to the expected value. However, I don't understand why the generated column could ever have an out of date value in the first place.
I don't have any triggers setup for this database (which I confirmed by checking SELECT * FROM information_schema.triggers), and looking at the PostgreSQL docs  I don't see any scenario where a generated column wouldn't have an up-to-date value.
Does anyone know any scenario that could explain why the generated columns in my PostgreSQL database might occasionally contain an incorrect value?
EDIT: Here's a little more information about the table:
           Column           |           Type           | Collation | Nullable |                                                                           Default
----------------------------+--------------------------+-----------+----------+--------------------------------------------------------------------------------------------------------------------------------------------------------------
 id                         | uuid                     |           | not null |
 snooze_until               | timestamp with time zone |           |          |
 latest_message_drafted_at  | timestamp with time zone |           |          |
 latest_message_received_at | timestamp with time zone |           |          |
 latest_message_sent_at     | timestamp with time zone |           |          |
 default_sort_date          | timestamp with time zone |           |          | generated always as (GREATEST(snooze_until, COALESCE(latest_message_received_at, latest_message_sent_at, latest_message_drafted_at))) stored

I don't understand how it is possible for:
SELECT COUNT(*)
FROM threads
WHERE default_sort_date != GREATEST(snooze_until, COALESCE(latest_message_received_at, latest_message_sent_at, latest_message_drafted_at))

to ever return anything other than 0 results (or, if I made a mistake in setting up the generation_expression, why it wouldn't match on 100% of the rows)

A: Sure, one obvious scenario is that you falsely declared a function to be immutable, and then used it in the generation expression.
Another obvious scenario, though less likely, is a bug.  What is the full version of PostgreSQL?
Based on our edit, this does seem like a bug.  But I cannot reproduce it.  Can you discern any pattern to the incorrect rows?  For example, is it storing NULL when it should be non-NULL, or storing a non-NULL when it should be NULL, or is it correctly non-NULL just the wrong non-NULL?  Does it have an old value of one of the underlying columns, or does it have a current value of one of the columns, but not the column which it should be?
I don't see anything between 13.3 and 13.4 which would have fixed this, but it wouldn't hurt to see if you can reproduce it in 13.4.


text:
Q: Guava Maps.uniqueIndex doesn't allow duplicates When I use Maps.uniqueIndex with a List that contains a duplicate value,
java.lang.IllegalArgumentException: duplicate key: 836
at com.google.common.base.Preconditions.checkArgument(Preconditions.java:115)

is thrown.
I find this inconvenient. I suppose it does make some sense, but if a unique collection is required for the function to work correctly, why does it accept an Iterable as an argument in stead of a Set?
List<GroupVO> groups = groupDao.getAll(groupIds);

Map<String,GroupVO> groupMap groupMap = Maps.uniqueIndex(groups, new Function<GroupVO,String>() {
    public String apply(GroupVO vo) {
        return vo.getId().toString();
}});

A: I think what confuses people here (including me when I'm not paying attention) is that typical Maps (e.g. HashMap) will quietly accept writing a new value to a key; the new value replaces the old one, so if the values are also the same, it's a silent no-op. The Immutable*.Builder family throws under the same circumstances.

A: It is simply not possible to have multiple values for one key in a plain Map, thus uniqueIndex cannot do anything else.
It accepts Iterable because accepting only Set would restrict its possible usages and still not solve the problem. Not the values in the given Iterable need to be unique, but the result of applying the given function on each of them.
If you need multiple values per key, you can simply use Multimaps.index, which does the same but returns a Multimap (which can contain an arbitrary number of values per key).


text:
Q: How to test Nestjs interceptor? I can't find any explanation on how to test interceptors in NestJS
This simple example intercepts a POST query to add an attribute to an Example Model provided in the body.
@Injectable()
export class SubscriberInterceptor implements NestInterceptor {
  async intercept(
    context: ExecutionContext,
    next: CallHandler,
  ): Promise<Observable<ExampleModel>> {
    let body: ExampleModel = context.switchToHttp().getRequest().body;
    body = {
      ...body,
      addedAttribute: 'example',
    };
    context.switchToHttp().getRequest().body = body;
    return next.handle();
  }
}

I would like to test what's happening in the intercept function.
So far:
const interceptor = new SubscriberInterceptor();

describe('SubscriberInterceptor', () => {
  it('should be defined', () => {
    expect(interceptor).toBeDefined();
  });

  describe('#intercept', () => {
    it('should add the addedAttribute to the body', async () => {
      expect(await interceptor.intercept(arg1, arg2)).toBe({ ...bodyMock, addedAttribute: 'example' });
    });
  });
});

My question: Should I mock only arg1: ExecutionContext and arg2: CallHandler? If so, how to mock arg1 and arg2? Else How should I proceed?

A: You are right, you should mock the arg1 and arg2,then pass them to intercept method, here is the solution:
SubscriberInterceptor.ts:
interface ExecutionContext {
  switchToHttp(): any;
}
interface CallHandler {
  handle(): any;
}
interface Observable<T> {}
interface ExampleModel {}

interface NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Promise<Observable<ExampleModel>>;
}

export class SubscriberInterceptor implements NestInterceptor {
  public async intercept(context: ExecutionContext, next: CallHandler): Promise<Observable<ExampleModel>> {
    let body: ExampleModel = context.switchToHttp().getRequest().body;
    body = {
      ...body,
      addedAttribute: 'example'
    };
    context.switchToHttp().getRequest().body = body;
    return next.handle();
  }
}

Unit test, mock chained method of executionContext
import { SubscriberInterceptor } from './';

const interceptor = new SubscriberInterceptor();

const executionContext = {
  switchToHttp: jest.fn().mockReturnThis(),
  getRequest: jest.fn().mockReturnThis()
};

const callHandler = {
  handle: jest.fn()
};

describe('SubscriberInterceptor', () => {
  it('should be defined', () => {
    expect(interceptor).toBeDefined();
  });
  describe('#intercept', () => {
    it('t1', async () => {
      (executionContext.switchToHttp().getRequest as jest.Mock<any, any>).mockReturnValueOnce({
        body: { data: 'mocked data' }
      });
      callHandler.handle.mockResolvedValueOnce('next handle');
      const actualValue = await interceptor.intercept(executionContext, callHandler);
      expect(actualValue).toBe('next handle');
      expect(executionContext.switchToHttp().getRequest().body).toEqual({
        data: 'mocked data',
        addedAttribute: 'example'
      });
      expect(callHandler.handle).toBeCalledTimes(1);
    });
  });
});

Unit test result:
 PASS  src/mock-function/57730120/index.spec.ts
  SubscriberInterceptor
    ✓ should be defined (10ms)
    #intercept
      ✓ t1 (11ms)

Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        1.235s, estimated 3s


text:
Q: awk sub in specified column I'm trying to remove text before and after different delimiters, in a specific column only, column 3.
First delimiter is semi-colon, second is comma. They exist in unshown columns too.
Input data:
chr2L   54273   2L_54273_SNP;rs203207895        A       G       999     PASS    ALTCOUNT=118;DB;REFCOUNT=69     GT      ./.     ./.     0/0
chr2L   54339   2L_54339_SNP;rs206877787,rs80377533     T       A       999     PASS    ALTCOUNT=114;DB;REFCOUNT=73     GT      ./.     ./.
chr2L   54587   2L_54587_SNP;rs203534836        A       G       999     PASS    ALTCOUNT=5;DB;REFCOUNT=199      GT      0/0     0/0     0/0

Required output:
chr2L   54273   rs203207895        A       G       999     PASS    ALTCOUNT=118;DB;REFCOUNT=69     GT      ./.     ./.     0/0
chr2L   54339   rs206877787     T       A       999     PASS    ALTCOUNT=114;DB;REFCOUNT=73     GT      ./.     ./.
chr2L   54587   rs203534836        A       G       999     PASS    ALTCOUNT=5;DB;REFCOUNT=199      GT      0/0     0/0     0/0

My efforts have focussed on just removing text before (and including) the semi-colon but with no significant results:
awk '{ if ($3 == ".*\;//") {$3 = ""; print} else { print }; }' < a > b
sed 's/.*;//' a > b
awk '{ sub(/*.;/,"",$3) }1 ' < a > b
awk '{sub(;/./*,""); print}' < a > b

A: I think that you can use something like this:
awk '{ gsub(/^.*;|,.*$/, "", $3) }1' file

This matches anything from the start of the third field up to a semicolon or anything from a comma to the end of a field and replaces them with an empty string.
One of your problems was that you were using *. (incorrect syntax) rather than .* (zero or more of any character).
As suggested in the comments (thanks), you might want to make the pattern slightly more strict, for example:
/^[^;]*;|,[^,]*$/

Which would only match from the start up to the first ; and from the last , to the end. If you're sure that your data always only has one ; and one ,, this isn't necessary but is something to be aware of.
If your input is tab-separated then you can preserve the spaces by instructing awk of this:
awk 'BEGIN { FS = OFS = "\t" } { gsub(/^.*;|,.*$/, "", $3) } 1' file

FS and OFS are the variables used to set the input and output field separators.


text:
Q: BEP-20 Contract no deploy public view functions I am studying how to make BEP-20 tokens. For this I copied the following contract in remix to be able to study it:
Contract in BscScan
If I copy the whole file and compile it in Remix, when I deploy it it doesn't show me any getters. No public view function appears. If I look at the contract displayed on the testnet, it doesn't have any supply of tokens either.
I separated the files and libraries for a better reading. And it is then, when I try to display it, that I get the following error:
VM error: revert. revert The transaction has been reverted to the initial state. Note: The called function should be payable if you send value and the value you send should be less than your current balance. Debug the transaction to get more information.

It gives me the feeling that this contract does not generate the tokens ... What am I wrong?

A: I managed to fix the problem. As I suspected, in order to deploy the contract I have to remove everything related to uniswap and cakeswap. This displays the contract correctly.
If you wanted to deploy the contract with the uniswap interfaces in injected web3, you would need the uniswap testnet.
I found a test address for cake here:
Binance Smart change tesnet


text:
Q: Blazor: How to get the hosted service instance? I added a background service that periodically does something, like the official sample.
public void ConfigureServices(IServiceCollection services)
{
    services.AddRazorPages();
    services.AddServerSideBlazor();
    services.AddHostedService<TimedHostedService>(); <-- here
    services.AddSingleton<WeatherForecastService>();
}

The TimedHostedService has StartAsync and StopAsync. Ultimately, I want to call these in the web browser.
In the FetchData.razor file in the default scaffolding, I tried to refer that service directly, but that did not work. So, I added Start and Stop method to the WeatherForecastService and called them on the click event.
<button @onclick="()=> { ForecastService.Stop(); }">Stop</button>

Now, the problem is, that I don't know how to get the running instance of TimedHostedService in the Stop method of WeatherForecastService.
public class WeatherForecastService
{
....
    public void Stop()
    {
        //how to get TimedHostedService instance?
    }
....
}

I have tried using dependency injection to  get the service provider, but GetService returned null.
IServiceProvider sp;
public WeatherForecastService(IServiceProvider sp)
{
    this.sp = sp;
}

public void Stop()
{
    var ts = sp.GetService(typeof(TimedHostedService)) as TimedHostedService;
    ts.StopAsync(new CancellationToken());
}

A: I question the wisdom of manipulating the service from the GUI but if you're sure you want this then it's about how to register that service.
In startup:
services.AddSingleton<TimedHostedService>();
services.AddHostedService(sp => sp.GetRequiredService<TimedHostedService>());

and then you can
@inject TimedHostedService TimedService


text:
Q: JPanel size issue I have Added two JPanels into a JPanel with GridBagLayout. Now the issue is :
When the main panel loads it shows the upper panel bit above the actual place it should be and when data from db loads into the JTextfields and JComboBox then panel goes to its actual size.
sample code:
public class JPanelIssue extends JPanel {
    public JPanelIssue() {
    JPanel mainPanel = new JPanel(new GridBagLayout());
    JPanel panel1 = new JPanel();
    JPanel panel2 = new JPanel();
    mainPanel.add(panel1, new GridBagConstraints(0, 0, 1, 1, 1.0, 0.6, GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
    mainPanel.add(panel2, new GridBagConstraints(0, 1, 1, GridBagConstraints.REMAINDER, 1.0, 0.4,GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));

    add(mainPanel, new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0, GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
    }
}

panel1 contains fields related to search criteria and panel2 contains JTable dispalying reults.
Is there any problem of AWT event queue or any other problem?
Thanks in advance.

A: comment only
not reproducible from this code snipped, because you forgot to add something about JTextfields and JComboBox then panel goes to its actual size.

When the main panel loads it shows the upper panel bit above the
  actual place it should be and when data from db loads into the
  JTextfields and JComboBox then panel goes to its actual size.

GBC is based on PreferredSize came from JComponents back to the contianer (by assuming that about JPanel)
there are two ways

*

*(proper)set proper PreferredSize for JTextField and JComboBox too

*(sizing hack)override getPreferredSize for JPanel contains  JTextField and JComboBox

*then all another parent(s) / containers should be notified without override any setSize, setBounds, setPreferredSize, only by JFrame.pack()


text:
Q: Example django session and angular cookie with django rest framework Is there any full example on how Django rest framework can send session key to angular to save as cookie ??
Has been struggling for days...
I am running django on port 8000 and in angular ngserve I override httpclient to change the base url from 4200 to 8000 . However , it doesnt get any session,cookie data in the header

A: I worked with Django and AngularJS for sometime. What we did was as below:
index.html
{% load google_analytics %}
{% load seo %}
{% load staticfiles %}
<!DOCTYPE html>
<html ng-app="myApp" lang="en">
<head>
  <!-- ur code -->
</head>
<script src="{% static "JS/external/angular.js" %}"></script>
<body ng-controller="SiteController">
  {{ my_meta.heading }}
  <div ng-init="init('{{ session_key }}','{{ some_other_params }}')">

   <!-- your site code here -->

  </div>
</body>
</html>

In your views.py file:
@csrf_protect
@requires_csrf_token
def index(request):
    if request.session.session_key is None:
        request.session['has_session'] = True
        request.session.modified = True
    return render(request, 'index.html', {'session_key': request.session.session_key,
                                           ..... params which are to be provided before index.html has been rendered ......
                                          }
                  , content_type="text/html")

The SiteController had ng-init which was executed as very 1st thing before any other controller and page was loaded. We had ecommerce site so, the user had to login and logout and we maintained their activity using session.
If you have some different scenario or you need more help then elaborate your question more.


text:
Q: Flattening a tree in linear time using Prolog I am trying to optimize the flattening of a tree data structure in Prolog. I was able to implement the naive solution to do an in-order traversal of the list like this:
naive_flatten_tree(leaf(X), [X]).
naive_flatten_tree(tree(Left, Val, Right), Flattened_Tree) :-
    naive_flatten_tree(Left, LFlat),
    naive_flatten_tree(Right, RFlat),
    append(LFlat, [Val|RFlat], Flattened_Tree).

Straightforward. If it's a leaf, return it, if not recurse on the left and right subtrees. Append the left, right and root values together and you get the flattened tree. Also worth noting that leaves are explicitly stated in the definition of a tree. An example tree is Tree(leaf(2), 1, leaf(3)). So the tree looks like
    1
   / \
  2   3

I need to optimize this to run in linear time to the size of the tree. The description says that this can be done using an accumulator and an auxiliary procedure in which you pass in an empty accumulator. Also states that you build the flattening of the tree in reverse order and then reverse the list once the auxiliary procedure has completed.
Edit:
Is this what you mean? Skeleton code:
flatten_tree(tree(Left, Val, Right), Final):-
    flatten_tree(Tree, Flat, []).

    flatten_tree(Tree, FlatHead, FlatTail):-

And then from here I go one by one adding to FlatTail because that is the accumulator?

A: As suggested by GuyCoder, follows a DCG solution:
%      1
%     / \
%    2   3
%   / \   \
%  4   5   6

example(tree(tree(leaf(4),2,leaf(5)),1,tree(nil,3,leaf(6)))).

% inorder(+Tree, -List)

inorder(Tree, List) :-  phrase(ft(Tree), List, []).

ft(nil) --> [].
ft(leaf(V)) --> [V].
ft(tree(L,V,R)) --> ft(L), [V], ft(R).

Examples:
?- example(T), inorder(T, L).
T = tree(tree(leaf(4), 2, leaf(5)), 1, tree(nil, 3, leaf(6))),
L = [4, 2, 5, 1, 3, 6].

?- inorder(nil, L).
L = [].

?- inorder(leaf(1), L).
L = [1].

?- inorder(tree(leaf(1),2,leaf(3)), L).
L = [1, 2, 3].

?- inorder(tree(leaf(1),2,nil), L).
L = [1, 2].

?- inorder(tree(nil,2,leaf(3)), L).
L = [2, 3].

A: An optimized solution is:
%      1
%     / \
%    2   3
%   / \   \
%  4   5   6

example(tree(tree(leaf(4),2,leaf(5)),1,tree(nil,3,leaf(6)))).

flatten_tree(Tree, InOrder) :-
    flatten_tree(Tree, [], InOrder).

flatten_tree(nil, Suffix, Suffix).
flatten_tree(leaf(Val), Suffix, [Val|Suffix]).
flatten_tree(tree(Left, Val, Right), Suffix, InOrder) :-
    flatten_tree(Right, Suffix, NewSuffix),
    flatten_tree(Left, [Val|NewSuffix], InOrder).

Examples:
?- example(A), flatten_tree(A, L).
A = tree(tree(leaf(4), 2, leaf(5)), 1, tree(nil, 3, leaf(6))),
L = [4, 2, 5, 1, 3, 6].

?- flatten_tree(nil, L).
L = [].

?- flatten_tree(leaf(1), L).
L = [1].

?- flatten_tree(tree(leaf(1),2,leaf(3)), L).
L = [1, 2, 3].

?- flatten_tree(tree(leaf(1),2,nil), L).
L = [1, 2].

?- flatten_tree(tree(nil,2,leaf(3)), L).
L = [2, 3].


text:
Q: What is the best open source SNMP monitoring tool? I am currently working on software that must emit SNMP traps for SNMP versions 1 & 2 and possibly v3 in the future. I have downloaded several and found them to be either too complex or too simplistic. All I want is to view traps and analyze the data structures within them, and the ability to import my custom MIB's. The best I have found so far is ireasonings MIB Browser, but would be greatful for any nice alternatives.

A: The only monitoring tools I've used that utilize SNMP monitoring are Nagios, Zenoss, OpenNMS, and the proprietary product from my company - but they're for full network monitoring.
How many devices are you looking to monitor? If it's only a couple, @Andrew's suggestion of netsnmp may be sufficient.

A: netsnmp - should do everything you're after, with a variety of language bindings to suit every taste.