dimanche 28 juin 2015

Regex to remove punctuation from tokenized text

I'm trying to remove punctuation from tokenized text using regular expressions. Can anyone explain the following behaviour:

$ STRING='hey , you ! what " are you doing ? say ... ," what '
$ echo $STRING | sed -r 's/ [^[:alnum:][:space:]-]+ / /g;'
hey you what are you doing say ," what
$ echo $STRING | sed -r 's/ [[:punct:]]+ / /g;'
hey you what are you doing say ," what
$ echo $STRING | perl -pe 's/ [^[:alnum:][:space:]-]+ / /g;'
hey you what are you doing say ," what
$ echo $STRING | perl -pe 's/ [[:punct:]]+ / /g;'
hey you what are you doing say ," what

The ," token is preserved in the output, which I don't want. It's possible to match this token with:

$ echo $STRING | perl -pe 's/ [",]+ / /g;'
hey you ! what are you doing ? say ... what

URL rewrite not found

My URL it's like this

http://ift.tt/1TWVaiZ

and i want to rewrite url's like this

http://ift.tt/1GTUlAH

I thought this was the way

RewriteEngine On
RewriteBase /validar/
RewriteRule ^/([^/]*)/([^/]*)/$/api.php?desde=$1&que=$2 [L]

But i'm getting 404 and cant make it work

Any ideas? Thanks

PHP: filter specific pattern out of string

My raw output of socket_recvfrom is:

ID IP PING IDENTIFIERNUMBER USERNAME


0 127.0.0.1:1234 0 ID123456789 Moritz

1 127.0.0.1:1234 46 ID123456789 August Jones

2 127.0.0.1:1234 46 ID123456789 Miller


It is a single string that contains all of this informations in once and just contains whitespaces between the informations. All keys can be longer or shorter.

My problem:

When I preg_split("/\s+/") it, then I get a good array with useable data, but when the username contains spaces it creates a second index for this. Not good, all data that comes after this just get destroyed.

I sort the array like this: ID, USERNAME, PING, IDENTIFIERNUMBER, IP

Example by the sorting output with username with one space in it:


ID: 0, USERNAME: Moritz, PING: 0, IDENTIFIERNUMBER: ID123456789, IP: 127.0.0.1:1234

ID: 1, USERNAME: August, PING: Jones, IDENTIFIERNUMBER: 46, IP: ID123456789

ID: 127.0.0.1:1234, USERNAME: 2, PING: Miller, IDENTIFIERNUMBER: 46, IP: ID123456789


How do I get the information correctly out of the string?

Just forgot to say:

The string begins with: --------------------------------- in a not countable order. So it can be like 10 characters or 12. The string ends with:

 (8 users in total)

The regex methode looks good. I only need to filter out the other characters.

--------------------------------- 0 127.0.0.1:1234 0 ID123456789(OK) Moritz 1 127.0.0.1:1234 46 ID123456789(OK) August Jones 2 127.0.0.1:1234 46 ID123456789(OK) Miller (7 users in total)

Last problem: http://ift.tt/1eRW0xy

Regex PHP: Get specific content from a block of code from another website

I have a site from which I want to get specific content from 7 posts. Those all 7 seven posts have same HTML layout (See Below)

<div class="eventInfo">
<h3>Z's(矢沢永吉)</h3>
  <h4>Z's TOUR 2015</h4>

<dl>
    <dt><img src="/event/img/btn_day.png" alt="公演日時" width="92" height="20"> </dt>
    <dd>
      <table width="99%" border="0" cellpadding="0" cellspacing="0">
        <tbody><tr>
      <td width="9%" nowrap="nowrap">2015年6月</td>
      <td width="74%">4日 (木) 19:00開演</td>
    </tr>

  </tbody></table>
</dd>
<dt><img src="/event/img/btn_price.png" alt="料金" width="92" height="20"> </dt>
<dd>S¥10,500 A¥7,500 (全席指定・消費税込)<br><span class="attention">※</span>注意事項の詳細を<a href="http://ift.tt/1HpdVrL" target="_blank">矢沢永吉公式サイト</a>より必ずご確認ください</dd>

<dt><img src="/event/img/btn_ticket.png" alt="一般発売" width="92" height="20"> </dt>
<dd>
 <table width="99%" border="0" cellpadding="0" cellspacing="0">
  <tbody><tr>
    <td width="9%" nowrap="nowrap">2015年5月</td>
    <td width="74%">16日(土)</td>
  </tr>
</tbody></table>
  </dd>

  <dt><img src="/event/img/btn_contact.png" alt="お問合わせ" width="92" height="20"> </dt>
  <dd><a href="http://www.siteurl.com/" target="_blank">ソーゴー大阪</a> 06-6344-3326</dd>

  <dt><img src="/event/img/btn_info.png" alt="公演詳細" width="92" height="20"> </dt>
  <dd><a href="http://ift.tt/1GF5ySz" target="_blank">http://ift.tt/1HpdVrN; </dd>
</dl>
</div>

I just want to fetch the H3 from this layout and the first table in the code. What regex method should I use to get the desired results?

Also these are 7 posts just like the code above and I have to get H3 and the first table from each of it.

I have tested it but not sure that is it a correct way or not: http://ift.tt/1GF5z8P

