text:
Q: Is it possible to "reset" docker from previous runs? I am fiddling with a MLFlow + MinIO docker set up, at the moment doing it locally and I have nothing important in the docker, I'm just learning.
Trying to update the MinIO docker image to a jan 2023 one, I am greeted with an error message regarding /data backends, which could be solved using this issue. However, as I said, I'm inexperienced with this stack (so the task seems daunting to me) and also I don't have anything worh saving and/or migrating from the previous docker, so my question is:

how would I "reset" whatever cache docker has from previous image runs so I start anew?


text:
Q: Создание промежуточных размеров изображений Допустим если скопировать изображение с другого сайта на свой сайт с помощью php-функции copy, тогда создаётся только одно скопированное изображение в папке uploads.
Подскажите, как нужно копировать изображения с другого сайта, чтобы создавались все промежуточные размеры, которые выбраны в настройках медиафайлов?
т.е. 150x150, 300x300, 100x100 и т.д.
$attach_id = wp_insert_attachment( $attachment, $guid . $nameImg );
$attach_data = wp_generate_attachment_metadata( $attach_id, $guid . $nameImg );
wp_update_attachment_metadata( $attach_id, $attach_data );

Этот код только делает запись в базу данных.
Плагины не подходят, нужно сделать свой плагин

redpajama_set_name: RedPajamaStackExchange


text:
Q: lightSlider destroy and rebuilt just run one time I have two and more buttons with same class to destroy and rebuild the lightSlider script.
The CMS where I built it, is loading the images and ajax. As the javascript is loaded by ready it does not allow me to trigger the button for a second time.
What would be the way to destroy and rebuild it after ajax is loaded (ajaxComplete)?
  $(document).ready(function() {
    var slider = $('#publicMethods').lightSlider({
        slideMargin:4,
        slideWidth:200,
        loop:false
    });
    $('.load').click(function(){
        slider.destroy();
    });
    $('.load').click(function(){
        if (!slider.lightSlider) {
            slider = $('#publicMethods').lightSlider({
                slideMargin:4,
                slideWidth:200,
                loop:false
            });
        }
    });
  });

A: $('.load').click(function(){
    slider.destroy();
});

Your attaching event handler to a DOM element directly , you need to attach to document instead, like :
$(document).on('click','.load',function(){
  //code here
})


text:
Q: I have a string date yyyymm in my bean and want to compare with present month or previous Calendar Date I have a java bean with String month, that holds a "YYYYMM" value.
I want to compare that value with the current month or previous month using calendar dates. I don't know how to do that.
Currently, in the DateBean bean class I am using a below property like:
private String month;

in the List<DateBean> this gives me "YYYYMM" format values, eg 201906.
I want to compare it with current calender date to check the month is current one or not.
How can I do that?

A: Would you keep an integer value in a string in your bean? A floating-point value? Of course you wouldn't. Then why a month value? Of course you won't do that either. You want:
private YearMonth month;

The YearMonth class is part of java.time, the modern Java date and time API. When your program accepts date and time data as a string, parse it into the appropriate date-time type. You may find it convenient to have a constructor for that, for example:
private static final DateTimeFormatter monthFormatter = DateTimeFormatter.ofPattern("uuuuMM");

public DateBean(String month) {
    this.month = YearMonth.parse(month, monthFormatter);
}

Comparing simply uses the equals method of YearMonth, for example:
    List<DateBean> dateBeans
            = List.of(new DateBean("201901"), new DateBean("201906"));
    YearMonth currentMonth = YearMonth.now(ZoneId.of("Europe/Sofia"));
    for (DateBean bean : dateBeans) {
        if (bean.getMonth().equals(currentMonth)) {
            System.out.println("" + bean.getMonth() + " is current month");
        } else {
            System.out.println("" + bean.getMonth() + " is not current month");
        }
    }

Output is:

2019-01 is not current month
2019-06 is current month

Since the new month doesn't start at the same point in all time zones, I recommend you pass your desired time zone to YearMonth.now().
Edit: Basil Bourque may have an excellent point in his comment: If the sole purpose of your DateBean class was to wrap your year and month strings, you are probably better off replacing it with YearMonth completely than wrapping a YearMonth.
Link: Oracle tutorial: Date Time explaining how to use java.time.


text:
Q: Compare 2 values from same doc in mongo I want to compare 2 values in same doc id
For example
{
    "_id" : ObjectId("5f180441ad1cd40008dc6a5a"),
    "fcount" : 5,
    "key" : "27b6e581-796c-4f3a-882b-0e0c2a0a8a64",
    "student_id" : "5f0ffbcdd67d70c1a3b143aa",
    "__v" : 0,
    "dcount" : 5
}

I have this doc, Now If I want to check fcount and dcount is same then return true. OR false
How can I do this with mongoose query?
update:
const result = await execute_reports_model.find({ _id: _id}).lean().cursor({batchSize: 10}).eachAsync(async ({fcount, dcount}) => {
                if (fcount === dcount) {
                    // true Logic
                } else  {
                   // false logic
                }
             }, { parallel: 10})

So here I will be passing the ID in find. and then compare values that I found from that ID. values are fcount and dcount

A: Using Mongoose's Model.aggregate you can compare a document's two fields and return a boolean:
const result = await model.aggregate([
    { $match: { _id: id } },
    { $project: { _id: 0, isMatch: { $eq: [ "$fcount", "$dcount" ] } } }
])

result value: { "isMatch" : true }

A: This precursor code will help you to solve your problem. It will allow you to find the necessary documents and then deal with all true and false cases.
{batchSize: 10} and {parallel:10} will help you to do your task at parallel. You could easily modify them.
Don't forget to add callback or handle all cases somehow, as you need it to.
await collection_name.find({ your_query: here}).lean().cursor({batchSize: 10}).eachAsync(async ({fcount, dcount}) => {
   if (fcount === dcount) {
       //true case
   } else  {
       //false case
   }
}, { parallel: 10})


text:
Q: Modes of Convergence, Real Analysis ch 2 problem 36 If $\mu(E_n) < \infty$ for $n\in\mathbb{N}$ and $1_{E_n}\rightarrow f$ in $L^{1}$, then $f$ is (a.e. equal to) the characteristic function of a measurable set.
I am not sure how to define $E_n$ in order to prove this, any suggestions is greatly appreciated.

A: Since $1_{E_n}\rightarrow f$ in $L^{1}$
$$
\lim_{n\to\infty}\int_{E_n}|1_{E_n}-f|d\mu=0
$$
So for any $\epsilon>0$, there is a $n$ that
$$
\int_{E_n}|1_{E_n}-f|d\mu<\frac{\epsilon}{2^n}
$$
Let $F_k=\bigcup_{n=k}^{\infty}E_n$. Then
$$
\int_{F_k}|1_{F_k}-f|d\mu\leqslant \sum_{n=k}^{\infty}\int_{E_n}|1_{E_n}-f|d\mu<\frac{\epsilon}{2^k}
$$
Clearly $F_1\supset\cdots \supset F_k\cdots$. So let $F=\bigcap_{k=1}^{\infty}F_k$ and by monotone class theorem
$$
\int_{F}|1_{F}-f|d\mu=\lim_{k\to\infty}\int_{F_k}|1_{F_k}-f|d\mu=0
$$
So $f=1_{F}$ a.e.


text:
Q: Find the extreme values of $x^2+xy+y^2-27=0$ I need to find the extreme values of $x^2+xy+y^2-27=0$. The hint is I need to use two points and use implicit function derivation. My thoughts were to pick up two points and then use the differentiation of this implicit function to get extrema by doing $g'(x)=0$. However, I don't even understand the hint, why would I pick two random points, and how do I know if I properly pick them?

A: To find extremized value of $y$ in$$x^2+xy+y^2-27=0$$
A quadratic equation in $y$ is apparent  here:
$$y^2+(x)y+(x^2-27)=0$$
Using Śrīdhara Ācāryya's method,
$$y=\frac{-x\pm\sqrt{x^2-4(x^2-27)}}{2 }\\y=\frac{-x\pm\sqrt{108-3x^2}}{2 }$$
Differentiating both sides and equating to zero, $$y'=-\frac{1}{2}\pm \frac{-3x}{2\sqrt{108-3x^2}}=0$$
The roots are at $x=\pm3$ which gives $y=\mp6$

The method suggested in the comment section by $\text{Jyrki Lahtonen}$ is a standard and swift way. It is depicted as follows:
Assume $y$ to be a function of $x$ and differentiate $x^2+xy+y^2-27=0$ w.r.t. $x$.
We get $$2x+y+x\frac{dy}{dx}+2y\frac{dy}{dx}=0 \\ \frac{dy}{dx}=\frac{-(2x+y)}{(2y+x)}$$
The extremisation occurs at critical points, i.e. when $\frac{dy}{dx}$ is zero or not defined, i.e.
$$\begin{align}
y&=-2x\\
y&=-\frac{x}{2}
\end{align}$$
Substituting $y$ in the primary equation, we get the values of $y=\pm3,\pm6$ which correspond to the extermisation in terms of $x$ and $y$ repectively.


text:
Q: Multi-threading and making code prettier I am just coding some classic brute force password cracking program, just to improve myself.
I've explained how my program works at the start of the code. Check some of those screenshots to understand easier.
My program works really well but it's a bit dirty and it can be faster if I solve this problems;
I've got two problems,
1-) My code looks so long and dirty because I copied a code block 8 times in a switch case statement. For example case 1 loops with one character length passwords. case 2 = two characters, case 8 = 8 characters length password. The one and only difference between those cases is the "for loop" count, case 1 got 1 for loop, case 8 got 8 nested for loops. I want to make my code prettier, so how can I get rid of this copy&paste code and make it 1/8 size of current size. CTRL + MOUSE WHEEL DOWN , zoom-out and see the copy pasted parts.
2-) It tries 1 digits first, then 2 digits, then 3 digits and so on. So it should wait for 1,2,3 to get the 4 digit ones. And it makes the program lose so much time at higher digits. My CPU i7 3770k got 6 cores, program runs only with one I guess because it says %13 CPU usage. I want to make it higher like 6 cores on the same task OR each core will take care of one part like first core will start looping only 8 character length ones, and second core will do the same with 7 character length ones... and when one of them finds the answer, program will end. Can we really do it?
Code is too long as I said, so I don't put it here,
Here is the code:
http://pastebin.com/ZT373674/
I hope I explained good, thank you for helping from now!

A: With regard to the 8 times duplicated code, factor out the duplicated code into a function.  Then, call the function from within each case.  Pass the number of repetitions for the loop into the function as an argument.
With regard to the multithreading, yes, you could dispatch to multiple threads and make it faster, but that will make your coding much more complex and bug prone.  If you really want to pursue that, it would be better to find a good book on it, or search for previously answered questions on writing multithreaded code.


text:
Q: Asymptotic evaluation of an oscillatory integral First of all, I am a physicist, so please excuse me if I make basic mistakes in the following, I will try to be as rigorous as possible. In my research, I recently came across the following integral for $\Omega>0$:
$\psi(t,\Omega)=\int_{0}^{+\infty}\mathrm{d}\omega\,\Phi(\omega)\frac{\mathrm{e}^{-\mathrm{i}\omega t}-\mathrm{e}^{-\mathrm{i}\Omega t}}{\omega-\Omega}$
$\Phi$ being a smooth and integrable function. Typically, I have to deal with functions of the kind:
$\Phi(\omega)\underset{\omega\to0^+}{\longrightarrow}0$ and $\Phi(\omega)\underset{\omega\to+\infty}{\simeq}K\omega^\alpha\mathrm{e}^{-\omega}$
I would like to estimate $\psi(t,\Omega)$ for $t\to+\infty$.
I tried to rewrite the integrand as follows:
$\frac{\mathrm{e}^{-\mathrm{i}\omega t}-\mathrm{e}^{-\mathrm{i}\Omega t}}{\omega-\Omega}=-\frac{2\mathrm{i}\mathrm{e}^{-\mathrm{i}\frac{\omega+\Omega}{2}t}}{\omega-\Omega}\sin(\frac{\omega-\Omega}{2}t)$
I then used the approximation (fairly widely used in my field, see https://en.wikipedia.org/wiki/Dirac_delta_function#Oscillatory_integrals):
$\frac{\sin(\omega t)}{\omega}\underset{t\to+\infty}{\simeq}\pi\delta(\omega)$, $\delta$ being the Dirac distribution
That would lead me to (warning, here comes the lack of mathematical rigor):
$\frac{\mathrm{e}^{-\mathrm{i}\omega t}-\mathrm{e}^{-\mathrm{i}\Omega t}}{\omega-\Omega}\underset{t\to+\infty}{\simeq}-2\mathrm{i}\pi\mathrm{e}^{-\mathrm{i}\frac{\omega+\Omega}{2}t}\delta(\omega-\Omega)=-2\mathrm{i}\pi\mathrm{e}^{-\mathrm{i}\Omega t}\delta(\omega-\Omega)$
This yields:
$\psi(t,\Omega)\underset{t\to+\infty}{\simeq}-2\mathrm{i}\pi\Phi(\Omega)\mathrm{e}^{-\mathrm{i}\Omega t}$
I tried to perform some numerical calculations with Wolfram Mathematica to check this result, and, if the oscillation induced by the factor $\mathrm{e}^{-\mathrm{i}\Omega t}$ seems present, the modulus of $\psi(t,\Omega)$ does not seem to follow the above approximation.
Since I am no expert in this kind of questions, I don't know how to find information that could help me with this question. If someone has an idea or a good reference to advise it would be of great help to me. Thank you in advance.

A: I followed Ian's suggestion of splitting the integral and, although I am still unable to justify rigorously every point, I think I eventually came up with the correct answer. First of all, the asymptotics of my integral seems to be:
$\psi(t,\Omega)\underset{t\to+\infty}{\simeq}\left(\mathrm{pv}\int_{0}^{\infty}\mathrm{d}\omega\,\frac{\Phi(\omega)}{\Omega-\omega}-\mathrm{i}\pi\Phi(\Omega)\right)\mathrm{e}^{-\mathrm{i}\Omega t}$
To get this result, you split the integral:
$\psi(t,\Omega)=\lim_{\delta\to0^+}\left(\mathrm{e}^{-\mathrm{i}\Omega t}\int_{|\omega-\Omega|>\delta}\mathrm{d}\omega\,\frac{\Phi(\omega)}{\Omega-\omega}+\int_{|\omega-\Omega|>\delta}\mathrm{d}\omega\,\frac{\Phi(\omega)\mathrm{e}^{-\mathrm{i}\omega t}}{\Omega-\omega}+\int_{|\omega-\Omega|<\delta}\mathrm{d}\omega\,\Phi(\omega)\frac{\mathrm{e}^{-\mathrm{i}\omega t}-\mathrm{e}^{-\mathrm{i}\Omega t}}{\omega-\Omega}\right)$
The real part of the asymptotics obviously comes from the first term in this development. The imaginary part comes from the second one, I still need to work a bit to prove this rigorously though. Finally, the third term should vanish, I did not prove it properly but this shouldn't be too difficult to do for someone more literate than I am in this field.


text:
Q: Getting a password from secure text in file to a plain text I have a Script in powershell called SecureText.ps1. what it does is it prompts the user for a password and then converts it into gibberish so the password is secured.
SecuredText.ps1
param([string] $FilePath = (([Environment]::GetFolderPath("myDocuments")+"\SecuredText.txt")))
#SecureText.ps1
#Program the secures text that is only accessable to the user. Defaults to the person "MyDoucments"
$SecurePassword = Read-Host -Prompt "Enter password" -AsSecureString | ConvertTo-SecureString -AsPlainText -Force
$SecurePassword | ConvertFrom-SecureString  | Out-File -FilePath $FilePath
$SecurePassword = $null

I then try to convert that into plain text with these commands
$Password = Get-Content C:\Users\fpettigrosso\Documents\SecuredText.txt | ConvertTo-SecureString -AsPlainText -Force
$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($Password)
$PlainPassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)
Write-Host $PlainPassword

I Expect to get the password back, but I just get back the gibberish. How do I get the password and not the gibberish?

A: e: Some time has passed since I authored this answer, so some knowledge has been gained
You can utilize the Export-CliXml and Import-CliXml cmdlets that handle serializing SecureString / Credential objects for you:
# an empty username causes focus to be on the password field
$credential = Get-Credential -Message 'Enter password' -UserName ' '

# encryption using DPAPI
$credential | Export-CliXml -Path $Path

# decryption
$credential = Import-CliXml -Path $Path

# accessing the password
$credential.GetNetworkCredential().Password

You're generating and decrypting your passwords incorrectly.
## Generation
Read-Host -Prompt 'Enter password' -AsSecureString |
    ConvertFrom-SecureString |
    Out-File -FilePath $Path

## Decryption
(New-Object -TypeName PSCredential -ArgumentList @(
    'user',
    ((Get-Content -Path $Path) | ConvertTo-SecureString)
)).GetNetworkCredential().Password


text:
Q: Flow type. What is the difference between type {} & {||} I dont know what is the exact differences.
I want to know what is the differences

A: According to doc
https://flow.org/en/docs/types/objects/#toc-exact-object-types
{||} is a way to check for "exact" object types => no extra properties will be authorized with type with {||} syntax
sample from doc
// @flow
var foo: {| foo: string |} = { foo: "Hello", bar: "World!" }; // Error!

=> failed because foo can only have a foo property. Bar is unauthorized
but if you do the following it will work
var foo: { foo: string } = { foo: "Hello", bar: "World!" }; // Work


text:
Q: I am using Kafka Producer Api to write messages from a file into kafka topic, but the logs of kafka topic is showing empty? I am using below Producer API code to write messages into Kafka topic, but its unable to write messages into topic:
import java.util.Properties
import com.typesafe.config.ConfigFactory
import org.apache.kafka.clients.producer.{KafkaProducer, ProducerConfig, ProducerRecord}
import scala.io.Source

object KafkaProducerDemo {

    def main(args: Array[String]): Unit = {

        val props = new Properties()
        props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092")
        props.put(ProducerConfig.CLIENT_ID_CONFIG, "KafkaProducerDemo")
        props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer")
        props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer")

        val producer = new KafkaProducer[Nothing, String](props)

        val logMessages = Source.
          fromFile("/opt/gen_logs/logs/access.log").
          getLines.
          toList

        logMessages.foreach(message => {
          val record = new ProducerRecord("retail-multi", message)
          producer.send(record)
        })
    }
}

A: Based on the error you mentioned in comments (java.lang.ArrayIndexOutOfBoundsException: 18), I'd say you've got a mismatch between your client library version and your broker version. Client lib should be < broker (unless client lib supports dynamic api-version checking).
So double check the broker version you are connecting to, and then double check your client library version. Once they match or are compatible, you should be good to go!

A: Hi I this may be because of some kafka version mismatch. I have re-install kafka and sbt. And it started working fine now.


text:
Q: What's the name of the idiom for #defining a symbol to nothing? If I see the line of code
#define IO_API __declspec(dllexport)

I would tell my colleagues "IO_API is defined to __declspec(dllexport)".
However, if I see the line of code
#define IO_API

I'm not sure what I would tell my colleagues briefly and unambiguously: any description tends to wander on a little. Is there a common descriptor?
Edit: I'm not looking for use cases here, merely a name for the idiom.

A: Around here we just say

The macro IO_API expands to nothing.

or

The macro IO_API is empty.

It's really quite subjective but I think the former leads to the least amount of confusion.


