text:
Q: How do I change the representation of a Python function? >>> def hehe():
...     return "spam"
...
>>> repr(hehe)
'<function hehe at 0x7fe5624e29b0>'

I want to have:
>>> repr(hehe)
'hehe function created by awesome programmer'

How do I do that? Putting __repr__ inside hehe function does not work.
EDIT:
In case you guys are wondering why I want to do this:
>>> defaultdict(hehe)
defaultdict(<function hehe at 0x7f0e0e252280>, {})

I just don't like the way it shows here.

A: Usually, when you want to change something about the function, say function signature, function behavior or function attributes, you should consider using a decorator. So here is how you might implement what you want:
class change_repr(object):
    def __init__(self, functor):
        self.functor = functor

        #  lets copy some key attributes from the original function
        self.__name__ = functor.__name__
        self.__doc__ = functor.__doc__

    def __call__(self, *args, **kwargs):
        return self.functor(*args, **kwargs)

    def __repr__(self):
        return '<function %s created by ...>' % self.functor.__name__

@change_repr
def f():
    return 'spam'

print f()  # spam
print repr(f)  # <function hehe created by ...>

Note, that you can only use class based decorator, since you need to override __repr__ method, which you can't do with a function object.

A: Not directly the answer to your question, but perhaps you really want a docstring?
>>> def hehe():
...  '''hehe function created by awesome programmer'''
...  return 'spam'
...
>>> help(hehe)
Help on function hehe in module __main__:

hehe()
    hehe function created by awesome programmer

A: Here's a slightly more flexible version of what's in Alexander Zhukov's answer:
def representation(repr_text):
    class Decorator(object):
        def __init__(self, functor):
            self.functor = functor

        def __call__(self, *args, **kwargs):
            return self.functor(*args, **kwargs)

        def __repr__(self):
            return (repr_text % self.functor.__name__ if '%' in repr_text
                    else repr_text)

    return Decorator

from collections import defaultdict

@representation('<function %s created by awesome programmer>')
def f():
    return list

dd = defaultdict(f)
print repr(dd)

Output:
defaultdict(<function f created by awesome programmer>, {})

Sincerepresentation()returns a decorator, if you wanted the same boilerplate on several functions you could do something like this:
myrepr = representation('<function %s created by awesome programmer>')

@myrepr
def f():
    ...

@myrepr
def g():
    ...

etc

A: No, you cannot change the representation of a function object; if you wanted to add documentation, you'd add a docstring:
def foo():
    """Frob the bar baz"""

and access that with help(foo) or print foo.__doc__.
You can create a callable object with a custom __repr__, which acts just like a function:
class MyCallable(object):
    def __call__(self):
        return "spam"
    def __repr__(self):
        return 'hehe function created by awesome programmer'

Demo:
>>> class MyCallable(object):
...     def __call__(self):
...         return "spam"
...     def __repr__(self):
...         return 'hehe function created by awesome programmer'
...
>>> hehe = MyCallable()
>>> hehe
hehe function created by awesome programmer
>>> hehe()
'spam'


text:
Q: Why does my Spyder code only work in console? I have never been more confused, when ran in the integrated console, line by line, my code works perfectly fine, but when ran from the IDE itself, it returns an empty list. (I'm using spyder).
from selenium import webdriver
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
driver = webdriver.Chrome(r"C:\Users\Tom\Desktop\chromedriver\chromedriver.exe")
driver.get('https://bonusbagging.co.uk/oddsmatching.php#')
test = WebDriverWait(driver, 10).until(EC.presence_of_all_elements_located((By.XPATH, '//*[@id="data_table"]/tbody')))
print([i.text for i in test])

redpajama_set_name: RedPajamaStackExchange


text:
Q: Learn C programming before start learning Microcontroller/Embedded Systems
Possible Duplicate:
How to become an embedded software developer?

I want to know whether it is mandatory to learn C/C++ programming before start learning Microcontroller or the Embedded Systems. If yes, why do I need C to start with?

A: By definition of "mandatory", of course not. How advantageous it would be very much has to do with what your personal goals are.   I suggest that many people who work with microcontrollers work in C, many of the libraries and drivers you can track down will be in C, and many of the discussions you'll find or take part in when you need a bit of help will be in C.  For me, that's enough of a reason right there, before any considerations of C vs assembler vs any other language can even start up.  If you don't embrace C at least a little, you're cutting yourself off from many resources.

A: It's Not mandatory to learn C/C++ programming before learning Embedded systems.
But yes Learning C/C++ will definitely pre-build your logic and understanding of programming methodology.
As you will be using Embedded C most probably so similar syntax will also help you.
All the way you will also develop all the skills of logic and programming in Embedded also, Hence it's not mandatory.
Depends on your interest.

A: You can start learning about microcontrollers and embedded systems without knowing C, but you won't be able to progress very far. Most real-life embedded projects will use C and most of the code written for embedded projects is written in C, although it is a good idea to learn some assembly programming as well. I would also recommend that you start with plain C rather than C++.
Michael Barr has a nice article on the subject:
http://embeddedgurus.com/barr-code/2009/08/real-men-program-in-c/


text:
Q: java copy-of xsl transformation removes namespace prefix I made a minimal example to reproduce the problem. This is the transformation (mini.xsl):
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet
    version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="/">
        <foo>
            <xsl:copy-of select="."/>
        </foo>
    </xsl:template>
</xsl:stylesheet>

and this is the input (mini.xml):
<?xml version="1.0" encoding="utf-8"?>
<bar xmlns:x="baz">
    <x:baz/>
</bar>

When I apply the transformation with
xsltproc mini.xsl mini.xml

the result looks as expected:
<?xml version="1.0"?>
<foo>
  <bar xmlns:x="baz">
    <x:baz/>
  </bar>
</foo>

However, when I run the transformation with the following Java program,
import java.io.FileInputStream;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Templates;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.w3c.dom.Document;
import org.xml.sax.SAXException;

public class Program
{
    public static void main(String[] args)
    {
        try
        {
            Source transform = new StreamSource(new FileInputStream(args[0]));

            Templates templates = TransformerFactory.newInstance().newTemplates(transform);

            Document input = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new FileInputStream(args[1]));

            Result result = new StreamResult(System.out);

            templates.newTransformer().transform(new DOMSource(input), result);
        }
        catch (TransformerFactoryConfigurationError | ParserConfigurationException | SAXException | IOException | TransformerException e)
        {
            e.printStackTrace();
        }
    }
}

the result looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<foo>
  <bar xmlns:x="baz">
    <baz/>
  </bar>
</foo>

(notice that the x: prefix in front of baz is missing.)
Why is that?
And what can I do about it (to preserve the namespace prefix)?

A: For what I can only assume are historical reasons, DocumentBuilderFactory is non-namespace-aware by default.  You need to explicitly switch on namespaces before you do newDocumentBuilder().
It would also be better to use the parse method that takes a File directly rather than creating your own FileInputStream (which your code is not closing once the parse is finished), and likewise with the StreamSource from which the Transformer is built.
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
Document input = dbf.newDocumentBuilder().parse(new File(args[1]));


text:
Q: Parse.com Saving images sample. retrieve only one image I have set up the sample from parse.com where you can upload an image from the camera and then display all the images in a grid view.
What I want is to display only the recent image taken instead of a total grid view.
The sample is located here : Parse example
The images is being downloaded and placed in some sort of grid view.
The use  NSMutableArray *allImages; to get all the images.
The images is being output with button classes and a link to a new view.
The new view then only contains the image from the grid view (the one you click).
I would like to instead of downloading all of the images and placing them inside a grid view - just to display the latest image.
They code used to take the image from a small thumbnail to the full image view is like this:
// When picture is touched, open a viewcontroller with the image
    PFObject *theObject = (PFObject *)[allImages objectAtIndex:[sender tag]];
    PFFile *theImage = [theObject objectForKey:@"imageFile"];

    NSData *imageData;
    imageData = [theImage getData];
    UIImage *selectedPhoto = [UIImage imageWithData:imageData];
    PhotoDetailViewController *pdvc = [[PhotoDetailViewController alloc] init];

    pdvc.selectedImage = selectedPhoto;
    [self presentViewController:pdvc animated:YES completion:nil];

The code to get allImages is like:
// Contains a list of all the BUTTONS
    allImages = [images mutableCopy];

    // This method sets up the downloaded images and places them nicely in a grid
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(queue, ^{
        NSMutableArray *imageDataArray = [NSMutableArray array];

        // Iterate over all images and get the data from the PFFile
        for (int i = 0; i < images.count; i++) {
            PFObject *eachObject = [images objectAtIndex:i];
            PFFile *theImage = [eachObject objectForKey:@"imageFile"];
            NSData *imageData = [theImage getData];
            UIImage *image = [UIImage imageWithData:imageData];
            [imageDataArray addObject:image];
        }

        // Dispatch to main thread to update the UI
        dispatch_async(dispatch_get_main_queue(), ^{
            // Remove old grid
            for (UIView *view in [photoScrollView subviews]) {
                if ([view isKindOfClass:[UIButton class]]) {
                    [view removeFromSuperview];
                }
            }

            // Create the buttons necessary for each image in the grid
            for (int i = 0; i < [imageDataArray count]; i++) {
                PFObject *eachObject = [images objectAtIndex:i];
                UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
                UIImage *image = [imageDataArray objectAtIndex:i];
                [button setImage:image forState:UIControlStateNormal];
                button.showsTouchWhenHighlighted = YES;
                [button addTarget:self action:@selector(buttonTouched:) forControlEvents:UIControlEventTouchUpInside];
                button.tag = i;
                button.frame = CGRectMake(THUMBNAIL_WIDTH * (i % THUMBNAIL_COLS) + PADDING * (i % THUMBNAIL_COLS) + PADDING,
                                          THUMBNAIL_HEIGHT * (i / THUMBNAIL_COLS) + PADDING * (i / THUMBNAIL_COLS) + PADDING + PADDING_TOP,
                                          THUMBNAIL_WIDTH,
                                          THUMBNAIL_HEIGHT);
                button.imageView.contentMode = UIViewContentModeScaleAspectFill;
                [button setTitle:[eachObject objectId] forState:UIControlStateReserved];
                [photoScrollView addSubview:button];
            }

            // Size the grid accordingly
            int rows = images.count / THUMBNAIL_COLS;
            if (((float)images.count / THUMBNAIL_COLS) - rows != 0) {
                rows++;
            }
            int height = THUMBNAIL_HEIGHT * rows + PADDING * rows + PADDING + PADDING_TOP;

            photoScrollView.contentSize = CGSizeMake(self.view.frame.size.width, height);
            photoScrollView.clipsToBounds = YES;
        });
    });

I'm not an expert at this iOS-coding and I'm really just looking for a simple solution to display the recent image posted.

A: Looking through the posted example code, it would be a big undertaking to modify it to handle just a one image (mostly deleting a lot of yuck that synchs object ids).  If you just want the quickest path to get started, you can do this:
// ...
// where you do the query for UserPhoto
[query orderByAscending:@"createdAt"];

