What interpretations exists for the singleton of the singleton of the empty set $\{\{\varnothing\}\}$ and its singleton $\{\{\{\varnothing\}\}\}$?

Question: What I know

I know from Peano's axioms that the empty set is equivalent to the natural number $0$ and that the singleton of the empty set is equivalent to the natural number $1$. ( http://www.proofwiki.org/wiki/Peano%27s_Axioms_Uniquely_Define_Natural_Numbers , http://www.proofwiki.org/wiki/Axiom:Peano%27s_Axioms)
I know from Kuratowski that the set $\{\{A\}\}$ is equivalent to the ordered pair $\langle A,A\rangle$.

What I want to know

Are there any alternative interpretations of $\{\{A\}\}$ other than Kuratowski's?
How can we express an ordered homogeneous triple (e.g. Would $\langle A,A,A\rangle$ be equivalent to $\{\{\{A\}\}\}$?)
It seems like the set $\{\{\varnothing\}\}$ can be interpreted as either $\{1\}$ or $\langle\varnothing,\varnothing\rangle$. Should $\{\{\{\varnothing\}\}\}$ be interpreted as $\langle\varnothing,\varnothing,\varnothing\rangle$ or as $\langle 1,1\rangle$.  Is it possible that these tuples are in some way equivalent?

Note, re: Peano's Axioms
My understanding of Peano's axioms is consistent with the formulation at WolframAlpha, which is expressed as the 5 postulates:

$0$ is a number.
If $a$ is a number, the successor of $a$ is a number.
$0$ is not the successor of a number
Two numbers of which the successors are equal are themselves equal.
If a set $S$ of numbers contains zero and also the successor of every number in $S$, then every number is in $S$.

These axioms are expressed in set notation at http://www.proofwiki.org/wiki/Axiom:Peano%27s_Axioms / http://www.proofwiki.org/wiki/Peano%27s_Axioms_Uniquely_Define_Natural_Numbers .
Answer: First let me correct one mistake you have in the first line. Peano's Axioms are about numbers. They don't know what are sets. Indeed most people consider PA to be a "good" axiomatization for the natural numbers, but many people don't care whether or not those numbers are sets or not.
It is the common set theoretic interpretation of Peano's axioms from which we understand the empty set as $0$.
Before proceeding I should also add that Zermelo's interpretation of PA was that $n+1=\{n\}$ (You can read more about that here: The history of set-theoretic definitions of $\mathbb N$). In this interpretation: $$0=\varnothing; 1=\{0\}=\{\varnothing\}; 2=\{1\}=\{\{\varnothing\}\}; \dots$$
This in addition to interpreting $\{\{\varnothing\}\}$ as $\langle 0,0\rangle$ and $\{1\}$.
Let me address your questions one at a time:

Yes. You can interpret $\{A\}$ as anything you would like to interpret it, as long as it is coherent with how you interpret other things too. There is nothing particular in how Kuratowski interpreted ordered pairs, or how von Neumann interpreted ordinals (and natural numbers). Those were just very convenient interpretations, so they stuck and became convention.
Kuratowski's idea to express ordered pairs actually came as a general idea, we identify a linearly ordered set with its initial segments. If we think of an ordered pair as "first element, $a$; second element, $b$" then the initial segments are exactly $\{\{a\},\{a,b\}\}$.
To represent an ordered triplet we therefore would like to write $\langle a,b,c\rangle$ as $\{\{a\},\{a,b\},\{a,b,c\}\}$. However now we have a true problem of interpretation, if $a=b=c$ then both $\langle a,a,a\rangle$ and $\langle a,a\rangle$ would be expressed as $\{\{a\}\}$. Because of that the "atomic" object is an ordered pair, from which we generate functions and treat triplets as indexed by a naturally ordered set like $\{0,1,2\}$.
We also can agree that $\langle a,b,c\rangle$ is a short for $\langle\langle a,b,\rangle, c\rangle$ (or any other composition of ordered pairs) and then $\langle a,a,a\rangle$ is really $\langle\langle a,a\rangle,a\rangle=\{\{\{a\}\},\{\{\{a\}\},a\}\}$.
Your suggestion to interpret $\langle a,a,a\rangle$ as $\{\{\{a\}\}\}$ might be useful in this case, but how would that translate to $\langle a,b,c\rangle$ when $a,b,c$ are not necessarily equal? We want definitions to be coherent and as general as possible.
We discussed a bit what $\{\{\varnothing\}\}$ can be interpreted as, and as before $\{\{\{\varnothing\}\}\}$ can be interpreted in many different ways, it just has to be compatible with how we interpret other things too.
If we agreed that $\{\{\varnothing\}\}=\{1\}$ then $\{\{\{\varnothing\}\}\}=\{\{1\}\}=\langle1,1\rangle$, for example.

All in all, this is just a good example for "type errors" when thinking in terms of sets. Much like when writing code in assembly both numbers and string are the same.
Comment: Even worse, if $\langle a,b,c\rangle = \{\{a\},\{a,b\},\{a,b,c\}\}$, then $\langle 0,0,1\rangle=\langle 0,1,1\rangle$, and we don't want that!
Comment: Thank you for the excellent answer.  Where can I find the formulation of "Zermelo's interpretation of PA was that n+1={n}"?
Comment: What about $(a,b,c)=\{\{\{a\},\{a,b\}\},\{\{a,b,c\}\}\}$ This has the advantage over the "double pair" $((a,b),c)$ that all elements are on the same "depth". Then $(a,a,a)=\{\{\{a\}\}\}$, $(a,a,b)=\{\{\{a\}\},\{\{a,b\}\}\}$, $(a,b,b)=\{\{\{a\},\{a,b\}\},\{\{a,b\}\}\}$. It has also an obvious generalization to $n$-tuples. Also I think it is worthwhile to be able to distinguish between $((a,b),c)$ and $(a,b,c)$.
Comment: @celtschk: It seems reasonable. I've been trying to find Kuratowski's original definition, but I couldn't locate it so far. Note that your definition is really a double tuple too, $\langle a,b,c\rangle=\langle\langle a,b\rangle,\{a,b,c\}\rangle$.
Comment: @AsafKaragila: $((a,b),\{a,b,c\})=\{\{(a,b)\},\{(a,b),\{a,b,c\}\}\} = \{\{\{\{a\},\{a,b\}\}\},\{\{\{a\},\{a,b\}\},\{a,b,c\}\}\}$. Which is not equivalent to my formula (and doesn't have all variables occurring at the same "depth", although the latter could be changed by using $((a,b),\{\{a,b,c\}\})$ instead (which wouldn't give my set either, though). Indeed, it is easy to see that my set in general isn't a classic pair, because none of the two subsets is a subset of the other.
Comment: @celtschk: Yes, you're right of course.
Comment: @celtschk: I found Kuratowski's original paper, [but my French is a bit rusty](http://matwbn.icm.edu.pl/ksiazki/fm/fm2/fm2122.pdf). It seems, however, that my original thought were how he saw it, and if we assume that the order is a linear order then it's a good definition too. Your suggestion may be useful, I suppose; but I think that using the idea of ordered-pairs and move to $k$-tuples in the general case is better anyway.
Comment: It might also be worth mentioning that it was Norbert Wiener, not Kuratowski, who first found a way to express ordered pairs directly in set theory, and that his definition was quite different from Kuratowski's. Wiener takes $(a,b) = \{\{\{a\},\emptyset\}, \{\{b\}\}\}$.
Comment: @Mark: In this case one should also mention Hausdorff, Quine and Morse.
Comment: @smartcaveman: I added a reference to another answer of mine, with some historical review and further references.
Answer: You're taking the Kuratowski ordered pair definition too seriously. It doesn't have any intrinsic intuitive meaning, and in particular does not tell us anything deep about the sets it chooses to represent ordered pair. Its only role is as a technical detail in the proof of

ORDERED-PAIR METATHEOREM. There exists a formula $\phi(x,y,p)$ with three free variables such that

For all $x$ and $y$ there is exactly one $p$ such that $\phi(x,y,p)$.
If $\phi(x,y,p)$ and $\phi(x',y',p)$, then $x=x'$ and $y=y'$.

are theorems of set theory.

In the entire rest of the development of set theory (including the very formulation of several of the axioms), and of the development of the rest of mathematics as an application of set theory, we forget completely which formula this $\phi(x,y,p)$ actually is and just write it as $\langle x,y\rangle=p$ instead.
This involves taking care that we never depend on any properties of ordered pairs other than what the metatheorem guarantees -- in particular we never put ordered pairs and other things into the same set and expect to be able to tell them apart later, because a priori anything might be a pair. We could have proved the ordered-pair metatheorem for a different $\phi$ -- for example one that represents the particular pair $\langle \omega_3,\{42,19\}\rangle$ as $\varnothing$ and everything else as Kuratowski pairs in reverse order -- and that should not make any difference at all for the rest of the development.
So yes, it is true in a technical sense that $\langle 0,0\rangle
$ and $\{1\}$ are the same set. But that is just a coincidence -- an implementation detail -- and we deliberately don't depend on such details when we do mathematics.
It makes very good sense, as Asaf suggests, to view this as a type system. In that view, asking whether $A=B$ when we know $A$ as an ordered pair, and $B$ as a set with particular members, is a type error which produces an implementation-dependent (even if definite) truth value.
Comment: I see that my idea about proof schema with "insert ordered pair here" stuck with you... :-)
Comment: @Asaf: Yes, indeed.
Comment: Maybe one could formalize the "forgetting" by saying that any formula involving pairs implicitly contains the condition "for any formula $\phi$ fulfilling those conditions" (or maybe that's how it's already done?). So if $p(\phi)$ is the formula formalizing those conditions, the statement $x\in S\times T$ would actually mean $\forall \phi: p(\phi)\rightarrow (\exists U: (x\in U\leftrightarrow \exists s:\exists t: s\in S\land t\in T\land \phi(s,t,x)))$.
Comment: @celtschk: But this is not just this formula. We use "proof schemas" *all the time*, because we may represent things in a myriad of formulas which may not produce the same object when translated to sets. However the point of the proof is that we use the properties provable from these formulas, and they are merely placeholders. The notion you suggest is somewhat formalized in category theory in the sense that the actual underlying set doesn't matter as long as there is an isomorphism (and sometimes a canonical one, or a unique one) between the different interpretations.
Comment: @celtschk: I understand that there is a formalization of this in many computer proof systems such as HOL. I've never used it myself, but what I understand is that you can prove a "definitional theorem" "there exist a functional relation with such-and-such properties", and henceforth you're allowed to use that relation and its properties as if they were primitives. Being higher-order helps this work smoothly, of course.


Access to App Engine Pull Queue - Activate TaskQueue API