But as you can see that I have to add unwanted data too like H4 DT IMG :(

This regex doesn't work in c++

It is supposed to match "abababab" since "ab" is repeated more than two times consecutively but the code isn't printing any output. Is there some other trick in using regex in C++.

I tried with other languages and it works just fine.

#include<bits/stdc++.h>

int main(){

  std::string s ("xaxababababaxax");
  std::smatch m;
  std::regex e ("(.+)\1\1+");   

   while (std::regex_search (s,m,e)) {
    for (auto x:m) std::cout << x << " ";
    std::cout << std::endl;
    s = m.suffix().str();
  }

  return 0;
}

Redirect Loops and .htaccess

I just moved from a CentOS dedi to an Ubuntu VPS. The site is custom coded PHP.

Frontend works fine (including rewrite rules). The admin backend I can't get rewrite rules to work...

First error:

H00124: Request exceeded the limit of 10 internal redirects due to probable configuration error. Use 'LimitInternalRecursion' to increase the limit if necessary. Use 'LogLevel debug' to get a backtrace.

Then after using debug level:

AH00122: redirected from r->uri = /admin/index.php

The relevant bits of my htaccess are:

# mod_rewrite set:

Options +Includes

RewriteEngine on

# Administration
RewriteCond %{REQUEST_URI} ^(/+)admin/(.*)$
RewriteRule (.*) %{DOCUMENT_ROOT}/admin/index.php [L,QSA]

# Rewrite orther
RewriteCond %{REQUEST_URI} !^(/+)index.php(.*)$
RewriteCond %{REQUEST_URI} !^(/+)syscmd.php$
RewriteRule ^(.*)$ %{DOCUMENT_ROOT}/index.php?page=$1 [L,QSA]

# If Rewriting Failure, Show error message (Internal backup)
RewriteCond %{REQUEST_URI} !^(/+)index.php$
RewriteCond %{REQUEST_URI} !^(/+)syscmd.php$
RewriteRule (.*) \1 [F]

This was working fine on CentOS too.

Any ideas? I already tried adding the following as the first condition:

RewriteCond %{REQUEST_URI} !/admin/ [NC]

That stopped it rewriting /admin completely.

Thanks

Grouping Output Pattern in Regex- Python

I would like to get only the sentences which match the regex pattern as output and avoid these NONE, how do i group the output which matches the pattern?

import re regex = re.compile('(.*)(?:India)') with open("D:/txt_res/abc.txt") as f: for line in f: result = regex.search(line) print(result)

The output which im getting is

None

None

None

<_sre.SRE_Match object; span=(0, 101), match='Email: abc.bitz@gmail.com >

None

None

None

<_sre.SRE_Match object; span=(0, 47), match='XYZ Engineer at ABC Organization, India'>

None

None

<_sre.SRE_Match object; span=(0, 32), match='Intern at S360, India'>

None

None

Using replace() replaces too much content

I'm using replace() to transform t in gwhen tis not followed by a letter p, I'm using this line of code:

"tpto".replace(/(t)[^p]/g, "g");

However, the result of this function is tpgand I was expecting tpgo. As I don't know which letter will follow the t I need something dynamic but I don't know what to do, any ideas?

Java String Replace Using Reular Expression

Original String: Flexible Premium Deferred Annuity (Policy #0410011)

Expected String : Flexible Premium Deferred Annuity

Would appreciate if someone can provide java code to accomplish this.

Thanks.

Download site with selected CGI input

So I have this script:
http://ift.tt/1JrcpWF
How do I download for example, file which has input 1880: http://ift.tt/1SUjWig from this site
They are all cgi files and when I enter http://ift.tt/Y9onHf, it gaves me output for 2013. But I checked the code of the sites and there is input for year and number of entries. So how do I select the entry I need using Python?

Extracting using a string pattern in Regex- Python

Cant we give a string in the Regex? For example, re.compile('((.*)?=<Bangalore>)'), in the below code i have mentioned <Bangalore> but its not displaying.

I want to extract the text before Bangalore.

import re

regex = re.compile('((.*)?=<>)')

line = ("Kathick Kumar, Bangalore who was a great person and lived from 29th 

March 1980 - 21 Dec 2014")

result = regex.search(line)

print(result)

Desired output: Kathick Kumar, Bangalore

How to censor website links?

I've been working on a regex censor for quite the time and can't seem to find a decent way of censoring address links (and attempts to circumvent that).

Here's what I got so far, ignoring escape sequences:

([a-zA-Z0-9_-]+[\\W[_]]*)+(\\.|[\\W]?|dot|\\(\\.\\)|[\\(]?dot[\\)]?)+([\\w]{2,6})((\\.|[\\W]?|dot|\\(\\.\\)|[\\(]?dot[\\)]?)([\\w]{1,4}))*

I'm not so sure what might be causing the problem but however it censors the word "com" and "come" and pretty much anything that is about 3+ letters.

Problem: I want to know how to censor website links and invalid links that are attempts to circumvent the censor. Examples:

Google.com

goo gle .com

g o o g l e . c o m

go o gl e % com

go og le (.) c om

Also a slight addition, is there a possible way to add links to a white list for this? Thank you.

regex encapsulation

I've got a question concerning regex.

I was wondering how one could replace an encapsulated text, something like {key:23} to something like <span class="highlightable">23</span, so that the entity will still remain encapsulated, but with something else.

I will do this in JS, but the regex is what is important, I have been searching for a while, probably searching for the wrong terms, I should probably learn more about regex, generally.

In any case, is there someone who knows how to perform this operation with simplicity?

Thanks!

samedi 27 juin 2015

Converting perl snippet to java

I want to rewrite a perl code in java:

sub validate_and_fix_regex {
    my $regex = $_[0];
    eval { qr/$regex/ };
    if ($@) {
        $regex = rquote($regex);
    }
    return $regex;
}

sub rquote {
    my $string = $_[0] || return;
    $string =~ s/([^A-Za-z_0-9 "'\\])/\\$1/g;
    return $string;
}

the code gets a regex and fix it if it has any escaped character. i cant find any alternative for eval { qr/$regex/ }; and $string =~ s/([^A-Za-z_0-9 "'\\])/\\$1/g; in java.

Regex Look Ahead

Today for a project I was trying to make use of regular expression and learnt about groups and how to use them. I am using this site to test it.The problem is that whenever I write the following regex:

(?=\S*\d)

, the site gives me an error : the expression can match 0 characters and therefore can match infinitely.

while this doesn't throw any error :

(?=\S*\d)(\S{6,16})

can anyone explain to me what is the meaning of the error.

PHP regex strip coma and space from beginning and end of string

I have some strings like this

", One "
", One , Two"
"One, Two "
" One,Two, "
" ,Two ,Three "

and need to remove space and or coma at beginning and end of string only tried few regex with preg_replace(), but they replace all occurrences.

EDIT: Actually would be great to remove all clutter like !@#$%^&*( etc whatever is at the end and beginning of string, but not in between.




Optionally need to make strings look proper by placing word then coma then space then another word (if there's coma one in between words).

Example "One,Two ,Three , Four" into "One, Two, Three, Four".

P.S. Please provide answer as two separate regex as its easier to understand.

In C#, how can I get the start/end indexes of all the replacements by the Regex.Replace() function

I have made a program to highlight the phrases in the input matched by a given Regex expression on the fly.

However, I want to highlight the replacements in the output panel too. To do this, I need to obtain the indexes and lengths found by Regex.Replace(). Unfortunately, it would seem C# doesn't give access to this data. Have I missed something?

I've thought about manually trying to figure out the indexes by accumulating sums given off from the MatchCollection produced by Regex.Matches(). But this is prone to error, and may not take into account the special $ symbol in the replace expression which could throw the figures off.

There must be a more elegant way.

Regex Expression replacing spaces in both end of the word

enter image description here

http://ift.tt/1ICDGzE

/(^|\s):bin:(\s|$)/gm

It is unable to scan and replace the one in the middle. How can I fix that without repeating replace() twice.

variable expansion as a pattern in sed not working

I've a simple script to set several parameters in /etc/ssh/sshd_config :

#! /bin/bash

declare -a param=('Banner' 'ClientAliveInterval' 'ClientAliveCountMax' 'Ciphers' \
'PermitUserEnvironment' 'PermitEmptyPasswords' 'PermitRootLogin' \
'HostbasedAuthentication' 'IgnoreRhosts' 'MaxAuthTries' \
'X11Forwarding' 'LogLevel'\
)

declare -a val=('/etc/issue.net' '300' '0' 'aes128-ctr,aes192-ctr,aes256-ctr' \
'no' 'no' 'no' 'no' 'yes' '4' 'no' 'INFO' \
)

for (( i=0;i<12;i++ ))
do
 #echo "${param[$i]} ${val[$i]}"
  egrep "^[ #]*${param[$i]}.*" /etc/ssh/sshd_config &> /dev/null
   if [ $? -eq 0 ];
    then
       sed -i "s|^[ #]*\$param[$i].*|${param[$i]} ${val[$i]}|1" /etc/ssh/sshd_config
  else
       echo "${param[$i]} ${val[$i]}" >> /etc/ssh/sshd_config
  fi
done;

However the variable expansion in sed pattern match is not working as desired:

sed -i "s|^[ #]*\$param[$i].*|${param[$i]} ${val[$i]}|1" /etc/ssh/sshd_config

Can someone help me. My array expansion and everything in the script is fine though. I've checked the same with an echo printout.

Regex Expressions For Emoji

http://ift.tt/1LneX8A

function custom() {
var str = document.getElementById('original').innerHTML;
var replacement = str.replace(/\B:poop:\B/g,'REPLACED');
document.getElementById('replaced').innerHTML = replacement;
}
custom()

Yes = :poop: should be replaced with "REPLACED" No = :poop: should not be replaced. In other words, remain untouched.

Number 4, 5, 6 doesn't seems to follow the rule provided. I do know why, but I don't have much idea how to combine multiple expressions into one. I have tried many others but I just can't get them to work the way I wanted them to be. Odds aren't in my favor.

And yes, this is very similar to how Facebook emoji in chat box works.

New issue:

enter image description here

http://ift.tt/1ICDGzE

/(^|\s):bin:(\s|$)/gm

It is unable to scan and replace the one in the middle. How can I fix that?

Python regex: Matching a URL

I have some confusion regarding the pattern matching in the following expression. I tried to look up online but couldn't find an understandable solution:

imgurUrlPattern = re.compile(r'(http://i.imgur.com/(.*))(\?.*)?')

What exactly are the parentheses doing ? I understood up until the first asterisk , but I can't figure out what is happening after that.

This is a code from Thinking in Java, I do not understand the output of the code. Please somebody help me

//I am trying to learn Java Regex and encountered a code on which I am stuck from a long while, please explain me the working of this code. //The command line arguement is //String args[] = "abcabcabcdefabc "abc+" "(abc)+" "(abc){2,}"

import java.util.regex.*;

public class PatternMatcher {

public static void main(String[] args) {    
    if(args.length < 2) {     
        System.out.println("Usage:\njava TestRegularExpression " +       
        "characterSequence regularExpression+");       
        System.exit(0);     
        }   

        System.out.println("Input: \"" + args[0] + "\"");    
        for(String arg : args) {      
        System.out.println("Regular expression: \"" + arg + "\"");      
        Pattern p = Pattern.compile(arg);      
        Matcher m = p.matcher(args[0]);       

        while(m.find()) { 
            System.out.println("Match \"" + m.group() + "\" at positions " +        
        m.start() + "-" + (m.end() - 1));      
            }   
        }  
    } 
} 

Output:- Input: "abcabcabcdefabc" Regular expression: "abcabcabcdefabc" Match "abcabcabcdefabc" at positions 0-14 Regular expression: "abc+" Match "abc" at positions 0-2 Match "abc" at positions 3-5 Match "abc" at positions 6-8 Match "abc" at positions 12-14 Regular expression: "(abc)+" Match "abcabcabc" at positions 0-8 Match "abc" at positions 12-14 Regular expression: "(abc){2,}" Match "abcabcabc" at positions 0-8

python regex use capture group to define another groups length { }

I am parsing hex data with python regex. I have the following packet structure:

'\xaa\x01\xFF\x44'

  • \xaa - start of packet
  • \x01 - data length [value can vary from 00-FF]
  • \xFF - data
  • \x44 - end of packet

i want to use python regex to indicate how much of the data portion of the packet to match as such:

r = re.compile('\xaa(?P<length>[\x00-\xFF]{1})(.*){?P<length>}\x44')

this compiles without errors, but it doesnt work (i suspect because it cannot convert the hex value to an appropriate integer) Is there a method by which this can be accomplished in python?

Background: I have been using erlang for packet unpacking and I was looking for something similar in python

Using arrays in regular expressions?

Does anyone know if there is a way to use an array in a regular expression? suppose I want to find out if somefile.txt contains one of an array's elements. Obviously the code below doesn't work, but is there something similar that does work?

array = [thing1 thing2 thing3]
file = File.open("somefile.txt")

file.each_do |line|
if /array/.match(line)
puts line
end

Basically I've got a big list of words to search for, and I'd like to avoid something like this:

($somefile =~ /(thing1|thing2|thing3)/)

Appending a line just after the matched pattern in sed not working

My /etc/pam.d/system-auth-ac has the below auth parameters set:

auth        required      pam_env.so
auth        sufficient    pam_unix.so nullok try_first_pass
auth        requisite     pam_succeed_if.so uid >= 500 quiet
auth        required      pam_deny.so

I want to insert pam_tally2.so just after pam_env.so. So I want it to be:

auth        required      pam_env.so
auth        required      pam_tally2.so onerr=fail audit silent deny=5 unlock_time=900
auth        sufficient    pam_unix.so nullok try_first_pass
auth        requisite     pam_succeed_if.so uid >= 500 quiet
auth        required      pam_deny.so

The script that I'm using is :

#! /bin/bash

grep "pam_tally2" /etc/pam.d/system-auth-ac &> /dev/null
if [ $? -ne 0 ];
then
   sed -i '/^[]*account[]*required[]*pam_unix.so/aauth\trequired\tpam_tally2.so onerr=fail audit silent deny=5 unlock_time=900' /etc/pam.d/system-auth-ac
else
   sed -i 's/.*pam_tally2.*/auth\trequired\tpam_tally2.so onerr=fail audit silent deny=5 unlock_time=900/1' /etc/pam.d/system-auth-ac
fi

But it gives this error:

sed: -e expression #1, char 116: unterminated address regex

What am I doing wrong ?

generate regex only between two number but find all number include 1 to 10

i want to generate regex only between 1 to 10 i use this

(10|[1-9])

but notepad++ find all the numbers that start 1 to 10 but i want to find only 1 to 10 numbers not all numbers that include part of 1 to 10

sorry for my poor english

fetch attribute of tag using curl request without domDocument in php using regex only

i have URL : https://mobile.twitter.com/session/new

want to find <meta name="csrf_id" content="ce7754058e42523e84e0443138f28f33"> and want to fetch only ce7754058e42523e84e0443138f28f33 value as output. content value may change according to your browser.

I dont want to use domDocument i have to do with regex only

Note : you have to open this URL in mozilla firefox only then only you will find <meta name="csrf_id" content="ce7754058e42523e84e0443138f28f33"> you wont be find this tag in any other browser

How do I report only one error for an XML validation failure of a single element?

I would like to know how to return only one error message when an element fails XML schema date validation. My goal was to preserve the validations provided by xs:date (such as February 29, 2015 being invalid due to 2015 not being a leap year), but also ensure that the date is of the pattern with the following regex:

"\d{4}[-]\d{2}[-]\d{2}"

I tried out this in an online XML schema tester, and I got the expected results. The entire schema is as follows:

<xs:schema xmlns:xs="http://ift.tt/tphNwY" elementFormDefault="qualified" attributeFormDefault="unqualified">
                        <xs:element name="tripDate">
                                                    <xs:simpleType>
                                                        <xs:restriction base="xs:date">
                                                            <xs:whiteSpace value="collapse"/>
                                                            <xs:pattern value="\d{4}[\-]\d{2}[\-]\d{2}"/>
                                                        </xs:restriction>
                                                    </xs:simpleType>
                                                </xs:element></xs:schema>

And the test element value I used (among others) is:

<tripDate>20115-02-20</tripDate>

When I entered these into the formatter at http://ift.tt/1lmKPLW , I got the following outputs back:

    Cvc-pattern-valid: Value '20115-02-20' Is Not Facet-valid With Respect To Pattern '\d{4}[\-]\d{2}[\-]\d{2}' For Type '#AnonType_tripDate'.. Line '1', Column '33'.

    Cvc-type.3.1.3: The Value '20115-02-20' Of Element 'tripDate' Is Not Valid.. Line '1', Column '33'.

My question is, how can I ensure that only one error will ever get returned? Specifically, I only want the "Cvc-type" error to be returned, because that comes in the cases when the pattern is invalid, even though the date itself is valid. Is there any kind of schema setting to suppress the "Cvc-pattern-valid" error, or to collapse error into the error of the parent restriction, which in this case is xs:date? I want the "Cvc-type" error only to be returned, because this is what is handled in the Java code for the application, and I am trying not to unnecessarily add Java code to handle the other error as well (at this point it throws an SQL exception error).

Thank you.

RegEx to match nested parentheses including the start and end parentheses

string st = "this (a,b) and this (s,(r,t),u) is a test";
var regex = new Regex(@"\(([^()]+| (?<Level>\()| (?<-Level>\)))+(?(Level)(?!))\)", RegexOptions.IgnorePatternWhitespace);

foreach (Match c in regex.Matches(input))
{
  Console.WriteLine(c.Value.Trim('(', ')'));
}

The above C# code in .NET 4.5 correctly returns:

a,b
s,(r,t),u

But I need the output including the parentheses as:

(a,b)
(s,(r,t),u)

is there any named regular expression capture for grep?

i'd like to know if its possible to get named regular expression with grep -P(linux bash) from a non formatted string? well.. from any string

For example: John Smith www.website.com john@website.com jan-01-2001 to capture as

$name
$website
$email
$date

but it seems I cant pass any variables from output?

echo "www.website.com" | grep -Po '^(www\.)?(?<domain>.+)$' | echo $domain

has no output

fetch attribute of tag using curl request without domDocument in php

i have URL : http://ift.tt/1LvbSlT

want to find <meta name="p:domain_verify" content="1e8715341cd73cff926f648b6dd4a089"/> and want to fetch only 1e8715341cd73cff926f648b6dd4a089 value as output. content value may change according to your browser.

I dont want to use domDocument

The regular expression in the FILTER option of gcovr

I use gcovr to read coverage information for program foo.c. The syntax is

gcovr -r . -b --filter=FILE_PATTERN

where the '-r .' part indicates the current directory as the search root, '-b' is for branch coverage, and the FILE_PATTERN part is to keep only the data files that match this regular expression, according to gcovr's user guide http://ift.tt/1HnhkFK.

So I use this following command line

gcovr -r . -b --filter='foo\\.c'

But this command finds no information regarding foo.c retrieved. It seems I use a wrong regular expression. What do you think?

Mocha Chai regex are equals

I am trying to test the behaviour of a method that produce regex.

Using Mocha/Chai test suite I have the following code :

describe('regexTest',function () {
  it('should return a regexp', function () {
    var regex = regexTest();
    assert.equal(regex, /someregex/);
  });
});

But it seems that the code above doesn't work. I tried in the chrome console :

/a/ == /a/ 
> false

For the moment the only way I found is to compare the toString of the two regex (that should be equals and that I can compare) :

describe('regexTest',function () {
  it('should return a regexp', function () {
    var regex = regexTest();
    assert.equal(regex.toString(), '/someregex/');
  });
});

Do you know a better way to do this ? Because I find this not really clean ...

regex validating url

I have the following urls as subjects

localhost/hx
localhost/h.php
localhost/h/x
localhost/h/x/y
localhsot/h?hello
localhost/h

Currently my pattern is something like /localhost/h[/]*/i, but this does not work.

I do not want to match line 1 or 2, but the others are valid.

  • Problem 1: I am not able to make / or ? optional, if I remove * from the pattern it does not match localhost/h.

  • Problem 2: I am not able to escape ? for line 5, I tried \\ and \ but neither worked.

Adding dot to rewrite rule

I want to add a dot (.) to my variable in the last rewrite rule, and I have no idea where to put it in this syntax. Does it go after A-Z?

ErrorDocument 404 /
ErrorDocument 403 /

Options ALL -Indexes

RewriteEngine On
RewriteRule ^([0-9/.]+)$ index.php?Patch_No=$1 [NC,L]
RewriteRule ^([0-9/.]+)&([0-9a-zA-Z_-]+)$ index.php?Patch_No=$1&tab=$2 [NC,L]
RewriteRule ^patches php/patches.php [NC,L]
RewriteRule ^([\s'0-9a-zA-Z_-]+)$ index.php?Champion=$1 [NC,L]

Notepad++ replace n characters in a certain pattern

In Notepad++ version 6.7.8.2, I would like to replace the string

<p class=question><b>nn.</b> 

where nn is any charachter 1-20000. (followed by a .)

I've tried expressions, etc. but can't get it to work.

Any help is appreciated.

Matching floating point range using regular expression

I need a regular expression, that matches within a range of floats.

For the range 12.33 - 13.41 I tried the following regex:

(12.[3-9][3-9]|13.?[0-4][0-1]?)\d{0,2}

but it doesn't match i.e. 12.41 or 13.39.

Is this possible with regular expressions?

Kind regards, bernie70

Javascript splitting between number and string with regexp

How can I split following string:

1D11M58S

by means of regexp in javascript?

My result should be:

[1D, 11M, 58S]

thanks

how to adjust javascript regexpression

I need to adjust a regex I am using for a file name. currently the file is structured 02-2015 VRF WE32.pdf the regex splits up the string into 3 pieces by the spaces. This works fine. the result is

02-2015
VRF
WE32

But now i need to split the string into 4 pieces. the 4th being the digits in the 'WE32'. so it needs to look like this

02-2015
VRF
WE
32

Here is what I am using, including some screenshots

var matchesPip = file.name.match(/^\d+\D\d+\s*(\S*\s*)(\S*)/i);
var matchesLoc = file.name.match(/^\d+\D\d+\s*?(\S*)\s*(\S*?)\./i);
var matchesLocCode = file.name.match(NEED HELP HERE);
    $scope.pip = $scope.pipeLookup[matchesPip[1]];
    $scope.loc = $scope.locationLookup[matchesLoc[2]];
    $scope.locCode = $scope.locationCodeLookup[matchesLocCode[3]];

pic1 pic2 pic3

JavaCC - Match some words except some others

I am trying to create a parser for first-order logic using the javacc and I have the following problem.

I have this:

< VARIABLE : < LOWER > (< INNER >)* >

where

< #INNER :
( < UPPER >
| < LOWER >
| < DIGIT >
| < UNDERSCORE > ) >

< #DIGIT : [ "0"-"9" ] >
< #LOWER : [ "a"-"z" ] >
< #UPPER : [ "A"-"Z" ] >
< #UNDERSCORE: "_" >

, but I want to exclude some words from this. In particular i want to exclude the words sum, count, avg, max and min. Is there a way to to this? In other words, I want the variables to begin with a lowercase letter followed by any number of inner tokens, where the inner token may be an uppercase letter, a lowercase letter, a digit or an underscore. However, i do not want the variables to take values such as sum, count, avg, max and min.

C++ regex for checking Gomoku win condition

I construct a string that represents my entire Gomoku game board (5x5 for example), where 0 indicates empty, and 1 or 2 indicates black or white.

A string "x" is placed between each row to separate the rows.

std::string state = "00000x012122x00100x00222x010201"

What I'm trying to do is check for a match of 3 for the current player horizontally (I will deal with vertical and diagonal later); let's say, white, so I am looking for a match of three 2's sequentially in the string, and only three 2's.

Gomoku does not allow overline, which means the regular expression cannot match 4 or more.

Here is my attempt at the problem:

bool Game::check_horizontal(std::string state)
// Checks if the current_player (stored in the class) has won horizontally.
{
    std::string pattern = "(" + std::to_string(current_player) + "{3})"; // Current player is white by default.
    std::regex reg1(pattern);
    if (regex_search(state, reg1) == true)
    {
        std::cout << "Match! Someone has won." << std::endl;
        return true;
    }
    else
    {
        std::cout << "No match... keep going." << std::endl;
        return false;
    }
}

So far it seems that the code works as intended for the state above, but it keeps matching if there are 4 or more of what I'm looking for. If I added another 2 on the 4th row, in the 2nd column, it will still match.

Is there a problem with my regular expression, or my usage of regex?

python regular expression in searching pattern

In Python ,I have pattern as

MY_PATTERN='[^\\\\]*\\\\\\w{0,4}First\\\\.+\\.\\w{3}|[^\\\\]*\\\\\\w{0,4}Second\\\\.+\\w{3}'

I use this pattern to search in my string.

Here What all strings the pattern matches in this case?

Making a [code][/code] for BBcode with php regex

I would like to make a [code][/code] tag for bbcode so that what would be inside wouldn't be taken into account by the php regex that I made.

Example :

Hello [b]newbie[/b], to write in bold, use the following : [code][b](YOURTEXT)[/b][/code]

Should return in HTML :

Hello <strong>newbie</strong>, to write in bold, use the following : [b](YOURTEXT)[/b]

Here is a view of a part of my bbcode function :

<?
function bbcode($var) {
   $var = preg_replace('`\[b\](.+)\[/b\]`isU', '<strong>$1</strong>', $var); 
   $var = preg_replace('`\[i\](.+)\[/i\]`isU', '<em>$1</em>', $var);
   $var = preg_replace('`\[u\](.+)\[/u\]`isU', '<u>$1</u>', $var);
   return $var;
}
?>

Thank you in advance for your kind help !


EDIT : Here is how I finally made it work :

<? 
function bbcode($var) {
$var2 = preg_split('`(\[code].*?\[/code])`isU', $var, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);

$var = preg_replace('`\[b\](.+)\[/b\]`isU', '<strong>$1</strong>', $var); 
$var = preg_replace('`\[i\](.+)\[/i\]`isU', '<em>$1</em>', $var);
$var = preg_replace('`\[u\](.+)\[/u\]`isU', '<u>$1</u>', $var);

$var = preg_replace('`(\[code].*?\[/code])`isU', $var2[1], $var);
$var = preg_replace('`\[code\](.+)\[/code\]`isU', '<div>$1</div>', $var);
return $var;
}

$text = 'Hello [b]newbie[/b], to write in bold, use the following [u]lol[/u] : [code][b](YOURTEXT) [u]lol[/u][/b][/code] [b][u]LOL[/u][/b]';

echo bbcode($text); 
?>

HOWEVER, there is a new problem left : if the character chain starts directly with '[code]' for example

[code][b]hello[/b][/code] test

than the result will be :

test test

This is because $var2[1] now leads to what comes after the [/code].

Could someone please help me to make a better delimitation that would also work for that second character chain ? Thank you in advance !

SED, deleting lines between the patterns

This is regarding deleting the lines between the pattern excluding the lines with pattern using SED. If the seconds pattern appears twice or thrice.. i want the lines to be deleted till the last occurrence of the second pattern.. Please help me in writing the regex for this.. Thanks a lot.

Extracting users from twitter status in R. Non-trivial cases like RT@user @user:

I want to extract usernames from a tweet where these usernames may be:

  • followed by some non-alphanumerical characters.
  • not preceded by a white space.

I have this:

    text <- "RT@user1: This is a retweet that mentions @user2."
    tokens <- unlist(strsplit(text, " "))
    mentions.mask <- grepl("@\\w+", tokens)
    mentions <- tokens[mentions.mask]
    mentions
    [1] "RT@user1:" "@user2."

But I would like to get just @user1 and @user2

How can I do it?

Parse text between multiple lines - Python 2.7 and re Module

I have a text file i want to parse. The file has multiple items I want to extract. I want to capture everything in between a colon ":" and a particular word. Let's take the following example.

Description : a pair of shorts
amount : 13 dollars
requirements : must be blue
ID1 : 199658
----

The following code parses the information out.

import re

f = open ("parse.txt", "rb")
fileRead = f.read()

Description = re.findall("Description :(.*?)amount", fileRead, re.DOTALL)
amount = re.findall("amount :(.*?)requirements", fileRead, re.DOTALL)
requirements = re.findall("requirements :(.*?)ID1", fileRead, re.DOTALL)
ID1 = re.findall("ID1 :(.*?)-", fileRead, re.DOTALL)

print Description[0]
print amount[0]
print requirements[0]
print ID1[0]

f.close()

The problem is that sometimes the text file will have a new line such as this

Description 
: a pair of shorts
amount 
: 13 dollars
requirements: must be blue
ID1: 199658
----

In this case my code will not work because it is unable to find "Description :" because it is now separated into a new line. If I choose to change the search to ":(.*?)requirements" it will not return just the 13 dollars, it will return a pair of shorts and 13 dollars because all of that text is in between the first colon and the word, requirements. I want to have a way of parsing out the information no matter if there is a line break or not. I have hit a road block and your help would be greatly appreciated.

How to create regular expression starting with different directory name in Python

Currently I am taking directory path as input from the user. The path will be different for each user(dir_name will be different)

/file/perm/perm13/user123/dir_name/ 

while the structure inside dir_name is same for all users given as below:

tar1 tar2 tar3 tar4 tar5 tar6 source

In each tar, three folders are there: build collateral fix in collateral: I have three different files

 _base.txt, _fullbase.txt and _skip.txt 

I also need corresponding .dot files from source/projectfiles/params/tar_base.dot | tar_fullbase.dot | tar_skip.dot

Here is what I need to do:
1. Take input from user 2. One by one- go into the targets. (tar1 -> tar2 -> tar3 ->tar4 ->tar5) 3. For each tar, search for collateral folder 4. and in collateral folder search for all three .txt files 5. for each .txt file search for corresponding .dot file

currently I do following: I take path for txt from the user

txtfilepath = raw_input (" Please provide file path for the desired txt")
dotfilepath = raw_input (" Please enter corresponding .dotfilepath")
<directory path>/<tar1>/collateral/<xyz_base.txt)

The regex:

platform = re.search("?<=/collateral/).(?="_(base|fullbase|skip)\.txt)",txtfilepath).group(0)

can some python geek help?

python regex to split by comma or space (but leave strings as it is)

I need to split a string by space or by comma. But it should leave single or double quoted strings as it is. Even if it is apart by many spaces or a single space it makes no difference. For e.g.:

    """ 1,' unchanged 1' " unchanged  2 "   2.009,-2e15 """

should return

    """ 1,' unchanged 1'," unchanged  2 ",2.009,-2e15 """

There may be no or more spaces before and after a comma. Those spaces are to be ignored. In this particular context, as shown in the ex string, if two quoted or double quoted strings happen to be next to each other, they will have a space in between or a comma.

I have a previous question at python reg ex to include missing commas, however, for that to work a splitting comma should have a space after.

How to translate a Ruby regex to JavaScript?

In Ruby I have a regex to get a string formatted like "@xxx":

(/(?<!\S)@[A-Za-z0-9\-]+/)

I also need this regex on the client side, but JavaScript can't read this.

How can I change this regex to JavaScript?

How to isolate only the first space in a string using regex?

I have a foreign language to English dictionary that I'm trying to import into a sql database. This dictionary is in a text file and the lines look like this:

field1 field2 [romanization] /definition 1/definition 2/definition 3/

I'm using regex in python to identify the delimiters. So far I've been able to isolate every delimiter except for the space in-between field 1 and field 2.

(?<=\S)\s\[|\]\s/(?=[A-Za-z])|/
#(?<=\S)\s\[  is the opening square bracket after field 2
#\]\s/(?=[A-Za-z]) is the closing square bracket after the romanization
#/ is the forward slashes in-between definitions.
#????????? is the space between field 1 and field two

samedi 9 mai 2015

Angular - Testing a websocket wrapper with jasmine

I'm having trouble testing my websocket wrapper: data-service is my Angular service to wrap around the native browser WebSocket implementation.

Implementation:

angular.module('core').factory('dataService', function ($interval, webSocket) {

  var sock;

  function openSocket() {
    sock = new webSocket('ws://localhost:9988');
  }

  function isReady() {
    return sock.readyState === 1;
  }

  openSocket();

  $interval(function () {
    !isReady() && openSocket();
  }, 5000);
});

webSocket is window.WebSocket extracted to an angular constant.

Test:

describe('Data Service', function () {

  var dataService,
    ws;

  jasmine.DEFAULT_TIMEOUT_INTERVAL = 15000;

  beforeEach(function () {
    module('core', function ($provide) {
      ws = jasmine.createSpy('constructor');
      $provide.constant('webSocket', ws);
    });

    inject(function (_dataService_) {
      dataService = _dataService_;
    });
  });

  it('should attempt to connect on load', function () {
    expect(ws).toHaveBeenCalled();
  });

  it('should attempt to reconnect every 5 seconds', function (done) {
    setTimeout(function () {
      expect(ws.calls.count()).toBe(2);
      done();
    }, 6000);
  });
});

should attempt to connect on load

passes: it was called once as expected.

should attempt to reconnect every 5 seconds

fails: no matter what timeout period I pass to setTimeout it's only ever called once. I'm wondering if this is due to the socket being re-instantiated every reconnect attempt with the new keyword. I'm not really familiar with how using new in javascript differs to using a normal function to construct an object.

Am I missing something? Or is the browser's WebSocket just a pain to test around?

Nesting ng-repeat at single level of DOM

I have nested collections, as follows:

[
  {
    name:    "foo",
    members: ["foo1","foo2"]
  }, {
    name:    "bar",
    members: ["bar1","bar2","bar3"]
  }, {
    name:    "qux",
    members: []
  }
]

From this, I would like to generate the following markup:

<tbody>
  <tr>
    <th scope="row" rowspan="2">foo</th>
    <td>foo1</td>
  </tr><tr>
    <td>foo2</td>
  </tr><tr>
    <th scope="row" rowspan="3">bar</th>
    <td>bar1</td>
  </tr><tr>
    <td>bar2</td>
  </tr><tr>
    <td>bar3</td>
  </tr>
</tbody>

It would also be acceptable to repeat the <th> cells in each row, if rowspan proves too awkward to work with:

<tbody>
  <tr>
    <th scope="row">foo</th>
    <td>foo1</td>
  </tr><tr>
    <th scope="row">foo</th>
    <td>foo2</td>
  </tr><tr>
    <th scope="row">bar</th>
    <td>bar1</td>
  </tr><tr>
    <th scope="row">bar</th>
    <td>bar2</td>
  </tr><tr>
    <th scope="row">bar</th>
    <td>bar3</td>
  </tr>
</tbody>

What is the idiomatic way to accomplish a task like this using AngularJS? In particular, I'm struggling to see how one can perform a nested ng-repeat at a single level of the DOM (i.e. on the <tr> element).

AngularJS, Web API authentication

Problem Statement:

I am using AngularJS as my front end, I have a service layer to get/save data from/to database. Before doing this I want to authenticate the user and perform actions based on role of the user. I am using SQL Server as my database.

What I tried:

I tried having an endpoint expose and validate the user for every request. I tried having a session but unfortunately I somehow feel it is obsolete method and may be (because I have not tried on mobile) will not work fine with mobile.

What I am looking for

I am looking for token based authentication, to validate user against the SQL Server table and return a token and validate token for every request.

Can someone suggest me some links with custom database.

Note: If my request is not asking for too much, I would like to learn doing this using OWIN. If someone can suggest me OWIN method for my above request, I would be glad.

how to pass only two properties to a $scope variable

ANGULARJS Question:

I got an array of objects and I need to pass it to my $scope variable. THe property that's creating a problem for me in special is the 'user:' property. since it holds elements like the name and email it affects the way the filter i set in the HTML is filtering the objects I want to display. The object is a list of notes and I want to be able to filter them by content in the note( title and body text)

I have tried to delete the property user from the object with the code below, but that does not work. $scope.notes still loads that attribute.

Ideally I should be able to pass to $scope.notes only the title and body attributes. Any ideas of how to do that efficiently?

 var notes = notesService.notesObjectInService;
    for (var i = 0;  i < notes.length; i++) {
        delete notes[i].user;
    };

    $scope.notes = notes;

This is the json object passed to notes in the first line.

[{"id":184,
"title":"Mari",
"body":"Mae",
"created_at":"2015-05-09T03:23:04.250Z",
"updated_at":"2015-05-09T03:23:04.250Z",
"user_id":1,
"user":{"id":1,
"email":"vini@vini.com",
"created_at":"2015-04-24T22:49:21.797Z",
"updated_at":"2015-05-09T03:04:27.739Z",
"username":"vinivini"}}]

angular.js: Dynamic navigation depending on login status

I have following routing with athentication, which is done via a PHP-Script and MySQL:

app.config

app.config(['$routeProvider',
  function ($routeProvider) {
        $routeProvider.
        when('/login', {
            title: 'Login',
            templateUrl: 'partials/login.html',
            controller: 'authCtrl'
        })
        .when('/logout', {
            title: 'Logout',
            templateUrl: 'partials/login.html',
            controller: 'logoutCtrl'
        })

        .when('/dashboard', {
            title: 'Dashboard',
            templateUrl: 'partials/dashboard.html',
            controller: 'authCtrl'
        })
        .otherwise({
            redirectTo: '/login'
        });
  }])
    .run(function ($rootScope, $location, Data) {
        $rootScope.$on("$routeChangeStart", function (event, next, current) {
            $rootScope.authenticated = false;
            Data.get('session').then(function (results) {
                if (results.uid) {
                    $rootScope.authenticated = true;
                    $rootScope.uid = results.uid;
                    $rootScope.name = results.name;
                    $rootScope.email = results.email;
                } else {
                    var nextUrl = next.$$route.originalPath;
                    if (nextUrl == '/signup' || nextUrl == '/login') {

                    } else {
                        $location.path("/login");
                    }
                }
            });
        });
    });

authCtrl

app.controller('authCtrl', function ($scope, $rootScope, $routeParams, $location, $http, Data) {
    $scope.login = {};
    $scope.signup = {};
    $scope.doLogin = function (customer) {
        Data.post('login', {
            customer: customer
        }).then(function (results) {
            Data.toast(results);
            if (results.status == "success") {
                $location.path('dashboard');
            }
        });
    };
    $scope.signup = {email:'',password:'',name:'',phone:'',address:''};
    $scope.signUp = function (customer) {
        Data.post('signUp', {
            customer: customer
        }).then(function (results) {
            Data.toast(results);
            if (results.status == "success") {
                $location.path('dashboard');
            }
        });
    };
    $scope.logout = function () {
        Data.get('logout').then(function (results) {
            Data.toast(results);
            $location.path('login');
        });
    }
});

Now I want to change the navigation depending on the login-status. If user is logged in there should bei a logOUT-Button and a link to the dashboard. If the user isn't logged in it should look like this

sample for unlogged-in user

<header id="navigation">
    <nav id="main">
        <ul>
            <li id="login"><a href="#/login" class="btn"><i class="fa fa-power-off"></i> Login</a></li>
        </ul>
    </nav>
</header>

What is the best way for creating the navigation? Should it be a seperate template?

QuantumUI Pagination

I'm new to Angularjs and trying to do pagination in Quantumui for which i get data from RestAngular, i can able to create pagination using ng-Table successfully for the same connects but i'm but cant able to do the same with Quantumui's '$pageableProvider' i tried it as below help me to understand the concept of Quantumui.

I Get the Following Error:

Uncaught Error: [$injector:modulerr] Failed to instantiate module restAngular due to:
Error: [$injector:modulerr] Failed to instantiate module nqPageable due to:
Error: [$injector:nomod] Module 'nqPageable' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument

My App.js:

i use RestAngular to get data

var get = angular.module('get', []);

var myApp =angular.module('restAngular',[
    'restangular',
    'get',
    'create',
    'ngSanitize',
    'ngAnimate',
    'ngQuantum',
    'nqPageable',
    'ngTable'
])
myApp.config([
    'RestangularProvider',
    '$pageableProvider',
    function(RestangularProvider,$pageableProvider){
        RestangularProvider.setBaseUrl('http://localhost:1337/lb4b/api/');
        var mydefaults = {
            seletable : true,
            pageNumber : 1,
            pageSize : 5
        }
        angular.extend($pageableProvider.defaults, mydefaults)
    }
])

get.controller('getCtrl',[
    'Restangular',
    '$scope',
    'ngTableParams',
    '$filter',
    function(Restangular,$scope,ngTableParams,$filter){

        var userData = Restangular.all('User').getList().then(
            function(user){
                $scope.users = user;
                //This is to check the data has passed succes
                console.log(user[0].business_category);
                //console.log(user.length);            
                //console.log('x  is :'+x );
            }
        )
    }
]);

Can Some one help me to understand the concept of pagination used in quantumui.

Thanks in advance.

Front-end development with conditional HTTP and HTTPs routes

I am currently using MEAN stack for web development. My questions is how do I mix HTTP and HTTPs on the same website?

For most scenarios I am communicating with the back-end using HTTP protocol. And for some pages I absolutely need to use HTTP (For example #!/shop/:shopId route, I used an iframe that displays info from other websites. and some pages I need to HTTP GET some info from other API services.) It seems that I cannot achieve these with HTTPs setup.

For some cases I am communicating with the back-end using HTTPs (such as #!/money route) ...etc. And apparently you need HTTPs with money involved.

My back-end has middlewares setup so that if you request /money using HTTP it will return some error (currently returning 301 but not sure if this sound correct..).

But I am not sure how do I proceed with front-end development. For angular should I just do some configurations so when the route consists of /money I just reload the whole page in HTTPs or should I just explicitly make sure the links look someting like this?

<a ng-href="http://ift.tt/1GVe3sV">money page</a>

But that seems like a lot of hard-coding for me.

My question is: 1. Am I thinking in the right direction?
2. Is it doable?

Thanks and any idea is greatly appreciated!

angular js ng-view returns blanc partials -- Express/ Jade

I am writing an angular application following a tutorial. To my surprise, i followed exactly and my node js is starting fine without an issue. However, my angular is not returning the template as suppose to . I saw a similar problem here same tutorial and the same issue. However, the question was not answered . Below is my dir structure

app.js

var app = angular.module('app', ['ngResource', 'ngRoute']);

angular.module('app').config(function($routeProvider, $locationProvider){
    $locationProvider.html5Mode(true);
    $routeProvider
        .when('/', { templateUrl: 'partials/main', controller: 'mainCtrl'});
});


angular.module('app').controller('mainCtrl', function($scope){
    $scope.myVar = "Hello Angular";
});

My layout.jade

doctype html
head
   link(rel="styleSheet",href="css/bootstrap.css")
   link(rel="styleSheet",href="vendor/toastr/toastr.css")
   link(rel="styleSheet",href="css/site.css")
body(ng-app='app')
   block main-content
   include scripts

My main.jade

h1 This is a partial
h2 {{ myVar }}

The route in my server.js are set as

app.get('partials/:partialPath',function(req,res){
    res.render('partials/' + req.params.partialPath);
});
app.get('*', function(req,res){
    res.render('index');
});

my index.jade

extends ../includes/layout

block main-content
    section.content
       div(ng-view)

Althought i am thinking that shouldn't be an issue because i am starting with a partial view which is part of a page. When i run, my page return black. I inspect the element and ensured that all the js and css where loaded. When i view the source, a html source below was generated.

<!DOCTYPE html>
<head><link rel="styleSheet" href="css/bootstrap.css">
<link rel="styleSheet" href="vendor/toastr/toastr.css">
<link rel="styleSheet" href="css/site.css">
</head>
<body ng-app="app">
  <section class="content">
   <div ng-view></div></section>
   <script type="text/javascript" src="vendor/jquery/dist/jquery.js"></script><script type="text/javascript" src="vendor/angular/angular.js"></script>
<script type="text/javascript" src="vendor/angular-resource/angular-resource.js"></script>
<script type="text/javascript" src="vendor/angular-route/angular-route.js"></script><script type="text/javascript" src="app/app.js"></script>
</body>

I was suspecting routeProvider from my app.js here

.when('/', { templateUrl: 'partials/main', controller: 'mainCtrl'});

tried

.when('/', { templateUrl: '/partials/main', controller: 'mainCtrl'});

All to no avail . please where do i go wrong ? I have tried everything possible. I even restarted the tut yet still blanc. any help would be appreciated.

How to update html header after login in an angular/node.js application?

I am trying to get a header to update after login. I have used both $on and $watch in this effort to no avail. When I refresh it works correctly. Code is as follows below.

header.html (missing excess nav bar code for simplicity)

<li><a ng-href="#/login" ng-hide="showMenu">Login</a></li>
<li><a ng-href="#/signup" ng-hide="showMenu">Signup</a></li>
<li><a href="javascript:" ng-click="logout()" ng-show="showMenu">Logout</a></li>

app.js

$stateProvider
  .state('app', {
    url: '',
    views: {
      'header': {
            templateUrl: 'views/partials/_header.html',
            controller: 'HeaderCtrl'
      }
    }
  })

header.js (The broadcast fires correctly as demonstrated by the console.logs)

angular.module('urbinsight')
.controller('HeaderCtrl', function ($scope, $rootScope, $state, $location, UserAuthFactory, AuthFactory) {

$scope.logout = function () {
  UserAuthFactory.logout();
  $rootScope.$broadcast('loginStateChange');
  $location.path('/');
};

$scope.showMenu = AuthFactory.loggedStatus();

$rootScope.$on('loginStateChange', function(){
  console.log($scope.showMenu)
  $scope.showMenu = AuthFactory.loggedStatus(); 
  console.log($scope.showMenu)
  })
})

authService

angular.module('urbinsight.services')
.factory('AuthFactory', function ($window) {
var isLogged = false;

return {
  check: function() {
    if ($window.sessionStorage.token && $window.sessionStorage.user) {
      isLogged = true;
    } else {
      isLogged = false;
      delete this.user;
    }
  },
  loggedStatus: function() {
    return isLogged;
  },
  changeLoggedStatus: function() {
    isLogged = !(isLogged);
  }
};
})

Please tell me what I am doing wrong.

angular partial not rendering with jade

I am building an angular app following a tut. However, my angular ng-view is not rendering. I have seen a similar question here yet it has not been answered. Below is my dir structure

app.js

var app = angular.module('app', ['ngResource', 'ngRoute']);

angular.module('app').config(function($routeProvider, $locationProvider){
    $locationProvider.html5Mode(true);
    $routeProvider
        .when('/', { templateUrl: 'partials/main', controller: 'mainCtrl'});
});


angular.module('app').controller('mainCtrl', function($scope){
    $scope.myVar = "Hello Angular";
});

My layout.jade

doctype html
head
   link(rel="styleSheet",href="css/bootstrap.css")
   link(rel="styleSheet",href="vendor/toastr/toastr.css")
   link(rel="styleSheet",href="css/site.css")
body(ng-app='app')
   block main-content
   include scripts

My main.jade

h1 This is a partial
h2 {{ myVar }}

The route in my server.js are set as

app.get('partials/:partialPath',function(req,res){
    res.render('partials/' + req.params.partialPath);
});
app.get('*', function(req,res){
    res.render('index');
});

my index.jade

extends ../includes/layout

block main-content
    section.content
       div(ng-view)

Although I am thinking that shouldn't be an issue because I am starting with a partial view which is part of a page. When I run my page it returns black. I inspected the elements and ensured that all the js and css where loaded. The html source below was generated on my page:

<!DOCTYPE html>
<head><link rel="styleSheet" href="css/bootstrap.css">
<link rel="styleSheet" href="vendor/toastr/toastr.css">
<link rel="styleSheet" href="css/site.css">
</head>
<body ng-app="app">
  <section class="content">
   <div ng-view></div></section>
   <script type="text/javascript" src="vendor/jquery/dist/jquery.js"></script><script type="text/javascript" src="vendor/angular/angular.js"></script>
<script type="text/javascript" src="vendor/angular-resource/angular-resource.js"></script>
<script type="text/javascript" src="vendor/angular-route/angular-route.js"></script><script type="text/javascript" src="app/app.js"></script>
</body>

I was suspecting routeProvider from my app.js here

.when('/', { templateUrl: 'partials/main', controller: 'mainCtrl'});

tried

.when('/', { templateUrl: '/partials/main', controller: 'mainCtrl'});

All to no avail. Please where do I go wrong ? I have tried everything possible. I even restarted the tut yet still blank. Any help would be appreciated.

Angular: add HTML markup to string depending on keyboard input

I have an inputfield and I would like to print the input to the screen while I'm filling in the inputfield. However I'd like to scan the input text, to print certain words bold.

So for example, if I'm typing: "Hello how are you?"

I want it to be printed under the input field but Hello has to be in bold: Hello how are you ?

Is there a way in Angular to achieve this?

How to set ng-attr-title using ternary operator in Angularjs?

I am very new to Angularjs. I want to set a value for title attribute, based on a boolean variable.

Sample code attached here.

 <tr ng-repeat="doc in $data" ng-class="{{doc.is_today}} ? 'highlight' : ''" 
                                        ng-attr-title="({{doc.is_today}}) ? 'Today' : ''"> 
     <td>1</td>
     <td>2</td>
     <td>3</td>
     <td>4</td>
     <td>5</td>
</tr>

Thanks,

Facebook connect using django rest framework and angularjs?

Im developing a website in which the user can signup using facebook connect, when he signup we will collect all his personal details from fb and store it in a user table. This user table id is used as foreign key in many other tables. My questions are,

  1. How can I implement fb signup using angularjs and DRF.
  2. Once the user logs in how can I get the corresponding data from related table since I will pass only the authentication token(Do I need to get user id matching the auth token?)
  3. We collect all his details only for the first login, how can we find out whether the user is already registered or not?
  4. Is there any valuable material available online for this?

Im using python-social-auth and oauth for the above, but they are very confusing.

AngularJS disable button during factory AJAX call

I want to disable a button while a factory AJAX request is running (after the button was clicked) and I used this SO answer as a starting point on how to do that, but I can't get my custom directive click-disable to execute the controller method (using ng-click works fine).

I suspect my directives doesn't get "compiled" at page load, directives with simple templates also don't seem to work.

js/services.js:

var raspiSurveillanceServices= angular.module('raspiSurveillanceServices', ['ngResource']);

raspiSurveillanceServices.factory('Camera', ['$resource',
    function($resource) {
        return $resource('/api/cameras/:id');
    }]);

js/directives.js:

var raspiSurveillanceDirectives = angular.module('raspiSurveillanceDirectives', []);

raspiSurveillanceDirectives.directive('clickDisable', function() {
    return {
        restrict: 'A',
        scope: {
            clickDisable: '&'
        },
        link: function(scope, element, attrs) {
            element.bind('click', function() {
                element.prop('disabled', true);

                scope.clickDisable().finally(function() {
                    element.prop('disabled', false);
                });
            });
        }
    };
});

js/controllers.js:

raspiSurveillanceControllers.controller('CameraListCtrl', ['$scope', 'Camera', function ($scope, Camera) {

    $scope.cameras = Camera.query();

    $scope.deleteCamera = function(camera) {
        return Camera.delete({ id: camera.id}).$promise.then(
            function(value) {
                // Remove item from array
                var index = $scope.cameras.indexOf(camera);
                $scope.cameras.splice(index, 1);
            },
            function(error) {
                alert("Delete failed");
            }
        )
    };

}]);

js/app.js:

var raspiSurveillanceApp = angular.module('raspiSurveillanceApp', [
  'raspiSurveillanceControllers',
  'raspiSurveillanceServices',
  'raspiSurveillanceDirectives',

  'xeditable'
]);

.blade.php:

<tr ng-repeat="camera in cameras">
    ...
    <button class="btn btn-danger" click-disable="deleteCamera(camera)">Delete</button>
</tr>
...
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.15/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.15/angular-resource.min.js"></script>

<script src="js/app.js"></script>
<script src="js/controllers.js"></script>
<script src="js/services.js"></script>
<script src="js/directives.js"></script>

Angular Material is slow to load?

When I load my website, sometimes I have to refresh a few times because the Angular Material style (and logic) don't load fine. Anyone know why can it be?

Click event on Angular Material Design Gridlist

I'm going through Angular Material Design Gridlist and they have not mentioned anything about handling hover/click on the grids. So, is there a way to do it or should I use buttons inside each grid to handle click events ?

Angular Ui router allowing API route

I have an AngularJS SPA Template for visual studio in my project and a WebApi 2.2 in the same project. But everytime I go to a /api link it gives me the 404 error

so I figured the routing isn't setup correct. Thisis the route provider:

$stateProvider
    .state('home', {
        url: '/',
        templateUrl: '/views/index',
        controller: 'HomeCtrl'
    })
    .state('about', {
        url: '/about',
        templateUrl: '/views/about',
        controller: 'AboutCtrl'
    })
    .state('units', {
        url: '/units',
        layout: 'basic',
        templateUrl: '/views/units',
        controller: 'UnitCtrl'
    })
    .state('otherwise', {
        url: '*path',
        templateUrl: '/views/404',
        controller: 'Error404Ctrl'
    });

$locationProvider.html5Mode(true);

So I don't know if I should add a state for the api or change the otherwise path? and what to add

Get the users location with ipaddress in Angularjs

I want to get the users location parameters in my Angularjs app like Country, city, state, postalcode etc based on the ip address.

Single Page Application over IIS vs Node + IIS?

We are developing a single page application using AngularJs having an index file at the root which will be served by web server to client. Currently when developing, we are using Node with express server. We need to deploy this application to azure. There are two deployment options available.

  1. Deploy either as web application on azure (I think its IIS server in this case)
  2. Or deploy on IIS using IIS Node module

We need to have a rewrite rule, which will serve index page for every other request to server in both cases.

Which is better deployment model or if anyone can suggest another option available for SPA on Azure?

Unknown provider: ngMessagesProvider with require.js

I am trying to use ngMessages in my controller:

I am setting up my require.js config:

require({

  // libraries dependencies (fallback support)
  paths: {

    jquery: [
      'vendor/jquery/2.1.3/jquery.min'
    ],

    bootstrap: [
      'vendor/bootstrap/3.3.2/js/bootstrap.min'
    ],

    angular: [
      'vendor/http://ift.tt/1P7EGVe'
    ],

    angularResource: [
      'vendor/http://ift.tt/1KSXhP2'
    ],

    angularAnimate: [
      'vendor/http://ift.tt/1P7EGVg'
    ],

    ngMessages: [
      'vendor/http://ift.tt/1KSXj9J'
    ],

    uiBootstrap: [
      'vendor/angular-ui/bootstrap/0.12.0/ui-bootstrap-tpls.min'
    ],

    uiRouter: [
      'vendor/angular-ui/ui-router/0.2.13/angular-ui-router.min'
    ],



  },

  // define js scripts dependencies
  shim: {

    'bootstrap': {
      deps: ['jquery']
    },

    'angular': {
      deps: ['bootstrap'],
      exports: 'angular'
    },

    'angularResource': {
      deps: ['angular']
    },

    'angularAnimate': {
      deps: ['angular']
    },

    'ngMessages': {
      deps: ['angular']
    },

    'uiBootstrap': {
      deps: ['bootstrap',  'angular']
    },

    'uiRouter': {
      deps: ['angular']
    },


  },

  priority: [
    'angular'
  ],

  deps: ['./ng.app']

});

and in module.js I am requiring ngMessages:

define(function(require) {
  'use strict';

  var angular = require('angular');
  require('angularResource');
  require('ngMessages');

  require('uiRouter');
  require('uiBootstrap');

  // angular module definition
  return angular.module(
    // module name
    'companies',

    // module dependencies
    [
      'ngResource',
      'ngMessages',

      'ui.router',
      'ui.bootstrap',

      require('shared/fend/input-utils/package').name,
      require('shared/fend/pagination/package').name
    ]
  );

});

and then in my controller I am trying to inject ngMessages:

define(function(require) {
  'use strict';

  var module = require('../module');
  require('../resources/rest');


  module.controller('CompaniesNewCtrl', CompaniesNewCtrl);


  CompaniesNewCtrl.$inject = [
    '$rootScope', '$scope', '$state',
    'CompaniesResource',
    'InputFocusFactory', 'ngMessages'
  ];

  function CompaniesNewCtrl($rootScope, $scope, $state, resource, input, ngMessages) {... })

but i am getting error: Error: $injector:unpr Unknown Provider Unknown provider: ngMessagesProvider

What am I doing wrong?

Ui Router tabs with routing

I'm using UI-Router and I need to hook up tabs where the url changes as well. So for example, I have a page with 3 sublinks:

  1. Customer Overview (templates/customer.overview.html): http://ift.tt/1KSWo9k
  2. Customer Settings (templates/customer.settings.html): http://ift.tt/1P7DjG2
  3. Customer Contact Info (templates/customer.contact.html): http://ift.tt/1KSWoGk

All three of these pages should be injected into one main customers.main.html page that includes the links.

My states are defined as follows:

  $stateProvider
    .state('customer', {
      abstract: true,
      url: '/customer',
      templateProvider: function($templateCache) {
        return $templateCache.get('templates/customer.overview.html');
      }
    })
    .state('customer.overview', {
      url:'/:id/overview',
      controller: ''
      templateProvider: function($templateCache) {
        return $templateCache.get('templates/customer.settings.html');
      }
    })
    .state('customer.contact', {
      url:'/:id/contact',
      controller: ''
      templateProvider: function($templateCache) {
        return $templateCache.get('templates/customer.contact.html');
      }
    });

And I have a customers.main.html page:

<div class="tabs" ng-controller="TabsCtrl as tabs">
   <a ng-repeat="tab in tabs" ui-sref='{{tab.route}}' ng-bind="tab.label">
</div>

TabsCtrl

angular.module('customers')
  .controller('TabsCtrl', [
    function() {

    var self = this;

    self.tabs = [
      {
        label: 'Overview',
        route: 'customer.overview',
        active: false
      },
      {
        label: 'Settings',
        route: 'customer.settings',
        active: false
      },
      {
        label: 'Contact',
        route: 'customer.contact',
        active: false
      }
    ];

    self.selectedTab = self.tabs[0];
  }
]);

However, this doesn't seem to be working correctly. The ui-sref directive when I click always resolves to something like: /customers//settings. It's not picking up the :id.

Any help?

What is the correct way to install and test how to install angular ui bootstrap in my application if I dont have bower or npm for project?

I downloaded ui-bootstrap-0.12.0.min.js (0.12.0 because I am upgrading an application and the angular.js used in the application is 1.2.x) and included it in my application via <script> tag. I tried testing by creating components like popover and dialog but none of them seem to be triggering.

Do I need to do something else?

Angular form validation on Yii Form

I am using AngularJS v1.3.15 for form validation within Yii dynamic form but it seems angular validation works on input names. the problem is that name of inputs are in array format such as: name="LoginForm[username]". i am copying my code here:

   <div class="col-md-4 col-md-offset-4 m-t-lg" ng-app="validationApp" ng-controller="mainController">
            <section class="panel">
                <header class="panel-heading text-center"><strong>Admin Sign in </strong> </header>
                <?php 
                        $form=$this->beginWidget('CActiveForm', array(
                            'id'=>'formLogin',
                            'htmlOptions'=> array('name'=>'userForm', 'class'=>'panel-body', 'ng-submit'=>'submitForm($event)', 'novalidate'=>'true'),
                            'action'=>'#',
                            'enableAjaxValidation'=>false,
                        )); 
                    ?>
                    <div class="form-group" ng-class="{'has-error' :  userForm.username.$invalid && !userForm.username.$pristine}">
                        <label class="control-label">Email</label> 
                        <?php echo $form->emailField($model, 'username', array('placeholder'=>'test@example.com', 'class'=>'form-control', 'ng-model'=>'user.username', 'ng-pattern'=>"/^[_a-z0-9]+(\.[_a-z0-9]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/", 'required'=>'true', 'id'=>'username')); ?>
                        <?php echo $form->error($model,'username'); ?>
                    </div>
                    <div class="form-group" ng-class="{'has-error' :  userForm.password.$invalid && !userForm.password.$pristine}">
                        <label class="control-label">Password</label> 
                        <input type="password" placeholder="Password" ng-minlength="6" class="form-control" name="password" ng-model="user.password" required>
                    </div>
                    <div class="checkbox">
                        <label> <input type="checkbox"> Keep me logged in
                        </label>
                    </div>
                    <button type="submit" class="btn btn-info" ng-disabled="userForm.$invalid">Sign in</button>
                <?php $this->endwidget(); ?>
            </section>
        </div>
    </div>

And here is script code for angular controller:

      var app = angular.module('validationApp',[]);
         app.controller('mainController', function($scope) {
            $scope.submitForm = function($event){
            if ($scope.userForm.$valid){
                $scope.submit();
            } else $event.preventDefault();
         } 
      });

it works fine if i change names of input as a single word such as "username" and "password" but its not working in current situation with having name "LoginForm[username]". its working fine with password field because its plain name but same is not true with username field.

pikaday angular sending date format in json

how do i send the pikaday plugin date format in my json using ng-model

i had been trying this

<input pikaday="" ng-model="products_chosen[$index].from.getDate()" placeholder="From">

js:

    $scope.products_chosen = [{"from":new Date(),"till":new Date(),"checkbox":0}];
    $scope.productChange = function(index, checkbox){
        if(checkbox==1){
            $scope.products_chosen.push({"from":"","till":"","checkbox":0});  
        }
        else{
            $scope.products_chosen.splice(index,1);
        } 
    }

Angular oi.multiselect how to get value of current changed modal

I need to pick the value of a model that has changed. I am using the oi.multiselect in angular. Each time I pick the model it gives me the initial value in it instead of the current changed one. Here is my html part of the code:

               <oi-multiselect
                ng-options="item for item in clientx"
                ng-model="bundlex"
                multiple
                placeholder="Select clients"
                ></oi-multiselect>

The model "bundlex" values initially are ["Brad Stan"," Calins mark"] reading from the controller. But after in select new values from the drop down the model changes to ["Brad Stan"," Calins mark"," Xavier Nato"," Frank Sunatra"]. When I post the model after changing it, it seem to only hold the initial values and not the new/current one. How can I solve this? Thank you. Here is a link to an example: http://ift.tt/1bFqlgu

Material design on web, who's closest to achieve it?

Material design is a unified system of visual, motion, and interaction design that adapts across different devices.

http://ift.tt/1jq9kdg

I am differentiating between frameworks, if I'd choose between one of these:

The polymer project: http://ift.tt/1GALwxu

Using Angular.js: http://ift.tt/1vyDYkS

Or the other CSS Play, using bootstrap:

materializecss.com/

http://ift.tt/XTuIxj

www.muicss.com/

This function's cyclomatic complexity is too high. (38)

I have a switch case statement for my filters. But it throws me complexity issues of 39 can u help me solve it??

Below is my sample code. It includes some more cases.

    angular.forEach(docsClone, function(doc) {
                var added = false;
                angular.forEach($scope.filterOptions, function(opt) {
                    if (!added) {
                        switch (opt.AttributeId) {
                            case 'documentStatus':
                                if ((doc.documentStatus !== undefined && doc.documentStatus !== null && doc.documentStatus.indexOf(opt.AttributeValue) !== -1)) {
                                    filteredDocs.push(doc);
                                    added = true;
                                }
                                break;
                            case 'planStatus':
                                if ((doc.planStatus !== undefined && doc.planStatus.indexOf(opt.AttributeValue) !== -1)) {
                                    filteredDocs.push(doc);
                                    added = true;
                                }
                                break;
                            case 'planFamily':
                                if ((doc.planProductFamily !== undefined && doc.planProductFamily !== null && doc.planProductFamily.indexOf(opt.AttributeValue) !== -1)) {
                                    filteredDocs.push(doc);
                                    added = true;
                                }
                                break;
                            case 'planYear':
                                planYear(doc, opt.AttributeValue, filteredDocs, added);
                                break;
                            case 'documentType':
                                if ((doc.documentType !== undefined && doc.documentType !== null && doc.documentType.indexOf(opt.AttributeValue) !== -1)) {
                                    filteredDocs.push(doc);
                                    added = true;
                                }
                                break;
                            case 'businessEntity':
                                if ((doc.businessEntity !== undefined && doc.businessEntity !== null && doc.businessEntity.indexOf(opt.AttributeValue) !== -1)) {
                                    filteredDocs.push(doc);
                                    added = true;
                                }
                                break;
                            case 'productClass':
                                if ((doc.productClass !== undefined && doc.productClass !== null && doc.productClass !== null && doc.productClass.indexOf(opt.AttributeValue) !== -1) ||
                                    (doc.planProductClass !== undefined && doc.planProductClass.indexOf(opt.AttributeValue) !== -1)) {
                                    filteredDocs.push(doc);
                                    added = true;
                                }
                                break;
                            case 'productType':
                                if ((doc.productType !== undefined && doc.productType !== null && doc.productType.indexOf(opt.AttributeValue) !== -1) ||
                                    (doc.planProductType !== undefined && doc.planProductType.indexOf(opt.AttributeValue) !== -1)) {
                                    filteredDocs.push(doc);
                                    added = true;
                                }
                                break;
    }

Angular Bootstrap DateTimePicker - Highlight Today Date on embedded Calender

Please accept my apologies if i had any mistakes in my post. This is my first post here. But, i am not new to StackOverflow. Correct me if any.

I am using angular-bootstrap-datetimepicker library from the below url: Link to library

I am currently embedding the calender on the page. I am using angular.js, moment.js, grunt and bower. Absolutely no issue loading the calender and can even select a date and display the selected date as well.

Here is the sample code:

<div>
  Selected Date: {{ data.embeddedDate | date:'yyyy-MMM-dd' }}
  <datetimepicker data-ng-model="data.embeddedDate" data-datetimepicker-config="{ startView:'day', minView:'day'}" />
</div>

I am trying to highlight today's date automatically when the datetimepicker shows on the page. As you can see, in the config options, i could set the default view and min view.

Note: I tried to mimic the working code (till now) in Plunkr but, its not showing the calendar. I added all libraries as well. Anyways, that's just for idea only. If i could get the Plunkr working, i will update again. Here is the link to Plunkr.

Any suggestions (regarding highlight today date by default) will be appreciated.

What's the main purpose of $scope in AngularJS controller?

Yesterday, I saw my co-worker write a huge controller with only one "god object" $scope that should look like this following code.

myApp.controller('ComplexController', ['$scope', function($scope) {

 $scope.firstTab = {
    init: function () {
      $scope.firstTab.data1.foo = $scope.firstTab.DefaultData1.foo;

      $scope.$watch('firstTab.data1.foo', function (){
        // do something
      });
    },
    defaultData1: {
      foo: 'bar'
    },
    data1: {
      foo: 'bar',
      publiclyUsedMethod1: function () {},
      publiclyUsedMethod2: function () {},
      privatelyUsedMethod1: function () {},
      privatelyUsedMethod2: function () {},
      privatelyUsedMethod3: function () {},
      privatelyUsedMethod4: function () {},
      privatelyUsedMethod5: function () {}
    },
    data2: {
      // Same code pattern as above
    },
    data3: {
      // Same code pattern as above
    },
    data4: {
      // Same code pattern as above
    }
  };

  $scope.secondTab = {
    // Same code pattern as above
  };

  $scope.thirdTab = {
    // Same code pattern as above
  };

  $scope.refresh = function(){
    // do something
  };

  $scope.$watchCollection('[$scope.firstTab.data1.foo, $scope.secondTab.data1.foo, $scope.thirdTab.data1.foo]',function(newValues,oldValues){
    // some logic
    $scope.refresh();
  });

  $scope.firstTab.init();
  $scope.secondTab.init();
  $scope.thirdTab.init();
}]);

What do you think which this pattern? What's the main purpose of $scope object? Is it OK to store every private and public object in $scope object?

Thanks,

SEO with angular.js application

In my application I used angular.js as a client side technology now i want my site SEO friendly I found the solution but I am little bit confused about it that is sitemap.xml is required or not for angular seo ?

Preventing multiple clicks in angularjs

When I want to delete a record from my page I need to show confirmation message before deleting. For this I have used anchor and ng-click='delete()' for deleting such row. Here user can click on anchor multiple times. It is a serious problem because confirmation popup render multiple times. My example is a sample. In my project I have faced too many problems like that.

Angular Error - Can't interpolate: (device.osVersion) Android 4.0.3

So I am running the Supersonic demo template on my Android phone, and I keep getting this error that is preventing the app from loading the page:

Can't interpolate: {{device.osVersion | strReplace:'_':'.'}} TypeError: Cannot read property 'replace' of undefined

Page setup tutorial page: http://ift.tt/1bFlxrs

Screenshot of debug console:

enter image description here

This is the raw untouched demo from AppGyver, so it should work out of the box! This does work on my iPad though so it seems to be an error with Android. I am running the app through the AppGyver Scanner on my phone.

Android version: 4.0.3

This is what the app screen looks like (the black space being the error as there should be text and buttons there):

enter image description here

What are the existing and recommended solution for authentication using Oauth in Java as backend and Angular as frontend?

I have an application in Java and using angular as frontend. I have checked couple of authentication solution including oauth.io (It's not for free), oauth-ng etc. but as I am new to this technology stack I am not sure about this. Any thoughts/inputs will be highly appreciated.

pikaday angular sending json format

how do i send json date format using pikaday angular plugin using ng-model.

i have been trying this

{{product.product_name}}
{{products_chosen[$index]}} {{myPickerObject}}

js:

    $scope.products_chosen = [{"from":new Date(),"till":new Date(),"checkbox":0}];
    $scope.productChange = function(index, checkbox){
        if(checkbox==1){
            $scope.products_chosen.push({"from":"","till":"","checkbox":0});  
        }
        else{
            $scope.products_chosen.splice(index,1);
        } 
    }

showing Time from database in Timepicker directive Angular

I'm using timepicker there is an error to getting data from database : here is what should it be :

VisitDate: "2015-05-21T17:30:00"  

here is what i get :

21:00  



<timepicker ng-model="visitPlaceViewModel.VisitDate" hour-step="hstep" minute-step="mstep" show-meridian="ismeridian" class="timePicker"></timepicker>

How to create a bill system with Node.js and front-end angular.js

How to create my first any billing system application by users node.js and angular js

very starnge behaviour with for loop and data-ng-init()

     I was trying to pass array of ids from controller to custom directive and in custom directive i need to get the whole object from server using some api and need to display it using ng-repeat. but when page gets loaded it should display, should not use any click events and all. 

here is my controller.

   $scope.$on('itemSelectedEvent', function (event, args) {
    $scope.selectedId = args.selectedId;
     $scope.searchId = args.searchId;
     $scope.searchType = args.searchType;
     getOrg($scope.selectedId).fetch({'searchType': $scope.searchType}).$promise.then(
              function (value) {
    switch($scope.data.searchType)

    {
    case 'tei_org' :
    $scope.recipientsOrgIdArr.push(data.relatedEntityInstanceId);

//need to pass this array of ids to directive
    break;
                 case 'tei_person' :
    $scope.recipientsPeopleIdArr.push(data.relatedEntityInstanceId);
//need to pass this array of ids to directive

      break;
                        }
    })
    });

my html file...

<search  searchobj="tei_org"  selecteditemslist="recipientsOrgIdArr"   searchid="organisation" />

sending array of ids (recipientsOrgIdArr) to the directive like this .

my directive html

{{list}}x

display(selecteditemslist,searchid,searchobj) function should get call when page is loaded

display() contains

  $scope.display = function (list, searchid, searchobj) {
    for (var i = 0; i < list.length; i++) {
            getOrg(list[i]).fetch({
                'searchType': searchobj
            }).$promise.then(
                function (value) {
    var data = {
                        'id': $scope.displayItem.id,

                        'item': $scope.displayItem.displayConfig[0].propertyValue
                    };
                    $scope.item.push(data.item);
    });
    }
    }

i had strucked with three problems.... 1) i dont know whats going wrong data-ng-init() was not getting call

2) my for loop is repeating twice of the length, i.e if length is 2 it was looping 4 times and iam getting duplicate items while displaying.

3) last thing is while displaying previous items aslo getting displayed but my requirment is they have to become null only current items should display.

please friends help me to solve this problem

Is it safe to use jQuery in _Layout.cshtml for a large Angular application?

I realise this question is somewhat broad, but I'm hoping I can provide enough contextual detail to narrow it down a bit. In a project I am very new to, one of my tasks is to add a confirmation dialogue when the user clicks the logout link. I have changed the link as follows, in _Layout.cshtml:

<div class="row inner">
    @if (Request.IsAuthenticated)
    {
        using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { @id = "logoutForm", @class = "col-md-8 col-md-offset-2 rightText" }))
        {
            @Html.AntiForgeryToken()
            <a href="@Url.Action("CreateNewMlamApplication", "MlamApplication")"><img src="/img/icons/plusIcon.png" class="icon" /></a>
            <a href="@Url.Action("Index", "Home")"><img src="/img/icons/documentIcon.png" class="icon" /></a>
            @* BKMOD <a href="javascript:document.getElementById('logoutForm').submit()"><img src="/img/icons/gearIcon.png" class="icon" /></a>*@
            <a class="logout-link-confirm" href="#" ><img src="/img/icons/gearIcon.png" class="icon" /></a>
        }
    }
</div>

Then, I hook a handler up to logout-link-confirm, at the bottom of the layout:

    <script>
        $(function() {
            $(".logout-link-confirm").click(function() {
                $('#modalLogoutConfirmation').modal('show');
            });
            $(".logout-link-final").click(function () {
                $('#logoutForm').submit()
            });
        });
    </script>
    @RenderSection("scripts", required: false)
</body>

And in the modalLogoutConfirmation popup, I perform the actual logout when the user confirms their choice: $('#logoutForm').submit().

This has nothing to do with angular directly, as angular only kicks in on some of the body views in this layout, but it is loaded, and I am a little concerned of any side effects my jQuery may introduce.

Angular New Router and grandchildren routes

I cannot find any examples on how to make grandchildren routes in the Angular New Router (1.4).

As I understand from a tutorial the router config is per component. And a component is self-contained and not aware of other components.

If I have a users component, and this component gives all users, and then this components has a child component that gives info on a specific user.

Is the following directory structure correct?

/app.js /app.html /components/users/users.js /components/users/users.html /components/users/components/user/user.js /components/users/components/user/user.html

Where /app.js contains the following route config:

$router.config([
 {path: '/users', component: 'users' }
]);

And /components/users/users.js contains the following route config:

$router.config([
 {path: '/user', component: 'user' }
]);

So the path in this example would be /users/user.

I probably have misunderstood, because when I tried it, it did not work. So anybody knows a tutorial or could enlighten me on how this really should be done?

Angular.module is not working

I am new to Angularjs and currently practising it .I have a simple example like this .

My View Index.cshtml

<div ng-app="MyApp">    
<div class="show-scope-demo">
        <div ng-controller="MainController">
            <p>Good {{timeOfDay}}, {{name}}!</p>
            <div ng-controller="subController1">
                <p>Good {{timeOfDay}}, {{name}}!</p>
                <div ng-controller="subController2">
                    <p>Good {{timeOfDay}}, {{name}}!</p>
                </div>
            </div>
        </div>
    </div>
</div>

and my controller is MyJsScript.js

(function (angular) {

angular.module('MyApp', []).controller('MainController', ['$scope', function ($scope) {
    $scope.timeOfDay = 'morning';
    $scope.name = 'sapan';
}]);
angular.module('MyApp', []).controller('subController1', ['$scope', function ($scope) {
    $scope.name = 'sapan';
}]);
angular.module('MyApp', []).controller('subController2', ['$scope', function ($scope) {
   $scope.timeOfDay = 'Evening';
    $scope.name = 'Tapan';
}]);
})(window.angular);

in this case I am getting error "[ng:areq] Argument 'MainController' is not a function, got undefined" But if I am changing my controller like this

(function (angular) {
var myApp = angular.module('MyApp', []);
myApp.controller('MainController', ['$scope', function ($scope) {
    $scope.timeOfDay = 'morning';
    $scope.name = 'sapan';
}]);
myApp.controller('subController1', ['$scope', function ($scope) {
    $scope.name = 'sapan';
}]);
myApp.controller('subController2', ['$scope', function ($scope) {
    $scope.timeOfDay = 'Evening';
    $scope.name = 'Tapan';
}]);
})(window.angular); 

It is working perfectly without any error .

Can anyone please tell me what is the exact difference between these two syntax.

vendredi 8 mai 2015

how to create multiple js files from index.html using grunt usemin

My index.html has split js files as follows:

<head>
  ....
  <!-- build:js js/app1.min.js -->
  <!-- js from lib -->
  <script src="bower_components/angular/angular.min.js"></script>
  <script src="bower_components/angular-route/angular-route.min.js"></script>

  <!-- js of this app -->
  <script src="js/app.js"></script>
  <script src="js/services.js"></script>

  <!-- external js -->
  <script type="text/javascript" src="http://ift.tt/1lrRXYd"></script>
  <!-- endbuild -->
  ....
</head>

.....
<body>
...
  <!-- build:js js/app2.min.js -->

  <!-- js from lib -->
  <script src="bower_components/jquery/dist/jquery.min.js"></script>
  <!-- angular-animate provides search functionality -->

  <!-- js of this app -->      
  <script src="js/filters.js"></script>
  <script src="js/directives.js"></script>

  <!-- endbuild -->
  ....
</body>

As you can see, I tried to use two sets of js files. The reason to split is performance. How to use usemin in this case. I tried with following:

'useminPrepare': {
  'html': 'app/index.html'
},

'usemin': {
  'html': ['dist/index.html']
},

However, there is no folder/file created. But in index.html, those two sections are replaced appropriately by app1.min.js and app2.min.js

Moreover, I do not understand one thing that all examples are using concat and uglify in combination of usemin. The files in index.html which are already *.min.js eg. files included in bower_components folder, what happens to them?

Why is my ng-repeat acting like the object is empty?

Here is my controller code:

// Called automatically with the response of the YouTube API request.
window.onSearchResponse = function(response) {
    console.log(response); //Shows entire response data
    console.log(response.items[0].snippet.title); //shows video title
    console.log(response.items[0].id.videoId); //shows video Id
    console.log(response.items[0].snippet.thumbnails.medium.url); //shows video thumbnail
    $scope.videos = response.items;
    console.log($scope.videos); //This outputs an object with 5 Objects in it. Proof that the API is picking up something.
};

}]);

And here is the partial:

<ul>
    <li ng-repeat="video in videos">
    hey
    </li>
</ul>

Since i'm using the youtubeAPI, every search result brings back 5 results. console.log($scope.video) shows in the console the 5 objects, so I know it's being populated.

However whenever I go to my partial page and inspect element, the tags are completely empty. like the ng-repeat never ran.

Why would it not run? I should be seeing "hey" 5 times.