Search Results

Search found 674 results on 27 pages for 'arg'.

Page 2/27 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Vim plugin only works when file is provided as arg to launch command

    - by nsfyn55
    I am using the plugin java_getset.vim. The issue is that the plugin's commands are only available when I launch vim with the file as an argument. user@machine~: vim myfile.java If launch vim and use command-t or NerdTree to open the file in a buffer the plugin's commands are not accessible. All the filetype detection stuff is configured and working(I have syntax highlighting and indentation). The plugin source appears to be written to the letter according the the vim docs for a filetype plugin. Can anyone help me understand what changes a can make so that I can use this plugin in conjunction with Command-t?

    Read the article

  • Help with malloc and free: Glibc detected: free(): invalid pointer

    - by nunos
    I need help with debugging this piece of code. I know the problem is in malloc and free but can't find exactly where, why and how to fix it. Please don't answer: "Use gdb" and that's it. I would use gdb to debug it, but I still don't know much about it and am still learning it, and would like to have, in the meanwhile, another solution. Thanks. #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <unistd.h> #include <string.h> #include <sys/wait.h> #include <sys/types.h> #define MAX_COMMAND_LENGTH 256 #define MAX_ARGS_NUMBER 128 #define MAX_HISTORY_NUMBER 100 #define PROMPT ">>> " int num_elems; typedef enum {false, true} bool; typedef struct { char **arg; char *infile; char *outfile; int background; } Command_Info; int parse_cmd(char *cmd_line, Command_Info *cmd_info) { char *arg; char *args[MAX_ARGS_NUMBER]; int i = 0; arg = strtok(cmd_line, " "); while (arg != NULL) { args[i] = arg; arg = strtok(NULL, " "); i++; } num_elems = i;precisa em free_mem if (num_elems == 0) return 0; cmd_info->arg = (char **) ( malloc(num_elems * sizeof(char *)) ); cmd_info->infile = NULL; cmd_info->outfile = NULL; cmd_info->background = 0; bool b_infile = false; bool b_outfile = false; int iarg = 0; for (i = 0; i < num_elems; i++) { if ( !strcmp(args[i], "<") ) { if ( b_infile || i == num_elems-1 || !strcmp(args[i+1], "<") || !strcmp(args[i+1], ">") || !strcmp(args[i+1], "&") ) return -1; i++; cmd_info->infile = malloc(strlen(args[i]) * sizeof(char)); strcpy(cmd_info->infile, args[i]); b_infile = true; } else if (!strcmp(args[i], ">")) { if ( b_outfile || i == num_elems-1 || !strcmp(args[i+1], ">") || !strcmp(args[i+1], "<") || !strcmp(args[i+1], "&") ) return -1; i++; cmd_info->outfile = malloc(strlen(args[i]) * sizeof(char)); strcpy(cmd_info->outfile, args[i]); b_outfile = true; } else if (!strcmp(args[i], "&")) { if ( i == 0 || i != num_elems-1 || cmd_info->background ) return -1; cmd_info->background = true; } else { cmd_info->arg[iarg] = malloc(strlen(args[i]) * sizeof(char)); strcpy(cmd_info->arg[iarg], args[i]); iarg++; } } cmd_info->arg[iarg] = NULL; return 0; } void print_cmd(Command_Info *cmd_info) { int i; for (i = 0; cmd_info->arg[i] != NULL; i++) printf("arg[%d]=\"%s\"\n", i, cmd_info->arg[i]); printf("arg[%d]=\"%s\"\n", i, cmd_info->arg[i]); printf("infile=\"%s\"\n", cmd_info->infile); printf("outfile=\"%s\"\n", cmd_info->outfile); printf("background=\"%d\"\n", cmd_info->background); } void get_cmd(char* str) { fgets(str, MAX_COMMAND_LENGTH, stdin); str[strlen(str)-1] = '\0'; } pid_t exec_simple(Command_Info *cmd_info) { pid_t pid = fork(); if (pid < 0) { perror("Fork Error"); return -1; } if (pid == 0) { if ( (execvp(cmd_info->arg[0], cmd_info->arg)) == -1) { perror(cmd_info->arg[0]); exit(1); } } return pid; } void type_prompt(void) { printf("%s", PROMPT); } void syntax_error(void) { printf("msh syntax error\n"); } void free_mem(Command_Info *cmd_info) { int i; for (i = 0; cmd_info->arg[i] != NULL; i++) free(cmd_info->arg[i]); free(cmd_info->arg); free(cmd_info->infile); free(cmd_info->outfile); } int main(int argc, char* argv[]) { char cmd_line[MAX_COMMAND_LENGTH]; Command_Info cmd_info; //char* history[MAX_HISTORY_NUMBER]; while (true) { type_prompt(); get_cmd(cmd_line); if ( parse_cmd(cmd_line, &cmd_info) == -1) { syntax_error(); continue; } if (!strcmp(cmd_line, "")) continue; if (!strcmp(cmd_info.arg[0], "exit")) exit(0); pid_t pid = exec_simple(&cmd_info); waitpid(pid, NULL, 0); free_mem(&cmd_info); } return 0; }

    Read the article

  • Liskov principle: violation by type-hinting

    - by Elias Van Ootegem
    According to the Liskov principle, a construction like the one below is invalid, as it strengthens a pre-condition. I know the example is pointless/nonsense, but when I last asked a question like this, and used a more elaborate code sample, it seemed to distract people too much from the actual question. //Data models abstract class Argument { protected $value = null; public function getValue() { return $this->value; } abstract public function setValue($val); } class Numeric extends Argument { public function setValue($val) { $this->value = $val + 0;//coerce to number return $this; } } //used here: abstract class Output { public function printValue(Argument $arg) { echo $this->format($arg); return $this; } abstract public function format(Argument $arg); } class OutputNumeric extends Output { public function format(Numeric $arg)//<-- VIOLATION! { $format = is_float($arg->getValue()) ? '%.3f' : '%d'; return sprintf($format, $arg->getValue()); } } My question is this: Why would this kind of "violation" be considered harmful? So much so that some languages, like the one I used in this example (PHP), don't even allow this? I'm not allowed to strengthen the type-hint of an abstract method but, by overriding the printValue method, I am allowed to write: class OutputNumeric extends Output { final public function printValue(Numeric $arg) { echo $this->format($arg); } public function format(Argument $arg) { $format = is_float($arg->getValue()) ? '%.3f' : '%d'; return sprintf($format, $arg->getValue()); } } But this would imply repeating myself for each and every child of Output, and makes my objects harder to reuse. I understand why the Liskov principle exists, don't get me wrong, but I find it somewhat difficult to fathom why the signature of an abstract method in an abstract class has to be adhered to so much stricter than a non-abstract method. Could someone explain to me why I'm not allowed to hind at a child class, in a child class? The way I see it, the child class OutputNumeric is a specific use-case of Output, and thus might need a specific instance of Argument, namely Numeric. Is it really so wrong of me to write code like this?

    Read the article

  • MS SQL Query Sum of subquery

    - by San
    Hello , I need a help i getting following output from the query . SELECT ARG_CONSUMER, cast(ARG_TOTALAMT as float)/100 AS 'Total', (SELECT SUM(cast(DAMT as float))/100 FROM DEBT WHERE DDATE >= ARG.ARG_ORIGDATE AND DDATE <= ARG.ARG_LASTPAYDATE AND DTYPE IN ('CSH','CNTP','DDR','NBP') AND DCONSUMER = ARG.ARG_CONSUMER ) AS 'Paid' FROM ARGMASTER ARG WHERE ARG_STATUS = '1' Current output is a list of all records... But what i want to achieve here is count of arg consumers Total of ARG_TOTALAMT total of that subquery PAID difference between PAID & Total amount. I am able to achieve first two i.e. count of consumers & total of ARG _ TOTALAMT... but i am confused about sum of of ...i.e. sum (SELECT SUM(cast(DAMT as float))/100 FROM DEBT WHERE DDATE >= ARG.ARG_ORIGDATE AND DDATE <= ARG.ARG_LASTPAYDATE AND DTYPE IN ('CSH','CNTP','DDR','NBP') AND DCONSUMER = ARG.ARG_CONSUMER) AS 'Paid' Please advice

    Read the article

  • Help with simple linux shell implementation

    - by nunos
    I am implementing a simple version of a linux shell in c. I have succesfully written the parser, but I am having some trouble forking out the child process. However, I think the problem is due to arrays, pointers and such, because just started C with this project and am not still very knowledgable with them. I am getting a segmentation fault and don't know where from. Any help is greatly appreciated. #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <sys/wait.h> #include <sys/types.h> #define MAX_COMMAND_LENGTH 250 #define MAX_ARG_LENGTH 250 typedef enum {false, true} bool; typedef struct { char **arg; char *infile; char *outfile; int background; } Command_Info; int parse_cmd(char *cmd_line, Command_Info *cmd_info) { char *arg; char *args[MAX_ARG_LENGTH]; int i = 0; arg = strtok(cmd_line, " "); while (arg != NULL) { args[i] = arg; arg = strtok(NULL, " "); i++; } int num_elems = i; if (num_elems == 0) return -1; cmd_info->infile = NULL; cmd_info->outfile = NULL; cmd_info->background = 0; int iarg = 0; for (i = 0; i < num_elems-1; i++) { if (!strcmp(args[i], "<")) { if (args[i+1] != NULL) cmd_info->infile = args[++i]; else return -1; } else if (!strcmp(args[i], ">")) { if (args[i+1] != NULL) cmd_info->outfile = args[++i]; else return -1; } else cmd_info->arg[iarg++] = args[i]; } if (!strcmp(args[i], "&")) cmd_info->background = true; else cmd_info->arg[iarg++] = args[i]; cmd_info->arg[iarg] = NULL; return 0; } void print_cmd(Command_Info *cmd_info) { int i; for (i = 0; cmd_info->arg[i] != NULL; i++) printf("arg[%d]=\"%s\"\n", i, cmd_info->arg[i]); printf("arg[%d]=\"%s\"\n", i, cmd_info->arg[i]); printf("infile=\"%s\"\n", cmd_info->infile); printf("outfile=\"%s\"\n", cmd_info->outfile); printf("background=\"%d\"\n", cmd_info->background); } void get_cmd(char* str) { fgets(str, MAX_COMMAND_LENGTH, stdin); str[strlen(str)-1] = '\0'; //apaga o '\n' do fim } pid_t exec_simple(Command_Info *cmd_info) { pid_t pid = fork(); if (pid < 0) { perror("Fork Error"); return -1; } if (pid == 0) { execvp(cmd_info->arg[0], cmd_info->arg); perror(cmd_info->arg[0]); exit(1); } return pid; } int main(int argc, char* argv[]) { while (true) { char cmd_line[MAX_COMMAND_LENGTH]; Command_Info cmd_info; printf(">>> "); get_cmd(cmd_line); if ( (parse_cmd(cmd_line, &cmd_info) == -1) ) return -1; parse_cmd(cmd_line, &cmd_info); if (!strcmp(cmd_info.arg[0], "exit")) exit(0); pid_t pid = exec_simple(&cmd_info); waitpid(pid, NULL, 0); } return 0; } Thanks.

    Read the article

  • How to get address of va_arg?

    - by lionbest
    I hack some old C API and i got a compile error with the following code: void OP_Exec( OP* op , ... ) { int i; va_list vl; va_start(vl,op); for( i = 0; i < op->param_count; ++i ) { switch( op->param_type[i] ) { case OP_PCHAR: op->param_buffer[i] = va_arg(vl,char*); // ok it works break; case OP_INT: op->param_buffer[i] = &va_arg(vl,int); // error here break; // ... more here } } op->pexec(op); va_end(vl); } The error with gcc version 4.4.1 (Ubuntu 4.4.1-4ubuntu9) was: main.c|55|error: lvalue required as unary ‘&’ operand So why exactly it's not possible here to get a pointer to argument? How to fix it? This code is executed very often with different OP*, so i prefer to not allocate extra memory. Is it possible to iterate over va_list knowing only the size of arguments?

    Read the article

  • Getting ellipses function parameters without an initial argument

    - by Tox1k
    So I've been making a custom parser for a scripting language, and I wanted to be able to pass only ellipses arguments. I don't need or want an initial variable, however Microsoft and C seem to want something else. FYI, see bottom for info. I've looked at the va_* definitions #define _crt_va_start(ap,v) ( ap = (va_list)_ADDRESSOF(v) + _INTSIZEOF(v) ) #define _crt_va_arg(ap,t) ( *(t *)((ap += _INTSIZEOF(t)) - _INTSIZEOF(t)) ) #define _crt_va_end(ap) ( ap = (va_list)0 ) and the part I don't want is the v in va_start. As a little background I'm competent in goasm and I know how the stack works so I know what's happening here. I was wondering if there is a way to get the function stack base without having to use inline assembly. Ideas I've had: #define im_va_start(ap) (__asm { mov [ap], ebp }) and etc... but really I feel like that's messy and I'm doing it wrong. struct function_table { const char* fname; (void)(*fptr)(...); unsigned char maxArgs; }; function_table mytable[] = { { "MessageBox", &tMessageBoxA, 4 } }; ... some function that sorts through a const char* passed to it to find the matching function in mytable and calls tMessageBoxA with the params. Also, the maxArgs argument is just so I can check that a valid number of parameters is being sent. I have personal reasons for not wanting to send it in the function, but in the meantime we can just say it's because I'm curious. This is just an example; custom libraries are what I would be implementing so it wouldn't just be calling WinAPI stuff. void tMessageBoxA(...) { // stuff to load args passed MessageBoxA(arg1, arg2, arg3, arg4); } I'm using the __cdecl calling convention and I've looked up ways to reliably get a pointer to the base of the stack (not the top) but I can't seem to find any. Also, I'm not worried about function security or typechecking.

    Read the article

  • jetty - javax.naming.InvalidNameException: A flat name can only have a single component

    - by Dinesh Pillay
    I have been breaking my head against this for too much time now. I'm trying to get maven + jetty + jotm to play nice but it looks like its too much to ask for :( Below is my jetty.xml:- <?xml version="1.0"?> <!DOCTYPE Configure PUBLIC "-//Jetty//Configure//EN" "http://www.eclipse.org/jetty/configure.dtd"> <Configure id="Server" class="org.mortbay.jetty.Server"> <New id="jotm" class="org.objectweb.jotm.Jotm"> <Arg type="boolean">true</Arg> <Arg type="boolean">false</Arg> <Call id="tm" name="getTransactionManager" /> <Call id="ut" name="getUserTransaction" /> </New> <New class="org.mortbay.jetty.plus.naming.Resource"> <Arg /> <Arg>javax.transaction.TransactionManager</Arg> <Arg><Ref id="ut" /></Arg> </New> <New id="tx" class="org.mortbay.jetty.plus.naming.Transaction"> <Arg><Ref id="ut" /></Arg> </New> <New class="org.mortbay.jetty.plus.naming.Resource"> <Arg>myxadatasource</Arg> <Arg> <New id="myxadatasourceA" class="org.enhydra.jdbc.standard.StandardXADataSource"> <Set name="DriverName">org.apache.derby.jdbc.EmbeddedDriver</Set> <Set name="Url">jdbc:derby:protodb;create=true</Set> <Set name="User"></Set> <Set name="Password"></Set> <Set name="transactionManager"> <Ref id="tm" /> </Set> </New> </Arg> </New> <New id="protodb" class="org.mortbay.jetty.plus.naming.Resource"> <Arg>jdbc/protodb</Arg> <Arg> <New class="org.enhydra.jdbc.pool.StandardXAPoolDataSource"> <Arg> <Ref id="myxadatasourceA" /> </Arg> <Set name="DataSourceName">myxadatasource</Set> </New> </Arg> </New> And this is the maven plugin configuration:- <plugin> <groupId>org.mortbay.jetty</groupId> <artifactId>maven-jetty-plugin</artifactId> <configuration> <scanIntervalSeconds>10</scanIntervalSeconds> <stopKey>ps</stopKey> <stopPort>7777</stopPort> <webAppConfig> <contextPath>/ps</contextPath> </webAppConfig> <connectors> <connector implementation="org.mortbay.jetty.nio.SelectChannelConnector"> <port>7070</port> <maxIdleTime>60000</maxIdleTime> </connector> </connectors> <jettyConfig>src/main/webapp/WEB-INF/jetty.xml</jettyConfig> </configuration> <executions> <execution> <id>start-jetty</id> <phase>pre-integration-test</phase> <goals> <goal>run</goal> </goals> <configuration> <scanIntervalSeconds>0</scanIntervalSeconds> <daemon>true</daemon> </configuration> </execution> <execution> <id>stop-jetty</id> <phase>post-integration-test</phase> <goals> <goal>stop</goal> </goals> </execution> </executions> <dependencies> <dependency> <groupId>org.apache.derby</groupId> <artifactId>derby</artifactId> <version>10.6.1.0</version> </dependency> <dependency> <groupId>jotm</groupId> <artifactId>jotm</artifactId> <version>2.0.10</version> <exclusions> <exclusion> <groupId>javax.resource</groupId> <artifactId>connector</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>com.experlog</groupId> <artifactId>xapool</artifactId> <version>1.5.0</version> </dependency> <dependency> <groupId>javax.resource</groupId> <artifactId>connector-api</artifactId> <version>1.5</version> </dependency> <dependency> <groupId>javax.transaction</groupId> <artifactId>jta</artifactId> <version>1.0.1B</version> </dependency> <!-- <dependency> <groupId>javax.jts</groupId> <artifactId>jts</artifactId> <version>1.0</version> </dependency> --> </dependencies> </plugin> I am using maven-jetty-plugin-6.1.24 cause I couldn't get the later one's to work either. When I execute this I get the following exception:- 2010-06-16 09:03:13.423:WARN::Config error at javax.transaction.TransactionManager java.lang.reflect.InvocationTargetException [INFO] ------------------------------------------------------------------------ [ERROR] BUILD ERROR [INFO] ------------------------------------------------------------------------ [INFO] Failure A flat name can only have a single component [INFO] ------------------------------------------------------------------------ Caused by: javax.naming.InvalidNameException: A flat name can only have a single component at javax.naming.NameImpl.addAll(NameImpl.java:621) at javax.naming.CompoundName.addAll(CompoundName.java:442) at org.mortbay.jetty.plus.naming.NamingEntryUtil.makeNamingEntryName(NamingEntryUtil.java:136) at org.mortbay.jetty.plus.naming.NamingEntry.save(NamingEntry.java:196) at org.mortbay.jetty.plus.naming.NamingEntry.(NamingEntry.java:58) at org.mortbay.jetty.plus.naming.Resource.(Resource.java:34) ... 31 more Help!

    Read the article

  • auth.getSession not working

    - by dC
    hi all, i am having troubles with calling auth.getSession in my proxy. It is being called from a iPhone connect client. When the proxy URL is invocated from the iphone, FB returns a 100 invalid parameter error to the proxy. However the 2nd attempt from iPhone yields success. Both times the proxy is doing the same code, only the auth_token is different. Doing a good search, shows that this is a problematic method. I have tried everything in code and even called in a iPhone expert to see if the problem is on the iPhone client. I have concentrated my efforts on the java api being the problem, however i believe the problem lies else where. I have done the following checked and tested java code checked and test iphone code checked FB application settings. any help is most appreciated. ------Here is my java code.--------- String api_secret = FacebookProperty.getString(FacebookConstants.PROPERTY_API_SECRET); String api_key = FacebookProperty.getString(FacebookConstants.PROPERTY_API_KEY); String call_back_url = FacebookProperty.getString(FacebookConstants.PROPERTY_CALLBACK_URL); int connectTimeout = 200000; //use the xml helper // Make sure the user is logged in to Facebook String authToken = request.getParameter("auth_token"); log.info( "FACEBOOK: auth_token?: " + authToken ); Map<String, Object> model = new HashMap<String, Object>(); model.put(FacebookConstants.MODEL_WELCOME_SELECTED, true); FacebookXmlRestClient facebookRestClient = new FacebookXmlRestClient(api_key, api_secret); boolean generateSessionSecret = true; //always true of connect client try{ facebookRestClient.setConnectTimeout(connectTimeout ); String authSessionKey = facebookRestClient.auth_getSession(authToken, true); } catch (Exception e) { log.log( Level.SEVERE, e.toString()); log.log( Level.SEVERE, e.getMessage()); } String rawResponse = facebookRestClient.getRawResponse(); log.info( rawResponse ); -------the iphone code is ----------- session = [FBSession sessionForApplication:myApiKey getSessionProxy:myURL delegate:self]; -----------the error is -------------- <error_response xmlns="http://api.facebook.com/1.0/" xmlns:xsi="http:// www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http:// api.facebook.com/1.0/ http://api.facebook.com/1.0/facebook.xsd"> <error_code>100</error_code> <error_msg>Invalid parameter</error_msg> <request_args list="true"> <arg> <key>api_key</key> <value>bf22a0512c8558a1656d73160507460b</value> </arg> <arg> <key>auth_token</key> <value>fcd1e597aca5c9ba43875cdd01221be5</value> </arg> <arg> <key>call_id</key> <value>1269066988055</value> </arg> <arg> <key>format</key> <value>xml</value> </arg> <arg> <key>generate_session_secret</key> <value>true</value> </arg> <arg> <key>method</key> <value>facebook.auth.getSession</value> </arg> <arg> <key>sig</key> <value>e9f477fd72adf74cd2de72528fd9aa72</value> </arg> <arg> <key>v</key> <value>1.0</value> </arg> </request_args> </error_response>

    Read the article

  • In Lua, how to pass vararg to another function while also taking a peek at them?

    - by romkyns
    It seems that in Lua, I can either pass vararg on to another function, or take a peek at them through arg, but not both. Here's an example: function a(marker, ...) print(marker) print(#arg, arg[1],arg[2]) end function b(marker, ...) print(marker) destination("--2--", ...) end function c(marker, ...) print(marker) print(#arg, arg[1],arg[2]) destination("--3--", ...) end function destination(marker, ...) print(marker) print(#arg, arg[1],arg[2]) end Observe that a only looks at the varargs, b only passes them on, while c does both. Here are the results: >> a("--1--", "abc", "def") --1-- 2 abc def >> b("--1--", "abc", "def") --1-- --2-- 2 abc def >> c("--1--", "abc", "def") --1-- test.lua:13: attempt to get length of local 'arg' (a nil value) stack traceback: ...test.lua:13: in function 'c' ...test.lua:22: in main chunk [C]: ? What am I doing wrong? Am I not supposed to combine the two? Why not?

    Read the article

  • Emacs Lisp: How to use ad-get-arg and ad-get-args?

    - by RamyenHead
    I'm not sure I am using ad-get-args and ad-get-arg right. For example, the following code doesn't work. (defun my-add (a b) (+ a b)) (defadvice my-add (after my-log-on activate) (message "my-add: %s" (ad-get-args))) (my-add 1 2) The last expression causes an error: Debugger entered--Lisp error: (void-function ad-get-args). The following doesn't work either. (defun my-substract (a b) (- a b)) (defadvice my-substract (around my-log-on activate) (message "my-substract: %s" (ad-get-arg 0)) (ad-do-it)) (my-substract 10 1) The defadvice gives a warning: Warning: `(setq ad-return-value (ad-Orig-my-substract a b))' is a malformed function And the last expression gives an error: Debugger entered--Lisp error: (invalid-function (setq ad-return-value (ad-Orig-my-substract a b))) (setq ad-return-value (ad-Orig-my-substract a b))() I was trying to use defadvice to watch start-process arguments for debugging purposes and I found my way of using ad-get-arg didn't work.

    Read the article

  • C#, Open Folder and Select multiple files

    - by Vytas999
    Hello, in C# I want to open explorer and in this explorer window must be selected some files. I do this like that: string fPath = newShabonFilePath; string arg = @"/select, "; int cnt = filePathes.Count; foreach (string s in filePathes) { if(cnt == 1) arg = arg + s; else { arg = arg + s + ","; } cnt--; } System.Diagnostics.Process.Start("explorer.exe", arg); But only the last file of "arg" is selected. How to make that all files of arg would be selected, when explorer window is opened..?

    Read the article

  • Open Folder and Select multiple files

    - by Vytas999
    In C# I want to open explorer and in this explorer window must be selected some files. I do this like that: string fPath = newShabonFilePath; string arg = @"/select, "; int cnt = filePathes.Count; foreach (string s in filePathes) { if(cnt == 1) arg = arg + s; else { arg = arg + s + ","; } cnt--; } System.Diagnostics.Process.Start("explorer.exe", arg); But only the last file of "arg" is selected. How to make that all files of arg would be selected, when explorer window is opened..?

    Read the article

  • Where can these be posted besides the Python Cookbook?

    - by Noctis Skytower
    Whitespace Assembler #! /usr/bin/env python """Assembler.py Compiles a program from "Assembly" folder into "Program" folder. Can be executed directly by double-click or on the command line. Give name of *.WSA file without extension (example: stack_calc).""" ################################################################################ __author__ = 'Stephen "Zero" Chappell <[email protected]>' __date__ = '14 March 2010' __version__ = '$Revision: 3 $' ################################################################################ import string from Interpreter import INS, MNEMONIC ################################################################################ def parse(code): program = [] process_virtual(program, code) process_control(program) return tuple(program) def process_virtual(program, code): for line, text in enumerate(code.split('\n')): if not text or text[0] == '#': continue if text.startswith('part '): parse_part(program, line, text[5:]) elif text.startswith(' '): parse_code(program, line, text[5:]) else: syntax_error(line) def syntax_error(line): raise SyntaxError('Line ' + str(line + 1)) ################################################################################ def process_control(program): parts = get_parts(program) names = dict(pair for pair in zip(parts, generate_index())) correct_control(program, names) def get_parts(program): parts = [] for ins in program: if isinstance(ins, tuple): ins, arg = ins if ins == INS.PART: if arg in parts: raise NameError('Part definition was found twice: ' + arg) parts.append(arg) return parts def generate_index(): index = 1 while True: yield index index *= -1 if index > 0: index += 1 def correct_control(program, names): for index, ins in enumerate(program): if isinstance(ins, tuple): ins, arg = ins if ins in HAS_LABEL: if arg not in names: raise NameError('Part definition was never found: ' + arg) program[index] = (ins, names[arg]) ################################################################################ def parse_part(program, line, text): if not valid_label(text): syntax_error(line) program.append((INS.PART, text)) def valid_label(text): if not between_quotes(text): return False label = text[1:-1] if not valid_name(label): return False return True def between_quotes(text): if len(text) < 3: return False if text.count('"') != 2: return False if text[0] != '"' or text[-1] != '"': return False return True def valid_name(label): valid_characters = string.ascii_letters + string.digits + '_' valid_set = frozenset(valid_characters) label_set = frozenset(label) if len(label_set - valid_set) != 0: return False return True ################################################################################ from Interpreter import HAS_LABEL, Program NO_ARGS = Program.NO_ARGS HAS_ARG = Program.HAS_ARG TWO_WAY = tuple(set(NO_ARGS) & set(HAS_ARG)) ################################################################################ def parse_code(program, line, text): for ins, word in enumerate(MNEMONIC): if text.startswith(word): check_code(program, line, text[len(word):], ins) break else: syntax_error(line) def check_code(program, line, text, ins): if ins in TWO_WAY: if text: number = parse_number(line, text) program.append((ins, number)) else: program.append(ins) elif ins in HAS_LABEL: text = parse_label(line, text) program.append((ins, text)) elif ins in HAS_ARG: number = parse_number(line, text) program.append((ins, number)) elif ins in NO_ARGS: if text: syntax_error(line) program.append(ins) else: syntax_error(line) def parse_label(line, text): if not text or text[0] != ' ': syntax_error(line) text = text[1:] if not valid_label(text): syntax_error(line) return text ################################################################################ def parse_number(line, text): if not valid_number(text): syntax_error(line) return int(text) def valid_number(text): if len(text) < 2: return False if text[0] != ' ': return False text = text[1:] if '+' in text and '-' in text: return False if '+' in text: if text.count('+') != 1: return False if text[0] != '+': return False text = text[1:] if not text: return False if '-' in text: if text.count('-') != 1: return False if text[0] != '-': return False text = text[1:] if not text: return False valid_set = frozenset(string.digits) value_set = frozenset(text) if len(value_set - valid_set) != 0: return False return True ################################################################################ ################################################################################ from Interpreter import partition_number VMC_2_TRI = { (INS.PUSH, True): (0, 0), (INS.COPY, False): (0, 2, 0), (INS.COPY, True): (0, 1, 0), (INS.SWAP, False): (0, 2, 1), (INS.AWAY, False): (0, 2, 2), (INS.AWAY, True): (0, 1, 2), (INS.ADD, False): (1, 0, 0, 0), (INS.SUB, False): (1, 0, 0, 1), (INS.MUL, False): (1, 0, 0, 2), (INS.DIV, False): (1, 0, 1, 0), (INS.MOD, False): (1, 0, 1, 1), (INS.SET, False): (1, 1, 0), (INS.GET, False): (1, 1, 1), (INS.PART, True): (2, 0, 0), (INS.CALL, True): (2, 0, 1), (INS.GOTO, True): (2, 0, 2), (INS.ZERO, True): (2, 1, 0), (INS.LESS, True): (2, 1, 1), (INS.BACK, False): (2, 1, 2), (INS.EXIT, False): (2, 2, 2), (INS.OCHR, False): (1, 2, 0, 0), (INS.OINT, False): (1, 2, 0, 1), (INS.ICHR, False): (1, 2, 1, 0), (INS.IINT, False): (1, 2, 1, 1) } ################################################################################ def to_trinary(program): trinary_code = [] for ins in program: if isinstance(ins, tuple): ins, arg = ins trinary_code.extend(VMC_2_TRI[(ins, True)]) trinary_code.extend(from_number(arg)) else: trinary_code.extend(VMC_2_TRI[(ins, False)]) return tuple(trinary_code) def from_number(arg): code = [int(arg < 0)] if arg: for bit in reversed(list(partition_number(abs(arg), 2))): code.append(bit) return code + [2] return code + [0, 2] to_ws = lambda trinary: ''.join(' \t\n'[index] for index in trinary) def compile_wsa(source): program = parse(source) trinary = to_trinary(program) ws_code = to_ws(trinary) return ws_code ################################################################################ ################################################################################ import os import sys import time import traceback def main(): name, source, command_line, error = get_source() if not error: start = time.clock() try: ws_code = compile_wsa(source) except: print('ERROR: File could not be compiled.\n') traceback.print_exc() error = True else: path = os.path.join('Programs', name + '.ws') try: open(path, 'w').write(ws_code) except IOError as err: print(err) error = True else: div, mod = divmod((time.clock() - start) * 1000, 1) args = int(div), '{:.3}'.format(mod)[1:] print('DONE: Comipled in {}{} ms'.format(*args)) handle_close(error, command_line) def get_source(): if len(sys.argv) > 1: command_line = True name = sys.argv[1] else: command_line = False try: name = input('Source File: ') except: return None, None, False, True print() path = os.path.join('Assembly', name + '.wsa') try: return name, open(path).read(), command_line, False except IOError as err: print(err) return None, None, command_line, True def handle_close(error, command_line): if error: usage = 'Usage: {} <assembly>'.format(os.path.basename(sys.argv[0])) print('\n{}\n{}'.format('-' * len(usage), usage)) if not command_line: time.sleep(10) ################################################################################ if __name__ == '__main__': main() Whitespace Helpers #! /usr/bin/env python """Helpers.py Includes a function to encode Python strings into my WSA format. Has a "PRINT_LINE" function that can be copied to a WSA program. Contains a "PRINT" function and documentation as an explanation.""" ################################################################################ __author__ = 'Stephen "Zero" Chappell <[email protected]>' __date__ = '14 March 2010' __version__ = '$Revision: 1 $' ################################################################################ def encode_string(string, addr): print(' push', addr) print(' push', len(string)) print(' set') addr += 1 for offset, character in enumerate(string): print(' push', addr + offset) print(' push', ord(character)) print(' set') ################################################################################ # Prints a string with newline. # push addr # call "PRINT_LINE" """ part "PRINT_LINE" call "PRINT" push 10 ochr back """ ################################################################################ # def print(array): # if len(array) <= 0: # return # offset = 1 # while len(array) - offset >= 0: # ptr = array.ptr + offset # putch(array[ptr]) # offset += 1 """ part "PRINT" # Line 1-2 copy get less "__PRINT_RET_1" copy get zero "__PRINT_RET_1" # Line 3 push 1 # Line 4 part "__PRINT_LOOP" copy copy 2 get swap sub less "__PRINT_RET_2" # Line 5 copy 1 copy 1 add # Line 6 get ochr # Line 7 push 1 add goto "__PRINT_LOOP" part "__PRINT_RET_2" away part "__PRINT_RET_1" away back """ Whitespace Interpreter #! /usr/bin/env python """Interpreter.py Runs programs in "Programs" and creates *.WSO files when needed. Can be executed directly by double-click or on the command line. If run on command line, add "ASM" flag to dump program assembly.""" ################################################################################ __author__ = 'Stephen "Zero" Chappell <[email protected]>' __date__ = '14 March 2010' __version__ = '$Revision: 4 $' ################################################################################ def test_file(path): disassemble(parse(trinary(load(path))), True) ################################################################################ load = lambda ws: ''.join(c for r in open(ws) for c in r if c in ' \t\n') trinary = lambda ws: tuple(' \t\n'.index(c) for c in ws) ################################################################################ def enum(names): names = names.replace(',', ' ').split() space = dict((reversed(pair) for pair in enumerate(names)), __slots__=()) return type('enum', (object,), space)() INS = enum('''\ PUSH, COPY, SWAP, AWAY, \ ADD, SUB, MUL, DIV, MOD, \ SET, GET, \ PART, CALL, GOTO, ZERO, LESS, BACK, EXIT, \ OCHR, OINT, ICHR, IINT''') ################################################################################ def parse(code): ins = iter(code).__next__ program = [] while True: try: imp = ins() except StopIteration: return tuple(program) if imp == 0: # [Space] parse_stack(ins, program) elif imp == 1: # [Tab] imp = ins() if imp == 0: # [Tab][Space] parse_math(ins, program) elif imp == 1: # [Tab][Tab] parse_heap(ins, program) else: # [Tab][Line] parse_io(ins, program) else: # [Line] parse_flow(ins, program) def parse_number(ins): sign = ins() if sign == 2: raise StopIteration() buffer = '' code = ins() if code == 2: raise StopIteration() while code != 2: buffer += str(code) code = ins() if sign == 1: return int(buffer, 2) * -1 return int(buffer, 2) ################################################################################ def parse_stack(ins, program): code = ins() if code == 0: # [Space] number = parse_number(ins) program.append((INS.PUSH, number)) elif code == 1: # [Tab] code = ins() number = parse_number(ins) if code == 0: # [Tab][Space] program.append((INS.COPY, number)) elif code == 1: # [Tab][Tab] raise StopIteration() else: # [Tab][Line] program.append((INS.AWAY, number)) else: # [Line] code = ins() if code == 0: # [Line][Space] program.append(INS.COPY) elif code == 1: # [Line][Tab] program.append(INS.SWAP) else: # [Line][Line] program.append(INS.AWAY) def parse_math(ins, program): code = ins() if code == 0: # [Space] code = ins() if code == 0: # [Space][Space] program.append(INS.ADD) elif code == 1: # [Space][Tab] program.append(INS.SUB) else: # [Space][Line] program.append(INS.MUL) elif code == 1: # [Tab] code = ins() if code == 0: # [Tab][Space] program.append(INS.DIV) elif code == 1: # [Tab][Tab] program.append(INS.MOD) else: # [Tab][Line] raise StopIteration() else: # [Line] raise StopIteration() def parse_heap(ins, program): code = ins() if code == 0: # [Space] program.append(INS.SET) elif code == 1: # [Tab] program.append(INS.GET) else: # [Line] raise StopIteration() def parse_io(ins, program): code = ins() if code == 0: # [Space] code = ins() if code == 0: # [Space][Space] program.append(INS.OCHR) elif code == 1: # [Space][Tab] program.append(INS.OINT) else: # [Space][Line] raise StopIteration() elif code == 1: # [Tab] code = ins() if code == 0: # [Tab][Space] program.append(INS.ICHR) elif code == 1: # [Tab][Tab] program.append(INS.IINT) else: # [Tab][Line] raise StopIteration() else: # [Line] raise StopIteration() def parse_flow(ins, program): code = ins() if code == 0: # [Space] code = ins() label = parse_number(ins) if code == 0: # [Space][Space] program.append((INS.PART, label)) elif code == 1: # [Space][Tab] program.append((INS.CALL, label)) else: # [Space][Line] program.append((INS.GOTO, label)) elif code == 1: # [Tab] code = ins() if code == 0: # [Tab][Space] label = parse_number(ins) program.append((INS.ZERO, label)) elif code == 1: # [Tab][Tab] label = parse_number(ins) program.append((INS.LESS, label)) else: # [Tab][Line] program.append(INS.BACK) else: # [Line] code = ins() if code == 2: # [Line][Line] program.append(INS.EXIT) else: # [Line][Space] or [Line][Tab] raise StopIteration() ################################################################################ MNEMONIC = '\ push copy swap away add sub mul div mod set get part \ call goto zero less back exit ochr oint ichr iint'.split() HAS_ARG = [getattr(INS, name) for name in 'PUSH COPY AWAY PART CALL GOTO ZERO LESS'.split()] HAS_LABEL = [getattr(INS, name) for name in 'PART CALL GOTO ZERO LESS'.split()] def disassemble(program, names=False): if names: names = create_names(program) for ins in program: if isinstance(ins, tuple): ins, arg = ins assert ins in HAS_ARG has_arg = True else: assert INS.PUSH <= ins <= INS.IINT has_arg = False if ins == INS.PART: if names: print(MNEMONIC[ins], '"' + names[arg] + '"') else: print(MNEMONIC[ins], arg) elif has_arg and ins in HAS_ARG: if ins in HAS_LABEL and names: assert arg in names print(' ' + MNEMONIC[ins], '"' + names[arg] + '"') else: print(' ' + MNEMONIC[ins], arg) else: print(' ' + MNEMONIC[ins]) ################################################################################ def create_names(program): names = {} number = 1 for ins in program: if isinstance(ins, tuple) and ins[0] == INS.PART: label = ins[1] assert label not in names names[label] = number_to_name(number) number += 1 return names def number_to_name(number): name = '' for offset in reversed(list(partition_number(number, 27))): if offset: name += chr(ord('A') + offset - 1) else: name += '_' return name def partition_number(number, base): div, mod = divmod(number, base) yield mod while div: div, mod = divmod(div, base) yield mod ################################################################################ CODE = (' \t\n', ' \n ', ' \t \t\n', ' \n\t', ' \n\n', ' \t\n \t\n', '\t ', '\t \t', '\t \n', '\t \t ', '\t \t\t', '\t\t ', '\t\t\t', '\n \t\n', '\n \t \t\n', '\n \n \t\n', '\n\t \t\n', '\n\t\t \t\n', '\n\t\n', '\n\n\n', '\t\n ', '\t\n \t', '\t\n\t ', '\t\n\t\t') EXAMPLE = ''.join(CODE) ################################################################################ NOTES = '''\ STACK ===== push number copy copy number swap away away number MATH ==== add sub mul div mod HEAP ==== set get FLOW ==== part label call label goto label zero label less label back exit I/O === ochr oint ichr iint''' ################################################################################ ################################################################################ class Stack: def __init__(self): self.__data = [] # Stack Operators def push(self, number): self.__data.append(number) def copy(self, number=None): if number is None: self.__data.append(self.__data[-1]) else: size = len(self.__data) index = size - number - 1 assert 0 <= index < size self.__data.append(self.__data[index]) def swap(self): self.__data[-2], self.__data[-1] = self.__data[-1], self.__data[-2] def away(self, number=None): if number is None: self.__data.pop() else: size = len(self.__data) index = size - number - 1 assert 0 <= index < size del self.__data[index:-1] # Math Operators def add(self): suffix = self.__data.pop() prefix = self.__data.pop() self.__data.append(prefix + suffix) def sub(self): suffix = self.__data.pop() prefix = self.__data.pop() self.__data.append(prefix - suffix) def mul(self): suffix = self.__data.pop() prefix = self.__data.pop() self.__data.append(prefix * suffix) def div(self): suffix = self.__data.pop() prefix = self.__data.pop() self.__data.append(prefix // suffix) def mod(self): suffix = self.__data.pop() prefix = self.__data.pop() self.__data.append(prefix % suffix) # Program Operator def pop(self): return self.__data.pop() ################################################################################ class Heap: def __init__(self): self.__data = {} def set_(self, addr, item): if item: self.__data[addr] = item elif addr in self.__data: del self.__data[addr] def get_(self, addr): return self.__data.get(addr, 0) ################################################################################ import os import zlib import msvcrt import pickle import string class CleanExit(Exception): pass NOP = lambda arg: None DEBUG_WHITESPACE = False ################################################################################ class Program: NO_ARGS = INS.COPY, INS.SWAP, INS.AWAY, INS.ADD, \ INS.SUB, INS.MUL, INS.DIV, INS.MOD, \ INS.SET, INS.GET, INS.BACK, INS.EXIT, \ INS.OCHR, INS.OINT, INS.ICHR, INS.IINT HAS_ARG = INS.PUSH, INS.COPY, INS.AWAY, INS.PART, \ INS.CALL, INS.GOTO, INS.ZERO, INS.LESS def __init__(self, code): self.__data = code self.__validate() self.__build_jump() self.__check_jump() self.__setup_exec() def __setup_exec(self): self.__iptr = 0 self.__stck = stack = Stack() self.__heap = Heap() self.__cast = [] self.__meth = (stack.push, stack.copy, stack.swap, stack.away, stack.add, stack.sub, stack.mul, stack.div, stack.mod, self.__set, self.__get, NOP, self.__call, self.__goto, self.__zero, self.__less, self.__back, self.__exit, self.__ochr, self.__oint, self.__ichr, self.__iint) def step(self): ins = self.__data[self.__iptr] self.__iptr += 1 if isinstance(ins, tuple): self.__meth[ins[0]](ins[1]) else: self.__meth[ins]() def run(self): while True: ins = self.__data[self.__iptr] self.__iptr += 1 if isinstance(ins, tuple): self.__meth[ins[0]](ins[1]) else: self.__meth[ins]() def __oint(self): for digit in str(self.__stck.pop()): msvcrt.putwch(digit) def __ichr(self): addr = self.__stck.pop() # Input Routine while msvcrt.kbhit(): msvcrt.getwch() while True: char = msvcrt.getwch() if char in '\x00\xE0': msvcrt.getwch() elif char in string.printable: char = char.replace('\r', '\n') msvcrt.putwch(char) break item = ord(char) # Storing Number self.__heap.set_(addr, item) def __iint(self): addr = self.__stck.pop() # Input Routine while msvcrt.kbhit(): msvcrt.getwch() buff = '' char = msvcrt.getwch() while char != '\r' or not buff: if char in '\x00\xE0': msvcrt.getwch() elif char in '+-' and not buff: msvcrt.putwch(char) buff += char elif '0' <= char <= '9': msvcrt.putwch(char) buff += char elif char == '\b': if buff: buff = buff[:-1] msvcrt.putwch(char) msvcrt.putwch(' ') msvcrt.putwch(char) char = msvcrt.getwch() msvcrt.putwch(char) msvcrt.putwch('\n') item = int(buff) # Storing Number self.__heap.set_(addr, item) def __goto(self, label): self.__iptr = self.__jump[label] def __zero(self, label): if self.__stck.pop() == 0: self.__iptr = self.__jump[label] def __less(self, label): if self.__stck.pop() < 0: self.__iptr = self.__jump[label] def __exit(self): self.__setup_exec() raise CleanExit() def __set(self): item = self.__stck.pop() addr = self.__stck.po

    Read the article

  • Extension methods on a null object instance – something you did not know

    - by nmarun
    Extension methods gave developers with a lot of bandwidth to do interesting (read ‘cool’) things. But there are a couple of things that we need to be aware of while using these extension methods. I have a StringUtil class that defines two extension methods: 1: public static class StringUtils 2: { 3: public static string Left( this string arg, int leftCharCount) 4: { 5: if (arg == null ) 6: { 7: throw new ArgumentNullException( "arg" ); 8: } 9: return arg.Substring(0, leftCharCount); 10...(read more)

    Read the article

  • How to configure Spring Security PasswordComparisonAuthenticator

    - by denlab
    I can bind to an embedded ldap server on my local machine with the following bean: <b:bean id="secondLdapProvider" class="org.springframework.security.ldap.authentication.LdapAuthenticationProvider"> <b:constructor-arg> <b:bean class="org.springframework.security.ldap.authentication.BindAuthenticator"> <b:constructor-arg ref="contextSource" /> <b:property name="userSearch"> <b:bean id="userSearch" class="org.springframework.security.ldap.search.FilterBasedLdapUserSearch"> <b:constructor-arg index="0" value="ou=people"/> <b:constructor-arg index="1" value="(uid={0})"/> <b:constructor-arg index="2" ref="contextSource" /> </b:bean> </b:property> </b:bean> </b:constructor-arg> <b:constructor-arg> <b:bean class="com.company.security.ldap.BookinLdapAuthoritiesPopulator"> </b:bean> </b:constructor-arg> </b:bean> however, when I try to authenticate with a PasswordComparisonAuthenticator it repeatedly fails on a bad credentials event: <b:bean id="ldapAuthProvider" class="org.springframework.security.ldap.authentication.LdapAuthenticationProvider"> <b:constructor-arg> <b:bean class="org.springframework.security.ldap.authentication.PasswordComparisonAuthenticator"> <b:constructor-arg ref="contextSource" /> <b:property name="userDnPatterns"> <b:list> <b:value>uid={0},ou=people</b:value> </b:list> </b:property> </b:bean> </b:constructor-arg> <b:constructor-arg> <b:bean class="com.company.security.ldap.BookinLdapAuthoritiesPopulator"> </b:bean> </b:constructor-arg> </b:bean> Through debugging, I can see that the authenticate method picks up the DN from the ldif file, but then tries to compare the passwords, however, it's using the LdapShaPasswordEncoder (the default one) where the password is stored in plaintext in the file, and this is where the authentication fails. Here's the authentication manager bean referencing the preferred authentication bean: <authentication-manager> <authentication-provider ref="ldapAuthProvider"/> <authentication-provider user-service-ref="userDetailsService"> <password-encoder hash="md5" base64="true"> <salt-source system-wide="secret"/> </password-encoder> </authentication-provider> </authentication-manager> On a side note, whether I set the password-encoder on ldapAuthProvider to plaintext or just leave it blank, doesn't seem to make a difference. Any help would be greatly appreciated. Thanks

    Read the article

  • Warning: comparison with string literals results in unspecified behaviour

    - by nunos
    So I starting the project of writing a simplified sheel for linux in c. I am not at all proficient with c nor with Linux that's exactly the reason I decided it would be a good idea. Starting with the parser, I have already encountered some problems. The code should be straightforward that's why I didn't include any comments. I am getting a warning with gcc: "comparison with string literals results in unspecified behaviour" at the lines commented with "WARNING HERE" (see code below). I have no idea why this causes an warning, but the real problem is that even though I am comparing an "<" to an "<" is doesn't get inside the if... I am looking for an answer for the problem explained, however if there's something that you see in the code that should be improved please say so. Just take in mind I am not that proficient and that this is still a work in progress (or better yet, a work in start). Thanks in advance. #include <stdio.h> #include <unistd.h> #include <string.h> typedef enum {false, true} bool; typedef struct { char **arg; char *infile; char *outfile; int background; } Command_Info; int parse_cmd(char *cmd_line, Command_Info *cmd_info) { char *arg; char *args[100]; int i = 0; arg = strtok(cmd_line, " \n"); while (arg != NULL) { args[i] = arg; arg = strtok(NULL, " \n"); i++; } int num_elems = i; cmd_info->infile = NULL; cmd_info->outfile = NULL; cmd_info->background = 0; int iarg = 0; for (i = 0; i < num_elems; i++) { if (args[i] == "&") //WARNING HERE return -1; else if (args[i] == "<") //WARNING HERE if (args[i+1] != NULL) cmd_info->infile = args[i+1]; else return -1; else if (args[i] == ">") //WARNING HERE if (args[i+1] != NULL) cmd_info->outfile = args[i+1]; else return -1; else cmd_info->arg[iarg++] = args[i]; } cmd_info->arg[iarg] = NULL; return 0; } void print_cmd(Command_Info *cmd_info) { int i; for (i = 0; cmd_info->arg[i] != NULL; i++) printf("arg[%d]=\"%s\"\n", i, cmd_info->arg[i]); printf("arg[%d]=\"%s\"\n", i, cmd_info->arg[i]); printf("infile=\"%s\"\n", cmd_info->infile); printf("outfile=\"%s\"\n", cmd_info->outfile); printf("background=\"%d\"\n", cmd_info->background); } int main(int argc, char* argv[]) { char cmd_line[100]; Command_Info cmd_info; printf(">>> "); fgets(cmd_line, 100, stdin); parse_cmd(cmd_line, &cmd_info); print_cmd(&cmd_info); return 0; }

    Read the article

  • Spawn a multi-threaded Java program from a Windows command line program, spawner won't end until spa

    - by Ross Patterson
    Short version: How can I prevent a spawned Java process in Windows from blocking the spawning process from ending? Long version: I'm trying to spawn a multi-threaded Java program (Selenium RC, not that it should matter) from a program launched from the Windows command line (NAnt's <exec> task, again, not that it should matter). I'm doing it using the Windows "start" command, and the spawned process is started and runs correctly. The spawning process receives control back and finishes (NAnt says "BUILD SUCCEEDED"), but doesn't actually exit to the command line. When the spawned process finally terminates (could be hours later), the command process returns and the command line prompt occurs. For example: <target name="start_rc"> <exec program="cmd" failonerror="false" workingdir="${ross.p5.dir}\Tools\selenium\selenium-server-1.0.1" verbose="true"> <arg value="/C"/> <arg value="start"/> <arg value="java"/> <arg value="-jar"/> <arg path="${ross.p5.dir}\Tools\selenium\selenium-server-1.0.1\selenium-server.jar"/> <arg value="-userExtensions"/> <arg path="${ross.p5.dir}\Tools\selenium\selenium-server-1.0.1\user-extensions.js"/> <arg value="-browserSideLog"/> <arg value="-log"/> <arg value="${ross.p5.dir}\artifacts\selenium.log"/> <arg value="-debug"/> </exec> </target> Produces: C :\Ross>nant start_rc NAnt 0.86 (Build 0.86.2898.0; beta1; 12/8/2007) Copyright (C) 2001-2007 Gerry Shaw http://nant.sourceforge.net Buildfile: file:///C:/Ross/ross.build Target framework: Microsoft .NET Framework 3.5 Target(s) specified: start_rc start_rc: [exec] Starting 'cmd (/C start java -jar C:\p5\Tools\selenium\selenium-server-1.0.1\selenium-server.jar -userExtensions C:\p5\Tools\selenium\selenium-server-1.0.1\user-extensions.js -browserSideLog -log C:\p5\artifacts\selenium.log -debug)' in 'C:\p5\Tools\selenium\selenium-server-1.0.1' BUILD SUCCEEDED Total time: 4.1 seconds. ... and then nothing until I close the window where Java is running, then ... C:\Ross> Obviously something is preventing the nant process from terminating, but shouldn't the Windows START command prevent that?

    Read the article

  • spring security : Failed to load ApplicationContext with pre-post-annotations="enabled"

    - by thogau
    I am using spring 3.0.1 + spring-security 3.0.2 and I am trying to use features like @PreAuthorize and @PostFilter annotations. When running in units tests using @RunWith(SpringJUnit4ClassRunner.class) or in a main(String[] args) method my application context fails to start if enable pre-post-annotations and use org.springframework.security.acls.AclPermissionEvaluator : <!-- Enable method level security--> <security:global-method-security pre-post-annotations="enabled"> <security:expression-handler ref="expressionHandler"/> </security:global-method-security> <bean id="expressionHandler" class="org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler"> <property name="permissionEvaluator" ref="aclPermissionEvaluator"/> </bean> <bean id="aclPermissionEvaluator" class="org.springframework.security.acls.AclPermissionEvaluator"> <constructor-arg ref="aclService"/> </bean> <!-- Enable stereotype support --> <context:annotation-config /> <context:component-scan base-package="com.rreps.core" /> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:applicationContext.properties</value> </list> </property> </bean> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="${jdbc.driver}" /> <property name="jdbcUrl" value="${jdbc.url}" /> <property name="user" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <property name="initialPoolSize" value="10" /> <property name="minPoolSize" value="5" /> <property name="maxPoolSize" value="25" /> <property name="acquireRetryAttempts" value="10" /> <property name="acquireIncrement" value="5" /> <property name="idleConnectionTestPeriod" value="3600" /> <property name="maxIdleTime" value="10800" /> <property name="maxConnectionAge" value="14400" /> <property name="preferredTestQuery" value="SELECT 1;" /> <property name="testConnectionOnCheckin" value="false" /> </bean> <bean id="auditedSessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="configLocation" value="classpath:hibernate.cfg.xml" /> <property name="hibernateProperties"> <value> hibernate.dialect=${hibernate.dialect} hibernate.query.substitutions=true 'Y', false 'N' hibernate.cache.use_second_level_cache=true hibernate.cache.provider_class=net.sf.ehcache.hibernate.SingletonEhCacheProvider hibernate.hbm2ddl.auto=update hibernate.c3p0.acquire_increment=5 hibernate.c3p0.idle_test_period=3600 hibernate.c3p0.timeout=10800 hibernate.c3p0.max_size=25 hibernate.c3p0.min_size=1 hibernate.show_sql=false hibernate.validator.autoregister_listeners=false </value> </property> <!-- validation is performed by "hand" (see http://opensource.atlassian.com/projects/hibernate/browse/HV-281) <property name="eventListeners"> <map> <entry key="pre-insert" value-ref="beanValidationEventListener" /> <entry key="pre-update" value-ref="beanValidationEventListener" /> </map> </property> --> <property name="entityInterceptor"> <bean class="com.rreps.core.dao.hibernate.interceptor.TrackingInterceptor" /> </property> </bean> <bean id="simpleSessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="configLocation" value="classpath:hibernate.cfg.xml" /> <property name="hibernateProperties"> <value> hibernate.dialect=${hibernate.dialect} hibernate.query.substitutions=true 'Y', false 'N' hibernate.cache.use_second_level_cache=true hibernate.cache.provider_class=net.sf.ehcache.hibernate.SingletonEhCacheProvider hibernate.hbm2ddl.auto=update hibernate.c3p0.acquire_increment=5 hibernate.c3p0.idle_test_period=3600 hibernate.c3p0.timeout=10800 hibernate.c3p0.max_size=25 hibernate.c3p0.min_size=1 hibernate.show_sql=false hibernate.validator.autoregister_listeners=false </value> </property> <!-- property name="eventListeners"> <map> <entry key="pre-insert" value-ref="beanValidationEventListener" /> <entry key="pre-update" value-ref="beanValidationEventListener" /> </map> </property--> </bean> <bean id="sequenceSessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="configLocation" value="classpath:hibernate.cfg.xml" /> <property name="hibernateProperties"> <value> hibernate.dialect=${hibernate.dialect} hibernate.query.substitutions=true 'Y', false 'N' hibernate.cache.use_second_level_cache=true hibernate.cache.provider_class=net.sf.ehcache.hibernate.SingletonEhCacheProvider hibernate.hbm2ddl.auto=update hibernate.c3p0.acquire_increment=5 hibernate.c3p0.idle_test_period=3600 hibernate.c3p0.timeout=10800 hibernate.c3p0.max_size=25 hibernate.c3p0.min_size=1 hibernate.show_sql=false hibernate.validator.autoregister_listeners=false </value> </property> </bean> <bean id="validationFactory" class="javax.validation.Validation" factory-method="buildDefaultValidatorFactory" /> <!-- bean id="beanValidationEventListener" class="org.hibernate.cfg.beanvalidation.BeanValidationEventListener"> <constructor-arg index="0" ref="validationFactory" /> <constructor-arg index="1"> <props/> </constructor-arg> </bean--> <!-- Enable @Transactional support --> <tx:annotation-driven transaction-manager="transactionManager"/> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="auditedSessionFactory" /> </bean> <security:authentication-manager alias="authenticationManager"> <security:authentication-provider user-service-ref="userDetailsService" /> </security:authentication-manager> <bean id="userDetailsService" class="com.rreps.core.service.impl.UserDetailsServiceImpl" /> <!-- ACL stuff --> <bean id="aclCache" class="org.springframework.security.acls.domain.EhCacheBasedAclCache"> <constructor-arg> <bean class="org.springframework.cache.ehcache.EhCacheFactoryBean"> <property name="cacheManager"> <bean class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"/> </property> <property name="cacheName" value="aclCache"/> </bean> </constructor-arg> </bean> <bean id="lookupStrategy" class="org.springframework.security.acls.jdbc.BasicLookupStrategy"> <constructor-arg ref="dataSource"/> <constructor-arg ref="aclCache"/> <constructor-arg> <bean class="org.springframework.security.acls.domain.AclAuthorizationStrategyImpl"> <constructor-arg> <list> <bean class="org.springframework.security.core.authority.GrantedAuthorityImpl"> <constructor-arg value="ROLE_ADMINISTRATEUR"/> </bean> <bean class="org.springframework.security.core.authority.GrantedAuthorityImpl"> <constructor-arg value="ROLE_ADMINISTRATEUR"/> </bean> <bean class="org.springframework.security.core.authority.GrantedAuthorityImpl"> <constructor-arg value="ROLE_ADMINISTRATEUR"/> </bean> </list> </constructor-arg> </bean> </constructor-arg> <constructor-arg> <bean class="org.springframework.security.acls.domain.ConsoleAuditLogger"/> </constructor-arg> </bean> <bean id="aclService" class="com.rreps.core.service.impl.MysqlJdbcMutableAclService"> <constructor-arg ref="dataSource"/> <constructor-arg ref="lookupStrategy"/> <constructor-arg ref="aclCache"/> </bean> The strange thing is that the context starts normally when deployed in a webapp and @PreAuthorize and @PostFilter annotations are working fine as well... Any idea what is wrong? Here is the end of the stacktrace : ... 55 more Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [applicationContext-core.xml]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.transaction.config.internalTransactionAdvisor': Cannot resolve reference to bean 'org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0' while setting bean property 'transactionAttributeSource'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0': Initialization of bean failed; nested exception is java.lang.NullPointerException at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:521) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:450) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:290) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:287) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:189) at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:322) ... 67 more Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.transaction.config.internalTransactionAdvisor': Cannot resolve reference to bean 'org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0' while setting bean property 'transactionAttributeSource'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0': Initialization of bean failed; nested exception is java.lang.NullPointerException at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:328) at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:106) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1308) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1067) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:511) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:450) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:290) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:287) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193) at org.springframework.aop.framework.autoproxy.BeanFactoryAdvisorRetrievalHelper.findAdvisorBeans(BeanFactoryAdvisorRetrievalHelper.java:86) at org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.findCandidateAdvisors(AbstractAdvisorAutoProxyCreator.java:100) at org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.findEligibleAdvisors(AbstractAdvisorAutoProxyCreator.java:86) at org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.getAdvicesAndAdvisorsForBean(AbstractAdvisorAutoProxyCreator.java:68) at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.wrapIfNecessary(AbstractAutoProxyCreator.java:359) at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.postProcessAfterInitialization(AbstractAutoProxyCreator.java:322) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsAfterInitialization(AbstractAutowireCapableBeanFactory.java:404) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1409) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513) ... 73 more Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0': Initialization of bean failed; nested exception is java.lang.NullPointerException at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:521) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:450) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:290) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:287) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:189) at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:322) ... 91 more Caused by: java.lang.NullPointerException at org.springframework.security.access.method.DelegatingMethodSecurityMetadataSource.getAttributes(DelegatingMethodSecurityMetadataSource.java:52) at org.springframework.security.access.intercept.aopalliance.MethodSecurityMetadataSourceAdvisor$MethodSecurityMetadataSourcePointcut.matches(MethodSecurityMetadataSourceAdvisor.java:129) at org.springframework.aop.support.AopUtils.canApply(AopUtils.java:215) at org.springframework.aop.support.AopUtils.canApply(AopUtils.java:252) at org.springframework.aop.support.AopUtils.findAdvisorsThatCanApply(AopUtils.java:284) at org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.findAdvisorsThatCanApply(AbstractAdvisorAutoProxyCreator.java:117) at org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.findEligibleAdvisors(AbstractAdvisorAutoProxyCreator.java:87) at org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.getAdvicesAndAdvisorsForBean(AbstractAdvisorAutoProxyCreator.java:68) at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.wrapIfNecessary(AbstractAutoProxyCreator.java:359) at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.postProcessAfterInitialization(AbstractAutoProxyCreator.java:322) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsAfterInitialization(AbstractAutowireCapableBeanFactory.java:404) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1409) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513) ... 97 more

    Read the article

  • Multiple SFINAE rules

    - by Fred
    Hi everyone, After reading the answer to this question, I learned that SFINAE can be used to choose between two functions based on whether the class has a certain member function. It's the equivalent of the following, just that each branch in the if statement is split into an overloaded function: template<typename T> void Func(T& arg) { if(HAS_MEMBER_FUNCTION_X(T)) arg.X(); else //Do something else because T doesn't have X() } becomes template<typename T> void Func(T &arg, int_to_type<true>); //T has X() template<typename T> void Func(T &arg, int_to_type<false>); //T does not have X() I was wondering if it was possible to extend SFINAE to do multiple rules. Something that would be the equivalent of this: template<typename T> void Func(T& arg) { if(HAS_MEMBER_FUNCTION_X(T)) //See if T has a member function X arg.X(); else if(POINTER_DERIVED_FROM_CLASS_A(T)) //See if T is a pointer to a class derived from class A arg->A_Function(); else if(DERIVED_FROM_CLASS_B(T)) //See if T derives from class B arg.B_Function(); else if(IS_TEMPLATE_CLASS_C(T)) //See if T is class C<U> where U could be anything arg.C_Function(); else if(IS_POD(T)) //See if T is a POD type //Do something with a POD type else //Do something else because none of the above rules apply } Is something like this possible? Thank you.

    Read the article

  • How to treat an instance variable as an instance of another type in C#

    - by Ben Aston
    I have a simple inheritance heirarchy with MyType2 inheriting from MyType1. I have an instance of MyType1, arg, passed in as an argument to a method. If arg is an instance of MyType2, then I'd like to perform some logic, transforming the instance. My code looks something like the code below. Having to create a new local variable b feels inelegant - is there a way of achieving the same behavior without the additional local variable? public MyType1 MyMethod(MyType1 arg) { if(arg is MyType2) { MyType2 b = arg as MyType2; //use b (which modifies "arg" as "b" is a reference to it)... } return arg; }

    Read the article

  • Allocating memory for a array to char pointer

    - by nunos
    The following piece of code gives a segmentation fault when allocating memory for the last arg. What am I doing wrong? Thanks. int n_args = 0, i = 0; while (line[i] != '\0') { if (isspace(line[i++])) n_args++; } for (i = 0; i < n_args; i++) command = malloc (n_args * sizeof(char*)); char* arg = NULL; arg = strtok(line, " \n"); while (arg != NULL) { arg = strtok(NULL, " \n"); command[i] = malloc ( (strlen(arg)+1) * sizeof(char) ); strcpy(command[i], arg); i++; } Thanks.

    Read the article

  • Why does JPA require a no-arg constructor for domain objects ?

    - by Jacques René Mesrine
    Why does JPA require a no-arg constructor for domain objects ? I am using eclipselink and just got this exception during deployment. Exception [EclipseLink-63] (Eclipse Persistence Services-1.1.0.r3639-SNAPSHOT): org.eclipse.persistence.exceptions.DescriptorException Exception Description: The instance creation method [com.me.model.UserVO.<Default Constructor>], with no parameters, does not exist, or is not accessible. Internal Exception: java.lang.NoSuchMethodException: com.me.model.UserVO.<init>() Descriptor: RelationalDescriptor(com.me.model.UserVO --> [DatabaseTable(user)])

    Read the article

  • How to resovle javax.mail.AuthenticationFailedException issue?

    - by jl
    Hi, I am doing a sendMail Servlet with JavaMail. I have javax.mail.AuthenticationFailedException on my output. Can anyone please help me out? Thanks. sendMailServlet code: try { String host = "smtp.gmail.com"; String from = "[email protected]"; String pass = "pass"; Properties props = System.getProperties(); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", host); props.put("mail.smtp.user", from); props.put("mail.smtp.password", pass); props.put("mail.smtp.port", "587"); props.put("mail.smtp.auth", "true"); props.put("mail.debug", "true"); Session session = Session.getDefaultInstance(props, null); MimeMessage message = new MimeMessage(session); Address fromAddress = new InternetAddress(from); Address toAddress = new InternetAddress("[email protected]"); message.setFrom(fromAddress); message.setRecipient(Message.RecipientType.TO, toAddress); message.setSubject("Testing JavaMail"); message.setText("Welcome to JavaMail"); Transport transport = session.getTransport("smtp"); transport.connect(host, from, pass); message.saveChanges(); Transport.send(message); transport.close(); }catch(Exception ex){ out.println("<html><head></head><body>"); out.println("ERROR: " + ex); out.println("</body></html>"); } Output on GlassFish 2.1: DEBUG SMTP: trying to connect to host "smtp.gmail.com", port 587, isSSL false 220 mx.google.com ESMTP 36sm10907668yxh.13 DEBUG SMTP: connected to host "smtp.gmail.com", port: 587 EHLO platform-4cfaca 250-mx.google.com at your service, [203.126.159.130] 250-SIZE 35651584 250-8BITMIME 250-STARTTLS 250-ENHANCEDSTATUSCODES 250 PIPELINING DEBUG SMTP: Found extension "SIZE", arg "35651584" DEBUG SMTP: Found extension "8BITMIME", arg "" DEBUG SMTP: Found extension "STARTTLS", arg "" DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg "" DEBUG SMTP: Found extension "PIPELINING", arg "" STARTTLS 220 2.0.0 Ready to start TLS EHLO platform-4cfaca 250-mx.google.com at your service, [203.126.159.130] 250-SIZE 35651584 250-8BITMIME 250-AUTH LOGIN PLAIN 250-ENHANCEDSTATUSCODES 250 PIPELINING DEBUG SMTP: Found extension "SIZE", arg "35651584" DEBUG SMTP: Found extension "8BITMIME", arg "" DEBUG SMTP: Found extension "AUTH", arg "LOGIN PLAIN" DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg "" DEBUG SMTP: Found extension "PIPELINING", arg "" DEBUG SMTP: Attempt to authenticate AUTH LOGIN 334 VXNlcm5hbWU6 aWpveWNlbGVvbmdAZ21haWwuY29t 334 UGFzc3dvcmQ6 MTIzNDU2Nzhf 235 2.7.0 Accepted DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc] DEBUG SMTP: useEhlo true, useAuth true

    Read the article

  • Spring security ldap authentication with different ldap for authorities

    - by wuntee
    I am trying to set up an ldap authentication context where the authorities is a separate ldap instance (with the same principal name). I am having trouble setting up the authentication part, the logs dont show any search results for the following context. Can anyone see what I am doing wrong? <beans:bean id="ldapAuthProvider" class="org.springframework.security.ldap.authentication.LdapAuthenticationProvider"> <beans:constructor-arg> <beans:bean class="org.springframework.security.ldap.authentication.BindAuthenticator"> <beans:constructor-arg ref="adContextSource" /> <beans:property name="userSearch"> <beans:bean class="org.springframework.security.ldap.search.FilterBasedLdapUserSearch"> <beans:constructor-arg index="0" value=""/> <beans:constructor-arg index="1" value="(samaccountname={0})"/> <beans:constructor-arg index="2" ref="adContextSource" /> <beans:property name="searchSubtree" value="true" /> <beans:property name="returningAttributes"> <beans:list> <beans:value>DN</beans:value> </beans:list> </beans:property> </beans:bean> </beans:property> </beans:bean> </beans:constructor-arg> <beans:constructor-arg> <beans:bean class="org.springframework.security.ldap.userdetails.DefaultLdapAuthoritiesPopulator"> <beans:constructor-arg ref="cadaContextSource" /> <beans:constructor-arg value="ou=groups" /> <beans:property name="groupRoleAttribute" value="cn" /> </beans:bean> </beans:constructor-arg> </beans:bean> The logs simply show this when trying to authenticate: [DEBUG,UsernamePasswordAuthenticationFilter] Request is to process authentication [DEBUG,ProviderManager] Authentication attempt using org.springframework.security.ldap.authentication.LdapAuthenticationProvider [DEBUG,LdapAuthenticationProvider] Processing authentication request for user: wuntee [DEBUG,FilterBasedLdapUserSearch] Searching for user 'wuntee', with user search [ searchFilter: '(samaccountname={0})', searchBase: '', scope: subtree, searchTimeLimit: 0, derefLinkFlag: false ] [DEBUG,AbstractContextSource] Got Ldap context on server 'ldap://adapps.cable.comcast.com:3268/dc=comcast,dc=com/dc=comcast,dc=com' [DEBUG,XmlWebApplicationContext] Publishing event in Root WebApplicationContext: org.springframework.security.authentication.event.AuthenticationFailureServiceExceptionEvent[source=org.springframework.security.authentication.UsernamePasswordAuthenticationToken@b777617d: Principal: wuntee; Password: [PROTECTED]; Authenticated: false; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@12afc: RemoteIpAddress: 127.0.0.1; SessionId: 191F70ED4E8351F8638868C34C6A076A; Not granted any authorities] [DEBUG,DefaultListableBeanFactory] Returning cached instance of singleton bean 'org.springframework.security.core.session.SessionRegistryImpl#0' [DEBUG,UsernamePasswordAuthenticationFilter] Authentication request failed: org.springframework.security.authentication.AuthenticationServiceException: Failed to parse DN; nested exception is org.springframework.ldap.core.TokenMgrError: Lexical error at line 1, column 21. Encountered: "=" (61), after : "" [DEBUG,UsernamePasswordAuthenticationFilter] Updated SecurityContextHolder to contain null Authentication [DEBUG,UsernamePasswordAuthenticationFilter] Delegating to authentication failure handlerorg.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler@28651c

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >