HandlerInterceptorAdapter and Zuul Filter

Question: It is possible add a HandlerInterceptorAdapter with Zuul Configuration. I need to intercept a request to a specific resource but I suppose because I have Zuul filter configuration, the interceptor is never called.
Is possible to do so?
Comment: some punctuation and formatting.
Answer: I have tried to achieve the same. We have a few Spring MVC controllers and Zuul proxying. But I still wanted the same Interceptor to be used.
The problem here is that zuul runs in its own ZuulServlet, and does not pick up the interceptors from your MVC servlet. Spring Cloud: ZuulConfiguration.java configures ZuulHandlerMapping, which is the only place interceptors could be set, but it's not configurable. Thus you need a InstantiationAwareBeanPostProcessorAdapter to interfere with the bean creation, to set your interceptors after instantiaton, but before initialization (before the interceptors are initialized).
This did the trick for me:
@Configuration
@RequiredArgsConstructor
public class ZuulHandlerBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter {

    @NonNull
    private final MyInterceptor myInterceptor;

    @Override
    public boolean postProcessAfterInstantiation(final Object bean, final String beanName) throws BeansException {

        if (bean instanceof ZuulHandlerMapping) {

            val zuulHandlerMapping = (ZuulHandlerMapping) bean;
            zuulHandlerMapping.setInterceptors(myInterceptor);
        }

        return super.postProcessAfterInstantiation(bean, beanName);
    }

}

Comment: Thanks a lot my lifesaver! +1 for you.


How can I rename uploaded files programatically? (auto-rename image files)

Question: I am aware that the File Paths module allows administrators to use tokens to set patterns for renaming files, but as of writing (Jan 2015) there are more than 100 bugs in the queue and no updates to the dev version in almost one year.  (I also installed it and it and was unable to get it working.) So, I want to do this programmatically.
My goal is to rename all new user-uploaded image files on my Drupal 7 site to this pattern: [uid of logged in user][timestamp].extension.
Being able to rename them with the UID is very important because these files are often downloaded and exchanged (sent back and forth via email, without reference to Drupal), and we need an easy way to identify which user originally uploaded the file after it has been downloaded from the site.
I am using the Transliteration module. For inspiration, I also took a look at the File Entity Paths module, but it didn't provide me any insight.  I further consulted this article on file-naming best practices from Acquia but it provides no suggestions for doing this programmatically.
Answer: Assuming you are talking about the core file functionality, you can modify the filename in hook_file_presave() and modify the filename property.
function mymodule_file_presave($file) {
  $parts = pathinfo($file->filename);
  $file->filename = $file->uid . $file->timestamp . '.' . $parts['extension'];
}

Drupal will handle changing any other properties that need to be changed.
Some issues to be aware of:

Upload forms will expose the new name to the user after he clicks 'Upload'. It may be confusing to upload a file with a regular filename and see it changed to a string of numbers.
There is a note on the hook_file_presave documentation that the hook "doesn't distinguish between files created as a result of a copy or those created by an upload." If you do need to distinguish, check out the $file->source property or try calling menu_get_object() to figure out if the user is on a page with an upload form or not.
Consider using a dash between the uid and the timestamp for your naming convention. Your timestamps will all start with 1 (until 2033 anyway), and users with UIDs ending in 1 (e.g 11, 21, etc.) will make the filename confusing to read.
Comment: I'm also noticing that hook_file_presave will get called when the entity is updated. I still think it is a better bet than hook_file_insert().
Comment: BUT someone should add an answer making the case for hook_file_insert(). You might need to file_move and protect against an infinite loop somewhere, but it could solve the UX issue I mention above, and more.
Comment: Great answer, and awesome of you to note the caveats.  I tried it on my site, and although `dpm()` in `file_presave()` shows that `$file->filename()` is changed, and this is also reflected in the UI, when I actually check the server, the file is saved with the original file name (not the one specified in the hook).
Comment: You can play with $file->destination and $file->uri if it matters what it is called on the filesystem. My understanding is that one is for filesystem access and the latter for the url. When I tested your requirement that it keep the name when downloaded and exchanged, $file->filename was the key to keeping that name.
Comment: How did you download the file?  When I right-click the image and choose "Save file as," the filesystem name is used.
Comment: Oh interesting, I had just clicked the file, not the rendered image. I did figure out that could happen sometime in the past 13 hours. I'll see if I can puzzle it out.
Answer: To rename files properly before they got saved (when a file being inserted or updated), use hook_file_presave() to change the filename in the table, or hook_file_insert() after a file has been added to the database, then use file_move() to actually move that uploaded file.
Here is an example using hook_file_insert:
/**
 * Implements hook_file_insert().
 */
function mymodule_file_insert($file) {

  if (strpos($file->filename, 'ShowImageXML.asp') !== FALSE) {
    $ext = strpos($filename, '.') !== FALSE ? drupal_strtolower(substr($file->filename, strrpos($file->filename, '.') + 1)) : '';

    $filename = sprintf("%d-%d.%s", $file->uid, $file->timestamp, $ext);
    $uri = 'public://' . $filename;
    watchdog('mymodule', 'File has been renamed from !old_file to !new_file.', array('!old_file' => $file->filename, '!new_file' => $filename), WATCHDOG_INFO);
    $file = file_move($file, $uri);
  }
}

If you need to do the same when a file has been added to the database, use hook_file_presave with similar code as above, but it's only for renaming file names in file_managed table, not in the file system.
Answer: Since Drupal manages the files usually you dont need to rely on file naming conventions to know what user uploaded a file and when. You can just look it up in the db.
If you really need to change the file paths:
Option 1
An easy way to do this is by adding a computed field that looks the managed files the user uploaded and creates/manages copies by appling any pattern you may want. Then on node display you use the copy
Option 2
You alter the file upload widget or you use a module like the ones you propose to do this. This method requires no copies
Option 3
You go with a headless Drupal method. I.e. you dont use the node edit form but you create your own with Jquery, Angular, or anyother fronted framework. Then you create an API on the drupal side and you do whatever you want with the uploaded files before you persist/manage them and create a node. This method gives you suberb control and you can apply other custom functionality too (e.g. conversion of file types with imagick or custom cropping or annotations...) Howver if you go with this method make sure you take care of security issues (e.g. CSRF handling) that normally drupal takes care of automatically


What is the probability that if five hats are distributed among five boxes that box $B_1$ has hat $H_1$ or hat $H_2$ but not both?

Question: There are $5$ different boxes $B_1, B_2, B_3, B_4, B_5$ and $5$ different hats $H_1, H_2, H_3 H_4, H_5$. The hats are to be distributed among the different boxes. Each box can accommodate all the hats.
A) What is the probability that $B_1$ has either $H_1$ or $H_2$ but not both?
B) If $B_1$ and $B_2$ have the hats $H_1$ and $H_2$ among themselves, in how many ways can you arrange the hats among the $5$ boxes?
Answer of A part is $2 \cdot 5^4-5^3/5^5=9/25$
Answer of B part is $4 \cdot 5^3$
Can anyone please explain this to me?
Comment: The content of the problem and tools used to answer are not actually related to permutations or combinations, but rather something more general and more fundamental.  I discourage the overuse of the words permutation and combination and encourage you to instead call this a counting problem, using the broader blanket term of combinatorics for the genre of question it is.
Comment: "question based on probability" is by no means an improvement over your previous title "question based on permutation and combinations" (the second question is not a probability issue) ...
Answer: Each of the different ways of distributing the hats can be described as a 5-tuple, $(x_1,x_2,x_3,x_4,x_5)$, where $x_i$ represents which box hat $i$ was placed in.
For example, $(1,1,2,1,4)$ corresponds to box1 containing hats 1 2 and 4, box2 containing hat3, and box4 containing hat5.
From rule of product we know that there are $5^5$ possible such 5-tuples and therefore $5^5$ different ways to distribute the hats.
The problem statement does not explicitly state how we randomly distribute the hats, but a common assumption for problems like these is that each hat is distributed uniformly and independently at random amongst the boxes, implying that each of those $5^5$ possible ways of distributing the hats are equally likely to occur.  This is an important observation because it allows us to use counting techniques to continue the problem.
For the first question, finding the probability that the first box has hat1 or hat2 but not both (while also possibly having additional hats beyond those), we count how many 5-tuples correspond to such an arrangement.  Again, approach via rule of product breaking it down into steps as follows:

Pick whether it is hat1 or hat2 that is in box1  (2 options)
Whichever wasn't picked in the first step, pick which box it does go to remembering that it cannot be box1 (4 options)
Pick which box hat3 is in (5 options)
Pick which box hat4 is in (5 options)
Pick which box hat5 is in (5 options)

Applying the rule of product, we have then $2\cdot 4\cdot 5\cdot 5\cdot 5 = 8\cdot 5^3$ such arrangements of hats satisfying the phrase "exactly one of (but not both of) the first two hats are in box1."
Using what we know about finite equiprobable sample spaces then, the probability of this happening is the ratio of the number of favorable outcomes divided by the total number of outcomes.  I.e. a probability of $\frac{2\cdot 4\cdot 5^3}{5^5}=\frac{8}{25}$.
This contradicts your answer in the original post which might have caused some of your confusion.  An answer of $\frac{9}{25}$ actually corresponds to the probability of at least one of the first two hats being in the first box, including the possibility of both.  To have calculated this, we could approach similarly to above, having first broken into cases based on whether exactly one or both of the first two hats were in the first box, giving a total number of valid sequences being $2\cdot 4\cdot 5^3+1\cdot 1\cdot 5^3$ and the probability then as $\frac{2\cdot 4\cdot 5^3+1\cdot 1\cdot 5^3}{5^5}=\frac{2\cdot 4+1}{5^2}=\frac{9}{25}$.  Alternatively, you could have calculated this using inclusion exclusion arriving at the same answer.
The second part of the problem is very similar to the first.  The steps for rule of product being:

Pick location of hat 1
Pick location of hat 2
Pick location of hat 3
Pick location of hat 4
Pick location of hat 5

 With 2 options for each of the first two steps and 5 options for each of the remaining steps, that gives the total number of valid arrangements as $2\cdot 2\cdot 5\cdot 5\cdot 5=4\cdot 5^3$ valid sequences.  Taking the ratio then, this gives the probability as $\frac{4\cdot 5^3}{5^5}=\frac{4}{25}$
