Accepted filename character for sharp #

Question: WRT filenames:
"b" (ascii 98) is an acceptable character for flat.
Is there an accepted character in place of the not-good-for-most-filesystems sharp "#"?
Comment: That's not actually 'sharp' [not that it really matters] but a 'US pound' or Number sign, UTF-8 23. The real sharp sign is ♯ UTF-8 E2 99 AF. I tested in macOS & Win7, both find the characters acceptable - https://i.stack.imgur.com/d8fiA.png
Comment: Americans call the number sign 'pound'. You have to blame them ;-) We Brits know what a pound sign looks like, it's just our transpondian cousins who get us confused ;) Its official name is "Number Sign", anything else is a preference, convenience, or attempt at distinguishing. Hash works for me, tbh.
Comment: @Tim - No, really, its proper name is "number sign" in the Unicode naming scheme. All others are 'convenience' descriptions, including *octothorpe*, which is a 'made up name' anyway, coined by Bell Labs - https://en.wikipedia.org/wiki/Number_sign
Comment: What file system chokes on a simple # character? Even FAT could deal with that. It's simple ASCII, after all.
Comment: Its proper name is *octothorpe* - the sharp-like sign on a phone pad. The French call that sign diese, which actually means 'sharp'. The 'hash' word also comes from French - they call the letter H 'hash' - not spelled, of course!
Comment: Do I understand the question correctly that it is not possible to use # when saving a piece or  Song-file e.g. *Prelude in C#* ?
Comment: Rather than an operating system not supporting unicode characters, I think the bigger issue would be whatever software is being used to open them. b, #, ♭, and ♯ should all be supported on standard OSes, but you can't trust software devs to always handle unicode characters.
Comment: It's more often called "hash" (as in "hashtag"). Calling it "pound" would be a bad idea  because there is the pound sign £.
Comment: What filesystem(s) are you targeting?  I haven't tried it,  but current ones should support Unicode, which, in turn, has proper flat/sharp symbols.
Comment: @AlbrechtHügli  the point is that some computer filesystems don't allow certain "special characters" to be in the file names.  The OP wants a naming system for his files that is accepted on any OS.
Comment: @CarlWitthoft the OP wants a naming system that is not "not-good-for-most-filesystems". But most filesystems nowadays are actually ok with pretty much all of Unicode, just not with those ASCII characters that have a special meaning!
Comment: Is anyone going to name the filesystem that can't handle ASCII "#" in filenames?  (I'm aware that a *leading* "#" can cause problems in most command-line shells, as it starts a comment, but that's not the case here.)
Comment: POSIX fully portable.
Answer: No, there's no de facto or official equivalent for sharp that compares to the accidental (ha!) equivalence of flat and lower case B.  But some filesystems will let you use # or even more esoteric symbols in file names.
Even so, even in 2019, it's safer to encode the key in some kind of metadata instead of in the filename.
Comment: I think these days most OSes default to UTF-8 encoding, so none of those symbols should be any issue - except that on Windows they're a bit tricky to actually generate, needing awkward alt-codes.
Answer: You can use the German/Dutch form: for example Ces, Cis for C-flat, C-sharp respectively.   Two characters, true, but they are regular (ascii) letters.
Comment: Cis and Ces don't mean sharp and flat. Cis means C♯and  Ces means C♭.
Comment: and I believe that B is B-flat in German, and H is B-natural
Answer: Ascii 98 is just letter 'b'.
Unicode would be the way to get a representation of the musical symbol.
Unicode U+266D is a musical flat sign.

https://en.wikipedia.org/wiki/Flat_(music)
https://en.wikipedia.org/wiki/Sharp_(music)
https://en.wikipedia.org/wiki/Miscellaneous_Symbols

Inputting Unicode is another issue. I just cut and paste from a site that displays the Unicode symbol.
In order for a user to actually see the symbol, they need a font with a glyph for the character.
Using such characters in a file name is yet another issue. I'm scarred from the bad old days when various filename systems could not handle much beyond plain ascii. So I would just write out 'sharp' or 'flat' or just give up and use ascii 'b' or '#'. Neither is what we want, but plain old alphabetic ascii shouldn't fail you.

Accepted filename character for sharp #


How to take JSON object element in Rails?

Question: When I run this:
@message_for = Message.message_for(@for, @from)
render :json => @message_for.to_json

I get the next array of array:
[Object, Object, Object, Object, Object, Object]

And each of these Object contains the next:
id: null
message: "hnjghj gjgk"
__proto__: Object

So, I want to just print message from all of them with:
<% @message_for.each do |message| %>

<%= message.message %>

<% end %>

How can I do it?
Answer: You have to parse a JSON object into Ruby hash first:
result_hash = JSON.parse(@message_for.to_json)
result_hash.map{|k,v| v if k == 'message'}.compact

Comment: It returns me html page with empty body part =/


How to determine a in r - in a function of relations

Question: I'm pretty stuck on the following question
$f$ on $\mathbb{R}$ given by $xfy\Leftrightarrow (y(2x-3)-3x=y(x^2-2x)-5x^3)$ is a function.
Let $g$ be the restriction of $f$ to $\mathbb{Z}^+$, implying $g(n) = f(n),\,n \in\mathbb{Z}^+$
Determine $a\in R\,$, so $g\in \Theta(n^a)$
Comment: If the question is solved, you indicate that by accepting an answer, not by changing the title to include the word solved.
Comment: Have you expressed $f(x)$ (by expressing $y$ in terms of $x$'s)?
Comment: In your last statement: "Determine $a \in R$...do you mean $a \in \mathbb{R}$?
Comment: @Berci: Could u eloborate it?
amWhy Yes :)
Comment: y=(-5x^3+5x)/(-x^2+4x-3) is that what u mean :)?
Comment: Noticed - thanks
Answer: Let's express $y=f(x)$:
$$(x^2-2x-2x+3)y=5x^3-3x \implies y =\frac{5x^3-3x}{x^2-4x+3} $$
So, $a=3-2=1$ by the leading exponents.
Update: Formally, you have to prove that there are constants $A,B>0$ such that
$An\le f(n)\le Bn\ $ (for $n\ge n_0$).
Comment: Sadly there isnt no further explanation for it.
So i simply have to look on the exponents, sounds kinda to simply but then again its only 1/5 of the solution
Comment: Ok. So, find 'Big Theta' in the following page, and use the definition given there: http://en.wikipedia.org/wiki/Big_O_notation


cloudera - Failed to execute command Start on service Accumulo 1.6

Question: I've been pulling my hair out trying to install accumulo on a cloudera quickstart VM (i've found quickstart to be anything but).  I'm attempting to install it via cloudera manager (which I thought would have been a lot more plug and play) however at step 5 when trying to Start the Accumulo service the process fails.  Digging into the logs I find that it has not been able to start the Master, Tracer, Tablet server, or Garbage Collector.  The Stderr for the master gives me the following:
++ hostname
+ HOST=quickstart.cloudera
+ '[' master = monitor -a '' = true ']'
+ exec /usr/lib/accumulo/bin/accumulo master --address quickstart.cloudera
grep: /var/run/cloudera-scm-agent/process/26-accumulo16-ACCUMULO16_MASTER/masters: No such file or directory
log4j:WARN No appenders could be found for logger (org.apache.accumulo.start.classloader.AccumuloClassLoader).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Uncaught exception: com/google/common/base/Preconditions
java.lang.NoClassDefFoundError: com/google/common/base/Preconditions
    at org.apache.hadoop.conf.Configuration$DeprecationDelta.<init>(Configuration.java:325)
    at org.apache.hadoop.conf.Configuration$DeprecationDelta.<init>(Configuration.java:338)
    at org.apache.hadoop.conf.Configuration.<clinit>(Configuration.java:420)
    at org.apache.hadoop.io.WritableComparator.<init>(WritableComparator.java:128)
    at org.apache.hadoop.io.WritableComparator.<init>(WritableComparator.java:116)
    at org.apache.hadoop.io.Text$Comparator.<init>(Text.java:360)
    at org.apache.hadoop.io.Text.<clinit>(Text.java:374)
    at org.apache.accumulo.server.master.Master.<clinit>(Master.java:192)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:270)
    at org.apache.accumulo.start.classloader.AccumuloClassLoader.loadClass(AccumuloClassLoader.java:378)
    at org.apache.accumulo.start.classloader.AccumuloClassLoader.loadClass(AccumuloClassLoader.java:385)
    at org.apache.accumulo.start.Main.main(Main.java:42)
Caused by: java.lang.ClassNotFoundException: com.google.common.base.Preconditions
    at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
    ... 13 more

Any help would be appreciated.  Unfortunately I don't speak much Java - im guessing i'm missing a crucial package however if that's the case im confused as to why this is installed as part of the accumulo set up (fyi this is a brand new cloudera.quickstart VM).
Comment: You need to have the guava libs in your path.  How to do that / why this isn't already done I can't help you with, but I've run across this type of stuff many times http://stackoverflow.com/questions/28317911/exception-in-thread-main-java-lang-noclassdeffounderror-com-google-common-bas
Comment: thanks, apologies but how do I add this to my path? do you mean the accumulo user path or is this the classpath.xml?
Comment: my current accumulo-site.xml has the following classpath  `general.classpaths$ACCUMULO_HOME/lib/[^.].*.jar,$HADOOP_CONF_DIR,$HADOOP_CLIENT_HOME/[^.](?!lf4j-log4j|uava|vro).*-[0-9a.]*.jar,$HADOOP_CLIENT_HOME/slf4j-log4j12.jar,$HADOOP_CLIENT_HOME/avro.jar,$HADOOP_CLIENT_HOME/[^.](?!ookeeper).*-[0-9.]*(?:-[^-]*)?-cdh.*.jar,$ZOOKEEPER_HOME/zookeeper.*-[0-9].*.jar,/usr/jars/guava-11.0.2.jar,/usr/lib/hadoop/lib/guava-11.0.2.jar
`
Answer: In regard to the services not starting; make sure that you have the Gateway role or some/any HDFS role assigned to your accumulo master, monitor, tracer and gc nodes.  I was having the same issue and once I realized that accumulo couldn't see HDFS I added the Gateway role.  I was then able to initialize accumulo and start the related master services.
You can check to see if accumulo can see the hadoop file system by running hdfs dfs -ls / on the accumulo master.  If you get an error saying

Warning: fs.defaultFS is not set when running 'ls' command

and it shows you the local file system, then you know that the accumulo master can't see HDFS and the necessary accumulo instance id.


Active directory account logging in from an unknown application or service

Question: I have a 2008 R2 AD domain, where there are repeated attempts to login by a user is no longer here. The password has been changed, so the failed attempts are expected, but what I don't know is where that account is trying to log in from. I know the name of the host from which the login attempt is coming, and I believe that it is a result of the user's account name being embedded in some application, which should have used the system account instead, but that is history.
What I am looking for is a way to scan the host in order to find the source of the login requests. They happen in groups and with frequency, so it is easy for me to locate the event in logs.
Any ideas ?
Answer: SysMon should be able to surface this information, including the executable image and parent image.  It would be recorded as an event Id 1, ProcessCreate.
https://technet.microsoft.com/en-us/sysinternals/sysmon
Comment: SysMon should definitely help determine the process.  As pure speculation, I'd bet that the login attempts are from a service or scheduled task. To check the services: Open services.msc and look for anything that has the user's name in the "Log On As" field. Stop that service and give it updated credentials if you want it to continue to run. Otherwise, disable it. Most user generated scheduled tasks will show up under "Task Scheduler Library" in Task Scheduler.


