Simple Directory Lookup in Azure Active Directory

Question: I am writing a simple desktop application that needs to retrieve some basic properties about a user from Microsoft' directory. Specifically:

I am writing a single tenant native LOB application.
The application runs on my desktop.
The application runs as my logged on domain account.
The organization' domain accounts are synced to AAD.
I am not trying to secure a native web app or a Web API or anything like that. I do not need users to sign in.
I have email addresses of folks in my organization from an external event management tool. I need to lookup the AAD account profile data (address book info - specifically job title) from AAD based on the email address. I will only be reading AAD data.

So far, I have done the following:-

It appears that the Azure AD Graph API is the right way to fetch the profile information. In particular, the information is available at the endpoint: https://graph.windows.net/{tenant}/users/{email}?api-version=1.6
When registering the native application in AAD, no key was provided. So I don't have a client secret.
Looked at the sample in GitHub here: https://github.com/Azure-Samples/active-directory-dotnet-graphapi-console. The instructions here seem to be wrong because no Keys section is available [see (2)].

Based on the sample above, I wrote a simple function. Code is below:
    private static async Task PrintAADUserData(string email)
    {
        string clientId = "0a202b2c-6220-438d-9501-036d4e05037f";
        Uri redirectUri = new Uri("http://localhost:4000");
        string resource = "https://graph.windows.net/{tenant}";
        string authority = "https://login.microsoftonline.com/{tenant}/oauth2/authorize";
        AuthenticationContext authContext = new AuthenticationContext(authority);

        AuthenticationResult authResult = await authContext.AcquireTokenAsync(resource, clientId, redirectUri, new PlatformParameters(PromptBehavior.Auto));

        string api = String.Format("https://graph.windows.net/{tenant}/users/{0}?api-version=1.6", email);
        LOG.DebugFormat("Using API URL {0}", api);

        // Create an HTTP client and add the token to the Authorization header
        HttpClient httpClient = new HttpClient();
        httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(authResult.AccessTokenType, authResult.AccessToken);
        HttpResponseMessage response = await httpClient.GetAsync(api);

        string data = await response.Content.ReadAsStringAsync();
        LOG.Debug(data);
    }

Questions

The application when run was able to bring up the authentication page. Why do I need that? The application already runs as my domain account. Is an additional authentication necessary? If I were to run this application in Azure as a worker process, then I would not want to use my domain credentials.
The primary problem seems to be the resource URL which is wrong. What resource do I need to specify to access the Azure AD Graph API?

Thanks,
Vijai.
EDITS
Based on the comments from @Saca, the code and application has been edited.
Code
string clientId = ConfigurationManager.AppSettings["AADClientId"];
string clientSecret = ConfigurationManager.AppSettings["AADClientSecret"];
string appIdUri = ConfigurationManager.AppSettings["AADAppIdURI"];
string authEndpoint = ConfigurationManager.AppSettings["AADGraphAuthority"];
string graphEndpoint = ConfigurationManager.AppSettings["AADGraphEndpoint"];

AuthenticationContext authContext = new AuthenticationContext(authEndpoint, false);
AuthenticationResult authResult = await authContext.AcquireTokenAsync("https://graph.windows.net", new ClientCredential(clientId, clientSecret));
ExistingTokenWrapper wrapper = new ExistingTokenWrapper(authResult.AccessToken);
ActiveDirectoryClient client = new ActiveDirectoryClient(new Uri(graphEndpoint), async () => await wrapper.GetToken());

IUser user = client.Users.Where(_ => _.UserPrincipalName.Equals(email.ToLowerInvariant())).Take(1).ExecuteSingleAsync().Result;

App

Error
Unhandled Exception: System.AggregateException: One or more errors occurred. ---> System.AggregateException: One or more errors occurred. ---> Microsoft.Data.OData.ODataErrorException: Insufficient privileges to complete the operation. ---> System.Data.Services.Client.DataServiceQueryException: An error occurred while processing this request. ---> System.Data.Services.Client.DataServiceClientException: {"odata.error":{"code":"Authorization_RequestDenied","message":{"lang":"en","value":"Insufficient privileges to complete the operation."}}}
It appears that despite giving the right permissions, the correct resource and being able to acquire a token, there is still something missing.
Comment: Have you found the way to solve the exception you got? Because I too get that exact exception **Authorization_RequestDenied**
Comment: @Arunkumar Yes. Please see the answer I added on Jan 21. Check with your tenant administrators for AAD.
Answer: The key thing to consider here is if your application will be a headless client run from a secure server or desktop client run by users on their machines.
If the former, then your application is considered a confidential client and can be trusted with secrets, i.e. the keys. If this is your scenario, which is the scenario covered by the sample, then you need to use clientId and clientSecret.
The most likely reason you are not seeing a Keys section in the your application's Configure page is that, instead of selecting Web Application and/or Web API as per step #7 in the sample, you selected Native Client Application when first creating the application. This "type" can't be changed, so you'll need to create a new application.
If your scenario is the latter, then your application is considered a public client and can't be trusted with secrets, in which case, your only options is to prompt the user for credentials. Otherwise, even if your app has it's own authorization layer, it can easily be decompiled and the secret extracted and used.
Your resource URL is correct by the way.
Comment: Thank you @Saca. I re-created the application as a native application. Also granted application permissions instead of delegated permissions to read directory data. In addition, it looks the resource URI should not include the tenant ID. After these fixes, I am able to get a token. However, when attempting to access the directory data, I still get a request denied error.

{"odata.error":{"code":"Authorization_RequestDenied","message":{"lang":"en","value":"Insufficient privileges to complete the operation."}}}

See EDITS in original question for updated code.
Answer: Turns out the real issue was not with the code. I am not an AAD administrator. It appears that any application needing to perform authentication against AAD in our tenant needs to have permissions enabled by the AAD administrators. Once they enabled permissions for my application (and took ownership of the AAD registration as well), this started working.
Answer: Hope help some one that are using GraphClient:
var userPriNam = "email@example.com";
var userLookupTask = activeDirectoryClient.Users.Where(
    user => user.UserPrincipalName.Equals(userPriNam, StringComparison.CurrentCultureIgnoreCase)).ExecuteSingleAsync();
User userJohnDoe = (User)await userLookupTask;

from https://www.simple-talk.com/cloud/security-and-compliance/azure-active-directory-part-5-graph-api/


deep learning - word embedding with parts of speech

Question: I'm building a sentence classifier with a Convolutional Neural Network (CNN) architecture. I would like to do the word embedding outside of my CNN using a pre-trained model such as GoogleNews (which is based on word2vec). I'm wondering if it is worthwhile to add part-of-speech information to this model and if so, how?
I see the following options:

Use just word2vec to embed words into 300-features vectors
Use two channels in my CNN - one for word2vec and one for part-of-speech tag. Do I have to then embed the part of speech tag into 300 features too?
Embed the part-of-speech tag to some other number of features (say 20 features) and concatenate this 20-feature vector to the word2vec vector (resulting with 320-feature vectors)