Question: I try to authenticate into Google Queue API using the Google Sample Code - Taskqueue-cmdline-sample,
You have to set a google client id and google client secret into the client_secrets.json file of the sample.
So my problem is which credentials to use there and how to obtain them! Plus we have to use an email address in the ACL of queue.xml in GAE and not a Client ID...
You have a link in the documentation who point there to get the client id/secret: http://code.google.com/p/google-api-java-client/source/browse/shared/shared-sample-cmdline/src/main/java/com/google/api/services/samples/shared/cmdline/oauth2/OAuth2Native.java?repo=samples
But it's dead... (404) --> FIXED
Documentation: http://samples.google-api-java-client.googlecode.com/hg/taskqueue-cmdline-sample/instructions.html
Checkout the sample there : http://code.google.com/p/google-api-java-client/source/checkout
Update
The TaskQueue API is not in my list of Services. How could I activate TaskQueue API?
Answer: Thanks for the heads-up regarding the documentation. It was updated accordingly.
The credentials for client_secrets.json comes from the Developer Console. You can follow these steps to obtain them (which are now listed at the documentation):

Visit the Google apis console
If this is your first time, click "Create project..."
Otherwise, click on the drop down under the "Google apis" logo at the top left, and click "Create..." under "Other projects"
Click on "API Access", and then on "Create an OAuth 2.0 Client ID...".
Enter a product name and click "Next".
Select "Installed application" and click "Create client ID".
In the newly created "Client ID for installed applications", click "Download JSON" on the right side. Later on after you check out the sample project, you will copy this downloaded file (e.g. ~/Downloads/client_secrets.json) to src/main/resources/client_secrets.json. If you skip this step, when trying to run the sample you will get a 400 INVALID_CLIENT error in the browser.

Note that the link used above and in the documentation automatically asks if you want to activate the TaskQueue API, which is necessary. If you manually go to the API console, be sure to go to the services tab and turn that API on yourself.
Comment: I don't find TaskQueue API in the list of services, how could I activate it? thanks ;)
Comment: Do you have any updates for me on the TaskQueueAPI side? Because we are thinking that we should build our own task queue to do a work around this problem if we don't find a solution to this problem soon :(


Powershell error saying the gallery is unavailable try again later

Question: I am running into this issue where iam unable to install any modules. even when i try to register i get this error. any ideas on resolving this appreciate it.
PS C:\Users\abc> Register-PSRepository -Name PSGallery -SourceLocation https://www.powershellgallery.com/api/v2
Get-PSGalleryApiAvailability : PowerShell Gallery is currently unavailable.  Please try again later.
At C:\Program Files\WindowsPowerShell\Modules\PowerShellGet\22.214.171.124\PSModule.psm1:4095 char:9
+         Get-PSGalleryApiAvailability -Repository $Name
+         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [Get-PSGalleryApiAvailability], InvalidOperationException
    + FullyQualifiedErrorId : PowerShellGalleryUnavailable,Get-PSGalleryApiAvailability

Register-PSRepository : Use 'Register-PSRepository -Default' to register the PSGallery repository.
At line:1 char:1
+ Register-PSRepository -Name PSGallery -SourceLocation https://www.pow ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (PSGallery:String) [Register-PSRepository], ArgumentException
    + FullyQualifiedErrorId : UseDefaultParameterSetOnRegisterPSRepository,Register-PSRepository

PS C:\Users\abc> $PSVersionTable

Name                           Value
----                           -----
PSVersion                      5.1.17134.858
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.17134.858
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           22.214.171.124

-- adding some more commands
Find-PackageProvider -Name nuget
WARNING: Unable to download from URI 'https://go.microsoft.com/fwlink/?LinkID=627338&clcid=0x409' to ''.
WARNING: Unable to download the list of available providers. Check your internet connection.
Find-PackageProvider : No match was found for the specified search criteria and package name 'nuget'. Try
Get-PackageSource to see all available registered package sources.
At line:1 char:1
+ Find-PackageProvider -Name nuget
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (Microsoft.Power...PackageProvider:FindPackageProvider) [Find-PackagePro
   vider], Exception
    + FullyQualifiedErrorId : NoMatchFoundForCriteria,Microsoft.PowerShell.PackageManagement.Cmdlets.FindPackageProvid
   er

Register seems to complete without any errors, but nothing gets added
PS C:\Users\abc> Register-PSRepository -Default
PS C:\Users\abc> Get-PSRepository
WARNING: Unable to find module repositories.
PS C:\Users\abc>

PS C:\Users\abc> [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
PS C:\Users\abc> Register-PSRepository -Name PSGallery -SourceLocation https://www.powershellgallery.com/api/v2
Get-PSGalleryApiAvailability : PowerShell Gallery is currently unavailable.  Please try again later.
At C:\Program Files\WindowsPowerShell\Modules\PowerShellGet\188.8.131.52\PSModule.psm1:4095 char:9
+         Get-PSGalleryApiAvailability -Repository $Name
+         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [Get-PSGalleryApiAvailability], InvalidOperationException
    + FullyQualifiedErrorId : PowerShellGalleryUnavailable,Get-PSGalleryApiAvailability

Register-PSRepository : Use 'Register-PSRepository -Default' to register the PSGallery repository.
At line:1 char:1
+ Register-PSRepository -Name PSGallery -SourceLocation https://www.pow ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (PSGallery:String) [Register-PSRepository], ArgumentException
    + FullyQualifiedErrorId : UseDefaultParameterSetOnRegisterPSRepository,Register-PSRepository

PS C:\Users\abc> Get-PSRepository
WARNING: Unable to find module repositories.

Comment: try forcing tls 1.2. This solves most powershell gallery issues `[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12`
Comment: what happens hwne you use `Register-PSRepository -Default`
Comment: and then check it out using `Get-PSRepository`
Comment: Yes forcing this worked
Comment: @PetertheAutomator you could have put this as answer instead of comments ...this saved my day
Comment: @DonWoodward it is done
Comment: I still have the same issue as the OP. Using Windows Server 20H2 behind a corporate proxy. Guess that's the issue. Any tips for that?
Answer: Try forcing tls 1.2. This solves most powershell gallery issues
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
Comment: I've also seen ServicePointManager.SecurityProtocol=(SecurityProtocolType)3072 which .NET 4 over .NET 4.5 can support.
Answer: Not really a solution, but rather an FYI piece.
This also seems to happen regularly every three months now when TLS cert in https://www.powershellgallery.com/api/v2 expires. For some reason, Microsoft are struggling to get the cert renewal to work properly.
When this happens, none of the above mentioned solutions will work.
In fact, this is happening right now, as I type this...
https://github.com/PowerShell/PowerShellGallery/issues/166
To see if the issue is caused by the expired (or otherwise invalid) cert, just open this URL https://www.powershellgallery.com/api/v2 in a browser and see if the browser complains about the certificate.
If you need to make it work just this one time, you can try tricking Powershell into ignoring invalid certificates like so:
[Net.ServicePointManager]::ServerCertificateValidationCallback = {$true};

...but be warned:
a) this is a bad practice and you shouldn't really have it as a permanent solution because this will expose you to man-in-the-middle attack; and
b) this may not help you because Microsoft guys usually disable PSGallery API when this situation happens. To check if the API is disabled right now, run:
# Set-PSRepository -Name PSGallery -InstallationPolicy Trusted
Get-PSGalleryApiAvailability : PowerShell Gallery is currently unavailable.  Please try again later.
At C:\Program Files\WindowsPowerShell\Modules\PowerShellGet\188.8.131.52\PSModule.psm1:4302 char:9
+         Get-PSGalleryApiAvailability -Repository $Name
+         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [Get-PSGalleryApiAvailability], InvalidOperationException
    + FullyQualifiedErrorId : PowerShellGalleryUnavailable,Get-PSGalleryApiAvailability

Update:
Also look here for any current ongoing issues with PSGallery:
https://github.com/PowerShell/PowerShellGallery/blob/master/psgallery_status.md
Answer: Actually forcing tls12 is not enough to solve, but, reading carefully to the error message said:  Use 'Register-PSRepository -Default'
So I tried: register-psrepository -Default
PS C:\Windows\system32> register-psrepository -Default
PS C:\Windows\system32> get-psrepository

Name                      InstallationPolicy   SourceLocation
----                      ------------------   --------------
PSGallery                 Untrusted            https://www.powershellgallery.com/api/v2

And it solve the problem.


Send apple push notification from azure

Question: i am trying send push notification from azure, when i send from my local server its working fine, but when i upload my web app to azure its not working (502 bad gateway error). so my code is here :
hostname = "gateway.push.apple.com";
PORT = 2195;
TcpClient client = new TcpClient();

X509Certificate2 clientCertificate = new X509Certificate2(System.IO.File.ReadAllBytes(System.Web.HttpContext.Current.Server.MapPath(path)), password);
X509Certificate2Collection certificatesCollection = new X509Certificate2Collection(clientCertificate);

client = new TcpClient(hostname, PORT);
SslStream sslStream = new SslStream(client.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);

sslStream.AuthenticateAsClient(hostname, certificatesCollection, SslProtocols.Tls, false);
MemoryStream memoryStream = new MemoryStream();
BinaryWriter writer = new BinaryWriter(memoryStream);

writer.Write((byte)0);
writer.Write((byte)0);
writer.Write((byte)32);

writer.Write(HexString2Bytes(ReciverDeviceToken.ToUpper()));
JObject payloadData = new JObject();
JObject aps = new JObject();

aps.Add("alert", Title);
aps.Add("badge", "1");
aps.Add("sound", "sound.caf");
payloadData.Add("aps", aps);

foreach (var m in Messages)
{
    payloadData.Add(m.Key, m.Value);
}

string payloadDataToString = payloadData.ToString();

writer.Write((byte)0);
writer.Write((byte)payloadDataToString.Length);

byte[] b1 = System.Text.Encoding.UTF8.GetBytes(payloadDataToString);

writer.Write(b1);
writer.Flush();

byte[] array = memoryStream.ToArray();

sslStream.Write(array);
sslStream.Flush();
client.Close();

i have googled, but there is no result. is there any idea? thanks
Answer: Try this
X509Certificate2 cert = new X509Certificate2(pfxFile, "password", X509KeyStorageFlags.MachineKeySet);

for more details please see this link
Windows Azure Management Libraries Certification Error on Web Jobs

Send apple push notification from azure


What happens when I perform this as root