text:
Q: Where can I edit the inline code style for a Jekyll blog? I'm trying to set up the styling of my Jekyll blog. I've noticed that the inline code highlighting that uses the two backticks `.
Here you can see the inline highlighting style is very different to the code block styling. The code block styling is done in the _highlighter.scss file. Any ideas where I can edit the style of the inline code?

A: The style location may vary depending on several factors:

*

*the theme you are using and if that theme is customized

*the syntax highlighter engine

In a standard Jekyll instance, inline code blocks will start like <code class="highlighter-rouge>, that is, the style would be a mix of the code tag and the above class.
The easiest way to find out where to change your jekyll instance styling is to use the browser inspect code mode, that will show you which file and style to change.


text:
Q: How to add multiple modules with -add-modules I would like to add multiple modules through the VM options in NetBeans. Currently i have just added 1 module( javafx.controls).

Here is the directory that has all the modules including the one already added.

Does anyone know the separating delimiter?

A: You can use the comma character: ,
The documentation says:

--add-modules <module name>[,<module name>...]
              root modules to resolve in addition to the initial module.
              <module name> can also be ALL-DEFAULT, ALL-SYSTEM,
              ALL-MODULE-PATH.

A: To run JavaFX you have to tell your VM where modules are:
--module-path /Users/sbrbot/JavaFX/javafx-sdk-11.0.2/lib

and then tell what modules to use:
--add-modules javafx.controls,javafx.fxml

A: --add-opens=java.base/java.lang.reflect=ALL-UNNAMED
maybe this helps.


text:
Q: Distriqt Share Native Extension not working with Bitmapdata on Android I want to share an image on social media. The extension works fine with plain text, but when it comes to sharing with bitmapData property, nothing happens (no errors, no prompts, nothing at all).
I've tried the sample project provided in the repository but I get the same result.
I've also found that if I try sharing a file using Share.service.shareFile() it gives me an error:

share:failed::shareFile::Could not access file. Check
WRITE_EXTERNAL_STORAGE permission and FileProvider

Edit: Working on the sample test project,
the manifest additions are as follows (air. included in the package name as it supposed to be).
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

<application>

    <provider
        android:name="com.distriqt.extension.share.content.ShareFileProvider"
        android:authorities="air.com.distriqt.test.sharefileprovider"
        android:grantUriPermissions="true"
        android:exported="false">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/distriqt_share_paths" />
    </provider>

    <activity   android:name="com.distriqt.extension.share.permissions.AuthorisationActivity"
                android:theme="@android:style/Theme.Translucent.NoTitleBar" />

</application>

Share extension version: 6.0.56
Any help is greatly appreciated.

A: Solved by updating the dependency ANEs:
androidx.core
com.distriqt.Core


text:
Q: Canonical Homomorphisms Let $G$ be a group and let $N$ be a normal subgroup. Let $\pi\colon G \to  G/N$ denote the canonical homomorphism. Prove that if $H$ is a subgroup of $G$ then $\pi(H) = \pi(HN)$. Then prove that if $H$ and $K$ are subgroups of $G$, then $\pi(H) = \pi(K)$ if and only if $HN = KN$.
I have been able to show that if $H$ is any subgroup of $G$ then $HN$ is also a subgroup. But I am not really sure where to go to from there.

A: $H \subseteq HN$ implies that $\pi(H)\subseteq\pi(HN)$
Any element of $\pi(HN)$ looks like $(h.n).N$ for some $h\in H$ and $n\in N$. We have to find an element $h_1$ of H s.t $(h_1).N=(h.n)N$ i.e. $((h_1).(h.n)^{-1} )\in N$ i.e. $h_1.n^{-1}.h^{-1}\in N$
So, we can choose our $h_1=h$ because $h.n^{-1}.h^{-1} \in N$ as N is normal
For the second part, assume $\pi (H)=\pi (K)$
To prove, $\pi (HN)=\pi(KN)$ Take $h.n\in HN$ $\pi(h.n)=(h.n).N$
To show $\pi(h.n)=(h.n).N\in \pi(KN)$
i.e. $\exists k_1\in K$ and $n_1 \in N$s.t. $(h.n).N=(k_1.n_1).N$
i.e. $h.n.(k_1.n_1)^{-1} \in N$
then $\pi(h)=h.N\in \pi (H)=\pi (K)$ i.e. $\exists k_2\in K$ $(h).N=(k_2).(N)$ i.e. $(h).(k_2)^{-1}\in(N)$
Let us say $n_2=h.(k_2)^{-1}$ i.e. $h=n_2.k_2$ it follows  $h.n=n_2.k_2.n$
i.e.$h.n.(k_2.n)^{-1}=n_2 \in N$
So our $k_1=k_2$ and $n_1=n$
Therefore, $\pi(HN) \subseteq \pi(KN) $
The inverse inclusion can be shown similarly.
Now, if $HN=KN$ implies $\pi(H)=\pi(K)$ obvious

A: Hints: (1) As $H \subseteq HN$, $\pi(H) \subseteq \pi(HN)$, for the other inclusion let $h \in H$, $n \in N$. Can you find an element $h' \in H$ with $hnN = h'N$ (this will give you $\pi(HN) \subseteq \pi(H)$).
(2) If $HN = KN$ then (1) gives you $\pi(H) = \pi(K)$. For the other direction, try to identify the subgroup $\pi^{-1}\bigl(\pi(H)\bigr)$ as $HN$.


text:
Q: Keeping array keys in JavaScript Is it a feasible solution to keep make arrays with _ids from mongodb database in front-end part?
Let us suppose that I need to maintain the status of people with their ids .
Is it good to associate things like this:
let arr=[];
arr['5bbaea8847910db52c7c3682']='p';
arr['5b9f6a1fd85effbb8acbd1fe']='a';
console.log(arr['5b9f6a1fd85effbb8acbd1fe']);

or Is It better to keep things like this :
 let arr=[];
 arr.push({
     _id:5bbaea8847910db52c7c3682,
     status:'p'
});

I fear if such big ids may lead to memory problems or such things. I have been a C++ programmer previously so it does not appear to be a cool thing to do. Is it OK to do such things in JavaScript ?

A: As said above, u can use object of objects:
let data = {};
data[5bbaea8847910db52c7c3682] = {
   status: 'p'
}

Or a map:
let data = new Map();
data.set(5bbaea8847910db52c7c3682, { status: 'p' });

A: Better to make arr as an object instead of array. Below is an example of creating new object as well as adding/editing it's property.
let obj = {} // or obj = new Object()
obj['5bbaea8847910db52c7c3682'] = 'p'
obj['5b9f6a1fd85effbb8acbd1fe'] = 'a'
console.log(obj)

To delete certain property, simply use delete keyword:
let obj = {}
obj['5bbaea8847910db52c7c3682'] = 'p'
delete obj['5bbaea8847910db52c7c3682']
console.log(obj)

if the property name is reserved keyword or it's contains a whitespace or special characters, then the way to set/get the property's value it's the same like set/get on array. Other than that, dot notation can be used.
let obj = {}

obj.someProperty = 'old value'
obj['someProperty'] = 'new value'

console.log(obj.someProperty) // 'new value'
console.log(obj['someProperty']) // 'new value'

A: In this situation, it is better to use an array of objects (as you suggested), or simply an ordinary object:
let ob = {};
ob['5bbaea8847910db52c7c3682'] = 'p';
ob['5b9f6a1fd85effbb8acbd1fe'] = 'a';

console.log(ob['5b9f6a1fd85effbb8acbd1fe']);


text:
Q: ms-access: doing something on database open is it possible to run a sub or function as soon as the user opens an access database file? if so, how?

A: You could open a hidden form on start up like in Access 2007 Startup.
This is also possible in older Access version.
You may use this hidden form for logging or other 'system'-related tasks.

A: Create your function:
Public Function DoSomething()
    ' do stuff '
End Function

Then create a macro with the run code action which calls your DoSomething function.  Name the macro autoexec.  Then, every time the data base starts up, it will run your autoexec macro.
Another thing you can do is set a form to open whenever the database starts.  You could then call your DoSomething function from a form event (on open, or on load).
Choose one of those approaches.  Either way, if you ever want to start the database without DoSomething running, hold down the shift key as the database opens to bypass your automatic startup routine.


text:
Q: Script to extract a zip password in Full ASCII with control characters (0-31 range)
*

*Suppose my foo.zip is encrypted with a password containing extended and control ASCII.

*Its password in hex format is e.g. something like 9E6A01D15774FF

*I have made a password.txt by editing its hex to match my password, so it will look like this when opening with a text editor: �j�ÑWtÿ

*I have no programming skills (!!!)

Problem is: I found no way to tell a zip extractor to read a binary password. I even tryed creating a simple script and editing its hex in the password part, so it looks like this
#!/bin/bash
unzip -P �j�ÑWtÿ /home/john/foo.zip

But stdin will always try to represent the non-printable characters and fails to pass the correct binary password to unzip.
My question is: Can you point me out a way to write a simple script (javascript?) that can extract zip files and supports full ascii passwords? (Please, remember I don't have any clue and my knowledge is very basic)
I know I may have made a stupid question, since nobody will want to include control characters in their password, but I'm stuck for a week in trying to figure this out. I would really appreciate your help!


text:
Q: How to make Textbox only accept alphabetic characters I have a windows forms app with a maskedtextbox control that I want to only accept alphabetic values in.
Ideally, this would behave such that pressing any other keys than alphabetic keys would either produce no result or immediately provide the user with feedback about the invalid character.

A: This question has probably been asked and answered a million times on every conceivable programming forum. Every answer provided has the distinction of being unique to the stated requirements.
Since you are using a MaskedTextBox, you have additional validation features available to you and do not really need to handle keypresses. You can simply set the Mask property to something like "L" (character required) or "?" (optional characters). In order to show feedback to the user that the input is not acceptable, you can use the BeepOnError property or add a Tooltip to show the error message. This feedback mechanism should be implemented in the MaskedInputRejected event handler.
The MaskedTextBox control offers a ValidatingType property to check input that passes the requirements of the Mask, but may not be the correct datatype. The TypeValidationCompleted event is raised after this type validation and you can handle it to determine results.
If you still need to handle keypress events, then read on...!
The method I would recommend in your case is that instead of handling the KeyDown event (you ostensibly do not need advanced key handling capability) or using a Regex to match input (frankly, overkill), I would simply use the built-in properties of the Char structure.
private void maskedTextBox1_KeyPress(object sender, KeyPressEventArgs e)
{
  Char pressedKey = e.KeyChar;
  if (Char.IsLetter(pressedKey) || Char.IsSeparator(pressedKey) || Char.IsPunctuation(pressedKey))
  {
    // Allow input.
    e.Handled = false
  }
  else
    // Stop the character from being entered into the control since not a letter, nor punctuation, nor a space.
    e.Handled = true;
  }
}

Note that this snippet allows you to handle punctutation and separator keys as well.

A: From MSDN (This code shows how to handle the KeyDown event to check for the character that is entered. In this example it is checking for only numerical input. You could modify it so that it would work for alphabetical input instead of numerical):
// Boolean flag used to determine when a character other than a number is entered.
private bool nonNumberEntered = false;

// Handle the KeyDown event to determine the type of character entered into the control.
private void textBox1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
    // Initialize the flag to false.
    nonNumberEntered = false;

    // Determine whether the keystroke is a number from the top of the keyboard.
    if (e.KeyCode < Keys.D0 || e.KeyCode > Keys.D9)
    {
        // Determine whether the keystroke is a number from the keypad.
        if (e.KeyCode < Keys.NumPad0 || e.KeyCode > Keys.NumPad9)
        {
            // Determine whether the keystroke is a backspace.
            if(e.KeyCode != Keys.Back)
            {
                // A non-numerical keystroke was pressed.
                // Set the flag to true and evaluate in KeyPress event.
                nonNumberEntered = true;
            }
        }
    }
    //If shift key was pressed, it's not a number.
    if (Control.ModifierKeys == Keys.Shift) {
        nonNumberEntered = true;
    }
}

// This event occurs after the KeyDown event and can be used to prevent
// characters from entering the control.
private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
    // Check for the flag being set in the KeyDown event.
    if (nonNumberEntered == true)
    {
        // Stop the character from being entered into the control since it is non-numerical.
        e.Handled = true;
    }
}

A: This code will distinguish alphabetic character key presses from non alphabetic ones:
private void maskedTextBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (Regex.IsMatch(e.KeyChar.ToString(), @"\p{L}"))
    {
        // this is a letter
    }
    else
    {
        // this is NOT a letter
    }
}

Update: note that the above regex pattern will match ONLY alphabetic characters, so it will not allow spaces, commas, dots and so on. In order to allow more kinds of characters, you will need to add those to the pattern:
// allow alphabetic characters, dots, commas, semicolon, colon
// and whitespace characters
if (Regex.IsMatch(e.KeyChar.ToString(), @"[\p{L}\.,;:\s]"))

A: // This is  to allow only numbers.
// This Event Trigger, When key press event occures ,and it only allows the Number and Controls.,
private void txtEmpExp_KeyPress(object sender, KeyPressEventArgs e)
{
    if(Char.IsControl(e.KeyChar)!=true&&Char.IsNumber(e.KeyChar)==false)
    {
        e.Handled = true;
    }
}

//At key press event it will allows only the Characters and Controls.
private void txtEmpLocation_KeyPress(object sender, KeyPressEventArgs e)
{
    if (Char.IsControl(e.KeyChar) != true && Char.IsNumber(e.KeyChar) == true)
    {
        e.Handled = true;
    }
}

A: //Add a text box select it & goto Events & In the event list double click on "keypress" event.
        if (!char.IsLetter(e.KeyChar))
        {
            MessageBox.Show("Enter only characters");
        }
    }

A: This works for me :)
    private void txt_KeyPress(object sender, KeyPressEventArgs e)
    {
        e.Handled = !((e.KeyChar != 'ñ' && e.KeyChar != 'Ñ') && char.IsLetter(e.KeyChar));
    }

A: Try this code
    private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        e.Handled = !(char.IsLetter(e.KeyChar) || e.KeyChar == (char)Keys.Back || e.KeyChar == (char)Keys.Space);
    }


text:
Q: extract some texts from html I have html "page" as follows:

ヤブツバキクラス(常緑広葉樹林) Camellietea japonicae Miyawaki et
Ohba 1963

 リュウキュウガキ-クスノハガシワオーダー Diospyro maritimae-Mallotetalia philippensis
Fujiwara 1981

  ナガミボチョウジ-リュウキュウガキ群団 Psychotrio manilensis-Diospyrion maritimae
Niiro et al. 1974

I need to extract as follows:
ヤブツバキクラス(常緑広葉樹林), Camellietea japonicae
リュウキュウガキ-クスノハガシワオーダー, Diospyro maritimae-Mallotetalia philippensis
ナガミボチョウジ-リュウキュウガキ群団, Psychotrio manilensis-Diospyrion maritimae
I tried as:
soup = BeautifulSoup(page, features="lxml")

rows = soup.find_all('span')
for row in rows:
        print (row.text.strip().split(' ')[0])

But, it extracted as follows:
ヤブツバキクラス(常緑広葉樹林)
Camellietea
Camellietea
Miyawaki
リュウキュウガキ−クスノハガシワオーダー
Diospyro
Diospyro
Fujiwara
ナガミボチョウジ−リュウキュウガキ群団
Psychotrio
Psychotrio
Niiro

A: Step through the results and take the first two of every four spans:
for i in range(1, len(rows), 4):
    print(rows[i].string.strip(),
          list(rows[i+1].children)[1].string.strip())

#ヤブツバキクラス(常緑広葉樹林)Camellietea japonicae
#リュウキュウガキ-クスノハガシワオーダー Diospyro maritimae-Mallotetalia philippensis
#ナガミボチョウジ-リュウキュウガキ群団 Psychotrio manilensis-Diospyrion maritimae

A: You can also use :first-child and attribute=value selectors with bs4 4.7.1
from bs4 import BeautifulSoup as bs

html = '''

ヤブツバキクラス(常緑広葉樹林) Camellietea japonicae Miyawaki et
Ohba 1963

 リュウキュウガキ-クスノハガシワオーダー Diospyro maritimae-Mallotetalia philippensis
Fujiwara 1981

  ナガミボチョウジ-リュウキュウガキ群団 Psychotrio manilensis-Diospyrion maritimae
Niiro et al. 1974

  '''

soup = bs(html, 'lxml')
print([i.text.strip() for i in item.select('span[style="font-size:11.0pt"], [lang=EN-US]:first-child')])


text:
Q: How to use FastAPI Depends objetcs with asyncio? I have a FastAPI endpoint where it need to download some files from HDFS to the local server.
I'm trying to use asyncio to run the function that will download the files in a separate process.
I'm using FastAPI Depends to create a HDFS client and inject the object in the endpoint execution.
from fastapi import Depends, FastAPI, Request, Response, status
from hdfs import InsecureClient
import asyncio
from concurrent.futures.process import ProcessPoolExecutor

app = FastAPI()

HDFS_URLS = ['http://hdfs-srv.local:50070']

async def run_in_process(fn, *args):
    loop = asyncio.get_event_loop()
    return await loop.run_in_executor(app.state.executor, fn, *args)  # wait and return result

def connectHDFS():
    client = InsecureClient(url)
    yield client

def fr(id, img, client):
    # my code here

    client.download(id_identifica_foto_dir_hdfs,  id_identifica_foto_dir_local, True, n_threads=2)

    # my code here

    return jsonReturn

@app.post("/")
async def main(request: Request, hdfsclient: InsecureClient = Depends(connectHDFS)):

    # Decode the received message
    data = await request.json()
    message = base64.b64decode(data['data']).decode('utf-8').replace("'", '"')
    message = json.loads(message)

    res = await run_in_process(fr, message['id'], message['img'], hdfsclient)

    return {
        "message": res
    }

@app.on_event("startup")
async def on_startup():
    app.state.executor = ProcessPoolExecutor()

@app.on_event("shutdown")
async def on_shutdown():
    app.state.executor.shutdown()

But I'm not able to pass ahead the hdfsclient object:
res = await run_in_process(fr, message['id'], message['img'], hdfsclient)

I'm getting the following error:
Traceback (most recent call last):
  File "/home/kleyson/.virtualenvs/reconhecimentofacial/lib/python3.7/site-packages/uvicorn/protocols/http/h11_impl.py", line 396, in run_asgi
    result = await app(self.scope, self.receive, self.send)
  File "/home/kleyson/.virtualenvs/reconhecimentofacial/lib/python3.7/site-packages/uvicorn/middleware/proxy_headers.py", line 45, in __call__
    return await self.app(scope, receive, send)
  File "/home/kleyson/.virtualenvs/reconhecimentofacial/lib/python3.7/site-packages/fastapi/applications.py", line 199, in __call__
    await super().__call__(scope, receive, send)
  File "/home/kleyson/.virtualenvs/reconhecimentofacial/lib/python3.7/site-packages/starlette/applications.py", line 111, in __call__
    await self.middleware_stack(scope, receive, send)
  File "/home/kleyson/.virtualenvs/reconhecimentofacial/lib/python3.7/site-packages/starlette/middleware/errors.py", line 181, in __call__
    raise exc from None
  File "/home/kleyson/.virtualenvs/reconhecimentofacial/lib/python3.7/site-packages/starlette/middleware/errors.py", line 159, in __call__
    await self.app(scope, receive, _send)
  File "/home/kleyson/.virtualenvs/reconhecimentofacial/lib/python3.7/site-packages/starlette/exceptions.py", line 82, in __call__
    raise exc from None
  File "/home/kleyson/.virtualenvs/reconhecimentofacial/lib/python3.7/site-packages/starlette/exceptions.py", line 71, in __call__
    await self.app(scope, receive, sender)
  File "/home/kleyson/.virtualenvs/reconhecimentofacial/lib/python3.7/site-packages/starlette/routing.py", line 566, in __call__
    await route.handle(scope, receive, send)
  File "/home/kleyson/.virtualenvs/reconhecimentofacial/lib/python3.7/site-packages/starlette/routing.py", line 227, in handle
    await self.app(scope, receive, send)
  File "/home/kleyson/.virtualenvs/reconhecimentofacial/lib/python3.7/site-packages/starlette/routing.py", line 41, in app
    response = await func(request)
  File "/home/kleyson/.virtualenvs/reconhecimentofacial/lib/python3.7/site-packages/fastapi/routing.py", line 202, in app
    dependant=dependant, values=values, is_coroutine=is_coroutine
  File "/home/kleyson/.virtualenvs/reconhecimentofacial/lib/python3.7/site-packages/fastapi/routing.py", line 148, in run_endpoint_function
    return await dependant.call(**values)
  File "./asgi.py", line 86, in main
    res = await run_in_process(fr, message['id'], message['img'], hdfsclient)
  File "./asgi.py", line 22, in run_in_process
    return await loop.run_in_executor(app.state.executor, fn, *args)  # wait and return result
  File "/usr/lib/python3.7/multiprocessing/queues.py", line 236, in _feed
    obj = _ForkingPickler.dumps(obj)
  File "/usr/lib/python3.7/multiprocessing/reduction.py", line 51, in dumps
    cls(buf, protocol).dump(obj)
TypeError: can't pickle _thread.lock objects

How can have the hdfsclient available inside the def fr() function without the need to create a new connection on every new request ? I mean, how to create the hdfsclient on the application startup and be able to use it inside the function ?

A: The entire point of asyncio is to do what you are trying to achieve in the same process.
The typical example is a web crawler, where you open multiple requests, within the same thread/process, and then wait for them to finish. This way, you will get data from multiple urls without having to wait each single request before starting the next one.
The same applies in your case: call your async function that downloads the file, do your stuff and then wait for the file download to complete (if it hasn't completed yet). Sharing data between processes is not trivial, and your function is not working because of that reason.
I suggest you to first understand what async is and how it works, before jumping into doing something that you don't understand.
Some tutorials on asyncio
https://www.datacamp.com/community/tutorials/asyncio-introduction
https://realpython.com/lessons/what-asyncio/
https://docs.python.org/3/library/asyncio.html


text:
Q: Should I buy a higher-output power supply if I don't play game at all? I'm buying a new power supply for my computer. I'm considering two models, one is 650W and the other 750W. The 750W one is cheaper than 650W, but my computer doesn't need that much power. I never play any graphic-intensive games. My current 350W PSU is barely doing the job well.
So which one should I buy? If a buy the 750W, will it consume more power in the long run?

A: The rating of the power supply is it's peak rating. That is the maximum power it can deliver.
If you only draw 500W of power (say) then the running costs of the 750W and 650W PSU will be the same - assuming they have roughly the same efficiency rating.
There are many other, possibly more important, factors than cost:

*

*Quality. This is a good guide to the efficiency and life-span of the PSU.

*Noise (thanks Richard). You are going to be sitting next to this device for long periods and a noisy fan is going to get annoying (at best) and really uncomfortable (at worst), so look for a quiet one.

*Cable management. A more expensive PSU might have more, and more varied internal power connectors so you can connect up all your internal peripherals without extra splitters/converters. Though this is also often a function of the output. A higher rated PSU is going to have more connectors than a lower rated one.

Therefore I'd consider buying the cheapest one that delivers more power than you need, but meets the other criteria outlined above. Having a good margin is useful as you don't have to worry if you add more hard-drives or a more powerful graphics card in the future.


text:
Q: Android store user data based on login I have a certain small amount of data that I would like to store and sync based on google id with which user has logged onto device.
For example , In app user saves his favourite book names.I want his favourite book names to available on his mobile / tablet or any device he logs in using that goole id.So basically I want this data to be tied to his login.
Any ideas how we can achieve this ? Is some sort of storing / syncing mechanism available in android or do i need to take some custom route ?

A: In one of the apps i am currently developing i decided to use the Google Drive SDK for this matter. What i do basically is to create a file in the server, with the entries i want to sync, lets say (this is an example):
color=blue
animal=monkey

And every time i create new entries, i would download that file from google drive, extend it, and then upload again.
Example of file creation (you can create folders also):
File Creation
For the sync purposes, all your devices are supposed to be connected with the same Google account, so all of them will have access to that file.
You can check at the beginning of the app if the file have changed, and download it to get the new entries. Or you can (never tried this yet) make create a subscription to a file, so you will receive a notification when that file changed and make the sync.
Subscription tutorial:
Subscription
Here are a couple of links you might find interesting:
GitHub with sample apps by the Google Drive team
Google Drive Android API guide
Hope it helps!


text:
Q: Changing the name of the html button that is located on another page I have page_a.cfm and page_b.cfm. On first page(page_a.cfm) a I have a cfinput (type submit) button that when is clicked it redirects you to page_b.cfm where some queries are run. On this page there is also a button (called "Back") that send you back to page_a.
I want the text of the button on page_a.cfm to change based on some condition on page_b.cfm so when I click the "back" button on page_b.cfm and send me back to page_a.cfm the button's text had changed.
On page_a.cfm I have this:
<cfform action="page_b.cfm">
      <cfinput type="Submit" name="multiring_btn" class = "multiringButton"
value="ACTIVATE after hours voicemail"/>
</cfform>

On page_b.cfm I have this:
<cfif someConditions = true>
    Successfully changed
<cfelse>
    An error has occurred!
</cfif>

<cfform action="page_a.cfm">
    <cfinput type="submit" name="back_btn" value="Back">
</cfform>

<script type="text/javascript">
    function toggleText(multiringButton)  {
        var text = document.getElementById(multiringButton).firstChild;
        text.data = text.data == "ACTIVATE after hours voicemail" ? "DEACTIVATE after hours voicemail" : "ACTIVATE after hours voicemail"; }
</script>

However when I click the button "back" the text of the button on page_a.cfm is still the same.

A: You can use a URL parameter. On your form action you can attach the parameter:
<cfform action="page_a.cfm?back=true">
    <cfinput type="submit" name="back_btn" value="Back">
</cfform>

Then on your page a you can pull the URL parameter using JS and change the text of the button. See this post for many ways to get the parameter: How can I get query string values in JavaScript?


text:
Q: How to handle sigaction() gracefully and give back to parent process Is there a way to catch a signal with sigaction and get back to parent process
after handle the error properly?
To be more specific, by following code I can do some error handle, but others can not get same crash notification after my sigaction handler.
..Thanks a lot!
static struct sigaction g_defaultsigsegvhndlr;

VOID InvokeDefaultHndlr(
    struct sigaction* pAction,
    INT32             sigNum,
    siginfo_t*        pSigInfo,
    VOID*             pContext)
{
    if (pAction->sa_flags & SA_SIGINFO)
    {
        pAction->sa_sigaction(sigNum, pSigInfo, pContext);
    }
    else
    {
        pAction->sa_handler(sigNum);
    }
}

VOID SignalCatcher(
    INT32      sigNum,
    siginfo_t* pSigInfo,
    VOID*      pContext)
{
    switch (sigNum)
    {
        case SIGSEGV:
            InvokeDefaultHndlr(&g_defaultsigsegvhndlr, sigNum, pSigInfo, pContext);
            break;
        default:
            {
            }
    }
}

VOID RegisterSignal()
{
    struct sigaction newSigAction;

    memset(&newSigAction, '\0', sizeof(struct sigaction));

    if (sigaction(SIGSEGV, NULL, &g_defaultsigsegvhndlr) < 0)
    {
        ALOGE("Failed to get signal handler for SIGSEGV");
    }

    newSigAction              = g_defaultsigsegvhndlr;
    newSigAction.sa_flags    |= SA_SIGINFO;
    newSigAction.sa_sigaction = SignalCatcher;

    if (sigaction(SIGSEGV, &newSigAction, NULL) < 0)
    {
        ALOGE("Failed to register signal handler for SIGSEGV");
    }
}

// Just a sample, I will invoke RegisterSignal() in main thread loop
int main()
{
    ...
    RegisterSignal();
    ...
}


text:
Q: How does injecting of EntityManager in Spring bean work? I'm trying to understand, how does injecting of EntityManger in Spring bean work.
I have bean
@Service
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class TestUpdateService {

    @PersistenceContext
    private EntityManager entityManager;

    private final OrderRepository orderRepository;

    @Transactional
    public void doWork(Long id) {
        Order order = orderRepository.findById(id).get();
        entityManager.detach(order);
        orderRepository.save(order);
    }
}

And have a couple of questions:

*

*Am I right that for every call of my transactional method doWork new instance of EntityManager will be created? I read (or mb misunderstood) on stackoverflow that entity manager annotated with @PersistanceContext creates own EntityManager for each transaction.

*If it is so, does @Autowired work the same way?

*If it isn't so, then how do these both annotations work?


text:
Q: Querying 2 arrays based on specific indices in Mongo I am trying to pull data from 2 arrays (date and price time series) above a certain date cutoff oldest using pymongo.
date_price_collection.aggregate([
        { '$match': { 'ticker': ticker } },
        {
            '$project': {
                'dates': { '$gte': ['dates', oldest] },
                #prices to match these dates
            },
        },
    ],
);

The way data is organized is there are 2 arrays, one for dates and one for prices of the same length. How can I pull prices as well that correspond to dates > oldest?
Thank you very much for any advice!

A: What you could do is first $filter the date array, then use $slice to match the proper prices, like so:
const oldest = ...date;

db.collection.aggregate([
  {
    "$addFields": {
      "dates": {
        $filter: {
          input: "$dates",
          as: "date",
          cond: {
            $gte: [
              "$$date",
              oldest
            ]
          }
        }
      }
    }
  },
  {
    $project: {
      dates: 1,
      prices: {
        $slice: [
          "$prices",
          {
            "$multiply": [
              -1,
              {
                $size: "$dates"
              }
            ]
          },
          2
        ]
      }
    }
  }
])

Mongo Playground


text:
Q: PHP-парсинг Всем привет. Хочу у вас узнать, как парсить страницу с помощью PHP. Приведу пример, как я, допустим, делал это на javascript:
var tmp = document.getElementsByTagName('td');
for (i = 0; i < tmp.length; i++) {
    if (tmp[i].innerHTML == 'lol') {
        //.....
    }
}

Как мне сделать подобное только на PHP? Желательно не подключать библиотек...
A: В PHP это не проблема, парсинг можно реализовать через: file_get_contents, curl, мульти curl и сокеты. Самыми простыми являются file_get_contents и curl.
Вот пример скрипта с file_get_contents и регуляркой:
$parser = file_get_contents("http://2ip.ru/index.php");
preg_match_all('#<big>([\d\.:]*)</big>#is', $parser, $stat);
foreach ($stat[1] as $ip) {

echo $ip;

}

A: Можно сначала вытащить все содержимое страницы. Это можно сделать двумя способами:
1) Функция file_get_contents(site). Но эта функция не сработает, например, для протокола https. В этом случае поможет cURL(проверьте, чтобы он был включен в PHP.ini):
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_URL, "https://accounts.google.com/ServiceLogin");
curl_exec($ch);

А уже после того, как получили содержимое страницы, можно пропарсить любыми функциями PHP, подходящие для парсинга.
A: Nokogiri
A: Парсят в основном через регулярные выражения, но если документ имеет четкий DOM можно воспользоватся функциями обхода DOM


text:
Q: Most elegant way to store string commands for a serial-port device? Let's say i am communicating with a serial-port device and have a significant number of commands (74) for controlling such a device. Wich is the best way to store and use them?
Of course i can organize them the following way:
static char *cmd_msgs[] =
{
    "start",
    "stop",
    "reset",
    "quit",
    "",
    "",
    "",
    "",
    ...
};

Or human readable:
char cmd_start_str[] = "start";
...
char cmd_quit_str[] = "quit";

Can someone point to a working example dealing such a task?

A: The first approach is fine - don't use a lot of global variables with a unique name, they're hard to reference especially when you want to loop through them. That's what the array of strings is for (your first way). If you want human readable code (which you should want), use a sensibly named enumeration of which the values correspond to the actual command strings. So do something like
const char *cmds[] = {
    "command 1",
    "command 2",
    "Print Hello World",
    "Explode House"
};

enum {
    COMMAND_ONE,
    COMMAND_TWO,
    COMMAND_SAYHELLO,
    COMMAND_BOOM
};

This way you can easily reference your commands by indexing the array, but you still have himan readability by writing cmds[COMMAND_SAYHELLO] etc.

A: If you use the first option, you would typically need a second set of constants, or #defines to define the offset of each string in the array:
e.g.
#DEFINE cmd_start 0
#DEFINE cmd_stop 1

so this could be used    cmd_msgs[cmd_start]
So I would go with your second option
char* cmd_start_str = "start";

A: For this application, I would use an array of structures.
// Command handler signature. Choose as per your requirement.
    typedef int (*cmdHandlerType)(char * hostCmdString);

    //Command Structure
    typedef struct
    {
        char *commandString; /**< points to the Command String*/
        cmdHandlerType cmdHandler; /**< points to the Command function*/
    } commandStruct;

    //All the commands and its functions
    static commandStruct  Commands[] = {
                            {"TEMP", TempCommand},
                            {"GAIN",   GainCommand},
                            {"SETPT", SetPtCommand},
                            {"...", ... },
                         };
int TempCommand( char *str)
{
     ...
}

This way when you get a command from the host, you could match the the command string and call the corresponding handler.


text:
Q: SQL Server Connection Limit What is the concurrent connection limit of SQL Server?
In the
microsoft docs ,it is saying "SQL Server allows a maximum of 32,767 user connections.".
Should we think that value as per SQL Server instance?
I mean Let's say we are using SQL Server high availability like the structure in high availability. Then we will have had multi SQL Server instances. One of them must be master instance and rest of them are slave instances.
Then shortly;

*

*Does 32,767 mean connection limit per instance?

*If so;
Let's say we have 1 master instance and 3 slave replica instances in  our SQL Server High Availability?

1 * 32,767 + 3 * 32,767 = 137,068
Then will our max connection limit be 137,068?


text:
Q: Remove Wordpress Kentha Theme Purchase Code I bought the Kentha Theme ver 3.2.2 and when I installed it on Wordpress, it was asking for an activation code. I had got the theme a long time ago and have forgot my credentials on Envato Market, so I can't really access the purchase code. How do I bypass the purchase code pop-up and gain access to the full theme since I want to use it for my website. Any help would be grateful!
P.S. I tried resetting my password... no luck sadly, must have used one of my spam emails.

A: You should contact Envato support, bypassing the license system is illegal and risky at the same time.
Look into your downloaded theme folder, there should be a text document containing your purchase information.

A: Simply contact Envato, give them your transaction ID, and then they will get it to sort it for you.


text:
Q: Долго выполняется запрос, почему SELECT * FROM c_lees
inner join c_price_list on c_lees.id_price_list=c_price_list.id
inner join c_price on c_price.id_price_list=c_lees.id_price_list
inner join c_propel on c_propel.id_price_list=c_lees.id_price_list
inner join c_impel on c_impel.id_price_list=c_lees.id_price_list
where c_lees.id_price_list=1

UPD

Добавила индексы, как мне советовали ( пункт 2 в ответе)

не помогло. Долго выполняется

A: Есть несколько способов оптимизации:

*

*Построить EXPLAIN запроса

*Добавить индексы по *.id_price_list

*Сменить на inner join на join

*Построить временную таблицу с индексом на id_price_list:

create temporary table tmp as (
SELECT * FROM c_lees
where c_lees.id_price_list=1);

CREATE INDEX id_price_list ON tmp (id_pl) USING BTREE;

SELECT * FROM tmp
inner join c_price_list on tmp.id_price_list=c_price_list.id
inner join c_price on c_price.id_price_list=tmp.id_price_list
inner join c_propel on c_propel.id_price_list=tmp.id_price_list
inner join c_impel on c_impel.id_price_list=tmp.id_price_list
where tmp.id_price_list=1;


text:
Q: Pesky permission issue I wrote a very simple function in Google App Script:
function addProduct(number) {
  var sheet = SpreadsheetApp.getActiveSheet();
  sheet.appendRow([number, number+1])
}

and tried to run it in Google Spreadsheets by entering =addProduct() in a cell. However, the Google Spreadsheets gave me an error that I don't have the permission to call the function appendRow().
Why is that?

A: *

*Every custom function must return a value to display.

*A custom function cannot affect cells other than those it returns a value to. In other words, a custom function cannot edit arbitrary cells, only the cells it is called from and their adjacent cells. To edit arbitrary cells, use a custom menu to run a function instead. Taken from: Google Developers


text:
Q: "Abstract away from": disregarding details in effort to reach higher general and overarching notion of something I am a native Danish speaker. The Danish definition of the verb abstract translates to "disregarding the subordinate details in an effort to build a general, overarching notion of something". Thus, the verb gives connotations of something elevated, refined or pure. When translating my dictionary suggests "abstract", "disregard", or "abstract away from". The British National Corpus has almost no entries for the term "abstract away", while my gut felling tells me that the connotations associated with "disregard" is not quite right (i.e. "ignore" or "make light of").
Example:

We abstract away from the specific mechanism and instead consider a general setting, where ...

I am open to rewriting the entire sentence, but I am unsure how to capture the feeling of something elevated, refined or pure, i.e. lifting it to a higher level. Or can I write "abstract away from"?

A: The verb to abstract is used in English in the way that the OP describes. Even though this way of using is likely to be found only in the contexts of theoretical nature, it is listed in the widely available, general-purpose dictionaries, such as Lexico

abstract something from
Consider something theoretically or separately from (something else)
'to abstract science and religion from their historical context can lead to anachronism'

and Merriam-Webster

abstract
to consider apart from application to or association with a particular instance

This way of using the verb calls for the preposition from. While saying to abstract away from would not be incorrect, away seems redundant, as it doesn't really add anything to to abstract from.

A: This is an interesting and difficult question.  The first thing to say is that the use of 'abstract' as a verb is uncommon in English.  The past form, 'abstracted' is applied as a description of someone whose mind is on other things, or removed from the world around them. I normally expect that Danes know English at least as well as I do.  The Danish word is closer to its Latin root 'abstraho' than the English, which reflects the supine form of that verb, which means 'I draw/drag away' or 'remove'.
The nearest I can get to your fascinating Danish usage is the noun 'abstract', which is an academic term for the summary of an academic paper or thesis or dissertation, which summarises the essence of the paper, without any of the detailed arguments beyond their general character.  So it does not apply to the sort of thing for which you are looking either.  It is something 'withdrawn' or 'taken away' from it.  Of course the adjective 'abstract' gets us a bit closer.  Abstract things are removed from everyday tangible reality.  We talk, similarly, of abstract art, and we can certainly talk of discussing things or plans 'in the abstract', meaning in a theoretical way.
Looking at Roget's wonderful Thesaurus, I do not get much further.  The verb can be used for to 'take away' 'shorten' or 'be concise'.
The full Oxford English Dictionary gets me a little bit closer to what you are looking for.

To withdraw, deduct, remove or take away something.  So Boyle in 1685 gives us:  "having <dephlagoned?> spirit of salt and gently abstracted the whole spirit, there remaineth in the retort a ???? substance."  (my apologies that my failing eyesight and magnifying glass cannot get me to see every word in this miniaturised OED!).

In 1690, John Locke in his *On Human Understanding *is saying:

Truth and Certainty of Moral Discourses abstracts from the Lives of Men."

This is getting a bit nearer the mark, but is still not quite there and takes us back nearly 350 years!.
Better is the definition:

To separate in mental conception; to consider apart from the physical manifestation.

This surely is on the money for you.  Citations go back the the sixteenth century and the latest is from the late 19th century, and they apply to logic and reasoning.

To abstract is to separate the qualities common to all individuals from the peculiarities of each individual. (Jevons Elements of Logic 1870)

So I am afraid I have failed and I cannot suggest an alternative word for the Danish.  Could it be, I wonder, that this is one of those beautiful places where one language (here Danish) has a word that has a useful meaning for which another language (here English) has no equivalent?


text:
Q: C++ - using GTest value-parameterized tests with structs causes valgrind errors Can you help me understand what is going on here with GTest and struct packing?
The problem seems to be related to how a struct is packed when used as a value in a value-parameterised test in GTest. Taking the straightforward approach of instantiating a struct for each value results in valgrind errors relating to uninitialised values.
Here's the code concerned:
#include <gtest/gtest.h>

struct TestItem
{
    const char * aString;
    int anInt0;
    int anInt1;
    int anInt2;
};

class TestBase : public ::testing::Test, public ::testing::WithParamInterface<TestItem> {};

TEST_P(TestBase, TestAtoi)
{
    TestItem item = GetParam();
    std::cout << sizeof(TestItem) << std::endl;
    ASSERT_FALSE(0);   // actual test doesn't matter
}

INSTANTIATE_TEST_CASE_P(
        TestBaseInstantiation,
        TestBase,
        ::testing::Values(
                TestItem { "0", 0, 0, 0 }
));

When this is compiled and linked (I built GTest with cmake):
g++ gtest_valgrind.c -o gtest_valgrind -I gtest-1.7.0/include -L gtest-1.7.0/build -lgtest -lpthread -lgtest_main -std=c++11

And then executed with:
valgrind --leak-check=full --show-leak-kinds=all --track-origins=yes ./gtest_valgrind

The following output is produced:
==17290== Memcheck, a memory error detector
==17290== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==17290== Using Valgrind-3.10.0.SVN and LibVEX; rerun with -h for copyright info
==17290== Command: ./gtest_valgrind
==17290==
Running main() from gtest_main.cc
==17290== Use of uninitialised value of size 8
==17290==    at 0x55B89F1: _itoa_word (_itoa.c:180)
==17290==    by 0x55BC6F6: vfprintf (vfprintf.c:1660)
==17290==    by 0x55E1578: vsnprintf (vsnprintf.c:119)
==17290==    by 0x55C3531: snprintf (snprintf.c:33)
==17290==    by 0x41F107: testing::(anonymous namespace)::PrintByteSegmentInObjectTo(unsigned char const*, unsigned long, unsigned long, std::ostream*) (in /home/davida/git/gitlab/fcdm/lwm2m.git/gtest_valgrind)
==17290==    by 0x41F1AA: testing::(anonymous namespace)::PrintBytesInObjectToImpl(unsigned char const*, unsigned long, std::ostream*) (in /home/davida/git/gitlab/fcdm/lwm2m.git/gtest_valgrind)
==17290==    by 0x41F252: testing::internal2::PrintBytesInObjectTo(unsigned char const*, unsigned long, std::ostream*) (in /home/davida/git/gitlab/fcdm/lwm2m.git/gtest_valgrind)
==17290==    by 0x409B8E: testing::internal2::TypeWithoutFormatter<TestItem, (testing::internal2::TypeKind)2>::PrintValue(TestItem const&, std::ostream*) (in /home/davida/git/gitlab/fcdm/lwm2m.git/gtest_valgrind)
==17290==    by 0x409B63: std::basic_ostream<char, std::char_traits<char> >& testing::internal2::operator<< <char, std::char_traits<char>, TestItem>(std::basic_ostream<char, std::char_traits<char> >&, TestItem const&) (in /home/davida/git/gitlab/fcdm/lwm2m.git/gtest_valgrind)
==17290==    by 0x409B3E: void testing_internal::DefaultPrintNonContainerTo<TestItem>(TestItem const&, std::ostream*) (in /home/davida/git/gitlab/fcdm/lwm2m.git/gtest_valgrind)
==17290==    by 0x409B19: void testing::internal::DefaultPrintTo<TestItem>(char, testing::internal::bool_constant<false>, TestItem const&, std::ostream*) (in /home/davida/git/gitlab/fcdm/lwm2m.git/gtest_valgrind)
==17290==    by 0x409ADB: void testing::internal::PrintTo<TestItem>(TestItem const&, std::ostream*) (in /home/davida/git/gitlab/fcdm/lwm2m.git/gtest_valgrind)
==17290==  Uninitialised value was created by a stack allocation
==17290==    at 0x404AAE: gtest_TestBaseInstantiationTestBase_EvalGenerator_() (in /home/davida/git/gitlab/fcdm/lwm2m.git/gtest_valgrind)
==17290==
==17290== Conditional jump or move depends on uninitialised value(s)
==17290==    at 0x55B89F8: _itoa_word (_itoa.c:180)
==17290==    by 0x55BC6F6: vfprintf (vfprintf.c:1660)
==17290==    by 0x55E1578: vsnprintf (vsnprintf.c:119)
==17290==    by 0x55C3531: snprintf (snprintf.c:33)
==17290==    by 0x41F107: testing::(anonymous namespace)::PrintByteSegmentInObjectTo(unsigned char const*, unsigned long, unsigned long, std::ostream*) (in /home/davida/git/gitlab/fcdm/lwm2m.git/gtest_valgrind)
==17290==    by 0x41F1AA: testing::(anonymous namespace)::PrintBytesInObjectToImpl(unsigned char const*, unsigned long, std::ostream*) (in /home/davida/git/gitlab/fcdm/lwm2m.git/gtest_valgrind)
==17290==    by 0x41F252: testing::internal2::PrintBytesInObjectTo(unsigned char const*, unsigned long, std::ostream*) (in /home/davida/git/gitlab/fcdm/lwm2m.git/gtest_valgrind)
==17290==    by 0x409B8E: testing::internal2::TypeWithoutFormatter<TestItem, (testing::internal2::TypeKind)2>::PrintValue(TestItem const&, std::ostream*) (in /home/davida/git/gitlab/fcdm/lwm2m.git/gtest_valgrind)
==17290==    by 0x409B63: std::basic_ostream<char, std::char_traits<char> >& testing::internal2::operator<< <char, std::char_traits<char>, TestItem>(std::basic_ostream<char, std::char_traits<char> >&, TestItem const&) (in /home/davida/git/gitlab/fcdm/lwm2m.git/gtest_valgrind)
==17290==    by 0x409B3E: void testing_internal::DefaultPrintNonContainerTo<TestItem>(TestItem const&, std::ostream*) (in /home/davida/git/gitlab/fcdm/lwm2m.git/gtest_valgrind)
==17290==    by 0x409B19: void testing::internal::DefaultPrintTo<TestItem>(char, testing::internal::bool_constant<false>, TestItem const&, std::ostream*) (in /home/davida/git/gitlab/fcdm/lwm2m.git/gtest_valgrind)
==17290==    by 0x409ADB: void testing::internal::PrintTo<TestItem>(TestItem const&, std::ostream*) (in /home/davida/git/gitlab/fcdm/lwm2m.git/gtest_valgrind)
==17290==  Uninitialised value was created by a stack allocation
==17290==    at 0x404AAE: gtest_TestBaseInstantiationTestBase_EvalGenerator_() (in /home/davida/git/gitlab/fcdm/lwm2m.git/gtest_valgrind)
==17290==
==17290== Conditional jump or move depends on uninitialised value(s)
==17290==    at 0x55BC742: vfprintf (vfprintf.c:1660)
==17290==    by 0x55E1578: vsnprintf (vsnprintf.c:119)
==17290==    by 0x55C3531: snprintf (snprintf.c:33)
==17290==    by 0x41F107: testing::(anonymous namespace)::PrintByteSegmentInObjectTo(unsigned char const*, unsigned long, unsigned long, std::ostream*) (in /home/davida/git/gitlab/fcdm/lwm2m.git/gtest_valgrind)
==17290==    by 0x41F1AA: testing::(anonymous namespace)::PrintBytesInObjectToImpl(unsigned char const*, unsigned long, std::ostream*) (in /home/davida/git/gitlab/fcdm/lwm2m.git/gtest_valgrind)
==17290==    by 0x41F252: testing::internal2::PrintBytesInObjectTo(unsigned char const*, unsigned long, std::ostream*) (in /home/davida/git/gitlab/fcdm/lwm2m.git/gtest_valgrind)
==17290==    by 0x409B8E: testing::internal2::TypeWithoutFormatter<TestItem, (testing::internal2::TypeKind)2>::PrintValue(TestItem const&, std::ostream*) (in /home/davida/git/gitlab/fcdm/lwm2m.git/gtest_valgrind)
==17290==    by 0x409B63: std::basic_ostream<char, std::char_traits<char> >& testing::internal2::operator<< <char, std::char_traits<char>, TestItem>(std::basic_ostream<char, std::char_traits<char> >&, TestItem const&) (in /home/davida/git/gitlab/fcdm/lwm2m.git/gtest_valgrind)
==17290==    by 0x409B3E: void testing_internal::DefaultPrintNonContainerTo<TestItem>(TestItem const&, std::ostream*) (in /home/davida/git/gitlab/fcdm/lwm2m.git/gtest_valgrind)
==17290==    by 0x409B19: void testing::internal::DefaultPrintTo<TestItem>(char, testing::internal::bool_constant<false>, TestItem const&, std::ostream*) (in /home/davida/git/gitlab/fcdm/lwm2m.git/gtest_valgrind)
==17290==    by 0x409ADB: void testing::internal::PrintTo<TestItem>(TestItem const&, std::ostream*) (in /home/davida/git/gitlab/fcdm/lwm2m.git/gtest_valgrind)
==17290==    by 0x409AA6: testing::internal::UniversalPrinter<TestItem>::Print(TestItem const&, std::ostream*) (in /home/davida/git/gitlab/fcdm/lwm2m.git/gtest_valgrind)
==17290==  Uninitialised value was created by a stack allocation
==17290==    at 0x404AAE: gtest_TestBaseInstantiationTestBase_EvalGenerator_() (in /home/davida/git/gitlab/fcdm/lwm2m.git/gtest_valgrind)
==17290==
==17290== Conditional jump or move depends on uninitialised value(s)
==17290==    at 0x55B9659: vfprintf (vfprintf.c:1660)
==17290==    by 0x55E1578: vsnprintf (vsnprintf.c:119)
==17290==    by 0x55C3531: snprintf (snprintf.c:33)
==17290==    by 0x41F107: testing::(anonymous namespace)::PrintByteSegmentInObjectTo(unsigned char const*, unsigned long, unsigned long, std::ostream*) (in /home/davida/git/gitlab/fcdm/lwm2m.git/gtest_valgrind)
==17290==    by 0x41F1AA: testing::(anonymous namespace)::PrintBytesInObjectToImpl(unsigned char const*, unsigned long, std::ostream*) (in /home/davida/git/gitlab/fcdm/lwm2m.git/gtest_valgrind)
==17290==    by 0x41F252: testing::internal2::PrintBytesInObjectTo(unsigned char const*, unsigned long, std::ostream*) (in /home/davida/git/gitlab/fcdm/lwm2m.git/gtest_valgrind)
==17290==    by 0x409B8E: testing::internal2::TypeWithoutFormatter<TestItem, (testing::internal2::TypeKind)2>::PrintValue(TestItem const&, std::ostream*) (in /home/davida/git/gitlab/fcdm/lwm2m.git/gtest_valgrind)
==17290==    by 0x409B63: std::basic_ostream<char, std::char_traits<char> >& testing::internal2::operator<< <char, std::char_traits<char>, TestItem>(std::basic_ostream<char, std::char_traits<char> >&, TestItem const&) (in /home/davida/git/gitlab/fcdm/lwm2m.git/gtest_valgrind)
==17290==    by 0x409B3E: void testing_internal::DefaultPrintNonContainerTo<TestItem>(TestItem const&, std::ostream*) (in /home/davida/git/gitlab/fcdm/lwm2m.git/gtest_valgrind)
==17290==    by 0x409B19: void testing::internal::DefaultPrintTo<TestItem>(char, testing::internal::bool_constant<false>, TestItem const&, std::ostream*) (in /home/davida/git/gitlab/fcdm/lwm2m.git/gtest_valgrind)
==17290==    by 0x409ADB: void testing::internal::PrintTo<TestItem>(TestItem const&, std::ostream*) (in /home/davida/git/gitlab/fcdm/lwm2m.git/gtest_valgrind)
==17290==    by 0x409AA6: testing::internal::UniversalPrinter<TestItem>::Print(TestItem const&, std::ostream*) (in /home/davida/git/gitlab/fcdm/lwm2m.git/gtest_valgrind)
==17290==  Uninitialised value was created by a stack allocation
==17290==    at 0x404AAE: gtest_TestBaseInstantiationTestBase_EvalGenerator_() (in /home/davida/git/gitlab/fcdm/lwm2m.git/gtest_valgrind)
==17290==
==17290== Conditional jump or move depends on uninitialised value(s)
==17290==    at 0x55B96DC: vfprintf (vfprintf.c:1660)
==17290==    by 0x55E1578: vsnprintf (vsnprintf.c:119)
==17290==    by 0x55C3531: snprintf (snprintf.c:33)
==17290==    by 0x41F107: testing::(anonymous namespace)::PrintByteSegmentInObjectTo(unsigned char const*, unsigned long, unsigned long, std::ostream*) (in /home/davida/git/gitlab/fcdm/lwm2m.git/gtest_valgrind)
==17290==    by 0x41F1AA: testing::(anonymous namespace)::PrintBytesInObjectToImpl(unsigned char const*, unsigned long, std::ostream*) (in /home/davida/git/gitlab/fcdm/lwm2m.git/gtest_valgrind)
==17290==    by 0x41F252: testing::internal2::PrintBytesInObjectTo(unsigned char const*, unsigned long, std::ostream*) (in /home/davida/git/gitlab/fcdm/lwm2m.git/gtest_valgrind)
==17290==    by 0x409B8E: testing::internal2::TypeWithoutFormatter<TestItem, (testing::internal2::TypeKind)2>::PrintValue(TestItem const&, std::ostream*) (in /home/davida/git/gitlab/fcdm/lwm2m.git/gtest_valgrind)
==17290==    by 0x409B63: std::basic_ostream<char, std::char_traits<char> >& testing::internal2::operator<< <char, std::char_traits<char>, TestItem>(std::basic_ostream<char, std::char_traits<char> >&, TestItem const&) (in /home/davida/git/gitlab/fcdm/lwm2m.git/gtest_valgrind)
==17290==    by 0x409B3E: void testing_internal::DefaultPrintNonContainerTo<TestItem>(TestItem const&, std::ostream*) (in /home/davida/git/gitlab/fcdm/lwm2m.git/gtest_valgrind)
==17290==    by 0x409B19: void testing::internal::DefaultPrintTo<TestItem>(char, testing::internal::bool_constant<false>, TestItem const&, std::ostream*) (in /home/davida/git/gitlab/fcdm/lwm2m.git/gtest_valgrind)
==17290==    by 0x409ADB: void testing::internal::PrintTo<TestItem>(TestItem const&, std::ostream*) (in /home/davida/git/gitlab/fcdm/lwm2m.git/gtest_valgrind)
==17290==    by 0x409AA6: testing::internal::UniversalPrinter<TestItem>::Print(TestItem const&, std::ostream*) (in /home/davida/git/gitlab/fcdm/lwm2m.git/gtest_valgrind)
==17290==  Uninitialised value was created by a stack allocation
==17290==    at 0x404AAE: gtest_TestBaseInstantiationTestBase_EvalGenerator_() (in /home/davida/git/gitlab/fcdm/lwm2m.git/gtest_valgrind)
==17290==
[==========] Running 1 test from 1 test case.
[----------] Global test environment set-up.
[----------] 1 test from TestBaseInstantiation/TestBase
[ RUN      ] TestBaseInstantiation/TestBase.TestAtoi/0
24
[       OK ] TestBaseInstantiation/TestBase.TestAtoi/0 (76 ms)
[----------] 1 test from TestBaseInstantiation/TestBase (126 ms total)

[----------] Global test environment tear-down
[==========] 1 test from 1 test case ran. (246 ms total)
[  PASSED  ] 1 test.
==17290==
==17290== HEAP SUMMARY:
==17290==     in use at exit: 0 bytes in 0 blocks
==17290==   total heap usage: 239 allocs, 239 frees, 46,622 bytes allocated
==17290==
==17290== All heap blocks were freed -- no leaks are possible
==17290==
==17290== For counts of detected and suppressed errors, rerun with: -v
==17290== ERROR SUMMARY: 20 errors from 5 contexts (suppressed: 0 from 0)

That's a lot of output, but essentially I think it's indicating that there's something unusual about the struct that is instantiated due to the TestItem { "0", 0, 0, 0 } line in INSTANTIATE_TEST_CASE_P.
Note also that the size of TestItem is output as 24. On a 64-bit system, I'm not quite sure how to reconcile this. 8 bytes for the char *, and 4 * 3 = 12 bytes for the int members. If they are aligned to 8 byte boundaries, this ought to be size 24 + 4 = 28 bytes (or 32 if including packing). If they are aligned to 4 byte boundaries, then this ought to be 20. There's something I don't understand here about struct packing.
The valgrind warning can be eliminated by packing the struct differently. For example, all three of these modifications result in a clean valgrind run:
Using #pragma pack:
#pragma pack(1)
struct TestItem
{
    const char * aString;
    int anInt0;
    int anInt1;
    int anInt2;
};

That outputs 20.
Using GNU g++ packing attribute:
struct TestItem
{
    const char * aString;
    int anInt0;
    int anInt1;
    int anInt2;
} __attribute__((packed));

That outputs 20 too.
Lastly, adding a dummy value to the struct:
struct TestItem
{
    const char * aString;
    int anInt0;
    int anInt1;
    int anInt2;
    int anInt3;   // add an extra member
};

That outputs 24.
I have a fair amount of project code that uses this exact technique for value-parameterized tests, and in all cases valgrind will complain if one of the avoidance strategies is not used.
I'd like to know if there's something fundamentally wrong with my approach of creating values for this test, or is this a consequence of something gtest does with instantiating test cases? Or, most unlikely, is this a gtest bug?

A: The output of sizeof for the TestItem structure is a consequence of compiler structure alignment and trailing padding.
From the link above:

[...] It is the first address following the structure data that has the same
  alignment as the structure.
The general rule of trailing structure padding is this: the compiler
  will behave as though the structure has trailing padding out to its
  stride address. This rule controls what sizeof() will return.
Consider this example on a 64-bit x86 or ARM machine:
struct foo3 {
    char *p;     /* 8 bytes */
    char c;      /* 1 byte */
};
struct foo3 singleton;
struct foo3 quad[4];

You might think that sizeof(struct foo3) should be 9, but it's actually 16. The stride
  address is that of (&p)[2]. Thus, in the quad array, each member has 7
  bytes of trailing padding, because the first member of each following
  struct wants to be self-aligned on an 8-byte boundary. The memory
  layout is as though the structure had been declared like this:
struct foo3 {
     char *p;     /* 8 bytes */
     char c;      /* 1 byte */
     char pad[7];
};

That explains why you are getting 24 for sizeof(TestItem) since the trailing padding will align the structure to a multiple of sizeof (const char*), which is 8.
This trailing padding bytes are uninitialized and that is what valgrind reports. Gtest is running some code in order to print the actual value of the TestItem parameter when a test fails. This could be confirmed if you make your test pass and valgrind doesn't show the error.
When you force the compiler to use a specific alignment or add a new member to the structure so that the structure doesn't need any trailing padding, valgrind doesn't find any uninitialized bytes in the TestItem instances.
Gtest usually calls operator<< when printing values and falls back to print the raw array of bytes in the object if it's not available. That's probably why the uninitialized trailing padding bytes are getting accessed. So you may also get rid of the valgrind errors by defining operator<< for TestItem.


text:
Q: PHP ini directive per directory depending of request_uri I'm trying to change the size limit of an upload. I know I have to change those directive, in Apache configuration (some can't be changed using ini_set)
php_value session.gc_maxlifetime 3600
php_value max_input_time         3600
php_value max_execution_time     3600
php_value upload_max_filesize    10M
php_value post_max_size          110M

Unfortunately, I can't do that directly in a <Directory> of my virtualhost, since the directory is always the same (I'm using a front controller, thus all request go through index.php & are dispatched to the proper controller - I use Symfony)
My question, then, is how can I avoid this problem ? I don't want to set those values for the whole application, only for a specific action.

A: This is possible, depending on how you map to your front controller. If you're doing it via rewrite rules then you can use a <Location> instead of <Directory> block to specify a chunk of path you want to change the settings for. <LocationMatch> lets you use a regexp for the same thing.
If all of your external URLs really start with /index.php? then consider setting up a redirect rule especially for these requests:
RewriteEngine on
RewriteRule ^foo/$ ^/index.php [L]

<Location /foo/>
    php_value ...
</Location>

If that's not the case, you'll need to tell us more about your application structure.

A: A possible workaround would be to create a directory with a single PHP file inside that implements your action and have the script that submits the POST target that file using a "custom" URL. After processing the input you would redirect back to a normal page through index.php. It's not clean, but it should work.
It could also be worth considering what exactly you stand to gain from this.

*

*it does not make any sense to set session.gc_maxlifetime in just one action (especially if you are increasing it)

*limiting max_input_time to one hour also does not make sense if max_execution_time is also one hour

*max_execution_time can be set at runtime

*the other two directives cannot be set at runtime, but the POST size should not matter and the uploaded file size can be checked at runtime and handled accordingly

So, what's the aim here?


text:
Q: Why do I keep getting this error: TypeError: 'bool' object is not iterable? I am making a text adventure game as part of my Learning Python book... Anyways this is what I am trying to do:
def is_a_song(song):
    valid_sung_songs = ["song 1", "song 2", "song 3"]
    valid_unsung_songs = ["s1", "s2", "s3"]
    if song.lower() in valid_sung_songs:
        return (True, 0)
    elif song.lower() in valid_unsung_songs:
        return (True, 1)
    else:
        return False

def favorite_song():
    choice = raw_input("> ")
    is_song, has_sung = is_a_song(choice)

    if is_song and (has_sung == 0):
         print "Good Song"
    elif is_song and (has_sung == 1):
         print "Good Song, But I haven't sung it"
    else:
         print "Not a valid song"

favorite_song()

Now this is just a cut down version of the code I actually used but when this is run this, it works when the song is valid and sung, when it is valid and unsung, but it crashes on the last else statement:
else:
    print "Not a valid song"

With an error of:
TypeError: 'bool' object is not iterable

If you want the actual code I'm using it is here:

*

*ex36songs.py: http://pastebin.com/EY54KJAK

*ex36.py:http://pastebin.com/a0vuZrxv (skip to phoebe(): function)

A: You need to return False, False here:
def is_a_song(song):
    ...
    else:
        return False, False

You call this function and try to unpack two values:
I would recommend to change your code to:
if song.lower() in valid_sung_songs:
    return True, False
elif song.lower() in valid_unsung_songs:
    return True, True
else:
    return False, False

and later do this:
if is_song and not has_sung:
     print "Good Song"
elif is_song and has_sung:
     print "Good Song, But I haven't sung it"
else:
     print "Not a valid song"

Seems to be cleaner to me.
is_song, has_sung = is_a_song(choice)


text:
Q: @csrf_exempt not working for rest api I am trying to exempt CSRF validation for a view that handles a REST API POST request, but I am still getting a CSRF verification failed error.
I tried the solution given in this question and it did not work.
My code:
sendmoney REST API view:
@api_view(["POST"])
@authentication_classes([TokenAuthentication,])
@permission_classes([IsAuthenticated, ])
@csrf_exempt
def send_money(request):
    if request.method == "POST":
        data = JSONParser().parse(request)
        success = send_money_api(request, data)
        if success["status"]:
            return Response(status=status.HTTP_202_ACCEPTED)
        else:
            return Response({"error": success["errors"]}, status=status.HTTP_400_BAD_REQUEST)

send_money_api method:
def send_money_api(request, data):
    if data["amount"] and data["to"]:
        wallet = Wallet.objects.get(username=request.user.username)
        users = User.objects.all()
        users_names = []
        for user in users:
            users_names.append(user)
        if int(data["amount"]) > int(wallet.amount):
            return {"status": False, "errors": "Withdraw amount greater than balance"}
        elif data["to"] == "ravinkohli" and data["to"] == request.user.username and data["to"] not in users_names:
            return {"status": False, "errors": "Invalid recipient"}
        else:
            wallet.subtract_money(data["amount"])
            wallet.save()
            transaction = Transaction(from_name=request.user.username, wallet_id=wallet, date=datetime.datetime.now(),
                                      to=data['to'], amount=data["amount"])
            transaction.save()
            return {"status": True}
    else:
        return {"status": False, "errors": "Missing content"}

Error
Forbidden (403)
CSRF verification failed. Request aborted.
You are seeing this message because this site requires a CSRF cookie when submitting forms. This cookie is required for security reasons, to ensure that your browser is not being hijacked by third parties.
If you have configured your browser to disable cookies, please re-enable them, at least for this site, or for 'same-origin' requests.

A: The CSRF validation fails for the send_money_api(...) view. Simply add the @csrf_exempt decorator above the second view too.


text:
Q: FastAPI python app error on Azure App Service I have a python web application that is using FastAPI. It works locally, but when I deploy it to a free linux Azure App Service (using GitHub Actions) and try to load the site it says "Internal Server Error". When I pull up the application logs I see the following error message
2023-02-06T23:44:30.765055894Z [2023-02-06 23:44:30 +0000] [90] [ERROR] Error handling request /
2023-02-06T23:44:30.765101490Z Traceback (most recent call last):
2023-02-06T23:44:30.765109589Z   File "/opt/python/3.10.9/lib/python3.10/site-packages/gunicorn/workers/sync.py", line 136, in handle
2023-02-06T23:44:30.765116389Z     self.handle_request(listener, req, client, addr)
2023-02-06T23:44:30.765122088Z   File "/opt/python/3.10.9/lib/python3.10/site-packages/gunicorn/workers/sync.py", line 179, in handle_request
2023-02-06T23:44:30.765128688Z     respiter = self.wsgi(environ, resp.start_response)
2023-02-06T23:44:30.765134688Z TypeError: FastAPI.__call__() missing 1 required positional argument: 'send'

Any suggestions on how to fix this issue?

A: I was able to resolve this issue by adding the following custom startup command in the Azure App Service Configuration General Settings
python -m uvicorn app:app --host 0.0.0.0

As h4z3 pointed out, gunicorn is wsgi and fastapi is asgi so I had to change the startup command to use uvicorn. Additional details can be found in the Azure docs here: https://learn.microsoft.com/en-us/azure/app-service/configure-language-python#example-startup-commands


text:
Q: WLST data source testPool- how to set timeout How to set timeout while testing a datasource using WLST.
When I do the testPool on a dataSource it waits indefinitely.
this also hangs the managed server.
is there a way we can set timeout?

A: Please set the below settings in the weblogic connection pools according to your requirement in weblogic console.
•Test Frequency—(TestFrequencySeconds in the JDBCConnectionPoolParamsBean) Use this attribute to specify the number of seconds between tests of unused connections. WebLogic Server tests unused connections, and closes and replaces any faulty connections. You must also set the Test Table Name.
•Test Reserved Connections—(TestConnectionsOnReserve in the JDBCConnectionPoolParamsBean) Enable this option to test each connection before giving to a client. This may add a slight delay to the request, but it guarantees that the connection is healthy. You must also set a Test Table Name


text:
Q: Query Kibana from javascript to change the graph I am plotting graph using kibana iframe tag on my webpage
I am trying to query kibana or elasticsearch to plot the graph when a field is equal to given value.
I know I can query ES for a field having a given value but how to change kibana graph based on the received data.
Basically I want to filter kibana like field (A = 20) and with this graph should get change.


text:
Q: convergence of series of sequence made by changing order. There is a sequence ${a_1, a_2, a_3, ... }$.
Suppose that the series of this sequence converges to a.
It is possible to make 1-1 function $f : \mathbb{N} \rightarrow \mathbb{N}.$
My question is,
${b_1, b_2, b_3, ... }$ where $b_i = a_j$ , $j = f(i)$. Then Does the series of ${b_n}$ converge to a?
I think that it is true, but I don't know how to prove it...

A: What you are asking about is so called conditional convergence. It turns out that a series may or may not converge (un)conditionally and it depends on whether the sum of the absolute values
$$
\sum_{i=1}^{\infty}|a_i|
$$
converges, see https://en.wikipedia.org/wiki/Riemann_series_theorem for a detailed discussion.


text:
Q: Parity of the eigenfunctions of Hamiltonian for a symmetrical potential I have seen in different posts (like this one) that, in case the potential $V(x)$ of a quantum system is symmetrical, you can always find a basis of eigenstates of the Hamiltonian that have definite even or odd parity.
Let such a basis of eigenstates be $\{\psi_n\}$. Can we know a priori for which $n$ they will be even and for which $n$ they will be odd?
For instance, in the one dimension infinite potential well centered at the origin, the eigenfunctions $\psi_n=\sqrt{\frac{2}{a}}\sin(\frac{n\pi}{a}(x-a/2))$ are even for odd $n$ and odd for even $n$.  Could we say the same for a symmetric potential like $V(x)=kx^4$?

A:
Could we say the same for a symmetric potential like $V(x)=kx^4$?

The $n^\text{th}$ eigenfunction of any Sturm-Liouville problem has exactly $n-1$ roots. (See Wikipedia for confirmation.) As you mentioned, for a symmetric potential the eigenfunctions are either even or odd. The first one has no roots so it must be even. The second has one root so it must be odd. Etc.
If $\psi_0$ is the ground state, the parity of $\psi_n$ is the parity of $n$. If $\psi_1$ is the ground state, the parities are opposite.


text:
Q: Activate specific panel in leftPanel in PDFNet Webviewer I remove 2 of the 3 panels of the leftPanel by using disableElements:
  setQuickBarPanelContents() {
    this.instance.disableElements(['notesPanel', 'notesPanelButton', 'outlinesPanel', 'outlinesPanelButton']);
  }

One of the removed panels is the default active one, so when leftPanel is now activated, the remaining panel(thumbnails) isn't active by default and shows up blank with the button on top. You need to press the button to activate and see the actual thumbnails in the panel.
I can't seem to find any way to (default) activate this panel through the PDFNet API. Am I overlooking something or is this a bug?

A: The API you'd want to use is setActiveLeftPanel: https://www.pdftron.com/api/web/WebViewer.html#setActiveLeftPanel__anchor.
In this particular case you can call instance.setActiveLeftPanel('thumbnailsPanel').


text:
Q: Mostrar o meu dispositivo físico conectado no Android Studio no logcat Depurar um código utilizando o Logcat é muito bom.
Devido a minha máquina não ter muitos recursos eu estou usando o dispositivo físico para testar meus apps.
Só esse dispositivo não aparece na lista de dispositivos conectados no Android Studio
O que do Androd SDK preciso configurar para que meu dispositivo físico apareça no Logcat?

Sendo que ele aparece bem na barra principal do Android Studio

Agradeço se puderem me ajudar
A aplicação que estou desenvolvendo é em Flutter


text:
Q: If $(x_n)$ converges weakly to $x$, then $x$ is in the closure of the span of the $x_n$ I need your help with this problem that I founded it in a lecture notes.
Then, the problem says:
Let $ X $ be a normed space.
Show that if a sequence $ (x_n) _ {n \in \mathbb {N}} $ in $ X $ converges weakly to $ x $ then $ x\in Y $, where $ Y $ is the closure of the vector space generated by $\{x_n : n \in \mathbb{N} \} $.

A: Suppose that $x\notin Y$.
Then, since $\{x\}$ is a compact convex set and $Y$ is a closed linear subspace (and therefore a closed convex set also), there exists a linear functional $h\in X^*$ such that $\langle h,x\rangle >0$ and $\langle h, x_i\rangle =0$ for every $i$.
It is a straightforward aplication of the Mazur-Eidelheit separation theorem, can also be proved using Hahn-Banach theorem.
Now observe that $\langle h,x_i\rangle =0<\langle h,x\rangle$ so we cannot have the convergence  $\langle h,x_i\rangle \rightarrow\langle h,x\rangle$, which is a contradiction since $x_i\rightarrow x$ in the weak sense.
Q.E.D.

A: For a convex set in a normed space, the closure and the weak closure coincide.
Let $S = \mathbb{sp}\{x_n\}$. Since $S$ is convex, we have $Y = \overline{S} = {\overline{S}}^w$ (the latter denoting the weak closure).
Since $x_n \to x$ weakly, we have $x \in {\overline{S}}^w$, hence $x \in \overline{S}$.
To see why $x$ must be in ${\overline{S}}^w$, suppose $x \notin {\overline{S}}^w$. Then there is a weak open set containing $x$ that does not intersect $S$. The open set must contain a weak neighborhood of the form $\{y \, |\,  |\phi_i(x-y)| < \epsilon, \,  \, i=1,...,n \}$. However, since $\phi_i(x_n) \to \phi(x)$, we quickly obtain a contradiction.

A: Hint: Proof by contradiction, using Hahn-Banach to produce a linear functional.


text:
Q: Probe returning: From which mineral field it gathered resources? If I have a Probe returning with minerals back to the base (Issued order "ProbeHarvest",1), how do I know where it was mining from?
I would like to write a trigger which orders the probe to return back to the mineral field early.
To clarify: I have a trigger whose action is one of those:

*

*order to return resources back to Nexus:
TriggerAddEventUnitOrder(null, "ProbeHarvest", 1)

*used an ability to return resources back to Nexus:
TriggerAddEventUnitAbility(null, "ProbeHarvest", 1, c_abilHarvestStageApproachDropOff, false)
and in the trigger action I want to learn were it was mining from.
Note: I know how learn when the probe is approaching the mineral field  TriggerAddEventUnitOrder(null, "ProbeHarvest", 0), but I don't need that information at that time.

A: You will need to read up on Units (anything you can click on). Each unit has an ID.
Next, you will have to use a trigger. When a harvester starts to harvest from a mineral patch, you will make a trigger that assigns that harvester to the mineral patch.
You can learn the basics of triggers here.
So once a probe starts harvesting, you can trigger a countdown or whatever you have in mind. Then in that trigger you will command it to go back to the ID it just harvested from which can be found from the resources it is currently gathering or the X/Y axis on the map (I'm also assuming there are other ways to get the ID of what it came from)

A: First of all - the gather resources ability is divided into several phases, each can be used as a trigger event. You don't need to check the orders, but only what the unit is actually doing.

*

*TriggerAddEventUnitAbility(null, "ProbeHarvest", 0, ApproachDropOffHarvest) - unit is aproaching the mineral field for harvesting

*...(null, "ProbeHarvest", 0, WaitatResourceHarvest) - unit reached the resource node and started waiting at it (maybe another unit is harvesting here already?). This is triggered even if no actual waiting is needed (it waits for 0 seconds).

*...(null, "ProbeHarvest", 0, HarvestHarvest) - the unit is at the resource node and started harvesting

*...(null, "ProbeHarvest", 1, WaittoReturnHarvest) - unit finished gathering resources. After this event there is usually a short period of time when the probe sits idle at the mineral field with the gathered resources.

*...(null, "ProbeHarvest", 1, ApproachDropOffHarvest) - the unit started approaching the drop-off building (Nexus)

*...(null, "ProbeHarvest", 1, WaitforDropOffHarveset) - the unit reached the drop-off building and started waiting at it. In the basic game mechanic there is no waiting time every, but this is always triggered anyway. You could imagine a custom game where one harvester cannot return resources when another is currently doing so.

*...(null, "ProbeHarvest", 1, DropOffHarveset) - the unit is dropping off the gathered resources into the player's bank.

For the events marked as "ProbeHarvest", 0 you can learn which mineral field it is approaching directly through EventUnitTargetTunit(). For "ProbeHarvest", 1 (unit returning) however, that function would give you back the drop-off building unit instead.
What you can do is that when harvesting begins (HarvestHarvest), you store the target mineral field unit in a custom "field" of your probe, and then retrieve the information in the next trigger when you return.
For creating custom fields you can check this answer: https://gaming.stackexchange.com/a/192794/92581
With that solution you would have:
(Trigger)
onStartGettingResources
    Events
        TriggerAddEventUnitAbility(null, "ProbeHarvest", 0, c_abilHarvestStageHarvest, false)
    Local Variables
        minerals <unit>
             EventUnitTargetUnit()
    Actions
        StoreUnitWithUnit(EventUnit(), "miningFrom", minerals)

(Trigger)
onStartReturningResources
    Events
        TriggerAddEventUnitAbility(null, "ProbeHarvest", 1, c_abilHarvestStageApproachDropOff, false)
    Local Variables
        minerals <unit>
            GetUnitWithUnit(EventUnit(), "miningFrom")
    Actions
        //use the "minerals"

Where StoreUnitWithUnit and GetUnitWithUnit are the counterparts of getters/setters for custom fields, working with units rather than integers.
Note that this can still cause errors when the mineral field the probe harvested from got depleted.