text:
Q: AttributeError: 'TensorVariable' object has no attribute 'nonezeros' I want to clip to specific values with reference to their location in a tensor. so I'm trying to get their locations when they equal to one in the tensor y. But I'm receiving this error message
AttributeError: 'TensorVariable' object has no attribute 'nonezeros'
I can't post all the code but it is similar to the tutorial CNN on theano website.
def MSE2(self, y):
    loc = T.eq(y,1).nonezeros()[0]
    # loc = np.where(y == 1)[0]
    S = T.clip(self.input1[loc],0,1)
    self.input1 = T.set_subtensor(self.input1[loc], S)
    return T.mean((y - self.input1) ** 2)

classifier.predictor.MSE2(y)

train_model = theano.function(
        inputs=[index],
        outputs=cost,
        updates=updates,
        givens={
            x: train_set_x[index * batch_size: (index + 1) * batch_size],
            y: train_set_y[index * batch_size: (index + 1) * batch_size]
        },
        on_unused_input='ignore'
    )

I tested nonzero out of this CNN code and it worked as a test
class test:
    def __init__(self, X):
        self.X = X
    def cost_MSE(self, Y):
        loc = T.eq(Y, 1).nonzero()[0]
        self.X = T.set_subtensor(self.X[loc], T.clip(self.X[loc], 0, 1))
        return T.mean((Y - self.X)**2)

X = T.vector()
Y = T.ivector()

cnn = test(X)
MSE = cnn.cost_MSE(Y)
grads = T.grad(MSE, X)

x = np.array([.5, 10], np.float32)
y = np.array([0,1], np.int32)
y_test = theano.shared(y)
f = theano.function(
    inputs = [],
    outputs = grads,
    givens = {
        X: x,
        Y: y_test
    },
    on_unused_input = 'ignore')
print(f())

A: The method is called nonzero, that's why your second example worked:
loc = T.eq(Y, 1).nonzero()[0]

and the first didn't:
loc = T.eq(y,1).nonezeros()[0]
#                  ^------- to fix it remove this "e"


text:
Q: How to get FileTrigger to work with Azure file storage in Webjob I have a webjob that I have set up to be triggered when a file is added to a directory:
[FileTrigger(@"<DIR>\<dir>\{name}", "*", WatcherChangeTypes.Created, autoDelete: true)] Stream file,

I have it configured:
var config = new JobHostConfiguration
                {
                    JobActivator = new NinjectActivator(kernel)
                };
                var filesConfig = new FilesConfiguration();
#if DEBUG
                filesConfig.RootPath = @"C:\Temp\";
#endif
                config.UseFiles(filesConfig);
                config.UseCore();

The path is for working locally and I was expecting that commenting out the FilesConfiguration object leaving it default would allow it to pick up the connection string I have set up and trigger when files are added. This does not happen it turns out that by default the RootPath is set to "D:\Home" and produces an InvalidOperationException
System.InvalidOperationException : Path 'D:\home\data\<DIR>\<dir>' does not exist.

How do I get the trigger to point at the File storage area of the storage account I have set up for it. I have tried removing the FilesConfiguration completely from Program.cs in the hope that it would work against the settings but it only produces the same Exception.

A:
System.InvalidOperationException : Path 'D:\home\data\\' does not exist.

When you publish to azure, the default directory is D:\HOME\DATA, so when you run webjob it could not find the path so you get the error message.

How do I get the trigger to point at the File storage area of the storage account I have set up for it.

The connectionstring you have set have two  applies: one is used for dashboard logging and the other is used for application functionality (queues, tables, blobs).
It seems that you could not get filetrigger working with azure file storage.
So, if you want to invoke your filetrigger when you create new file, you could go to D:\home\data\ in KUDU to create a DIR folder and then create new .txt file in it.
The output is as below:

BTW, it seems that you'd better not use autoDelete when you create file, if use you will get error like:
NotSupportedException: Use of AutoDelete is not supported when using change type 'Changed'.

redpajama_set_name: RedPajamaStackExchange


text:
Q: External unit normal field of cylinder

Hello, I consider
    $$
A:=\left\{(x,y,z)\in\mathbb{R}^3:x^2+y^2\leq 1,0\leq z\leq 1\right\}
$$
    and
    $$
v(x,y,z):=(x^3,x^2y,zx^2).
$$
    and the task is to calculate the surface of $A$ by using the integral theorem of Gauß.

I guess it is meant to use
$$
\int\limits_{\partial A}\langle v,w\rangle\, dS=\int\limits_A\mbox{div } v\, d^3x,
$$
where $w$ is the external unit normal field of $\partial A$.
Am I right that the external normal field of $\partial A$ is given by $w(x)=e_3$, when $x$ is in the "cover" of the cylinder $A$, $w(x)=-e_3$, when $x$ is in the "ground" of the cylinder "A" and $w(x)=(x,y,0)$ is $x$ is the rest of the cylinder $A$?

A:
$\displaystyle{\vec{r}_{\perp} \equiv x\,\hat{x}\ +\ y\,\hat{y}}$.

\begin{eqnarray*}
\int\left\vert{\rm d}\vec{S}\right\vert
& = &
\int\hat{r}_{\perp}\cdot{\rm d}\vec{S}
=
\int\nabla\cdot\left(\vec{r}_{\perp} \over r_{\perp}\right)\,{\rm d}V
=
\int\left\lbrack
\vec{r}_{\perp}\cdot\nabla\left(1 \over r_{\perp}\right)
+
{1 \over r_{\perp}}\,\nabla\cdot\vec{r}_{\perp}
\right\rbrack\,{\rm d}V
\\
& = &
\int\left\lbrack
\vec{r}_{\perp}\cdot\left({-1 \over r_{\perp}^{2}}\,{\vec{r}_{\perp} \over r_{\perp}}\right)
+
{1 \over r_{\perp}}\,2
\right\rbrack\,{\rm d}V
=
\int{1 \over r_{\perp}}\,{\rm d}V
=
\int_{0}^{r}{\rm d}r_{\perp}\int_{0}^{2\pi}\,{\rm d}\theta\int_{0}^{h}{\rm d}z
\\
& = &
2\pi rh
\end{eqnarray*}


text:
Q: Simply put Floer homology I would like to understand what exactly Floer homology $HF_*(Y)$ for a simply connected compact 3-manifold $Y$ is. I understand there are many variants of Floer homology (and cohomology) but I would like to ask for a "take home universal informal definition".
Of special interest, as a physicist, is the instanton-Floer homology. But what mathematical information is encoded there? Since it is a homology theory over a space such as $\Sigma_g \times S^1$, I should be able to define it solely in terms of singular homology? Or can I somehow view instanton Floer cohomology in terms of de Rham cohomology?
Most textbooks require a lot of background, so I am happy with a vague answer to help me get intuition.


text:
Q: Is there a character encoding or a markup language with a lettercase modifier? Not sure if this fits here. If there is something like "Computer history and future" please direct me there.
Question
Since the rise of computers, were there any character encodings (or markup languages on top of that), that differentiate between uppercase and lowercase letters, but not by defining the entire alphabet twice (once in capitals and once in lowercase letters), but by adding a modifier or keyword that specifies a character to be in a specific case.
Why Would Someone Do This?
Maybe to encod text in less space, or simply because the authors considered the choice between ABC and abc more cosmetic than meaningful, which brings me to a lengthy and philosophical background explanation, see next section:

Skip everything from here if you are not interested in how I came up with this question.
Representation and Meaning
"Modern" encodings like ASCII and UTF-8 differentiate between uppercase and lowercase by assigning individual code points to each. This fundamental decision is so ubiquitous today, that concepts like case sensitivity appear rather natural to us. But when comparing Morse code, ASCII and Unicode, there are are a lot of distinctions that were traditionally stored in markup languages on top of the plain text encoding (e.g. rtf, tex, html, doc) but could be stored in plain text today:

*

*Letter casing ABC, abc

*Style ABC, , , ℂ, , ℭ,

*Decorations ABC, A̲B̲C̲, A̶B̶C̶, A̷B̷C̷

*Color

Very old encodings like Braille and Morse code do not encode letter casing, but ASCII does. In fact, it forces you to pick either capitals or lowercase letters. There is no definitive default style if you don't care.
Unicode and its UTF encodings often continued on that route by forcing you to differentiate not only between letter cases, but also between regular, italic, bold; sans-serif, serif; script, Fraktur; and more. But Unicode also supports modifiers. Instead of defining the entire alphabet again, only underlined/colored/..., there are combining characters that behave similar to keywords in markup languages. A special (sequence of) code points indicates that the next symbol should be underlined / have a different color / ... .
Unicode aims at encoding meaning and not representation. We have all these seemingly cosmetic variants in Unicode, because they convey a different meaning to someone. However, the more "meaningful" distinctions are made, the more I get a feeling that standardizing meaning without representation is impossible. Some examples:
Purely cosmetic representation that became standardized meaning

*

*Lowercase letters were invented as a script. If lowercase was invented today, we would simply call it a "Font" and consider it to be purely cosmetic.

*Mathematicians used bold letters for non-scalar variables. As writing bold by hand was tedious, some teachers drew only the outline of those bold letters, resulting in double struck blackboard bold fonts (ℂ). Nowadays, the styles N and ℕ imply very different things to mathematicians.

Standardized meaning that changed based on the representation

*

*You might be irritated at your grandma writing things like "Your grandpa died " because she misinterpreted the emoji as being sad. But let's be honest, do you really know the standardized meaning of emojis, or do you simply use them like the people around you, turning them into a mix of inside jokes and a full-blown cant.  and  might be popular emojis, but not because they are standardized as eggplant and peach. And if you are using  to express anger, are you really better than your grandma?

An obscure mix of both

*

*The variant pi ϖ probably started out as a cursive/curly lowercase pi π, but might have been misread as an overlined lowercase omega ω and is therefore known as pomega and drawn more like an omega than a pi.

In an alternate universe ...
I wondered if history could have taken another turn, where people looked at these problems and thought: You know what? We cannot tell cosmetics and meaning apart. So lets try to create an encoding for the plainest of plain texts where you cannot even distinguish between uppercase and lowercase. Then add another encoding or markup language on top, that offers tons of modifiers or keywords to express whatever cosmetics you like.
In such a world, "plain text" could mean something like "a sequence of "regular" keystrokes" where computer keyboards send standardized and internationally unique scan codes.

A:
were there any character encodings (or markup languages on top of that), that differentiate between uppercase and lowercase letters, but not by defining the entire alphabet twice (once in capitals and once in lowercase letters), but by adding a modifier or keyword that specifies a character to be in a specific case.

That's pretty much exactly how ASCII works. The letter "A" is the bit-sequence 1x0 0001. The x defines which letter-case you want. Similarly, 000 0001 is "Control-A". It's also no accident that 001 0001 is the digit 1 (the digit equivalent of "A"). The leading two bits of ASCII sequences establish the kind of character the next 5 bits identify. The kind of modifier you're describing is sent in every byte. This is entirely on purpose. It allows extremely efficient hardware implementations for printing characters on a teletype.
This can be very good for normalizing letters in search. You can just set bit 6 to 0 (or ignore bit 6), and then upper and lowercase letters are the same.
In a different way, TTS (Teletypesetting) systems also had what you're describing. It was a modified Baudot code with an extra rail that allowed encoding of both upper-vs-lower case letters and standard-vs-italic.
The key feature of Baudot code is that it shifts modes using LTRS and FIGS codes. (Be very careful when researching Baudot codes. "Lower case" generally means "uppercase letters" and "upper case" generally means figures. These harken back to the more literal meaning of "case.")
6-unit TTS extended this by adding an additional rail allowing a "double-shift" to set letter-case and formatting (italic). This is very close to what you're describing.
The big disadvantage to the "shift" approach is that it's not self-synchronizing. If you jump into the middle of a stream, you don't know how to display the characters because you don't know what mode you're in. So it's very nice to send modifiers directly on the code. But this makes codes larger.
Many of the things you describe in your question about Unicode aren't quite for the reasons you're suggesting. For example,  is MATHEMATICAL SCRIPT CAPITAL A, which expressly is not for style, but to convey specific semantic meaning. ("The characters in this block are intended for use only in mathematical or technical notation, and not in nontechnical text.")  exists for backward compatibility with previous Japanese standards. It's not an indication that Unicode intends to encode cosmetics. ("Nearly all of the enclosed and square symbols in the Unicode Standard are considered compatibility characters, encoded for interoperability with other characters sets.")

So lets try to create an encoding for the plainest of plain texts where you cannot even distinguish between uppercase and lowercase.

This could be an entertaining hobby project, and possibly very educational. Best of luck with it. I would recommend studying the history and controversy around Han unification to get a feel for how complex these topics become in practice. Some starter questions just to think about:

*

*Some forms of Romanized Arabic (also Klingon, though not currently part of Unicode) use letter case to distinguish between completely different letters. Does that change anything about your encoding?

*On AZERTY keyboards é has its own key. In your encoding is é a single "letter" or a modification of e? How do "regular keystrokes" apply to this?

*What does "scan code" mean for this? Usually scan codes represent just a location on a keyboard, so how does that work for other keyboard layouts like AZERTY or Dvorak?
I would also study the history of UTF-16, and why UTF-8 has been so much more successful. Creating a new encoding that is not backward compatible with Latin-1 and requires substantially more space to store English is going to need some major advantages to actually be deployed. (See also IPv6.) But that impracticality should not dissuade you from exploring it.


text:
Q: How to create a fake class from scratch with PHPUnit? I currently need to test a method that checks a class for the existance of a supplied method with PHPUnit.
Currently I simply create an empty class inside my unit test and it works fine. I am guessing there is probably a better solution though. This is the code that I am currently running:
class ControllerMiddleWareTest extends TestCase
{
    /**
     * Check to see if a faulty method name leads to a MethodNotFoundException.
     */
    public function testShouldMethodNotFoundException()
    {
        $this->expectException(MethodNotFoundException::class);

        $parameterBag = new Bag(['lang' => 'NL']);

        // This class name(and method) should never exist.
        new ControllerMiddleware('AwesomeController', 'init', $parameterBag);
    }
}

// Mock class so we get a MethodNotFoundException.
class AwesomeController{}

I have found plenty of examples where an existing class is being mocked but not where a class is created like this. How would I go about doing this properly?

A: Found the solution:
$this->getMockBuilder('AwesomeController')->getMock();

If anybody else knows a better way or has any suggestions, I would be happy to hear it.


text:
Q: What is an example of a search problem that is not in NP? I feel like there should be an easy example, but I can't think of one. So, specifically, I am looking for a Yes/No search problem that is not in the class NP. When you learn about P and NP, you get a lot of examples of problems in P, NP, NP-hard, NP-complete, co-NP, etc. I guess, halting problem would work, but I would like something for which computability is not the reason why it is not NP.

A: You can use the time hierarchy theorem to manufacture problems that have yes/no answers but which aren't in NP by, say, requiring they take at least a super-polynomial amount of nondeterministic time to compute.
Another option is to look at NEXP-complete problems. The time hierarchy theorem guarantees that none of these problems are solvable in nondeterministic polynomial time, yet they're all yes/no problems.

A: Actually, no such problem exists! We know this because the way we define the class NP is essentially as the class of all search problems. Remember that any search problem can be defined by an input instance I, and a verification algorithm C, where C(I) returns true if and only if I satisfies whatever constraints we want. C must do this in polynomial time. In the case of the Traveling Salesman Decision problem, C check that our instance I (a path in a graph) is a cycle, touches all vertices exactly once, and has weight less than some budget b. So, even though all problems in NP don't seem like search problems at first, they are. We know this because for all problems in NP, we can solve them via an exhaustive search (iterating through all possible valid inputs to C and seeing if any return True).


text:
Q: Three.js - Shadow.bias fixes shadow static, but moves the shadows. How to fix? I have a scene with a light casting shadows. It does well, except from the static from the shadow. Like so:

When I add a simple light.shadow.bias = -0.005;:

It fixes the issue, but causes another. As you can see from the building's shadow, the shadows are completely out of place! Is there a way to fix this, or an alternative method of getting rid of the shadow static?

A: You should be able to mitigate the issue by using the new normalBiasBias property. From the documentation:

Defines how much the position used to query the shadow map is offset along the object normal. The default is 0. Increasing this value can be used to reduce shadow acne especially in large scenes where light shines onto geometry at a shallow angle. The cost is that shadows may appear distorted.


text:
Q: ArcGIS Server Object Extension (SOE) RestOperation configuration How would you accept a call to a RestOperation with string and reply back with a json array of the column names in the table holding this information?
So, if string is 'owners' then get names of col1,col4,col9,col10, if string is 'zipcode' get name of col9. etc...
New to the SOE, and excited for some guidance, thanks.


text:
Q: QWebView: Get size of the content does anybody know how to retrieve the Size of the content within a QWebView?
I've tried
QWebView v;
...
v.page()->mainFrame()->contentsSize();

but this always returns 640x480, independend of the current Content.

A: There are two caveats with the mentioned v.page().mainFrame().contentsSize().
wait until the page has finished loading
The mentioned method only works properly if the content has finished loading. You can not call it directly after a call to v.load(QUrl("https://example.com"));. Instead, connect to the loadFinished(bool) signal and wait for it to be emitted. Even if you set some static HTML with no external references with v.setHtml(const QString&), you still have to wait for the loadFinished(bool) signal to be emitted.
set preferredContentsSize to a smaller value
If your page is smaller than 800x600, then you probably want to set the QWebPage::preferredContentsSize to something small before loading the new page. If you do not do that, the v.page().mainFrame().contentsSize() will always return 800x600. However, the page will not be rendered wider than the specified preferred width but it can be rendered higher/longer than the specified height.
You should decide on a QWebPage::preferredContentsSize before loading the first page. Prepare for heavy rendering bugs when passing a smaller size than the QWebView widget had before to QWebPage::setPreferredContentSize after a previous page has already been rendered. (I am using Qt 5.212.0)


text:
Q: I just saw this sentence on the internet there is a sentence below..

"no politician in history, and I say with surety, has been treated worse, more unfairly."

I don't understand this sentence grammatically
no politician and I together are the subject with plural form
so has must be changed to have.. IMO

A: Your sentence is

"no politician in history has been treated worse, more unfairly."

no politician is the subject

and I say with surety

is a subordinate clause emphasizing that the speaker is sure of the fact they are stating, and no one is more sure of themself than The Donald

A: I am not sure of the context, but if this is the quote, it is not at all grammatically correct.  Instead, it is very colloquial.
My guess is that this was written about a politician.  Perhaps Mr. Trump?
The person quoted is basically stating that that the politician, in the opinion of the speaker ("and I say with surety") has been treated very poorly  and unfairly.
Try not to take these types of quotes too literally.   This quote, in particular, is not at all proper English.


text:
Q: Reload jquery after ajax request I'm using ajax with jquery and after request the jquery stopped and can't edit or delete for example, how can I reload or reactive jquery after ajax request.
This code here:
$('.create-div').on('click', function(event){
    event.preventDefault();

    $.ajax({
        method:'POST',
        url: '.....',
        data: {.....},
    }).done(function(data) {
    // do something
    });

});

Can you places help.


text:
Q: JSch - Is there a way to connect to a SFTP server if it requires MFA, i am getting SocketTimeoutException I am able to connect to our SFTP server using WinScp(sftp client app) but before that i need to establish a session locally using MFA.
Now i am trying to achieve this programmatically using JSch but i am getting SocketTimeoutException
because i think it requires the same MFA setup to be done programmatically, if my understanding is correct then is there a way to achieve this using JSch ?
JSch jsch = new JSch();
Session session = jsch.getSession(userName, hostName, 22);
session.setPassword(password);
session.connect();

It throws exception at session.connect().

A: I am closing this question myself as there is no additional setup is required for this. From the machine on which this code is getting executed, if that machine has established the MFA session then it should work seamlessly and without making any other change.
It did not work for me earlier because my MFA session was expired.


text:
Q: Strategy for finding a missing mouse event in AS3 Will make this brief, I have a game map with units on it and had finalized a fully interactive minimap where the units on the minimap have event listeners for rollover/rollout (displays a small popup unit data summary) and click (selects the "real" unit on the main game map and scrolls the viewpoint to that location). All done, tested, working.
I then implement an interactive scrollable unit list with more status summary data and dozens of objects with rollover/rollout/click listeners. All tested and working fine.
Then I go back and look at my minimap, and the listeners on the mini-ships aren't working anymore. Things tried:

*

*Debug code to make sure listeners still being added

*Debug to watch the one place where I remove those listeners to make sure that ain't happening unexpectedly

*Debug to watch all the places I refresh that dialog to make sure every iteration adds the listeners back

*Can't see that there is any transparent object on top intercepting

*Checked mini-ship parents to make sure I didn't turn off mouseChildren or something like that somewhere

*No added stage-level listener, in fact I killed all of them temporarily to test this

What happens when I debug with a breakpoint on the mini-ship listener handler is nada. It's no longer receiving mouse events. So either something I haven't thought of has stopped them from listening or something I don't know of is intercepting.
So what is the strategy here? How can I find the break in the chain?

A: Well knowing what the actual problem was certainly gives us the advantage of hindsight... that being said, you could have detected the error by adding a trace call inside your function that adds the listener and another one inside your function that removes it. Then you would have seen that it isn't getting re-added. Or you could set break points there.


text:
Q: 2D drawing c++ for grid maze project I am building a c++ maze project for school and want to create a 2d graphics window in c++ that will let me render something like this http://www.dreamincode.net/forums/uploads/monthly_07_2011/post-114496-13104660729008.png.
Can anyone suggest a 2d graphics library to use? I have looked into openGL but am worried that the geometry necessary is too complicated for what I need. Of course I may be overlooking some things.
I am working in Xcode on OS X and if the library is not multiplatform that is okay. Can anyone suggest me something?