How to change MS-SSTP (RRAS) server port?

Question: I have a webservice on port 443 and 80 in IIS. I want run SSTP Server on port 8443. How can I change the default port (443) to 8443?
Answer: As long as you use IIS for web (and therefor system http.sys driver), you can keep using SSTP on port 443 as the system will allow port sharing and you don't need to change SSTP port.
System HTTP driver will redirect requests to specific application based on URIs. SSTP listens on a specific URI and does not interfere with IIS.
Comment: thanks, but i really need to change it
Answer: You officially can't, as SSTP is handled by http.sys in the kernel.
You should use IIS for hosting, IIS+ARR for any other webservices. Use IIS hostheaders (with or without ARR) and/or with SNI to use any other ports with SSL. This works perfect for 80 and 443. If you have to use other stuff (Apache, Tomcat ...) IIS SSL offloading is pretty fast, too. The only thing you should not do is using 443 natively, as it is already used natively by RRAS.
If you can't use hostheaders, please let us know why.
Anyway, there is a unsupported hack to change the MS-SSTP listener:

Get ownership (and write access) to this registry key:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\SstpSvc\Parameters\ConfigStore

Change ListenerPort to whatever you like

Restart RRAS

The MS-SSTP client is capable of using other ports than 443, just put the port in the hostname (like vpn.mycompany.com:8443).
Be aware that this is not a supported configuration, will expose your machine to various migration- and upgrade issues and may (read: will) be overwritten by Cumulative Update (and some other updates, too).


UIView Rotation

Question: Hello All I want to rotate UIView on single finger touch and it still rotate untill finger moves on screen of iPhone and it stops rotation when I stop the finger moving or remove it from screen.
Thanks in Advance.
Answer: Try similar code

-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.2];
    CGAffineTransform rr=CGAffineTransformMakeRotation(5);
    yourView.transform=CGAffineTransformConcat(yourView.transform, rr);
    [UIView commitAnimations];
}

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    [self touchesBegan:touches withEvent:event];
}
Answer: Pradeepa's code is nice, however, that animation system is getting deprecated (if not already). Try something like this instead:
<code>CABasicAnimation *rotation = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
double startRotationValue = [[[yourView.layer presentationLayer] valueForKeyPath:@"transform.rotation.z"] doubleValue];
rotation.fromValue = [NSNumber numberWithDouble:startRotationValue];
rotation.toValue = [NSNumber numberWithDouble:startRotationValue+5];
rotation.duration = 0.2;
[yourView.layer addAnimation:rotation forKey:@"rotating"];
</code>
I took Pradeepa's numbers to make them comparable, but i believe Apple prefers you using this or block-based animation instead of the old system.
Answer: rotating a view on touch may help you

UIView Rotation


Find word from dictionary in string

Question: I am working a on problem in my project.
I have a DB with column where I have stored types like "15 mins break" or "30 min free time"
I want to make another column with category.
My categories are stored in dictionary:
{ "short":["10","5","15","10min","5min","15min","shorter"],
"middle":["20","25","30","35","20min","25min","30min","35min"],
"long":["40","45","50","55","60","40min","45min","50min","55min","60min"]}

Any idea how can I assign category to types using python ?
I mean just that part to find similarity with word in dictionary ?
my code so far
...calling sql select
for i, index in rows():
    type = index[0]
    if (any of words from dictionary) is in type:
        category = (name of category, for example "short")
        update in sql
        ...

THx
Comment: I do not really get what you want. Can you provide an example with *input* and *output*?
Comment: Do you know the algorithm you want to apply ? If not, this is not the correct place to ask. If so, you should specify it in your question.
Comment: I added pseudocode of my code to better understand my problem.
Answer: You want to find out if any of the category markers are in the break description. Suppose s1 and s2 are you sample descriptions, and d is your dictionary:
s1 = "15 mins break"
s2 = "30 min free time"
s3 = "something5something"

Then the following expression evaluates to their category (the purpose of re.findall() is to tokenize the text; replace the regular expression with whatever is suitable for your project.)
[cat for cat in d if any(marker in re.findall(r'[a-z0-9]+',s1) for marker in d[cat])]
#['short']

[cat for cat in d if any(marker in re.findall(r'[a-z0-9]+',s2) for marker in d[cat])]
#['middle']

[cat for cat in d if any(marker in re.findall(r'[a-z0-9]+',s3) for marker in d[cat])]
#[]

This assumes that all strings are in the lower case.
Comment: I tried something like this, but it gives me false positive answers.
For example when i look in string like: `s = "something5something"`
Comment: Then you need some sort of a tokenizer, e.g., `re.findall()` (see updated answer) or `nltk.world_tokenize()`.
Comment: Nice thank you, it works.
I am going to study how and why it works.

Ty
Comment: How can I figure out if it is "short", "long" or another key ?
Comment: It's the value of the expression.
Comment: My bad didnt realize, it is too late, Thanks

Find word from dictionary in string


VSFTPD does not allow upload with virtual users

Question: I am attempting to setup VSFTPD with virtual users on a server running Ubuntu 12.04. I have configured the server to allow for virtual users to login, but I am having trouble getting it to allow uploads. My vsftpd.conf is as follows:
listen=YES
anonymous_enable=NO
local_enable=YES
write_enable=YES
local_umask=022
anon_upload_enable=YES
dirmessage_enable=YES
use_localtime=YES
xferlog_enable=YES
connect_from_port_20=YES

chroot_local_user=YES
virtual_use_local_privs=YES
guest_enable=YES
guest_username=virtual
user_sub_token=$USER
local_root=/var/www/$USER
hide_ids=YES

secure_chroot_dir=/var/run/vsftpd/empty
pam_service_name=vsftpd
rsa_cert_file=/etc/ssl/private/vsftpd.pem

/etc/pam.d/vsftpd contains:
auth required pam_pwdfile.so pwdfile /etc/vsftpd.passwd crypt=hash
account required pam_permit.so crypt=hash

I have two virtual users set up, one of which has the same name as a local user. They each have a directory in /var/www/ owned by 'virtual'. As I understand it, when a virtual user logs in this way they will appear to the system as the user virtual. Using this configuration user can log on, but cannot upload files. The error given in /var/log/vsftpd.log is:
Tue Nov 20 19:49:00 2012 [pid 2] CONNECT: Client "188.8.131.52"
Tue Nov 20 19:49:07 2012 [pid 1] [zac] OK LOGIN: Client "18.104.22.168"
Tue Nov 20 19:49:11 2012 [pid 2] CONNECT: Client "18.104.22.168"
Tue Nov 20 19:49:11 2012 [pid 1] [zac] OK LOGIN: Client "220.127.116.11"
Tue Nov 20 19:49:11 2012 [pid 3] [zac] FAIL CHMOD: Client "184.108.40.206", "/test.ppm 644"

I have tried changing the permissions of these directories in all sorts of ways, but nothing seem to work. I have a feeling that it is something simple related to permissions. Any ideas?
Comment: Could you provide ls -la in /var/www and /var/www/$USER ?
Answer: The problem may caused by directory permission, I've vsftpd that worked for me as below:
anonymous_enable=NO
local_enable=YES
write_enable=YES
local_umask=022
dirmessage_enable=YES
xferlog_enable=YES
connect_from_port_20=YES
chown_uploads=YES
xferlog_file=/var/log/vsftpd.log
xferlog_std_format=YES
ftpd_banner=Welcome to blah FTP service.
ls_recurse_enable=NO
listen=YES
pam_service_name=vsftpd
userlist_enable=YES
tcp_wrappers=YES
Comment: This doesn't look like it's set up for virtual users. Is it?
Answer: Does the directory exist?
 /var/www/zac

and does this directory belong to zac?
try:
 mkdir -p /var/www/zac; chown zac /var/www/zac; chmod 600 /var/www/zac;

and upload the file again
Comment: Being that `zac` is a virtual user it's unlikely that the directory is owned by `zac` since it's not an actual user on the server.
Comment: The directory should be owned & readable by virtual. Due to chroot, it is required that it is *not* writable. You need to create a read-writable subdirectory within (owned by virtual) to be able to upload therein.
Answer: VSFTP does not allow uploads for virtual users you need to create local user or you can use single user mapped to all virtual users in that case you cannot control user wise permission
check this link - https://gist.github.com/stas/315765
Answer: Try this for virtual users to enable write access:
virtual_use_local_privs=YES

Comment: If you *carefully* read the question again, you will notice that this line is already part of the OPs config file.
Comment: You are right...


Python on Arm, Illegal Instructions

Question: I am trying to compile Python 3.2 for an ARM920T (architecture 4T) but I am getting some strange errors.
I am compiling Python inside a Scratchbox environment, configured to use the following compiler: "gcc version 4.3.3 (Sourcery G++ Lite 2009q1-203)" which is an arm cross compiler.
When compiling I have made sure to set the -march=armv4t architecture flag, in the following environment variables: CFLAGS, CPPFLAGS, SBOX_EXTRA_COMPILER_FLAGS.
It compiles fine in scratchbox, and I am able to run the python interpreter with the scratchbox arm emulator.
When I move it to my ARM920T however, I get an Illegal Instruction error immeadiately after running the python exe.
A core dump yeilds the following output:
Program terminated with signal 4, Illegal instruction.
#0 0x00138810 in __aeabi_dadd ()

And the first few lines of the back-trace:
#0  0x00138810 in __aeabi_dadd ()
#1  0x001134f4 in PyLong_FromString (str=0x402de300 "3644798167", pend=0x0, base=10) at Objects/longobject.c:2001
#2  0x00132478 in parsenumber (s=<value optimized out>, c=<value optimized out>) at Python/ast.c:3189
#3  ast_for_atom (n=<value optimized out>, c=<value optimized out>) at Python/ast.c:1396
#4  ast_for_power (n=<value optimized out>, c=<value optimized out>) at Python/ast.c:1726
#5  ast_for_expr (c=0xbeaf7f50, n=0x402f5b78) at Python/ast.c:191

As far as I have been able to research, the __aeabi_dadd call is a library call for adding two floating point numbers (Double Add).
I looked up the python code which the backtrace reports is causing the error (longobject.c line 2001):
if (log_base_BASE[base] == 0.0) {
            twodigits convmax = base;
            int i = 1;

            log_base_BASE[base] = (log((double)base) /        // Line 2001
                                   log((double)PyLong_BASE));
            for (;;) {
                twodigits next = convmax * base;
                if (next > PyLong_BASE)
                    break;
                convmax = next;
                ++i;
            }

I dont really see why this code should cause any errors. I tried making a small C++ program which added/subtracted/divided e.t.c a lot of doubles, like in the code above, and it ran fine on the device.

Any help would be much appreciated. The only things I can think of is that perhaps the wrong floating point library is being compiled into the exe. The ARM920T does not have hardware floating point support as far as I could tell from Google.
Another cause could be alignment errors. When compiling Python with the -Wcast-align flag, it does report a few casting warnings. The ARM doesn't like it when certain data-types are not aligned at even addresses in memory. /proc/cpu/alignment does not report anything however.
Sorry for the wall of text, thanks if you read this far :)
Answer: I found the solution!
I made a file-dump of everything spewed out on the console during the make call, and I noticed that a few calls to gcc did not contain the -march=armv4t option.
I noticed that I had spelled the SBOX_EXTRA_COMPILER_FLAGS wrong. It should be SBOX_EXTRA_COMPILER_ARGS. With that set, and CFLAGS set to -march=armv4t Python now successfully builds and runs without illegal instructions.
Thanks Leo, for pointing me in the right direction!
Answer: It sounds like you are linking to some library that is compiled for a higher architecture than the one on the device. We had the same problem when compiling with CodeSourcery for a device with a ARMv4 CPU. Apparantly the CodeSourcery libraries were compiled for ARMv5. It might be the floating point library like you said, or it might be some other library. Can you find the place in the build-script where the file in question is being compiled and check exactly which libraries are used?
Comment: Great! This is in the right direction! I managed to do a disassembly in the gnu debugger, to see what exactly the illegal instruction was. It turns out that it is a CLZ instruction, which is executed in the aeabi_* functions. According to the ARM documentations, the CLZ instruction is an ARM5 and above instruction. That explains the error. Now All I need to do is track down where this instruction is generated, which is a bit more complicated. I checked that none of the libraries being linked in contain this instruction.