Answer: I'm assuming that we're supposed to think each possible matching is equally likely.
There are $5^5$ possible matchings, as each hat can be assigned to any one of the five boxes. To answer part (a), we need to know how many matchings include exactly one of {H1, H2}. Well, 1/5 of the possible matchings - that is, $5^4$ of them - will include H1, and by symmetry $5^4$ will include H2. Summing those gives us $2\times5^4$, but we have actually included some possibilities twice: the ones where both H1 and H2 are included in B1. In fact, we need to remove these matchings twice, as the question states only one of H1 and H2 can be in B1.
Matchings which include both will have the positions of H1 and H2 fixed in B1, but {H3, H4, H5} can still go in any of five positions, so that's $5^3$ possible matchings out of $5^5$.
In summary, we have $(2\times5^4 - 2\times5^3)/5^5 = 8/25$ probability for (A).
For (B), the last three hats can still go anywhere - we saw before that gave $5^3$ options. And now there are only 2 choices for H1 and H2, and $2\times2=4$, so our total number of possibilities is $4\times5^3 = 500$.
Comment: Same incorrect answer as the OP for (a).  Read the phrasing more carefully.
Comment: I was under the impression that the OP had been given the correct answer in the form of a calculation, but didn't understand it, and needed it explaining. I reached the answer 9/25. Where exactly is the mistake I made?
Comment: @JMoravitz Ah, ignore me. Found the mistake.
Answer: Part (A) :
No of ways of distributing hats to boxes such that B1 has neither H1 nor H2 = $4^2\times5^3$.
[As each hat except H1 and H2 can go to any 5 boxes while H1 and H2 both have 4 choices.]
Also, total no of ways = $5^5$
So, probability ($P$) that B1 has neither H1 nor H2 = $\frac{4^2 \times 5^3}{5^5} = \frac{16}{25}$.
Since the above is the complementary event of either H1 or H2 in B1.
Probability that B1 has either H1 or H2 = $1 - P = \frac{9}{25}$.
Probability that B1 has both H1 and H2 = $\frac{1 \times 1 \times 5^3}{5^5}$ = $\frac{1}{25}$.
Hence, required probability = $\frac{8}{25}$.
Part (B) :
No. of ways of arranging B1 and B2 among H1 and H2 is 4.
[Both B1, (B1-H1,B2-H2), (B1-H2, B2-H1), both B2.]
Other hats in $5^3$ ways.
So,total no. of ways = $4 \times 5^3$.
Comment: Same incorrect answer as OP for part (a).  The complementary event for "Exactly one of H1 and H2 are in B1" is actually "Both or none of H1 and H2 are in B1."  You neglected the possibility of both, and as a result calculated the probability of "At least one of (and possibly both of) H1 or H2 being in B1" rather than the probability of "One of (but not both of) H1 or H2 are in B1."
Comment: Yeah, you are right @JMoravitz. I have corrected my answer.
Answer: My reasoning seems too simplistic and is probably flawed but does give the solution to the first problem. The chance of hat1 not being in box1 is $\frac 4 5$ and likewise for hat2. $\frac 4 5 \times \frac 4 5 = \frac {16} {25}$. Thus the chance of one or both being in box1 is $\frac {25} {25} - \frac {16} {25} = \frac 9 {25}$. The chance of both being in box1 is $ \frac 1 5 \times \frac 1 5 = \frac 1 {25}$. So for only one of them we have $\frac 9 {25} - \frac 1 {25} = \frac 8 {25}$.


An inequality in triangle geometry involving triangle OIH

Question: Let triangle ABC be such that the points O,I,H are not collinear (O,I,H being the circumcenter, incenter and orthocenter respectively.) Show that $2R_{OIH} > R_{ABC}$, where $R_{ABC}$ and $R_{OIH}$ are the circumradiuses of triangles ABC, OIH.
I was able to prove it only for obtuse or right triangles. It is well known that $\angle OIH > 90$, thus $\sin OIH < 1$. Next, by the sine law we obtain that
$  \dfrac{OH}{\sin{OIH}} = 2R_{OIH} $ thus the inequality we have to show becomes $ \dfrac{OH}{\sin{OIH}} > R_{ABC}$, or equivalently $\dfrac{OH}{R} > \sin{OIH}$. Since $OH \geq R$ when $ABC$ is obtuse or right, we obtain that $\dfrac{OH}{R} \geq 1 > \sin{OIH}$ and thus the inequality is proven.
How could one go about proving the inequality for acute triangles? I tried many tricks, such as using the formulas
$$ R = \dfrac{abc}{4S} , S_{OIH} = \dfrac{1}{8r}(a-b)(b-c)(c-a)$$
in order to obtain an expression for $R_{OIH}$; I have also tried to use the Mitrinovici inequality, which in this case says $R_{OIH} \geq \dfrac{2}{3 \sqrt{3}} (OI + IH + OH)$, using which one arrives at the following inequality, after applying the formulas for the three distances:
$$14R^2 + 10Rr + 5r^2 - 3p^2 > \dfrac{3\sqrt{3}}{2} R ,$$
where $R,r,p$ are the circumradius, inradius and semiperimeter of ABC. I have not been able to prove this inequality.
Another interesting and possibly useful fact is that $\angle IOH < \dfrac{\pi}{6}.$ However, using this in order the bound the sinus of $\angle IOH$ is not strong enough to prove the inequaity.
Source for almost all inequalities mentioned: https://en.wikipedia.org/wiki/List_of_triangle_inequalities
The formula for the area of triangle OIH can be found in Titu Andreescu's Complex Numbers from A to Z.
Answer: By Feuerbach's theorem the incircle is tangent to the nine-point-circle, whose radius equals $\frac{1}{2}R_{ABC}$, since the nine-point-circle is the circumcircle of the median triangle. It follows that the distance of $I$ from the midpoint of $OH$ is exactly $\frac{R}{2}-r$, and the circumradius of $OIH$ is larger than the circumradius of an isosceles triangle with base $OH$ and height $\frac{R}{2}-r$. It is enough to show
$$ (R-2r)^2+OH^2 \geq 2R(R-2r) $$
which is equivalent to
$$ 8R^2+4r^2 \geq a^2+b^2+c^2\qquad \Longleftrightarrow\quad  OH^2+4r^2\geq R^2$$
just a slight strengthening of $9R^2\geq a^2+b^2+c^2$.


jquery mmenu opens by default

Question: I've set up a new page and added jQuery.mmenu. now when I load the page the mmenu opens already by default.
mmenu is firing and adding mm-opened on the body on page load. Then the css transition kicks in and mmenu is opened nicely.
But I want it only to be opened when click on a menu button. Very strange. Anybody heard this before?
jquery:
$(document).ready(function() {
  $("#my-menu").mmenu();
});

html:

But WHy?

//content

Nothing special going on in the markup
Answer: Add this to your css stylesheet and test it:
#my-menu:not(.mm-menu) {
  display: none;
}

Answer: Add "mm-wrapper_sidebar-closed" class to html tag.
Answer: I added in html (javascript):
window.location.hash = "menu";
Answer: Ivan, I upvoted you because it made me realize that the issue for me is related to the hash, thanks : ).
If you're not opening the mmenu programmatically with JS, it instructs you to have a link with the href property set to the selector of the menu that you want to open. So I have something like:
 ...

to target the menu selector with an ID of navbar-menu. What I didn't realize was I had clicked on this link before all of my JS code was in place, so the current URL still had a hash in it pointing to the menu selector. e.g.
https://yourdomain.com/#navbar-menu

I'd refresh the page and the menu would just open automatically. Because mmenu allows you to use a hash to define the state of the menu - open when the hash corresponding to the menu selector is in the URL.
FYI for anyone who is running into the same issue. If the menu is opening automatically, remove the hash.
Answer: You can use the "initial" option under the sidebar addons.
    sidebar: {
        collapsed: {
            use: '(min-width: 450px)',
            hideNavbar: false,
        },
        expanded: {
            use: '(min-width: 992px)',
            initial: 'closed'
        },
    },

reference: https://github.com/FrDH/mmenu-js/issues/967

jquery mmenu opens by default


What does a singing teacher refer to when he/she says that a singer should use the ears and listen?

