Search Results

Search found 501 results on 21 pages for 'sequential'.

Page 17/21 | < Previous Page | 13 14 15 16 17 18 19 20 21  | Next Page >

  • networking tunnel adapter connections?

    - by Karthik Balaguru
    I understand that Tunnel Adapter LAN is for encapsulating IPv6 packets with an IPv4 header so that they can be sent across an IPv4 network. Few queries popped up in my mind based on this :- If i do 'ipconfig', Apart from ethernet adapter LAN details, I get a series of statments as below - Tunnel adapter Local Area Connection* 6 Tunnel adapter Local Area Connection* 7 Tunnel adapter Local Area Connection* 12 Tunnel adapter Local Area Connection* 13 Tunnel adapter Local Area Connection* 14 Tunnel adapter Local Area Connection* 15 Tunnel adapter Local Area Connection* 16 Except for the *16, all the other Tunnel Adapter Local Area Connections show Media Disconnected. Why is the numbering for the Tunnel adapter LAN not sequential? It is like 6, 7, 12, 13, 14, 15, 16. A strange numbering scheme! I tried to figure it out by thinking of some arithmetic series. But, it does not seem to fit in. There is a huge gap between 7 and 12. Any ideas? What is the need for so many Tunnel Adapter LAN connections? Can you tell me a scenario that requires all of those ? I did ipconfig /all to get more information. From the listing, I understand that: 16, 15, 14, 12 are Microsoft 6to4 Adapters 13, 6 are isatap Adapters 7 is Teredo Tunneling Pseudo-interface I understand that the above are for automatic tunneling so that the tunnel endpoints are determined automatically by the routing infrastructure. 6to4 is recommended by RFC3056 for automatic tunneling that uses protocol 41 for encapsulation. It is typically used when an end-user wants to connect to the IPv6 Internet using their existing IPv4 connection. Teredo is an automatic tunneling technique that uses UDP encapsulation across multiple NATs. That is, It is to grant IPv6 connectivity to nodes that are located behind IPv6-unaware NAT devices ISATAP treats the IPv4 network as a virtual IPv6 local link, with mappings from each IPv4 address to a link-local IPv6 address. That is to transmit IPv6 packets between dual-stack nodes on top of an IPv4 network. That is, to put in simple words, ISATAP is an intra-site mechanism, while the 6to4 and Teredo are for inter-site tunnelling mechanisms. It seems that Teredo should alone enabled by default in Vista, But my system does not show it to be enabled by default. Interestingly, it shows a 6to4 tunnel adapter (Tunnel adapter LAN connection 16) to be enabled by default? Any specific reasons for it? If i do ipconfig /all, why is only one Teredo present while four 6to4 are present ? I searched the internet for answers to the above queries, but I am unable to find clear answers.

    Read the article

  • JSF index out of bounds exception when submiting a form

    - by selvin
    When I click submit button in a JSF form the following exception occurs. It says an Indexout of bounds exception, but I did not use any ArrayList associated with the code. Is this a bug? what should i do to get rid of this error.. Mojarra: 2.0.2 FCS with primefaces 2.2 JSF: 2.0 NetBeans IDE 6.8 Glassfish Domain V3 Form Code: <p:panel id="jobres" style="min-width: 200px" header="Reservation" widgetVar="jres" closable="true" toggleable="true" > <h:form id="arj" prependId="false" style="width:550px;max-height:400px;overflow:auto;"> <p:tooltip global="true"/> <h:panelGrid columns="2" > <p:panel style="min-width: 220px"> <h:outputLabel value="1.Job type:"/> </p:panel> <h:panelGroup> <h:messages id="aerr"/> <h:selectOneMenu title="Choose a Jobtype" value="#{arjob.jobtype}"> <f:selectItem itemLabel="Sequential" itemValue="sequential"/> <f:selectItem itemLabel="Parallel" itemValue="parallel"/> </h:selectOneMenu> </h:panelGroup> <p:panel> <h:outputLabel value="2.Executable: *"/> </p:panel> <h:panelGroup> <p:fileUpload id="aexeupload" fileUploadListener="#{arjob.chooseListener}" auto="true" update="adlist :erdialog" description="Resource Files"> </p:fileUpload> <br/> <h:panelGroup id="aexelistwrapper"> <p:dataList var="fileList" type="ordered" id="adlist" value="#{arjob.fexelist}"> <p:column> #{fileList}&nbsp; <p:commandLink ajax="true" update="aexelistwrapper" actionListener="#{arjob.removeExe(fileList)}"> <p:graphicImage value="images/closebar.png"/> </p:commandLink> </p:column> </p:dataList> </h:panelGroup> </h:panelGroup> <p:panel> <h:outputLabel value="3.Argument(s):"/> </p:panel> <h:panelGroup> <u style="color:orange"> <i> <p:inplace emptyLabel="Add Arguments" onEditUpdate="aarglist"> <h:inputText title="Enter the arguments" id="aiparg" value="#{arjob.args}"> <f:ajax event="valueChange"/> </h:inputText> <p:commandButton update="aarglistwrapper erdialog" value="add" actionListener="#{arjob.addArg}"/> </p:inplace> </i> </u> </h:panelGroup> <h:panelGroup> </h:panelGroup> <h:panelGroup> <h:panelGrid id="aarglistwrapper"> <p:dataList id="aarglist" type="ordered" var="args" value="#{arjob.arglist}"> <p:column id="col2"> #{args}&nbsp; <p:commandLink ajax="true" update="arj:arglistwrapper" actionListener="#{arjob.removeArgs(args)}"> <p:graphicImage title="remove" value="images/closebar.png"/> </p:commandLink> </p:column> </p:dataList> </h:panelGrid> </h:panelGroup> <p:panel> <h:outputLabel value="4.InputFile(s): *"/> </p:panel> <h:panelGroup> <p:fileUpload id="ainpupload" fileUploadListener="#{arjob.inputChooseListener}" auto="true" update="aipfilelistwrapper :erdialog" description="Resource Files"> </p:fileUpload> <br/> <h:panelGroup id="aipfilelistwrapper"> <p:dataList var="ipfile" type="ordered" id="aipflist" value="#{arjob.finlist}"> <p:column> #{ipfile}&nbsp; <p:commandLink ajax="true" update="aipfilelistwrapper" actionListener="#{arjob.removeInfile(ipfile)}"> <p:graphicImage value="images/closebar.png"/> </p:commandLink> </p:column> </p:dataList> </h:panelGroup> </h:panelGroup> <h:panelGroup> <p:panel > 5)Output File(s): </p:panel> </h:panelGroup> <h:panelGroup> <u style="color:orange"> <i> <p:inplace emptyLabel="Add file name" id="aipexe"> <h:inputText title="Enter the output filenames" id="aexe" value="#{arjob.ofilename}"> <f:ajax event="valueChange"/> </h:inputText> <p:commandButton update="adoutlist :erdialog" value="add" actionListener="#{arjob.addOutfile}"/> </p:inplace> </i> </u> </h:panelGroup> <h:panelGroup> </h:panelGroup> <h:panelGroup> <h:panelGrid id="afilelistwrapper"> <p:dataList id="adoutlist" type="ordered" var="ofile" value="#{arjob.foutlist}"> <p:column id="acol"> #{ofile}&nbsp; <p:commandLink ajax="true" update="afilelistwrapper" actionListener="#{arjob.removeOutfile(ofile)}"> <p:graphicImage value="images/closebar.png"/> </p:commandLink> </p:column> </p:dataList> </h:panelGrid> </h:panelGroup> <p:panel> <h:outputLabel value="6) Operating System"/> </p:panel> <h:panelGroup> <h:selectOneMenu title="Select an OperatingSystem" value="#{arjob.os}"> <f:selectItem itemLabel="CentOS Release 5.2" itemValue="Cent OS 5.2"/> <f:selectItem itemLabel="RHEL Server Release 5" itemValue="RHEL server 5"/> <f:selectItem itemLabel="RHEL Server Release 5.2" itemValue="RHEL server 5.2"/> </h:selectOneMenu> </h:panelGroup> <h:panelGroup> <p:panel> <h:outputLabel value="7) Physical Memory:"/> </p:panel> </h:panelGroup> <h:panelGroup> <p:spinner min="0" style="width: 100px" stepFactor="10" value="#{arjob.mem}"> </p:spinner>(MB) </h:panelGroup> <h:panelGroup> <p:panel> <h:outputLabel value="8) Disk Space:"/> </p:panel> </h:panelGroup> <h:panelGroup> <p:spinner min="0" style="width: 100px" stepFactor="10" value="#{arjob.diskspace}"> </p:spinner>(MB) </h:panelGroup> <h:panelGroup> <p:panel> <h:outputLabel value="9) CPU Mhz:"/> </p:panel> </h:panelGroup> <h:panelGroup> <p:spinner min="0" style="width: 100px" stepFactor="10" value="#{arjob.cpumhz}"> </p:spinner>(Mhz) </h:panelGroup> <p:panel> <h:outputLabel value="10) Start Time:"/> </p:panel> <h:panelGroup> <p:inputMask title="(YYYY-MM-DD HH:MM:SS)" mask="9999-99-99 99:99:99" value="#{arjob.startt}"> </p:inputMask> </h:panelGroup> <p:panel> <h:outputLabel value="11) End Time:"/> </p:panel> <h:panelGroup> <p:inputMask title="(YYYY-MM-DD HH:MM:SS)" mask="9999-99-99 99:99:99" value="#{arjob.endt}"> <p:ajax event="valueChange"/> </p:inputMask> </h:panelGroup> <p:panel> <h:outputLabel value="12) LRMS type"/> </p:panel> <h:panelGroup> <h:selectOneMenu value="#{arjob.lrms}"> <f:selectItem itemLabel="PBS" itemValue="PBS"/> <f:selectItem itemLabel="SGE" itemValue="SGE"/> </h:selectOneMenu> </h:panelGroup> <h:panelGroup> <p:panel> <h:outputLabel value="13)Number of Nodes: *"/> </p:panel> </h:panelGroup> <h:panelGroup> <h:panelGroup> <p:spinner style="width: 100px" min="1" max="100" value="#{arjob.numnodes}"> </p:spinner> </h:panelGroup> </h:panelGroup> <h:panelGroup> </h:panelGroup> <h:panelGroup> <p:commandButton ajax="false" value="Submit" action="#{arjob.jobSubmitAction}"/> </h:panelGroup> </h:panelGrid> </h:form> <p:draggable for="jobres" handle=".ui-panel-titlebar"/> </p:panel> Exception: SEVERE: javax.faces.FacesException: Unexpected error restoring state for component with id j_idt7. Cause: java.lang.IndexOutOfBoundsException: Index: 0, Size: 0. at com.sun.faces.application.view.StateManagementStrategyImpl$2.visit(StateManagementStrategyImpl.java:239) at com.sun.faces.component.visit.FullVisitContext.invokeVisitCallback(FullVisitContext.java:147) at javax.faces.component.UIComponent.visitTree(UIComponent.java:1446) at javax.faces.component.UIComponent.visitTree(UIComponent.java:1457) at javax.faces.component.UIComponent.visitTree(UIComponent.java:1457) at javax.faces.component.UIComponent.visitTree(UIComponent.java:1457) at com.sun.faces.application.view.StateManagementStrategyImpl.restoreView(StateManagementStrategyImpl.java:223) at com.sun.faces.application.StateManagerImpl.restoreView(StateManagerImpl.java:177) at com.sun.faces.application.view.ViewHandlingStrategy.restoreView(ViewHandlingStrategy.java:131) at com.sun.faces.application.view.FaceletViewHandlingStrategy.restoreView(FaceletViewHandlingStrategy.java:430) at com.sun.faces.application.view.MultiViewHandler.restoreView(MultiViewHandler.java:143) at javax.faces.application.ViewHandlerWrapper.restoreView(ViewHandlerWrapper.java:288) at com.sun.faces.lifecycle.RestoreViewPhase.execute(RestoreViewPhase.java:199) at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101) at com.sun.faces.lifecycle.RestoreViewPhase.doPhase(RestoreViewPhase.java:110) at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118) at javax.faces.webapp.FacesServlet.service(FacesServlet.java:312) at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1523) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:343) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:215) at org.primefaces.webapp.filter.FileUploadFilter.doFilter(FileUploadFilter.java:79) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:215) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:277) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:188) at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:641) at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:97) at com.sun.enterprise.web.PESessionLockingStandardPipeline.invoke(PESessionLockingStandardPipeline.java:85) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:185) at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:332) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:233) at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:165) at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:791) at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:693) at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:954) at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:170) at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:135) at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:102) at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:88) at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:76) at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:53) at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:57) at com.sun.grizzly.ContextTask.run(ContextTask.java:69) at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:330) at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:309) at java.lang.Thread.run(Thread.java:619) Caused by: java.lang.IndexOutOfBoundsException: Index: 0, Size: 0 at java.util.ArrayList.RangeCheck(ArrayList.java:547) at java.util.ArrayList.get(ArrayList.java:322) at javax.faces.component.AttachedObjectListHolder.restoreState(AttachedObjectListHolder.java:161) at javax.faces.component.UIComponentBase.restoreState(UIComponentBase.java:1427) at com.sun.faces.application.view.StateManagementStrategyImpl$2.visit(StateManagementStrategyImpl.java:231) ... 45 more

    Read the article

  • Windows Azure Use Case: Hybrid Applications

    - by BuckWoody
    This is one in a series of posts on when and where to use a distributed architecture design in your organization's computing needs. You can find the main post here: http://blogs.msdn.com/b/buckwoody/archive/2011/01/18/windows-azure-and-sql-azure-use-cases.aspx  Description: Organizations see the need for computing infrastructures that they can “rent” or pay for only when they need them. They also understand the benefits of distributed computing, but do not want to create this infrastructure themselves. However, they may have considerations that prevent them from moving all of their current IT investment to a distributed environment: Private data (do not want to send or store sensitive data off-site) High dollar investment in current infrastructure Applications currently running well, but may need additional periodic capacity Current applications not designed in a stateless fashion In these situations, a “hybrid” approach works best. In fact, with Windows Azure, a hybrid approach is an optimal way to implement distributed computing even when the stipulations above do not apply. Keeping a majority of the computing function in an organization local while exploring and expanding that footprint into Windows and SQL Azure is a good migration or expansion strategy. A “hybrid” architecture merely means that part of a computing cycle is shared between two architectures. For instance, some level of computing might be done in a Windows Azure web-based application, while the data is stored locally at the organization. Implementation: There are multiple methods for implementing a hybrid architecture, in a spectrum from very little interaction from the local infrastructure to Windows or SQL Azure. The patterns fall into two broad schemas, and even these can be mixed. 1. Client-Centric Hybrid Patterns In this pattern, programs are coded such that the client system sends queries or compute requests to multiple systems. The “client” in this case might be a web-based codeset actually stored on another system (which acts as a client, the user’s device serving as the presentation layer) or a compiled program. In either case, the code on the client requestor carries the burden of defining the layout of the requests. While this pattern is often the easiest to code, it’s the most brittle. Any change in the architecture must be reflected on each client, but this can be mitigated by using a centralized system as the client such as in the web scenario. 2. System-Centric Hybrid Patterns Another approach is to create a distributed architecture by turning on-site systems into “services” that can be called from Windows Azure using the service Bus or the Access Control Services (ACS) capabilities. Code calls from a series of in-process client application. In this pattern you move the “client” interface into the server application logic. If you do not wish to change the application itself, you can “layer” the results of the code return using a product (such as Microsoft BizTalk) that exposes a Web Services Definition Language (WSDL) endpoint to Windows Azure using the Application Fabric. In effect, this is similar to creating a Service Oriented Architecture (SOA) environment, and has the advantage of de-coupling your computing architecture. If each system offers a “service” of the results of some software processing, the operating system or platform becomes immaterial, assuming it adheres to a service contract. There are important considerations when you federate a system, whether to Windows or SQL Azure or any other distributed architecture. While these considerations are consistent with coding any application for distributed computing, they are especially important for a hybrid application. Connection resiliency - Applications on-premise normally have low-latency and good connection properties, something you’re not always guaranteed in a distributed and hybrid application. Whether a centralized client or a distributed one, the code should be able to handle extended retry logic. Authorization and Access - In a single authorization environment like a Active Directory domain, security is handled at a user-password level. In a distributed computing environment, you have more options. You can mitigate this with  using The Windows Azure Application Fabric feature of ACS to make the Azure application aware of the App Fabric as an ADFS provider. However, a claims-based authentication structure is often a superior choice.  Consistency and Concurrency - When you have a Relational Database Management System (RDBMS), Consistency and Concurrency are part of the design. In a Service Architecture, you need to plan for sequential message handling and lifecycle. Resources: How to Build a Hybrid On-Premise/In Cloud Application: http://blogs.msdn.com/b/ignitionshowcase/archive/2010/11/09/how-to-build-a-hybrid-on-premise-in-cloud-application.aspx  General Architecture guidance: http://blogs.msdn.com/b/buckwoody/archive/2010/12/21/windows-azure-learning-plan-architecture.aspx   

    Read the article

  • await, WhenAll, WaitAll, oh my!!

    - by cibrax
    If you are dealing with asynchronous work in .NET, you might know that the Task class has become the main driver for wrapping asynchronous calls. Although this class was officially introduced in .NET 4.0, the programming model for consuming tasks was much more simplified in C# 5.0 in .NET 4.5 with the addition of the new async/await keywords. In a nutshell, you can use these keywords to make asynchronous calls as if they were sequential, and avoiding in that way any fork or callback in the code. The compiler takes care of the rest. I was yesterday writing some code for making multiple asynchronous calls to backend services in parallel. The code looked as follow, var allResults = new List<Result>(); foreach(var provider in providers) { var results = await provider.GetResults(); allResults.AddRange(results); } return allResults; You see, I was using the await keyword to make multiple calls in parallel. Something I did not consider was the overhead this code implied after being compiled. I started an interesting discussion with some smart folks in twitter. One of them, Tugberk Ugurlu, had the brilliant idea of actually write some code to make a performance comparison with another approach using Task.WhenAll. There are two additional methods you can use to wait for the results of multiple calls in parallel, WhenAll and WaitAll. WhenAll creates a new task and waits for results in that new task, so it does not block the calling thread. WaitAll, on the other hand, blocks the calling thread. This is the code Tugberk initially wrote, and I modified afterwards to also show the results of WaitAll. class Program { private static Func<Stopwatch, Task>[] funcs = new Func<Stopwatch, Task>[] { async (watch) => { watch.Start(); await Task.Delay(1000); Console.WriteLine("1000 one has been completed."); }, async (watch) => { await Task.Delay(1500); Console.WriteLine("1500 one has been completed."); }, async (watch) => { await Task.Delay(2000); Console.WriteLine("2000 one has been completed."); watch.Stop(); Console.WriteLine(watch.ElapsedMilliseconds + "ms has been elapsed."); } }; static void Main(string[] args) { Console.WriteLine("Await in loop work starts..."); DoWorkAsync().ContinueWith(task => { Console.WriteLine("Parallel work starts..."); DoWorkInParallelAsync().ContinueWith(t => { Console.WriteLine("WaitAll work starts..."); WaitForAll(); }); }); Console.ReadLine(); } static async Task DoWorkAsync() { Stopwatch watch = new Stopwatch(); foreach (var func in funcs) { await func(watch); } } static async Task DoWorkInParallelAsync() { Stopwatch watch = new Stopwatch(); await Task.WhenAll(funcs[0](watch), funcs[1](watch), funcs[2](watch)); } static void WaitForAll() { Stopwatch watch = new Stopwatch(); Task.WaitAll(funcs[0](watch), funcs[1](watch), funcs[2](watch)); } } After running this code, the results were very concluding. Await in loop work starts... 1000 one has been completed. 1500 one has been completed. 2000 one has been completed. 4532ms has been elapsed. Parallel work starts... 1000 one has been completed. 1500 one has been completed. 2000 one has been completed. 2007ms has been elapsed. WaitAll work starts... 1000 one has been completed. 1500 one has been completed. 2000 one has been completed. 2009ms has been elapsed. The await keyword in a loop does not really make the calls in parallel.

    Read the article

  • YouTube SEO: Video Optimization

    - by Mike Stiles
    SEO optimization is still regarded as one of the primary tools in the digital marketing kit. However and wherever a potential customer is conducting a search, brands want their content to surface in the top results. Makes sense. But without a regular flow of good, relevant content, your SEO opportunities run shallow. We know from several studies video is one of the most engaging forms of content, so why not make sure that in addition to being cool, your videos are helping you win the SEO game? Keywords:-Decide what search phrases make the most sense for your video. Don’t dare use phrases that have nothing to do with the content. You’ll make people mad.-Research those keywords to see how competitive they are. Adjust them so there are still lots of people searching for it, but there are not as many links showing up for it.-Search your potential keywords and phrases to see what comes up. It’s amazing how many people forget to do that. Video Title: -Try to start and/or end with your keyword.-When you search on YouTube, visual action words tend to come up as suggested searches. So try to use action words. Video Description: -Lead with a link to your site (include http://). -Don’t stuff this with your keyword. It leads to bad writing and it won’t work anyway. This is where you convince people to watch, so write for humans. Use some showmanship. -At the end, do a call to action (subscribe, see the whole playlist, visit our social channels, etc.) Video Tags:-Don’t over-tag. 5-10 tags per video is plenty. -If you’re compelled to have more than 10, that means you should probably make more videos specifically targeting all those keywords. Find Linking Pals:-45% of videos are discovered on video sites. But 44% are found through links on blogs and sites.-Write a blog about your video’s content, then link to the video in it. -A good site for finding places to guest blog is myblogguest.com-Once you find good linking partners, they’ll link to your future videos (as long as they’re good and you’re returning the favor). Tap the Power of Similar Videos:-Use Video Reply to associate your video with other topic-related videos. That’s when you make a video responding to or referencing a video made by someone else. Content:-Again, build up a portfolio of videos, not just one that goes after 30 keywords.-Create shorter, sequential videos that pull them deeper into the content and closer to a desired final action.-Organize your video topics separately using Playlists. Playlists show up as a whole in search results like individual videos, so optimize playlists the same as you would for a video. Meta Data:-Too much importance is placed on it. It accounts for only 15% of search success.-YouTube reads Captions or Transcripts to determine what a video is about. If you’re not using them, you’re missing out.-You get the SEO benefit of captions and transcripts whether the viewers has them toggled on or not. Promotion:-This accounts for 25% of search success.-Promote the daylights out of your videos using your social channels and digital assets. Don’t assume it’s going to magically get discovered. -You can pay to promote your video. This could surface it on the YouTube home page, YouTube search results, YouTube related videos, and across the Google content network. Community:-Accounts for 10% of search success.-Make sure your YouTube home page is a fun place to spend time. Carefully pick your featured video, and make sure your Playlists are featured. -Participate in discussions so users will see you’re present. The volume of ratings/comments is as important as the number of views when it comes to where you surface on search. Video Sitemaps:-As with a web site, a video sitemap helps Google quickly index your video.-Google wants to know title, description, play page URL, the URL of the thumbnail image you want, and raw video file location.-Sitemaps are xml files you host or dynamically generate on your site. Once you’ve made your sitemap, sign in and submit it using Google webmaster tools. Just as with the broadcast and cable TV channels, putting a video out there is only step one. You also have to make sure everybody knows it’s there so the largest audience possible can see it. Here’s hoping you get great ratings. @mikestiles

    Read the article

  • MVC 2 View Layout CSS Control Layout

    - by Cory Mathewson
    I'm new to a lot of what I'm trying to do with the development of a new MVC2 web application so this is a beginner question. I need to understand my options for control and content layout on a web page. I’m using MVC2 so I’m using Controllers, Views, ViewModels, and View Templates. What I need to spin up on…fast…is control the granular layout of controls and content on any particular view. Below I’ve pasted two examples of auto generated templates that illustrate my challenge. I see that layout is controlled by CSS in my Site.css document. In the first example I get a sequential flow of DisplayLabel and DisplayField. I prefer the adjacent layout of DisplayLabel on the same line as DisplayField produced from example 2. However, example 2 is too simple because the formatting is applied to the Label and the Field. I think the correct way to tackle this learning curve is Microsoft Expression but I don’t have personal bandwidth at the moment to tackle Expression. Can anyone point me to a resource that will expose me to lots of examples for CSS formatting? I have lots of syntax questions. For instance, I believe is referencing the Site.css but I can’t find a "display-label" section in Site.css. Example 1 <fieldset> <legend>Fields</legend> <div class="display-label">DocTitle</div> <div class="display-field"><%: Model.DocTitle %></div> <div class="display-label">DocoumentPropertiesID</div> <div class="display-field"><%: Model.DocumentPropertiesID %></div> Example 2 <h2>Title: <%: Model.DocTitle %></h2> <h2>Created: <%: Model.Created %></h2> <h2>Modified: <%: Model.Modified %></h2> <h2>Author: <%: Model.tbl_Author.Name %></h2> <h2>Genre: <%: Model.tbl_DocumentGenre.GenreName %></h2>

    Read the article

  • ZPL II Extended Characters

    - by Mauro
    I'm trying to print extended code page 850 characters using ZPL II to a Zebra S4M. Whenever one of the extended characters I.E. ASCII value 127 is used I get a box of varying shades of grey instead of the actual value. I'm trying to print ± and ° (ALT+0177 and ALT+0176). I suspect its the RawPrinterHelper I am trying to use (as downloaded from MS, and another from CodeProject) however I cant see where the character codes are going wrong. Weirdly, printing direct from Notepad renders the correct characters, which leads me to believe it is a problem with the raw printer helper class. I am not tied to using the Raw Printer Helper class so if there is a better way of doing it, I am more than happy to see them. SAMPLE ZPLII Without escaped chars ^XA ^FO30,200^AD^FH,18,10^FD35 ± 2 ° ^FS ^FS ^XZ With escaped chars (tried both upper and lower case) ^XA ^FO30,200^AD^FH,18,10^FD35 _b0 2 _b1 ^FS ^FS ^XZ Raw Printer Helper [StructLayout(LayoutKind.Sequential)] public struct DOCINFO { [MarshalAs(UnmanagedType.LPWStr)] public string printerDocumentName; [MarshalAs(UnmanagedType.LPWStr)] public string pOutputFile; [MarshalAs(UnmanagedType.LPWStr)] public string printerDocumentDataType; } public class RawPrinter { [ DllImport("winspool.drv", CharSet = CharSet.Unicode, ExactSpelling = false, CallingConvention = CallingConvention.StdCall)] public static extern long OpenPrinter(string pPrinterName, ref IntPtr phPrinter, int pDefault); [ DllImport("winspool.drv", CharSet = CharSet.Unicode, ExactSpelling = false, CallingConvention = CallingConvention.StdCall)] public static extern long StartDocPrinter(IntPtr hPrinter, int Level, ref DOCINFO pDocInfo); [ DllImport("winspool.drv", CharSet = CharSet.Unicode, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)] public static extern long StartPagePrinter(IntPtr hPrinter); [ DllImport("winspool.drv", CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)] public static extern long WritePrinter(IntPtr hPrinter, string data, int buf, ref int pcWritten); [ DllImport("winspool.drv", CharSet = CharSet.Unicode, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)] public static extern long EndPagePrinter(IntPtr hPrinter); [ DllImport("winspool.drv", CharSet = CharSet.Unicode, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)] public static extern long EndDocPrinter(IntPtr hPrinter); [ DllImport("winspool.drv", CharSet = CharSet.Unicode, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)] public static extern long ClosePrinter(IntPtr hPrinter); public static void SendToPrinter(string printerJobName, string rawStringToSendToThePrinter, string printerNameAsDescribedByPrintManager) { IntPtr handleForTheOpenPrinter = new IntPtr(); DOCINFO documentInformation = new DOCINFO(); int printerBytesWritten = 0; documentInformation.printerDocumentName = printerJobName; documentInformation.printerDocumentDataType = "RAW"; OpenPrinter(printerNameAsDescribedByPrintManager, ref handleForTheOpenPrinter, 0); StartDocPrinter(handleForTheOpenPrinter, 1, ref documentInformation); StartPagePrinter(handleForTheOpenPrinter); WritePrinter(handleForTheOpenPrinter, rawStringToSendToThePrinter, rawStringToSendToThePrinter.Length, ref printerBytesWritten); EndPagePrinter(handleForTheOpenPrinter); EndDocPrinter(handleForTheOpenPrinter); ClosePrinter(handleForTheOpenPrinter); } }

    Read the article

  • DbgHelp.dll : Problem calling SymGetModuleInfo64 from C#

    - by Civa
    Hello everyone, I have quite strange behaviour calling SymGetModuleInfo64 from C# code.I always get ERROR_INVALID_PARAMETER (87) with Marshal.GetLastWin32Error().I have already read a lot of posts regarding problems with frequent updates of IMAGEHLP_MODULE64 struct and I just downloaded latest Debugging Tools For Windows (x86) , loaded dbghelp.dll from that location and I was quite sure it would work.Nevertheless I am getting the same error.Can anyone point me what is wrong here? IMAGEHLP_MODULE64 struct is defined in my code as follows : [StructLayout(LayoutKind.Sequential)] public struct IMAGEHELP_MODULE64 { //************************************************ public int SizeOfStruct; public long BaseOfImage; public int ImageSize; public int TimeDateStamp; public int CheckSum; public int NumSyms; public SymType SymType; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] public string ModuleName; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)] public string ImageName; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)] public string LoadedImageName; //************************************************ //new elements v2 //************************************************* [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)] public string LoadedPdbName; public int CVSig; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 780)] public string CVData; public int PdbSig; public GUID PdbSig70; public int PdbAge; public bool PdbUnmatched; public bool DbgUnmatched; public bool LineNumbers; public bool GlobalSymbols; public bool TypeInfo; //************************************************ //new elements v3 //************************************************ public bool SourceIndexed; public bool Publics; //************************************************ //new elements v4 //************************************************ public int MachineType; public int Reserved; //************************************************ } the piece of code that actually calls SymGetModuleInfo64 is like this : public void GetSymbolInfo(IntPtr hProcess,long modBase64,out bool success) { success = false; DbgHelp.IMAGEHELP_MODULE64 moduleInfo = new DbgHelp.IMAGEHELP_MODULE64(); moduleInfo.SizeOfStruct = Marshal.SizeOf(moduleInfo); try { success = DbgHelp.SymGetModuleInfo64(hProcess, modBase64, out moduleInfo); if (success) { //Do the stuff here } } catch (Exception exc) { } } Im stuck here...always with error 87.Please someone points me to the right direction. By the way modBase64 is value previously populated by : modBase64 = DbgHelp.SymLoadModule64(_handle, IntPtr.Zero, fileName, null, baseAddress, size); where _handle is process handle of process being debugged,fileName is path of current loaded module, baseAddress is address base of currently loaded module and size is of course the size of current loaded module.I call this code when I get LOAD_DLL_DEBUG_EVENT. Edit : Sorry, I forgot to mention that SymGetModuleInfo64 signature is like this : [DllImport("dbghelp.dll", SetLastError = true)] public static extern bool SymGetModuleInfo64(IntPtr hProcess, long ModuleBase64, out IMAGEHELP_MODULE64 imgHelpModule); Best regards, Civa

    Read the article

  • Still getting duplicate token error after calling DuplicateTokenEx for impersonated token

    - by atconway
    I'm trying to return a Sytem.IntPtr from a service call so that the client can use impersonation to call some code. My imersonation code works properly if not passing the token back from a WCF service. I'm not sure why this is not working. I get the following error: "Invalid token for impersonation - it cannot be duplicated." Here is my code that does work except when I try to pass the token back from a service to a WinForm C# client to then impersonate. [DllImport("advapi32.dll", EntryPoint = "DuplicateTokenEx")] public extern static bool DuplicateTokenEx(IntPtr ExistingTokenHandle, uint dwDesiredAccess, ref SECURITY_ATTRIBUTES lpThreadAttributes, int TokenType, int ImpersonationLevel, ref IntPtr DuplicateTokenHandle); private IntPtr tokenHandle = new IntPtr(0); private IntPtr dupeTokenHandle = new IntPtr(0); [StructLayout(LayoutKind.Sequential)] public struct SECURITY_ATTRIBUTES { public int Length; public IntPtr lpSecurityDescriptor; public bool bInheritHandle; } public enum SecurityImpersonationLevel { SecurityAnonymous = 0, SecurityIdentification = 1, SecurityImpersonation = 2, SecurityDelegation = 3 } public enum TokenType { TokenPrimary = 1, TokenImpersonation = 2 } private const int MAXIMUM_ALLOWED = 0x2000000; [PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")] public System.IntPtr GetWindowsUserToken(string UserName, string Password, string DomainName) { IntPtr tokenHandle = new IntPtr(0); IntPtr dupTokenHandle = new IntPtr(0); const int LOGON32_PROVIDER_DEFAULT = 0; //This parameter causes LogonUser to create a primary token. const int LOGON32_LOGON_INTERACTIVE = 2; //Initialize the token handle tokenHandle = IntPtr.Zero; //Call LogonUser to obtain a handle to an access token for credentials supplied. bool returnValue = LogonUser(UserName, DomainName, Password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref tokenHandle); //Make sure a token was returned; if no populate the ResultCode and throw an exception: int ResultCode = 0; if (false == returnValue) { ResultCode = Marshal.GetLastWin32Error(); throw new System.ComponentModel.Win32Exception(ResultCode, "API call to LogonUser failed with error code : " + ResultCode); } SECURITY_ATTRIBUTES sa = new SECURITY_ATTRIBUTES(); sa.bInheritHandle = true; sa.Length = Marshal.SizeOf(sa); sa.lpSecurityDescriptor = (IntPtr)0; bool dupReturnValue = DuplicateTokenEx(tokenHandle, MAXIMUM_ALLOWED, ref sa, (int)SecurityImpersonationLevel.SecurityDelegation, (int)TokenType.TokenImpersonation, ref dupTokenHandle); int ResultCodeDup = 0; if (false == dupReturnValue) { ResultCodeDup = Marshal.GetLastWin32Error(); throw new System.ComponentModel.Win32Exception(ResultCode, "API call to DuplicateToken failed with error code : " + ResultCode); } //Return the user token return dupTokenHandle; } Any idea if I'm not using the call to DuplicateTokenEx correctly? According to the MSDN documentation I read here I should be able to create a token valid for delegation and use across the context on remote systems. When 'SecurityDelegation' is used, the server process can impersonate the client's security context on remote systems. Thanks!

    Read the article

  • Taking screenshot with Win32 API (C# pInvoke) not working in IIS

    - by Dillen Meijboom
    I want to take a screenshot of an external website. Currently my workflow is to start a Firefox instance with the specified URL and take a screenshot using PrintWindow in the Win32 API When I run this application in IISExpress it works fine but when I run the same application in IIS on a windows VPS it is not working (screenshot is blank). I don't know what I'm doing wrong? My code: using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; using System.Drawing.Imaging; using System.Linq; using System.Runtime.InteropServices; using System.Security; using System.Threading; using System.Web; namespace WebTools.Web { public class RemoteScreenshot { public static Bitmap TakeScreenshot(Process process) { // may need a process Refresh before return TakeScreenshot(process.MainWindowHandle); } public static Bitmap TakeScreenshot(IntPtr handle) { RECT rc = new RECT(); GetWindowRect(handle, ref rc); Bitmap bitmap = new Bitmap(rc.right - rc.left, rc.bottom - rc.top); using (Graphics graphics = Graphics.FromImage(bitmap)) { PrintWindow(handle, graphics.GetHdc(), 0); } return bitmap; } [DllImport("user32.dll")] private static extern bool GetWindowRect(IntPtr hWnd, ref RECT rect); [DllImport("user32.dll")] private static extern bool PrintWindow(IntPtr hWnd, IntPtr hDC, int flags); [StructLayout(LayoutKind.Sequential)] private struct RECT { public int left; public int top; public int right; public int bottom; } public static void Save(string url, string file, int timeout = 0) { Process.Start(new ProcessStartInfo("C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe", url) { CreateNoWindow = false, WindowStyle = ProcessWindowStyle.Maximized }); Thread.Sleep(timeout); var bitmap = TakeScreenshot(Process.GetProcessesByName("firefox").First()); bitmap.Save(file, ImageFormat.Png); bitmap.Dispose(); Process.GetProcessesByName("firefox").First().Kill(); } } } EDIT: Running Firefox works fine because the AppPool is under another account that has the rights to execute firefox.

    Read the article

  • CodeGolf: Brothers

    - by John McClane
    Hi guys, I just finished participating in the 2009 ACM ICPC Programming Conest in the Latinamerican Finals. These questions were for Brazil, Bolivia, Chile, etc. My team and I could only finish two questions out of the eleven (not bad I think for the first try). Here's one we could finish. I'm curious to seeing any variations to the code. The question in full: ps: These questions can also be found on the official ICPC website available to everyone. In the land of ACM ruled a greeat king who became obsessed with order. The kingdom had a rectangular form, and the king divided the territory into a grid of small rectangular counties. Before dying the king distributed the counties among his sons. The king was unaware of the rivalries between his sons: The first heir hated the second but not the rest, the second hated the third but not the rest, and so on...Finally, the last heir hated the first heir, but not the other heirs. As soon as the king died, the strange rivaly among the King's sons sparked off a generalized war in the kingdom. Attacks only took place between pairs of adjacent counties (adjacent counties are those that share one vertical or horizontal border). A county X attacked an adjacent county Y whenever X hated Y. The attacked county was always conquered. All attacks where carried out simultanously and a set of simultanous attacks was called a battle. After a certain number of battles, the surviving sons made a truce and never battled again. For example if the king had three sons, named 0, 1 and 2, the figure below shows what happens in the first battle for a given initial land distribution: INPUT The input contains several test cases. The first line of a test case contains four integers, N, R, C and K. N - The number of heirs (2 <= N <= 100) R and C - The dimensions of the land. (2 <= R,C <= 100) K - Number of battles that are going to take place. (1 <= K <= 100) Heirs are identified by sequential integers starting from zero. Each of the next R lines contains C integers HeirIdentificationNumber (saying what heir owns this land) separated by single spaces. This is to layout the initial land. The last test case is a line separated by four zeroes separated by single spaces. (To exit the program so to speak) Output For each test case your program must print R lines with C integers each, separated by single spaces in the same format as the input, representing the land distribution after all battles. Sample Input: Sample Output: 3 4 4 3 2 2 2 0 0 1 2 0 2 1 0 1 1 0 2 0 2 2 2 0 0 1 2 0 0 2 0 0 0 1 2 2 Another example: Sample Input: Sample Output: 4 2 3 4 1 0 3 1 0 3 2 1 2 2 1 2

    Read the article

  • Unexpected behavior of IntentService

    - by kknight
    I used IntentService in my code instead of Service because IntentService creates a thread for me in onHandleIntent(Intent intent), so I don't have to create a Thead myself in the code of my service. I expected that two intents to the same IntentSerivce will execute in parallel because a thread is generated in IntentService for each invent. But my code turned out that the two intents executed in sequential way. This is my IntentService code: public class UpdateService extends IntentService { public static final String TAG = "HelloTestIntentService"; public UpdateService() { super("News UpdateService"); } protected void onHandleIntent(Intent intent) { String userAction = intent .getStringExtra("userAction"); Log.v(TAG, "" + new Date() + ", In onHandleIntent for userAction = " + userAction + ", thread id = " + Thread.currentThread().getId()); if ("1".equals(userAction)) { try { Thread.sleep(20 * 1000); } catch (InterruptedException e) { Log.e(TAG, "error", e); } Log.v(TAG, "" + new Date() + ", This thread is waked up."); } } } And the code call the service is below: public class HelloTest extends Activity { //@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Intent selectIntent = new Intent(this, UpdateService.class); selectIntent.putExtra("userAction", "1"); this.startService(selectIntent); selectIntent = new Intent(this, UpdateService.class); selectIntent.putExtra("userAction", "2"); this.startService(selectIntent); } } I saw this log message in the log: V/HelloTestIntentService( 848): Wed May 05 14:59:37 PDT 2010, In onHandleIntent for userAction = 1, thread id = 8 D/dalvikvm( 609): GC freed 941 objects / 55672 bytes in 99ms V/HelloTestIntentService( 848): Wed May 05 15:00:00 PDT 2010, This thread is waked up. V/HelloTestIntentService( 848): Wed May 05 15:00:00 PDT 2010, In onHandleIntent for userAction = 2, thread id = 8 I/ActivityManager( 568): Stopping service: com.example.android/.UpdateService The log shows that the second intent waited the first intent to finish and they are in the same thread. It there anything I misunderstood of IntentService. To make two service intents execute in parallel, do I have to replace IntentService with service and start a thread myself in the service code? Thanks.

    Read the article

  • stdio's remove() not always deleting on time.

    - by Kyte
    For a particular piece of homework, I'm implementing a basic data storage system using sequential files under standard C, which cannot load more than 1 record at a time. So, the basic part is creating a new file where the results of whatever we do with the original records are stored. The previous file's renamed, and a new one under the working name is created. The code's compiled with MinGW 5.1.6 on Windows 7. Problem is, this particular version of the code (I've got nearly-identical versions of this floating around my functions) doesn't always remove the old file, so the rename fails and hence the stored data gets wiped by the fopen(). FILE *archivo, *antiguo; remove("IndiceNecesidades.old"); // This randomly fails to work in time. rename("IndiceNecesidades.dat", "IndiceNecesidades.old"); // So rename() fails. antiguo = fopen("IndiceNecesidades.old", "rb"); // But apparently it still gets deleted, since this turns out null (and I never find the .old in my working folder after the program's done). archivo = fopen("IndiceNecesidades.dat", "wb"); // And here the data gets wiped. Basically, anytime the .old previously exists, there's a chance it's not removed in time for the rename() to take effect successfully. No possible name conflicts both internally and externally. The weird thing's that it's only with this particular file. Identical snippets except with the name changed to Necesidades.dat (which happen in 3 different functions) work perfectly fine. // I'm yet to see this snippet fail. FILE *antiguo, *archivo; remove("Necesidades.old"); rename("Necesidades.dat", "Necesidades.old"); antiguo = fopen("Necesidades.old", "rb"); archivo = fopen("Necesidades.dat", "wb"); Any ideas on why would this happen, and/or how can I ensure the remove() command has taken effect by the time rename() is executed? (I thought of just using a while loop to force call remove() again so long as fopen() returns a non-null pointer, but that sounds like begging for a crash due to overflowing the OS with delete requests or something.)

    Read the article

  • Use native HBitmap in C# while preserving alpha channel/transparency. Please check this code, it works on my computer...

    - by David
    Let's say I get a HBITMAP object/handle from a native Windows function. I can convert it to a managed bitmap using Bitmap.FromHbitmap(nativeHBitmap), but if the native image has transparency information (alpha channel), it is lost by this conversion. There are a few questions on Stack Overflow regarding this issue. Using information from the first answer of this question (How to draw ARGB bitmap using GDI+?), I wrote a piece of code that I've tried and it works. It basically gets the native HBitmap width, height and the pointer to the location of the pixel data using GetObject and the BITMAP structure, and then calls the managed Bitmap constructor: Bitmap managedBitmap = new Bitmap(bitmapStruct.bmWidth, bitmapStruct.bmHeight, bitmapStruct.bmWidth * 4, PixelFormat.Format32bppArgb, bitmapStruct.bmBits); As I understand (please correct me if I'm wrong), this does not copy the actual pixel data from the native HBitmap to the managed bitmap, it simply points the managed bitmap to the pixel data from the native HBitmap. And I don't draw the bitmap here on another Graphics (DC) or on another bitmap, to avoid unnecessary memory copying, especially for large bitmaps. I can simply assign this bitmap to a PictureBox control or the the Form BackgroundImage property. And it works, the bitmap is displayed correctly, using transparency. When I no longer use the bitmap, I make sure the BackgroundImage property is no longer pointing to the bitmap, and I dispose both the managed bitmap and the native HBitmap. The Question: Can you tell me if this reasoning and code seems correct. I hope I will not get some unexpected behaviors or errors. And I hope I'm freeing all the memory and objects correctly. private void Example() { IntPtr nativeHBitmap = IntPtr.Zero; /* Get the native HBitmap object from a Windows function here */ // Create the BITMAP structure and get info from our nativeHBitmap NativeMethods.BITMAP bitmapStruct = new NativeMethods.BITMAP(); NativeMethods.GetObjectBitmap(nativeHBitmap, Marshal.SizeOf(bitmapStruct), ref bitmapStruct); // Create the managed bitmap using the pointer to the pixel data of the native HBitmap Bitmap managedBitmap = new Bitmap( bitmapStruct.bmWidth, bitmapStruct.bmHeight, bitmapStruct.bmWidth * 4, PixelFormat.Format32bppArgb, bitmapStruct.bmBits); // Show the bitmap this.BackgroundImage = managedBitmap; /* Run the program, use the image */ MessageBox.Show("running..."); // When the image is no longer needed, dispose both the managed Bitmap object and the native HBitmap this.BackgroundImage = null; managedBitmap.Dispose(); NativeMethods.DeleteObject(nativeHBitmap); } internal static class NativeMethods { [StructLayout(LayoutKind.Sequential)] public struct BITMAP { public int bmType; public int bmWidth; public int bmHeight; public int bmWidthBytes; public ushort bmPlanes; public ushort bmBitsPixel; public IntPtr bmBits; } [DllImport("gdi32", CharSet = CharSet.Auto, EntryPoint = "GetObject")] public static extern int GetObjectBitmap(IntPtr hObject, int nCount, ref BITMAP lpObject); [DllImport("gdi32.dll")] internal static extern bool DeleteObject(IntPtr hObject); }

    Read the article

  • Marshal.PtrToStructure (and back again) and generic solution for endianness swapping

    - by cgyDeveloper
    I have a system where a remote agent sends serialized structures (from and embedded C system) for me to read and store via IP/UDP. In some cases I need to send back the same structure types. I thought I had a nice setup using Marshal.PtrToStructure (receive) and Marshal.StructureToPtr (send). However, a small gotcha is that the network big endian integers need to be converted to my x86 little endian format to be used locally. When I'm sending them off again, big endian is the way to go. Here are the functions in question: private static T BytesToStruct<T>(ref byte[] rawData) where T: struct { T result = default(T); GCHandle handle = GCHandle.Alloc(rawData, GCHandleType.Pinned); try { IntPtr rawDataPtr = handle.AddrOfPinnedObject(); result = (T)Marshal.PtrToStructure(rawDataPtr, typeof(T)); } finally { handle.Free(); } return result; } private static byte[] StructToBytes<T>(T data) where T: struct { byte[] rawData = new byte[Marshal.SizeOf(data)]; GCHandle handle = GCHandle.Alloc(rawData, GCHandleType.Pinned); try { IntPtr rawDataPtr = handle.AddrOfPinnedObject(); Marshal.StructureToPtr(data, rawDataPtr, false); } finally { handle.Free(); } return rawData; } And a quick example structure that might be used like this: byte[] data = this.sock.Receive(ref this.ipep); Request request = BytesToStruct<Request>(ref data); Where the structure in question looks like: [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)] private struct Request { public byte type; public short sequence; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 5)] public byte[] address; } What (generic) way can I swap the endianness when marshalling the structures? My need is such that the locally stored 'public short sequence' in this example will be little-endian for displaying to the user. I don't want to have to swap the endianness on a structure-specific way. My first thought was to use Reflection, but I'm not very familiar with that feature. Also, I hoped that there would be a better solution out there that somebody could point me towards. Thanks in advance :)

    Read the article

  • BASH, multiple arrays and a loop.

    - by S1syphus
    At work, we 7 or 8 hardrives we dispatch over the country, each have unique labels which are not sequential. Ideally drives are plugged in our desktop, then gets folders from the server that correspond to the drive name. Sometimes, only one hard drive gets plugged in sometimes multiples, possibly in the future more will be added. Each is mounts to /Volumes/ and it's identifier; so for example /Volumes/f00, where f00 is the identifier. What I want to happen, scan volumes see if any any of the drives are plugged in, then checks the server to see if the folder exists, if ir does copy folder and recursive folders. Here is what I have so far, it checks if the drive exists in Volumes: #!/bin/sh #Declare drives in the array ARRAY=( foo bar long ) #Get the drives from the array DRIVES=${#ARRAY[@]} #Define base dir to check BaseDir="/Volumes" #Define shared server fold on local mount points #I plan to use AFP eventually, but for the sake of ease #using a local mount. ServerMount="BigBlue" #Define folder name for where files are to come from Dispatch="File-Dispatch" dir="$BaseDir/${ARRAY[${i}]}" #Loop through each item in the array and check if exists on /Volumes for (( i=0;i<$DRIVES;i++)); do dir="$BaseDir/${ARRAY[${i}]}" if [ -d "$dir" ]; then echo "$dir exists, you win." else echo "$dir is not attached." fi done What I can't figure out how to do, is how to check the volumes for the server while looping through the harddrive mount points. So I could do something like: #!/bin/sh #Declare drives, and folder location in arrays ARRAY=( foo bar long ) ARRAY1=($(ls ""$BaseDir"/"$ServerMount"/"$Dispatch"")) #Get the drives from the array DRIVES=${#ARRAY[@]} SERVERFOLDER=${#ARRAY1[@]} #Define base dir to check BaseDir="/Volumes" #Define shared server fold on local mount points ServerMount="BigBlue #Define folder name for where files are to come from Dispatch="File-Dispatch" dir="$BaseDir/${ARRAY[${i}]}" #List the contents from server directory into array ARRAY1=($(ls ""$BaseDir"/"$ServerMount"/"$Dispatch"")) echo ${list[@]} for (( i=0;i<$DRIVES;i++)); (( i=0;i<$SERVERFOLDER;i++)); do dir="$BaseDir/${ARRAY[${i}]}" ser="${ARRAY1[${i}]}" if [ "$dir" =~ "$sir" ]; then cp "$sir" "$dir" else echo "$dir is not attached." fi done I know, that is pretty wrong... well very, but I hope it gives you the idea of what I am trying to achieve. Any ideas or suggestions?

    Read the article

  • Logging raw HTTP request/response in ASP.NET MVC & IIS7

    - by Greg Beech
    I'm writing a web service (using ASP.NET MVC) and for support purposes we'd like to be able to log the requests and response in as close as possible to the raw, on-the-wire format (i.e including HTTP method, path, all headers, and the body) into a database. What I'm not sure of is how to get hold of this data in the least 'mangled' way. I can re-constitute what I believe the request looks like by inspecting all the properties of the HttpRequest object and building a string from them (and similarly for the response) but I'd really like to get hold of the actual request/response data that's sent on the wire. I'm happy to use any interception mechanism such as filters, modules, etc. and the solution can be specific to IIS7. However, I'd prefer to keep it in managed code only. Any recommendations? Edit: I note that HttpRequest has a SaveAs method which can save the request to disk but this reconstructs the request from the internal state using a load of internal helper methods that cannot be accessed publicly (quite why this doesn't allow saving to a user-provided stream I don't know). So it's starting to look like I'll have to do my best to reconstruct the request/response text from the objects... groan. Edit 2: Please note that I said the whole request including method, path, headers etc. The current responses only look at the body streams which does not include this information. Edit 3: Does nobody read questions around here? Five answers so far and yet not one even hints at a way to get the whole raw on-the-wire request. Yes, I know I can capture the output streams and the headers and the URL and all that stuff from the request object. I already said that in the question, see: I can re-constitute what I believe the request looks like by inspecting all the properties of the HttpRequest object and building a string from them (and similarly for the response) but I'd really like to get hold of the actual request/response data that's sent on the wire. If you know the complete raw data (including headers, url, http method, etc.) simply cannot be retrieved then that would be useful to know. Similarly if you know how to get it all in the raw format (yes, I still mean including headers, url, http method, etc.) without having to reconstruct it, which is what I asked, then that would be very useful. But telling me that I can reconstruct it from the HttpRequest/HttpResponse objects is not useful. I know that. I already said it. Please note: Before anybody starts saying this is a bad idea, or will limit scalability, etc., we'll also be implementing throttling, sequential delivery, and anti-replay mechanisms in a distributed environment, so database logging is required anyway. I'm not looking for a discussion of whether this is a good idea, I'm looking for how it can be done.

    Read the article

  • architecture python question

    - by tom smith
    hi. creating a distributed crawling python app. it consists of a master server, and associated client apps that will run on client servers. the purpose of the client app is to run across a targeted site, to extract specific data. the clients need to go "deep" within the site, behind multiple levels of forms, so each client is specifically geared towards a given site. each client app looks something like main: parse initial url call function level1 (data1) function level1 (data) parse the url, for data1 use the required xpath to get the dom elements call the next function call level2 (data) function level2 (data2) parse the url, for data2 use the required xpath to get the dom elements call the next function call level3 function level3 (dat3) parse the url, for data3 use the required xpath to get the dom elements call the next function call level4 function level4 (data) parse the url, for data4 use the required xpath to get the dom elements at the final function.. --all the data output, and eventually returned to the server --at this point the data has elements from each function... my question: given that the number of calls that is made to the child function by the current function varies, i'm trying to figure out the best approach. each function essentialy fetches a page of content, and then parses the page using a number of different XPath expressions, combined with different regex expressions depending on the site/page. if i run a client on a single box, as a sequential process, it'll take awhile, but the load on the box is rather small. i've thought of attempting to implement the child functions as threads from the current function, but that could be a nightmare, as well as quickly bring the "box" to its knees! i've thought of breaking the app up in a manner that would allow the master to essentially pass packets to the client boxes, in a way to allow each client/function to be run directly from the master. this process requires a bit of rewrite, but it has a number of advantages. a bunch of redundancy, and speed. it would detect if a section of the process was crashing and restart from that point. but not sure if it would be any faster... i'm writing the parsing scripts in python.. so... any thoughts/comments would be appreciated... i can get into a great deal more detail, but didn't want to bore anyone!! thanks! tom

    Read the article

  • Problem with final branch in a parallel activity

    - by Dan Revell
    This might seem like a silly thing to say, the final branch in a parallel activity so I'll clarify. It's a parallel activity with three branches each containing a simple create task, on task changed and complete task. The branch containing the task that is last to complete seems to break. So every task works in it's own right, but the last one encounters a problem. Say the user clicks the final tasks link to open the attached infopath form and submits that. Execution gets to the event handler for that onTaskChanged where a taskCompleted variable gets set to true which will exit the while loop. I've successfully hit a breakpoint on this line so I know that happens. However the final activity in that branch, the completeTask doesn't get hit. When submit is clicked in the final form, the operation in progess screen says of for quite a while before returning to the workflow status page. The task that was opened and submitted says "Not Started". I can disable any of the branches to leave only two, but the same problem happens with the last to be completed. Earlier on in the workflow I do essencially the same thing. I have another 3 branch parallel activity with each brach containing a task. This one works correctly which leads me to believe that it might be a problem with having two parallel activites in the same sequential workflow. I've considered the possibility that it might be a correlation token problem. The token that every task branch uses is unique to that branch and it's owner activity name is est to that of the branch. It stands to reason that if the task complete variable is indeed getting set to true but the while loop isn't being exited, then there's a wire crossing with the variable somewhere. However I'd still have thought that the task status back on the workflow status page would at least say that the task is in progress. This is a frustrating show stopper of a bug for me. Any thoughts or suggestions would be much appricated so I can investigate them.

    Read the article

  • Problem getting correct parameters for C# P/Invoke call to C++ dll

    - by Jim Jones
    Trying to Interop a functionality from the Outside In API from Oracle. Have the following function: SCCERR EXOpenExport {VTHDOC hDoc, VTDWORD dwOutputId, VTDWORD dwSpecType, VTLPVOID pSpec, VTDWORD dwFlags, VTSYSPARAM dwReserved, VTLPVOID pCallbackFunc, VTSYSPARAM dwCallbackData, VTLPHEXPORT phExport); From the header files I reduced the parameters to: typedef VTSYSPARAM VTHDOC, VTLPHDOC * typedef DWORD_PTR VTSYSPARAM typedef unsigned long DWORD_PTR typedef unsigned long VTDWORD typedef VTVOID* VTLPVOID #define VTVOID void typedef VTHDOC VTHEXPORT, *VTLPEXPORT These are for 32 bit windows Going through the header files, the example programs, and the documentation I found: 1. That pSpec could be a pointer to a buffer or NULL, so I set it to a IntPtr.Zero (documentation). 2. That dwFlags and dwReserved according to the documentation "Must be set by the developer to 0". 3. That pCallbackFunc can be set to NULL if I don't want to handle callbacks. 4. That the last two are based on structs that I wrote C# wrappers for using the [StructLayout(LayoutKind.Sequential)]. Then instatiated an instance and generated the parameters by first creating a IntPtr with Marshal.AllocHGlobal(Marshal.SizeOf(instance)), then getting the address value which is passed as a uint for dwCallbackData and a IntPtr for phExport. The final parameter list is as follows: 1. phDoc as a IntPtr which was loaded with an address by the DAOpenDocument function called before. 2. dwOutputId as uint set to 1535 which represents FI_JPEGFIF 3. dwSpecType as int set to 2 which represents IOTYPE_ANSIPATH 4. pSpec as an IntPtr.Zero where the output will be written 5. dwFlags as uint set to 0 as directed 6. dwReserved as uint set to 0 as directed 7. pCallbackFunc as IntPtr set to NULL as I will handle results 8. dwCallBackDate as uint the address of a buffer for a struct 9. phExport as IntPtr to another struct buffer still get an undefined error from the API. Meaning that the call returns a 961 which is not defined in any of the header files. In the past I have gotten this when my choice of parameter types are incorrect. I started out using Interop Assistant which was helpful in learning how many of the parameter types get translated. It is however limited by how well I am able to glean the correct native type from the header files. For example the hDoc parameter used in the preceding function was defined as a non-filesytem handle, so attempted to use Marshal to create a handle, then used an IntPtr, and finally it turned out to be an int (actually it was &phDoc used here). So is there a more scientific way of doing this, other than trial and error? Jim

    Read the article

  • Multiprogramming in Django, writing to the Database

    - by Marcus Whybrow
    Introduction I have the following code which checks to see if a similar model exists in the database, and if it does not it creates the new model: class BookProfile(): # ... def save(self, *args, **kwargs): uniqueConstraint = {'book_instance': self.book_instance, 'collection': self.collection} # Test for other objects with identical values profiles = BookProfile.objects.filter(Q(**uniqueConstraint) & ~Q(pk=self.pk)) # If none are found create the object, else fail. if len(profiles) == 0: super(BookProfile, self).save(*args, **kwargs) else: raise ValidationError('A Book Profile for that book instance in that collection already exists') I first build my constraints, then search for a model with those values which I am enforcing must be unique Q(**uniqueConstraint). In addition I ensure that if the save method is updating and not inserting, that we do not find this object when looking for other similar objects ~Q(pk=self.pk). I should mention that I ham implementing soft delete (with a modified objects manager which only shows non-deleted objects) which is why I must check for myself rather then relying on unique_together errors. Problem Right thats the introduction out of the way. My problem is that when multiple identical objects are saved in quick (or as near as simultaneous) succession, sometimes both get added even though the first being added should prevent the second. I have tested the code in the shell and it succeeds every time I run it. Thus my assumption is if say we have two objects being added Object A and Object B. Object A runs its check upon save() being called. Then the process saving Object B gets some time on the processor. Object B runs that same test, but Object A has not yet been added so Object B is added to the database. Then Object A regains control of the processor, and has allready run its test, even though identical Object B is in the database, it adds it regardless. My Thoughts The reason I fear multiprogramming could be involved is that each Object A and Object is being added through an API save view, so a request to the view is made for each save, thus not a single request with multiple sequential saves on objects. It might be the case that Apache is creating a process for each request, and thus causing the problems I think I am seeing. As you would expect, the problem only occurs sometimes, which is characteristic of multiprogramming or multiprocessing errors. If this is the case, is there a way to make the test and set parts of the save() method a critical section, so that a process switch cannot happen between the test and the set?

    Read the article

  • Event sourcing: Write event before or after updating the model

    - by Magnus
    I'm reasoning about event sourcing and often I arrive at a chicken and egg problem. Would be grateful for some hints on how to reason around this. If I execute all I/O-bound processing async (ie writing to the event log) then how do I handle, or sometimes even detect, failures? I'm using Akka Actors so processing is sequential for each event/message. I do not have any database at this time, instead I would persist all the events in an event log and then keep an aggregated state of all the events in a model stored in memory. Queries are all against this model, you can consider it to be a cache. Example Creating a new user: Validate that the user does not exist in model Persist event to journal Update model (in memory) If step 3 breaks I still have persisted my event so I can replay it at a later date. If step 2 breaks I can handle that as well gracefully. This is fine, but since step 2 is I/O-bound I figured that I should do I/O in a separate actor to free up the first actor for queries: Updating a user while allowing queries (A0 = Front end/GUI actor, A1 = Processor Actor, A2 = IO-actor, E = event bus). (A0-E-A1) Event is published to update user 'U1'. Validate that the user 'U1' exists in model (A1-A2) Persist event to journal (separate actor) (A0-E-A1-A0) Query for user 'U1' profile (A2-A1) Event is now persisted continue to update model (A0-E-A1-A0) Query for user 'U1' profile (now returns fresh data) This is appealing since queries can be processed while I/O-is churning along at it's own pace. But now I can cause myself all kinds of problems where I could have two incompatible commands (delete and then update) be persisted to the event log and crash on me when replayed up at a later date, since I do the validation before persisting the event and then update the model. My aim is to have a simple reasoning around my model (since Actor processes messages sequentially single threaded) but not be waiting for I/O-bound updates when Querying. I get the feeling I'm modeling a database which in itself is might be a problem. If things are unclear please write a comment.

    Read the article

  • java.util.zip - ZipInputStream v.s. ZipFile

    - by lucho
    Hello, community! I have some general questions regarding the java.util.zip library. What we basically do is an import and an export of many small components. Previously these components were imported and exported using a single big file, e.g.: <component-type-a id="1"/> <component-type-a id="2"/> <component-type-a id="N"/> <component-type-b id="1"/> <component-type-b id="2"/> <component-type-b id="N"/> Please note that the order of the components during import is relevant. Now every component should occupy its own file which should be externally versioned, QA-ed, bla, bla. We decided that the output of our export should be a zip file (with all these files in) and the input of our import should be a similar zip file. We do not want to explode the zip in our system. We do not want opening separate streams for each of the small files. My current questions: Q1. May the ZipInputStream guarantee that the zip entries (the little files) will be read in the same order in which they were inserted by our export that uses ZipOutputStream? I assume reading is something like: ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis)); ZipEntry entry; while((entry = zis.getNextEntry()) != null) { //read from zis until available } I know that the central zip directory is put at the end of the zip file but nevertheless the file entries inside have sequential order. I also know that relying on the order is an ugly idea but I just want to have all the facts in mind. Q2. If I use ZipFile (which I prefer) what is the performance impact of calling getInputStream() hundreds of times? Will it be much slower than the ZipInputStream solution? The zip is opened only once and ZipFile is backed by RandomAccessFile - is this correct? I assume reading is something like: ZipFile zipfile = new ZipFile(argv[0]); Enumeration e = zipfile.entries();//TODO: assure the order of the entries while(e.hasMoreElements()) { entry = (ZipEntry) e.nextElement(); is = zipfile.getInputStream(entry)); } Q3. Are the input streams retrieved from the same ZipFile thread safe (e.g. may I read different entries in different threads simultaneously)? Any performance penalties? Thanks for your answers!

    Read the article

  • PInvokeStackImbalance C# call to unmanaged C++ function

    - by user287498
    After switching to VS2010, the managed debug assistant is displaying an error about an unbalanced stack from a call to an unmanaged C++ function from a C# application. The usuals suspects don't seem to be causing the issue. Is there something else I should check? The VS2008 built C++ dll and C# application never had a problem, no weird or mysterious bugs - yeah, I know that doesn't mean much. Here are the things that were checked: The dll name is correct. The entry point name is correct and has been verified with depends.exe - the code has to use the mangled name and it does. The calling convention is correct. The sizes and types all seem to be correct. The character set is correct. There doesn't seem to be any issues after ignoring the error and there isn't an issue when running outside the debugger. C#: [DllImport("Correct.dll", EntryPoint = "SuperSpecialOpenFileFunc", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi, ExactSpelling = true)] public static extern short SuperSpecialOpenFileFunc(ref SuperSpecialStruct stuff); [StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Ansi)] public struct SuperSpecialStruct { public int field1; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)] public string field2; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 20)] public string field3; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 10)] public string field4; public ushort field5; public ushort field6; public ushort field7; public short field8; public short field9; public uint field10; public short field11; }; C++: short SuperSpecialOpenFileFunc(SuperSpecialStruct * stuff); struct SuperSpecialStruct { int field1; char field2[256]; char field3[20]; char field4[10]; unsigned short field5; unsigned short field6; unsigned short field7; short field8; short field9; unsigned int field10; short field11; }; Here is the error: Managed Debugging Assistant 'PInvokeStackImbalance' has detected a problem in 'Managed application path'. Additional Information: A call to PInvoke function 'SuperSpecialOpenFileFunc' has unbalanced the stack. This is likely because the managed PInvoke signature does not match the unmanaged target signature. Check that the calling convention and parameters of the PInvoke signature match the target unmanaged signature.

    Read the article

  • how to create a system-wide independent universal counter object primarily for Database keys?

    - by andora
    I would like to create/use a system-wide independent universal 'counter object' that can be called via COM in a thread-safe manner. The counter object will be passed an ID to identify which counter to return, handle the counting, 'persist' the count (occasionally), have reasonable performance (as fast as possible) perhaps capable of 1000 counts per second or better (1mS) and be accessible cross-process/out-of-process. The current count status must be persisted between object restarts/shutdowns. The counter object is liklely to be a 'singleton' type object implemented in some form of free-threaded dictionary, containing maybe 10 counters (perhaps 50 max). The count needs to be monotonic and consistent, (ie: guaranteed unique sequential values). Each counter should have a few methods, like reset, inc, dec, set, clear, remove. As a luxury, I would like to have a variable-increment (ie: 'step by' value). To support thread-safefty, perhaps some sorm of critical-section or mutex call. It just needs to return a long/4byte signed integer. I really want something that can be called from anywhere, including VBScript, so I figure COM is my preferred solution. The primary use of this is for database keys. I am unable to use autoinc or guid type keys and have ruled out database-generated counting systems at this point. I've spent days researching this and I have really struggled to find a solution. The best I can find is a free-threaded dictionary object that can be instantiated using COM+ from Motobit - it seems to offer all the 'basics' and I guess I could create some form of wrapper for this. So, here are my questions: Does such a 'general purpose counter-object already exist? Can you direct me to it? (MS did do an IIS/ASP object called 'MSWC.Counter' but this isn't 'cross-process'/ out-of-process component and isn't thread-safe. (but if it was, it would do!) What is the best way of creating such a Component? (I'd prefer VB6 right-now, [don't ask!] but can do in VB.NET2005 if I had to). I don't have the skills/knowledge/tools to use anything else. I am desparate for a workable solution. I need specific guidance! If anybody can code something up for me I am prepared to pay for it.

    Read the article

< Previous Page | 13 14 15 16 17 18 19 20 21  | Next Page >