Python on Arm, Illegal Instructions


How to send notification when node similar to flagged one is posted

Question: I want to send notifications to the user when a new node similar to one he has flagged is posted.
Comment: What do you mean by similar nodes ? Based on what condition you are meaning it similar ?
Comment: By similar i mean if the new node has same values as the flagged one by the user e.g city, location, price.
Answer: You need to user RULES module to achieve this functionality. Drupal flag module has full integration with rules modules.
By creating a rule saying condition is "Node is flagged" add an action saying "Send email to author of node."
Comment: Your answer does not explain how to identify similar types of nodes.
Comment: Hi, I want to send mail after comparing the values of new node to the node that has been flagged by the user e.g city, location, price. I tried to to it with Data comparison in rules but dont see relative token values for flagged node.


Nested JSON with objects and arrays, find value

Question: Im building a React app and I have a quite complex JSON file where I need to find and output certain values of an object in an array.
Im trying to output all my people from my JSON, they look something like this:
people: [
    {
        "id": 1,
        "email": "firstname.lastname@example.com",
        "address": [
            {
                "street": "Kulas Light",
                "type": "house",
                "attribute": {
                    "sketch": "sketch.jpg",
                    "photo": "photo.jpg"
                }
            },
            {
                "street": "Lorem Ipsum",
                "type": "apartment",
                "attribute": {
                    "sketch": "sketch.jpg",
                    "photo": "photo.jpg"
                }
            }
        ]
    }
]

I have no problem to output the email, doing it like so:
var App = React.createClass({

getInitialState: function () {
    return {
        results: {}
    }
},
componentDidMount() {
    fetch(REQUEST_URL) // fetch from API, returns JSON
    .then(res => res.json())
    .then(data => {this.setState(
        { results: data.people}
        );
    })
},
renderResult : function(key){
    return <Result key={key} index={key} details={this.state.results[key]}/>
},
render : function() {
    return (

            {Object.keys(this.state.results).map(this.renderResult)}

    )
}
});

var Result = React.createClass({
render : function() {
    return (

          {this.props.details.email}

    )
}
});

ReactDOM.render(App, document.querySelector('#app'));

However, now I need to output "photo" but only for "type": "house". I tried this but no luck, well aware that this is way off. Im quite new to handling JSON data and React and Google hasn't helped me even after a few hours of trying to solve this.
Answer:
The .address property isn't an object but an array of objects so
  .type is not available directly on .address:

this.state.results.people.address.type
//  .type property doesn't exist on array

Solution:
You can use Array.prototype.filter on .address to obtain an array of objects that have a property type whose value is "house":
var houseAddresses = this.state.results.people.address.filter(function(value){
  return value.type === "house";
});

Here, houseAddress will be an array of objects whose type value is 'house".
You can then loop through the array to create the relevant JSX using for, Array#forEach or Array#map.  The following example uses Array#map:
const houseImgTags = houseAddresses.map(function(house, index){
  return (

  );
});

(A key was added here in case there are more than one instance of a house object)
Comment: Ah i see what you are doing, but I cant really get it to work. There are errors while trying to compiling the code.

This logs all objects:

`var houseAddresses = this.props.details.address;`

This causes compiling error:

 `var houseAddresses = this.props.details.address.filter((value){
   value.type === "house";
  });`
Comment: @dilla: needs the `function` keyword when declaring the function passed to filter: `this.state.results.people.address.filter(function(value){
      return value.type === "house";
    });`
Comment: Ah that fixed it, cool and thanks for your help man! Im not fully there though, cant manage to implement it in my component that renders all info such as email and street. If you have time and want to, id just want to ask if you could check my code privately? It's a about 70 rows.
Comment: Is there a reason you removed the chosen answer/did not up-vote?
Comment: Sorry, my mistake!
Comment: If you have time, wanna help me implement your solution in my original code (edited original post)
Answer: You can simply write.

Basically this would compare address.type is house or not,then return the result corresponded.
Comment: There is no `type` property on `this.states.results.address`, **it's an array that contains objects that do have the `type` property**


H2 - can't write to database in 'after insert' trigger

Question: I am 300% sure the id field is autogenerated just fine, as this was perfectly working before adding the trigger.
I have an entity which extends a base entity with an autogenerated id field:
@MappedSuperclass
public abstract class BaseEntity {

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;

I have registered a trigger for that entity in H2:
create trigger after_subtest_result_insert after insert on subtest_result
for each row call "package.path.SubtestResultTrigger";

The trigger itself:
public class SubtestResultTrigger implements Trigger {

  private static final int EQUIPMENT_ID = 5;

  @Override
  public void init(Connection conn, String schemaName, String triggerName,
      String tableName, boolean before, int type) {
  }

  @Override
  public void fire(Connection conn, Object[] oldRow, Object[] newRow)
      throws SQLException {
    try (PreparedStatement ps = conn.prepareStatement(
        "update equipment e set " +
        (...)
       )
    ) {
      ps.setObject(1, newRow[EQUIPMENT_ID]);
      ps.setObject(2, newRow[EQUIPMENT_ID]);

      ps.executeUpdate();
    }
  }

  @Override
  public void close() throws SQLException {
  }

  @Override
  public void remove() throws SQLException {
  }
}

When I uncomment ps.executeUpdate();, it breaks with HibernateException: The database returned no natively generated identity value.
It seems like somewhere under the hood H2 gets the generated keys from the last prepared statement that was executed, rather than the first one, since everything is fine when the update in the trigger is not run. Is there any fix or workaround for this?
EDIT: I realize what's happening, I still have zero idea how to work around it. Digging into the code, the H2 driver has a session-wide GeneratedKeys object, that is cleared every time the keys are requested, and presumably overwritten every time a PreparedStatement is executed in the same session. This makes it literally impossible to have a post insert trigger that writes anything at all to the database. I'll write a bug report, in the meantime I'll have to either not use triggers (hard in this context, I'm already only resorting to triggers because every alternative is even worse) or just ditch H2 entirely, which I'm not sure I can since the stack is out of my hands.
Answer: I had the same problem but found a different workaround, one you might like better. Like you, I'm using Hibernate, and Spring.
I was able to make the H2 Trigger work fully, but the key was to use Hibernate within the Trigger for all of its database manipulation. Here's how I did it:

Used this technique to create a static method from which to access the Spring ApplicationContext. I did it this way:
@Service
public class SpringContextHook {

    private static ApplicationContext context;

    @Autowired
    public SpringContextHook(ApplicationContext inContext) {
        context = inContext;
    }

    public static ApplicationContext getContext() {
        return context;
    }
}

Inside the H2 Trigger, I get the currently active Session by digging around a little in Spring JPA:
private Session getHibernateSession() {
    ApplicationContext context = SpringContextHook.getContext();
    EntityManagerFactory emf = (EntityManagerFactory) context.getBean("entityManagerFactory");
    EntityManager entityManager = SharedEntityManagerCreator.createSharedEntityManager(emf, null, true);
    return entityManager.unwrap(Session.class);
}

Use Hibernate @Entity objects to perform the update, using getHibernateSession().save(entity) to save them.
I had to make sure to not take action on the Hibernate object that is the reason the trigger was fired.

I can give more details if you're interested in pursuing this strategy and need more help.
Comment: It worked! I changed the query from an update to a select, fetched the entities and persisted them with the changes. I'm editing my answer. Thank you!
Answer: EDIT: I went with arogos's solution, which is better, afterwards. I'm leaving this here in case someone needs to do a more esoteric update where Hibernate won't cut it.
While I never managed to find a true solution, I found a workaround in the context of spring boot, which works as long as you need to or don't mind applying the trigger also on update. It has many of the downsides that forced me to the last resort of using triggers in the first place, but at least this minimizes the scope of the issue to only H2 and only inserts, in a project that must support two other DBMSes where the trigger approach works just fine.
I basically created an update trigger, a post insert handler that forces a bogus update if the DBMS is H2, and a comment reminding that every insert operation that does not come from a REST endpoint request must invoke the handler manually. This behaviour was in fact the reason I endep up resorting to triggers, after trying JPA's @PostInsert and @PostUpdate and getting errors which stem from attempting to read from the table you just wrote to - my understanding of it was that there's a reading lock so your @PostInsert/@PostUpdate cannot read from the table in any way.
The trigger in my src/main/resources/data-h2.sql:
-- creating schema changes in data file because schema.sql overwrites JPA schema intialization
-- https://github.com/spring-projects/spring-boot/issues/9048
create trigger after_subtest_result_update after update on subtest_result
for each row call "com.siemens.mftool.dialects.H2SubtestResultTrigger";

The handler:
package com.siemens.mftool.entity.handlers;

import com.siemens.mftool.entity.SubtestResult;
import com.siemens.mftool.repositories.SubtestResultRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.rest.core.annotation.HandleAfterCreate;
import org.springframework.data.rest.core.annotation.RepositoryEventHandler;
import org.springframework.stereotype.Component;

/** workaround for H2 post insert triggers not working because of improperly
 *  handled generated keys
 *  must be called manually if the repo invocation does not come from a REST
 *  request
 */
@Component
@RepositoryEventHandler(SubtestResult.class)
public class H2WorkaroundSubtestResultHandler {

  private final SubtestResultRepository subtestResultRepository;

  @Value("${spring.datasource.platform}")
  private String platform;

  @Autowired
  public H2WorkaroundSubtestResultHandler(SubtestResultRepository subtestResultRepository) {
    this.subtestResultRepository = subtestResultRepository;
  }

  @HandleAfterCreate
  public void handleAfterCreate(final SubtestResult subtestResult) {
    if("h2".equals(platform)) {
      subtestResultRepository.h2Workaround(subtestResult);
    }
  }
}

The repository method:
  // force an update to the newly inserted subtestResult so the
  // after-update trigger is triggered
  @Modifying
  @Query(nativeQuery = true, value =
      "update subtest_result " +
      "set id = :#{ #subtestResult.id } " +
      "where id = :#{ #subtestResult.id } ")
  void h2Workaround(SubtestResult subtestResult);

How the call looks when done programatically:
h2WorkaroundSubtestResultHandler.handleAfterCreate(subtestResult);

Still a pain point, but it's a least a pain point rather a whole pain line.


TcpClient C# Windows Form como fechar e abrir a mesma conexão

Question: Estou desenvolvendo uma aplicação Windows Form C# e estou usando TcpClient para realizar comunicação dentro da minha rede interna, em alguns momentos necessito fechar uma conexão existente e após alguns minutos reabrir esta conexão, mas estou tendo problemas ao realizar este procedimento.
Primeiramente inicializo o TcpClient.
TcpClient clientSocket = new TcpClient();
clientSocket.Connect(textBox1.Text, int.Parse(textBox2.Text));

Em determinado momento desejo fechar esta conexão, tentei o Dispose() e Close().
clientSocket.Dispose();
clientSocket.Close();

