Search Results

Search found 332 results on 14 pages for 'cb'.

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

  • Labels aren't shown properly in combo box

    - by Vishal
    The below code show the labels from previously selected list any ideas? Steps to reproduce: Click on List AB Open the list but don't select / click any item Now click on List CD Open the list again and you see A, B as labels instead of C,D but if you click on any item then everything comes properly <mx:Script> <![CDATA[ import mx.collections.ArrayCollection; public var ab:ArrayCollection=new ArrayCollection([{label: A, data: 1}, {label: B, data: 2}]); public var cd:ArrayCollection=new ArrayCollection([{label: C, data: 3}, {label: D, data: 4}]); private function abClick(event:Event):void { cb.dataProvider=ab; } private function cdClick(event:Event):void { cb.dataProvider=cd; } ]]> </mx:Script> <mx:Panel title="ComboBox Control Example" height="75%" width="75%" layout="horizontal" paddingTop="10" paddingBottom="10" paddingLeft="10" paddingRight="10"> <mx:ComboBox id="cb" width="150"/> <mx:Button label="List AB" click="abClick(event);"/> <mx:Button label="List CD" click="cdClick(event);"/> </mx:Panel>

    Read the article

  • callback on a variable which is inside a .each() loop

    - by Stoic
    I have this function, which is doing an asynchronous call to FB.api method. Now, i am looping over some data and capturing result of the above method call successfully. However, I am using a .each loop and I really can not figure out how to place my callback in this method, so that the outer method is only executed once. Here are the functions I am using: ask_for_perms($(this).val(),function(result) { $('#some-div').html('<a onclick = "get_perms(result);" >get perms</a>'); }); function ask_for_perms(perms_requested,cb) { var request = []; $.each(perms_requested,function(i,permission) { FB.api({ method: 'users.hasAppPermission', ext_perm: permission }, function(response) { if (response == 0) request.push(permission); request.join(','); cb(request); // cb is called many times here. }); }); } I am trying to return the request string from ask_for_perms function. Can anyone suggest me on where to place a proper callback to ask_for_perms. Right now, however, it works for me, but the callback is being called many times since it is inside a for loop. referencing: returning a variable from the callback of a function

    Read the article

  • Relating text fields to check boxes in Java

    - by Finzz
    This program requires the user to login and request a database to access. The program then gets a connection object, searches through the database storing the column names into a vector for later use. The problem comes with implementing text fields to allow the user to search for specific values within the database. I can get the check boxes and text fields to appear using a gridlayout and add them to a panel. How do I relate the text fields to their appropriate check box? I've tried adding them to a vector, but then they can't also be added to the panel as well. I've searched for a way to name the text fields as the loop cycles through the column names, but it seems impossible to do without having them declared ahead of time. This can't be done either, as it's impossible to determine the attributes that the user will request. I just need to be able to know the names of the text fields so I can test to see if the user entered information and perform the necessary logic. Let me know if you have to see the rest of the code to give an answer, but hopefully you get the general idea of what I'm trying to accomplish. Picture of UI: try { ResultSet r2 = con.getMetaData().getColumns("", "", rb.getText(), ""); colNames1 = new Vector<String>(); columns1 = new Vector<JCheckBox>(); while (r2.next()) { colNames1.add(r2.getString(4)); JCheckBox cb = new JCheckBox(r2.getString(4)); JTextField tf = new JTextField(10); columns1.add(cb); p3.add(cb); p3.add(tf); } }

    Read the article

  • Div Container Cleanup?

    - by Nto
    Just wondering if its possible to cleanup (less code needed to do the same thing) making this div container. Basically it's just a div with a background image however the top & bottom of the div have rounded graphical corners which is why I have a top, middle, and bottom div inside the container div. <div class="fbox"> <div class="ftop"></div> <div class="fmid"> Fullbox Text Goes Here </div> <div class="fbot"></div> </div> Css: .fbox { width: 934px; margin: 0 auto; opacity: 0.70; } .ftop { width: 934px; background:url(../images/cb/full.png) no-repeat 0 -34px; height: 17px; margin:0 } .fmid { width: 894px; padding-left: 20px; padding-right: 20px; background:url(../images/cb/fullmid.png) repeat-y; min-height: 50px; margin:0 } .fbot { width: 934px; background:url(../images/cb/full.png) no-repeat 0 -17px; height: 17px; margin:0 } Outcome: http://img709.imageshack.us/img709/6681/fbox.jpg

    Read the article

  • InputStreamBody in HttpMime 4.0.3 settings for content-length

    - by Ram
    I am trying to send a multi part formdata post through my java code. Can someone tell me how to set Content Length in the following?? There seem to be headers involved when we use InputStreamBody which implements the ContentDescriptor interface. Doing a getContentLength on the InputStreamBody gives me -1 after i add the content. I subclassed it to give contentLength the length of my byte array but am not sure if other headers required by ContentDescriptor will be set for a proper POST. HttpClient httpclient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(myURL); ContentBody cb = new InputStreamBody(new ByteArrayInputStream(bytearray), myMimeType, filename); //ContentBody cb = new ByteArrayBody(bytearray, myMimeType, filename); MultipartEntity mpentity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); mpentity.addPart("key", new StringBody("SOME_KEY")); mpentity.addPart("output", new StringBody("SOME_NAME")); mpentity.addPart("content", cb); httpPost.setEntity(mpentity); HttpResponse response = httpclient.execute(httpPost); HttpEntity resEntity = response.getEntity();

    Read the article

  • ASP.NET 'Check all checkboxes' control

    - by RUiHAO
    I am using visual studio 2005 c#, and doing server side coding. I have a list of checkboxes in my gridview via checkbox template. I have tried to assign a checkbox in my header template, and assigned a checkbox_checkchange method to make it such that when the checkbox at the header is checked, the list of checkboxes in the template will be checked as well. However, it does not work and I am not able to spot the mistake. Below is my code for my checkbox in header template: protected void CheckAllCB_CheckedChanged(object sender, EventArgs e) { CheckBox chk = (CheckBox)GridView1.HeaderRow.FindControl("CheckAll"); if (chk.Checked) { for (int i = 0; i < GridView1.Rows.Count; i++) { CheckBox chkrow = (CheckBox)GridView1.Rows[i].FindControl("UserSelector"); chkrow.Checked = true; } } else { for (int i = 0; i < GridView1.Rows.Count; i++) { CheckBox chkrow = (CheckBox)GridView1.Rows[i].FindControl("UserSelector"); chkrow.Checked = false; } } } Thus I tried using a button to assign the checkall command instead. However, when I clicked on the button, the page does nothing but just refreshes itself. Below is my code for the checkall and uncheckall button: private void ToggleCheckState(bool checkState) { // Iterate through the Products.Rows property foreach (GridViewRow row in GridView1.Rows) { // Access the CheckBox CheckBox cb = (CheckBox)row.FindControl("UserSelector"); if (cb != null) cb.Checked = checkState; } } protected void CheckAll_Click(object sender, EventArgs e) { ToggleCheckState(true); } protected void UncheckAll_Click(object sender, EventArgs e) { ToggleCheckState(false); } Anyone can help me identify the mistake I did in my method? Thank you UserSelection GridView template:

    Read the article

  • Syncing Data with a Server using Silverlight and HTTP Polling Duplex

    - by dwahlin
    Many applications have the need to stay in-sync with data provided by a service. Although web applications typically rely on standard polling techniques to check if data has changed, Silverlight provides several interesting options for keeping an application in-sync that rely on server “push” technologies. A few years back I wrote several blog posts covering different “push” technologies available in Silverlight that rely on sockets or HTTP Polling Duplex. We recently had a project that looked like it could benefit from pushing data from a server to one or more clients so I thought I’d revisit the subject and provide some updates to the original code posted. If you’ve worked with AJAX before in Web applications then you know that until browsers fully support web sockets or other duplex (bi-directional communication) technologies that it’s difficult to keep applications in-sync with a server without relying on polling. The problem with polling is that you have to check for changes on the server on a timed-basis which can often be wasteful and take up unnecessary resources. With server “push” technologies, data can be pushed from the server to the client as it changes. Once the data is received, the client can update the user interface as appropriate. Using “push” technologies allows the client to listen for changes from the data but stay 100% focused on client activities as opposed to worrying about polling and asking the server if anything has changed. Silverlight provides several options for pushing data from a server to a client including sockets, TCP bindings and HTTP Polling Duplex.  Each has its own strengths and weaknesses as far as performance and setup work with HTTP Polling Duplex arguably being the easiest to setup and get going.  In this article I’ll demonstrate how HTTP Polling Duplex can be used in Silverlight 4 applications to push data and show how you can create a WCF server that provides an HTTP Polling Duplex binding that a Silverlight client can consume.   What is HTTP Polling Duplex? Technologies that allow data to be pushed from a server to a client rely on duplex functionality. Duplex (or bi-directional) communication allows data to be passed in both directions.  A client can call a service and the server can call the client. HTTP Polling Duplex (as its name implies) allows a server to communicate with a client without forcing the client to constantly poll the server. It has the benefit of being able to run on port 80 making setup a breeze compared to the other options which require specific ports to be used and cross-domain policy files to be exposed on port 943 (as with sockets and TCP bindings). Having said that, if you’re looking for the best speed possible then sockets and TCP bindings are the way to go. But, they’re not the only game in town when it comes to duplex communication. The first time I heard about HTTP Polling Duplex (initially available in Silverlight 2) I wasn’t exactly sure how it was any better than standard polling used in AJAX applications. I read the Silverlight SDK, looked at various resources and generally found the following definition unhelpful as far as understanding the actual benefits that HTTP Polling Duplex provided: "The Silverlight client periodically polls the service on the network layer, and checks for any new messages that the service wants to send on the callback channel. The service queues all messages sent on the client callback channel and delivers them to the client when the client polls the service." Although the previous definition explained the overall process, it sounded as if standard polling was used. Fortunately, Microsoft’s Scott Guthrie provided me with a more clear definition several years back that explains the benefits provided by HTTP Polling Duplex quite well (used with his permission): "The [HTTP Polling Duplex] duplex support does use polling in the background to implement notifications – although the way it does it is different than manual polling. It initiates a network request, and then the request is effectively “put to sleep” waiting for the server to respond (it doesn’t come back immediately). The server then keeps the connection open but not active until it has something to send back (or the connection times out after 90 seconds – at which point the duplex client will connect again and wait). This way you are avoiding hitting the server repeatedly – but still get an immediate response when there is data to send." After hearing Scott’s definition the light bulb went on and it all made sense. A client makes a request to a server to check for changes, but instead of the request returning immediately, it parks itself on the server and waits for data. It’s kind of like waiting to pick up a pizza at the store. Instead of calling the store over and over to check the status, you sit in the store and wait until the pizza (the request data) is ready. Once it’s ready you take it back home (to the client). This technique provides a lot of efficiency gains over standard polling techniques even though it does use some polling of its own as a request is initially made from a client to a server. So how do you implement HTTP Polling Duplex in your Silverlight applications? Let’s take a look at the process by starting with the server. Creating an HTTP Polling Duplex WCF Service Creating a WCF service that exposes an HTTP Polling Duplex binding is straightforward as far as coding goes. Add some one way operations into an interface, create a client callback interface and you’re ready to go. The most challenging part comes into play when configuring the service to properly support the necessary binding and that’s more of a cut and paste operation once you know the configuration code to use. To create an HTTP Polling Duplex service you’ll need to expose server-side and client-side interfaces and reference the System.ServiceModel.PollingDuplex assembly (located at C:\Program Files (x86)\Microsoft SDKs\Silverlight\v4.0\Libraries\Server on my machine) in the server project. For the demo application I upgraded a basketball simulation service to support the latest polling duplex assemblies. The service simulates a simple basketball game using a Game class and pushes information about the game such as score, fouls, shots and more to the client as the game changes over time. Before jumping too far into the game push service, it’s important to discuss two interfaces used by the service to communicate in a bi-directional manner. The first is called IGameStreamService and defines the methods/operations that the client can call on the server (see Listing 1). The second is IGameStreamClient which defines the callback methods that a server can use to communicate with a client (see Listing 2).   [ServiceContract(Namespace = "Silverlight", CallbackContract = typeof(IGameStreamClient))] public interface IGameStreamService { [OperationContract(IsOneWay = true)] void GetTeamData(); } Listing 1. The IGameStreamService interface defines server operations that can be called on the server.   [ServiceContract] public interface IGameStreamClient { [OperationContract(IsOneWay = true)] void ReceiveTeamData(List<Team> teamData); [OperationContract(IsOneWay = true, AsyncPattern=true)] IAsyncResult BeginReceiveGameData(GameData gameData, AsyncCallback callback, object state); void EndReceiveGameData(IAsyncResult result); } Listing 2. The IGameStreamClient interfaces defines client operations that a server can call.   The IGameStreamService interface is decorated with the standard ServiceContract attribute but also contains a value for the CallbackContract property.  This property is used to define the interface that the client will expose (IGameStreamClient in this example) and use to receive data pushed from the service. Notice that each OperationContract attribute in both interfaces sets the IsOneWay property to true. This means that the operation can be called and passed data as appropriate, however, no data will be passed back. Instead, data will be pushed back to the client as it’s available.  Looking through the IGameStreamService interface you can see that the client can request team data whereas the IGameStreamClient interface allows team and game data to be received by the client. One interesting point about the IGameStreamClient interface is the inclusion of the AsyncPattern property on the BeginReceiveGameData operation. I initially created this operation as a standard one way operation and it worked most of the time. However, as I disconnected clients and reconnected new ones game data wasn’t being passed properly. After researching the problem more I realized that because the service could take up to 7 seconds to return game data, things were getting hung up. By setting the AsyncPattern property to true on the BeginReceivedGameData operation and providing a corresponding EndReceiveGameData operation I was able to get around this problem and get everything running properly. I’ll provide more details on the implementation of these two methods later in this post. Once the interfaces were created I moved on to the game service class. The first order of business was to create a class that implemented the IGameStreamService interface. Since the service can be used by multiple clients wanting game data I added the ServiceBehavior attribute to the class definition so that I could set its InstanceContextMode to InstanceContextMode.Single (in effect creating a Singleton service object). Listing 3 shows the game service class as well as its fields and constructor.   [ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple, InstanceContextMode = InstanceContextMode.Single)] public class GameStreamService : IGameStreamService { object _Key = new object(); Game _Game = null; Timer _Timer = null; Random _Random = null; Dictionary<string, IGameStreamClient> _ClientCallbacks = new Dictionary<string, IGameStreamClient>(); static AsyncCallback _ReceiveGameDataCompleted = new AsyncCallback(ReceiveGameDataCompleted); public GameStreamService() { _Game = new Game(); _Timer = new Timer { Enabled = false, Interval = 2000, AutoReset = true }; _Timer.Elapsed += new ElapsedEventHandler(_Timer_Elapsed); _Timer.Start(); _Random = new Random(); }} Listing 3. The GameStreamService implements the IGameStreamService interface which defines a callback contract that allows the service class to push data back to the client. By implementing the IGameStreamService interface, GameStreamService must supply a GetTeamData() method which is responsible for supplying information about the teams that are playing as well as individual players.  GetTeamData() also acts as a client subscription method that tracks clients wanting to receive game data.  Listing 4 shows the GetTeamData() method. public void GetTeamData() { //Get client callback channel var context = OperationContext.Current; var sessionID = context.SessionId; var currClient = context.GetCallbackChannel<IGameStreamClient>(); context.Channel.Faulted += Disconnect; context.Channel.Closed += Disconnect; IGameStreamClient client; if (!_ClientCallbacks.TryGetValue(sessionID, out client)) { lock (_Key) { _ClientCallbacks[sessionID] = currClient; } } currClient.ReceiveTeamData(_Game.GetTeamData()); //Start timer which when fired sends updated score information to client if (!_Timer.Enabled) { _Timer.Enabled = true; } } Listing 4. The GetTeamData() method subscribes a given client to the game service and returns. The key the line of code in the GetTeamData() method is the call to GetCallbackChannel<IGameStreamClient>().  This method is responsible for accessing the calling client’s callback channel. The callback channel is defined by the IGameStreamClient interface shown earlier in Listing 2 and used by the server to communicate with the client. Before passing team data back to the client, GetTeamData() grabs the client’s session ID and checks if it already exists in the _ClientCallbacks dictionary object used to track clients wanting callbacks from the server. If the client doesn’t exist it adds it into the collection. It then pushes team data from the Game class back to the client by calling ReceiveTeamData().  Since the service simulates a basketball game, a timer is then started if it’s not already enabled which is then used to randomly send data to the client. When the timer fires, game data is pushed down to the client. Listing 5 shows the _Timer_Elapsed() method that is called when the timer fires as well as the SendGameData() method used to send data to the client. void _Timer_Elapsed(object sender, ElapsedEventArgs e) { int interval = _Random.Next(3000, 7000); lock (_Key) { _Timer.Interval = interval; _Timer.Enabled = false; } SendGameData(_Game.GetGameData()); } private void SendGameData(GameData gameData) { var cbs = _ClientCallbacks.Where(cb => ((IContextChannel)cb.Value).State == CommunicationState.Opened); for (int i = 0; i < cbs.Count(); i++) { var cb = cbs.ElementAt(i).Value; try { cb.BeginReceiveGameData(gameData, _ReceiveGameDataCompleted, cb); } catch (TimeoutException texp) { //Log timeout error } catch (CommunicationException cexp) { //Log communication error } } lock (_Key) _Timer.Enabled = true; } private static void ReceiveGameDataCompleted(IAsyncResult result) { try { ((IGameStreamClient)(result.AsyncState)).EndReceiveGameData(result); } catch (CommunicationException) { // empty } catch (TimeoutException) { // empty } } LIsting 5. _Timer_Elapsed is used to simulate time in a basketball game. When _Timer_Elapsed() fires the SendGameData() method is called which iterates through the clients wanting to be notified of changes. As each client is identified, their respective BeginReceiveGameData() method is called which ultimately pushes game data down to the client. Recall that this method was defined in the client callback interface named IGameStreamClient shown earlier in Listing 2. Notice that BeginReceiveGameData() accepts _ReceiveGameDataCompleted as its second parameter (an AsyncCallback delegate defined in the service class) and passes the client callback as the third parameter. The initial version of the sample application had a standard ReceiveGameData() method in the client callback interface. However, sometimes the client callbacks would work properly and sometimes they wouldn’t which was a little baffling at first glance. After some investigation I realized that I needed to implement an asynchronous pattern for client callbacks to work properly since 3 – 7 second delays are occurring as a result of the timer. Once I added the BeginReceiveGameData() and ReceiveGameDataCompleted() methods everything worked properly since each call was handled in an asynchronous manner. The final task that had to be completed to get the server working properly with HTTP Polling Duplex was adding configuration code into web.config. In the interest of brevity I won’t post all of the code here since the sample application includes everything you need. However, Listing 6 shows the key configuration code to handle creating a custom binding named pollingDuplexBinding and associate it with the service’s endpoint.   <bindings> <customBinding> <binding name="pollingDuplexBinding"> <binaryMessageEncoding /> <pollingDuplex maxPendingSessions="2147483647" maxPendingMessagesPerSession="2147483647" inactivityTimeout="02:00:00" serverPollTimeout="00:05:00"/> <httpTransport /> </binding> </customBinding> </bindings> <services> <service name="GameService.GameStreamService" behaviorConfiguration="GameStreamServiceBehavior"> <endpoint address="" binding="customBinding" bindingConfiguration="pollingDuplexBinding" contract="GameService.IGameStreamService"/> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" /> </service> </services>   Listing 6. Configuring an HTTP Polling Duplex binding in web.config and associating an endpoint with it. Calling the Service and Receiving “Pushed” Data Calling the service and handling data that is pushed from the server is a simple and straightforward process in Silverlight. Since the service is configured with a MEX endpoint and exposes a WSDL file, you can right-click on the Silverlight project and select the standard Add Service Reference item. After the web service proxy is created you may notice that the ServiceReferences.ClientConfig file only contains an empty configuration element instead of the normal configuration elements created when creating a standard WCF proxy. You can certainly update the file if you want to read from it at runtime but for the sample application I fed the service URI directly to the service proxy as shown next: var address = new EndpointAddress("http://localhost.:5661/GameStreamService.svc"); var binding = new PollingDuplexHttpBinding(); _Proxy = new GameStreamServiceClient(binding, address); _Proxy.ReceiveTeamDataReceived += _Proxy_ReceiveTeamDataReceived; _Proxy.ReceiveGameDataReceived += _Proxy_ReceiveGameDataReceived; _Proxy.GetTeamDataAsync(); This code creates the proxy and passes the endpoint address and binding to use to its constructor. It then wires the different receive events to callback methods and calls GetTeamDataAsync().  Calling GetTeamDataAsync() causes the server to store the client in the server-side dictionary collection mentioned earlier so that it can receive data that is pushed.  As the server-side timer fires and game data is pushed to the client, the user interface is updated as shown in Listing 7. Listing 8 shows the _Proxy_ReceiveGameDataReceived() method responsible for handling the data and calling UpdateGameData() to process it.   Listing 7. The Silverlight interface. Game data is pushed from the server to the client using HTTP Polling Duplex. void _Proxy_ReceiveGameDataReceived(object sender, ReceiveGameDataReceivedEventArgs e) { UpdateGameData(e.gameData); } private void UpdateGameData(GameData gameData) { //Update Score this.tbTeam1Score.Text = gameData.Team1Score.ToString(); this.tbTeam2Score.Text = gameData.Team2Score.ToString(); //Update ball visibility if (gameData.Action != ActionsEnum.Foul) { if (tbTeam1.Text == gameData.TeamOnOffense) { AnimateBall(this.BB1, this.BB2); } else //Team 2 { AnimateBall(this.BB2, this.BB1); } } if (this.lbActions.Items.Count > 9) this.lbActions.Items.Clear(); this.lbActions.Items.Add(gameData.LastAction); if (this.lbActions.Visibility == Visibility.Collapsed) this.lbActions.Visibility = Visibility.Visible; } private void AnimateBall(Image onBall, Image offBall) { this.FadeIn.Stop(); Storyboard.SetTarget(this.FadeInAnimation, onBall); Storyboard.SetTarget(this.FadeOutAnimation, offBall); this.FadeIn.Begin(); } Listing 8. As the server pushes game data, the client’s _Proxy_ReceiveGameDataReceived() method is called to process the data. In a real-life application I’d go with a ViewModel class to handle retrieving team data, setup data bindings and handle data that is pushed from the server. However, for the sample application I wanted to focus on HTTP Polling Duplex and keep things as simple as possible.   Summary Silverlight supports three options when duplex communication is required in an application including TCP bindins, sockets and HTTP Polling Duplex. In this post you’ve seen how HTTP Polling Duplex interfaces can be created and implemented on the server as well as how they can be consumed by a Silverlight client. HTTP Polling Duplex provides a nice way to “push” data from a server while still allowing the data to flow over port 80 or another port of your choice.   Sample Application Download

    Read the article

  • Can't clone gitosis-admin.git local from my snow leopard server running gitosis

    - by joggink
    I've installed gitosis as described here: http://gist.github.com/264304 One of the things that I had to adjust was to give my git user permissions to use ssh (which I did trough server admin - access - ssh and added the 'git' user). When I ssh from my local machine (mac osx) as the git user, I get this response: PTY allocation request failed on channel 0 bash: gitosis-serve: command not found Connection to 10.0.0.108 closed. Which I think is normal, because in Pro GIT the author says you should get something like this if you try ssh'ing to the server using your git user: PTY allocation request failed on channel 0 fatal: unrecognized command 'gitosis-serve schacon@quaternion' Connection to gitserver closed. So far so good, I think? Now when I try to clone my gitosis-admin.git repository using this command: $git clone [email protected]:gitosis-admin.git I get this: Initialized empty Git repository in /Users/joggink/gitosis-admin/.git/ bash: gitosis-serve: command not found fatal: The remote end hung up unexpectedly So after doing some searching, I found an answer here on serverfault claiming I should use ssh:// as protocol for my git clone (which I thought is the default git protocol?) However, when I try: $git clone ssh://[email protected]:gitosis-admin.git This is the response: The authenticity of host ' (::1)' can't be established. RSA key fingerprint is 80:4d:77:c7:78:cb:c9:42:e3:82:06:7c:fe:c0:08:ce. Are you sure you want to continue connecting (yes/no)? yes Warning: Permanently added '' (RSA) to the list of known hosts. Password: Password: Password: Permission denied (publickey,keyboard-interactive). fatal: The remote end hung up unexpectedly When I type in my own password (because my git user has no password), I get following error: The authenticity of host ' (::1)' can't be established. RSA key fingerprint is 80:4d:77:c7:78:cb:c9:42:e3:82:06:7c:fe:c0:08:ce. Are you sure you want to continue connecting (yes/no)? yes Warning: Permanently added '' (RSA) to the list of known hosts. Password: bash: git-upload-pack: command not found fatal: The remote end hung up unexpectedly I added my upload-pack location as followed: $git clone -u /usr/local/git/bin/git-upload-pack ssh://[email protected]:gitosis-admin.git I get the error that gitosis-admin.git isn't a git repo... Initialized empty Git repository in /Users/joggink/gitosis-admin/.git/ The authenticity of host ' (::1)' can't be established. RSA key fingerprint is 80:4d:77:c7:78:cb:c9:42:e3:82:06:7c:fe:c0:08:ce. Are you sure you want to continue connecting (yes/no)? yes Warning: Permanently added '' (RSA) to the list of known hosts. Password: fatal: '[email protected]:gitosis-admin.git' does not appear to be a git repository fatal: The remote end hung up unexpectedly I've been searching for a solution for almost a week now, and every topic I've found on the internet gives no result...

    Read the article

  • Android save Checkbox State in ListView with Cursor Adapter

    - by Ricardo
    I cant find a way to save the checkbox state when using a Cursor adapter. Everything else works fine but if i click on a checkbox it is repeated when it is recycled. Ive seen examples using array adapters but because of my lack of experience im finding it hard to translate it into using a cursor adapter. Could someone give me an example of how to go about it. Any help appreciated. private class PostImageAdapter extends CursorAdapter { private static final int s = 0; private int layout; Bitmap bm=null; private String PostNumber; TourDbAdapter mDbHelper; public PostImageAdapter (Context context, int layout, Cursor c, String[] from, int[] to, String Postid) { super(context, c); this.layout = layout; PostNumber = Postid; mDbHelper = new TourDbAdapter(context); mDbHelper.open(); } @Override public View newView(Context context, final Cursor c, ViewGroup parent) { ViewHolder holder; LayoutInflater inflater=getLayoutInflater(); View row=inflater.inflate(R.layout.image_post_row, null); holder = new ViewHolder(); holder.Description = (TextView) row.findViewById(R.id.item_desc); holder.cb = (CheckBox) row.findViewById(R.id.item_checkbox); holder.DateTaken = (TextView) row.findViewById(R.id.item_date_taken); holder.Photo = (ImageView) row.findViewById(R.id.item_thumb); row.setTag(holder); int DateCol = c.getColumnIndex(TourDbAdapter.KEY_DATE); String Date = c.getString(DateCol); int DescCol = c.getColumnIndex(TourDbAdapter.KEY_CAPTION); String Description = c.getString(DescCol); int FileNameCol = c.getColumnIndex(TourDbAdapter.KEY_FILENAME); final String FileName = c.getString(FileNameCol); int PostRowCol = c.getColumnIndex(TourDbAdapter.KEY_Post_ID); String RowID = c.getString(PostRowCol); String Path = "sdcard/Tourabout/Thumbs/" + FileName + ".jpg"; Bitmap bm = BitmapFactory.decodeFile(Path, null); holder.Photo.setImageBitmap(bm); holder.DateTaken.setText(Date); holder.Description.setText(Description); holder.cb.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { CheckBox cBox = (CheckBox) v; if (cBox.isChecked()) { mDbHelper.UpdatePostImage(FileName, PostNumber); } else if (!cBox.isChecked()) { mDbHelper.UpdatePostImage(FileName, ""); } } }); return row; }; @Override public void bindView(View row, Context context, final Cursor c) { ViewHolder holder; holder = (ViewHolder) row.getTag(); int DateCol = c.getColumnIndex(TourDbAdapter.KEY_DATE); String Date = c.getString(DateCol); int DescCol = c.getColumnIndex(TourDbAdapter.KEY_CAPTION); String Description = c.getString(DescCol); int FileNameCol = c.getColumnIndex(TourDbAdapter.KEY_FILENAME); final String FileName = c.getString(FileNameCol); int PostRowCol = c.getColumnIndex(TourDbAdapter.KEY_Post_ID); String RowID = c.getString(PostRowCol); String Path = "sdcard/Tourabout/Thumbs/" + FileName + ".jpg"; Bitmap bm = BitmapFactory.decodeFile(Path, null); File x = null; holder.Photo.setImageBitmap(bm); holder.DateTaken.setText(Date); holder.Description.setText(Description); holder.cb.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { CheckBox cBox = (CheckBox) v; if (cBox.isChecked()) { mDbHelper.UpdatePostImage(FileName, PostNumber); } else if (!cBox.isChecked()) { mDbHelper.UpdatePostImage(FileName, ""); } } }); } } static class ViewHolder{ TextView Description; ImageView Photo; CheckBox cb; TextView DateTaken; } }

    Read the article

  • Help deciphering exception details from WebRequestCreator when setting ContentType to "application/json"

    - by Stephen Patten
    Hello, This one is real simple, run this Silverlight4 example with the ContentType property commented out and you'll get back a response from from my service in xml. Now uncomment the property and run it and you'll get an exception similar to this one. System.Net.ProtocolViolationException occurred Message=A request with this method cannot have a request body. StackTrace: at System.Net.Browser.AsyncHelper.BeginOnUI(SendOrPostCallback beginMethod, Object state) at System.Net.Browser.ClientHttpWebRequest.EndGetResponse(IAsyncResult asyncResult) at com.patten.silverlight.ViewModels.WebRequestLiteViewModel.<MakeCall>b__0(IAsyncResult cb) InnerException: What I am trying to accomplish is just pulling down some JSON formatted data from my wcf endpoint. Can this really be this hard, or is it another classic example of just overlooking something simple. Edit: While perusing SO, I noticed similar posts, like this one Why am I getting ProtocolViolationException when trying to use HttpWebRequest? Thank you, Stephen try { Address = "http://stephenpattenconsulting.com/Services/GetFoodDescriptionsLookup(2100)"; // Get the URI Uri httpSite = new Uri(Address); // Create the request object using the Browsers networking stack // HttpWebRequest wreq = (HttpWebRequest)WebRequest.Create(httpSite); // Create the request using the operating system's networking stack HttpWebRequest wreq = (HttpWebRequest)WebRequestCreator.ClientHttp.Create(httpSite); // http://stackoverflow.com/questions/239725/c-webrequest-class-and-headers // These headers have been set, so use the property that has been exposed to change them // wreq.Headers[HttpRequestHeader.ContentType] = "application/json"; //wreq.ContentType = "application/json"; // Issue the async request. // http://timheuer.com/blog/archive/2010/04/23/silverlight-authorization-header-access.aspx wreq.BeginGetResponse((cb) => { HttpWebRequest rq = cb.AsyncState as HttpWebRequest; HttpWebResponse resp = rq.EndGetResponse(cb) as HttpWebResponse; StreamReader rdr = new StreamReader(resp.GetResponseStream()); string result = rdr.ReadToEnd(); Jounce.Framework.JounceHelper.ExecuteOnUI(() => { Result = result; }); rdr.Close(); }, wreq); } catch (WebException ex) { Jounce.Framework.JounceHelper.ExecuteOnUI(() => { Error = ex.Message; }); } catch (Exception ex) { Jounce.Framework.JounceHelper.ExecuteOnUI(() => { Error = ex.Message; }); } EDIT: This is how the WCF 4 end point is configured, primarily 'adapted' from this link http://geekswithblogs.net/michelotti/archive/2010/08/21/restful-wcf-services-with-no-svc-file-and-no-config.aspx [ServiceContract] public interface IRDA { [OperationContract] IList<FoodDescriptionLookup> GetFoodDescriptionsLookup(String id); [OperationContract] FOOD_DES GetFoodDescription(String id); [OperationContract] FOOD_DES InsertFoodDescription(FOOD_DES foodDescription); [OperationContract] FOOD_DES UpdateFoodDescription(String id, FOOD_DES foodDescription); [OperationContract] void DeleteFoodDescription(String id); } // RESTfull service [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] public class RDAService : IRDA { [WebGet(UriTemplate = "FoodDescription({id})")] public FOOD_DES GetFoodDescription(String id) { ... } [AspNetCacheProfile("GetFoodDescriptionsLookup")] [WebGet(UriTemplate = "GetFoodDescriptionsLookup({id})")] public IList<FoodDescriptionLookup> GetFoodDescriptionsLookup(String id) { return rda.GetFoodDescriptionsLookup(id); ; } [WebInvoke(UriTemplate = "FoodDescription", Method = "POST")] public FOOD_DES InsertFoodDescription(FOOD_DES foodDescription) { ... } [WebInvoke(UriTemplate = "FoodDescription({id})", Method = "PUT")] public FOOD_DES UpdateFoodDescription(String id, FOOD_DES foodDescription) { ... } [WebInvoke(UriTemplate = "FoodDescription({id})", Method = "DELETE")] public void DeleteFoodDescription(String id) { ... } } And the portion of my web.config that pertains to WCF <system.serviceModel> <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" /> <standardEndpoints> <webHttpEndpoint> <standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true" /> </webHttpEndpoint> </standardEndpoints> </system.serviceModel>

    Read the article

  • Unit Tests as a learning tool - a good idea?

    - by Ekkehard.Horner
    I'm interested in ways and means for learning (a) programming language(s) efficiently. I believe that using Unit Test concepts and infrastructure early in that process is a good thing, even better than starting with "Hello world". Why: To write a decent program even for a toy/restricted problem in a new language, you'll have to master many heterogenous concepts (control flow & variables & IO ...), you are tempted to glance over details just to get your program 'to work'. Putting (your understanding of) the facts about the new language in assertions with good descriptions (=success messages) enforces thinking thru/clearness/precision. Grouping topics and adding assertions to such groups is much easier than incorporation features from the 2. chapter of your "Learning X" book to your chapter 1 program. Why not: 'Real' Unit Tests are meant to output "1234 tests ok; 1 failure: saveWorld() chokes on negative input"; 'didactic' Unit Tests should output relevant facts about the new language like perl6 10-string.t # ### p5chop ... ok 13 - p5chop( "cbä" ) returns "ä" ok 14 - after that, victim is changed to "cb" # ### (p6) chop ... ok 27 - (p6) chop( "cbä" ) returns chopped copy: "cb" ok 18 - after that, victim is unchanged: "cbä" # ### chomp ... So (mis?)using Unit Tests may be counterproductive - practicing actions while learning you wouldn't use professionally. How: Writing 'didactic' Unit Tests in languages with lightweight testing systems (Perl 5/6) is easy; (mis?)using more elaborate systems (JUnit, CppUnit) may be not worth the effort or not suitable for a person just starting with a new language. So Is using Unit Tests as a learning tool a bad idea? Can the Unit Test tool(s) of your favourite language(s) used didactically? Should implementation details (eventually) be discussed here or over at stackoverflow.com?

    Read the article

  • Broken corba object references

    - by cube
    I'm working on a homework and got stuck. The task is to serve objects using a default servant. But when I try to use the reference, weird things happen. Some part of corba prints a stack trace, but no exception is thrown. The problem happens when the server receives the reference and should call some method on it. The reference is then shortened and doesn't contain the object ID (which means that my servant implementation can't do anything reasonable). This is the implementation of the servant, where the problem appears: public class ModelFileImpl extends ModelFilePOA{ @Override public String getName() { try { return new String(_poa().reference_to_id(_this_object())); } catch (Throwable e) {} assert false; return null; } } If I take _this_object().toString() inside the try block and put it into dior -i i get this: ------IOR components----- TypeId : IDL:termproject/idl/ModelFile:1.0 TAG_INTERNET_IOP Profiles: Profile Id: 0 IIOP Version: 1.2 Host: 127.0.0.1 Port: 45954 Object key (URL): %AF%AB%CB%00%00%00%00%20Q%BA%F4%FF%00%00%00%01%00%00%00%00%00%00%00%01%0000%00%08RootPOA%00%00%00%00%08%00%00%00%02%00%00%00%00%14 Object key (hex): 0xAF AB CB 00 00 00 00 20 51 BA F4 FF 00 00 00 01 00 00 00 00 00 00 00 01 00 00 00 08 52 6F 6F 74 50 4F 41 00 00 00 00 08 00 00 00 02 00 00 00 00 14 -- Found 2 Tagged Components-- #0: TAG_CODE_SETS ForChar native code set Id: ISO8859_1 Char Conversion Code Sets: UTF8 , Unknown TCS: 10020 ForWChar native code set Id: UTF16 WChar Conversion Code Sets: Unknown TCS: 10100 Unknown tag : 38 however the part of server that makes the reference and the client see the reference as ------IOR components----- TypeId : IDL:termproject/idl/ModelFile:1.0 TAG_INTERNET_IOP Profiles: Profile Id: 0 IIOP Version: 1.2 Host: 127.0.0.1 Port: 45954 Object key (URL): %AF%AB%CB%00%00%00%00%20Q%BA%F4%FF%00%00%00%01%00%00%00%00%00%00%00%02%00%00%00%08RootPOA%00%00%00%00%09modelPoa%00%00%00%00%00%00%00%10testModel1.MyIDL%14 Object key (hex): 0xAF AB CB 00 00 00 00 20 51 BA F4 FF 00 00 00 01 00 00 00 00 00 00 00 02 00 00 00 08 52 6F 6F 74 50 4F 41 00 00 00 00 09 6D 6F 64 65 6C 50 6F 61 00 00 00 00 00 00 00 10 74 65 73 74 4D 6F 64 65 6C 31 2E 4D 79 49 44 4C 14 -- Found 2 Tagged Components-- #0: TAG_CODE_SETS ForChar native code set Id: ISO8859_1 Char Conversion Code Sets: UTF8 , Unknown TCS: 10020 ForWChar native code set Id: UTF16 WChar Conversion Code Sets: Unknown TCS: 10100 Unknown tag : 38 ("modelPoa" (the name of the poa working with default clients) and "testModel1.MyIDL" (the identifier of the object) in the object key are missing in the first one) I've tried sniffing the traffic and found out that the client still sends the correct reference. This is how i create the references: ret[i] = ModelFileHelper.narrow(modelFilePoa.create_reference_with_id(files[i].getBytes(), ModelFileHelper.id())); And this is how i set up the server: // init ORB ORB orb = ORB.init(args, null); // init POA POA poa = POAHelper.narrow(orb.resolve_initial_references("RootPOA")); // create the POA for the models. Policy[] policies = { poa.create_request_processing_policy(RequestProcessingPolicyValue.USE_DEFAULT_SERVANT), poa.create_servant_retention_policy(ServantRetentionPolicyValue.NON_RETAIN), poa.create_id_assignment_policy(IdAssignmentPolicyValue.USER_ID) }; POA modelPoa = poa.create_POA("modelPoa", poa.the_POAManager(), policies); modelPoa.the_POAManager().activate(); modelPoa.set_servant(new ModelFileImpl()); modelPoa.the_POAManager().activate(); ModelStoreImpl impl = new ModelStoreImpl(modelPoa); // create the object reference org.omg.CORBA.Object obj = poa.servant_to_reference(impl); // ... store the IOR file ... orb.run(); I'd be really grateful for any pointers (or references :-) )

    Read the article

  • FB.ui and setting popup size

    - by manuelpedrera
    I am using FB.ui with the display parameter set to popup. When the method is 'stream.publish', it autoresizes when the content is loaded. However, when using 'fbml.dialog' (in order to display a multi-friend selector) it shows a size that I'm not able to change (and the content is displayed cropped). I have tried with the following approaches, with no luck: FB.ui({ method: 'fbml.dialog', size: {width: 800, height: 500}, ... FB.ui({ method: 'fbml.dialog', width: 800, height: 500, ... Also I've been looking at the API source code, and it declares the method this way: Method declaration: 'fbml.dialog': { size : { width: 575, height: 300 }, url : 'render_fbml.php', loggedOutIframe : true }... Functions that executes the methods: // the basic call data var call = { cb : cb, id : id, size : method.size || {}, url : FB._domain.www + method.url, params : params }; Any help would be much appreciated...

    Read the article

  • In JPA 2, using a CriteriaQuery, how to count results

    - by seanizer
    I am rather new to JPA 2 and it's CriteriaBuilder / CriteriaQuery API: http://java.sun.com/javaee/6/docs/api/javax/persistence/criteria/CriteriaQuery.html http://java.sun.com/javaee/6/docs/tutorial/doc/gjivm.html I would like to count the results of a CriteriaQuery without actually retrieving them. Is that possible, I did not find any such method, the only way would be to do this: CriteriaBuilder cb = entityManager.getCriteriaBuilder(); CriteriaQuery<MyEntity> cq = cb .createQuery(MyEntityclass); // initialize predicates here return entityManager.createQuery(cq).getResultList().size(); And that can't be the proper way to do it... Is there a solution?

    Read the article

  • Obtaining IP addresses in Bittorrent

    - by Legend
    I am trying to get a list of IP addresses serving or downloading a file. What I did was to contact a tracker like openbittorrent.com to get the following (as part of the scrape file): B%00%00%0C%5F%B1%B1l%CAGa%84S%CB%B0%9BG%84%3BE:0:1 Now, the long string in the beginning is the info hash. As a next step, I did this: http://tracker.sometracker.com/announce?info_hash=B%00%00%0C%5F%B1%B1l%CAGa%84S%CB%B0%9BG%84%3BE It gave me back the following. So far so good. The message contained this: d8:completei0e10:downloadedi0e10:incompletei2e8:intervali1931e12:min intervali965e5:peers12:U????????^@^@e Can someone tell me what should I be doing after this to get the IP addresses currently serving the file or downloading it?

    Read the article

  • Casting a object to a base class , return the extented object??

    - by CrazyJoe
    My Code: public class Contact { public string id{ get; set; } public string contact_type_id { get; set; } public string value{ get; set; } public string person_id { get; set; } public Contact() { } } public class Contact:Base.Contact { public ContactType ContactType { get; set; } public Person Person {get; set;} public Contact() { ContactType = new ContactType(); Person = new Person(); } } And: Contact c = new Contact(); Base.Contact cb = (Base.Contact)c; The Problem: The **cb** is set to **Contac** and not to **Base.Contact**. Have any trick to do that????

    Read the article

  • How do I set a matplotlib colorbar extents?

    - by Adam Fraser
    I'd like to display a colorbar representing an image's raw values along side a matplotlib imshow subplot which displays that image, normalized. I've been able to draw the image and a colorbar successfully like this, but the colorbar min and max values represent the normalized (0,1) image instead of the raw (0,99) image. f = plt.figure() # create toy image im = np.ones((100,100)) for x in range(100): im[x] = x # create imshow subplot ax = f.add_subplot(111) result = ax.imshow(im / im.max()) # Create the colorbar axc, kw = matplotlib.colorbar.make_axes(ax) cb = matplotlib.colorbar.Colorbar(axc, result) # Set the colorbar result.colorbar = cb If someone has a better mastery of the colorbar API, I'd love to hear from you. Thanks! Adam

    Read the article

  • how to pass an xml file to lxml to parse?

    - by BeeBand
    I'm trying to parse an xml file using lxml. xml.etree allowed me to simply pass the file name as a parameter to the parse function, so I attempted to do the same with lxml. My code: from lxml import etree from lxml import objectify file = "C:\Projects\python\cb.xml" tree = etree.parse(file) but I get the error: Traceback (most recent call last): File "cb.py", line 5, in <module> tree = etree.parse(file) File "lxml.etree.pyx", line 2698, in lxml.etree.parse (src/lxml/lxml.etree.c:4 9590) File "parser.pxi", line 1491, in lxml.etree._parseDocument (src/lxml/lxml.etre e.c:71205) File "parser.pxi", line 1520, in lxml.etree._parseDocumentFromURL (src/lxml/lx ml.etree.c:71488) File "parser.pxi", line 1420, in lxml.etree._parseDocFromFile (src/lxml/lxml.e tree.c:70583) File "parser.pxi", line 975, in lxml.etree._BaseParser._parseDocFromFile (src/ lxml/lxml.etree.c:67736) File "parser.pxi", line 539, in lxml.etree._ParserContext._handleParseResultDo c (src/lxml/lxml.etree.c:63820) File "parser.pxi", line 625, in lxml.etree._handleParseResult (src/lxml/lxml.e tree.c:64741) File "parser.pxi", line 565, in lxml.etree._raiseParseError (src/lxml/lxml.etr ee.c:64084) lxml.etree.XMLSyntaxError: AttValue: " or ' expected, line 2, column 26 What am I doing wrong?

    Read the article

  • Python question, how to pass an xml file to lxml to parse?

    - by BeeBand
    I'm relatively new to python, my code is: from lxml import etree from lxml import objectify file = "C:\Projects\python\cb.xml" tree = etree.parse(file) but I get the error: Traceback (most recent call last): File "cb.py", line 5, in <module> tree = etree.parse(file) File "lxml.etree.pyx", line 2698, in lxml.etree.parse (src/lxml/lxml.etree.c:4 9590) File "parser.pxi", line 1491, in lxml.etree._parseDocument (src/lxml/lxml.etre e.c:71205) File "parser.pxi", line 1520, in lxml.etree._parseDocumentFromURL (src/lxml/lx ml.etree.c:71488) File "parser.pxi", line 1420, in lxml.etree._parseDocFromFile (src/lxml/lxml.e tree.c:70583) File "parser.pxi", line 975, in lxml.etree._BaseParser._parseDocFromFile (src/ lxml/lxml.etree.c:67736) File "parser.pxi", line 539, in lxml.etree._ParserContext._handleParseResultDo c (src/lxml/lxml.etree.c:63820) File "parser.pxi", line 625, in lxml.etree._handleParseResult (src/lxml/lxml.e tree.c:64741) File "parser.pxi", line 565, in lxml.etree._raiseParseError (src/lxml/lxml.etr ee.c:64084) lxml.etree.XMLSyntaxError: AttValue: " or ' expected, line 2, column 26 What am I doing wrong?

    Read the article

  • Global Timer in Javascript with Multiple Callbacks

    - by Mike Beepo
    I want to create a global timer object in javascript and then be able to add callbacks to it on the fly. This way I can just use one global timer in my script to execute all actions at a certain interval rather than wasting resources by using multiples. This is how I want to be able to piece things together: var timer = new function() { clearInterval( this.interval ); //[1] At this point I want the Callbacks to be run var self = this; setTimeout(function() {self.timer()}, 200); } function otherObject = new function() { //When created I want to bind my object's function called cb to the global timer at [1] } otherObject.prototype.cb = function() { //Stuff that should be done every time the timer is run } var someObject = new otherObject(); How would I make it possible bind any number functions (most of which are functions within other objects) to run at the interval of my timer on the fly?

    Read the article

  • ASP.Net Checkbox value at postback is wrong?

    - by Duracell
    We have a checkbox that is initially disabled and checked. It is then enabled on the client side through javascript. If the user then unchecks the box and presses the button to invoke a postback, the state of the checkbox remains as checked on the server side. This is obviously undesirable behaviour. Here is an example. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="testcb.aspx.cs" Inherits="ESC.testcb" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <script type="text/javascript"> function buttonClick() { var cb = document.getElementById('<%= CheckBox1.ClientID %>'); cb.disabled = false; cb.parentNode.disabled = false; } </script> <div> <asp:CheckBox ID="CheckBox1" runat="server" Checked="true" Enabled="false" /> <asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="buttonClick(); return false;" /> <asp:Button ID="Button2" runat="server" Text="Button2" OnClick="button2Click" /> </div> </form> </body> </html> And the Server-side code: using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace ESC { public partial class testcb : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void button2Click(object sender, EventArgs e) { string h = ""; } } } So we break at the "string h" line and check the value of CheckBox1.Checked. It is true, even if it is unchecked on the form.

    Read the article

  • Port C's fread(&struct,....) to Python

    - by user287669
    Hey, I'm really struggling with this one. I'am trying to port a small piece of someone else's code to Python and this is what I have: typedef struct { uint8_t Y[LUMA_HEIGHT][LUMA_WIDTH]; uint8_t Cb[CHROMA_HEIGHT][CHROMA_WIDTH]; uint8_t Cr[CHROMA_HEIGHT][CHROMA_WIDTH]; } __attribute__((__packed__)) frame_t; frame_t frame; while (! feof(stdin)) { fread(&frame, 1, sizeof(frame), stdin); // DO SOME STUFF } Later I need to access the data like so: frame.Y[x][y] So I made a Class 'frame' in Python and inserted the corresponding variables(frame.Y, frame.Cb, frame.Cr). I have tried to sequentially map the data from Y[0][0] to Cr[MAX][MAX], even printed out the C struct in action but didn't manage to wrap my head around the method used to put the data in there. I've been struggling overnight with this and have to get back to the army tonight, so any immediate help is very welcome and appreciated. Thanks

    Read the article

  • Show/hide views with checkbox

    - by DixieFlatline
    Hi! I want to show or hide some elements (textviews and edittexts) with checkbox. I set their visibility to gone in layout file. Showing them when user checks the box works, but the when user unchecks it, they don't hide. (android 1.5 and 1.6) My code: cb=(CheckBox)findViewById(R.id.cek); cb.setOnClickListener(new OnClickListener() { // checkbox listener public void onClick(View v) { // Perform action on clicks, depending on whether it's now checked if (((CheckBox) v).isChecked()) { tv1.setVisibility(0); //visible==0 et3.setVisibility(0); } else if (((CheckBox) v).isChecked() == false) { tv1.setVisibility(2); //gone=2 et3.setVisibility(2); } } });

    Read the article

  • How to convert an existing callback interface to use boost signals & slots

    - by the_mandrill
    I've currently got a class that can notify a number of other objects via callbacks: class Callback { virtual NodulesChanged() =0; virtual TurkiesTwisted() =0; }; class Notifier { std::vector<Callback*> m_Callbacks; void AddCallback(Callback* cb) {m_Callbacks.push(cb); } ... void ChangeNodules() { for (iterator it=m_Callbacks.begin(); it!=m_Callbacks.end(); it++) { (*it)->NodulesChanged(); } } }; I'm considering changing this to use boost's signals and slots as it would be beneficial to reduce the likelihood of dangling pointers when the callee gets deleted, among other things. However, as it stands boost's signals seems more oriented towards dealing with function objects. What would be the best way of adapting my code to still use the callback interface but use signals and slots to deal with the connection and notification aspects?

    Read the article

  • Feeding PDF through IInternetSession to WebBrowser control - Error

    - by Codesleuth
    As related to my previous question, I have developed a temporary asynchronous pluggable protocol with the specific aim to be able to serve PDF documents directly to a WebBrowser control via a database. I need to do this because my limitations include not being able to access the disk other than IsolatedStorage; and a MemoryStream would be far better for serving up PDF documents that average around 31kb. Unfortunately the code doesn't work, and I'm getting an error from the WebBrowser control (i.e. IE): Unable to download . Unable to open this Internet site. The requested site is either unavailable or cannot be found. Please try again later. The line in my code where this occurs is within the following: pOIProtSink.ReportData(BSCF.BSCF_LASTDATANOTIFICATION, (uint)_stream.Length, (uint)_stream.Length); However, if you download the project and run it, you will be able to see the stream is successfully read and passed to the browser, so it seems like there's a problem somewhere to do with the end of reading the data: public uint Read(IntPtr pv, uint cb, out uint pcbRead) { var bytesToRead = Math.Min(cb, _streamBuffer.Length); pcbRead = (uint)_stream.Read(_streamBuffer, 0, (int)bytesToRead); Marshal.Copy(_streamBuffer, 0, pv, (int)pcbRead); return (pcbRead == 0 || pcbRead < cb) ? HRESULT.S_FALSE : HRESULT.S_OK; } Here is the entire sample project: InternetSessionSample.zip (VS2010) I will leave this up for as long as I can to help other people in the future If anyone has any ideas why I might be getting this message and can shed some light on the problem, I would be grateful for the assistance. EDIT: A friend suggested inserting a line that calls the IInternetProtocolSink.ReportProgress with BINDSTATUS_CACHEFILENAMEAVAILABLE pointing at the original file. This prevents it from failing now and shows the PDF in the Adobe Reader control, but means it defeats the purpose of this by having Adobe Reader simply load from the cache file (which I can't provide). See below: pOIProtSink.ReportProgress(BINDSTATUS.BINDSTATUS_CACHEFILENAMEAVAILABLE, @"D:\Visual Studio Solutions\Projects\InternetSessionSample\bin\Debug\sample.pdf"); pOIProtSink.ReportData(BSCF.BSCF_LASTDATANOTIFICATION, (uint)_stream.Length, (uint)_stream.Length); This is progress though, I guess.

    Read the article

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