Is the secondary dominant the same if my target chord is a major or minor of the same root?

Question: Say my target chord is D major or D minor in two separate keys. For example let's say D major is in the key of G major (the V chord) and let's say the D minor is in the key of F major (the vi chord).
Do they both have the same secondary dominant (A7)? the V7/V in the key of G is the same as the V7/vi in key of F? In other words, when I'm trying to figure out a secondary dominant, the V7 of a minor scale is just like V7 of a major scale, provided they share the same tonic (in this example D).
Comment: I'm not entirely sure what the question is, but I'm fairly sure that the answer is "yes."
Comment: V is the primary dominant of the key. Secondary dominants are dominants of chords that are not the I or i chord. In D major, E7 is a secondary dominant because it is the dominant of A. A is the V in D major, so E7 is analyzed as V7/V, which is said out loud "five-seven of five". (Also assuming that an A chord of some sort follows the E7).
Comment: Also, as @phoog pointed out, you are correct. Both major and minor use the same dominant V chord, which is a major triad.
Comment: The V of a major scale is always a major or dominant chord based on that scale.  The V of a minor scale depends on the scale being used; your V7 can be a minor triad or m7 in the natural minor, or a major chord or 7 in the harmonic or melodic minor.
Answer: In whatever key, the dominant of D major is A, or A7. In whatever key, the dominant of D minor is A, or A7. The key doesn't influence the secondary dominant. Since there needs to be that leading note (here, C♯) leading to the root D, it applies to both major and minor.
Thus V(7) of V is A(7)>D. Assuming the key of G. Note that a secondary dominant is not always the dominant of the dominant. It could be the dominant of another diatonic chord. If the key is C, then it's V(7) of ii, or, V(7) of II (which is chromatic). Or, in key F, A would be a secondary dominant leading to the vi, diatonically Dm. If, in key C, we're talking about an A chord, some might even call it V of V of V,(V/V/V) but that gets complex.
Answer:
Say my target chord is Dmajor or Dminor in some random scale. Is it
  safe to say they will both have A7 as their secondary dominant?

No.  The dominant is the fifth scale degree, so A7 is the dominant seventh of both D major and D minor (using the harmonic or melodic minor scale).
The secondary dominant is the dominant of the dominant.  That would be an E7 chord.
EDIT: I realized you may have some confusion over terminology.  A7 will be the dominant of either D or Dm, but if you're in some other key the same A7 chord will be called a secondary dominant relative to the key.
If you're in C, A7 will be the V/ii; if you're in Bb A7 will be the V/iii, etc.  But if you're in D or Dm, A7 is simply the dominant, and E7 is the secondary dominant.
Comment: I am familiar with the use of "secondary dominant" to refer to any tonicized dominant. So not just V/V, but also V/vi V/ii, V/IV, etc.
Comment: @trlkly - yes, that's true.  But A is always the dominant of D, not the secondary dominant - it's only called a secondary dominant when some other note is the true tonic.  The question has been edited since I answered it, and it's now clearer that the OP means some other note is the tonic.
Answer:
Do they both have the same secondary dominant (A7)? the V7/V in key of G is the same as the V7/vi in key of F? In other words, when I'm trying to figure out a secondary dominant, the V7 of a minor scale is just like V7 of a major scale, provided they share the same tonic (in this example D).

A7 will be the dominant of your goal chord D / dm. The secondary dominant would be E7.

A secondary dominant is the dominant of the dominant.
A dominant chord is by definition a major chord with a leading tone by the major third.
This implies that the dominants of all relative chords (major or minor chords with identical root) are the same.
this implies that the secondary dominants of all relative chords (major or minorchords with identical root) are the same, following the circle of fifths.
Answer: No... but yes.
Let me explain...
If you take that major scale, the 5th degree's chord will always be a major triad.
However, the minor scale is more complicated. Since there's 3 of them (harmonic, melodic and natural) you can use all of them to create triads. And even though when it comes to chords, the harmonic minor is the one which is the most used (the name gives you some hint there).
So in a natural minor scale, you'll get a minor 5th degree triad, while in both others you'll get a major one. This means you can actually choose whichever you prefer as your dominant.
Then you get to secondary dominants. To simplify things, let's take your example, in D minor.
So if you chose as your dominant a major chord (A7) then you get back to dominants of major chords which are always major. So you'll get as secondary dominant E7.
Now, if you chose Amin as your primary dominant then you could also choose as secondary dominant a minor chord. You could have Emin as secondary dominant.
And this keeps going. It means you could have something like this:
C#7 --------- F#min --------- Bmin --------- Emin --------- Amin --------- Dmin
V7/Vmin -- Vmin/Vmin -- Vmin/Vmin -- Vmin/Vmin ---- Vmin ----------- I
Okay, this would probably sound like shit but it would syntaxically by perfect.
Another interesting thing is about 9ths because in a minor scale, the 5th degree could be either 9 (melodic minor) or b9 (harmonic minor). While in Major, you'll never get a 5th degree with a b9.
So to summarize:

In D Major, your dominant will always be A, A7, or A9, and thus your secondary dominant will always be E, E7 or E9.
In D minor, your dominant could be A, A7, A9, but also A7(b9) and Amin. Your secondary dominant could be:

If your dominant was major: E, E7 or E9;
If it was minor: E, E7, E9, E7(b9) or Emin.

And of course, that's if you omit 11th and 13th, 6th and suspended chords, and much more.
P.S. It's fun to realise that your forth degree in melodic minor (ascending. Oh... I forgot about ascending and descending melodic minor! Even more fun!) is actually a dominant 7 chord. It's however rarely used. I've only seen it once in Gluck's Orfeo, act II, number 18, maestoso, measure 4.
Answer: A Dominant (or secondary dominant) is always a fifth above your "key of the moment" and it's  a major chord with minor 7. So yes it doesn't matter what chord quality you are looking at, it will always be the exact same chord.
Well to clear up a little misconception here, a lot of people say a dominant could be e.g.g. A or A7 but this is only to a small percentage true. It is true that you call the fifth chord of a major scale dominant (when leaving the minor7 out) when thinking of the Roman numeral theory or functional analysis. However, it is in deeper conceptual analysis a statement about the quality of a chord. So to represent a true dominant, quality-wise, you have to play a minor7 over a major chord. You need the tritone intervall in your dominant chord to make it truly dominant. The tritone is in this case the intervall between major3 and minor7.  This is also the reason why some people call the 7th chord in a major scale, the half diminished chord, a shortened or rootles dominant.
To take it a step further, now we know it is the tritone. Turns out that always two chords share the same tritone intervall and you can substitute them. This is called tritone substitution. You can basically always substitute your dominant for the dominant a tritone(6 half tones) away from it, as both contain the same tritone intervall and resolve to the same target chords.
This sounds complex at first but it is really easy and once you know of it you should be able to easily identify it in chord progressions.
Many times it's used in a 2-5-1 to create a chromatic run. For example dm G7 C becomes dm Db7 C. You can find this for example in Bill Evans "Alice in wonderland".
Sorry if I went a bit off topic here but I feel it is still within the boundaries of Dominants.


How to switch datasources in loopback

Question: I have a loopback 4 application that uses a mysql db as the datasource. It is created like
export class ES {
  public readonly app: express.Application;
  public readonly myApp: myApplication;
  private server?: http.Server;

....
}

I would like to switch the datasource to an in memory datasource when testing, so I tried
export async function setupEAWithInMemoryDb(): Promise<AWC> {

  const testdb: juggler.DataSource = new juggler.DataSource({
    name: 'db',
    connector: 'memory',
  });

  const server = new ES({rest: givenHttpServerConfig()});
  await server.boot();
  const myApp = server.myApp;

  myApp.dataSource(testdb);

  await server.start();

  const client = supertest(server.app);

  return {server, client, myApp};
}

export interface AWC {
  server: ES;
  client: Client;
  myApp: MyApplication;
}

but the datasource doesnt switch (it keeps using the original datasource). What am I missing?
Answer: I did this kind of thing by defining alternate config objects in my .datasource.ts file ( in my case one config for when the app is running on linux and one for android) and then using code like this:
constructor(
@inject('datasources.config.db', {optional: true})
dsConfig: any = process.platform === 'linux' ? linuxconfig : androidconfig) {

How to switch datasources in loopback


Uniquely identify a point in 2d space in reference to known points

Question: Context
I'm making a 2D sci-fi game, and I've convinced myself that it would be neat to have player positions described in reference to nearby stars rather than using some kind of coordinate system. Realistically, the player would not have any way to measure its distance to nearby stars, but it could measure angles between nearby stars.
Problem
You would need to use at least 3 nearby stars to identify the Player's location, but just any old 3 stars are not sufficient. Under certain conditions, the 3 angles between the Player and each of the 3 stars can represent 2 points.
Visual showing 3 stars, the player position, and a degenerate point that has the same angles as the player
Here the red circles are the 3 stars, the pink circle is the Player, and the Yellow circle is a degenerate point. The arcs show all of the points (with some error margin) that can be represented by just a single angle (ie. The green arcs show all the possible positions that have the same angle Star 2 - Player - Star 3).
Keeping the same star positions, you can manipulate the player position to find an arangement that does not produce a degenerate point.
Visual showing 3 stars and the player position, with the player position modified so that there is no degenerate point
(Here is the janky jsfiddle I made that generates these images. Re-run to randomize the star positions, click to move the player position to the mouse position. This is not precise nor efficient, but serves to provide a visual aid)
Question
How could I compute whether or not a given relationship produces a degenerate point?
Or perhaps more relevant to my problem: Given a set of nearby stars, how could I select 3 stars such that the angles produced resolve to exactly 1 point in space?
Comment: 3 stars should not be on straight line.
Comment: 3 stars in a straight line will produce a degenerate point, yes. But the player has no means of identifying whether or not any 3 stars are in a straight line. Remember, the player only knows the angles to each star. You would also need distance to identify whether or not the stars make a straight line.

A straight line is also clearly not the only degenerate case, as the example image I provided shows 3 stars not in a straight line that still produce a degenerate point.
Answer: This isn't anywhere near a complete answer.
But this could be on the way to one.
I have tried to reproduce your diagrams in Desmos. (The diagrams are interactive.)
The construction appears to be:

Given three fixed points (the stars)
Given a point (the ship)
Two stars and the ship determine a circle containing those three points.
The
angle between the displacement vectors from the ship to the two stars is constant for all ship positions on the arc containing the ship. (The other arc [which completes the circle] does not contain the ship.)
Two stars and the ship determine another circle containing those two stars and a point that is the ship reflected across the line joining the two stars. (The reflected-ship is the magenta X.) The
angle between the displacement vectors from the reflected-ship to the two stars is the same constant for all positions on the arc containing the reflected-ship.
The three circles associated with the reflected-ships have a common intersection,
which could lead to a degenerate point.

https://www.desmos.com/calculator/htw1bniiod

The three dashed circles associated with the reflected-ships intersect in the arcs
that contains the reflected-ships.

https://www.desmos.com/calculator/jxruewsve2

Here, the green dashed arc where the common intersection occurs does not contain the reflected-ship. (This might be a condition to test for.)
Note that you can move the ship and obtain a degeneracy point like in the previous case. (Drag R to the lower right corner.) So, it's not just about the arrangement of the three stars.

Hope this helps.
Comment: Wow Desmos is amazing! I've been building these diagrams myself with Javascript, but Desmos is way nicer
Answer: After doing more digging, I think the simplest way to guarantee uniqueness is to select 3 stars such that the Player is contained within the triangle formed by those 3 stars. Constructing a naive example we can see only 1 intersection of the 3 circles that circumscribe each of the pairs of stars and the player.
Checking this constraint in programmatically is pretty simple, as I just need to find the angles $S_1 R S_2$, $S_2 R S_3$, and $S_3 R S_1$. If the sum of angles is $360^o$, then our point is within that triange.
From there we ensure that we order the stars in a clockwise manner. This ordering makes it much more feasible to reconstruct the point from the encoded coordinates we generate. In my case, I decided to construct a coordinate in the form $S_A/A_{AB}/S_B/A_{BC}/S_C/A_{CA}$ where $S_i$ is the ID of the star, $A_{ij}$ is the angle $S_i R S_j$, and $A$, $B$, $C$ are the clockwise ordering of stars about the player.
Now to transform that coordinate back into a point in space. For each pair of stars, construct a perpendicular bisector (shown below in green).

Now find a point on each bisector $T_{AB}$ such that the angle $S_A T_{AB} S_B$ is equal to $A_{AB}$ from our given coordinate. This is doable with some fairly basic trig.

With that new point we construct a circle (an arc would also do) that passes through $S_A$, $T_{AB}$, and $S_B$. See Get the equation of a circle when given 3 points on how to construct said circle.

Repeat for all 3 pairs and you now have something like this

Since we enforced that the player be within the triangle formed by the stars, we have also guaranteed that there will be exactly one point at which the 3 circles intersect. I followed the answers on Find intersecting point of three circles programmatically to build a method that takes those 3 circles and finds their intersect. With a properly tuned epsilon, we can now find our ship!
As a bonus here's a screen recording of the tool I built while I was working out this method:


Matrix Index Notation and Transpose

Question: I never got introduced to how, formally, indexing of elements forms a matrix – I suppose it works via mapping of ordered pairs. Now, dealing with transposed matrices, I am slightly confused:
Let $A=(a_{ij})_{i=1:m,j=1:n}$ be any matrix. Now, I have two definitions of the transpose $A^t$:
1) $A^{t,1} := (a_{ji})_{i=1:m, j=1:n}$
2) $A^{t,2} := (a_{ij})_{j=1:n, i=1:m}$
I get the first: When pointing on the second entry of the third row of $A^{t,1}$ the first index – $j$ in my presentation – is $3$ and the second, $i$, is $2$, that is, I get $a_{23}$, the third entry in the second row of $A$. That is how the transpose should work.
However, I cannot work with the second. How does the order in the subscript affect the matrix? In any way that I could imagine the first definition would not make sense then and produce $A$? Whats the right way to define the transpose?
Thanks in advance.
Comment: where did you take the second one?
Comment: From a german textbook on numerical linear algebra and the german wikipedia page on the transpose.
Answer:
The second entry of the third row of $A^{t,1}$ is $(a_{ji})_{i=3,j=2}=a_{2,3}$.
The second entry of the third row of $A^{t,2}$ is $(a_{ij})_{j=3,i=2} = a_{2,3}$. The key is that outside the parentheses, the subscript "$j=1:n,i=1:m$" implies that $j$ now counts rows and $i$ counts columns (in contrast to "$i=1:m,j=1:n$").