Question: Sometimes singing teachers say things like: use your ears and listen when you sing.
To me this sounds a bit crazy. I would say that what most people do is focusing on feeling the notes rather than on hearing them. I am not the expert so I might be wrong. I myself try to feel the notes rather than hearing them. This is why I don't understand why focusing on hearing is the best thing to do. I am not sure that singers even hear what they sing. Pianists might hear but not singers.
What does a singing teacher refer to when he/she says that a singer should use the ears and listen?
Comment: @Hank Can you hear if/when your singing goes out of tune? I can, and I have to correct myself quickly whenever I do so. (I'm worried that you sing off-key due to not hearing yourself sing.)
Comment: What do you refer to when you say that you feel and don't hear? Do you "feel" when you're out of tune, or rushing or dragging, or too aggressive in a soft passage, or too soft in an aggressive passage? Can you feel the lyrics?
Comment: feeling? let's say I sing Do-Re-Mi-Fa. I will feel eg. the Mi-Fa rather than just hear it. It just have to come. It is super difficult to explain. It's like Mi just leads me to Fa. Sometime I will fail because I refuse to just go with how Mi leads to Fa. I will be able to hear afterwards on a recording. I feel how difficrent notes lead to echother. When I sing Do-Mi-Sol I just have to let harmonics do the job. It is not about hearing.
Comment: Have you tried singing and playing the same notes on an instrument at the same time? How do you tell if you sang the same or different notes you played on the instrument?
Comment: you could be very correct
Answer:
For timing.

To keep in tune with whatever else is going on.

To listen to the quality of the voice.

To balance with whatever else is going on.

To be aware of diction and appropriate volume for each word/phrase.

When using a mic, to have it in the best place for tone and volume.

Can't really understand why every singer doesn't listen properly, but some need to work on that side of things. Not so much 1 2 and 3, but certainly 4, 5 and 6.
And why single out vocals? Every musician's most important organs are their ears!
No doubt others will mention lots that have been missed here.
Comment: I guess an easy test would be to wear some ear defenders and try singing - record it. Hear what happens.
Comment: so listening is more important than feeling what you do?
How do singers listen? I just find that feeling what I do is easier than hearing what I do.
Answer: Singing by feeling involves a lot of guesswork that a person might not be aware of. When a person can't hear himself sing, his brain doesn't have enough information to know exactly how to adjust muscle control in the voice box, breath control and volume control. Finding your pitch is next to impossible for most folks. If you've ever heard someone singing along to music while listening on headphones without their own voice in the mix, you can appreciate the importance of being able to hear yourself when you sing. Try cupping your hand around your ear, holding it close to the side of your face and notice the difference in the way you sing when you can hear yourself. You'll probably notice both a difference in the way you sound when you sing, and because you'll be adjusting the sound of your voice according to what you're hearing, the way it feels will also feel differently to you. I'm a strong advocate of experimentation and I encourage others to try as many different ways as they can think of to grow and develop their musical skills.
Comment: It's been said tat we can 'hear' what we sing due to the vibrations going from mouth/throat through our skull's bone structure and eventually to our ears. Not sure if that 'fact' has relevance here.
Comment: @Tim- I can't dispute your point, but I know I sound much different to others when I sing than I do to myself when I sing without the help of a good monitor system. I'm guessing the voice instructor is trying to help the student realize how they sound to others by listening to the external sound of the voice as compared to the internal sound  you are referring too.
Comment: We all sound very different when we compare our voice played back in recordings to what we think we sound like! And when using amps, that quality, for want of a better term, is generally enhanced to sound better than we would 'acoustically'. I stopped using foldback several years ago, for many reasons - one being it couldn't be guaranteed that the monitor sound was anything like the p.a. sound, so it was sometimes a red herring.When I did sound for jazzers from all over the world, we could take time to adjust the p.a. and foldback so it sounded just like acoustic, for those who knew what ...
Comment: ...they wanted. That was a joy. But now, I don't have that luxury afforded, so feel safer listening to what the p.a. is delivering.


Load java libraries from relative path

Question: I've written a Java program that uses OpenCV library. So far, I executed the program with eclipse (and set the Jar location in eclipse properties).
This is a college final project. My instructor now wants to run the program in his computer. How can I generate a runnable jar(using Ant or using Java code) that will load the Java OpenCV jar from specific location (a directory that will be located in the executable Jar directory), that will work with Linux and Windows (I understood that linux uses a Jar file, and Windows uses a dll file)?
I've tried using:
String currentDir = System.getProperty("user.dir");
System.load(currentDir + "/path_to_jar/opencv-248.jar");

(let's ignore the fact that it will only work with linux) But when executing the jar, the following error occurs:

OpenJDK 64-Bit Server VM warning: You have loaded library /path_to_jar/opencv-248.jar which might have disabled stack guard. The VM will try to fix the stack guard now.
  It's highly recommended that you fix the library with 'execstack -c ', or link it with '-z noexecstack'.
  Exception in thread "main" java.lang.UnsatisfiedLinkError: /path_to_jar/opencv-248.jar: /path_to_jar/opencv-248.jar: invalid ELF header (Possible cause: endianness mismatch)

Any help would be highly appreciated.
Comment: linux does not load "jars", it loads '.so' files.  the jar goes on the classpath.  the shared library '.so' should be available in a location defined by the java command line argument '-Djava.library.path'.
Answer: Use the classpath option for your java executable.
If you're running OpenJDK read the manpage at http://linux.die.net/man/1/java-java-1.6.0-openjdk
You should be able to use something along the lines of:
java -jar yourapp.jar -cp ./path_to_jar/
Another option is to build a JAR which includes its own dependencies. Here are some examples I found using the search terms "java create jar include dependencies":
Using Maven
Using Eclipse
Comment: Both options output the error: "java.lang.UnsatisfiedLinkError: no opencv_java248 in java.library.path". Couldn't it be done without the user having to change his system?
Comment: The links I provided should explain how to build a JAR which includes its dependencies. Can you update your original question with the alternatives you tried and any errors produced?

Load java libraries from relative path


Cachefilesd (cachefiles) everything seems to be set up, still not working

Question: I'm trying to set up cachefilesd to work with my network folder shared using NFS.
I have seemingly everything set up, however cachefilesd starts normally, however caching isn't functioning.
Here is output of commands, which I ran in the same order
1
sudo mount
...
cache-1:/mnt/datashared on /mnt/nfsshare type nfs (rw,sync,ac,acregmin=3,acregmax=60,acdirmin=30,acdirmax=300,lookupcache=pos,vers=3,fsc)
...

2
lsbmod | grep cachefiles
cachefiles             40555  1
fscache                57430  4 nfs,cifs,cachefiles,nfsv4

3
[edited - deleted]

4
uname -r
3.8.0-34-generic

5
grep CONFIG_NFS_FSCACHE /boot/config-3.8.0-34-generic
CONFIG_NFS_FSCACHE=y

6
lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 13.04
Release:    13.04
Codename:   raring

7
sudo service cachefilesd restart
* Restarting FilesCache daemon cachefilesd     [ OK ]

8
dmesg
[6211206.141781] FS-Cache: Withdrawing cache "mycache"
[6211210.135236] FS-Cache: Cache "mycache" added (type cachefiles)
[6211210.135242] CacheFiles: File cache on sdb1 registered
[6214644.348929] CacheFiles: File cache on sdb1 unregistering
[6214644.348935] FS-Cache: Withdrawing cache "mycache"
[6214654.575909] FS-Cache: Cache "mycache" added (type cachefiles)
[6214654.575915] CacheFiles: File cache on sdb1 registered

9
ps aux | grep cachefilesd
root     65399  0.0  0.0   4460   540 ?        Ss   23:14   0:00 /sbin/cachefilesd
1000     65464  0.0  0.0   8160   916 pts/0    S+   23:16   0:00 grep --color=auto cachefilesd

finally, biggest problem is
10
cat /proc/fs/nfsfs/volumes
NV SERVER   PORT DEV     FSID              FSC
v3 64476645  801 0:24    233e020f0da07a93  no

tl;dr I think I configured everything properly but FSC mount option + fscachefilesd don't seem to work
Answer: What does cat /etc/default/cachefilesd say?
Is it set to on?
# Defaults for cachefilesd initscript
# sourced by /etc/init.d/cachefilesd

# You must uncomment the run=yes line below for cachefilesd to start.
# Before doing so, please read /usr/share/doc/cachefilesd/howto.txt.gz as
# extended user attributes need to be enabled on the cache filesystem.
RUN=yes # <------ this line needs to be uncommented

# Additional options that are passed to the Daemon.
DAEMON_OPTS=""


Is there a theme equivalent of hook_install()?

Question: I want my theme to control certain block settings, like which elements of the system branding block are enabled. To me it makes sense for that to be code in the theme, not a module, because at the moment the only way I've found to access the config programmatically involves using the theme name.
/** @var Drupal\Core\Config\Config $config */
$config = \Drupal::service('config.factory')->getEditable('block.block.my_theme_branding');
$config->set('settings.use_site_logo', false);
$config->save();

Since this is a one off config change, I think it should only happen when the theme is installed/activated. It there a theme function/hook that behaves like hook_install does for modules?
Answer: You may provide configuration via YAML files as part of a module, profile or theme install by adding them to the config/install directory inside the respective project. So, for example, a file block.block.my_theme_branding.yml would install the branding block into the specified region. This would then contain the setting to disable the site slogan by default. Take a look at block.block.bartik_branding.yml in the standard profile as a starting point.
If the specific block is provided by another module, then it should probably be placed in the config/optional directory.
Answer: That was a missing feature; however, after a conversation in IRC that is a feature that we want to implemented. Its currently been working at Add (back) hook_install for themes.
The solution from @mradcliffe have a lot limitation, because you cant override a anything unless you are a profile.


Gibbs sampling for a simple linear model -- need help with the likelihood function

Question: So in order to better acquaint myself with Gibbs sampling, I've been working on a fairly simple linear model, written in Python/R. Basically, I have 2-dimensional input data (the xi) and a scalar output vector (the yi). I am looking to fit a beta vector, i.e. βT * xi = yi + εi (εi is the noise).
So I decided I'd use a Gaussian prior for the betas, plus an inverse gamma prior for their variance, giving me a posterior distribution that is Gaussian (thanks conjugacy!). And so I used the formula from the Wikipedia page on conjugate distributions to get the likelihood function I need to generate random samples of my beta coefficients and their variances, given the data (by their notation, xi's):
So, it would seem in order to do Gibbs sampling I simply iterate through β1, γ1, β2, and γ2, generating samples from the distributions listed on that wikipedia page. My confusion is, what exactly are my data points (the "samples" I'm using to calculate the distribution parameters, which I need to sample my own betas, i.e. the xi's on the Wikipedia page)??? The way I see it, it could be one of two things. For discussion purposes, let's discuss β1 for now.

First thought is, I'll just iterate over each i, generating my data points using (yi - β2*xi,2) / xi,1 — basically, I subtract out the influence of the second factor and divide the "leftovers" by the first factor, to obtain the impact of the first factor on the response variable. Then I can just use that population to get my distribution parameters, and finally can sample my β1 and γ1.
Second thought is, I'll just go through each i, and generate my data points as (yi / xi), meaning I do NOT subtract out the influence of the other factors on the response variable; it treats everything independently.

So far I've been using #1, but even with artificial data sets, I'm finding that it is implying enormous beta variances that don't seem to make any sense — BUT, they are darn close to the sample variances in the populations I'm generating (my "data points" I use to calc those distribution parameters). What am I doing wrong? Is #1 or #2 the right way to do a linear model? Or am I missing something entirely?
Thanks in advance for your help! Please let me know if any info would help.
Answer: This is a statistics question, not a programming question, and would better be asked on CrossValidated. At least, the LaTeX code is getting parsed there automatically :). Also, this is more complicated than what is readily available on that webpage. I'll give some guidance, but as long as you want to learn how to do things, this won't be the complete answer. (If you don't want to do that, we can locate the cooked answers on the web, too.)
Each sampling of betas relies on the complete data set. If you are doing this with individual y_i's and x_i's, you are not doing this right. Before you start working with the code, you need to sit down with a piece of paper (letter size or A4, depending on your geography) and derive the posterior distributions of betas:

This is given: y|beta is normal with mean x'beta and precision tau
This is given: prior for beta is normal with mean mu and precision gamma
Obtain this: the marginal distribution of y, by integrating the betas out (which is easy to do, since the joint distribution of y and beta is multivariate normal, and you can do this by kernel matching: the part that depends on beta is going to be exp[ a quadratic form in beta], so you recognize this to be a relevant part of a normal distribution distribution to integrate over; whatever's left after integration should be a normal density in y and the prior parameters)
Obtain this: the posterior distribution of beta given y, by Bayes theorem (the likelihood times the prior divided by the posterior; again this should be a moderately complicated combination of exp[ jointly quadratic in y and beta ])
Obtain this: the conditional distribution of beta_1 given beta_2 and y, one of the margins of the multivariate normal distribution obtained at the previous step.

You need to know how to manipulate the multivariate normal distribution and get conditional and marginal distributions out of it. Again, if this is over your head, we can find the ready solutions.
Note that you also need a sampler for the variance of regression errors, unless you treat it as known (which is hardly a practical situation). This will be slightly more complicated, as you would need to incorporate another dimension into your integration procedures.
Comment: Precision is the inverse of variance. Just a different name. As you've seen on Wikipedia page, it is easier to work with precisions, as they are additive as far as computing the posteriors are concerned. You could check your calculations by having a regression with a single explanatory variable, an intercept. Then your formulae should reduce to the ones on Wikipedia page.
Comment: Thanks so much for answering. I thought if I did derive it by hand (like I used to do for prob sets in college) I would just end up with those formulas for the Wikipedia page, but with the data transformed in some manner. I was trying to circumvent the derivation step by transforming the data directly and using those formulas. Guess I will have to suck it up and get down to business on that. Will report back after I do - but one question first. In part #1, you mention a variable tau. I assume that is what I am supposed to sample from the gamma distribution? How do I derive the form of that?Thx


Show that the measure is equal to zero

Question: Let $\mu$ be a Borel measure in $\mathbb{R}$ such that $\mu(I) \leq v^a(I)$ for each bounded interval $I$, where $a>1$. Show that $\mu=0$.
($v(R)$ is the volume of $R$)
Do we maybe use the following to show that?
For each rectangle $R$, $m^*(R)=v(R)$.
Or do I have to do it otherwise?? Could you give me some hints??
Comment: Could you say what is $v$?
Comment: It should be $\mu(I) \le (v(I))^a$, where $v(\cdot)$ is the Lebesgue measure.
Comment: @LiuGang  $v(R)$ is the volume of $R$
Answer: For every interval $I =[x,y)$ and every $n \in \mathbb{N}$ we have that
$$I= [x,y)= \bigcup_{k = 0}^{n-1} \underbrace{\left[ x + (y-x)\frac{k}{n},x + (y-x)\frac{k+1}{n}\right)}_{I_k}$$
Then $$\mu(I_k) \leq \nu(I_k)^a = \left(\frac{y-x}{n}\right)^a$$
Now by additivity we have
$$\mu(I) = \sum_{k=0}^{n-1} \mu(I_k) \leq \sum_{k=0}^{n-1}\left(\frac{y-x}{n}\right)^a = (y-x)^a n^{1-a} \stackrel{n \to \infty}{\longrightarrow} 0 $$
Hence $\mu(I)=0$ for every interval so $\mu = 0$.
Comment: I understand!! Thank you very much!!! :-)
Answer: Hint: Notice that $[a,a+b)=[a,a+b/2)\cup [a+b/2,a+b)$. Use this to show that $\mu([a,a+b))$ is smaller than any $\varepsilon>0$.
Comment: Ok!!! Thanks a lot!!! :-)

Show that the measure is equal to zero


Github: added to org and have rights but unable to push

Question: I was added to my work org's github, to which it's an organization assigned github username.  I was added to that repo and cloned it locally.  I made a change and went to push and see fatal: Could not read from the remote repository Please make sure you have the correct access rights and the repo exists.
I checked the ssh pub key I added to my github org profile and it's the same as my computer's.
The only other thing I changed, which I would suspect would not effect this, was I edited git.config --global user.name and  git.config --global user.email to put in my "Phillip C" for my name and "email@example.com" for email.
The ssh key has:
ssh-rsa [My whole long key]firstname.lastname@example.com

