Blog coding and discussion of coding about JavaScript, PHP, CGI, general web building etc.

Latest Posts

Saturday, March 11, 2017

REST API Client Library for Android

REST API Client Library for Android


We are building a location based messaging app which uses Parse.com as back-end (Parse.com is similar to Urban Airship/PubNub, etc) and we now want to switch to our own back-end for better control. For this, we have built a node.js based back-end with functionality exposed over REST API

To consume this API, we want to build an Android library (similar to Parse.com's Android SDK) which abstracts all the HTTP Requests/Response or REST API calls and provides direct functions for various operations like getUsers(), sendMessage(), etc

Ways to implement REST API Client in Android :

Now, considering that we want to build an android library and there could be simultaneous REST API calls while the user is interacting with the app, which approach would be the best to go ahead with ? I am open to other suggestions / recommendations as well.

UPDATE: We first built our own library using IntentService + ResultReceiver which worked fine. But we later stumbled across Android Async Http. Use it. It's awesome!

Answer by Chris.Jenkins for REST API Client Library for Android


Best implimentation I have seen based on Google IO Pro Tips 2010 is the RoboSpice library, which is REST based and very cleverly works with the Activity lifecycle as to not leak memory.

Quick infographic the library is here

  • Loaders are designed for database, not REST, they are reset on activity reset meaning you loose your data.
  • Async task, just no.
  • Intent Service + Result receiver is basically how RoboSpice work, so if you are building your own lib, I would take this approach!
  • Service is also good, similar to the IntentService Method, but IntentService works a little better in this instance.

The Service method maybe better, look at the robospice service they use an ExecutorService which terminates the Service when it has run out of Requests to work through, this is more Java concurrency than Android specific. Main thing to note that the service runs whilst processing requests then terminates its self if their are none left.

The advantage of using the ExecutorService or any type of thread pool, is that you can define how many requests you can run at once. unless you have a very fast connection 2-4 is the most i would ever suggest.

Answer by dineth for REST API Client Library for Android


If I may add one more thing, I recently started writing a nice library to implement Engines (as used by MKNetworkKit in iOS) and Commands to communicate with REST APIs for Android. Might be helpful for anyone trying to reach REST APIs. https://github.com/m2d2/MDBaseAndroidLibraries

Answer by Pcriulan for REST API Client Library for Android


You can also use RESTDroid. It's quite similar to RoboSpice but simpler to use (although also less powerful.)

If you create a Parse.com module for RESTDroid, don't hesitate to add it on GitHub!

Answer by Bhavit S. Sengar for REST API Client Library for Android


MAY BE THIS CLASS CAN HELP :-

/*Copyright 2014 Bhavit Singh Sengar  Licensed under the Apache License, Version 2.0 (the "License");  you may not use this file except in compliance with the License.  You may obtain a copy of the License at    http://www.apache.org/licenses/LICENSE-2.0  Unless required by applicable law or agreed to in writing, software  distributed under the License is distributed on an "AS IS" BASIS,  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the License for the specific language governing permissions and  limitations under the License.*/    package com.infotech.zeus.util;    import java.io.IOException;  import java.io.UnsupportedEncodingException;  import org.apache.http.HttpEntity;  import org.apache.http.HttpResponse;  import org.apache.http.client.ClientProtocolException;  import org.apache.http.client.HttpClient;  import org.apache.http.client.ResponseHandler;  import org.apache.http.client.methods.HttpGet;  import org.apache.http.client.methods.HttpPost;  import org.apache.http.entity.StringEntity;  import org.apache.http.impl.client.BasicResponseHandler;  import org.apache.http.impl.client.DefaultHttpClient;  import org.apache.http.protocol.HTTP;  import org.apache.http.util.EntityUtils;  import org.json.JSONException;  import org.json.JSONObject;  import android.widget.Toast;    public class RestClient {              JSONObject data = new JSONObject();          String url;          String headerName;          String headerValue;            public RestClient(String s){                url = s;          }              public void addHeader(String name, String value){                headerName = name;              headerValue = value;            }            public void addParam(String key, String value){                try {                  data.put(key, value);              } catch (JSONException e) {                  // TODO Auto-generated catch block                  e.printStackTrace();              }              }            public String executePost(){  // If you want to use post method to hit server                HttpClient httpClient = new DefaultHttpClient();              HttpPost httpPost = new HttpPost(url);              httpPost.setHeader(headerName, headerValue);              HttpResponse response = null;              String result = null;              try {                  StringEntity entity = new StringEntity(data.toString(), HTTP.UTF_8);                  httpPost.setEntity(entity);                  response = httpClient.execute(httpPost);                  HttpEntity entity1 = response.getEntity();                  result = EntityUtils.toString(entity1);                  return result;                  //Toast.makeText(MainPage.this, result, Toast.LENGTH_LONG).show();              } catch (UnsupportedEncodingException e) {                  // TODO Auto-generated catch block                  e.printStackTrace();              } catch (ClientProtocolException e) {                  // TODO Auto-generated catch block                  e.printStackTrace();              } catch (IOException e) {                  // TODO Auto-generated catch block                  e.printStackTrace();              }              return result;                }            public String executeGet(){ //If you want to use get method to hit server                HttpClient httpClient = new DefaultHttpClient();              HttpGet httpget = new HttpGet(url);              String result = null;              ResponseHandler responseHandler = new BasicResponseHandler();              try {                  result = httpClient.execute(httpget, responseHandler);              } catch (ClientProtocolException e) {                  // TODO Auto-generated catch block                  e.printStackTrace();              } catch (IOException e) {                  // TODO Auto-generated catch block                  e.printStackTrace();              }                return result;          }  }  

A SIMPLE EXAMPLE TO USE THIS CLASS :

RestClient client = new RestClient("http://www.example.com/demo.php");  //Write your url here          client.addParam("Name", "Bhavit"); //Here I am adding key-value parameters          client.addParam("Age", "23");            client.addHeader("content-type", "application/json"); // Here I am specifying that the key-value pairs are sent in the JSON format            try {              String response = client.executePost(); // In case your server sends any response back, it will be saved in this response string.            } catch (Exception e) {              e.printStackTrace();          }  

Answer by Hugo Gresse for REST API Client Library for Android


I've used Retrofit and it's really good library which provide an easy structure for managing endpoints and parse data/collections/object.

The documentation is complete enough to write easily you code.

CQFD > go for it

Answer by Hemant Sharma for REST API Client Library for Android


You could also try Android Annotations with rest-spring plugin to do these tasks automatically.

They use a wrapper on spring framework for android and provide a really good way to handle rest apis.

Examples:

Replace AsyncTask -> doInBackground() with @Background annotation:

@Background  protected void backgroundWork(){      // do something in background  }  

Replace runOnUiThread, onPostExecute() with @UiThread

@UiThread  protected void uiWork(){      // do something on UI Thread  }  

For Rest API's

create rest client:

@Rest(rootUrl = "http://company.com/ajax/services",        converters = { MappingJackson2HttpMessageConverter.class })  public interface MyRestClient {        @Get("/events")      EventList getEvents();  }  

use rest client:

@RestClient  MyRestClient myRestClient;    public void showAllEvents(){      EventList list = myRestClient.getEvents();      // do something with this list    }  


Fatal error: Call to a member function getElementsByTagName() on a non-object in D:\XAMPP INSTALLASTION\xampp\htdocs\endunpratama9i\www-stackoverflow-info-proses.php on line 72

Problems with a single line break in JavaScript

Problems with a single line break in JavaScript


Hello I've looked through JavaScript related questions and can find no result. What I'm trying to do is very simple; I know how to do it but for some reason it isn't working.

Here's the code I'm having the problem with:

playersScore = rollDie();  document.write('Score: ' + playersScore);  playersPosition = playersScore + playersPosition;  document.write(', Square: ' + playersPosition);    indexOfNumber = findIndexOf(playersPosition, specialSquaresArray);    if (indexOfNumber != -1) {      document.write(', Ladder to Square: ' + connectedSquaresArray[indexOfNumber] + '
'); playersPosition = connectedSquaresArray[indexOfNumber]; indexOfNumber = -1; } // end of question(iii) // start of question(iv)(b) while (playersPosition < 80) { playersScore = rollDie() document.write('Score: ' + playersScore) playersPosition = playersPosition + playersScore document.write(', Square: ' + playersPosition) indexOfNumber = findIndexOf(playersPosition, specialSquaresArray) if (indexOfNumber != -1) { document.write(', Ladder to Square: ' + connectedSquaresArray[indexOfNumber]); playersPosition = connectedSquaresArray[indexOfNumber]; } document.write('
');

And here's the result in the browser:

Score: 4, Square: 4Score: 4, Square: 8  Score: 2, Square: 10  Score: 1, Square: 11  Score: 2, Square: 13  Score: 5, Square: 18  Score: 4, Square: 22  Score: 1, Square: 23  Score: 5, Square: 28  Score: 3, Square: 31  Score: 5, Square: 36  Score: 3, Square: 39, Ladder to Square: 51  Score: 4, Square: 55  Score: 6, Square: 61  Score: 6, Square: 67  Score: 1, Square: 68, Ladder to Square: 73  Score: 1, Square: 74  Score: 3, Square: 77, Ladder to Square: 58  Score: 5, Square: 63  Score: 1, Square: 64  Score: 4, Square: 68, Ladder to Square: 73  Score: 6, Square: 79  Score: 6, Square: 85

The first line is the player's 'first go' (Score: 4, Square: 4) yet I need the line that immediately follows it (Score: 4, Square: 8) to break to the line below but no matter where I place
it will not do it. Is the a problem with the first few lines or is it an issue at the start of the while loop? I really can't figure it out!!

I'd really appreciate some help with this. Many thanks in advance.

Answer by Arun for Problems with a single line break in JavaScript


Change line number 4 to the following

document.write(', Square: ' + playersPosition + '
');

Answer by Shadow Wizard for Problems with a single line break in JavaScript


Just write line break if no ladder is found:

if (indexOfNumber != -1) {      document.write(', Ladder to Square: ' + connectedSquaresArray[indexOfNumber] + '
'); playersPosition = connectedSquaresArray[indexOfNumber]; indexOfNumber = -1; } else { document.write('
'); }

Answer by Furqan for Problems with a single line break in JavaScript


Put another

     document.write('
');

as the first line of While Loop.

Answer by pcjuzer for Problems with a single line break in JavaScript


You would have to explicitly write out HTML and line breaks, e.g. document.write('
');
.

Answer by Steve Claridge for Problems with a single line break in JavaScript


You need to add a

document.write('
');

before your while loop to break the line after the first section of output. You do have a BR up there but it only gets output if the if test passes.

Remove the BR from the first 'Ladder to Square:' output line and just add one before the while loop so that it will be always be output.


Fatal error: Call to a member function getElementsByTagName() on a non-object in D:\XAMPP INSTALLASTION\xampp\htdocs\endunpratama9i\www-stackoverflow-info-proses.php on line 72

Friday, March 10, 2017

Calculate AUC in R?

Calculate AUC in R?


Given a vector of scores and a vector of actual class labels, how do you calculate a single-number AUC metric for a binary classifier in the R language or in simple English?

Page 9 of "AUC: a Better Measure..." seems to require knowing the class labels, and here is an example in MATLAB where I don't understand

R(Actual == 1))  

Because R (not to be confused with the R language) is defined a vector but used as a function?

Answer by semaj for Calculate AUC in R?


The ROCR package will calculate the AUC among other statistics:

auc.tmp <- performance(pred,"auc"); auc <- as.numeric(auc.tmp@y.values)  

Answer by J. Won. for Calculate AUC in R?


With the package pROC you can use the function auc() like this example from the help page:

> data(aSAH)  >   > # Syntax (response, predictor):  > auc(aSAH$outcome, aSAH$s100b)  Area under the curve: 0.7314  

link to pROC

Answer by George Dontas for Calculate AUC in R?


I usually use the function ROC from the DiagnosisMed package. I like the graph it produces. AUC is returned along with it's confidence interval and it is also mentioned on the graph.

ROC(classLabels,scores,Full=TRUE)  

Answer by erik for Calculate AUC in R?


As mentioned by others, you can compute the AUC using the ROCR package. With the ROCR package you can also plot the ROC curve, lift curve and other model selection measures.

You can compute the AUC directly without using any package by using the fact that the AUC is equal to the probability that a true positive is scored greater than a true negative.

For example, if pos.scores is a vector containing a score of the positive examples, and neg.scores is a vector containing the negative examples then the AUC is approximated by:

> mean(sample(pos.scores,1000,replace=T) > sample(neg.scores,1000,replace=T))  [1] 0.7261  

will give an approximation of the AUC. You can also estimate the variance of the AUC by bootstrapping:

> aucs = replicate(1000,mean(sample(pos.scores,1000,replace=T) > sample(neg.scores,1000,replace=T)))  

Answer by Max Ghenis for Calculate AUC in R?


Along the lines of erik's response, you should also be able to calculate the ROC directly by comparing all possible pairs of values from pos.scores and neg.scores:

score.pairs <- merge(pos.scores, neg.scores)  names(score.pairs) <- c("pos.score", "neg.score")  sum(score.pairs$pos.score > score.pairs$neg.score) / nrow(score.pairs)  

Certainly less efficient than the sample approach or the pROC::auc, but more stable than the former and requiring less installation than the latter.

Related: when I tried this it gave similar results to pROC's value, but not exactly the same (off by 0.02 or so); the result was closer to the sample approach with very high N. If anyone has ideas why that might be I'd be interested.

Answer by AGS for Calculate AUC in R?


Without any additional packages:

true_Y = c(1,1,1,1,2,1,2,1,2,2)  probs = c(1,0.999,0.999,0.973,0.568,0.421,0.382,0.377,0.146,0.11)    getROC_AUC = function(probs, true_Y){      probsSort = sort(probs, decreasing = TRUE, index.return = TRUE)      val = unlist(probsSort$x)      idx = unlist(probsSort$ix)          roc_y = true_Y[idx];      stack_x = cumsum(roc_y == 2)/sum(roc_y == 2)      stack_y = cumsum(roc_y == 1)/sum(roc_y == 1)            auc = sum((stack_x[2:length(roc_y)]-stack_x[1:length(roc_y)-1])*stack_y[2:length(roc_y)])      return(list(stack_x=stack_x, stack_y=stack_y, auc=auc))  }    aList = getROC_AUC(probs, true_Y)     stack_x = unlist(aList$stack_x)  stack_y = unlist(aList$stack_y)  auc = unlist(aList$auc)    plot(stack_x, stack_y, type = "l", col = "blue", xlab = "False Positive Rate", ylab = "True Positive Rate", main = "ROC")  axis(1, seq(0.0,1.0,0.1))  axis(2, seq(0.0,1.0,0.1))  abline(h=seq(0.0,1.0,0.1), v=seq(0.0,1.0,0.1), col="gray", lty=3)  legend(0.7, 0.3, sprintf("%3.3f",auc), lty=c(1,1), lwd=c(2.5,2.5), col="blue", title = "AUC")  

enter image description here

Answer by arun for Calculate AUC in R?


Combining code from ISL 9.6.3 ROC Curves, along with @J. Won.'s answer to this question and a few more places, the following plots the ROC curve and prints the AUC in the bottom right on the plot.

Below probs is a numeric vector of predicted probabilities for binary classification and test$label contains the true labels of the test data.

require(ROCR)  require(pROC)    rocplot <- function(pred, truth, ...) {    predob = prediction(pred, truth)    perf = performance(predob, "tpr", "fpr")    plot(perf, ...)    area <- auc(truth, pred)    area <- format(round(area, 4), nsmall = 4)    text(x=0.8, y=0.1, labels = paste("AUC =", area))      # the reference x=y line    segments(x0=0, y0=0, x1=1, y1=1, col="gray", lty=2)  }    rocplot(probs, test$label, col="blue")  

This gives a plot like this:

enter image description here

Answer by Ben for Calculate AUC in R?


I found some of the solutions here to be slow and/or confusing (and some of them don't handle ties correctly) so I wrote my own data.table based function auc_roc() in my R package mltools.

library(data.table)  library(mltools)    preds <- c(.1, .3, .3, .9)  actuals <- c(0, 0, 1, 1)    auc_roc(preds, actuals)  # 0.875    auc_roc(preds, actuals, returnDT=TRUE)  Pred CountFalse CountTrue CumulativeFPR CumulativeTPR AdditionalArea CumulativeArea  1:  0.9          0         1           0.0           0.5          0.000          0.000  2:  0.3          1         1           0.5           1.0          0.375          0.375  3:  0.1          1         0           1.0           1.0          0.500          0.875  

Answer by Jussi Kujala for Calculate AUC in R?


Currently top voted answer is incorrect, because it disregards ties. When positive and negative scores are equal, then AUC should be 0.5. Below is corrected example.

computeAUC <- function(pos.scores, neg.scores, n_sample=100000) {    # Args:    #   pos.scores: scores of positive observations    #   neg.scores: scores of negative observations    #   n_samples : number of samples to approximate AUC      pos.sample <- sample(pos.scores, n_sample, replace=T)    neg.sample <- sample(neg.scores, n_sample, replace=T)    mean(1.0*(pos.sample > neg.sample) + 0.5*(pos.sample==neg.sample))  }  


Fatal error: Call to a member function getElementsByTagName() on a non-object in D:\XAMPP INSTALLASTION\xampp\htdocs\endunpratama9i\www-stackoverflow-info-proses.php on line 72

How to use bootstrap with 16 or 24 columns

How to use bootstrap with 16 or 24 columns


I need some help setting bootstrap 2.0.4 to be 16 or 24 column instead of the default 12 columns i can't understand what am i doing wrong i tried the customize option on the bootstrap site and i tried changing the grid variables in the variables.less file and recompile bootstrap.less using Crunch but for both trials i still have the same result .it is still 12 columns !!! when i try to set a div to be span12 it still takes the whole screen ?

Can anyone guide me to what's wrong i am doing or if someone can generate a 16 and 24 columns versions and send them to me that would be perfect

Answer by Intenex for How to use bootstrap with 16 or 24 columns


Simple enough to alter in less - http://twitter.github.com/bootstrap/scaffolding.html#gridCustomization

You'll want to change the variables there to what you want -

e.g.

@gridColumns: 24  @gridColumnWidth: 30px  @gridGutterWidth: 10px  

If using a fluid-grid, you'll want to change these variables proportionally too, otherwise span12 will still take up 100% of the width and span24 will take up 200%

@fluidGridColumnWidth  @fluidGridGutterWidth  

As stated:

How to customize

Modifying the grid means changing the three @grid* variables and recompiling Bootstrap. Change the grid variables in variables.less and use one of the four ways documented to recompile. If you're adding more columns, be sure to add the CSS for those in grid.less.

You can change the variables and download the new css right here: http://twitter.github.com/bootstrap/download.html#variables

Here's a compiled example that should work for 16 columns (haven't tested, let me know how it works): https://s3.amazonaws.com/intenex/bootstrap16columns.zip

Answer by Hasan Atbinici for How to use bootstrap with 16 or 24 columns


This method is for an older version of Bootstrap - Version 2.3.1

Click this link to customize bootstrap: http://twitter.github.com/bootstrap/customize.html

You will find examples such as this. Change the parameters to fit your needs.

16 Grid system with Gutter  @gridColumns: 16  @gridColumnWidth: 45px  @gridGutterWidth: 15px  @gridColumnWidth1200: 52.5px  @gridGutterWidth1200: 22.5px  @gridColumnWidth768: 31.5px  @gridGutterWidth768: 15px    16 Grid system without Gutter  @gridColumns: 16  @gridColumnWidth: 60px  @gridGutterWidth: 0px  @gridColumnWidth1200: 75px  @gridGutterWidth1200: 0px  @gridColumnWidth768: 46.5px  @gridGutterWidth768: 0px  

24 Grid system with Gutter  @gridColumns: 24  @gridColumnWidth: 30px  @gridGutterWidth: 1px  @gridColumnWidth1200: 35px  @gridGutterWidth1200: 15px  @gridColumnWidth768: 21px  @gridGutterWidth768: 10px    24 Grid system without Gutter  @gridColumns: 24  @gridColumnWidth: 40px  @gridGutterWidth: 0px  @gridColumnWidth1200: 50px  @gridGutterWidth1200: 0px  @gridColumnWidth768: 31px  @gridGutterWidth768: 0px  

Answer by User for How to use bootstrap with 16 or 24 columns


16 Column

960px

45px *16 =720 Column

15px *16 =240 Gutter

1200px

53px *16 =848 Column

22px *16 =352 Gutter

768px

33px *16 =528 Column

15px *16 =240 Gutter

Answer by User for How to use bootstrap with 16 or 24 columns


Set 24 Columns:

960
35px Column
5px Gutter

1200
40px Column
10px Gutter

768
29px Column
3px Gutter

Answer by Maciej Gurban for How to use bootstrap with 16 or 24 columns


Edit: Creating grids with custom number of columns has been restored, and can be done on Bootstrap's customization page.

For reasons unknown to me, the latest version of Bootstrap (3.0.0/1) doesn't allow you to create grid different than 12 columns, which is a big shame.

What we can do currently, and which will in turn allow for creating more customized bootstrap packages, is to set up your own Bootstrap customizer.

Edit: I just tried it. Installing all the dependencies went quite smooth while sticking to guidelines on their Docs GitHub page.

Sample generated 24 column grid

Editor required inserting some code along with jsfiddle link. There's no point in pasting anything though.  

Answer by ?smail Hakk? Şen for How to use bootstrap with 16 or 24 columns


For 24 colums you can split main div

nothing
nothing
nothing
nothing
nothing
nothing
nothing
nothing
nothing
nothing
nothing
nothing
12 here

codepen demo

Answer by nalcus for How to use bootstrap with 16 or 24 columns


Here is a quick and easy way I found to do 16 columns using nesting...

.no-padding {    padding-left: 0 !important;    padding-right: 0 !important;  }
col
col
col
col
col
col
col
col
col
col
col
col
col
col
col
col

Answer by ARUN Edathadan for How to use bootstrap with 16 or 24 columns


I use Grid 30 columns for my project (Grid 24 and 100 also available)

https://github.com/zirafa/bootstrap-grid-only

some customization may be required depending on you requirement


Fatal error: Call to a member function getElementsByTagName() on a non-object in D:\XAMPP INSTALLASTION\xampp\htdocs\endunpratama9i\www-stackoverflow-info-proses.php on line 72

Thursday, March 9, 2017

How to populate a ComboBox with a Recordset using VBA

How to populate a ComboBox with a Recordset using VBA


There is some literature available at expert's exchange and at teck republic about using the combobox.recordset property to populate a combobox in an Access form.

These controls are usually populated with a "SELECT *" string in the 'rowsource' properties of the control, referencing a table or query available on the client's side of the app. When I need to display server's side data in a combobox, I create a temporary local table and import requested records. This is time consuming, specially with large tables.

Being able to use a recordset to populate a combobox control would allow the user to directly display data from the server's side.

Inspired by the 2 previous examples, I wrote some code as follow:

Dim rsPersonne as ADODB.recordset  Set rsPersonne = New ADODB.Recordset    Set rsPersonne.ActiveConnection = connexionActive  rsPersonne.CursorType = adOpenDynamic  rsPersonne.LockType = adLockPessimistic  rsPersonne.CursorLocation = adUseClient    rsPersonne.Open "SELECT id_Personne, nomPersonne FROM Tbl_Personne"    fc().Controls("id_Personne").Recordset = rsPersonne  

Where:

  • connexionActive: is my permanent ADO connection to my database server
  • fc(): is my current/active form
  • controls("id_Personne"): is the combobox control to populate with company's staff list
  • Access version in 2003

Unfortunately, it doesn't work!

In debug mode, I am able to check that the recordset is properly created, with requested columns and data, and properly associated to the combobox control. Unfortunately, when I display the form, I keep getting an empty combobox, with no records in it! Any help is highly appreciated.

EDIT:

This recordset property is indeed available for the specific combobox object, not for the standard control object, and I was very surprised to discover it a few days ago. I have already tried to use combobox's callback function, or to populate a list with the "addItem" method of the combobox,. All of these are time consuming.

Answer by Tony Toews for How to populate a ComboBox with a Recordset using VBA


A combo box control does not have a recordset property. It does have a RowSource property but Access is expecting a SQL string in there.

You can change the RowSourceType to the name of a user defined "callback" function. Access help will give you more information including sample code by positioning yourself on the RowSourceType and pressing F1. I use this type of function when I want to give the users a list of available reports, drive letters, or other data that is not available via a SQL query.

I don't understand what you mean by your third paragraph with respect to using data directly from the server side. Or rather I don't understand what the problem is with using standard queries.

Answer by Philippe Grondier for How to populate a ComboBox with a Recordset using VBA


I found the trick ... the "rowSourceType" property of the combobox control has to be set to "Table/List". Display is now ok, but I have now another issue with memory. Since I use these ADO recordsets on my forms, memory usage of Access is increasing each time I browse a form. Memory is not freed either by stopping the browsing or closing the form, making MS Access unstable and regularly freezing. I will open a question if I cannot solve this issue

Answer by Marcand for How to populate a ComboBox with a Recordset using VBA


As was said, you have to get the RowSourceType to "Table/List" (or "Table/Requ?te" if in french) in order to show query results in the combobox.

Your memory problems arise from opening the recordset (rsPersonne) without closing it. You should close them when closing/unloading the form (but then again you would have scope problems since the recordset is declared in the function and not in the form).

You could also try to create and save a query with Access's built-in query creator and plug that same query in the RowSource of your combobox. That way the query is validated and compiled within Access.

Answer by Bitsqueezer for How to populate a ComboBox with a Recordset using VBA


good method with using the Recordset property, thanks for that hint!

Patrick, the method you shown on your page has a big disadvantage (I tried that too on my own): The value list can only be 32 KB, if you exceed this limit the function will throw an error. The callback method has the big disadvantage that it is very slow and it is called once for every entry which makes it unuseable for a longer list. Using the recordset method works very well. I needed this because my SQL string was longer than 32 KB (lot of index values for WHERE ID IN(x,x,x,x,x...)).

Here's a simple function which uses this idea to set a recordset to the combobox:

' Fills a combobox with the result of a recordset.  '  ' Works with any length of recordset results (up to 10000 in ADP)  ' Useful if strSQL is longer than 32767 characters  '  ' Author: Christian Coppes  ' Date: 16.09.2009  '  Public Sub fnADOComboboxSetRS(cmb As ComboBox, strSQL As String)      Dim rs As ADODB.Recordset      Dim lngCount As Long       On Error GoTo fnADOComboboxSetRS_Error        Set rs = fnADOSelectCommon(strSQL, adLockReadOnly, adOpenForwardOnly)        If Not rs Is Nothing Then          If Not (rs.EOF And rs.BOF) Then              Set cmb.Recordset = rs              ' enforces the combobox to load completely              lngCount = cmb.ListCount          End If      End If    fnADOComboboxSetRS_Exit:      If Not rs Is Nothing Then          If rs.State = adStateOpen Then rs.Close          Set rs = Nothing      End If      Exit Sub    fnADOComboboxSetRS_Error:      Select Case Err          Case Else              fnErr "modODBC->fnADOComboboxSetRS", True              Resume fnADOComboboxSetRS_Exit      End Select  End Sub  

(The function fnADOSelectCommon opens an ADO recordset and gives it back. The function fnErr shows a message box with the error, if there was one.)

As this function closes the opened recordset there should be no problem with the memory. I tested it and didn't saw any increasing of memory which wasn't released after closing the form with the comboboxes.

In the Unload Event of the form you can additionaly use a "Set rs=Me.Comboboxname.Recordset" and then close it. This should not be necessary regarding memory, but it may be better to free up open connections (if used with a backend database server).

Cheers,

Christian

Answer by rexreponte for How to populate a ComboBox with a Recordset using VBA


In MS Access, it's ok, but in VB, you may use something like this using adodc (Jet 4.0):

Private sub Form1_Load()     with Adodc1       .commandtype = adcmdtext       .recordsource = "Select * from courses"       .refresh         while not .recordset.eof             combo1.additem = .recordset.coursecode             .recordset.movenext       wend     end with  End Sub  

Answer by Lance S for How to populate a ComboBox with a Recordset using VBA


To set a control that accepts a rowsource to a recordset you do the following:

Set recordset = currentDb.OpenRecordset("SELECT * FROM TABLE", dbOpenSnapshot)  Set control.recordset = recordset  

Works with DAO Recordsets for sure, I haven't tried ADO recordsets because I don't have any real reason to use them.

When done this way, a simple requery will not work to refresh the data, you must do a repeat of the set statement.


Fatal error: Call to a member function getElementsByTagName() on a non-object in D:\XAMPP INSTALLASTION\xampp\htdocs\endunpratama9i\www-stackoverflow-info-proses.php on line 72

Wednesday, March 8, 2017

Markdown to create pages and table of contents?

Markdown to create pages and table of contents?


I started to use mardown to take notes.

I use marked to view my markdown notes and its beautiful.

But as my notes get longer I find it difficult to find what I want.

I know markdown can create tables, but is it able to create table of contents, that jumps to sections, or define page sections in markdown?

Alternatively, are there markdown readers/editors that could do such things. Search would be good feature to have too.

In short, I want to make it my awesome note taking tool and functions much like writing a book etc.

Answer by mxro for Markdown to create pages and table of contents?


MultiMarkdown Composer does seem to generate a table of contents to assist while editing.

There might also be the one or the other library, who can generate TOCs: see Python Markdown TOC Extension.

Answer by sdaau for Markdown to create pages and table of contents?


I just coded an extension for python-markdown, which uses its parser to retrieve headings, and outputs a TOC as Markdown-formatted unordered list with local links. The file is

... and it should be placed in markdown/extensions/ directory in the markdown installation. Then, all you have to do, is type anchor tags with an id="..." attribute as a reference - so for an input text like this:

$ cat test.md   Hello  =====    ## SECTION ONE ##    something here    ### ehSECTION TWO ###    something else    #### SECTION THREE    nothing here    ### SECTION FOUR    also...  

... the extension can be called like this:

$ python -m markdown -x md_toc test.md   * Hello      * [SECTION ONE](#sect one)          * [SECTION TWO](#sect two)              * SECTION THREE          * [SECTION FOUR](#four)  

... and then you can paste back this toc in your markdown document (or have a shortcut in your text editor, that calls the script on the currently open document, and then inserts the resulting TOC in the same document).

Note that older versions of python-markdown don't have a __main__.py module, and as such, the command line call as above will not work for those versions.

Answer by user2502476 for Markdown to create pages and table of contents?


Um... use Markdown's headings!?

That is:

# This is the equivalent of < h1 >

## This is the equivalent of < h2>

### This is the equivalent of < h3>

Many editors will show you a TOC. You can also grep for the heading tags and create your own.

Hope that helps!

--JF

Answer by albertodebortoli for Markdown to create pages and table of contents?


You could try this ruby script to generate the TOC from a markdown file.

#!/usr/bin/env ruby    File.open("your_file.md", 'r') do |f|    f.each_line do |line|      forbidden_words = ['Table of contents', 'define', 'pragma']      next if !line.start_with?("#") || forbidden_words.any? { |w| line =~ /#{w}/ }        title = line.gsub("#", "").strip      href = title.gsub(" ", "-").downcase      puts "  " * (line.count("#")-1) + "* [#{title}](\##{href})"    end  end  

Answer by jonschlinkert for Markdown to create pages and table of contents?


If you want to use a javascript/node.js tool, take a look at markdown-toc.

Answer by dgn for Markdown to create pages and table of contents?


Depending on your workflow, you might want to look at strapdown

That's a fork of the original one (http://strapdownjs.com) that adds the generation of the table of content.

There's an apache config file on the repo (might not be properly updated yet) to wrap plain markdown on the fly, if you prefer not writing in html files.

Answer by Martin for Markdown to create pages and table of contents?


I just started doing the same thing (take notes in Markdown). I use Sublime Text 2 with the MarkdownPreview plugin. The built-in markdown parser supports [TOC].

Answer by Rick for Markdown to create pages and table of contents?


You can give this a try.

# Table of Contents  1. [Example](#example)  2. [Example2](#example2)  3. [Third Example](#third-example)    ## Example  ## Example2  ## Third Example  

Answer by Luca Davanzo for Markdown to create pages and table of contents?


There are 2 way to create your TOC (summary) in your markdown document.

1. Manually

# My Table of content  - [Section 1](#id-section1)  - [Section 2](#id-section2)    
## Section 1
## Section 2

2. Programmatically

You can use for example a script that generate summary for you, take a look to my project on github - summarizeMD -

I've tried also other script/npm module (for example doctoc) but no one reproduce a TOC with working anchors.

Answer by Antonio Maiorano for Markdown to create pages and table of contents?


I wrote a python script that parses a markdown file and outputs a table of contents as a markdown list: md-to-toc

Unlike other scripts I've found, md-to-toc correctly supports duplicate titles. It also doesn't require an internet connection, so it works on any md file, not just those available from a public repo.

Answer by Tumtum for Markdown to create pages and table of contents?


Here's a useful method. Should produce clickable references in any MarkDown editor.

# Table of contents  1. [Introduction](#introduction)  2. [Some paragraph](#paragraph1)      1. [Sub paragraph](#subparagraph1)  3. [Another paragraph](#paragraph2)    ## This is the introduction   Some introduction text, formatted in heading 2 style    ## Some paragraph   The first paragraph text    ### Sub paragraph   This is a sub paragraph, formatted in heading 3 style    ## Another paragraph   The second paragraph text  

Produces:

Table of contents

  1. Introduction
  2. Some paragraph
    1. Sub paragraph
  3. Another paragraph

This is the introduction

Some introduction text, formatted in heading 2 style

Some paragraph

The first paragraph text

Sub paragraph

This is a sub paragraph, formatted in heading 3 style

Another paragraph

The second paragraph text

Answer by dmigous for Markdown to create pages and table of contents?


Based on albertodebortoli answer created the function with additional checks and substitution of punctuation marks.

# @fn       def generate_table_of_contents markdown # {{{  # @brief    Generates table of contents for given markdown text  #  # @param    [String]  markdown Markdown string e.g. File.read('README.md')  #  # @return   [String]  Table of content in markdown format.  #  def generate_table_of_contents markdown    table_of_contents = ""    i_section = 0    # to track markdown code sections, because e.g. ruby comments also start with #    inside_code_section = false    markdown.each_line do |line|      inside_code_section = !inside_code_section if line.start_with?('```')        forbidden_words = ['Table of contents', 'define', 'pragma']      next if !line.start_with?('#') || inside_code_section || forbidden_words.any? { |w| line =~ /#{w}/ }        title = line.gsub("#", "").strip      href = title.gsub(/(^[!.?:\(\)]+|[!.?:\(\)]+$)/, '').gsub(/[!.,?:; \(\)-]+/, "-").downcase        bullet = line.count("#") > 1 ? " *" : "#{i_section += 1}."      table_of_contents << "  " * (line.count("#") - 1) + "#{bullet} [#{title}](\##{href})\n"    end    table_of_contents  end  

Answer by msanford for Markdown to create pages and table of contents?


For the benefit of those of us making README.md files in Atom (how I found this thread):

apm install markdown-toc  

https://atom.io/packages/markdown-toc

Answer by Paul Jurczak for Markdown to create pages and table of contents?


Typora generates Table of Content by adding [TOC] to your document.

Answer by Zhuang Ma for Markdown to create pages and table of contents?


Anchor tags generated by different Markdown parsers are not even.

If you are working with Markdown parsers GFM (GitHub Flavored Markdown) or Redcarpet, I wrote a Vim plugin to handle table of contents.

Features

  1. Generate table of contents for Markdown files.

    Supported Markdown parsers:

    • GFM (GitHub Flavored Markdown)
    • Redcarpet
  2. Update existing table of contents.

  3. Auto update existing table of contents on save.

Screenshots

vim-markdown-toc

Usage

Generate table of contents

Move the cursor to the line you want to append table of contents, then type a command below suit you. The command will generate headings after the cursor into table of contents.

  1. :GenTocGFM

    Generate table of contents in GFM link style.

    This command is suitable for Markdown files in GitHub repositories, like README.md, and Markdown files for GitBook.

  2. :GenTocRedcarpet

    Generate table of contents in Redcarpet link style.

    This command is suitable for Jekyll or anywhere else use Redcarpet as its Markdown parser.

    You can view here to know differences between GFM and Redcarpet style toc links.

Update existing table of contents manually

Generally you don't need to do this, existing table of contents will auto update on save by default. If you want do it manually, just use :UpdateToc command.

Downloads and documents

https://github.com/mzlogin/vim-markdown-toc

Answer by dosmanak for Markdown to create pages and table of contents?


I am not sure, what is the official documentation for markdown. Cross-Reference can be written just in brackets [Heading], or with empty brackets [Heading][].

Both works using pandoc. So I created a quick bash script, that will replace $TOC in md file with its TOC. (You will need envsubst, that might not be part of your distro)

#!/bin/bash  filename=$1  __TOC__=$(grep "^##" $filename | sed -e 's/ /1. /;s/^##//;s/#/   /g;s/\. \(.*\)$/. [\1][]/')  export __TOC__  envsubst '$__TOC__' < $filename  

Answer by Michael R for Markdown to create pages and table of contents?


MultiMarkdown 4.7 has a {{TOC}} macro that inserts a table of contents.

Answer by Christophe Roussy for Markdown to create pages and table of contents?


If you happen to use Eclipse you can use the Ctrl+O (outline) shortcut, this will show the equivalent of the table of contents and allow to search in section titles (autocomplete).

You can also open the Outline view (Window -> Show View -> Outline) but it has no autocomplete search.

Answer by M.Geiger for Markdown to create pages and table of contents?


You could also use pandoc, the "swiss-army knife" for converting "one markup format into another". It can automatically generate a table of content in the output document if you supply the --toc argument.

Hint: If you want a table of contents in html output, you also need to supply -s which generates a standalone document.

Example shell command line:

./pandoc -s --toc input.md -o output.html  


Fatal error: Call to a member function getElementsByTagName() on a non-object in D:\XAMPP INSTALLASTION\xampp\htdocs\endunpratama9i\www-stackoverflow-info-proses.php on line 72

C# Regular expressions, retrieving two words separated by a comma, parenthesis operator

C# Regular expressions, retrieving two words separated by a comma, parenthesis operator


I've been playing around with retrieving data from a string using regular expression, mostly as an exercise for myself. The pattern that I'm trying to match looks like this:

"(SomeWord,OtherWord)"  

After reading some documentation and looking at a cheat sheet I came to the conclusion that the following regex should give me 2 matches:

"\((\w),(\w)\)"  

Because according to the documentation the parenthesis should do the following:

(pattern) Matches pattern and remembers the match. The matched substring can be retrieved from the resulting Matches collection, using Item [0]...[n]. To match parentheses characters ( ), use "\ (" or "\ )".

However using the following code (removed error checking for conciseness) matches quite something different:

string line = "(A,B)";  string pattern = @"\((\w),(\w)\)";  MatchCollection matches = Regex.Matches(line, pattern);  string left = matches[0].Value;  string right = matches[1].Value;  

Now I would expect left to become "A" and right to become "B". However left becomes "(A,B)" and there is no second match at all. What am I missing here?

(I know this example is trivial to solve without regexes but to learn how to properly use regexes I should be able to make something simple as this work)

Answer by pstrjds for C# Regular expressions, retrieving two words separated by a comma, parenthesis operator


You want the Groups member of the first match. In your example case there is only 1 match, which is the whole string. In the Groups collection you will have 3 items. Try this sample code, left should be A, and right should be B. If you look at the group[0] value it will be the whole string.

string line = "(A,B)";  string pattern = @"\((\w),(\w)\)";  MatchCollection matches = Regex.Matches(line, pattern);  GroupCollection groups = matches[0].Groups;  string left = groups[1].Value;  string right = groups[2].Value;  

Answer by Olivier Jacot-Descombes for C# Regular expressions, retrieving two words separated by a comma, parenthesis operator


\w matches only one word character. If words have to contain at least one character, the expression should be:

string pattern = @"\((\w+),(\w+)\)";   

if words may be empty:

string pattern = @"\((\w*),(\w*)\)";   

+: means one or more repetitions.

*: means zero, one or more repetitions.

In any case, you will get one match with three groups, the first containing the whole string including the left and right parentheses, the two others the two words.

Answer by Timothy Khouri for C# Regular expressions, retrieving two words separated by a comma, parenthesis operator


First off, it's one "match", with 2 "groups"...

I would recommend you name the groups anyway...

string pattern = @"\((?\w+),(?\w+)\)";  

Then you could do...

Match m = Regex.Match(line, pattern);    string firstWord = m.Groups["FirstWord"].Value;  

Answer by ean5533 for C# Regular expressions, retrieving two words separated by a comma, parenthesis operator


I think the problem is that you're confusing the concept of a match and a group.

A MatchCollection contains a list of strings that matched your entire regex, not just the parenthetical groups inside that Regex. For example, if the string you searched looked like this...

(A,B)(C,D)  

...then you would have two matches: (A,B) and (C,D).

However, there's good news: you can get the groups from each match very easily, like so:

string line = "(A,B)";  string pattern = @"\((\w),(\w)\)";  MatchCollection matches = Regex.Matches(line, pattern);  string left = matches[0].Groups[1].Value;  string right = matches[0].Groups[2].Value;  

That Groups variable is a collection of parenthetical groups from a single match.

Edit: Olivier Jacot-Descombes made a very good point: we all got so hung up explaining match vs. group that we forgot to notice a second problem: \w will only match a SINGLE character. You need to add a quantifier (such as +) in order to grab more than one character at a time. Olivier's answer should explain that part clearly.

Answer by Novus for C# Regular expressions, retrieving two words separated by a comma, parenthesis operator


Since all you are looking for are the characters separated by a comma, you can simply use \w as your pattern. The matches will be A and B.

A handy site for testing your Regex is http://gskinner.com/RegExr/


Fatal error: Call to a member function getElementsByTagName() on a non-object in D:\XAMPP INSTALLASTION\xampp\htdocs\endunpratama9i\www-stackoverflow-info-proses.php on line 72

Popular Posts

Powered by Blogger.