If you want an intuitive understanding of the transpose, an animation (Wikipedia) is much more helpful.
Comment: Sorry to dig this out, but should it not be $a_{2,3}$ in both cases in your answer?
Comment: @Ramen Yes, sorry about that

Matrix Index Notation and Transpose


Character of the subobject classifier in the topos of $\mathbf{M}$-sets.

Question: I'm currently reading Goldblatt's Topoi - The categorial analysis of logic and at some point he lets one verification to the reader and I must admit that I'm stuck.
He's just introduced $\mathbf{M}$-sets where $\mathbf{M}$ is a monoid, and he's showing that the category of $\mathbf{M}$-sets and multiplication-preserving maps is a topos.
He also introduced the concept of a left ideal and called $L_M$ the set of left ideals of $M$, and his claim is that $L_M$ together with the multiplication $m\cdot B = \{n\mid nm \in B\}$; and with the true arrow $true : \{0\} \to L_M$, $true(0) = M$ is a subobject classifier in this category.
Then he considers a monic arrow $k: X\to Y$ and argues that the character $\chi : Y\to L_M$ associated with this subobject is defined by $\chi(y) = \{n \mid n\cdot y \in X\}$.
This is where I'm stuck : I've managed to show that this does make the associated square a pullback square, and that any other arrow $g:Y\to L_M$ that makes it a pullback square has $g(x) = M$ for $x\in X$. I've also shown that it has $\chi(y) \subset g(y)$ for all $y\in Y$, but I can't prove that $\chi$ is the only one that works...
Any indications?
Answer: Suppose $m\in g(y)$.  We then have $g(my)=mg(y)=\{n\mid nm\in g(y)\}$.  But since $m\in g(y)$, $nm\in g(y)$ for all $n$, so $g(my)=M$.  Since $g$ forms a pullback square, this implies $my\in X$, so $m\in\chi(Y)$.
Comment: Oh right I hadn't thought of that ! Thank you so much !


From managed file ID to end-user link - neat and clean way?

Question: I have a structure in database, and I want it printed. So in hook menu I have entry with
'page callback' => 'mymodule_mystructure_display',

And in inc file I have
function mymodule_mystructure_display($id_structure) {
  $mystructure= something(); // Data preparation
  return $mystructure;
}

And I have all helpers set up so in mystructure.tpl.php I can simply use:
kpr($mystructure);

and it all works, so let me omit details for now, they are covered in Examples for Developers anyway.
The real struggle is with files.
In $mystructure['files'] I have a nested array like this:

array(2) {
  [0]=>
  array(2) {
    ["name"]=>
    string(26) "Display name of first file"
    ["fid"]=>
    int(34)
  }
  [1]=>
  array(2) {
    ["name"]=>
    string(27) "Display name of second file"
    ["fid"]=>
    int(62)
  }
}

where ["fid"] corresponds to {file_managed}.fid field in Drupal's database.
What's the cleanest way to output links to files, with ["name"] used as link text?
What I'm doing now is pretty dirty:

In function mymodule_mystructure_display I foreach or array_walk over files.
For each element, I take file id, and use this helper function on it:
_uri_by_id($id) {
  $file = file_load($id);
  return $file->uri;
}

Result is fed to file_create_url function, and it's result is saved under ["url"] index, to give me this array in $mystructure['files']:

array(2) {
  [0]=>
  array(2) {
    ["name"]=>
    string(26) "Display name of first file"
    ["fid"]=>
    int(34)
    ["url"]=>
    string(50) "http://example.com/sites/default/files/example.pdf"
  }
  [1]=>
  array(2) {
    ["name"]=>
    string(27) "Display name of second file"
    ["fid"]=>
    int(62)
    ["url"]=>
    string(50) "http://example.com/sites/default/files/example.txt"
  }
}

In mystructure.tpl.php I use l() to print actual link:
echo l($item["name"], $item["url"]);

This all works. But it feels bad. I was always a backend guy, my frontend knowledge is somehow lacking. But I'm sure there should be a shorter way from managed file ID to a link. So what would it be?
Note: value under ["name"] is derived from $mystructure, it is not something taken directly from file object. This pretty much stopped me from using theme_file_link(). But even if it wouldn't be the problem, I still need to load file object manually to use theme_file_link().
Answer: I'd personally prefer something like this:
// Extract file IDs so we only run one file_load().
$fids = array_map($mystructure['files'], function($x) { return $x['fid']; });
$files = file_load_multiple($fids);

$build = array();
foreach ($mystructure['files'] as $file) {
  // Update the description
  $files[$file['fid']]->description = $file['name'];

  // Add to the build
  $build[] = array(
    '#theme' => 'file_link',
    '#file' => $files[$file['fid']],
  );
}

return $build;

A bit cleaner/more performant, and using as much core API as possible.


What is the error function in multi-class classification?

Question: I am in trouble to know what is the loss function of a neural network. For a binary classification problem, is it mean squared error, as described in the following video :https://www.youtube.com/watch?v=5u0jaA3qAGk&t=59s or is it cross entropy as defined here http://work.caltech.edu/slides/slides09.pdf and why ?
Moreover, in case of multi classification, I think there is sth like softmax but I don't really know how it works. Could s.o. explain me properly ?
Thanks !
Comment: Please copy the definition to your question. I'm on mobile and I can't access it like this
Answer: Softmax is the activation function, not the loss. Softmax is defined as (source):
$$\varphi(\mathbf{x})_j = \frac{e^{\mathbf{x}_j}}{\sum_{k=1}^K e^{\mathbf{x}_k}}$$
The cross entropy is also defined for multiple classes (and multiple labels):
$$E_{-x} = - \sum_{k}[t_k^x \log(o_k^x) + (1-t_k^x) \log (1- o_k^x)]$$
Where k is the class, o is the output of the classifier and t is the true label. The x superscript indicates that it belongs to x.
Comment: Thanks for your answer; could you also provide some explanation about softmax, please (formula + comment). Thanks !
Comment: I've added the formula. See https://en.wikipedia.org/wiki/Softmax_function for explanations.
Comment: Ok, thanks, it seems quite clear


Hyperledger Fabric: [Java] ContractException- Transaction commit was rejected by peer peer0.org2.example.com

Question: I'm going through the commercial paper tutorial in the Hyperledger Fabric docs, and I'm getting a runtime error when I try to use the Issue application (Issue.java).
https://hyperledger-fabric.readthedocs.io/en/latest/tutorial/commercial_paper.html
I've used the Java chaincode and Java application code given in the commercial paper folder of fabric-samples. https://github.com/hyperledger/fabric-samples/tree/main/commercial-paper
My OS is Debian GNU/Linux 10 (Buster).
When I run mvn exec:java -Dexec.mainClass="org.magnetocorp.AddToWallet", it successfully adds to the wallet.
But when I run mvn exec:java -Dexec.mainClass="org.magnetocorp.Issue" it yields the following:
Read wallet info from: ./wallet
log4j:WARN No appenders could be found for logger (org.hyperledger.fabric.sdk.helper.Config).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Use network channel: mychannel.
Use org.papernet.commercialpaper smart contract.
Submit commercial paper issue transaction.

org.hyperledger.fabric.gateway.ContractException: Transaction commit was rejected by peer peer0.org2.example.com
        at org.hyperledger.fabric.gateway.impl.commit.CommitHandlerImpl.onTxEvent(CommitHandlerImpl.java:104)
        at org.hyperledger.fabric.gateway.impl.commit.CommitHandlerImpl.access$000(CommitHandlerImpl.java:26)
        at org.hyperledger.fabric.gateway.impl.commit.CommitHandlerImpl$1.acceptCommit(CommitHandlerImpl.java:33)
        at org.hyperledger.fabric.gateway.impl.event.Listeners.lambda$transaction$7(Listeners.java:122)
        at java.base/java.lang.Iterable.forEach(Iterable.java:75)
        at org.hyperledger.fabric.gateway.impl.event.Listeners.lambda$fromTransaction$0(Listeners.java:32)
        at org.hyperledger.fabric.sdk.Channel.lambda$null$12(Channel.java:5974)
        at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
        at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
        at java.base/java.lang.Thread.run(Thread.java:829)

Why was the transaction commit rejected? (And how do I resolve this error?) Any help would be much appreciated.
Comment: I'm facing the same problem using the same OS. Unfortunately, I still can't find a solution online neither fix it. It was hard to find the same exact question. What was the exact problem if you ever fixed it. I tried @bestbeforetoday solution but it doesn't provide more details about the exception itself.

A hand would be deeply appreciated. Thanks.
Answer: Assuming you are using a current v2.2.x version of fabric-gateway-java, you should be able to get at some information about the reason for the failure by inspecting the cause linked to that ContractException. Something like this:
Throwable cause = e.getCause();
if (cause instanceof TransactionEventException) {
    BlockEvent.TransactionEvent txEvent = ((TransactionEventException) cause).getTransactionEvent();
    byte validationCode = txEvent.getValidationCode();
}

The validation code values are in the Fabric protobuf definitions.
You can also inspect the proposal responses received from peers to endorse this transaction if the validation code indicates that the endorsement requirements were not met. The proposal responses can be obtained from the ContractException.
The peer logs may also contain more detail about the reason for the failure.
Comment: Hello, I'm facing the exact same issue. I added this block of code but it doesn't provide more deep information about what the error is. Any other option to resolve it would be appreciated. I'm new to hyperledger.
Comment: The validation code will give you an indication of why the transaction committed unsuccessfully. From there your course of action depends on that reason. For example an MVCC_READ_CONFLICT indicates that another transaction modified keys accessed by your transaction before it committed, so you can just try executing the transaction again. Logs from the peer that rejected the transaction are often a good place to look for additional information.


Invoke a Dialogflow event with a specific device source

Question: After trying and trying countless times, I ask for your help to call a Dialogflow event (GoogleHome) with a specific GoogleHome device.
Through nodeJS I managed to successfully call a Dialogflow event and I get the fullfillment response. All perfect, only I have to let my GoogleHome device speak with fullfillment, I do not need a text-only answer.
My goal is to let my GoogleHome device speak first, without the word "Ok, Google" and wait for a response from the user.
I did not find anything on the web, my attempts stop to invoke the Dialogflow event and have a console response.
This is the code i have tried for fullfillment
<code>test: async function () {
    console.log("[funcGHTalk|test] CALLED");

    const projectId = "[[projectid]]";
    const LANGUAGE_CODE = 'it-IT';
    let eventName = "[[eventname]]";
    const sessionId = uuid.v4();

    const sessionClient = new dialogflow.SessionsClient();
    const sessionPath = sessionClient.sessionPath(projectId, sessionId);

    // The text query request.
    const request = {
        session: sessionPath,
        queryInput: {
            event: {
                name: eventName,
                languageCode: LANGUAGE_CODE
            },
        },
    };

    // Send request and log result
    const responses = await sessionClient.detectIntent(request);
    console.log('Detected intent');

    const result = responses[0].queryResult;
    console.log(result);

    console.log(`  Query: ${result.queryText}`);
    console.log(`  Response: ${result.fulfillmentText}`);
    if (result.intent) {
        console.log(`  Intent: ${result.intent.displayName}`);
    } else {
        console.log(`  No intent matched.`);
    }
}
</code>
Comment: Could you share code for what you've tried or documentation that you think might work? This type of question can seem a little too open and hard to answer as it would entail writing an entire solution to the problem. Is there any specific piece you are struggling with?
Answer: The code you have written is using the Dialogflow Detect Intent API. This is meant to run on consoles and servers to send a message to Dialogflow, which will parse it, determine which Intent it matches, call fulfillment with that information, and return all the results.
You don't need to run this on a Google Home, since the Google Assistant does all this for you.
What I think you're looking for is to develop fulfillment with Actions on Google and the Dialogflow Fulfillment API. This handles things on the other end - after Dialogflow determines what Intent matches what the user has said, and if that Intent has fulfillment enabled, it will send the information to your webhook which is running on a cloud server somewhere. You would then process it, send a reply (either using the actions-on-google library or the dialogflow-fulfillment library is easiest), and it would send it back to the Assistant.
You indicated that you want the Action to "let my GoogleHome device speak first, without the word "Ok, Google" and wait for a response from the user". This is much more complicated, and not really possible to do with the Google Home device right now. Most Actions have the user initiating the conversation with "Ok Google, talk to my test app" or whatever the name of the Action is.
You don't indicate how you expect to trigger the Home to begin talking, but you may wish to look into notifications to see if those fit your model, however notifications don't work with the Home right now, just the Assistant on mobile devices.
Comment: Thank you for your reply, very clear.

I understand that it is very complicated to let GoogleHome speak first and request an answer. For example, as we said, to unleash an event that says "Hello, welcome back! How are you?" and wait for a reply that is then processed by Dialogflow.

Can you tell me, please, what should I do to choose this solution?
Even without detailed explanation, only suggestions.

Thank you!


C++: Passing reference of constructing object to constructed member objects?

Question: Okay, consider the following classes:
class Object
{
public:
    // Constructor
    Object() :
        [Initialization List]
    {
        ...
    }
    ...
};

class Container
{
public:
    Object A;
    Object B;

    ....

    Container() :
        [Initialization List]
    {
    }
};

I'd like to provide [access to Container and it's members] to the Objects.
My first thought was to somehow pass a reference to the current Container object to the constructors of the Objects.  But I can't figure out how to do this.
I've messed around with "this", but I'm not getting anything that works.  I tried something like this:
class Object
{
public:
    Container& c

    // Constructor
    Object(Container& c_) :
        c(c_)
    {
        ...
    }
    ...
};

class Container
{
public:
    Object A;
    Object B;

    ....

    Container() :
        A(Object(this))
        B(Object(this))
    {
    }
};

My eventual goal is to be able to access Object B from inside a member method of Object A.
Does anyone have any insight on how to get closer to what I'm looking for?
Thanks!
Answer: It is not UB or bad, necessarily, to use this in an initializer list, although care is needed, and your code is perfectly valid with minor modification.
class Container;
class Object
{
public:
    Container& c

    // Constructor
    Object(Container& c_) :
        c(c_)
    {
    }
};

class Container
{
public:
    Object A;
    Object B;

    Container() :
        A(Object(*this))
        B(Object(*this))
    {
    }
};

this is a pointer, you wanted a reference, and a simple de-reference will do the trick. This is perfectly legal and defined code. What's not allowed is to access any member data or functions through the pointer, because those member data or functions simply may not exist yet until the init list is finished. But it definitely is allowed to take a pointer or reference to an object during it's initializer list and pass it around.
Comment: I can edit the "can't" to be a "shouldn't", but I've used compilers that will reject your code or misbehave on it, so your solution definitely is not portable. Also note the *IIRC* in my comment about the UB - as you pointed out in chat, the standard allows it. That doesn't make is portable, nor necessarily a good idea.
Comment: @RonaldLandheer-Cieslak: [Your comment](http://stackoverflow.com/questions/5905498/c-passing-reference-of-constructing-object-to-constructed-member-objects/5905534#comment-6797641) says "IIRC", but your answer does not.  With which compilers does it fail?
Answer: How about just using pointers? Edit: fixed code to avoid this in initializer list.
class Container;

class Object
{
public:
    Container *c;

    // Constructor
    Object(Container *c_) :
        c(c_)
    {
    }
};

class Container
{
public:
    Object *A, *B;

    Container()
    {
        A = new Object(this);
        B = new Object(this);
    }
};

Comment: @jedwards in the code you provided the constructor is `Object::Object(Container&)`, not `Object::Object(Container*)`. That said, it is a *bad* idea to pass `this` in an initializer list - IIRC, it's UB
Comment: Thats actually what I have right now, but I get compile error noting that it is looking for Object::Object(Object).  My constructor is, of course, Object::Object(Container *)
Comment: @jedwards, I forgot the forward declaration `class Container`, that should fix the error. @Ronald, I wasn't aware that it was UB. I suppose A and B should be pointers, then, which are set in the constructor itself.
Answer: You shouldn't pass this in initializers for members of the class whose instance you're constructing, but you can pass it later, so there's two easy ways around your problem

use a setter on the object (A.setContainer(*this)) in the constructor's body
make A and B pointers, initialize them to NULL and do a A = new Object(this) in the constructor's body
Comment: [Is it safe to bind a reference to a not yet constructed object in C++?](http://stackoverflow.com/questions/4815689/is-it-safe-to-bind-a-reference-to-a-not-yet-constructed-object-in-c/4815754#4815754) "In a nutshell: don't access any members, methods, or pass it to anything that does. You can take its address and bind references to it."
Comment: @Xeo: You can de-reference it too, to get a reference. You just can't access anything.
Comment: Thank you for the concise and clear explanation of what I was doing wrong -- all is well in container/object-ville now!
Comment: @Fred not portably, you can't
Comment: @Ronald: You can, you just shouldn't access any members. It's a normal pointer after all, i.e. an address.


bounded real parts and removable singularity

Question: I was reading this proof here: holomorphic function with bounded real part on punctured neighborhood $\dot{D}_{\epsilon}(z_0)$, which was proving that
Let $f$ be holomorphic on a punctured disk $D_\epsilon(z_0)/\{z_0\}$ and $Re(f(z)) < M$ for all $z \in D_\epsilon(z_0)/\{z_0\}$. Then it implies that $f$ has a removable singularity at $z_0$.
In the answer to the original post, they supposed that $z_0$ is a pole for the sake of contradiction, but why $g = \frac{1}{f}$ holomorphic in a "possible smaller" punctured neighbourhood $D_\delta(z_0)/\{z_0\}$? Also, why is $g(D_\delta(z_0)/\{z_0\})$ an open neighbourhood of $0$? The open mapping theorem might have been used here but why is it a neighbourhood of $0$? Last, why is $\frac{1}{D_r(0)\setminus \{0\}} = \mathbb{C}\setminus \overline{D_{\frac{1}{r}}(0)}$?
Thank you .
Answer: The proof in the link given does not say $g(D(z_0)\setminus\{z_0\})$ is an open neighborhood of $0.$ That doesn't even make sense: $0\notin g(D(z_0)\setminus\{z_0\})!$ What is stated is that $g$ has a removable singularity at $z_0.$ Still using the notation $g$ for the extension, we have $g(z_0)=0.$ It is the extended $g$ that maps $D(z_0)$ onto a neighborhood of $0.$
Answer: First question: if $f$ has a pole at $z_0$ then $|f(z)| \to \infty$ as $z \to z_0$ so $f$ does not vanish in some deleted neighborhood of $z_0$. Hence $\frac 1 f$ is analytic there.
Second question: it is already stated in the link that $g$ is defined to be $0$ at $z_0$ (to get rid of  removable singularity). Now open mapping theorem shows that $g(D_{\delta} (z_0))\setminus \{z_0\}$ is an open set containing $0$.
Third question: $0<|z| <r$ iff $z\neq 0$ and $|\frac 1 z| >\frac  1 r$.
Comment: thank you, for the first question i was asking why is the punctured disk "possible smaller"?
Comment: If $f$ has a zero in the original disk then $g$ is not defined there. So you have to take a smaller disk to make sure that $f$ has no zeros there and this is possible because $|f(z)| \to \infty$. @beigecamellia
Answer: 1) Because $f$ can have a zero in $D_\varepsilon(z_0) \setminus \{z_0\}$ so $1/f$ can be non holomorphic on $D_\varepsilon(z_0) \setminus \{z_0\}$. One have to consider a smaller disk: if $f$ has a pole at $z = z_0$, then by continuity, $f$ does not vanish around $z = z_0$ that is to say in $D_\delta(z_0) \setminus \{z_0\}$ for $\delta \leq \varepsilon$, so $g=1/f$ is holomorphic on $D_\delta(z_0) \setminus \{z_0\}$.
2) By the open mapping theorem, $g(D_\delta(z_0) \setminus \{z_0\})$ is open because $D_\delta(z_0) \setminus \{z_0\}$ is open. It is a neighbourhood of 0 because if one takes a sequence $(z_n)_n$ in  $D_\delta(z_0) \setminus \{z_0\}$ such that $z_n \to z_0$, then $g(z_n) = 1/f(z_n) \to 0$, so $0 \in \overline{g(D_\delta(z_0) \setminus \{z_0\})}$.
3) $z \in 1/\dot{D}_r(0)$ iff ($\vert 1/z \vert < r$ and $z \neq 0$) iff $ \vert z \vert > r$ iff $z \in \mathbb C \setminus \overline{D_{1/r}(0)}$.
Comment: Your proof of 2) has some problems. $g(D(z_0)\setminus\{z_0\})$ is not an open neighborhood of $0$ because $0$ is not in that set. And I'm not sure what you're doing with $z_n\to z_0$ etc.