Could it be because the username/email was expecting firstname.lastname@example.com from the ssh pub key?
Comment: The last part of an SSH key is a comment and can be anything. It's not used for authentication. `user.name`/`user.email` also aren't used for authentication, only for commit creation.
Comment: thanks @phd .  So how does git know who i am?  iSo would it be something on the org's side that is restricting me then?
Comment: Not enough info. Verify `git remote -v` — is it the correct repo? Does it use SSH protocol — either `firstname.lastname@example.com:user/repo` or `ssh://email@example.com/user/repo`? Try `ssh -Tv firstname.lastname@example.com` — does it recognize you?
Comment: it's the correct repo..it uses `email@example.com:user/repo`.  I just tried `ssh -Tv firstname.lastname@example.com` and it was a long debug output, which at the end says `The authenticity of host email@example.com can't be established.  RSA key fingerprint is SHA256:***********. Are you sure you want to continue connecting (yes/no/[fingerprint])`
Comment: https://stackoverflow.com/search?q=%5Bssh%5D+The+authenticity+of+host+can%27t+be+established
Comment: "The authenticity of host email@example.com can't be established.  RSA key fingerprint is SHA256:***********. Are you sure you want to continue connecting (yes/no/[fingerprint])" That would a "yes", eh.
Answer: Your key (ahem) question is actually in a comment:

So how does git know who i am?

The answer is: Git does not know or care.  Git does no authentication at all.  Git makes commits (git commit), extracts commits (git checkout), and does other things purely locally, on your computer.  For this, it does not need authentication.  Your computer does whatever authentication your computer does, and that's all Git cares about.
Git also, however, transfers commits to another Git (git fetch or git push).  This involves calling up some other Git, typically over the Internet-phone.  This does need authentication.
Git doesn't do it.
Git relies on external software—software that establishes the connection to the other Git, so that your Git can talk to their Git—to do all the authentication.  Git continues not to know or care who you are.  It will, under various circumstances and/or using various helpers, deliver some claim(s) from you about who you are to whatever software is going to vet those claims.  This is where things start getting complicated.  Fortunately you're using ssh here.  Ssh authentication is extremely complex (and flexible) but ssh needs no help from Git.  You just plug in a URL, such as:
ssh://email@example.com/path/to/repo.git

or:
email@example.com:path/to/repo.git

(these two strings mean exactly the same thing to Git; Git takes the ssh:// part as meaning "use ssh", and the firstname.lastname@example.com: part as meaning "use ssh", and then passes the email@example.com part to ssh).
The reason phd suggests using ssh -Tv firstname.lastname@example.com is that this takes Git entirely out of the equation.  You can now see whether ssh is able to call up email@example.com and if so, whether whoever answers the "phone" there believes that you are you.  You now need only deal with ssh itself.
What you need to know here is that when ssh sees firstname.lastname@example.com, your ssh:

turns github.com into an Internet address (IPv4 or IPv6);
uses your OS's networking to contact someone there on the standard ssh port (TCP port 22);
verifies that as far as you / your system can tell, you're talking to the same system you were talking to last time—or if this can't be discovered, gives you that authenticity of host ... can't be established message, and lets you decide whether to risk talking to them; and
assuming you allow it to proceed (or that you did before and so it seems safe to talk to the same computer again), sends some credential information to them, saying I would like to log in as user git.

This last part is correct!  You don't have an actual login account on GitHub.  You log in as the pseudo-user named git.  So do I, and so does everyone else who uses GitHub (well, everyone except the internal administrators and such).
In order to log in as user git, they demand that you send them a key, and they send you a key.  The key you send them is derived from the ones you generated above.  (These—the ones you generated, that has that comment at the end, are actually a pair, a public key and a private key.)
The trick that GitHub use here is that they know who you are by the key that you give to them.  All of these key exchanges and cryptographic tricks result in them—GitHub—getting, from you, a secret that you gave to them earlier.  Only you know that secret (presumably) so if they see that particular secret, this must be you.  If they see my secret, they know that some connection trying to "log in" as git is from me.
Once GitHub figure out who you are—from this information—they then allow this firstname.lastname@example.com connection to proceed, or not, to talk to a Git program that accesses the repository at the path you supply, based on whether the "you" that they figured out here is supposed to be able to access that repository.
The ssh -Tv trick is a simple way to have them tell you who they have figured you out to be.  The user firstname.lastname@example.com has only limited access on GitHub: it can only run Git commands.  Successfully authenticating to log in, but asking for a shell instead of to run Git transfers, gets a friendly "error message" of the form:
Hi _____! You've successfully authenticated, but GitHub
does not provide shell access.

(except that the blank is filled in) and then immediately quits.
This way you can tell who they think you are
The reason we need this is that if you have multiple accounts and different ways to access GitHub—which often occurs in corporate environments, for instance—you may have multiple keys that would give you access to various repositories.  Some key will identify you as "you at home" for instance.  You would use these for your personal repositories.  Other keys might identify you as "you at job X" and "you at job Y" and these would authenticate access to job-X and job-Y repositories respectively.
If you only have one key, all this stuff simplifies away: you either successfully authenticate as yourself, or you don't authenticate at all.  The test is still useful.  If you have more than one key, this test is even more useful because now you can see which key—or more precisely, which key that worked—you had your ssh send first.
If you have a very large number of keys, you'll need to learn more about ssh to learn how to control which keys get offered.  If your ssh comes along with a ring of a million keys and just keeps trying them randomly, they are probably going to get suspicious and kill your connection.  You'll want to have your ssh pre-select the right key.  This is also useful when you have two or three keys that will work, since the first (correct) key is the one that causes GitHub to believe you are who you claim to be, via that key.


Can't run global babel-node in es2015 mode

Question: so when I install these packages locally they work, but when installed globally (and removed them locally)
 npm i babel-cli -g
 npm i -g babel-preset-es2015
 npm i -g babel-preset-es2015-node

seems like that flag isn't setting es2016-node to look in the global package list. anyways this following error occurs:

npm run start myfile.js

babel-node --presets es2015-node -- bin/myScript.js "myfile.js"

/usr/local/Cellar/node/6.1.0/lib/node_modules/babel-cli/node_modules/babel-core/lib/transformation/file/options/option-manager.js:395
          throw new Error("Couldn't find preset " + (0, _stringify2.default)(val) + " relative to directory " + (0, _stringify2.default)(dirname));
          ^

Error: Couldn't find preset "es2015-node" relative to directory "/Users/user/project/bin"
    at /usr/local/Cellar/node/6.1.0/lib/node_modules/babel-cli/node_modules/babel-core/lib/transformation/file/options/option-manager.js:395:17
    at Array.map (native)
    at OptionManager.resolvePresets (/usr/local/Cellar/node/6.1.0/lib/node_modules/babel-cli/node_modules/babel-core/lib/transformation/file/options/option-manager.js:387:20)
    at OptionManager.mergePresets (/usr/local/Cellar/node/6.1.0/lib/node_modules/babel-cli/node_modules/babel-core/lib/transformation/file/options/option-manager.js:370:10)

npm ERR! Darwin 14.5.0
npm ERR! argv "/usr/local/Cellar/node/6.1.0/bin/node" "/usr/local/bin/npm" "run" "start" "myfile.js"
npm ERR! node v6.1.0
npm ERR! npm  v3.7.3
npm ERR! code ELIFECYCLE
npm ERR! email@example.com start: `babel-node --presets es2015-node -- bin/myScript.js "myfile.js"`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the email@example.com start script 'babel-node --presets es2015-node -- bin/myScript.js "myfile.js"'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the project package,

Answer: A hint is in the error message:

Couldn't find preset "es2015-node" relative to directory "/Users/user/project/bin"

Install the presets locally and have them saved as dependencies in your package.json by using the --save flag:
npm install --save babel-preset-es2015-node babel-preset-es2015

It is a wise move by Babel that presets are looked for locally only. This way you are forced to produce a module that is portable by describing the necessary dependencies required for its operation within the package.json, which are then installed by users via npm install.
Comment: wouldn't it be wiser to build the es2015 within the babel-node, so people can use flag to fast configure it instead of dealing with a global executable looking for dirpath modules/configs?
Comment: Babel isn't exclusively an ES6 -> ES5 transpiler, hence the configuration necessary for it to do this.
Comment: maybe not, but i feel that babel-node without es2015 is inadaquete as a node runner as it doesn't understand module pattern, destructuring and perhaps other important features, why not have babel-node as a separate package that include babel-node-es2015.
Answer: npm update

solved the issue for me.
Comment: i think babel recently adopted the es2015 as 2016 is almost ending.


Convergence of $\sum_{n=1}^{\infty} \frac{1}{n^2}$ by comparing with $\frac{1}{1} + \frac{1}{2} + \frac{1}{4} + \ldots+$

Question: I am trying to prove that $\sum_{n=1}^{\infty} \frac{1}{n^2}$ converges using the series $\sum_{n=1}^{\infty} \frac{1}{2^{n-1}}$.
I know that the latter series converges to 2. Each term of the latter series is bigger than the corresponding term in the former series so the former series converges. I think the proof right now is already sufficient.
However, in my handwritten notes I see something that says "Twice of $\sum_{n=1}^{\infty} \frac{1}{2^{n-1}}$ converges, so $\sum_{n=1}^{\infty} \frac{1}{n^2}$ converges. Why do we need to look at twice of $\sum_{n=1}^{\infty} \frac{1}{2^{n-1}}$, i.e., $\sum_{n=1}^{\infty} \frac{1}{2^{n-2}}$, instead of just $\sum_{n=1}^{\infty} \frac{1}{2^{n-1}}$?
I could have miswritten something, so I just want to make sure the looking at $\sum_{n=1}^{\infty} \frac{1}{2^{n-1}}$ alone is sufficient.
Comment: This argument doesn't work at all. The terms of the exponential series decay much faster.
Comment: You are using both n's and i's as indexes.  Pick one.
Comment: @player3236 That was a typo that has now been corrected. It should have been twice of $\sum \frac{1}{2^{n-1}}$
Comment: $\sum_{n=1}^\infty n^2$ converges???
Comment: We don't need the factor $2$. Maybe there is a typo for $2\sum_{n=1}^{\infty} \frac{1}{2^{n}}$?
Answer: We can use the idea of Cauchy condensation test which leads to
$$\sum_{n=1}^{\infty}\frac1{n^2} \le \sum_{n=0}^{\infty}\frac{2^n}{2^{2n}}=\sum_{n=0}^{\infty}\frac{1}{2^{n}}=\sum_{n=1}^{\infty}\frac{1}{2^{n-1}} $$
that is
$$1+\frac14+\frac19+\frac1{16}+\ldots+\frac1{n^2}+\ldots \le 1+2\left(\frac1{4} \right)+2^2\left(\frac1{16}\right)+2^3\left(\frac1{64}\right)+\ldots$$
therefore the factor $2$ is not necessary at all even of course it leads to a sufficient condition for the convergence.
Comment: Wait is the series on the RHS just the one I wrote, i.e., $\sum_{i=1}^{\infty} \frac{1}{2^{i-1}}$?
Comment: Yes it is exactly that.
Comment: I'm now confused because doesn't each term on the LHS decrease slower than the terms on the RHS? So the inequality seems to be backwards?
Comment: I summed up some times and your inequality is correct. Interesting!
Comment: @roulette01 Take a look to the given link for more detail and feel free to ask for any clarification.
Answer: I like this one...
For $n> 1$
$\frac{1}{n^2} < \frac {1}{n(n-1)}$
$\sum_\limits{n=1}^\infty \frac{1}{n^2} < 1 + \sum_\limits{n=2}^\infty \frac{1}{n(n-1)} = 1 + \sum_\limits{n=2}^\infty (\frac{1}{n-1} - \frac{1}{n})$
$\sum_\limits{n=2}^N (\frac{1}{n-1} - \frac{1}{n}) = 1-\frac {1}{N}$
Taking the limit as N approaches infinity...
$\sum_\limits{n=1}^\infty \frac{1}{n^2} < 2$
What it looks like you have been asked for, though, is to break up this series into blocks like so $(1),(2,3), (4,5,6,7), \cdots.$ With succeeding block twice as big as the one before...
And for each block...
$\sum_\limits {n=2^k}^{2^{k+1}-1}\frac 1{n^2} < 2^k\frac {1}{2^{2k}} = \frac {1}{2^k}$
$\sum_\limits{n=1}^\infty \frac{1}{n^2} < \sum_\limits{n=1}^\infty \frac 1{2^n}$
This can be generalized to show that the series $\sum_\limits{n=1}^\infty \frac{1}{n^p}$ converges for all $p>1$
$\sum_\limits{n=1}^\infty \frac{1}{n^p} < \sum_\limits{n=1}^\infty 2^{(1-p)n}$


Can I use this Dirac delta distribution identity to evaluate this integral?

Question: I know of the identity $\int dy \delta(x-y)\delta(y-x') = \delta(x-x')$ but what about if I have an integral like $$\int dy \delta(x-y)\delta(y-x')f(y)$$Can the above identity be used in any way? Can say something like this?$$\int dx\int dy\delta(x-y)\delta(y-x')f(y) = \int dx \delta(x-x')f(x)$$
Comment: Intuitively that should equal $f(x)\delta(x-x')$.
Answer: Yes. You can think of integrals with delta functions as this: the integral will only not be zero at x=x'. You can plug the function g(x)=1 into the identity you listet and the result is g(x')* delta(x-x')=delta(x-x'). Applying this to the second integral gives the result f(x')*delta(x-x')
Comment: For some basic information about writing mathematics at this site see, *e.g.*, [basic help on mathjax notation](/help/notation), [mathjax tutorial and quick reference](//math.meta.stackexchange.com/q/5020), [main meta site math tutorial](//meta.stackexchange.com/a/70559) and [equation editing how-to](//math.meta.stackexchange.com/q/1773).
Comment: How is this an answer to the question? I don't follow at all. Where do you "plug $g=1$"? And how does this prove the formula for an arbitrary $f$?


Formatting date in domForm.toJson in dojo

Question: In my Web Application i have changed my dijit/form/DateTextBox date format using constraints="{datePattern:'MM/dd/yyyy'}" attribute,
But when i call the form containing the dijit/form/DateTextBox using domForm.toJson the format is changed to yyyy/dd/MM
why?
How to solve it
Comment: Check this [Getting different date pattern when using dojo.formToJson](http://stackoverflow.com/a/35102794/2932476)
Answer: Dijit/Form/DateTextBox is a dojo/widget not dom.
domForm.toJson access Dom's value not Dijit widget's get('value') function which gives you a formatted output as you expect.
To get correct value - Use Dijit/Form and then use form.get("value")
Dijit Form
Comment: is it possible to convert dijit form elements to json like domform
Comment: @nithinalways yes, indeed, form.get("value") returns an object


CAS username field value to be manually added to the existing user on import?

Question: I installed the CAS module on a Drupal 8 site, and it is working fine. For new users, it auto-registers the user with cas_username, but I would like to import the cas_username manually for the existing Drupal 8 user.
I also tried importing users in CSV format; I have been able to add the $account(row[0],row1), but for the CAS username import, i don't know how to import it, and in which field is stored.
<code>'uid' => NULL,
'name' => $username,
'field_first_name' => row[0],
'field_last_name' => $row[1],
'pass' => $username,
'mail' => $row[2],
'status' => 1,
'created' => REQUEST_TIME,
'roles' => array_values($config['roles']),
</code>
I tried Managing CAS username; the suggestion given is for Drupal 7, but the same method doesn't work for Drupal 8.
How do I import the CAS username in CSV?
Answer: I find out the solution for the CAS_username import in CSV method. The method of db_insert in (authmap) table, which dynamically insert the CAS_username in respective field.
The authmap table is present in external authentication module.
<code>    db_insert('authmap')
    ->fields(array(
     'uid' => $uid,
     'provider' => 'cas',
     'authname' => $row[0],
     'data' => 'N;',
     ))
    ->execute();
</code>
So this is the method, i dynamically update the CAS_username using CSV. If any suggestions or update in that. Kindly Prescribe it.


How many moves are at least needed to change the order of cubes to a arbitrary order?

Question: We have some distinct cubes that are ordered like below:

How many moves are at least needed to change the order of cubes to a arbitrary order?
valid moves:
in every step we can take a cube and put it on another cube or on the desk.

1.$11$
2.$14$
3.$17$
4.$23$
5.$25$

My attempt:If we put all cubes on the desk and then bring them together we will need $17$ moves so every case can be made using $17$ moves.I also got a combination that needs at least $16$ moves because it is a test the answer will be $17$ but I need a complete proof.So my question is which combination needs $17$ moves to be made?
Comment: what is a random order?
Comment: @NathanaelSkrepek I think he means "arbitrary". "Think" being the operative word.
Comment: Which order have you found that needs 16? And when you say "we can take a cube and put it on another cube or on the desk" do we have to take a cupe which is on the top, or can we take a cube in the middle (and have all the cubes on top of it follow along)?
Comment: I would probably go for a tower of IKHEDCBAFJ. To achieve that, I have to put everything from every tower somehwere else ( 7 moves) to access their bottoms, than put it everything on I (that makes 10 moves). All assuming I understand the question correctly.
Comment: @Arthur Yes I do.I edited it.Thanks.
Comment: There's 11 cubes, so 11 moves to put them on the desk, and another 11 moves to put them back again, which is 22 moves (not 17), right?  (Also, this assumes the desk can have more than one cube at a time.)
Comment: @RebeccaJ.Stones But some of them ar ealready on the desk.
Comment: @RebeccaJ.Stones 4 cubes are already on the desk, and to order them, you only need to move 10 of them with relation to a chosen static one
Comment: @TStancek Where is $G$ in your combination?
Comment: @TahaAkbari I missed that one, it should be between F and J. Basically, the idea was to access the bottoms, that way everything must come down, and next step is to put all in one tower starting with the bottoms, that way everything must be moved except for the I.
Comment: @TStancek I think it is better to bring $G$ befor $F$ in that way we are sure that non of the the upper cubes can move using $1$ move to the main tower because then the lower floors cube will be upper than that so we will need at least $7*2+3=17$ moves feel free to add your answer.
Answer: As already stated in the comment section, I would probably go for a tower of this kind
$$\begin{matrix}
J\\
F\\
G\\
A\\
B\\
C\\
D\\
E\\
H\\
K\\
I
\end{matrix}
$$
To achieve that, I have to put everything from every tower somehwere else ( 7 moves) to access their bottoms, because the bottoms come first (that makes 3 moves), than put everything else in this one tower (that makes 7 moves) in original order just to be sure none of the remaining cubes can be moved from its original position. Though the maximum should be guaranteed already by forcing the bottoms to go first.


Optimizing big SQL migrations

Question: Is there a tool that detects "inverse" operations (like add column/table in the beginning, drop it later) in a big (1800 statements) migration script?
Comment: You want to do this just once, or you want to check many scripts?
Comment: I don't know if a tool like this exists. I'll poke around but I feel like this would generate a large amount of false positives because adding and dropping tables is a pretty common way to deal with data transformations and such.
Comment: You can compare databases with the Visual Studio schema comparer, if you make a backup of your DB, run the migration script and compare the updated DB with the backup, you'll get "inverse" script.
Comment: sql server projects in visual studio 2012. use source control to keep a "before" and "after"
Answer: There is a tool that is all about 'revision' control for your database, for automating both structural changes and data migrations as part of your application upgrade process. I have used this tool successfully and with great effect for a number of years. I cannot recommend it highly enough.
http://www.liquibase.org/

Optimizing big SQL migrations


Merging CSV files with partly same filename

Question: I have a directory containing aprox. 1500 csv files with measuring data, like level, pressure, volume, etc.
The measuring data is exported every hour for every measurement.
So the generated filenames of Level would be Levelxx.csv, where xx ranges from 00-23
The same method applies for Volume and Pressure and all the other measurements, like volume00.csv - volume23.csv.
I want to merge all 24 files of a given measurement to one, like level-day.csv, volume-day.csv and so on.
The command: "copy /b level*.csv level-day.csv /y" works fine for one set,
but how to do that for many more measurements each having 24 hourly files?
The only common denominator in the filenames is the xx which ranges form 00-23.  Thanks in advance
Answer: You could simply iterate a static list of property names in a FOR loop. Note that multiple word names should be enclosed within quotes:
<code>@echo off
for %%A in (
  level
  pressure
  volume
  "multiword name"
   etc.
) do copy /b %%A??.csv %%a-day.csv /y
</code>
Or you could dynamically discover the names of the properties.
Assuming every property always has a time 00 file:
<code>@echo off
setlocal enableDelayedExpansion
for %%A in (*00.csv) do (
  set "prop=%%~nA"
  set "prop=!prop:~0,-2!"
  copy /b "!prop!??.csv" "!prop!-day.csv"
)
</code>
If time 00 might be missing sometimes:
<code>@echo off
setlocal enableDelayedExpansion

:: Delete any existing -day files
delete *-day??.csv 2>nul

for /f "eol=: delims=" %%A in (
  'dir /b /a-d *.csv^|findstr "[^0-9][0-9][0-9]\.csv$"'
) do (
  set "prop=%%~nA"
  set "prop=!prop:~0,-2!"
  if not exist "!prop!-day.csv" copy /b "!prop!??.csv" "!prop!-day.csv"
)
</code>


How to update two f.select from 2 different tables on ruby on rails

Question: I just started working on a Ruby On Rails project and i got to the point where i need to see the contacts of a company.
They should appear once the company is selected..

    <%= f.label :empresa_id %>

    <%= f.select(:empresa_id, @empresa.map {|e| [e.nombre, e.id]} )%>

<%= observe_field  :empresa_id, :url=>{:action => "get_contactos",
     :controller=> :contactos, :updatewith =>:empresa_id} %>

But nothing happens, i don't see even a error on the script/server.
Can someone point me in the right direction?
http://nealenssle.com/blog/2007/04/12/how-to-dynamically-update-form-elements-in-rails-using-ajax/
I see on the link that a guy did the exact same thing i need but did not post any info.
Cheers.
Answer: Kinda got this working.. here's my update..
This is the form were my select boxes are placed:

       ">

   "contacto_id",
  :with => "empresa_id", :url => { :controller => "contactos",
  :action => "get_contactos" } %>

The function get_contactos on the contactos controller :
def get_contactos
   @contacto = Contacto.find_all_by_empresa_id(params[:empresa_id])
    render :layout => false
 end
And the view get_contactos.rhtml (contactos):

  ">%>

I just need to bind the form to the correct fields and the job will be finished.
I couldn't get this to work by observing the field :empresa_id but "empresa_id" works..
Edit: Got it to work.
I just binded the field on the form to the proper ones on the model and now i have the data =)

       ">

   "llamada_contacto_id",
  :with => "empresa_id", :url => { :controller => "contactos",
  :action => "get_contactos" } %>


How to get term frequency and doc frequency from index produced by Lucene(version5.3)

Question: I am trying to get term frequency and doc frequency from index file produced by Lucene(5.3). The implementation is shown as below:
private static void showIndex(String iNDEX_DIR2) throws IOException {
    // TODO Auto-generated method stub
    System.out.println("INDEX_DIR:" + iNDEX_DIR2);
    IndexReader reader = DirectoryReader.open(FSDirectory.open(new File(iNDEX_DIR2).toPath()));

    int num_doc = reader.numDocs();
    System.out.println("number of docs: "+String.valueOf(num_doc));
    for(int docNum=0; docNum<num_doc; docNum++){
        Document doc = reader.document(docNum);
        System.out.println("Processing file:"+doc.get("id"));

        System.out.println("doc is null? "+ String.valueOf(doc==null));
        Terms termVector = reader.getTermVector(docNum, "content");
        TermsEnum itr = termVector.iterator();
        BytesRef term = null;

        while((term = itr.next()) != null){
            try{
                String termText = term.utf8ToString();
                Term termInstance = new Term("contents",term);
                long termFreq = reader.totalTermFreq(termInstance);
                long docCount = reader.docFreq(termInstance);

                System.out.println("term: "+termText+", termFreq = "+termFreq+", docCount = "+docCount);
            }catch(Exception e){
                System.out.println(e);
            }
        }
    }
}

When I run the snippet, I got the information:
INDEX_DIR:F:\Information Retrieval\project\TEST\INDEX
number of docs: 4
Processing file:null
doc is null? false
Exception in thread "main" java.lang.NullPointerException
   at IndexManager.showIndex

However, it show that the doc is not null.
May somebody help me with this problem?
Great thanks!
Answer: I'd guess that the NPE is thrown on:
TermsEnum itr = termVector.iterator();

IndexReader.getTermVector returns null if the field was not stored with TermVectors, which TextField, for example, is not.
You can set a field to store TermVectors in the FieldType.  If you need a TextField with TermVectors, you can pass the FieldType for TextField into the FieldType constructor to create a mutable copy of it, for example:
FieldType myFieldType = new FieldType(TextField.TYPE_STORED);
myFieldType.setStoreTermVectors(true);

doc.add(new Field("contents", fieldContents, myFieldType));

Comment: Actually, there is a field named "content". And if I invoke doc.get("content"), the program returns something.
Comment: Never said there wasn't.  I suspect that field was indexed *without TermVectors*.
Comment: So, what's the fieldContents?
Comment: https://lucene.apache.org/core/5_3_1/core/org/apache/lucene/document/Field.html#Field(java.lang.String,%20java.lang.String,%20org.apache.lucene.document.FieldType)


Fazer Lista Par e Impar

Question: Fiz um código onde o usuário vai inserir uma quantidade ilimitada de números em uma lista dinâmica encadeada até que digite 0 e pare a inserção, mostrando no final, todos os números digitados pelo usuário. Agora quero verificar os valores inseridos pelo o usuário e dividí-los em uma lista de números pares e outra lista de números impares. Alguém consegue me ajudar a desenrolar o restante desse código?
código que fiz até agora:
<code>#include <stdio.h>
#include <stdlib.h>

typedef struct ponto{
    int num;
    struct ponto * proximo; //PONTEIRO PARA O PRÓXIMO ELEMENTO
}t_ponto; //QUANDO FOR DECLARAR UMA VARIÁVEL NÃO SERÁ PRECISO DECLARAR TODO O "STRUCT", BASTA DECLARAR O t_ponto

int main (){

    t_ponto * ini_ponto; //PONTEIRO QUE MARCA O INÍCIO DA LISTA
    t_ponto * proximo_ponto; //PONTEIRO QUE MARCA O PRÓXIMO PONTEIRO DA LISTA

    int resp; //VARIÁVEL PARA COLETAR A RESPOSTA DO USUÁRIO
    ini_ponto = (t_ponto *) malloc (sizeof(t_ponto)); //ALOCANDO A MEMÓRIA

    if(ini_ponto == NULL){ //TESTANDO SE A LISTA ESTÁ VAZIA
        exit(1);
    };

    proximo_ponto = ini_ponto; //PRÓXIMO PONTO ESTÁ AGORA APONTANDO PARA O INÍCIO DA LISTA

    while(1){

        printf("Digite um numero para inserir na lista: ");
        scanf("%d", &proximo_ponto->num); //A VARIÁVEL DE UMA STRUCT É ACESSADA ATRAVÉS DA "->"

        printf("Deseja continuar? <1> SIM <0> NAO: ");
        scanf("%d", &resp);

        if(resp == 1){
            proximo_ponto->proximo = (t_ponto *) malloc (sizeof(t_ponto)); //AQUI ESTAMOS ALOCANDO A MEMÓRIA PARA O PRÓXIMO ELEMENTO
            proximo_ponto = proximo_ponto->proximo;
        } else
            break;

    }

    printf("\n");

    proximo_ponto->proximo = NULL; //DIZENDO QUE A LISTA CHEGOU AO FIM, CASO O USUÁRIO NÃO QUEIRA MAIS INSERIR NÚMEROS
    proximo_ponto = ini_ponto; //APONTANDO PARA O INÍCIO DA LISTA PARA COMEÇAR A LISTÁ-LA.

    while(proximo_ponto != NULL){
        printf("Os valores da lista original sao: %d;\n", proximo_ponto->num);
        proximo_ponto = proximo_ponto->proximo;
    }

    return 0;
}
</code>
Comment: Mas é para inserir logo em duas listas diferentes ou tem que inserir tudo numa lista para depois dividir em duas ?
Answer: Crie duas listas. Uma para números pares e uma para números ímpares.
Depois percorra a sua lista com o for e testa dentro dela se um número é par ou ímpar.
Você pode fazer isso dividindo o número por 2 e pegando o resto da divisão. Se o resto da divisão for igual a 1, significa que o número é ímpar.
Exemplo:
<code>for(int i = 0; i < tamanhoDaLista; i++){

   // Pego o resto da divisão por 2
   int restoDivisao = lista[i] % 2;

   if(restoDivisao == 1){ //Se for igual a 1 significa que é um número ímpar

      // Código para adicionar o número na lista de valores ímpares

   } else {

      // Código para adicionar o número na lista de valores pares

   }

}
</code>
Comment: Nesse código que você colocou, você está trabalhando com vetores. No código que estou tentando fazer estou trabalhando com listas dinâmicas.
Comment: A ideia é a mesma, você só precisa adaptar o seu código para a ideia. Percorra a lista dinâmica, acesse o valor dela, divida por 2 e pegue o resto da divisão para testar no if. Não tenho como criar o código completo p você, pois não sei como você estruturou suas classes e como pode acessar e percorrer a lista.
Comment: Esse é o caso. Não estou conseguindo abstrair. Estou trabalhando com ponteiros e não sei como faço para percorrer uma lista dinâmica.
Comment: Eu não manjo muito de C. Mas pelo que vi no seu código, você percorre a lista nesse trecho:

  while(proximo_ponto != NULL){
        printf("Os valores da lista original sao: %d;\n", proximo_ponto->num);
        proximo_ponto = proximo_ponto->proximo;
    }
Comment: A ideia é essa, percorra a lista e ao invés de exibir os valores, divida eles por 2 e pegue o resto da divisão para testar no if.
Comment: em uma lista dinamica. os elementos tem um ponteiro para o endereço do próximo valor, é só fazer isso para percorrer toda sua lista, até chegar no ultimo elemento que não irá ter o ponteiro, será nulo no caso, ai para cada elemento é só jogar no if e separar em outras duas listas..

Fazer Lista Par e Impar


Copying snapshot to another machine

Question: I currently have exported an OVA of certain systems so I have a complete backup. After certain changes were made ( additional users added to LDAP for example), I created a snapshot. Would I be able to copy this snapshot to the location where my OVA is? So that I may import an OVA, and then revert to the snapshot? I am having a hard time finding a straight forward answer online or via VMwares website. Could I take the OVA, and whatever the latest snapshot of, copy to separate storage location, and then import the OVA/revert to snapshot?
I am on an entire Linux backbone and will be migrating copies/backups via command-line (bash). Not sure if that helps but gives an idea of my environment.
Thank you.
Answer: No, you cannot "copy" a snapshot.
Creating a snapshot on a VM simply adds another "virtual disk" file. The hypervisor stops writing to the original "disk" file and from the creation of the snapshot on, it writes to the new "disk" file.
Reverting to a snapshot just deletes the added "disk" file.
In your case, you have to do a new OVA export.
A snapshot cannot be used as a sort of "incremental" backup.

Copying snapshot to another machine


Cannot read property 'length' of undefined - Variáveis declaradas erradamente?

Question: No momento em que executo a função javascript abaixo, é-me dado o erro:

Cannot read property 'length' of undefined.

Podem dizer-me o que está errado? Estou a declarar mal as variáveis?
function validate()
{

var i = 0, j = 0, counter = 0, counter1 = 0, areas, disponibilidade;

areas = document.forms[0].elements['areas[]'];

disponibilidade = document.forms[0].elements['disponibilidade[]'];

for (; i < areas.length; i++) {
    if (areas[i].checked) {
      counter++;
  }
}

for (; j < disponibilidade.length; j++) {
    if (disponibilidade[j].checked) {
      counter1++;
  }
}

if (counter==0){
alert("Selecione pelo menos uma área!")
return false;
}

if (counter1==0){
alert("Selecione pelo menos uma disponibilidade!")
return false;
}

return true;
}

CÓDIGO COMPLETO:

function myFunction() {
  // Get the checkbox
  var checkBox = document.getElementById("sexta");
  // Get the output text
  var formulario = document.getElementById("formulario");

  // If the checkbox is checked, display the output text
  if (checkBox.checked == true) {
    formulario.style.display = "block";
  } else {
    formulario.style.display = "none";
    $('#formulario input').val("");
  }
}

function myFunctionSabado() {
  // Get the checkbox
  var checkBox2 = document.getElementById("sabado");
  // Get the output text
  var formularioSabado = document.getElementById("formularioSabado");

  // If the checkbox is checked, display the output text
  if (checkBox2.checked == true) {
    formularioSabado.style.display = "block";
  } else {
    formularioSabado.style.display = "none";
    $('#formularioSabado input').val("");
  }
}

function myFunctionDomingo() {
  // Get the checkbox
  var checkBox3 = document.getElementById("domingo");
  // Get the output text
  var formularioDomingo = document.getElementById("formularioDomingo");

  // If the checkbox is checked, display the output text
  if (checkBox3.checked == true) {
    formularioDomingo.style.display = "block";
  } else {
    formularioDomingo.style.display = "none";
    $('#formularioDomingo input').val("");
  }
}

var cont = 1;
//https://api.jquery.com/click/
$('#add-campo').click(function() {
  cont++;
  //https://api.jquery.com/append/
  $('#formulario').append('
  das<input type="time" id="sexta1' + cont + '" name="sexta1[]" oninput="Concatena2()">as<input type="time" id="sexta2' + cont + '" name="sexta2[]" oninput="Concatena2()"><input type="hidden" id="nomeSacado' + cont + '" name="nomeSacado[]"> <button type="button" id="' + cont + '" class="btn-apagar"> - </button>
');
});

$('form').on('click', '.btn-apagar', function() {
  var button_id = $(this).attr("id");
  $('#campo' + button_id + '').remove();
});

var cont2 = 1;
//https://api.jquery.com/click/
$('#add-campo2').click(function() {
  cont2++;
  //https://api.jquery.com/append/
  $('#formularioSabado').append('
  das<input type="time" id="sabado1' + cont2 + '" name="sabado1[]" oninput="Concatena5()">as<input type="time" id="sabado2' + cont2 + '" name="sabado2[]" oninput="Concatena5()"><input type="hidden" id="nomeSacadoSabado' + cont2 + '" name="nomeSacadoSabado[]"> <button type="button" id="' + cont2 + '" class="btn-apagar2"> - </button>
');
});

$('form').on('click', '.btn-apagar2', function() {
  var button_id = $(this).attr("id");
  $('#campo1' + button_id + '').remove();
});

var cont3 = 1;
//https://api.jquery.com/click/
$('#add-campo3').click(function() {
  cont3++;
  //https://api.jquery.com/append/
  $('#formularioDomingo').append('
  das<input type="time" id="domingo1' + cont3 + '" name="domingo1[]" oninput="Concatena7()">as<input type="time" id="domingo2' + cont3 + '" name="domingo2[]" oninput="Concatena7()"><input type="hidden" id="nomeSacadoDomingo' + cont3 + '" name="nomeSacadoDomingo[]"> <button type="button" id="' + cont3 + '" class="btn-apagar3"> - </button>
');
});

$('form').on('click', '.btn-apagar3', function() {
  var button_id = $(this).attr("id");
  $('#campo11' + button_id + '').remove();
});

function Concatena() {
  //atribui a variável nome o valor do input cujo id = nome
  var sexta1 = document.getElementById('sexta1').value;
  //atribui a variável numProcesso o valor do input cujo id = numProcesso
  var sexta2 = document.getElementById('sexta2').value;
  //concatena as duas variaveis separadas por espaço e joga no value do input cujo id = nomeSacado
  document.getElementById('nomeSacado').value = "das " + sexta1 + " as " + sexta2;

}
Concatena();

function Concatena2() {
  //atribui a variável nome o valor do input cujo id = nome
  var sexta1 = document.getElementById('sexta1' + cont).value;
  //atribui a variável numProcesso o valor do input cujo id = numProcesso
  var sexta2 = document.getElementById('sexta2' + cont).value;
  //concatena as duas variaveis separadas por espaço e joga no value do input cujo id = nomeSacado
  document.getElementById('nomeSacado' + cont).value = "das " + sexta1 + " as " + sexta2;

}
Concatena2();

function Concatena4() {
  //atribui a variável nome o valor do input cujo id = nome
  var sabado1 = document.getElementById('sabado1').value;
  //atribui a variável numProcesso o valor do input cujo id = numProcesso
  var sabado2 = document.getElementById('sabado2').value;
  //concatena as duas variaveis separadas por espaço e joga no value do input cujo id = nomeSacado
  document.getElementById('nomeSacadoSabado').value = "das " + sabado1 + " as " + sabado2;

}
Concatena4();

function Concatena5() {
  //atribui a variável nome o valor do input cujo id = nome
  var sabado1 = document.getElementById('sabado1' + cont2).value;
  //atribui a variável numProcesso o valor do input cujo id = numProcesso
  var sabado2 = document.getElementById('sabado2' + cont2).value;
  //concatena as duas variaveis separadas por espaço e joga no value do input cujo id = nomeSacado
  document.getElementById('nomeSacadoSabado' + cont2).value = "das " + sabado1 + " as " + sabado2;

}
Concatena5();

function Concatena6() {
  //atribui a variável nome o valor do input cujo id = nome
  var domingo1 = document.getElementById('domingo1').value;
  //atribui a variável numProcesso o valor do input cujo id = numProcesso
  var domingo2 = document.getElementById('domingo2').value;
  //concatena as duas variaveis separadas por espaço e joga no value do input cujo id = nomeSacado
  document.getElementById('nomeSacadoDomingo').value = "das " + domingo1 + " as " + domingo2;

}
Concatena6();

function Concatena7() {
  //atribui a variável nome o valor do input cujo id = nome
  var domingo1 = document.getElementById('domingo1' + cont3).value;
  //atribui a variável numProcesso o valor do input cujo id = numProcesso
  var domingo2 = document.getElementById('domingo2' + cont3).value;
  //concatena as duas variaveis separadas por espaço e joga no value do input cujo id = nomeSacado
  document.getElementById('nomeSacadoDomingo' + cont3).value = "das " + domingo1 + " as " + domingo2;

}
Concatena7();

function validate() {
  var i = 0,
    j = 0,
    counter = 0,
    counter1 = 0,
    areas, disponibilidade;
  areas = document.forms[0].elements['areas[]'];
  disponibilidade = document.forms[0].elements['disponibilidade[]'];

  for (; i < areas.length; i++) {
    if (areas[i].checked) {
      counter++;
    }
  }

  for (; j < disponibilidade.length; j++) {
    if (disponibilidade[j].checked) {
      counter1++;
    }
  }

  if (counter == 0) {
    alert("Selecione pelo menos uma área!")
    return false;
  }

  if (counter1 == 0) {
    alert("Selecione pelo menos uma disponibilidade!")
    return false;
  }

  return true;
}

<form method="POST" action="roda.php" onsubmit="return validate()">

      Nome:
      <input type="text" name="nome" placeholder="Nome" required>

      Apelido:
      <input type="text" name="apelido" placeholder="Apelido" required>

      Sexo:
      <select name="sexo">
        <option value="masculino" required>Masculino</option>
        <option value="feminino" required>Feminino</option>
      </select>

      Idade:
      <input type="number" name="idade" min="12" required>

      Morada:
      <input type="text" name="morada" placeholder="Morada" required>

      Contacto:
      <input type="tel" name="contacto" required>

      E-mail:
      <input type="email" name="email" placeholder="E-mail" required>

      Habilitações literárias:
      <input type="text" name="habilitacoes" placeholder="Habilitações Literárias" required>

      Possui algum tipo de restrição alimentar? (deixar em branco se não se aplicar)
      <input type="text" name="restricoes_alimentares" placeholder="Restrições alimentares">

      Áreas de Interesse:

      <input id="interesse1" type="checkbox" name="areas[]" value="bilheteira">Bilheteira

      <input id="interesse2" type="checkbox" name="areas[]" value="guarda-roupa">Guarda-Roupa

      <input id="interesse3" type="checkbox" name="areas[]" value="venda de artesanato">Venda de artesanato

      <input id="interesse4" type="checkbox" name="areas[]" value="restauracao">Restauração

      <input id="interesse5" type="checkbox" name="areas[]" value="figuracao">Figuração

      <input id="interesse6" type="checkbox" name="areas[]" value="legiao">Legião

    Disponibilidade:

        <input type="checkbox" id="sexta" name="disponibilidade[]" value="sexta-feira" onclick="myFunction()">sexta-feira

        das
        <input type="time" id="sexta1" name="sexta1[]" oninput="Concatena()">
        as
        <input type="time" id="sexta2" name="sexta2[]" oninput="Concatena()">
        <input type="hidden" id="nomeSacado" name="nomeSacado[]">
        <button type="button" id="add-campo"> + </button>

        <input type="checkbox" id="sabado" name="disponibilidade[]" value="sabado" onclick="myFunctionSabado()">sábado

        das
        <input type="time" id="sabado1" name="sabado1[]" oninput="Concatena4()">
        as
        <input type="time" id="sabado2" name="sabado2[]" oninput="Concatena4()">
        <input type="hidden" id="nomeSacadoSabado" name="nomeSacadoSabado[]">
        <button type="button" id="add-campo2"> + </button>

        <input type="checkbox" id="domingo" name="disponibilidade[]" value="domingo" onclick="myFunctionDomingo()">domingo

        das
        <input type="time" id="domingo1" name="domingo1[]" oninput="Concatena6()">
        as
        <input type="time" id="domingo2" name="domingo2[]" oninput="Concatena6()">
        <input type="hidden" id="nomeSacadoDomingo" name="nomeSacadoDomingo[]">
        <button type="button" id="add-campo3"> + </button>

      Possui transporte próprio?

      <input type="radio" name="transporte" value="sim" required> Sim
      <input type="radio" name="transporte" value="nao" required> Não

      Já foi voluntário de alguma edição anterior do Festival e/ou em alguma atividade promovida pela associação?

      <input type="radio" name="voluntarioAPPACDM" value="sim" required> Sim
      <input type="radio" name="voluntarioAPPACDM" value="nao" required> Não

      Autoriza o uso da sua imagem em conteúdos multimédia (fotografia e vídeo), como forma de publicitação no presente website e nas demais redes sociais do Festival?

      <input type="radio" name="autorizaImagem" value="sim" required> Sim
      <input type="radio" name="autorizaImagem" value="nao" required> Não

    <input type="submit" value="Enviar">

</form>

Comment: `document.forms[0].elements['areas[]']` ou `document.forms[0].elements['disponibilidade[]']` é `undefined`, verifique os nomes no JS e no HTML
Comment: @GuilhermeCostamilam , editei e postei o código completo. Se você executar, vai ver que funciona, porém, quando eu colo o código na minha página Wordpress, ele me dá o erro que eu disse
Comment: tente mudar as variáveis dessa forma `areas = document.querySelectorAll('input[name="areas[]"]')` e `disponibilidade = document.querySelectorAll('input[name="disponibilidade[]"]');`
Comment: Tome cuidado com o momento em que chamas o método! Nesse caso você pode estar sofrendo com o assincronismo entre ter carregado a view (html) completamente ou não.
Rodando localmente, por exemplo, pode ser que já tenha sido carregado, no Wordpress ainda não. Verifique se variável está preenchida, antes de chamar o método .lenght
Comment: Não encontro o erro que referes no código. Testaste correr o código que tens aqui na pergunta?
Comment: @MáttheusSpoo , DEU CERTO!!! OBRIGADO!!!
Comment: @Sergio , como disse não havia nenhum erro quando tentava correr o código normalmente. O problema aconteceu quando o implementei no Wordpress, porque essa função era saltada. Ao substituir as variáveis por `areas = document.querySelectorAll('input[name="areas[]"]');` e `disponibilidade = document.querySelectorAll('input[name="disponibilidade[]"]');` consegui resolver o problema.
Answer: Ao substituir as variáveis por areas = document.querySelectorAll('input[name="areas[]"]'); e disponibilidade = document.querySelectorAll('input[name="disponibilidade[]"]'); consegui resolver o problema.


SSIS Derived Column condition to replace null values based on a specific date

Question: I am working on a SSIS Package that will populate a SharePoint 2013 list with data from other SP lists.
I have created a Derived Column in the package, which is intended to replace null based on dates that are greater than or equal to a specific date in the data list. However, I am having trouble with the expression. Below is a condition and expression example that I am have trouble with.
REPLACENULL(ColumnName,"mm/dd/yyyy" > = GETDATE())

Any assistance to point out what I am doing wrong is appreciated.
Comment: You are comparing a string to a date. Replace your mm/dd/yyyy to a DATETIME.ParseExact("YOUR DATE", "YOUR FORMAT)
Comment: I was not able to get your suggestion to work properly, so I revised the package, which created a new problem that I will post as a new question.
Answer: Use this expression:
((DT_DATE)"9-1-2016") >=  (DT_DATE)ColumnName ? NULL((DT_WSTR, 50)) : ColumnName

Notice: REPLACENULL is not useful for you here. What REPLACENULL does is that it:

Returns the value of second expression parameter if the value of first expression parameter is NULL". (See here)

You don't want to replace NULL, you want NULL!
Comment: Understood. Thank you for pointing me in the right direction.
Comment: @DavidF You are welcome. If it answers your question, please mark it as the answer.
Comment: I apologize for the delayed response to your suggestion. I just had the opportunity to get back on the project and try it. Unfortunately what you suggested does not work.

I have tried a variation of what you suggested, but it doesn't work either. Below is my variation.
ISNULL([ColumnName]) >= (DT_WSTR)"9/1/2016"

Do you have any additional suggestions that I can try?
Comment: OK, you sad: "is intended to replace null based on dates that are greater than or equal to a specific DATE". I have 3 questions: 1. What is this specific DATE?  2. What is the your desired datatype of the derived column? 3. What is the error you get when you try my solution?
Comment: From an earlier comment, I understood that I should not use ISNULL and not REPLACENULL..

The specific date is 9-1-2016 and the data type from the server is DT_WSTR.

Thanks
Comment: @DavidF I updated my answer. Please check it and let me know if there are issues.
Answer: Syntax for REPLACENULL is REPLACENULL(expression 1,expression 2) where
expression 1 :
The result of this expression is checked against NULL.
expression 2 :
The result of this expression is returned if the first expression evaluates to NULL.
If you're trying to REPLACE NULL values of a column based on another column's datetime condition, try something like this :
[column_1] >= GETDATE() ? REPLACENULL([column_2],"desired value") : [column_2]

Comment: Thank you for the explanation.


Database in settings.php doesn't exist yet site is live. Where is the data?

Question: I've inherited a Drupal 6 site running on an Ubuntu 10.04.4 LTS server. I'm trying to understand the configuration of it to create a local version of it work on.
I can't figure out how the data is being accessed. The settings file shows the following:
$db_url = 'mysql://root@localhost/drupal';
$db_prefix = 'dru_';

However when I list the databases, I can't find it:
mysql -u root
mysql> show databases \g
+--------------------+
| Database           |
+--------------------+
| information_schema |
| gitpull            |
| mysql              |
+--------------------+
3 rows in set (0.01 sec)

In addition running drush status says it can't find it either.
$ drush status
SQLSTATE[42000] [1049] Unknown database 'drupal'                   [warning]

The site is up and running so it's got to have access to the database somehow.
I figure I'm in the right directory because it's defined in /etc/apache2/sites-available and /etc/apache2/sites-enabled/
Any help would be greatly appreciated.
Comment: Don't think this can be answered without actually looking into the code base of the site. But the first thing I would check if its a multisite, or is the settings.php includes another file with the db information.
Comment: `The site is up and running so it's got to have access to the database somehow.` maybe try using [Backup and Migrate](https://www.drupal.org/node/189065/release?api_version%5B%5D=87)
Comment: Have you checked the profile folder?
Comment: First step towards exploring is checking in settings.php file. Check there if any database is connected or not.
Comment: @TonyMao good call there was a profile folder. @Alexei another good call, it is indeed multisite. Turns out there were a bunch of backups in non-intuitively named folders so I was looking in the wrong place. What worked was running `sudo find . -name settings.php` and then checking out each of the results until I found the right one.
Answer: The hints from Tony Mao & Alexei pointed me in the right direction. It turned out there were a bunch of backups in non-intuitively named folders, so I was looking in the wrong place.
I ended up finding the right settings.php file with sudo find . -name settings.php.