E depois desejo em um momento reconectar realizando o seguintes comandos
 if (!clientSocket.Connected)//Verifico se a conexão esta ativa
 {
      clientSocket = new TcpClient();//Estáncio novamente clientSocket
      clientSocket.Connect(textBox1.Text, int.Parse(textBox2.Text));//Mas dá exceção nesta linha.
 }

Com todos procedimentos adotados acima é retornado um Exception
System.Net.Sockets.SocketException: 'Uma operação de soquete foi tentada em um host inacessível xx.xx.x.xx:8080', na linha abaixo
clientSocket.Connect(textBox1.Text, int.Parse(textBox2.Text));

Isto quer dizer que a conexão realmente fica instanciada não deixando realiza uma nova conexão.
Como realizar este procedimento, para que tenha a liberdade de realizar estes procedimentos ?
Answer: O erro é devido a não ter correctamente desconectado a conexão anterior e fazer uma nova ligação usando a mesma porta.
Para fechar a conexão use
NetworkStream stream = clientSocket.GetStream();
stream.close();
clientSocket.close();

Quando quiser conectar novamente crie uma nova instância e use o Connect(....) dessa instância.


Best modeling technique for predicting waiting times?

Question: I'm exploring some Stack Overflow data. Amongst other variables, I have variables for the time questions were asked and the time they were answered.
I'm interested in predicting how long a questioner might expect to wait before their question is answered, based on the programming language.
I have 26k observations divided between 10 languages. Format-wise, I can format the time differentials between question asked and answered as integers, and group the data by programming language as neccesary.
The output of my model would ideally be very simple: just an integer/float representing the number in minutes a user might typically expect to wait before their question is answered.
What would be the most suitable modelling / machine learning technique for this (ideally in Python)? I've explored various GLM types in StatsModels but can't find something that's clearly suitable. As the data are neither continuous nor linear I don't think OLS is right. The data's obviously not binary either, so logistic regression's out. As I'm just dealing with time differentials as integers, I don't think this requires a Time Series analysis model either.
For the record this is just a personal project based on a publicly available Stack Overflow data dump. I have no affiliation with Stack Overflow.
Comment: Googling for ["survival analysis"](https://en.wikipedia.org/wiki/Survival_analysis) would be a good start.
Comment: The best solutions discussed here are not from machine learning, so consider changing the title to omit machine learning.
Answer: Waiting times can often be modelled by the exponential distribution, but this better describes the time between two events of the same type, e.g. it would probably nicely model the time between two subsequent questions.
The time to answer has some more complex properties:

There is a real chance of it never being answered
There will be some delay before an answer can realistically appear
Complex questions take longer (maybe approximately captured by #characters in question?)

For these reasons the exponential distribution won't be a perfect fit. The point about the delay is the most serious defect.
Survival analysis might be another option, but also hasn't got the "waiting" time for people to read and understand the question, before they can answer.
Other concerns include dependence on time of day and day of week. There could be spam bots that answers the question very quickly.
Since this is exploratory anyway, I would start by plotting the data. Start with some histograms of the time until an answer, look at how many never get answered. Go the same plots by time of day and day of week. See if there are differences. Then plan from there.
Comment: (1) An exponential distribution *can* be fitted to censored time-to-event data. But, probably ruling out an exponential model more decisively than the necessary initial delay before an answer can first appear, it's clear that the hazard's far from constant over time - that a day-old question's much more likely to be answered in the next hour than a fortnight-old question. (2) Kaplan-Meir survival plots would be more suitable for exploratory analysis than histograms, allowing censored times to be included. (3) The median time to answer for each language could be easily calculated if more ...
Comment: ... than half the questions concerning that language have been answered, & would be perhaps good enough for the OP's purposes.
Comment: @Scortchi 1. I agree, the delay is the more serious defect. I should have highlighted that; I think that I did not think about the non-answered question as censoring, because I assumed that they will never be answered. 2. I was thinking about histograms with an artificial bin to the right for non-answered questions. But there is probably more than one option here. The survival plots are certainly a good option as well. 3. Maybe, but depends on how strong the time effects are. I also suspect there will be a language-time interaction.
Comment: @Scortchi More on three: I think an English language question will get quicker answer at unusual local times (i.e. 01:00 a.m) since other people around the globe can and will answer in English. This might not be the case for other languages, but Spanish should get faster answers than German.
Comment: (1) No, I think the non-constant hazard's likely the more serious, & obvious, defect; the delay might not greatly impact the model's fit if it's small relative to the average waiting time. It's cleaner to think of unanswered questions as having a censored time-to-answer because it spares you having to decide a cut-off time between not-answered-yet & never-will-be-answered, which will always be at least a little unsatisfactory. (2) Trouble is, differences in bin frequencies may reflect changes in the frequency of questions over time. (3) The q. refers to  *programming* languages.
Comment: It's interesting to speculate how the time of asking might affect the waiting time. It'll probably change the *shape* of the survival curve a bit if there are peak times for answering. Asking at a quiet time means you wait longer for more potential answerers to have visited the site, but on the other hand your question'll stay on the front page for longer.
Answer: I have accepted an answer above and am only writing this as an answer because I think my research could be beneficial to other Python users.
The comments and answers above helpfully directed me towards Survival Analysis. After exploring the modelling options in StatsModels, I then discovered the library Lifelines by Cameron Davidson Pilon (@Cam.Davidson.Pilon).
I can thoroughly recommend Lifelines to anyone looking to do duration-based analysis in Python. It's excellent in many ways. I particularly like the way it addresses - both theoretically and practically -  the concept of Censorship. Given how elegant and effective the library is, and how broad the applications of Survival Analysis are, I'm somewhat surprised Lifelines isn't better known.
I can also recommend watching this introductory talk. It got me up and running with Lifelines in no time.
Comment: Note that in other languages such as R, survival analysis is thoroughly known and used.  The survival package in R is the gold standard.
Comment: @FrankHarrell - Yes, I actually started out with R so to speak, and knew of the existence of survival analysis. I'd just never used it and thus it wasn't on my radar. But I'm very happy to have found this Python implementation.


Ranking computed variables

Question: I am using the Cigarette dataset from the Ecdat package. I need to find the median annual rank of number of packs/capita sold between 1985 and 1995. As well as the lowest, whereby higher rank is defined as having a grater number of packs/capita.
I have tried to filter based on year and compute a median packs variable using median(packpc) and arrange by that mutated variable but continue to get error messages.
Any suggestions?
Comment: What is "the median annual rank"?  If you have 100 observations and rank them on anything, the median is 50.
Answer: What you are looking for is summarize:
library(Ecdat)
library(dplyr)
Cigarette %>%
  filter(year>=1985, year<=1995) %>%
  summarise(min=min(packpc), median=median(packpc), max=max(packpc))
#>       min   median     max
#> 1 49.2722 105.9096 197.994

As you put the dplyr tag to this question, you might want to check out tutorials on this package.
PS: If this is your homework, you should state it clearly so we don't just give out the answer.
Answer: I guess the idea is to get the states' ranks for each year and then find the median and minimum of those ranks over the years.
Since the dataset only includes years 1985 to 1995, there is no need for filtering.
So I came up with this rather ugly solution:
ranks_perYear <- aggregate(packpc ~ year, Cigarette, rank)$packpc
colnames(ranks_perYear) <- levels(Cigarette$state)
medianRank <- apply(ranks_perYear, 2, median)
minRank <- apply(ranks_perYear, 2, min)

I am actually not entirely sure whether the states are assigned correctly here. Maybe the dataset has to be sorted by state (e.g., dplyr::arrange(Cigarette, state)) beforehand.

Ranking computed variables


How to solve System.ArgumentException: An item with the same key has already been added in mvc 3?

Question: i created ViewModel to test this answer : How to fill ViewModel which has List<T> property after clicking submit button mvc 3?
i need checkboxlist look please WeeklyModel.Also WeeklyViewModel. i want to list alldoays in checkboxes. Nut my error below . it is stupid error. i can not understand reson to solve how to solve it? thanks...
Look please helpful ( what i need artcile) article : When do I use View Models, Partials, Templates and handle child bindings with MVC 3
Models:

   public class WeeklyModel

        {
            public string Name { get; set; }
            public string Value { get; set; }
            public bool IsChecked { get; set; }
        }

       public class WeeklyViewModel
        {
            public IEnumerable<WeeklyModel> Settings { get; set; }
            public WeeklyViewModel()
            {
                Settings = new List<WeeklyModel>();
            }

        }

Controller:

 public ActionResult CreateWeekly()
       {
           var model = new WeeklyViewModel();
            List<WeeklyModel> li = new List<WeeklyModel>();
            li.Add( new WeeklyModel(){ Name="Monday", Value="mon", IsChecked=false});
            model.Settings = li;
               return View(model);
       }
       [HttpPost]
        public ActionResult CreateWeekly( WeeklyViewModel weekly)
       {

           return View("CreateWeekly", weekly);
       }

i created Views/Trigger/EditorTemplates/WeeklyModels.aspx :

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/ChildSite.Master" Inherits="System.Web.Mvc.ViewPage<GenSystem.Models.WeeklyModel>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">

</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<%:Html.CheckBoxFor(m=>m.IsChecked) %>
<%:Html.LabelFor(m=>m.IsChecked,Model.Name) %>
<%:Html.HiddenFor(m=>m.Name) %>
<%:Html.HiddenFor(m=>m.Value) %>

</asp:Content>

View :

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/ChildSite.Master" Inherits="System.Web.Mvc.ViewPage<GenSystem.Models.WeeklyViewModel>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    CreateWeekly
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

<%

    using (Html.BeginForm())
    {
          %>

     <%:Html.EditorFor(m => m.Settings)%>

       <input value="GenerateForWeekly" name="submitButton" type="submit" />
          <%} %>
</asp:Content>

How to solve this Error:
System.ArgumentException: An item with the same key has already been added.
at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource)
at System.Collections.Generic.Dictionary2.Insert(TKey key, TValue value, Boolean add)
at System.Collections.Generic.Dictionary2.Add(TKey key, TValue value)
at Transformer.NET.Token.ParseAnchors()
at Transformer.NET.TextTransformer.Parse(List1 tokensType, Dictionary2 variables)
at Transformer.NET.TextTransformer.Transform(List1 tokensType, Dictionary2 variables)
at Transformer.NET.TextTransformer.Transform(List`1 tokensType)
at Transformer.NET.TextTransformer.Transform()
at Ext.Net.ExtNetTransformer.Transform(String text)
at Ext.Net.InitScriptFilter.Transform()
at Ext.Net.InitScriptFilter.Flush()
at System.Web.HttpWriter.Filter(Boolean finalFiltering)
at System.Web.HttpResponse.FilterOutput()
at System.Web.HttpApplication.CallFilterExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
Answer: Editor templates should be .ascx controls, not .aspx pages. Also your file is wrongly named. It is named WeeklyModels.aspx but the correct name is WeeklyModel.ascx (without s) because your class is called WeeklyModel and not WeeklyModels.
So inside ~/Views/Shared/EditorTemplates/WeeklyModel.ascx you could put the following:
<%@ Control
    Language="C#"
    Inherits="System.Web.Mvc.ViewUserControl<GenSystem.Models.WeeklyModels>"
%>
<%= Html.CheckBoxFor(m => m.IsChecked) %>
<%= Html.LabelFor(m => m.IsChecked, Model.Name) %>
<%= Html.HiddenFor(m => m.Name) %>
<%= Html.HiddenFor(m => m.Value) %>

and inside your main view CreateWeekly.aspx:
<%@ Page
    Title=""
    Language="C#"
    MasterPageFile="~/Views/Shared/ChildSite.Master"
    Inherits="System.Web.Mvc.ViewPage<GenSystem.Models.WeeklyViewModel>"
%>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    CreateWeekly
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <% using (Html.BeginForm()) { %>

            <%= Html.EditorFor(m => m.Settings) %>

        <input value="GenerateForWeekly" name="submitButton" type="submit" />
    <% } %>
</asp:Content>

Comment: thanks working but a little bit question: <%@ Control  Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
 why drawing underline blue and say : Statement cannot appear outside of method body /multiline lambda
Comment: Thanks again.This ascx not underline blue: <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="WebUserControl1.ascx.cs" Inherits="GenSystem.Views.Shared.EditorTemplates.WebUserControl1" %>


Vue.js: como formatar um valor em um v-model?

Question: Estou com o seguinte problema, eu preciso formatar um valor de um input, diretamente quando o usuário vai preenchendo o campo (@keypress ou @input).
Quando eu utilizo o método para formatar fora do input ele funciona, porém se eu tentar utilizar com o v-model acredito que ele conflite os valores.
Qual seria uma alternativa para essa questão?
Esse é o método:
formatPrice(value) {
      let val = (value / 1).toFixed(2).replace(".", ",");
      return val.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");
    }

Essa é a chamada:
    {{ formatPrice(valorPrecoImovel) }}
      <input class="ipt-precoimovel" type="text" v-model="valorPrecoImovel" v-on:keypress="isNumber($event); formatPrice;" id="precoImovel">

Eu não consigo chamar o método dentro do v-model, por exemplo:
v-model="formatPrice(valorPrecoImovel)"

Comment: Queres formatar o valor dentro do input ou só o que está no template dentro de `{{ }}`?
Comment: o valor dentro do input
Answer: v-model é apenas para atribuição. Você não vai conseguir formatar os resultados da forma que você chamou v-model="formatPrice(valorPrecoImovel)" pois não se trata de uma expressão de atribuição.
O que eu sugiro para você é deixar o v-model livre para definir os valores e formatá-lo através de um callback em @input.

window.addEventListener('load', function () {

  new Vue({
   el: "#app",
   data: {
       meu_valor: 0
   },
   methods: {
    somenteNumeros: function (valor) {
      return (valor + '').replace(/\D+/g, '');
    }
   }
  })

})

<input type="text" @input="meu_valor = somenteNumeros(meu_valor)" v-model="meu_valor">

{{ meu_valor }}

Answer: O que queres fazer tem alguma complexidade pois combinas o v-model com a formatação do valor do input que o utilizador está a inserir.
Podes fazer isso usando um valor computed e usando setters e getters para ter mais controlo sobre o seu valor. Combinando isso com uma variável/propriedade interna meu_valor podes fazer o que procuras.
Fica um aspeto por tratar (que creio estar fora do escopo da pergunta) que é o posicionamento do cursor quando se escreve.
Uma sugestão da primeira parte (que descreves na pergunta) seria:

new Vue({
  el: "#app",
  data: {
    meu_valor: '0,00'
  },
  computed: {
    valorPrecoImovel: {
      // getter
      get: function() {
        return this.meu_valor;
      },
      // setter
      set: function(newValue) {
        this.meu_valor = this.formatPrice(newValue);
      }
    }
  },
  methods: {
    formatPrice(value) {
      const val = Number(value.replace(",", "."));
      if (!val) return '0,00';
      const valueString = val.toFixed(2).replace(".", ",");
      return valueString.replace(/\B(?=(\d{3})+(?!\d))/g, ".");
    }
  }
})

  <input class="ipt-precoimovel" type="text" v-model="valorPrecoImovel" ref="precoImovel" id="precoImovel">


Rspec problems with namespaced controllers

Question: I am having trouble testing my a few controllers using Rspec, especially those that use namespaces in their routes. Does anyone have an idea for why this is happening and how I can correct it? It's driving me crazy.
Here is my error.
Failure/Error: get 'show'
ActionController::RoutingError:
No route matches {:controller=>"community/vendors", :action=>"show"}
Here is my controller.
class Community::VendorsController < ApplicationController
  def show
    @vendor = Vendor.find_by_uuid(params[:uuid])
    render :file => "#{Rails.root}/public/404.html",  :status => 404 if @vendor.nil?
  end
end

Here is my spec.
describe Community::VendorsController do
  let(:vendor){FactoryGirl.create(:vendor)}
  before(:each) do
    @user = FactoryGirl.create(:vendor_single_user)
    sign_in @user
  end

  it 'should return 404 if no vendor found' do
    Vendor.stub(:find_by_uuid => nil)
    get 'show'
    response[:status].should == 404
  end
end

Here are the routes.
  namespace :community do
    get  ':uuid/intake' => 'vendors#show'
    put ':uuid/intake/' => 'vendors#update'
    get ':uuid/check-email' => 'vendors#check_email'
  end

Answer: Your route expects a :uuid parameter but in your spec you are not supplying that parameter.  Update your spec to pass in the uuid parameter:
describe Community::VendorsController do
  ...

  it 'should return 404 if no vendor found' do
    Vendor.stub(:find_by_uuid => nil)
    get 'show', uuid: uuid # Replace uuid with your object's uuid
    response[:status].should == 404
  end
end


Views dont render on ViewController presented programmatically from a different storyboard

Question: I'm developing app with a structure like this:
Edit: There's a common tab bar controller on main.storyboard
main.Storyboard -> NavController -> (relationship) ViewControllerA -> (show/push segue) ViewControllerB
secondary.Storyboard -> NavController -> (relationship) ViewControllerC
From ViewControllerC, I need to segue to ViewControllerB. I'm doing this using a Storyboard reference. The segue works, dependencies are passed in the segue, but I have one programmatic view that I load which isn't loading when the VC is presented from ViewControllerC on secondary.Storyboard and loads normally when presented with a storyboard segue
Here's how I'm triggering the segue to ViewControllerB:
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let someObject = fetchedResultsController.object(at: indexPath).someRepresentation
    performSegue(withIdentifier: "theIdentifier", sender: someObject)
}

Here's how I'm handling the segue:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "theIdentifier" {
        guard let destination = segue.destination as? ViewControllerB,
        let sender = sender as? SomeCustomClass else { return }
        destination.receivedObject = sender
    }
}

I'm creating the views and adding to the view's subView in ViewWillAppear. I've also tried this in ViewDidAppear with no changed effect. Again, the views are created when the ViewController is presented from the same storyboard
Here's how I'm eventually creating the views
let webNavView = WebNavToolbarView(viewLayoutMarginsGuide: view.layoutMarginsGuide)
let yPosition: CGFloat = webNavView.frame.height / 4
let xOffset: CGFloat = 8

let backButton = createButton(
    image: .back,
    xPosition: xOffset,
    yPosition: yPosition,
    selector: #selector(goBackPressed)
)

let forwardButton = createButton(
    image: .forward,
    xPosition: backButton.frame.maxX + xOffset,
    yPosition: yPosition,
    selector: #selector(goForwardPressed)
)

// FIXME: Doing this just to get the width for the createButtonMethod's xPosition parameter
let homeButton = createButton(
    image: .home,
    xPosition: webNavView.frame.maxX - forwardButton.frame.width - xOffset,
    yPosition: yPosition,
    selector: #selector(goHomeButtonPressed)
)

webNavView.translatesAutoresizingMaskIntoConstraints = false
webNavView.addSubview(backButton)
webNavView.addSubview(forwardButton)
webNavView.addSubview(homeButton)

self.view.addSubview(webNavView)

The webNavView is using the layoutGuide that's passed in to get its width. X and Y are 0,0
All views are being created without constraints (using frames). The createButton method is just positioning the buttons after calling an initializer that styles them.
If I print view.subViews, webNavView is in there, but it doesn't appear on screen or in the Views Debugger. It's height and width are both 0, though it's height is hard-coded to 60
Also, if I add the toolbar to parent.view, it gets added but doesn't respect any of the safe area (it gets placed over the status bar)
Checking webNavView's frame:

Subviews also print out with the right position. But again, nothing even shows in Views Debugger
Main.storyboard:

secondary.storyboard:

storyboard reference:
Comment: @matt I don't believe that's true. He can modally present ViewControllerB from ViewControllerC or he can push it and in this case ViewControllerB will just be another viewController in second storyboard's nav controller's stack.
Comment: Can you share the code that creates the views when loading ViewControllerB? Also, can you specify what kind of segue you are using from VCC to VCB?
Comment: @matt the ViewController gets pushed onto the stack just fine. It's a different storyboard, so it's not going "backward"
Comment: @rs7 I'm using a storyboard reference and show/push segue
Comment: It's unclear to me how you are able to access VCB using a segue from a different storyboard while VCB is not the entry point of its own storyboard.
Comment: added pictures of storyboards. We use one storyboard per main feature to avoid merge conflicts. @matt - I'm not 100% sure, but I think when you segue from a different storyboard, the destination's view hierarchy is ignored. The reason I think this is I've used this type of segue each with independent nav controllers without a hiccup or even a warning in the console. In one project, I pulled from 2 different storyboards... destination VCs in their own nav controllers. I don't see any information from Apple on using a storyboard reference let alone what it actually does with view hierarchies.
Answer: I think I may have found your problem. You said you were laying out your views using frames, yet you are setting: webNavView.translatesAutoresizingMaskIntoConstraints = false. You need to get rid of this line of code because this tells the compiler that you are laying out your view using autolayout, and so it will ignore the frame. And since don't have any auto layout constraints defined, your webview is not showing on the screen.
I would also double check to make sure that you are not setting translatesAutoresizingMaskIntoConstraints to false for the webNavView's subviews.
Comment: Good catch, however I added that as a debugging step somewhere in my madness to try and get around this
Answer: Setting the webNavView.frame.origin.y = view.safeAreaInsets.top resolved the issue


Leitura de Strings de Struct com scanf Dando Errado

Question: Bom galera, estou desenvolvendo um código em C que realiza cadastro de dados em arquivos. Porém, estou com um problema na função cadastrarCliente, a qual vocês verão abaixo entre os códigos.
Struct do cliente:
typedef struct
{
        int idCliente;
        char nome[NOME_TAM_MAX];
        char CPF[16];
        char endereco[ENDERECO_TAM_MAX];
}Cliente;

Macros:
#define NOME_TAM_MAX 51
#define ENDERECO_TAM_MAX 101

Função cadastrarCliente:
void cadastrarCliente (void)
{
        Cliente *newCliente = (Cliente *) malloc(sizeof(Cliente));
        if (!newCliente)
        {
                printf("ERRO DE MEMORIA!!!\n");
                exit(-1);
        }
        else
        {
                printf("\n--- PRENCHA OS DADOS DE CADASTRO DO CLIENTE ---\n\n");
                printf("Digite o ID do cliente: ");
                scanf(" %d", &newCliente->idCliente);
                printf("Digite o nome do cliente: ");
                scanf(" %s", newCliente->nome);
                printf("Digite o CPF do cliente: ");
                scanf(" %s", newCliente->CPF);
                printf("Digite o endereco do cliente: ");
                scanf(" %s", newCliente->endereco);

                stream = fopen("cliente.txt", "w+b"); // stream é global
                if (!stream)
                {
                        fputs("ERRO AO TENTAR LER ARQUIVO!!!\n", stderr);
                        exit(-1);
                }
                else
                {
                        fwrite(newCliente, sizeof(Cliente), 1, stream);
                        fclose(stream);
                }
        }

        return;
}

O erro é o seguinte, após digitar o nome do cliente e apertar enter, todos os outros atributos são pulados (mostrando apenas o conteúdo dos printf) e a função chega ao fim. Inverti os campos, colocando o CPF primeiro e depois endereço, após ler o CPF, tudo ocorre bem sucedido, mas o erro se repete ao ler o endereço também.
Comment: O nome que está a colocar tem espaços ? Vale lembrar que `scanf("%s` lê apenas uma palavra, deixando as restantes na stream de input. Se quiser ler uma linha inteira troque por `scanf("%[^\n]`
Comment: Tem espaços sim, mas achei que este problema poderia ser resolvido dando um espaçamento dentro do scanf, tal como está no código. Tentei utilizar como sugeriu, mas não funciona.
Comment: Dê um exemplo do tipo input que esteja a ler, para ser possivel de dizer a forma apropriada de o ler
Comment: Yuri Coelho Rosario
Comment: Cada um desses seria colocado de cada vez separado por enter ? Ou a seperação seria pelas virgulas ? O seu código interpreta 1 numero seguido de 3 textos. Não vejo como isso possa encaixar no exemplo que deu
Comment: A separação seria através do enter, após o enter, passa pro próximo. No caso, a primeira entrada é um número qualquer, a segunda o nome completo, a terceira o CPF e a quarta o endereço completo.
Answer: Começo por reiterar o que tinha já dito em comentário:

Vale lembrar que scanf("%s lê apenas uma palavra, deixando as restantes na stream de input. Se quiser ler uma linha inteira troque por scanf("%[^\n]

No entanto este é o exemplo genérico. Olhando para o seu caso em particular, tem uma leitura de um inteiro antes, por isso vai ficar uma quebra de linha por ler após o primeiro número, que será aquela que é apanhada logo a seguir se fizer scanf("%[^\n]. A solução é simplesmente consumir essa quebra com um pequeno espaço:
scanf(" %[^\n]",
//     ^--aqui

Tendo isto em consideração poderia reescrever o seu código de leitura assim:
printf("Digite o ID do cliente: ");
scanf("%d", &newCliente->idCliente);
printf("Digite o nome do cliente: ");
scanf(" %[^\n]", newCliente->nome); //mais que uma palavra
printf("Digite o CPF do cliente: ");
scanf(" %s", newCliente->CPF); //uma palavra
printf("Digite o endereco do cliente: ");
scanf(" %[^\n]", newCliente->endereco); //mais que uma palavra

Veja este exemplo a funcionar no Ideone
Outra alternativa seria ler com fgets que até seria mais seguro, mas isso tem as suas implicações. Uma delas seria que o fgets deixa a quebra de linha lida dentro da string. Neste caso não a sugeri pois quando utiliza fgets regra geral é mais apropriado fazer todas as leituras com fgets e não intercalar com scanf, o que pode complicar um pouco.
Tem aqui outra resposta que dei que detalha a leitura com fgets:
problema-com-gets-e-fgets
Comment: Desta vez funcionou. Muito obrigado pela solução e pela explicação, Isac. Li a resposta em outro tópico sobre fgets e agora está tudo claro pra mim. Abraços!
Answer: Tenta usar scanf("\n %s"), porque se não ele vai ler apenas uma string e deixar as outras para trás. E se o seu nome a inserir tiver espaços o scanf não amarzena, pois ela encerra a leitura no primeiro espaço ou seja barra \0, caso seja este seu problema experimente usar fgets.
Comment: Tentei como sugeriu, mas não funcionou. Achei que o fgets não lia do teclado, apenas de arquivos.
Answer: Boa Noite Yuri, testei seu codigo e aparentemente consegui resolver o problema da seguinte forma:
printf("\n--- PRENCHA OS DADOS DE CADASTRO DO CLIENTE ---\n\n");
    printf("Digite o ID do cliente: ");
    scanf(" %d", &newCliente->idCliente);

    fflush(stdin);

    printf("Digite o nome do cliente: ");
    fgets(newCliente->nome,51,stdin);

    fflush(stdin);

    printf("Digite o CPF do cliente: ");
    fgets(newCliente->CPF,16,stdin);

    fflush(stdin);

    printf("Digite o endereco do cliente: ");
    fgets(newCliente->endereco,101,stdin);

Utilizei o fflush(stdin) para limpar o buffer, evitando pular os campos que vem depois, alem disso foi possivel capturar as string pelo teclado utilizando o fgets()
Comment: Olá Rogi, boa noite. Não sabia que fgets lia do teclado, achava apenas que era pra ler de arquivo, que bom saber disso. Mas bem, a solução apresentada não funcionou, agora o campo de nome está sendo pulado após apresentar o ID.


Сreating a dictionary of several pairs of elements

Question: There are files in the directory:
environment1_--_192.168.12.239
environment1_--_192.168.12.46
environment1_--_192.168.12.72
environment1_--_192.168.12.83
environment2_--_192.168.12.150
environment2_--_192.168.12.53
environment2_--_192.168.12.44
environment2_--_192.168.12.90

Find files:
- ansible.builtin.find:
    paths: "./environments/"
    file_type: file
  register: environment_hosts_files

I need to get a list of dictionaries:
environment_hosts:
  - name: environment1
    hosts:
      - 192.168.12.239
      - 192.168.12.46
      - 192.168.12.72
      - 192.168.12.83
  - name: environment2
    hosts:
      - 192.168.12.150
      - 192.168.12.53
      - 192.168.12.44
      - 192.168.12.90

How to do this?
Answer: Get the lists
    files: "{{ environment_hosts_files.files |
               map(attribute='path') |
               map('basename') |
               map('replace', '_', '') |
               map('split', '--') |
               map('zip', ['name', 'host']) |
               map('map', 'reverse') |
               map('community.general.dict') |
               groupby('name') }}"

gives
  files:
    - - environment1
      - - {host: 192.168.12.72, name: environment1}
        - {host: 192.168.12.239, name: environment1}
        - {host: 192.168.12.83, name: environment1}
        - {host: 192.168.12.46, name: environment1}
    - - environment2
      - - {host: 192.168.12.53, name: environment2}
        - {host: 192.168.12.150, name: environment2}
        - {host: 192.168.12.44, name: environment2}
        - {host: 192.168.12.90, name: environment2}

Get the lists of the environments and hosts, and create the dictionary
    env: "{{ files | map('first') }}"
    host: "{{ files | map('last') |
              map('map', attribute='host') }}"
    env_hosts: "{{ dict(env|zip(hosts)) }}"

gives
  env_hosts:
    environment1: [192.168.12.72, 192.168.12.239, 192.168.12.83, 192.168.12.46]
    environment2: [192.168.12.53, 192.168.12.150, 192.168.12.44, 192.168.12.90]

Convert the dictionary to a list if you want to
    env_hosts_list: "{{ env_hosts |
                        dict2items(key_name='name', value_name='hosts') }}"

gives
  env_hosts_list:
    - hosts: [192.168.12.72, 192.168.12.239, 192.168.12.83, 192.168.12.46]
      name: environment1
    - hosts: [192.168.12.53, 192.168.12.150, 192.168.12.44, 192.168.12.90]
      name: environment2

Given the tree
shell> tree /tmp/ansible/env
/tmp/ansible/env
├── environment1_--_192.168.12.239
├── environment1_--_192.168.12.46
├── environment1_--_192.168.12.72
├── environment1_--_192.168.12.83
├── environment2_--_192.168.12.150
├── environment2_--_192.168.12.44
├── environment2_--_192.168.12.53
└── environment2__--_192.168.12.90

Example of a complete playbook for testing
- hosts: all

  vars:

    files: "{{ environment_hosts_files.files |
               map(attribute='path') |
               map('basename') |
               map('replace', '_', '') |
               map('split', '--') |
               map('zip', ['name', 'host']) |
               map('map', 'reverse') |
               map('community.general.dict') |
               groupby('name') }}"
    env: "{{ files | map('first') }}"
    host: "{{ files | map('last') |
              map('map', attribute='host') }}"
    env_hosts: "{{ dict(env|zip(host)) }}"
    env_hosts_list: "{{ env_hosts |
                        dict2items(key_name='name',
                                   value_name='hosts') }}"

  tasks:

    - ansible.builtin.find:
        paths: /tmp/ansible/env
        file_type: file
      register: environment_hosts_files

    - debug:
        var: files | to_yaml
    - debug:
        var: env_hosts | to_yaml
    - debug:
        var: env_hosts_list | to_yaml


Is there a site as good as Smashing Magazine geared towards drupal rather than wordpress?

Question: As the title says, I'd like to find a site that is similar to the Smashing Magazine site that caters more to drupal users.
I love this site. I have yet to find a Drupal centered one that keeps me checking the feed so often for quality content.
I'll try any suggestion.
Answer: Well I have been trying to make such a website www.techiestuffs.com, but since I haven't found authors to write drupal based content I have scattered the site with categories I am comfortable with. If I find authors I will work with them.
Comment: There's not so much [Drupal content](http://www.techiestuffs.com/search/node/drupal) on your website, was the goal to cover Drupal stuff or build a site like Smashing using Drupal ?
Comment: My first thought was to build a theme like mashable and other news site and I did it but then when comes to content I know about Drupal than any other thing so i decided to concentrate more on Drupal ad web designing.it is launched just a week ago so there is not much content but I am working on that.
Answer: I check Planet Drupal often. I've set it up on Flipboard on the iPad. You can also setup an RSS reader to find you Drupal content.


SubQuery não interpretada / falhando

Question: Utilizando Sub-Query, faça uma query que retorne os materiais ativos, com a Descrição, Lote, Cod de Barras e Validade somente da Dt Validade menor de cada Material.
Meu código até o momento:
select R.COD_MATERIAL,
   M.DESCRICAO,
   (select L.LOTE from TR_LOTE L
           where L.DT_VALIDADE = (select min(L.DT_VALIDADE) from TR_LOTE L
                                        where L.LOTE = (select L.LOTE from TR_LOTE L))) as LOTE,
   (select R.COD_BARRA from TR_REL_MATERIAL_LOTE R
           where R.LOTE = NULL) as COD_BARRAS,
   min(L.DT_VALIDADE)

   from TR_REL_MATERIAL_LOTE R

   inner join TR_MATERIAL M on R.COD_MATERIAL = M.COD_MATERIAL
   inner join TR_LOTE L on R.LOTE = L.LOTE

   group by R.COD_MATERIAL, M.DESCRICAO

   order by R.COD_MATERIAL

Não estou conseguindo retornar o esperado, não sei se foi por falta de interpretação ou não faço idéia de como fazer isso.
Mas preciso retornar especificamente o Lote de cada Material em sua respectiva data de validade (menor data da validade) além de seu código de barras, seguindo o exemplo do retorno dessa query abaixo:
select R.COD_MATERIAL,
   M.DESCRICAO,
   min(L.DT_VALIDADE)

   from TR_REL_MATERIAL_LOTE R

   inner join TR_MATERIAL M on R.COD_MATERIAL = M.COD_MATERIAL
   inner join TR_LOTE L on R.LOTE = L.LOTE

   group by R.COD_MATERIAL, M.DESCRICAO

   order by R.COD_MATERIAL

A imagem em anexo mostra como são estruturadas as tabelas.
Obrigado a quem puder ajudar!
1
Answer: Olá
A subquery no SELECT só pode/deve retornar 1 registro, então você deve sempre colocar "TOP 1" nela, e uma cláusula "ORDER BY" para dizer qual seu critério do que constitui um primeiro registro.
O "inner join TR_LOTE" obviamente também não é mais necessário, e poderia gerar um produto cartesiano, já que você está buscando os dados do lote unica e exclusivamente nas subqueries.
O "group by R.COD_MATERIAL, M.DESCRICAO" também não é mais necessário, visto que nosso SELECT principal não contém mais funções agregadoras.
Então ficaria:
select
  R.COD_MATERIAL,
  M.DESCRICAO,
  (select top 1 L.LOTE from TR_LOTE L where L.LOTE = R.LOTE order by L.DT_VALIDADE) as LOTE,
  (select top 1 L.DT_VALIDADE from TR_LOTE L
   where L.LOTE = R.LOTE order by L.DT_VALIDADE) as DT_VALIDADE,
  (select top 1 R.COD_BARRA from TR_LOTE L
   inner join TR_REL_MATERIAL_LOTE R on R.LOTE = L.LOTE
   order by L.DT_VALIDADE) as COD_BARRA

from TR_REL_MATERIAL_LOTE R
inner join TR_MATERIAL M on R.COD_MATERIAL = M.COD_MATERIAL
order by R.COD_MATERIAL

Esta query porém não ficou elegante, pois em casa subquery buscamos novamente a mesma consulta em TR_LOTE, sempre ordenada por DT_VALIDADE, somente para em cada caso retornar uma coluna diferente. Além disso, na terceira subquery, eu consulto novamente TR_REL_MATERIAL_LOTE, numa nova instância, que é a mesma tabela da minha query principal.
Não precisamos usar subqueries somente na cláusula SELECT. Há vários outros pontos onde podemos utilizá-las, que podem dar soluções melhores.
Este problema se encaixa num padrão que frequentemente acontece, em que temos que encontrar o campo de menor valor (no caso, DT_VALIDADE) e, a partir daí, encontrar vários outros campos correlatos a este. Não há uma forma trivial de trazer tudo de uma vez só. Este tipo de padrão requer a quebra de query em duas etapas.
Uma solução melhor seria:
select
  R.COD_MATERIAL,
  M.DESCRICAO,
  R.LOTE,
  MenorDataMaterial.DT_VALIDADE,
  R.COD_BARRA
from (
  select RX.COD_MATERIAL, MIN(L.DT_VALIDADE) [DT_VALIDADE]
  from TR_REL_MATERIAL RX
  inner join TR_LOTE L on L.LOTE = RX.LOTE
  group by RX.COD_MATERIAL
) MenorDataMaterial
inner join TR_REL_MATERIAL_LOTE R on R.COD_MATERIAL = MenorDataMaterial.COD_MATERIAL
inner join TR_MATERIAL M on R.COD_MATERIAL = M.COD_MATERIAL
order by R.COD_MATERIAL

Ficou bem mais simples, não? Ainda há outras soluções possíveis.

SubQuery não interpretada / falhando


Alteração de objeto com javascript

Question: Minha API esta retornando um array com os objetos na seguinte estrutura:
[
  {id: 1, name: "Flávio", position: "SP - Atacante"},
  {id: 2, name: "João", position: "SP - Goleiro"},
  {id: 3, name: "Fernando", position: "RJ - Zagueiro"},
  {id: 5, name: "Robert", position: "SP - Todas"},
];

Eu preciso pegar a última posição desse cara (objeto com position: 'SP - Todas') e remover o texto SP - , deixando apenas a escrita "Todas".
Tentei da seguinte forma e funcionou (não deve ser a melhor forma, se tiverem sugestão, agradeço).
jogadores.map((jogador, i) => {
    if (jogador.position.includes('Todas')) {
    console.log(jogador.position.substr(4));
  };
});

O problema é que preciso retornar o array com este último objeto editado, mas não estou sabendo como fazer.
Exemplo JsFiddle
Comment: Queres remover o `SP` na "ultima posição" ou na que tem o texto "Todas"? no exemplo é a mesma, mas é sempre a mesma?
Answer: Para resolver este problema, basta apenas utilizar a função split, o resultado desta operação  é um array em que:

na posição zero estará o valor "SP "
na posição um estará o valor " Todas"

Assim basta remover os espaços em branco para a posição um do array [chamando a função trim()].
const jogadores = [
    {id: 1, name: "Flávio", position: "SP - Atacante"},
    {id: 2, name: "João", position: "SP - Goleiro"},
    {id: 3, name: "Fernando", position: "RJ - Zagueiro"},
    {id: 5, name: "Robert", position: "SP - Todas"},
]

const j = jogadores.map((jogador) => {
    if (jogador.position.includes('Todas')) {
      jogador.position = jogador.position.split('-')[1].trim();
      return jogador;
    }
    return jogador;
})

Comment: Estás a usar o `.map` para mudar a array inicial... devias usar o retorno do `map` para gerar uma array alterada e não mudar a array inicial.
Comment: Obrigado por reportar o erro. Já corrigi.

Alteração de objeto com javascript


Expansion of $\sin x$

Question: I wanted to know, how can I derive:
$$\sin x = x - \frac{x^3}{3!} + \frac{x^5}{5!} - \frac{x^7}{7!}+\cdots$$
Comment: Try googling Taylor expansion.
Answer:
Let $f(x)$ and its derivative $f'(x),f''(x),...,f^{(n)}(x)$ exist and are continous on $[a,b]$ and suppose that $f^{(n+1)}(x)$ exists in $(a,b)$. Then we can have $$f(x)=f(a)+f'(a)(x-a)+\frac{f''(a)}{2!}(x-a)^2+\dots+\frac{f^{(n)}(a)(x-a)^n}{n!}+R_n$$

This fact, sometimes, is called Taylor's Theorem of the mean
Comment: @PeterTamaroff: I didn't want Michael's edit removed. :-)
Comment: Moreover, if for all $x$ and $\xi$ in $[a,b]$; we can see that the remainder is approaching zero then we can write $f(x)$ as follows: $$f(x)=f(a)+f'(a)(x-a)+\frac{f''(a)}{2!}(x-a)^2+\frac{f'''(a)}{3!}(x-a)^3+\cdots
$$In fact, as above, we have a Power series and this is what you are looking for. Now set $a=0$.
Comment: Why not put that comment in the answer?
Comment: @BabakS. It needs double `+`. One for the answer and one for generosity. GOOD JOB MAN
Comment: Well written! $\ddot\smile$
Answer: Use Mclaren series : $f(x) = f(0)+f^{'}(0)\frac{x}{1!}+f^{''}(0)\frac{x^2}{2!}+f^{'''}(0)\frac{x^3}{3!}+\cdots$
for $f(x)=\sin x$
Answer: One could use Euler's Theorem to get $$\cos x + i\sin x=e^{ix}=\sum_{k=0}^\infty \frac{(ix)^k}{k!}=\left(1-\frac{x^2}{2!}+\frac{x^4}{4!}-\cdots\right)+i\left(x-\frac{x^3}{3!}+\frac{x^5}{5!}-\cdots  \right)$$ Now equating real and imaginary parts you will get the series expansion for both $\cos x$ and $\sin x$.

Expansion of $\sin x$


Writing log likelihood for WAIC (logistic hierarchal stan model)

Question: I'm creating a new model and I want to compare this with another model using WAIC. I understand that I need to write a generated quantities block. However, I'm struggling to convert the logsumexp of beta. I would greatly appreciate any leads/help. My model block looks like this:
model {

    //prior for phi,b
    phi ~ cauchy(0,5);
    mu_b ~ normal(0,1);
    sigma_b ~ cauchy(0,1);
    mu ~ normal(0,1);
    sigma ~ cauchy(0,1);

   //model
   log_b_z ~ normal(0, 1);
   theta_raw ~ normal(mu, sigma);

   for (i in 1:n) {
       vector[number_segments] test;
       for (j in 1:number_segments) {
           test[j] = beta_lpdf(response[i] | p[j][i]*phi, (1-p[j][i])*phi) + log(prob_segment[j]);
       }
       target += log_sum_exp(test);
   }
}

Comment: Have a look at R library [`loo`](https://cran.r-project.org/web/packages/loo/index.html), which provides a method for calculating WAIC based on `stan` models.
Answer: You need to define a generated quantities block that defines your posterior predictive log likelihood for each data point.
You can do it this way for a mixture with minimal recomputation.
transformed parameters {
  vector[n] log_lik;
  {
    vector[number_semgnents log_prob_segment = log(prob_segment);
    for (i in 1:n) {
      vector[number_segments] lp = log_prob_segment;
      for (j in 1:number_segments) {
        lp[j] += beta_lpdf(response[i] | p[j, i] * phi, (1 - p[j, i]) * phi);
      log_lik[i] = log_sum_exp(lp);
   }
}
...
model {
  target += sum(log_lik);
...

You could also define log_lik as a generated quantity---that can be more efficient if you can vectorize the likelihood (which isn't possible yet for mixtures in Stan).
Once you've done that, you can use the loo package to calculate WAIC, etc., as described in the vignette and references.


How to make bootstrap headings responsive?

Question: I'm making a bootstrap website. Everything is working smooth on all the screen sizes but the heading(h1) remains fixed size. It is too big for small screens. How can I fix the bootstrap h1 or headings in general.
Answer: You can use <code>@media</code> for this
<code>@media screen and (max-width: 768px) {
    h1{
        font-size:14px;
    }
}
</code>
That means less than 768px the h1 tag font size will be 14px.
Like this you can set for all pixel you required.
Comment: You may need to add **!important** as well
Answer: That is my solution. Fully responsive bootstrap headings
<code>@import "bootstrap/scss/functions.scss";
@import "bootstrap/scss/variables.scss";
@import "bootstrap/scss/mixins.scss";

@each $breakpoint in map-keys($grid-breakpoints) {
  @include media-breakpoint-up($breakpoint) {
    $infix: breakpoint-infix($breakpoint, $grid-breakpoints);

    .h1#{$infix} { font-size: $h1-font-size!important; }
    .h2#{$infix} { font-size: $h2-font-size!important; }
    .h3#{$infix} { font-size: $h3-font-size!important; }
    .h4#{$infix} { font-size: $h4-font-size!important; }
    .h5#{$infix} { font-size: $h5-font-size!important; }
    .h6#{$infix} { font-size: $h6-font-size!important; }

    .display-1#{$infix} {
      font-size: $display1-size!important;
      font-weight: $display1-weight;
      line-height: $display-line-height;
    }
    .display-2#{$infix} {
      font-size: $display2-size!important;
      font-weight: $display2-weight;
      line-height: $display-line-height;
    }
    .display-3#{$infix} {
      font-size: $display3-size!important;
      font-weight: $display3-weight;
      line-height: $display-line-height;
    }
    .display-4#{$infix} {
      font-size: $display4-size!important;
      font-weight: $display4-weight;
      line-height: $display-line-height;
    }
  }
}
</code>
Answer: best use the bootstrap sass in your own sass, keep it DRY and maintainable
<code>@import "../bootstrap-sass/bootstrap/variables";

@media screen and (max-width: $screen-md-max) {
    h1 {
        font-size:14px;
    }
}
</code>


PHP-FPM/nginx-SELinux: No input file specified

Question: I have problem setting up nginx (with passenger, which works fine) with php-fpm on Fedora. When I try access index.php via browser, I get "No input file specified."
Nginx error log:

2013/11/29 12:50:47 [error] 2218#0: *15 FastCGI sent in stderr: "Unable to open primary script: /home/nginx/html/phptest/index.php (No such file or directory)" while reading response header from upstream, client: 184.108.40.206, server: ..., request: "GET /index.php HTTP/1.1", upstream: "fastcgi://127.0.0.1:9000", host: "..."
  That file exists.

PHP-FPM error log shows nothing.
PHP-FPM status page works. Nginx and PHP-FPM are running under user nginx.
Nginx conf:
<code>        server {
            listen 80;
            server_name ...;
            root /home/nginx/html/phptest;
            index index.php index.html index.htm;
            location ~ \.php$ {
                    include fastcgi.conf;
                    try_files $uri =404;
                    fastcgi_pass 127.0.0.1:9000;
            }
            location ~ ^/(status|ping)$ {
                 #access_log off;
                 include fastcgi.conf;
                 fastcgi_pass 127.0.0.1:9000;
            }
    }
</code>
PHP: doc_root is empty, open_basedir is not defined, cgi.fix_pathinfo=0
https://gist.github.com/anonymous/7705152
PHP-FPM www.conf: https://gist.github.com/anonymous/7705155
index.php file exists and is accesible from user nginx itself and from different user.
I have tried different nginx configuration and nothing helped. I guess it has something with different path handling around fastcgi, but I have no idea what to do with it.
Thanks for help.
UPDATE:
SELinux was causing this problem, now I am running it in permissive mode. Not sure how to create proper policy without causing outage.
Comment: Can you post /etc/php5/fpm/pool.d/www.conf  and /etc/php.ini please
Comment: Updated question with links.
Comment: Check to see that the file `/home/nginx/html/phptest/index.php` exists and is readable.
Comment: Yes it is. I have just disabled selinux enforcement and php file executes. I have forgot about it, because self compiled nginx (gem passenger) did not have problem with that. I have tried installing Apache and I have found following in error log: [Fri Nov 29 20:16:34.112015 2013] [suexec:notice] [pid 5447] AH01232: suEXEC mechanism enabled (wrapper: /usr/sbin/suexec)
AH00112: Warning: DocumentRoot [/home/nginx/html/phptest] does not exist
Answer: Can you try changing your server block to this;
<code>server {
    listen 80;
    server_name ...;
    root /home/nginx/html/phptest;
    index index.php index.html index.htm;
    location ~ \.php$ {
        root           /home/nginx/html/phptest;
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME   $document_root$fastcgi_script_name;
        include        fastcgi_params;
    }
}
</code>
Comment: Did not help, same result. Same error in nginx log.
Comment: Can you try using a socket rather than 127.0.0.1:9000 - you can change this in the www.conf and also then change the fastcgi_pass to path of your socket too.


Best way to organise back end (Node) processes and front end (Vue / Nuxt) that uses part of these processes

Question: I have a few tiny node apps doing some basic stuff like checking things and filling my DB (triggered by CRON). In my Nuxt app I will need to use part of what is insinde these Node apps. What is the best way to organise it, do I keep them separated or do I fuse them with my Nuxt app ? Do I copy what I need from these node apps and adapt it in Nuxt, do I use the serverside middlewares to add those node apps inside my Nuxt project or do I create my Nuxt app with express and I use /server/index.js to add my node apps there in some way ?
Let's take an example. You have a node app that check very hour some data and fill a DB. In the Nuxt app you have a page showing the content of the DB but you want first to be sure that nothing new has to be added in the DB since the last hour. The code I would have to run in th every Nuxt page is the same code as the Node app (check and fill the DB). It looks a bit stupid (and hard to maintain and update) to have twice the same code at two places. But I 'm not sure how would I have this node app running every hour in my Nuxt app. Any advice would be greatly appreciated
Comment: This is a pretty high level question. In general, decoupling the front and back ends is optimal, because then your backend can serve other front ends (i.e., mobile and desktop).

In terms of having same code in two places, this is a scenario where you would develop a microservice to handle the change detection for both front and back ends. This allows you to follow DRY (do not repeat yourself). In node, understanding microservices is essential for this reason.
Comment: All this is still very new to me but I understand what you say. I will learn more about microservices, it looks like the way to go. If I understand well, I will be able to launch my micro service from my server / CRON and from my Nuxt app. The microservice will detect from where comes the request and act differently ...? I didn't realized microservices were such an important part in Node. Although it may not seem so, your answer has been very valuable !
Comment: That sounds like an appropriate configuration. When you build it, try editing this question with your code included and I will give some feedback.

Microservices are not always necessary in Node, depending on the use case. But many times that is the most sensible approach for handling situations where more than one component requires the same functionality. An example from my app is that I use the Axios HTTP handler, and instead of initializing Axios in each component I built an Axios microservice that can serve each component, thus reducing my Axios instances to 1.I will post some steps.
Answer: Here is a control flow that may help your thinking about designing this CRON microservice. There are many ways to do this, and this may not be the best approach, but I think it will work for your use case.

Have a services directory in your server (can also be called middleware).
Include a cron.js file that contains the logic for the task runner.
Within cron.js, issue a scheduled response from node to Vue, such as a JSON keyword like res.JSON({message: 'checkNewData'}). This will be something called a "server sent event". A server sent event is simply an event that happens autonomously on a defined schedule within node environment.
In Vue, at the root level App.vue, use the created() hook to register an event listener that will listen for the server sent "checkNewData" JSON object. When this event listener hears the JSON response, it should trigger Vue to check the appropriate component, package up any new data, and send it down to the DB in a post or put http call, depending on whether you're adding new data, or replacing the old with the new.

This configuration would give you a closed-loop system for automatic updates. The next challenge would be making this operation client-specific, but that is something to worry about once you got this working. Again, others may have a different approach to this, but this is how I would handle the flow.
Comment: Sure thing, let me know if you have any questions


Como colocar logo no cabeçalho?

Question: Possuo um site onde uso dois cabeçalhos para mostrar minhas opções para o usuário, mas me deparei com um problema, preciso colocar o logo da empresa e não estou conseguindo fazer, preciso que a logo fique em um tamanho proporcional ao cabeçalho, se coloco no primeiro ou no segundo a logo fica pequena.
Tentei criar uma estrutura, mas meus conhecimentos de CSS não ajudaram muito, tentei algo como isso:

Falando pode ser que eu não consiga exemplificar o que preciso, por isso vou disponibilizar uma imagem.
O site é este e o que tentei fazer foi isto:
Answer: Tenta essa solução aqui:

          <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#MenuUm">  </button>

              <form autocomplete="off" role="search" method="get" class="searchform" action="#">
                <input type="text" value="" name="s" id="s" placeholder="Buscar...">
              </form>

 catálogos e manuais

 cores e linha

 garantia e uso

          <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#MenuDois">  </button>

 INÍCIO

 EMPRESA

 PRODUTOS

 REPRESENTANTES

 ONDE ENCONTRAR

CONTATO

Ficou assim:

No caso eu usei uma cor para demonstrar, mas é só trocar por uma imagem.
Explicação:

Criei uma div nova para alocar a imagem com um `backgroud´.
Usei o z-index para deixar a imagem por cima das outras duas divs.
Com Position: Absolute deixei ele estático na posição.

Observação:
No responsivo ele precisa de alguns ajustes, porém poucos ajustes. Você pode fazer a logo ficar para cima da navbar no responsivo, acredito que seria a melhor solução.
Substitui todo o header por esse código.
Comment: Olá @GiovanniBernini, obrigado pela grande ajuda, mas me diga uma coisa, se possível, como posso deixar a logo acima da navbar?
Comment: @adventistapr Você pode usar css com media queries para arrumar isso, por exemplo `@media screen and (min-width: 400px) and (max-width: 600px) {.logo{float:none; position: relative;}}` Você controla que em certo tamanho de tela, tal coisa irá mudar. No exemplo que eu dei, entre 400 e 600px a classe logo, não vai ter mais o `float: left` e o `position: absolute`, logo a div do logo, não vai mais ficar do lado em cima das outras divs.
Comment: Olá novamente @GiovanniBernini, devo estar fazendo algo errado, mas a alteração que fiz como código sugerida não surtiu efeito.
Answer: Agora que notei que é uma questão duplicada, então vou migrar minha resposta para cá, já que este tópico está mais desenvolvido.
Outro modo de obter o resultado seria:
Primeiramente, se você pretende deixar o seu trabalho reponsivo, ou seja, acessível em mobile, não é recomendável utilizar um valor de width fixo, como você fez nas divs #logo, #superior e #inferior, pois quando o website for acessado em mobile, ele terá um "scroll" horizontal. Utilize % ao invés disso.
Quanto a sua dúvida em si, a ideia é que você crie um bloco para armazenar todo o conteúdo. Logo, menu superior e inferior.
Dentro dela você terá ainda 2 sub blocos para armazenar, sendo 1 para o logo e outro para os 2 menus. Depois basta dividir os 2 menus com largura 100% dentro do bloco destinado apenas ao menu.
Assim você não cria dependência de position ou entre os diferentes conteúdos (menu e logo).
Fiz um exemplo que está funcionando com a ideia geral disso, dê uma olhada e veja se resolve o seu problema: http://jsfiddle.net/f19tc70y/1/
Answer: você pode deixar o seu header e apenas posicionar os #logo, #superior, #inferior dentro do header.

header, div {
  box-sizing: border-box;
}

header {
  position: relative;
  width: 1220px;
  max-width: 90%;
  height: 120px;
  top: 0px;
  right: 0px;
  left: 0px;
  margin: 0px auto;

}

#logo {
  position: absolute;
  width: 120px;
  top: 0px;
  bottom: 0px;
  left: 0px;

  border: 1px solid red;
  background-color: rgba(255, 0, 0, 0.1);
}

#superior {
  position: absolute;
  top: 0px;
  right: 0px;
  bottom: 60px;
  left: 120px;

  border: 1px solid green;
  background-color: rgba(0, 255, 0, 0.1);
}

#inferior {
  position: absolute;
  top: 60px;
  right: 0px;
  bottom: 0px;
  left: 120px;

  border: 1px solid blue;
  background-color: rgba(0, 0, 255, 0.1);
}

