Jenkins fails to build Java project if local jar file included in pom.xml

Question: This time we use Jenkins to help us to build Java, it used to work well, but if we add a local jar file, it failed.
...
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:2.6:resources (default-resources) on project ruoyi-admin: /BOOT-INF/lib/cesiumlanguagewriter-2.20.1.jar (No such file or directory) -> [Help 1]
[ERROR]
[JENKINS] Archiving /var/lib/jenkins/workspace/qrd_back/ruoyi-system/pom.xml to com.ruoyi/ruoyi-system/3.8.5/ruoyi-system-3.8.5.pom
[JENKINS] Archiving /var/lib/jenkins/workspace/qrd_back/ruoyi-system/target/ruoyi-system-3.8.5.jar to com.ruoyi/ruoyi-system/3.8.5/ruoyi-system-3.8.5.jar
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException
[ERROR]
[ERROR] After correcting the problems, you can resume the build with the command
[ERROR]   mvn <goals> -rf :ruoyi-admin
...

this jar file cesiumlanguagewriter-2.20.1.jar is our local jar file, we include it in ruoyi-admin\pom.xml file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>ruoyi</artifactId>
        <groupId>com.ruoyi</groupId>
        <version>3.8.5</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <packaging>jar</packaging>
    <artifactId>ruoyi-admin</artifactId>

    <dependencies>

        ......
        <dependency>
            <groupId>cesiumlanguagewriter</groupId>
            <artifactId>cesiumlanguagewriter</artifactId>
            <version>2.20.1</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/lib/cesiumlanguagewriter-2.20.1.jar</systemPath>
        </dependency>
    </dependencies>

    <build>
        <resources>
            <resource>
                <directory>lib</directory>
                <targetPath>/BOOT-INF/lib/</targetPath>
                <includes>
                    <include>**/*.jar</include>
                </includes>
            </resource>
        </resources>
        <plugins>
            <plugin>
                ...
            </plugin>
            <plugin>
                ...
           </plugin>
        </plugins>
        <finalName>${project.artifactId}</finalName>
    </build>

</project>

it looks fine, and exactly, it can build with command mvn clean package in our local Windows environment, and in our local Ubuntu environment, but not enable to build in Jenkins, what are the difference between the Ubuntu environment and Jenkins?
Ubuntu and Jenkins use the same Maven, the difference between them may be the settings.xml, but because I am newbie in Java, so I can not find the difference between them
the mavn version on the Ubuntu(it can build success):
jenkins@sakuramoyu:~/workspace/ruoyi_qrd$ mvn --version
Apache Maven 3.6.3
Maven home: /usr/share/maven
Java version: 11.0.19, vendor: Ubuntu, runtime: /usr/lib/jvm/java-11-openjdk-amd64
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "5.15.0-71-generic", arch: "amd64", family: "unix"

Edit
The command Jenkins use is mvn -B -f /var/lib/jenkins/workspace/qrd_back/pom.xml clean package, I think it will cause the problem, what are the difference between mvn clean package
Edit2
If I run build with mvn -B -f /var/lib/jenkins/workspace/qrd_back/pom.xml clean package -X, it tells me
...
[DEBUG] ignoreDelta true
[INFO] Copying 1 resource to /BOOT-INF/lib/
[DEBUG] file cesiumlanguagewriter-2.20.1.jar has a filtered file extension
[DEBUG] copy /var/lib/jenkins/workspace/qrd_back/ruoyi-admin/lib/cesiumlanguagewriter-2.20.1.jar to /BOOT-INF/lib/cesiumlanguagewriter-2.20.1.jar
[INFO] ------------------------------------------------------------------------
[INFO] Reactor Summary for ruoyi 3.8.5:
[INFO]
[INFO] ruoyi .............................................. SUCCESS [  0.186 s]
[INFO] ruoyi-common ....................................... SUCCESS [  8.158 s]
[INFO] ruoyi-system ....................................... SUCCESS [  2.043 s]
[INFO] ruoyi-framework .................................... SUCCESS [  1.785 s]
[INFO] ruoyi-quartz ....................................... SUCCESS [  1.148 s]
[INFO] ruoyi-generator .................................... SUCCESS [  1.174 s]
[INFO] ruoyi-admin ........................................ FAILURE [  0.701 s]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  15.679 s
[INFO] Finished at: 2023-05-23T09:40:23+08:00
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:2.6:resources (default-resources) on project ruoyi-admin: /BOOT-INF/lib/cesiumlanguagewriter-2.20.1.jar (No such file or directory)
-> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:2.6:resources (default-resources) on project ruoyi-admin: /BOOT-INF/lib/cesiumlangua
gewriter-2.20.1.jar (No such file or directory)
...

it means the local jar file is filtered? so it can not find it?
Comment: Do not use images for textual information like logs and configurations in Stackoverlow.
Comment: Start using a repository manager / Proxy and deploy your own artifacts there...
Comment: First using this: `org.apache.maven.plugins:maven-resources-plugin:2.6:resources (default-resources) on project ruoyi-admin: /BOOT-INF/lib/cesiumlanguagewriter-2.20.1.jar`. on a spring boot project looks completely wrong... I don't know what you are trying to do here? Packaging of the jar in spring boot the spring-boot-maven-plugin is intended to handle that apart from that you use using an very old version of Maven. Furthermore using `-f ` option in Jenkins build looks a bit strange to be honest... why do you need that? The project can be built from root location...via configuration...
Comment: @khmarbaise first question, cause `cesiumlanguagewriter-2.20.1.jar` is a local jar we build, we can not find it on the public maven repo. The second quesition, the Jenkins use of `-f` was not defined by us, it's the default by Jenkins. I think your opinion is right, it may cause by the folder Jenkins choose to run maven was wrong, so it can't find the external jar file.
Answer: You are not building that jar. You are telling Maven that it is to be found at a given directory relative to the project directory. It seems that in the Jenkins build that directory is set to a path where that jar is not there:
/BOOT-INF/lib/cesiumlangua
gewriter-2.20.1.jar (No such file or directory)

You didn't share enough information to find more but if you are using a Maven plugin to copy the jar file it maybe filtering a jar file because it is not supposed to do that.
Comment: You should publish it to a Maven repository, the local one or a remote one. Don't treat a library as a resource.
Comment: that `cesiumlanguagewriter-2.20.1.jar` jar is built before maven start building, I try to install it in the maven local path
Answer: after a long time struggle, I found a solution: Edit ruoyi-admin\pom.xml,
remove all the resource part in <build>

<resources>
  <resource>
     <directory>lib</directory>
     <targetPath>/BOOT-INF/lib/</targetPath>
     <includes>
        <include>**/*.jar</include>
     </includes>
  </resource>
</resources>

add one line here:
<plugin>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-maven-plugin</artifactId>
  <version>2.1.1.RELEASE</version>
  <configuration>
    <includeSystemScope>true</includeSystemScope>
    <fork>true</fork>
  </configuration>
  <executions>
    <execution>
      <goals>
        <goal>repackage</goal>
      </goals>
    </execution>
  </executions>
</plugin>

sorry I just a newbie in Java and Maven, so why it can happen, I don't know
EDIT:
it may cause by the folder run maven bu Jenkins, I think if I change <targetPath>/BOOT-INF/lib/</targetPath> to <targetPath>BOOT-INF/lib/</targetPath>, it will work.


file change auditing (especially for web.configs)

Question: We occasionally have configurations in web.config(s) being changed by the IT team on live production servers.  I would like to create an audit trail, e.g., "On October 11 the property "foo" in file "bar" was changed to "banana".
My first thought was to create a PowerShell script that would run every hour, and if one of the .config files changed, save it off in a time stamped folder.  My second thought was that this must be a problem that has already been solved.
Ideally, config file changes would not be allowed and any change would require a new deployment, but it's unlikely I could push that through.
I say "web.config" but I have a few different xml config files: web.config, app.config, nant.configs.
I need to know exactly what in these config files changed (approximately) when and (ideally) by whom.
Is there some kind of standard way or open source tool to do file change logging?
Comment: Not answering because I don't know what the windows equivalent might be, but the `inotify` system would be equivalent to what you'd want in Linux. All you'd need to do would be hook up `inotify` handlers for file change events within a given directory hierarchy, and then have the handlers apply version control to those files (e.g. `git add `, `git commit -m `, `git push origin master`).
Comment: I'm betting you could also have a (non-agentless) config management system like Salt or Puppet alert you about unexpected file contents in config files, though that's a slightly different thing. Salt would probably be better for what you'd want b/c it's more extensible and would be better able to handle version controlling the files. However, again, I haven't tried to do that so I don't know what issues inherently exist.
Comment: Followup question, though... Would you care if the thing used polling on an interval, or an interrupt-based model? I'm guessing if you require interrupts that's a more niche question.
Comment: There are many different file auditing tools for windows, if they detect a change, you can have it run a script, that will back up the file. So every change that is made, a back-up is made. These tools hook into the windows event notification apis and wait for a callback that triggers them.
Answer: As mentioned in the comments, there are most likely third party tools that could help here. There is nothing built into Windows which allows you to do this out of the box.
If I had to do this myself I would do something like this:
Write a small tool to monitor the files to watch. This would use a FileSystemWatcher object. On NTFS drives a change to a watched file would trigger an event automatically.
The code for the event would just copy the file over to a different location which is under source control (say Git) and trigger a commit and possibly a push to a remote server.
Using this you can see what exactly changed in the file.
In addition you can enable Windows auditing on the files to see who made the changes.
I wouldn't write the tool in PowerShell, but as a Windows service that runs in the background and monitors changes in real time.


Java, JoptionPane: the yes-no dialog keeps on showing

Question: I'm trying to solve an exercise from a Java textbook, that requires to write a piece of code that opens a yes-no gialog which asks the user if he wants to draw and color a solid circle in red (yes) or not (no), in which case the color is black (by default; but for clarity I decided to include in my piece of code a specific statement anyway). I thought of (IDE: NetBeans) ...:
int centre = JOptionPane.showConfirmDialog(null, "Do you want I turn the solid center circle color from black to red?",
                    "Click Yes or No:", JOptionPane.YES_NO_OPTION);

            if (centre == JOptionPane.YES_OPTION)
            {
                canvas.setColor(Color.RED);

            }
            else if (centre == JOptionPane.NO_OPTION)
            {
                canvas.setColor(Color.BLACK);
            }

            canvas.drawOval(200, 200, 100, 100);
            canvas.fillOval(225, 225, 50, 50);

