Disable Rule which is causing a redirect loop

Question: I have created a rule for logged in members that if they go to the home page it redirects them to a different page. The home page needs to be different for anonymous and authenticated users.
One problem is that my rule is not working. I have created a redirect loop by mistake. This means I can not get to the rules interface to disable the module. I know I could disable the rules module via drush however I will have the same problem when I turn it back on.
I had a quick look in db and see the rules_rules table. However the data is stored as a blob so I can not edit it. Except for deleting my rules what could I do to disable it?
Comment: It always redirects, whatever page you're on?
Comment: Yep. The rule I set up ended matching all pages rather than the home page. So all pages for authenticated users cause a redirection loop.
Answer: You got a few options.

You can try to edit the data by deserializing it with PHP and try to get some meaning out of it. Most likely there is a status which is either 1 or 0.
You could delete the rule from the database entirely.
You can temporarily modify the rules_invoke_event (rules.module line 249 for 1.4), if you comment out the call_user_func_array call, no rule should be invoked on the site.

Either of these should work, personally I would go for the last one if I had write access to the rules files.
Comment: /sites/all/modules/rules/rules/rules.module Worked for me on D6. Thanks
Answer: In Rules 7.x-2.6:

In the rules_config table set the active column to 0 for the problematic rule
Empty/Truncate the cache_rules table
Answer: They way i did to revert reload in one of my drupal 6 project.

logged in using ssh to the terminal.
logged in to database.
selected database.
goto rules_rules table.
written sql quary to delete affcting rule.
Answer: Devel Module module has a nifty setting for this. Install devel module and visit devel/settings, enable the option Display redirection page.
As the description says

When a module executes drupal_goto(), the query log and other
  developer information is lost. Enabling this setting presents an
  intermediate page to developers so that the log can be examined before
  continuing to the destination page.

you can visit the intermediate page in-spite of the redirection.


How to set up an Android source repo while hosting the git trees as private repositories on github?

Question: I am trying to set up a private repository of Android source code while hosting the git trees on github as private repos.
I have no problem changing the manifest.xml file to point to public git trees hosted on github in the same way that CynagonMod does, but when trying to point to private repos I get the following error when trying "repo sync":

Initializing project username/android_external_webkit ...
fatal: The remote end hung up unexpectedly
error: Cannot fetch username/android_external_webkit

Where username/android_external_webkit is of course a private github repo of the same name.
I understand the error occurs since I did not specify my user name and credentials to github, but I fail to see how to do it in the manifest.xml with repo.
Any ideas?
Thanks!
Gilad
Answer: Well, feeling silly to answer my own question but I found out the answer so maybe I will save a few minutes to the next person that runs into it.
The answer is very simply: in the manifest.xml file, create a remote tag with the fetch specifying ssh as the transport and "git" as the username. Here is an example:
<remote name="private_stuff" fetch="ssh://firstname.lastname@example.com/" />

Now use "private_stuff" as the remote field of the git trees you want to pull. For example:
<project path="xyz" name="username/xyz" remote="private_tuff" />

And init and sync the repo as usual.
Comment: Its completely okay to answer your own question.
Comment: Man I do wish repo was a bit more documented. How did you find this?
Answer: It seems the proper method is to use a local_manifest.xml in the ./repo directory as per this link
see also the official repo documentation
Answer: just add this to your manifest
<remote name="github" fetch="https://github.com/" />


How to ignore backslashes as escape characters in Python?