Question: (don't try this!)
lsof  -i | head 100 | xargs rm-r

After executing this I'm not able to login as it removed /bin/bash. Reboot also don't work. Shows kernel error and server crashed.
Comment: We used to get newbies in the multiplayer game Homeworld to type `ACCESS` as a cheat code (it would actually scuttle all your ships). I can only assume this is that sort of scenario. **Don't run shell commands you don't understand.**
Comment: What possessed you to run a line of code including the rm command as root without understanding what the line does? Restore the machine from your backups and learn from this mistake.
Answer: You will need to reinstall the operating system.
lsof -l lists open files
head -100 returns the top 100
xargs rm -r recursively delete them
You've likely deleted 100 random open files, including things like shared libraries and core utilities. The OS is now unusable.


How to generate a link as 'href="#"'?

Question: In my theme, I have to output a toggle link like this:
Show LessShow More

Its not a real field or anything like that. Is there a way I can use link or path functions to generate this output instead? I am guessing since the title has two spans in it that I cannot, but lets assume there were no spans, I'd like to know if this is possible.
I tried:
{{ link('Show More', 'internal:#') }}

and
{{ link('Show More', '#') }}

The first one creates an empty href, which does not work. The second throws a fatal error.
Comment: see https://drupal.stackexchange.com/questions/231491/create-a-link-pointing-to
Comment: Why not using built-in Twig functions? Macros, include, embed,... should do the same
Comment: You can't. You have to use preprocessor and inline template.
Comment: If you really must use an `a` element better use `href="javascript:void(0)"`. Related discussion: https://stackoverflow.com/q/134845/2199525
Comment: At best use `{{ 'Show more'|t }}`.
Answer: You could just type it into the template and dont have to do anything clever or twig based? e.g.
Show more

The core html.html.twig quite happily does this for the #main-content link:
https://api.drupal.org/api/drupal/core%21modules%21system%21templates%21html.html.twig/8.2.x
Comment: `{{ 'Show more'|t }}`
Comment: That is what I am already doing, I just don't like it very much.

How to generate a link as 'href="#"'?


Returning HTML from a controller

Question: I have followed the guide at http://befused.com/drupal/first-drupal8-module to create a simple Drupal 8 controller, and it works as described. Instead of printing "Hello World" I would like to create more complex HTML.
I found a guide that appears to step through what I need to do at http://jonathanpatrick.me/blog/safe-markup. I added hook_theme to my flot_d8.module file:
function flot_d8_theme(array $existing, $type, $theme, $path) {
  return array(
    'flot_d8_my_template' => array(
      'template' => 'my-template',
      'variables' => array(
        'variable1' => NULL,
        'variable2' => NULL,
      ),
    ),
  );
}

and created the my-template.html.twig file exactly as shown:

  This is the first variable: {{ variable1 }}.
  This is the second variable: {{ variable2 }}.

I'm guessing my problem is in the way I try to call the theme. My controller code is:

namespace Drupal\flot_d8\Controller;
use Drupal\Core\Controller\ControllerBase;
class Flot_d8 extends ControllerBase {
  public function content() {
    return [
      '#theme' => 'flot_d8_my_template',
      '#variable1' => t("First"),
      '#variable2' => t("Second"),
    ];
  }
}

Is this the correct way to print a
 to the screen? Do I need to register the template file in my info file somewhere?
Comment: This may help https://drupal.stackexchange.com/questions/136139/how-to-render-a-template-in-drupal-8?rq=1
Comment: You do not need to declare template in hook_theme, that is the default value now(instead of render element). Also your template should be flot-d8-my-template.html.twig, and it has to be placed in templates directory in your module. Other than that clearing cache should be all that is needed since all looks good.
Answer: I removed the template line from hook_theme and renamed the file to flot-d8-my-template. Cleared the cache and it worked.
Comment: Please don't add "thanks" as answers. Invest some time in the site and you will gain sufficient [privileges](//drupal.stackexchange.com/privileges) to upvote answers you like, which is the Drupal Answers way of saying thank you.

Returning HTML from a controller


iOS 8 :MFMailComposeViewController automatic called cancel button

Question: iOS 7 email send work perfectly but iOS 8 view automatic disappear and send button also not enable.
<code>error is :timed out waiting for fence barrier from com.apple.MailCompositionService
</code>
Comment: which xcode you have used to test app? and its perfectly working in iOS 8 device..
Comment: xcode 6 and ios 8 working perfectly ..
Answer: i got answer,
this is the xcode problem. try to run on iOS 8 updated devise or iPhone 6 then check. it's work perfectly.


Passing dict from one view controller to another via segue wont work

Question: I am trying to access a dictionary from MainViewController to dataViewController.
in dataViewController i have created a property in ".h file:

    @property (nonatomic, retain) NSDictionary *dataDict;
Synthasized the file in the ".m" file

@synthesize dataDict;
and in the viewDidLoad method, placed this:

-(void)viewDidLoad {
[super viewDidLoad];
NSLog(@"Time: %@", dataDict);
}

Now in my MainViewController i have imported into the .h file:

    #import "dataViewController.h"
and in the ".m" placed in ViewWillAppear:

dataViewController *controller = [[dataViewController alloc] init];
controller.dataDict = jsonDict;
NSLog(@"Time: %@", controller.dataDict);

NSLog from the MainViewController displays as it should.
NSLog from the dataViewController say NULL.
Comment: Can you post the code that set the value to jsonDict?
Comment: What is dataViewController ? Is it connected somehow to UIViewController ? What is an order of logs ? Which one is showing first ?
Comment: `NSLog(@"Time: %@", dataDict);` add this line in your viewWillAppear instead of viewDidLoad
Comment: What does this have to do with JSON?
Comment: You are making a common (but, to me, inexplicable) mistake.  When you alloc/init dataViewController in MainViewController you're creating a new copy, unrelated to the one where you execute viewDidLoad.
Comment: MainViewController has 4 buttons across the bottom, when the button that says Data is pressed a segue is created that pushes dataViewController to the ContainerView on MainViewController.  what do i need to change in the code to make it work?
Comment: i have also tried:    dataViewController *destViewController = segue.destinationViewController;
    destViewController.dataDict = jsonDict;
but i keep getting a [uiviewcontroller setinfo:] unrecogonised selector sent to instance
Answer: i needed to have dataArray in the 4 different segue destination's as only one had it. so more info might have helped peeps. code that fixed the data transfer:
if ([segue.identifier isEqualToString:@"graphSegue"]) {
    graphViewController *destViewController = (graphViewController *) segue.destinationViewController;
    destViewController.dataArray = locationArray;


Piecewise Continuity

Question: Find all values of A and B for which f(x) is continuous for all read x values.
f(x)=
<code>  (-4Ax+B, x<1)

  [A(x^2-4/x-2), -1< x <2]

  (Bx+2, x>2)
</code>
I know how to solve this type of problem with only A, but where do I start when trying to find A and B?
Comment: Is this homework?
Answer: We immediately have $f$ is continuous on $(-\infty,-1) \cup (-1,2) \cup (2,\infty)$ since, on these intervals, it is the composition of continuous functions.
We now need to ensure that also $$\lim_{x \rightarrow -1} f(x)=f(-1)$$ and $$\lim_{x \rightarrow 2} f(x)=f(2).$$
This means we must have $$4A+B=\lim_{x \rightarrow -1_-} -4Ax+B=\lim_{x \rightarrow -1_+} A(x^2-\tfrac{4}{x}-2)=3A$$ and $$0=\lim_{x \rightarrow 2_-} A(x^2-\tfrac{4}{x}-2)=\lim_{x \rightarrow 2_+} Bx+2=2B+2.$$
So, we solve the system of equations $$2B+2=0$$ and $$4A+B=3A.$$

Piecewise Continuity


Node_save fails silently

Question: I am trying to programmatically update a node with a value from another entity. When I call node_save, the function just "stops". There is nothing in watchdog or in my php_logs that would indicate that any issue was encountered.
$node = node_load($base_node->nid, FALSE, TRUE);

$node->field_product[LANGUAGE_NONE][] = array('product_id' => $entity->product_id->value());

dpm('This text prints.');

node_save($node);

dpm('This text does not print.'); //This line is never executed.

I have tried a variety of methods for saving the node including using entitymetadatawrappers on $node. So far, nothing I have tried has gotten me anywhere.
Thanks!
Edit:
A few more details on what I have tried/am trying to do.
This field is a product reference field that I am adding a reference to.
There is nothing at all in the php logs or the watchdog logs.
I am trying to do this as a part of custom rules action. I was originally using the add item to list action, but only one item was being added to the list (usually there will be 4-5). As a test, I tried to update and save the node manually (thus the code above).
I should have specified that part, but got a bit wrapped up in my own solution. Either way, it seems pretty odd to me.
Edit Part 2:
I have confirmed that the structure for field_product is correct. I am also doing checks to make sure that I am not referencing a non-existent field, etc.
I wasn't originally using dpms for debugging, it just seemed like the simplest way to communicate my issue. Originally I was doing some further processing on my data that was not being done. Since that further logic isn't pertinent to the problem, I added a dpm as an example. There were no errors in the following logic and it wasn't dependent on the node save.
Comment: by doing $node->field_product[LANGUAGE_NONE][] you are implying that  $node->field_product[LANGUAGE_NONE][1] will be created if [0] already exists. Moreover are you sure it is 'product_id' and not 'value'. Last dpm may not be the best way to debug a rules action. use watchdog('debug', ''.print_r($var,true).''); instead and make  sure the action is triggered by enabling rules debug in advanced options.
Comment: Do you get a WSOD? Did you check you server logs for PHP errors?
Comment: I don't get a WSOD. Everything continues as though nothing went wrong. There is nothing in the logs.
Comment: Please try to use `dsm($node->field_product);` to display the content and structure of that variable. Check if the structure of the value you're assigning is the same. Where are you executing this code also? Thanks!
Comment: I have done that, and the format is the same. This code is part of a custom rules action.
Comment: Updated post to provide further details. Thanks for your time!
Comment: Have you confirmed that $entity->product_id->value() is returning something valid and that node_load($base_node->nid, FALSE, TRUE) is returning a valid node? It seems extremely unlikely that it is actually failing to complete all the code without throwing any errors in the PHP/Apache or watchdog logs (unless your PHP error handling is incorrectly configured).
Comment: To debug further you could start putting dpm() calls in the node_save() function to try to pin down exactly where it is having issues. You can put a series of sequential numbers like dpm(1), dpm(2), etc. in all the conditional blocks in there and get a quick overview of how it is running through that function.
Comment: I have confirmed that both are returning expected values. I agree with you that what I am describing is extremely unlikely. And that is why I created this question, as I am at my wit's end regarding what the issue could be. I did consider going down the path of debugging node_save(), but figured that there was likely a more obvious solution that I was missing.
Comment: I did have a thought, would it maybe have something to do with Rules' recursion prevention? If rules thought that my function was recursive, it might kick out and not log it as an error? Just a thought.
Comment: Maybe, in which case your rules logs should say so right? Even still it would seem strange that your last dpm() doesn't run as I can't imagine rules would just exit processing entirely in the case of recursion.
Answer: The field structure you are using for your entity reference field is not correct. See entityreference_field_schema().
The correct column name is target_id, not product_id, so it should be like this:
$node = node_load($base_node->nid, FALSE, TRUE);

$node->field_product[LANGUAGE_NONE][]['target_id'] = $entity->product_id->value();

node_save($node);

This assumes you are using an entity wrapper to access the $entity object but not for accessing the $node object.
[edit]
Regarding your dpm() not firing, it is quite possible it is firing but you aren't seeing the output. This can happen depending on where you are calling it from.
A good alternative in these cases could be dd() or watchdog() since their output will be visible regardless of where you call it from.
Comment: I got my wires crossed. This is a product reference field, not an entity reference field. For a product reference field  product_id is the correct column name. I have tried alternatives to`dpm()` and it isn't making a difference. I've updated the post to try to provide some additional clarity

Node_save fails silently


Google Cloud Virtual Machine : Unable to resolve external URLs

Question: my google cloud VM is not able to resolve external URLs , please see the screenshot.

any help in addressing this issue , greatly appreciated
As recommended attaching screenshot of resolv.conf

After restarting systemd-resolved getting below error
systemd-resolved.service - Network Name Resolution
   Loaded: loaded (/lib/systemd/system/systemd-resolved.service; enabled; vendor preset: enabled)
   Active: active (running) since Thu 2020-02-13 10:25:59 UTC; 41s ago
     Docs: man:systemd-resolved.service(8)
           https://www.freedesktop.org/wiki/Software/systemd/resolved
           https://www.freedesktop.org/wiki/Software/systemd/writing-network-configuration-managers
           https://www.freedesktop.org/wiki/Software/systemd/writing-resolver-clients
 Main PID: 10316 (systemd-resolve)
   Status: "Processing requests..."
    Tasks: 1 (limit: 4915)
   CGroup: /system.slice/systemd-resolved.service
           └─10316 /lib/systemd/systemd-resolved

Feb 13 10:26:38 dev.seconize.co systemd-resolved[10316]: Failed to open /etc/hosts: Permission denied
Feb 13 10:26:38 dev.seconize.co systemd-resolved[10316]: Failed to start query: Permission denied
Feb 13 10:26:40 dev.seconize.co systemd-resolved[10316]: Failed to open /etc/hosts: Permission denied
Feb 13 10:26:40 dev.seconize.co systemd-resolved[10316]: Failed to start query: Permission denied
Feb 13 10:26:40 dev.seconize.co systemd-resolved[10316]: Server returned error NXDOMAIN, mitigating potential DNS violation DVE-2018-0001, retrying transaction with
Feb 13 10:26:40 dev.seconize.co systemd-resolved[10316]: Server returned error NXDOMAIN, mitigating potential DNS violation DVE-2018-0001, retrying transaction with
Feb 13 10:26:40 dev.seconize.co systemd-resolved[10316]: Server returned error NXDOMAIN, mitigating potential DNS violation DVE-2018-0001, retrying transaction with
Feb 13 10:26:40 dev.seconize.co systemd-resolved[10316]: Server returned error NXDOMAIN, mitigating potential DNS violation DVE-2018-0001, retrying transaction with
Feb 13 10:26:40 dev.seconize.co systemd-resolved[10316]: Server returned error NXDOMAIN, mitigating potential DNS violation DVE-2018-0001, retrying transaction with
Feb 13 10:26:40 dev.seconize.co systemd-resolved[10316]: Server returned error NXDOMAIN, mit

Comment: /etc/hosts permissions were messed up some how , so had to fix and then restart systemd-resolved to bring it back
Comment: Looks like your OS thinks that DNS at 127.0.0.1. Did you change DNS servers for your VM? Please run `cat /etc/resolv.conf` and update your question with output.
Comment: By default DNS setting for your VM managed by Google Cloud and no changes needed.
Comment: added the screenshot , yeah we did not touch any of that
Comment: Thanks! Please run `sudo systemctl restart systemd-resolved`, then `sudo systemctl status systemd-resolved` and after that check `cat /etc/resolv.conf` again.  In addition, provide output of `cat /etc/systemd/resolved.conf `.
Comment: Do you have admin permissions? Please  provide output of `cat /etc/systemd/resolved.conf` and `cat /etc/hosts`.
Comment: yeah its permissions issue , resolved it now , thanks ! not sure how to close the quesiton
Comment: Please let me know if restart of `systemd-resolved` service with admin privileges helped you to solve this issue.
Comment: Thanks! Could you post an answer and then accept it? It'll be useful for community.
Answer: As it was explained in comments by @sashank the cause of this issue was wrong permissions on file /etc/hosts. When permissions were fixed restart of systemd-resolved service finally solved the issue.


Exibição do nome na Diagonal (Cima para Baixo)

Question: Tenho que ler um nome e exibi-lo na diagonal, ou seja, de cima para baixo.
Porém não estou conseguindo desenvolver a lógica correta, consegui chegar a isto:
nome = input('Digite o seu nome: ')
tamanho = len(nome)

for nome in range(tamanho):
    print(nome)

Mas ele retorna apenas a contagem do tamanho da String, e quero que no lugar da contagem exiba a respectiva letra do nome que o usuário digitou.
Comment: Você pode me explicar melhor por favor? voce quer que o usuario digite um numero e aparece a letra que corresponde a esse numero?
Answer: A função range(n) irá gerar uma sequência de números inteiros [0, n[, o que não é muito útil para você nesse caso. Se entendi bem, você precisa imprimir o nome informado na "diagonal", algo como:
>>> Insira seu nome: anderson
a
 n
  d
   e
    r
     s
      o
       n

Ou seja, você incrementa o número de espaços em branco antes de cada letra. A primeira letra, no índice 0, possui zeros espaços; a segunda, no índice 1, possui um espaço; assim sucessivamente. Então, para você obter a letra e seu respectivo índice dentro do nome você deve usar a função enumerate:
nome = input('Insira seu nome:')

for indice, letra in enumerate(nome):
    print(' ' * indice + letra)

E você terá a apresentação do nome como exemplificado.
Comment: Bom vendo a sua solução consegui fazer de uma forma mais simples, porem nao entendi a parte do '   print(' ' * indice + letra)   '
Comment: esse foi meu codigo        nome = input('Digite o seu nome: ')
                                        for c in nome:
                                               print(c)
Comment: @GiovanniManganotti E onde entra o "diagonal" aí?
Comment: ele vai imprimir uma letra a cada laço, assim o nome fica na diagonal, executa ele pra tu ve, usa esse compilador online ---> https://www.onlinegdb.com/online_python_compiler


How to model a distribution from simple capital cost data?

Question: I want to create scenarios for a simulation model I am working on. Someone recommended me a distribution and select instances to create different scenarios. But my data is limited. For example, my total data is as follows:
Capital cost #1=100-150
capital cost#2=280
capital cost#3=35
capital cost#4=42-45
As you can see capital 1 and 4 have a range, but the other two only one value. I cannot just choose, for example, 100 (capital 1) and ignore the other value. I was wondering how can I create a distribution with these values and how much uncertainty it will create? I know that more values reduce uncertainty, so how can I do this? Because I am dealing with monetary values so I don't think it will be a normal distribution, more like a linear distribution.
Comment: Hi @Moni and welcome to Cross Validated! I have edited the title of your question to make it more general so that other people can learn from it. Finding the right way to ask questions here can be difficult, but we are here to help you!
Answer: Using a random distribution is certainly a good way to proceed. There are many good options, and only your background knowledge of the problem can help you choose the best.
Because the data is displayed as a range, I suggest that you start with the uniform distribution. In other words, you pick a random number between 100 and 150 in the case of capital #1.
As to how much uncertainty this will create, this is exactly the kind of information that you will obtain by running your scenario multiple times.


jq: group objects by string

Question: I have some json from eurostat, which looks like this:
<code>{
  "version": "2.0",
  "label": "Principaux agrégats des administrations publiques, y compris recettes et dépenses",
  "href": "http://ec.europa.eu/eurostat/wdds/rest/data/v2.1/json/fr/gov_10a_main?unit=PC_GDP&na_item=TE&sector=S13&time=2008&time=2009&time=2010&time=2011&time=2012&time=2013&time=2014&time=2015&time=2016&time=2017&geo=DE&geo=AT&geo=BE&geo=BG&geo=CY&geo=HR&geo=FI",
  "source": "Eurostat",
  "updated": "2018-10-26",
  "status": {
    "57": "b"
  },
  "extension": {
    "datasetId": "gov_10a_main",
    "lang": "FR",
    "description": null,
    "subTitle": null,
    "status": {
      "label": {
        "b": "rupture de série"
      }
    }
  },
  "class": "dataset",
  "value": {
    "0": 49.9,
    "1": 54.1,
    "2": 52.8,
    "3": 50.9,
    "4": 51.2,
    "5": 51.6,
    "6": 52.4,
    "7": 51.1,
    "8": 50.3,
    "9": 49.2,
    "10": 50.3,
    "11": 54.2,
    "12": 53.3,
    "13": 54.5,
    "14": 55.9,
    "15": 55.8,
    "16": 55.3,
    "17": 53.7,
    "18": 53,
    "19": 52.2,
    "20": 37.1,
    "21": 39.4,
    "22": 36.2,
    "23": 33.8,
    "24": 34.5,
    "25": 37.7,
    "26": 43.1,
    "27": 40.5,
    "28": 35.1,
    "29": 35.1,
    "30": 38.4,
    "31": 42.1,
    "32": 42,
    "33": 42.3,
    "34": 41.9,
    "35": 41.9,
    "36": 48.8,
    "37": 40.6,
    "38": 38,
    "39": 37.5,
    "40": 43.6,
    "41": 47.6,
    "42": 47.3,
    "43": 44.7,
    "44": 44.3,
    "45": 44.7,
    "46": 44,
    "47": 43.7,
    "48": 43.9,
    "49": 43.9,
    "50": 48.3,
    "51": 54.8,
    "52": 54.8,
    "53": 54.4,
    "54": 56.2,
    "55": 57.5,
    "56": 58.1,
    "57": 57.1,
    "58": 55.9,
    "59": 54,
    "60": 45.3,
    "61": 48.3,
    "62": 48,
    "63": 48.5,
    "64": 47.8,
    "65": 47.6,
    "66": 48.1,
    "67": 48.3,
    "68": 46.9,
    "69": 45
  },
  "dimension": {
    "unit": {
      "label": "unit",
      "category": {
        "index": {
          "PC_GDP": 0
        },
        "label": {
          "PC_GDP": "Pourcentage du produit intérieur brut (PIB)"
        }
      }
    },
    "sector": {
      "label": "sector",
      "category": {
        "index": {
          "S13": 0
        },
        "label": {
          "S13": "Administrations publiques"
        }
      }
    },
    "na_item": {
      "label": "na_item",
      "category": {
        "index": {
          "TE": 0
        },
        "label": {
          "TE": "Total des dépenses des administrations publiques"
        }
      }
    },
    "geo": {
      "label": "geo",
      "category": {
        "index": {
          "AT": 0,
          "BE": 1,
          "BG": 2,
          "CY": 3,
          "DE": 4,
          "FI": 5,
          "HR": 6
        },
        "label": {
          "AT": "Autriche",
          "BE": "Belgique",
          "BG": "Bulgarie",
          "CY": "Chypre",
          "DE": "Allemagne (jusqu'en 1990, ancien territoire de la RFA)",
          "FI": "Finlande",
          "HR": "Croatie"
        }
      }
    },
    "time": {
      "label": "time",
      "category": {
        "index": {
          "2008": 0,
          "2009": 1,
          "2010": 2,
          "2011": 3,
          "2012": 4,
          "2013": 5,
          "2014": 6,
          "2015": 7,
          "2016": 8,
          "2017": 9
        },
        "label": {
          "2008": "2008",
          "2009": "2009",
          "2010": "2010",
          "2011": "2011",
          "2012": "2012",
          "2013": "2013",
          "2014": "2014",
          "2015": "2015",
          "2016": "2016",
          "2017": "2017"
        }
      }
    }
  },
  "id": [
    "unit",
    "sector",
    "na_item",
    "geo",
    "time"
  ],
  "size": [
    1,
    1,
    1,
    7,
    10
  ]
}
</code>
I would like to produce a csv file.
First, I need to concatenate .status with .value by string (sorry for my poor json knowledge) --> "status":{"57": "b"} with "value":{"57": 57.1}.
Second, I need to produce the same table as the original one (downloaded from eurostat).
I try many jq commands, like:
<code>.status,.value | to_entries
</code>
I'm far from finding a solution.
Any help? I think map or map_values/group_by command are needed, but I don't really understand these functions.
EDIT :
I download data from eurostat.
I use their web service here, where I can download data in json format.
I would like to reproduce in shell same table as original, with jq. In my exemple, it should look like :
GEO/TIME,2010,2011,2012,2013,2014,2015,2016,2017
Belgique,"53,3","54,5","55,9","55,8","55,3","53,7","53,0","52,2"
Bulgarie,"36,2","33,8","34,5","37,7","43,1","40,5","35,1","35,1"
"Allemagne (jusqu'en 1990, ancien territoire de la RFA)","47,3","44,7","44,3","44,7","44,0","43,7","43,9","43,9"
Croatie,"48,0","48,5","47,8","47,6","48,1","48,3","46,9","45,0"
Chypre,"42,0","42,3","41,9","41,9","48,8","40,6","38,0","37,5"
Finlande,"54,8","54,4","56,2","57,5","58,1","57,1","55,9","54,0"
But json contain metadata, and Finlande must have 57,1b value.
I hope it's more clear with this edit.
And many thanks for your help.
Comment: For the first part, `.value[.status|keys[]]` should work. It's not clear what your desired CSV file actually looks like.
Comment: thx, but it produce just 57.1
Answer: Your question doesn't indicate very precisely what output you want, but hopefully you'll be able to adapt the following:
<code>.value as $dict
| .status
| to_entries
| map( [.key, .value, $dict[.key]] )
| .[]
| @csv
</code>
With your input, and invoking jq with the -r option, this produces:
<code>"57","b",57.1
</code>
Comment: sorry, I'll try to explain better. I'll edit the post.

jq: group objects by string


Can you bass boost a song repeatedly?

Question: I was using a plugin/service to bass boost a song when this question came to mind:
Can you Bass Boost a song that has already been Bass Boosted after being Bass Boosted? In other words, can you essentially just repetitively bass boost a song? If you can, then will it sound good?
Comment: As there is a limit to the actual volume of any audio, surely this repeated bass boosting just ends up cutting all the other frequencies. If that's what you want, fine, but it's going to get closer and closer to a band pass filter.
Comment: Generally speaking, if you're serious about audio you should use a proper [DAW](https://en.wikipedia.org/wiki/Digital_audio_workstation), not some online service. There are plenty of free / gratis / cheap ones available.
Comment: @J... it's perfectly sensible to discuss infinite application of effects whose result _converges_ after sufficiently many finite applications. For example, a limiter is mathematically a projection, so applying it once or twice or infinitely often has the same result. More interestingly, you can consider applying a filter infinitely often to approximate a brickwall filter. (In practice, "infinite" would mean something like 4 here...)
Comment: Hmmm Interesting. I just found out that I could upload a bass boosted file into the bass booster, Boost that file and then download the bass boosted boosted file and do it again, I just wanted to see if it would work before I did it.
Comment: Imagine a number that is between 0.0 and 1.0.   Your sound initially starts somewhere between those numbers, but if you keep boosting it, it will eventually hit 1.0.  Then you can't boost it any more.  It'll probably sound like very dull noise.
Answer: Yes, you can feed back processed audio into the same system that processed it originally, again and again. However, whenever you feed back audio into a non-idempotent system, the audio will always degrade over time, especially over many repetitions. The nature and rate of the degradation will depend on the system you're feeding back into. Whether this degradation "sounds good" will be subjective. See I am Sitting in a Room for an "artistic" example, or Re-uploading a video for a similar technical example using video.
Comment: Yes I just realized that when I overdid it on a song by Gotye. It screwed around with the Vocals as well. Basically im just torchure testing songs to try to find the right bass and pitch frequency that makes it sound good but is different from the regular version.
Comment: @leftaroundabout the OP is asking about boosting repeatedly, not "alternating boost-attenuate pairs".
Comment: The inherent degradation of digital audio effects is very low to pretty much negligible though. With something like a slight EQ in the mid range, you could chain _hundreds_ of alternating boost-attenuate pairs together and may in the end get a result that's almost indistinguishable from the original. (With an online up/download it may be a different story, but that has other reasons.)
Comment: Exactly, but you didn't discuss anything comparable to boosting repeatedly.
Answer: Applying an equalizer twice gives (to a good approximation, at least in case of digital EQs) the same result as applying it only once with the controls cranked twice as far from neutral. I.e. there's not much point in actually doing that, just do it once and use the controls stronger.
Now, many EQs have a limit on how strongly you can boost or cut a band. In the analogue case, there are clear technical reasons for this, but for digital EQs it's generally just an arbitrary parameter constraint which has more to do with the fact that more extreme settings would typically just not make any sense musically. IMO that's not a reason to disable them though. The basic equalizer plugin in Reaper, which is also available gratis as a plugin, lets you set arbitrary values, and sometimes this can actually be useful – if you want to completely change the character of an individual instrument or voice.
Specifically bass boosting however is generally speaking a rather counterproductive thing to do, and certainly not a good idea to apply too strongly on a complete mix. The reason is that bass frequencies need to have a stronger amplitude to achieve a given loudness than mid/treble frequencies, so they're typically already maxed out on the mix to begin with. If you then boost them further, you run out of headroom, i.e. you either need to reduce the overall gain (in which case the procedure is better described as a mid/treble attenuation rather than a bass boost), or you need to apply extra compressing/limiting/clipping, all of which leave certain artifacts. (Which can be a valid artistic choice: pumping excessive bass into a compressor is essentially how the ducking effect works.)
Here then it does actually make a difference whether you use two EQs or one EQ twice as strong: in the presence of other effects. Indeed, if you're determined to boost as much bass as possible out of a record, it can make sense to do it in stages: first boost the bass slightly, then bring back the peak levels with a slow compressor and/or soft clip. Then boost some more, and again bring it back with a compressor and final limiter. This combination will typically leave less obvious artifacts than if you handle the same amount of total bass boost in a single step.
But an even better approach may be to not use a standard EQ at all, but rather a multiband compressor. These allow you to strongly compress the bass, thus achieving a higher average bass volume without either exceeding the master peak level or pumping the rest of the spectrum too much.
Yet there's no free lunch: compression always comes at the cost of less dynamic range, less snappy peaks. The only way to truely get much more bass is to use more capable speakers. If you're limited by the speakers, then it can actually be more a effective strategy to remove low bass frequencies that the speakers can't transmit at all anyway; this way you get more headroom and can then turn up the signal louder and boost the lower mids. The final result can thus sound fatter despite actually having less bass frequencies in it. It probably won't sound better though.

Can you bass boost a song repeatedly?


Arduino stuck in an infinite loop

Question: My Arduino is stuck in an infinite loop trying to read from a pin and print it to the serial console. I can't upload any other programs now. What can I do to get the chip out of the loop?
Comment: Have you tried resetting the device?
Comment: @Jonathan, I have tried pushing the reset button as I click the "Upload" button in the Arduino IDE, however, it still does not upload.
Comment: I would advise you to try also http://electronics.stackexchange.com (no flag cause still in beta)
Comment: Have you tried *physically* resetting the device? As in, powering it off and on again via judicious use of *unplugging it from the wall*?
Comment: @Jonathan, I have tried this many times. It is powered via usb, and I have unplugged it and reconnected it many times now.
Answer: Remove the USB connection, close the IDE, open the IDE, open BareMinimum, hold the reset button, plugin the USB connection, click the upload button 1/2 a second after removing your finger from the reset button.
Comment: Yeah, Timing it is a bitch but it's better than replacing it.
Comment: This worked on my Uno -- I didn't need to bother upgrading the firmware. In the future, I'm going to add a `delay(1000);` to my setup code.
Answer: If you're using an Arduino Uno, you might want to check out Updating the Atmega8U2 on an Uno or Mega2560 using DFU. Apparently there was a bug in the interface firmware.
Answer: This may sounds silly but what about disconnect it from the power supply to reset the MCU?
Edit:
I see it is powered via USB; then make sure you disconnect the device, remove/discharge any battery/capacitors whatsoever. If nothing works, close down the Arduino IDE, change the USB port you are using (sometimes it does happen that they get stuck..), reboot the PC.. Good luck!
Answer: Reprogramming the interface firmware (see ViennaMike's response) did not work for me, so I purchased another Arduino and turned it into an ISP programmer and overwrote the offending application:
https://stackoverflow.com/a/8453576/1090713
While this approach had some cost, I now have another tool and a way to save an Arduino in the future.
Answer: Upload your boot loader using Avr pocket programmer. This solves your MCU reset.
Use Watchdog timer instruction while coding infinite loop provided you are dealing with critical parameter to be written when it restarts.
Answer: If you run across the same problem with Arduino Yun, try uploading empty sketch using WIFI as port. It worked for me when I couldn't upload new sketch via USB.
Answer: The Arduino will wait a short while when attempting to upload. So you can press the reset and hold it until the Ide shows attempting to upload. then let go of it.
The problem can be that when you click upload the Ide first compiles then at the end of the process attempts to upload. So pressing reset, clicking compile and immediately letting go of reset doesn't always work because you let go of the reset too quickly.

Arduino stuck in an infinite loop


Term translations not working as View's path contextual filter

Question: Let's say you have a taxonomy called Animals and you have terms like Dog, Cat, Horse, etc. Every term has its translation, so for example for dogs you have Hund and Chien. Now you want to make a View which generates a page that lists content tagged with the Animals term reference, contextually filtering the tag based on the URL part.
And this is the part I'm having difficulties with.
The contextual filter I made works perfectly with source language values and converts properly to term ID. So I'm getting correct listing (both in preview pane and generated page) for /animals/dog but incorrect for /tiere/hund.
The contextual filter is set to Content: Animal Genre (Translated) and validation to Localised term or synonym converted to term ID (actually I tried perhaps every possible combination of i18n and non-i18n options here, no joy).
I trie out another solution - with Content: Has taxonomy term ID + relationship (as described here).
Is it something I'm not setting up correctly or is there a bug around i18n, Views, i18nviews...? I'd be grateful for any guidance
Comment: It could be related to the capital letters in your taxonomy terms. Try /Tiere/Hund or /tiere/Hund.
Answer: Implementing hook_language_switch_links_alter() is definitely the way to go.  Here is the code along with two (2) helper functions, assuming there are display variants for each language.
/**
 * Implements hook_language_switch_links_alter().
 *
 * This is a workaround for Path Translation not supporting Views' contextual filters.
 * Alter the language switcher to switch between path/to/[term] and different
 * paths for different languages.
 */
function mymodule_language_switch_links_alter(array &$links, $type, $path) {

  // Load the current view if there is one.
  $view = views_get_page_view();

  // Act only if we're looking at the view in question.
  if (($type == "language_content") && isset($view) && ($view->name == 'myview')) {

    // Skip situations where there's no argument.  This is handled by Path Translatoon.
    if (isset($view->args[0]) && ($view->args[0] != mymodule_get_myview_view_all_term($view))) {

      // Iterate across all language links.
      $language_active = $GLOBALS['language']->language;
      $displays = mymodule_get_myview_view_language_displays();
      foreach ($links as $language_current => &$link) {

        // Skip the active language.
        if ($language_current == $language_active) {
          continue;
        }

        // Set the path for the current language.
        $path = $view->display[$displays[$language_current]]->display_options['path'];
        $link['href'] = strtok($path, '/') . '/' . $view->args[0];
      }
      // Break the foreach reference.
      unset($link);
    }
  }
}

/**
 * Returns the list of displays for the view in question, keyed by language.
 *
 * @return array
 *   The list of displays.
 */
function mymodule_get_myview_view_language_displays() {
  return array(
    'en' => 'page_myview_en',
    'fr' => 'page_myview_fr',
  );
}

/**
 * Get the language-specific term representing all items.
 *
 * @param view $view
 *   The previously loaded view in question.  Optional.
 * @return string
 *   The term.  If there's no translation in the current language, "all" is used.
 */
function mymodule_get_myview_view_all_term($view = NULL) {

  // Load the view if it wasn't provided.
  $view = (is_null($view) ? views_get_view('myview') : $view);

  // Get the current language and the display names for each defined language.
  $language = $GLOBALS['language']->language;
  $displays = mymodule_get_myview_view_language_displays();

  // Return the language's "all" term, or the default if there isn't one.
  if (isset($view->display[$displays[$language]]->display_options['arguments']['tid']['exception']['value'])) {
    return $view->display[$displays[$language]]->display_options['arguments']['tid']['exception']['value'];
  }
  else {
    return 'all';
  }
}

Note that this doesn't handle the translation of the term itself within the path, only the part of the path leading up to it.  For now, that will always be in the default language. This is the separate issue Views contextual filter validation: Support ET-translated taxonomy term name.


Disclaimer screen when adding new content

Question: I'm looking for a way to have a disclaimer page/popup be a part of creating a certain type of content, in this case a OG group. Is this something that could somehow be done with Webforms?
I found http://drupal.org/project/legal but it just doesn't quite do the trick... Any other ideas? :)
Answer: One way to accomplish this would be to make a small custom module utilizing hook_form_alter().  Substitute "example" with your module name to implement.
example.module
/**
* Implementation of hook_form_alter()
* Add Disclaimer Message to Article Create Form
*/
function example_form_article_node_form_alter(&$form, $form_state) {
  if (arg(1) == 'add') {
    drupal_set_message('Legal Disclaimer: By filling out this form you are agreeing.','warning');
  }
}

example.info
name = "Example module"
description = "Adds a disclaimer to node/add/article page."
package = Example
core = 7.x

Or if you want a popup, you could instead use drupal_add_js and a little Javascript
example.module
/**
* Implementation of hook_form_alter()
* Add Popup Disclaimer to Article Create Form
*/
function example_form_article_node_form_alter(&$form, $form_state) {
  if (arg(1) == 'add') {
    drupal_add_js(drupal_get_path('module', 'example').'example.js');
  }
}

example.js
// if user agrees continue, else redirect
if (!window.confirm('Legal Disclaimer: Press OK if you agree.')) {
  window.location.href='http://example.com';
}

Of course this is all pretty simple and ugly.  One could combine both approaches and using CTools Modal or JQueryUI build a prettier dialog.  With JQueryUI you might do:
example.js
// if user agrees continue, else redirect using JQueryUI
// requires JQueryUI loaded (you can use [drupal_add_js()][5] for this too).
(function ($) {
  $(document).ready( function() {
    $("

Legal Disclaimer

Do you agree?

").dialog({
      resizable: false,
      height:140,
      modal: true,
      buttons: {
        "I Agree": function() {
          $( this ).dialog( "close" );
        },
        "No Way": function() {
          $( this ).dialog( "close" );
          window.location.href='http://example.com';
        }
      }
    });
  });
});


SailsJS issues with select, sort inside populate

Question: I wants to retrieve last 2 customer invoices with selected fields, but select, sort are not working with populate, is any way to solve this problem without using Model.query.
<code>Customer.find({customer_type: 'full'})
        .populate('invoices', {
             invoice_type: 'monthly',
             select: ['id', 'customer_id', 'discount', 'total'],
             sort:{invoice_date: 'desc'}
             limit: 2
        }).exec(function(err, custumers){ //-------- });
</code>
Answer: Update. In new Waterline v0.12 you can use select for populate method (Waterline 0.12 changelog)
In current Waterline v.0.11 you can solve this problem only with Model.query().


Can zero be used as exception case for MurmurHash3

Question: In a specific use case in our organisation I have chosen to use MurmurHash3 (128-bit version) to determine whether a record consisting of multiple elements are unique compared to another record. Choice of algorithm and debate regarding the wisdom of using a hash to determine uniqueness aside, can the value zero (0) be used as an exception value for the hash return?
We are currently using Guava's Hashing to generate the hash on a String input and  exceptions cannot be used to report an exception on a null (which is possible) input. Also, the return value has to be a primitive 64-bit value as it is consumed by an external system that I do not have control over so the equivalent of a null cannot be used to report on the exception either.
Note: Expected range of characters in the input string is in the Basic Latin and Latin-1 unicode blocks. No NUL characters.
Answer: Well, one in 2^128 inputs will genuinely hash to 0.
You could create a slightly modified hash function that never returns 0, however -- perhaps if the hash genuinely comes out to zero, it hashes the input concatenated with an arbitrary extra byte, and keeps concatenating until the hash comes out nonzero.
Comment: Better than trying to deterministically produce "an arbitrary byte": Just say "if the hash came out to zero, then return 1 instead." Sure, this makes "1" come up twice as often as "2" or any other number — but the difference is $1/2^{128}$ — 0.000000000000000000000000000000000000588% versus 0.000000000000000000000000000000000000294%. It's astronomically unlikely for _either_ 0 or 1 to be rolled before the heat death of the universe, and the chance that they'd _both_ be rolled is... well, functionally impossible.


Header Content Type in axios can't set application/json

Question: I am trying to configure headers in a project with vue.js and axios to call a service that expects a json. My problem is that when I make my call with the POST method, axios puts to the request Content-Type header with x-www-urlencoded, but in my code, I put manually Content-Type header with application / json.
var loginObj = {
    var1: payload.login,
    var2: payload.password
}

const jsonLogin = JSON.stringify(loginObj)

const config = {
    headers: {
      'content-type': 'application/json',
      'Accept': 'application/json'
    }
}

axios({
    url: 'url/example',
    method: 'post',
    data: jsonLogin,
    config
})
.then(response => {
    console.log(response);
})
.catch(error => {
    console.log(error);
})

Answer: The Axios property to set header config should be headers: and you are setting with config:
try with:
axios({
    url: 'url/example',
    method: 'post',
    data: jsonLogin,
    headers: config.headers
  })

or change your const config to:
const configHeaders = {
  "content-type": "application/json",
  "Accept": "application/json"
};

and use it with:
axios({
  url: "url/example",
  method: "post",
  data: jsonLogin,
  headers: configHeaders
});

Comment: Thanks for the reply. My solution was to install the qs library and convert the object into json with qs.stringify when it is sent.

axios.post('url/example',
        qs.stringify(loginObj),
        headers
      )


Imprimir String na vertical em Python

Question: É um exercício que utiliza apenas strings, ainda não cheguei na parte de listas
Qual meu erro ?
print("-"*30)
nome = str(input("Digite seu nome: "))
cont = '0'
while cont < nome:
    c = int(cont)
    print(nome[c])
    cont += '1'

Comment: isto de ajudaria? ou  você precisa msmo declarar cont sendo string?
print("-"*30)
nome = str(input("Digite seu nome: "))
cont = 0
tam=len(nome)
while cont<tam:
    c = int(cont)
    print(nome[c])
    cont += 1
Comment: Se ajudar ai sim coloco como resposta, senão seria apenas pra atrapalhar respostas melhores
Comment: Ótimo, essa está valendo... Tinha me esquecido do recurso "len". Obrigado cara
Answer: Substitua todo o seu código por essa linha:
for c in input("Digite seu nome: "): print(c)

Não use o while para iterar sobre uma string, a forma mais simples de iterar por uma string é usando uma declaração for:
for item in String:

Ou então não itere, apenas desempacote e retorno da função embutida input() como argumentos posicionais para função print() e use um caractere \n, new line, como valor para argumento nomeado sep.
print(*input("Novamente digite seu nome: "), sep="\n")

Teste os dois exemplos no Repl.it
Retorno dos dois exemplos:
Digite seu nome: Augusto
A
u
g
u
s
t
o
Novamente digite seu nome: Vasques
V
a
s
q
u
e
s

Answer: Você esta concatenando string ao invés de somar na sua variável cont e não estava pegando o tamanho do nome
print("-"*30)
nome = str(input("Digite seu nome: "))
cont = 0 # era '0' string
while cont < len(nome): # aki coloquei len(nome) que é o tamanho
    c = int(cont)
    print(nome[c])
    cont += 1 # aki estava '1' string

https://repl.it/repls/GraveCadetblueOutput

Como foi comentado por @AndersonCarlosWoss, você esta utilizando o python 3.x então você não precisa converter o retorno do input()
# nome = str(input("Digite seu nome: "))
nome = input("Digite seu nome: ") # ficando assim

Comment: Você não precisa converter a saída de `input` para `str.` No Python 3+ sempre será `str`
Answer: Existem algumas formas se mostrar uma string na vertical. Para complementar, poderia ser feito de maneira muito simples utilizando um for, ficando dessa maneira:
print("-"*30)

# Utilização com python versão 2.7
for x in str(input("Digite seu nome: ")):
   print(x)

# Utilização com python versão 3+
for x in input("Digite seu nome: "):
   print(x)

Essa seria uma maneira mais simples e fácil de implementar.
Você pode ler mais sobre iteração de string em Python em: artigo e artigo.
Comment: Você não precisa converter a saída de `input` para `str`. No Python 3+ sempre será `str`.
Comment: Verdade, mas como não foi especificado a versão forcei a conversão.  Irei alterar para servir para mais casos.
Answer: Para resolver esta questão, basta implementar o seguinte código...
palavra = input('Digite uma palavra: ')

for c in palavra:
    print(c)

Imprimir String na vertical em Python


Why Views Data relationship between custom entity type and node doesn't work?

Question: Fields names are equal in both tables.
Inside hook_views_data:
<code>  $data['stream']['table']['join'] = array(
    'node' => array(
      'left_field' => 'nid',
      'field' => 'nid',
    ),
  );

 $data['stream']['nid'] = array(
    'title' => t('Related node'),
    'help' => t('Node related to stream item.'),
    // Define a relationship to the {node} table, so example_table views can
    // add a relationship to nodes. If you want to define a relationship the
    // other direction, use hook_views_data_alter(), or use the 'implicit' join
    // method described above.
    'relationship' => array(
      'base' => 'node', // The name of the table to join with.
      'base field' => 'nid', // The name of the field on the joined table.
      'field' => 'nid',
      'handler' => 'views_handler_relationship',
      'label' => t('Default label for the relationship'),
      'title' => t('Title shown when adding the relationship'),
      'help' => t('More information on this relationship'),
    ),
  );
</code>
(similar to example from api page)
but there isn't above relation in Add relationships box. Could some one give me any hint?
Answer: I solved it by this way:
<code>$data['stream']['table']['join'] = array(
  'node' => array(
    'left_field' => 'nid',
    'field' => 'nid',
    'handler' => 'views_join', // this is actually optional
    'left_table' => 'node'
  ),
);

$data['stream']['nid'] = array(
    'title' => t('Related node'),
    'help' => t('Node related to stream item.'),

    'field' => array(
      'handler' => 'views_handler_field_numeric',
      'click sortable' => TRUE,
    ),

    'filter' => array(
      'handler' => 'views_handler_filter_numeric',
      'allow empty' => TRUE,
      'help' => 'Filter on a related node nid.',
    ),
    'argument' => array(
      'handler' => 'views_handler_argument_numeric',
      'numeric' => TRUE,
      'validate type' => 'nid',
      'help' => 'Argument on related node nid.',
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
      'help' => 'Sort on related node nid field.',
    ),
    'relationship' => array(
      'title' => t('Stream node'),
      'help' => t('Relation to node related to current stream item'),
      'label' => t('Stream node'),
      'base' => 'node',
      'base field' => 'nid',
    ),
  );
</code>


get values of display:table columns to action class struts2

Question: I am creating a table using display tag in JSP, and I'm using decorator to display the last column(Action) which is a link to my action class.
<display:table id='listDisplay' name='detailsList' list='detailsList' requestURI=""  cellpadding="0" cellspacing="0" decorator="com.abc.RecBackupDetailsDecorator">
    <display:column title="Rule Name" property="rulename"></display:column>
    <display:column title="Campaign" property="campname"></display:column>
    <display:column title="Dispositions" property="dispositions"></display:column>
    <display:column title="Backup Server" property="backupserver"></display:column>
    <display:column title="Backup Directory" property="backupdir"></display:column>
    <display:column title="Frequency" property="frequency"></display:column>
    <display:column title="Added On" property="addedon"></display:column>
    <display:column title="Last Run Date" property="lastrundate"></display:column>
    <display:column title="Status" property="status"></display:column>
    <display:column title="Action" property="editDetails"></display:column>
</display:table>

Decorator Class :
public class RecBackupDetailsDecorator extends TableDecorator {

public String getEditDetails() {
    System.out.println("Index of List : " + getViewIndex());
    String editDetails = "Edit";
    return editDetails;
}
}

Now, when I click on edit, I want to get the values of display-table columns in my action class method (editDetailsRecBackupConf) but don't know how can I get the values in my action class.
Answer: You have to make an ajax call to the action class.

suppose on clicking edit link , js function passValueToAction(val) is called where val is the value you need to pass to action. Here the action class called is myActionClass.action along with query parameters.
Register your action call in  struts2.xml (config xml) to map this action call to the action class and give the method you want to call.


SQL LEFT JOIN is not filling a column with values from table 2

Question: SELECT zmogaus_id, hobio_id, hobio_pav2
FROM zmogaus_hobiai
LEFT JOIN hobiai
ON zmogaus_hobiai.hobio_pav2=hobiai.hobio_pav
WHERE zmogaus_id=3

Using this I want to get
zomgaus_id =3 . hobio_id =1 . hobio_pav2 =name1 (from hobio_pav)
zomgaus_id =3 . hobio_id =2 . hobio_pav2 =name2 (from hobio_pav)

But hobio_pav2 stays as an empty column. I tried not having hobio_pav2 column but the problem persists of not adding hobio_pav values to corresponding IDs to hobio_id.
hobio_pav2 column is empty
EDIT:
sample data:
table hobiai: id = 1, hobio_pav = name1;id = 2, hobio_pav = name2;id = 3, hobio_pav = name3;

    table zmogaus_hobiai:
id =1, zmogaus_id=2, hobio_id=2, hobio_pav2 = null;
id =2, zmogaus_id=2, hobio_id=3, hobio_pav2 = null;
id =4, zmogaus_id=3, hobio_id=1, hobio_pav2 = null;
id =5, zmogaus_id=3, hobio_id=3, hobio_pav2 = null;

Desired result:
generated table:
zmogaus_id=3, hobio_id=1, hobio_pav2=name1;
zmogaus_id=3, hobio_id=3, hobio_pav2=name3;

Got result:
generated table:
zmogaus_id=3, hobio_id=1, hobio_pav2= ;
zmogaus_id=3, hobio_id=3, hobio_pav2= ;

Comment: Sample data and desired results, please.
Answer: If you want to update
zmogaus_hobiai
UPDATE zmogaus_hobiai zh INNER JOIN hobiai h
    ON zh.hobio_id=h.id
    SET zh.hobio_pav2 = h.hobio_pav
    WHERE zmogaus_id=3;

And your SELECT would look like this
SELECT zmogaus_id, h.hobio_id, hobio_pav
FROM zmogaus_hobiai  zh
INNER JOIN hobiai h
ON zh.hobio_id=h.id
WHERE zmogaus_id=3:

Comment: I did not want to update the table, I wanted to filter just those hobio_id that have the same zmogaus_id also, and then use that hobio_id and hobio_pav to do some stuff in php, i thought it will be easyer if i just used left join, but now i think i should just give not just hobio_id to zmogaus_hobiai but also hobio_pav.
Sorry im rambling, you gave me an easier solution than waht i was looking for haha
Comment: no in your case is better to use INNEr JOIN and you will se my SELECT query will give you the correct result.
Answer: Are you looking for coalesce()?
SELECT zh.zmogaus_id, coalesce(h.hobio_id, zh.hobio_pav2)
FROM zmogaus_hobiai zh LEFT JOIN
     hobiai h
     ON zh.hobio_pav2 = h.hobio_pav
WHERE zh.zmogaus_id = 3;

Answer: From your sample data, it looks like you just need to fix your join condition - you should be joining on ids rather than on those other string columns:
SELECT z.zmogaus_id, z.hobio_id, h.hobio_pav2
FROM zmogaus_hobiai z
LEFT JOIN hobiai h ON h.id = z.zmogaus_id
WHERE z.zmogaus_id = 3

Note that I added table aliases and prefixed all columns with the table they belong to. This makes the query easier to read, and avoids ambiguity when different tables have homonym columns.


How would you call matrix of response variables?

Question: Matrix of input variables may be called design matrix with each row to be a single datapoint and each column to be a single feature value.
How would you call matrix of response variables with each row to correspond to the same row of the design matrix and each column to be a single component of multivariate response?
(Response matrix? Output matrix?)
Comment: I meant to say I think *multivariate response* is a fitting name for a matrix of response variables.
Comment: @FransRodenburg I ask exactly about multivariate response
Comment: *Data matrix*? I suspect the name you choose is less important than clarifying in context what the rows and columns represent.
Answer: What I know is the term multivariate response is appropriate when referring to such matrix. The term output matrix is somewhat also used, but can be ambiguous since many operations can also have a matrix as a result, yet not appropriately a response.


6502 Assembly question: Should I have an instance of SEC for each SBC when there are multiple SBC in a string of calculations?

Question: According to this website, under the "major uses" for CLC, it states:

If there are to be a series of additions (multiple-byte addition), only the first ADC is preceded by CLC since the carry feature is necessary.

Under the "major uses" for SBC it states:

You always SEC (set the carry flag) before an SBC operation so you can tell if you need a "borrow".

In other words for a series of consecutive ADC operations, you only need a CLC before the first, but before a series of consecutive SBC operations, you should have a SEC before each. Is this correct?
Comment: If you use the consecutive `SBC` to implement multi-byte subtraction then you must not use a `SEC` to allow the borrow (carry) to propagate. Similarly for `ADC` of course.
Answer:
If there are to be a series of additions (multiple-byte addition), only the first ADC is preceded by CLC since the carry feature is necessary

This is written kind of misleadingly.  If you are using a series of ADC to implement multiple-precision addition, e.g. adding two 16-bit or 32-bit numbers, then you do want CLC before the first one only.  But if you have several consecutive ADC that are adding unrelated 8-bit numbers, then you want a CLC before each of them.  Otherwise, a carry from one addition would be propagated into an unrelated sum.
Then the case for SBC is exactly analogous.  If you are doing several unrelated 8-bit subtractions, you want to SEC before each one.  If you are using a series of SBC to implement 16-bit or 32-bit subtraction, etc, then you want SEC before the first one only.
Answer: There is no difference between adding and substracting numbers in 6502. So, CLC and SBC behaves the same. Clearing or setting carry flag before the next operation is completely your decision. You should also understand CLC can be used with substraction and SBC can be used with addition. For example;
lda #$40
clc
adc $10
sta $1000
inc $1000

In this example we add $10 memory address value to $40 and then increase the ending result by one. Instead we can do this.
lda #$40
sec
adc $10
sta $1000

This will give you the same result without an extra INC operation.
CLC and SEC use cases are very similar and has no difference like your original question. But you should not directly relate them to addition and substraction. You should always ask the question "which carry state do i need at this stage?" and if required, use CLC and SEC accordingly.


Pre-select Group Audience for Organic Groups

Question: Here is my situation.
I am using the latest version of Organic Groups on Drupal 7. Every user on my site is part of one group and one group only. Is there a way to make it so that when users are creating group content, the group they belong to is automatically pre-selected? Again, every user is only in one group (but there are numerous groups), so it's superfluous to force them to make a group selection whenever they are creating group content.
Answer:
You can use Field Permission module to not allow a user to see the group field on content type.
Use  hook_form_BASE_FORM_ID_alter() to set a default field value for group field based on current logged in user.

as a sample code (not tested)
<code>function mymodule_form_node_form_alter(&$form, &$form_state) {
  $node = $form_state['node'];
  if (!isset($node->nid) || isset($node->is_new)) {
    global $user;
    $groups = og_get_groups_by_user($user);
      if(is_array($groups)) {
      // This needs to be evaluated to check proper mapping of what field expect to set a default default field value
      $form['group_field_name']['#default'] = $groups[0];
      }
  }
}
</code>
Comment: Hmmmm, but right now, when creating the content type, the group options are None and whatever group the user is in. If I just hid the field using Field Permission, the user's group wouldn't end up getting selected...
Comment: for now do not hide the field, keep it there till you fix second step to make, once you make sure you are able to set the default group then hide the field. If you are not finding the codes mentioned in second point, there is an alternate approach http://drupal.stackexchange.com/questions/16151/organic-groups-automatic-audience-selection
Comment: if I went with your code approach, where would I put it?
Answer: Entity Reference Prepopulate is the best way to do this without custom code like arpitr described. You would rewrite the links to look like
<code>/node/add/article?og_group_ref=123
</code>
These links could be on the group's page or you may find a token to populate the gid automatically based on user.


How to load a node given a menu link id?

Question: I have this id via $link->getParent():
menu_link_content:6cf83fce-228f-42da-bc39-bea06c767510

How do I get the node id of that menu link?
Answer: Something like:
if ('entity.node.canonical' == $link->getRouteName()) {
  $params = $link->getRouteParameters();
  $nid = $params['node'];
}

Answer: See EntityRepository::loadEntityByUuid() for a non-deprecated way of loading by UUID.
Comment: that would load the menu item, not the node?
Answer: You can load the node from the (already depreciated) entityManager using the UUID:
$node = \Drupal::entityManager()->loadEntityByUuid('6cf83fce-228f-42da-bc39-bea06c767510');

Comment: I would use the depreciated method mostly because the documentation and tutorials haven't yet been updated to make it clear how to use the replacement interface based solution. And because D8 will have a long shelf life so I would not be too worried about using a D8-only solution.  If you need more help more code/context would be useful.
Comment: the menu:uuid string actually loads the menu link, not the corresponding node
Comment: why would I want to use a deprecated method? :) whats the not deprecated way? thanks!
Comment: it says `Uncaught PHP Exception Drupal\Component\Plugin\Exception\PluginNotFoundException: "The "1365f9ba-2052-4773-827a-2475f1347aa0" entity type does not exist."`
Comment: see my above comment please
Answer: Elaborating on simesy's answer.
$menu_id = $link->getParent();
$menu_link_manager = \Drupal::service('plugin.manager.menu.link');
$menu_item = $menu_link_manager->createInstance($menu_id);
if ('entity.node.canonical' == $menu_item->getRouteName()) {
  $params = $menu_item->getRouteParameters();
  $nid = $params['node'];
}

Comment: How to get a node by menu link as `$entity->id()` with bundle `'menu_link_content'` inside of the function `mymodulename_entity_update()` ? If I use your way, I receive the error `Call to undefined method Drupal\menu_link_content\Entity\MenuLinkContent::getRouteParameters()...`


How to use jsf in "namespaced mode"

Question: In a website we want to integrate some snippets provided by jsf-applications, think of a dashboard-app or a "portal-light". While analyzing the requirements we came across a blog-post by Arjan Tjims on jsf 2.3 new features, where he mentioned a new "namespaced mode":

In namespaced mode, which is specifically intended for Portlets but can be used in other environments as well, the partial response is given an id that's taken to be the "naming container id". All predefined postback parameter names (such as "javax.faces.ViewState", "javax.faces.ClientWindow", "javax.faces.RenderKitId", etc) are prefixed with this and the naming separator (default ":"). e.g. javax.faces.ViewState" becomes "myname:javax.faces.ViewState". Namespaced mode is activated when the UIViewRoot instance implements the NamingContainer interface.

Our application might be a usecase for that "namespaced mode", so we want to give it a try.
We built a MyUIViewRoot where we implemented NamingContainer and wrapped the original UIViewRoot-instance. We registered a MyViewHandler in faces-config.xml which handles the wrapping of the ViewRoot. For testing we used a simple counter-app with two <h:form>-elements (seems to be important).
We find that "namespace mode" seems to be activated, eg the javax.faces.ViewState indeed is prepended by some namespace and becomes j_id1:javax.faces.ViewState:0. But both actions do not work any more - the postback request does not restore the View any more but creates a new one. So with our simple approach we are missing something (btw, removing only the implements NamingContainer from MyUIViewRoot the counter-app works fine again).

Is there some documentation, a howto or a working example out there that we have overlooked?
How to activate "namespace mode" correctly? What have we missed to make the postback work again?
How can we make MyUIViewRoot to prepend the ViewState with myNamespace?

The application is running in a payara-5 application server.
Our index.xhtml:

<h:head/>
<h:body>
  <h:form id="counterForm">
    <h:panelGrid columns="2">
      <h:outputLabel value="Counter" />
      <h:outputText value="#{counterUiController.counter}" />
    </h:panelGrid>
    <h:commandButton value="inc" action="#{counterUiController.incAction}">
      <f:ajax execute="@form" render="@form" />
    </h:commandButton>
  </h:form>
  <h:form id="resetForm">
    <h:commandButton value="reset" action="#{counterUiController.resetAction}">
      <f:ajax execute="@form" render=":counterForm" />
    </h:commandButton>
  </h:form>
</h:body>

The CounterUiController:
@Named
@ViewScoped
public class CounterUiController implements Serializable {

    private int counter;

    public int getCounter() {
        return counter;
    }

    public void incAction() {
        counter++;
    }

    public void resetAction() {
        counter=0;
    }
}

Our UIViewRoot-Implementation:
public class MyUIViewRoot extends UIViewRoot implements NamingContainer, FacesWrapper<UIViewRoot> {

    private static final Logger LOG = Logger.getLogger(MyUIViewRoot.class.getName());

    private UIViewRoot wrapped;

    public MyUIViewRoot(UIViewRoot wrapped) {
        this.wrapped = wrapped;
        LOG.log(Level.INFO, "new instance created: {0}", this);
    }

    @Override
    public UIViewRoot getWrapped() {
        return wrapped;
    }

    @Override
    public String createUniqueId() {
        return wrapped==null ? null : wrapped.createUniqueId();
    }

    @Override
    public void setId(String id) {
        if( wrapped!=null ) {
            wrapped.setId(id);
        }
    }
    // all other methodes delegated to `wrapped` directly
}

Our ViewHandler:
public class MyViewHandler extends ViewHandlerWrapper {

    private static final Logger LOG = Logger.getLogger(MyViewHandler.class.getName());

    public MyViewHandler(ViewHandler wrapped) {
        super(wrapped);
    }

    @Override
    public UIViewRoot createView(FacesContext context, String viewId) {
        UIViewRoot retval = super.createView(context, viewId);
        retval = wrapIfNeeded(retval);
        LOG.log(Level.INFO, "view created: {0}", retval);
        return retval;
    }

    @Override
    public UIViewRoot restoreView(FacesContext context, String viewId) {
        UIViewRoot retval =  super.restoreView(context, viewId);
        retval = wrapIfNeeded(retval);
        LOG.log(Level.INFO, "view restored: {0}", retval);
        return retval;
    }

    private UIViewRoot wrapIfNeeded(UIViewRoot root) {
        if (root != null && !(root instanceof MyUIViewRoot)) {
            LOG.log(Level.INFO, "view wrapped: {0}, {1}", new Object[] { root, root.getId() });
            return new MyUIViewRoot(root);
        } else {
            return root;
        }
    }
}

Answer: You need to replace the UIViewRoot not to wrap it.
public class NamespacedView extends UIViewRoot implements NamingContainer {
    //
}

And then in faces-config.xml.
<component>
    <component-type>javax.faces.ViewRoot</component-type>
    <component-class>com.example.NamespacedView</component-class>
</component>

That's basically all. See also the Mojarra IT on this.
Comment: Ouch, thats simple. And to prepend with `myNamespace` we only have to override `getId` I suppose?
Comment: The `` is not (yet?) supported. So overriding `getId()` is probably your best bet.

How to use jsf in "namespaced mode"


Why gradle is throwing error on missing project property

Question: I'm using maven-publish plugin to release an artifact to nexus repository. I don't want to put the actual credentials of my nexus repository in my build.gradle file. So I decided to use project properties like shown below
credentials {
            username "$nexus_username"
            password "$nexus_password"
}

Now I can use gradle publish -Pnexus_username=<myusername> -Pnexus_password=<mypass> to publish my artifact to my nexus repository. But it doesn't make any sense to keep passing this project properties for a normal gradle build. And if I don't pass gradle is throwing an error saying Could not find property 'nexus_username' Anybody know a better approach to solve this.
Comment: Thanks for this question and answer - this workaround is a lifesaver. Wondering if since posting this you've found any better alternatives? Thanks.
Answer: Found a solution after some digging
if(! hasProperty("nexus_username")){
    ext.nexus_username=""
}
if(! hasProperty("nexus_password")){
    ext.nexus_password=""
}

Here what I'm doing is creating a blank username and password if the project property is not available. But I still feel this is a work around and not the right solution. Please do respond if anybody find a more elegant solution.
Answer: I keep my credentials in my user-specific Gradle properties, so only my user account has access to the values and I can leave dummy (or undefined) values in the Gradle project.  That way, if I distribute the project to others or commit the project to source control, no one gets my personal credentials or settings.
As explained in the Gradle User Guide: The Build Environment, your user-specific properties will override any properties set in a project's local gradle.properties file where the property names match. Values entered on the command line using -P will still take precedence over both of the former sources.
Your user-specific file is named gradle.properties and is located in the path specified by the GRADLE_USER_HOME environment variable (if set), and defaults to:

Linux / OS X: ~/.gradle/gradle.properties
Windows: %USERPROFILE%\.gradle\gradle.properties

You can then use the hasProperty approach in the build script, or define default values by editing (or creating) the project's gradle.properties file (at the same level as your build.gradle file):
# Do not put real credentials here!
# Instead, copy to ~/.gradle/gradle.properties and set the values there.
nexus_username =
nexus_password =

The main caveat to this approach is that your user-specific property file can only provide a single value for a given property name. That could be an issue if you have multiple projects that use the same property names but need different values.  Also, the file is plain text, so it might not be the best place for passwords unless you're willing to take that risk.


Intuition of conditional independence in DAGs

Question:
In the DAG above, we have $A$ conditionally independent of $E$ when $C$ and $B$ are observed (that is $A\perp E|B,C$), but not when only $C$ is observed  (that is $A\not\perp E|C$). I don't have a good intuition on why this is true, it feels to me like it should still be conditionally independent.
Could anyone give me a good explanation of why my intuition is wrong?
Answer: Flow of dependencies in DAGs are determined by the d-separation criteria, and two variables are d-separated if and only if every path (without considering the orientation of the arrows) is blocked.
Now in your specific example, by conditioning on $C$ you block the path $A \rightarrow C \rightarrow E$ but you also open the path $A \rightarrow C \leftarrow B \rightarrow D \rightarrow E$, therefore not all paths are blocked and we got $A\not\perp E|C$.
On the contrary, by conditioning on both $C,B$ or $C,D$, all the paths between $A$ and $E$ are d-separated.


Annotation Type Expected

Question: I just created this unit test, and I get a red squiggly under @Test that says "Annotation Type Expected". What does this mean?
package com.sample.bank.account;

import junit.framework.Test;
import static org.junit.Assert.*;

public class LoanTest {

    @Test
    public void testAppliyPaymentSubtractsCorrectAmount()
    {
        Loan loan = new Loan("test subtract", 1000);
        loan.applyPayment(100);
        assertEquals(900, loan.getBalance());
    }
}

Answer: The import should be
import org.junit.Test;

and not
import junit.framework.Test;

Answer: The import should be
import org.junit.Test;

If you are using jUnit 4.
If you are using upto jUnit 3.8.
import junit.framework.Test;

should work fine.

Annotation Type Expected