How to get Twitter-Bootstrap navigation to show active link?

Question: I'm not understanding how Twitter Bootstrap does active links for the navigation. If I have a regular navigation like this (with ruby on rails linking):

 Link

 Link

 Link

How do I keep it active based on the link clicked?
Comment: FYI: I use the active_link_to gem and specify {:wrap_class => :li}. This will create: ... when the REQUEST_URI matches the HREF value...
Answer: You can use something like (very similar to what @phil mentioned, but a little shorter):

  <li class="<%= 'active' if current_page?(root_path) %>"><%= link_to "Home", root_path %>

  <li class="<%= 'active' if current_page?(about_path) %>"><%= link_to "About", about_path %>

  <li class="<%= 'active' if current_page?(contact_path) %>"><%= link_to "Contact", contact_path %>

Comment: doesn't work if you have subnavigation. The path changes but you're in the same section.. makes sense?
Comment: yes, correct, if you want to highlight a menu item no matter what method you are running inside the same controller, you could use @Pierre solution: `'active' if params[:controller] == 'controller1'`
Comment: How can I add more paths or a specific path like `user_*_path` in `<%= 'active' if current_page?(root_path) %>` ?
Comment: How would you add more than one path to make the menu item active? For instance, if you have several items in a dropdown that are components of the same menu item, and you'd like to make the menu item active when you're on any of the pages found in the dropdown menu? Please let us know as soon as possible.
Answer: Just made an answer on the very same question here
Twitter Bootstrap Pills with Rails 3.2.2

  <li class="<%= 'active' if params[:controller] == 'controller1' %>"> Link

  <li class="<%= 'active' if params[:controller] == 'controller2' %>"> Link

  <li class="<%= 'active' if params[:controller] == 'controller3' %>"> Link

Comment: I think the idea is correct here, but going directly to the params hash seems like a bad idea. Likewise for repeating the same code over and over. I would recommend at least using the current_page? method to check the current controller/action, and would also move the code into a helper to avoid the code repetition.
Comment: HAML implementation `%li{:class => "#{'active' if current_page?(root_path)}"}=link_to "Home", root_path `
Comment: Rails docs recommends the use of `controller_name` and `action_name` helpers instead of accessing them from  the params hash.
Comment: I wonder how do I write the same in haml. Converting to haml doesn't work for me. Or perhaps I'm wrong somewhere
Comment: Is there an elegant way of making this work with friendly_id gem without doing db requests?
Comment: Or another one for HAML: `%li{class: params[:controller].nil? ? 'active' : ''}= link_to 'Home', root_path`
Answer: https://github.com/twg/active_link_to
<%= active_link_to 'Users', users_path, :wrap_tag => :li %>

#=>
Users

Comment: Love it.  Why rewrite the wheel?
Comment: This should really be the way to go...Unless you don't want to pull in another dependency.
Answer: I used a helper to implement this in the style of Rails' form helpers.
In a helper (e.g. app/helpers/ApplicationHelper.rb):
def nav_bar
  content_tag(:ul, class: "nav navbar-nav") do
    yield
  end
end

def nav_link(text, path)
  options = current_page?(path) ? { class: "active" } : {}
  content_tag(:li, options) do
    link_to text, path
  end
end

Then, in a view (e.g. app/views/layouts/application.html.erb):
<%= nav_bar do %>
  <%= nav_link 'Home', root_path %>
  <%= nav_link 'Posts', posts_path %>
  <%= nav_link 'Users', users_path %>
<% end %>

This example produces (when on the 'users' page):

Home

Posts

Users

Comment: This is great! Thanks!
Comment: I like this idea, however I'd add a third argument to the nav_link function called html={} that's then passed to link_to.  That way you can pass an html hash to nav_link the same way you'd use link_to normally.
Answer: Use this instead to select active link in nav based on the current route without server code:
    $(document).ready(function () {
        $('a[href="' + this.location.pathname + '"]').parent().addClass('active');
    });

Comment: This is the best solution cause it works with dropdown menus as well, and I include the line ```$('li.active').closest('.dropdown').addClass('active');``` to highlight the parent menu too.
Comment: how to change it to apply for sub-pages also? like http://example.com/home will work. I need link "Home" to be active in case of http://example.com/home/page also.
Answer: I've found success using the logical and (&&) in haml:
%ul.nav
  %li{class: current_page?(events_path) && 'active'}
    = link_to "Events", events_path
  %li{class: current_page?(about_path) && 'active'}
    = link_to "About Us", about_path

Answer: For each link:
<% if current_page?(home_path) -%>
<% else -%>
<% end -%>
  <%= link_to 'Home', home_path %>

or even
<li <% if current_page?(home_path) -%>class="active"<% end -%>>
  <%= link_to 'Home', home_path %>

Answer: not sure if you are asking about how the twitter bootstrap css is used, or the rails side.  I'm assuming the rails side.
if so checkout the #link_to_if method
or the #link_to_unless_current method
Answer: Today I had the same question/problem but with an other approach for the solution.
I create a helper function in application_helper.rb:
def navMainAktiv(actionName)
    if params[:action] == actionName
    "active"
    end
end

and the link looks like this:
<li class="<%= navMainAktiv('about')%>"><%= link_to "About", about_path %>

You can replace params[:action] with params[:controller] and set your controller name in the link.
Answer: Basic, No Helper
<%= content_tag(:li, class: ('active' if request.path == '/contact')) do %>
    <%= link_to 'Contact', '/contact' %>
<% end %>

I use this since I have more than one class -
<%= content_tag(:li, class: (request.path == '/contact' ? 'active black' : 'black')) do %>
    <%= link_to 'Contact', '/contact' %>
<% end %>

Comment: This will work for any sub navigation also...just use the parent request path in the sub link.
Answer: I use this for each li:

<%= link_to_unless_current('Home', root_path) {  link_to('Home', root_path, class: 'active') } %>

Comment: Class needs to be set for `li` not `a`
Answer: You may define a helper method in application_helper.rb
def create_link(text, path)
  class_name = current_page?(path) ? 'active' : ''

  content_tag(:li, class: class_name) do
    link_to text, path
  end
end

Now you can use like:
create_link 'xyz', any_path which would render as

  xyz

Hope it helps!
Answer: Here's what I did:
I created a ViewsHelper and included in ApplicationController:
include ViewsHelper

Inside ViewsHelper I created a simple method like this:
def page_state(path)
  current_page?(path) ? 'active' : ''
end

In my view I do this:
<li class="<%= page_state(foobar_path) %>"><%= link_to 'Foobars', foobar_path %>

Answer: You should do it yourself by manipulating CSS classes. That is, if a user clicks on some link, then do something (target action), set previous link inactive and new link active.
If your links take you to the server (that is, make page reload), then you can just render active link correctly on the server. Otherwise, if you're doing some client-side stuff (switching tab panes or whatever), you have to use javascript.
Answer: you could use tabulous for the links
article here on how to combine tabulous with twitter bootstrap and rails 3.x
Answer: I wrote simple helper method using build in view helper current_page? when you can specify custom class name in html_options hash.
def active_link_to(name = nil, options = nil, html_options = nil, &block)
  active_class = html_options[:active] || "active"
  html_options.delete(:active)
  html_options[:class] = "#{html_options[:class]} #{active_class}" if current_page?(options)
  link_to(name, options, html_options, &block)
end

Examples (when you are on root_path route):
<%= active_link_to "Main", root_path %>
# Main

<%= active_link_to "Main", root_path, class: "bordered" %>
# Main

<%= active_link_to "Main", root_path, class: "bordered", active: "disabled" %>
# Main

Answer: Many of the answers here have things that will work, or partial answers. I combined a bunch of things to make this rails helper method I use:
# helper to make bootstrap3 nav-pill
's with links in them, that have
# proper 'active' class if active.
#
# the current pill will have 'active' tag on the

#
# html_options param will apply to
, not .
#
# can pass block which will be given to `link_to` as normal.
def bootstrap_pill_link_to(label, link_params, html_options = {})
  current = current_page?(link_params)

  if current
    html_options[:class] ||= ""
    html_options[:class] << " active "
  end

  content_tag(:li, html_options) do
    link_to(label, link_params)
  end
end

It could be made even fancier with argument checking to support &block on the link_to etc.
Answer: Many answers already, but here is what I wrote to get Bootstrap Icons working with active link. Hope It will help someone
This helper will give you:

li element with link containing custom text
Optional Bootstrap3 Icon
will turn active when you're on the right page

Put this in your application_helper.rb
def nav_link(link_text, link_path, icon='')
  class_name = current_page?(link_path) ? 'active' : ''
  icon_class = "glyphicon glyphicon-" + icon

  content_tag(:li, :class => class_name) do
    (class_name == '') ? (link_to content_tag(:span, " "+link_text, class: icon_class), link_path)
    : (link_to content_tag(:span, " "+link_text, class: icon_class), '#')
  end
end

And use link:
<%= nav_link 'Home', root_path, 'home'  %>

Last argument is optional - it will add icon to the link. Use names of glyph icons.
If you want icon with no text:
    <%= nav_link '', root_path, 'home'  %>

Answer: You sound like you need to implement a navigation system. If it's complex, it might get pretty ugly and pretty fast.
In this case, you might want to use a plugin that can handle that. You could use navigasmic or simple navigation (I would recommend navigasmic because it keeps the main layer in a view, where it belongs, and not in some configuration)
Answer: Shortest code
This deals with BOTH nav, and sub nav list elements. You can pass either an array a single path and will deal with both.
application_helper
# Active page method
def ap(p:);'active' if p.class == Array ? p.map{|m| current_page? m}.any? : (current_page? p) end

view (html.erb)

  <li class="<%= ap p: home_path %>">Home

  <li class="<%= ap p: account_path %>">Account

  <li class="dropdown <%= ap p: [users_path, new_user_path] %>">
    Users

      <li class="<%= ap p: users_path %>">Users

      <li class="<%= ap p: new_user_path %>">Add user

Answer: Using ruby on Sinatra ..
I m using bootstrap bare theme, here is the sample navbar code. Note the class name of the element -> .nav - as this is referred in java script.
/ Collect the nav links, forms, and other content for toggling
    #bs-example-navbar-collapse-1.collapse.navbar-collapse
      %ul.nav.navbar-nav
        %li
          %a{:href => "/demo/one"} Page One
        %li
          %a{:href => "/demo/two"} Page Two
        %li
          %a{:href => "/demo/three"} Page Three

in the view page (or partial) add this :javascript, this needs to be executed every time page loads.
haml view snippet ->
- content_for :javascript do
  :javascript
      $(function () {
          $.each($('.nav').find('li'), function() {
              $(this).toggleClass('active',
                  $(this).find('a').attr('href') == window.location.pathname);
          });
      });

In the javascript debugger make sure you have value of 'href' attribute matches with window.location.pathname. This is slightly different than the solution by @Zitrax which helped me fixing my issue.
Answer:   def active_navigation?(controllers_name, actions_name)
   'active' if controllers_name.include?(controller_name) && actions_name.include?(action_name)
  end

slim
li class=(active_navigation?(['events'], ['index', 'show'])) = link_to t('navbar.events'), events_path

Answer: This worked for me:
          <li class="nav-item <%= 'active' if current_page?(root_path) %>" >
            <%= link_to 'Home', root_path, class:"nav-link"%>

          <li class="nav-item <%= 'active' if current_page?(tools_path) %>" >
            <%= link_to 'Tools', tools_path, class:"nav-link" %>

            Request a new tool

          <li class="nav-item <%= 'active' if current_page?(home_about_path) %>" >
            <%= link_to 'About us', home_about_path, class:"nav-link"%>