Como somar um número a um array?

Question: Olá! Tudo bem com vocês?
Estou fazendo um código e precisei definir uma função:
<code>def sigmoid (v):
return 1/(1+np.exp(-v))
</code>
Só que o que estou atribuindo para a função é um array 2d.
A minha dúvida é: na teoria estou somando 1 com um array 2d. isto era para dar erro, não? Mas está funcionando sem problema. Ele está fazendo o cálculo da função sigmoide para todos os elementos do array. Meu pensamento está incorreto?
Answer: Sim, seu pensamento está correto (em tese), mas essa característica é proposital e muitíssimo bem-vinda. Esse comportamento acontece porque numpy aplica uma prática chamada broadcasting. Quando você faz uma operações entre arrays com uma quantidade diferente de dimensões, o de menor dimensão é 'replicado' quantas vezes forem necessárias para passar pela operação com o de maior dimensão.
Veja a definição da prática dada na documentação do numpy:

The term broadcasting describes how numpy treats arrays with different shapes during arithmetic operations. Subject to certain constraints, the smaller array is "broadcast" across the larger array so that they have compatible shapes. Broadcasting provides a means of vectorizing array operations so that looping occurs in C instead of Python. It does this without making needless copies of data and usually leads to efficient algorithm implementations.

Assim, se você somar um escalar a um vetor ou matriz, o escalar vai ser somado a cada elemento do vetor ou matriz. Se somar um vetor a uma matriz, o vetor vai ser somado a cada coluna da matriz (se as dimensões forem compatíveis).
Este link tem uma explicação gráfica mais clara, caso ainda tenha dúvidas.

Como somar um número a um array?


When is a $C^1$-function $f:\mathbb R^m \to \mathbb R^n$ Lipschitz-continuous?

Question: Let $f:\mathbb R^m \to \mathbb R^n$ be continuously differentiable. I'm looking for a proof that there is an $M>0$ such that $\|f(x)-f(y)\| \le M \| x-y\|$ for all $x,y \in A=[-1,1]^m \subset \mathbb R^m$. This proposition is familiar to me from the one dimensional $\mathbb R \to \mathbb R$ case, but I somehow can't wrap my head around this one.
I'm aware that in fact
$$\|f(x)-f(y)\| = \| \left(f_1(x)-f_1(y),...,f_m(x)-f_m(y) \right)\|$$
Where $f_i:\mathbb R^m \to \mathbb R$ are continuous functions, with a relevant domain of $A=[-1,1]^m$ which is compact. Therefore they're uniformly continuous there. I'm also aware that $\displaystyle\frac {\partial f}{\partial x_j}:\mathbb R^m \to \mathbb R$ are continuous functions.
I just can't seem to put it all together and I feel like I'm missing something.
Thanks for any input!
Comment: FredrikMeyer, he's asking about continuously differentiable functions. AdarHefer, try proving this for $n=1$ first (in much the same method one utilizes for $m=n=1$), then consider methods to generalize the result.
Comment: Oh, I should also ask (playing devil's advocate): which norm are you using in $\mathbb{R}^m$,$\mathbb{R}^n$?
Comment: Could you write down what you're trying to prove in the body of the question? As it is written now, it is not completely clear. It seems that you want to prove that any continuous function $f:[-1,1]^m \to \mathbb{R}^m$ is Lipschitz. Is that correct?
Comment: Thanks to the great edit by Christian Blatter I think it should all be clear now. Haha! *embarrassed*
Comment: The standard norm: $\|x\| = \left(\sum_{i=1}^n x_i^2 \right)^{1/2}$ details, details. :)
Comment: Well try writing a solution using my first comment. If you stumble into any difficulties, let us know where.
Comment: Thank you, I'll try the $n=1$ case and report back.
Comment: @JonathanY. So since the partial derivatives are bounded, the gradient's norm is bounded. Here's where I got to: (The n=1 case)
$|f(x)-f(y)| = |\langle \nabla f (y),x-y \rangle + o( \|x-y \|) | \le \|\nabla f(y)\| \|x-y\| + |o( \|x-y \|)| \le M\|x-y\|+ |o( \|x-y \|)|$

But how do I control the little o term?
Comment: The same way one does it in one variable: the mean value theorem.
Answer: Let $\|\cdot\|_O$ denote the operator norm. We have that $Df_a$ varies continuous on $A$, so $\|Df_a\|_O$ is continuous on $A$, hence bounded as $A$ is compact, say by $M$. Then for any $x,y\in A$ we have
$$\begin{align}
\|f(x)-f(y)\| &=\left\|\int_0^1Df_{tx+(1-t)y}(x-y)dt\right\|\\
&\leq \int_0^1\|Df_{tx+(1-t)y}(x-y)\|dt\\
&\leq \int_0^1M\|x-y\|dt=M\|x-y\|
\end{align}$$
as desired.
Comment: @AdarHefer I'm giving it some thought, but I can't think of a way off-hand that avoids integration of vector functions. But integration of vector functions is not complicated; you just integrate component-wise.
Comment: Thank you for your answer, however I'm unfamiliar with intergration over vectors (I suppose that's on my next Calculus course). Do you have an idea that does not employ that technique?
Comment: AlexBecker, one needs also show the triangle inequality for 'vector integrals' (after, naturally, introducing the notation), using this approach.


How can show pdf preview first image?

Question: Hope you can help me.
I use drupal 8.
I want pdf preview like this http://prntscr.com/j08ljo.

Need uploud pdf file in node and showing just first image in front page.
I check use module pdfpreview https://www.drupal.org/project/pdfpreview
Have with tutorial and dependence. Setup ImageMagick and configured it in image toolkit.
Sent in server files with imagemagick and write path.
"Path to the package executables" ... http://prntscr.com/j08ogh

After this showing in display manage full content "pdf preview" http://prntscr.com/j08r9i

But nothing happened. I hear about "may be i need install for other way imagemagick"
Can you help me?
Thanks for your future answers.
Answer: You have to firstly install imagemagick in your operating system.
for Ubuntu please follow below procedure:-
(1)https://medium.com/@sanjaywrites/install-latest-version-of-imagemagick-in-ubuntu-16-04-c406ddea1973
(2) https://www.enovate.co.uk/blog/2015/12/16/how-to-install-imagemagick-from-source-on-ubuntu-14.04
For window download imagemagic exe file.
https://imagemagick.org/script/download.php
once your Operating System have magicmagick  then install these module pdfpreview https://www.drupal.org/project/pdfpreview
and do a needful change as shown in image
and on your view  do a needful change as shown in image

How can show pdf preview first image?


Is there a constant $c$ that $\frac{c}{1+x}$ be a probability density function for $x>0$?

Question: There are two conditions for probability density function: $f(x)\geq0$ and $\int_{-\infty}^{+\infty}f(x)dx=1$.
Here for the first condition we must have $c\geq 0$. for the second condition:
$$\int_{0}^{+\infty} \frac{c}{1+x}=1 \Rightarrow \frac{1}{c} = lim_{t\to \infty} \int_{0}^{t} \frac{1}{1+x} \Rightarrow \frac{1}{c}=lim_{t \to \infty} (ln\vert1+t\vert - ln\vert1+0\vert) \Rightarrow \frac{1}{c}=\infty$$
so $c$ must be zero or there are no such $c$?
Comment: You are right. The function is not integrable for any $c>0$ so it is not a pdf.
Comment: You did the calculation right. And yes. There is no constant $c$.
Comment: What is the domain of $x$? Is it $0<x<\infty$?
Comment: @callculus42 $f(x)$ for $x\leq 0$  is zero.
Comment: @Lucy The integral $\int_0^{\infty }\frac{c}{1+x} \ dx$ does not converge. So it seems ill-defined. The integral of the pdf $f_X(x)=\frac{c}{(1+x)^2}_{0<x<\infty}$ does converge.
Answer: There is no such $c$. You can't even take $c=0$, because then the PDF is $0$ everywhere, so the integral is $0$, not $1$.


There is no largest rational number $p$ such that $p^2 < 2$

Question: In Rudin's analysis example 1.1, he tried to show the following
Let $A$ be the set of all positive rationals $p$ such that $p^2<2$ and let $B$ consist of all positive rationals $p$ such that $p^2 > 2$. He show that $A$ contains no largest number and $B$ contains no smallest
More explicitly, for every $p$ in $A$ we can find a rational $q$ in $A$ such that $p < q$ and vice versa
He then shows
$$q = p - \frac{p^2 - 2}{p + 2}$$
$$q^2 - 2 = \frac{2(p^2 - 2)}{(p + 2)^2}$$
and conclude that if $p$ in $A$ then $p^2 - 2 < 0 \rightarrow q^2 < 2$ and $q > p $ and vice versa.
I understand the conclusion, and I understand the hypothesis, but I didn't understand how he got
$$q = p - \frac{p^2 - 2}{p + 2}$$
and
$$q^2 - 2 = \frac{2(p^2 - 2)}{(p + 2)^2}$$
Specifically, I think he is trying to show the following
If $p$ in $A$, let $q$ be a number greater than $p$
$$q = p + \beta$$
now show
$$q^2 - 2 < 0 \Rightarrow q^2 - 2 = p^2 + 2\beta p  + \beta^2 - 2$$
I use the quadratic equation to find the threshold for $\beta$, but I can't derive what Rudin give, can someone explain how Rudin got his equations?
Answer: Observe that: $p^2 < 2 \Rightarrow p^2+2p < 2 + 2p \Rightarrow p(p+2) < 2+2p \Rightarrow p < \dfrac{2+2p}{p+2}\in \mathbb{Q}$. He then set $q = \dfrac{2+2p}{p+2}$, then $p < q$ from definition of $q$, and furthermore: $q^2 - 2 = \left(\dfrac{2+2p}{p+2}\right)^2 - 2= \dfrac{4+8p+4p^2}{p^2+4p+4} - 2= \dfrac{2}{(p+2)^2}\cdot (p^2-2) < 0\Rightarrow q^2< 2.$
Comment: Once you have the formula it is easy to verify the proof, but I think the question, as I understood it, is: how does he know this value of $q$, that is indeed larger than $p$, will suffice to produce the result of your last line. So where does the formula come from?
Comment: I know... Maybe this is it, but it still looks a bit artificial to me.  I mean: by the same logic, $p^2<2 \implies p < \frac{p+2}{1+p}$, $p<\frac{2+3p}{3+p}$, $p<\frac{2+p^3}{p+p^2}$  and a ton of other formulae. So why does this one work?
Comment: I'm still not sure, after reading your post, what the thought process could have been for this term. I can see that what you have written is true, but there's no exposition about the approach to choosing this term. I'm not sure whether I should open another question on this, or comment on those that are here, I'm doing the latter for now.
Answer: maybe you can see it the following way:
you are looking for a $\beta >0$ and rational such that $(p+\beta)^2 < 2$,
note that this means that necessarily $p+\beta < 2^{\frac{1}{2}}<2$ .
Now $(p+\beta)^2 < 2 \Leftrightarrow 2\beta p + \beta^2 < 2-p^2 \Leftrightarrow \beta< \frac{2-p^2}{p + p +\beta} $ but for any $\beta$ you are looking for, you have  $p+\beta <2$ and so $\frac{2-p^2}{p + 2}<\frac{2-p^2}{p + p +\beta}$. And so any $\beta \in ]0;\frac{2-p^2}{p + 2}]$ should be ok for what you want, you can therefore take $\beta = \frac{2-p^2}{p + 2}$.
Does it appears to you a little more natural now ?