..., but the dialog keeps on opening again and again after choosing either choice. Without the dialog + else-if branching the code executes correctly, even though by drawing the solid circle only in red or black according you include the canvas.setColor(Color.RED); statement or not.
What [do I miss/don't I know] ?
Many thanks to all those who'll be able to suggest me the simplest (hey! I'm a beginner) way to write the required piece of code. And many thanks to all the others too :) .
Comment: When yes action is completed it will start no action and vice  versa. Better change this idea of canvas.
Comment: Thank you both, JB Nizet and Prasath Bala. I'll arrange to implement your suggestions. Thank you both a lot. You were very useful.
Answer: You probably have this code inside paintComponent(), which is a very, very bad idea. paintComponent() is called every time swing needs to paint the component.
This dialog box should be called in an event listener instead (i.e. when the user clicks a button, for example). It should then store the answer in some boolean field, and the paintComponent() method should read that boolean field to decide what to draw.
Comment: Thank you both, JB Nizet and Prasath Bala. I'll arrange to implement your suggestions. Thank you both a lot. You were very useful.


MySQL is SELECT with LIKE expensive?

Question: The following question is regarding the speed between selecting an exact match (example: INT) vs a "LIKE" match with a varchar.
Is there much difference? The main reason I'm asking this is because I'm trying to decide if it's a good idea to leave IDs out of my current project.
For example Instead of:
http://mysite.com/article/391239/this-is-an-entry

Change to:
http://mysite.com/article/this-is-an-entry

Do you think I'll experience any performance problems on the long run? Should I keep the ID's?
Note:
I would use LIKE to keep it easier for users to remember. For example, if they write "http://mysite.com/article/this-is-an" it would redirect to the correct.
Regarding the number of pages, lets say I'm around 79,230 and the app. is growing fast. Like lets say 1640 entries per day
Answer: An INT comparison will be faster than a string (varchar) comparison. A LIKE comparison is even slower as it involves at least one wildcard.
Whether this is significant in your application is hard to tell from what you've told us. Unless it's really intensive, ie. you're doing gazillions of these comparisons, I'd go with clarity for your users.
Another thing to think about: are users always going to type the URL? Or are they simply going to use a search engine? These days I simply search, rather than try and remember a URL. Which would make this a non-issue for me as a user. What are you users like? Can you tell from your application how they access your site?
Comment: The main problem, is that the application is actually growing faster than expected. So at one point it'll have lets say 1,000,000 entries and still grow more and more. Maybe I should keep ints?
Comment: Int is the only scalable option I'd say.
Comment: But how fast? that's the question.
Comment: Very fast... :) If you want be more accurate - it depends of machine, etc.
Answer: Firstly I think it doesn't really matter either way, yes it will be slower as a LIKE clause involves more work than a direct comparison, however the speed is negligible on normal sites.
This can be easily tested if you were to measure the time it took to execute your query, there are plenty of examples to help you in this department.
To move away slighty from your question, you have to ask yourself whether you even need to use a LIKE for this query, because 'this-is-an-entry' should be unique, right?
SELECT id, friendly_url, name, content FROM articles WHERE friendly_url = 'this-is-an-article';

Comment: I doubt very much that a user will simply type a URL from memory, most are picked up through Google or the users bookmarks.
Comment: I would use LIKE to keep it easier for users to remember. For example, if they write "http://mysite.com/article/this-is-an" it would redirect to the correct.
Comment: So what about when you have in your database: `this-is-an-article` and `this-is-an-unwanted-page` ?
Comment: hsz +1, sure he can display a list of all matching articles, but that would pose a small yet significant usability problem.
Comment: @hsz there are ways for disambiguation. @ILMV that's what I'm thinking really, not many will remember any part of the URL..
Comment: @kuroir Of course, but in the @dave's case it will just learn users bad habbits to access elements with a names that do not exist.
Comment: I would simply advise keeping your int and usin the string part of the URL for SEO.
Answer: A "SELECT * FROM x WHERE  = 391239" query is going to be faster than "SELECT * FROM x WHERE  = 'some-key'" which in turn is going to be faster than "SELECT * FROM x WHERE  LIKE '%some-key%'"  (presence of wild-cards isn't going to make a heap of difference.
How much faster?  Twice as fast? - quite likely. Ten times as fast? stretching it but possible.  The real questions here are 1) does it matter and 2) should you even be using LIKE in the first place.
1) Does it matter
I'd probably say not.  If you indeed have 391,239+ unique articles/pages - and assuming you get a comparable level of traffic, then this is probably just one of many scaling problems you are likely to encounter.  However, I'd warrant this is not the case, and therefore you shouldn't worry about a million page views until you get to 1 million and one.
2) Should you even be using LIKE
No.  If the page/article title/name is part of the URL "slug", it has to be unique.  If it's not, then you are shooting yourself in the foot in term of SEO and writing yourself a maintanence nightmare.  If the title/name is unique, then you can just use a "WHERE title = 'some-page'", and making sure the title column has a unique index on.
Edit
You plan of using LIKE for the URL's is utterly utterly crazy.  What happens if someone visits
yoursite.com/articles/the

Do you return a list of all the pages starting "the" ?  What then happens if:
Author A creates
yoursite.com/articles/stackoverflow-is-massive

2 days later Author B creates
yoursite.com/articles/stackoverflow-is-massively-flawed

Not only will A be pretty angry that his article has been hi-jacked, all the perma-links he may have been sent out will be broken, and Google is going never going to give your articles any reasonable page-rank because the content keeps changing and effectively diluting itself.
Sometimes there is a pretty good reason you've never seen your amazing new "idea/feature/invention/time-saver" anywhere else before.
Comment: Great point on the possibility of the article "hi-jacking". I encountered something similar to this on a project I worked on, and it was a nightmare to fix.
Answer: INT is much more faster.
In the string case I think you should not select query with LIKE but just with = because you look for this-is-an-entry, not for this-is-an-entry-and-something.
Answer: There are a few things to consider:
The type of search performed on the DataBase will be an "index seek", search for single row using an index, most of the time.
This type of exact match operation on a single row is not significantly faster using ints than strings, they are basically the same cost, for any practical purpose.
What you can do is the following optimization, search the database using a exact match (no wildcards), this is as fast as using an int index. If there is no match do a fuzzy search (search using wildcards) this is more expensive, but on the other hand is more rare and can produce more than one result. A form of ranking results is needed if you want to go for best match.
Pseudocode:

Search for an exact match using a string: Article Like 'entry'
if (match is found) display page
if (match is not found) Search using wildcards

If (one apropriate match is found) display page
If (more relevant matches) display a "Did you tried to find ... page"
If (no matches) display error page

Note: keep in mind that fuzzy URLs are not recommended from a SEO perspective, because people can link your site using multiple URLs which will split your page rank instead of increase it.
Answer: If you put an index on the varchar field it should be ok (performance wise), really depends on how many pages you are going to have. Also you have to be more careful and sanitize the string to prevent sql injections, e.g. only allow a-z, 0-9, -, _, etc in your query.
I would still prefer an integer id as it is faster and safer, change the format to something nicer like:
http://mysite.com/article/21-this-is-an-entry.html
Answer: As said, comparing INT < VARCHAR, and if the table is indexed on the field you're searching then that'll help too, as the server won't have to create a manual index on the fly.
One thing which will help validate your queries for speed and sense is EXPLAIN. You can use this to show which indexes your query is using, as well as execution times.
To answer your question, if it's possible to build your system using exact matches on the article ID (ie an INT) then it'll be much "lighter" than if you're trying to match the whole url using a LIKE statement. LIKE will obviously work, but I wouldn't want to run a large, high traffic site on it.

MySQL is SELECT with LIKE expensive?


Get value from field in php

Question: I am trying to get fields value in php but I cannot make it work. My code
<?php
$value = $node->field_price;
return $value;
?>

Can somebody please help me to solve this? I believe it has to be something very simple.
Comment: Welcome to Drupal Answers! Please make your questions more detailed. Without any context, it is not possible to understand what is not working; it could be your are trying to access `$node` where it is not available, or it could be the node doesn't contain the field you are trying to access. When talking about code, it is very important to show which function contains the code and, in the case it is a custom hook used by a module, to say that.
Answer: You should first load your node with $node = node_load($nid). You can also use the Devel module (dpm(noad_load($nid))) to debug the node and make sure you're calling the right path to the value.
Answer: The values of fields are stored a bit deeper in $node->field_price, to be more specific they're stored like this:
$node->FIELD_NAME['LANGUAGE_CODE'][INDEX]['value']

The LANG_CODE is usually 'und' or undefined (if you run a multi-lang setup they correspond to the fields lang). The index specifies what exact value are you looking for (makes sense just for fields with cardinality higher than 1).
E.g. if you have a field with infinite cardinality that stores 3 taxonomy tags, you'll have three separate values under:
$node->FIELD_NAME['LANGUAGE_CODE'][0]['value']
$node->FIELD_NAME['LANGUAGE_CODE'][1]['value']
$node->FIELD_NAME['LANGUAGE_CODE'][2]['value']

Comment: Note that instead of `'und'`, use the `LANGUAGE_NONE` constant.
Answer: Try this safer method:
  $node = noad_load($nid);
    if (isset($node->field_price[LANGUAGE_NONE][0]['value']))
    {
      $value = $node->field_price[LANGUAGE_NONE][0]['value'];
    }

Comment: Why did this get voted down? It looks like a good answer to me.

Get value from field in php


Weighted Coin Toss Probablity