The code inside the <%= %> is just ruby, and the = means that the result of that code will be displayed on the HTML.Do this for every option you want to add in your navbar and it should work fine.


Is it safe to return a string object which points to a local char variable

Question: I believe that the following code is safe to return the string, even though inelegant, and works as expected, but I'd like confirmation of that, and I'd also like a test case to wrap around it that proves it is safe; ie that the contents of the string are available to the caller via .c_str() method, after the stack is re-used: ie, how can I force the stack on which the local variable resides to be freed/re-used (I'm using Visual Studio 2019 and PVS-Studio static code analysis, neither of which generates a warning). I don't like replacing the local szLocalTime with a global, nor do I like the idea of a malloc in the function as that places the onus on the caller to free. I've added some examples of cases that fill in the char[], eg C lib or Win32 functions that don't know about strings.
string FormatTimestamp(SYSTEMTIME st)
{
    char szLocalTime[1000];

    szLocalTime[0] = 0;

    // *** Some code that depends on a char buffer fills szLocalTime...
    // eg. strftime(szLocalTime, sizeof(szLocalTime)...);
    // eg. GetDlgItemText(hDlg, ID, szLocalTime, sizeof(szLocalTime));

    string s = szLocalTime; // <-- the question relates to this
    return s;
}

Comment: std::strings don't "point" to anything
Comment: Anything named an iterator, view, range or ptr will need to keep the original source around. However, most standard containers make copies and don't need the original.
Comment: Unrelated: Possibly `*** Some code that fills szLocalTime in Here ***` could take advantage of a `std::stringstream` or [Howard Hinnant's Date library](https://github.com/HowardHinnant/date) to simplify things.
Comment: Are you sure you meant your code like that? Maybe you were actually wondering about [returning a reference to a local var](https://stackoverflow.com/questions/4643713/c-returning-reference-to-local-variable)? Which in your case would mean changing the function signature to returning a string&.
Answer: std::string always copies its initializer. So it is safe.
Answer: As stated by Maxim, std::string always makes a copy of whatever it's given, so this is safe to do. If you want to avoid copying, you could also just do this:
string FormatTimestamp(SYSTEMTIME st)
{
    std::string szLocalTime(1000, '\0');

    // String automatically initialized to 0
    // *** Some code that fills szLocalTime in Here ***

    szLocalTime.resize(strlen(szLocalTime.data()));
    return szLocalTime; // <-- the question relates to this
}

Comment: `std::string szLocalTime(1000);` won't compile.  You need `std::string szLocalTime(1000, 0);`  which means  `szLocalTime[0] = 0;` is not needed.
Comment: @BiagioFesta The copying of the characters is avoided by this solution. Move semantics are irrelevant.
Comment: Moreover, with *move semantic* the string is not copied, just moved.


When do $\epsilon$-Nash equilibrium strategies converge to Nash equilibrium strategies?

Question: Suppose I have a game on $n$ players and a sequence of strategy profiles $(s_1^{(1)},\dots,s_n^{(1)}), (s_1^{(2)},\dots,s_n^{(2)}), (s_1^{(3)},\dots,s_n^{(3)}), \dots$.
Each $(s_1^{(i)},\dots,s_n^{(i)})$ is a $\epsilon_i$-Nash equilibrium, and the sequence $\epsilon_1,\epsilon_2,\epsilon_3,\dots$ converges to zero.
My questions:

When (under what conditions/assumptions) do all the strategies converge? That is, for each player $j$, $s_j^{(1)},s_j^{(2)},s_j^{(3)},\dots$ necessarily converges.
Under what further conditions is the limit of this sequence actually a Nash equilibrium of the game?

Thanks very much!
Answer: This was too long for a comment. Do you have a specific game being considered? Just your property 1 is not true for in general, even for $2 \times 2$ games.
For convergence, you need that, in two strategy profiles, if player $i$ is best-responding up to $\epsilon_1$ and $\epsilon_2$ respectively, then the distance (assuming strategies lie in a metric space) between his strategies $s_1$ and $s_2$ is controllable by $|\epsilon_1 - \epsilon_2|$. Take any $2 \times 2$ game with two Nash equilibrium strategy profiles $\sigma_1$ and $\sigma_2$. Let player 1's strategies in the two profiles be $s_1$ and $s_2$ respectively and $s_1 \neq s_2$. Here $\epsilon_1 = \epsilon_2 = 0$. But the sequence of strategies $s_1, s_2, s_1, s_2, \cdots$ is clearly divergent.
For (2), again in general it's too much to hope for. Let's assume $s_i^1 \rightarrow s_1$ with $\epsilon_i \rightarrow 0$. The sequence $\{s_i^1\}$ is only one way to perturb the response $s_1$. This is much weaker than the definition of NE. (What you have is something akin to the consistency condition for off-equilibirum beliefs in a sequential equilibrium. Stability under one sequence of approximating beliefs is much weaker than stability under any small perturbation of the given belief.)
But in specific models you can arrange for these (very special) conditions. For example, in the Rubinstein bargaining model, this is probably true.
Comment: Thanks for responding! Yes, so, what I hope to find out is the exact sufficient condition for (1) to hold. I guess we need a unique equilibrium, which is not what I was thinking of. So maybe there is some other question I should be asking to capture this intuition?
Comment: But even if there's no nice answer to (1), maybe there is something interesting to say about (2)?
Comment: Was too long for comment again, so I added to the above answer.


How do you count the 1st 4 bars of Beethoven's Pathétique, Op. 13, 1st movement?

Question: There are two counting problems in the opening of Beethoven's Pathétique, Op. 13, 1st movement.

How do the subdivisions of the beat work here?
The tempo is very slow, so it can be hard to keep a steady pulse.

Here are the first two measures. Getting these should take care of what I'm looking for.
Comment: It might helps us if you can explain why counting it "1 & 2 & 3 & 4 &", etc., isn't working for you.
Comment: There's insufficiant detail for any good answers so far.
Comment: Please clarify: are you asking about counting for the purpose of "feeling" the pulse, or do you have trouble to realize the rhythm at all?
Answer: In 8.
But maybe just a couple of times in 32 (well, 4 groups of 8) if you're having trouble grokking the rhythm.
ONE 2 3 4 5 6 7 8 1 2 3 FOUR FIVE 6 7 EIGHT ONE 2 3 4 5 6 7 8 ONE 2 3 4 (5 6 7 8).

Would it be more approachable written like this?   Same thing...

Now, the  decision whether to play it absolutely metronomically, slightly relaxed, or 'over-dotted' in 'French overture' style.    Welcome to the wonderful world of musical (and historical) interpretation.  The one way this sort of music ISN'T played is with rigid obedience to the notation.  Enter the notes into a sequencer to remind yourself why!
Comment: Well, "count in 8" usually means that you count 8 beats where there are 4 (so, eights in this case), and for this case it also makes sense: if that was an orchestral piece, the conductor would probably use 4 beats with subdivisions. The fact is that, while "scanning" all 32nds could help for precision, excessive subdivision is never really helpful in music, as in most cases the result that it breaks the phrasing, often making it sound more slow and "fatigued" than it should.
Comment: No, you're not getting what I mean: "count in 8" means counting to 8 for each **bar**. So, in this case, it also means counting *eights*. Your "count in 8" means "8 for each *beat*" (so, technically it's more like "counting in 32" or "4 times 8"), and that's really not a good suggestion for the reasons I wrote above.
Comment: For what counting should *count* (pun intended), I doubt any pianist would *really* count it like that.
Comment: What, not in 8?
Comment: And that is exactly the point I made!  32 if necessary to pin it down.  Then 8 to perform.  Sorry if my answer was that unclear!
Comment: @musicamante When I first learned this piece, I had great difficulty feeling the proportions, so I counted it exactly the way Laurence suggests. It was, as you suggest, mechanical at first, but once I understood the timing I could then relax the counting to allow for the musicality.
Comment: @Aaron I'm not saying that's completely wrong, counting the smallest subdivisions can be useful to *understand* the rhythm *at first*, but, as I said in the first comment, from the point of view of "counting" in the *musical* sense (related to the beat - the "rithmic breath"), similar to what a conductor physically does, and I believe in the sense the OP was asking too, one should only count in eights at most.
Comment: @musicamente - What's wrong with 1 e & a, etc.? That's counting in 16s, right?
Comment: I've updated the question and voted to reopen. I tried to update so that your answer would remain pertinent, but FYI in case there's a need to revise.
Answer:
The subdivisions work the same way as they normally do, but the thirty-second notes are divisions of the subdivisions

At very slow tempi the key is to make your counts fractions of a beat.  I count this piece with one count for every half beat (so I'm counting in eighths).  The 32nd notes then become a subdivision of the count:

1 (2) (3) a 4 a 5 (6) 7 (8)


Prove $\sum_{k = 1}^n \mu(k)\left[ \frac nk \right] = 1$

Question: I need to prove the identity $$\sum_{k = 1}^n \mu(k)\left[ \frac{n}{k} \right] = 1$$ where $n$ is a natural number, and $[n]$ denotes the floor function. The proof also should not use the Möbius Inversion Formula; I'm looking for something elementary. I've tried to give a counting argument, and to give a proof using the identity $$\sum_{d|n}^n\mu(d)= 0$$ for $n > 1,$ but I haven't succeeded. What's a good way to solve this problem?
Comment: Ah yes, that's classical. Indeed that comes in handy, see my answer below. The last equality is from that identity. Though your example doesn't match the formula still.
Comment: If $n=3$ your "identity" gives $1-1-1=-1\ne 0$.
Comment: Does it? If $n = 3$ we get $$\mu(1) \cdot 3 + \mu(2) \cdot 2 + \mu(3) \cdot 1 = 3 - 2 - 1 = 0.$$
Comment: Reread what you wrote, you don't have the $k$ factor in it the way you wrote it.
Comment: Oh, woops, I was not paying attention. I'll fix that.
Answer: I guess the direct way is to write out the hyperbola summation
$$\sum_{k\le n}\mu(k)\sum_{d\le {n\over k}}1$$
$$=\sum_{dk\le n}\mu(k)$$
Now, this is all products with values $\le n$. But then this is the same as summing over all products $dk$ which are equal to each of the different integers $\le n$, hence we get:
$$=\sum_{i=1}^n\left(\sum_{dk=i}\mu(d)\right)=1+\underbrace{0+0+\ldots+0}_{n-1\text{ times}}$$
The last equality because aside from $i=1$ all the other sums on the inside are $0$ because

$$\sum_{d|n}\mu(d)=\delta(n)$$

where
$$\delta(n)=\begin{cases} 1 & n=1 \\ 0 &\text{o/w}\end{cases}$$
Comment: Can you explain how the third equality follows from the second a little more? Thanks.
Comment: Do you mean the third equality or the third line, because the third equality is just that last bit.
Comment: The third equality, as in, the second double summation. I think I'm confused because I'm not really understanding your notation on the second line. What are you iterating in the summation?
Comment: @JamesPirlman those two designators are registering as totally separate objects to me, can you type exactly which summation you want to how it follows from the previous?
Comment: Sure. I'm confused about what the summation $\sum_{dk \leq n} \mu(k)$ means, and why it is equal to $$\sum_{i=1}^n\left(\sum_{d|i} \mu(d) \right).$$
Comment: @JamesPirlman try taking a look now.
Comment: That makes much more sense to me now. Thanks!


Finding the right joint distribution

Question: I'm starting a research on Multi-Object-Tracking, the current state-of-the-art real-time methods have a detector that outputs a bounding_box and an embedding vector: $$ e \in \mathbb{R}^n $$
When a new target is found the embedding is saved and a new Kalman filter is created and together they form a tracker .
Each frame the the detections and the trackers are matched in the following manner:
the embedding distance  (i.e. cosine distance) and the Mahalanobis distance(Kalman to bounding box) are measured  between all the trackers and detections.
the distances are merged using a simple blending:
$$d = \lambda e + (1- \lambda) m ; \lambda \in [0,1] $$
what I'm trying to investigate is to what is the proper representation of these two distances (if I can do any thing to improve their performance).
what I reached so far is that there is some correlation between these values:
$$  \rho_{x,y} = \frac{E[ (x - \mu_x) (y - \mu_y)^T]} {(\sigma_x  \sigma_y)} = 0.23$$
the histograms:

How should I approach this problem?
Answer: Based on your title and the two histograms, a simple bivariate scatter plot, histogram, etc. would be useful without any fancy modeling.  The marginal distributions look like a log-normal, gamma, or other familiar skewed distribution.  You don't necessarily need to fully specify the joint distribution to account for the correlation between the marginal endpoints.  You could use generalized estimating equations to model the means and variances using the mean-variance relationship of, say, a log-normal distribution while accounting for the correlation between observations using either a model-based correlation structure or an empirical sandwich covariance estimate.  You could use the resulting parameter estimates and their standard errors to perform inference on other aspects of the marginal distributions, like percentiles, by fully specifying lognormal marginal distributions.  If you ultimately end up just focusing on describing and inferring the aspects of the marginal endpoints, ignoring the correlation is not so awful.  The resulting estimation and inference is still valid, it is just not as efficient.
Let me know if I have addressed your question or if you had something else in mind.

Finding the right joint distribution


How to create M365 dynamic groups from CSV file using powershell

Question: I've been tasked with creating 1600 O365 dynamic groups for our Azure AD deployment. We currently have all the syntax/group rules created for these groups in a CSV file. My problem is: i'm using the following script to try to create these groups
Connect-AzureAD
$Groups = Import-Csv -Path C:\Temp\AzureAD_Groups.csv
$dynamicGroupTypeString = "DynamicMembership"

foreach($Group in $Groups)
{
New-AzureADGroup -DisplayName $Group.DisplayName -Description $Group.Description -MailEnabled $False -MailNickName "group" -SecurityEnabled $True -membershipRule $Group.MembershipRule -GroupTypes $dynamicGroupTypeString
}

After running this script i get the error:
New-AzureADGroup : A parameter cannot be found that matches parameter name 'membershipRule'.
At line:8 char:147
+ ...  -MailNickName "group" -SecurityEnabled $True -membershipRule $Group. ...

I looked into this error and i see that this flag/parameter doesnt exist for New-AzureADGroup and i also saw that it works for Set-AzureADGroup. My question is: instead of creating then setting the group rules after, can i perform this task all in one script so it creates the groups then uses the pre-made syntax in my CSV?
My CSV file is setup as such:

Any help is much appreciated, thanks.
Answer: I tried to reproduce the same in my environment and got the same error like below:

My Imported CSV file looks like below:

Please note that, you have to use New-AzureADMSGroup command to create M365 Dynamic group. Make sure to include -MembershipRuleProcessingState "On" while using that command.

I'm able to create dynamic groups successfully after changing the script like below:
Connect-AzureAD
$Groups = Import-Csv -Path "C:\test\AzureAD_groups.csv"
$dynamicGroupTypeString = "DynamicMembership"

foreach($Group in $Groups)
{
New-AzureADMSGroup -DisplayName $Group.DisplayName -Description $Group.Description -MailEnabled $False -MailNickName "group" -SecurityEnabled $True -membershipRule $Group.MembershipRule -GroupTypes $dynamicGroupTypeString -MembershipRuleProcessingState "On"
}

M365 dynamic groups created successfully like below:

Members are dynamically allotted to groups based on membership rules like below:
Comment: This is great! Thank you SrideviMachavarapu! Is there a way to silence the welcome message/notification for new users that are dynamically added to the group? I see this parameter: [-UnifiedGroupWelcomeMessageEnabled]
Is there a way to run this inline so it silences all new notifications?
Would it be after "-MembershipRuleProcessingState "On" -UnifiedGroupWelcomeMessageEnabled "false""

Thank you!


anuglar js: ng-repeat doesn't displaying anything

Question: I'm not really a js guy but i tried to show something with the ng-repeat in angular. But it doesn't display anything.
HTML:

contact: {{ customer[0].Name }}

Label

JS
var app = angular.module('contact', []);

app.controller('ContactController', function($scope){
    var customers = myContext.customer.toArray();

    $.when(customers).then(function(customers) {
        $scope.customers = customers;
    });
});

Debug
I tried to find error out with the debug chrome extension:

This Image i can see for 1 sec and then it goes away and only the title stays there.

Maybe somebody know what i'm doing wrong?
Best Regards
Comment: @KalhanoToressPamuditha myContext comes from JayData
Comment: @DavinTryon acontact is ``
Answer: I agree with the above answers, as far as customer is an object and not an array.
But maybe try accessing the name with:
customer.initData.Name

i.e.

contact: {{ customer.initData.Name }}

Label

and because you attached customers to $scope, here:
 $.when(customers).then(function(customers) {
        $scope.customers = customers;
    });

It means you dont have to reference the controller object,
ng-repeat="customer in acontact.customers"
Try just using
ng-repeat="customer in customers"

Comment: yes i attacht it to an outer div i updated the `html code` but it also doesn't work with `customer.initData.Name`
Answer: Your customer variable is not an array, it is already one of the customers. Try with contact: {{ customer.Name }} and all should be good.
Comment: still doesnt work :( I tried it with customer[0] because i thought like that i have to go in the initData object or array or whatever this is..
Comment: Int he picture you have posted there don't seem to be any Name parameter, try it with customer.Address and see if that works
Comment: Why are you iterating through acontact.customers in your ng-repeat instead of just customers? Shouldn't it be ng-repeat="customer in customers"? Try it like this ...
Answer: Maybe becouse of the $scope?, when you use it you can't use alias "as" in youre controller...
Comment: this question was asked 2 years ago and already has an accepted answer..


How do I programmatically update the rendering language?

Question: I am trying to programmatically set the Views rendering language of a couple of Views having multiple displays. I found that doing it manually is error prone.
use Drupal\views\Views;

$view = Views::getView('ap_country');
print_r($view->display_id);

$view->setHandlerOption('page_2', 'argument', 'nid', 'admin_label', 'Foo');
$view->save();

I am trying to achieve something like the above and then export the View. However rendering language does not seem to be a handler.
The reason behind dong this is currently all the views are set to the current Interface language and I want to switch to the content language.
Comment: Export, edit the YML file in a text-editor, search and replace the config key you want to change, re-import.
Comment: Why don't you do this with configuration management? Like get a local copy of the site. Export all config. Then update either the Views and export config again or update the config manually; and push.
Answer: Yes, this is not a handler setting. This is configured directly in a display.
To update a View programmatically use the storage property of the View object (which is by the way a reference to the config object discussed in the comments) and get a reference of a display (the master display is default):
$view = \Drupal\views\Views::getView('myview');
$storage = $view->storage;
$display = &$storage->getDisplay('page_2');
$display['display_options']['rendering_language'] = '***LANGUAGE_language_content***';
$storage->save();


404 Pages when tampering with the extention of the page

Question: I have a Sitecore solution, where we handle 404 requests.
We do that by setting "ErrorPage" and the "ItemNotFoundUrl" in the web.config:
<setting name="ErrorPage" value="/sitecore/service/error.aspx" />

And
<setting name="ItemNotFoundUrl" value="/Global/ErrorPages/404" />

Now, this works when we edit the name of the page. So if we have www.domain.com/mypage.aspx , and go to www.domain.com/mysdfsa.aspx which doesn't exist, it will show our error-page.
However, if we go to something like:
www.domain.com/mypage.zip / www.domain.com/mypage.gosfgfgs
It gives the IIS error:
Error Summary
HTTP Error 404.0 - Not Found
The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.

What have I tried?
We need to make it for for ZIP files at least.

Made sure that .ZIP is added to both IIS and Sitecore MIME types
Hooked in before the ExecuteRequest pipeline and tried to redirect (this is never called because the IIS gives the errorpage before we get to execute the request)

Any ideas? :-) Thanks
Answer: I think in the <preprocessRequest> pipeline there's a processor for extensions that Sitecore handles. You should try to update that:
<processor type="Sitecore.Pipelines.PreprocessRequest.FilterUrlExtensions, Sitecore.Kernel">
  <param desc="Allowed extensions (comma separated)">aspx, ashx, asmx</param>
  <param desc="Blocked extensions (comma separated)">*</param>
  <param desc="Blocked extensions that stream files (comma separated)">*</param>
  <param desc="Blocked extensions that do not stream files (comma separated)"></param>
</processor>

Comment: It would be more correct to make sure your IIS handles 404 messages to the same page Sitecore is setup to.


Specifying the sources of many unioned COUNT-statements

Question: My objective is to count the number of records associated with three tables and combine the results into one another. However, it seems UNION automatically orders the result, so there is no way to know which result is from which table.
SELECT COUNT(*) FROM ACTM JOIN CUS_CHILD
    ON actm.cust_id = cus_child.cust_id
UNION
SELECT COUNT(*) FROM ACTM JOIN CUS_ADULT
    ON actm.cust_id = cus_adult.cust_id
UNION
SELECT COUNT(*) FROM ACTM JOIN CUS_ELDER
    ON actm.cust_id = cus_elder.cust_id

/* Results in: */
COUNT(*)
    0
    3
    4

Two possible solutions come to mind:

Adding a column with the table names or just some string
Showing the results in some different, possibly matrix form

They would look something like this:
Name  | COUNT(*)    Child | Adult | Elder    Child | Adult | Elder
----------------    ---------------------    ---------------------
Child | 3             3       4       0        3       0       0
Adult | 4                                      0       4       0
Elder | 0                                      0       0       0

I tried to rename each result COUNT(*) as "Child" and so on to achieve the middle, but it just produced a single column named Child.
So I have no idea how these might be achieved, I'm quite new to SQL. Any ideas would be greatly appreciated.
Answer: Try this :
SELECT COUNT(*),
       'Child' as Name FROM ACTM JOIN CUS_CHILD
    ON actm.cust_id = cus_child.cust_id
UNION
SELECT COUNT(*),
       'Adult ' FROM ACTM JOIN CUS_ADULT
    ON actm.cust_id = cus_adult.cust_id
UNION
SELECT COUNT(*),
       'Elder' FROM ACTM JOIN CUS_ELDER
    ON actm.cust_id = cus_elder.cust_id

OR
SELECT SUM(CASE WHEN CUS_CHILD.cust_id is not null
            THEN 1
            ELSE 0
        END) AS Child ,
        SUM(CASE WHEN cus_adult.cust_id is not null
            THEN 1
            ELSE 0
        END) AS Adult  ,
        SUM(CASE WHEN cus_elder.cust_id is not null
            THEN 1
            ELSE 0
        END) AS Elder
FROM ACTM
LEFT JOIN CUS_CHILD
    ON actm.cust_id = cus_child.cust_id
LEFT JOIN CUS_ADULT
    ON actm.cust_id = cus_adult.cust_id
LEFT JOIN CUS_ELDER
    ON actm.cust_id = cus_elder.cust_id

Comment: Uh.. Simple, elegant. I love it! And the second one is good to know as well. Thanks!
Comment: `SUM(CASE WHEN CUS_CHILD.cust_id is not null
            THEN 1
            ELSE 0
        END)`  is same as `COUNT(CUS_CHILD.cust_id)` and much efficient.
Comment: As for the union all I also agree I just left it as yours, Regurding the second solution - probably more correct and better in terms of performance since it passes the table only one time!.
Answer: Do not use UNION -- unless you want to incur the overhead of removing duplicates.
SQL result sets are unordered, unless you have an explicit ORDER BY.  So, don't depend on the ordering and include a column that says what the number is for:
SELECT 'child' as which, COUNT(*)
FROM ACTM JOIN
     CUS_CHILD
     ON actm.cust_id = cus_child.cust_id
UNION ALL
SELECT 'adult' as which,  COUNT(*)
FROM ACTM JOIN
     CUS_ADULT
     ON actm.cust_id = cus_adult.cust_id
UNION ALL
SELECT 'elder' as which, COUNT(*)
FROM ACTM JOIN
     CUS_ELDER
     ON actm.cust_id = cus_elder.cust_id;

You can also make these subqueries and simply do:
SELECT (SELECT COUNT(*)
        FROM ACTM JOIN
            CUS_CHILD
            ON actm.cust_id = cus_child.cust_id
       ) as num_child,
       (SELECT COUNT(*)
        FROM ACTM JOIN
             CUS_ADULT
             ON actm.cust_id = cus_adult.cust_id
       ) as num_adult,
       (SELECT COUNT(*)
        FROM ACTM JOIN
             CUS_ELDER
             ON actm.cust_id = cus_elder.cust_id
       ) as num_elder
FROM dual;

Comment: I don't quite understand, which duplicates are removed in this case?
Comment: @Felix : This definitely should be the best  answer not the other.
Comment: @KaushikNayak I "definitely" am not convinced of that. But given an explanation, I might agree. So: why?
Comment: @Felix : Read the very first line from Gordon carefully and compare it with  other answer, using `UNION` is the first thing anyone arriving here seeking an answer should avoid.
Comment: @KaushikNayak Yes, and that was my question above: which duplicates are removed? I can't accept that it's a bad thing if, from what I gather, there only is 3 members to the result set in total.
Comment: @KaushikNayak Though I see why unioning huge sets could be undesirable.
Comment: @Felix : Do refer my comments to  that answer. I won't persuade you much, it's all  your discretion  :-)
Comment: @Felix . . . The duplicates that would be removed (in your query) are any two counts that have the same value.  The point, though, is that you should not incur the overhead of removing duplicates unless you really want to remove them.  So `union` is something that can produce the wrong answer and it incurs unnecessary overhead.  Seems like a bad idea to me.
Comment: @GordonLinoff Now I understand! Yeah, seems like a really bad idea.


Two definitions of exactness

Question: Given a functor $F:A\to B$ of abelian categories we may say that $F$ is left exact if it maps exact sequences to left exact sequences, and similarily for right. For arbitrary categories, we may say that $F$ is left exact if it preserves finite limits (supposedly, this was introduced in SGAIV, but I don't have it). The question is thus: are these definitions equivalent in an abelian category? That this latter definition implies the first is clear to me, but the other gives me more trouble.
Thanks,
Eivind
Answer: Yes. $F$ is exact in the first sense if it maps left exact sequences to left exact sequences (this is an easy exercise). So $F$ is exact in the first sense iff it preserves kernels. But an additive functor that preserves kernels preserves all finite limits (because any finite limit can be built from a product of direct products and equalizers, and finite direct products are always preserved by an additive functor).
Comment: Thanks a lot! I suspected it would have something to do with building the limit from products and equalizers. That fact will probably prove a good exercise :)

Two definitions of exactness


Linear maps: Do this functions produce a linear map

Question: I want to know if there exists a linear map $$A: \mathbb{R}^3 \rightarrow P_{\mathbb{R}}^{2}$$
with
$$A(1,2,3) = x^2 -1$$
$$A(0,2,1) = 3x + 4$$
$$A(-1,0,-2) = x^2+x+1$$
Is there any possibility to show it? I hope you can help me!
Comment: Isn't the domain of $A$ $\mathbb{R}^3$?
Comment: That is right. I corrected it.
Comment: What is $L$ in $L(-1,0,-2)$? Shouldn't it be $A$?
Comment: Yes, right. It should be A
Answer: Hint: the three vectors for which an image is specified satisfy a linear dependence relation (their alternating sum is zero). Do the specified images satisfy the same relation? Conclude.
Comment: An _alternating_ sum has alternating signs $+v_1-v_2+v_3-v_4+\cdots$. A linear dependence relation involves arbitrary coefficients (but not all zero): $c_1v_1+c_2v_2+\cdots=0$. You should have learned how in general one finds whether such a linear dependence relation between given vectors exists; my sentence was just quick a hint about the outcome for these particular vectors, but you should be able to find it without the hint.
Comment: Do you mean I shall simply sum up the three vectors and the result has to be zero? $$\begin{pmatrix}
1\\2\\3
\end{pmatrix} + \begin{pmatrix}
0\\2\\1
\end{pmatrix} + \begin{pmatrix}
-1\\0\\-2
\end{pmatrix} = \vec{0}$$ Is that right?
Comment: Do you mean I shall simply sum up the three vectors and the result has to be zero? $$\begin{pmatrix}
1\\2\\3
\end{pmatrix} + \begin{pmatrix}
0\\2\\1
\end{pmatrix} + \begin{pmatrix}
-1\\0\\-2
\end{pmatrix} = \vec{0}$$ Is that right? My result is $$\begin{pmatrix}
0\\4\\2
\end{pmatrix}$$ But I guess that is not correct. Don't I need the second parts of my functions? Or do I have to sum up $$(x^2 -1 )+(3x + 4)+(x^2 + x + 1) = 0$$
Answer: I'll try to make Marc's answer less cryptic.
If $A$ is linear, then we must have that $A(0,0,0)=\mathbf{0}$, where $\mathbf{0}$ is the zero polynomial.
But in your case, notice that your vectors $v_1, v_2, v_3$ satisfy $$v_2-v_1=v_3$$Therefore $$-v_1+v_2-v_3=(0,0,0)$$
So we must have $$A(-v_1+v_2-v_3)=A(0,0,0)=\mathbf{0}$$
But if $A$ is linear, then we must also have $$A(-v_1+v_2-v_3)=-A(v_1)+A(v_2)-A(v_3)=-(x^2-1)+(3x+4)-(x^2+x+1)$$
Is this the zero polynomial?
Comment: The result of your equation is $$-2x^2+2x+4$$ and therefore it is not the zero polynomial. Thus I can say it does not exist a linear map with these vectors. Am I right?
Comment: Yes, that's right...


Find the CDF of this random variable

Question: Suppose $X = X_1$ with probability $p$ and $X = X_2$ with probability $1– p$ , where $p \in (0,1)$, $X_1$ and $X_2$ are random variables with CDF's $F_1(x)$ and $F_2(x)$ respectively. Find
the CDF of $X$.
I don't know where to go to find the CDF of $X$. I don't know how to use the fact that $X = X_1$ with probability p and $X = X_2$ with probability $1– p$.
Answer: Recall that the CDF $F(x)$ of $X$ is defined by
$$
F(x) = \textrm{Pr}(X \leq x).
$$
Apply the definition of $X$, and we see that
$$
F(x) = \textrm{Pr}[X \leq x] = p \textrm{Pr}[X_1 \leq x] + (1-p)\textrm{Pr}[X_2 \leq x] = pF_1(x) + (1-p)F_2(x).
$$
Comment: Sorry, why Pr[≤]=Pr[1≤]+(1−)Pr[2≤]?

Find the CDF of this random variable


Requests to domain using wrong domain name

Question: I`m getting strange requests to my domain using different domain host header -> as.eu.angsrvr.com .
The requests are coming from all different ip addresses, different os, different browsers and seems to be made by real  users. And the referrer are different for request, like for example
http://emilyaclark.com/
http://phimmoi.net/
http://fool.com/
etc.. there really a lot
Some of them are application/x-shockwave-flash .
~1500req/hour. Its pretty consistent.
46.66% requests to http://as.eu.angsrvr.com/select
53.34% requests to http://as.eu.angsrvr.com/crossdomain.xml
How this request are happening? It seems to be some ad network, but how it make people to hit my domain using wrong domain name?
I checked how as.eu.angsrvr.com resolve using dns
<code>as.eu.angsrvr.com
Server:  UnKnown
Address:  192.168.0.1

Non-authoritative answer:
Name:    lb-adselect-1417292246.eu-west-1.elb.amazonaws.com
Addresses:  18.104.22.168
          126.96.36.199
          18.104.22.168
          22.214.171.124
          18.104.22.168
          126.96.36.199
          184.108.40.206
          126.96.36.199
</code>
And none of this ip are point to my server. My ip are 22.214.171.124, 220.127.116.11
Im using amazon elb and this site seems to be using elb too. Not sure if it relevant or not.
I know i can block them on nginx level, but i want to figure out how they are happening at all and who to contact to stop this..
Answer: Looks like you have a new server, and it's IP earlier belonged to as.eu.angsrvr.com. The reason why you still receiving those requests is that either the visitors have the IP cached in their DNS (usually it should expire in less than two days) or the IP is hard-coded in configs (good lesson how NOT to do configs)
Another reason is admin at angsrvr.com mistyped when configured their DNS.
Solution: ask your hosting provider to change the server's IP or contact angsrvr.com support (see 'whois')
Comment: We have different ips, i posted mine ip in post and what whois responds to their ip. And its not really new, my elb was up for half year, and this starts only a week ago.
Comment: dont really think ip hardcoded in visitors configs, it doesnt make any sense, there like 1000 different persons every hour and it makes no sense.  I tried again and it seems that as.eu.angsrvr.com reply with different ip addreses on every whois lookup, probably there A LOT of ip addresses for this domain..
Comment: Well, as soon ass it is AWS LB-backed service - maybe some glitches at amazon?
Comment: Actually their ip addresses are the same, dont have mine in them.Trying to contact aws support regarding this
Answer:
I know i can block them on nginx level

You should do that.  In fact, you should have already been doing that in your own interests -- nginx or any front-side service with the capability, should be configured to throw back errors (503, 502, pick your poison) on any unexpected host header coming in.
Since the domain in question does not seem to be misconfigured, it is likely that this is a browser DNS caching issue, and your ELB now has a public address formerly associated with this site.  Browsers are terrible about holding on to resolved addresses until all windows are closed, DNS TTL be darned.
Note that there are at least 8 IP addresses for the other site's ELB.  This is apparently a site that is handling a significant volume of traffic.  8 IP addresses suggests an ELB that has scaled itself up to at least 4 times the baseline capacity you'd see for a site deployed across 2 availability zones.  You're seeing a tiny amount of fallout, relatively speaking...

who to contact to stop this

1500 requests per hour is probably not worth worrying about.  It should go away on its own.
Of course, you could clone your ELB, move your site's DNS to the new one, then turn off the old one once everything drains -- that would give you new public IP addresses.  AWS support might be able to force your ELB to reconfigure itself different public IPs on the outside.
But running servers on the Internet is inherently messy and this is a case where there really doesn't appear to be anything to "fix" at this point.  The behavior could be eliminated, as discussed above, but since it does not appear to be malicious and can reasonably be expected to clear up on its own... is it worth the trouble?


what is the correct way to handle a caught exception and raise it outside of try block

Question: Im just starting my python learning journey and need some help with the correct way to raise an exception.
Consider a block of code which loops thru a list and performs a task. If an exception occurs,continue with the program execution. And execute the rest of the code. At the end of the program raise the exception and system the application with non zero code. The idea is the program should continue executing all the tasks, but exit with a non 0 code for an external application to track and report.
save_exc_info = None

def numMatcher(numbers):
    try:
        if numbers != 2:

            print('number match ' + str(numbers))

        else:
            raise ValueError('Number not in list. Will be logged for troubleshooting')  # raise exception and log it

    except ValueError as veer:  # exception 1 caught and saved
        save_exc_info = sys.exc_info()

    except (IOError, OSError) as ioerr:  # exception 2 caught and saved
        save_exc_info = sys.exc_info()

try:
    print('Next step')  # Perform rest of the tasks in the code

except Exception as excp:  # exception 3 caught and saved
    save_exc_info = sys.exc_info()

print('final step')

numlist = [1, 2, 3]

for numbers in numlist:
    numMatcher(numbers)

if save_exc_info is not None:
    traceback.print_exception(*save_exc_info)  # how to return the right exception and print?
    sys.exit(1)  # At the end of the program, exit with non zero code as there was an exception in the program.

Comment: As a side note, I wouldn't recommend using `AssertionError` in this context let alone catching its error. `AssertionError` is used for debugging purposes with the `assert` statement. A more helpful error type such as `ValueError` would be appropriate here.
Answer: When handling the exception, you can assign it to a variable, e.g.:
    except AssertionError as aerr:
        saved_exception = aerr

Which you can later access e.g.:
print(saved_exception)

For you code, this gives you an option of not having two variable, and instead of isError just use saved_exception = None and later test if saved_exception is not None: ...
Not sure how useful saving exception for later (using it as general interface to pass information around) is. Perhaps it may be worth rethinking a bit more.
N Chauhan also made a good point int the comment about AssertionError not being very suitable exception to use to convey this type of information.

To your updated question. If you want to print the traceback is you'd see it when the exception was raised, probably the most straightforward would be to save exception information and use print_exception() (or its format_exception friend):
except ValueError:
    save_exc_info = sys.exc_info()
...
traceback.print_exception(*save_exc_info)

You could have extracted the same information from / use the saved exception as well, *save_exc_info could have also been: type(saved_exception), saved_exception, saved_exception.__traceback__ (for the saved exception in the first example).
Comment: Thanks. I have updated the code based on your suggestion. Is it possible to also save and print the stack track for other exception types?
Comment: Great! The solution is working as I expected. Thanks for all the inputs. But when I try the same within a function, it does not return the exception. Tried adding a return statement. Didnt work either. Any further thoughts?
Comment: Scoping: if you handle that exception in a function, you need to make the exception you've saved visible outside of that function, normally by making it part of the what the function `return`s: `return save_exc_info` (NOTE: `save_exc_info = None` must be in the function for that)... and of course you "receive" it outside by assigning the `return`ed value to a variable.... However, scoping is distinctly different topic and really should be in its own question. Q/A format should provide closed pair hopefully useful to posterity, not wander across various topics as a continuous chat.


Count files in a network folder using PowerShell

Question: I've searched numerous MSDN/Technet and StackOverflow articles regarding this but I can't find a solution to my problem.
SO references below.
I am trying to run a script on my server that simply counts the files in a folder on a network location.
I can get it working if it's a local folder, and I can get it working when I map the network drive. However I can't use a network drive because I'll be running this script from a web interface that doesn't have a user account (local drives work fine).
My script is:
$Files = Get-ChildItem \\storage\folder -File
$Files.count

I get the error:
Get-ChildItem : Cannot find path '\\storage\folder' because it does not exist.

[0]open folder from Network with Powershell
[1]File counting with Powershell commands
[2]Count items in a folder with PowerShell
[3]Powershell - remote folder availability while counting files
Comment: You can't enumerate files on a share without having access to the share. Map a drive using explicit credentials, or grant the user running the code (usually the webserver service account) access to the share. Either way this is off topic on SO.
Comment: Can you please explain why this is off topic for SO? I found very similar questions on SO.
Comment: It's a system management problem rather than a programming problem.
Comment: Fair enough. Which network would you have suggested I post it on?
Comment: I'd consider [SuperUser](http://superuser.com/) the best place for this kind of question.
Answer: Try this:
set-location \\\storage\folder\

dir -recurse |  where-object{ $_.PSIsContainer } | ForEach{ Write-Host $_.FullName (dir $_.FullName | Measure-Object).Count }

This will count the number of files in each sub-folder (recurse) and display the full path and count in the output.
Answer: Two things that I can think of,
One would be to add -path to your get-childitem call. I tested this on my Powershell and it works fine.
$files = get-childitem -path C:\temp
$files.count
This returns the number of files in that path.
However I am testing this on a local file. If you are sure it is the remote access part giving you trouble I would suggest trying to set credentials. Besides the get-credentials option, you could also try setting them yourself.
$Credentials = New-Object System.Management.Automation.PsCredential("Username", "password")
Then perhaps you can set the drive and still be able to access your files. Hope that helps.


Microsoft azure mobile service does not show the tables existing already in the database

Question: _I'm making an android app with Microsoft azure mobile service and it does not show the tables existing already in the database it's only showing tables that have been created in the mobile service
how should I use the data existing in the Database .
if there is no solution
_I have seen a PHP connection String in the sql database , if i used a PHP scripts what should be the URL to use in the android application
Help in one of them please :)
Answer: As far as I understood, your problem is the following: You created a table in the database (e.g. using the SQL Server Management Platform or a Visual Studio connection) and the table is then not showing up in the Management Portal of the Mobile Service.
Solution
If so, you can make them show up by creating a "new" database table with the same table name that already exists in the database. In fact the table is not created again but it shows up in the Management Portal with the same structure and data as it is in the database.
Hope it helps.
Comment: I have the same problem, i see the mobile service in visual studio but there is no table under the node. In the tutorial, it says to right click the table to edit the permissions but there is no table.  Is there a way to edit the table permission some other way?
Comment: As far as I know you can only change permissions via the management portal. So go to your mobile service at managewindowsazure.com and click "Data". There, select the table and click on "permissions" afterwards. Hope this helps.
Comment: Hi, I dont see the Data option in management portal. I click on the mobile service and get the (Dashboard, Scheduler, Push Identity Configure, Scale, Logs) menu.
Comment: What backend type did you choose? If you chose .NET backend, then you can change the permissions by adding an `[AuthorizeLevel(AuthorizationLevel.User)]` attribute in your Table Controller class (or methods in this class)
Comment: Thanks, i will try this attribute. I choose the .net backend.
Answer: i have figured it out !
it was the schema name
if you create a mobile service the tables of this in the database will have your service name as a schema
changing the schema name will solve the problem


php5-gd shows in "php -i | grep -i gd" but not in phpinfo();

Question: I am trying to enable GD in my installation of Apache2, PHP5 and MySQL on my Ubuntu server.
I installed php5-gd with:
apt-get install php5-gd
And when I run php -i I get:
gd

GD Support => enabled
GD Version => 2.0
FreeType Support => enabled
FreeType Linkage => with freetype
FreeType Version => 2.4.8
T1Lib Support => enabled
GIF Read Support => enabled
GIF Create Support => enabled
JPEG Support => enabled
libJPEG Version => unknown
PNG Support => enabled
libPNG Version => 1.2.46
WBMP Support => enabled

Directive => Local Value => Master Value
gd.jpeg_ignore_warning => 0 => 0

But it does not show up in phpinfo();
I have restarted the server four times and I have tried to restart Apache2 four million times.
Does anyone have any idea of how to fix this problem?
Answer: It looks like libjpeg62 isn't installed on your server.
Install libjpeg62and restart Apache2.
sudo apt-get install libjpeg62
Comment: I did not even think about that when I read the error message.
Answer: Are you sure that the php being pointed in your apache webserver is the same as the php you are running in your program?
From what I can see, php -i, is actually running phpinfo();.
If you are in doubt:
   echo '<?php phpinfo(); ?>' | php

Comment: http://www.pastebay.net/1150906?p=serverfault&submit=unlock
Comment: But when I do  in a php-file and run it in the browser it doesn't show.
Comment: In `/etc/apache2/mods-enabled/php5.load` it sais `LoadModule php5_module /usr/lib/apache2/modules/libphp5.so`. But when i do `which php5` it sais `/usr/bin/php5`. Does that have anything to do with this?
Comment: What about 'which php'?
Comment: `which php` shows `/usr/bin/php`
Comment: After a little bit of tinkering with Apache2/PHP logs I managed to get a error in my log file. `PHP Warning:  PHP Startup: Unable to load dynamic library '/usr/lib/php5/extensions/gd.so' - libjpeg.so.62: cannot open shared object file: No such file or directory in Unknown on line 0`
Answer: had the same issue in Windows / Apache. Fixed by using the full path in extension_dir
change: extension_dir = "ext"
to: extension_dir = "c:/progra~1/php5513/ext"
obviously change your path to suit your install folder


Existe alguma forma de usar Laravel Eloquent no microframework Silex?

Question: Eu estou refatorando uma estrutura de um site e passando para o microframework Silex.
Gostaria de saber se há alguma maneira de utilizar o ORM Eloquent do Laravel, para conectar com o banco de dados.
Eu li na documentação que tem como usar Doctrine, porém não gostei muito da ideia.
Então gostaria de saber se existe alguma biblioteca que possibilite eu usar o ORM do Laravel (Eloquent) no Silex?
Comment: https://github.com/ziadoz/silex-capsule
Answer: Tem como usar sim, conforme o próprio repositório illuminate/database, na verdade é possivel usa-lo independente de qualquer coisa, ou seja poderá usar provavelmente em qualquer framework, as únicas dependências é instalar via composer e ter o php5.6+, ou seja isso funcionará tanto para Silex quanto para qualquer coisa equivalente.
Digite no terminal dentro do seu projeto composer require "illuminate/database", se for usar os eventos é necessário também o comando composer require "illuminate/events"
Ou configure o composer.json (5.4 é a versão mais atual antes da versão de desenvolvimento, pode ver outras versões):
"illuminate/database": "~5.4",
"illuminate/events": "~5.4"

E depois rode o composer update.
Adicione o autoload.php e chame em um PHP assim:
<?php

use Illuminate\Database\Capsule\Manager as Capsule;

require __DIR__ . '/vendor/autoload.php';

$capsule = new Capsule;

//Exemplo mysql
$capsule->addConnection([
    'driver'    => 'mysql',
    'host'      => 'localhost',
    'database'  => 'database',
    'username'  => 'root',
    'password'  => 'password',
    'charset'   => 'utf8',
    'collation' => 'utf8_unicode_ci',
    'prefix'    => '',
]);

// Define o dispatcher usado pelos models do Eloquent (opcional)
use Illuminate\Events\Dispatcher;
use Illuminate\Container\Container;
$capsule->setEventDispatcher(new Dispatcher(new Container));

// Faz essa instancia de Capsule ficar disponível globalmente usando metodos estaticos (opcional)
$capsule->setAsGlobal();

// Configura o Eloquent ORM... (opcional e desnecessário se você já usou setEventDispatcher())
$capsule->bootEloquent();

Essa parte acima você poderia colocar em um arquivo global o qual ficaria acessivel a todos, ou quando você chamar um namespace especifico, por exemplo \Model\foo\bar (falo disto depois).
Depois de incluir o arquivo acima, você pode usar:

QueryBuilder
$users = Capsule::table('users')->where('votes', '>', 100)->get();

Schema Builder
Capsule::schema()->create('users', function($table)
{
    $table->increments('id');
    $table->string('email')->unique();
    $table->timestamps();
});

Eloquent ORM (creio que seja este que lhe interessa):
class User extends Illuminate\Database\Eloquent\Model {}

$users = User::where('votes', '>', 1)->get();

Criando um namespace para usar os Models
Agora digamos que você não vai usar o ORM em todas páginas, realmente não há motivo para carregar tudo se não vai usar, então você pode querer organizar o seu projeto se baseando em um namespace, sugiro fazer algo como:

Crie no composer.json um namespace para apontar para uma pasta aonde ficarão os models:
...
"require": {
    "php": ">=5.6.4",
    "illuminate/database": "~5.4",
    "illuminate/events": "~5.4"
},
"autoload": {
    "psr-4": {
        "FooBarModel\\": "app/Models"
    }
},
...

Esse caso é um exemplo, supondo que tenha uma pasta chamada ./app/Models dentro do projeto.

Você pode criar um Model abstrato que será a base de tudo em ./app/Models/Model.php, assim evitará de incluir o Eloquent em chamadas que não vai usar o banco (claro que isso é só uma maneira de organizar)
Neste caso você deve remover do arquivo global tudo o que citei antes deixando lá somente o require:
<?php

namespace FooBarModel;

use \Illuminate\Database\Capsule\Manager as Capsule;
use \Illuminate\Events\Dispatcher;
use \Illuminate\Container\Container;

$capsule = new Capsule;

$capsule->addConnection([
    'driver'    => 'mysql',
    'host'      => 'localhost',
    'database'  => 'database',
    'username'  => 'root',
    'password'  => 'password',
    'charset'   => 'utf8',
    'collation' => 'utf8_unicode_ci',
    'prefix'    => '',
]);

$capsule->setAsGlobal();

$capsule->bootEloquent();

//Cria a classe
abstract class Model extends \Illuminate\Database\Eloquent\Model {}

Então agora na mesma pasta você pode criar um Model chamado User (./app/Models/User.php):
<?php

namespace FooBarModel;

class User extends Model {}

Se estiver em uma sub-pasta (./app/Models/Admin/FooBar.php):
<?php

namespace FooBarModel\Admin;

class FooBar extends \FooBarModel\Model {}

Crie o tal global.php (ou qualquer coisa assim) que possua o require __DIR__ . '/vendor/autoload.php';, ou se tiver um boot.php ou no seu index.php da vida jogue lá, supondo:
<?php

require __DIR__ . '/vendor/autoload.php';

Então para chamar um Model especifico, por fazer assim:
<?php

require __DIR__ . '/vendor/autoload.php';

$user = new FooBarModel\User\User;

Um exemplo com Silex pode ser assim:
<?php

use FooBarModel\User;
use FooBarModel\Admin\FooBar;

require_once __DIR__ . '/../vendor/autoload.php';

$app = new Silex\Application();

$app->get('/', function ()
{
    return 'Home';
});

$app->get('/user', function ()
{
    $user = new User;
    ....
});

$app->get('/user', function ()
{
    $user = new FooBar;
    ....
});

$app->run();


Property 'opacity' does not exist on type 'IntrinsicAttributes' throwing and error for view Opacity in React native

Question: After writing this sentence, typescript file shows an error on below line.
React-Native 0.60+
There is a new opacity prop that you can pass in:
<View opacity={true ? 0.5 : 1}> </View>

Error stack: error property 'opacity' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes view opacity.
No overload matches this call. Overload 1 of 2, '(props: ViewProps | Readonly): View', gave the following error. Type '{ children: Element; opacity: boolean; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes & Readonly & Readonly<{ children?: ReactNode; }>'.
Property 'opacity' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes & Readonly & Readonly<{ children?: ReactNode; }>'.
Overload 2 of 2, '(props: ViewProps, context: any): View', gave the following error.
Type '{ children: Element; opacity: boolean; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes & Readonly & Readonly<{ children?: ReactNode; }>'.
How to resolve this warning, thanks in advance.
Comment: Looks to me like you're setting opacity as a boolean rather than a number. Double check how you're setting the opacity and maybe hardcode to 0.5 or something to see if it works?
Comment: What kind of code gives this error. It's quite hard to just guess
Answer: I resolved this error by followin code :
<View style={{ opacity: true  ? 0.5 : 1 }}>

Happy Coding !


Rust JSON API Request Formatting

Question: I am trying to perform a search request given the API structure by:
https://api.wigle.net/swagger#/
Currently, I have attempted to perform a /api/v2/network/search through the given structure by doing this (sorry for the long url!):
#[macro_use]
extern crate serde;
extern crate serde_derive;
extern crate reqwest;
use reqwest::Error;
use serde_json;

#[derive(Deserialize, Debug)]
struct Output {
    trilat: f64,
    trilong: f64,
}

fn main() -> Result<(), Error> {
    let request_url = format!("https://api.wigle.net/api/v2/network/search?first=0&latrange1={lat_range_min}&latrange2={lat_range_max}&longrange1={long_range_min}&longrange2={long_range_max}&freenet=false&paynet=false&ssid={ssid}",
                              lat_range_min = "41.159",
                              lat_range_max = "42.889",
                              long_range_min = "-73.5081",
                              long_range_max = "-69.7398",
                              ssid= "XFINITY"
                            );

    let mut response = reqwest::get(&request_url)?;

    println!("{:?}", response);

    //let result: Vec<Output> = response.json()?;
    //println!("{}", result[0].trilat);
    Ok(())
}

The output I get is:
Response { url: "https://api.wigle.net/api/v2/network/search?first=0&latrange1=41.159&latrange2=42.889&longrange1=-73.5081&longrange2=-69.7398&freenet=false&paynet=false&ssid=xfinity", status: 401, headers:
{"server": "nginx/1.16.1", "date": "Tue, 24 Dec 2019 19:51:14 GMT", "content-type": "application/json", "content-length": "14", "connection": "keep-alive"} }

However if you were to do an actual request, you would get detailed api output from WiGLE.
What do I do in order to get the correct output so I can parse it as a json output?
Thanks!
Comment: Not a Rust coder, but aren't you supposed to call something like [`json()`](https://docs.rs/reqwest/0.9.24/reqwest/struct.Response.html#method.json) on the response?
Comment: Could you determine the final aim of your programme? So ... You would like to print json or to treat it as a json within other parts of your programme?
Comment: Sorry for any confusion, because the response I am getting isn't even the correct response I have not gotten to the parsing part. I wanted to extract the trilat and trilong data out from the API, but the output I get is not the actual data, but the headers.
Comment: Update: I've realized you needed an authorization header for this API in order to work. Thanks for all the help guys!
Answer: This crate doesn't support such a possibility to transform its type Response to the serde_json::Value type. But you can implement it by yourself.
You should define your structure and operate on it. For instanse it may be somehow like the following:
use serde::{Serialize, Deserialize};
use std::collections::HashMap;
use serde_json;
use reqwest;
use reqwest::Error;

#[derive(Serialize, Deserialize, Debug)]
struct Req {
  url: String,
  status: u16,
  headers: HashMap<String, String>,
  body: Option<serde_json::Value>
}

fn main() -> Result<(), Error> {
    let request_url = format!("https://api.wigle.net/api/v2/network/search?first=0&latrange1={lat_range_min}&latrange2={lat_range_max}&longrange1={long_range_min}&longrange2={long_range_max}&freenet=false&paynet=false&ssid={ssid}",
                              lat_range_min = "41.159",
                              lat_range_max = "42.889",
                              long_range_min = "-73.5081",
                              long_range_max = "-69.7398",
                              ssid= "xfinity"
                            );
    let mut response = reqwest::get(&request_url)?;
    let mut hm = HashMap::new();
    for (key, val) in response.headers().into_iter() {
      hm.insert(key.as_str().to_owned(), val.to_str().ok().unwrap_or("").to_owned());
    }

    let req = Req {status: response.status().as_u16(), url: request_url, body: response.json().ok(), headers: hm};

    println!("{}", serde_json::to_string(&req).unwrap_or("".to_owned()));

    Ok(())
}

to improve such a solution you can implement the trait From not to be so descriptive each time.
Comment: Hello, sorry if I wasn't being clear, but even with your code I get the same output with status code 401 unauthorized. However if I were to visit the fully constructed request in a web browser https://api.wigle.net/api/v2/network/search?first=0&latrange1=41.159&latrange2=42.889&longrange1=-73.5081&longrange2=-69.7398&freenet=false&paynet=false&ssid=xfinity it would give me the intended output

Rust JSON API Request Formatting


PHP include unless on a certain page, then include different

Question: I have a php site that includes a menu.  There is a section that I do not want to include that menu, but want to include a different one.  I am sure I need an if/else but am struggling.
my index is built like this
html and head
div wrapper
include header
include page build
include footer
the page build file uses the index template and calls for each pages content.  therefore each page uses the same header and footer. i want to use a second header on a specific section.
so section 1, 3, 4, 5, 6, 7, 8 uses header 1
section 2 uses header 2
Comment: Include some code in your question if you want us to help
Comment: `'site is built (using "page build")'` - It is not so clear what you mean by this...
Comment: This might be helpful: http://php.net/manual/en/language.control-structures.php
Comment: use if(){...}else{.....}
Comment: Your question is not clear.
Answer: say, you have a file called menu.php which you want to include in index.php and in that menu you do not want to include a menu/text called Loggin. Ok? Now, in menu.php you can do like this:

 Home

 about

 profile

 blog
<?php if(isset($allow)) {echo '
 Loggin
';} else {echo "";}

With the above if/else you are telling PHP, if the variable $allow has any value echo Loggin, else show nothing. now all you have to do, is include your menu, but in index.php either set $value to anything if you want Loggin to be shown, or just leave it if you don't want loggin to not appear
Answer: You could try using:
if ($_SERVER['SCRIPT_NAME'] == "/page1.php") {
    include("fileToInclude.php");
} else {
    include("differentFileToInclude.php");
}


Are predicate or function symbols with 3+ places actually used in mathematical logic?

Question: Let $n$ be a nonnegative integer. The language of first-order logic includes the following symbols :

predicate symbols with $n$ places: $P^n_0$, $P^n_1$, $P^n_2$, $\dots$
function symbols with $n$ places: $f^n_0$, $f^n_1$, $f^n_2$, $\dots$

What is an example of a formal system which actually uses a predicate or function symbol with 3 or more places? I am asking about a specific symbol, not predicate variables. It seems that, in practice, only unary (1-place) and binary (2-place) symbols are used.
Examples.

Axiomatic set theory uses one binary predicate symbol (membership) and no function symbols.
Formal number theory uses one binary predicate symbol (equality), one unary function symbol (succession) and two binary function symbols (addition, multiplication).
Formal group theory uses one binary predicate symbol (equality), one unary function symbol (inversion), and one binary function symbol (multiplication).

*The last two systems use a constant symbol, which may be regarded as a 0-place function symbol.
Answer:
What is an example of a formal system which actually uses a predicate or function symbol with 3 or more places? I am asking about a specific symbol, not predicate variables. It seems that, in practice, only unary (1-place) and binary (2-place) symbols are used.

Hmm, I am a little unclear on your question ... but I think your question is about something we use in practice. For example, when doing something with numbers, we might use a 2-place predicate that we want to use for 'Smaller than'. Or, we could use a 1-place predicate 'Even'.  And for functions we could use the 1-place function 'successor', or the 2-place function 'addition'.  So yes, plenty of 1-place or 2-place relations or functions here. But do we have any 'natural' 3-place predicates or functions when we apply our logic system to some domain?
Well, I suppose something like '$Sum(x,y,z)$', meant to mean: '$x$ is the sum of $y$ and $z$' could work
Or maybe someone could make good use of a $Between(x,y,z)$ ('$X$ is between $y$ and $z$') predicate ... which could be used in all kinds of domains (e.g. not just numbers, but think of objects having some location in some world)
Comment: I'm asking about a formal system. For example, set theory only uses the binary predicate symbol $\in$. This seems like informal or philosophical usage.
Comment: @simplejack Between(x,y,z) is something a formal system for geometry would use. And Sum(x,y,z) is used in formalizations of computability theory
Answer: Tarskian geometry uses 3-place and 4-place predicates (at least I think they are 3-place relations, not functions, I haven't studied it in detail).  Here's an example paper on the topic.
Comment: Yes, if I remember correctly Tarski used the $3$-place predicate "between" (as in Bram28's answer) and the $4$-place equidistance predicate, "the distance from $a$ to $b$ equals the distance from $c$ to $d$.
Comment: @AndreasBlass Thanks!
Comment: Not enough rep to upvote :(
Comment: @simplejack Thanks for trying!
Comment: Couldn't Tarskian geometry be reformulated using unary and binary relations? Define a term $L(x,y)$ as the line segment with endpoints $x$ and $y$, a formula $R(x,y)$ meaning that $x$ belongs to $y$, and take equality to mean congruence of line segments. If this is correct, why did Tarski choose not to do this?
Comment: @simplejack I think Tarski wanted only one kind of object in the base language, to keep things simple (metamathematically).


Linux Kernel Driver: Returning a pointer to a kfifo results in a null pointer

Question: I've come up against a problem passing a pointer to a kfifo that I can't seem to solve.
A little background; I've taken over the development a of Kernel Driver for a Gumstix interface with an FPGA. The FPGA in this scenario is basically taking multiple serial streams, doing some processing on the data and then making it available to the Gumstix via the GPIO. Since this is actually quite a complex project, I'll spare the details - since it would turn into quite a lengthly post, of mostly irrelevant information. I have working prototype drivers for the individual serial interfaces - this driver is just all of those combined.
In the first / main file (gpio.c) of this driver a number of kfifo's are initialised and stored in an array, in a structure:
#define NUM_DEVICES 31
#define DEVICE_FIFO_SIZE 65536

struct fpga_interface {
    ...
    struct kfifo fifos[NUM_DEVICES];
    spinlock_t fifo_locks[NUM_DEVICES];
    ...
};

static struct fpga_interface fpga;

int __init fpga_init_interface(void)
{
    int i;

    info("Initialising\n");

    // KFifo initialisation
    for(i=0; i<NUM_DEVICES; i++)
    {
        if(kfifo_alloc(&(fpga.fifos[i]), DEVICE_FIFO_SIZE, GFP_KERNEL)) {
            printk(KERN_ERR, "Error allocating the KFIFOs\n");
            return 1;
        }

        spin_lock_init(&fpga.fifo_locks[i]);

        info("Initialised KFIFO %d with addr=%x\n", i, &(fpga.fifos[i]));
    }
    ...
    info("Initialised\n");
}

void get_fifo(int dev, struct kfifo* fifo, spinlock_t* lock)
{
    fifo = &(fpga.fifos[dev]);
    lock = &(fpga.fifo_locks[dev]);

    info("Returning the KFIFO for devid=%d, fifo=%x, lock=%x", dev, fifo, lock);
}

Then in another file (primary.c - which deals a specific interface) we have this:
struct fpga_primary {
    ....
    struct kfifo* fifo;
    spinlock_t* fifo_lock;
...
};

static struct fpga_primary primary;

int fpga_primary_init(void)
{
    info("Starting Primary\n");

    //Get our fifo and fifo lock
    get_fifo(1, primary.fifo, primary.lock_fifo);

    info("Got kfifo_addr=%x, lock_addr=%x\n", primary.fifo, primary.fifo_lock);
    ...
    info("Completed Primary\n");
}

Now, below is the kernel log from the gumstix:
Nov 30 02:28:14 overo [17837.989776] GPIO: Initialising
Nov 30 02:28:14 overo [17837.997497] Initialised KFIFO 0 with addr=bf062bb4
Nov 30 02:28:14 overo [17838.005249] Initialised KFIFO 1 with addr=bf062bc8
Nov 30 02:28:14 overo [17838.012847] Initialised KFIFO 2 with addr=bf062bdc
...
Nov 30 02:28:14 overo [17838.233947] GPIO: Initialised
...
Nov 30 02:28:14 overo [17838.264984] PRIMARY: Starting Primary
Nov 30 02:28:14 overo [17838.272979] GPIO: Returning the KFIFO for devid=1, fifo=bf062bc8, lock=bf062e20
Nov 30 02:28:14 overo [17838.281280] PRIMARY: Got kfifo_addr=0, lock_addr=0
Nov 30 02:28:14 overo [17838.296203] PRIMARY: Completed Primary

What you'll notice is that the call to get_fifo(...) returns NULL pointers. Which is not good really and I can't seem to find out why.
I'm using the OpenEmbedded / BitBake standard environment, with Kernel version 3.2.0 and Angstrom 2011.03 tool chain. I'm building on Ubuntu 10.04.
Any ideas? I'm left thinking that for some reason I'm being prevented from passing a pointer to the kfifo around...but I've not been able to find anything documented as to why I can't / shouldn't do this, considering we pass pointers to kfifo's along to the kifo_ functions.
Comment: How does `get_fifo()` return values?  It needs a double pointer to *write back* the value.
Answer: I think the wrong result is due to the function void get_fifo(int dev, struct kfifo* fifo, spinlock_t* lock), in this function, you assign the results to local variables: fifo and lock; when the get_fifo() return, the local variable will be invalid.
So my suggestion is: declare the get_fifo() function as:
    void get_fifo(int dev, struct kfifo** fifo, spinlock_t** lock)
    {
        *fifo = &(fpga.fifos[dev]);
        *lock = &(fpga.fifo_locks[dev]);

        info("Returning the KFIFO for devid=%d, fifo=%x, lock=%x", dev, *fifo, *lock);
    }

In function int fpga_primary_init(void), call get_fifo() as:
    get_fifo(1, &(primary.fifo), &(primary.lock_fifo));

I think it will solve your problem.


Does there exist an $x$ such that $3^x = x^2$?

Question: I tried solving for $x$ by using $x \log(3) = \log(x^2)
$$\log(3) = \frac{\log(x^2)}{x}$$
I'm stuck on this part. how do I isolate $x$ by itself?
Any help would be appreciated.
Comment: If you just want to find if a root exists, it is unnecessary to solve for the numerical value of the root itself. One may use the intermediate value theorem (Bolzano's theorem, in particular) since the function $f(x) = 3^x - x^2$ is continuous.
Comment: There is no simple algebraic method to solve such expression.  The thing you need is Lambert W-function.  Otherwise, as Michael T mentioned, you need Intermediate Value Theorem, which determines the existence of the points on $3^x - x^2$.  The answer is yes, but you will need to back up with proof.
Comment: Did you try graphing it?
Comment: yea i ended graphing it and found an intersection. I just wanted to know if there was a way to solve it algebraically. Thanks
Comment: whoops- i think i made a mistake in my edit- is there something wrong with the first logarithm?
Answer: Let $f:\mathbb{R}\rightarrow \mathbb{R}$, $f(x)=3^x-x^2$.
Note that $f$ is continuous and $f(0)>0$ and $f(-1)<0$, then exists $\alpha\in (-1,0)$ such that $f(\alpha)=0$, i.e., $\exists \alpha \in(-1,0)$ such that $3^{\alpha}-\alpha^2=0$.
However, only a numerical method solves this problem.
Answer: The unique real solution is $$-2 \dfrac{W(\ln(3)/2)}{\ln(3)}$$
where $W$ is the Lambert W function.  There are also complex solutions, corresponding to the different branches of $-2 \dfrac{W(\pm\ln(3)/2)}{\ln(3)}$
Answer: As Robert Israel wrote, the two roots of the equation are $$x_{\pm}=-2 \dfrac{W(\pm\ln(3)/2)}{\ln(3)}$$ The solution $x_-$ can be discarded if $x$ is supposed to be real because, for this case, the argument of Lambert function is smaller that $-\frac{1}{e}$.
As showed by Michael T, there is a solution such that $-1<x<1$ (in fact subbing in $x=0$, we find that $3^0-0=1$ is positive and then the root is somewhere between $x=-1$ and $x=0$). By inspection, you coul find an evn shorter range for the solution.
As you were told, the solution cannot be expressed using basic functions and, if you do not access Lambert function, only numerical methods could be used. Newton iterative scheme is probably the simplest and, starting from a reasonable guess, this will be updated according to $$x+\frac{x^2-3^x}{3^x \log (3)-2 x}$$ So, being very lazy and starting the iterative process at $x=0$, the successive iterates will then be $-0.910239$, $-0.703169$, $-0.686137$, $-0.686027$ which is the solution.
More generally, the solution of an equation such as $$a b^x=x^c$$ has a solution which write $$x=-\frac{c W\left(-\frac{a^{\frac{1}{c}} \log (b)}{c}\right)}{\log (b)}$$
Answer: There is no simple algebraic way to find a numerical value to solve this expression, you would need the Lambert W-function. However, you can affirm that a root exists.
Using the (true) assumption that $3^x - x^2$ is continuous, we can show that a root exists by showing that $3^x - x^2$ is positive for a value of $x$ and negative for another. This follows from the intermediate value theorem.
Subbing in $x = -1$, we find that $3^{-1} - (-1)^2 = \frac 13  - 1 = - \frac 23$ is negative.
Subbing in $x = 1$, we find that $3^1 - (1)^2 = 2$ is positive.
Thus, a root exists and it is somewhere between $x = -1$ and $x = 1$.


Detecting pinch in Android browser

Question: So there seems very little around about this. I need to be able to detect pinching in the Android browser with Javascript. Not with use of a plugin (except jQuery). The only site I have seen this implemented is Google Maps.
Lets just say for now I want to be able to pinch inside of a div and it will log when I do so.
Struggling to find any examples.
Answer: Check hammer.js http://eightmedia.github.com/hammer.js/ it looks like transform gesture may do what you want.

Detecting pinch in Android browser


Why does the TCP server wait for an ACK when sufficient window is available at client side

Question: I'm observing the below behavor in a TCP connection between a server application and a client which run on two different Red Hat machines.
Example 1

Client acks everything until now (ACK with WND = 1424)
Server sends 296 bytes to TCP layer and it is sent to the client(PUSH/ACK)
Server sends 296 bytes to TCP layer and it is sent to the client(PUSH/ACK)
Server sends 296 bytes to TCP layer and it is sent to the client(PUSH/ACK)
Server sends/tries to send 239 bytes to TCP layer but: either one of the following two happens

the OS waits ~30ms until ACK from client is received before sending these bytes (this x bytes send will be referred as delayed message below)
the tcp send call returns EWOULDBLOUCK or EAGAIN (I think this is not possible because 239+239+239+239 < 1424. Please correct me if I'm wrong

Example 2

Client acks everything until now (ACK with WND=1424)
Server sends 239 bytes to TCP layer and it is sent to the client
Server sends/tries to send 239 bytes to TCP layer and one of the two things in the above happens

The problem I want to understand is why the server application or the OS waits until the ACK when window size for the client is big enough? Is this something I can tune in the OS level. Can I force server to send all bytes until the window of the client is filled?
As per my understanding there are two possible reasons

Server application does not pass the 'delayed message' to TCP level becuase the send system call returned EWOULDBLOUCK or EAGAIN.
Application does pass the message to TCP layer, but the operating system does not send it until an ACK from the client is received.

In all the delayed message scenarios, there is an ACK from the client before the SEND of the delayed message. Also the working logic of the application suggests that it does pass the message to the TCP layer.
Can you please suggest where I should focus on the troubleshooting of this.

Is it some OS level setting I can set in either the client or server side
Is this somehow a fault in the application server?
Am I wrong in assuming OS doesn't return EWOULDBLOCK until messages fill up the window

edit: Reason for duplicate: I was not sure where the issue is; network/os. I have added aditional details. Also, I need a POV from TCP implementation of linux so I think this question belongs here.
Comment: Possible duplicate of your question from 12 hours ago: [Why is a packet is not sent by TCP until ACK is received when window size is sufficient](https://serverfault.com/questions/986824/why-is-a-packet-is-not-sent-by-tcp-until-ack-is-received-when-window-size-is-suf).
Comment: But duplicate question is deleted(
Answer: This is called "Delayed ACK" and it's the way TCP protocol works. See https://en.m.wikipedia.org/wiki/TCP_delayed_acknowledgment for more details. You can disable this feature if it affects your applications's performance. Say iSCSI has delayed ACK turned off by default.
Comment: I think the answer misses something. For sure "delayed ack" is what causes the delay of the ack, but I don't see how this answers why the opposite side doesn't proceed until the ack arrives, which is the point of the question.
Comment: TCP_NODELAY is for Nagle algorithm, it has nothing to do with delayed ACK, these are two different things. See https://www.extrahop.com/company/blog/2016/tcp-nodelay-nagle-quickack-best-practices/ for more details.
Comment: This is distro-dependent. If you however control application's source code you can play with these settings independently of your environment. See https://stackoverflow.com/questions/1615447/disable-tcp-delayed-acks for similar case.
Comment: But I have set TCP_NO_DELAY in the server application box
Comment: I have set tcp_low_latency=1
Comment: Because it's the way TCP/IP works. To avoid flooding (which is basically a DoS thing) sent packets must be acknowledged by receiver.


Within Subjects Design question

Question: I have 75 participants and each participant has an exam on 15 questions. These questions are words. Their answers are 0 and 1 (known-unknown). Then I have another variable, their fixation on those words in a text: it is continuous (300 milliseconds for example). The data in long form looks like this.

And it goes on. For each participant I have 15 variables as 0 and 1 (index variables). I hypothesize that participants look longer at unknown words. But I cannot figure out the accurate procedure. I need millisecond means for 0 and 1 and the significance but it inflates my degrees of freedom (more than 1100) although I have only 75 participants.
I use spss, all suggestions are welcome.
Comment: Did each participant see exactly the same list of words or were there randomly choose? This sounds like a logistic regression or mixed-effects model problem. Also notice that the `descriptive-statistics` tag seems to be unrelated and can be misleading.
Comment: I edited your tags, please check if they are correct and if not edit them to be more precise.
Comment: Yes Tim, all learners saw the same words, same text, everthing is same. But their answers differ, some knew many words, some did not. Thanks for editing also.
Answer: I would model the fixation time with a mixed effects model, with a random intercept for ID, and maybe also a random slope within ID. Using the R package lme4 such a model could be written as
lme4::lmer( fixation ~ index*answer + (1 | ID), data=your_data_frame )

which means that index, answer and their interaction are fixed effects while there is a random intercept within ID. But the difference in time between known and unknown words could well differ between persons, so a random slope seems needed, leading to
lme4::lmer( fixation ~ index*answer + (1 + answer | ID), data=your_data_frame )

Within Subjects Design question


Form.Owner set from separate thread in .NET 3.5

Question: I am writing a test application where I need to put Form on separate thread.
So if I create Form window from main thread and set its .Owner = this everything works.
If I spawn thread UIThread and set Owner from new thread I get exception.
Getting exception is understandable since you can't access forms directly.
My question is is there a message that I need to catch on main thread and do BeginInvoke to push it on it's message pump? Since UIForm ShowInTaskbar is set to false I need to click on main application in taskbar and restore with all its children windows.
private void UIThread() // New Thread call
{
        UIForm form = new UIForm();

        form.ShowInTaskbar = false;
        form.Owner = this;

        Application.Run(form); // Expected Exception
}

Comment: You'll have to pinvoke SetParent to get around this.  Best thing to do is to not do this.
Answer: I am not sure, maybe Application.Run shall be called only once per application. See if this one will work for you
Application.Run(new Form1());
-----------------
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

        var thread = new Thread(
            () =>
                {
                    var form2 = new Form {Owner = this};
                });
        thread.Start();
    }
}


java get value from JTextField and set it as BigInteger

Question: I have two classes in a package: firstClass and secondClass.
I created a textfield in firstClass, let's assume it's txtStringNumber.
I created a method in firstClass to get txtStringNumber value, like this:
public String getStrNumber(){
    String strNumber = txtStringNumber.getText();
    return strNumber;
}

I must pass it to secondClass as String and put the strNumber as BigInteger value.
In second class I created a method to get value of txtStringNumber from firstClass, like tis:
public static String theNumbers(){
     firstClass f = new firstClass();

     return f.getStrNumber();
 }
public static String strAllNumbers = theNumbers();

When I print strAllNumbers in secondClass, it prints the correct value. Then I add this:
public static BigInteger bigAllNumbers = new BigInteger(strAllNumbers);

In my mind, it should works. But in real, it doesn't. Error occurs.
So I check the error, there said:
throw new NumberFormatException("Zero length BigInteger");

I guess BigInteger accept strAllNumbers as empty.
But just like I already said, when I print strAllNumbers directly without set it to BigInteger, it returns the correct value.
What's wrong here and how can I fix this?
Answer: You're creating a firstClass object, f, and getting a String from its textfield before anybody ever has a chance to enter text in it. So no surprise that it's empty.
Solution: Don't do this! Only get the text after something that makes sense has been entered.
I'm guessing that you have two firstClass objects, one displayed, and a second one created in this method, and are guilty of magical thinking that changes to the displayed object will be reflected in the newly created one, but that's not how programming works. Instead pass a valid reference of the displayed object to the other object that needs it.
Comment: @MadProgrammer: indeed. and a ditto 1+!
Answer: You're creating a new instance of firstClass in the theNumbers method (firstClass f = new firstClass();), it's very unlikely the the value of the text field has been set to anything useful (especially by the user)
You either need to supply a means of firstClass to pass the value from the text field to secondClass, probably via a setter of some kind (this is classic producer-consumer pattern) or set up a mechanism for firstClass to notify secondClass when the value changes and then have secondClass retrieve that value (this is a class observer pattern).
In any case, you should not be creating a new instance of these classes, you need to create them and then pass these instance to which ever one is going to act as the controller...


Eliminar Tabela gerada e voltar a recriar com outros dados

Question: Tenho esta tabela que será gerada com valores de checkboxes que eu seleciono.
HTML:

JavaScript:
$('#preVisualizar').click(function () {
        var checkbox = $('input:checkbox[name^=mcheckbox]:checked');

        if (checkbox.length > 0) {
            var val = [];
            checkbox.each(function () {
                val.push($(this).val());
            });

            var context = document.getElementById("table");
            context.className = "table";
            var header = context.createTHead();
            var row = header.insertRow();

            for (var i = 0; i < val.length; i++) {
                var th = document.createElement('th');
                th.innerHTML = val[i];
                row.appendChild(th);

                var row2 = document.getElementById("Row2");
                var y = row2.insertCell(i);
                y.innerHTML = "Ex. " + val[i];
            };

        } else {}
}
});

WEB:

Ao clicar num botão para pré-visualizar fica assim:

Até aqui tudo bem. Essa tabela é aberta num model. Quando clico no botão 'ok' para fechar o model e volto a clicar no botão pré-visualizar fica assim:

Isto é, eu no botão 'Ok' queria limpar a tabela toda e depois voltar a gerá-la ao clicar em pre-visualizar para não me replicar os dados. Tentei colocar $('#table').remove(); mas quando volto a carregar em pré-visualizar dá-me o seguinte erro:
Uncaught TypeError: Cannot set property 'className' of null

Como poderei fazer um 'clean' à table e voltar a gerá-la?
Comment: não seria mais simples se a tabela já possuise todos os dados, e ao cliclar no checkBox apenas realizar um toggleClass na respectida coluna?
Comment: Sou bastante noob em HTML, não sei o que é o toggleClass :s
Comment: algo do genero: http://jsfiddle.net/8pxsymjv/
Comment: Gostei bastante do seu exemplo, desde já obrigado, certamente será útil. Só uma questão, da forma que está, dá para por a aparecer a tabela depois das checks selecionadas? Isto é, seleciono Codigo e Designação, clico num botão e aí sim, aparecer a tabela , ou o toggleClasse só permite assim digamos que a aparecer em tempo real ?
Comment: neste caso o evento deve esta associado ao Click deste Button e nao ao Click do checkBox.
O toggleClass apenas "liga/desliga" a classe.
Answer: @HugoMachado, uma abordagem mais simples seria apenas alterar a visibilidade das colunas.
HTML

    <input id="ckCodigo" name="ckCodigo" type="checkbox" data-type="ckColuna" data-column="codigo" />
    Código

    <input id="ckDesignacao" name="ckDesignacao" type="checkbox" data-type="ckColuna" data-column="designacao" />
    Designação

    <input id="ckQuantidade" name="ckQuantidade" type="checkbox" data-type="ckColuna" data-column="quantidade" />
    Quantidade

          Código
          Designação
          Quantidade

          Código
          Designação
          Quantidade

          Código
          Designação
          Quantidade

          Código
          Designação
          Quantidade

JS
var checkBoxes = $("[data-type='ckColuna']");
var tabela = $("#table");

checkBoxes.click(function () {
    if (checkBoxes.filter(":checked").length > 0) {
        tabela.removeClass("hide");
    } else {
        tabela.addClass("hide");
    }

    var checkBox = $(this);
    var celulas = $("table [data-column='" + checkBox.attr("data-column") + "']");
    celulas.toggleClass("hide");
});

CSS
.hide {
    display: none;
}

Alternativamente você pode colocar o CSS na propria pagina.
É aconselhavel faze-lo no cabeçario da pagina.
Mas lembresse que o ideal é sempre ter o CSS em um arquivo separado.
HTML - Header

    ...

    ...

JSFIDDLE
http://jsfiddle.net/8pxsymjv/1/
Comment: A parte do css é necessário defini-la ?
Comment: É preciso ter uma classe com display: none;
é esta classe que será ativada/desativada para exibir ou não a coluna.
Comment: É que eu não estou a mexer no css, nunca mexi, não posso definir essa classe noutro lado ?
Comment: você pode adicionar na propria pagina, vou colocar uma nota na resposta.
Comment: Desculpe mas tou muito verde nisto ainda. No javascript posso definir a class assim?   hide = function(){
        display: none;
    }
Comment: Já consegui, muito Obrigado era exatamente isto ;) Não estou a conseguir é por a acontecer na ação do botão e não na ação das checkboxes. Ao clicar no botão abre um model, onde estará a tabela
Comment: neste caso a tabela ficaria dentro do modal, o evento Click do button apenas abriria o Modal. não é necessario alterar o evento Click do CheckBox.
Comment: Já está resolvido. Muito obrigado @TobyMosque