Aplicativo android fecha assim que carrega (NoClassDefFoundError)

Question: Eu instalei o Android SDK tudo certinho, instalei os drivers USB do meu Motorola Moto G. Tá tudo certo, tanto que quando vou executar a aplicação diretamente do Eclipse, ele acha o meu dispositivo conectado. Depuração USB está habilitada.
Só que quando rodo a aplicação, e o Eclipse faz a instalação do .apk, o meu aparelho, ao abrir a aplicação, exibe instantaneamente "O My App parou".
Já tentei de tudo e não consigo fazer rodar. Quero rodar no meu aparelho por que é Android KitKat e porque o AVD é meio lento, às vezes.
O logcat exibe isso quando executo a aplicação no dispositivo:
04-28 22:27:07.680: W/dalvikvm(13905): VFY: unable to resolve static field 1630 (ActionBarWindow) in Landroid/support/v7/appcompat/R$styleable;
04-28 22:27:07.681: D/dalvikvm(13905): VFY: replacing opcode 0x62 at 0x0004
04-28 22:27:07.682: D/AndroidRuntime(13905): Shutting down VM
04-28 22:27:07.682: W/dalvikvm(13905): threadid=1: thread exiting with uncaught exception (group=0x41ef5d40)
04-28 22:27:07.684: E/AndroidRuntime(13905): FATAL EXCEPTION: main
04-28 22:27:07.684: E/AndroidRuntime(13905): Process: com.example.myfirstapp, PID: 13905
04-28 22:27:07.684: E/AndroidRuntime(13905): java.lang.NoClassDefFoundError: android.support.v7.appcompat.R$styleable
04-28 22:27:07.684: E/AndroidRuntime(13905):    at android.support.v7.app.ActionBarActivityDelegate.onCreate(ActionBarActivityDelegate.java:104)
04-28 22:27:07.684: E/AndroidRuntime(13905):    at android.support.v7.app.ActionBarActivityDelegateICS.onCreate(ActionBarActivityDelegateICS.java:57)
04-28 22:27:07.684: E/AndroidRuntime(13905):    at android.support.v7.app.ActionBarActivity.onCreate(ActionBarActivity.java:98)
04-28 22:27:07.684: E/AndroidRuntime(13905):    at com.example.myfirstapp.MainActivity.onCreate(MainActivity.java:18)
04-28 22:27:07.684: E/AndroidRuntime(13905):    at android.app.Activity.performCreate(Activity.java:5248)
04-28 22:27:07.684: E/AndroidRuntime(13905):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1110)
04-28 22:27:07.684: E/AndroidRuntime(13905):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2173)
04-28 22:27:07.684: E/AndroidRuntime(13905):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2269)
04-28 22:27:07.684: E/AndroidRuntime(13905):    at android.app.ActivityThread.access$800(ActivityThread.java:139)
04-28 22:27:07.684: E/AndroidRuntime(13905):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210)
04-28 22:27:07.684: E/AndroidRuntime(13905):    at android.os.Handler.dispatchMessage(Handler.java:102)
04-28 22:27:07.684: E/AndroidRuntime(13905):    at android.os.Looper.loop(Looper.java:136)
04-28 22:27:07.684: E/AndroidRuntime(13905):    at android.app.ActivityThread.main(ActivityThread.java:5102)
04-28 22:27:07.684: E/AndroidRuntime(13905):    at java.lang.reflect.Method.invokeNative(Native Method)
04-28 22:27:07.684: E/AndroidRuntime(13905):    at java.lang.reflect.Method.invoke(Method.java:515)
04-28 22:27:07.684: E/AndroidRuntime(13905):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
04-28 22:27:07.684: E/AndroidRuntime(13905):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
04-28 22:27:07.684: E/AndroidRuntime(13905):    at dalvik.system.NativeStart.main(Native Method)

Comment: E no emulador funciona bem?
Comment: Também não, @JorgeB.
Comment: Pelo que vi no stacktrace, ele precisa de um jar que está referenciado no BuildPath: appcompat_v7.jar. Só que ele tá referenciando esse cara e não tá achando.
Comment: Resolvi o problema @JorgeB. Eu adicionei no AndroidManifest.xml a seguinte linha: ``
Comment: Cria uma resposta com o que fizeste e daqui a dois dias podes aceita-la.
Comment: Já criei. Obrigado.
Answer: Resolvido o problema.
Adicionei no AndroidManifest.xml a linha
<library android:name="C:\dev\android\workspace\appcompat_v7\bin\appcompat_v7.jar" />