Question: Suppose two weighted coins are tossed. The first is weighted so that it comes up heads with probability $\frac{1}{3}$. The second is weighted so that it comes up heads with probability $\frac{1}{4}$. What is the probability that when both coins are tossed, one comes up heads and the other comes up tails?
Comment: Try building a probability tree: HH, HT, TH, TT.
Comment: hint: p(A and B)=p(A)p(B) when A and B are independent.
Answer:
$P(HH)=\dfrac{1}{3}\cdot\dfrac{1}{4}=\dfrac{1}{12}$
$P(HT)=\dfrac{1}{3}\cdot\dfrac{3}{4}=\dfrac{1}{4}$
$P(TH)=\dfrac{2}{3}\cdot\dfrac{1}{4}=\dfrac{1}{6}$
$P(TT)=\dfrac{2}{3}\cdot\dfrac{3}{4}=\dfrac{1}{2}$

So the answer to your question is $P(HT)+P(TH)=\dfrac{1}{4}+\dfrac{1}{6}=\dfrac{5}{12}$

Weighted Coin Toss Probablity


vmware esx4.1 virtual disk locked after failed snapshot creation

Question: I have vmware vsphere 4 esx4.1.
I have a virtual machine with centos6 64bit OS and 3 virtual disks (50GO system/ 250 GO user data / 250 GO backup)
When I tried to take a snapshot of the VM, I got an error message like unspecifi-ed filename has bigger size than biggest size authorized by the datastore.
My problem is that the VM could not start after I got this message error because it could not get access to the 2nd and 3rd disk (only the system disk is normal). It seems that these 2 disks are locked.
I restart the physical esx machine but I had the same thing!
Could you please help! I'm realy blocked and I need your help!
Answer: When I've encountered similar situations, I've shut the virtual machine down and navigated to the datastore containing the VM. I use NFS for most datastores, so there are lock (.lck) files that can be removed. Easy.
However, I'm assuming you're using VMFS on local storage. The process is less-transparent. VMWare has a knowledge base article outlining the troubleshooting steps for locked VM files. Enable SSH access to the host if you can.
These virtual machine files are commonly locked for runtime:

<VMNAME>.vswp
<DISKNAME>-flat.vmdk
<DISKNAME>-<ITERATION>-delta.vmdk
<VMNAME>.vmx
<VMNAME>.vmxf
vmware.log

Since this issue occurred during a snapshot, you'll want to focus on the <DISKNAME>-flat.vmdk and <DISKNAME>-<ITERATION>-delta.vmdk files. Either way, follow the steps listed in the VMWare article.
Comment: Thank you for your answer. I tried to follow this link but I didn't find any locked disk!

Could the snapshot makes the disk irreadable?

In the VM I made fdisk -l and it says that it has not a valid partition table!
Comment: Were there any "delta" files in your datastore? What errors are you getting in the vSphere client console?
Comment: there are no any *delta files. It was the first time that I made a snapshot for this virtual machine
Comment: in the vspehere client there is no error! The VM runs until mounting the 2nd and 3dr disk!

I have this message in the Centos Os VM:
<<
fsck.ext3 : Périphérique ou ressource occupée lors de la tentative d'ouverture de /dev/sdb1

Système de fichier monté ou ouvert en mode exclusive par un autre programme? >>

I could login in into the VM, but the 2nd and 3rd disk are not seem by the OS.
Comment: Now, I have this error when I start a VM :

Motif : The destination file system does not support large files.
Impossible d'ouvrir le disque '/vmfs/volumes/4f9d56ed-dfb9f20e-00e3-d4ae52734324/hosting/hosting_1.vmdk' ou l'un des disques snapshot dont il dépend.


How do you use aggregated values within PySpark SQL when() clause?

Question: I am trying to learn PySpark, and have tried to learn how to use SQL when() clauses to better categorize my data. (See here: https://sparkbyexamples.com/spark/spark-case-when-otherwise-example/) What I can't seem to get addressed is how to insert actual scalar values into the when() conditions for comparison's sake explicitly. It seems the aggregate functions return more tabular values than actual float() types.
I keep getting this error message unsupported operand type(s) for -: 'method' and 'method'     When I tried running functions to aggregate another column in the original data frame I noticed the result didn't seem to be a flat scaler as much as a table (agg(select(f.stddev("Col")) gives a result like: "DataFrame[stddev_samp(TAXI_OUT): double]") Here is a sample of what I am trying to accomplish if you want to replicate, and I was wondering how you might get aggregate values like the standard deviation and mean within the when() clause so you can use that to categorize your new column:
samp = spark.createDataFrame(
    [("A","A1",4,1.25),("B","B3",3,2.14),("C","C2",7,4.24),("A","A3",4,1.25),("B","B1",3,2.14),("C","C1",7,4.24)],
    ["Category","Sub-cat","quantity","cost"])

    psMean = samp.agg({'quantity':'mean'})
    psStDev = samp.agg({'quantity':'stddev'})

    psCatVect = samp.withColumn('quant_category',.when(samp['quantity']<=(psMean-psStDev),'small').otherwise('not small')) ```

Comment: Try this psCatVect = samp.withColumn('quant_category',.when(samp['quantity']<=(psMean-psStDev),.lit('small')).otherwise(.lit('not small')))
Answer: psMean and psStdev in your example are dataframes, you need to use collect() method to extract the scalar values
psMean = samp.agg({'quantity':'mean'}).collect()[0][0]
psStDev = samp.agg({'quantity':'stddev'}).collect()[0][0]

Comment: Thank you! I kept searching and had the collect() at one point, but didn't realize I needed to use the indexes. I assume due to this being a dataframe, one needs to specify both the first row and column; hence the "[0][0]"?
Answer: You could also create one variable with all stats as pandas DataFrame and reference to it later in pyspark code:
from pyspark.sql import functions as F

stats = (
    samp.select(
        F.mean("quantity").alias("mean"),
        F.stddev("quantity").alias("std")
    ).toPandas()
)

(
    samp.withColumn('quant_category',
                F.when(
                    samp['quantity'] <= stats["mean"].item() - stats["std"].item(),
                    'small')
                .otherwise('not small')
               )
    .toPandas()
)

Comment: Thank you Pav3k, so would the "item()" replace the [][] in this case?
Comment: Yes and that is because data type is different.
stats is pandas DataFrame with only one row so if you type stats["mean"] you have returned pandas Series of size 1. Because this is only 1 element, you can use stats["mean"].item() to extract scalar value.
If you had more than 1 row in there, that .item() method would return ValueError: can only convert an array of size 1 to a Python scalar.


AWS S3 redirect https to a new domain

Question: So I am changing the domain for my website to another. Because some users might have it bookmarked I need to redirect from old domain to new domain. They all use https.
I tried creating a S3 bucket in Amazon and Route 53 to redirect (https://aws.amazon.com/premiumsupport/knowledge-center/redirect-domain-route-53/) and it works fine for my old domain in http, however my server has a redirect rule from http to https so must likely users have bookmarked the https address.
In this case,
http://olddomain.com redirects fine to https://newdomain.com
but
https://olddomain.com presents an error (it doesn't load, "This site can't be reached").
I looked through the AWS documentation and it says that S3 can't redirect from https.
Is there a workaround for this?
Thank you in advance.
Comment: I solved it by creating a S3 bucket with the old domain and redirection. Then associating that with a  Distribution at CloudFront to redirect to https and finally in route53 assigning the alias to the distribution. so the distribution will take care of the https redirection and the s3 to the actual domain redirection.
Answer: Instead of doing a bucket redirect, create a CNAME or Alias record in your old domain DNS records which points to your new domain.
See here:
https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/resource-record-sets-choosing-alias-non-alias.html

AWS S3 redirect https to a new domain


Retornar a última posição de um elemento em uma cadeia de caracteres

Question: Desejo que o código retorne a ultima posição de uma letra, no caso a letra 'a', que aparece em uma frase.
frase = input('Escreva uma frase: ').lower()
print(frase.find('a', -1, -len(frase)))

O código está retornando -1, ou seja, que não foi encontrada nenhuma letra 'a'.
Onde está o erro?
Comment: eu tinha votado para fechar, mas pode ser aproveitado realmente. vlw @hkotsubo.
Comment: Considero que é um erro de digitação, pois está utilizando o valor `-len(frase)`. Quando na verdade deveria utilizar `len(frase)` (sem o sinal de `menos`).
Comment: como eu quero que venha de traz para frente começo do -1 e vou ate o - tamanho da str.
Comment: O segundo e terceiro argumentos do `find` indicam apenas o intervalo no qual será feito a busca. Por exemplo, `find('a', 4, 7)` restringe a busca entre as posições 4 e 7 da string (em vez de procurar na string inteira), mas isso não quer dizer que ela será feita de trás pra frente. Na [minha resposta](https://pt.stackoverflow.com/a/559562/112052) abaixo eu explico um pouco melhor porque não funciona
Comment: Respostas baseadas em pilhas ou expressões regulares serão bem vindas?
Answer: De acordo com a documentação, basta usar o método rfind:
frase = input('Escreva uma frase: ').lower()
print(frase.rfind('a'))

Funciona de forma similar à find, mas em vez de retornar o índice da primeira ocorrência, retorna o índice da última (ou -1 se não for encontrado).

No seu caso, retornou -1 porque os índices que você indicou para a busca não fazem sentido. Segundo a documentação, ao fazer string.find(sub, start, end), a busca é feita no intervalo string[start:end].
Por exemplo, se o tamanho da string for 3, ao passar -1 e -len(frase), a busca está sendo feita no slice [-1:-3]. Como índices negativos são contados a partir do final da string, então -1 indica que vai começar pelo último caractere da string, e -3 indica que vai terminar no antepenúltimo elemento. Portanto, isso é um intervalo vazio, e o resultado é uma string vazia.
Por isso nunca vai achar nada. E mesmo que você passe um intervalo válido, ainda sim a busca não será feita "de trás pra frente", então find definitivamente não é a solução.

Outra forma é usar rindex (por exemplo, frase.rindex('a')). A diferença é que se não for encontrado nada, ele lança um ValueError (e aí precisa de um bloco try/except para verificar se não foi encontrado):
try:
    print(frase.rindex('a'))
except ValueError:
    print('Não foi encontrado')


Elementary set theory homework proofs

Question: I've been given some statements to prove using only the following facts.

The set of all integers is countably infinite.
Let $X$ and $Y$ be sets and suppose $f:X\rightarrow Y$ is surjective. If $X$ is countable, then $Y$ is also countable.
The union of a countably infinite family of sets is countable.

I'd like your opinion on my proofs. I feel like the first could be simpler.
Exercise 1. The set $\mathbb{Z}\times\mathbb{Z}$ is countable.
Proof. Let $A_n=\{n\}\times\mathbb{Z}$ for each $n\in\mathbb{Z}$. Define a mapping $f:\mathbb{Z}\rightarrow A_n$ by $f(x)=(n,x)$ for all $x\in\mathbb{Z}$. To see that $f$ is surjective, consider $(n,p)\in A_n$. Since $p\in\mathbb{Z}$, $f(p)=(n,p)$. Thus, $f$ is surjective. By (2), since (1) $\mathbb{Z}$ is countable, $A_n$ is countable.
Let $S=\{A_n:n\in\mathbb{Z}\}$. Notice that $S$ is infinite since it is indexed over $\mathbb{Z}$. Define $g:\mathbb{Z}\rightarrow S$ by $g(x)=A_x$ for all $x\in\mathbb{Z}$. To see that $g$ is surjective, consider $A_q\in S$. Since $q\in\mathbb{Z}$, $g(q)=A_q$. Thus, $g$ is surjective. By (2), $S$ is countable. Thus, $S$ is a countably infinite family of countable sets.
Let $U=\bigcup S$. Then, by (3), $U$ is countable. To see that $U=\mathbb{Z}\times\mathbb{Z}$, we will show that $U$ and $\mathbb{Z}\times\mathbb{Z}$ are subsets of each other.
Let $x\in U$. Then $x\in A_n$ for some $n\in\mathbb{Z}$. Hence, $x=(n,p)$ for some $p\in\mathbb{Z}$. Therefore, $x=(n,p)\in\mathbb{Z}\times\mathbb{Z}$, and it follows that $U\subseteq\mathbb{Z}\times\mathbb{Z}$.
Let $x\in\mathbb{Z}\times\mathbb{Z}$. Then $x=(p,q)$ for some $p,q\in\mathbb{Z}$. Thus, $x\in A_p$, which implies that $x\in U$. Therefore, $\mathbb{Z}\times\mathbb{Z}\subseteq U$, and it follows that $U=\mathbb{Z}\times\mathbb{Z}$.
Therefore, $\mathbb{Z}\times\mathbb{Z}$ is countable.
Exercise 2. Every infinite subset of a countable set is countable.
Proof. Let $X$ be a countable set and let $Y$ be an infinite subset of $X$. Then $X$ is countably infinite and there exists a surjection $f:\mathbb{N}\rightarrow X$. Since $Y\subseteq X$ and $Y$ is nonempty, there exists a surjection $g:X\rightarrow Y$. Thus, $gf:\mathbb{N}\rightarrow Y$ is a surjection. Therefore, by (2), $Y$ is countable.
Comment: These proofs work. You were very precise and detailed.
Comment: Your use of "countable" and "countably infinite" is slightly confusing. Fact 2 is only true if you're using "countable" to mean "finite or countably infinite", not "countably infinite". But then the assumption in Exercise 2 that the subset is infinite is not required to prove that it's countable, and indeed your proof doesn't really use it; you conclude that $X$ is countably infinite but what follows would work just as well for $X$ merely countable.
Comment: In our course, we say a set $X$ is countable if it is finite or if there exists a bijection between $X$ and $\mathbb{N}$. We also call $X$ countably infinite in the second case. In exercise 2, I said the subset was countable because that's how the exercise is worded.
Comment: Perhaps there's a misunderstanding -- I wasn't commenting on the subset being countable but on it being infinite. I understand that this is part of the given wording of the exercise (so the given wording of the exercise is bad), but even so, your proof concludes that $X$ is countably infinite without ever using that fact.
Comment: Grad: I think @joriki is saying you could leave the words "$X$ is countably infinite and" out of your second proof and it would still be valid: indeed it would be better because it avoids using a fact you have not been told.
Comment: Ok, I see what you mean. Thanks joriki and Henry.
Answer: To reduce the number of unanswered questions, I answer here (albeit belatedly).
Your first proof is just fine. However, depending on what your definition of "countable" is, you may not have followed the instructions for your second proof. Consider the two following definitions (the first of which is standard, and the second of which is equivalent but nonstandard).

A set $X$ is said to be countable if there is an injective function $X\to\Bbb N$.
A set $X$ is said to be countable if there is a surjective function $\Bbb N\to X$.

If you were given the latter definition, then your second proof is just fine (though, as joriki and Henry pointed out in the comments above, the fact that $X$ is countably infinite needn't even be mentioned). However, if you were given the former definition, then you didn't follow the directions, as you concluded without "acceptable" justification that the surjection $f:\Bbb N\to X$ exists.
Now, there are easy fixes for this. The simplest is just to use the surjection $g:X\to Y$, which is easily constructed (if you want to be cautious) by fixing some $y_0\in Y$ and letting $g(x)=x$ for $x\in Y$, $g(x)=y_0$ otherwise. Since $X$ is countable, then your given fact 2 shows us that $Y$ is countable. Alternately, you can show that there is a surjection $f:\Bbb N\to X$ as follows:

Since $X$ is countable, then there is an injective function $h:X\to\Bbb N$.
Since $X$ has an infinite subset $Y$, then $X$ is non-empty, so in particular, we can fix an element $x_0\in X$.
Define $f:\Bbb N\to X$ by $f(n)=x$ if there is some $x\in X$ such that $h(x)=n$ (such $x$ will be unique if it exists, since $h$ is injective) and $f(n)=x_0$ if $n$ isn't in the range of $h$. $f$ can readily be shown to be a surjective function, and at that point, you can proceed as in your proof.

There are other ways we can fix it, too, but these are probably the simplest.

Elementary set theory homework proofs


How to pass var from controller into a different view with Cakephp

Question: I am new to Cakephp and indeed OOP, so forgive me if i haven't fully grasped the MVC concept yet.  I have search a lot but cannot find an answer - perhaps my way of working below is not correct.  I hope you can help.
I am building a site which will have many elements relating to their tables and data.  I intend to use a view to pick and choose the relevant elements and any parameters needed.
For example, the homepage of my site will have two elements - a latestusers element and a latestscores element.  I am trying to use a view not related to either the users or scores models/controllers, stored in 'other/index.ctp'.
I have tried using set() to pass a variable from the users controller (latestusers action) into the other/index.ctp view, but the viewVars remain empty.  Could this be due to scope of the variable (i think it is fine for a view in the users folder, i.e. a view specific to the users controller).
I could achieve what i want to do by using global variables, but i think this is missing the point of MVC/OOP.  Would be grateful for any suggestions.
I can include code if need be - it is fairly basic at this stage - but i feel my problem lies with how i am going about things, not the code itself.
Cheers,
James
Comment: Yes, example code would be a good idea to see what exactly you are doing. I don't think you'd want to mess with viewVars directly.
Answer: Yes, the issue is with the scope. If you're going to use variables in the element you'll need to pass them in from your view. So the flow would look something like this

Controller $this->set()s the variable into your current view/layout
Your view/layout calls $this->element with the current element path.
Your element uses those variables.

In number 2 you need to pass your variables as an array of data. This section on the cookbook gives more information : http://book.cakephp.org/view/1081/Elements
<?php echo$this->element('helpbox',
      array("helptext" => "Oh, this text is very helpful."));?>

Note - I didn't understand part of the question. Just want to make sure you are passing data to the correct view. You should not be calling the view of another controller in your active controller.
Your other/index.ctp should be an element and that element should be called from your layout.
Comment: Thanks for the very quick reply John.  I thought i must be doing something illegal!  After years of writing procedural code, its taking me a little while to get my head round the MVC, particularly with regards to page flow.  I will rethink what i am trying to achieve.


Plot and fill 3D volumes in Python

Question: I am working with some 3D (volumetric) data using Python, and for every tetrahedron, I have not only the vertices's coordinates but also a fourth dimension which is the value of some parameter for that tetrahedron volume.
For example:
# nodes coordinates that defines a tetrahedron volume:
x = [0.0, 1.0, 0.0, 0.0]
y = [0.0, 0.0, 1.0, 0.0]
z = [0.0, 0.0, 0.0, 1.0]
# Scaler value of the potential for the given volume:
c = 100.0

I would like to plot a 3D volume (given by the nodes coordinates) filled with some solid color, which would represent the given value C.
How could I do that in Python 3.6 using its plotting libraries?
Answer: You can use mayavi.mlab.triangular_mesh():
from mayavi import mlab

from itertools import combinations, chain

x = [0.0, 1.0, 0.0, 0.0, 2.0, 3.0, 0.0, 0.0]
y = [0.0, 0.0, 1.0, 0.0, 2.0, 0.0, 3.0, 0.0]
z = [0.0, 0.0, 0.0, 1.0, 2.0, 0.0, 0.0, 3.0]
c = [20, 30]

triangles = list(chain.from_iterable(combinations(range(s, s+4), 3) for s in range(0, len(x), 4)))
c = np.repeat(c, 4)

mlab.triangular_mesh(x, y, z, triangles, scalars=c)

Comment: Thank you! Is there any other library for that purpose? Because I've been having some issues [installing Mayavi](https://stackoverflow.com/questions/46597013/mayavi-install-on-python-3-6).

Plot and fill 3D volumes in Python


Static from the amp

Question: I have a Yamaha electro-acoustic guitar and recently bought a Fender acoustasonic 15w amp. It worked fine for arround 10 days, but now all I get is very aggressive, sometimes pulsating static. I checked the wiring on the guitar but found no loose wires.  Is there anything else I can check, or is it the amp that's defective?
Comment: I found the answer myself - I had changed the guitar's alkaline batteries for non-alkaline ones not realising that that would make a difference, and it seems to work fine now. Crisis averted!
Comment: More likely  "old dead" vs. "New powerful" batteries.  You might check the User Manual in case the guitar's amp requires the slightly higher voltage that alkalines provide.
Answer: Looks like the OP found the issue but wanted to give some tips for others that may have similar problems.
When looking for an issue like this it is a good idea to figure out exactly where in the signal chain the issue is.
If you have a guitar > pedal > pedal > amp the issues could be in any of the cables, the guitar, any of the pedals, or the amp itself.
I would trouble shoot this issue by eliminating as much of the stuff between the source (guitar) and the amp by plugging the guitar directly in the amp with nothing between.
If the problem remains, try a different cable. If the problem remains and you have another guitar and or another amp, swap one of those out. At this point you should have narrowed it down to the amp, or the guitar.
If plugging the guitar straight into the amp works you know the issues was in a pedal or in a cable. Slowly add pedals back in until you find the issue. This technique can be expanded out to any size and complexity of a signal chain.
I hope this helps.
As the OP remembered, it's always good to consider the last thing that you changed. Good chance the last change has something to do with the new problem.
Comment: If, when holding perfectly still (so no mechanical stress changes), the noise/static pulses as described, then it's most likely a failure of some power supply (battery or other).  Voltage drops can screw up amps and/or AGC, and a dropout often leads to a brief  current backflow, voltage goes up briefly, and so on

Static from the amp


Finding maximum CSV field sizes for large file using Ruby

Question: I'm trying to determine maximum field sizes for a large CSV file (~5GB) with over 300 fields that I want to dump into a MySQL table. The CSV file schema I have for the file gives incorrect maximum field lengths, so I run into errors on the table import. I'm running Ruby 2.0 on Windows.
I'm using an array to store the maximum field lengths according to the field's index (or column) location, i.e. ignoring the fields actual name in the header. I've tried fancier things like using hashes, inject, and zip, etc, but it seems that a simple array works fastest here.
 field_lengths[0] = Max length of first field
 field_lengths[1] = Max length of second field
 etc.

The file is too large to slurp at once or parse column-wise using CSV. So, I open the CSV file and use CSV#foreach to parse each line (ignoring the header using the :headers => true option). For each row, I loop through the parsed array of field values and compare the field's length with the current maximum length stored in the field_length array. I realize there are much easier ways to do this with smaller files. This method works OK for larger files, but I still haven't been able to make it to the end of my particular file using this method.
To get around not being able to finish the file, I currently define a number of lines to read including the header (=n), and break once I've reached the n-th line. In the example below, I read 101 lines from the CSV file. (1 header row + 100 actual data rows). I'm not sure how many total rows are in the file since the process hasn't finished.
 require 'csv'
 require 'pp'

 data_file = 'big_file.csv'

 # We're only reading the first 101 lines in this example
 n = 101
 field_lengths = []

 File.open(data_file) do |f|
   CSV.foreach(f, :headers => true, :header_converters => :symbol) do |csv_row|
       break if $. > n
       csv_row.fields.each_with_index do |a,i|
           field_lengths[i] ||= a.to_s.length
           field_lengths[i] = a.to_s.length if field_lengths[i] < a.to_s.length
       end
   end
 end

 pp field_lengths

IO#read can read a certain number of bytes, but if I parse the file by bytes the records may get split. Does anyone have alternate suggestions for parsing the CSV file, by splitting it up into smaller files? O'Reilly's Ruby Cookbook (Lucas Carlson & Leonard Richardson, 2006, 1st ed), suggests breaking a large file into chunks (as below), but I'm not sure how to extend it to this example, particularly dealing with the line breaks etc.
 class File
    def each_chunk(chunk_size = 1024)
        yield read(chunk_size) until eof?
    end
 end

 open("bigfile.txt") do |f|
    f.each_chunk(15) {|chunk| puts chunk}
 end

Comment: Split won't work with csv though because it doesn't consider escaping with line breaks.
Comment: I would use the Unix `split` command rather than try to do everything in Ruby: http://kb.iu.edu/data/afar.html
Comment: @AlistairIsrael split wouldn't work on csv very well.
Comment: I'd use `split` only to split the large main file into multiple smaller files, using the `-l` option (number of lines). Say, from one 5GB file (with, say 5 million lines) into 100 files of 50,000 lines each. From then I'd use some kind of multi-threaded or multi-process map-reduce type implementation to find the longest columns.
Comment: @pguardiario Ahh, I was assuming that the CSV would have C-style strings and not allow actual newline characters in fields. In that case, maybe a quick pass using [CSVfix](https://code.google.com/p/csvfix/) first?
Comment: There's really no point. It won't help.
Answer: You're using CSV.foreach wrong, it takes a string for a filename:
field_lengths = {}

CSV.foreach(data_file, :headers => true, :header_converters => :symbol) do |csv_row|
  csv_row.each do |k, v|
    field_lengths[k] = [field_lengths[k] || 0, v.length].max
  end
end

pp field_lengths

Comment: Thanks for point out the CSV.foreach correction. This hash solution is much more concise and it gives the field names also. I think v.length should be v.to_s.length in the event v is nil.
Comment: My file still seems to large with this method, though. Baron Schwartz of High Performance MySQL gives a solution using a perl script "...that reads lines out of the huge file and prints them to a fifo...Every million lines, the script prints an EOF character to the fifo, closes it and removes it, then re-creates it and keeps printing more lines. If you 'cat' the fifo file, you get a million lines at a time from it." http://www.mysqlperformanceblog.com/2008/07/03/how-to-load-large-files-safely-into-innodb-with-load-data-infile/ Is it possible to implement a similar method with Ruby?
Comment: What does mysql have to do with csv?
Comment: I mentioned the article in reference to splitting the CSV into smaller chunks. MySQL is a coincidence.
Comment: I see. Splitting the file into smaller chunks won't make it faster though. I don't think anything will (except a faster computer).
Comment: Agreed. As far as the field lengths though, this works. Just need some patience!
Answer: Given a CSV::Table in a variable called csv, you can change it to be "by column" and use collect or map...or inject.  There's lots of approaches.
e.g.
csv.by_col!
field_lengths = cols.map{|col| col.map{|r| r.is_a?(String) ? r.to_s.length : r.map{|v| v.to_s.length}.max }.max}

The first map iterates through the columns.
The second map iterates through the header (String) then the array of row values.
So the third map iterates through the rows where you can convert the values into a string and return its length.
The first max is the maximum value string length.
The second max is the maximum between the header's lengths and the max value length.
At the end, you may wish to return the csv to col_or_row

e.g.
csv.by_col_or_row!


Converter uma stream para string?

Question: Estou pegando emails da caixa de entrada de uma conta que criei para testes, estou buscando eles com o node-imap e fazendo o parse deles com o MailParser e estou conseguindo recuperar a maior parte das informações que necessito, exceto o texto do email, pois o mesmo se encontra em formato de stream e não sei como transformar ele em uma string para poder enviar para o cliente.
Já estou lendo a documentação do Node.JS para descobrir como faço isso, assim como também estou lendo a documentação do MailParser, porém ainda não achei exatamente o que preciso, agradeço se alguém puder me ajudar.
Answer: Se o retorno da Stream for um buffer você pode fazer algo mais ou menos assim:
<code>let string = ''

stream.on('readable',function(buffer){
  let part = buffer.read().toString()
  string += part
  console.log('Stream em string: ' + part)
})

stream.on('end',function(){
 console.log('String final ' + string)
})
</code>

Converter uma stream para string?


PHP: Output name of array variable for use in one of its elements

Question: In the code below, is there a way to get the name of the array from within that same array so it doesn't have to be typed multiple times?
<code>$awesome_array = array(
    'fruit'=>'apple',
    'name'=>'awesome_array', // Name of array here
    'you_are_an'=>'awesome_array' // Name goes here too
);
</code>
That is all.
Answer: Its not possible directly. But you can achieve this behavior by defining the name prior to defining the array.
Here is 3 ways to do it. There can be more. But I cant recall any other way right now.
Array name is in a string
<code>$array_name = 'awesome_array';
$$array_name = array(
    'fruit'=>'apple',
    'name'=>$array_name, // Name of array here
    'you_are_an'=>$array_name // Name goes here too
);
</code>
Most common way
Pekka reminded me in the comments.
<code>$awesome_array = array('fruit'=>'apple');
$awesome_array['name'] = 'awesome_array';
$awesome_array['you_are_an'] = 'awesome_array';
</code>
Dynamically collect the name
<code>$awesome_array = array('fruit'=>'apple');
// dynamically extracting the name of last defined variable
list($name) = array_slice(array_keys(get_defined_vars()), -1 , 1);
$awesome_array['name'] = $name;
$awesome_array['you_are_an'] = $name;
</code>
Comment: This is nice, but doing it on an entirely array basis instead of with variable variables would be nicer :)
Comment: Thats not possible as The variable is not yet defined.
Comment: I mean storing the array in an array itself `$my_array_container[$array_name] = array(....)`
Comment: @Pekka Yeah I agree. See my another new way. Pretty much dynamic.
Answer: <code>$array_name = "awesome_array";
$$array_name = array(
    'fruit'=>'apple',
    'name'=> $array_name  // Name of array here
    'you_are_an'=>$array_name  // Name goes here too
}
</code>
Answer: Not sure I understood the question, but you can use variable variables:
<code>$var = 'awesome_array';
$$var = array(
    'fruit'=>'apple',
    'name'=>$var, // Name of array here
    'you_are_an'=>$var // Name goes here too
);
</code>


React Native Reanimated

Question: Ao instalar o react-native-reanimated e iniciar o aplicativo é gerado esse erro:

Procurando um pouco na internet encontrei esse tópico Link
Seguindo as informações seria necessário apenas fazer o seguinte comando no CMD/PowerShell porém ao executar apresenta o segundo erro

Verificando o package.json realmente eu não tenho essa importação nas dependencies, não sei exatamente o que devo adicionar aqui

Obs: Se eu for na pasta node_modules eu encontro o pacote react-native-reanimated instalado, a última imagem é o arquivo package.json dentro da pasta do react-native-reanimated
Answer: Foi necessário adicionar no arquivo package.json principal a dependência do react-native-reanimated manualmente
<code>"react-native-reanimated": "^1.4.0",
</code>
Após isso reiniciando a máquina e utilizando os comandos
<code>npm cache clean --force
react-native run-android
</code>
O projeto iniciou sem o erro antes descrito
Answer: para evitar esse tipo de problema sempre instale como administrador. Dessa forma ele adiciona todas as informações automaticamente

React Native Reanimated


Why can't singleton methods be defined on Symbols or Fixnums?

Question: There are a some Ruby classes that don't allow singleton methods to be defined on their instances. For example, Symbol:
var = :asymbol

def var.hello
  "hello"
end

# TypeError: can't define singleton method "hello" for Symbol

I thought this might be a restriction on all immediate values, but it seems to work for nil, true, and false (but not instances of Fixnum or Bignum):
var = true

def var.hello
  "hello"
end

var.hello #=> "hello"

I don't understand why why Ruby allows singleton methods to be defined on certain classes of objects but not others.
Comment: It seems to not just be `Fixnum`s, but any `Numeric`.
Comment: My gut reaction is that it has something to do w/ types that would be the same value regardless of context. A symbol `:fred` will always be the same symbol object, as will `5`. Unfortunately, the same is true for `true`, so it's something deeper than that; I'd wonder first if it's the same across versions, then wonder how each type's constancy was implemented.
Comment: The doc for [Object#singleton_class](http://ruby-doc.org/core-2.3.0/Object.html#method-i-singleton_class) states, "If [receiver] `obj` is `nil`, `true`, or `false` it returns `NilClass`, `TrueClass` or `FalseClass`, respectively. If `obj` is a `Fixnum` or a `Symbol`, it raises a `TypeError`." As @Andrew notes, however, no numeric value can have a singleton class. `nil`, `true` and `false` have singleton classes (e.g., `class << false; puts self; end #=> FalseClass`), but since those classes have only a single instance, there's no point to distinguish between the class and the singleton class.
Comment: I suspect `nil` has a singleton class for the same reason that it has instance methods `to_a`, `to_c`, `to_f`, `to_h`, `to_i`, `to_r` and `to_s`; namely, it allows for a soft landing when, for example, the receiver of `singleton_class` could be either `nil` or something else. That logic does not extend to `true` and `false`, however.
Answer: This has to do with a concept called 'immediate values' as described here by Matz.
In truth, no immediate values should permit a singleton method.  However, in the case of true, false, and nil, there are actually singleton classes that back these values (or the value is actually the singleton class - I'm not sure about this).  You can therefore add singleton instances to the backing class which manifests as though it were the value itself.  Numeric and Symbol instances are not singletons (obviously) and have nowhere to hold singleton methods.
Comment: It appears that they [are indeed still immediate values](http://www.ruby-doc.org/core-1.9.3/ObjectSpace.html#each_object-method).  The actual difference is described above, see updated.
Comment: Hmm, are `true`, `false`, and `nil` really no longer immediate values? Do you have a reference for that?
Comment: It's not clear why immediate values should not permit singleton methods. It's not like adding a method mutates the value. Some integers, floats and symbols are stored as objects (non-immediate values). And as such could potentially have singleton methods. The values of `true`, `false`, `nil` are not actually the singleton classes. Add singleton methods, not instances to the backing class? See [my answer](https://stackoverflow.com/a/75633801/52499).
Comment: @x-yuri at the end of your answer: "If you were able to add singleton methods to integers, floats and symbols, then ruby would be forced to store them as objects (those with extra methods). Which eliminates the optimization."  Which was exactly my point.  Immediate values that don't have a backing singleton class have nowhere to store the method without losing the implementation as an immediate value.
Answer: At the moment (ruby-3.2.1) you can't define singleton methods for integers, floats, symbols and frozen strings (I also confirmed it with ruby-2.6.10):
v = Object.new
v = nil
v = false
v = true
v = 'string'
v = 1                       #=> TypeError: can't define singleton
v = 1000000000000000000000  #=> TypeError: can't define singleton
v = 1.0                     #=> TypeError: can't define singleton
v = 1e100                   #=> TypeError: can't define singleton
v = :sym                    #=> TypeError: can't define singleton
v = :"sym#{v}"              #=> TypeError: can't define singleton
v = -'string'               #=> TypeError: can't define singleton
def v.m() end

And the corresponding part of the code is here:
static VALUE
singleton_class_of(VALUE obj)
{
    VALUE klass;

    switch (TYPE(obj)) {
      case T_FIXNUM:
      case T_BIGNUM:
      case T_FLOAT:
      case T_SYMBOL:
        rb_raise(rb_eTypeError, "can't define singleton");

      case T_FALSE:
      case T_TRUE:
      case T_NIL:
        klass = special_singleton_class_of(obj);
        if (NIL_P(klass))
            rb_bug("unknown immediate %p", (void *)obj);
        return klass;

      case T_STRING:
        if (FL_TEST_RAW(obj, RSTRING_FSTR)) {
            rb_raise(rb_eTypeError, "can't define singleton");
        }
    }
    ...

Now, let's look at what TYPE does:
#define TYPE(_)           RBIMPL_CAST((int)rb_type(_))

rb_type():
static inline enum ruby_value_type
rb_type(VALUE obj)
{
    if (! RB_SPECIAL_CONST_P(obj)) {
        return RB_BUILTIN_TYPE(obj);
    }
    else if (obj == RUBY_Qfalse) {
        return RUBY_T_FALSE;
    }
    else if (obj == RUBY_Qnil) {
        return RUBY_T_NIL;
    }
    else if (obj == RUBY_Qtrue) {
        return RUBY_T_TRUE;
    }
    else if (obj == RUBY_Qundef) {
        return RUBY_T_UNDEF;
    }
    else if (RB_FIXNUM_P(obj)) {
        return RUBY_T_FIXNUM;
    }
    else if (RB_STATIC_SYM_P(obj)) {
        return RUBY_T_SYMBOL;
    }
    else {
        RBIMPL_ASSUME(RB_FLONUM_P(obj));
        return RUBY_T_FLOAT;
    }
}

That's a lot of information. Let me give you some constants first:
    RUBY_Qfalse         = 0x00, /* ...0000 0000 */
    RUBY_Qnil           = 0x04, /* ...0000 0100 */
    RUBY_Qtrue          = 0x14, /* ...0001 0100 */
    RUBY_Qundef         = 0x24, /* ...0010 0100 */
    RUBY_IMMEDIATE_MASK = 0x07, /* ...0000 0111 */
    RUBY_FIXNUM_FLAG    = 0x01, /* ...xxxx xxx1 */
    RUBY_FLONUM_MASK    = 0x03, /* ...0000 0011 */
    RUBY_FLONUM_FLAG    = 0x02, /* ...xxxx xx10 */
    RUBY_SYMBOL_FLAG    = 0x0c, /* ...xxxx 1100 */

and some type constants:
    RUBY_T_FLOAT    = 0x04, /**< @see struct ::RFloat */
    RUBY_T_STRING   = 0x05, /**< @see struct ::RString */
    RUBY_T_BIGNUM   = 0x0a, /**< @see struct ::RBignum */
    RUBY_T_NIL      = 0x11, /**< @see ::RUBY_Qnil */
    RUBY_T_TRUE     = 0x12, /**< @see ::RUBY_Qfalse */
    RUBY_T_FALSE    = 0x13, /**< @see ::RUBY_Qtrue */
    RUBY_T_SYMBOL   = 0x14, /**< @see struct ::RSymbol */
    RUBY_T_FIXNUM   = 0x15, /**< Integers formerly known as Fixnums. */

So, what are immediate values?
RB_IMMEDIATE_P:
static inline bool
RB_IMMEDIATE_P(VALUE obj)
{
    return obj & RUBY_IMMEDIATE_MASK;
}

RB_SPECIAL_CONST_P:
static inline bool
RB_SPECIAL_CONST_P(VALUE obj)
{
    return RB_IMMEDIATE_P(obj) || obj == RUBY_Qfalse;
}

The names in the code seems a bit misleading, but the following way it more or less makes sense. Immediate values are values that have any of the 3 least significant bits set and RUBY_Qfalse. Some of the immediate values are constants, like nil (0x04), false (0x00), true (0x14). Some simply store the values inline (or at least don't point somewhere), like fixnums (integers), flonums (floats) and static symbols.
RB_FIXNUM_P (is a fixnum?):
static inline bool
RB_FIXNUM_P(VALUE obj)
{
    return obj & RUBY_FIXNUM_FLAG;
}

RB_FLONUM_P (is a flonum?):
static inline bool
RB_FLONUM_P(VALUE obj)
{
#if USE_FLONUM
    return (obj & RUBY_FLONUM_MASK) == RUBY_FLONUM_FLAG;
#else
    return false;
#endif
}

RB_STATIC_SYM_P (is a static symbol?):
static inline bool
RB_STATIC_SYM_P(VALUE obj)
{
    RBIMPL_ATTR_CONSTEXPR(CXX14)
    const VALUE mask = ~(RBIMPL_VALUE_FULL << RUBY_SPECIAL_SHIFT);
    return (obj & mask) == RUBY_SYMBOL_FLAG;
}

RB_BUILTIN_TYPE (returns the type of a non-immediate value, of a value that the pointer points to):
static inline enum ruby_value_type
RB_BUILTIN_TYPE(VALUE obj)
{
    ...
    VALUE ret = RBASIC(obj)->flags & RUBY_T_MASK;
    return RBIMPL_CAST((enum ruby_value_type)ret);
}

RBASIC (typecast to struct RBasic*, that's a struct that conforms to any VALUE, that's not a pointer):
#define RBASIC(obj)                 RBIMPL_CAST((struct RBasic *)(obj))

And FL_TEST_RAW(obj, RSTRING_FSTR)? That's a way to check if a string is frozen.
Now, actually some integers, floats and symbols are stored as pointers. That's why I have 2 checks per each of these types: 1 (immediate) and 1000000000000000000000 (pointer), 1.0 (immediate) and 1e100 (pointer), :sym (immediate) and :"sym#{v}" (pointer, dynamic symbol). In ruby-2.6 the distinction is more apparent.
As for why you can add methods to nil, but not to integers? Beats me :) Most likely because nil is one, and integers are many. At the moment it's up to ruby to choose whether to store a value inline or in an object. If you were able to add singleton methods to integers, floats and symbols, then ruby would be forced to store them as objects (those with extra methods). Which eliminates the optimization. And was probably considered as doing more harm than good.
And -'string' is a frozen string, by the way.


Module Views automatically replace underscores in css classname to hyphens?

Question: The situation is like this: I created an article list block with Views, and I want give the list row a custom css classname, ex it's called "focus_img", but when I saw the output, "focus_img" was converted to "focus-img" automatically. How can I turn off this annoying feature? I don't get it, why it made this change, I just need it output what I want..
Comment: How are you adding a custom class to each row?
Comment: At Views editing interface, "setting" besides "list format"
Answer: It's by design... Views module is cleaning class in views_plugin_style.inc..
<code>  /**
   * Return the token replaced row class for the specified row.
   */
  function get_row_class($row_index) {
    if ($this->uses_row_class()) {
      $class = $this->options['row_class'];
      if ($this->uses_fields() && $this->view->field) {
        $class = strip_tags($this->tokenize_value($class, $row_index));
      }

      $classes = explode(' ', $class);
      foreach ($classes as &$class) {
        $class = drupal_clean_css_identifier($class);
      }
      return implode(' ', $classes);
    }
  }
</code>
Below statement is converting _ (Underscore) to - (hyphens)
<code>$class = drupal_clean_css_identifier($class);
</code>
If you see documentation of drupal_clean_css_identifier by default filters replaces _ with -.
Comment: `drupal_clean_css_identifier()` lists `underscore` as a **valid** character, though. So that can't be right ;)
Comment: Sorry my bad, I didn't see the first lines...
Comment: thx man, but when I use block, give block a classname, it hasn't been changed, just stay what value I gave to it. I think this is a little tricky, too hard to find where get wrong..
Comment: Agree with you clive...  It's a views module issue.. They should send empty array or give some sort of settings for this.. It's already reported in issue queue here.. https://drupal.org/node/1111258 .. hope we will have fix soon..


Can a sumo wrestler touch the ground before his opponent in the act of forcing him to the ground?

Question: According to Wikipedia (emphasis mine for clarity),

Sumo (相撲 sumō?) is ... where a rikishi (wrestler) attempts to force another wrestler ... into touching the ground with anything other than the soles of the feet (hereafter referred to as "touch/touches/touching the ground").

I was watching footage of a takedown in which the one giving the takedown nearly touches the ground  before his opponent (and was quite amazed he didn't touch the ground).
Can a sumo wrestler touch the ground before his opponent in the act of forcing him to the ground? Would this be forcing himself into touching the ground, and thus allowable, or unallowable due to touching the ground in any way?
Answer: While unlikely, the concept you describe is one with legitimate use.
A wrestler who touches the ground first may still be declared victor if it is clear that the opponent had no chance themselves of winning.
For example, a wrestler driving his opponent onto the ground backwards may extend a hand to prevent injury to either wrestler. Even though the hand touches first, they were sure to win otherwise, and so they are declared victor instead. There is apparently record of this happening several decades ago.
Comment: Thanks for the info. Is this considered a universal rule?
Comment: I'm not able to find reference to different rulesets, but I would operate on the basis that the Japanese Sumo Association is a standard given its status, and the ruleset used by them is "the one".


View listing related nodes by taxonomy term

Question: I have a content type representing a book. Each book as a genre (SciFi, Fantasy, Thriller ...) and I would like to expose, on the page of a book some books sharing the same genre.
I created a view with a contextual filter on the taxonomy term, but I retrieved the current book so I added a contextual filter on tue current node id to exclude it.
Now I don't retrieve anything from my view.
Each contextual filter on his own his working. If I just use the contextual filter on the content id, I retrieve the list of my books without the current book. If I just use the contextual filter on the taxonomy term, I retrieve the list of my book for that genre (including my current book).
How am I supposed to proceed to have both filter working together ?
Answer: Many of the Drupal features seem magical, but sometimes there are more steps to configure to make them work.
How to use Views Preview with Contextual filters
Contextual filters are strictly linked to individual Fields. It isn't enough to use only the NID Contextual filter (in your Preview) that would then be able to "pull" all the other information, no matter if you have the other Contextual filters set up.
What you enter into the Preview field is what Drupal would take from the URL, or the specified default value as if the URL value is available.
If you have two Contextual filters, you need to enter two filter values into the Preview, one for each filter, in the correct order, separated by /.
To test the complete situation you enter a value for both Contextual filters, for example thriller/35 or 21/35 if Thriller has TID 21 and your first Contextual filter is for term ID and not term name, and 35 is the "current node" NID.
Most Contextual filters have the Exception value set to all. This is a sort of a bypass, the Contextual filter behaves as if it weren't there.
So if you have two Contextual filters and you enter all/all you will see the Views results as if there are no Contextual filters at all.
This is useful when you have to test a Contextual filter while making sure the other one isn't in the way. So you enter all/35 to see all nodes but not the current one (if the current one has NID 35). Or you enter thriller/all so see nodes tagged Thriller but the current one is still on the list.
The Views Preview field (arguments) can test only the part of the Contextual filter that has Provide default value or When the filter value IS available or a default is provided options.
Preview does help to test and configure Contextual filters more quickly, but it doesn't gurantee that you have set them up correctly for cases that don't take values from the URL, so you have to test the Block on the appropriate location anyway.
Answer: It appears I'm just too stupid to understand Drupal. The view is working when I place a block on the book page. The problem was in the preview with contextual filters. I specified the node id, expecting Drupal to retrieve everything from this id but it appeared it is not enought so it was answering me that No query was run.
Answer: Use Similar terms module.
Usage:

Create a freetagging vocabulary called "Tags" assigned to the
content types on which you'd like to display the "Similar" view
block.
2) Enable the view block called "Similar entries from the
Tags vocabulary".
3) Add keyword tags to the content.


Why did I get the same graph?

Question: I use networkx in ipython to analysis my graph or network, when I generated the maximum spanning tree and the minimum spanning tree, I got a very strange result that these two graph is the same!
This is my code below:
a=nx.maximum_spanning_tree(pearson_net)
b=nx.minimum_spanning_tree(pearson_net)

pearson_net is my original network(graph), I want to get the edges of these two graph, but these edges are completely the same!
a.edges()

This is the edges of graph a:
EdgeView([('600000.SH', '600015.SH'), ('600000.SH', '600016.SH'),
('600000.SH', '600030.SH'), ('600000.SH', '600036.SH'),
('600000.SH','600109.SH'), ('600000.SH', '600816.SH'),
('600000.SH','600837.SH'), ('600000.SH', '600999.SH'),
('600000.SH', '601009.SH'), ('600000.SH', '601099.SH'),
('600000.SH', '601166.SH'), ('600000.SH', '601288.SH'),
('600000.SH', '601318.SH'), ('600000.SH', '601328.SH'),
('600000.SH', '601336.SH'), ('600000.SH', '601377.SH'),
('600000.SH', '601398.SH'), ('600000.SH', '601555.SH'),
('600000.SH', '601601.SH'), ('600000.SH', '601628.SH'),
('600000.SH', '601688.SH'), ('600000.SH', '601788.SH'),
('600000.SH', '601818.SH'), ('600000.SH', '601939.SH'),
('600000.SH', '601988.SH'), ('600000.SH', '601998.SH'),
('600000.SH', '000001.SZ'), ('600000.SH', '000686.SZ'),
('600000.SH', '000728.SZ'), ('600000.SH', '000750.SZ'),
('600000.SH', '000776.SZ'), ('600000.SH', '000783.SZ'),
('600000.SH', '002142.SZ'), ('600000.SH', '002500.SZ'),
('600000.SH', '002673.SZ')])

and then
b.edges()

These are the edges of graph b:
    EdgeView([('600000.SH', '600015.SH'), ('600000.SH', '600016.SH'),
('600000.SH', '600030.SH'), ('600000.SH', '600036.SH'),
('600000.SH','600109.SH'), ('600000.SH', '600816.SH'),
('600000.SH','600837.SH'), ('600000.SH', '600999.SH'),
('600000.SH', '601009.SH'), ('600000.SH', '601099.SH'),
('600000.SH', '601166.SH'), ('600000.SH', '601288.SH'),
('600000.SH', '601318.SH'), ('600000.SH', '601328.SH'),
('600000.SH', '601336.SH'), ('600000.SH', '601377.SH'),
('600000.SH', '601398.SH'), ('600000.SH', '601555.SH'),
('600000.SH', '601601.SH'), ('600000.SH', '601628.SH'),
('600000.SH', '601688.SH'), ('600000.SH', '601788.SH'),
('600000.SH', '601818.SH'), ('600000.SH', '601939.SH'),
('600000.SH', '601988.SH'), ('600000.SH', '601998.SH'),
('600000.SH', '000001.SZ'), ('600000.SH', '000686.SZ'),
('600000.SH', '000728.SZ'), ('600000.SH', '000750.SZ'),
('600000.SH', '000776.SZ'), ('600000.SH', '000783.SZ'),
('600000.SH', '002142.SZ'), ('600000.SH', '002500.SZ'),
('600000.SH', '002673.SZ')])

I can not understand this result.Why maximum_spanning_tree is the same as minimum_spanning_tree?
This is the graph of pearson_net:

It is a complete graph, one node can be linked with any other node.
This is the part of the pearson_net'dataset below:

The columns and the index are the node of the graph, the number(pearson correlated coefficient) is the weight of the edge.
This is my complete code:
pearson_net=nx.Graph()
for i in range(pearson):
   for j in range(i+1,pearson):
     pearson_net.add_edge(pearson.index[i],pearson.columns[j],......
     weights=pearson.iloc[i][j])
tree1=nx.minimum_spanning_tree(pearson_net)
tree2=nx.maximum_spanning_tree(pearson_net)

"pearson" is the matrix of the correlated coefficient, which is the dataset before.
Comment: If every edge has the same weight then min and max spanning trees can be equal. Can't say much more without knowing what `pearson_net` looks like.
Comment: You didn't show us your input, only your output. Can you reproduce this with a small enough graph to post here?
Comment: This question have been edited.
Comment: The weight is not the same.
Comment: There is something odd with your graph construction. You say that `pearson` is a matrix but you are using `range()` on it. Can you try using the `nx.from_numpy_matrix()` function instead ?
Comment: But my original graph is right.
Answer: Testing minimum and maximum spanning tree
We need to use a minimal example to control the results of the minimum_spanning_tree() and maximum_spanning_tree() functions:
a_mat = [
    [1.,0.661435,0.667419,0.547633],
    [0.661435,1.,0.676438,0.542115],
    [0.667419,0.676438,1.,0.500370],
    [0.547633,0.542115,0.500370,1.]
]
G = nx.from_numpy_matrix(np.array(a_mat))
pos = nx.spring_layout(G)
nx.draw_networkx_nodes(G,pos=pos)
nx.draw_networkx_edges(G,pos=pos)
nx.draw_networkx_edge_labels(G, pos=pos)
plt.axis('off')
plt.show()

From this example, we can easily find the minimum spanning tree by adding the lowest edges weights (0.50037, 0.547633, 0.542115)
Indeed:
mi = nx.minimum_spanning_tree(G)
mi.edges(data=True)

[Out]:
EdgeDataView([(0, 3, {'weight': 0.547633}), (1, 3, {'weight': 0.542115}), (2, 3, {'weight': 0.50037})])

For the maximum spanning tree, we can anticipate from the graph the maximum edges weights sum (0.661435, 0.667419,0.547633):
ma = nx.maximum_spanning_tree(G)
ma.edges(data=True)

[Out]:
EdgeDataView([(0, 2, {'weight': 0.667419}), (0, 3, {'weight': 0.547633}), (1, 2, {'weight': 0.676438})])

From this simple example, we can observe that the two functions behave as expected.
If you show us your code, we may be able to spot the error for you.
[Edit] Graph construction from a Dataframe
It appears from your update that your pearson matrix is a pandas Dataframe. Here is the same procedure starting from a Dataframe. You can use the networkx dedicated method nx.from_pandas_adjacency().
import pandas as pd
df = pd.DataFrame(a_mat)

Create the graph
pearson_net = nx.from_pandas_adjacency(df)

pos = nx.spring_layout(pearson_net)
nx.draw_networkx_nodes(pearson_net,pos=pos)
nx.draw_networkx_edges(pearson_net,pos=pos)
nx.draw_networkx_edge_labels(pearson_net, pos=pos)
plt.axis('off')
plt.show()

[Out]:

Invoking the spanning tree methods
tree1=nx.minimum_spanning_tree(pearson_net)
tree2=nx.maximum_spanning_tree(pearson_net)

tree1.edges(data=True)

[Out]:
EdgeDataView([(0, 3, {'weight': 0.547633}), (1, 3, {'weight': 0.542115}), (2, 3, {'weight': 0.50037})])

nx.draw_networkx_nodes(tree1,pos=pos)
nx.draw_networkx_edges(tree1,pos=pos)
nx.draw_networkx_edge_labels(tree1, pos=pos)
plt.axis('off')
plt.show()

[Out]:

tree2.edges(data=True)

[Out]:
EdgeDataView([(0, 2, {'weight': 0.667419}), (0, 3, {'weight': 0.547633}), (1, 2, {'weight': 0.676438})])

nx.draw_networkx_nodes(tree2,pos=pos)
nx.draw_networkx_edges(tree2,pos=pos)
nx.draw_networkx_edge_labels(tree2, pos=pos)
plt.axis('off')
plt.show()

[Out]:
Comment: Could I send the whole dataset to you? In this case you can use my dataset to generate a minimum spanning tree. Thanks very much.
Comment: I think your problem is in the way you invoke this two functions rather than in the dataset. You should update your question with the code you use to obtain that result.

Why did I get the same graph?


In a topological vector space, if $A$ is compact and $B$ is closed, then $A+B$ is closed.

Question: If $x\notin A+B$, then there is a neighborhood $V$ of $0$ such that $(x+V)\cap (A+B)=\emptyset$. But I am stuck in this step.
I have seen some solutions concerning about $\mathbb R^n$, but I don't know how to apply it to topological vector space which is more general.
Comment: The argument for $\mathbb R^{n}$ works here too if you replace sequences by nets.
Comment: Sorry, I am not familiar with nets yet.
Comment: I am not sure if there is an elegant way to show this without using nets. Probably, you should start to get familiar with nets. If your topological vector space fulfills the first axiom of countability, then I guess you can work with sequences instead of nets.
Answer: Assume that $x\in\overline{A+B}$ but $x\notin A+B$, then $(-A+x)\cap B=\emptyset$. So $-A+x\subseteq B^{c}$ and note that $B^{c}$ is open and $-A+x$ is compact.
Assume at the moment that there is some neighborhood $V$ of $0$ such that $(-A+x)+V\subseteq B^{c}$, then $((-A+x)+V)\cap B=\emptyset$.
Note that $((-A+x)+V)\cap B=(x+V)\cap(A+B)$.
On the other hand, since $x\in\overline{A+B}$, we must have $(x+V)\cap(A+B)\ne\emptyset$, so we have a contradiction.
Now it is left to show the fact assumed.
We are to show that, for compact set $K$ and open set $G$ such that $K\subseteq G$, there is a neighborhood $V$ of $0$ such that $K+V\subseteq G$.
For every $x\in K$, there is a neighborhood $V_{x}$ of $0$ such that $x+V_{x}\subseteq G$. Since the addition is continuous, there is a neighborhood $W_{x}$ of $0$ such that $W_{x}+W_{x}\subseteq V_{x}$.
So $\{x+W_{x}\}_{x\in K}$ is an open cover for $K$ and hence there is some finite subcover $x_{i}+W_{i}$, $i=1,...,n$ for $K$. Let $V=\displaystyle\bigcap_{i=1}^{n}W_{i}$, then $V$ is also a neighborhood of $0$.
For $u\in K+V$, then $u=x+v$ for some $x\in K$ and $v\in V$, and we have some $i$ such that $x\in x_{i}+W_{i}$ and hence $u\in x_{i}+W_{i}+V\subseteq x_{i}+W_{i}+W_{i}\subseteq x_{i}+V_{x_{i}}\subseteq G$, this shows that $K+V\subseteq G$.


How can i use MATCH and AGAINST with db_select?

Question: I have a query like:
$query = db_query("
    SELECT *, MATCH(field1,field2) AGAINST ('$s' IN BOOLEAN MODE) AS Relevance
    FROM {my_table}
    ORDER BY Relevance DESC, created DESC
    ");

That is working well with db_query.
How can i use same query with db_select function for drupal 7?
Answer: Adding an expression should work:
 $query = db_select('foo');
 ...
 $expression = 'MATCH(field1,field2) AGAINST (:search IN BOOLEAN MODE)';
 $query->addExpression($expression, 'Relevance', [':search' => '$s']);
 ...

See SelectQuery::addExpression for more info.


FineUploader UI shows thumbnail on file select, but not drag-n-drop

Question: Using React and FineUploader 5.14.2-rc1 in UI mode. Uploads work great, but the displayed thumbnails are inconsistent. When I click the component and select a file from the system file selection dialog, the file is represented by a thumbnail of the image. But when I drag the same file and drop it on the component, it displays a generic file icon rather than an image thumbnail. I'm assuming this is a configuration problem, but I can't find anything germane in the documentation. Here's the relevant component:
import FineUploaderS3 from 'fine-uploader-wrappers/s3'
import Gallery from 'react-fine-uploader'

export default class FileUploader extends React.Component {

    constructor(props){
        super(props)

        this.state = {
            showModal: props.showModal || false,
            fileName: props.fileName,
            s3Key: props.s3Key,
            title: props.title,
            description: props.description,
            fileUrl: props.fileUrl,
            success: props.success || true,
        }

        let uploaderInstance = null

        this.uploader = () =>{
            uploaderInstance = new FineUploaderS3({
                options: {
                    chunking: {
                        enabled: true
                    },
                    resume: {
                        enabled: true
                    },
                    request: {
                        endpoint: 'http://ourbucketurl',
                        accessKey: ourAccessKeyId,
                    },
                    signature: {
                        endpoint: '/api/s3handler',
                    },
                    uploadSuccess: {
                        endpoint: '/api/s3uploadsuccess',
                    },
                    callbacks: {
                        onComplete: this.uploadCompleteHandler
                    },
                }
            })

            return uploaderInstance
        }

        this.uploadCompleteHandler = (id, name, responseJSON) => {
            this.setState({showModal: responseJSON.success,
                s3Key: responseJSON.key,
                fileName: responseJSON.name,
                fileUrl: `https://ourbucketurl/${responseJSON.key}`})
        }

    render() {

        return

            <Gallery uploader={this.uploader()} />

    }
}

I can put this component anywhere, and files upload without incident.
The problem occurs regardless of browser. What do I need to do to show thumbnails consistently regardless of how the user invokes the upload operation?
Comment: I'm not seeing any code to support file dropping here, or a file input element, or a UI for that matter.
Comment: Fair enough. I've updated the question to include more context.
Answer: I've encountered this myself, downgraded to react-fine-uploader 0.6.0 and all works again.
Comment: Thanks for the tip! Have you noticed any undesirable side-effects from the downgrade?


R: replace all values in a dataframe lower than a threshold with NA

Question: I would like to replace all values in a dataframe lower than a given threshold minval with NA. What would be the most elegant way to do this?
Answer: Try this:
 df[df<minval]=NA

df < minval creates a boolean matrix, which is used to select the values you want to replace with NA.
Comment: Ha yes of course - I got confused trying with which(...) - this works perfectly - thanks!


Update build podTemplate for Jenkins X

Question: If I modify the pod template in UI as suggested in adding-your-own-pod-templates my changes get lost on the node restart (we are running on GKE with preemptive nodes)
Is there another reccomendation how to do that? I tried to update .jx/cloud-environments/env-jx-infra/myvalues.yaml and run jx upgrade platform but that does not seem to  work yet. Any chance it will work from jx install?
I am kind of hesistating to re-create my environment. As a last resort I will modify the jenkins-x-pod-templates configmap, which will likely help till the next jx upgrade
Comment: For the time being I updated the `jenkins` configmap from jx namespace. Updating jenkins-x-pod-templates configmap did not have any effect.
Answer: we recently fixed jx upgrade platform so that it can work properly with myvalues.yaml files as described here.
there's some docs on how to do this with helm here: https://jenkins-x.io/getting-started/create-custom-builder/

Update build podTemplate for Jenkins X