#superior, #inferior {
  text-align: right;
  line-height: 40px;
  padding: 10px;
}

    Superior

    Inferior

Tomei a liberdade de aplicar algumas alterações no estilo da sua pagina usando o Developer Tools do Opera, segue a imagem da janela do mesmo já com as alterações aplicadas:

eu apaguei a div.hidden-header, pois como ela te um height fixo, ela estava empurrando o header.clearfix para baixo... caso prefira, pode simplesmente remover o height do div.hidden-header ou aplicar um position: absolute ao header.clearfix.
Por fim, adicionei uma div#logo a sua logo deverá ficar dentro dele, e o valor do width da div#logo, left do div.nav-top:nth-child(0) e left do div.nav-top:nth-child(1) devem ser iguais, de preferencia use a largura da imagem do logo.
Comment: Como posso postar o exemplo de como a minha página está ficando depois das dicas informadas? Ainda não consegui, mas gostaria de postar para possível ajuda, edito a minha pergunta colocando o código atual? Creio que deixaria descaracterizada.
Comment: @adventistapr, atualizei a resposta com uma edição aplicada direto ao seu HTML.
Comment: Olá@TobyMosque, não estou conseguindo identificar onde estão essas opções div.nav-top:nth-child(0) e left do div.nav-top:nth-child(1) para fazer  a alteração.
Comment: Este e um seletor css, :nth-child() selecioma um elemento pelo indice, entao estava me referindo a primeira e a segunda div com a classe nav-top
Comment: Olá @TobyMosque, obrigado pela ajuda e grande paciência, fiz as alterações solicitadas, ficaram legais, mas tenho agora um novo problema, acesse: http://ancestofados.com.br/anc/ e redimensione até a menor resolução e tente navegar pelas opções do menu, por favor.

Como colocar logo no cabeçalho?