Search Results

Search found 6242 results on 250 pages for 'named pipe'.

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

  • C# 4.0 Optional/Named Parameters Beginner&rsquo;s Tutorial

    - by mbcrump
    One of the interesting features of C# 4.0 is for both named and optional arguments.  They are often very useful together, but are quite actually two different things.  Optional arguments gives us the ability to omit arguments to method invocations. Named arguments allows us to specify the arguments by name instead of by position.  Code using the named parameters are often more readable than code relying on argument position.  These features were long overdue, especially in regards to COM interop. Below, I have included some examples to help you understand them more in depth. Please remember to target the .NET 4 Framework when trying these samples. Code Snippet using System;   namespace ConsoleApplication3 {     class Program     {         static void Main(string[] args)         {               //C# 4.0 Optional/Named Parameters Tutorial               Foo();                              //Prints to the console | Return Nothing 0             Foo("Print Something");             //Prints to the console | Print Something 0             Foo("Print Something", 1);          //Prints to the console | Print Something 1             Foo(x: "Print Something", i: 5);    //Prints to the console | Print Something 5             Foo(i: 5, x: "Print Something");    //Prints to the console | Print Something 5             Foo("Print Something", i: 5);       //Prints to the console | Print Something 5             Foo2(i3: 77);                       //Prints to the console | 77         //  Foo(x:"Print Something", 5);        //Positional parameters must come before named arguments. This will error out.             Console.Read();         }           static void Foo(string x = "Return Nothing", int i = 0)         {             Console.WriteLine(x + " " + i + Environment.NewLine);         }           static void Foo2(int i = 1, int i2 = 2, int i3 = 3, int i4 = 4)         {             Console.WriteLine(i3);         }     } }

    Read the article

  • Using HtmlAnchor for anchor tag that navigates in-page named anchor

    - by Frank Schwieterman
    I am trying to render a simple hyperlink that links to a named anchor within the page, for example: <a href="#namedAnchor"scroll to down</a <a name="namedAnchor"down</a The problem is that when I use an ASP.NET control like asp:HyperLink or HtmlAnchor, the href="#namedAnchor" is rendered as href="controls/#namedAnchor" (where controls is the subdirectory where the user control containing the anchor is). Here is the code for the control, using two types of anchor controls, which both have the same problem: <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="Test.ascx.cs" Inherits="TestWebApplication1.controls.Test" % <a href="#namedAnchor" runat="server"HtmlAnchor</a <asp:HyperLink NavigateUrl="#namedAnchor" runat="server"HyperLink</asp:HyperLink The generated source looks like: <a href="controls/#namedAnchor"HtmlAnchor</a <a href="controls/#namedAnchor"HyperLink</a I really just want: <a href="#namedAnchor"HtmlAnchor</a <a href="#namedAnchor"HyperLink</a I am using the HtmlAnchor or HyperLink class because I want to make changes to other attributes in the code behind. I do not want to introduce a custom web control for this requirement, as the requirement I'm pursuing is not that important and it would be hard to talk the team into abandoning the traditional ASP.NET link controls. It seems like I should be able to use the ASP.NET link controls to generate the desired link.

    Read the article

  • Firefox reloading parent page in iframe when clicking named anchor

    - by masty
    My site has an iframe which is dynamically populated with html content. The html often contains named anchors, which work fine in IE/Chrome but in Firefox it reopens the entire page within the iframe. Here's an example: load the page in firefox, scroll to the bottom of the iframe, click the "back to top" link, and you will see what I am talking about. <html><head></head><body onload="setFrameContent();"><script> var htmlBody = '<html> <head></head> <body>' + '<a name="top"><h1>top</h1></a>' + '<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>' + '<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>' + '<a href="#top">back to top</a></body> </html> '; function setFrameContent(){ if (frames.length > 0) { var d = frames[0].document; d.open(); d.write(htmlBody); d.close(); } } </script> <h1>Here's an iframe:</h1> <iframe id="htmlIframe" style="height: 400px; width: 100%"><p>Your browser does not support iframes.</p></iframe> </body></html> Any ideas?

    Read the article

  • Linux C: "Interactive session" with separate read and write named pipes?

    - by ~sd-imi
    Hi all, I am trying to work with "Introduction to Interprocess Communication Using Named Pipes - Full-Duplex Communication Using Named Pipes", http://developers.sun.com/solaris/articles/named_pipes.html#5 ; in particular fd_server.c (included below for reference) Here is my info and compile line: :~$ cat /etc/issue Ubuntu 10.04 LTS \n \l :~$ gcc --version gcc (Ubuntu 4.4.3-4ubuntu5) 4.4.3 :~$ gcc fd_server.c -o fd_server fd_server.c creates two named pipes, one for reading and one for writing. What one can do, is: in one terminal, run the server and read (through cat) its write pipe: :~$ ./fd_server & 2/dev/null [1] 11354 :~$ cat /tmp/np2 and in another, write (using echo) to server's read pipe: :~$ echo "heeellloooo" /tmp/np1 going back to first terminal, one can see: :~$ cat /tmp/np2 HEEELLLOOOO 0[1]+ Exit 13 ./fd_server 2 /dev/null What I would like to do, is make sort of a "interactive" (or "shell"-like) session; that is, the server is run as usual, but instead of running "cat" and "echo", I'd like to use something akin to screen. What I mean by that, is that screen can be called like screen /dev/ttyS0 38400, and then it makes a sort of a interactive session, where what is typed in terminal is passed to /dev/ttyS0, and its response is written to terminal. Now, of course, I cannot use screen, because in my case the program has two separate nodes, and as far as I can tell, screen can refer to only one. How would one go about to achieve this sort of "interactive" session in this context (with two separate read/write pipes)? Thanks, Cheers! Code below: #include <stdio.h> #include <errno.h> #include <ctype.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> //#include <fullduplex.h> /* For name of the named-pipe */ #define NP1 "/tmp/np1" #define NP2 "/tmp/np2" #define MAX_BUF_SIZE 255 #include <stdlib.h> //exit #include <string.h> //strlen int main(int argc, char *argv[]) { int rdfd, wrfd, ret_val, count, numread; char buf[MAX_BUF_SIZE]; /* Create the first named - pipe */ ret_val = mkfifo(NP1, 0666); if ((ret_val == -1) && (errno != EEXIST)) { perror("Error creating the named pipe"); exit (1); } ret_val = mkfifo(NP2, 0666); if ((ret_val == -1) && (errno != EEXIST)) { perror("Error creating the named pipe"); exit (1); } /* Open the first named pipe for reading */ rdfd = open(NP1, O_RDONLY); /* Open the second named pipe for writing */ wrfd = open(NP2, O_WRONLY); /* Read from the first pipe */ numread = read(rdfd, buf, MAX_BUF_SIZE); buf[numread] = '0'; fprintf(stderr, "Full Duplex Server : Read From the pipe : %sn", buf); /* Convert to the string to upper case */ count = 0; while (count < numread) { buf[count] = toupper(buf[count]); count++; } /* * Write the converted string back to the second * pipe */ write(wrfd, buf, strlen(buf)); } Edit: Right, just to clarify - it seems I found a document discussing something very similar, it is http://en.wikibooks.org/wiki/Serial_Programming/Serial_Linux#Configuration_with_stty - a modification of the script there ("For example, the following script configures the device and starts a background process for copying all received data from the serial device to standard output...") for the above program is below: # stty raw # ( ./fd_server 2>/dev/null; )& bgPidS=$! ( cat < /tmp/np2 ; )& bgPid=$! # Read commands from user, send them to device echo $(kill -0 $bgPidS 2>/dev/null ; echo $?) while [ "$(kill -0 $bgPidS 2>/dev/null ; echo $?)" -eq "0" ] && read cmd; do # redirect debug msgs to stderr, as here we're redirected to /tmp/np1 echo "$? - $bgPidS - $bgPid" >&2 echo "$cmd" echo -e "\nproc: $(kill -0 $bgPidS 2>/dev/null ; echo $?)" >&2 done >/tmp/np1 echo OUT # Terminate background read process - if they still exist if [ "$(kill -0 $bgPid 2>/dev/null ; echo $?)" -eq "0" ] ; then kill $bgPid fi if [ "$(kill -0 $bgPidS 2>/dev/null ; echo $?)" -eq "0" ] ; then kill $bgPidS fi # stty cooked So, saving the script as say starter.sh and calling it, results with the following session: $ ./starter.sh 0 i'm typing here and pressing [enter] at end 0 - 13496 - 13497 I'M TYPING HERE AND PRESSING [ENTER] AT END 0~?.N=?(?~? ?????}????@??????~? [garble] proc: 0 OUT which is what I'd call for "interactive session" (ignoring the debug statements) - server waits for me to enter a command; it gives its output after it receives a command (and as in this case it exits after first command, so does the starter script as well). Except that, I'd like to not have buffered input, but sent character by character (meaning the above session should exit after first key press, and print out a single letter only - which is what I expected stty raw would help with, but it doesn't: it just kills reaction to both Enter and Ctrl-C :) ) I was just wandering if there already is an existing command (akin to screen in respect to serial devices, I guess) that would accept two such named pipes as arguments, and establish a "terminal" or "shell" like session through them; or would I have to use scripts as above and/or program own 'client' that will behave as a terminal..

    Read the article

  • MySQL to PostreSQL and Named Scope

    - by Lowgain
    I've got a named scope for one of my models that works fine. The code is: named_scope :inbox_threads, lambda { |user| { :include => [:deletion_flags, :recipiences], :conditions => ["recipiences.user_id = ? AND deletion_flags.user_id IS NULL", user.id], :group => "msg_threads.id" }} This works fine on my local copy of the app with a MySQL database, but when I push my app to Heroku (which only uses PostgreSQL), I get the following error: ActiveRecord::StatementInvalid (PGError: ERROR: column "msg_threads.subject" must appear in the GROUP BY clause or be used in an aggregate function: SELECT "msg_threads"."id" AS t0_r0, "msg_threads"."subject" AS t0_r1, "msg_threads"."originator_id" AS t0_r2, "msg_thr eads"."created_at" AS t0_r3, "msg_threads"."updated_at" AS t0_r4, "msg_threads"."url_key" AS t0_r5, "deletion_flags"."id" AS t1_r0, "deletion_flags"."user_id" AS t1_r1, "deletion_flags"."msg_thread_id" AS t1_r2, "deletion_flags"."confirmed" AS t1_r3, "deletion_flags"."created_at" AS t1_r4, "deletion_flags"."updated_at" AS t1_r5, "recipiences"."id" AS t2_r0, "recipiences"."user_id" AS t2_r1, "recipiences"."msg_thread_id" AS t2_r2, "recipiences"."created_at" AS t2_r3, "recipien ces"."updated_at" AS t2_r4 FROM "msg_threads" LEFT OUTER JOIN "deletion_flags" ON deletion_flags.msg_thread_id = msg_threads.id LEFT OUTER JOIN "recipiences" ON recipiences.msg_thread_id = msg_threads.id WHERE (recipiences.user_id = 1 AND deletion_flags.user_id IS NULL) GROUP BY msg_threads.id) I'm not as familiar with the working of Postgres, so what would I need to add here to get this working? Thanks!

    Read the article

  • How can I determine which named property (or properties) are filling my exchange 2007 information st

    - by Mikey B
    Hi Guys, I'm experiencing the following error on an Exchange 2007 server: Event ID: 9667 Type: Error Category: General Source: msgidNamedPropsQuotaError Description: Failed to create a new named property for database "" because the number of named properties reached the quota limit (). User attempting to create the named property: . Named property GUID: . Named property name/id: . I understand that this can occur if the exchange information store is filling up with named properties... but I don't know how to determine which specific named property is at fault here. Is there a way to examine the DB for this type of info to see if there's a specific recurring named property that is consuming resources? -M

    Read the article

  • named responding recursive on norecurse queries

    - by Keks
    I have a server on which named is running. It is intercepted with another named server which it is not aware of. Querying the first named server results in timeouts. The server tries to resolve the query recursively. During that the firewall redirects the DNS Request from the first named server to the second one (the query from the first one is addressed to a e.g. a root server and has its "Recursion desired" bit set to 0). Despite that the second named responds to this request with a entirely or at least 1 level more resolved response than the first named server expects. So it ends up with a timeout even though it got a correct name server or even the full IP for the queried domain. In the first case the first name server tries to follow the authority domain ignoring the coresponding glue record and ends up in a loop it aborts: queried: google.com -> got from named#2: ns1.google.com -> ignore glue record and query: ns1.google.com -> got authority from named#2: google.com In the second case it ignores the answer section with the correct IP and instead tries to follow the name servers from the authority section, which ends up in the same dead end as case 1. So how can it be that the second named responds with recursive results even though the bit was explicitly set to 0 in the request from the first named?

    Read the article

  • Templates, interfaces (multiple inheritance) and static functions (named constructors)

    - by fledgling Cxx user
    Setup I have a graph library where I am trying to decompose things as much as possible, and the cleanest way to describe it that I found is the following: there is a vanilla type node implementing only a list of edges: class node { public: int* edges; int edge_count; }; Then, I would like to be able to add interfaces to this whole mix, like so: template <class T> class node_weight { public: T weight; }; template <class T> class node_position { public: T x; T y; }; and so on. Then, the actual graph class comes in, which is templated on the actual type of node: template <class node_T> class graph { protected: node_T* nodes; public: static graph cartesian(int n, int m) { graph r; r.nodes = new node_T[n * m]; return r; } }; The twist is that it has named constructors which construct some special graphs, like a Cartesian lattice. In this case, I would like to be able to add some extra information into the graph, depending on what interfaces are implemented by node_T. What would be the best way to accomplish this? Possible solution I thought of the following humble solution, through dynamic_cast<>: template <class node_T, class weight_T, class position_T> class graph { protected: node_T* nodes; public: static graph cartesian(int n, int m) { graph r; r.nodes = new node_T[n * m]; if (dynamic_cast<node_weight<weight_T>>(r.nodes[0]) != nullptr) { // do stuff knowing you can add weights } if (dynamic_cast<node_position<positionT>>(r.nodes[0]) != nullptr) { // do stuff knowing you can set position } return r; } }; which would operate on node_T being the following: template <class weight_T, class position_T> class node_weight_position : public node, public node_weight<weight_T>, public node_position<position_T> { // ... }; Questions Is this -- philosophically -- the right way to go? I know people don't look nicely at multiple inheritance, though with "interfaces" like these it should all be fine. There are unfortunately problems with this. From what I know at least, dynamic_cast<> involves quite a bit of run-time overhead. Hence, I run into a problem with what I had solved earlier: writing graph algorithms that require weights independently of whether the actual node_T class has weights or not. The solution with this 'interface' approach would be to write a function: template <class node_T, class weight_T> inline weight_T get_weight(node_T const & n) { if (dynamic_cast<node_weight<weight_T>>(n) != nullptr) { return dynamic_cast<node_weight<weight_T>>(n).weight; } return T(1); } but the issue with it is that it works using run-time information (dynamic_cast), yet in principle I would like to decide it at compile-time and thus make the code more efficient. If there is a different solution that would solve both problems, especially a cleaner and better one than what I have, I would love to hear about it!

    Read the article

  • how do I paste text to a line by line text filter like awk, without having stdin echo to the screen?

    - by Barton Chittenden
    I have a text in an email on a windows box that looks something like this: 100 some random text 101 some more random text 102 lots of random text, all different 103 lots of random text, all the same I want to extract the numbers, i.e. the first word on each line. I've got a terminal running bash open on my Linux box... If these were in a text file, I would do this: awk '{print $1}' mytextfile.txt I would like to paste these in, and get my numbers out, without creating a temp file. my naive first attempt looked like this: $ awk '{print $1}' 100 some random text 100 101 some more random text 101 102 lots of random text, all different 103 lots of random text, all the same 102 103 The buffering of stdin and stdout make a hash of this. I wouldn't mind if stdin all printed first, followed by all of stdout; this is what would happen if I were to paste into 'sort' for example, but awk and sed are a different story. a little more thought gave me this: open two terminals. Create a fifo file. Read from the fifo on one terminal, write to it on another. This does in fact work, but I'm lazy. I don't want to open a second terminal. Is there a way in the shell that I can hide the text echoed to the screen when I'm passing it in to a pipe, so that I paste this: 100 some random text 101 some more random text 102 lots of random text, all different 103 lots of random text, all the same but see this? $ awk '{print $1}' 100 101 102 103

    Read the article

  • IO::Pipe - close(<handle>) does not set $?

    - by danboo
    My understanding is that closing the handle for an IO::Pipe object should be done with the method ($fh->close) and not the built-in (close($fh)). The other day I goofed and used the built-in out of habit on a IO::Pipe object that was opened to a command that I expected to fail. I was surprised when $? was zero, and my error checking wasn't triggered. I realized my mistake. If I use the built-in, IO:Pipe can't perform the waitpid() and can't set $?. But what I was surprised by was that perl seemed to still close the pipe without setting $? via the core. I worked up a little test script to show what I mean: use 5.012; use warnings; use IO::Pipe; say 'init pipes:'; pipes(); my $fh = IO::Pipe->reader(q(false)); say 'post open pipes:'; pipes(); say 'return: ' . $fh->close; #say 'return: ' . close($fh); say 'status: ' . $?; say q(); say 'post close pipes:'; pipes(); sub pipes { for my $fd ( glob("/proc/self/fd/*") ) { say readlink($fd) if -p $fd; } say q(); } When using the method it shows the pipe being gone after the close and $? is set as I expected: init pipes: post open pipes: pipe:[992006] return: 1 status: 256 post close pipes: And, when using the built-in it also appears to close the pipe, but does not set $?: init pipes: post open pipes: pipe:[952618] return: 1 status: 0 post close pipes: It seems odd to me that the built-in results in the pipe closure, but doesn't set $?. Can anyone help explain the discrepancy? Thanks!

    Read the article

  • FreeBSD Traffic Shaping

    - by alexus
    Hi I'm trying to do traffic shaping with FreeBSD, here are my rules su-3.2# ipfw show | grep pipe 08380 1514852 125523804 pipe 1 tcp from any to any dst-port 80 su-3.2# ipfw pipe 1 show 00001: 2.000 Mbit/s 0 ms 50 sl. 1 queues (1 buckets) droptail mask: 0x00 0x00000000/0x0000 - 0x00000000/0x0000 BKT Prot ___Source IP/port____ ____Dest. IP/port____ Tot_pkt/bytes Pkt/Byte Drp 0 tcp 64.237.55.83/60598 72.21.81.133/80 6520267 1204533020 0 0 1216 su-3.2# first of all why when I run ipfw pipe 1 show i get same source and destination ip, that doesnt seem like ever change yet total packets/bytes increasing and most important question, after donig all that I'm looking at my MRTG stats and I see i'm very well over 2Mbit/s limit. what am I doing wrong? here is config file flush pipe flush pipe 1 config bw 2Mbit/s add 100 allow ip from any to any via lo0 add 200 deny ip from any to 127.0.0.0/8 add 300 deny ip from 127.0.0.0/8 to any add 8380 pipe 1 tcp from any to any src-port www uid daemon add 8380 pipe 1 tcp from any to any dst-port www uid daemon add 65000 pass all from any to any

    Read the article

  • How do I pipe a list of numbers straight from the shell into a command?

    - by learnvst
    How do I pipe a list of numbers straight from the shell into a command? For exampe something like this [1,2,3,4] | sort would give 1 2 3 4 EDIT: In response to the answers kindly posted so far . . . I ask this, because I want to quickly test and debug a console application that takes many numbers as it input without having to type lots of individual values followed by carriage returns. I'd like to just type in the 'one liner' and hit the up arrow now and then to replay the command. Ideally, I'd like to do this without using a text file containing the values (which would obviously be the most simple way to do this.)

    Read the article

  • ruby on rails named scope implementation

    - by Engwan
    From the book Agile Web Development With Rails class Order < ActiveRecord::Base named_scope :last_n_days, lambda { |days| {:conditions => ['updated < ?' , days] } } named_scope :checks, :conditions => {:pay_type => :check} end The statement orders = Orders.checks.last_n_days(7) will result to only one query to the database. How does rails implement this? I'm new to Ruby and I'm wondering if there's a special construct that allows this to happen. To be able to chain methods like that, the functions generated by named_scope must be returning themselves or an object than can be scoped further. But how does Ruby know that it is the last function call and that it should query the database now? I ask this because the statement above actually queries the database and not just returns an SQL statement that results from chaining.

    Read the article

  • Registering a Named Function as a Listener with Jquery

    - by Marcus
    I'm new to javascript/jquery and I've done some poking around the web, but I can't figure out why the following is invalid: var toggleSection = function(sectionName) { // Do some Jquery work to toggle stuff based on sectionName string // (concatenate sectionName with other text to form selectors) }; $('#togglecont1').click(toggleSection("container1")); Is there something obvious I'm missing? Thanks in advance.

    Read the article

  • ASP Classic Named Parameter in Paramaterized Query: Must declare the scalar variable

    - by My Alter Ego
    I'm trying to write a parameterized query in ASP Classic, and it's starting to feel like i'm beating my head against a wall. I'm getting the following error: Must declare the scalar variable "@something". I would swear that is what the hello line does, but maybe i'm missing something... <% OPTION EXPLICIT %> <!-- #include file="../common/adovbs.inc" --> <% Response.Buffer=false dim conn,connectionString,cmd,sql,rs,parm connectionString = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Data Source=.\sqlexpress;Initial Catalog=stuff" set conn = server.CreateObject("adodb.connection") conn.Open(connectionString) set cmd = server.CreateObject("adodb.command") set cmd.ActiveConnection = conn cmd.CommandType = adCmdText cmd.CommandText = "select @something" cmd.NamedParameters = true cmd.Prepared = true set parm = cmd.CreateParameter("@something",advarchar,adParamInput,255,"Hello") call cmd.Parameters.append(parm) set rs = cmd.Execute if not rs.eof then Response.Write rs(0) end if %>

    Read the article

  • Rails Named Scope and overlapping conditions

    - by Tumtu
    Hi everyone, have a question about rails SQL generation: class Organization < ActiveRecord::Base has_many :people named_scope :active, :conditions => { :active => 'Yes' } end class Person < ActiveRecord::Base belongs_to :organization end Rails SQL for all active people in the first organiztion Organization.first.people.active.all [4;36;1mOrganization Load (0.0ms)[0m [0;1mSELECT TOP 1 * FROM [organizations] [0m [4;35;1mPerson Load (0.0ms)[0m [0mSELECT * FROM [people] WHERE ((([people].[active] = 'Yes') AND ([people].organization_id = 1)) AND ([people].organization_id = 1)) [0m Why Rails generates "[people].organization_id = 1" condition twice ? Does someone know how to make it DRY ? e.g. SELECT * FROM [people] WHERE (([people].[active] = 'Yes') AND ([people].organization_id = 1))

    Read the article

  • Disambiguating Named Entities in Java

    - by Alterscape
    I have a list of strings (company names, in this case), and a Java program that extracts a list of things that look like company names out of mostly-unstructured text. I need to match each element of extracted text to a string in the list. Caveat: the unstructured text has typos, things like "Blah, Inc." referred to as "Blah," etc. I've tried Levenshtein Edit Distance, but that fails for predictable reasons. Are there known best-practices ways of tackling this problem? Or am I back to manual data-entry?

    Read the article

  • Named keywords in decorators?

    - by wheaties
    I've been playing around in depth with attempting to write my own version of a memoizing decorator before I go looking at other people's code. It's more of an exercise in fun, honestly. However, in the course of playing around I've found I can't do something I want with decorators. def addValue( func, val ): def add( x ): return func( x ) + val return add @addValue( val=4 ) def computeSomething( x ): #function gets defined If I want to do that I have to do this: def addTwo( func ): return addValue( func, 2 ) @addTwo def computeSomething( x ): #function gets defined Why can't I use keyword arguments with decorators in this manner? What am I doing wrong and can you show me how I should be doing it?

    Read the article

  • Properly using subprocess.PIPE in python?

    - by Gordon Fontenot
    I'm trying to use subprocess.Popen to construct a sequence to grab the duration of a video file. I've been searching for 3 days, and can't find any reason online as to why this code isn't working, but it keeps giving me a blank result: import sys import os import subprocess def main(): the_file = "/Volumes/Footage/Acura/MDX/2001/Crash Test/01 Acura MDX Front Crash.mov" ffmpeg = subprocess.Popen(['/opt/local/bin/ffmpeg', '-i', the_file], stdout = subprocess.PIPE, ) grep = subprocess.Popen(['grep', 'Duration'], stdin = subprocess.PIPE, stdout = subprocess.PIPE, ) cut = subprocess.Popen(['cut', '-d', ' ', '-f', '4'], stdin = subprocess.PIPE, stdout = subprocess.PIPE, ) sed = subprocess.Popen(['sed', 's/,//'], stdin = subprocess.PIPE, stdout = subprocess.PIPE, ) duration = sed.communicate() print duration if __name__ == '__main__': main()

    Read the article

  • Bash script 'while read' loop causes 'broken pipe' error when run with GNU Parallel

    - by Joe White
    According to the GNU Parallel mailing list this is not a GNU Parallel-specific problem. They suggested that I post my problem here. The error I'm getting is a "broken pipe" error, but I feel I should first explain the context of my problem and what causes this error. It happens when trying to use any bash script containing a 'while read' loop in GNU Parallel. I have a basic bash script like this: #!/bin/bash # linkcheck.sh while read domain do host "$domain" done Assume that I want to pipe in a large list (250mb say). cat urllist | ./linkcheck.sh Running host command on 250mb worth of URLs is rather slow. To speed things up I want to break up the input into chunks before piping it and then run multiple jobs in parallel. GNU Parallel is capable of doing this. cat urllist | parallel --pipe -j0 parallel ./linkcheck.sh {} {} is substituted by the contents of urllist line-by-line. Assume that my systems default setup is capable of running 500ish jobs per instance of parallel. To get round this limitation we can parallelize Parallel itself: cat urllist | parallel -j10 --pipe parallel -j0 ./linkcheck.sh {} This will run 5000'ish jobs. It will also, sadly, cause the error "broken pipe" (bash FAQ). Yet the script starts to work if I remove the while read loop and take input directly from whatever is fed into {} e.g., #!/bin/bash # linkchecker.sh domain="$1" host "$1" Why will it not work with a while read loop? Is it safe to just turn off the SIGPIPE signal to stop the "broken pipe" message, or will that have side effects such as data corruption? Thanks for reading.

    Read the article

  • How can I both pipe and display output in Windows' command line?

    - by Bob
    I have a process I need to run within a batch file. This process produces some output. I need to both display this output to the screen and send (pipe) it to another program. The bash method uses tee: echo 'ee' | tee /dev/tty | foo Is there an equivalent for Windows? I am happy to use PowerShell if necessary. There are tee ports for Windows, but there does not appear to be an equivalent for /dev/tty, which complicates matters. The specific use-case here: I have a program (launch4j) that I need to run, displaying output to the user. At the same time, I need to be able to detect success or failure in the script. Unfortunately, this program does not set an exit code, and I cannot force it to do so. My current workaround involves piping to find, to search the output (launch4j config.xml | find "Successfully created") - however, that swallows the output I need to display. Therefore, I need some way to both display to the screen and send the ouput to a command - and this command should be able to set ERRORLEVEL (it cannot run asynchronously).

    Read the article

  • MySQL on Windows - how do I set the wait_timeout for connections using named pipes?

    - by gustafc
    I use a MySQL database running on a Windows box, and for performance reasons I'm connecting to it using named pipes. The (Java) application using the database (through Hibernate) can let the connection lie idle for quite a long time, which causes the connection to fail with the following message: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: The last packet successfully received from the server was 33 558 297 milliseconds ago. The last packet sent successfully to the server was 33 558 297 milliseconds ago. is longer than the server configured value of 'wait_timeout'. You should consider either expiring and/or testing connection validity before use in your application, increasing the server configured values for client timeouts, or using the Connector/J connection property 'autoReconnect=true' to avoid this problem. autoReconnect unfortunately has no effect (and neither does autoReconnectForPools), but the wait_timeout docs state that wait_timeout only applies "to TCP/IP and Unix socket file connections, not to connections made via named pipes, or shared memory". How can I change the wait_timeout for named pipes?

    Read the article

  • C check before writing to closed pipe

    - by Gary
    Is there an easy way to check if a pipe is closed before writing to it in C? I have a child and parent process, and the parent has a pipe to write to the child. However, if the child closes the pipe and the parent tries to read - I get a broken pipe error. So how can I check to make sure I can write to the pipe, so I can handle it as an error if I can't? Thanks!

    Read the article

  • How do you send a named pipe string from umnanaged to managed code space?

    - by billmcf
    I appear to have a named pipes 101 issue. I have a very simple set up to connect a simplex named pipe transmitting from a C++ unmanaged app to a C# managed app. The pipe connects, but I cannot send a "message" through the pipe unless I close the handle which appears to flush the buffer and pass the message through. It's like the message is blocked. I have tried reversing the roles of client/server and invoking them with different Flag combinations without any luck. I can easily send messages in the other direction from C# managed to C++ unmanaged. Does anyone have any insight. Can any of you guys successfully send messages from C++ unmanaged to C# managed? I can find plenty of examples of intra amanged or unmanaged pipes but not inter managed to/from unamanged - just claims to be able to do it. In the listings, I have omitted much of the wrapper stuff for clarity. The key bits I believe that are relevant are the pipe connection/creation/read and write methods. Don't worry too much about blocking/threading here. C# Server side // This runs in its own thread and so it is OK to block private void ConnectToClient() { // This server will listen to the sending client if (m_InPipeStream == null) { m_InPipeStream = new NamedPipeServerStream("TestPipe", PipeDirection.In, 1); } // Wait for client to connect to our server m_InPipeStream.WaitForConnection(); // Verify client is running if (!m_InPipeStream.IsConnected) { return; } // Start listening for messages on the client stream if (m_InPipeStream != null && m_InPipeStream.CanRead) { ReadThread = new Thread(new ParameterizedThreadStart(Read)); ReadThread.Start(m_InPipeStream); } } // This runs in its own thread and so it is OK to block private void Read(object serverObj) { NamedPipeServerStream pipeStream = (NamedPipeServerStream)serverObj; using (StreamReader sr = new StreamReader(pipeStream)) { while (true) { string buffer = "" ; try { // Blocks here until the handle is closed by the client-side!! buffer = sr.ReadLine(); // <<<<<<<<<<<<<< Sticks here } catch { // Read error break; } // Client has disconnected? if (buffer == null || buffer.Length == 0) break; // Fire message received event if message is non-empty if (MessageReceived != null && buffer != "") { MessageReceived(buffer); } } } } C++ client side // Static - running in its own thread. DWORD CNamedPipe::ListenForServer(LPVOID arg) { // The calling app (this) is passed as the parameter CNamedPipe* app = (CNamedPipe*)arg; // Out-Pipe: connect as a client to a waiting server app->m_hOutPipeHandle = CreateFile("\\\\.\\pipe\\TestPipe", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); // Could not create handle if (app->m_hInPipeHandle == NULL || app->m_hInPipeHandle == INVALID_HANDLE_VALUE) { return 1; } return 0; } // Sends a message to the server BOOL CNamedPipe::SendMessage(CString message) { DWORD dwSent; if (m_hOutPipeHandle == NULL || m_hOutPipeHandle == INVALID_HANDLE_VALUE) { return FALSE; } else { BOOL bOK = WriteFile(m_hOutPipeHandle, message, message.GetLength()+1, &dwSent, NULL); //FlushFileBuffers(m_hOutPipeHandle); // <<<<<<< Tried this return (!bOK || (message.GetLength()+1) != dwSent) ? FALSE : TRUE; } } // Somewhere in the Windows C++/MFC code... ... // This write is non-blocking. It just passes through having loaded the pipe. m_pNamedPipe->SendMessage("Hi de hi"); ...

    Read the article

  • C# 4.0: Named And Optional Arguments

    - by Paulo Morgado
    As part of the co-evolution effort of C# and Visual Basic, C# 4.0 introduces Named and Optional Arguments. First of all, let’s clarify what are arguments and parameters: Method definition parameters are the input variables of the method. Method call arguments are the values provided to the method parameters. In fact, the C# Language Specification states the following on §7.5: The argument list (§7.5.1) of a function member invocation provides actual values or variable references for the parameters of the function member. Given the above definitions, we can state that: Parameters have always been named and still are. Parameters have never been optional and still aren’t. Named Arguments Until now, the way the C# compiler matched method call definition arguments with method parameters was by position. The first argument provides the value for the first parameter, the second argument provides the value for the second parameter, and so on and so on, regardless of the name of the parameters. If a parameter was missing a corresponding argument to provide its value, the compiler would emit a compilation error. For this call: Greeting("Mr.", "Morgado", 42); this method: public void Greeting(string title, string name, int age) will receive as parameters: title: “Mr.” name: “Morgado” age: 42 What this new feature allows is to use the names of the parameters to identify the corresponding arguments in the form: name:value Not all arguments in the argument list must be named. However, all named arguments must be at the end of the argument list. The matching between arguments (and the evaluation of its value) and parameters will be done first by name for the named arguments and than by position for the unnamed arguments. This means that, for this method definition: public static void Method(int first, int second, int third) this call declaration: int i = 0; Method(i, third: i++, second: ++i); will have this code generated by the compiler: int i = 0; int CS$0$0000 = i++; int CS$0$0001 = ++i; Method(i, CS$0$0001, CS$0$0000); which will give the method the following parameter values: first: 2 second: 2 third: 0 Notice the variable names. Although invalid being invalid C# identifiers, they are valid .NET identifiers and thus avoiding collision between user written and compiler generated code. Besides allowing to re-order of the argument list, this feature is very useful for auto-documenting the code, for example, when the argument list is very long or not clear, from the call site, what the arguments are. Optional Arguments Parameters can now have default values: public static void Method(int first, int second = 2, int third = 3) Parameters with default values must be the last in the parameter list and its value is used as the value of the parameter if the corresponding argument is missing from the method call declaration. For this call declaration: int i = 0; Method(i, third: ++i); will have this code generated by the compiler: int i = 0; int CS$0$0000 = ++i; Method(i, 2, CS$0$0000); which will give the method the following parameter values: first: 1 second: 2 third: 1 Because, when method parameters have default values, arguments can be omitted from the call declaration, this might seem like method overloading or a good replacement for it, but it isn’t. Although methods like this: public static StreamReader OpenTextFile( string path, Encoding encoding = null, bool detectEncoding = true, int bufferSize = 1024) allow to have its calls written like this: OpenTextFile("foo.txt", Encoding.UTF8); OpenTextFile("foo.txt", Encoding.UTF8, bufferSize: 4096); OpenTextFile( bufferSize: 4096, path: "foo.txt", detectEncoding: false); The complier handles default values like constant fields taking the value and useing it instead of a reference to the value. So, like with constant fields, methods with parameters with default values are exposed publicly (and remember that internal members might be publicly accessible – InternalsVisibleToAttribute). If such methods are publicly accessible and used by another assembly, those values will be hard coded in the calling code and, if the called assembly has its default values changed, they won’t be assumed by already compiled code. At the first glance, I though that using optional arguments for “bad” written code was great, but the ability to write code like that was just pure evil. But than I realized that, since I use private constant fields, it’s OK to use default parameter values on privately accessed methods.

    Read the article

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