If #2 or #3 are preferable, which methods are available to embed a POS tag to a vector representation?
Comment: I am using parsey mcparseface (AKA syntaxnet) to extract part-of-speech information. The part of speech tags have two levels - general POS and a more specific POS. For instance "walking" - general POS is 'verb', specific POS is 'gerund verb'
Comment: CNN - convolutional neural network
Comment: Can you give an example of part-of-speech information?  I would also recommend calling a sentence a document, since you are treating each sentence as a separate document.
Comment: I wouldn't recommend use of acronyms without defining them first, as it's not best practice.  What is CNN?  You might withdraw this question and go to a natural language processing or text mining forum.
Comment: I accidentally hit enter while typing...
Comment: There's no natural language processing SO. Since corresponding tags exist on this SO, and this question requires good understanding of deep learning, I decided to post it here. http://meta.stackexchange.com/questions/188835/why-isnt-there-is-any-section-for-natural-language-processing-nlp
Comment: okay, even though I have significant experience in text mining (stemming, stopping), document clustering, and n-grams, I would say to just try to obtain some sort of word frequency for each document (sentence), where the words used for the frequencies are the same for all the sentences, and then input the sentences (objects) as rows and frequencies for the e.g. 30 to 100 words in columns into the neural network.   There are a lot of parameter settings for neural networks, so you'll just have use a lot of trial and error.
Answer: 1. Concatenating word2vec and POS features
Adding POS information to your classifier is fine. You will of course want to create a train/dev/test split, eg 5-way cross-validation, to test to what extent adding this information improves your results (it's data dependent, really depends on your data, only you can test this, using your own data).
To combine the POS and word2vec features, you can simply concatenate them.  I assume when you say 'CNN', you mean '1-dimensional CNN', is that right?  So your input data if you were just using word2vec features, would be something like:
[batch size][sequence length][word2vec dimensions (ie 300)]

ie, a batch size * sequence_length * word2vec_dim sized tensor.  So, concatenating with the POS features, your input data tensor will become:
[batch size][sequence length][
    word2vec dimensions (ie 300) + POS dimensions (ie 20)]

ie a batch size * sequence_length * 320 sized tensor.
2. sense2vec
You might also want to check out sense2vec, from Trask et al, 2016, https://arxiv.org/pdf/1511.06388.pdf , which makes use of POS information to disambiguate word2vec embeddings:
"This paper presents a novel approach which addresses these concerns by
modeling multiple embeddings for each word based on supervised disambiguation,
which provides a fast and accurate way for a consuming NLP model to select
a sense-disambiguated embedding. We demonstrate that these embeddings can
disambiguate both contrastive senses such as nominal and verbal senses as well
as nuanced senses such as sarcasm. We further evaluate Part-of-Speech disambiguated
embeddings on neural dependency parsing, yielding a greater than 8%
average error reduction in unlabeled attachment scores across 6 languages."
Comment: Is there any experience if it is advisable to also learn an embedding for the POS tags or should one just use one-hot encoding if it are not too many tags?
Answer: I understand that this is an old question, but since there's no answer yet I'll add one.
The intuition here is a well-motivated one: feed the grammatical structure to your model by using a good existing parser, so that your model doesn't have to learn to understand the grammatical structure from scratch.
Something along these lines was (somewhat recently) implemented by the SEST/SEDT model from CMU. Instead of tagging the parts of speech they actually feed in a full parse tree. The results appear to be favorable.


Where do I store classes and ids that the user inputs in my custom module?

Question: I am creating a module that I would like to submit to the drupal.org repository. In the admin section of the module there are various input fields where the user is able to enter classes and ids for various elements that appear on specific nodes. It's basically a module that enables the user to do theming that would otherwise require custom code.
Since I'm not a Drupal rock-star in any way, and I have only worked in custom code and website specific modules, I have a very important question:
How do I store the classes/ids that the module's user will submit?
I guess that there are 3 options here:

Store the classes/ids in a module-specific table in the database
Store the classes/ids in the "Variable" table of the database
Store the classes/ids in a file, in the module's directory

I have some pros/cons in mind about each case (e.g. I don't like the idea that a theming element would be stored in the database) but I would like your input too: which one of the methods above is the best and drupal-friendly? If I missed an option, please feel free to list it.
Answer: Of your three options, 2 would be a huge burden to a site in performance, and 3 will likely be a security issue. So I'd go with 1.
For reference, see the Block Class module.
Comment: With mem cache #2 will give the best performance.
Comment: Depends on the amount of such classes. Drupal has a huge memory footprint problem, due to all these large "load everything into a static cache" caches, like variables, schema, views. Every single added variable makes it a tiny bit larger, doesn't matter if memcached or not.
Answer: Saving the classes in a Drupal persistent variables would make sense if the module just need to save a few classes; if the module allows the user to save an undefined number of classes, then saving them in a custom database table is what I would do.
As far as I remember, modules are not allowed to write in their own directory. Saving in a file data that needs to be retrieved seems less performant than using the database, though, especially if the code needs to get specific data, and not all the saved data.
Comment: Is there any rule of thumb for the number of classes that will not significantly undermine the performance? Also, do you happen to know if it is viable to give the user the option to choose between the variable table and a custom table? Do you happen to know if a module has already followed this method? Thx a lot for the reply.
Comment: @F1234k If you are going to allow the users to save an (virtually) unlimited number of classes, then you should already consider using a custom database table. There isn't a thumb rule for the number of items that should be saved in a Drupal variable. For example, the User module saves in Drupal variables [the content of the emails sent to the users in specific moments](http://api.drupal.org/api/drupal/modules--user--user.admin.inc/function/user_admin_settings/7); the number of the messages saved is limited, but the content of those emails could be theoretically unlimited.
Comment: If you limit the number of classes a user can set, then 10-12 classes would be fine to be saved in a Drupal variable. As far as I know, no module allows the user to set where the module values are saved. It would not make sense to let the users decide where to save the data, as it is the developer of the module who knows how the data will be used from the module; supposing the module needs to filter out the data, or make a join between those data and the data contained in a database table, how can the user know that?
Answer: I recommend option 1 too. Why shouldn't classes be in the database? That is node related context information, just like some comment related flags per node (show comments, allow comments, ..) for example.
You can store it in a separate table and reference it to the nid.
Then implement hook_entity_prepare_view() (better than hook_node_load(), because only invoked for nodes which are actually going to be displayed) and load those classes in a single query for all $entities if $type is node.
The variables table is loaded into memory on every request (completely), you should only store information there that you need frequently.


Not Able to Loop up to the end of the Column in Google Spreadsheet using Google App Script

Question: I am trying to scrape through a column using for loop and rearrange the data into different categories. Let say the raw data have the name, address, email and phone number of the customer and it is separated by comma. I was able to create a simple script that will separate the information by comma, but it wont loop to the whole column A. The script will run up to 1654 of column A only.
I would like to ask if there is a limitation in looping through columns or row using Google App Script. Also, the data is consist of 3000 data, so that is 3000 cell in a column. Is there a way that we can loop up to the last data of my sheet?
function rawDataAlteration() {
  var days = new Array('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday');
  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Raw Data');
  var data = spreadsheet.getRange('A1:A').getValues();
  var filteredData = new Array();
  for (let q in data) {
    if(data[q] != "") {
      filteredData.push(data[q]);
    }
  }
  for (let x in filteredData) {
    if (filteredData[x] != "") {
      var convertedToArray = filteredData[x][0].split(',');
      var nametoArray = convertedToArray[0].split(' ');
      var name = new Array();
      var day = "";
      var columnNum = Math.floor(x)+1;
      var nameColumn = 'A'+ columnNum;
      var dayColumn = 'B' + columnNum;
      var dateColumn = 'C' + columnNum;
      var shiftColumn = 'D' + columnNum;
      for(let i in nametoArray){
          let found = false;
          for(let j in days){
              if(nametoArray[i] == days[j]){
                  day = days[j];
                  found = true;
              }
          }
          if(!found){
              name.push(nametoArray[i]);
          }
      }
      var columnB = spreadsheet.getRange(nameColumn).setValue(name.toString().replace(',', ' '));
      var columnD = spreadsheet.getRange(dayColumn).setValue(day);
      var columnD = spreadsheet.getRange(dateColumn).setValue(convertedToArray[1]);
      // Logger.log(filteredData);
    }
  }
}

Answer: There is no limitation for looping of rows or column but there is limitation for run time. The maximum run time is 6 mins, exceeding 6 mins will cause the script to fail. See Quotas for Google Services.
These are the factors that affect the run time of your code.

Having 3 nested for loops.
Instead of using this to check if an element is present in days array:

let found = false;
for (let j in days) {
  if (nametoArray[i] == days[j]) {
    day = days[j];
    found = true;
  }
}
if (!found) {
  name.push(nametoArray[i]);
}

Use this:

  if(days.indexOf(nametoArray[i]) >= 0){
    day = days[j];
  }else{
    name.push(nametoArray[i]);
  }

Using A1:A as range means that the script will get all the value in column A including the empty cells. Example, if you have 3000 data and 1000 empty space below it, getValues() will return 4000 sub-arrays or rows of data.

To ensure that you will only take the rows that has of data, change your code
From:

var data = spreadsheet.getRange('A1:A').getValues();

To:

var data = spreadsheet.getRange(1, 1, spreadsheet.getLastRow(), 1).getValues();

3.Instead of calling setValue() multiple times, Arrange the data into a single array and use setValues(). This will lessen your function call from 9000 to 1.
Reference:

getRange(row, column, numRows, numColumns)
setValues()
Comment: I tried the script above, but it stops around 300+ cell.
Comment: @ian - How long is the run time of your script? Does it have errors?
Comment: @ian - Could share a sample spreadsheet and the expected output.


Can I use ICC (Intraclass Correlation) as a decision criteria to use a model with random intercepts or a model with random intercepts and slopes?

Question: I am thinking on using a ICC as a decision criteria for choosing a mixed model with different random structures in r
for (i in 1:nrow(distinct_pairs)) {
    dat1 <- datab

    model1 <- glmer(data = dat1, formula = var ~ condition + (condition|group), family = Gamma(link = "log"))
    model2 <- glmer(data = dat1, formula = var ~ condition + (1|group), family = Gamma(link = "log"))

#Calculate intraclass correlation so the model specification can be decided

    vars1 <- lapply(summary(model1)$varcor,diag)
vars2 <- lapply(summary(model2)$varcor,diag)
    resid_var1 <- attr(summary(model1)$varcor, "sc")^2
resid_var2 <- attr(summary(model2)$varcor, "sc")^2
    total_var1 <- sum(sapply(vars1, sum), resid_var1)
    total_var2 <- sum(sapply(vars2, sum), resid_var2)
    ICCmodel1 <- sapply(vars1, sum)/total_var1#random slopes & intercepts
    ICCmodel2 <- sapply(vars2, sum)/total_var2#random intercepts

    if (ICCmodel1>ICCmodel2) {
      model <- model1
      ICCd <- list(ICCmodel1, "S&I")
    }
    else {
      model <- model2
      ICCd <- list(ICCmodel2, "I")
    }

    ls <- lsmeans(model, pairwise~condition, adjust="tukey")
    s <- summary(ls$contrasts)

... and other secondary data tidying code.

So the question is if this would be a good use of the coefficient. I would appreciate feedback on the possibility of this method. I guess the answer is no as it is normally contingent to a range, but I would be interested if some statistician or someone with the knowledge could answer the why not.
Thanks in advance!
Answer: ICC is helpful to understanding the degree to which the outcome is correlated in your data according to different groups (the random effects you specify). However, I would not use it as a decision criteria for whether to use one model or another. You can use model testing for these purposes. The anova() command in R is perfectly suited for this. It computes a likelihood ratio test to compare nested models (models in which you can get from one model to the other by constraining parameters to 0). You can also use AIC and BIC as information criteria to compare models. See also here.
Comment: Thanks for your input Erik, this really is helpful.


closure of. a point

Question: I have this topology  on $\mathbb{R}^2$
$\tau=\{\emptyset\}\cup \{\Omega_r, r\geq0\}$ where $\Omega_r=\{(x,y)\in \mathbb{R}^2, (x-2)^2+(y+2)^2\geq r^2\}$
How to find the closure of the center $cl(\{(2,-2)\})$?
The only open which intersect the center is $\Omega_0=\mathbb{R}^2$
how to continue ?
Comment: What do you mean by *center*?
Comment: $Omega_r$ is the complement of the disc of center (2,-2) and reduce r
Answer: The set $\Bbb R^2\setminus\{(2,-2)\}=\bigcup_{r\gt0}\Omega_r$ is open.  Thus $\{(2,-2)\}$ is closed, and is its own closure.
Comment: but is $\cup_{r>0}\Omega_r$ open in this topology ?
Comment: Arbitrary unions of open sets are open.
Comment: Technically you need to consider the topology _generated_ by the open sets you gave.
Comment: Your comment is a good point: $\tau$ is a base for a topology, but $\tau$ is not a topology because $\cup_{r>0}\Omega_r \not \in \tau$.

closure of. a point


No SYN/ACK answer from server

Question: At first I describe my LAN organization. I have 2 Networks (scheme http://take.ms/s3CSy):

192.168.0.0 / 255.255.255.0, router ASUS RT-N65U with internal IP 192.168.0.1, static external IP without NAT: 188.8.131.52. Router running VPN PPTP server, VPN LAN IP range 172.16.0.0/255.255.255.0, VPN Server IP 172.16.0.1, MTU/MRU 1300. My laptop (laptop #1) in this network now.
192.168.2.0 / 255.255.255.0, router ZyXEL Keenetic 4G with internal IP 192.168.2.1, dynamic external IP with NAT: 10.0.0.1. All clients connected to switch Cisco sg200-26p.

In second LAN I have a web-server with Debian Linux and PPTP VPN client installed. PPTP client connected to router in first LAN and obtain IP 172.16.0.11. Immediately after connecting pptp client add two routes:
ip route add 172.16.0.0/24 dev ppp0
ip route add 192.168.0.0/24 dev ppp0

So route table on VPN client (Web-server):
root@system:~# ip route
default via 192.168.2.1 dev eth0
184.108.40.206 via 192.168.2.1 dev eth0  src 192.168.2.3
172.16.0.0/24 dev ppp0  scope link
172.16.0.1 dev ppp0  proto kernel  scope link  src 172.16.0.11
192.168.0.0/24 dev ppp0  scope link
192.168.2.0/24 dev eth0  proto kernel  scope link  src 192.168.2.3

On web-server "iptables -L -v -n" shows empty table.
Route table on VPN server (ASUS RT-N65U router):
/home/root # ip route
default via 22.214.171.124 dev ppp0
22.214.171.124 dev ppp0  proto kernel  scope link  src 184.108.40.206
127.0.0.0/8 dev lo  scope link
172.16.0.12 dev ppp10  proto kernel  scope link  src 172.16.0.1
192.168.0.0/24 dev br0  proto kernel  scope link  src 192.168.0.1
192.168.2.0/24 dev ppp10  scope link

On router ASUS RT-N65U I also have DynDNS activated, domain home.example.com; and 2 port forwarding settings:
1. Synology NAS web remote access: Remote port 6667, local IP: 192.168.0.2, local port 5000, Protocol BOTH (TCP & UDP)
2. Web server remote access: Remote port 6668, local IP: 192.168.2.3, local port 80, Protocol BOTH (TCP & UDP)

When I try to access to Web server (URL http_//192.168.2.3:80) from My laptop in first LAN - no problem, all works like a charm.
But if I try to access form some another laptop (laptop #2 on scheme) to Web server (URL http_//188.8.131.52:6668) - page not found. If I try to access to Synology - no problem.
I installed tcpdump on web server and captured packets:

Access from Laptop in first lan, all seems good. PCAP file https_//www.dropbox.com/s/pvg5rd4rw5omz9z/fromlan.pcap?dl=0 (replace _ with :)
Access from remote host. I see that my web-server receive SYN packets, but doesn't send ACK packets back to client. PCAP file https_//www.dropbox.com/s/hxfxudtrre12i7s/fromremote.pcap?dl=0  (replace _ with :)

On web-server installed iptstate, that shows connection from remote server:
Source                      Destination                Prt State         TTL
126.96.36.199:58540         192.168.2.3:80             tcp SYN_RECV      0:00:59

Where is the problem?
Maybe here is route problem, packets from remote server coming by VPN connection route, but outgoing by default (through 192.168.2.1) route?
Answer: Problem was in a route on web-server:
For testing added route to 184.108.40.206/24 through ppp0 interface and page opened successfully.

No SYN/ACK answer from server


Nav-burger collapse onclick

Question: Boa tarde, procuro quem me ajude a transformar um nav-burger do fontawesome (fa-fa-bars) em X quando é feito um click e vice-versa.
Comment: Tem um exemplo aq usando o animate (Style 2 – Animate To "X"): http://callmenick.com/post/animating-css-only-hamburger-menu-icons
Answer: É só adicionar um eventListener e trocar a classe do elemento validando se o menu se encontra aberto (então está fechando e deve-se trocar para fa-close) ou não (está abrindo e deve-se trocar para fa-bars).
Fica um exemplo simplório de presente.

var aberto = false;

document.getElementById('troca').addEventListener('click', function(){
  this.className  = aberto ? "fa fa-close" : "fa fa-bars";
  aberto = !aberto;
});
div { font-size: 50px; }
span { cursor: pointer; }
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">

Comment: Já consegui resolver, obrigado

Nav-burger collapse onclick


Deploying Python Flask Application on IIS with wfastcgi in Python 3.7+ with Numpy, Pandas, etc

Question: When deploying a python 3.7+ flask or Dash application on IIS using wfastcgi, there are many great tutorials to get a hello work program working such as
https://medium.com/@bilalbayasut/deploying-python-web-app-flask-in-windows-server-iis-using-fastcgi-6c1873ae0ad8
Where this process fell apart for me and seeming for other users such as
Can't get dash app run on IIS with flask server
How to deploy python flask application in conda base environment on IIS server?
was when other packages started coming into the mix such as Numpy, Pandas, Dash, Plotly Express, etc.
The error that get throw tended to depend on the package but usually resembled a large block of test that looks like the error bellow starting with Error occurred while reading WSGI handler and featuring things like Dll load failures or missing components.
Error occurred while reading WSGI handler: Traceback (most recent call last): File "C:\ProgramData\Anaconda3\envs\dash_search_app\lib\site-packages\wfastcgi.py", line 791, in main env,
handler = read_wsgi_handler(response.physical_path) File "C:\ProgramData\Anaconda3\envs\dash_search_app\lib\site-packages\wfastcgi.py", line 633,
in read_wsgi_handler handler = get_wsgi_handler(os.getenv("WSGI_HANDLER")) File "C:\ProgramData\Anaconda3\envs\dash_search_app\lib\site-packages\wfastcgi.py", line 616,
in get_wsgi_handler raise ValueError('"%s" could not be imported%s' % (handler_name, last_tb)) ValueError: "dashapp.server" could not be imported: Traceback
(most recent call last): File "C:\ProgramData\Anaconda3\envs\dash_search_app\lib\site-packages\wfastcgi.py", line 600,
in get_wsgi_handler handler = __import__(module_name, fromlist=[name_list[0][0]]) File ".\dashapp.py", line 3, in from flaskapp import app File ".\flaskapp\__init__.py",
line 67, in register_dashapps(app) File ".\flaskapp\__init__.py", line 19, in register_dashapps from flaskapp.dashapp_searchtool.layout import layout File ".\flaskapp\dashapp_searchtool\layout.py", line 30,
 in import pandas as pd File "C:\ProgramData\Anaconda3\envs\dash_search_app\lib\site-packages\pandas\__init__.py", line 17, in "Unable to import required dependencies:\n" + "\n".join(missing_dependencies)
 ImportError: Unable to import required dependencies: numpy: IMPORTANT: PLEASE READ THIS FOR ADVICE ON HOW TO SOLVE THIS ISSUE! Importing the numpy c-extensions failed. -
 Try uninstalling and reinstalling numpy. - If you have already done that, then: 1. Check that you expected to use Python3.7 from "C:\ProgramData\Anaconda3\envs\dash_search_app\python.exe",
 and that you have no directories in your PATH or PYTHONPATH that can interfere with the Python and numpy version "1.17.3" you're trying to use. 2. If (1) looks fine,
 you can open a new issue at https://github.com/numpy/numpy/issues. Please include details on: - how you installed Python
 - how you installed numpy - your operating system - whether or not you have multiple versions of Python installed - if you built from source, your compiler versions and
 ideally a build log - If you're working with a numpy git repository, try `git clean -xdf` (removes all files not under version control) and rebuild numpy. Note:
 this error has many possible causes, so please don't comment on an existing issue about this - open a new one instead. Original error was: DLL load failed:
 The specified module could not be found. StdOut: StdErr: C:\ProgramData\Anaconda3\envs\dash_search_app\lib\site-packages\flask_sqlalchemy\__init__.py:794:
 FSADeprecationWarning: SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and will be disabled by default in the future. Set it to True or False to suppress this warning.

The most common advice is to downgrade to python 3.6, however this is not possible for every project.
I've answered bellow my solution in case others may have the same issue as my hours of googling did not result in me finding a solution.
Answer: For me, this came down to a permissions issue. My first speculation was that the environment was not registering correctly, however in fact it was that IIS did not have permission to access all the dependencies of the environment.
How I resolved this was to navigate to my Anaconda3 folder, right click and select properties. In the properties window, I navigated to the security tab and clicked Edit

I then clicked 'Add' to add users and bring up the following window

Under Object Type, I selected all the options, and Locations I selected the top level location.
Under Object names I wrote iis apppool<yoursitename>
for example, for an IIS site named app, it would be iis apppool\app
I then clicked check names to ensure the app could be found, and then proceeded to click ok and apply.
Once the permissions were added, the IIS site could access all the required dlls and such and the app functioned correctly
Comment: it didnt work for me


Helper functions in jsviews

Question: I am going through the following examples in JsViews site for buttons http://www.jsviews.com/#link-button. When I modify the code to take an input and display the same in the alertbox on clicking the button, the helper function gets executed onload. Also, instead of on click of the button, the function gets executed when the input value changes. I am guessing since the model value is changed in the view, the function gets called with the updated model value but why is it not working on click of the button. I am quite new to jsviews and not able to understand what is happening. Can anyone tell me what is wrong with my approach. Below is the updated code.

<input type="text" data-link="test"/>
 <button data-link="{on ~doSomething(test)}">Do something</button>
<input type="button" data-link="{on ~doSomething(test)}" value="Do something" />

  var person = {};

var helpers = {
  doSomething: function(val) {
    alert(val);
  }
}

$.link(true, "#topLinked", person, helpers); // Data-link top-level content

Answer: You made a mistake this: data-link="{on ~doSomething(test)}".
Arguments are passed through the one or more spaces like this:  data-link="{on ~doSomething test test2 ...}".
I changed the example like this:
html

js
var person = {
    test : "start value"
};

var helpers = {
    doSomething : function (val) {
        alert(val);
        return false;
    }
}

var tmpl = $.templates("#tmpl");
tmpl.link("#result", person, helpers);

example on jsfiddle
Comment: Thanks a lot. There are a couple of examples with the wrong syntax in  https://www.jsviews.com/#helpers. Is that outdated or that is usage for a different scenaior.
Comment: @user1776573 It's not a bug, it's a feature! This is correct for _jsrender_ and
not quite right for _jsviews_. Just need to know what `~doSomething(test)` performed at the time of template render and `~doSomething test` is done at the suitable event.

Helper functions in jsviews


Another 3 level hierarchical regression

Question: I have a dependent variable: rtln (log transformed reaction time) and 3 predictors:
choicenum (ranging from 1 to 6), ifrelevant (0 and 1), and condition (0 and 1), and I have a variable with subject IDs.
I would like to estimate a model where choicenum is nested within subjects.
I use the following notation:
lmer(rtln~choicenum + ifrelevant + condition
 + (1|subject/choicenum),    data=myData)

for some reason this estimates 5 fixed effects for choicenum.

Here's the output: http://dl.dropbox.com/u/22681355/output.tiff
Here's the dataset: http://dl.dropbox.com/u/22681355/data.csv
Here's the stata output of what I'd like to get: http://dl.dropbox.com/u/22681355/output.pdf
Comment: you seem to be posting the same question using different variable names, see [here](http://stats.stackexchange.com/questions/12960/error-message-when-estimating-group-level-interactions-lmer) and [here](http://stats.stackexchange.com/questions/13161/testing-group-level-interactions-using-lmer).
Comment: so are you **really** sure you want to have `choicenum` nested within `subject`?
Comment: Your stata output has ifIncongruent as a numeric variable. It does not correspond to your question here. You should make more of an effort to describe what you want.
Comment: @wolf.rauch yes I want to have the exact same output as in stata. I want two grouping factors nested within each other.
Comment: @wolf.rauch I'm terribly sorry, I provided the wrong output. I've edited the question with the new (correct output)
Answer: I guess that you have specified choicenum as a factor, but you assume that it is numeric.
If you specify choicenum as a factor in the fixed effects part, lmer will --- as you should know from the help pages of lmer, lm and the R Introduction, estimate effects comparing all factor levels to a 'baseline' level (see ?contr.treatment and ?contrasts), so that is why you get 5 entries for choicenum in the fixed effects part.
But you need a factor in the random effects part of the equation for lmer. So you might try the following:
First, specify choicenum as numeric in your data.frame. Then, run
m1 <- lmer(rtln~choicenum + ifrelevant + condition + (1|subject/as.factor(choicenum)),
  data= YourData)

Of course you could also specify ... as.numeric(choicenum) ...
Comment: @Bernd-Weiss: yes, I know about the schools/classes :-) I have that problem too. Try to think of every student (student in N) being taught by every teacher (in M) with N>>M, and there are *repeated measures* for students:teachers. Each teacher has a "fixed effect" (i.e. some are "better" than others), and there is also variability of the teacher effect *within students*. And yes, I think that it makes more sense to include a random coefficient for `choicenum` instead of a grouping factor.
Comment: I have specified choicenum<-as.numeric(choicenum) and then entered the code you pasted. R just freezes and processes for ever. Did you manage to run this code?
Comment: problem solved: first specify subject as factor choicenum as numeric and then your code works. thank you for resolving this problem, this finally solves every question for all of my posts
Comment: @wolf.rauch Do you know any literature that shows that a grouping variable (`choicenum`) can also be included as a fixed effect? As far as I know, it makes no sense but I may be wrong...
Comment: @Bernd-Weiss: As far as I understood DBR's design, `choicenum` is a within-subjects ordered factor, so there should be no problem about its fixed effect. I had my problems with `choicenum` as a grouping factor, but now I think it might make a little sense. Beside its fixed effects, there might be different between-subjects variances at each level of `choicenum`.
Comment: @Bernd-Weiss: But I haven't really worked it out, I mainly wanted to see if it works at all ;-) I guess the more sensible model is to include both fixed and random effects for `choicenum` and then maybe to check for heteroscedasticity at different levels of `choicenum`, i.e. using `weights=varIdent(form=~1|choicenum)` in `nlme`.
Comment: @wolf.rauch Thanks for your explanation! I am still not convinced but this is probably due to my lack of understanding. I am still thinking too much in terms of countries/counties or schools/classes etc. (which are the 'natural' grouping units in my field...).

Another 3 level hierarchical regression


Statistical difference between numbers of porpoise deaths between 1989-2002 and 2021

Question: to investigate whether there has been a statistically significant difference in the
number of animals that died because of physical trauma in recent years, and 2) to
investigate whether there has been a statistically significant difference in the number of
animals that died because of infectious disease in recent years
Comment: Let's make sure it's clear what data the table contains. The way I read the table, in 1989-2002 there were 257 purposes and 131 of them died of physical trauma, 70 died of infections. What happened with the other 257 - 131 - 70 = 56 purposes? And similarly for 2021, what about the other 53 - 20 - 27 = 6 purposes?
Comment: Another point is that the first column is a period of 13 years. You'll have to make strong assumptions that the probability of death due to trauma or infections didn't vary in that period.
Comment: Hi. Welcome to CV. I notice you tagged your post with [tag:t-test]. And then you are asking what test to use. Perhaps more context is needed.
Comment: The meanings of these numbers are unclear.  Are they averages, totals, or something else?  How are we to compare the meaning of 257 porpoises during a 14 year period to 70 during a one-year period? E.g., were all 257 present all 14 years or is this a cumulative number of distinct individuals (or maybe individual-years)? It is apparent, due to features pointed out by other commenters, that some form of *survival analysis* is required to account for the different durations and that strong assumptions must be made about how disease and death rates might vary over time.
Answer: Your data is not continuous. It consists of natural integers (deaths). This means there are no 0.33 deaths or 0.56 deaths, and so on. So strictly speaking, it could be convenient for you to use a so-called "non-parametric" test, like the Mann Whitney U Test, the Wilcoxon Signed Rank Test or the Kruskal-Wallis Test.
However, if you are not bothered by results as "an average of 2.5 deaths" and similar, and there is a big debate around such issues among social scientists, you can either use t-tests or analysis of variance (ANOVA), for each of the categories in the two groups. You have to pick one of these methods.
The t-test is more common for smaller samples (i.e. under 30), and ANOVA is normally used when you are comparing the means of more than two groups. In both cases, you have to define your level of confidence for when your results will be significant (for example 90 % or 95 %, which means p-values have to be smaller than 0.1 or 0.05 respectively). And for reliable results, you have to make sure that the data fulfill the assumptions of the particular tests you are performing.
For instance, t-tests can be one-sided, two sided, paired (for data that is not independent), your groups could have homogeneity of variances or not, for which you have to run a modified test that accounts for this. ANOVA can be one way, which means you just compare the means of two groups, or two-way, when you take into account factors. These factors could be your categories. ANOVA works for groups with homogenous variances. Other important assumptions for the tests are independence of groups and normal distribution of variables. If all this is fulfilled, t-tests and ANOVA are reliable. If not, you are probably better off with the non-parametric tests, which have less assumptions.
Roughly speaking, for any of the tests, what you will be looking for is if the means (averages) in each of the groups are confidently different from each other or not. What this means is if you are mostly sure that the data points are around the observed means, to a degree of certainty that makes it possible for you to conclude that the possible differences in means confidently reflect differences between the observations in the groups. You determine this degree of confidence, by choosing your critical value and p-value.
In the case of the parametric tests, which tend to be more common, both the t-test and ANOVA take in consideration how the data points are disseminated around the mean in each of the groups. If the data points are not neatly aligned around the mean, there is less confidence in the differences between the means of the groups.
For example, consider a hypothetical Group A, with four observations: 15, 585 and 1400 and 4000, for an average of 1500, and another Group B, with four observations: 2900, 3000, 3100 and 3000, for an average of 3000. The average of Group B is double the average of Group A. However, is this difference "significant"? It is easy to see that Group A has a larger dissemination of data around the mean than Group B. In other words, Group A has a population variance of 2325612.5, whereas group B has a population variance of just 5000. If you consider another, Group C, with observations 1400, 1500, 1500 and 1600, which also has an average of 1500, like Group A, the difference in means between Group C and B would be more significant than the difference between Group A and B. Because Group C only has a variance of 5000, compared to the variance of 2325612.5 in Group A. This means that the observations in Group C are closer to the mean of 1500, so we can be more confident that the differences between most observations in Group B and C are reflected in the means, to a larger extent than the differences between observations in Group A and B. The differences in the means between Group A and B could be greatly explained due to individual values in Group A, but not most of the values for our confidence level. If we run two-sided t-tests, that assume homogeneity of variances, the p-value for the difference in means between Group B and A is 0.14, which is not significant for a confidence level of 95 % nor 90 %. But the difference between Group B and C (and remember that Group C has the same average as Group A) has a p-value of 2.14E−07 (or much closer to zero), which would be significant at a confidence level of 95 %.
If I interpret your table correctly, it contains averages. You want to run the tests on the individual observations that are the basis to calculate these averages. This means you have to have access to this information. It is the only way you will be able to account for variance or similar measures of how the data is organized around the mean.
Comment: I believe there are fundamental characteristics to this problem that rule out any of the approaches you suggest, mainly because of the possibility of radically different interpretations of the data.  See my comment to the question.


Batch file input phone number

Question: I wrote a batch file to send a text message to the phone number %number%. (if your curios, it uses curl and the textbelt.com system).  I used a overly-complicated way for having the user input a phone number.  I restricted the characters to only numbers, automatically ten characters long, and automatically add dashes.
Here's my code:
:start
cls
echo Enter phone number:
choice /c 0123456789 >nul
set x=%errorlevel%
set /a x1=%x% - 1
cls
echo Enter phone number:
echo %x1%
choice /c 0123456789 >nul
set x=%errorlevel%
set /a x2=%x% - 1
cls
echo Enter phone number:
echo %x1%%x2%
choice /c 0123456789 >nul
set x=%errorlevel%
set /a x3=%x% - 1
cls
echo Enter phone number:
echo %x1%%x2%%x3%-
choice /c 0123456789 >nul
set x=%errorlevel%
set /a x4=%x% - 1
cls
echo Enter phone number:
echo %x1%%x2%%x3%-%x4%
choice /c 0123456789 >nul
set x=%errorlevel%
set /a x5=%x% - 1
cls
echo Enter phone number:
echo %x1%%x2%%x3%-%x4%%x5%
choice /c 0123456789 >nul
set x=%errorlevel%
set /a x6=%x% - 1
cls
echo Enter phone number:
echo %x1%%x2%%x3%-%x4%%x5%%x6%-
choice /c 0123456789 >nul
set x=%errorlevel%
set /a x7=%x% - 1
cls
echo Enter phone number:
echo %x1%%x2%%x3%-%x4%%x5%%x6%-%x7%
choice /c 0123456789 >nul
set x=%errorlevel%
set /a x8=%x% - 1
cls
echo Enter phone number:
echo %x1%%x2%%x3%-%x4%%x5%%x6%-%x7%%x8%
choice /c 0123456789 >nul
set x=%errorlevel%
set /a x9=%x% - 1
cls
echo Enter phone number:
echo %x1%%x2%%x3%-%x4%%x5%%x6%-%x7%%x8%%x9%
choice /c 0123456789 >nul
set x=%errorlevel%
set /a x10=%x% - 1
set number=%x1%%x2%%x3%%x4%%x5%%x6%%x7%%x8%%x9%%x10%
cls
echo is this the correct number?
echo. %number%
choice /c yn
set x=%errorlevel%
if %x%==2 goto start

As you can see, it is really long and complicated.  It works, but its what you call "spaghetti code".  I am willing to bet that there is a MUCH simpler way to achieve my goal.
Answer: If you can use an external program, you can use editv32.exe (32-bit) or editv64.exe (64-bit) program to get input into an environment variable. Sample shell script (batch file):
@echo off
setlocal enableextensions
set PHONE=
editv32 -l 10 -n -p "Enter phone number: " PHONE
echo You entered: %PHONE%

-l 10 limits input length to 10 characters, and -n allows only numeric input. You can download editv32.exe/editv64.exe from here: http://www.westmesatech.com/editv.html (Copyrighted freeware)
Answer: An idea :
@echo off
setlocal enabledelayedexpansion
    cls
:start
set number=
for /l %%a in (1,1,9) do (
cls
if defined number echo !number!
echo Enter phone number:
choice /c 0123456789 >nul
set /a x=!errorlevel!-1
set  number=!number!!x!
)

echo is this the correct number?
echo. %number:~0,3%-%number:~3,3%-%number:~6,3%
choice /c yn
set x=%errorlevel%
if %x%==2 goto start

Answer: You may use ReadFormattedLine subroutine in a very simple way; for example:
:start
cls
call :ReadFormattedLine number="###-###-####" /M "Enter phone number: "
echo Is this the correct number?
choice /c yn
if %errorlevel% equ 2 goto start
echo The correct number is: %number%

This subroutine is written in pure Batch so it does not require any additional program, and it allows several formatted input operations, like read passwords, conversions to uppercase letters, etc. You may download it from: Read a line with specific format.
Answer: My open-source editenv tool replaces my older editv32/editv64 utilities:
https://github.com/Bill-Stewart/editenv
Sample usage:
editenv -n 10 -a 0123456789 -p "Enter phone number: " PHONE

This command will display an Enter phone number: prompt and wait for input. Input length is limited to 10 characters (-n), and allowed characters are limited to numbers (-a).
Download here:
https://github.com/Bill-Stewart/editenv/releases

Batch file input phone number


Display column headings on multiple tables from different lists

Question: I have a view in ASP.NET MVC that accesses a viewmodel with 2 separate lists.  The problem I am having is accessing the column headings from the lists to display them above each data set.  The foreach statements accurately display the data but currently I am using a foreach statement on the column headings as well (Display name for).  I need to modify this statement to access the list (NotesList) and to only display one iteration of them above the dataset shown in the td statements.  I appreciate your feedback.  The view is below.
@model Risk.ViewModel.ListCatViewModel
....

    @foreach (var item in Model.NotesList)
    {

            @Html.DisplayNameFor(modelItem => item.Category)
            @Html.DisplayNameFor(modelItem => item.CountOfLoans)
            ....

    }
    @foreach (var item in Model.NotesList)
    {

            @Html.DisplayFor(modelItem => item.Category)
            @Html.DisplayFor(modelItem => item.CountOfLoans)
            ....

    }

Comment: I got it to work by manually typing the column headings in each th html tag.  However, I am looking for an automated solution as if I change the class that ties to the sql server that will change the columns and then I would have to change each column heading in the view vs. having an automated solution.
Answer: You can create your  elements using
@Html.DisplayNameFor(m => m.NotesList.FirstOrDefault().Category)
@Html.DisplayNameFor(m => m.NotesList.FirstOrDefault().CountOfLoans)
....

Note this works even of the FirstOrDefault() returns null (i.e. because the collection is empty) because HtmlHelper use values from the objects ModelMetadata
Side note: Recommend you header elements be wrapped in a


Windows Phone and Website Request

Question: I wish to send a request to a Website (server) to update a potential scoreboard which everyone who has the application can see. This website isn't of course restricted to just the application users - but it can be accessible to anyone.
Is it possible to call a WCF from a Windows Phone app for example where the WCF can then update the database. So whenever someone goes on the website, the updated changes will be seen.
Is this at all possible? And if it is, would this be the most sensible/optimised way of doing things?
Answer: I did this using a BsckgroundWorker in my ViewModel to prevent hanging the UI. This way, you can "set it and forget it". Something like this:
<code>private void UpdateScoreboard()
{
  var scoreboardWorker = new BackgroundWorker();
  scoreboardWorker.DoWork += (s,dwe)=>{
       //call some WCF service compleate async
  };
  scoreboardWorker.RunWorkerCompleted += (s,rwe)=>{
       // check whether rwe.Error is not null, indicating an exception. Show an alert maybe
  };
  scoreboardWorker.RunWorkerAsync();
}
</code>

Windows Phone and Website Request


Discrete Mathematics - Intersection of a collection of sets

Question: Let $ B_n $ = (0,$\frac{1}{n}]$ for all n ∈ N.
(a) Find $ ⋂_{n=1}^∞ = B_n $ and
(b) For each n ∈ N, find $ ⋂_{k=1}^n = B_k $
I know that the answer to (a) is ∅ but for (b) I think that when n ≠ 1, the answer is (0,$\frac{1}{n}]$ because n ≠ ∞ as ∞ ∉ N.
Am i right?
Answer: You are right, but it's true for $n = 1$ as well. The key is to notice that the $B_k$ are nested, i.e.
$$B_1 \supset B_2 \supset B_3 \supset \cdots,$$
thus
$$\bigcap_{k=1}^{n}B_k = B_n = (0,1/n].$$
Answer: For a), as you said the answer is indeed $\emptyset$ due to the following:
Assuming it is nonempty, let $r \in \bigcap_{n=1}^{\infty} B_n $. It follows that $0 < r \leq \frac{1}{n}$ for every $n \in \mathbb{N}$. By the Archimedean Principle, there is an $n_0 \in \mathbb{N}$ such that $\frac{1}{n_0} < r$. But we also have $r \leq \frac{1}{n_0}$ (by assumption), a contradiction. Thus the intersection is empty.
For part b) you are also correct, but for it's also true for $n=1$. That is, $\bigcap_{k=1}^{n} B_k  = B_n$. We can prove this by induction if you want the details.
Certainly for $n = 2$,
$$\bigcap_{k=1}^{2} B_k = B_1 \cap B_2 = (0, 1] \cap (0, \frac{1}{2}] = (0, \frac{1}{2}] = B_2$$
Suppose this holds for all such intersections up to $n$ and let us consider the intersection of $n + 1$:
$$ \bigcap_{k=1}^{n+1} B_k = \bigcap_{k=1}^{n} B_k \cap B_{n+1}$$
By the induction hypothesis, the above intersection is simply
$$ B_n \cap B_{n+1} = (0, \frac{1}{n}] \cap (0, \frac{1}{n+1}] = (0, \frac{1}{n+1}] = B_{n+1}$$
as desired.


Internet Explorer 7 transparency fix

Question: I have a menu that has a transparent background with the following CSS:
background-color: transparent;
background-color: rgba(113,157,174,0.7);
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#99dddddd,endColorstr=#99dddddd);
-ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#99dddddd,endColorstr=#99dddddd)";

In IE, it doesn't have any color; it is just white. I used an Internet Explorer fix, in which I used the following code:
filter: alpha(Opacity=45);
background-color: #0010A5;
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#99dddddd,endColorstr=#99dddddd);
-ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#99dddddd,endColorstr=#99dddddd)";

The only thing this did was to make it purple, but it wasn't transparent at all.
![screenshot][1]

I know it is possible because I've seen it done before. What am I doing wrong? How do I fix it?
Answer: I found the answer, it was in fact filter: alpha(Opacity=45); inside the IE fix, but apparently it needed to be in the -inner of the class, instead of the regular class.
Answer: Did you try the PNG Fix module? Maybe it can solve the problem.
Comment: I'm working off of drupal 7, that only has versions for 5 and 6.
Comment: You can try http://drupal.org/project/pngbehave then.
Comment: It's not an image file though. it's just a menu with a background-color. will it still work?

Internet Explorer 7 transparency fix


How do you remap a share to a different drive?

Question: I want to write a start up script to take an mapped drive, change the drive letter, then put a different share on the original drive. How can this be done?
Comment: Check out the answer to this question as it might help you in capturing the drive path prior to the delete command: http://stackoverflow.com/questions/840677/how-can-i-get-a-drive-list-from-a-batch-file
Answer: Absolutely.
If for example the existing drive is X: and has \server1\shareA on it and you wanted to remap X: to Y:you could do it with a batch script.
net use x: /delete
net use y: \\server1\shareA

If you need to pass credentials you'd have to add the username (and possibly the password if you want it to run totally automated.  Note that it's a bad idea to do this with privileged accounts and there are way smarter ways.  But for a quick change over this will do it
net use x: /delete
net use y: \\server1\shareA <password> /user:<username>

If you don't include the password it will prompt.   You can save this in a .bat file and it will run just fine.
EDITED TO ADD more complete solution
So you want to take a drive mapping X: change it to Y: and then connect X: to the new share \server1\newshare?  Here you go.  You can of course still pass credentials if necessary.
for /F "skip=1 tokens=3" %%i IN ('net use x:') = DO (
        set OLDSHARE=%%i
        goto :DONE
        )
:DONE

net use x: /delete
net use y: %oldshare%
net use x: \\server1\newshare

The for loop parses out the existing share path for the drive letter you want to change.  Then you disconnect it from x: reconnect it to y: and then connect the new thing to x: all in quick succession.
Comment: Is it possible to pick up the location of the existing share before deleting it?
Comment: You mean determine it from the script?  Possibly with a bit of fancy parsing.  net use with no arguments returns all the mapped network shares.  Net use with only the drive letter returns information including the remote name.
Comment: I edited my answer above.  Hopefully this is what you want.  It's sort of quick and dirty but it works.
Comment: Hmm, I'm trying to figure out what question you answered with "Absolutely". ;)
Answer: Check out the NET USE command.
You will need to delete the current mapping, then remap with the desired drive letters and shares.
Answer: net use X: /DELETE
net use X: \\newshare

Where X: is the drive letter you want to map and \\newshare is the location of the new share you want mapped


O que é o ponto de interrogação em uma query?

Question: Usar ? em uma query realmente evita o SQL injection? Evita 100%? Vi este código e ouvi muitas pessoas falando sobre isso, dizendo que ajuda neste caso e como usar? Alguém poderia dar um exemplo melhor?
$query = "SELECT * FROM tabela WHERE username = ? OR username = ?";

Answer: Este é um placeholder para uma consulta parametrizada (parameterized query).
É um parâmetro anônimo para a query. Ele é usado para evitar SQL Injection mesmo, mas não só. Com ele não dá para injetar partes de uma query dentro da sua query.
Seria algo como usar "SELECT * FROM tabela WHERE username = $par1 OR username = $par2" mas tem a vantagem que é controlado pelo banco de dados através da API do PHP ao invés de puramente pelo PHP, portanto é bem mais seguro. O banco de dados terá a query pronta esperando o parâmetro. Não é uma string com a query. O SQL injection ocorre por causa da manipulação de strings que, por acaso, contém queries.
Uma das formas de usar seria:
$stmt = $mysqli->prepare("SELECT * FROM tabela WHERE username = ? OR username = ?");
$stmt->bind_param('ss', $userName, $userName);

Desta forma há a vinculação da variável $userName do PHP para os dois parâmetros que a query SQL está esperando.
Este é um recurso disponível no banco de dados. Isto é chamado de prepared query. Originalmente é usado para agilizar a execução da query. Com ele uma query é cacheada pelo planejador do banco de dados permitindo algumas otimizações já que apenas os parâmetros são diferentes mas a execução segue o mesmo esquema sempre. Em alguns casos o ganho pode ser considerável.
Como consequência você ganha uma segurança maior contra SQL injection. Mas é importante notar que a segurança vem mais por um efeito colateral do recurso. Você evita que algo assim possa acontecer sem o programador perceber:
$query = "SELECT * FROM tabela WHERE username = $userName";

Suponha que alguém digite e $userName receba "" OR 1 = 1; DROP TABLE tabela;. Pronto, sua tabela foi para o espaço.
Este recurso de prepared query é disponibilizado pela API mysqli do PHP e é usado da forma indica acima.
Usei o exemplo do MySQL que é o banco de dados mais usado com PHP mas pode ser usado com qualquer outro banco de dados que forneça alguma forma de "consultas preparadas". Portanto não precisa usar apenas a mysqli. Se o banco de dados e a API do PHP que faz o acesso fornecerem o recurso, é possível usá-lo de forma padronizada. Portanto não é algo que o PHP faz por você, isto vem do banco de dados.
Só para complementar:
$stmt = $pdo->prepare("SELECT * FROM tabela WHERE username = :user OR username = :user");
$stmt->bindParam(':user', $userName);

Coloquei no GitHub para referência futura.
Isto é o PDO onde você tem mais controle como o parâmetro é usado, você coloca mais significado do que está passando e onde ele é usado. Não estou dizendo que o PDO é necessariamente melhor. Em alguns casos a sintaxe pode ser um pouco diferente.
Referência.
Sintaxe do SQL do MySQL se for usar o recurso independente do PHP ou quiser entender melhor o recurso.
Comment: Interessante, não sabia desta questão de ser o banco de dados, ao invés do php.Também não sabia que agilizava a execução da query...
Comment: Me surgiu uma outra dúvida, mas vou colocar como pergunta, se der me responde lá também. Cara estou gostando disso. Receber conhecimento é algo impolgante. Valeu ai bigown!
Comment: Se não for relacionado, é melhor outra pergunta mesmo. Se eu souber e tiver tempo, eu respondo. Eu ainda vou melhorar algumas coisas na pergunta, mas vou fazer com calma agora.
Comment: Se vale a sugestão, tecnicamente *paramterized query* é a técnica em si, a interrogação é um simples *placeholder*
Comment: @BrunoAugusto Boa, fica melhor assim mesmo, editado. O crédito é seu.
Comment: *Oh! Stop it you...* :p
Answer: Problemas de injeção de código podem ocorrer sempre que você mistura duas linguagens separadas. Por exemplo, bugs de injeção de SQL ocorrem quando tratamos dados do usuário como código SQL e passamos para o banco de dados executar e defeitos de XSS (cross site scripting) surgem quando pegamos texto do usuário e passamos para o browser como se fosse HTML (e esse HTML pode conter tags script).
Num mundo ideal, ao invés de usar strings pra representar tanto a query quanto os dados do usuário (permitindo que dados e código sql sejam concatenados/interpolados de forma perigosa) usaríamos tipos separados para esses valores que proibissem misturar um com o outro.
Tudo bem, mas então, como programar para evitar problemas com injeção?
Uma primeira alternativa é oferecer uma função de "escape", que converta dados do usuário em código seguro. Por exemplo, em HTML convertemos todos os & em & e em SQL protegemos as aspas. Usar uma função de escapa é uma abordagem bastante simples e comum mas você tem que ter cuidado para não escapar algo duas vezes sem querer, já que essa operação normalmente não é não é idempotente.
A segunda alternativa no caso do SQL é parametrizar a query. Ao invés de sair concatenando as coisas na mão você diz (com os ? ou alguma sintaxe similar) onde estão as "lacunas" da query e o próprio banco preenche essas lacunas com os parâmetros, que são passados separadamente. Como os dados do usuário são passados para o banco como parâmetros, não há risco deles serem executados como código SQL.


Como usar o valor de saída

Question: Gostaria de saber como uso o valor de uma entrada depois que eu uso o botão ok!, pois preciso usar o valor da entrada que servirá como o raio, para poder fazer o calculo que será impresso dentro das outras duas labels.
<!DOCTYPE html>

    <title>area da esfera</title>
    <meta charset="utf-8">

        Informe o raio<input type="text" name="raio">
        <button id="BUTTON" name = "button">OK!</button>

        Área<input type="text" name="area" id = "circunferencia" disabled="" />

        Volume<input type="text" name="circunferencia" id = "circunferencia" disabled="" />

Answer: Tem várias coisas que precisa de corrigir primeiro:

number entrada = - Isso não existe. Para declarar uma variavel tem de usar uma das três possibilidades: var, let ou const.
entrada = document.getElementsByTagName("raio"); - O <input> que você quer ir buscar:
<input type="text" name="raio">

É uma etiqueta <input> e não <raio>, por esse motivo não iria funcionar com getElementsByTagName. Para além disso essa função devolve uma "lista" com todos os inputs que jogam com o nome passado, logo teria que indicar que quer o primeiro com [0].
AreaEsf =  entrada * entrada  * 3.14; - Assumindo que chegava ao <input> necessário, é necessário interpretar o seu valor com .value e ainda transformar em numero com parseInt antes sequer de o utilizar.
A busca de BUTTON é feita duas vezes sem necessidade:
var buttons = document.getElementById("BUTTON");
...
document.getElementById("BUTTON").onclick = function() {

Acabando por apenas complicar o código.

Haveria muitas outras coisas a melhorar, mas alterando apenas esses erros que eu indiquei, e deixando o código o mais parecido com o que tinha ficaria assim:
var buttons = document.getElementById("BUTTON");

//getElementsByName em vez de ByTagName e a posição [0]
var entradaInput = document.getElementsByName("raio")[0];

buttons.onclick = function() { //utilizar o buttons de cima
    //interpretar o valor do input com .value e transformar em numero com parseInt
    var entrada = parseInt(entradaInput.value);

    var AreaEsf =  entrada * entrada  * 3.14; //com var em vez de number
    var VolEsf  = (4/3) * 3.14 * entrada * entrada * entrada; //com var em vez de number
    document.writeln(AreaEsf);
    document.writeln(VolEsf);
}

Exemplo a funcionar:

<!DOCTYPE html>

    <title>area da esfera</title>
    <meta charset="utf-8">

        Informe o raio<input type="text" name="raio">
        <button id="BUTTON" name = "button">OK!</button>

        Área<input type="text" name="area" id = "circunferencia" disabled="" />

        Volume<input type="text" name="circunferencia" id = "circunferencia" disabled="" />

Answer: Bastam poucas linhas de código javascript.

Basicamente, recupera o valor digitado, faz uma comparação se é um positivo, processa os cálculos e coloca os values nos devidos inputs

function Calcular() {
//recupera valor digitado
var radius = document.getElementById('raio').value;

  if (0 < radius){
    var resultArea = document.getElementById("area").value = (radius * radius * Math.PI).toFixed(2);
    var resultCirc = document.getElementById("circunferencia").value = (2 * (Math.PI) * radius).toFixed(2);
    var resultVolume = document.getElementById("volume").value = ((4/3) * (Math.pow(radius, 3)) * (Math.PI)).toFixed(2);
  }else{
    alert("Erro - o raio deve ser um número inteiro maior que 0.");
    return false;
  }
}
label{
    display: inline-block;
    width: 200px;
    text-align: right;
}
  Informe o raio
  <input type="text" id="raio" size="10" />

  Área <input type="text" name="area" id="area" disabled="" />

  Volume <input type="text" name="volume" id="volume" disabled="" />

  Circunferência <input type="text" name="circunferencia" id="circunferencia" disabled="" />
  <input type="button" value="OK!" onclick="Calcular()"/>

A função Math.pow() retorna a base elevada ao expoente, ou seja, baseexpoente

No exemplo do volume: raio3

document.getElementById, função javascript que serve para retornar um elemento do DOM que é identificado por um ID específico e que deve ser único
Em um controle HTML do tipo textbox, password ou uma textarea, poderemos utilizar a propriedade value que se refere ao valor do campo.

Se não houver a necessidade de utilizar uma variável

poderemos , então, acessar diretamente:

document.getElementById("area").value = (radius * radius * Math.PI).toFixed(2);

Answer: Olá, dei uma mexida no teu código, vê se era isso que você estava querendo fazer.

var button = document.getElementById('BUTTON');
var inputRaio = document.getElementById('raio')
var inputArea = document.getElementById('area')
var inputCircunferencia = document.getElementById('circunferencia')

button.addEventListener('click', function () {
    var raio = inputRaio.value;

    if (!raio.length) {
      alert('Por favor, insira um valor no raio');
      inputRaio.focus();
      return false;
    }

    inputArea.value = raio * raio * 3.14;
    inputCircunferencia.value = (4 / 3) * 3.14 * raio * raio * raio;
});

Informe o raio
<input type="text" name="raio" id="raio">

Área
<input type="text" name="area" id="area" disabled="" />

Volume
<input type="text" name="circunferencia" id="circunferencia" disabled="" />

<button id="BUTTON" name="button" type="button">OK!</button>

Como usar o valor de saída


2sls - instrumental variables mean and variance of exogenous variable

Question: I do not usually use two-stage-least-square regression technique and I am not a theorist of econometrics; thus, I hope you will pardon me for this (possibly) clumsy post.
Introduction
Let's start from the second stage.
Here, I regress the outcome variable on the control variables plus the predicted covariate of interest, which comes from the first stage.
At the first stage, I regress my endogenous variable on at least one instrument, plus all of the control variables used in the second stage.
The instrument has to fulfill two assumptions: i) INDEPENDENCE, that is, it cannot directly affect the outcome variable of the second stage (i.e. it has to be valid), and it has to be as good as randomly assigned; ii) MONOTONICITY, for all of the units of observation, the instrument has to affect the endogenous variable in the same direction (i.e. there are no defiers).
Moreover, the instrument cannot only weakly affect the endogenous variable.
After I have computed the estimates from this regression, I compute the predicted covariate of interest, which will be used as a covariate in the second stage (see above).
First, I describe the situation, pose my question, and then provide an example:
I do not have a proper instrumental variable in my dataset, so I have to create one.
My question is:
can I compute the mean and the variance of the endogenous variable by group (i.e. by age group and by nationality) and use them as instrumental variables?
I have never seen done it, and there must be a good and banal answer for that--which I cannot see at this time of the day.
For instance, assume that my endogenous variable is x3, but this variable is endogenous only for a few people (i.e. most of the people are compliers, although there are a few never-takers and always-takers) and thus I will have to implement a 2SLS to gain a causal interpretation of b3_hat.
These are the variables:
Y = salary; x1 = age; x2 = gender; x3 = education; x4 = parents' country of birth; x5 = first language
I compute the mean and the variance of education (x3) by age (x1) and gender (x2).
Then I proceed as usual:
Stage 1 (endogenous variable = x3)

x3 = z0 + z1mean_x3 + z2var_x3 + z3x1 + z4x2 + z5x4 + z6x5 + error
compute x3_hat to be used in Stage 2

Stage 2

Y = b0 + b1x1 + b2x2 + b3x3_hat + b4x4 + b5*x5 + error

z1 and z2 do not directly affect y.
z1 and z2 return the expected level of x3--i.e. as if it was exogenous, z3-z5 tell us the individual deviation from that expected level.
Comment: The info displayed in this question does not reflect a case study; so, the example I have provided might or might not reflect the literature on the economics of education.
Answer: A relatively recent way to create instrumental variables--when your data set does not include instruments yet--is the method proposed in the following paper:

Lewbel, A, 2012.  Using Heteroscedasticity to Identify and Estimate Mismeasured and Endogenous Regressor Models.  Journal of Business and Economic
  Statistics, 30:1, 67-80. http://fmwww.bc.edu/EC-P/wp587.pdf.

In short, potential instruments are created exploiting the existence of heteroskedastic error; thus, the greater the degree of heteroskedasticity, the higher is the correlation between the generated instruments and the
endogenous variable(s).
Lewbel's approach may be applied when: (i) no (or too few) external instruments are available; (ii) to supplement external instruments to improve the efficiency of the IV estimator (you have the right amount of instruments, but you want more).
Point (ii) is relevant also because it allows the researcher to conduct Sargan-Hansen tests on the orthogonality conditions or overidentifying restrictions--the latter test is not feasible when the number of instrumented variables is equal to the number of instrumental variables.
[For interested Stata users, the user-written xtivreg2 and the ivreg2h routines allow the researchers to construct these instruments automatically]
Answer: Recently, I have found one additional alternative, that is, the use of imperfect instruments.
In the case of imperfect instruments, the INDEPENDENCE assumption is weakened.

Nevo, A., Rosen, A. M. (2008) Identification with Imperfect Instruments. NBER Working Paper No. 14434. https://www.nber.org/papers/w14434.pdf

The authors assume that

(i) the correlation between the instrument and the error term has the same sign as the correlation between the endogenous regressor and the error term, and (ii) that the instrument is less correlated with the error term than is the endogenous regressor.

I have not read any application of this method; however, several studies in very good journals use it: https://scholar.google.com/scholar?cites=3308366933447025703&as_sdt=8000005&sciodt=0,19&hl=it


Calculate the variance explained in matrix Y by matrix X

Question: I have two matrices corresponding to the same set of $n$ samples, with $j$ and $k$ variables, respectively ($j > 10000$, $k > 10000$). $X$ is an $n \times j$ matrix and $Y$ is an $n \times k$ matrix.
I'm interested to know what proportion of the overall variance of $Y$ can be explained by $X$. The ultimate goal is to compare $X$ to a similar matrix $X'$ and see which one explais $Y$ and what overlap in the explained variance these both matrices have.
My first approach was to try PLS, however I don't understand this method enough to know what I'm doing, and in any case, the implementation I tested (pls package in R) exited with an error indicating the failure to allocate half a terabyte of memory.
Furthermore, I was considering a following approach (possibly this is re-inventing the wheel; also, it might be completely wrong). PCA can partition the variance in both $X$ and $Y$, such that the resulting components have variances that sum up to 1, and are orthogonal. Therefore, I could try to calculate for the first component of $PCA(Y)$, what percentage of variance is explained using $X$; in R code, I'd try
set.seed(2708)
data(iris)
Y    <- iris[,1:4]
X    <- apply(Y, 2, function(x) x + rnorm( length(x), sd= 0.5))
pcaX <- prcomp(X, scale.= TRUE)
pcaY <- prcomp(Y, scale.= TRUE)

lm.m <- lm(pcaY$x[,1] ~ pcaX$x)
print( summary( lm.m )$r.squared)
# [1] 0.9319846

Then I could add these values for each component, multiplied by the fraction of variance in Y that this component holds:
Yvars <- pcaY$sdev^2/sum(pcaY$sdev^2)
foo   <- apply(pcaY$x, 2, function(y) summary(lm(y ~ pcaX$x))$r.squared)
print(sum(foo * Yvars))
# [1] 0.7993989

X2    <- apply(Y, 2, function(x) x + rnorm(length(x), sd= 5))
pcaX2 <- prcomp(X2, scale.= T)
foo2  <- apply(pcaY$x, 2, function(y) summary(lm(y ~ pcaX2$x))$r.squared)
print(sum(foo2 * Yvars))
# [1] 0.1344896

Does this make ANY sense? Computationally, it works as intended, i.e. the $X$es that are less predictive for $Y$ get a lower value.
However, it does not work (obviously) when $n < j$ (I thought one might choose first $m < j$ components that include 99% of the variance).
Finally, I would like to have a test or criterion to compare $X$ and $X'$.
Comment: Hi @January! I know this is an old question, but I was wondering if you had time to look at my answer; I am curious what you think about it.
Answer: Yes, you did re-invent the wheel.

What proportion of the overall variance of $Y$ can be explained by $X$

This question is answered by $R^2$ of linear regression, it's just that in this case you have to deal with multivariate regression. Still, you can regress your whole matrix $\mathbf Y$ on $\mathbf X$ (both centered) by finding matrix $\mathbf B$ minimizing $\|\mathbf Y-\mathbf X\mathbf B\|$, and then proportion of explained variance is given by $$R^2 = 1-\frac{\|\mathbf Y-\mathbf X\mathbf B\|^2}{\|\mathbf Y\|^2}.$$ It is probably a one-liner in R using lm.
What you did is a complicated way to compute the same quantity. You can regress each variable in $\mathbf Y$ on all variables in $\mathbf X$, take $R^2$ multiplied by the fraction of variance of $\mathbf Y$ that this variable captures, and sum over all variables. You can replace $\mathbf X$ by its principal components. You can replace $\mathbf Y$ by its principal components too. In each case you will get the same number.
Finally, regarding the situation when there is less data points than dimensions in $\mathbf X$. In this case $R^2 = 1$, because any $\mathbf Y$ can be explained by any $\mathbf X$: you can find $\mathbf B$ such that $\mathbf Y=\mathbf X\mathbf B$ holds exactly.


How do you plot survival functions for specific values of covariates in SAS?

Question: Suppose I do the following:
<code>    proc phreg data = new;
         model time*censor(0) = x y;
    run;
</code>
Also suppose $x$ is a binary variable and $y$ is a continuous variable. How would I plot the survival function for $x = 1$ and $y = 100$ (for example) in SAS?
Answer: From the help files of phreg (assuming neither X or Y in your example are time varying):
<code>ods graphics on;
    proc phreg data=Myeloma plots(overlay)=survival;
    model Time*VStatus(0)=LogBUN HGB;
    baseline covariates=Inrisks out=Pred1 survival=_all_ / rowid=Id;
    run;
    ods graphics off;
</code>
The COVARIATES= option in the BASELINE statement specifies the data set that contains the
set of covariates of interest. The PLOTS= option in the PROC PHREG statement creates the survivor
plot. The OVERLAY suboption overlays the two curves in the same plot. If the OVERLAY
suboption is not specified, each curve is displayed in a separate plot. The ROWID= option in the
BASELINE statement specifies that the values of the variable Id in the COVARIATES= data set be
used to identify the curves in the plot. The SURVIVAL=ALL option in the BASELINE statement
requests that the estimated survivor function, standard error, and lower and upper confidence limits
for the survivor function be output into the SAS data set specified in the OUT= option.
The survival Plot (Output 64.8.1) contains two curves, one for each of row of covariates in the data
set Inrisks.
Comment: I'm assuming its because your data is censored after 10% of the data experiences the event?
Comment: That is what I did. But it seems that the survival functions stops at 0.9. So it doesn't go all the way down to 0.


jQuery uncaught reference error $foo is not defined

Question: I'm trying to expand and collapse single divs on click using jQuery on the Laravel Spark framework.  My code is mostly coming from the answer to this question.
When the selectShow text is clicked, the alert works fine, but the console shows this error "Uncaught ReferenceError: $selectShow is not defined".  Even if I use the exact code from the link I provided, I get the error.  A quick search mentioned that jQuery needs to be the first thing to load, but I've already placed this function in the document ready function block.  Also, the alert works fine (as do other jQuery functions I'm using), which is why I don't think that this is an issue with loading jQuery improperly.
There's probably a simple answer to this, but I'm at a loss.  Thanks.
Code:

Show Media

.mediaContainer {
    width:100%;
}
.mediaContainer div {
    width:100%;
}
.mediaContainer .selectShow {
    font-size: 12px;
    color: #0084B4;
    padding: 5px;
    cursor: pointer;
}
.mediaContainer .media {
    display: none;
}

$(".selectShow").click(function () {
    alert('Click!');
    $selectShow = $(this);
    $media = $selectShow.next();
    $(".media").not($media).slideUp().prev().text("Show Media");
    $media.slideToggle(500, function () {
        $selectShow.text(function () {
            return $media.is(":visible") ? "Hide Media" : "Show Media";
        });
    });

});

Comment: @PraveenKumar That's why I was so confused... the code I was using worked fine within a fiddle, but not on my site.  I'm not sure why, but Alexander's idea of declaring vars helped it work.  Thanks for checking it out!
Comment: Maybe you want to declare `$selectShow` and `$media` with `var`? Perhaps they are being overwritten by some other code because they are not locally scoped.
Comment: @AlexanderO'Mara The code works as expected.
Comment: @AlexanderO'Mara Thank you!  I declared them with var and now the code works (more or less) like it's supposed to.  If you post your comment as an answer, I'll accept it.
Answer: You're code can work as-is, but you may be running into problems with global name collision and your $selectShow ends up being overwritten.
So solve this, declare you local variables with var. Then they will not pollute the global space, and you can avoid naming collision with other uses of the variable.
$(".selectShow").click(function () {
    alert('Click!');
    var $selectShow = $(this);
    var $media = $selectShow.next();
    $(".media").not($media).slideUp().prev().text("Show Media");
    $media.slideToggle(500, function () {
        $selectShow.text(function () {
            return $media.is(":visible") ? "Hide Media" : "Show Media";
        });
    });
});


Port Forwarding with Cisco SR520 IOS

Question: I've been tasked with setting up port forwarding for access to remote desktop on a server. I'm having trouble making it work.
Server IP 192.168.1.20, port 3389
The router is a Cisco SR520. It is behind our ISP's modem, which has an IP of 192.168.5.1. Their modem's NAT should be sending incoming connections to 192.168.5.100 (which is the router's IP for that interface, FastEthernet4).
We do have a couple VLANs, the server is on VLAN 1.
I'm not much of a network guy, just dipping my feet in. I believe the NAT is configured to forward the port correctly, and I added access-list rules to allow it. There's also some zone security, which I'm not sure about however. Does this look correct? Did I miss something?
<code>ip source-route
!
!
ip dhcp excluded-address 192.168.75.1 192.168.75.10
ip dhcp excluded-address 192.168.1.1 192.168.1.64
ip dhcp excluded-address 192.168.10.1 192.168.10.64
ip dhcp excluded-address 192.168.20.1 192.168.20.64
!
ip dhcp pool inside
   import all
   network 192.168.75.0 255.255.255.0
   default-router 192.168.75.1
!
ip dhcp pool dpool1
   import all
   network 192.168.1.0 255.255.255.0
   default-router 192.168.1.1
   domain-name midwaybc.org
   dns-server 22.214.171.124 184.108.40.206
!
ip dhcp pool dpool10
   import all
   network 192.168.10.0 255.255.255.0
   default-router 192.168.10.1
   domain-name midwaybc.org
   dns-server 188.8.131.52 22.214.171.124
!
ip dhcp pool dpool20
   import all
   network 192.168.20.0 255.255.255.0
   default-router 192.168.20.1
   domain-name midwaybc.org
   dns-server 220.127.116.11 22.214.171.124
!
!
ip cef
no ip domain lookup
ip domain name Midwaybc.org
ip name-server 184.108.40.206
ip name-server 188.8.131.52
!
no ipv6 cef
multilink bundle-name authenticated
!
!
username cisco privilege 15 secret 5 {REMOVED}
!
!
!
archive
 log config
  logging enable
  logging size 600
  hidekeys
!
!
!
class-map type inspect match-any SDM-Voice-permit
 match protocol h323
 match protocol skinny
 match protocol sip
class-map type inspect match-any sdm-cls-icmp-access
 match protocol icmp
 match protocol tcp
 match protocol udp
class-map type inspect match-any sdm-cls-insp-traffic
 match protocol cuseeme
 match protocol dns
 match protocol ftp
 match protocol h323
 match protocol https
 match protocol icmp
 match protocol imap
 match protocol pop3
 match protocol netshow
 match protocol shell
 match protocol realmedia
 match protocol rtsp
 match protocol smtp extended
 match protocol sql-net
 match protocol streamworks
 match protocol tftp
 match protocol vdolive
 match protocol tcp
 match protocol udp
class-map type inspect match-all sdm-invalid-src
 match access-group 100
class-map type inspect match-all sdm-protocol-http
 match protocol http
!
!
policy-map type inspect sdm-permit-icmpreply
 class type inspect sdm-cls-icmp-access
  inspect
 class class-default
  pass
policy-map type inspect sdm-inspect
 class type inspect sdm-invalid-src
  drop log
 class type inspect sdm-cls-insp-traffic
  inspect
 class type inspect sdm-protocol-http
  inspect
 class type inspect SDM-Voice-permit
  pass
 class class-default
  pass
policy-map type inspect sdm-inspect-voip-in
 class type inspect SDM-Voice-permit
  pass
 class class-default
  drop
policy-map type inspect sdm-permit
 class class-default
  drop
!
zone security out-zone
zone security in-zone
zone-pair security sdm-zp-self-out source self destination out-zone
 service-policy type inspect sdm-permit-icmpreply
zone-pair security sdm-zp-out-self source out-zone destination self
 service-policy type inspect sdm-permit
zone-pair security sdm-zp-in-out source in-zone destination out-zone
 service-policy type inspect sdm-inspect
zone-pair security sdm-zp-out-in source out-zone destination in-zone
 service-policy type inspect sdm-inspect-voip-in
!
!
!
interface Loopback0
 ip address 10.108.1.1 255.255.255.0
!
interface FastEthernet0
 switchport mode trunk
!
interface FastEthernet1
 switchport access vlan 10
!
interface FastEthernet2
 switchport access vlan 10
!
interface FastEthernet3
!
interface FastEthernet4
 description $FW_OUTSIDE$
 ip address 192.168.5.100 255.255.255.0
 ip nat outside
 ip virtual-reassembly
 zone-member security out-zone
 duplex auto
 speed auto
!
interface Vlan1
 ip address 192.168.1.1 255.255.255.0
 ip nat inside
 ip virtual-reassembly
 zone-member security in-zone
!
interface Vlan10
 description $FW_INSIDE$
 ip address 192.168.10.1 255.255.255.0
 ip nat inside
 ip virtual-reassembly
!
interface Vlan20
 description $FW_INSIDE$
 ip address 192.168.20.1 255.255.255.0
 ip access-group 130 in
 ip nat inside
 ip virtual-reassembly
 zone-member security in-zone
!
interface Vlan75
 description $FW_INSIDE$
 ip address 192.168.75.1 255.255.255.0
 ip nat inside
 ip virtual-reassembly
 zone-member security in-zone
!
router rip
 version 2
 network 192.168.1.0
 network 192.168.10.0
 network 192.168.20.0
 no auto-summary
!
ip forward-protocol nd
ip route 0.0.0.0 0.0.0.0 192.168.5.1
ip route 192.168.1.0 255.255.255.0 172.17.14.1
ip route 192.168.10.0 255.255.255.0 172.17.14.1
ip route 192.168.20.0 255.255.255.0 172.17.14.1
!
ip http server
ip http authentication local
ip http secure-server
ip http timeout-policy idle 60 life 86400 requests 10000
ip nat inside source list 1 interface FastEthernet4 overload
ip nat inside source static tcp 192.168.10.2 5060 interface FastEthernet4 5060
ip nat inside source static udp 192.168.10.2 5060 interface FastEthernet4 5060
ip nat inside source static tcp 192.168.10.2 1720 interface FastEthernet4 1720
ip nat inside source static tcp 192.168.1.20 3389 184.108.40.206 3389 extendable
ip nat inside source static tcp 192.168.1.20 3389 192.168.5.100 3389 extendable
!
access-list 1 remark SDM_ACL Category=2
access-list 1 permit 192.168.75.0 0.0.0.255
access-list 1 permit 192.168.10.0 0.0.0.255
access-list 1 permit 10.1.1.0 0.0.0.255
access-list 1 permit 192.168.1.0 0.0.0.255
access-list 1 permit 192.168.20.0 0.0.0.255
access-list 100 permit udp any host 192.168.1.20 eq 3389
access-list 100 permit tcp any host 192.168.1.20 eq 3389
access-list 100 remark SDM_ACL Category=128
access-list 100 permit ip host 255.255.255.255 any
access-list 100 permit ip 127.0.0.0 0.255.255.255 any
access-list 130 deny   ip 192.168.20.0 0.0.0.255 192.168.0.0 0.0.255.255
access-list 130 permit ip any any
!
!
!
!
!
control-plane
!
banner login ^C{REMOVED}^C
!
line con 0
 password 7 {REMOVED}
 no modem enable
line aux 0
line vty 0 4
 password 7 {REMOVED}
 transport input telnet ssh
!
scheduler max-task-time 5000
ntp server 188.8.131.52 prefer
end
</code>
Answer: I figured it out, the issue was with the zone based firewall.
All I needed was the NAT rule, plus to modify the firewall to allow specific incoming ports.
I found this article very useful and explained everything needed for zone-based port forwarding.

Port Forwarding with Cisco SR520 IOS


Is there an alternative console for administering websites in IIS6?

Question: I've used many web site hosting services in the past and I've grown very comfortable with the web based site administration tools. Does anyone have a recomendation for a replacement for IIS Managment Console? Perhaps something that would provide a web based interface for administering web sites.
Answer: You can use the Remote Administration (HTML) Tool that comes with Windows/IIS to accomplish this.  Microsoft has a couple of relevant articles that cover this topic:

http://support.microsoft.com/kb/324282
http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/aae1d311-103e-4b06-8788-e6b0554d7230.mspx?mfr=true


JQuery Accordion Multi Opens with Different Background Colors

Question: Below is a code for JQuery Accordion Multi Opens.  It is working fine.  I want to change different background colors for open and close tags, but Don't have any idea.
Please give a hand.  Thanks
LIVE CODE
HTML

Section 1

    Mauris mauris ante, blandit et, ultrices a, suscipit eget, quam. Integer
    ut neque. Vivamus nisi metus, molestie vel, gravida in, condimentum sit
    amet, nunc. Nam a nibh. Donec suscipit eros. Nam mi. Proin viverra leo ut
    odio. Curabitur malesuada. Vestibulum a velit eu ante scelerisque vulputate.

Section 2

    Sed non urna. Donec et ante. Phasellus eu ligula. Vestibulum sit amet
    purus. Vivamus hendrerit, dolor at aliquet laoreet, mauris turpis porttitor
    velit, faucibus interdum tellus libero ac justo. Vivamus non quam. In
    suscipit faucibus urna.

Section 3

    Nam enim risus, molestie et, porta ac, aliquam ac, risus. Quisque lobortis.
    Phasellus pellentesque purus in massa. Aenean in pede. Phasellus ac libero
    ac tellus pellentesque semper. Sed ac felis. Sed commodo, magna quis
    lacinia ornare, quam ante aliquam nisi, eu iaculis leo purus venenatis dui.

List item one

List item two

List item three

Section 4

    Cras dictum. Pellentesque habitant morbi tristique senectus et netus
    et malesuada fames ac turpis egestas. Vestibulum ante ipsum primis in
    faucibus orci luctus et ultrices posuere cubilia Curae; Aenean lacinia
    mauris vel est.

    Suspendisse eu nisl. Nullam ut libero. Integer dignissim consequat lectus.
    Class aptent taciti sociosqu ad litora torquent per conubia nostra, per
    inceptos himenaeos.

JS
jQuery('#accordion').accordion({ collapsible:true, active:false, autoHeight:         false, disabled:true});
jQuery('#accordion h3.ui-accordion-header').click(function(){
      jQuery(this).next().slideToggle();
});
jQuery('.accordion-expand-all').click(function(){
      jQuery('#accordion h3.ui-accordion-header').next().slideDown();
});

Answer: You should add a class on active items with .addClass(), .toggleClass().
jQuery('#accordion').accordion({ collapsible:true, active:false, autoHeight:         false, disabled:true});
jQuery('#accordion h3.ui-accordion-header').click(function(){
      jQuery(this).toggleClass('active').next().slideToggle();
});
jQuery('.accordion-expand-all').click(function(){
      jQuery('#accordion h3.ui-accordion-header').addClass('active').next().slideDown();
});

.active { background: orange !important; }

Fiddle: http://jsfiddle.net/AR57Y/70/