How do while(!kbhit()) COBOL Equivalent?

Question: I want to detect a key press event in COBOL, using isCOBOL compiler. How to do that?
EX in C:
if(time==despert_time){
    while(!kbhit()){
        Beep(500,500);
    }
}
Comment: Presumably you have a manual?
Comment: Because COBOL was originally designed without much means to interact with humans, compiler vendors have augmented, with their own extensions, the simple DISPLAY and ACCEPT that are available. You need to find out *if* and *how* isCOBOL allows you to do that. The `do` is a simple in-line `PERFORM`.
Comment: GUI or not GUI?  From console you might be able to get away with calling into Java System.in.Available() (if the terminal is not buffering on lines).  If there are graphics involved, write up a tiny class to add an ActionListener and a handler for keyPressed, keyReleased, or keyTyped (depending on how you want to handle it).  In short, this will likely be easier from Java than COBOL.  If you really need to do this from COBOL, look to `CALL "SYSTEM" using "stty raw"`,  then `"stty cooked"` after you've accepted a keypress (on GNU/Linux).  Windows console will have a different sequence.
Answer: It looks like you want to get a user interaction from console.
If it isn't happening within a time frame: beep
PERFORM FOREVER *> or UNTIL EXIT or UNTIL 0 = 1, depending on the available extensions
   ACCEPT OMITTED *> or ACCEPT DUMMY [which you'd define as 77 DUMMY PIC X.], depending on the available extensions
      BEFORE TIME 500 *> [or WITH TIMEOUT 500] this is a more or less common extension, with most vendors using a different time scale --> may need to change the 500
   END-ACCEPT
   IF keypressed NOT = timeout *> the actual var to be checked and the timeout value need to be checked in the docs
      EXIT PERFORM
   END-IF
   CALL x'E5'
      ON EXCEPTION *> the system call x'E5' for beep may not be available
         DISPLAY SPACE AT 2080 WITH BEEP *> may not be available, too...
   END-CALL
END-PERFORM

Check the online documentation that ships with your compiler (it is "available for clients only", therefore we can not check).
Comment: Done, sorry for the late answer haha


How to show that $\int_p^x dT \int_{p}^T dt \ f(t) = \int_{p}^x dt\ (x - t) f(t)$

Question: Suppose $f(t)$ is continuous on the interval $[p,q]$ and that $p \leq x \leq q$. Formula (4.631) of Gradshteyn and Ryzhik then states that
$$
\int_p^x dT \int_{p}^T dt \ f(t) = \int_{p}^x dt\ (x - t) f(t) \ .
$$
How does one prove this result?
Comment: Use Fubini's theorem after converting to an integral over $[p,x]^2$.
Comment: What is the coordinate change required to map to $[p,x]^2$? As I understand it the above region is a triangle.
Comment: A graph makes it clear, but I'll give you a trick in an answer.
Answer: (Gradshteyn/Rhyzik 4.631)
$$ \int_p^x dt_{n-1} \int_p^{t_{n-1}} dt_{n-2}\   \dots \dots \int_p^{t_1} \ f(t)\ dt  = \frac{1}{(n-1)!} \ \int_p^x\ (t-x)^{n-1} \ f(t)\ dt
$$
Using the indicator function $\mathbf{1}_{t \leqslant T}(t,T) = \begin{cases}1, & t \leqslant T\\0, &t > T \end{cases}$ and Fubini's theorem,
$$\int_p^x\ \left(\int_p^Tf(t)\, dt \right)\  dT = \int_p^x \ \left(\int_p^x\ f(t) \ \mathbf{1}_{t \leqslant T}\  dt \right)\ dT=$$
$$\int_p^x \ \left(\int_p^xf(t)\ \mathbf{1}_{t \leqslant T}\ dT\  \right)\ dt = \int_p^x\left(\int_t^xf(t)\, dT
\right)\  dt  = \int_p^x \ (x-t) \ f(t) \ dt$$


Help with proof that $\sum_{n \in \Bbb{N}} \frac{1}{an + b}$ also diverges?

Question: We know that $\sum_{n \in \Bbb{N}} \frac{1}{n}$ diverges.  So it seems likely that $\sum_{n \in \Bbb{N}} \frac{1}{a n  + b}$ will for any real $a, b$.  I'm having trouble proving it just for the $\frac{1}{n + c}$ form special case.  Any hints?
Comment: Limit comparison test.
Comment: For $c = \frac ba \in \Bbb{N}$ at least, $\sum_{n\ge1}\frac{1}{a(n + c)} = \frac1a\sum_{n\ge c+1}\frac1n = \frac1a\left(\sum_{n\ge1}\frac1n - H_{c}\right)\to \infty$. A similar argument can be applied for all $a,\ b$.
Answer: Let $a,b \in \mathbb{R}$ and let $a \neq 0$. Since
$$
\frac{1}{an+b} \sim \frac{1}{an}
$$
as $n$ grows,
that is to say,
$$
\frac{n}{an+b} \to \frac{1}{a}
$$
as $n$ grows,
so by the limit comparison test the series $\sum 1/(an+b)$ diverges.
Answer: Hint(s):
$$\sum_{n \in \mathbb N} \frac{1}{n+c}=\sum_{n \in \mathbb N} \frac{1}{n}- \sum_{k=1}^c \frac {1}{k}$$
And $\frac{1}{an+b}$ can be rewritten as $\frac{1}{a} \cdot \frac{1}{n+\frac{b}{a}}$.
Now let $\frac{b}{a}:=c$.
Answer: First, since
$\sum_{n=1}^M \frac1{n}
\to \infty
$
as $M \to \infty
$,
then,
for any $m > 0$,
$\sum_{n=m}^M \frac1{n}
\to \infty
$
as $M \to \infty
$.
Do you see why?
Now,
let's look at the partial sums
of the problem's series.
$\sum_{n=1}^M \frac1{an+b}
=a\sum_{n=1}^M \frac1{n+b/a}
$.
Let $k$ be an integer
such that $k \ge b/a$.
Then
$\frac1{n+b/a}
\ge \frac1{n+k}
$,
so
$\sum_{n=1}^M \frac1{n+b/a}
\ge \sum_{n=1}^M \frac1{n+k}
= \sum_{n=k+1}^{M+k} \frac1{n}
$.
By the comment above,
$\sum_{n=k+1}^{M+k} \frac1{n}
\to \infty
$
as
$M \to \infty
$.
Therefore
$\sum_{n=1}^M \frac1{an+b}
\to \infty
$
as $M \to \infty
$.
Answer: It very simple to proof that if $(*)\frac{|u_n|}{|v_n|}\to L\neq 0,\infty$ so
$$\sum_n |u_n|<\infty \qquad \iff\qquad \sum_n |v_n|<\infty$$
in fact $(*)$ implies that : for all $L>\epsilon>0$ it exist $N_0\in\mathbb{N}$ such that $\forall n\geq N_0$  $\left| \frac{|u_n|}{|v_n|}- L\right|<\epsilon$ and this implies that for  $N_0\in\mathbb{N}$
$$
(L-\epsilon)|v_n|<|u_n|<(L+\epsilon)|v_n|
$$
So
$$
(L-\epsilon)\sum_{n\geq N_0}|v_n|\leq \sum_{n\geq  N_0} |u_n|\leq (L+\epsilon)\sum_{n\geq N_0}|v_n|
$$
and this proof our result.
Now we applies this result to your case :
where $v_n=n$ and $u_n=an+b$.
So $\frac{|u_n|}{|v_n|}\to a$
if $a>0$ so $\exists N \in \mathbb{N}$ such that $v_n\geq0$ for all $n\geq N$ and then $\sum_n v_n =\infty$.
If $a<0$ so $\exists N' \in \mathbb{N}$ such that $-v_n\geq0$ for all $n\geq N'$ and then $-\sum_n v_n =\infty$.
In booth cases $\sum_n\frac{1}{an+b}$ diverge for all $a,b\in\mathbb{R}$
Answer: Here's a quick one. $an + b \leq an + bn = (a + b) n$, so
\begin{align*}
\sum_{n = 1}^{\infty} \frac{1}{an + b} & \geq \sum_{n = 1}^{\infty} \frac{1}{an + bn} \\
& = \frac{1}{a + b} \sum_{n = 1}^{\infty} \frac{1}{n} \\
& = \frac{+ \infty}{a + b} \\
& = + \infty .
\end{align*}


Could not get unknown property 'apkNames' in android gradle plugin 4.1.0

Question: I am using this code in build.gradle:
android {
    applicationVariants.all { variant ->
        variant.packageApplicationProvider.configure { packageApplicationTask ->
            doLast {
                packageApplicationTask.apkNames.each { apkName ->
                    def apkDir = "./build/outputs/apk/${flavorName}/${buildType.name}"
                    def apkDestName = apkName.replace("app-", "stickerly-android-" + variant.versionName + "-").replace(".apk", "-" + getDate() + ".apk")

                    println "#####Rename ${variant.name} Apk File"
                    copy {
                        from("$apkDir/$apkName").into(apkDir).rename { String fileName -> apkDestName }
                    }

                    println "#####Copy mapping File"
                    def mappingDir = "./build/outputs/mapping/${flavorName}${buildType.name.capitalize()}"
                    copy {
                        from("$mappingDir/mapping.txt").into(mappingDir).rename {
                            "mapping-stickerly-${variant.versionName}.txt"
                        }
                    }
                }
            }
        }
    }
}

With this code I rename apk file and copy mapping file. I worked in android gradle plugin 4.0, but it does not work in 4.1 with this message

Where:
Script '/Users/snow/workspace/stickerly-android/app/build-android-extra.gradle' line: 5
What went wrong:
Execution failed for task ':app:packageExternalArm8Debug'.
Could not get unknown property 'apkNames' for task ':app:packageExternalArm8Debug' of type com.android.build.gradle.tasks.PackageApplication.

I think API has changed but I can not find any documents. Someone can help me?
Thanks.
Answer: property apkNames is removed in AGP 4.1
you can try this

gradle.taskGraph.afterTask { Task task, TaskState state ->
    if (!state.failure
            && task.project.name == project.name
            && task.name.startsWith("package")
            && !task.name.endsWith("UnitTest")) {
        def outputDir = task.outputDirectory.getAsFile().get()
        task.variantOutputs.getOrNull()?.each { variant ->
            println "" + outputDir + "/" + variant.outputFileName.get()
        }
    }
}

add this at the end of your build.gradle file.
change println to whatever logic you want.
by the way, if you want to check the properties you may use, just add gradle plugin as a dependency of your project, click Sync in Android Stuido, then you can find it in External Librarys (key map: Command + 1, and switch to project view).
like this
dependencies {
    implementation 'com.android.tools.build:gradle:4.1.0'
}

and these properties and tasks are intentionally invisible in lib com.android.tools.build:gradle-api, modifications in future releases are expected.