Question: I know this is similar to many other questions regarding backslashes, but this deals with a specific problem that has yet to have been addressed. Is there a mode that can be used to completely eliminate backslashes as escape characters in a print statement? I need to know this for ascii art, as it is very difficult to find correct positioning when all backslashes must be doubled.
print('''
/\\/\\/\\/\\/\\
\\/\\/\\/\\/\\/
''')
\```

Comment: `print(r'''
/\\/\\/\\/\\/\\
\\/\\/\\/\\/\\/
''')` using `r` for raw string maybe?
Answer: Preface the string with r (for "raw", I think) and it will be interpreted literally without substitutions:
>>> # Your original
>>> print('''
... /\\/\\/\\/\\/\\
... \\/\\/\\/\\/\\/
... ''')

/\/\/\/\/\
\/\/\/\/\/

>>> # as a raw string instead
>>> print(r'''
... /\\/\\/\\/\\/\\
... \\/\\/\\/\\/\\/
... ''')

/\\/\\/\\/\\/\\
\\/\\/\\/\\/\\/

These are often used for regular expressions, where it gets tedious to have to double-escape backslashes. There are a couple other letters you can do this with, including f (for format strings, which act differently), b (a literal bytes object, instead of a string), and u, which used to designate Unicode strings in python 2 and I don't think does anything special in python 3.


Throw-in directly into the goal

Question: At the international playing level, has anyone ever thrown the ball directly into the goal, from a throw-in?  Directly meaning, without touching a member from either team, including the goalie.  It does not matter if it touches the ground first.
Comment: Yes.  Without touching either team, or the goalie.  The ground would be acceptable.
Comment: PSA: [This question is being discussed on meta](https://sports.meta.stackexchange.com/questions/919/are-questions-specifically-asking-about-trivial-illegal-situations-without-being). Everyone is also reminded of the [Code of Conduct](https://sports.stackexchange.com/conduct) - it is possible to disagree without being rude.
Comment: Do you mean without touching any player or ground?
Comment: Most players probably know that you can not score from a throw in though...
Comment: It happened [here](https://www.youtube.com/watch?v=T_zPxzbBV4c). I don't know the exact references of this situation, but considering the joy of the scorer, it seems that the goal has been accepted... but it souldn't.
Answer: Yes, it happened the 2 october 2014 in a Europa League game between Feyenoord and Standard Liege (2-1).

It was officially credited to defender Sven van Beek (wearing 22), but it looked as though it was scored directly from the throw by Miquel Nelom.

It seems the referee judged that the ball touched someone, even it didn't.
Source.
Comment: Thanks.  I do appreciate this answer.  I was hoping to find an instance where it was not presumed to have gone off another player.  I'll give it a little time.  If no one comes to the dance, the cred is yours.

Throw-in directly into the goal


Given a node object how can I detect if it's first term (or term in a chosen vocabulary) contains a taxonomy image?

Question: Using php code and a node object, how can I detect whether or not the node's first term (or term in a chosen vocabulary) has a taxonomy image? Any help appreciated.
Answer: taxonomy_image_display returns an empty string iff the term has no image.
Given a node $node, the terms are stored in $node->taxonomy as an array indexed by term ID (see taxonomy_nodeapi($node, $op = 'load')).


How to give the total of the price and the quantity at the same time

Question: First of all, please excuse my JS script knowledge. It's very little and mainly I'm a PHP programmer. I've found this great and simple script which calculates the total of the products table rows and also gives the grand total of the whole table. However, it only does the calculation when I change the quantity. Is it possible to make it does the calculation every time I change the price OR the quantity?
Here is the code:

Comment: Why is this tagged with php.
Comment: Yes, but nothing you show makes this run anytime so how do you run this
Answer: Does something like this work?

Comment: Thank you so much dear Shadab it worked perfectly. You made my day friend :)))
Comment: Glad to be of help :)
Answer: Could you try this? You can trigger an event using '.qty, .price' in the table.
And I recommend using constants like const qty = ... instead of global variable var qty= ... inside of a block.


How many ways are there to distribute $2$ indistinguishable white and $4$ indistinguishable black balls into $4$ indistinguishable boxes?

Question: How many ways are there to distribute $2$ indistinguishable white and $4$ indistinguishable black balls into $4$ indistinguishable boxes?
If the question was asked as "distinct boxes", I can solve. But now, I am confused. Please show how to solve this type of question explicitly.
Comment: They are just letting you know there is nothing different about the boxes.  They are distinct as they are not the same box, but they are identical.
Answer: Since the bags are indistinguishable, what matters here is the number of balls of each color in the boxes.
There are two distinguishable ways to distribute the two indistinguishable white balls to the four indistinguishable boxes, either both balls are placed in one box or two boxes receive one white ball apiece.
There are five ways to distribute the four indistinguishable black balls to the four indistinguishable boxes.  They correspond to the partitions of a set with four elements:
\begin{align*}
4 & = 4\\
  & = 3 + 1\\
  & = 2 + 2\\
  & = 2 + 1 + 1\\
  & = 1 + 1 + 1 + 1
\end{align*}
Note that there are two partitions of a set with two elements:
\begin{align*}
2 & = 2\\
  & = 1 + 1
\end{align*}
We consider cases (a brute force approach).
Case 1:  The two white balls are placed in one box. The four black balls are placed in one box.
There are two possible outcomes.  Either all six balls are placed in one box or the two white balls are placed in a separate box from the four black balls.
\begin{align*}
&\{4b, 2w\}\\
&\{4b\}, \{2w\}
\end{align*}
Case 2:  The two white balls are placed in one box.  Three of the black balls are in one box, and the other is placed in a separate box.
There are three possible outcomes.  The two white balls are placed in the box with three black balls, the box with one black ball, or a box with no black balls.
\begin{align*}
&\{3b, 2w\}, \{b\}\\
&\{3b\}, \{b, 2w\}\\
&\{3b\}, \{b\}, \{2w\}
\end{align*}
Case 3:  The two white balls are placed in one box.  Two of the black balls are placed in one box, and the other two black balls are placed in another box.
There are two possible outcomes.  The two white balls are placed in a box with two black balls or a box with no black balls.
\begin{align*}
&\{2b, 2w\}, \{2b\}\\
&\{2b\}, \{2b\}, \{2w\}
\end{align*}
Case 4:  The two white balls are placed in one box.  Two of the black balls are placed in one box, with two other boxes receiving one black ball apiece.
There are three possible outcomes.  The two white balls are placed in the box containing two black balls, a box containing one black ball, or the box containing no black balls.
\begin{align*}
&\{2b, 2w\}, \{b\}, \{b\}\\
&\{2b\}, \{b, 2w\}, \{b\}\\
&\{2b\}, \{b\}, \{b\}, \{2w\}
\end{align*}
Case 5:  Two white balls are placed in one box.  Each of the four black balls is placed in a separate box.
There is one possible outcome.  Two white balls are placed in one of the four boxes with a black ball.
$$\{b, 2w\}, \{b\}, \{b\}, \{b\}$$
Case 6:  The two white balls are placed in separate boxes.  All four black balls are placed in one box.
There are two cases.  The four black balls are placed in a box with one white ball or no white balls.
\begin{align*}
&\{4b, w\}, \{w\}\\
&\{4b\}, \{w\}, \{w\}
\end{align*}
Case 7:  The two white balls are placed in separate boxes.  Three black balls are placed in one box, and one black ball is placed in another box.
There are four possible outcomes.  Either a white ball is placed in the box with three black balls or it is not.  Either a white ball is placed in the box with one black ball or it is not.
\begin{align*}
&\{3b, w\}, \{b, w\}\\
&\{3b, w\}, \{b\}, \{w\}\\
&\{3b\}, \{b, w\}, \{w\}\\
&\{3b\}, \{b\}, \{w\}, \{w\}
\end{align*}
Case 8:  The white balls are placed in separate boxes.  Two black balls are placed in one box, and the other two are placed in another.
There are three possible outcomes.  The white balls are placed in both boxes containing two black balls, exactly one white ball is placed in a box containing two black balls, or no white balls are placed in a box containing two black balls.
\begin{align*}
&\{2b, w\}, \{2b, w\}\\
&\{2b, w\}, \{2b\}, \{w\}\\
&\{2b\}, \{2b\}, \{w\}, \{w\}
\end{align*}
Case 9:  The white balls are placed in separate boxes.  Two black balls are placed in one box, with two other boxes receiving one black ball apiece.
There are four possible outcomes.  If a white ball is placed in the box with two black balls, the other white ball is placed in a box containing one black ball or no black balls.  Otherwise, one white ball is placed in each box containing one black ball or one white ball is placed in a box containing one black ball and the other white ball is placed in a box containing no black balls.
\begin{align*}
&\{2b,w\}, \{b,w\}, \{b\}\\
&\{2b, w\}, \{b\}, \{b\}, \{w\}\\
&\{2b\}, \{b, w\}, \{b, w\}\\
&\{2b\}, \{b, w\}, \{b\}, \{w\}
\end{align*}
Case 10:  The two white balls are placed in separate boxes.  Each of the four black balls is placed in a separate box.
There is one possible outcome.  Two boxes receive a black ball ball and a white ball, while the other two receive only a black ball.
$$\{b, w\}, \{b, w\}, \{b\}, \{b\}$$
Total:  Since the ten cases are mutually exclusive, the answer to your question is found by adding the number of outcomes for each case.
$$2 + 3 + 2 + 3 + 1 + 2 + 4 + 3 + 4 + 1 = 25$$
Answer: If the answer for distinct box is $N$, then $N/4!$ for indistinquisable box. When the boxs are distinct, let them be A,B,C,D. You may think that you have to put balls into boxes by the order of A,B,C,D one by one, and the permutation is 4! for 4 boxes' orders. When the boxes are the same, 4! is not needed. For this kind of questions, "distinct" ones are generally more directly available than "indistinquisable" ones. The solution always involves "cancle the order".
Comment: Your answer is incorrect.  For instance, there are four ways of placing all the balls in one box when the boxes are indistinguishable and one way to place them all in one box when the boxes are indistinguishable.  Dividing $4$ by $4!$ yields $1/6$ rather than $1$.


REST domino data services mailbox appointment compute with form error

Question: I am developing a client application to integrate with Domino 8.5.3 (I have added the OSGI pack from openntf). Specifically when trying to add a new appointment via domino data services, I can add the document using the call to
http://xx.xx.xx.xx/mail/administ.nsf/api/data/documents?form=Appointment

but if I try and use the compute with form option ie
http:/xx.xx.xx.xx/mail/administ.nsf/api/data/documents?computewithform=true&form=Appointment

I get a 400 error (bad request) the error as show below. I have also tried to ad a reservation in the Resource and reservation database and the computewithform works. Any ideas why the appointments form doesn't allow the computewithform option ?
Error Trace :
"code":400,
    "text":"Bad Request",
    "message":"@Function is not valid in this context",
    "type":"text",
    "data":"NotesException: @Function is not valid in this context

lotus.domino.local.Document.NcomputeWithForm(Native Method)
  lotus.domino.local.Document.computeWithForm(Unknown Source)
  com.ibm.domino.das.resources.DocumentCollectionResource.postDocument(DocumentCollectionResource.java:162)
  sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:60)
  sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:37)
  java.lang.reflect.Method.invoke(Method.java:611)
  org.apache.wink.server.internal.handlers.InvokeMethodHandler.handleRequest(InvokeMethodHandler.java:63)
  org.apache.wink.server.handlers.AbstractHandler.handleRequest(AbstractHandler.java:33)
  org.apache.wink.server.handlers.RequestHandlersChain.handle(RequestHandlersChain.java:26)
  org.apache.wink.server.handlers.RequestHandlersChain.handle(RequestHandlersChain.java:22)
  org.apache.wink.server.handlers.AbstractHandlersChain.doChain(AbstractHandlersChain.java:63)
  org.apache.wink.server.internal.handlers.CreateInvocationParametersHandler.handleRequest(CreateInvocationParametersHandler.java:54)
  org.apache.wink.server.handlers.RequestHandlersChain.handle(RequestHandlersChain.java:26)
  org.apache.wink.server.handlers.RequestHandlersChain.handle(RequestHandlersChain.java:22)
  org.apache.wink.server.handlers.AbstractHandlersChain.doChain(AbstractHandlersChain.java:63)
  org.apache.wink.server.internal.handlers.FindResourceMethodHandler.handleResourceMethod(FindResourceMethodHandler.java:151)
  org.apache.wink.server.internal.handlers.FindResourceMethodHandler.handleRequest(FindResourceMethodHandler.java:65)
  org.apache.wink.server.handlers.RequestHandlersChain.handle(RequestHandlersChain.java:26)
  org.apache.wink.server.handlers.RequestHandlersChain.handle(RequestHandlersChain.java:22)
  org.apache.wink.server.handlers.AbstractHandlersChain.doChain(AbstractHandlersChain.java:63)
  org.apache.wink.server.internal.handlers.FindRootResourceHandler.handleRequest(FindRootResourceHandler.java:95)
  org.apache.wink.server.handlers.RequestHandlersChain.handle(RequestHandlersChain.java:26)
  org.apache.wink.server.handlers.RequestHandlersChain.handle(RequestHandlersChain.java:22)
  org.apache.wink.server.handlers.AbstractHandlersChain.doChain(AbstractHandlersChain.java:63)
  org.apache.wink.server.internal.handlers.HeadMethodHandler.handleRequest(HeadMethodHandler.java:53)
  org.apache.wink.server.handlers.RequestHandlersChain.handle(RequestHandlersChain.java:26)
  org.apache.wink.server.handlers.RequestHandlersChain.handle(RequestHandlersChain.java:22)
  org.apache.wink.server.handlers.AbstractHandlersChain.doChain(AbstractHandlersChain.java:63)
  org.apache.wink.server.internal.handlers.OptionsMethodHandler.handleRequest(OptionsMethodHandler.java:46)
  org.apache.wink.server.handlers.RequestHandlersChain.handle(RequestHandlersChain.java:26)
  org.apache.wink.server.handlers.RequestHandlersChain.handle(RequestHandlersChain.java:22)
  org.apache.wink.server.handlers.AbstractHandlersChain.doChain(AbstractHandlersChain.java:63)
  org.apache.wink.server.internal.handlers.SearchResultHandler.handleRequest(SearchResultHandler.java:33)
  org.apache.wink.server.handlers.RequestHandlersChain.handle(RequestHandlersChain.java:26)
  org.apache.wink.server.handlers.RequestHandlersChain.handle(RequestHandlersChain.java:22)
  org.apache.wink.server.handlers.AbstractHandlersChain.doChain(AbstractHandlersChain.java:63)
  org.apache.wink.server.internal.log.ResourceInvocation.handleRequest(ResourceInvocation.java:92)
  org.apache.wink.server.handlers.RequestHandlersChain.handle(RequestHandlersChain.java:26)
  org.apache.wink.server.handlers.RequestHandlersChain.handle(RequestHandlersChain.java:22)
  org.apache.wink.server.handlers.AbstractHandlersChain.doChain(AbstractHandlersChain.java:63)
  org.apache.wink.server.internal.log.Requests.handleRequest(Requests.java:76)
  org.apache.wink.server.handlers.RequestHandlersChain.handle(RequestHandlersChain.java:26)
  org.apache.wink.server.handlers.RequestHandlersChain.handle(RequestHandlersChain.java:22)
  org.apache.wink.server.handlers.AbstractHandlersChain.doChain(AbstractHandlersChain.java:63)
  org.apache.wink.server.handlers.AbstractHandlersChain.run(AbstractHandlersChain.java:48)
  org.apache.wink.server.internal.RequestProcessor.handleRequestWithoutFaultBarrier(RequestProcessor.java:207)
  org.apache.wink.server.internal.RequestProcessor.handleRequest(RequestProcessor.java:154)
  org.apache.wink.server.internal.servlet.RestServlet.service(RestServlet.java:119)
  com.ibm.domino.services.AbstractRestServlet.doService(AbstractRestServlet.java:70)
  com.ibm.domino.das.servlet.DasServlet.doService(DasServlet.java:182)
  com.ibm.domino.services.AbstractRestServlet.service(AbstractRestServlet.java:55)
  javax.servlet.http.HttpServlet.service(HttpServlet.java:806)
  org.eclipse.equinox.http.registry.internal.ServletManager$ServletWrapper.service(ServletManager.java:180)
  org.eclipse.equinox.http.servlet.internal.ServletRegistration.handleRequest(ServletRegistration.java:90)
  org.eclipse.equinox.http.servlet.internal.ProxyServlet.processAlias(ProxyServlet.java:111)
  org.eclipse.equinox.http.servlet.internal.ProxyServlet.service(ProxyServlet.java:67)
  javax.servlet.http.HttpServlet.service(HttpServlet.java:806)
  com.ibm.domino.xsp.adapter.osgi.OSGIModule.invokeServlet(OSGIModule.java:165)
  com.ibm.domino.xsp.adapter.osgi.OSGIModule.access$0(OSGIModule.java:151)
  com.ibm.domino.xsp.adapter.osgi.OSGIModule$1.invokeServlet(OSGIModule.java:132)
  com.ibm.domino.xsp.adapter.osgi.AbstractOSGIModule.invokeServletWithNotesContext(AbstractOSGIModule.java:179)
  com.ibm.domino.xsp.adapter.osgi.OSGIModule.doService(OSGIModule.java:126)
  com.ibm.domino.xsp.adapter.osgi.OSGIService.doService(OSGIService.java:391)
  com.ibm.designer.runtime.domino.adapter.LCDEnvironment.doService(LCDEnvironment.java:341)
  com.ibm.designer.runtime.domino.adapter.LCDEnvironment.service(LCDEnvironment.java:297)
  com.ibm.domino.xsp.bridge.http.engine.XspCmdManager.service(XspCmdManager.java:272)"
Answer: The Appointment form (actually _CalendarEntry) was designed to be rendered in the Notes client.  I'm guessing it executes @Functions that will only run in the context of Notes.
There is a separate form called _wCalendarEntry.  It has the same alias (Appointment) as does _CalendarEntry, but _wCalendarEntry was designed to be rendered by the web engine.  Ideally you should be able to compute with that form instead.  You can experiment with that idea, but I'm not sure that will work.
As I mentioned in the answer to this question, the Domino calendar service is much more suited to creating events on a calendar, but you would have to upgrade to 9.0.1 or at least 9.0.
Comment: I agree the version 9x will be easier that will be my next Domino project, but before that I have to finish the 8.5.x integration. I have now moved the solution to a web services server side and can book a meeting, send a Notice to the RnRmgr and get an answer. The answer I get back doesn't appear to effect the Appointment, do you know if this has to be done manually ? As it may also be an issue with my notice not being connected properly to the Appointment. Thanks a lot for your help.
Comment: When the system sends an Accept notice for the room, that should automatically be reflected in the View Invitee Status dialog.  You shouldn't have to do any manual steps to make that happen.  If View Invitee Status isn't picking up the Accept notice, there could be a problem with your original invitation.
Comment: I checked and the Invitee Status is set correctly on Accept and Decline, so it looks good for that. For the computewithform I tried the other form I don't get any error but I think it is not detecting the form and so uses the default, in Notes it says unknown form.         Given the workflow is correct, I think I don't require the computewithform functionality.


how are scales of the same class (e.g. major scales) musically different?

Question: I have recently learned the principles of the standard twelve-tone octave applied to major and minor scales. I understand each scale is defined by its main note, and the pattern of intervals, of half versus full tones, ascending the octave.
The C-major scale, for example, shares with other major scales the interval relationship that the half-tone interval mediates the third and fourth tones, as well as the seventh and eighth (final) tones, with all other intervals being full tones.
Since musical structure is carried essentially by the relationship among tones (the ratio of physical frequencies between any two tones), not by a tone itself (the absolute physical frequency of any single tone), it would seem to follow that any composition based on the tones of the  C-major scale may be readily translated to any other major scale with full preservation of the musical structure. Of course, many compositions are described as following a major key other than C. In all, twelve major keys exist, corresponding to the twelve tones into which the octave divides.
In musical terms, artistic or technical, what is the reason for all compositions using a major key not simply using the same particular scale? For example, what is the reason for some compositions being written in C major, while yet others in G major, if both keys share the same essential musical structure?
Comment: Today there definitely are genres and cultures where key is no longer fixed, where the performers pick it at will and transpose as necessary. Jazz—what's the official key of Mack the Knife?—pop, etc (do you tune your "two turntables and a microphone" to A=440?).
Comment: Essentially the question is the same. A further question seemingly not addressed by the responses is why the social conventions have not emerged such that they key would be chosen through the arrangement, or by a soloist, or the members of quartet, and so on, instead of the composer prescribing to the performers that one of the keys is correct.
Comment: The second paragraph describes the intervals of the minor scale while claiming to describe the C major scale.  As to the "further question," composers typically do specify a key. Whether performers are at liberty to transpose them to other keys depends on several factors.  I doubt anyone has ever performed Mozart's _Requiem_ in G minor, for example.
Comment: Try singing Happy Birthday in C major. Then sing it in F major. Compare and analyze these as subjective experiences. Did it feel exactly the same in both keys, or was something different?
Comment: It's interesting that the duplicate contains nothing taking a historical overview of "how we got here." Because that's a big part of the answer: We're working with trends set in motion in medieval days. I'll try to contribute an answer there soon, but the short version is: At first (plainchant, early renaissance) nobody cared much about instrumentation or absolute pitch. It really was infinitely transposable. Ca 1600s-1800s, it started to matter a great deal what instrument a piece was for (thus the physicality), plus pitch became standardized, plus all the temperaments mattered.
Comment: @Andy: The historic background is relevant, but I am trying to understand the question in terms of the historical period (i.e. Common Practice) in which major and minor keys developed not only as essential structural elements, but as identifying characteristics. If [K. 551](https://en.wikipedia.org/wiki/Symphony_No._41_(Mozart)) is given its character by following a major key, then one might describe it as Symphony No. 41 in *the major key*, leaving the distinction between *C* versus *E*, *G*, or another, as a more circumstantial detail than an identifying trait.
Comment: @epl Right; I mean, within that broad overview, that BaroqueClassicalRomantic zone is where it "mattered most." It has a lot to do, as suggested elsewhere, with instrumentation. It started being "Sonata in G" partly because it started being "*Violin* Sonata in G." Early Renaissance stuff is just "Canzonetta for whatever treble instrument you happen to have."
Comment: @Andy: It does make sense to consider that modern developments have provided us with a kind of insulation from the essential character of instruments. Some traditions might be more accessible to a contemporary public through reforming the framing. Considering five pieces of information normally communicated in identifying a work (composer, genre, instruments, key type, central tone), The responses suggest that the association between instrument and central tone may be stronger than either to key type. Today, relations musicians take for granted may confuse rather than inform the public.
Comment: I read this question, then ended up answering the proposed original question (that this got labelled as a duplicate of) instead. Note that the proposed original question ends with "Maybe some keys are particularly easy or hard depending what instrument you are playing?" My added answer to the proposed original gives examples for how some keys are *much* easier to read than others for beginner students who haven't learned notes with accidentals yet.
Answer: A composition doesn't "breathe" until it's performed either on instruments or by vocalists.  Changes to the key signature create opportunities to match the optimal pitches for either.  A vocalist or instrumentalist may perform horribly in one key, but fantastically in another.
Answer:
Since musical structure is carried essentially by the relationship among tones (the ratio of physical frequencies between any two tones), not by a tone itself (the absolute physical frequency of any single tone) (...)

This is not true. Even people without perfect pitch perceive transposed music differently, simply because it's played higher or lower.

In musical terms, artistic or technical, what is the reason for all compositions using a major key not simply using the same particular scale?

Because arranging music is often a substantial creative work (even if arrangement itself not copyrighted). The composer chooses pitch of the notes for the effect they want, as well as takes advantage of the characteristics of the instrument. Changing the key involves redoing this work. It might be difficult or even impossible for given instrument, or may require creative choices of changing notes (e.g. changing voicings, chord inversions, even reharmonizing). The performer may not have time or necessary skills to do it.
Comment: Listeners are generally able to perceive differences in pitch, yes, even without a mutual reference, if the difference is adequate. The premise I gave is that such differences do not account for a difference in musical structure, which is given only by the differences among the tones within the same performance. Thus all major scales carry the same essential musicality, not shared with minor or other scales.
Comment: This is addressed by the answers: https://music.stackexchange.com/a/15225/63781 https://music.stackexchange.com/a/15250/63781 and others. Consider this remix:
https://www.youtube.com/watch?v=jEOPp4iV1WQ Is its "essential musicality" the same as of the original? If you played it on a disco would you expect the audience to react the same?
Comment: @epl This must vary a lot from case to case. I'm fairly sure Chopin's Piano Concertos were composed for the piano. Good composers learn about the instruments they compose for, to make sure what they write is playable and sounds the way they wish. Songwriters need to have an idea of vocal ranges, especially if they write for a specific singer. etc. A counterexample might be transposing jazz standards, which is a common practice, but these tunes were often composed as pop or music theater compositions with a specific key in mind, and it's jazz musicians who are skilled in rearranging them.
Comment: Is a composer's choice to use C major versus D major substantially determined by an understanding of the practical physical properties of the target instrument, more so than of the musical and emotional concepts embodied in the work? It seems doubtful to me, as writing music for a particular instrument or arrangement is by no means universal among composers' techniques. Don't many write music as a pure form, with the instrumental properties considered only later?
Comment: True, there's a big, discernible difference between a song in, say, C as opposed to G, sung or played on any instrument,  but that same song in C or C#? I'd argue that well over half the people, including musos, would be able to tell, unless they had the both back to back.
Comment: @Tim the point of my answer is to demonstrate certain misconception in the question. The rest is clarified in the other question marked as a duplicate. I agree the difference between C and G is large, and C and C# is small and _might_ indeed be unnoticeable in some situations. I disagree with statement that the choice of the key is a trivial task or that it doesn't matter.


$(z-k)$ is composite then $(z-1)+(k-1)$ is also composite(A proof for composite number).

Question:
Given

$z(z-1)$  is divisible by all prime $< n$ where  $ n>\sqrt z$
$(z+k)$ is prime.

Prove or disprove if $(z-k)$ is composite then $(z-1)+(k-1)$ is also composite.

Proof
$z-k=(z-1)-(k-1)=E$, where $E$ is a composite number, consider  $e$, where  $e | E$.
If $\gcd((z-1),(k-1))=g>1$ then  $(z-1)+(k-1)$ is composite.
If $\gcd((z-1),(k-1))=1$ then there is no such $e \mid E$, so that    $e \mid E$ and  $e \mid (z-1),(k-1)$ at the same time.
$e \not\mid z, k$ since  $(z+k)$ is prime,  which implies $(z,k)=1$.
So, $e \not\mid z, k, (z-1),(k-1)$.
But $E$ must have a prime $< E^{1/2} =(z-k)^{1/2}  <z^{1/2}<n .$ So, $((z-1),(k-1))>1 $since $((z-1),(k-1))=1$ does not allow  $E$ to have any prime of $z,(z-1)$. So, if $(z-k)$ is composite then $(z-1)+(k-1)$ is also composite.

** this mundane problem might have a relation to brocard's problem!! any kind of comment would help.
Comment: In a [tag:solution-verification] question your solution should be part of the question, not a separated answer.
Answer: The proof you give is a bit unstructured and difficult to follow, and as a result not very convincing. However, the underlying idea seems to be correct. Here is almost the same proof, but rendered differently.
Assume $z$ and $k$ with $k < z$ are positive integers such that $z + k$ is prime, $z - k$ is composite, and any prime number smaller or equal to $\sqrt z$ divides $z(z-1)$. We want to prove that $(z - 1) + (k - 1)$ is composite.
Let $p$ be the smallest prime dividing $z - k$. Since $z - k$ is composite, it follows that $p \leq \sqrt{z - k} < \sqrt z$. By the assumption on $z$, it follows that $p$ divides $z(z -1)$. Since $p$ divides $z-k$ and does not divide $z+k$, $p$ does not divide $z$, and so we conclude that $p$ divides $z - 1$.
But then $p$ divides both $z-k$ and $z - 1$, so it also divides $k- 1$, and therefore also $(z -1) + (k - 1)$. In particular this last number is composite, and this is what we wanted to prove.
As a final remark, I would like to add that the assumption that any prime smaller than $\sqrt z$ divides $z(z - 1)$ forces $z$ to be smaller than $17^2 = 289$, since otherwise the product of all primes smaller than $\sqrt z$ is already (much) larger than $z(z-1)$. So one could also check all pairs $(z, k)$ satisfying your conditions with a computer.


iPhone UIButton addTarget not working

Question: In my iPhone app, I have SPGameDesk : UIView class, creating it from other class like:
SPGameDesk* gameDesk = [[SPGameDesk alloc] init];
[gameDesk createWithLevel:5];
[appWindow addSubview:gameDesk];

In my SPGameDesk class, in one method, I create UIButtons:
holesRow = [[NSMutableArray alloc] init];
for (int i=0; i<3; i++) {
    [holesRow addObject:[[UIButton alloc] initWithFrame:CGRectMake((40*i)+5, 150, 30, 30)]];
    [[holesRow objectAtIndex:i] setBackgroundColor:[UIColor blueColor]];
    [[holesRow objectAtIndex:i] addTarget:self action:@selector(holeSelected:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview: [holesRow objectAtIndex:i]];
}

And lower in SPGameDesk class I have method:
- (void)holeSelected:(id)sender {
    NSLog(@"SELECTED");
}

But when I touch my button, nothing happens, like some other UIView covers my button (there is no other UIView), or like SPGameDesk has userInteraction disabled (I checked - it is not).
Where is my problem? What should I check?
Comment: You can debug it by cycling through after and seeing what the target and action pointers are (make sure they are not nil and correct.
Comment: Are you sure holesRow isn't being released somewhere?
Answer: What is the frame for your gameDesk view?  It looks like it could be 0,0,0,0.  Try setting it to the bounds of the parent window.  Use initwithframe instead of init.
Comment: Yes you are right! I just didn't think about it. Thx for your help!

iPhone UIButton addTarget not working


Add js script to register page

Question: Like the title says really, I'm trying to add a script to my register page, I'm using Zen as my theme, and I've added a script into the .info file, and to just test that it works I have added an alert() function, and it runs on just about every page except the default register page, and I don't know why, it just doesn't call the script at all.
The longer version is that I have a bespoke Drupal site, not intended for public use, just for specific medical personnel to use for an event we have coming up. What the client has requested is that the user must tick a box declaring they are a healthcare professional before they can register. I have added a boolean checkbox to my register form, and set it to mandatory, but obviously Drupal will accept either checked or unchecked, I want to make it so that they have to check the box before they can register (it's just a legal compliance thing)
I wanted to try to do it via Drupals methods only, but my backup was creating a js solution which would set the register button to disabled until the box was checked, except it doesnt seem to work on the register page.
Can this be done?
Answer: If you make a checkbox required it should force the user to check it (if you have an up to date version of drupal core). See the issue here where that was fixed.
For older versions of drupal there was the checkbox validate module.
As for adding javascript in your info file. That will add it to every page.
So either the page it doesn't work on is using a different theme (and therefore a different info file), or there is a javascript error on the page that is preventing your code from running.
Check your page for javascript errors.
There is also the legal module, which allows you to set terms and conditions that the user has to agree to when signing up. The module handles the checkboxes.
It might not be right for you but it is another option.
Comment: I think I was possibly being a little hasty in writing off the Drupal default. I've sort of inherited a previous code build and I think the previous developer had written some custom code which ended up affecting the perceived register page. However, I think that legal module is absolutely ideal for what I want to do, thanks :)

Add js script to register page


Multiple forms on the same page are causing conflicts?

Question: I have the following code.
function mymodule_get_node_create_or_edit_form($nodeType = '', $inputNode = null, $prepopulationFields = array())
{
  if (empty($inputNode))
  {
    $values = array(
      'type' => $nodeType,
    );
    $values = array_merge($values, $prepopulationFields);
    $node = \Drupal::entityTypeManager()
      ->getStorage('node')
      ->create($values);
    $form = \Drupal::service('entity.form_builder')->getForm($node);
  }
  else
  {
    $form = \Drupal::entityTypeManager()
      ->getFormObject('node', 'default')
      ->setEntity($inputNode);
    $form = \Drupal::formBuilder()->getForm($form);
  }

  return \Drupal::service('renderer')->render($form);
}

I use this function to create edit forms for a node. So I can, for example, create a form that can be used to create a form:
print mymodule_get_node_create_or_edit_form('page', null, array());

Or I can get the edit form:
$node = node_load(1);
print mymodule_get_node_create_or_edit_form($node->getType(), $node , array());

The problem is if I execute both on the same page. Eg:
print mymodule_get_node_create_or_edit_form('page', null, array());
$node = node_load(1);
print mymodule_get_node_create_or_edit_form($node->getType(), $node , array());

If I now make changes to node 1, instead of saving it, it creates a new node with the changes I made, Instead of actually editing the existing node.
Comment: Why are you using `print` and not adding the form to the render array?
Comment: @IsmailCherri, it seems it solves my problem if I put everything into one form array.
Comment: I believe the answer will be having to have its form builder generate unique IDs, and ttheir submits too.
Comment: @coderama Should I add it as an answer?
Comment: @IsmailCherri, yes, it seems to be the most correct answer. So you would get the points :-)
Answer: To apply the workaround suggested in The same form twice on one page with different arguments may process the wrong form when submitted, you need an instance of a class implementing FormStateInterface. It cannot be applied to the code you are using, since you don't have any instance of a class implementing FormStateInterface.
Altering the form ID for each form, which is essentially the Drupal 8 to achieve what hook_forms() achieved in Drupal 7 (see hook_forms() has been removed), would require to sub-class a class marked as @internal (the NodeForm class), and alter the Node entity to change its edit form.
I would instead implement hook_ENTITY_TYPE_prepare_form().
function mymodule_node_prepare_form(EntityInterface $entity, $operation, FormStateInterface $form_state) {
  if ($operation == 'edit') {
    $form_state->setRequestMethod('POST');
    $form_state->setCached(TRUE);
  }
}

The other function is still required. This is how I would implement it.
function mymodule_get_node_edit_form($node, array $entity_values = []) {
  if (is_string($node)) {
    $node = \Drupal::entityTypeManager()->getStorage('node')
      ->create(array_merge(['type' => $node], $entity_values));
  }
  $form = \Drupal::service('entity.form_builder')->getForm($node, 'edit');
  return \Drupal::service('renderer')->render($form);
}

Essentially, I am applying the workaround given in The same form twice on one page with different arguments may process the wrong form when submitted inside a hook.
Comment: Setting the form state to cached indeed fixes this issue -- but also potentially opens up a new, horrible bug! We added these lines, and now when more than one guest user opens a page with this form, only one of them can submit the form (whoever is quickest). The rest get a "Integrity constraint violation, duplicate entry for node_field__uuid__value" error. This only happens for guest users, because for them the whole page is cached. If your form is not shown to guest users, this might be ok. Or you can use the page_cache_kill_switch to not put these pages in the static cache.
Answer: I recently had the same issue and found a workaround in the corresponding Drupal core issue: The same form twice on one page with different arguments may process the wrong form when submitted.
The third comment suggests to enable FormState caching, and that worked great for me.
$form_state->setRequestMethod('POST');
$form_state->setCached(TRUE);

Comment: My form is of type = NodeForm. I dont seem to have SetRequestMethod and setCached that I can call.
Comment: There must be something in the entity form type that could.
Answer: According to coments in the original question, the issue is resolved by adding the forms to the render array rather than using print directly.
Comment: You should show the corrected code, instead of referring to comments. I doubt it's the solution, since there is a bug report open for Drupal core. Drupal core doesn't print the form as the OP does, but the bug about two forms of the same type on the same page is still present.
Comment: I take that back. The form is still giving issues. You might still be right though, but it might also be a bigger issue. I.e. That drupal doesnt like multiple forms on the same page. The search continues...
Comment: Ok, no problem. I will look for another solution
Answer: I ran into this problem in Drupal 6 and at the time the solution was to use hook_forms. That function still existed in Drupal 7 (see hook_forms docs for Drupal 7) but it has been removed from Drupal 8. There is a change record for Drupal 8 about how hook_forms has been removed and how to migrate code.
Perhaps from those documentation pages it will be clear what you need to do?
Comment: This is what I would do, for a form implemented by a module I wrote. (Possibly, it would be the same module that is showing two forms of the same type in the same page.) In the specific case, this requires to extend a class that is marked as internal (NodeForm). Otherwise, this would be the simpler solution.
Comment: Aha, I missed the (very important) element that this is coming from the NodeForm so this technique won't work.
Comment: I think it would work. It's just that a class marked as internal is telling me not to extend it.


Unable to get dynamic value of input ID to javascript function

Question: Please i need help..
@foreach
 <input  id="mar1bags" class="form-control" name="mar1bags" value="">
@endforeach

I am using foreach loop to get some data and also this input field is also inside for me to input data.
But the problem now is i am unable to use GetelementbyID to get the values in javascript. it returns only for the first input field, but the others don't get.
I get this error in my console when i try to submit  to javascript function

[DOM] Found 3 elements with non-unique id #mar1bags:
Answer: It seems that this loop create more then one input but keep setting them the same id.
Since ID suppose to be unique it is not valid (and also the getElementById method would fail).
You can use the .querySelectorAll method instead, and the syntax is:
document.querySelectorAll('[property=value]');

EDIT to your case:

Enjoy code!
Comment: thanks..let me try and get back pls...dont go anywhere my friend...can u iterate for me let me see pls
Comment: please help with the iteration let me see how u will do it pls
Comment: No problem, give me a sec
Comment: inputData[i].value. this is what i see in the console...pls help
Comment: yeah... remove the quotes (:
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/205653/discussion-between-midel-group-and-a-meshu).
Answer: as mentionned above, your id is duplicated that's why it won't work.
instead, i would do:
@foreach
 <input  id="mar1bags-{{ $loop->iteration }}" class="form-control" name="mar1bags-{{ $loop->iteration }}" value="">
@endforeach

Comment: This use different selector but eventually prints the same data on the demo i posted in the chat. Apparently this is not what the OP seeks. You should stay in the chat  (:
Answer: Hey if you are using jquery or javascript to interact with this values you need to add a unique input name and ID: check answer from @erwan
or if you are using a normal form. than maybe just  change the input name to accept an array of values , so you can get all the inputs in form of an array on the backend when you submit the form.
@foreach
 <input  id="mar1bags" class="form-control" name="mar1bags[]" value="">
@endforeach


Working with sequences of random variables

Question: Let $X_n$ with $n \ge 1$ a sequence of random variables such that, for each $n$, $X_n$ has density $n(1-x)^{n-1}$ with $x \in (0,1)$ ($X_n$ is $Beta (1,n)$). For each $n\ge 1$, let $T_n = (1-X_n)^n$
I need to find the distribution of $T_n$ and calculate $P(T_1 + \dots + T_{108} >50)$
I'm a bit confused on how to work with this sequence. I tried:
$P(T_n \le x) = \int_{0}^{x} (1-n(1-x)^{n-1})^n dx$
But this doesn't seem to work. How should I work with sequences such as these?
Comment: Another useful property should be a symmetry property of the Beta distribution to the transformation $1-X$, see the Wikipedia page.
Comment: The density of the function of a random variable is not simply that function of the density, but given by the change of variables rule, see, e.g., https://en.wikipedia.org/wiki/Probability_density_function#Dependent_variables_and_change_of_variables.
Comment: Yes, having the cdf would solve the problem, but your approach in the originial post is not the way to go,
Comment: I was actually trying to find the cdf to then derive it. Wouldn't it work even with the change in variable?
Answer: Strong hint: If $X_n\sim \mathcal{Be}(1,n)$, the density of the distribution is$$f_n(x)=n(1-x)^{n-1}$$and its cdf is$$F_n(x)=1-(1-x)^n$$Therefore,$$T_n=1-F_n(X_n)$$Now,

if $X_n\sim F_n$, what is the distribution of $F_n(X_n)$?

Additional hint: the formula
$$P(T_n \le x) = \int_{0}^{x} (1-n(1-x)^{n-1})^n dx$$
is not correct.
Comment: The important item is that $F_n$ is the cdf of $X_n$.
Comment: Just checking, in this case $F_n(X_n)$ would be a regularized incomplete beta function right? Or I am missing something special here? I'll see if I can solve it with the hints! Thanks!
Comment: Okay, I think I got. $T_n$ would have a distribution $f(t_n) = 1$, which is a uniform (0,1). Now for  $P(T_1,\dots,T_{108} >50)$ I could use a normal approximation with mean $108/2$ and variance $108/12$. Thanks for all the help!
Comment: Almost there: the law of the sum of $k$ uniforms is called an [Irwin-Hall distribution](https://en.wikipedia.org/wiki/Irwin%E2%80%93Hall_distribution) so you do not need to use the Normal approximation.


data dependent quantiles

Question: Could you please explain, what does "data dependent quantiles" mean, as mentioned in the following paragraph:

Quantiles appear intuitively appealing to epidemiologists as they can
be thought of in terms of low, medium and high risk groups. Moreover,
the association between exposure and outcome can be described in terms
of a relative risk between these groups. However, these perceived
benefits are outweighed by several important problems that arise when
a continuous variable is categorized, particularly if data dependent
quantiles are used to form categories.

Many Thanks...
Answer: I believe the intent is simply to describe the situation where specific quantiles of the data are used to form groups, such as dividing the data at its median (a "median split") to get two groups, or putting the highest third of the data into one group, the lowest third into another group and all the middle third into a group.
This is distinct from a split where the dividing line is determined not by a quantile of the data at hand, but on some other criterion (such as some externally determined standard of what divides high from low).
Comment: +1 -- as a side note it is also possible to have something akin to "population quantiles" for a reference population, such as birthweight distribution across infants.

data dependent quantiles


TypeError: replaceAll is not a function

Question: Estou desenvolvendo um sistema em Electron que funciona bem, mas ao rodar os testes no Jest eu recebo o seguinte erro:
 console.error
    Error: Uncaught [TypeError: value.replaceAll is not a function]
        at reportException (C:\Users\rafae\Desktop\VisualData\pdv\node_modules\jsdom\lib\jsdom\living\helpers\runtime-script-errors.js:62:24)
        at innerInvokeEventListeners (C:\Users\rafae\Desktop\VisualData\pdv\node_modules\jsdom\lib\jsdom\living\events\EventTarget-impl.js:333:9)
        at invokeEventListeners (C:\Users\rafae\Desktop\VisualData\pdv\node_modules\jsdom\lib\jsdom\living\events\EventTarget-impl.js:274:3)
        ...

O meu código é o seguinte:
let index = 0;
const value = 'Alguma string';
return value.replaceAll('.', match => index++ === 0 ? match : '');

Estou utilizando a versão 26.0.1 do Jest e 14.5.4 do Node. O Electron é a versão 11.4.7, Chrome 87.0.4280.141.

Por que esse problema ocorre se no meu sistema está funcionando bem?
Como posso consertar isso no Jest sem usar .replace com RegExp?
Comment: Rafael, não estão trocados os parâmetros? o regex/match deveria vir primeiro eu acho.. veja a documentação: https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll
Comment: A sintaxe é `const newStr = str.replaceAll(regexp|substr, newSubstr|function)`. No caso eu usei `str.replaceAll(substr, function)`, onde `substr` é a string a ser substituída pela função. A função substitui todos os pontos `.` com exceção do primeiro, por isso o `index++ === 0`. Não usei RegExp.
Answer: O problema
Esse problema acontece porque o String.prototype.replaceAll é um método novo, adicionado no ES2021. Além de navegadores antigos, versões mais antigas do Node.js (v14 ou anterior) não suportam esse método, e é por isso que o teste no Jest falha.
Você pode ver a tabela de suporte de navegadores no Can I Use:

O shim desse método pode ser obtido no pacote string.prototype.replaceall.
A solução
Suporte para navegadores
Para permitir que navegadores executem esse código sem problema, é necessário realizar o polyfill, incluindo o shim e executando o método .shim() uma única vez.

Instale o pacote como uma dependência do projeto com npm i string.prototype.replaceall ou yarn add string.prototype.replaceall;

Adicione o polyfill:

import replaceAllInserter from 'string.prototype.replaceall';

replaceAllInserter.shim();

Suporte para o Node.js e Jest
Atualizar o Node.js
Caso seja possível atualizar o Node.js, você pode atualizá-lo para uma versão mais recente, que utilize a versão 8.5 do V8, que é quando o .replaceAll foi implementado.
De acordo com a lista disponível no site do Node.js, nenhuma versão utiliza o V8 8.5, mas a partir do Node.js 15.0.0 é utilizada a versão 8.6 do V8. Então, atualize o Node.js para v15 ou superior.
Utilizar o polyfill em desenvolvimento
Como no Electron está funcionando, já que a versão 87 do Chrome já possui a implementação do método, você pode utilizar o polyfill apenas no ambiente de desenvolvimento, conforme mencionado nessa issue.

Instale o pacote como uma dependência de desenvolvimento com npm i -D string.prototype.replaceall ou yarn add -D string.prototype.replaceall;

Modifique a sua configuração do Jest, adicionando um novo arquivo na propriedade setupFilesAfterEnv:

{
  "jest": {
    "setupFilesAfterEnv": ["<rootDir>/jestSetup.js"]
  }
}

No arquivo jestSetup.js, adicione o código do polyfill:

import replaceAllInserter from 'string.prototype.replaceall';

replaceAllInserter.shim();

TypeError: replaceAll is not a function


htaccess 301 redirect root only but exclude all files and subfolders with exceptions

Question: I am not a programmer of .htaccess code, I read the other related posts but do not understand them. Non of them do what I need.
I have a Wordpress site that runs on http://example.com/main but want to redirect http://example.com to http://otherexample.com/page.php. Also need that http://example.com/anyfile not be redirected.
Answer: Assuming example.com and otherexample.com point to different places then try something like the following in the root .htaccess file at example.com:
RedirectMatch 302 ^/$ http://otherexample.com/page.php

The regex ^/$ matches / only, ie. the root directory.

^ asserts the start-of-string (ie. URL-path)
/ matches a literal slash
$ asserts the end-of-string

UPDATE: I found that secondary.com also is redirected.

If you have multiple domains pointing to the same place and you only want to redirect one of them then you'll need to use mod_rewrite to check the hostname first before redirecting.
For example, the following would need to go at the top of the .htaccess file before the WordPress front-controller:
RewriteCond %{HTTP_HOST} ^(www\.)?example\.com [NC]
RewriteRule ^$ http://otherexample.com/page.php [R=302,L]

Note that the RewriteRule pattern matches against the URL-path less the slash prefix, hence the regex ^$ (different to the RedirectMatch directive), which matches an empty URL-path (ie. the root directory only).
Comment: after testing it more closely I found that http://secondary.com also is redirected.
Comment: If you have multiple domains then you'll need to use mod_rewrite instead. I've updated my answer.
Comment: I don't see why the Cond is ^ negative. If I see the Cond as an AND   then is like ^$ AND ^(www\.)?example\.com [NC]
Comment: The Cond is not negative. `^` in regex is the start-of-string anchor. This ensures we match from the _start_ of the `Host` header and don't get partial matches, which could result in false positives, depending on the domains you have (but it is more efficient this way too). But otherwise, yes, this is an AND. `^$` matches against the URL-path and the Cond matches against the hostname.


How can I delete properly an old translation string?

Question: I found an old string into locales_source table, like that:

The associated 8.5.3 version seems outdated.
I would like to understand the usefulness of the keep this data in my database ? How to clean it properly ?
Answer: In Drupal 7, you could delete unnecessary strings in the UI.
Drupal 8 and 9 are missing this functionality; there is an open bug report to add it back, and hopefully it will eventually be fixed in Drupal 10.
There is a working patch in the issue to get a mostly working version of the function now.


Length of Perpendicular/Parallel Vectors

Question:
Knowing the two vectors in black, and the point x,y at the end of the two red vectors.
I'm having trouble figuring out a formula to get the perpendicular/parallel vectors represented in red in order to calculate their lengths.
My end goal is to figure out the ratio of length between one of the black vectors and its parallel red vector passing through the point x,y
[EDIT]
It would be great if the solution is in terms of x,y coordinates and was solved from three sets of points, the x,y point represented then the two end points of the black vectors
Answer: Your diagram may be somewhat misleading in that the point $x,y$ seems to lie halfway between the tips of the two black vectors. If that were the case, then the ratio would trivially be $2$. Also, it's not clear (to me) what you're referring to as "perpendicular", since there are no right angles in the diagram.
For general position of $x,y$, you can find two vectors parallel to the two black vectors that add up to $(x,y)$ by solving a linear system of equations:
$$a\vec v+b\vec w=\vec x\;,$$
where $\vec v$ and $\vec w$ are the two black vectors, $\vec x=(x,y)$, and $a$ and $b$ are parameters to be determined by solving the resulting $2\times2$ system of equations. The two desired vectors are then $a\vec v$ and $b\vec w$.
[Edit in response to the comment:]
If we denote the components of the black vectors by $(x_1,y_1)$ and $(x_2,y_2)$, respectively, the above linear system of equations becomes
$$
\begin{eqnarray}
ax_1+bx_2&=&x\\
ay_1+by_2&=&y\;.
\end{eqnarray}
$$
This can be solved explicitly using Cramer's rule:
$$a=\frac{\left|\begin{array}{cc}x&x_2\\y&y_2\end{array}\right|}{\left|\begin{array}{cc}x_1&x_2\\y_1&y_2\end{array}\right|}=\frac{xy_2-x_2y}{x_1y_2-y_1x_2}\;,$$
$$b=\frac{\left|\begin{array}{cc}x_1&x\\y_1&y\end{array}\right|}{\left|\begin{array}{cc}x_1&x_2\\y_1&y_2\end{array}\right|}=\frac{x_1y-xy_1}{x_1y_2-y_1x_2}\;.$$
Then the components of the two red vectors are $(ax_1,ay_1)$ and $(bx_2,by_2)$, respectively (where $a$ and $b$ are determined as above).
Comment: Thank you very much for this, is there a possibility you could list the solution based on x,y coordinates,  where i have the x,y coordintates of each of the black vectors and the point I want to solve for? I not having much success converting the points i have into the mathematical representation of vectors
Comment: I edited the answer. I hope this is what you need -- I'm not sure I understand the distinction between coordinates and "the mathematical representation of vectors" that you're making.
Comment: Admittedly very nitpicky, but if you're using $|\cdot|$, there's no need for $\det$, no? :)
Comment: @J. M.: You're quite right -- at first I used parentheses, then I thought it looked weird, and I checked [the Wikipedia article](http://en.wikipedia.org/wiki/Cramer%27s_rule), wondered why the notation should be so redundant, and then copied it mindlessly :-)
Comment: I've corrected the notation in the Wikipedia article.


perforce command to know the non versioned files

Question: I am new to perforce. i have client created in linux.
and synced all the files from the repository. previously we were using svn to add and delete files to a repository.
in svn we have a command to know the status of the tree by "svn st" which shows all the local modifications(with symbol M) and also the non versioned files(with symbol ?).
i want to know what is the equivalnet command for this in perforce which shows all the non versioned files also.
Could anyone please help me with th command in linux.
Answer: In Perforce changes that have been "opened" (using P4 terminology) are attached to changelists.  To list the changelists use the changes command:
p4 changes
To see the changes attached to a specific changelist use the change command:
p4 change -o $CHANGELIST
The status command without any options will preview files that are added, deleted or modified but that haven't been opened (which really means haven't been attached to a changelist).
p4 status
The status command or the reconcile command can also be used to "open" the changes.  Note that the status command will of course exclude files you have ignored.  If you want to see them use the -I option.


Permissions issue directing domain networked printer to LPT1

Question: We have an old FoxPro 2.6 application, that cannot print to a networked printer. Knows nothing about domains, etc, and uses it's own built-in drivers instead of Windows drivers, and can only print to lpt ports. Our normal setup to allow network users to print is for a printer to be attached to one computer, share that printer, then use a net use command from another computer to connect to the the shared printer and redirect it to lpt1. Works great, no issues, except that the computer the printer is attached to has to be on at all times. We want to get away from that, and have the printer's setup on the Active Directory server, shared from that like all of our other printers, and then do the net use command to redirect to lpt1, so that our outdated application can print to it.
Setup:

Domain, swtechinc, with AD server as swkcdc01. IP address of 192.168.1.10
Domain users have standard user permissions
LaserJet 5n printer, networked with IP of 192.168.1.207
The printer is setup and shared on the AD server as LJShip

If I do a net use lpt1: \\swkcdc01\LJShip as domain admin, I have to enter in the AD Administrator username and password, but then it completes successfully. Go into the user account, and do a net use, and the mapping is gone.
Do the same command from the user account, and it again asks for user name and password. BUT, it will not complete, says System Error 5, Access is denied.
I have tried adding his user account on the AD to the security tab of the printer on the AD server, and still get the same results.
I am hoping someone here can help me out, because I am at a loss.
Comment: Are you ok with doing a lot of manual setup on the workstations?
Comment: Do your users have local admin privileges?  I would guess mapping to parallel port requires local admin.
Comment: If it's on the network as 192.168.1.207 why not map directly to it instead of through a shared printer off the server?  Are you wanting to restrict access or log printing?
Comment: Also, which version of Windows is the server running ?
Comment: lsmooth - I figured manual setup was going to be required. Out of about 30 PCs here, only about 5 or so need this, as the others either connect directly to the printer or do not use the application at all. In reply to your second question, it is Server 2003 32-bit
Comment: @Grant - no local admin priveleges, and we try to limit that at all times. this same setup of mapping to lpt1 works, if I am connecting to another domain computer. 'net use lpt1: \\cmoyer\hplj' allows me to set up a client to print directly to her printer, but requires her computer to be on at all times, even though the printer itself is connected to the network, and she is connected to it through a printer share from the domain controller for all of her windows printing. For the FoxPro printing, she is connected to it through the parallel port
Answer: I did find out the answer - took me a bit to realize it.
The standard users do not have access to make changes to the hardware. Due to their being a physical LPT port on the computer, and it being enabled in the BIOS, that is why I was getting the error I was getting. When I tried lpt2 or lpt3, I did not get the error.
So, disabling the lpt port in the BIOS solves my issue, since their is not a physical port there anymore, the standard users can NET USE to add the shared printer. I was thinking it was on the Active Directory side, but it wasn't.
Thanks to everyone who replied.
Answer: What you should be able to do, is install the printer twice on each PC that needs it. For one as a local printer on LPT1: and the other should be the server's shared printer. Now go to the properties of one of the two printers and activate printer pooling and then additionally select the port that is not already used by this printer.
The purpose of printer pooling is to divide print jobs on two or more of the same printers. This also has the nice side-effect that when one of the printers is offline windows automatically using a printer that is online, regardless on which printer and port the job was originally printed.
Another way would be using a Group Policy Object to install a network shared printer on the workstations in question. You can then also map the printer to a local port. But that will probably only work up to Windows XP.


Required database permissions

Question: I have to make a new install for Drupal 7 and i need to request the database space on Oracle DB to the DB guy, who wants to know exactly which permissions should have the drupal account that will handle the database.
I have read a lot do documentation, and everywhere is just said that the account for the database should have full privileges. I have told this to the DB guy and he refused that statement, arguing for example that Drupal will not need the "drop database" privilege, as an example.
So my question is: where can I find the exact minimum list of database privileges that Drupal needs to work properly?
Answer: There's no official documentation for Oracle (I don't think), but INSTALL.mysql.txt states you need the following permissions for MySQL in Drupal 7:
SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, INDEX, ALTER

I came across an INSTALL.oracle.txt on http://drupalcode.org, but I can't vouch for it's accuracy. It says to run the following with regards to permissions:
grant dba, create any trigger, drop any table, select any table, select any sequence, create user to drupal identified by drupal;
grant connect, resource to drupal with admin option;
alter user drupal default tablespace users temporary tablespace temp;

Show both of those files to your DBA, it should be enough for him to go on.
Answer: Drupal 7 needs more permissions for work correctly if you are using modules like Views, the correct list is:
SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, INDEX, ALTER, LOCK TABLES, CREATE TEMPORARY TABLES
Comment: Actually, [db_query_temporary](https://api.drupal.org/api/drupal/includes!database.pgsql.inc/function/db_query_temporary/6) existed in every version of Drupal from 4.7 up, and is supposed to exist in 8 too. So if there is separate `CREATE TEMPORARY TABLES`, Drupal may need it. On the other hand, wouldn't `CREATE` imply `CREATE TEMPORARY`?

Required database permissions


How to add Javascript code into a block

Question: I have a Drupal 7 site. I'd like to add Social Media follow buttons
(i.e. Follow us on Facebook, Twitter, Linkedin).
I grabbed some Javascript code from http://www.addthis.com
 which generates these buttons and also links to some analytics services I will be using.
Now I need to figure out how to place the AddThis Javascript code I generated, to a Drupal block. Once it's in a block, it will be easy for me to move around my Drupal site pages.
Answer: Why not just use the addthis module rather than adding a block. If you however want to add a block, just go to admin/structure/block click on add block. Paste your script in and select filter type of php code and click save
If you do not have PHP filter in the filter type, enable it under the core module
Comment: The other alternative is creating a custom block in a custom module, but the addthis module works fine for most cases.
Comment: Just to mention that save php into the DB is not a good choice. DB should store content and not the system logic.
Comment: The addthis module is for sharing buttons, not for "Follow us" buttons. Perhaps I missed something when I installed and played with the module.
Comment: 4life, you're solution was simple and it worked perfectly. I just added a block, selected PHP and pasted in the javascript. Thanks!
Comment: Sorry, in order to add Social Media follow buttons you can use the Follow module.
Answer: In order to add Social Media follow buttons you can use the Follow module. If you need to add Social Media share buttons you can use the AddThis module or the Easy Social module.
To attach CSS or JS files to a specific block you will need to build a custom module that implements the hook_block_view_alter to manipulate the block render array and then use Drupal 7 FAPI's #attached attribute to attach the file to the block.
Comment: The addthis module is for share buttons, not for follow us buttons. Perhaps I missed something.
Comment: Sorry, I've edited the answer to add the module for follow buttons.
Comment: Also, I'm sticking with the Addthis code, I'm glad to know about the Follow module and I'm sure others reading this thread will want to know about.

How to add Javascript code into a block


How to store value of variable if it is changed inside of ajax callback function?

Question: I have a form with several ajax callback functions.
And I have a variable which should change its value inside these  callback functions.
Unfortunately, I have faced with a problem. Namely, I don't know how to store the value of the variable after change. Because after the callback function executed the value is lost.
There is a little example of code.
class MyForm extends FormBase {
    public $i = 0;

public function buildForm(array $form, FormStateInterface $form_state){
    ...
    $form['add_more'] = [
        '#type' => 'submit',
        '#value' => 'Add More ...',
        '#ajax' => [
            'callback' => '::addMore',
        ]
    ];
    ...
}

public function addMore(array &$form, FormStateInterface $form_state){
    ...
    $this->i++;
    ...
}
}

Here the variable $i doesn't increase its value whenever the button is being pressed.
Could you clarify, what should I do if I want the variable to increase its value whenever the button has been pressed ?
Answer: The ajax callback is not for form logic. It's only supposed to send back a new version of $form or part of it in a wrapper. Or in more advanced cases a collection of ajax commands.
Use instead buildForm(). You can check which button was clicked with $form_state->getTriggeringElement().
  public function buildForm(array $form, FormStateInterface $form_state) {

    $form['#prefix'] = '
';
    $form['#suffix'] = '
';

    $i = $form_state->get('elem') ? $form_state->get('elem') : 1;
    $trigger = $form_state->getTriggeringElement();
    if (isset($trigger['#ajax']['callback']) && $trigger['#ajax']['callback'] === '::addMore') {
      $i++;
    }
    $form_state->set('elem', $i);

    $form['counter'] = [
      '#markup' => $form_state->get('elem') ?? 1,
    ];

    $form['btn'] = [
      '#type' => 'button',
      '#value' => 'Btn',
      '#ajax' => [
        'callback' => '::addMore',
        'wrapper' => 'ajax_wrapper',
      ]
    ];

    return $form;
  }

  public function addMore(array &$form, FormStateInterface $form_state){
    return $form;
  }

  public function submitForm(array &$form, FormStateInterface $form_state){

  }

Comment: I created a test form, but it doestn't work.
Here is the code - https://slexy.org/view/s2NVttIMjM
A field "counter" should display changing value of the iterator, but it doesn't do it.
Comment: You need to add a wrapper and some minor things (type button for ajax, get() instead of getValue()), then it works. I've modified your latest code example.
Comment: Your code didn't work, but I added into method submitForm the following content "$form_state->setRebuild();" and it has worked.
Comment: You don't need this for the example to work, but this is a good idea as fallback, if js is not available.
Comment: But if I doesn't return $form, but execute several Ajax operations in the callback function ?
That is, I create an AjaxResponce object, next I add several different ajax commands into it, and I returns the object instead $form.

Could you clarify me, what should i do in this case ?
Comment: A form rebuild without js always returns the complete form, so this is difficult to replicate then (but this would be a different topic I think, the example works fine with js enabled and without rebuild)
Comment: In my task I have to return the AjaxResponse object instead a $form. Can I store the value of the variable in this case ?
Comment: Yes, you can do it as in the example. We got off topic with your remark that you need to set rebuild, which is not necessary for the example to work, but might be for other things.


Could not resolve all files for configuration ':app:androidApis'.

Question: Could not resolve all files for configuration ':app:androidApis'.
Failed to transform file 'android.jar' to match attributes {artifactType=android-mockable-jar, returnDefaultValues=false} using transform MockableJarTransform
Comment: You should read this link: https://stackoverflow.com/help/how-to-ask
Comment: have the same problem
```
Caused by: java.io.IOException: Please correct the above warnings first.
        at proguard.Initializer.execute(Initializer.java:485)
        at proguard.ProGuard.initialize(ProGuard.java:271)
        at proguard.ProGuard.execute(ProGuard.java:113)
        at com.android.build.gradle.internal.transforms.BaseProguardAction.runProguard(BaseProguardAction.java:64)
        at com.android.build.gradle.internal.transforms.ProGuardTransform.doMinification(ProGuardTransform.java:262)
        at com.android.build.gradle.internal.transforms.ProGuardTransform.acce
