text:
Q: Filtering calculated values with pandas in python I am trying to filter the values of 'BMI', such that I'm left with all values less than 35. However, when executing this (see code) I end up with a 248x19 (i.e. the imported file) matrix with some (for me unexplainable) NaN values inside of it, instead of getting a single column of filtered 'BMI'-values, which I ultimately want.
Code in pycharm:
df = pd.read_csv('BodyFat.csv', sep=';',decimal=',')
df['BMI'] = 703*df.WEIGHT/(df.HEIGHT**2)

df_filter = df[df['BMI'] < 35]

print(df_filter)

Code
Edit* Output
How can I solve this?

A: I am guessing this might be due to NaN values :
new_data = df[(df[''BMI'] < 35) & (df['BMI'].notnull())]

len(df)
len(new_data)


text:
Q: is it possible to project any triangle on a plane as a right triangle on another plane? I scratching my head over this problem from my projective geometry book (C. R. Wylie, Jr).
Given a triangle in the plane $z = 0$, is it possible to find a viewing point, $C$, from which the triangle will appear on the plane $y = 0$ as a right triangle.
What about for isosceles triangle? For equilateral triangle?
I have tried using algebra to find the dot product of the image vectors to find a solution of constructing right angle triangles, but it seems really messy. Is there a way to prove or disprove using elementary geometry?

A: Let $m_1$ and $m_2$ be two sides of the original triangle that are not parallel to the image plane, meeting at $A$.
Consider the plane through $A$ parallel to the image plane and choose two lines $k_1$ and $k_2$ in it, which meet in a right angle at $A$, such that neither $k_1$ nor $k_2$ is parallel to the plane of the original triangle.
Let $P_1$ be the plane spanned by $m_1$ and $k_1$, and let $P_2$ be the plane spanned by $m_2$ and $k_2$.  Clearly $P_1$ and $P_2$ intersect each other (because both contain $A$) but do not coincide (because then they would be the triangle plane, contradicting the choice of $k_1$ and $k_2$).
Chose $C$ on the intersection between $P_1$ and $P_2$, far enough form $A$ that the entire triangle projects onto the image plane in one piece.
Then the image of $m_1$ as seen from $C$ is the intersection between $P_1$ and the image plane (which exists because $m_1$ wasn't parallel to the image plane), and is therefore parallel to $k_1$. Similarly the image of $m_2$ is parallel to $k_2$. Therefore the image of the triangle is right.

This works whenever the triangle is not parallel to the image plane. In fact, by projecting back to the camera point from all three sides, you can get to choose all three angles of the image triangle and except for degenerate cases even its orientation. So it is also possible to get the image to be isosceles or equilateral (or for that matter right isosceles).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using locally loaded images with docker-compose I'm connected to a machine with no internet connection, so I loaded the Docker image I want to use locally:
docker load -i backend.tar

It's tagged backend:latest.
My docker-compose.yaml is configured like so:
version: '3.7'

services:
  backend:
    image: backend:latest
    ports:
      - 1234:1234

But when I'm running docker-compose up -d backend I'm getting:

Error response from daemon: Get "https://registry-1.docker.io/v2/": read tcp <local-ip>:46344-><remote-ip>:443: read: connection reset by peer

Which means docker-compose is trying to reach out to the internet, which he shouldn't.
Is there a way I can force docker-compose to use the locally loaded image?

A: The kind docker-compose community have merged a fix for this. Coming soon!


text:
Q: Tomcat and garbage collecting database connections I asked (and answered myself) this question a couple of days ago, and resolved the problem, but I can't quite understand why the problem was solved and was hoping to get some clarification.
Essentially, I have implemented a jax-rs-based REST service that retrieves information from a RavenDB database and returns that content in a stream. The problem that I had was an unclosed database results iterator, which caused the REST service to hang (and accept no further requests) after exactly 10 requests.
My code is, roughly, as follows:
public Response ...
    {
        (...)

        StreamingOutput adminAreaStream = new StreamingOutput()
        {
            ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();

            @Override
            public void write(OutputStream output) throws IOException, WebApplicationException
            {
                try(IDocumentSession currentSession = ServiceListener.ravenDBStore.openSession())
                {
                    Writer writer = new BufferedWriter(new OutputStreamWriter(output));
                    (...)
                    CloseableIterator<StreamResult<AdministrativeArea>> results;
                    (...)
                    writer.flush();
                    writer.close();
                    results.close();
                    currentSession.advanced().clear();
                    currentSession.close();
                }
                catch (Exception e)
                {
                    System.out.println("Exception: " + e.getMessage() + e.getStackTrace());
                }
            }
        };
        if(!requestIsValid)
            return Response.status(400).build();
        else
            return Response.ok(adminAreaStream).build();
    }

From what I understand about the object lifecycle in Java, or rather more specifically object reachability and garbage collection, even though I didn't properly close that CleasableIterator, it should go out of scope/become unreachable by the time my method finishes with either a 400 or 200 status - and therefore get garbage collected.
Just to be clear: I am certainly not suggesting that one shouldn't properly close opened connections etc. - I AM doing that now - or rely on Java's garbage collection mechanism to save us from lazy/unclean coding... I am just struggling to understand exactly how those unclosed iterators could have caused the Tomcat behaviour observed.
In fact, my assumption is that we don't even need to know the details about the iterator's implementation, because at the "galactic level" of Java the object lifecycle, implementation differences are irrelevant. => "Once an object has become unreachable, it doesn't matter exactly how it was coded".
The only thing I can imagine is that Tomcat somehow, (through its container mechanism ?), slightly changes the game here, and causes things to "hang around".
Could someone please shed some light on this ?
Thanks in advance !

A: The CloseableIterator refers to a CloseableHttpResponse which refers to a HTTP connection. No finalizer releases the response or the connection,  when CloseableIterator is not reachable anymore. You created a connection leak. Your bug is similar to the one described here: https://phillbarber.blogspot.com/2014/02/lessons-learned-from-connection-leak-in.html
See here why finalize methods to release resources are a bad idea: https://www.baeldung.com/java-finalize


text:
Q: C# - How to pick element inside frame using HTMLDocument.getElementById and InternetExplorer object I have an html that looks like this

    <frameset id="workFrame" rows="45,*" border="0" frameSpacing="0">
        <frame name="menuFrame" id="menuFrame" src="Test.aspx" frameBorder="0" noResize="noresize" scrolling="no">

                    <form id="form1" action="./Test.aspx" method="post">

    </frameset>
</html

I want to get the "anchorTwo" and put it inside a HTMLAnchorElement so
  that I can click it. But when I try to do it with my code, I get a
  NULL HTMLAnchorElement. Does anyone know a way to work around this? I've been trying for hours, I can't seem to find a way.

This is my code:
InternetExplorer ieObject = new InternetExplorer();
HTMLDocument htmlDocObject = null;
ieObject.Visible = true;
ieObject.Navigate("http://samplewebsite.com");

while (ieObject.ReadyState != tagREADYSTATE.READYSTATE_COMPLETE || ieObject.Busy)
{
    Console.WriteLine("Sleeping for 2 seconds...");
    Thread.Sleep(2000);
}

Console.WriteLine($"Website loaded");
htmlDocObject = ieObject.Document;

HTMLFrameElement frame = (HTMLFrameElement)htmlDocObject.getElementById("menuFrame");
Console.WriteLine(frame.name);
Console.WriteLine(frame.src);

HTMLDocument frameDocument = frame.document;

HTMLAnchorElement anchor = (HTMLAnchorElement)frameDocument.getElementById("anchorTwo"); \\null pointer here

anchor.click();

Console.ReadLine();

A: use
HTMLDocument frameDocument = (HTMLDocument)frame.contentWindow.document

instead of
HTMLDocument frameDocument = frame.document;


text:
Q: Can quantum entanglement contribute to entangled particle's decay? Does a quantum entanglement have an influence on the entangled particle's decay?

A: Considering that the neutrons in the nucleus are entangled quantum mechanically, the fact that the half-lives of the beta decay depend on the isotope means that yes, entanglement affects decays.


text:
Q: How to attach a delegate when adding a new record I have a form where i attach the OnChange method like
$(document).ready(function () {
    $('#fieldId').change(function () {
    ...
   }
}

But i have the case when i add a new record with the Id "fieldId" from a function as
function addTeamMember() {
var newItem= "<input  id='fieldId' type='text'>"
$("#other").append(newItem);
...
}

But the Change is not fired when i change the newly added field. Can somebody help me with an idea?
Thanks.

A: Change the onchange event listener to:
$('body').on('change', '#fieldId', function () {
  // ...
}

you can replace the 'body' with any container that is wrapping the dynamically added DOM element. This way, you delegating the event to existing or not existing yet elements.


text:
Q: Business Central Workbench (drools) add user is not working from custom datasource I have setup a wildfly-server with a legacy security domain using postgresql. Now I can add users and role into db and can login. The issue is after I add users through business central GUI I am not able to login using those new users. Also I am not able to see those users in my DB.
Can somebody help me understand where Business Central Workbench stores the user data, and how can I configure it to use postgres? The screenshot below shows the list of users I have created from workbench but these users are neither in the database or able to login.

I tried directly adding users into DB, and it works. I tried searching new user in application-roles.properties and application-users.properties. It's not there. I have no idea where these users are getting stored. Its not cached as when I restart the server, the users will show up below.


text:
Q: html2canvas is not working in Safari browser: Taking Screenshot I just want to take a screenshot of any HTML element ( "container" div in my case ).
it works fine in Chrome and Firefox browsers but not in Safari.
Following is how I am doing it:
<!doctype HTML>

Take screenshot of webpage with html2canvas

DIV 1

DIV 2

DIV 3

<input type='button' id='but_screenshot' value='Take screenshot' onclick='screenshot();'>

it shows the following error in the Safari browser:
and here is the specific part of code of html2canvas.js (it is by-default file I have just used).

A: we just have to enable the CORS in safari-mac browser. So, we'll do it by modifying our function screenshot() as follows:
function screenshot(){
    html2canvas(document.getElementById('id-screenshot'),{
        allowTaint: true,
        useCORS : true,
    }).then(function(canvas) {
        console.log("canvas: " + canvas);
        document.getElementById('test-s').appendChild(canvas);
    });
}


text:
Q: IIS exclude specific host? I have an IIS server running several websites. It is stationed behind an ISA server of which I do not have access. But I do have all of the defined websites (on port 80) routed to my server.
So I want to take down one website, say it's foo.bar.com and in its place setup a LAMP server instead using a VM software. It needs to run alongside all the existing websites and it should not interfere with them.
I have full control over my server, but not the ISA.
Is this possible? If so, how?
The OS is Win Server 2003 Standard with IIS6

A: how many websites are running on the windows box?  are they setup with host headers or IP addresses?
If they're setup with IP addresses (i.e. each site has its own IP), then  its easy.  Have your LAMP box take over the IP of the website you wish to convert.
If it's a single IP & you have host header, then its not so good.  You really should be speaking to your ISA administrator. The only other way i can see it working is if you setup your own server to do reverse proxying & then forward the traffic to your LAMP or IIS server depending on the hostname.  Apache has a reverse proxy module, so you can do it right off your LAMP box.

A: This might be possible if you configure the IIS 6 server as a proxy server.  Managed Fusion has a URL Rewriter that can do transparent proxy that should be able to have the IIS server pull all requests from your LAMP server.
In the discussion forum of the URL Rewriter project is an article that talks about doing something similar to your request; this article is about Apache on a localhost but shouldn't be much different for a remote Apache Server).
EDIT:  Keep in mind that using IIS as a proxy to a LAMP (or any other server) is incredibly wastful...  You should work with the ISA Admins to redirect the web publishing to the actual target server.


text:
Q: filter and create table I am trying to create a table from text, but I cannot get the result I want.
this is the text:

Reading sequence file /scratch/mauve_pro/populations/africa/rebuild_xmfa/block_fasta/africa_final_remove_new.100.fasta

NSS:                 1.60e-02  (1000 permutations)
Max Chi^2:           6.20e-02  (1000 permutations)
PHI (Permutation):   5.28e-01  (1000 permutations)
PHI (Normal):        4.73e-01

Reading sequence file /scratch/mauve_pro/populations/africa/rebuild_xmfa/block_fasta/africa_final_remove_new.101.fasta
NSS:                 8.52e-01  (1000 permutations)
Max Chi^2:           2.20e-02  (1000 permutations)
PHI (Permutation):   3.78e-01  (1000 permutations)
PHI (Normal):        4.53e-01

and this is the code:
cat africa_final_conca_phi.txt | sed 's/NSS/NSS NA/g' | grep -E "^NSS|^Max|^PHI" | awk '{{print $1 "\t" $2 "\t" $3 "\t{genome_stem}\t{single_gene_stem}"}}' > phiresult.tab

another code I try:
cat africa_final_conca_phi.txt | sed 's/NSS/NSS NA/g' | grep -E "^NSS|^Max|^PHI" | gene=$(printf '%s' "$africa_final_conca_phi.txt" | grep -Eo 'africa_final_remove_new.[0-9][0-9][0-9].fasta') | awk '{{print $1 "\t" $2 "\t" $3 "\t gene \t{single_gene_stem}"}}' > phiresult.tab

Outcome:
NSS NA: 1.60e-02    {genome_stem}
Max Chi^2:  6.20e-02    {genome_stem}
PHI (Permutation):  5.28e-01    {genome_stem}
PHI (Normal):   4.73e-01    {genome_stem}
NSS NA: 8.52e-01    {genome_stem}
Max Chi^2:  2.20e-02    {genome_stem}
PHI (Permutation):  3.78e-01    {genome_stem}
PHI (Normal):   4.53e-01    {genome_stem}
NSS NA: 0.00e+00    {genome_stem}

what I want:
NSS NA: 1.60e-02    africa_final_remove_new.100.fasta
Max Chi^2:  6.20e-02    africa_final_remove_new.100.fasta
PHI (Permutation):  5.28e-01    africa_final_remove_new.100.fasta
PHI (Normal):   4.73e-01    africa_final_remove_new.100.fasta
NSS NA: 8.52e-01    africa_final_remove_new.101.fasta
Max Chi^2:  2.20e-02    africa_final_remove_new.101.fasta
PHI (Permutation):  3.78e-01    africa_final_remove_new.101.fasta
PHI (Normal):   4.53e-01    africa_final_remove_new.101.fasta

A: This oneliner may help:
awk '{sub(/[(][^)]*[)]$/,"")}/^NSS/{$1="NSS AN:"}{$(NF+1)=FILENAME}7' *.fasta

Let's give it a test:
kent$  head *.fasta
==> 100.fasta <==
NSS:                 1.60e-02  (1000 permutations)
Max Chi^2:           6.20e-02  (1000 permutations)
PHI (Permutation):   5.28e-01  (1000 permutations)
PHI (Normal):        4.73e-01

==> 101.fasta <==
NSS:                 8.52e-01  (1000 permutations)
Max Chi^2:           2.20e-02  (1000 permutations)
PHI (Permutation):   3.78e-01  (1000 permutations)
PHI (Normal):        4.53e-01

kent$  awk  '{sub(/[(][^)]*[)]$/,"")}/^NSS/{$1="NSS AN:"}{$(NF+1)=FILENAME}7' *.fasta
NSS AN: 1.60e-02 100.fasta
Max Chi^2: 6.20e-02 100.fasta
PHI (Permutation): 5.28e-01 100.fasta
PHI (Normal): 4.73e-01 100.fasta
NSS AN: 8.52e-01 101.fasta
Max Chi^2: 2.20e-02 101.fasta
PHI (Permutation): 3.78e-01 101.fasta
PHI (Normal): 4.53e-01 101.fasta


text:
Q: How to merge changes to another svn repo? I have two svn repositories containing the same project, the first one is the trunk (the main place where development takes place), the second was forked off of the master a few revisions ago and contains a slightly customized version.
Now I have made changes to the main repo and would like to merge these changes to the forked one.
What would be the most efficient way to do this?
I've tried working with svn diff and patch but I can't quite figure it out.

A: Link branch from Repo1 to any node (outside branch in question) of Repo2 (using svn:externals) and you can after it diff or even merge subtrees of single repo

A: cd /home/user/repo-branch
svn merge -r PREV:HEAD svn://localhost/repo/

did the trick. PREV and HEAD can also be replaced with actual revision numbers.


text:
Q: Select2 dropdown fails inside Colorbox Select2 dropdown options fail to appear when Select2 is used inside a Colorbox.
I am using the Select2 dropdown successfully elsewhere in my application, but this is the first time I've tried to use it inside a colorbox popup.
I've tried all of the suggestions listed here, to no avail:https://github.com/jackmoore/colorbox/issues/474#issuecomment-25836400
I'm using jquery v3.1.1, jquery-ui v1.12.1, jquery.Select2 v4.0.3, and jquery.colorbox v1.4.29.  My browser is IE 11.
I'm opening the colorbox like this (I'm not using an iframe, and modal is the default value of "false"):
$.colorbox(
        {
            href: '/MyDomain/MyAction',
            open: true,
            scrolling: true,
            width: '60%',
            height: "60%",
            onComplete: function () {
                myJavascriptFunction();
            }
        });

The function that runs onComplete looks like this:
    myJavascriptFunction = function () {
    $('#SelectId option[value="0"]').prop('disabled', true);
    $("#SelectId ").select2({
        minimumResultsForSearch: Infinity,  //turns off the search box
        width: '400px',
        theme: "classic",
        dropdownAutoWidth: true,
        templateResult: myMethod,
        templateSelection: myOtherMethod
    }).on('select2:select', function (e) {
        yetAnotherMethod(e);
    });
}

I suspect this is a display issue.  The Select2 method call seems to be working--it has the correct width, displays the selected option correctly, and when I click it both the templateResult and templateSuggestion methods fire correctly, and it visibly goes through the same slight flicker and change in color that Select2 elements do when I use them successfully elsewhere.  When I click the Select2 element and view the page in DOM Explorer I can see that select2 html exists, along with the options. They just are not visible.
From the user's perspective the dropdown simply fails to drop and display the select options.

A: Actually I did not apply the suggestions correctly from https://github.com/jackmoore/colorbox/issues/474#issuecomment-25836400.
One of the suggestions there is to change the z-index, like so:
.select2-close-mask {
z-index: 10000;
}
.select2-dropdown {
z-index: 10001;
}

I thought I had tried that, but on closer inspection my css was being overridden by the select2.css file, which loaded after I applied my z-index and thus over-wrote what I was trying to do.
I even tried applying the z-index via a jquery call, eg:
$('.select2-dropdown').css('z-index',10005);

both before and after the call to Select2, but for whatever reason this had no effect.
But loading my style change after select2.css is loaded fixed the problem.

A: Use the link below to type in the input search select2:
https://select2.org/troubleshooting/common-problems
add code :
$('#mySelect2').select2({
    dropdownParent: $('#myModal')
});


text:
Q: Could not get unknown property 'PLAY_SERVICES_VERSION' i am getting Could not get unknown property 'PLAY_SERVICES_VERSION' error in ionic build after installing cordova-plugin-googlemaps in my ionic 3 app. if i remove this plugin then no error is showing in build. after adding this plugin again error is showing.

ionic cordova plugin add cordova-plugin-googlemaps --variable
  API_KEY_FOR_ANDROID="YOUR_ANDROID_API_KEY_IS_HERE"

i replaced YOUR_ANDROID_API_KEY_IS_HERE with the key i got from google.
same way i added in another app there it was working. here its not working

A: In \platforms\android\project.properties, replace PLAY_SERVICES_VERSION by "+" only
com.google.android.gms:play-services-base:+
com.google.android.gms:play-services-ads:+

Another way: install cordova plugin to create version automatically
cordova plugin add cordova-android-play-services-gradle-release

A: If you build your app with PhoneGap build, you need to specify the phonegap-version because that is a bug of PhoneGap build.
<widget ...>
  <plugin name="cordova-plugin-googlemaps" spec="^2.2.3">
    <variable name="API_KEY_FOR_ANDROID" value="(api key)" />
    <variable name="API_KEY_FOR_IOS" value="(api key)" />
    <variable name="PLAY_SERVICES_VERSION" value="11.8.0" />
    <variable name="LOCATION_WHEN_IN_USE_DESCRIPTION" value="Show your location on the map" />
    <variable name="LOCATION_ALWAYS_USAGE_DESCRIPTION" value="Trace your location on the map" />
  </plugin>

  <!--
    You need to specify cli-7.1.0 or greater version.
    https://build.phonegap.com/current-support
  -->
  <preference name="phonegap-version" value="cli-7.1.0" />
</widget>

https://github.com/mapsplugin/cordova-plugin-googlemaps/tree/3ee006140b4c83d59a6545aa5218fbcdb962cb9b#phonegap-build-settings

A: Had the same problem. I started with this approach: https://github.com/mapsplugin/cordova-plugin-googlemaps/issues/2039
I changed the project.properties and build.gradle in the platforms android folder. Replaced the $PLAY_SERVICES_VERSION variable with 11.8.0+ and removed the PLAY_SERVICES_VERSION parameter from config.xml
After this I checked for the latest update for google-play-services in the new SDK manager in Android Studio.
Maybe the last step is enough, but this were the steps I took.
EDIT:
A quick solution can be adding the line maven { url 'https://maven.google.com' } to your build.gradle
allprojects {
    repositories {
        maven { url 'https://maven.google.com' }
        mavenCentral();
        jcenter()
    }
}


text:
Q: jQuery Datepicker: select month with tab key I'm stuck trying to enable a keydown event on the "Next Month" button in jQuery datepicker.
The idea is to let users select the date without using a mouse, only tabulation and Enter key.
I know that there is a keydown map for the datepicker (http://hanshillen.github.io/jqtest/#goto_datepicker), but I want something easier and intuitively understandable. By the way, there's no "page down" button on my Mac (which is reserved for "next month"), so I cannot navigate through the datepicker using this default key settings.
By default, on tabulation "previous month" and "next month" buttons don't even come into focus. Still, I can solve this by adding "tabindex" attribute to the corresponding div. But even in the focus, the button doesn't respond to Enter key. Only clicking works.
Here's html of this piece of datepicker:
Next

(I added classes "ui-state-hover ui-datepicker-next-hover ui-state-active" using my javascript function).
What's next? Is this is the issue of changing data-event="click" to something else? I tried to do it, as well as to find the corresponding functions or handlers in both jquery.js and jquery-ui.js files, but failed. I've really got poor knowledge of advanced javascript and jQuery UI, as there must be some simple solution for this problem.
Appreciate any help, thanks.
P.S. Here, in StackOverflow I read lot's of discussions, but only this one:  Focus on jQuery UI Calender accessibility with TAB key seems to deal with datepicker accessibility / tabulation issue and still nothing is said there about selecting months.

A: Here is my solution based on the fact that the anchor tags for next/prev month are missing a href attribute, reason for which they do not receive focus (at least in chrome):
$('.js-calendar').datepicker({
        inline: true,
        altField: '.js-date-input',
        onChangeMonthYear: function (year, month, inst) {
            setTimeout(function () {
                // add href to prev/next anchors so that they can receive TAB focus
                $('.ui-datepicker-prev, .ui-datepicker-next').attr("href", "#");
            }, 50);
        }
    });

// add href to prev/next anchors so that they can receive TAB focus
$('.ui-datepicker-prev, .ui-datepicker-next').attr("href", "#");

Notice I added the hrefs outside the datepicker call (for initial purposes) and also in the onChangeMonthYear function (otherwise, they are lost after a change of month).
Note: using jquery-ui-1.11.2

A: I decided to post here a solution I've finally come up with. I'm not totally happy with it, by still this code does what I wanted, i.e.:

*

*'next month' button comes into focus when Tab key is hit

*on Enter key, user can move to the next month

*if this is the desired month, then pressing Tab moves focus to month days (one can access the needed day by successively hitting Tab)

*if this is NOT the desired month, then on Enter key user skips to the next month and steps 3–4 are repeated.

The major problem was that after selecting next month, the 'next' button on datepicker went out of focus and even when I managed it, the button didn't respond to Enter key. This is probably because the button is accessed by class name and after the month is changed in the datepicker, the element this class is referred to changes also (it's not, say, link to September, but to October instead). So, trying to trigger keydown (Enter) event for the second (or third, fourth etc) time on the same element didn't work. I guess this is also why I wasn't able to use this instead of className inside jQuery selectors.
I solved this by triggering keydown event inside separate function that calls itself.
Here's the code (which also includes some basic styling for the button depending on whether it is in focus or not):
function out_of_focus(id) {
    $(id).blur(function() {
      $(this).removeClass("ui-state-active");
    });
 }

 $(".ui-datepicker-next").attr("tabindex", "1");
 $(".ui-datepicker-next").focus(function() {
    tabulation();
 });

function tabulation() {
    $(".ui-datepicker-next").addClass("ui-state-active");
    $(".ui-datepicker-next").keydown(function(evt) {
      if (evt.which == 13) {
        $.datepicker._adjustDate("#datepicker", +1, "M");
        $(".ui-datepicker-next").attr("tabindex", "2");
        $(".ui-datepicker-next").focus();
        tabulation();
        out_of_focus(".ui-datepicker-next");
      }
  });
}
out_of_focus(".ui-datepicker-next");

Any suggestions on how to improve this are appreciated.


text:
Q: Transpose a list of dictionaries Given the following list of dictionaries representing a dataset:
a = [{"animal":"dog", "age":2},{"animal": "duck", "age": "3"}, {"animal": "duck", "age": "5"},{"animal":"dog", "age":10}]

How can I transpose this row-wise representation to the following column-wise representation:
b = {"animal":["dog","duck","duck","dog"],"age":[2,3,5,10]}

The only way that I am seeing to do this is not efficient - from the first entry extract the keys and then for each key iterate over the rows to extract the values.
Do you know a better way of doing this?

A: This is likely what you're describing, but I see this as a perfectly reasonable approach, making use of a collections.defaultdict to initialize values in b to empty lists:
from collections import defaultdict
b = defaultdict(list)
for animal in a:
    for key, val in animal.items():
        b[key].append(val)
print(b)

Output:
defaultdict(<class 'list'>, {'animal': ['dog', 'duck', 'duck', 'dog'], 'age': [2, '3', '5', 10]})

A: keys = a[0].keys() if len(a) > 0 else []
vals = zip(*map(lambda x: x.values(), a))
b = dict(zip(keys, vals)))


text:
Q: how to change a specifc number of items in a list in python I have a list like this:
 my_list=[False, False, True, True, False, False, True]

I want to change this list so that the first n occurrence of True remain in place and all others became False.
for example, if n=1, I want to create a new list same as this one:
my_new_list=[False, False, True, False, False, False, False]

and if n=2; this list should be created:
my_new_list=[False, False, True, True, False, False, False]

I can do this in a for loop easily, but what is the best way of doing this in Python?
Edit1
This is my code:
def f(l,n):
   c=1
   new_l=[False] * len(l)
   if n>= len(l):
       return new_l
   for i,v in enumerate(l):
      if v:
         if(c >= n):
            return new_l
         new_l[i]=True
         c +=1

   return new_l

This code goes over all the items of the list, but a portion of it. But it has 9 lines of code, is there any shorter version or a faster version?

A: With a list comp:
my_new_list = [x and (n := n - 1) >= 0 for x in my_list]

Try it online!

A: You could use accumulate (from itertools) to count how many True values you have so far and match it to the value of n:
my_list=[False, False, True, True, False, False, True]

from itertools import accumulate

n = 1
r = [isTrue and count<=n for isTrue,count in zip(my_list,accumulate(my_list))]
print(r)
[False, False, True, False, False, False, False]

n = 2
r = [isTrue and count<=n for isTrue,count in zip(my_list,accumulate(my_list))]
print(r)
[False, False, True, True, False, False, False]

using numpy
The same approach can be used more concisely with numpy:
import numpy as np

my_list=[False, False, True, True, False, False, True]

n=1
r = my_list & (np.cumsum(my_list)<=n)
print(r)
# [False False  True False False False False]

n=2
r = my_list & (np.cumsum(my_list)<=n)
print(r)
# [False False  True  True False False False]

A: def function(l,n):
new_list = []
c = 0
for i in l:
    if not i:
        new_list.append(False)
    else:
        if c < n:
            new_list.append(False)
            c+=1
        else:
            new_list.append(True)
return new_list

OR:
def function(l,n):
return [False if (not i) or (n := n-1) >= 0 else True for i in l]


text:
Q: Azure: there was a failure to launch the remote debugger I deployed a web role in windows Azure, based on the following tutorial.
http://weblogs.asp.net/scottgu/archive/2013/10/22/windows-azure-announcing-release-of-windows-azure-sdk-2-2-with-lots-of-goodies.aspx
but when I try attaching the debugger I get the following message:
"there was a failure to launch the remote debugger"
apparently this is a known issue, and the suggested solution from Microsoft is to restart the visual studio and try again, which unfortunately didn't work for me

http://msdn.microsoft.com/en-us/library/windowsazure/dn459835.aspx
Remote debugging may fail to attach to an existing Cloud Service:
After deploying a new Cloud Service the debugger may fail to attach to
an existing cloud service with the error message "There was a failure
to launch the remote debugger".  To correct this problem, restart
Visual Studio and reattach the debugger to the new deployment.

So I thought to ask here in case anybody faced the same issue and found another solution other than restarting the visual studio!
I'm using visual studio 2012, with Azure SDK 2.2

A: Make sure that you deployed a Debug build to your web role and that you have checked "Enable Remote Debugging for all roles" on the advanced tab during deployment.  Failure to do either of these could lead to the problem your seeing.

A: I was using Azure SDK 2.2, so as to use "Attach debugger", but unfortunately I needed to use SDK 2.1 as 2.2 needs some references that weren't included in 2.1, so I guess this is the problem.
Thank you all for your help

A: I tried all of the solutions above and found that none worked for me.  My problem turned out to be stale or inaccessible certificates that the VS debugger uses to connect to the service.  I discovered this was the problem by going to event viewer and found:

A fatal error occurred when attempting to access the SSL client
  credential private key. The error code returned from the cryptographic
  module is 0x8009030D. The internal error state is 10003.

I had had other problems with permissions on private keys and so I ended up deleting all of the certificates from my personal store (current user) with the "Issued To" equal to "Windows Azure Tools".  When I redeployed my service VS created new certificates and uploaded them.
Voilà -- attach remote debugger works again.

A: I got the same exception trying to remotely debug a VM in Azure, following the guide in Debugging Azure Virtual Machines.
What worked for me was to simply install the remote debugging tools matching my version of Visual Studio (VS2013 Update2).
Further I had to add a new endpoint in the Azure portal. This didn't work initially but eventually using the same public and private port number did the trick. The default port of 4018 worked.
Start the remote debugger program on the client machine in adminstrator mode and remember to set to port number, e.g. to 4018. I chose Windows authentication as well.
From within Visual Studio: Debug menu -> Attach to Process -> [yourVMName].cloudapp.net:4018 or whatever port number you chose. You should now see a list of processes on the virtual machine.

A: In case its helpful for someone else, I've just spent 3 hours on this! In the end I gave up and using 'Cloud Explorer' (in VS 2013, after installing the Azure SDK) I selected 'Disable Debugging' and noticed it cleared out port rules in the Network Security Group for the VM.
I hadn't seen it set these up (which is where I'd spent hours guessing that these were the issue and trying to figure them out from patchy MS documentation, broken links, etc).
So, I 'enabled debugging' for the VM and saw it set up security rules - something it didn't do the first time!
At a guess this is because I had initially enabled debugging for my VM soon after I installed the Azure SDK into VS. Since then I rebooted the VS server, and that may have enabled something in the SDK.
Anyway - before spending hours figuring out ports, reboot the VS server and then disable/reenable debugging in Cloud Explorer - you should see a status message (in the Azure Activity Log) saying 'Configuring networking security group debugging port' - this is the magic step that it didn't do the first time around.

A: I think you should try lunching VS in administrator mode, and see if you always have the same problem.
Else I think you should put more details about your problem.

A: This is what I did to enable debugging on an Azure VM.
At the time of this writing my current setup is as follows

*

*Windows Server 2012 R2 IIS 8.5 (Virtual Machine)

*Visual Studio 2013 Update 4

*Microsoft Azure SDK Tools 2.5

*

*Update Visual Studio to the latest Azure SDK

*go th the server window (server explorer)

*Expand the Azure node

*Expand the virtual machines node

*Right click on the VM you want to debug

*Choose "Enable Debugging" Visual Studio will begin to add a debugger extension to your virtual machine

*Once complete, Right click on the virtual machine from the virtual explorer and choose attach debugger


text:
Q: Deleting values from a variable I am a new python learner and have a question about deleting values from variables.
The first 11 data records look like this:
Type Latitude Longitude

Dog     41.9595 82.494997
Cat     41.4388 82.493585
Other   41.5238 82.482829
Bird    41.3848 82.493739
Lizard  41.3838 82.383883
Lizard  41.7238 82.293848
Other   41.7483 82.283848
Other   41.2747 82.474484
Dog     41.3838 82.393949
Cat     41.3883 82.373848
Bird    41.3828 82.383838

So, I have imported this to python using
import pandas as pd
Pet_Data = pd.read_csv('PetMap.csv',sep=',')
Pet_Data.head()

I have made an interactive dot map in bokeh using
TOOLTIPS = [("type", "@Type"),       # this accesses 'Type' column
        ("lat", "@Latitude"),    # this accesses 'Latitude' column
        ("lat", "@Longitude")]   # this accesses 'Longitude' column

p = figure(tooltips=TOOLTIPS)        # initiate your figure and add TOOLTIP

p.circle(x='Latitude',               # circles on x
     y='Longitude',                and on y
     source=Pet_Data             # points to Pet_data df
     size=40)                    # simple circle size argument

show(p)

So my question is how to delete the 'other' data records from the type variable because I don't want those to show on my map?

A: Pet_Data = pd.read_csv('PetMap.csv',sep=',')
Pet_Data = Pet_Data[Pet_Data['Type']!='Other']

A: This should work:
Pet_Data = Pet_Data[Pet_Data.Type != 'Other']


text:
Q: Grouping and searching the users in Azure B2C I want to create different groups in Azure B2C like Department 1, Department 2 and assign employees for each department. I want to then search for all the employees under each department.
I noticed that Azure B2C does not have Groups, Users and Roles. How can I structure the Azure B2C to achieve it?

A: Even though out-of-the-box AAD B2C does not expose functionality related to managing Security Groups, the following approach could be considered:

*

*use regular AAD portal blade to create groups

*assign users to groups via Azure AD B2C
Another option would be to introduce department as custom attribute of User entity:

*

*via Azure AD B2C create a custom attribute or via API: create a extensionProperty endpoint

*update user to save a department claim:

Example:
PATCH https://graph.microsoft.com/v1.0/users/{id-or-upn}
Content-type: application/json

{
  "extension_{b2c-extensions-app-id}_Department": "--department name goes here--"
}

where extension_{b2c-extensions-app-id}_Department corresponds to department custom attribute named by using the convention application (client) ID of the b2c-extensions-app without the dashes

*and finally retrieve user properties along with department: GET https://graph.microsoft.com/v1.0/users?$select=extension_{b2c-extensions-app-id}_Department


text:
Q: PivotProtocol in vapor How to make a Pivot with the same objects?
I have this tried but get an mySQL error:
final class UserParent: Model, PivotProtocol {
    var storage = Storage()

    typealias Left = User
    typealias Right = User

    static var leftIdKey: String = "user_id_parent"
    static var rightIdKey: String = "user_id_child"

    init(row: Row) throws { }

    func makeRow() throws -> Row {
        let row = Row()
        return row
    }

}

//MARK: - Preparation
extension UserParent: Preparation {
    static func prepare(_ database: Database) throws {
        try database.create(self, closure: { builder in
            builder.id()
            builder.int("user_id_parent")
            builder.int("user_id_child")
        })
    }

    static func revert(_ database: Database) throws {
        try database.delete(self)
    }
}

and then i have this on my user object
var users: Siblings<User, User, UserParent> {
    return siblings()
}

but I get this mySQL error
[MySQL Error: Unknown column 'user_parents.user_id' in 'where clause']

A: To complete tanner0101's answer:
Your model is correct, but your Siblings implementation must specify the custom keys as well.
var parentUsers: Siblings<User, User, UserParent> {
  return siblings(localIdKey: "user_id_child", foreignIdKey: "user_id_parent")
}
var childUsers: Siblings<User, User, UserParent> {
  return siblings(localIdKey: "user_id_parent", foreignIdKey: "user_id_child")
}


text:
Q: Remove the DOM element in jQuery How do I remove the one element from DOM, Kindly refer my Image 1 (Actual UI) and Image 2(DOM element which need to be deleted).
NOTE:- All element in that <td> has same class name, so I have to be careful while removing specific element
enter image description here
enter image description here

A: it will be better to provide you code but try this
Give the table or tr id for example
<table id="#multColumnListTable">.....
then in the jquery part(if you have jquery):
$('#multColumnListTable input:checked').each(function() {
    $(this).closest("div").remove();
})

good luck.


text:
Q: The right method for animation once the page is loaded? I would like to set up animations of appearance once the page loaded. The problem is that before the CSS is loaded the elements arrive suddenly, and finally, once I have all that is loaded I have my animation that starts. It's not very cool visually.
The solution that I came up with defaults opacity on the container! Not sure, The problem is that if the browser does not support animations, the user will see the site with an opacity of 0. In other words, he will not see anything.
So are there ways to do it?
PS: I tried a lot of searches on Google without ever finding the answer to my question, maybe I have not used the right terms.

A: Keeping browser compatibility in mind is very important. However, your desired result can be achieved with CSS Animations and little stress: https://caniuse.com/#feat=css-animation.
If you provide some HTML and CSS a more specific answer could be provided. But, I would recommend defining keyframes for each element you want to animate (several could use the same one if desired) and use this for a one time animation at site load. No JS necessary.


text:
Q: SCR for load bank switching? I'm building a load bank for testing high power lead acid batteries, and expect to pass up to 800 amps at 12 VDC. I could do it with contactors but would like to use an SCR with a pot and allow the current to be ramped up with the pot. Any thoughts?

A:
I could do it with contactors but would like to use an SCR with a pot
  and allow the current to be ramped up with the pot. Any thoughts?

It's a foolish idea for at least two reasons: -

*

*An SCR will latch once conducting and stay latched hence to disconnect the "load bank" from the battery you will need a contactor. Of course it makes sense to just use the contactor for full functionality.

*Current won't ramp up with either a contactor or an SCR with or without a pot. If you require a variable load impedance then use something else that can be controlled on/off in a PWM manner. I'm thinking banks of MOSFETs and an inductor here.

There will be kilowatts of heat to get rid of so design your load bank rig carefully.

A: SCRs are not appropriate switches for DC because they are difficult to turn off. There are commutation circuits that you could build, but it would be a lot easier to use an IGBT or MOSFET.
To control current, you would need to use pulse width modulation (PWM). With PWM, the current drawn from the batteries would be pulses, not steady DC. You would need to determine if that is appropriate for testing the batteries. The current could be smoothed with filtering, but that adds to the equipment required.
The use of the plural "contactors" implies that you are thinking of a bank of small resistors rather than one large resistor. You could easily use a potentiometer to sequence the connection and disconnection of resistors. You can use contactors, solid state relays, MOSFETs or IGBTs.
If you are designing something for industrial use, you should consider a system that would return power to the AC power system. That is much more complex, but it would reduce operating cost and save money in a situation where the testing is going on for an extended period of time.


text:
Q: With the Arcgis SDK, Is it possible to store a tile package (.tpk) or a compact cache on the sdcard in a Windows Store App ? I can successfully load a .tkp package in a Windows Store App using the Arcgis SDK when the file is stored in the AppData Folder or the Instal Folder off the App.
Like this :
        StorageFile sf = await ApplicationData.Current.LocalFolder.GetFileAsync("Test.tpk");

        Layer bkgLayer = new ArcGISLocalTiledLayer(sf);

        Map.Layers.Add(bkgLayer);

note : ApplicationData.Current.LocalFolder is the standard local folder :
C:\Users\username\AppData\Local\Packages\app_guid\LocalState
=> The base map is successfully displayed.
But, I have to store the data to the sd card or another folder like My document
So I use :
       StorageFile sf= await Windows.Storage.StorageFile.GetFileFromPathAsync(@"C:\Users\<user>\Documents\Test.tpk");

        Layer bkgLayer = new ArcGISLocalTiledLayer(sf);

        Map.Layers.Add(bkgLayer);

=> The base map is not displayed
In the application manifest, I have access to the documents folder and to .tpk files.  I can successfully read and write in this folder using a Stream.
I notice that in the SDK documentation we can read :

ArcGISLocalTiledLayer(StorageItem) : The storage file must be located in a location accessible by the app, ie only local data and app
  storage. If the file resides outside these folders, it must be copied
  to the local data store first.

So, is it a limitation of the Argis SDK or I made something wrong ?
Is there another way to store a base map outside the AppData folder ?
(The size of the base map is 40Go, and I have to share it between multiple user account)
Thanks a lot for any help :)


text:
Q: why I can't iterate through anonymous type ControllerAction:
{

    AddLeadSourcesModel model = new AddLeadSourcesModel();
    List<LeadSourceModel> models = LeadSourceModel.Get()
                                                  .Where(c => c.Active == true)
                                                  .ToList();
    var A = LeadSourceModel.GetSubLeadSources(leadSourceID);
    model.LeadSources = new SelectList(
        LeadSourceModel.Get().Where(c => c.Active == true),
        "LeadSourceID",
        "Name",
        models.Where(c => c.LeadSourceID == leadSourceID).FirstOrDefault().LeadSourceID
    );

    model.SubLeadSources = new SelectList(A, "LeadSourceID", "Name");

    var flattenedData = model.SubLeadSources.SelectMany(subLead => model.LeadSources, (n, a) => new { n,a });

    return PartialView("_AddLeadSources", flattenedData.ToList());

}

View:

        Lead Source
        Sub Lead Source
        Action

    @foreach(var item in Model)
    {

        @item.a
        @item.n
        Remove

    }

My problem is when I get to the partial it says it expects a different type but I've not told it a type. And I technically don't know the type coz it's annoymous
How do I get this to work?

A: Somewhere you've defined class PartialView with a constructor that takes two parameters.
Alas you forgot to give us the signature of this constructor, but I think that the first one is a string, the second one is list / sequence / collection of some defined type. I expect something like:
class PartialView
{
     public PartialView(string txt, List<MyType> items) {...}
}

If you want to use this constructor you'll have to provide a List<MyType>. To do this, use Select before you create FlattenedData:
List<MyType> flattenedData = model.SubLeadSources
    .SelectMany(subLead => model.LeadSources, (n, a) => new { n,a })
    .Select(item => new MyType()
    {
        // fill the MyType properties, something like:
        N= item.n
        A = item.a,
    };

Now you can use the constructor.
PartialView partialView = new PartialView("_AddLeadSources", flattenedData);

Extension Function
If you'll convert quite often some anonymous type to a sequence of MyType and a PartialView, consider creating an extension function that will take as input a sequence of any (anonymous) type, a string, and two lambda expressions that will tell you which values of the anonymous types are the A and N.
See extension methods demystified
We already know that MyType has properties like A and an N, where you'd like to put your anonymous a and n in. Let's assume they have non-generic type Atype and Ntype, for instance int, or DateTime, or MyElaborateClass, like this:
class MyType
{
     public Atype A {get; set;}
     public Btype B {get; set;}
}

Extension class for PartialView:
static class PartialViewExtension
{
    // Creates one PartialView object from a sequence of MyType objects and a text
    public static PartialView ToPartialView(this IEnumerable<MyType> source, string text)
    {
         return  new PartialView(text, source.ToList());
    }

    // uses the source + predicates to create a sequence of MyType objects
    public static IEnumerable<MyType> ToMyType<TSource>(this IEnumerable<TSource> source,
        Func<TSource, Atype> aSelector,
        Func<TSource, Ntype> nSelector)
    {
         return source.Select(sourceItem => new MyType()
         {
              A = aSelector(sourceItem),
              B = bSelector(sourceItem),
         });
    }
}

Usage would be like:
var flattenedData = model.SubLeadSources
    .SelectMany(subLead => model.LeadSources, (n, a) => new { n,a });

PartialView partialView = flattenedData
      .ToMyType(flattenedInput => flattenedInput.n,
                flattendInput => flattenedInput.a)
      .ToPartialView("_AddLeadSources");

Now that we are already creating extension functions, lets combine these two into one, that will call the other two:
public static PartialView ToPartialView<TSource>(this IEnumerable<TSource> source,
    string text,
    Func<TSource, Atype> aSelector,
    Func<TSource, Ntype> nSelector)
{
    return source.ToMyType(aSelector, bSelector).ToPartialView(text);
}

Usage:
var flattenedData = model.SubLeadSources
    .SelectMany(subLead => model.LeadSources, (n, a) => new { n,a });

PartialView = flattenedData.ToPartialView("_AddLeadSources",
    flattenedInput => flattenedInput.a,
    flattenedInput => flattenedInput.n);


text:
Q: Trivial norm and topology It's a well known fact that every norm in finite dimensional vector spaces are equivalent. So these norms have to induce the same topology, right? My question is If I take, for example, $\mathbb{R}^n$ as a $\mathbb{R}$-vector space and put the trivial metric $d: \mathbb{R}^n \times \mathbb{R}^n \rightarrow \mathbb{R}$ defined by:
$$d(x,y) =
\left\{
 \begin{array}{ll}
  0  & \mbox{if } x=y \\
  1 & \mbox { otherwise}
 \end{array}
\right.$$
The topology induced by it is the discrete one, but if you take the Euclidean norm, for example, the topology induced is not the discrete! What's wrong with my reasoning?

A: Your metric is not induced by a norm. A norm satisfies $\|cx\| = \mid c\mid \|x\|$ and $\|x+y\|\leq \|x\|+\|y\|$. Then the associated distance is $d(x,y)=\|x-y\|$.
For your distance, if it was associated to a norm, you would have had  for $x\neq y$ $d(2x,2y)=1=2 \|x-y\|=2d(x,y)=2$. Impossible.


text:
Q: python reportlab categoryAxis label placement I've written a simple function that generates a simple bar chart from a single data series as shown below. The input data can be positive or negative, which when negative results in the category axis labels being covered by the bar (charts 2 and 3 in the code below).
I have searched the reportlab graphics reference, and on page 202 a bar chart with labels placed "low" is shown. However the command used to do this: bc.categoryAxis.labels.dy = -60, appears to be arbitrarily chosen. How would one know the negative offset if the input data is not known? Is there a way to identify the x axis location on the drawing and then determine the label offset from that location, or any other work-around when the input data is unknown?
Thanks for any guidance.
from reportlab.graphics.shapes import Drawing
from reportlab.graphics.charts.barcharts import VerticalBarChart
from reportlab.graphics.charts.textlabels import Label
from reportlab.lib import colors
from reportlab.platypus import SimpleDocTemplate
from reportlab.lib.units import inch
from reportlab.lib.pagesizes import letter

def vbar_one_series(data, xlabels, chart_title, xaxis_text):
    drawing = Drawing(180, 180)

    bc = VerticalBarChart()
    bc.x = 25
    bc.y = 25
    bc.height = 125
    bc.width = 150
    bc.data = [data]
    bc.valueAxis.valueMin = int(min(min(bc.data[0]), 0))
    bc.valueAxis.valueMax = int(max(bc.data[0]) + 2)
    bc.valueAxis.labels.fontName = 'Helvetica'
    bc.valueAxis.labels.fontSize = 7
    bc.valueAxis.labelTextFormat = '%0.1f'
    bc.bars[0].fillColor = colors.HexColor('#000035')
    bc.categoryAxis.labels.boxAnchor = 'c'
    bc.categoryAxis.labels.fontName = 'Helvetica'
    bc.categoryAxis.labels.fontSize = 7
    bc.categoryAxis.tickDown = 0
    bc.categoryAxis.labels.dx = 0
    bc.categoryAxis.labels.dy = -7
    bc.categoryAxis.labels.angle = 0

    bc.categoryAxis.categoryNames = xlabels

    bc.barLabels.nudge = 10
    bc.barLabelFormat = '%0.1f'
    bc.barLabels.dx = 0
    bc.barLabels.dy = 0
    bc.barLabels.fontName = 'Helvetica'
    bc.barLabels.fontSize = 7

    xlabel = Label()
    xlabel.setText(xaxis_text)
    xlabel.fontSize = 7
    xlabel.fontName = 'Helvetica'
    xlabel.dx = 90
    xlabel.dy = 5

    title = Label()
    title.setText(chart_title)
    title.fontSize = 7
    title.fontName = 'Helvetica'
    title.dx = 90
    title.dy = 175

    drawing.add(bc)
    drawing.add(xlabel)
    drawing.add(title)

    return drawing

if __name__ == '__main__':

    bar1 = vbar_one_series([1.0, 2.3, 1.8], ['A', 'B', 'C'],
                                 'Title 1', '')

    bar2 = vbar_one_series([-25, 50, 10], ['A', 'B', 'C'],
                           'Title 2', '')

    bar3 = vbar_one_series([0, -1.1, -0.4], ['A', 'B', 'C'],
                           'Title 3', '')

    doc = SimpleDocTemplate('H:/Desktop/report.pdf', pagesize=letter,
                            topMargin=0.5 * inch, bottomMargin=0.5 * inch)
    Catalog = []
    Catalog.append(bar1)
    Catalog.append(bar2)
    Catalog.append(bar3)
    doc.build(Catalog)

report.pdf

A: After some additional research, I found that this problem can be solved using the .categoryAxis.labelAxisMode = 'low' property.


text:
Q: application taking time while launching first time on iOS 6.X.X application launch is taking 5-6 seconds on iOS 6.X.X versions in iPads. This works well on iOS 5.X. The default.png file remains a little longer on the screen with iOS 6.X.X.What could be wrong with loading.
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
UIInterfaceOrientation orientation=[[UIApplication sharedApplication] statusBarOrientation];
if (orientation==UIInterfaceOrientationLandscapeLeft || orientation==UIInterfaceOrientationLandscapeRight)
{                                                         self.viewController=[[EBHomeViewController alloc] initWithNibName:@"EBHomeViewController-LA" bundle:nil] ;
}
else if(orientation==UIInterfaceOrientationPortrait || orientation==UIInterfaceOrientationPortraitUpsideDown)
{
    self.viewController=[[EBHomeViewController alloc] initWithNibName:@"EBHomeViewController-PT" bundle:nil] ;
}

navController = [[UINavigationController alloc] initWithRootViewController:self.viewController];
self.window.rootViewController = navController;
[self.window makeKeyAndVisible];

there is no heavy code in applicationDidFinishLaunching.It takes time when we install the app & open it for first time /restarting iPad & launching application.


text:
Q: Windows Phone Power Tool (Pre WP-8) Fails To Load Folder Content My environment : Win7, VS2010 Pro, Windows Phone Emulator 10.1.40219.390, HTC T8788, Windows Phone Power Tool v1.6.
I need to Get multiple files (they are <3kb json files) to my dev box from a folder on my emulator/device. I had been happily doing this with Isolated Explorer command tool and/or Windows Phone Power Tool till the number of files was very limited. As soon as the number of files increased in the folder both the tools mentioned above failed to open the folder from device. The application on device and emulator is handling large number of files as expected (tested with 4000+ files). Following are my findings regarding the issue with WPPT (and IS explorer): if a folder contains more than 1024 files, WPPT does not load the folder. The physical size of individual file in the folder does not matter. The issue can be reproduced with same effect on emulator and device. On further investigation I found that WPPT breaks at a call to Microsoft.SmartDevice.Connectivity.RemoteIsolatedStorageFile.GetDirectoryListing() which just says - "Unspecified error" with no details. It seems the said API method is now obsolete and i could not find any substantial information on MSDN about it or the issue
Did somebody else also encounter this problem? Is there some way I can pull large number of files (4000+) to my dev box from IS folder on device/emulator (please note, i can only work with the environment mentioned above, so Win8 or WP8 emulator are out of question)?
Regards.


text:
Q: MySQL Join with min and max date I have two tables
profile
--------
id
name

Profile_dates
--------------
id
profile_id
entry_date

The tables have 1 to many relationships
I want to get min and max entry_date for each profile like
id
name
profile_dates.first_date
profile_dates.last_date

the profiles_dates table can have thousands of entries per profile. The simple join was very expensive for me. Is there another option?

A: simply join two tables and group by id:
select p.id , name , min(pd.entry_date) first_date, max(pd.entry_date) last_date
from profiles p
left join Profile_dates pd
 on p.id = pd.id
group by p.id , name

A: Sometimes subquery performance is far better than left join. Please try this simple solution.
id, name, (select min(entry_date) from  Profile_dates pd where pd.profile_id=p.id) first_date,
(select max(entry_date) from  Profile_dates pd where pd.profile_id=p.id) last_date
from profile p


text:
Q: Allow user interaction outside a non rectangular UIView content On a UIView that shows a circle image (needs to stay interactive), how would you prevent the area out side of the circle from receiving any user interactions, so the other ui under that view will still be active?
i tried masking the UIView with CGPath but that didn't help.
any ideas?

A: Since a touch event bubble down in the view hierarchy, as a UIView, you can check if a touch event is relevant to you, if it is not just return NO and that event will travel down to the next UIView in the hierarchy
- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event
{
    for (UIView * view in [self subviews]) {
        if ([view pointInside:[self convertPoint:point toView:view] withEvent:event]) {
            return YES;
        }
    }
    return NO;
}

A: Don't put any elements that receive UI events outside the circle.
If this is unavoidable, then just disable all of the elements outside of the circle for as long as you need.


text:
Q: Не меняется http на https в вордпресс В админке вордпресса указываю адрес wordpress и адрес сайта
https://site.ru

В админку нельзя зайти так как пишет слишком много редиректов. Сайт работает, но все стили с http, т.е. get_template_directory_uri() выдает http://site.ru  вместо https://site.ru.
Выключаю все плагины, ставлю тему по умолчанию, обновляю вордпресс, удаляю .htaccess ничего не меняется.
В файле wp-config.php пишу:
define('WP_HOME','https://site.ru');
define('WP_SITEURL','https://site.ru');

Изменений нет.
Вывожу на сайте для проверки:
С WP_HOME проблем нет, выводится "https://site.ru"
А вот get_site_url выводит: "http://site.ru" без "s".
Меняю
define('WP_SITEURL','https://sItE.rU');

И get_site_url выводит: "http://sItE.rU" с горбами, но всё равно без "https".
В function.php прописываю
update_option('siteurl','https://site.ru');

не помогает.
Почему режется https ?

A: Прописал в function.php
$_SERVER['HTTPS'] = 'on';

Примерный смысл, что функции резали https, потому что там использовалась функция is_ssl(), которая говорит, что нет ssl. Это из-за особенностей хостинга.


text:
Q: How to create a drop down by fetchng the elements from other table(in rails) Say I have created to two scaffold service and home..I want a list of  services in a drop down in home controller.As I'm new to rails ..please help me

A: "drop down in home controller" is not a clear statement, but if you're saying you want to be able to select a service in a view, you can define a form and include a select_tag
select_tag "service_id", options_from_collection_for_select(Service.all, "id", "name")

This assumes a service has a column name which is the text you want to appear on the drop-down.


text:
Q: Listen to EditText OnFocusChangeListener Globally I am interested in building a system application for Android which can globally listen to all EditText on focus change event, somehow I am gonna provide certain service when the user gain focus on any EditText.
I have successfully downloaded AOSP(Android Open Source Project) and I want to start writing my app as system application.
My question is can I do that as a system application "listening to global events" ?
if possible what are they areas I need to dig up to learn more about gaining such a privilege.
Any suggestion or help would be greatly appreciated.

A: I suggest you start by looking at View.java class which basically has the basic building block for user interface component.
../frameworks/base/core/java/android/view/View.java

and lookup the method onFocusChanged if you are only interested in EditText add the following line
 if (this instanceof EditText) {
      Toast.makeText(getContext(), "focus gained!", Toast.LENGTH_SHORT).show();
 }

build again and you will see toast notification everytime you gain focus to any EditText around the OS


text:
Q: Audiokit drum synthesis I would like to make drum sounds using audiokit , the obvious thing would be to use samples, the less obvious approach would be to synthesise from base waveforms/white noise e.t.c
Two questions:
1: Has anyone got/come across any tutorials for drum synthesis on audiokit?
2: While Im asking, are there any good articles about the legalities of sound files like drum samples, for example can I generate my own sounds on the like of reason or abelton and use those in an application?

A: In AudioKit there's an example of synthesizing kicks and snares: https://github.com/AudioKit/AudioKit/blob/2c1049689a473b2743e97a8c0bd63d03ab32c46f/Sources/AudioKit/Nodes/Generators/Physical%20Models/DrumSynths.swift
You may find this interesting as well: https://audiokitpro.com/how-to-make-synth-drums/


text:
Q: Backbone doesn't update the template after a second render call I have a Backbone view and I'm using Handlebars to create template for the render method.
In my view I have a variable:
model  = [
        {key: '1', value: 'a'},
        {key: '2', value: 'b'},
        {key: '3', value: 'c'},
        {key: '4', value: 'd'}
       ]

I display several inputs and have the following events which listen:
'change input' : 'onInputChange'
$('.my-class').on 'keydown', (event) => @onKeydown(event)

So this is working fine. When the change event is fired I have some logic which updates the model according to the new input's value. And here is where the problem comes.
Both events are calling render() and I can verify that the last call i with the updated value, however if I change the input value and trigger the keydown event I don't see the change, if I trigger it again, then I get, even though console.log(model) shows that the model is already updated.
My render function looks like this:
render: ->
  @$el.html @template(model)

However if I wrap this in document.ready :
render: ->
  $(document).ready(() =>
    @$el.html @template(model)
  )
Then my template is updating properly.
My guess is that the fact that the change event can be triggered onkeydown so both are executed pretty much at the same time messes up with the render() execution, however I've tried to put a 1 second delay on the change event in order to be sure that the first call to render() has finished before I make the second call. Alas this didn't change the output I am still NOT getting my template updated. Only wrapping it in document.ready seems to solve the issue but I have no idea why thus I'm not sure this is the actual solution to the prbolem.

A: You seem to be using a non delegated jQuery event listener,
$('.my-class').on 'keydown', (event) => @onKeydown(event).
This won't work until the view/dom is rendered and matching elements are available(delegated events created by backbone will work even if view was in memory at the time of binding).
It'll also stop working once the view is re-rendered with new elements, unless re-binding is done.
^ There is a reason backbone provides easy way to use delegated event listeners (events hash). Using it should solve the problem


text:
Q: vue cli global body style not included in build I added this css rule

to my App.vue file within the  tag (not scoped ;-); as learned in vue mastery courses. Which BTW are a great help!
This approach also is proposed by Babacadabra in a related post.
Everything builds fine, and the locally defined (scoped) styles of a component can be found in the dist/css folder.
But my global  style declaration for the background-color disappeared. As result the website layout is different than the one I tested locally (using 'vue serve'):
The background color is not applied.
What am I making wrong?
I helped myself by adding the background-color declaration directly to my index file, but that should be a patch only. I'm looking for a final solution, so the complete workflow works as expected and local and remote versions behave the same.
UPDATE (more code):
As requested here more details, i.e. the complete App.vue. I hope that is sufficient, since to my (very basic ;.-) understanding of vue the global style declarations go into this Module.
<template>

    <HelloWorld msg="Welcome to VservU GmbH Munich"/>

</template>

UPDATE2:
Since I could not reproduce that behavior in a new project, I guess I simply missed to clear the cache!


text:
Q: NPN vs PNP current limiter So I'm trying to design two mirroring current limiters for a +-15 volt power supplies.
I don't understand why these two circuits don't behave more like each other.

The PNP circuit has +15 on the top and ground on the bottom and
The NPN has ground on top and -15 at the bottom.
The npn limits at around 600mA which is what we expect ,but I'm not sure why the PNP is 450mA.
I don't understand why the Vbe on the PNP is only 0.46 V and not around 0.65.
Any comments are much appreciated.

A: Looking at the datasheet, we can get the current gain for both PNP and NPN:

It seems that the NPN variant gives sightly higher current gain than the PNP variant. There are more parameters that differ, probably the VBE, etc. which is a reason why both configurations won't give same results.

A: 1Ω Resistor Sense2 is passing 455mA so must be dropping 0.455V, and Q6 VBE must also be 0.455V. This is much lower than expected (should be ~0.65V) so I suspect the D45H11G model is wrong.
To confirm, I measured the Base-Emitter voltage of several D45H11 transistors drawing ~60mA with 0.9V from Collector to Emitter. All 3 samples had a VBE of 0.655V.

A: This current limiter is very similar to a SCR structure so generally to avoid oscillations with the load it is employed with an emitter resistor on both transistors so the gain will be lower. Probably the simulator computes the base current that flows thru the opposite transistor so an unpredictable working point is computed. Try with a 10 to 100 R in series with emitter of the Q4 or Q6 and probably the results will be more similar.

A: I simulated your PNP circuit with LTSpice, using the standard model from LTSpice for the D45H11. I got similar results to you, with a current of 452mA through the load.
On Semi have a number of different spice models for the D45H11. I used this one for the MJD45H11. You can either change your transistors to MJD45H11's or change the model statement to D45H11. In LTSpice I simply pasted the .model statement onto the schematic.
Using the MJD45H11 model I get a current of 712mA through the load.
The conclusion has to be that the standard model for the D45H11 is wrong.


text: Q: Magento: I want my bundled product report It includes the product name and quantity as well as it will display the report on corresponding day how much product ordered. Actually i am selling food product daywise weekly bundled product. Please help me to get custom report in magento i am new here.


text:
Q: How does learning assembly aid in programming? I have been programming in higher level languages (Python, C#, VBA, VB.NET) for around 10 years and I have completely zero understanding on what's going on, "under the hood."
I am wondering what are the benefits of learning assembly, and how will it aid me as a programmer? Can you please provide me with a resource that will show me exactly the connection between what I write in higher level code to what happens in assembly?

A: Since you didn't mention C or C++ in the languages you know list. I would STRONGLY recommend learning them well before even thinking about assembly. C or C++ will give all the basic concepts that are totally transparent in managed languages and you will understand most of the concepts mentioned in this page with one of the most important languages that you could use in real world projects. It is a real added value to your programming skills. Please, be aware that assembly is used in very specific areas and it is not nearly as useful as C or C++.
I would even go further to say that you should not dive to assembly before understanding how unmanaged languages work. It is almost a mandatory reading.
You should learn assembly if you want to go even further down. You want to know how exactly each and every construct of the language is created. It is informative but it is a whole lot different level complexity.

A: If you know a language well, you should have at least basic knowledge of the technology one level of abstraction lower.
Why? When things go wrong, knowledge of the underlying mechanics makes it far easier to debug strange problems, and naturally write more efficient code
Using Python(/CPython) as an example, if you start getting weird crashes or poor performance, knowledge of how to debug C code can be very useful, same with is knowledge of it's ref-counting memory management method. This would also help you know when/if to write something as a C extension, and so on...
To answer your question in this case, knowledge of assembly really wouldn't help an experienced Python developer (it's too many steps down in abstraction - anything done in Python would result in many many assembly instructions)
..but, if you are experienced with C, then knowing "the next level down" (assembly) would indeed be useful.
Similarly, if you are using CoffeScript then it's (very) useful to know Javascript. If you are using Clojure, knowledge of Java/JVM is useful.
This idea also works outside of programming languages - if you are using Assembly, it's a good idea to be familiar with how the underlying hardware functions. If you are a web-designer, it's a good idea to know how the web-application is implemented. If you are a car mechanic, it's a good idea to have some knowledge of some physics

A: It will give you a better understanding of what is "happening under the hood" and how pointers work and the meaning of register variables and architecture (memory allocation and management, parameter passing (by value/by reference), etc) in general.
For a quick peek with C how's this?
#include <stdio.h>

main()
{
  puts("Hello World.");
  return(0);
}

compile with gcc -S so.c and take a look at the assembly output in so.s:
 $ cat so.s

    .file   "so.c"
    .section    .rodata
.LC0:
    .string "Hello World."
    .text
.globl main
    .type   main, @function
main:
    pushl   %ebp
    movl    %esp, %ebp
    andl    $-16, %esp
    subl    $16, %esp
    movl    $.LC0, (%esp)
    call    puts
    movl    $0, %eax
    leave
    ret
    .size   main, .-main
    .ident  "GCC: (Ubuntu 4.4.3-4ubuntu5.1) 4.4.3"
    .section    .note.GNU-stack,"",@progbits

A: I think the answer you seek is here: http://www.codeproject.com/Articles/89460/Why-Learn-Assembly-Language
A quote from the article:

Though it's true, you probably won't find yourself writing your next customer's app in assembly, there is still much to gain from learning assembly. Today, assembly language is used primarily for direct hardware manipulation, access to specialized processor instructions, or to address critical performance issues. Typical uses are device drivers, low-level embedded systems, and real-time systems.
The fact of the matter is, the more complex high level languages become, and the more ADT (abstract data types) that are written, the more overhead is incurred to support these options. In the instances of .NET, perhaps bloated MSIL. Imagine if you knew MSIL. This is where assembly language shines.
Assembly language is as close to the processor as you can get as a programmer so a well designed algorithm is blazing -- assembly is great for speed optimization. It's all about performance and efficiency. Assembly language gives you complete control over the system's resources. Much like an assembly line, you write code to push single values into registers, deal with memory addresses directly to retrieve values or pointers.
To write in assembly is to understand exactly how the processor and memory work together to "make things happen". Be warned, assembly language is cryptic, and the applications source code size is much much larger than that of a high-level language. But make no mistake about it, if you are willing to put in the time and the effort to master assembly, you will get better, and you will become a stand out in the field.

Additionally, I'd recommend this book because it has a simplified version of computer architecture:
Introduction to Computing Systems: From Bits and Gates to C and Beyond, 2/e
Yale N. Patt, University of Texas at Austin
Sanjay J. Patel, University of Illinois at Urbana/Champaign

A: Write a small c program, and disassemble the output.  That's all.  However, be prepared for a greater or lesser degree of "housekeeping" code that is added for the benefit of the Operating System.
Assembly helps you understand what's going on under the hood because it deals directly with memory, processor registers and the like.
If you really want to go bare-metal without all of the complexity of an operating system complicating things, try programming an Arduino in assembly language.

A: There is no definitive answer, since programmers are not all of a type.  Do you NEED to know what lurks underneath?  If so, then learn it.  do you just merely want to learn it, out of curiosity?  If so, then learn it.  If it will have no practical benefit to you, then why bother?  Does one need a mechanic's level of knowledge just to drive a car?  Does a mechanic need an engineer's level of knowledge, just to work on a car?  This is a serious analogy.  A mechanic can be a very good, productive mechanic without diving to engineer depth understand of the vehicles he maintains.  Same for music.  Do you really to plumb the complexities of melody, harmony and rhythm to be a good singer or player?  No.  Some exceptionally talented musicians can't read a lick of sheet music, let alone tell you the difference between Dorian and Lydian modes.  If you want to, fine, but no, you don't need to.  If you are a web developer, assembly has no practical use that I can think of.  If you are in embedded systems or something really specially, then it might be necessary, but if it were, you'd know it.
Here's Joel's take on these value of leaning a non-high level language:
http://www.joelonsoftware.com/articles/ThePerilsofJavaSchools.html

A: In my humble opinion, it doesn't help much.
I used to know x86 assembly very well.  It helped a little when assembly came up in my courses, it came up once during an interview, and it helped me prove that a compiler (Metrowerks) was generating bad code.  It's fascinating how the computer actually works, and I feel intellectually richer for having learned it.  It was also very fun to play with at the time.
However, today's compilers are better at generating assembly than almost anyone on almost any piece of code.  Unless you're writing a compiler or checking that your compiler is doing the right thing, you are probably wasting your time by learning it.
I admit that many questions that C++ programmers still usefully ask are informed by knowing assembly.  For example: should I use stack or heap variables? should I pass by value or by const reference?  In almost all cases, however, I think that these choices should be made based on code readability rather than computational time savings.  (E.g., use stack variables whenever you want to limit a variable to a scope.)
My humble suggestion is to focus on skills that really matter: software design, algorithm analysis, and problem solving.  With experience developing big projects, your intuition will improve, which increases your value much more than knowing assembly (in my opinion).

A: You should be familiar with one level 'deeper' in the system that you are working at.  Skipping too far down in one go isn't bad, but may not be as helpful as one would desire.
A programmer in a high level language should learn a lower level language (C is an excellent option).  You don't need to go all the way to assembly to have an appreciation of what goes on under the covers when you tell the computer to instantiate an object, or create a hash table, or a set - but you should be able to code them.
For a java programmer, learning some C would help you with memory management, passing arguments.  Writing some of the extensive java library in C would go a  ways to understanding when to use what implementation of Set (do you want a hash? or tree?).  Dealing with char* in a threaded environment will assist in understanding why String is immutable.
Taken to the next level... A C programmer should have some familiarity with assembly, and assembly types (oft found in embedded systems shops) would likely do well with understanding things at the level of gates.  Those who work with gates should know some quantum physics.  And those quantum physicists, well, they are still trying to figure out what the next abstraction is.

A: Actually, what would probably be best for you would be a class that doesn't (to my knowledge) exist anywhere:  It would be a class that combines a brief overview of machine/assembler language and storage addressing concepts with a tour through compiler construction, code generation, and runtime environments.
The problem is that with a high-level, far-away-from-the-hardware language like C# or Python you don't really appreciate the fact that every move you make turns into hundreds if not thousands of machine instructions, and you don't tend to comprehend how a few lines of a high-level language can cause vast amounts of storage to be accessed and modified.  It's not so much that you need to know precisely what is going on "beneath the covers", but you need to have an appreciation for the scope of what's happening, and a general conception of the types of things that occur.

A: Because you'll understand how it really works.

*

*You'll understand that function calls are not for free and why the call stack can overflow (e.g., in recursive functions). You'll understand how arguments are passed to function parameters and the ways in which it can be done (copying memory, pointing to memory).

*You'll understand that memory is not for free and how valuable automatic memory management is. Memory is not something that you "just have", in reality it needs to be managed, taken care of and most importantly, not forgotten (because you need to free it yourself).

*You'll understand how control flow works at a most fundamental level.

*You'll appreciate the constructs in higher-level programming languages more.

What it boils down to is that all the things we write in C# or Python need to be translated into a sequence of basic actions that a computer can execute. It's easy to think of a computer in terms of classes, generics and list comprehensions but these only exist in our high-level programming languages.
We can think of language constructs that look really nice but that don't translate very well to a low-level way of doing things. By knowing how it really works, you'll understand better why things work the way they do.

A: My answer to this question has evolved relatively recently. The existing answers cover what I would have said in the past. Actually, this is still covered by the top answer - the "appreciate the constructs in higher-level programming" point, but it's a special-case that I think is worth mentioning...
According to this Jeff Atwood blog post, which references a study, understanding assignment is a key issue in understanding programming. Learner programmers either understand that the notation just represents steps that the computer follows, and reasons by the steps, or else gets perpetually confused by misleading analogies to mathematical equations etc.
Well, if you understand the following from 6502 assembler...
LDA variable
CLC
ADC #1
STA variable

That really is just the steps. Then when you learn to translate that to an assignment statement...
variable = variable + 1;

You don't need an misleading analogy to a mathematical equation - you already have a correct mental model to map it to.
EDIT - of course if the explanation you get of LDA variable is basically ACCUMULATOR = variable, which is exactly what you get from some tutorials and references, you end up back where you started and it's no help at all.
I learned 6502 assembler as my second language, the first being Commodore Basic, and I hadn't really learned much of that at the time - partly because there was so little to learn, but also because assembler just seemed so much more interesting back then. Partly the times, partly because I was a 14 year old geek.
I don't recommend doing what I did, but I wonder if studying a few very simple examples in a very simple assembler language might be a worthwhile preliminary to learning higher-level languages.

A: Unless you are a compiler writer, or need something highly optimized (like data processing algorithm), learning assembly coding will provide you no benefits.
Writing and maintaining code written in assembly is very difficult, therefore even if you know assembler language very well, you shouldn't use it, unless there are no other ways.
The "Optimizing for SSE: A Case Study" article shows what is possible to do if you go to assembly. The author managed to optimize the algorithm from 100 cycles/vector to 17 cycles/vector.

A: Writing in assembly would not give you magic increase of speed as due to amount of details (register allocation etc.) you will probably write the most trivial algorithm ever.
Additionally with modern (read - designed after 70-80's) processors assembly will not give you sufficient number of details to know what is going on (that is - on most processors). Modern PU (CPUs and GPUs) are quite complex as far as scheduling instructions go. Knowing basics of assembly (or pseudoassembly) will allow to understand computer architecture books/courses which would provide further knowledge (caches, out-of-order execution, MMU etc.). Usually you don't need to know complex ISA to understand them (MIPS 5 is quite popular IIRC).
Why understand processor? It might give you much more understanding what's going on. Let's say you write matrix multiplication in naive way:
for i from 0 to N
    for j from 0 to N
        for k from 0 to N
            A[i][j] += B[i][k] + C[k][j]

It may be 'good enough' for your purpose (if it is 4x4 matrix it might be compiled to vector instructions anyway). However there are quite important programs when you compile massive arrays - how to optimize them? If you write the code in assembly you might have a few % of improvement (unless you would do as most people do - also in naive way, underutilizing registers, loading/storing to memory constantly and in effect having slower program then in HL language).
However you can reverse tho lines and magically gain performance (why? I leave it as 'homework') - IIRC depending on various factors for large matrices it can be even 10x.
for i from 0 to N
    for k from 0 to N
        for j from 0 to N
            A[i][j] += B[i][k] + C[k][j]

That said - there are working on compilers being able to do it (graphite for gcc and Polly for anything using LLVM). They are even capable of transforming it into (sorry - I'm writing blocking from memory):
for i from 0 to N
    for K from 0 to N/n
        for J from 0 to N/n
            for kk from 0 to n
                for jj from 0 to n
                    k = K*n + kk
                    j = J*n + jj
                    A[i][j] += B[i][k] + C[k][j]

To summarise - knowing basics of an assembly allows you to dig into various 'details' from processor design which would allow you to write faster programs. It might be good to know differences between RISC/CISC or VLIW/vector processor/SIMD/... architectures. However I would not start with x86 as they tend to be quite complicated (possibly ARM too) - knowing what is a register etc. is IMHO sufficient for start.

A: Well, the answer is that just simply because the language you are using must be interpreted or compiled into assembler at the end. No matter the language or the machine.
The design of languages derives from the way the CPU works. More on low level programs, less on high level programs.
I will end by saying that it is not only that you need to know little assembler but CPU architecture, which you learn by learning assembler.
Some examples: There are many java programmers that do not understand why this does not work, and even less than know what happens when you run it.
String a = "X";
String b = "X";
if(a==b)
    return true;

If you knew a little assembler you would always know that it is not the same the content of a memory location vs the number in the pointer variable that "points" to that location.
Even worse, even in published books you will read something like in JAVA primitives are passed by value and objects by reference, which is completely incorrect. All arguments in Java are passed by value, and Java can NOT pass objects to functions, only pointers, which are passed by value.
If you now assembler its obvious what's going on, if not it is so complicated to explain that most authors just give you a pious lie.
Of course, the ramifications of these are subtle but can get you in real trouble later on. If you know assembler it's a non-issue, if no, you are in for a long long night of debugging.

A: I would recommend learning algorithms: sorting, linked lists, binary trees, hashing, etc.
Also learn lisp see Structure and Interpretation of Computer Programs groups.csail.mit.edu/mac/classes/6.001/abelson-sussman-lectures this video course will teach you everything you need to know, including algorithms (how to do everything based on a few primitive commands, one lisp primitive and some assembler provocatives).
Finally if you must learn assembler learn an easy one like ARM ( also it is used in about 4 times more devices than x86).

A: In short I think the answer is because you can do more if you learn assembly.  Learning assembly grants access to the realms of embedded device programming, security penetration and circumvention, reverse engineering and system programming which are very hard to work in if you don't know assembler.
As for learning it to improve program performance, this is doubtful in applications programming.  Most of the time there are so many things to focus on first before ever hitting this level of optimization like optimizing your i/o access on both disk and network, optimizing how you build the GUI, choosing the right algorithms, maxing out all your cores, running on the best hardware money can buy and switching from interpreted to compiled languages.  Unless you're creating software for other end users, hardware is cheap compared to a programmer's hourly wage, especially with cloud availability.
Also, you have to weigh increased program execution speed with readability of your code after you get hit by a bus, quit or come back to the code base to change it a year after you wrote the last version.

A: Normally it's VERY important for debugging purposes.  What do you do when the system breaks in the middle of an instruction and the error makes no sense?  It's much less of an issue with .NET languages so long as you're only using safe code--the system will almost always shield you from what's going on under the hood.


text:
Q: What is the most feasible way to authenticate using OAUTH2.0 in appscript? code sample:
var propertyStore = PropertiesService.getScriptProperties();

//Logger.log(DriveApp.getFileById('1c4azrEgTFk7ujAF7dn2SL3whXEnTF6Mg'));

cGoa.GoaApp.setPackage(propertyStore,
    cGoa.GoaApp.createServiceAccount (DriveApp , {
    packageName: 'mypackage',
    fileId: '1c4azrEgTFk7ujAF7dn2SL3whXEnTF6Mg',
    scopes: cGoa.GoaApp.scopesGoogleExpand(['https://www.googleapis.com/auth/devstorage.full_control']),
    service: 'google_service'
    }));

but without the comment line it shows error:

You do not have permission to call DriveApp.getFileById. Required permissions: https://www.googleapis.com/auth/drive (line 256, file "GoaApp", project "cGoa")"

A: For some reason, the consent dialog cannot be opened for you (the script creator) to authorize it. To make it to, add a function with a call to DriveApp and run it. You should then be shown the consent screen to authorize. Then you can run the oneoff function.
function runThenDeleteMe() {
  DriveApp.getFiles();
}


text:
Q: Areas vs Folders in MVC I am not to relate to Areas in MVC, why cannot we have simple folders to indicate modules, is the web.config which needs to be there, the below is the reason why i am asking this
Views -unfortunately for views it's not possible. All the views must be placed inside "~/Views/ControllerName" or "~/Views/Shared" folder.

A: The following article describes in detail the reasons for Areas and the difference between Areas and folder-based conventions in ASP.NET MVC.
http://www.codeguru.com/csharp/.net/net_asp/mvc/article.php/c20227/Using-Areas-in-ASPNET-MVC-Application.htm
The essential idea is contained in the Introduction of the article:

ASP.NET MVC relies on certain folder and class naming conventions to
  organize models, views and controllers. A large application often
  consists of functionally independent modules with the result that the
  main application is essentially a bundle of these sub-applications. In
  such cases, organizing various models, views and controllers can be
  tedious. Luckily, ASP.NET MVC allows you to split your application
  into what is known as Areas. Each area mimics the folder structure and
  conventions as required by ASP.NET MVC. This article shows you how
  Areas are used in an ASP.NET MVC application.

When someone is trying to develop a sub-module suitable for inclusion in any ASP.NET MVC application (as an example, think deployment/inclusion of 3rd party code via a NUGET package) then the Areas construct is very helpful, and arguably a necessity.

A: Areas are folder structure which contains its independent set of Controller,
View, Model. Consider we are creating an area called Admin then the folder structure for the Admin area will be,

The same setup can be created by adding folders, Subfolder, and Required files.


text:
Q: How to fix the behavior of this wijmo popup when I update an *ngIf condition I have wijmo popup with some content inside, there is a ng-container with a *ngIf condition that if evaluates to true shows X and else show the ng-template. The problem is that if I update the condition inside the ng-container to show the else statement, this causes to close the wijmo popup(else statement is shown rapidly before closure).
If I update the condition outside the ng-container(still inside wijmo popup) the behavior is correct. I tried the same code outside a wijmo popup and the behavior is correct.
<wj-popup id="wj_popup_1 [modal]="true">
   <ng-container *ngIf="!estListeTropLongue; else messageListeTropLong">
      <button (click)="estListeTropLongue = true"></button>
   </ng-container>
   <ng-template #messageListeTropLong>

Veuillez saisir des caractères pour
      lancer la recherche

   </ng-template>
</wj-popup>

The wijmo popup shouldn't close and show the ng-template information but the popup closes without any console error.
Thank you

A: You could set the hide trigger of the wijmo popup to 'None';
<wj-popup id="wj_popup_1 [modal]="true" [hideTrigger]="None">
   <ng-container *ngIf="!estListeTropLongue; else messageListeTropLong">
      <button (click)="estListeTropLongue = true"></button>
   </ng-container>
   <ng-template #messageListeTropLong>

Veuillez saisir des caractères pour
      lancer la recherche

   </ng-template>
</wj-popup>


text:
Q: In Typescript, how can I implementing bare function interface with overloads? I'm using Typescript 2.3.3
I'm trying to create a nice API for some code I'm writing, so I'm experimenting with what's possible in Typescript's generics.
I'd like to be able to call a function with a generic type, and use that type to present choices to the user, some of which may be functions with different signatures.
Here's my attempt so far.
I declared an interface with two bare function signatures (the two options I'd like to present to the developer):
interface api<T1> {

  <T2>(second: T2):  {
    first: T1
    second: T2;
  };

  <T2, T3>(second: T2, third: T3):  {
    first: T1
    second: T2;
    third: T3;
  };

}

And I create a function that contains the implementations of each function signature, using the generic type parameter passed to it:
const test = <TFirst>(first: TFirst) : api<TFirst> => {

  const impl1 = <T2>(second: T2) => ({
    first, second
  });

  const impl2 = <T2, T3>(second: T2, third: T3) =>({
    first, second, third
  });

  return ...?
};

I have no idea, though, where to assign those implementations or how to create a return object that meets api's specification.
Is this even possible?

A: It's possible. You could do something like this:
interface api<T1> {

  <T2>(second: T2):  {
    first: T1;
    second: T2;
  };

  <T2, T3>(second: T2, third: T3):  {
    first: T1;
    second: T2;
    third: T3;
  };
};

function createApi<T1>(first: T1): api<T1> {

  function impl<T2>(second: T2): { first: T1; second: T2; };
  function impl<T2, T3>(second: T2, third: T3): { first: T1; second: T2; third: T3; };
  function impl<T2, T3>(second: T2, third?: T3): { first: T1; second: T2; third?: T3; } {
    if (third === undefined) {
      return { first, second };
    }
    return { first, second, third };
  }

  return impl;
}

const test = createApi<number>(1);
console.log(test(2));
console.log(test(2, 3));

The createApi function just returns an inner, overloaded function.
For more information on TypeScript overloads, see the Overloads section in the documentation.


text:
Q: cx_Oracle Giving DLL load failed exception I have

*

*Oracle 11g client installed,

*64 bit Windows 7 machine,

*Python 3.4,

*cx_Oracle 64 bit installed.

Still facing the exception ImportError: DLL load failed: The specified procedure could not be found. during run time.

A: First, make sure that the Oracle client, the Python installation and the cx_Oracle installation all match with each other. In your case you need to make sure they are all 64-bit and also all 11g. Second, if all of that is correct and you are still getting that error, you'll need to find out what dependency is missing. You can use this tool for that purpose:
http://www.dependencywalker.com/


text:
Q: Android App in Phone does not receive Data from WearApp when is closed Good morning,
I'm facing this problem. I developed an Android Wear App that sends messages to the Mobile App using the DataApi and PutDataRequest.
Everything works fine, and the mobile receives the messages and I can store them in a DataBase, etc.
The problem is that when the App in the phone is close, not in background, but completely closed, then it does not receive any messages. That means that all the info that I was sending from the Smartwatch to the Phone is lost.
Once I open the App in the Phone, all the data that was sent while the App was closed, is not syncronized anymore.
I would like to Open the mobile Phone from the Smartwatch, when it checks that is closed, so the info that it sends won't be lost. It is that possible to do??
Thanks!
Carlos

A: You need to create a Service on your phone that extends WearableListenerService and then declare it in your manifest as follows :
<service
        android:name=".MessageListener"
        android:enabled="true"
        android:exported="true">
        <intent-filter>
            <action android:name="com.google.android.gms.wearable.BIND_LISTENER" />
        </intent-filter>
    </service>

You don't need to start this service, it will be started when a message, or a data change will be received.


text:
Q: What does Context Root mean? I am deploying a simple web module to glassfish server.
The package name is test2.war.
The runtime deployment descriptor file sun-web.xml specifies the Context Root as below:
  <context-root>/myTest</context-root>

According to the Java EE 5 tutorial, A context root identifis a web application in a Java EE server. I expected that I should visit my site like below:
http://localhost:8080/myTest

But it turns out I still have to use:
http://localhost:8080/test2

So what's the purpose of Context Root? How to use it?
ADD 1
According to Setting context root does not work in Glassfish
This seems to be a glassfish bug.


text:
Q: Extract data from csv in RASA I am making a chatbot in RASA which helps High school graduates find university according to their desired location. I have all my data stored in a CSV file. So is there any way we can extract some specific data from that CSV.
Example: If a user asks to show universities available in a certain location, how to extract the specific data from CSV which is the name of the university according to the location given by the user.

A: Seems like you will need to train the model with location entity. Create a story that will link an intent with location entity to a custom action.
Sample story could like something like this:

story 1
* ask_university{"location":New York}
 - action_get_universities

In the custom action action_get_universities, you will then need to handle the CSV query based on the location entity that the model detected. Pandas should work just fine.
Have fun exploring !