O aplicativo rodou com sucesso. :)
Comment: Uma referência no [SOEN](http://stackoverflow.com/questions/22992434/unable-to-run-androids-hello-world-in-ecplise)


Adding Java Objects to database

Question: For a university assignment I have been assigned I have a Prize object which contains either text, image, or video content. I would like to persist this information into a BLOB field within an Apache Derby database (which will be running on a low powered PDA). How can I add this data to the database?
Thanks in advance.
Answer: In this article Five Steps to Managing Unstructured Data with Derby
you can read how to do this.
It describes how to insert binary data into a column with the BLOB datatype in Apache Derby using JDBC.
Answer: I assume you'll be connecting via JDBC.  If so, simply write your SQL and look at the setBlob method of a PreparedStatement.  Should be pretty straightforward.
Answer: Serialization is the easy way to do it, however if possible you could make it look like a real database table with a structure containing id (bigint), datatype (smallint), creationdate (date) and data (blob) and specifically make the client code to save the object's data there. This way you could do searches like "get all video prizes created between January 1st 2008 and January 15th 2009" and it wouldn't break down old data if your class would change too much for the serialization to stop working.
This sort of solution would be easy to extend in the future too if there would be need for it; I understand this is a school assignment and such need most likely won't ever surface but if your teacher/professor knows his stuff, I bet he's willing to give an extra point or two for doing this excercise in this way since it takes a bit more time and shows that you can take the steps to prepare in advance for coping in the everchanging landscape of software development.
Answer: If you are using Netbeans (I assume Eclipse has similar functionality) you can setup your database schema and the create new Java entity classes from the database and it will generate the appropriate JPA classes for you.
http://hendrosteven.wordpress.com/2008/03/06/simple-jpa-application-with-netbeans/
This is nice as it allows you to focus on your code rather than the database glue code.
Answer: The best solution , is to use Derby, because it keep being a multi platform app developed via Java.

Adding Java Objects to database


New to TypeScript, Errors converting JS to TS learning as I go

Question: I'm converting an existing Reactjs project to typescript. I'm also learning TS as I go on this project. I am getting a few errors that I am not sure how to navigate and can't seem to find a good answer on Google.
One of my errors, I am pulling a useState boolean from my useContext into my protected route:

Property 'loggedIn' does not exist on type '{}'.

Protected Route:
import { Navigate } from "react-router-dom";
import { useAuthContext } from "../context/AuthContext";
import { ReactNode } from "react";

// type ProtectedRouteProps = {
//   children: ReactNode;
// };

export const ProtectedRoute = ({ children }: any) => {
  const { loggedIn } = useAuthContext();
  if (!loggedIn) {
    // user is not authenticated
    return <Navigate to="/" />;
  }
  return children;
};

My AuthContext:
import { useState, createContext, useContext, ReactNode } from "react";
import { useNavigate } from "react-router-dom";

const AuthContext = createContext({});

export function useAuthContext() {
  return useContext(AuthContext);
}
type AuthProviderProps = {
  children: ReactNode;
};

export function AuthProvider({ children }: AuthProviderProps) {
  const [loggedIn, setLoggedIn] = useState<boolean>(
    localStorage.getItem("loggedIn") === "true"
  );

  const [selectedDogs, setSelectedDogs] = useState<number[]>([]);
  const navigate = useNavigate();

  function setDogMatch(data: number[]) {
    setSelectedDogs(data);
    navigate("/dog-match");
  }

  return (
    <AuthContext.Provider
      value={{
        loggedIn,
        setLoggedIn,
        selectedDogs,
        setDogMatch,
      }}
    >
      {children}
    </AuthContext.Provider>
  );
}

Not sure what I am missing for that type and where it would need to be set if in my AuthContext or Protected Route.
I also created another error myself my SearchFilter.tsx. Error:

Parameter 'props' implicitly has an 'any' type.
Parameter 'data' implicitly has an 'any' type.

Here's my SearchFilter.tsx not sure what to do with that map type error. My SearchFilter.tsx takes in data from an API containing strings(dog breeds) and numbers(dog ids):
import Select from "react-select";

export default function SearchFilters(props) {
  const options =
    props.data &&
    props.data.map((data) => {
      return { value: data, label: data };
    });

  return (

{props.name}

      <Select options={options} isSearchable={true} {...props} />

  );
}

To expand further on Part 2: here is what is being passed into props for my SearchFilter.tsx:
<SearchFilters
            name="MIN AGE"
            data={Age_Menu}
            value={[minAge]}
            onChange={setMinAge}
          />
          <SearchFilters
            name="MAX AGE"
            data={Age_Menu}
            value={[maxAge]}
            onChange={setMaxAge}
          />
          {ageAlert && (
            <Alert
              variant="danger"
              onClose={() => setAgeAlert(false)}
              dismissible
            >

Maximum Age Cannot be less than Minimum Age

            </Alert>
          )}
          <SearchFilters
            name="SORT BY"
            options={Sort}
            value={[selectedSort]}
            onChange={setSelectedSort}
          />

          <>
            <SearchFilters
              name="BREEDS"
              data={dogBreeds}
              placeholder="All Breeds"
              value={selectedBreeds}
              onChange={handleSelectedBreeds}
              isMulti
            />
          </>
          <>
            <SearchFilters
              name="STATES"
              data={getStates}
              placeholder="All States"
              value={selectedStates}
              onChange={handleSelectedStates}
              isMulti
            />
          </>

Answer:
Currently the type of the value the context holds is being inferred from the default value given to createContext, which does not have a loggedIn field.

You could instead set the type explicitly through the generic parameter to createContext, e.g. createContext<T>(defaultVal). Alternatively, pass a default value that contains all the type information.
const AuthContext = createContext({
    loggedIn: false,
    setLoggedIn: (val: boolean) => {},
    selectedDogs: [] as number[],
    setDogMatch: (val: number[]) => {}
});

It seems like props.data should be an array, but you have typed it as either a string or a number.

type Props = {
  data: (string | number)[]
  name: string
};

const options = props.data?.map(data => ({ value: data, label: data }));

Comment: So part 1 of your response was able to work with some adjusting on my end. part 2. ended up throwing more errors. I am not sure if I had my types right to begin with when I set it, I wasnt sure if I was doing that one correct. I did edit my question so you could see how it initially was before I put any type.
Comment: @NewBeeee What is the error after applying the second part of the answer?
Comment: Never mind  you were right, I was just trying to put props into my types Props to and that was throwing the error. went from 24 to 30 more errors to fix but only on two big pages to go  lol then im done transitioning
Comment: if i have a passed a component a function and accessing it as a props, how do you set types for functions?
Comment: @NewBeeee You can set the type like `{propName(arg: ArgType): returnType}`.
Comment: Here is a function being passed a prop:

` const handlePrevPage = () => {
    if (currentPage > 1) {
      if (currentPage === startPageIndex) {
        setStartPageIndex(currentPage - Max_Page);
        setEndPageIndex(currentPage - 1);
      }
      props.prevPage();  ** This is what needs a type set**
      setCurrentPage((curr) => curr - 1);
    }
  };`

the prevPage() is what it says needs a type set.
Comment: @NewBeeee If it takes no arguments and doesn't return anything, then it can be `{prevPage(): void}`
Comment: `Property 'prevPage' does not exist on type 'Props'.` Thats the Error it gives.

so I would do something like this  types Props ={prevPage(): void } ?
Comment: @NewBeeee Yes, that is what I was referring to.
Comment: that ended up throwing `This expression is not callable.
  Type 'void' has no call signatures.`
Comment: @NewBeeee Can't reproduce. Works fine [here](https://www.typescriptlang.org/play?#code/C4TwDgpgBACgTgezAZygXigbzHCA3GAQwHMIAKASgC4o8EBLAEwF8BuAKHoFswE5goAKiiFUAJQiEAxgIBmiLlADkuacCUd2sgK4A7GfQS6oAWRABhBDzI4kyGvDsUs7KG6i2UAOhz4ipSg53KFxgbThjAB5GejwAPgBlK2hgCAAPYC8syIB6GPiOZnZ2SLNLHg9cAhIINExKdDioKSNkBAAbCC92hGIyJV9q0mbCds7GJQpmHLiOIA).
Comment: hmm okay i see what I had different. could you show me this one that you mentioned `{propName(arg: ArgType): returnType}.`
Comment: @NewBeeee That's just specifying the types of the parameters. It works the same way as typing any other value.
Comment: @NewBeeee If you have more issues, it is best to ask a new question instead of using the comments.
Answer: 1. Property 'loggedIn' does not exist on type '{}'.
export function useAuthContext() {
  return <{ loggedIn: any }>useContext(AuthContext);
}

2. Property 'map' does not exist on type 'string | number'. Property 'map' does not exist on type 'string'.
You're calling .map() on props.data, which is of type string | number. .map() is only callable on objects which are iterable. Your SearchFilter.tsx is unclear about the exact type, so I'm only guessing.
type Props = {
  [_: string | number]: any
}

This will make this error go away, but may introduce another error somewhere else.


When I should create a new permission in my custom module?

Question: Once I create a custom module where I'll have some kind of administrative tasks like configurations should I create a new permission or just use any available permission?
This question comes to my mind because when we create a custom module for the community we can imagine how this module will be used, but maybe in some scenarios some admins need to give specific permission to others users to configure the site and in this case if we have specific permission for this tasks made this work is very easy, if not this admins need to create a new custom module to handle this situation.
But in the other hand if we create one permission for each administrative task in our custom module maybe we are overloading the site with permission that are rarely used.
When I should create a new permission in my custom module?
Note: I'm not trying to create primarily opinion-based question here, if some user feel this, please help me to improve the question.
Comment: If access is a concern, my rule of thumb is yes, create permissions.
Comment: @Kevin can you post your answer with some examples please?
Answer: If you are creating a custom module for a client-only (or yourself), then you can do whatever is appropriate for the situation.
When creating a contrib module, you have to consider that you probably don't know all of the potential uses.  In general, I would make your own permission; typically as a project reviewer, this is something I point out as part of peer review.
I do not see too-many-permissions as a problem.  In fact, I see it as a benefit.  When I build sites for clients, I try to build out roles that can stack (users can have multiple roles) and roles have the minimum permissions needed to meet the needs of that role.
One common complaint about Drupal is that it is too complicated.  By using roles and permissions, you can limit what users can do, and minimize the complexity to exactly what they need to do (no more, no less).  When you gang up tasks into a single permission, you may give the option to people to do things that they may not need or want to do.
Another way to look at this, is that permissions can be used as a security method to limit what uses can do.  They can also be used by an organization to limit what users need to do as part of their job function.


Update Node JS on Ubuntu

Question: Ubuntu 20.04.3 LTS
Version 14.0.0 is installed, node -v always shows it. Although in the list of programs Node appears as 16.13.1. I can manually change the version via nvm, but this is very inconvenient. How to make sure that there is no ghost on my computer about version 14?
Answer: You can use n module from npm in order to upgrade node
sudo npm cache clean -f
sudo npm install -g n
sudo n stable

to update to the latest version use
sudo n latest

Explained
Comment: `antonz@comp:~$ node -v`
`v14.0.0`
`antonz@comp:~$ sudo npm cache clean -f`
`[sudo] password for antonz: `
`npm WARN using --force Recommended protections disabled.`
`antonz@comp:~$ sudo npm install -g n`

`added 1 package, and audited 2 packages in 2s`

`found 0 vulnerabilities`
`antonz@comp:~$ sudo n stable`
   `installed : v16.13.1 (with npm 8.1.2)`
`antonz@comp:~$ node -v`
`v14.0.0`
Comment: 14.0.0 again..(((
Answer: I solved this problem
rm -rf ~/.nvm
nvm install 16

Update Node JS on Ubuntu


Editar dados em modal preenchedo com dados do banco php

Question: Tenho um formulário que faz a edição dos dados do banco com base no id recebido.

/*
função para atualizar os dados quando clicado em submit
*/

$('.editfoto').submit(function () {
        var form = $(this);
        var dados = new FormData($(this)[0]);
        $("#btnEdit").prop("disabled", true);

        id = $(this).data("idedit");

        $.ajax({
            url: 'editafoto.php?id=' + id,
            cache: false,
            contentType: false,
            processData: false,
            data: dados,
            type: 'GET'
        }).done(function (data) {
            fetchUser();
            alert("Dados Atualizados com Sucesso");
            console.log("STATUS : ", data);
            $("#btnEdit").prop("disabled", false);
            $('#modalEdit').modal('hide');
            $('.editfoto')[0].reset();

        }).fail(function (jqXHR, textStatus) {
            console.log("Request failed: " + textStatus);
            $("#btnEdit").prop("disabled", false);
        });
        return false;

    });

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>

 <a id="editfoto" data-idedit="<?php echo $row['idfoto']; ?>">

Editar Foto

                <button type="button" class="close" data-dismiss="modal" aria-label="Fechar">
                    ×
                </button>

                <form class="editfoto" method="POST" enctype="multipart/form-data">
                    <input type="hidden" id="idfoto" name="idfoto" value="<?php echo $ftvi->getIdfoto(); ?>" />

                            Data Vísita

                            <input type="text" name="dtvisita" id="dtvisita" required autocomplete="off" class="form-control  form-control-sm form-group small" value="<?php echo $ultil->formataData($ftvi->getIdfoto()); ?>" />

                            Visíta

                            <input type="text" name="idvisita" id="idvisita" readonly class="form-control  form-control-sm form-group small" value="<?php echo $_SESSION['id']; ?>" />

                            Porcentagem Andamento

                            <input type="range" name="percentandamento" id="percentandamento" required min="1" max="100" value="<?php echo $ftvi->getPercentandamento(); ?>" class="form-control-range slider" oninput="disp.value = percentandamento.value">
                            <output  id="disp"></output>

                            Foto

                            <input type="file" name="caminhofoto" id="caminhofoto" required class="form-control-file form-control-sm form-group small" accept="image/png,image/jpg" value="<?php echo $ftvi->getCaminhofoto(); ?>" />

                            Descrição Foto

                            <textarea name="descricaofoto" id="descricaofoto" cols="25" rows="3" class="form-control  form-control-sm form-group small" ><?php echo $ftvi->getDescricaofoto(); ?></textarea>

                <button type="button" class="btn btn-secondary" data-dismiss="modal">Fechar</button>
                <button type="submit" id="btnEdit" class="btn btn-primary">Salvar</button>

            </form>

O problema é que eu não estou conseguindo passar as informações do PHP para o Modal.
para que ele carregue as informações para ser editada.
Encontrei um exemplo que usa data-atributos, porém se eu for colocar todos data-atributos no meu  link de chamada ele vai ficar enorme.
Já tem um tempo que tento resolver esse problema e nada.
Tenho a listagem e ao clicar no icon/link editar ele abra um modal como esse do adicina, só que com os dados carregados do banco.
Um print:
Comment: Você quer puxar os dados da sua página PHP para a JS correto? Nessa situação a única situação 'correta' para se aplicar é realizar uma requisição via JS para a página em PHP. Não tem como o servidor enviar informações para o front sem uma requisição, a menos que você utilize WebSockets.
Answer: Percebi um erro de sintaxe no seu código que pode não estar permitindo você encontrar o id correto do que quer editar:
url: 'editafoto.php=id' + id,

Onde deveria na verdade passar:
url: 'editafoto.php?id=' + id,

a "?" é para sinalizar que a partir deste ponto inicia-se a sua "Query String", e você diz que há um "parâmetro" chamado "id" cujo valor "=" é o conteúdo da variável "id".
Mas você também já tem um campo do tipo HIDDEN no formulário como o nome "idfoto" que vai passar esse valor, então, você realmente precisa montar essa query string na url da página que está chamando?
Tenha muito cuidado com relação à segurança, pois, qualquer usuário poderá alterar esse "ID" e submeter o formulário, alterando então os dados de outro registro, que pode não ser o adequado.
Vale também aí entender que se você está pretendendo carregar uma lista de fotos para abrir cada uma em um modal, dessa forma você terá que carregar todos os dados de todas as fotos da lista na tela para abrir uma por uma, ou seja, seu retorno html poderá ficar enorme. uma maneira mais econômica talves seria carregar a lista e ao clicar em uma foto, carregar os dados a serem editados por meio de ajax.
Talvez eu não tenha respondido sua questão, mas preferi relacionar aqui alguns alertas que poderão te dar alguma orientação de por onde seguir.
Comment: Exatamente isso que quero fazer.

"uma maneira mais econômica talves seria carregar a lista e ao clicar em uma foto, carregar os dados a serem editados por meio de ajax."

Eu tenho a listagem exibida na tela, ao clicar no botão editar só preciso que abra o modal com os dados carregados.
Vou postar um print do insert na pergunta.


What's the log probability of a Gaussian whose mean is conditioned on another Gaussian?

Question: Define a multi-variate Gaussian as $f(\pmb y|\pmb x)=\mathcal N(\pmb x,.5)$, where $\pmb x$ is a sample from a pre-defined multi-variate Gaussian function $g(\pmb x)=\mathcal N(\pmb \mu, \pmb \Sigma)$. How should I compute the log probability of $\pmb y\sim\mathcal f(\pmb y|\pmb x)$?
I can think of the following answers but I'm not so sure if I take them right

For a given $\pmb x$, it's $\log f(\pmb y|\pmb x)$
Otherwise, it's $\int \log \mathcal f(\pmb y|\pmb x)+\log g(\pmb x)d\pmb x$
Comment: It's not entirely clear what you mean by "the log probability of $\mathbf y\sim f(\mathbf y\mid\mathbf x)$". If we take this literally, the answer would be trivial, since you've specified $f(\mathbf y\mid\mathbf x)$. Also, what do you mean by "for a given $\mathbf x$, it's $\log f(\mathbf y)$; otherwise..."? $f(\mathbf y\mid \mathbf x)$ is by definition "for a given $\mathbf x$". I get the impression that there's some conceptual confusion here. Is it perhaps the logarithm of $f(\mathbf y)$ that you're actually interested in?
Comment: Sorry for that I misuse some mathematical notations. What I tried to express was that if we compute the log probability of $\pmb y$ for a given $\pmb x$, then it's just $\log f(\pmb y|\pmb x)$. If there is no $\pmb x$ is given, then its the otherwise part. I think the otherwise part is the logarithm of $f(\pmb y)$ you mentioned at last.
Answer: I'm answering the question as clarified in the comments.
$\mathbf y$ is the sum of the two multivariate Gaussian variables with distributions $\mathcal N(\mathbf\mu,\mathbf\Sigma)$, and $\mathcal N(0,0.5)$ (where I presume that by $0.5$ you mean $0.5\cdot\mathbf 1$). The sum of the two multivariate Gaussian variables is again a multivariate Gaussian variable, with mean the sum of the means and variance the sum of the variances (see e.g. this question). So $\mathbf y\sim\mathcal N(\mathbf \mu,\mathbf\Sigma+0.5\cdot\mathbf1)$.
Comment: Hi, thanks. I can make sense of what you said and you were definitely right. However, it does not seem to be consistent with the otherwise part I said. May I ask where am I wrong? Because my real question actually involves applying another intermediate tanh to x before using it as the mean of the next Gaussian
Comment: @Maybe: I don't know what you're referrring to with "the other part I said".
Comment: Hi, @joriki. That is $\log f(\pmb y)=\int\log f(\pmb y|\pmb x)+\log g(\pmb x)d\pmb x$.
Comment: @Maybe: Ah, I see, sorry, I should have commented on that. That's wrong. It's

$$
f(\mathbf y) = \int f(\mathbf y\mid\mathbf x)g(\mathbf x)\mathrm d\mathbf x\;,
$$

and you can't apply this to the logarithms instead; you'll get a different (and thus wrong) result.
Comment: Hi, @joriki. Is there any way to compute $f(\pmb y)$ without integration if I further apply another itermediate $\tanh$ to $\pmb x$ before using it as the mean of the next Gaussian.
Comment: @Maybe: I doubt it. I don't see one.
Comment: Yeah, I see. Thanks


Lista como entrada de funções

Question: Em Python 3.7 itens de uma lista podem ser argumentos de uma função?
def media(x,y,z):  lista = [7,8,9]

Comment: Possível duplicata de [Qual significado do operador ( \* ) asterisco?](https://pt.stackoverflow.com/questions/162956/qual-significado-do-operador-asterisco)
Answer: Bom, este código não parece fazer muito sentido, mas imagino que seja isto que deseja:
def media(x, y, z):
    return (x + y + z) // 3
lista = [7, 8, 9]
media(*lista)

Note que este exemplo em específico não faz tanto sentido, o ideal em caso de média já é receber uma lista mesmo e não um número limitado de argumentos. Isto daria erro:
print(media(*[8, 9]))
print(media(*[6, 7, 8, 9]))

Isto parece mais com o que deseja:
def media(*lista):
    soma = 0
    for i in lista:
        soma += i
    return soma // len(lista)
lista = [7, 8, 9]
print(media(*lista))

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Comment: Muito obrigado!. Faz parte de um exercício que estou praticando. Coloquei apenas um pedaço, o qual me tirou o sono, para seguir com os demais.
Comment: No código apresentado da função media o uso o * para o parâmetro lista pode ser omitido. Caso feito isso, na última linha, quando é feito a impressão da média, não se deve usar o * também.
Comment: @Pa me parece não ser verdade, eu teste e deu erro.

Lista como entrada de funções


For each loop in vb.net

Question: How do I use for loop in vb.net something like
dim start as integer
Dim customers as New List(Of Customers)

Customers=dataAcess.GetCustomers()

For each start=500 in  Customers.count
  'Do something here'
Next

I want to process some data for each 500 customers.. Please help
Comment: Could you clarify what you mean by "each 500 customers"?
Comment: don't create a "new" list of customers if you're just going to replace it on the next line.
Comment: Do you mean you want the loop to iterate on the List of Customers in chunks of 500?
Answer: First of all, don't create a New list of customers if you're just going to assign a different list to the variable on the next line.  That's kinda dumb. Do it like this:
Dim customers As List(Of Customer) = dataAccess.GetCustomers()

Then, for the loop you need a plain For loop rather than a For Each. Don't forget to stop before the count of items, since for .Net the first index is 0 instead of 1:
For i As Integer = 500 To Customers.Count -1
    ' Do something with Customers(i) here
Next i

If you're using Visual Studio 2008 or later you could also write it like this:
For Each item As Customer in  Customers.Skip(500)
   ' Do something with "item" here
Next

Answer: Try the following
For Each current In customers
    ' Do something here
    Console.WriteLine(current.Name)
Next

Answer: 'This will start at 500 and process to the end....
for start as integer = 500 to Customers.Count

'process customer....
customer = Customers(start)

Next

To iterate the entire list:
for each cust as Customer in Customers

Next

One note.... VB is case insensitive and your sample code seems to use lower case and upper case customers
Comment: When I try this for start as integer = 500 to Customer.Count
I am getting an error saying customer cannot be converted to int
Answer: Something like this:-
Dim customers as New List(Of Customer)

Customers=dataAcess.GetCustomers()

For Each customer AS Customer in  Customers
   '' // do something with the customer object
Next

Edit
Sounds like you want to select 500 of N items or perhaps the next 500.  You could use the LINQ extension methods .Take and/or .Skip to achieve this.  Use ToList then to create your list.  E.g.:-
Dim customers as List(Of Customer)
customers = dataAccess.GetCustomers().Skip(500).Take(500).ToList()

If all you want to do enum through the customers then you could dispense with ToList().
Comment: I want to do it for each 500 customers.
Comment: Do you mean you want to do it for every 500th customer, perhaps? It is still unclear what you are trying to accomplish.
Answer: You can either try:
    For i As Integer = 500 To (customers.Count -1)
        ''do something
    Next

Or
    For i As Integer = 0 To (customers.Count - 1) step 500
        ''do something
    Next

Answer: Dim start as Integer
Dim customers as New List(Of Customers)

Customers = dataAcess.GetCustomers()

For i as Integer = start to Customers.count Step 500
    Debug.Print Customers(i).someProperty
    Do something here
Next i

I think you need to use the Customer index and Step in 500s. This will only process customer(start), Customer(start+500), Customer(start+1000) etc, not all the customers. Is that what you intend?
Answer: I'm not exactly sure what you're trying to do, but maybe you could try this:
Dim count As Integer = 0
Const MAX_CUSTOMERS As Integer = 500
Dim customers As List(Of Customers) = dataAcess.GetCustomers()

For Each c As Customer In customers
    'do stuff here'
    c.Name = "Billy"
    count+=1

    If count = MAX_CUSTOMERS Then Exit For
Next

It's not elegant by any means, but it makes sense and it will work.
Answer: Obviously, there is no shortage of variety.  I don't recognize your "DataAcess" object type, but if you can pull that table in as a Recordset (i.e. a SQL table) then try this. (Don't forget to return the recordset when your done)
Option Explicit

Dim Customers As Recordset
Set Customers=currentdb.openrecordset("???")

While Customers.EOF=False
   'do stuff here using the recordset object
   'i.e. Customers.Fields("Name")="Billy"
   Customers.MoveNext
Wend

For each loop in vb.net


Manually Adding JAR files in Maven or Spring Boot project

Question: I am developing a Spring Boot project on Office LAPTOP by using Eclipse.
Due to the firewall restriction the Springframework jar files cannot be downloaded into when I update the pom.xml.
Is there any way I can add the required Spring Boot Framework jar files manually ?
For example can I copy the entire .m2/repository folder from another system that is connected to internet and had automatically downloaded all the jar files ?
Or what is the best approach to load the .jar file in Offline mode (without Internet connectivity)
Comment: Option1: There are always proxies used in Organizations. Ask someone about that and add the relevant information in settings.xml
Option2: Manually copy the JARS in M2. It will not fail. If find in m2.  it looks the dependencies in local m2 first.
Answer: You can use
mvn dependency:go-offline

on a computer with internet access.
Then copy the .m2/repository to your office computer.
Maven also have a flag -o to tell maven that it must run offline. For example:
mvn -o verify

Please find more information about the offline mode here. https://books.sonatype.com/mvnref-book/reference/running-sect-options.html#running-sect-offline-option


Entry systems for math that are simpler than LaTeX

Question: This may belong in Meta.  Please don't say Software Recommendations.  I have yet to receive a meaningful recommendation from that group due to a paucity of other users.
I work with kids whose handwriting is their own worst enemy. (Typically junior and senior high school.  Most already are 10-20 wpm typists)
I'd like to find a way for them to enter algebra  that is keyboard centric (not endlessly dragging and dropping, and nudging symbols) but is more or less WYSIWYG. Unusual symbols may end up be drag and drop, but I would like to be able to, say, derive the quadratic formula without having to recourse to drag and drop.
The editor should make it easy to edit.  I've run into a couple that were 'write only' systems where you couldn't change something.  Much like doing math with a quill pen and india ink.
It needs to be close to as fast as writing by hand for someone who is a touch typist.  It should support cut and paste for bring down parts of an equation that are unchanged.
The closest I've come is FrameMaker, which used ^ to start a superscript _ to start a subscript, and space bounced you out one level.I don't remember the rest.  I no longer have FM so it's moot.
An example of an awful system is the Microsoft equation editor, at least as of 15 years ago.
I would expect such a system to use LaTex under the hood, but it doesn't have to.  A fringe benefit would be the LaTex of the current equation showing up in a sub window, and being able to edit in either.
The symbol set doesn't have to be vast.  Being able to readily handle 2 levels of nested brackets, Equations with fractions.
I'd like to have a way for them to work out problems that don't proceed linearly down the page.  E.g. a way to do polynomial long division.
Small matrices.   First course in calculus.
In essence I'm looking for something that does for math what markdown does for writing html.
Anyone know of such a system?
Moderators: I couln't find a tag Latex or interactive math editor.  Adjust tags.  This likely means this is in the wrong SE.  Please advise.
Comment: lyx.org This is WYSIWYG tex. It looks ugly, but works.
Comment: Something which you should emphasize about your question, "*I work with* **kids**" which implies to me that the library of available symbols does not need to be large at all.  One of the main strengths of $\LaTeX$ is that you have tens of thousands of symbols available to you with the ability to define more, which is surely overkill for children (*but if you learn how to use the symbols you use most often, it really makes little difference*).  You should include what types of symbols you would want access to.
Comment: As for whether or not you're in the wrong SE... this question might get better results at [Tex.StackExchange](https://tex.stackexchange.com/).
Comment: Wolfram Language Notebooks?
Comment: What age are the chidren you teach ?
Comment: I'm not sure if this is what you are looking for, but there is "TeXmacs".
Answer: You mentioned Microsoft as of 15 years ago. I just opened up Word 2016, and the equation editor there is probably about the level you are after. For example, typing the following input:
<code>y >= 2 + 3 sin(x^3)
</code>
produced $$y \geq 2 + 3 \sin(x^3)$$ which is considerably nicer to input than anything LaTeX based.
Answer: A couple solutions come to mind, depending the age of the kids.  Some hand writing software now does some degree of optional smoothing and clean up as you write with the pen.  Microsoft's One-Note worked really well for me writing lecture notes.  You can swap between typing or writing with a pen or finger and you can optionally have it smooth out or guess what text you intend.
Another option is to use wiki products, just like this.  They have very simple interfaces for math.  Example: read this on the screen $f(x)=x^2$, or $\int x^2 dx = \frac{x^3}{3}$ then hit "edit" and see what it was I actually typed.  The viewer cleaned it up.
The engine behind that is MathJax.  It would be my strongest suggestion.
Comment: Yes I often use the excellent OCR capabilities of One-Note.
Comment: Thanks for the referral to one note. -- I looked at that, and for kids it would be incredibly distracting.  They are still shaky on what $(x+1)^2$ means.


Como Unir Duas Tabelas com Distribuição Exata de Dados no SQL Server?

Question: Olá! Estou trabalhando com SQL Server.
Preciso unir duas tabelas com base na coluna "Ctrl". A primeira tabela, "Cad_Clients", contém informações de clientes, enquanto a segunda, "Cad_Colors", possui a descrição das informações. A condição para uni-las é que o valor de "Ctrl" seja o mesmo em ambas as tabelas. No entanto, a distribuição precisa ser exata, ou seja, não podem ocorrer duplicatas.
Imagine que eu crie um laço 'for' na tabela ´Cad_Colors´. Em cada iteração, adiciono um registro da tabela à 'Cad_Clients', desde que o valor 'Ctrl' corresponda. Após, excluo esse registro de ´Cad_Colors´. Se a tabela em loop ficar vazia ou o laço chegar ao fim, significa que distribuí o máximo possível dos registros. É apenas isso, mas não quero usar um laço no banco; estou confiante de que, discutindo aqui, podemos obter um resultado muito mais conciso.

Representação visual do problema: clique aqui

Cad_Clients
| idPerson | Person         | Ctrl  |
|----------|----------------|-------|
| 1        | John           | 100   |
| 2        | Sarah          | 101   |
| 3        | Michael        | 102   |
| 4        | Emily          | 103   |
| 5        | William        | 104   |
| 6        | Olivia         | 105   |
| 7        | James          | 100   |
| 8        | Emma           | 101   |
| 9        | Benjamin       | 102   |
| 10       | Sophia         | 103   |
| 11       | Samuel         | 104   |
| 12       | Ava            | 105   |
| 13       | Joseph         | 100   |

Cad_Colors
| Ctrl | Color    | idColor |
|------|----------|---------|
| 100  | Red      | 1       |
| 104  | Blue     | 2       |
| 105  | Green    | 3       |
| 103  | Yellow   | 4       |
| 104  | Purple   | 5       |
| 105  | Red      | 6       |

União das duas tabelas:
| idPerson | Person  | Ctrl | Color  |
|----------|---------|------|--------|
| 1        | John    | 100  | Red    |
| 4        | Emily   | 103  | Yellow |
| 5        | William | 104  | Blue   |
| 6        | Olivia  | 105  | Green  |
| 11       | Samuel  | 104  | Purple |
| 12       | Ava     | 105  | Red    |

Algumas tentativas frustradas:
INSERT INTO @Tmp
SELECT ccl.idPerson, ccl.Person, ccl.Ctrl,
(SELECT TOP 1 cco.idColor FROM Cad_Colors cco WHERE cco.Ctrl = ccl.Ctrl AND cco.idColor NOT IN(SELECT idColor FROM @Tmp))
FROM Cad_Clients ccl

INSERT INTO @Tmp
SELECT ccl.idPerson, ccl.Person, ccl.Ctrl, cco.idColor, cco.Color
FROM Cad_Clients ccl
JOIN (SELECT TOP 1 cco.* FROM Cad_Colors cco WHERE cco.idColor NOT IN(SELECT idColor FROM @Tmp)) cco ON cco.Ctrl = ccl.Ctrl

INSERT INTO @Tmp
SELECT ccl.idPerson, ccl.Person, ccl.Ctrl, cco.idColor, cco.Color
FROM Cad_Clients ccl
JOIN Cad_Colors cco ON cco.Ctrl = ccl.Ctrl
WHERE NOT EXISTS (SELECT 1 FROM @Tmp WHERE Ctrl = cco.Ctrl)

MERGE INTO Cad_Clients AS target
USING Cad_Colors AS source
ON target.Ctrl = source.Ctrl
WHEN MATCHED THEN
UPDATE SET target.idPerson = target.idPerson
OUTPUT inserted.idPerson, inserted.Person, inserted.Ctrl, inserted.idColor, inserted.Color INTO @tmp;

Ajuda para criar os cenários
CREATE TABLE Cad_Clients( [idPerson] [int] IDENTITY(1,1) NOT NULL, [Person] [varchar](60) NULL, [Ctrl] [int] NULL );
CREATE TABLE Cad_Colors( [Ctrl] [int] NULL, [Color] [varchar](60) NULL, [idColor] [int] IDENTITY(1,1) NOT NULL );
INSERT INTO Cad_Clients (Person, Ctrl) VALUES ('John',100), ('Sarah',101), ('Michael',102), ('Emily',103), ('William',104), ('Olivia',105), ('James',100), ('Emma',101), ('Benjamin',102), ('Sophia',103), ('Samuel',104), ('Ava',105), ('Joseph',100);
INSERT INTO Cad_Colors (Ctrl, Color) VALUES (100, 'Red'), (104, 'Blue'), (105, 'Green'), (103, 'Yellow'), (104, 'Purple'), (105, 'Red');
DECLARE @Tmp TABLE( idPerson INT, Person VARCHAR(60), Ctrl INT, idColor INT /*Color VARCHAR(60)*/ );

Comment: Sem problemas! Consegui encontrar uma solução na gringa. Geralmente disparo em vários fóruns para receber ajuda  De toda forma, agradeço pelo seu tempo, de verdade. Link da resolução: https://stackoverflow.com/questions/77412913/merge-two-tables-with-exact-data-distribution/77413037?noredirect=1#comment136478853_77413037
Comment: Qual seria o critério de "exclusão" p.ex. Jonh e James com 100 ? Não sei se entendi o problema.
Comment: Na tabela "Cad_Colors" eu só tenho um Ctrl 100, certo?  No momento que adicionei esse registro para John, não ha mais registros do tipo "Ctrl 100" para serem distribuídos. Imagine que o IdColor deve ser único em Cad_Clients.
Comment: Para solucão via sql tentou um subselect com MIN. ? https://pt.stackoverflow.com/questions/481479/subconsulta-com-min-e-max-juntos
Comment: Não entendi como "MIN" e "MAX" se aplicariam aqui.
Comment: Eu não devo ter entendido o problema então.
Answer: Nesse cenário, você cria um contador para cada pessoa agrupada por 'Ctrl' usando a função ROW_NUMBER() OVER (partição por ctrl, ordenado por idperson). O mesmo procedimento é realizado para as cores e, em seguida, os resultados são combinados. Em outras palavras, você cria códigos de associação exclusivos que obedecem as condição de associação.
SELECT
    p.idPerson, p.Person, p.Ctrl, c.Color
FROM
    (SELECT  *,   ROW_NUMBER() OVER(partition BY ctrl ORDER BY idperson) AS sort FROM Cad_Clients) p
    INNER JOIN (SELECT  *, ROW_NUMBER() OVER(partition BY ctrl ORDER BY idcolor) AS sort FROM Cad_Colors) c ON  c.Ctrl = p.Ctrl AND c.sort = p.sort

Comment: Como está escrito atualmente, sua resposta não é clara. Por favor, pode [edit] para adicionar mais detalhes, que ajudarão outras pessoas a entender como isso resolve a pergunta feita. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).


How does the Digitech Freqout pedal work?

Question:
The DigiTech FreqOut Natural Feedback Creator allows you to get sweet, natural feedback at any volume, with or without distortion. The FreqOut is perfect for situations where volume must be controlled like in the studio, with in ear monitors, or low-volume performance and practice. However, the FreqOut can also be used at gig volume to focus out-of-control feedback on a preferred harmonic at any stage position.

According to musicradar, it uses a "cunning inversion of dbx's feedback-suppression technology". Could anyone explain what that means? Does it actually sustain the vibration of strings? How do you compare it to the Boss FB-2?
Answer: dbx's feedback suppression technology analyzes the audio that is fed through and looks for resonant frequencies that ring on longer and/or have higher average level than the other frequencies present. Once the algorithm has found a resonant frequency, it applies a digital notch filter to reduce the amplitude of the frequency to prevent feedback.
All you have to do is replace the words "reduce" and "prevent" in the previous paragraph with "increase" and "encourage" to see how the dbx algorithm could be inverted to actually create feedback.
It's not clear to me exactly how this works with in-ear monitors, but one way to do that would be that the notch filter, when in boost mode (instead of cut mode as used in dbx feedback elimination), could easily be made to self-oscillate and therefore actually synthesize the feedback frequency, meaning you can get feedback that naturally follows the guitar signal without needing any kind of acoustic signal path.
From their marketing material:

The DigiTech FreqOut pedal uses pitch detection technology to constantly monitor the harmonic content of your guitar signal.

If the guitar signal completely dies away, the feedback stops. Note that guitar signals persist on the electrical level longer than they are audible in some situations. So you might not be able to hear the guitar even if there's still enough level left for the FreqOut to keep operating. You just have to hold the notes on the guitar as long as possible.
When bending on the guitar, the strings move across the surface of the fret, so just bending strings makes them vibrate a little and maintains the note. In fact, one way to sustain a note on the guitar is to use vibrato, because the constant rubbing of the string by the fret acts like a very quiet violin bow to keep the note going. With the FreqOut, this vibrato sustain would be enhanced.
Regarding the Boss FB-2, that seems to require an amp to really create feedback. Their marketing says:

Advanced Feedback function provides smooth and natural amp feedback

So it's almost certainly boosting frequencies in a way similar to the FreqOut, but without the semi-synthesis aspect of it.
Comment: By "naturally follows the guitar signal", you mean sending feedback signal to the pickups?
Comment: @qed No. The only way this pedal could send a signal to the pickups is via a speaker pushing air that causes the body of the guitar to resonate, which is the normal mechanism for feedback which this pedal enhances. I'm talking about the pedal following the pickups, not the pickups following the pedal. The analysis process is the common element that "listens" to and reacts to the input signal. That is how this pedal follows the natural guitar tone. That enables it to create and enhance frequencies that are already present in the signal, as opposed to making random frequencies that don't work.
Comment: Ok. But the guitar signal has a short lifespan, how could the pedal create an infinite sustain by following that?
Comment: And how could the pedal react to string bending over a long duration?
Comment: @qed It just holds the boost filter after the original signal is gone. It knows when to drop the filter because other frequencies appear which change the response of the algorithm. Notes and frequencies created by bent strings are just other notes and frequencies just like those created by unbent strings.
Comment: @qed Notice that at no point during the demo video is the pedal making feedback while the guitar is not making any sound. The pedal doesn't create feedback from nothing. It follows the sound coming from the guitar.
Comment: @ToddWilcox _actually_, assuming the guitar is passive, it _is_ possible to send a signal back to the pickup and in principle also to excite string vibrations this way... but in practice, this won't give anywhere near as well-controllable feedback as acoustic speaker feedback. I've modified a guitar to use one of the PUs as an infinite-sustain exciter à la Fernandes Sustainer, but it only works because the other pickup still works as, well, an ordinary pickup. The stupidly high impedance of most guitar pickups is also a hurdle, requiring a big voltage to output decent power.
Comment: I don't like this answer. I don't believe the FreqOut is just a fancy compressor. There has to be feedback. And since it's not a requirement for you to turn up the volume, acoustic or magnetic feedback coming from your amp clearly is not an option. That leave the only possibility being that the pedal is actually sending a signal back to the pickup. I've heard people say that the FreqOut can't create infinite sustain, but I suspect these people never actually used it and are simply posting conjecture based on false assumptions on how the pedal works.
Comment: Even if the FreqOut is incapable of infinite sustain, the is another pedal, the BOSS FB-2 which **IS** confirmed to create infinite sustain, again with no requirements from your amp. So again, the pedal MUST be sending a driving signal back through the pickups to resonate the strings somehow.