```
Answer: compileSdkVersion 28
Sync success


How to make a muted key sounds by using pedals?

Question: One of my friends insists that he can make a muted (but undamaged) key/chord  sounds using some pedaling technique. Does anyone know what the technique is and how to do it?
Thanks
Comment: I don't have the faintest idea what "muted (but undamaged) key/chord sounds" are supposed to sound like. A recording might help.
Comment: Does your friend refuse to explain or demonstrate his technique? Seems like he would be the ideal person to ask.
Comment: Sure! However, he bet me to find it out!
Answer: On a normal piano, the left pedal is pressed to make the sound quieter. It does this by moving the whole hammer mechanism closer to the strings on most uprights, and often by moving the mechanism to one side on grands. thus it's less distance for the strike to take place.
On some pianos, there is a practice pedal, often the middle of three, which brings a piece of felt down onto the strings, damping them slightly. This pedal is lockable. With both pedals in operation, the sound is very quiet.
If you're used to an electronic piano, there will often only be a sustain pedal, as you can turn down the volume.
Answer: The sustain pedal can also be used (on a real piano) for a muting effect.  You strike a chord, release the keys, and a split second after you release the keys you depress the sustain pedal.  If done well, this produces a sforzando effect: the chord is initially loud but then echos on quietly.  Takes practice.
Comment: I asked a question about this here a couple of years ago. Glad someone else uses the same idea!
Comment: @Tim- I like this technique because it's one of the few things you can do on a piano that's not straightforward "hit the key harder to make it louder".  You can also sustain a chord with the pedal but very gently let the pedal go just enough to slightly damp the notes, and then press it again.
Comment: When i play an electronic piano at gigs, I find myself doing the same technique - but it doesn't work on  many of these sort of pianos. Can't stop trying though - it's a very effective effect...
Comment: This is not the same technique, but it makes a similar effect: on my double harp I pluck a chord strongly on the gut strings (on the right side) and immediately damp them- the metal strings on the left side go on resonating sympathetically, making an echo.


Class or function variable?

Question: As a means of speeding up my program, I have it look through a list of words and see if a certain string contains any of those words, in which case it can skip following code and move on.  This happens thousands of times.
I'm in the process of cleaning up my code, and where before I had my list defined as a private string[], it makes more sense visually to have it inside my new ContainsWordsToSkip() method.  However, unless I'm mistaken, string[] wordsToSkip would have to be reallocated in memory with each call and it would be better leave it as a class member.
Is this correct?
Comment: You may want to mention / tag the language you're using.
Comment: It's C#.  I didn't think the language was particularly relevant for this.  I'll tag it anyway, though.
Answer: Yes, it should be a class member. Additionally, if it's not changing between instances, it should be static (all based on the assumption that your code looks like C#)
Comment: Right on.  Thanks! (I hadn't thought about the static part.)

Class or function variable?


Looking for a function

Question: I am looking for a function (double exponential maybe?). Its curve should look like $\tanh x$, but it should pass exactly points $(0,0)$ and $(1,1)$, so that I can use the region $0<x<1$. Is there such a function?
I seems to me that something like $x=\frac{\exp \left(-Cy\right)-\exp \left(Cy\right)}{\exp \left(C\right)-1}$ can, but I don't know how to rewrite it in the format of $y=f(x)$?
Comment: Anything wrong with $\frac{tanh(x)}{tanh(1)}$?
Comment: anything to the power of 0 is not 0, so I don't think there is a double exponential function with this characteristic
Comment: @SanathDevalapurkar it doesn't pass (0,0)
Comment: Thanks, I found $\frac{\tanh(Cx)}{\tanh(C)}$ satisfies my needs.
Answer: Take any function on Earth, choose two points $(x_0,f(x_0)),(x_1,f(x_1))$ and define
$$\phi(t)=\frac{f(x_0+(x_1-x_0)t)-f(x_0)}{f(x_1)-f(x_0)}.$$
Now the two points are mapped to $(0,0),(1,1)$.

Looking for a function


Intercalação de vetores em python

Question: Faça um programa que preencha dois vetores de cinco elementos numéricos cada um e mostre o vetor resultante da intercalação deles. Os vetores devem ser inicializados com a valores abaixo:
https://photos.app.goo.gl/egHj5dYLAXxfbLoW6
Primeiro resolvi fazer uma versão mais reduzida, onde o terceiro vetor terá apenas 5 elementos.
Consegui isso aqui(caso a visualização esteja confusa, o código tá mais organizado no Google docs:
https://docs.google.com/document/d/13poguwUMA4y3mumadOkDJgarwzqx_vr-HkZgw9MMmg4/edit?usp=drivesdk):
vetor1 = [0]*5
vetor1[0] = 4
vetor1[1] = -9
vetor1[2] = 78
vetor1[3] = 0
vetor1[4] = 25
print(vetor1)

vetor2 = [0]*5
vetor2[0] = 8
vetor2[1]= 2
vetor2[2] = 34
vetor2[3] = 90
vetor2[4]= 200
print(vetor2)

v3 = [0] * 5

for i in range(5):
    if i%2 == 0:
        v3[i]  = vetor1[i/2]
    else:

E é aqui que começo a ter problemas. Não consigo achar uma fórmula pra relacionar todos os índices de v3 e de v2.
Answer: Usando listas em compreensão (nomeadamente [ x | par ∈ zip(a,b) ∧ x ∈ par ]):
a=[4, -9, 78, 0, 25]
b=[8, 2, 34, 90, 200]
print([x for par in zip(a,b) for x in par])

Saída:
[4, 8, -9, 2, 78, 34, 0, 90, 25, 200]

Comment: Muito mais pythonica!  +1
Comment: Não entendi o funcionamento da estrutura " x for par in zip(a,b)"
Comment: @PabloLeonardo em linguagem matemática, isto costuma escrever-se como `[ x | par ∈ zip(a,b) ∧ x ∈ par ]`
Answer: Uma forma trivial de se resolver isso é utilizando a estrutura itertools.chain em conjunto com a zip:
from itertools import chain

a = [4, -9, 78, 0, 25]
b = [8, 2, 34, 90, 200]

resultado = chain.from_iterable(zip(a, b))

print(*resultado)
# 4 8 -9 2 78 34 0 90 25 200

A classe zip irá gerar um objeto iterável que produzirá tuplas com os dois valores respectivos a cada posição das listas e a função chain.from_iterable irá aplanar essa estrutura com todos os valores em um mesmo nível. O retorno é um gerador, pois isso foi necessário o * para consumí-lo e exibir os valores.
O código em Python equivalente para esse trecho seria:
def intercalar(a, b):
  for i, j in zip(a, b):
    yield i
    yield j

Ou de maneira mais genérica, sem limitar à duas listas:
def intercalar(*listas):
  for valores in zip(*listas):
    for valor in valores:
      yield valor

Ou ainda:
def intercalar(*listas):
  for valores in zip(*listas):
    yield from valores

Answer: Não entendi  por que usar um terceiro vetor, acredito que seja para atribuir os valores dos vetor1 e vetor2, correto? Caso sim, não é necessário um novo vetor. Para realizar tal intercalação usamos o método zip().
Seu código ficará assim:
vetor1 = [0]*5
vetor1[0] = 4
vetor1[1] = -9
vetor1[2] = 78
vetor1[3] = 0
vetor1[4] = 25
print(vetor1)

vetor2 = [0]*5
vetor2[0] = 8
vetor2[1]= 2
vetor2[2] = 34
vetor2[3] = 90
vetor2[4]= 200
print(vetor2)

v3 = [0] * 5

def zipar(v1,v2):
    zipar = []
    for x,y in zip(v1, v2):
        zipar.append(x)
        zipar.append(y)
    return zipar

ListaZipada = zipar(vetor1, vetor2)

for i in ListaZipada:

    print(i ,end=" " )

Saída:
[4, -9, 78, 0, 25]
[8, 2, 34, 90, 200]
4 8 -9 2 78 34 0 90 25 200

Usei como base está resposta, recomendo ler ela e a documentação sobre o método zip()
Observe que houve uma modificação no último print(i ,end=" " ) para obter a saída em uma única linha.
Recomendo a leitura: Há uma maneira de imprimir tudo sem a quebra de linha?
Comment: Fiquei confuso com a necessidade do return. Retirei ele do código e verifiquei que o compilador acusa que "zipar" não é um objeto iterável. Então pelo menos já entendi o que o return faz aí, mas não entendi porque ele faz de zipar um objeto iterável.

Intercalação de vetores em python


Bacula backup on Linux, restore on FreeBSD

Question: I'd like to migrate my storage server from Linux (Debian) to FreeBSD. Biggest part of this is restoring backups saved on Linux to tape volumes on the newly installed FreeBSD.
Unfortunately I don't have anywhere to test this on at the moment but I'd like to ask you if you're aware of any incompatiblities or Bacula specific settings that should be used to make this as smooth of a process as possible.
Comment: Why not just copy from one server to the other using something like rsync? Are you planning on reusing the existing server to make your new one?
Comment: Yes, that's the case. Even if it was going to be a different machine, restoring from tape would still be faster in my case (LTO4). I'm not looking for alternative solutions - I'm merely interested if anyone is aware of any gotchas or incompatibilities.
Answer: Bacula volume format is OS- and architecture-independent, so any problems are likely to be caused by OS drivers -- the manual recommends to alter specific settings.


insert array foreach

Question: estou tend um problema ao inserir dados no banco com php , tenho um form com varios checkbox , entao quero selecionar mais de 1 checkbox e inserir no banco , fiz assim
form
<code><input type="checkbox" name="f_carteira[]" value="'.$cart['id'].'">
</code>
action
<code>  $carteira = $_POST['f_carteira'];

  if($carteira){
      foreach ($carteira as $car) {

        $cadastrarmensagem = $pdo->prepare("INSERT INTO mensagem(codigo,conteudomsg,categoria_id,carteira_id,usuario_id) VALUES(:codigo,:conteudo,:categoria,:carteira,:usuarioid)");
  $cadastrarmensagem->bindValue(":codigo",$_POST["f_codigo"]);
  $cadastrarmensagem->bindValue(":conteudo",$_POST["f_msg"]);
  $cadastrarmensagem->bindValue(":categoria",$_POST["f_cat"]);
  $scarteira = implode(",",$carteira);
  $cadastrarmensagem->bindValue(":carteira",$scarteira);
  $cadastrarmensagem->bindValue(":usuarioid",$_POST["f_usuario"]);
  $cadastrarmensagem->execute();
  $linha = $cadastrarmensagem->rowCount();
  if($linha > 0){
     echo "Mensagem Cadastrada com Sucesso";

     header ("Location: ../index.php?pg=mensagens");
  }else {
    echo "Erro";
    //imprimindo erro da variavel de consulta
   print_r($cadastrarmensagem->errorInfo());

    echo "$idlogado";
  }
      }
  }

}else{echo "aconteceu algum erro";}
</code>
estava tendo problemas porque não estava aceitando array , ai usei json e transformei em strings porem agora ele quer inserir tudo em uma linha só , tipo
1,2,3 no campo da categoria , sendo que quero que ele insira o 1 , pula pra proxima linha insere o 2 , e assim em diante
Comment: Pelo que intendi você deseja usar uma unica coluna para salvar multiplos valores? Se for isso, essa ação viola o dito "FNF (First Normalization Form)". Em resumo: fazer isso pode funcionar, pode ser extremamente estável e nunca apresentar problema, porém não é recomendado. Veja em https://en.wikipedia.org/wiki/First_normal_form sobre isso. Você está usando um banco de dados relacional. Crie uma tabela única para armazenar as categorias e associe usando o ID. Dessa forma crie `ID | Categoria` e relacione o ID ao ID da mensagem, depois apenas faça um JOIN entre eles, ou similar.
Comment: poderia me ajudar com um exemplo pratico disso , quero que o cadastrar um topico eu possa selecionar em mais de uma categoria
Answer: Primeiro, não faça o implode, use a variável $car que possui a sua categoria:
<code>  $cadastrarmensagem->bindValue(":categoria",$_POST["f_cat"]);
  //$scarteira = implode(",",$carteira);
  //use a avariavel $car que nao vai mais ser um array
  $cadastrarmensagem->bindValue(":carteira",$car);
  $cadastrarmensagem->bindValue(":usuarioid",$_POST["f_usuario"]);
</code>
Isso vai permitir que seu codigo funcione. Mas será complexo para gerenciar no futuro. Seguindo o comentário anterior, vejamos:
Pequeno exemplo. Você tem a tabela mensagem:
codigo, conteudomsg, ... categoria
Crie uma outra tabela exemplo, categorias:
id, nome_da_categoria
Você teria todas as categorias salvas na tabela categorias e iria inser na coluna mensagem.categoria (chave estrangeira) o numero equivalente ao id da categoria marcada no checkbox.
Só que a abordagem acima tem um problema você vai inserir os dados da mensagem varias vezes, mudando apenas o valor da categoria. Para evitar isso crie mais uma tabela, exemplo: mensagem_categoria
codigo_mensagem, categoria_id
Então a sua tabela mensagem não teria mais a coluna categoria. Você salvaria a mensagem apenas uma vez. Pegaria o codigo (é o id da tabela mensagem?) e os ids das categorias marcadas nos check box e iria inserir n vezes na tabela mensagem_categoria. Dá uma olhada em relações n para n e n para 1. Há muitos exemplos em php.
Comment: poxa amigo , vlw pelas dicas , tinha testado pensei que estava funcionando , mas ele cadastrou apenas o primeiro registro , o que pode ser ?

insert array foreach


Como usar um banco de dados pronto no Android com SQLite

Question: Estou desenvolvendo um aplicativo que faz download de um banco de dados de acordo com o estado (UF) do usuário.  Alguém sabe como faço para inserir os dados no banco de dados?
Obs.: o arquivo de banco de dados, pode chegar há 200 MB.
Answer: Olha, já fiz algo parecido mas não sei se vai ajudar, mas vamos lá:
Alimentar o banco de dados manualmente utilizando JSON
Eu fiz a carga no banco de dados utilizando um serviço. Este serviço retornova um JSON paginado de 1000 em 1000 registros e eu incluia isso no banco de dados.
Carregar o banco de dados binário em seu app fonte SOen
Você pode usar este método para gravar em seu private storage
<code>private static boolean downloadDatabase(Context context) {
            try {
                   // Log.d(TAG, "downloading database");
                    URL url = new URL("http://some-url.com/db/" + "db_name.s3db");
                    /* Open a connection to that URL. */
                    URLConnection ucon = url.openConnection();
                    /*
                     * Define InputStreams to read from the URLConnection.
                     */
                    InputStream is = ucon.getInputStream();
                    BufferedInputStream bis = new BufferedInputStream(is);
                    /*
                     * Read bytes to the Buffer until there is nothing more to read(-1).
                     */
                    ByteArrayBuffer baf = new ByteArrayBuffer(50);
                    int current = 0;
                    while ((current = bis.read()) != -1) {
                            baf.append((byte) current);
                    }

                    /* Convert the Bytes read to a String. */
                    FileOutputStream fos = null;
                    // Select storage location
                    fos = context.openFileOutput("db_name.s3db", Context.MODE_PRIVATE);

                    fos.write(baf.toByteArray());
                    fos.close();
                   // Log.d(TAG, "downloaded");
            } catch (IOException e) {
                    Log.e(TAG, "downloadDatabase Error: " , e);
                    return false;
            }  catch (NullPointerException e) {
                    Log.e(TAG, "downloadDatabase Error: " , e);
                    return false;
            } catch (Exception e){
                    Log.e(TAG, "downloadDatabase Error: " , e);
                    return false;
            }
            return true;
    }
</code>
Comment: Pensei em transformar o banco de dados em JSON e inserir com uma activity, mas acho que é muito grande, o aplicativo pode fechar. Não sei, sou novato. Mas se o arquivo demora para abrir no meu computador, imagina processar o texto num smartphone, mas se deu certo para você, deve funcionar. Agora pouco encontrei uma classe que acho que vai resolver o problema. https://github.com/jgilfelt/android-sqlite-asset-helper
Comment: @JorgyanRibeiro Se vc transformar o banco em JSON você deve carregar os registros em bloco. Mas logo abaixo tem um exemplo para baixar o banco sqlite para o seu app.
Answer: Edgar Muniz Berlinck a classe SQLiteAssetHelper resolveu meu problema.