A: The Qt framework is a cross-platform solution for building applications.
There is a basic drawing example that shows how to use basic graphic primitives:

The core of the technique consists in reimplementing a widget's paintEvent() method to control how it is displayed (painted) on the screen. The QPainter class provides many drawing methods to suit your needs.

A: Since cross-platform is not a problem, just use Quartz or SpriteKit. Quartz is general 2D drawing, SpriteKit is specifically for games. All the docs you can access directly in Xcode through the documentation window, and Apple provides a bunch of sample code too.


text:
Q: Looking for a JSF/RichFaces control to popup an input field I need a text box like control.
When clicked on it pops up a small window or area where the user can see his previous text and update/edit his text.
I have a data table and what I'm trying to do is allow the user to edit the description,
but the description area is small so we won't fit everything.
So on click I'm trying to use a tool that pop up a small text window on the page that allows the user to add/update/delete
Any idea? Is there a such tool?

A: You can use a <rich:modalPanel> containing a <h:inputText> with its value bound to the text the user needs to edit/update.
When facing a similar requirement, I used the RichFaces.showModalPanel JS function on the oncomplete event of an `:
<a4j:commandButton actionListener="..."
    oncomplete="RichFaces.showModalPanel('myPopupPanel', {width: 500, top: 200});" />


text:
Q: Find automatically the index of a list item which is contained in a specific pandas column for each row I am trying to find automatically without using for the index of a list item which is contained in a specific pandas column per row.
Imagine that I have a list with names = ["U9", "Z9", "H10"] and a pandas dataframe with a column that contains the following
dat['col1'] = ["U9", "U9", "U9", "Z9", "Z9", "H10", "H10", "H10", "H10", "H10"]

I am trying to replace the first code with the second one which starts from mask however I have the following error.

for i in range(len(dat)):
    index = names.index(dat['col1'][i])
    if index < len(names)-1:
        dat.loc[i, 'col2'] = names[index + 1]
    else:
        break

mask = []

for i in range(len(dat)):
    mask.append(names.index(dat['col1'][i]) < len(names) - 1)

dat['col2'] = np.where(mask, names[names.index(dat['col1'])+1], np.NaN)

The error that I get is

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

This happens because names[names.index(dat['col1'])+1] is not iterating for each row in the dat['col1'].
So what I want is to iterate through rows in pandas without using the for which is mentioned below and assign to dat['col2'] the values of dat['col1'] but shifted. The expected result should be like
dat['col2'] = ["Z9", "Z9", "Z9", "H10", "H10", nan, nan, nan, nan, nan]

A: you can use series.map() after creating a dict from the list:
d={a:b for a,b in zip(names,names[1:])}
#{'U9': 'Z9', 'Z9': 'H10'}
dat['col2']=dat.col1.map(d)

0     Z9
1     Z9
2     Z9
3    H10
4    H10
5    NaN
6    NaN
7    NaN
8    NaN
9    NaN

Using get you can also get index vs values:
pd.Series(d).get(dat.col1)

col1
U9      Z9
U9      Z9
U9      Z9
Z9     H10
Z9     H10
H10    NaN
H10    NaN
H10    NaN
H10    NaN
H10    NaN


text:
Q: How to avoid Gutenberg crash after code upload? I have a question about Gutenberg Blocks: due to the Blocks structure, every time I update the render of my block, either on back- or front-end, the block crashes, because the data saved to the db are different from those of the updated block. Is there a workaround to this problem? Because if I use my block multiple times in my editor and in several posts as I plan to do, at the first update I should manually update all my posts and of course this would be nonsense.
Thanks

A: If you have already authored a block and are releasing a new version, its advisable to deprecate the older block version. If the old block content can be transitioned into the updated rendered content, provide a migrate function and/optionally a isEligible function to handle the transformation (see Block Deprecation in the Block Editor Handbook for examples). If you follow this path, you won't have to update all your posts that use your block - the update will be handled gracefully.
Alternatively, if you are doing active development/testing of a unreleased block where the output in edit() changes frequently, you could temporarily disable the save() function via:
save(){ return  null }

Once you have finalized content the edit() function renders, remember to update the save() function to match so no validation errors occur.
Also worth noting, if your blocks purpose is only saving meta values to the database then the save function should also return null.


text:
Q: How to inject a list of properties with name pattern or regular expression in Google Guice? Using Google Guice, we can inject from property files like this:
@Inject(optional = true)
@Named("api.server.ip")
private final String ip = "localhost";

So what if I have a property file like this:
api.server.ip.1=10.11.12.13
api.server.port.1=3000
api.server.path.1=/maps
api.server.ip.2=10.11.12.14
api.server.port.2=3001
api.server.path.2=/phones

The mission is the application needs to access to multiple servers to call requests, so is there any way to inject properties using pattern in Google Guice, or any recommendation to solve this issue? Thank you!!!

A: There is no out of the box solution coming from Google Guice but you can do something with TypeListener api.
Here is a piece of code which will inject fields annotated by my custom Property annotation -
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.MembersInjector;
import com.google.inject.TypeLiteral;
import com.google.inject.matcher.Matchers;
import com.google.inject.spi.TypeEncounter;
import com.google.inject.spi.TypeListener;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

public class PropertiesInjection {

    static class PropertiesModule extends AbstractModule {

        @Override
        protected void configure() {
            bindListener(Matchers.any(), new PropertiesTypeListener());
        }
    }

    static class PropertiesTypeListener implements TypeListener {

        public <T> void hear(TypeLiteral<T> typeLiteral, TypeEncounter<T> typeEncounter) {
            Class<?> clazz = typeLiteral.getRawType();
            while (clazz != null) {
                for (Field field : clazz.getDeclaredFields()) {
                    if (field.getType() == String.class && field.isAnnotationPresent(Property.class)) {
                        Property annotation = field.getAnnotation(Property.class);
                        typeEncounter.register(new PropertyInjector<T>(field, annotation.value()));
                    }
                }
                clazz = clazz.getSuperclass();
            }
        }
    }

    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.FIELD)
    @interface Property {
        String value();
    }

    static class PropertyInjector<T> implements MembersInjector<T> {

        private final Field field;
        private final String key;

        PropertyInjector(Field field, String key) {
            this.field = field;
            this.key = key;
        }

        @Override
        public void injectMembers(T instance) {
            try {
                field.set(instance, PropertiesFileDataProvider.getValue(key));
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
        }
    }

    static class PropertiesFileDataProvider {

        private static final Map<String, String> PROPERTIES = new HashMap<>();

        static {
            PROPERTIES.put("api.server.ip", "localhost"); //load it from properties file. I am putting dummy values just for an example.
        }

        static String getValue(String key) {
            return PROPERTIES.getOrDefault(key, key);
        }
    }

    static class TestData {
        @Property("api.server.ip")
        private String property;
    }

    public static void main(String[] args) {
        Injector injector = Guice.createInjector(new PropertiesModule());
        TestData instance = injector.getInstance(TestData.class);

        System.out.println(instance.property); //prints localhost
    }
}


text:
Q: css top attribute behaviour in Firefox and Chrome I have a problem related with the css 'top' attribute of a Foundation modal.
I have long list of anchors and when I click in each anchor, a modal is opened. I have the css top attibute set to 100px.
When I use Chrome, even if I am in the bottom of the list and I click in one of the last anchors, my modal appears always at 100px of the top of the screen, i.e at 6356px of the top of the body. However, using Firefox, when I click in one of these last anchors, my modal appears at 100px of the top of the body, so I have to scroll up to see the modal. What can I do to make Firefox behave like Chrome?


text:
Q: Circle not showing while using Canvas This is the code from a course in Udemy. I did not understand why circle is not showing up for me. The same code when used by the instructor produces a circle.
Rectangle works fine for me.

var canvas, canvasContext;
console.log("text from script");
window.onload = function() {
  canvas = document.getElementById('gameCanvas');
  canvasContext = canvas.getContext('2d');

  canvasContext.fillStyle = "red";
  canvasContext.fillRect(0, 0, canvas.width, canvas.height);

  // cavasContext.fillStyle="white";
  // canvasContext.beginPath();
  // canvasContext.arc(100,100,10,0,Math.PI*2,true);

  cavasContext.beginPath();
  cavasContext.arc(100, 75, 50, 0, 2 * Math.PI);
  cavasContext.stroke();
}
<canvas id="gameCanvas" width="800" height="600"></canvas>

A: There is a typo, you've spelled canvasContext wrong, missed a "n".
cavasContext.beginPath();
cavasContext.arc(100,75,50,0,2*Math.PI);
cavasContext.stroke();

Should probably be:
canvasContext.beginPath();
canvasContext.arc(100,75,50,0,2*Math.PI);
canvasContext.stroke();


text:
Q: Links with target="_blank" jquery-mobile require two clicks when viewed in safari view controller I have a jquery mobile web app that has links that look like this:
LINK TEXT

When users come to my site using Safari View Controller (that is, they're on an iphone or ipad but they're inside an app like Apple's News app, not running Safari on its own.) this link doesn't work at first. On the first click, nothing happens. On the second click it goes to its intended location.
How can I fix this? I want to do something like this:
if (((strstr($_SERVER['HTTP_USER_AGENT'],'iPhone')) ||
(strstr($_SERVER['HTTP_USER_AGENT'],'iPad')))
&&
(strstr($_SERVER['HTTP_USER_AGENT'],'Safari'))){
    //
}else{
    $blank='target="blank"';
}

and then just put $blank into the link:
<a href="EXTERNAL_URL" class="ui-btn" rel="external" <?=$blank?>>LINK TEXT

Is there a smarter way to do this?


text:
Q: Data from database is not fetched/displayed in listview flutter I have a screen which shows list of customers using listview. Next when I click on a customer I want to show the notes(records) only of that particular customer(customerId) in next screen in listview. This is my code which should work fine but its not displaying anything. I have checked if noteDetails table contains data and it has. Can anyone tell where am I wrong or what code should i add more please.
main.dart
import 'package:flutter/material.dart';
import 'package:vers2cts/screens/user_login.dart';

void main() {
  runApp(MyApp());
}
Map<int, Color> color ={50:Color.fromRGBO(170, 0, 95,  .1),
  100:Color.fromRGBO(170, 0, 95, .2),
  200:Color.fromRGBO(170, 0, 95, .3),
  300:Color.fromRGBO(170, 0, 95, .4),
  400:Color.fromRGBO(170, 0, 95, .5),
  500:Color.fromRGBO(170, 0, 95, .6),
  600:Color.fromRGBO(170, 0, 95, .7),
  700:Color.fromRGBO(170, 0, 95, .8),
  800:Color.fromRGBO(170, 0, 95, .9),
  900:Color.fromRGBO(170,0,95, 1),};
MaterialColor colorCustom = MaterialColor(0xFF880E4F, color);
class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'NoteKeeper',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
          primarySwatch:colorCustom,
          primaryColor:colorCustom//primarySwatch: Colors.purple
      ),
      home: UserLogin(),
    );
  }
}

Note_info.dart //This is the file where i want to display the notes of particular customer.
import 'dart:io';
import 'package:customer/models/CustomerNote.dart';
import 'package:customer/models/addCustomer.dart';
import 'package:customer/services/db_service.dart';
import 'package:customer/utils/database_helper.dart';
import 'package:flutter/material.dart';
import 'package:sqflite/sqflite.dart';
import 'New_Note.dart';

class Note_Info extends StatefulWidget{
  final String appBarTitle;
  final AddCustomer customer;

  Note_Info(this. customer, this.appBarTitle);
  @override
  State<StatefulWidget> createState() {
    return Note_InfoState(this. customer,this.appBarTitle);
  }

}

class Note_InfoState extends State<Note_Info> {
  DBService dbService = DBService();
  List<CustomerNote> noteList;
  int count = 0;

  static final GlobalKey<ScaffoldState> scaffoldKey = new GlobalKey<ScaffoldState>();
  CustomerNote note=CustomerNote();
  String appBarTitle;
  AddCustomer customer;
  Note_InfoState(this.customer, this.appBarTitle);

  DateTime _date = DateTime.now();
  TextEditingController custNameController = TextEditingController();

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    int customerId=customer.custId;
    if (noteList == null) {
      noteList = List<CustomerNote>();
      updateListView();
    }

    TextStyle titleStyle = Theme.of(context).textTheme.subhead;
    var height = MediaQuery.of(context).size.height;
    custNameController.text = customer.custName;

    return DefaultTabController(
        length: 4,
        child: Scaffold(
            appBar: AppBar(
              actions: [
                IconButton(
                  icon: Icon(
                    Icons.add,

                  ),
                  onPressed: () {
                    Navigator.of(context).push(MaterialPageRoute(
                        builder: (BuildContext context) => NewNote(note)));
                  },
                )
              ],
            ),
            body: Container(
              child: Column(
                  children: <Widget>[
                    TextField(controller: custNameController,
                        style: TextStyle(
                            fontSize: 20.0, fontWeight: FontWeight.bold),

                        textAlign: TextAlign.center),
                    Padding(
                      padding: const EdgeInsets.all(15.0),
                      child: Row(children: [
                        ImageProfile(customer.custPhoto),
                        Padding(
                          padding: const EdgeInsets.only(left: 30.0),
                          child: IconButton(
                            icon: Icon(
                              Icons.call,
                              color: Colors.green,
                              size: 45,
                            ),
                            onPressed: () {

                            },
                          ),
                        ),

                      ],),
                    ),

                    SizedBox(
                      height: 50,
                      child: AppBar(
                        bottom: TabBar(
                          tabs: [
                            Tab(
                              text: "All",
                            ),
                            Tab(
                              text: "Pending",
                            ),
                            Tab(
                              text: "Cancelled",
                            ),
                            Tab(
                              text: "Completed",

                            ),
                          ],
                        ),
                      ),
                    ),

                    // create widgets for each tab bar here
                    Expanded(
                      child: TabBarView(
                        children: [
                          // first tab bar view widget
                          Container(
                              child: getNoteListView()
                          ),

                          // second tab bar viiew widget
                          Container(

                          ),

                          Container(
                            child: Center(
                              child: Text(
                                'Cancelled',
                              ),
                            ),
                          ),
                          Container(

                            child: Center(
                              child: Text(
                                'Completed',
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                    Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Container(
                        height: 55.0,
                        width: 200,
                        child: RaisedButton(
                          elevation: 2,

                          shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(20)),
                          color: Theme
                              .of(context)
                              .primaryColorDark,
                          textColor: Colors.white,
                          child: Text('Save', textScaleFactor: 1.5,),
                          onPressed: () {
                            setState(() {
                              //_reset();
                            });
                          },
                        ),
                      ),
                    ),
                  ]
              ),
            )
        ));
  }

  Widget ImageProfile(String fileName) {
    return Center(
      child: CircleAvatar(
          radius: 80.0,
          backgroundImage:  fileName == null
              ?AssetImage('images/person_icon.jpg')
              :FileImage(File(customer.custPhoto))),

    );

  }

  ListView getNoteListView() {

    TextStyle titleStyle = Theme.of(context).textTheme.subhead;

    return ListView.builder(
      itemCount: count,
      itemBuilder: (BuildContext context, int position) {

        return Card(
          color: Colors.white,
          elevation: 2.0,
          child: ListTile(

            title: Text(this.noteList[position].note, style: titleStyle,),

            trailing: GestureDetector(
              child: Icon(Icons.delete, color: Colors.grey,),
              onTap: () {

              },
            ),
            onTap: () {

            },

          ),
        );
      },
    );
  }
  void updateListView() {
    final Future<Database> dbFuture = DB.init();
    dbFuture.then((database) {
      int cid=customer.custId;
      Future<List<CustomerNote>> noteListFuture = dbService.getCustomerNotes(cid);
      noteListFuture.then((noteList) {
        setState(() {
          this.noteList = noteList;
          this.count = noteList.length;
        });
      });
    });
  }

}

New_Note.dart  //This is where new note is added in database successfully
import 'package:customer/models/CustomerNote.dart';
import 'package:customer/models/addCustomer.dart';
import 'package:customer/screens/Note_info.dart';
import 'package:customer/services/db_service.dart';
import 'package:customer/utils/form_helper.dart';
import 'package:flutter/material.dart';
import 'package:flutter/painting.dart';
import 'package:table_calendar/table_calendar.dart';
import 'package:flutter_speed_dial/flutter_speed_dial.dart';
import 'package:smooth_star_rating/smooth_star_rating.dart';
import 'package:intl/intl.dart';

class NewNote extends StatefulWidget{
    final CustomerNote note;
    NewNote(this. note);

   final Function(Color) onChanged;
  final double height;
  final double width;

  NewNote({
    Key key,
    this.onChanged,
    this.height = 25,
    this.width = 150,
    this.label,
  }) : super(key: key);*/
  @override
  State<StatefulWidget> createState() {
    return New_NoteState(this.note);
  }

}
class New_NoteState extends State<NewNote> with SingleTickerProviderStateMixin{
  New_NoteState(this.note);
  CustomerNote note=new CustomerNote();
  AddCustomer customer=new AddCustomer();
  TextEditingController NoteController=TextEditingController();
  TextEditingController custNameController = TextEditingController();
  DateTime _reminderDate = DateTime.now();
DBService dbService=new DBService();

SpeedDial _speedDial(){
  return SpeedDial(
    animatedIcon: AnimatedIcons.add_event,

    animatedIconTheme: IconThemeData(size: 24.0),
    backgroundColor: Colors.yellow,
    curve: Curves.easeInCirc,
    children: [
      SpeedDialChild(
        child: Icon(Icons.location_on,color: Colors.yellow,),
        label: 'Add Location',
      ),
      SpeedDialChild(
          child: Icon(Icons.keyboard_voice),
          //backgroundColor: Colors.yellow,
          label: 'Add voice',
          //labelBackgroundColor: Colors.yellow

      ),
      SpeedDialChild(
          child: Icon(Icons.attachment_outlined,color :Colors.redAccent),
          label: 'Add File',
      ),
      SpeedDialChild(
          child: Icon(Icons.image,color: Colors.lightBlue,),
          label: 'Add Image',

      ),
    ],
  );
}

  //for DropDownMenu
  Color value=Colors.red;
  final List<Color> colors = [
    Colors.red,
    Colors.blue,
    Colors.green,
    Colors.yellow,
    Colors.pink,
    Colors.purple,
    Colors.brown,
  ];

  bool isSwitched = false;
  var textValue = 'Switch is OFF';

  void toggleSwitch(bool value) {

    if(isSwitched == false)
    {
      setState(() {
        isSwitched = true;
        this.note.remindOn = _reminderDate.toString();

      });
    }
    else
    {
      setState(() {
        isSwitched = false;
      });
    }
  }
  @override
  Widget build(BuildContext context) {
    var height = MediaQuery.of(context).size.height;
    var width = MediaQuery.of(context).size.width;
    custNameController.text = customer.custName;

    return WillPopScope(

      onWillPop: () {
        moveToLastScreen();
      },
child: Scaffold(
      appBar:AppBar(),
      body:ListView(
        children: <Widget>[
        SizedBox(
          height: 2.0,
        ),
          TextField(controller: custNameController,
              style: TextStyle(
                  fontSize: 20.0, fontWeight: FontWeight.bold),

              textAlign: TextAlign.center),
        Align(
      alignment: Alignment.centerLeft,
          child: Text("Add New",textAlign: TextAlign.left,
          style: TextStyle(fontSize: 22,fontWeight: FontWeight.bold),),
        ),

      SizedBox(
        height: 2.0,
      ),
      Divider(),
      SizedBox(
        height: 2.0,
      ),
      Padding(
        padding: const EdgeInsets.all(8.0),
        child: TextField(
          controller: NoteController,
          decoration: InputDecoration(
          border: OutlineInputBorder(
            borderSide: const BorderSide(width: 2.0),)),
          keyboardType: TextInputType.multiline,
          minLines: 5,
          maxLines: 5,
          onChanged: (value) {
            this.note.note = value;
          },

        ),
      ),
      TableCalendar(
        selectedDayPredicate: (day) {
          return isSameDay(_reminderDate, day);
        },
        onDaySelected: (selectedDay, focusedDay) {
          setState(() {
            _reminderDate = selectedDay;
          });
        },
              focusedDay: DateTime.now(),
              firstDay: DateTime.utc(2010, 10, 16),
              lastDay: DateTime.utc(2030, 3, 14),),

        SizedBox(
          height: height*0.03,
        ),
        Padding(
          padding: const EdgeInsets.all(10.0),
          child: Row(//mainAxisAlignment: MainAxisAlignment.start,
            children: <Widget>[
              Text("Remind me",style: TextStyle(fontSize: 20),),

            Padding(
              padding: const EdgeInsets.only(left:80.0),
              child: Container(
                child: Switch(
                    onChanged: toggleSwitch,
                    value: isSwitched,

              ),
            ),

          ],),
        ),
        Padding(
          padding: const EdgeInsets.all(10.0),
          child: Row(mainAxisAlignment: MainAxisAlignment.start,
            children:<Widget>[
              Text("Priority",style: TextStyle(fontSize: 20.0),),
             Padding(
               padding: const EdgeInsets.only(left:20.0),
               child: Container(
                 child: SmoothStarRating(
                  size: height=50.0,
                   allowHalfRating: false,
                   onRated: (value) {
                    this.note.priority=value;
                     print("rating value -> $value");

                   },
            ),
               ),
             )]),
        ),

        Padding(
          padding: const EdgeInsets.all(10.0),
          child: Row(mainAxisAlignment: MainAxisAlignment.start,
            children: <Widget>[

            Text("Color",style: TextStyle(fontSize: 20),),
            Padding(
              padding: const EdgeInsets.only(left:80.0),
              child: Container(
                child: DropdownButton<Color>(
                value: value,

                onChanged: (color) {
                  setState(() => value = color);

                },
                items: colors.map((e) => DropdownMenuItem(
                      value: e,
                      child: Container(
                       width: 60.0,
                        color: e,
                      ),
                  ),
                )
                      .toList(),
          ),
              ),
            ),

          ],),
        ),

          SizedBox(
          height: height*0.08,
        ),
        Padding(
          padding: const EdgeInsets.all(8.0),
          child: Container(
            height: 55.0,
            width: 200,
            child: RaisedButton(
              elevation: 2,

              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(20)),
              color: Theme.of(context).primaryColorDark,
              textColor: Colors.white,
              child: Text('Save',textScaleFactor: 1.5,),
              onPressed: (){
                setState(() {
                  _save();
                });
              },
            ),
          ),
        ),

      ],

    ),
 floatingActionButton:_speedDial(),
    ));

  }
  void moveToLastScreen() {
    Navigator.pop(context, true);
  }

  void _save() async {
    moveToLastScreen();
    note.custId=customer.custId;
    note.date = DateFormat.yMMMd().format(DateTime.now());
    int result;
    if (note.id != null) {  // Case 1: Update operation
      result = await dbService.updateNote(note);
    } else { // Case 2: Insert Operation
      result = await dbService.insertNote(note);
    }

    if (result != 0) {  // Success
      FormHelper.showAlertDialog(context,'Status', 'Note Saved Successfully');
    } else {  // Failure
      FormHelper.showAlertDialog(context,'Status', 'Problem Saving Note');
    }

  }
}

db_service.dart
 Future<bool> insertCustomer(AddCustomer model) async {
      await DB.init();
      bool isSaved = false;
      if (model != null) {
        int inserted = await DB.insert(AddCustomer.table, model);

        isSaved = inserted == 1 ? true : false;
      }

      return isSaved;
  }
Future<List<Map<String, dynamic>>> getCustomerMapList() async {
    await DB.init();
    var result = await DB.query(AddCustomer.table);
    return result;
  }

  Future<List<AddCustomer>> getCustomerList() async {

    var CustomerMapList = await getCustomerMapList();
    int count = CustomerMapList.length;

    List<AddCustomer> customerList = List<AddCustomer>();

    for (int i = 0; i < count; i++) {
      customerList.add(AddCustomer.fromMap(CustomerMapList[i]));
    }
    return customerList;
  }
 Future<int> insertNote(CustomerNote note) async {
    await DB.init();
    var result = await DB.insert(CustomerNote.table, note);
    return result;
  }

    Future<List<CustomerNote>> getCustomerNotes(int customer) async {
        await DB.init();
        var res = await DB.rawQuery("noteDetails WHERE custId = '$customer'");
        int count = res.length;
        List<CustomerNote> notelist = List<CustomerNote>();
        for (int i = 0; i < count; i++) {
          notelist.add(CustomerNote.fromMap(res[i]));
        }
        return notelist;
      }

database_helper.dart
import 'dart:async';
import 'package:customer/models/model.dart';
import 'package:path/path.dart' as p;
import 'package:sqflite/sqflite.dart';

abstract class DB {
  static Database _db;

  static int get _version => 1;

  static Future<Database> init() async {
    if (_db != null) {
      return _db;
    }

    try {
      var databasesPath = await getDatabasesPath();
      String _path = p.join(databasesPath, 'Customer.db');
      _db = await openDatabase(_path, version: _version, onCreate: onCreate);
      print('db location:'+_path);

    } catch (ex) {
      print(ex);
    }
  }

  static void onCreate(Database db, int version) async {
    await db.execute(
        'CREATE TABLE userDetails (id INTEGER PRIMARY KEY AUTOINCREMENT, '
            'firstName STRING, '
            'lastName STRING, mobileNum STRING, emailId STRING, address String,'
            'userType STRING,password STRING)');
    await db.execute(
        'CREATE TABLE customerDetails (custId INTEGER PRIMARY KEY AUTOINCREMENT, '
            'custName STRING, '
            'mobileNum STRING, company STRING, custPhoto STRING, showOnCall bool,'
            'remindOn STRING,location STRING)');
    await db.execute(
        'CREATE TABLE noteDetails (noteId INTEGER PRIMARY KEY AUTOINCREMENT, '
            'custId STRING, '
            'custName STRING, date STRING, note STRING, remindOn STRING,'
            'priority STRING,status STRING,attachment STRING)');
    await db.execute(
    'CREATE TABLE languagesKnown(custId INTEGER REFERENCES customerDetails(custId),'
        ' languages STRING,PRIMARY KEY(custId))');

    }

  static Future<List<Map<String, dynamic>>> query(String table) async =>
      _db.query(table);

  static Future<int> insert(String table, Model model) async =>
      await _db.insert(table, model.toMap());

  static Future<int> update(String table, Model model) async => await _db
      .update(table, model.toMap(), where: 'id = ?', whereArgs: [model.id]);

  static Future<int> delete(String table, Model model) async =>
      await _db.delete(table, where: 'id = ?', whereArgs: [model.id]);

  static Future<int> deleteCustomer(String table, Model model) async =>
      await _db.delete(table, where: 'custId = ?', whereArgs: [model.custId]);

  static Future<Batch> batch() async => _db.batch();

  static Future<List<Map<String, dynamic>>> rawQuery(String table) async =>
      _db.query(table);

}

people_list.dart // This is where list of customers is displayed and by clicking on a listtile i.e customer, Note_info opens
import 'package:customer/models/addCustomer.dart';
import 'package:customer/screens/Note_info.dart';
import 'package:customer/screens/User_Settings.dart';
import 'package:customer/screens/add_person.dart';
import 'package:customer/services/db_service.dart';
import 'package:customer/utils/database_helper.dart';
import 'package:customer/utils/form_helper.dart';
import 'package:flutter/material.dart';
import 'dart:io';
import 'package:sqflite/sqflite.dart';

class People_List extends StatefulWidget{

  @override
  State<StatefulWidget> createState() {
    return People_ListState();
  }

}

class People_ListState extends State<People_List> with SingleTickerProviderStateMixin{

  DBService dbService = DBService();
  List<AddCustomer> customerList;
  int count = 0;

  static final GlobalKey<ScaffoldState> scaffoldKey = new GlobalKey<ScaffoldState>();
  var _isSelectedItemIndex;

  @override
  void initState() {
    super.initState();
    _searchQuery = new TextEditingController();
  }

  Widget _buildTitle(BuildContext context) {
    var horizontalTitleAlignment =
    Platform.isIOS ? CrossAxisAlignment.center : CrossAxisAlignment.start;

    return new InkWell(
      onTap: () => scaffoldKey.currentState.openDrawer(),
      child: new Padding(
        padding: const EdgeInsets.symmetric(horizontal: 12.0),
        child: new Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: horizontalTitleAlignment,
          children: <Widget>[
            const Text(''),
          ],
        ),
      ),
    );
  }
  @override
  Widget build(BuildContext context) {
    var height = MediaQuery.of(context).size.height;
    var width = MediaQuery.of(context).size.width;
    if (customerList == null) {
      customerList = List<AddCustomer>();
      updateListView();
    }

    return Scaffold(
      appBar: new AppBar(

      ),
      body:getCustomerListView(),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          navigateToCustomer(AddCustomer(), 'Add Person');
        },

        child: const Icon(Icons.add),

      ),

  }

  ListView getCustomerListView() {

    TextStyle titleStyle = Theme.of(context).textTheme.subhead;

    return ListView.builder(
      itemCount: count,
      itemBuilder: (BuildContext context, int position) {
        var _imageFile=customerList[position].custPhoto;
        return Card(
          color: Colors.white,
          elevation: 2.0,
          child: ListTile(
            leading: CircleAvatar(
            backgroundImage: _imageFile==null?AssetImage('images/person_icon.jpg')
                :FileImage(File(_imageFile.toString()))),
            title: Text(this.customerList[position].custName, style: titleStyle,),
            trailing: Icon(Icons.keyboard_arrow_right),
            onTap: () {
              navigateToDetail(this.customerList[position],'Edit ');
            },

          ),
        );
      },
    );
  }

  void navigateToDetail(AddCustomer customer, String title) async {
    bool result = await Navigator.push(context, MaterialPageRoute(builder: (context) {
     return Note_Info(customer, title);
    }));

    if (result == true) {
      updateListView();
    }
  }

  void updateListView() {
    final Future<Database> dbFuture = DB.init();
    dbFuture.then((database) {

      Future<List<AddCustomer>> customerListFuture = dbService.getCustomerList();
      customerListFuture.then((customerList) {
        setState(() {
          this.customerList = customerList;
          this.count = customerList.length;
        });
      });
    });
  }

}

A: Finally I myself had to solve the problem. The problem was that where I was creating note and saving it in "note" table cust_id was not saved in the table. So I passed CustomerModel object and NoteModel object to New_Note(). Now its working fine
new_note.dart
 class NewNote extends StatefulWidget{
      final NoteModel note;
      final CustomerModel customer;

      NewNote(this.customer,this. note);

      @override
      State<StatefulWidget> createState() {
        //return New_NoteState(this.customer);
        return New_NoteState(this.customer,this.note);
      }
class New_NoteState extends State<NewNote> with SingleTickerProviderStateMixin{
  New_NoteState(this.customer,this.note);
  NoteModel note=new NoteModel();
  CustomerModel customer=new CustomerModel();
}
void _save() async {
    note.cust_id=customer.cust_id;
...
}


text:
Q: Estimators for Bernoulli trials I have failure data for an experience over  $T$  years: at the beginning of each year I have $n_t$ subjects and $d_t$ of these subjects experience a "failure" at the end of the year.
Now if I assume that the trials are iid Binomial and the probability of failure $p$ is homogenous (i.e. constant over time), the ML estimator is given by
$$\hat{p}=\frac{\sum\limits_{i=1}^T d_t}{\sum\limits_{i=1}^T n_t}$$
However, there is an alternate estimator:
$$\bar{p}=\frac{1}{T}\sum\limits_{i=1}^T \frac{d_t}{n_t}.$$
What would be the assumptions and the model so that the estimate is $\bar{p}$?
===========================
EDIT:
The question is not about the relative merits of the two estimators. For example, it is not necessary to assume homogeneity for the second estimator. I am wondering about the assumptions that would "naturally" lead to the second estimator.
===========================
EDIT2:
I am in a situation where $\bar{p}$ is imposed as an estimator. I need to come up with confidence intervals or credible intervals for the estimate. My idea was to determine the assumptions (possibly a hierarchical model) and do a MCMC using JAGS...

A: Your model for estimator $\hat{p}$ is actually of a single system that was operated $n_i$ times in year $i$, $1 \leq i \leq T$, and failed $d_i$ times that year. Presumably the system was successfully repaired and restored to perfect working
condition before the next time it was operated.
Your model for estimator $\bar{p}$ is that of $n_i$ independent
copies of Model $i$ of
the system being put in operation in year $i$ and $d_i$ of those copies
failing independently.  You wish to estimate the average failure rate
per year over $T$ years.

A: I believe both can be considered as estimators of $p$ for the same model under different 'estimating equations'. It $appears$ to me that both estimators have the same mean (see the discussion below). Therefore, I don't think biasedness is a useful criteria to pick one. Let me define $N:=\sum_{t=1}^T n_t$, then
$$\hat p = \sum_{t=1}^T \frac{d_t}{N} =\sum_{t=1}^T \frac{n_t}{N}\frac{d_t}{n_t} .$$
Therefore, if $n_t$ does not change much over time, $\frac{n_t}{N} \approx \frac{1}{T}$, the estimators will be very similar. But if this values are different, they will differ of course. Check the following R code for an illustration.
ss = c(10,50)
e1 = function(x) return(sum(x)/sum(ss))
e2 = function(x) return(mean(x/ss))
e1v = e2v = rep(0,100)
for(j in 1:100){
    x = rbinom(length(ss), size = ss, 0.5)
    e1v[j] = e1(x)
    e2v[j] = e2(x)
}
plot(e1v-e2v,type='l',col='red')
plot(e1v,type='l',col='red',ylim=c(0.2,0.8))
points(e2v,type='l',col='blue')

Second code
ss = seq(10,20,1)
e1 = function(x) return(sum(x)/sum(ss))
e2 = function(x) return(mean(x/ss))
e1v = e2v = rep(0,10000)
for(j in 1:10000){
x = rbinom(length(ss), size = ss, 0.5)
e1v[j] = e1(x)
e2v[j] = e2(x)
}

c(quantile(e1v,0.025),quantile(e1v,0.975))
 hist(e1v)

 c(quantile(e2v,0.025),quantile(e2v,0.975))
 hist(e2v)


text:
Q: MS-DOS 8.0: Determine String Length? Using MS-DOS 8.0, what is the best way to determine the length of a string?
I looked through Computer Hope (http://www.computerhope.com/msdos.htm), but no commands jumped out at me...
Is there a built in command or must a function be built to address this?
Thanks a ton.

A: From here I got and example and this is it cleaned up a litte
@echo off
setlocal
set #=%1
set length=0
:loop
if defined # (set #=%#:~1%&set /A length += 1&goto loop)
echo %1 is %length% characters long!
endlocal

A: Here's another option. Pass the string as a paramter like this:
   LEN "this is a long string"

Here's the code:
   @echo off

   echo.%~1>len
   for %%a in (len) do set /a len=%%~za -2

   echo %len%

Copy and paste the code into Notepad and save it as LEN.BAT.
NOTE: The fullstop following the ECHO statement is vital should a NUL string be entered. The -2 is required because ECHO automatically adds a CR & LF at the end of each line.

A: I regularly use the following method:
   @echo off
   set str=This is a line of text

   echo.%str%>len
   for %%a in (len) do set /a len=%%~za -2

   echo %len%


text:
Q: Why can't I use a map's value without having to use a temporary variable? Ok so this is my scenario:
rascal>map[int, list[int]] g = ();
rascal>g += (1:[2]);

This will result in:
rascal>g[1];
list[int]: [2]

So far so good, but now I wanted to do this, but it didn't work:
rascal>g[1] += 3;
|stdin:///|(2,1,<1,2>,<1,3>): insert into collection not supported on value and int

So I can't directly use the value from g[1] and will have to use a temporary variable like this:
rascal>lst = g[1];
rascal>lst += 3;
rascal>g[1] = lst;
map[int, list[int]]: (1:[2,3])

But doing this everytime I want to extent my list is a drag!
Am I doing something wrong or would this be an awesome feature?
Richard

A: Good question! + on lists is concatenation not insert, so you could type the following to get the desired effect:
g[1] += [2];


text:
Q: Including images by file path in lyx I am trying to include an image by path into a lyx document. My latex code is the following:
\begin{figure}
\graphicspath{{C:\Paper\images\}}
\centering\includegraphics[scale=0.1]{imageName}\caption{This is an image}
\end{figure}

but I get the error:
Paragraph ended before \graphicspath was complete

How can I set the path? Is it possible to set it once in the preamble?

A: I think your problem is the \. You should use / in the path like discussed in the following answer:
How to use \graphicspath?
There is also a more general path description provided.
Your path should look like:
\graphicspath{{C:/Paper/images/}}


text:
Q: Why is "I'm on Team X" correct? I'm a non-native English speaker and I've heard the expression "I'm on Team X" (and not "I'm on X's team") for quite a while now (the first time I heard it was when the Twilight novels were published, where Team Edward and Team Jacob was used to show preference for one of the characters)
An also non-native friend asked me why that was correct and couldn't come up with anything better that "it's just how they speak". It only appears to be valid with the word "team". If you are asked if you prefer white or black shoes, you wouldn't reply "shoes white all the way!".
My question is why "I'm in team X" is used and not "I'm on X's team"?

A: I think is because Edward is not the owner of the Team. Team Edward is the name of the team so you say I'm in Team Edward.
But if the team has a captain, for example, Maria is the captain of one team and you're in that team. The you can say I'm on Maria's team, because Maria is the owner of the team.


text:
Q: glfwGetWindowSize results in SIGSEGV (LWJGL) I'm trying to get into Vulkan with LWJGL.
Currently I'm creating some sort of window (wrapper) class, however whenever i try to invoke glfwGetWindowSize, glfwGetWindowPos or glfwGetMonitorPos the program crashes with a segmentation fault. The window creation itself works fine though, and i can also move the window programatically. I use default window hints (glfwDefaultWindowHints).
The code:
var wbuf = IntBuffer.allocate(1);
var hbuf = IntBuffer.allocate(1);
glfwGetWindowSize(this.handle, wbuf, hbuf);
this.width = wbuf.get();
this.height = hbuf.get();

# A fatal error has been detected by the Java Runtime Environment:
#
#  SIGSEGV (0xb) at pc=0x00007f29938156b5, pid=13791, tid=13797
#
# JRE version: OpenJDK Runtime Environment Temurin-17.0.5+8 (17.0.5+8) (build 17.0.5+8)
# Java VM: OpenJDK 64-Bit Server VM Temurin-17.0.5+8 (17.0.5+8, mixed mode, sharing, tiered, compressed oops, compressed class ptrs, g1 gc, linux-amd64)
# Problematic frame:
# C  [libglfw.so+0x156b5]  glfwGetWindowSize+0x5

Environment: LWJGL v3.3.1 (with GLFW linux natives), Vulkan SDK v1.3.236.0 x86_64, Java 17 (Temurin), Fedora 36
As a side note: I'm also applying class loader tweaks before the GLFW init.

A: I was using non-direct buffers, while the LWJGL GLFW bidings only support direct ones.
Using direct buffers works fine:
try (var stack = MemoryStack.stackPush()) {
    var width = stack.mallocInt(1);
    var height = stack.mallocInt(1);
    glfwGetWindowSize(this.handle, width, height);
    this.width = width.get();
    this.height = height.get();
}

MemoryUtil.memAllocInt(1) and ByteBuffer.allocateDirect(4).asIntBuffer() works as well.


text:
Q: Holomorphic primitive of several complex variables function Let $f:\Omega\subset\mathbb{C}^n\rightarrow\mathbb{C}$ a holomorphic function. For any $m\leq n$ I would like to find an $m-primitive$ of $f$, which is still holomorphic in each variable.
If we assume that for any $z=(z_1,...,z_n)\in\Omega$, the set $\Omega^m(z):=\{w\in\mathbb{C}\mid (z_1,...,z_{m-1},w,z_{m+1},...,z_n\in\Omega\}$ is simply connected, we could define
$$F^m(z):=\int_\gamma f(z_1,...,z_{m-1},w,z_{m+1},...,z_n)dw,
$$
where $\gamma$ is any path from a chosen $z^0\in\Omega$, with $z_m^0=z_m$ to $z$ entirely contained in $\Omega^m(z)$.
It is easy to see that $F^m$ is a $m-$primitive of $f$. But, what about the other variables? Is $F^m$ still holomorphic w.r.t. $z_i$, for $i=1,...,n$?

A: If $\Omega\subset \mathbb{C}^n$, and $f:\Omega \rightarrow \mathbb{C}$ is a let's say a smooth function, then you can look at $f$ as a function of $2n$ variables mapping to $\mathbb{R}^2$. First suppose that $n=1$, then it is a classical theorem of complex calculus that $f:\Omega \rightarrow \mathbb{C}$ is holomorphic, if and only it satisfies the Cauchy-Riemann equations, i.e. if $f(x,y)=(f_1(x,y),f_2(x,y))$, then $\partial_{x}f_1=\partial_y f_2$, and $\partial_{y}f_1=-\partial{x}f_2$. (Satisfiyng the Cauchy-Riemann equation means that the tangent map of $f$ in the basis $\partial_x$ and $\partial_y$ is a Complex linear map.) Now we can encode this system in one clever equation. Let $\partial_{\overline{z}}=1/2(\partial_x+i\partial_y)$. This operator acts on complex valued function as follows, if $f(x,y)=f_1(x,y)+f_2(x,y)$, then $$\partial_{\overline{z}}f(x,y)=1/2(\partial_xf_1(x,y)-\partial_yf_2(x,y)+i(\partial_xf_2(x,y)+\partial_yf_1(x,y)).$$
It follows that $f$ satisfies the Cauchy-Riemann eqations if and only if $\partial_{\overline{z}}f=0$. Now suppose that $n>1$, and suppose that $z_j=x_j+iy_j$, then we can define the operators $\partial_{z_j}=1/2(\partial_{x_j}+i\partial_{y_j})$, and this acts on complex valued functions just like before. Now we see, that a function $f$ is partially homolorphic, if and only if $\partial_{\overline{z}_j}f=0$ for all $j$. One can show using Cauchy's integral formula, that a smooth function is holomorphic if and only if it is partially holomorphic. Now getting back to your question, you only have to check that $\partial_{\overline{z}_j}F^m(Z)=0$, for all $j$, and this follows from the fact that $f$ is smooth , so you can swap the derivation and integration. (For the variable $m$ to show that $\partial_{\overline{z}_m}F^m(z)=0$ you just have to copy the proof of the one variable case when we make the primitive function.)


text:
Q: DB2 ODBC C++ call procedure and get back the value In my DB2 database I have a procedure with name get_mood. The first parameter is IN Integer, the second is OUT varchar(50).
With that code I try to get back the value:
    SQLHANDLE hstmt;
    SQLAllocHandle(SQL_HANDLE_STMT, hdbc, &hstmt);
    char *value = new char();
    SQLINTEGER length = 0;
    strcpy(stmt, "call get_mood(2201, ?)";
    SQLRETURN cliRC = SQLPrepare(hstmt, (SQLCHAR*)stmt, SQL_NTS);
    SQLSMALLINT cbParm1 = SQL_NTS;
    cliRC = SQLBindParameter(hstmt,
                       1,
                       SQL_PARAM_OUTPUT,
                       SQL_C_CHAR,
                       SQL_VARCHAR,
                       SQL_MAX_CHAR_LITERAL_LEN,
                       SQL_MAX_CHAR_LITERAL_LEN,
                       &value,
                       length,
                       NULL);
    cliRC = SQLExecute(hstmt);
    if (cliRC == SQL_NO_DATA_FOUND) {
        std::cout << "no data" << std::endl;
    }
    SQLFreeHandle(SQL_HANDLE_STMT, hstmt);
    std::cout << std::string(reinterpret_cast<const char*>(value)) << std::endl;

When I try the call in IBM Data Studio, I get a value. But here it is empty. What I made wrong?


text:
Q: Como verifico se duas strings são anagramas uma da outra? Preciso comprar duas strings e verificar se a segunda é um anagrama da primeira. Pensei em usar laços de repetição FOR. Creio que deva primeiramente verificar se ambas têm o mesmo tamanho, depois percorrê-las e ir verificando se cada letra da primeira existe também na segunda. Caso todas existam, uma é anagrama da outra. Só não sei como fazer isso...
public static void main(String[] args) {
        Scanner ent = new Scanner(System.in);
        String s, r;
        int i, j;
        System.out.println("Digite a palavra/frase:");
        // crio as strings
        s = ent.nextLine();
        r = ent.nextLine();
        // verifico se têm o mesmo tamanho
        if (s.length()==r.length()) {
            // percorro ambas verificando se cada letra da 1ª existe na 2ª
            for (i=0; i<s.length(); i++) {
                for (j=0; j<r.length(); j++) {
                // não sei continuar...
                }
            }
        }
    }

A: Penso em três formas de fazer isso.
A primeira forma é contar a frequência de cada caractere para cada String e então comparar as frequências.
A segunda forma é ordenar as letras de ambas as Strings e ver se o resultado coincide.
A terceira forma é usar funções do Java já prontas para isso:
    s = ent.nextLine();
    r = ent.nextLine();
    char[] a = s.toCharArray();
    char[] b = r.toCharArray();
    Arrays.sort(a);
    Arrays.sort(b);
    if (Arrays.equals(a, b)) {
        System.out.println("Anagrama");
    } else {
        System.out.println("Não é anagrama");
    }

A: Achei essa resposta no SO que é o que você precisa:
public static boolean isAnagram(String s1, String s2) {
    //se as duas strings não tem o mesmo tamanho, não é anagrama
    if ( s1.length() != s2.length() ) {
        return false;
    }
    //tranfroma em arrays para poder ordenar
    char[] c1 = s1.toCharArray();
    char[] c2 = s2.toCharArray();
    //ordena para garantir a comparação simplificada
    Arrays.sort(c1);
    Arrays.sort(c2);
    //cria as novas strings baseadas nos arrays ordenados
    String sc1 = new String(c1);
    String sc2 = new String(c2);
    return sc1.equals(sc2);
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.


text:
Q: Overloading operator ++ Class declaration:
class unaryOperators
{
    public:
        int i;

        unaryOperators (int tempI = 0)
        {
            i = tempI;
        }

        unaryOperators operator++ (int);
        unaryOperators operator++ ();
};

Does this global definition correspond to postfix or prefix version of the overloaded operator++? Why?
unaryOperators operator++ (unaryOperators &one)
{
    return one;
}

A: unaryOperators& operator++ (unaryOperators &one)
              ^^

is the non-member prefix unary increment operator.
The non-member postfix unary increment operator takes an additional int as an policy enforcing parameter.
unaryOperators operator++ (unaryOperators &one, int)

Reference:
C++03 Standard 13.5.7 Increment and decrement [over.inc]

The user-defined function called operator++ implements the prefix and postfix ++ operator. If this function is a member function with no parameters, or a non-member function with one parameter of class or enumeration type, it defines the prefix increment operator ++ for objects of that type. If the function is a member function with one parameter (which shall be of type int) or a non-member function with two parameters (the second of which shall be of type int), it defines the postfix increment operator ++ for objects of that type. When the postfix increment is called as a result of using the ++ operator, the int argument will have value zero.125)

[Example:
class X {
   public:
      X& operator++(); // prefix ++a
      X operator++(int); // postfix a++
};
class Y { };
Y& operator++(Y&); // prefix ++b
Y operator++(Y&, int); // postfix b++

void f(X a, Y b) {
++a; // a.operator++();
a++; // a.operator++(0);
++b; // operator++(b);
b++; // operator++(b, 0);
a.operator++(); // explicit call: like ++a;
a.operator++(0); // explicit call: like a++;
operator++(b); //explicit call: like ++b;
operator++(b, 0); // explicit call: like b++;
}
—end example]

A: I think this will help you.

A: Every operator (that can be overloaded as a free function) takes one more argument when overloaded as a free function. The first argument corresponds to *this when overloaded as a member function.
bool AsMember::operator!() const;
bool operator!(const AsFreeFunction&);

bool AsMember::operator==(const AsMember& rhv) const;
bool operator==(const AsFreeFunction& lhv, const AsFreeFunction& rhv);

etc.

Increment operator is no exception to this.

A: Global overloaded operator++ functions expect the explicit specification of all the arguments, so if the overloaded operator ++ is postfix, we are supposed to add one default int argument (to distinguish postfix version from prefix) in addition to the prerequisite one (which determines the type on which the function needs to be applied).
unaryOperators operator++ (unaryOperators &one, int dummy)
{
    return one;
}

In the case of prefix global overloaded operator++ functions, the only argument we need to specify is the prerequisite one (which determines the type on which the function needs to be applied).
unaryOperators operator++ (unaryOperators &one)
{
    return one;
}

A: The free function is prefix as it lacks an int parameter.
Helpful guide for operator signatures.

A: The canonical version of preincrement is:
T &operator++(T &)

That is, return the operand by reference. Postincrement takes an unused int, so the global operator++ you defined is the preincrement operator.


text:
Q: Matching cardinality of varargs when passing parameters A simple function that accepts a File and a function that will be passed a PrintWriter for that file:
def printToFile(f: java.io.File)(op: java.io.PrintWriter => Unit) {
  val p = new java.io.PrintWriter(f)
  try { op(p) } finally { p.close() }
}

How to generalise this to any number of Files, while just passing the resulting PrintWriters to one function? I want to make the decision as to which PrintWriter to use in the client function.
I want a signature similar to (psuedocode):
def printToFile(f: java.io.File*)(op: (java.io.PrintWriter*) => Unit)

Here's how I'd like to write my client function:
printToFile(new File("file1.txt"), new File("file2.txt"), new File("file3.txt")) {
    (file1PrintWriter, file2PrintWriter, file3PrintWriter) =>
        // do stuff, decide which PrintWriter to write to
}

Where the cardinality of both *ed types are the same.
Importantly, I want the client function to be able to declare the PrintWriter variables it receives and not just have a Seq[PrintWriter] or similar to deal with.

A: I looks like you need to create as many PrintWriter instances as the number of arguments. The following should work.
import java.io._

object Foo {
  def printToFile(files: File*)(op: (PrintWriter*) => Unit) {
    val printers: Seq[PrintWriter] = files.map(file => new PrintWriter(file))

    try {
      op(printers :_*)
    } finally {
      printers.foreach(_.close)
    }
  }
}


text:
Q: Vuejs select option submits the form I am using vuesax 4 and I have select options in my form but each time I select an option it submits my form! how to prevent that of happening?
Code
HTML
<form
    class="mt-2"
    ref="form"
    :model="form"
    enctype="multipart/form-data"
>
    <vs-select
        :key="tags.length"
        filter
        :label="$t('posts.tags')"
        v-model="form.tags"
        multiple
    >
        <vs-option
        v-for="tag in tags"
        :key="tag.id"
        :label="tag.name"
        :value="tag.id"
        >
        {{ tag.name }}
        </vs-option>
    </vs-select>

    <vs-button @click="onSubmit" native-type="submit" gradient>
        {{ $t("posts.save") }}
    </vs-button>
</form>

SCRIPT
data() {
    return {
      categories: [],
      tags: [],
      form: {
        name: "",
        slug: "",
        image: "",
        icon: "",
        body: "",
        online: "",
        template: "",
        quote: "",
        video: "",
        tags: [],
        categories: [],
        metaTags: [],
        metaDescription: "",
      },
    };
},
mounted() {
   this.fetchTags();
},
methods: {
    fetchTags() {
      axios
        .get("/api/admin/tags", {
          headers: {
            Authorization: localStorage.getItem("access_token"),
          },
        })
        .then((response) => {
          this.tags = response.data.data;
        })
        .catch(function (error) {
          console.log("error", error);
        });
    },
    onSubmit(e) {
        e.preventDefault();

        let formData = new FormData();
        formData.append("name", this.form.name);
        formData.append("slug", this.form.slug);
        formData.append("image", this.form.image);
        formData.append("icon", this.form.icon);
        formData.append("body", this.form.body);
        formData.append("online", this.form.online);
        formData.append("template", this.form.template);
        formData.append("quote", this.form.quote);
        formData.append("video", this.form.video);
        formData.append("tags", this.form.tags);
        formData.append("categories", this.form.categories);
        formData.append("metas", this.form.metaTags);
        formData.append("metas", this.form.metaDescription);

        axios
        .post("/api/admin/posts/add", formData, {
        headers: {
            Authorization: localStorage.getItem("access_token"),
        },
        })
        .then((res) => {
        this.$router.push({ name: "adminPosts" });

        this.form = {
            name: "",
            slug: "",
            image: "",
            icon: "",
            body: "",
            online: "",
            template: "",
            quote: "",
            video: "",
            tags: [],
            categories: [],
            metaTags: [],
            metaDescription: "",
        };

        const noti = this.$vs.notification({
            position: "top-right",
            color: "success",
            icon: "",
            title: "Done!",
            text: res.data.message,
        });
        })
        .catch((error) => {
            var errors = error.response.data;
            let errorsHtml = "
";
            $.each(errors.errors, function (k, v) {
                errorsHtml += "
" + v + "
";
            });
            errorsHtml += "
";
            const noti = this.$vs.notification({
                position: "top-right",
                color: "danger",
                icon: "",
                title: "Oops!",
                text: errorsHtml,
            });
        });
    },
}

Any idea?

A: In the Vuesax 4 <vs-select> docs, there is no <form> tag and perhaps you shouldn't have one either. (In a SPA, you don't typically submit the form using the browser's built in form handling anyway, and you are not using it like that either, nor the ref or the model.)
If you still want to continue using the <form> tag, you can use the @submit.prevent modifier:
<form
    class="mt-2"
    ref="form"
    :model="form"
    enctype="multipart/form-data"
    @submit.prevent
>


text:
Q: Convert form with dynamic element to support back button history I have a form.  For simplicity, let's say there's a list and you can pick from the list and press Add, which appends the item in the list into an HTML element with hidden <input> elements so the values submit.  jQuery works fine for htat,
When I submit the form, fine. However, using the back button reverts the page to the initial page state.
I've read a number of posts on SO (https://stackoverflow.com/questions/116446/what-is-the-best-back-button-jquery-plugin and more) and they all seem to deal with elements hiding/showing, like tabs on a page.
I started installing this history plugin (http://balupton.com/sandbox/jquery-history/demo/) but it seemed like I was going to hook into every form change and save the values myself. Or, they're trying to save the state off server-side and reload it when the back button is pressed.
Is there a way to just set a history savepoint?  I'm really only worried about history; deep linking and bookmarking don't matter for this project.
If not, any generic way to handle the form?  If I'm making this too hard, let me know. It sure seems like it should Just Work.


text:
Q: Get Incorrect test coverage during Vue.js unit test I'm trying Vuejs unit test using karma+mocha+chai+webpack and get code coverage with istanbul.
Here's the issue, when I import some utils function or some other component in my component to be tested, the code coverage I got will include those utils code.This is not what I want.
In the component I want to test :
// src/home/mod_setting/upgrade_management/common/uploader.vue

import FileUploader from 'src/components/file_upload/index';
import Uploader from './uploader';
import logger from 'src/util/logger';

The coverage report will include these files.

Is there a solution ?

A: This should be possible by affecting the 'preprocessor' entry in your karma conf : only files matching this will be monitored for coverage.
See following issue > https://github.com/karma-runner/karma-coverage/issues/13
In your case something like
preprocessor: { 'src/!(util)/**/*.js' : 'coverage' }

should do the trick


text:
Q: JsonPatch to preserve naming of properties (camel-cased) I am using Microsoft.AspNetCore.JsonPatch which I've added via NuGet from here and got stuck when trying to match my properties back on API-side.
Is there any way to preserve the camel-case naming of my properties when serializing/deserializing.
My simplified object:
public class MyObject
{
    public string MyCamelCaseProperty { get; set; }
}

When creating a JsonPatchDocument<MyObject> with the operation Replace I get the path /mycamelcaseproperty. But, on API-side I want to make some sort of switch-case by the path property (without the leading '/') like
var normalizedPath = operation.path.Replace("/", string.Empty)
switch(normalizedPath)
{
    case nameof(MyObject.MyCamelCaseProperty):
        // do replacement of the MyCamelCaseProperty property
        break;
}

The question is: Can the camel-case be preserved or do I have to find another way on how to match the property-names I have to do actions on?
Any ideas would be greatly appreciated.


text:
Q: iAd banner is not showing in iPad mini with iOS 9.2 I am working with iAd. The ad banner is not showing in iPad mini with iOS 9.2, but it is working fine on all other devices, including iPad.
I checked the iPad setting that the developer ad rate is 100%.
My app is a universal app.
How to solve this issue?
And one another in iPhone 5s iAd banner change color.
- (void)createAdBannerView {
    Class classAdBannerView = NSClassFromString(@"ADBannerView");
    if (classAdBannerView != nil) {
        self.adBannerView = [[classAdBannerView alloc] initWithFrame:CGRectZero];
        self.adBannerView.tag = 200;
        [_adBannerView setFrame:CGRectOffset([_adBannerView frame], 0,-[self getBannerHeight])];
        [_adBannerView setDelegate:self];
          [_adBannerView setAutoresizingMask:UIViewAutoresizingFlexibleWidth ];
        [_adBannerView setBackgroundColor:[UIColor clearColor]]
          [_contentView addSubview:_adBannerView];
    }
}

- (void)bannerViewDidLoadAd:(ADBannerView *)banner {
    if (!_adBannerViewIsVisible) {
        _adBannerViewIsVisible = YES;
        [self fixupAdView:[UIDevice currentDevice].orientation:YES];
    }
}

- (void)bannerView:(ADBannerView *)banner didFailToReceiveAdWithError:(NSError *)error
{
    if (_adBannerViewIsVisible)
    {
        _adBannerViewIsVisible = NO;
        [self fixupAdView:[UIDevice currentDevice].orientation:YES];
    }
}
- (BOOL)bannerViewActionShouldBegin:(ADBannerView *)banner willLeaveApplication:(BOOL)willLeave
{
    return YES;
}

- (void)bannerViewActionDidFinish:(ADBannerView *)banner
{
    NSLog(@"%s",__PRETTY_FUNCTION__);
}


text:
Q: How can I calculate the shortest distance from a point to a line(Route) joining two other points Suppose my route is defined by going NC to UTAH and my third point is somewhere in Michigan, how can I calculate the shortest distance from Michigan to the nearest point on the straight line joining NC and UTAH? the distance that is shown by the black line
How can I calculate the shortest distance from a point to a line(Route) joining two other points.? All of the points are given in terms of latitude and longitude.


text:
Q: how to connect data from a drop down list to data from a input text in javascript Say I have this problem using forms
<form name = "card">
    Your Card's Number: <input type="text" placeholder="XXXX XXXX XXXX XXXX" onfocus="this.placeholder = ''" onblur="this.placeholder = 'XXXX XXXX XXXX XXXX'" id = "card_num"/></br>
</form>

    Type of Credit Card:
    <select id = "typeCard">
    <option value="none" selected="selected">-- choose one --</option>
    <option>Visa</option>
    <option>Master</option>
    <option>JCB</option>
    </select>
    <input type = "button" value = "Validate" onclick = "validateCard()">

this is my html code i want to get the value of the credit card number in order to validate it using javascript
    function validateCard()
{

    var card = document.getElementById("typeCard").value;
    var cardNum = document.getElementById("card_num").value;
    document.write(cardNum);

    if (card === "Visa")
    {
        alert("hey");
    }

    else if (card ==="Master")
    {
        alert("hoy");
    }

    else if (card ==="JBC")
    {
        alert("hoy");
    }
}

this is my javascript code it doesn't work with the
var cardNum = document.getElementById("card_num").value;
    document.write(cardNum);

code, can anyone help me I've googled it, but I can't have any solutions.

A: Where does your script come from? It may not loaded at the point you are binding click event handler. So you better use
document.getElementById('validateBtn').addEventListener('click', validateCard, null);

in the code. Also don't use document.write. I have created working demo.

A: I wish .value worked normally on selects :P
Try this:
var card = document.getElementById("typeCard").options[document.getElementById("typeCard").selectedIndex].value;


text:
Q: Delete all records by user id laravel I want to delete all records corresponding to user id here is my query
DB::table('permissions')->find($data['user_id'])->delete();

A: if you use find method it will delete only one row,for delete all records you need to use where method like
DB::table('permissions')->where('user_id', $data['user_id'])->delete();

A: $rows = DB::table('permissions')->find($data['user_id']);
$rows->delete();


text:
Q: Whose responsibility to enforce threading in RxJava/RxAndroid, caller's or callee's In RxJava/RxAndroid, you often need to enforce the threading especially when doing network operations, for example:
Single.fromCallable(/*download*/)
      .subscribeOn(Schedulers.io())
      .observeOn(AndroidSchedulers.mainThread())

Support the single is inside a static method or a method, which one of the following makes more sense:
public static Single<File> download(URL url) {
      return Single.fromCallable(/*download*/);
}

public static Single<File> download(URL url) {
     return Single.fromCallable(/*download*/)
      .subscribeOn(Schedulers.io())
      .observeOn(AndroidSchedulers.mainThread())
}

Basically, whose responsibility it is to enforce the threading, the callers' or the callee's and why?

A: It makes more sense to only handle the subscription part with the source. If the thread doesn't matter at all, you can skip it as well. Otherwise you know the requirements to the thread exactly at this place.
public static Single<File> download(URL url) {
     return Single.fromCallable(/*download*/)
      .subscribeOn(Schedulers.io());
}

The observeOn() operator should be used when you consume the events and have specific requirements to the thread at this place.
download(url).observeOn(AndroidSchedulers.mainThread()).subscribe();

Also you could provide a possibility to define it with the method or use other naming conventions like downloadOnIo.
public static Single<File> download(URL url, Scheduler subscribeOn) {
     return Single.fromCallable(/*download*/)
      .subscribeOn(subscribeOn);
}


text:
Q: Pull date record is first in current status I have a table with the current record information and a history table.  Each time a record is updated a new record is created in the current table and the previous is moved to the history table.  I want to return the date when the current client, connection, status was first set.  The kicker is the connection could move out of and back into the current status so I can't just generically look for the first date in the history table that matches the client, connection, status from the ConnectionStatus table.  In the example below I would be looking to return the DateChanged from the second record in the history table - 1-19-2021.
ConnectionStatus

Client
Connection
Status
DateChanged

ABCD
1234
4
1-27-2021

ConnectionStatusHistory

Client
Connection
Status
DateChanged

ABCD
1234
4
1-24-2021

ABCD
1234
4
1-19-2021

ABCD
1234
3
1-16-2021

ABCD
1234
3
1-12-2021

ABCD
1234
4
1-8-2021

A: This is a bit tricky.  One method is to get the most recent date associated with another status and then only choose rows bigger than that:
select csh.client, csh.connection, csh.status, min(csh.date)
from (select t.*,
             max(case when most_recent_status <> status then date end) over (partition by client, connection) as other_date
      from (select csh.*,
                   first_value(csh.status) over (partition by client, connection order by date desc) as most_recent_status
            from ConnectionStatusHistory csh
           ) csh
     ) csh
where date > other_date or other_date is null
group by client, connection, status;

A more clever approach uses row_number():
select client, connection, status, min(date)
from (select csh.*,
             row_number() over (partition by client, connection order by date desc) as seqnum,
             row_number() over (partition by client, connection, status order by date desc) as seqnum_s
      from ConnectionStatusHistory csh
     ) csh
where seqnum = seqnum_s
group by client, connection, status;

This is more inscrutable.  But if you look at the results of the subquery, you will see that seqnum enumerates all the rows starting from the most recent as 1.  Then seqnum_s enumerates the rows by status.  These values are equal only when the status is the most recent status.


text:
Q: Access denied in powershell when executing command to remote servers I'm trying to execute the following script on several remote servers and I think the syntax is correct, but it keeps coming back as "access denied".  A few things to note - I am executing the script as an admin on the destination boxes, so creds shouldn't be an issue.  I also tried using -cred just in case and the same error occurs.
Essentially what the script is trying to do is execute the nsrports command from that static location and change the port range, then recycle the networker service.
$servers = Get-Content Z:\scripts\computers2.txt
invoke-command -ComputerName $servers -ScriptBlock {cd "C:\Program
Files\Legato\nsr\bin\"; .\nsrports -s "7937-9000"}
Restart-service -DisplayName "*Networker Remote Display Service" -force

Output:
Program 'nsrports.exe' failed to execute: Access is denied
At line:1 char:50
+ cd "C:\Program Files\Legato\nsr\bin\"; .\nsrports <<<<  -s "7937-9000".
+ CategoryInfo          : ResourceUnavailable: (:) [],
ApplicationFailedException
+ FullyQualifiedErrorId : NativeCommandFailed

Any thoughts / suggestions are greatly appreciated!