// use the getFirst form of the query
[query getFirstObjectInBackgroundWithBlock:^(PFObject *object, NSError *error) {
    if (!error) {
        // build the objects array that the demo code expects, but out of just one object
        NSArray *objects = @[ object ];
        // the remainder of the code as it is

A lot of UI code can get simpler, too.  But the key is to skip all of the grid/button building code and do something like this:
 // ...
 // inside the method called setUpImages:
 // this loop will only run once since we have only one object in the array
 for (int i = 0; i < [imageDataArray count]; i++) {
     PFObject *eachObject = [images objectAtIndex:i];
     UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
     UIImage *image = [imageDataArray objectAtIndex:i];

     // you're essentially done here.  add a big image view
     // that replaces photoScrollView, then:
     self.myBigImageView.image = image;

Hope that helps.


text:
Q: nearly equal arithmetical expressions This is for teaching math. I'm wondering if someone knows some striking near-equalities between simple arithmetic expressions. I vaguely remember that such things exist (e.g., numbers that look alike out 10 digits, but that are really different), but I don't remember where I saw them or what they are. I think there are even some famous historical instances where it was debated whether certain expressions were equal or not.
One possibility I am particularly interested in is integer combinations of (integer) square roots that turn out to be very very close to zero (but that are nonzero). Does anyone know how to construct these? I am assuming they exist because I read somewhere (and forgotten again!) that there is currently no efficient algorithm---or maybe even no algorithm at all, can't remember---for determining the sign of such a sum.
Thank you!
PS: I'm also interested in sources (e.g., book of number puzzles or relevant number theory, etc).

A: $e^{\sqrt{163}\pi}=262537412640768743.99999999999925$ is almost an integer.  It was conjectured for a long while this number could in fact be an integer.
You can find more on this here:
https://www.youtube.com/watch?v=DRxAVA6gYMM
Why is $e^{\pi \sqrt{163}}$ almost an integer?

A: Imagine the following scenario: A physicist modeling a certain system finds out that the number
$$\alpha:={1\over10}\sum_{n=-\infty}^\infty e^{-(n/10)^2}$$
is relevant for his problem. He numerically computes partial sums $s_N:=\sum_{|n|\leq N}$ and obtains, e.g.,
$$s_{10}=1.529\ldots,\quad s_{20}=1.7659\ldots,\quad s_{40}=1.772454\ldots,\quad s_{100}=1.77245385090552\ldots\ .$$
From the website Inverse Symbolic Calculator he learns that his $s_{100}$ agrees with $\sqrt{\pi}$ in all given decimal places. Is this just a numerical coincidence?
Our scientist then turns to a mathematician and is told that the number $\alpha$ is a value of  the theta function $\theta(x):=\sum_{k=-\infty}^\infty e^{-k^2\pi x}$:
$$\alpha:={1\over10}\>\theta\bigl({1\over 100\pi}\bigr)\ .$$
Now comes the upshot:  Jacobi's famous theta transformation allows to rewrite $\alpha$ in the form
$$\alpha={\sqrt{100\pi}\over 10}\theta(100\pi)=\sqrt{\pi}\sum_{k=-\infty}^\infty e^{-100\pi^2k^2}=\sqrt{\pi}(1+\epsilon)\ ,$$
where $\epsilon:=\sum_{k\ne0} e^{-100\pi^2k^2}<10^{-428}$. In other words: The number $\alpha$ resembles $\sqrt{\pi}$ up to more than $400$ decimal places, but is $\ne\sqrt{\pi}$.

A: additional reference: Section 1.4 (High Precision Fraud) in Borwein, Bailey, Girgensohn: Experimentation in Mathematics, A.K.Peters 2004.


text:
Q: Artificially Increasing Training data I am trying to predict sales quantity based on attributes of the item.Sales are aggregated by week wise and prediction is also done by week wise.I am having large number records with zero sales quantity than compared to positive sales(for 20 positive sales 250 zero sales records are there).I want to increase my training data by adding small values to sales quantity and combining with total records. At present I am using RANDOM FOREST and NEURAL NETWORK .I am not getting any good results Please correct me if anything is not considerable.
Can anybody suggest way to increase my training data

A: If your sales are aggregated by week then you data is most likely highly autocorrelated. You can test whether autocorrelation in your data is significant that with a simple autocorrelogram or a Ljung-Box test.
Cross-sectional methods such as standard neural networks and random forest cannot handle a high degree of autocorrelation. You will need to apply a time series approach such as ARMA models, exponential smoothing, autoregressive neural networks, or something equivalent.

A: at first I don't quite understand the meaning of "increase my training data by adding small values to sales quantity", I guess you mean  adding items that are barely sold to the positive sales category. I think that if your goal is to find a robust model to distinguish items that can sell well, you should not mix in not well sold items to the postive category.
A solution to get better accuracy is to resolve the issue of unbalanced data and probably try some other models/ with more aggressive parameter tuning(searching). I would start with resampling(repeating) the positive sales samples so that its case number is roughly the same as the negative sales sample number. This strategy works surprisingly well esp if you are using boosting in building the decision tree.


text:
Q: Expendable Floating Button redirecting to another Activity   addFAB.setOnClickListener{
//            val intent = Intent(this, FloatingActionButton::class.java)
//            startActivity(intent)
            if (!fabVisible){
                uploadfolder.show()
                uploadfile.show()
                createFolder.show()

                uploadfolder.visibility = View.VISIBLE
                uploadfile.visibility = View.VISIBLE
                createFolder.visibility = View.VISIBLE

                addFAB.setImageDrawable(resources.getDrawable(R.drawable.ic_close))

                fabVisible = true
            }else   {
                uploadfolder.hide()
                uploadfile.hide()
                createFolder.hide()

                uploadfolder.visibility = View.GONE
                uploadfile.visibility = View.GONE
                createFolder.visibility = View.GONE

                addFAB.setImageDrawable(resources.getDrawable(R.drawable.add))

                fabVisible = false
            }
        }
        uploadfolder.setOnClickListener{
            Toast.makeText(this@MainActivity, "Upload Folder", Toast.LENGTH_LONG).show()
        }

        uploadfile.setOnClickListener{
            Toast.makeText(this@MainActivity, "Upload File...", Toast.LENGTH_LONG).show()
        }
        createFolder.setOnClickListener {
           Toast.makeText(this@MainActivity, "Create new Folder...", Toast.LENGTH_LONG).show()
        }

I am making an App which it required an Expendable Floating Button but it must be redirected on another Activity.
I have tried on many ways but its still an error. If anyone can help me it will be very cool.
I have tried a normal call Activity in many ways but I don't have any further idea how to implement a new Intent on on an Extended Floating Button when there is an if and else.

A: The this is referencing to your onClickListener not to your activity,
val intent = Intent(this, FloatingActionButton::class.java)
startActivity(intent)

so if your activity's name is MySampleActivity your intent should look like this
val intent = Intent(this@MySampleActivity, FloatingActionButton::class.java)
startActivity(intent)


text:
Q: Azure subscription/service principal retrieve app_id and app secret for rbac role after creation After creating an rbac role for the subscription or service principal you are given the app id and the app secret, but how do you retrieve these later?
For instance creating the rbac role
az ad sp create-for-rbac --role="Contributor" --scopes="/subscriptions/${SUBSCRIPTION_ID}"

You then get the reply of the reply of
{
  "appId": "{appid_hash}",
  "displayName": "----------------------------",
  "name": "http://----------------------------",
  "password": "{password_hash}",
  "tenant": "{tenant_hash}"
}

I am looking to find the passowrd and appId again but am finding it hard to figure that out. Any suggestions? Working through the cli would be preferable. I already know where to get the appId from the Portal but want to be able to retrieve this through a script if lost. Or do I just need to save these some place that can be retrieved.
And if so how is that done?

A: It's not possible to retrieve the password after creation:
Get existing service principle

az ad sp list or az ad sp show get the user and tenant, but not any authentication secrets or the authentication method. Secrets for certificates in Key Vault can be retrieved with az keyvault secret show, but no other secrets are stored by default. If you forget an authentication method or secret, reset the service principal credentials.

You can list other details of a service principle but you need to know either the name or the ID e.g:
az ad sp show --id "http://testsp"
az ad sp show --id "21cd9589-6f82-435b-9193-b5238fa194e4"

You can list all service principles with az ad sp list but you might have created a hundred of them. You should store the ID and secret securely and retrieve them later as required


text:
Q: OpenAI GPT-3 API errors: 'text' does not exist TS(2339) & 'prompt' does not exist on type 'CreateChatCompletion' TS(2345) import openai from "./zggpt";

const query = async (prompt:string,  chatId:string, model:string) => {
    const res= await openai
    .createChatCompletion({
        model,
        prompt,
        temperature: 0.9,

        top_p:1,

        max_tokens:1000,
        frequency_penalty:0,
        presence_penalty:0,
    })
    .then((res) => res.data.choices[0].text)
    .catch((err)=>
    `ZG was unable to find an answer for that!
     (Error: ${err.message})`
     );
     return res;
};

export default query;

Property 'text' does not exist on type 'CreateChatCompletionResponseChoicesInner'.ts(2339)
Argument of type '{ model: string; prompt: string; temperature: number; top_p: number; max_tokens: number; frequency_penalty: number; presence_penalty: number; }' is not assignable to parameter of type 'CreateChatCompletionRequest'.
Object literal may only specify known properties, and 'prompt' does not exist in type 'CreateChatCompletionRequest'.ts(2345)
even though I do everything as in the video, I get these errors.
i'm a beginner in coding, so I'm trying to make applications based on videos to learn.
Thanks
the application responds without returning an error.
enter image description here
https://www.youtube.com/watch?v=V6Hq_EX2LLM&t=6293s

A: You watched a tutorial which used the GPT-3 Completions endpoint (you need to provide the prompt and parameters to get a completion). In this case, this is the function which generates a completion:
openai.createCompletion()

Whereas, you used the code from the tutorial, but used the ChatGPT Completions endpoint (you need to provide the chat message to get a completion). In this case, this is the function which generates a completion:
openai.createChatCompletion()

Solution
So, change this...
openai.createChatCompletion()

...to this.
openai.createCompletion()

Both errors will disappear.

A: The answer from Rok is correct, but also in the past 2 days OpenAI has released the ChatGPT model and endpoint.
Ref: https://platform.openai.com/docs/api-reference/chat/create?lang=python
In the Chat endpoint your code would look like this:
import openai
import os
openai.api_key = os.getenv("OPENAI_API_KEY")

const query = async (prompt:string,  chatId:string, model:string) => {
    const res= await openai
    .createChatCompletion({
        model="gpt-3.5-turbo",
        messages=[{"role": "user", "content": prompt}]
    })
    .then((res) => res.choices[0].message)
    .catch((err)=>
    `ZG was unable to find an answer for that!
     (Error: ${err.message})`
     );
     return res;
};

export default query;


text:
Q: Free word list of English words of interest to children? I'm developing a software application for children and it would be useful to have an English dictionary with terms/words sorted by their "interestingness" to children aged 4-8.
Terms like "unicorn", "bunny", "cat", "dog" would be on top and terms like "differential equations" and "econometrics" would be at the bottom (or not present).
Any ideas on where to find such a list?
Are there any open source / free children's encyclopedia's or books available from which such a list could be generated?

A: You can find many word lists in general internet searches, although as a parent of a young child, I found the following resources useful for the 4-8 year age bracket:
If you intend to have this age group read the words, then I hope you will consider including words from the Dolch List.
The Oxford wordlist allows you to create customised word lists based on high-frequency words found in children's books.
There are also many sources for public domain children's books. I found this (recently updated) resource from Gizmo's Freeware site particularly useful for sourcing ePub files and online books. If you are tech-savvy, you should be able to generate wordlists from ePub and/or pdf files from some of these links. There are literally hundreds of book links here.
I'm sure there are many other resources out there also; these are some that I found useful in my own experience.


text:
Q: Calculating the integral of exponential of exponential I've been trying to integrate the following expression:
$$\int_{0}^{\infty} (1- \exp(-a e^{-bx})) dx$$
I started to solve this integral by first using the substitution method. With $t = e^{-bx}$, then the integral is:
$$\frac{1}{b} \int_{0}^{1} \frac{1}{t}(1-e^{-at})dt$$
The only thing that comes to my mind is solving this using integration by parts, but it ends up complicating the integration way too much. For example, let $u = \frac{1}{t}$ and $dv = 1 - e^{-at}$. Is there any easier way to solve this integral?

A: The integral of $\dfrac {e^{a x} } x$ does not work out easily.
Here is how it is done on ProofWiki:
https://proofwiki.org/wiki/Primitive_of_Exponential_of_a_x_over_x
$$\int \frac {e^{a x} \, \mathrm d x} x = \ln |x| + \sum_{k \mathop \ge 1} \frac {(a x)^k} {k \times k!} + C$$
This will allow you to actually get the answer to your substituted integral, and it should be straightforward to get the answer out from there. Just that it ain't very pretty.

A: We begin with the integral $I$ given by
$$I=\int_0^1 \frac{1-e^{-at}}{t}\,dt\tag1$$

Enforcing the substitution $t\mapsto t/a$ in $(1)$ reveals
$$I=\int_0^a \frac{1-e^{-t}}{t}\,dt \tag2$$

Integrating by parts the integral in $(2)$ with $u=1-e^{-t}$ and $v=\log(t)$, we find that
$$\begin{align}
I&=(1-e^{-a})\log(a)-\int_0^a \log(t)e^{-t}\,dt\\\\
&=(1-e^{-a})\log(a)+\gamma+\int_a^\infty \log(t)e^{-t}\,dt\tag3
\end{align}$$
where $\gamma =-\int_0^\infty \log(t) e^{-t}\,dt$ is the Euler-Mascheroni constant.

A subsequent integration by parts in $(3)$ with $u=\log(t)$ and $v=-e^{-t}$ yields
$$\bbox[5px,border:2px solid #C0A000]{I=\log(a)+\gamma+\Gamma(0,a)}\tag 4$$
where $\Gamma(0,a)=\int_a^\infty \frac{e^{-t}}{t}\,dt$ is the upper Incomplete Gamma function.

Note that we could have alternatively expressed $(4)$ as
$$\bbox[5px,border:2px solid #C0A000]{I=\log(a)+\gamma-\text{Ei}(-a)}$$
in terms of the Exponential integral $\text{Ei}(-a)=-\int_a^\infty \frac{e^{-t}}{t}\,dt$.


text:
Q: Finding an explicit formula for $a_n$ defined recursively by The sequence $a_n$ is defined recursively by $a_0=0$, $a_n=4a_{n-1}+1$. I must use generating functions to solve this. $n\geq1$.
I have found a pattern:
$$\sum_{n=1}^\infty(4a_{n-1}+1)x^n = x+5x^2+21x^3+85x^4+341x^5+\ldots$$
If we subtract 1 from each term, respectively (ignoring the first term) we would have:
$$x+4x^2+20x^3+84x^4+340x^5+\ldots$$
As you can see, the pattern is the second term increases by 4, the third term increases by 4^2, the fourth term increases by 4^3, and the fifth term increases by 4^4. I wanted to use the formula for the geometric series, but the common ratio isn't 4, but $4^n$. Is there any way I can use this pattern to help me find the explicit formula, using generating functions?
Using $$\sum_{n=0}^\infty 4^nx^n = \frac{1}{1-4x}$$ Isn't helping me too much. But I have a feeling I can manipulate this generating function to solve this.
However, this might seem helpful:
$$\sum_{n=0}^\infty4^nx^{n+1} = 4^0x+4^1x^2+4^2x^3+4^3x^4+\ldots = x+4x^2+16x^3+64x^4+\ldots$$
After some work I have gotten this:
$$A(x)=\frac{x^2}{(1-x)(x-4)}$$ Where $A(x)$ is our unknown generating function (which we have been looking for). But I don't think this is correct because it does not match the answer down below.
Edit: I have finally figured it out, I will be back with my LaTex code to present it.
Final edit:
Find an explicit formula for $a_n$ using the generation function technique.
\newline We will begin by multiplying each side by $x^n$ and summing over $n\geq1$. We will also let $A(x)=\sum_{n=0}^\infty a_nx^n$ be the unknown generating function which we are looking for.
$$\begin{align*}
\implies \sum_{n=1}^\infty a_nx^n&=\sum_{n=1}^\infty (4a_{n-1}+1)x^n
\end{align*}
$$
Because
$a_0=0$ is given, we can rewrite $A(x)$:
$$
\begin{align*}
A(x)=a_0+\sum_{n=1}^\infty a_nx^n=\sum_{n=1}^\infty a_nx^n
\end{align*}
$$
Now, we continue to manipulate our equality.
$$
\begin{align*}
\implies \sum_{n=1}^\infty a_nx^n&=\sum_{n=1}^\infty (4a_{n-1}+1)x^n \\[2mm]
&=\sum_{n=1}^\infty 4a_{n-1}x^n + x^n \\[2mm]
&=\sum_{n=1}^\infty 4a_{n-1}x^n+\sum_{n=1}^\infty x^n \\[2mm]
&=\sum_{n=1}^\infty 4a_{n-1}x^n+ \frac{x}{1-x} \\[2mm]
&=\sum_{n=0}^\infty 4a_{n}x^{n+1}+ \frac{x}{1-x} \\[2mm]
&=a_0+\sum_{n=1}^\infty 4a_{n}x^{n+1}+ \frac{x}{1-x} \\[2mm]
&=\sum_{n=1}^\infty 4a_{n}x^{n+1}+ \frac{x}{1-x} \\[2mm]
&=4x\sum_{n=1}^\infty a_{n}x^{n}+ \frac{x}{1-x}. \\[2mm]
\end{align*}$$
It is clear now, that we have a multiple of our previously stated $A(x)$ on the left and right hand side.
$$
\begin{align*}
\implies&\sum_{n=1}^\infty a_{n}x^{n}=4x\sum_{n=1}^\infty a_{n}x^{n}+ \frac{x}{1-x} \\[2mm]
\implies&A(x)=4xA(x)+\frac{x}{1-x} \\[2mm]
\implies&A(x)-4xA(x)=\frac{x}{1-x}\\[2mm]
\implies& A(x)(1-4x)=\frac{x}{1-x}\\[2mm]
\implies& A(x)=\frac{x}{(1-x)(1-4x)}=\frac{x}{4x^2-5x+1} \\[2mm]
\end{align*}$$
Thus, the explicit formula for $a_n$ is given by $A(x)=\dfrac{x}{4x^2-5x+1}$ through the use of generating functions.
Finally, it follows that we have $$A(x)=\sum_{n=0}^\infty\frac{4^n-1}{3}x^n=\frac{x}{4x^2-5x+1}.$$

A: A way to go about this is to define
$$f(x) = \sum_{n=0}^{\infty} a_n x^n$$
Then
$$x f(x) = \sum_{n=0}^{\infty} a_n x^{n+1} = \sum_{n=1}^{\infty} a_{n-1} x^n$$
Using your recurrence, we find that
$$(1-4 x) f(x) = a_0 + \sum_{n=1}^{\infty} (a_n-4 a_{n-1}) x^n = a_0 + \sum_{n=1}^{\infty} x^n = a_0 + \frac{x}{1-x}$$
Note that $a_0=0$, so that we now have the generating function $f(x)$:
$$f(x) = \frac{x}{(1-x)(1-4 x)} = \frac{x}{1-5 x+4 x^2}$$

A: The characteristic equation for the homogenous part is: $x^2 - 4x = 0$ gives: $x = 0$ and $x = 4$. So the solution to the equation is: $a_n = c\cdot 4^n + b$. Now $a_0 = 0$ and $a_1 = 1$ gives: $0 = c + b$, and $1 = 4c + b$. So $b = -c$, and $c = \dfrac{1}{3}$, and $b = -\dfrac{1}{3}$. So: $a_n = \dfrac{4^n - 1}{3}$

A: $\newcommand{\bbx}[1]{\,\bbox[15px,border:1px groove navy]{\displaystyle{#1}}\,}
 \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\mc}[1]{\mathcal{#1}}
 \newcommand{\mrm}[1]{\mathrm{#1}}
 \newcommand{\on}[1]{\operatorname{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$
A particular solution is $\ds{-\,{1 \over 3}}$.
Then
$\ds{\pars{~\mbox{with}\ a_{0} = 0~}}$,
\begin{align}
a_{n} + {1 \over 3} & =
4\pars{a_{n - 1} + {1 \over 3}} =
4^{2}\pars{a_{n - 2} + {1 \over 3}} =
4^{3}\pars{a_{n - 3} + {1 \over 3}}
\\[5mm] & = \cdots =
4^{n}\pars{a_{0} + {1 \over 3}} = {4^{n} \over 3}
\implies
\bbx{a_{n} = {4^{n} - 1 \over 3}} \\ &
\end{align}


text:
Q: Iterate images and convert to base64 format for table OCR in Python I have several image format tables from here and I'm able to extract them one by one use the following code.
import base64
from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.ocr.v20181119 import ocr_client, models

path = './test/1.png'
def imgget(path):
    with open(path,'rb') as f:
        base64_data = base64.b64encode(f.read())
    return base64_data.decode('utf-8')

try:
    cred = credential.Credential('***', '***')
    httpProfile = HttpProfile()
    httpProfile.endpoint = 'ocr.tencentcloudapi.com'

    clientProfile = ClientProfile()
    clientProfile.httpProfile = httpProfile
    client = ocr_client.OcrClient(cred, 'ap-guangzhou', clientProfile)

    req = models.TableOCRRequest()

    params = imgget(path)
    req.ImageBase64 = str(params)
    # req.from_json_string(params)

    resp = client.TableOCR(req)
    # print(resp.to_json_string())

except TencentCloudSDKException as err:
    print(err)

data = base64.b64decode(resp.Data)

def save(data, name):
    path = name
    with open(path, 'wb') as f:
        f.write(data)
    f.close
# print(data)
name = './data/1.xlsx'
save(data, name)

But now I want iterate all the image files from the link in the beginging of this question and pass them to path = './test/1.png', then extract tables and save them in one sheet of one excel file in Python, how could I modify the code above to do that?
Thank you.
Update:
We can loop all the images's path with:
for path in glob.iglob('./test/*.png'):
    print(path)

Out:
./test/4.png
./test/3.png
./test/2.png
./test/1.png

A: My solution so far, not able to save result into one excel file but it works somehow.
Welcome to improve it.
import base64
from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.ocr.v20181119 import ocr_client, models
import glob
import os

directory = './images/test/'

def imgget(path):
    with open(path,'rb') as f:
        base64_data = base64.b64encode(f.read())
    return base64_data.decode('utf-8')

# save files
def save(data, name):
    path = name
    with open(path, 'wb') as f:
        f.write(data)
    f.close

try:
    cred = credential.Credential('***', '***')
    httpProfile = HttpProfile()
    httpProfile.endpoint = 'ocr.tencentcloudapi.com'

    clientProfile = ClientProfile()
    clientProfile.httpProfile = httpProfile
    client = ocr_client.OcrClient(cred, 'ap-guangzhou', clientProfile)

    req = models.TableOCRRequest()

    for image in os.listdir(directory):
        if image.endswith(".png") or image.endswith(".jpg"):
            print(image)
            file_names = os.path.splitext(image)[0]
            print(file_names)
            path = os.path.join(directory, image)
            params = imgget(path)
            req.ImageBase64 = str(params)
            # req.from_json_string(params)
            resp = client.TableOCR(req)

            data = base64.b64decode(resp.Data)
            print(data)
            name = './tables/{}.xlsx'.format(file_names)
            save(data, name)
            continue
        else:
            pass

except TencentCloudSDKException as err:
    print(err)


text:
Q: Multiple Dependent Drop Down Lists based on Database I have an Excel database of component costs that is laid out as follows in a sheet.
Vendor    -     Category  --  Component    -- Price
Vendor A    Category A  Component A  $5.00
Vendor A    Category A  Component B  $8.00
Vendor A    Category B  Component A  $9.00
Vendor A    Category B  Component B  $11.00
Vendor B    Category A  Component A  $14.00
Vendor B    Category C  Component A  $14.00
Vendor B    Category C  Component B  $17.00
Vendor B    Category D  Component A  $6.00
Vendor C    Category C  Component C  $7.00
Vendor C    Category D  Component A  $4.00
Vendor C    Category D  Component B  $12.00
What I am trying to do is have a user come in and build a piece of equipment that is made up of different components. That user would use a drop down list to choose the vendor, then another drop down list to choose the category, then finally use another drop down list to choose the component. (that is based on the vendor and category) From these, the price would be populated into the sheet as well.
The empty sheet would look something like this...
Vendor ------------ Type ------- Component ---- Cost -------    Quantity -------  Extended Cost
(drop down) -- (drop down) -- (drop Down) -- VLOOKUP
Populating the price doesn't seem too hard, except it is based on multiple criteria. VLOOKUP for that. My main problem is 1) creating the drop down list from the column that has multiple repeats as it is database format and 2) using multiple dependent drop downs.
Thank you!

A: assuming there are no duplicates in the data list (e.g. Vendor A Category A Component A can't appear twice)
a Sumproduct or a SUMIFS (depending on excel version) gives you the value
SUMIFS:
Sumifs will return the price when the vendor is equal to A2, the Category/Type is equal to B2, and the Componenet is equal to C2
=SUMIFS(Data!D:D,Data!A:A,A2,Data!B:B,B2,Data!C:C,C2)

SUMPRODUCT:
Sumproduct works better with fixed size ranges, as multiplying 16,384 or 1,000,000+ rows takes a much longer time
=SUMPRODUCT(Data!D1:D999,--(Data!A1:A999=A2),--(Data!B1:B999=B2),--(Data!C1:C999=C2))


text:
Q: Error: ; expected (Compile error in Java) When isLetter() method is deleted everything is working fine but when I add it it gives an error. I removed private as it is in the main method. Please help. Thanks in advance.
import java.io.*;
class WordCounter{

public static void main(String args[]){
    File file_in_obj = new File("E:/Problems","notes.txt");
    File file_out_obj = new File("E:/Problems","notes_sorted.txt");

    boolean isLetter(char let){
        return ( let>= 'a'&& let <= 'z') || ( let >= 'A' && let <='Z');
    }

    try(BufferedReader fin = new BufferedReader(new FileReader(file_in_obj));
    BufferedWriter fout = new BufferedWriter(new FileWriter(file_out_obj));){

    String array[]=new String[500];
    char ch[]=new char[25];
    int rd,k=0;
    String line=null;

        /*do{
            rd=fin.read();
            if(Character.isWhitespace((char)rd))
                fout.write(" ");
            else if(Character.isLetter((char)rd)){

                    fout.write((char)rd);
                }
        }while(rd!=-1); */

        while((line=fin.readLine())!=null){
            //  System.out.println(j++);
            String[] tokens = line.split ("\\s+");
            for(int i = 0; i < tokens.length; i++){
                    array[k]=tokens[i];
                    fout.write(array[k]+" ");
                    k++;
                    //System.out.println(tokens.length);
            }

        }
        for(int p=0;p<k;p++){
            for(int i=0;i<array[p].length();i++){
                if(Character.isLetter(array[p].charAt(i)))
                    System.out.print(array[p].charAt(i));
            }
            System.out.println(p);
        }

    /*for(int j=tokens.length;j>1;j--)
    for(int i=0;i<j-1;i++){
        if(tokens[i].compareTo(tokens[i+1])>0){
                String temp=tokens[i+1];
                tokens[i+1]=tokens[i];
                tokens[i]=temp;
        }
    }*/

    } catch(IOException e){
        System.out.println("I/O Exception occured");
    }

}
}

A: You can't have a method inside another method.  Try this:
boolean isLetter(char let){
        return ( let>= 'a'&& let <= 'z') || ( let >= 'A' && let <='Z');
}

public static void main(String args[]){
    File file_in_obj = new File("E:/Problems","notes.txt");
    File file_out_obj = new File("E:/Problems","notes_sorted.txt");
...
}


text:
Q: Keep Generics in tact when line length is exceeded (ESLint) Is there an ESLint property that will prevent breakage of generic chevron tags over several lines if the line length is exceeded? It just looks so messy the way it splits the generic.
current behavior
return this.http.post(url, verifyContactRequest, httpOptions) as Observable<
  ContactVerificationResponse
>

desired behavior
return this.http.post(url, verifyContactRequest, httpOptions) as
    Observable<ContactVerificationResponse>


text:
Q: How to set the time to a standard value when using a DatePicker in SwiftUI I have a date-picker in my app, which only selects the date, not the time. Looks like this:
DatePicker("Birthday",
          selection: $date,
          displayedComponents: [.date])

A date picker gives you a date object to work with. So, when the user selects a date, it of course also comes with a time, timezone, etc. My problem is, that the time is set to the current time by default. However, I need it to be set to midnight always. How can I provide a default value?
A possible solution that came to my mind was using a formatter and storing the date as a String (instead of a Date), but since I need to do some work with it later (e.g. calculate days between two dates), this doesn't seem like the best approach to me.

A: you could try this:
struct ContentView: View {
    @State var date = Date()

    var body: some View {
        VStack {
            Text("\(date)")
            DatePicker("Birthday", selection: $date, displayedComponents: [.date])
                .onChange(of: date) { newDate in
                    if let midnight = Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, of: newDate) {
                        date = midnight

                    }
                }
        }
    }
}

or this:
struct ContentView: View {
    @State var date = Date()

    var body: some View {
        VStack {
            Text("\(date)")
            DatePicker("Birthday", selection: $date, displayedComponents: [.date])
        }
        .onAppear {
            if let midnight = Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, of: Date()) {
                date = midnight
            }
        }
    }
}

or this:
struct ContentView: View {
    @State var date = Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, of: Date())!

    var body: some View {
        VStack {
            Text("\(date)")
            DatePicker("Birthday", selection: $date, displayedComponents: [.date])
        }
    }
}


text:
Q: How to fill value from API to checkbox.Group with antd I have an array menu to render all the checkbox and and a data object retrieved from the api.
Currently I want when the return data is true, it will be checked
The difficulty data to display here is the key keyword to identify, if according to antd example, it is just an element array without a key.
I know Checkbox.Group has 1 attribute value to fill data, but I don't know how to deal with it , pls help me
  const menu = [
    {
      label: "System",
      level: 1,
      view: true,
      add: true,
      edit: true,
      del: true,
      key: "agmdb"
    },
    {
      label: "Agent",
      level: 1,
      view: true,
      add: true,
      edit: true,
      del: true,
      key: "agent"
    },
    {
      label: "User",
      level: 2,
      view: true,
      add: true,
      edit: true,
      del: true,
      key: "users"
    }
  ];

Data object retrieved from the api:
  let userPermission = {
    agent: { view: true, edit: true, del: false, add: false },
    agmdb: { view: true, edit: false, del: true, add: false },
    users: { view: true, edit: false, del: false, add: true }
  };

Render Menu:
 const onChangeCheckbox = (arr, key) => {
    console.log(arr);
  };

      {menu.map((item) => {
         let arrKey = [
           userPermission[item.key]?.view ? `view` : "",
           userPermission[item.key]?.add ? `add` : "",
           userPermission[item.key]?.del ? `del` : "",
           userPermission[item.key]?.edit ? `edit` : ""
         ];
        return (
          <Form>
            <Form.Item
              style={{ margin: "10px 0" }}
              key={item.label}
              labelCol={{
                span: 6
              }}
              wrapperCol={{
                span: 12
              }}
              label={item.label}
            >
              <Checkbox.Group
                onChange={(e) => {
                  onChangeCheckbox(e, item.key);
                }}
                value={arrKey}
              >
                <Checkbox value="view">
                  View
                </Checkbox>
                <Checkbox value="add">
                  Add
                </Checkbox>
                <Checkbox value="del">
                  Delete
                </Checkbox>
                <Checkbox value="edit">
                  Edit
                </Checkbox>
              </Checkbox.Group>
            </Form.Item>
          </Form>
        );
      })}

example code : https://codesandbox.io/s/busy-pine-n0iku4?file=/src/App.jsx
*UPDATE: i have add the value to checkbox.Group and it filled the data when checking the condition, there is a new problem that can't check another box, you can see it in codesanbox

A: use name instead of value in checkbox component.
<Checkbox name="view">

and use form hook ...
const [form] = Form.useForm();
<Form form={form}>

and u should use
form.setFieldsValue()

to fill inputs

A: To make it work using Form, you need to specify name prop to Form.Item. In your case, name will be agmdb, agent, users.
In useEffect, get all the userPermissions and store it in a state if required. Checkbox group value format should be an array of string ['view', 'edit']. But userPermission have a different format where value is key value pair. So we need to filter out those keys that have value true.
Then set the values in form. Since each Checkbox.Group have 4 options so i created an options array of label and value. You can also use disabled in options if you need that. On submit, you may required the original data format. I also write a code that will convert the values into original format.
Hope this solves your problem
import { useEffect } from 'react';
import { Button, Checkbox, Form } from 'antd';

const menu = [
    { label: 'System', level: 1, view: true, add: true, edit: true, del: true, key: 'agmdb' },
    { label: 'Agent', level: 1, view: true, add: true, edit: true, del: true, key: 'agent' },
    { label: 'User', level: 2, view: true, add: true, edit: true, del: true, key: 'users' }
];

const userPermission = {
    agent: { view: true, edit: true, del: false, add: false },
    agmdb: { view: true, edit: false, del: true, add: false },
    users: { view: true, edit: false, del: false, add: true }
};

const options = [
    { label: 'View', value: 'view' },
    { label: 'Add', value: 'add' },
    { label: 'Edit', value: 'edit' },
    { label: 'Delete', value: 'del' }
];

const App = () => {
    const [form] = Form.useForm();

    useEffect(() => {
        // Fetch userPermission from API
        // Each Checkbox.Group value is an array of string (true means checked)
        // Example: { agmdb: ['view', 'del'], agent: ['view'], users: ['view', 'add'] }

        const data: Record<string, Array<string>> = {};

        Object.entries(userPermission).forEach(([key, value]) => {
            data[key] = Object.keys(value).filter((key) => value[key as keyof typeof value]);
        });

        form.setFieldsValue(data);
    }, [form]);

    const onFinish = (values: any) => {
        const finalData: Record<string, Record<string, boolean>> = {};

        Object.entries(values).forEach(([key, value]: any) => {
            finalData[key] = value.reduce((acc: any, cur: string) => {
                acc[cur] = true;
                return acc;
            }, {});
        });

        console.log(finalData);
    };

    return (

            <Form form={form} onFinish={onFinish}>
                {menu.map((item) => {
                    return (
                        <Form.Item
                            key={item.key}
                            style={{ margin: '10px 0' }}
                            labelCol={{ span: 6 }}
                            wrapperCol={{ span: 12 }}
                            label={item.label}
                            name={item.key}
                        >
                            <Checkbox.Group options={options} />
                        </Form.Item>
                    );
                })}

                <Button htmlType='submit'>Submit</Button>
            </Form>

    );
};

export default App;


text:
Q: java: Can't check this string Can't convert String into json, and it seems that it will be superfluous for the entire string.
Was thinking maybe json might have helped me out here, but it doesn't seem to give me what I want or I don't know how it will be work.
How I can check the string?
I need to check:

*

*METHOD: GET and URL: http://google.com/

*also to check the BODY contains the fields userId, replId and view (no values, only keys)
I was trying to find a way to check that:
if (msg.contains("METHOD: GET") && msg.contains("URL: http://google.com/") && msg.contains("BODY: etc...")) {
        System.out.println("ok");
    }

It doesn't work. Some values from BODY that are dynamic and that's why for BODY the check won't pass if it's so hardcoded String. And I guess there're any better ways to do that.
I'd like to have something like:
Assert.assertEquals(
   msg,
   the expected value for METHOD, which contains GET); // same here for URL: http://google.com/

Assert.assertEquals(
   msg,
   the expected value for BODY that has userId, replId, and view fields); // or make this assertion for each field separately, such as there is an assertion for the userId field, the same assertions for replId and view

And here's the String:
String msg = "METHOD: GET\n" +
                 "URL: http://google.com/\n" +
                 "token: 32Asdd1QQdsdsg$ff\n" +
                 "code: 200\n" +
                 "stand: test\n" +
                 "BODY: {\"userId\":\"11022:7\",\"bdaId\":\"110220\",\"replId\":\"fffDss0400rDF\",\"local\":\"not\",\"ttpm\":\"000\",\"view\":true}";

I can't think of any way to check that. Any ideas?

A: You can use the java.util.List Interface (of type String) and place the string contents into that list. Then you can use the List#contains() method, for example:
String msg = "METHOD: GET\n" +
         "URL: http://google.com/\n" +
         "token: 32Asdd1QQdsdsg$ff\n" +
         "code: 200\n" +
         "stand: test\n" +
         "BODY: {\"userId\":\"11022:7\",\"bdaId\":\"110220\",\"replId\":\"fffDss0400rDF\",\"local\":\"not\",\"ttpm\":\"000\",\"view\":true}";

// Split contents of msg into list.
java.util.List<String> list = Arrays.asList(msg.split("\n"));

if (list.contains("METHOD: GET")) {
    System.out.println("YUP! Got: --> 'METHOD: GET'");
}
else {
    System.out.println("NOPE! Don't have: --> 'METHOD: GET'");
}

A: I've tried to use Assert:
String[] arr1 = msg.split("\n");
Map<String, String> allFieldsMessage = new HashMap<>();
for (String s : arr1) {
    String key = s.trim().split(": ")[0];
    String value = s.trim().split(": ")[1];
    allFieldsMessage.put(key, value);
}
Assert.assertEquals(
        allFieldsMessage.get("METHOD"),
        "GET"
);

And the same for URL. But my problem is in BODY part. I thought maybe try to parse this particular part of String into json and then only check the necessary keys.


text:
Q: Downloading file using aws sdk for Nodejs not giving most recent file Summary
I have a json file that gets updated nightly from an automated testing service. I use this json file to update a UI to show the most recent addition. I am downloading it using nodejs and the aws-sdk.
The problem
The file is updated. I have downloaded it and checked it myself. Downloading it programatically using the aws-sdk does not show the updated file however. It's still feeding me an outdated file.
Code
Code is fairly simple:
 var s3 = new AWS.S3();
        var params ={
            Bucket: 'vs2020',
            Key: 'nightly/UT Results/UTR.json',
        };
        s3.getObject(params, function(err, data){
        var response = new TextDecoder('utf-8').decode(data.Body)
        var json = JSON.parse(response)
        console.log(response)
}

I've tried updating the meta data as found through other stack overflow posts, but to no avail.
For example i set cache-control to max-age 0,no-cache,no-store,must-revalidate
Thinking this may be wrong syntax, i also set cache-control to max-age = 0
Neither seemed to work.

A: Turns out S3 keeps a cache of the files and doesn't update it after a certain amount of time. You have to set a metadata field as follows:
cache-control : max-age=0


text:
Q: How to create a view where all data are collected concerning the person who uses the view in ORACLE? The data should come from table Emp and from the other tables Dept and Salgrade. Assume that the user's identifier is available through the constant user (see the result of the query: SELECT User FROM Dual;) is the same as the value Ename. I want to create a row in table Emp with own identifier as Ename.
DB:
EMP
EMPNO | ENAME  |   JOB   |    MGR | HIREDATE |  SAL | COMM |DEPTNO
----- ------- --------- ---- --------- ----- ---- ------
 7839 KING    PRESIDENT NULL 17-NOV-81  5000 NULL     10
 7698 BLAKE   MANAGER   7839 01-MAY-81  2850 NULL     30
 7782 CLARK   MANAGER   7839 09-JUN-81  2450 NULL     10
 7566 JONES   MANAGER   7839 02-APR-81  2975 NULL     20
 7654 MARTIN  SALESMAN  7698 28-SEP-81  1250 1400     30
 7499 ALLEN   SALESMAN  7698 20-FEB-81  1600  300     30
 7844 TURNER  SALESMAN  7698 08-SEP-81  1500    0     30
 7900 JAMES   CLERK     7698 03-DEC-81   950 NULL     30
 7521 WARD    SALESMAN  7698 22-FEB-81  1250  500     30
 7902 FORD    ANALYST   7566 03-DEC-81  3000 NULL     20
 7369 SMITH   CLERK     7902 17-DEC-80   800 NULL     20
 7788 SCOTT   ANALYST   7566 09-DEC-82  3000 NULL     20
 7876 ADAMS   CLERK     7788 12-JAN-83  1100 NULL     20
 7934 MILLER  CLERK     7782 23-JAN-82  1300 NULL     10

DEPT
DEPTNO | DNAME    |   LOC
------ ----------- --------
    10 ACCOUNTING  NEW YORK
    20 RESEARCH    DALLAS
    30 SALES       CHICAGO
    40 OPERATIONS  BOSTON

SALGRADE
GRADE | LOSAL | HISAL
----- ----- -----
    1   700  1200
    2  1201  1400
    3  1401  2000
    4  2001  3000
    5  3001  9999

A: Those tables are owned by user SCOTT so - connect as it; Scott will create a view and grant other users select privileges on a public synonym.
SQL> connect scott/tiger
Connected.
SQL> create or replace view v_emp as
  2    select d.deptno, d.dname, e.empno, e.ename, e.job
  3    from emp e join dept d on e.deptno = d.deptno
  4    where e.ename = user;

View created.

SQL> create public synonym psyn_v_emp for v_emp;

Synonym created.

SQL> grant select on psyn_v_emp to public;

Grant succeeded.

OK; so, what does the owner see?
SQL> show user
USER is "SCOTT"
SQL> select * from psyn_v_emp;

    DEPTNO DNAME               EMPNO ENAME      JOB
---------- -------------- ---------- ---------- ---------
        20 RESEARCH             7788 SCOTT      ANALYST
                                     -----
                                     Scott sees only Scott's data

Connect as some other user (I previously created user named KING):
SQL> connect king/king
Connected.
SQL> show user
USER is "KING"
SQL> select * from psyn_v_emp;

    DEPTNO DNAME               EMPNO ENAME      JOB
---------- -------------- ---------- ---------- ---------
        10 ACCOUNTING           7839 KING       PRESIDENT
                                     -----
                                     King sees only King's data

SQL>

Therefore, if I understood what you're asking, that would be "it".


text:
Q: How to backspace on a numeric (number only) cell in ag-grid? Using the example that AG-Grid has generously provided [https://next.plnkr.co/edit/Gbwc2rBQKJRFbLxS?preview] I'm currently trying to use the numeric editor.
This example is from the ag-grid official site [https://www.ag-grid.com/javascript-grid-cell-editor/#example-cell-editing-using-angular-components]
One thing I've noticed is even on the example provided by AG-Grid, the backspace does not work.
I'm fairly new to AG-Grid and would appreciate any help!
This is the numeric-editor.ts that I am using:
import {AfterViewInit, Component, ViewChild, ViewContainerRef} from
"@angular/core";

import {ICellEditorAngularComp} from "ag-grid-angular";

@Component({
    selector: 'numeric-cell',
    template: `<input #input (keydown)="onKeyDown($event)"
[(ngModel)]="value" style="width: 100%">`
})
export class NumericEditor implements ICellEditorAngularComp,
AfterViewInit {
    private params: any;
    public value: number;
    private cancelBeforeStart: boolean = false;

    @ViewChild('input', {read: ViewContainerRef}) public input;

agInit(params: any): void {
    this.params = params;
    this.value = this.params.value;

    // only start edit if key pressed is a number, not a letter
    this.cancelBeforeStart = params.charPress &&
('1234567890'.indexOf(params.charPress) < 0);
}

getValue(): any {
    return this.value;
}

isCancelBeforeStart(): boolean {
    return this.cancelBeforeStart;
}

// will reject the number if it greater than 1,000,000
// not very practical, but demonstrates the method.
isCancelAfterEnd(): boolean {
    return this.value > 1000000;
};

onKeyDown(event): void {
    if (!this.isKeyPressedNumeric(event)) {
        if (event.preventDefault) event.preventDefault();
    }
}

// dont use afterGuiAttached for post gui events - hook into
ngAfterViewInit instead for this
ngAfterViewInit() {
    window.setTimeout(() => {
        this.input.element.nativeElement.focus();
    })
}

private getCharCodeFromEvent(event): any {
    event = event || window.event;
    return (typeof event.which == "undefined") ? event.keyCode :
event.which;
}

private isCharNumeric(charStr): boolean {
    return !!/\d/.test(charStr);
}

private isKeyPressedNumeric(event): boolean {
    const charCode = this.getCharCodeFromEvent(event);
    const charStr = event.key ? event.key :
String.fromCharCode(charCode);
    return this.isCharNumeric(charStr);
}
}

A: private isCharNumeric(charStr): boolean {
    return !!/\d/.test(charStr) || charStr === 'Backspace';
}

adding backspace to the ischarnumeric function did the trick!


text:
Q: RecyclerView duplicates items I looked the same topics and found nothing that could help me.
So this is my problem. I have an activity with a RecyclerView. I'm using Retrofit2 library to get list of news, here it is:
@GET(VERSION_V1 + "/news")
    Observable<BaseResponse<NewsListResponse>> getCompanyNews(@Query("companyId") String companyId,
                                                              @Query("query") String query,
                                                              @Query("offset") Integer offset,
                                                              @Query("limit") Integer limit,
                                                              @Query("creator") NewsCreatorType creator,
                                                              @Query("date")NewsFilterType dateFilter);

And I have a Presenter:
public void loadData(boolean refresh) {
    mCoreServices
            .getApiService()
            .getApi()
            .getCompanyNews(mCompanyId, "", 0, 100, mCompanyId == null ? NewsCreatorType.SYSTEM : NewsCreatorType.COMPANY, mFilterType)
            .map(response -> response.getResult().getItems())
            .flatMap(news -> {
                if (mCompanyId == null || "".equals(mCompanyId)) {
                    return Observable.just(news);
                } else {
                    return mCoreServices
                            .getApiService()
                            .getApi()
                            .getCompanyNews(null, "", 0, 100, NewsCreatorType.SYSTEM, mFilterType)
                            .map(response -> {
                                news.addAll(response.getResult().getItems());

                                return news;
                            });
                }
            })
            .flatMapIterable(newsItems -> newsItems)
            .map(NewsViewModel::new)
            .toSortedList((news1, news2) -> news2.getDate().compareTo(news1.getDate()))
            .retryWhen(errors -> retryAfterRefreshToken(errors))
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .doOnSubscribe(() -> {
                if (refresh) {
                    getViewState().onShowRefresh(true);
                } else {
                    getViewState().onShowProgressBar(true);
                }

            })
            .doOnUnsubscribe(() -> {
                if (refresh) {
                    getViewState().onShowRefresh(false);
                } else {
                    getViewState().onShowProgressBar(false);
                }
            })
            .subscribe(news -> {
                mResults = news;

                getViewState().onLoadNews(mResults);
            }, new ApiExceptionObservable(TAG) {
                @Override
                public void call(String message) {
                    getViewState().onShowErrorMessage(message);
                }

                @Override
                public void unauthorized() {
                    getViewState().showUnauthorizedDialog();
                }
            });
}

And ofc I have a RecyclerView adapter, this is my onBindViewHolder:
@Override
public void onBindViewHolder(RecyclerView.ViewHolder baseHolder, int position) {
    if (baseHolder instanceof ViewHolder) {
        ViewHolder holder = (ViewHolder) baseHolder;

        NewsViewModel newsViewModel = mResults.get(position);

        holder.mTVTitle.setText(newsViewModel.getTitle());
        holder.mTVContent.setText(newsViewModel.getContent());

        if (NewsCreatorType.SYSTEM.equals(newsViewModel.getCreator())) {
            holder.mTVCreator.setText(newsViewModel.getCreator().getTitle());
        } else {
            holder.mTVCreator.setText(
                    holder.mTVCreator.getContext().getString(
                            newsViewModel.getCreator().getTitle(),
                            mCompanyTitle
                    )
            );
        }
    }
}

Well, I have 2 companies doing news. News from company#1 are not duplicated, news from company#2 are always duplicated.. I don't understand where's my mistake. I checked (using debugger) the answer on my GET, it has no duplicated news, so the problem with my adapter I guess..
Thank you.
EDIT:
I get duplicated news from Creator.SYSTEM only.
EDIT 2.0:
Okay, I removed .flatMap in my Presenter, now it works fine, but I can't understand why it was there, can someone explain please?


text:
Q: Webpack2 + Typescript2 fails to dynamic import json I have a problem at import json dynamically using webpack.
(https://webpack.js.org/api/module-methods/#import-)
It keep shows this error - TS2307: Cannot find module
package versions are..

*

*webpack version: 2.7.0

*typescript version: 2.4.2

*awesome-typescript-loader: 3.2.1
tsconfig.json
{
  "compilerOptions": {
    "outDir": "./dist/",
    "sourceMap": true,
    "noImplicitAny": true,
    "module": "esnext",
    "moduleResolution": "node",
    "target": "es6",
    "jsx": "react",
    "allowJs": true,
    "allowSyntheticDefaultImports": true
  },
  "awesomeTypescriptLoaderOptions": {
    "useBabel": true,
    "useCache": true
  },
  "exclude": ["node_modules"],
  "include": [
    "./components/**/*",
    "./core/*",
    "./pages/*",
    "./utils/*",
    "./urls/*",
    "./translations/**/*",
    "./main.tsx"
  ]
}

webpack.config.js
const path = require('path');
const webpack = require('webpack');
const AssetsPlugin = require('assets-webpack-plugin');
const pkg = require('./package.json');

const isDebug = global.DEBUG === false ? false : !process.argv.includes('--release');
const isVerbose = process.argv.includes('--verbose') || process.argv.includes('-v');
const useHMR = !!global.HMR; // Hot Module Replacement (HMR)
const babelConfig = Object.assign({}, pkg.babel, {
  babelrc: false,
  cacheDirectory: useHMR,
});

// Webpack configuration (main.js => public/dist/main.{hash}.js)
// http://webpack.github.io/docs/configuration.html
const config = {

  // The base directory for resolving the entry option
  context: __dirname,

  // The entry point for the bundle
  entry: [
    // require('babel-polyfill'),
    './main.tsx'
  ],

  // Options affecting the output of the compilation
  output: {
    path: path.resolve(__dirname, './public/dist'),
    publicPath: '/dist/',
    filename: isDebug ? '[name].js?[hash]' : '[name].[hash].js',
    chunkFilename: isDebug ? '[id].js?[chunkhash]' : '[id].[chunkhash].js',
    sourcePrefix: '  ',
  },

  // Developer tool to enhance debugging, source maps
  // http://webpack.github.io/docs/configuration.html#devtool
  devtool: isDebug ? 'inline-source-map' : false,

  // What information should be printed to the console
  stats: {
    colors: true,
    reasons: isDebug,
    hash: isVerbose,
    version: isVerbose,
    timings: true,
    chunks: isVerbose,
    chunkModules: isVerbose,
    cached: isVerbose,
    cachedAssets: isVerbose,
  },

  // The list of plugins for Webpack compiler
  plugins: [
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': isDebug ? '"development"' : '"production"',
      __DEV__: isDebug,
    }),
    // Emit a JSON file with assets paths
    // https://github.com/sporto/assets-webpack-plugin#options
    new AssetsPlugin({
      path: path.resolve(__dirname, './public/dist'),
      filename: 'assets.json',
      prettyPrint: true,
    }),
  ],

  // Options affecting the normal modules
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        include: [
          path.resolve(__dirname, './components'),
          path.resolve(__dirname, './core'),
          path.resolve(__dirname, './pages'),
          path.resolve(__dirname, './apis'),
          path.resolve(__dirname, './urls'),
          path.resolve(__dirname, './translations'),
          path.resolve(__dirname, './main')
        ],
        loader: 'awesome-typescript-loader'
      },
      {
        test: /\.css/,
        use: [{loader: 'style-loader'}, {loader: 'css-loader', options:
          {
            sourceMap: isDebug,
            // CSS Modules https://github.com/css-modules/css-modules
            modules: true,
            localIdentName: isDebug ? '[name]_[local]_[hash:base64:3]' : '[hash:base64:4]',
            // CSS Nano http://cssnano.co/options/
            minimize: !isDebug,
          }},
          // {loader: 'postcss-loader'}
          ],
      },
      {
        test: /\.(png|jpg|jpeg|gif|svg|woff|woff2)$/,
        loader: 'url-loader?limit=10000',
      },
      {
        test: /\.(eot|ttf|wav|mp3)$/,
        loader: 'file-loader',
      },
    ],
  },

  externals: {
    react: 'React'
  },

  resolve: {
    extensions: ['.js', '.ts', '.tsx']
  }
};

// Optimize the bundle in release (production) mode
if (!isDebug) {
  config.plugins.push(new webpack.optimize.UglifyJsPlugin({ compress: { warnings: isVerbose }, sourceMap: isDebug }));
  config.plugins.push(new webpack.optimize.AggressiveMergingPlugin());
}

// Hot Module Replacement (HMR) + React Hot Reload
if (isDebug && useHMR) {
  babelConfig.plugins.unshift('react-hot-loader/babel');
  config.entry.unshift('react-hot-loader/patch', 'webpack-hot-middleware/client');
  config.plugins.push(new webpack.HotModuleReplacementPlugin());
  config.plugins.push(new webpack.NoEmitOnErrorsPlugin());
}

module.exports = config;

custom.d.ts
declare module "*.json" {
  const value: any;
  export default value;
}

my error code
// TS2307: Cannot find module './test.json'.
import('./test.json').then(_ => {
  console.log(_
})

// but these codes work
import './test.json'
import('./test.js').then(_ => { console.log(_)})

I have searched issues as much as possible I can. but no one seems to encountered this issue.
Here's related links what I found.

*

*https://github.com/Microsoft/TypeScript/issues/16820

*https://blog.josequinto.com/2017/06/29/dynamic-import-expressions-and-webpack-code-splitting-integration-with-typescript-2-4/
If anyone have a clue, please let me know.

A: Are you sure your custom.d.ts is in a folder included in the compilation? I believe only typings in packages under node_modules/@types are included if they are not in the "files" or "include" properties in tsconfig.json.


text:
Q: How do I override my SOAP requests when __call() is deprecated? I have extended the SoapClient for authentication and would like to manipulate the request parameters before they are encoded into xml.
I am informed __call() is deprecated and thought __soapCall() was the successor of it. But calling $soapclient->anymethod() does not trigger __soapCall(). Is it not a magic method as __get() is deprecated? How else would I override the requests for adding my Authentication node?
https://www.php.net/manual/en/soapclient.call


text:
Q: retrieving a list element in O(1) in R suppose I have the following:
a <- vector('list',50)

for(i in 1:50)
{
  a[[i]] <- list(path=paste0("file",sample(0:600,1)),contents=sample(1:5,10*i,replace=TRUE))
}

Now, for example; I want to retrieve the contents of file45(assuming it exists in this randomly generated data) as fast as possible.
I have tried the following:
contents <- unlist(Filter(function(x) x$path=="file45",a),recursive=FALSE)$contents

However, the list searching overhead makes reading from memory even slower than reading directly from disk (to some extent).
Is there any other way of retrieving the contents in something reasonably faster than reading from disk ideally O(1) ?
edit: assume that there are no duplicate filepaths in my sublists and that there are largely more than 50 sublists

A: Use the names attribute to track the items instead:
a <- vector('list',50)

for(i in 1:50)
{
  a[[i]] <- list(contents=sample(1:5,10*i,replace=TRUE))
}

names(a) <- paste0("file",sample(1:600,50))

a[["file45"]]
NULL
a[["file25"]]
$contents
 [1] 3 1 3 1 2 5 1 5 1 2 3 1 4 1 1 4 1 5 1 5 1 4 5 2 5 2 2 5 1 1

A: Try the following:
a[sapply(a, function(x) x$path == "file45")][[1]]$contents


text:
Q: Regression in DL4J - predict the next time-step I have a multiLayer network trained, but I'm stuck on how to do a prediction for additional time-steps.
I tried following the character iteration example by creating this method -
public float[] sampleFromNetwork(INDArray testingData, int numTimeSteps, DataSetIterator iter){
    int inputCount = this.getNumOfInputs();
    int outputCount = this.getOutputCount();

    float[] samples = new float[numTimeSteps];

    //Sample from network (and feed samples back into input) one value at a time (for all samples)
    //Sampling is done in parallel here
    this.network.rnnClearPreviousState();
    INDArray output = this.network.rnnTimeStep(testingData);
    output = output.tensorAlongDimension(output.size(2)-1,1,0); //Gets the last time step output

    for( int i=0; i<numTimeSteps; ++i ){
        //Set up next input (single time step) by sampling from previous output
        INDArray nextInput = Nd4j.zeros(1,inputCount);

        //Output is a probability distribution. Sample from this for each example we want to generate, and add it to the new input
        double[] outputProbDistribution = new double[outputCount];
        for( int j=0; j<outputProbDistribution.length; j++ ) {
            outputProbDistribution[j] = output.getDouble(j);
        }
        int nextValue = sampleFromDistribution(outputProbDistribution, new Random());

        nextInput.putScalar(new int[]{0,nextValue}, 1.0f);      //Prepare next time step input
        samples[i] = (nextValue);   //Add sampled character to StringBuilder (human readable output)
        output = this.network.rnnTimeStep(nextInput);   //Do one time step of forward pass
    }

    return samples;
}

but the sampleFromDistribution() doesn't make sense because I am not using discrete classes.
Any thougts?

A: I solved the issue by adjusting my network to use the IDENTITY activation and used the resulting values directly.  Still lots of tweaking to do, but it functions.
public float[] sampleFromNetwork(INDArray priori, int numTimeSteps){
    int inputCount = this.getNumOfInputs();
    float[] samples = new float[numTimeSteps];

    if(priori.size(1) != inputCount) {
        String format = String.format("the priori should have the same number of inputs [%s] as the trained network [%s]", priori.size(1), inputCount);
        throw new RuntimeException(format);
    }
    if(priori.size(2) < inputCount) {
        String format = String.format("the priori should have enough timesteps [%s] to prime the new inputs [%s]", priori.size(2), inputCount);
        throw new RuntimeException(format);
    }

    this.network.rnnClearPreviousState();
    INDArray output = this.network.rnnTimeStep(priori);

    output = output.ravel();
    // Store the output for use in the inputs
    LinkedList<Float> prevOutput = new LinkedList<>();
    for (int i = 0; i < output.length(); i++) {
        prevOutput.add(output.getFloat(0, i));
    }

    for( int i=0; i<numTimeSteps; ++i ){
        samples[i] = (prevOutput.peekLast());
        //Set up next input (single time step) by sampling from previous output
        INDArray nextInput = Nd4j.zeros(1,inputCount);

        float[] newInputs = new float[inputCount];
        newInputs[inputCount-1] = prevOutput.peekLast();
        for( int j=0; j<newInputs.length-1; j++ ) {
            newInputs[j] = prevOutput.get(prevOutput.size()-inputCount-j);
        }

        nextInput.assign(Nd4j.create(newInputs)); //Prepare next time step input
        output = this.network.rnnTimeStep(nextInput); //Do one time step of forward pass
        // Add the output to the end of the previous output queue
        prevOutput.addLast(output.ravel().getFloat(0, output.length()-1));
    }
    return samples;
}


text:
Q: Why are my swagger docs showing 'additionalProperties = false' for my custom schema filter? I have this SchemaFilter in my swagger config
public class SmartEnumSchemaFilter : ISchemaFilter
{
    public void Apply(OpenApiSchema schema, SchemaFilterContext context)
    {
        if (!TryGetSmartEnumValues(context.Type, out var values))
        {
            return;
        }

        var openApiInts = new OpenApiArray();
        openApiInts.AddRange(values.Select(x => new OpenApiInteger(x.Value)));

        schema.Type = "integer";
        schema.Enum = openApiInts;
        schema.Properties = null;
        schema.Description = string.Join(", ", values.Select(v => $"{v.Value}: {v.Name}"));
    }
}

It is working well, but for some reason this "additional properties" always appears in the docs:

But only for this particular schema - all the other schemas don't have it. Is there some way of removing it?
I tried setting both
schema.AdditionalProperties = null;
schema.AdditionalPropertiesAllowed = false;

but it made no difference


text:
Q: serializeObject on form selector I have a HTML form with a number of inputs, I wish to turn the elements of the form into a JSON string. So I have something like the following
$('#myForm').submit( function() {
    var data = JSON.stringify($(this).serializeObject());
    //do more stuff
});

I am however getting

Object doesn't support property or method 'serializeObject'

Any ideas? I can see from the debugger that this is a HTMLFormElement

A: There is serialize() and serializeArray() but no serializeObject().
are you using any other library or what?

A: What you're looking for is .serializeArray() which returns, like the jQuery Docs say:

a JavaScript array of objects, ready to be encoded as a JSON string. It operates on a jQuery collection of forms and/or form controls.

You should update your code to the following:
$('#myForm').submit( function() {
    var data = JSON.stringify($(this).serializeArray());
    //do more stuff
});


text:
Q: rvest scrape links from webpage I'm using rvest to scrape some links from the magazine 'The Hustle'. I've used this code
library(rvest)

page <- read_html("https://thehustle.co/daily/page/33/") %>%
  html_nodes(".daily-article-title") %>%
  html_attr('href')

However this returns a vector of 30 NAs. I used SelectorGadget to find the class, so not sure what is going wrong here.

A: The links are present above the class '.daily-article-title'. Here is a way to get title and the corresponding links.
library(rvest)

webpage <- read_html("https://thehustle.co/daily/page/33/")

webpage %>%
  html_nodes("h3.daily-article-title") %>%
  html_text() -> title

title

# [1] "\nApple buys itself a $400m Christmas present\n"
# [2] "\nSan Francisco wages war on robots\n"
# [3] "\nThe US could lose its greatest export\n"
# [4] "\n\"Mom, where do podcasts come from?\"\n"
# [5] "\nTencent Music to team up with Spotify?\n"
# [6] "\nFirst rule of the Farmers Business Network?\n"
# [7] "\nSpiegel goes HAM on social media\n"
# [8] "\nBanks won't take weed companies' cash\n"
# [9] "\nThe Koch bros just took a $650m stake in Time\n"
#[10] "\n4 mins to smarter Monday smalltalk\n"
#...
#...

webpage %>%
  html_nodes("[class='col-md-12 daily-wrap clearfix'] a") %>%
  html_attr('href') -> link

# [1] "https://thehustle.co/apple-christmas-present"
# [2] "https://thehustle.co/war-on-robots"
# [3] "https://thehustle.co/big-data-trade-nafta-daily"
# [4] "https://thehustle.co/apple-podcast-market"
# [5] "https://thehustle.co/tencent-spotify-truce"
# [6] "https://thehustle.co/first-rule-of-farmers"
# [7] "https://thehustle.co/snap-anti-facebook"
# [8] "https://thehustle.co/weed-banking"
# [9] "https://thehustle.co/pepshi-bros"
#[10] "https://thehustle.co/rundown"
#...
#...


text:
Q: Software Updater not giving option to upgrade I am anup from delhi ,India and  my server is http://repos.del.extreme-ix.org/ubuntu ,since  yesterday (23 april 2020) I have  been trying  to  check and  recheck by clicking on software updater and  unfortunately  it is not giving me  any option  to  upgrade to   latest version of ubuntu 20.04 .
I am currently  working on ubuntu 18.04 .Please  let me  know   if  there is  a workaround


text:
Q: Data not being displayed in form when fetching values from database I am wanting to put the values I have fetched from my database through a query into my HTML form's drop down menu. However, the drop down menu in my form shows blank values, and I am not sure if it is to do with the syntax of my code or the query itself.
SQL Query:
SELECT CONCAT(acd.Room_No, SPACE(1), acd.Band, SPACE(1), acd.Total_Cost, SPACE(1), ad.Street) as info FROM accommodation_details as acd
 INNER JOIN Address as ad
 WHERE ad.Address_ID = acd.Address_ID AND acd.Availability = "Y";

on running this query in get this output:
+-------------------------------+
| info                          |
+-------------------------------+
| 1D A 6950 Basketball Lane     |
| 2C B 7000 ONCE Housing        |
| 2D B 7000 ONCE Housing        |
| 2E B 7000 ONCE Housing        |
| 3B C 7000 Petits Filous Road  |
| 3D C 7000 Petits Filous Road  |
| 3E C 7000 Petits Filous Road  |
| 4B D 7000 Sanpei Heights      |
| 4C D 7000 Sanpei Heights      |
| 4E D 7000 Sanpei Heights      |
| 14A D 6900 Golden Gate Towers |
| F7 B 4530 Hudson River        |
| F8 B 4530 Sora Close          |
+-------------------------------+

in which the query is shown to be working, now when I try to put these values into my HTML form drop down box using PHP through this code:
    <label for = "rooms_avail">Select a room: </label>
    <select name = "rooms_avail" id = "rooms_avail" style="width: 300px;">
        <option>Select</option>
        <?php
             $query = 'SELECT CONCAT(acd.Room_No, SPACE(1), acd.Band, SPACE(1), acd.Total_Cost, SPACE(1),
ad.Street) FROM accommodation_details as acd
             INNER JOIN Address as ad WHERE ad.Address_ID = acd.Address_ID AND acd.Availability = "Y";';
            $result = mysqli_query($con, $query);
            while ($row = mysqli_fetch_array($result)) {
                echo '<option>'.$row["acd.Room_No"].'</option>';
                echo '<option>'.$row["acd.Band"].'</option>';
                echo '<option>'.$row["acd.Total_Cost"].'</option>';
                echo '<option>'.$row["Street"].'</option>';
            }
            ?>
    </select>

I get the following output in my form:

any advise on how i can get around this issue?
Also sorry if I posted in the wrong forum, I am not sure if this is to do with my query (through the database hence on the db forum).

A: I found out the issue. I was echoing each field of my query rather than echoing the id of the concatenated version of the row.
My previous code (which was echoing each id of each fields)
        echo '<option>'.$row["acd.Room_No"].'</option>';
        echo '<option>'.$row["acd.Band"].'</option>';
        echo '<option>'.$row["acd.Total_Cost"].'</option>';
        echo '<option>'.$row["Street"].'</option>';

I changed my code to:
         $query = 'SELECT CONCAT(acd.Room_No, SPACE(1), acd.Band, SPACE(1), acd.Total_Cost, SPACE(1), ad.Street) as info FROM accommodation_details as acd
         INNER JOIN Address as ad WHERE ad.Address_ID = acd.Address_ID AND acd.Availability = "Y";';

where I used as info in the query (to name the whole row) and instead echoed the name used to recognize each row (with concatenated fields):
        while ($row = mysqli_fetch_array($result)) {
            echo '<option>'.$row["info"].'</option>';

And now displays each row in info in the drop down box


text:
Q: refreshing data in component after BehaviorSubject changed i have a total price in BehavoiurSubject
 export class ShoppingCartService {`

      public totalPriceSubject = new BehaviorSubject<number> (this.getTotalPrice(this.loadOrderedProducts()));

      getTotalPrice(selectedProducts: SelectedProductOrderModel[]): number {
        let totalPrice = 0;
        for (const orderedProduct of selectedProducts) {
          totalPrice += orderedProduct.quantity * orderedProduct.product!.price;
        }
        return totalPrice;
      }
    }

i display it in shopping cart component.ts
export class ShoppingCartComponent implements OnInit {

  totalPrice: number;
  private totalPriceSub: Subscription;

  ngOnInit(): void {
    this.usersSelectedProducts = JSON.parse(<string>localStorage.getItem('selectedProductOrders'));
    this.totalPriceSub = this.cartService.totalPriceSubject
            .subscribe(totalPrice => {
              this.totalPrice = totalPrice;
            });
  }

.html
 <td>${{totalPrice}}</td>

but when i m adding one more product in shopping cart component, totalPrice doesnt update, i need to refresh page and then i get new number. Can anyone please advise me how to solve it, i want it after i add one more product it will update totalPrice. thx

A: Try to do following changes in your service files
export class ShoppingCartService {

  calTotalPrice  = (selectedProducts: SelectedProductOrderModel[]) : number => {
    let totalPrice = 0;
    for (const orderedProduct of selectedProducts) {
      totalPrice += orderedProduct.quantity * orderedProduct.product!.price;
    }
    return totalPrice;
  }

  public totalPriceSubject = new BehaviorSubject<number>(this.calTotalPrice(cartItemList))

  totalPrice = this.totalPriceSubject.asObservable();

  constructor() { }

  setTotalPrice(price: number) {
    this.totalPriceSubject.next(price);
  }

}

In your component, you can subscribe and receive the values.
this.totalPriceSub = this.cartService.totalPrice
            .subscribe(totalPrice => {
              this.totalPrice = totalPrice;
            });


text:
Q: Decode JSON one time and shows data Well, from the beginning. I have a link to the API from which I download data to the website:
<?php
$api = file_get_contents('LINK DO API');
$decoded_json = json_decode($api, true);
$data = $decoded_json['data'];
$dane = $data['temp_and_humidity_ch3']['temperature'];

{
  echo $dane['value'].$dane['unit'];
}
?>

it works and everything shows up. The problem is that I have 19 such data to download and display. When I insert the same code 19 times, changing only the displayed parameter, the page instead of loading less than a second takes almost 8 seconds... I have no idea how to do it in such a way that the whole thing is downloaded only once and then only displayed, without re-decoding the JSON.

A: As far as I can tell, a single API call returns all the values you need. Of course I cannot test this, but try this code:
<?php

$json = file_get_contents('LINK DO API');
$data = json_decode($json)->data;

echo '
';
print_r($data);
echo '
';

foreach (range(1, 8) as $channelNo) {
  $temperature = $data->{'temp_and_humidity_ch' . $channelNo}->temperature;
  echo "ChannelchannelNo {$temperature->value}{$temperature->unit}
";
}

This code should first show you all the data that the API returns and then give you the temperature readings of all 8 channels with one API call.


text:
Q: Stream using libstreaming to VLC 2.2.4 exception I setup libstreaming to stream video from Android camera to VLC 2.2.4 on my macOS.
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(context).edit();
editor.putString(RtspServer.KEY_PORT, String.valueOf(1777));
editor.apply();

SessionBuilder.getInstance()
                .setContext(context)
                .setCallback(this)
                .setAudioEncoder(SessionBuilder.AUDIO_NONE)
                .setVideoEncoder(SessionBuilder.VIDEO_H264)
                .setVideoQuality(new VideoQuality(640, 480, 15, 500000));

context.startService(new Intent(context, RtspServer.class));

Then I builded url bellow and opened it in VLC 2.2.4:
rtsp://172.xx.xx.67:1777?h264=500000-15-640-480

Then I received some logs on Android side:
OPTIONS
RTSP/1.0 200 OK
Server: MajorKernelPanic RTSP Server
Cseq: 2
Content-Length: 0

DESCRIBE
SPS: Z0KAHtoCgPaAbQoTUA==
PPS: aM4G4g==
RTSP/1.0 200 OK
Server: MajorKernelPanic RTSP Server
Cseq: 3
Content-Length: 272
Content-Base: 172.xx.xx.53:1777/
Content-Type: application/sdp

v=0
o=- 0 0 IN IP4 172.xx.xx.53
s=Unnamed
i=N/A
c=IN IP4 172.xx.xx.26
t=0 0
a=recvonly
m=video 5006 RTP/AVP 96
a=rtpmap:96 H264/90000
a=fmtp:96 packetization-mode=1;profile-level-id=42801e;sprop-parameter-sets=Z0KAHtoCgPaAbQoTUA==,aM4G4g==;
a=control:trackID=1

SETUP
PPS: aM4G4g==
SPS: Z0KAHtoCgPaAbQoTUA==
RTSP/1.0 200
Server: MajorKernelPanic RTSP
Cseq: 4
Content-Length: 0
Transport: RTP/AVP/UDP;unicast;destination=172.xx.xx.26;client_port=5006-5007;server_port=42104-42497;ssrc=68db94da;mode=play
Session: 1185d20035702ca
Cache-Control: no-cache

PLAY
RTSP/1.0 200 OK
Server: MajorKernelPanic RTSP Server
Cseq: 5
Content-Length: 0
RTP-Info: url=rtsp://172.xx.xx.53:1777/trackID=1;seq=0
Session: 1185d20035702ca

TEARDOWN
RTSP/1.0 200 OK
Server: MajorKernelPanic RTSP Server
Cseq: 6
Content-Length: 0

java.lang.IllegalStateException: No successful match so far
at java.util.regex.Matcher.ensureMatch(Matcher.java:471)
at java.util.regex.Matcher.group(Matcher.java:579)
at net.majorkernelpanic.streaming.rtsp.RtspServer$Request.parseRequest(RtspServer.java:643)
at net.majorkernelpanic.streaming.rtsp.RtspServer$WorkerThread.run(RtspServer.java:393)
E/RtspServer:Error parsing CSeq: Attempt to read from field 'java.util.HashMap net.majorkernelpanic.streaming.rtsp.RtspServer$Request.headers' on a null object reference
RTSP/1.0 400 Bad Request
Server: MajorKernelPanic RTSP Server
Content-Length: 0

Or shortly:
OPTIONS 200 -> DESCRIBE 200 -> SETUP 200 -> PLAY 200 -> TEARDOWN 200
-> Error parsing CSeq (IllegalStateException: No successful match so far)
- no method in the request

After successful connect (all steps above) I get exception in RtspServer.
As result I can't play the stream.

Here is the log for official example spydroid-ipcamera (connecting from VLC 2.2.4):

!!! It works on VLC 1.1.5:


text:
Q: Hungarian BibLaTeX online citation How to make BibLaTeX print

Elérhető: http://digitus.itk.ppke.hu/~lazar/cnn/SegedFileok/ZA_TemplTervArt.pdf (elérés dátuma 2014. 04. 22.).

instead of

Available: http://digitus.itk.ppke.hu/~lazar/cnn/SegedFileok/ZA_TemplTervArt.pdf (visited on 04/22/2014).

?
MWE:
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage[magyar]{babel}
\usepackage{lmodern, filecontents}
\usepackage[style=ieee]{biblatex}

\begin{filecontents}{\jobname.bib}
@article{zarandy_art_temdesign,
    author = {Zarándy, Ákos},
    title = {The art of {CNN} template design},
    journal = {International Journal of Circuit Theory and Applications},
    volume = {27},
    number = {1},
    publisher = {John Wiley & Sons, Ltd.},
    issn = {1097-007X},
    url = {http://digitus.itk.ppke.hu/~lazar/cnn/SegedFileok/ZA_TemplTervArt.pdf},
    urldate = {2014-04-22},
    pages = {5--23},
    year = {1999}
}
\end{filecontents}

\addbibresource{\jobname.bib}

\begin{document}
\cite{zarandy_art_temdesign}
\printbibliography
\end{document}

A: UPDATE
The next version of biblatex (3.12, no release date announced yet as of August 2018) will come with built-in Hungarian support. If you have this or a later version, you do not need to do anything else.

PREVIOUS
Put this in the magyar.lbx file:
\DeclareBibliographyStrings{%
    % ...
    url          = {{Elérhető}{Elérhető}},
    urlfrom      = {{elérhető}{elérhető}},
    urlseen      = {{elérés dátuma}{elérés dátuma}},
}

\DeclareBibliographyExtras{
    % ...
    \protected\def\mkbibordinal#1{\stripzeros{#1}\adddot}%
    \protected\def\mkbibdatelong#1#2#3{% suppose that all fields are defined, until a bug pops up
        \mkbibordinal{\thefield{#1}}%
        \space%
        \mkbibmonth{\thefield{#2}}%
        \nobreakspace%
        \mkbibordinal{\thefield{#3}}%
    }
    \protected\def\mkbibdateshort#1#2#3{% suppose that all fields are defined, until a bug pops up
        \mkbibordinal{\thefield{#1}}%
        \space%
        \mkbibordinal{\thefield{#2}}%
        \nobreakspace%
        \mkbibordinal{\thefield{#3}}%
    }
}


text:
Q: How can I disable script in runtime? I have a problem, it is that gameobject.enabled does not work, and I tried everything but I can not solve it, I would appreciate very much if you help me. Here are the scripts I wrote:

Beforehand, thank you very much.
Here the code:
public class GenerarCartaAleatoria : MonoBehaviour
{
    public GameObject go, padre;

    string numSprite;
    int contador = 1;
    int contadorChild;
    int contadorOrder = 329;

    public void Generar()
    {
        string numRandom = Random.Range(1,36).ToString();
        int numLenght = numRandom.Length;

        if (numLenght == 1)
        {
            numSprite = "Sprites/000" + numRandom;
        }
        else if(numLenght == 2)
        {
            numSprite = "Sprites/00" + numRandom;
        }
        else if (numLenght == 3)
        {
            numSprite = "Sprites/0" + numRandom;
        }
        else if (numLenght == 4)
        {
            numSprite = "Sprites/" + numRandom;
        }

        GameObject spriteCosa = Instantiate(go);

        spriteCosa.transform.parent = padre.transform;

        GameObject cosasa = transform.GetChild(contadorChild).gameObject;

        cosasa.AddComponent<Image>();

        cosasa.GetComponent<GenerarCartaAleatoria>().enabled = false;

        cosasa.transform.SetSiblingIndex(0);

        cosasa.name = contador.ToString();

        cosasa.GetComponent<Image>().sprite = Resources.Load<Sprite>(numSprite);

        cosasa.GetComponent<RectTransform>().localScale = new Vector3(1,1,0);

        cosasa.GetComponent<RectTransform>().localPosition = new Vector3(-171, contadorOrder, 0);

        contador++;
        contadorChild++;
        contadorOrder += 100;
    }
}

My hierarchy:

A: If you are trying to disable a GameObject, the use is gameObejct.SetActive(bool) where bool is either true or false. To turn it off, the line would be yourGameObjectHere.SetActive(false) or in your case, cosas.SetActive(false).
I am a bit confused with the wording of your question though. You wrote gameObject.enabled does not work. Do you mean that the .enabled is not working on your component? When you use the .enable it is used on a component-wise basis, so it would be disabling the component called GenerarCartaAleotoria on the gameObject you are finding. Is this .enabled = false not working and that is your question?