text:
Q: Formatting percentages in ASP.NET C# databinding using Eval There is a col in a database that is declare as decimal 4 precision 3. I need to multiply this number by 100 (I am doing that in the stored procedure query) and display it as a decimal with only significant zeros after the decimal point. If the resulting value is less than 1%, I suppose it should be displayed with a 0 before the decimal. The display should include a % mark. For example:
 100 %
 99.1 %
 0.1 %
 56 %
 0 %

The web page is using data binding:
 <asp:Label ID="lblTMLY_POL_HLDER_NOTC_PCT" runat="server" Text='<%# Eval("DECIMAL_COL_PREC_4_SCALE_3") %>'></asp:Label>

I suppose I'd probably have an easier time handling this in the Data Bound Item even and using string formatting functions there. Ideally, I'd like to know what format string in the markup to use and how one would handle this in the code behind.
  <asp:Label ID="lblTMLY_POL_HLDER_NOTC_PCT" runat="server" Text='<%# Eval("DECIMAL_COL_PREC_4_SCALE_3","{00:??????}") %>'></asp:Label>

A: Is this what you are looking for?

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
    <Columns>
        <asp:BoundField HeaderText="Id" DataField="Id" />
        <asp:BoundField HeaderText="Name" DataField="Name" />
        <asp:BoundField HeaderText="Actual Value" DataField="Total" />
        <asp:BoundField HeaderText="Using Bound Field" DataField="Total"
            DataFormatString="{0:0.### %}" />
        <asp:TemplateField HeaderText="Using Eval">
            <ItemTemplate>
                <asp:Label runat="server" ID="Label1"
                    Text='<%# string.Format("{0:0.### %}", Eval("Total")) %>'>
                </asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

private class Item
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Total { get; set; }
}

protected void Page_Load(object sender, EventArgs e)
{
    var items = new List<Item>
        {
            new Item {Id = 1, Name = "One", Total = 1.0M},
            new Item {Id = 2, Name = "Two", Total = 0.2M},
            new Item {Id = 3, Name = "Three", Total = 0.03M},
            new Item {Id = 4, Name = "Four", Total = 0.004M},
            new Item {Id = 5, Name = "Five", Total = 0.0005M},
            new Item {Id = 6, Name = "Six", Total = 0.00006M},
        };

    GridView1.DataSource = items;
    GridView1.DataBind();
}


text:
Q: Dependent dropdown not working correctly this is my first time on this site so I'll cut to chase.
I've been working on a fixed assets control web system using PHP, AJAX, jquery and MySQL as database (the project structure was made by following the tutorial from this website: https://www.itechempires.com/2016/07/pdo-crud-operations-using-php-bootstrap/ ), where such items are registered along with the categories to which each asset belongs, the transactions made by the users within the company and the reports generated by each transaction.
Currently I'm stuck with the dropdowns since I tried anything I could to make them work but without the results I've been looking for, which is:
in a modal there's a form where an asset is going to be added with its related information, two of those details are categories and subcategories which are handled by dependent dropdowns, the dropdown regarding to subcategories will be displayed once a category is selected.
The code snippets will be up for review which will be focused on the ones related to the dropdowns:
Tables
grupo (group or category)

*

*id_grp (group id,autoincremented, not visible by the user)

*codigo_grp (code)

*nombre_grp (name)

subgeupo (subgroup or subcategory)

*

*id_sgrp (subgroup id, autoincremented, not visible by the user)

*codigo_sgrp (code)

*nombre_sgrp (name)

*vidaUtil_sgrp (useful life)

*id_grp (group id, foreign key)

libAF.php: Contains all queries for crud operations
    /*
    * Get group's id and name
    *
    * @return $id_grp, $nombre_grp
    * */
    public function populateSelGrp()
    {
        $query = $this->db->prepare("SELECT id_grp, nombre_grp FROM grupo");
        $query->execute();
        $data = array();
        while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
            $data[] = $row;
        }
        return $data;
    }

    /*
    * Get sub-group's id and name
    *
    * @return $id_grp, $nombre_grp
    * */
    public function populateSelSgrp($id_grp)
    {
        $query = $this->db->prepare("SELECT * FROM subgrupo WHERE id_grp = :id_grp");
        $query->bindParam("id_grp", $id_grp, PDO::PARAM_STR);
        $query->execute();
        $data = array();
        while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
            $data[] = $row;
        }
        return $data;
    }

populateSelGrp.php: loads the categories on to the parent dropdown
<?php

require 'libAF.php';

$data = "";

$object = new CRUD();

$grupos = $object->populateSelGrp();

$data .= '<select id="select_grp" class="form-control" onchange="populateSelSgrp()">';
$data .= '<option value="0" disabled selected>Escoja grupo</option>';
if (count($grupos) > 0) {
    foreach ($grupos as $grupo) {
        $data .= '<option id="selected_grp" value="' . $grupo['id_grp'] . '"> ' . $grupo['nombre_grp'] . '</option>';
    }
}
else
{
    $data .= '<option>No hay opciones disponibles</option>';
}

$data .= '</select>';

echo $data;

?>

populateSelSgrp.php: loads the subcategories on to the child dropdown
<?php

require 'libAF.php';

if (isset($_POST['id_grp']) && isset($_POST['id_grp']) != "") {
    $id_grp = $_POST['id_grp'];
    $data = "";

    $object = new CRUD();

    $subgrupos = $object->populateSelSgrp($id_grp);

    $data .= 'Sub-grupo';
    $data .= '<select id="select_sgrp" class="form-control">';
    $data .= '<option value="0" disabled selected>Escoja sub-grupo</option>';

    if (count($subgrupos) > 0) {
        foreach ($subgrupos as $subgrupo) {
            $data .= '<option value="' . $subgrupo['id_sgrp'] . '"> ' . $subgrupo['nombre_sgrp'] . '</option>';
        }
    }
    else
    {
        $data .= '<option>No hay opciones disponibles</option>';
    }

    $data .= '</select>';

    echo $data;
}

?>

scptAF.js: Contains the scripts needed to make the inputs work
function populateSelGrp(){
$.get("ajax/activoFijo/populateSelGrp.php", {
},
    function (data, status) {
//load options to dropdown list
        $(".option_grp").html(data);
    }
);
}

function populateSelSgrp(id_grp){
$.ajax({
    url: "ajax/activoFijo/populateSelSgrp.php",
    method: "POST",
    data:{id_grp: id_grp},
    success:function(data){
        $(".option_sgrp").html(data);
    }
})
}

activos.php (assets): visible page where the user adds, removes or updates an asset.

     Grupo

A: I finally found a solution for this mess, was a little code I had to add to the javaScript file to send the id to the second dropdown. Although I finally fixed my problem, I'd like to see other suggestions on how to tackle this problem.
Here's my snippet
scptAF.js
function populateSelGrp() {
$.get("ajax/activoFijo/populateSelGrp.php", {
},
    function (data, status) {
//load options to dropdown list
        $(".option_grp").html(data);
    }
);
}

function changeGrpId(){
var id_grp = document.getElementById("select_grp").value;
populateSelSgrp(id_grp);
}

function populateSelSgrp(id_grp) {
$.ajax({
    url: "ajax/activoFijo/populateSelSgrp.php",
    method: "POST",
    data:{id_grp: id_grp},
    success:function(data){
        $(".option_sgrp").html(data);
    }
})
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: python LinkedIn api connection I am connecting to linkedin api through python.
url = 'https://www.linkedin.com/uas/oauth2/accessToken'

data = [
        {'client_id': 'xxx'},
        {'client_secret': 'xxx'},
        {'grant_type': 'authorization_code'},
        {'redirect_uri' : 'xxx'},
        {'code': xxx}
      ]

headers = {'Content-type': 'application/x-www-form-urlencoded'}
r = requests.post(url, data=json.dumps(data), headers=headers)
return HttpResponse(r)

but I am getting the following error :
{"error_description":"missing required parameters, includes an invalid parameter value, parameter more than once. : client_id","error":"invalid_request"}

what is the reason for this error ? how to debug ? please help.

A: That is a strange way to format the data. You have each parameter in a separate dictionary. I guess you want a single dict:
data = {
         'client_id': 'xxx',
         'client_secret': 'xxx',
         'grant_type': 'authorization_code',
         'redirect_uri' : 'xxx',
         'code': xxx
       }

Also, you specify the content type as form-encoded, but you then serialize the actual data as JSON. Don't do that.
r = requests.post(url, data=data, headers=headers)


text:
Q: htaccess mod_rewrite - exclude last / in REQUEST_URI I've tried searching for the answer to this but I can't seem to find an answer.
What I want is when somebody goes to a page, apache checks if a cache file exists for that page and then loads that instead of letting php serve it.
EG: http://example.com/about
For this, I use the code below and it works. But as soon as I add a / on the end like this: http://example.com/about/ It doesn't work anymore. I tried making my cache file include the slash but that's not possible.
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_METHOD} !^(POST)$
RewriteCond %{DOCUMENT_ROOT}/cached_pages/%{REQUEST_URI}.html -f
RewriteRule . %{DOCUMENT_ROOT}/cached_pages/%{REQUEST_URI}.html
</IfModule>

A: I found a solution. @ishegg helped me with the RewriteRule and for the ReWriteCond I used a variable.
<IfModule mod_rewrite.c>
RewriteEngine On
SetEnvIf Request_URI "^(.+?)/?$" PATH=$1
RewriteCond %{REQUEST_METHOD} !^(POST)$
RewriteCond %{DOCUMENT_ROOT}/cached_pages/%{ENV:PATH}.html -f
RewriteRule ^(.+?)/?$ %{DOCUMENT_ROOT}/cached_pages/$1.html
</IfModule>


text:
Q: How to set an icon image and a text heading side by side in Bootstrap framework in following scenario? I'm using Bootstrap 2.0.1 framework for my website.
I want to show the icon image and on right side of an icon image I want to show the text. Both should be inline and vertically center aligned. I managed to bring the icon image vertically center align but not able to show the text on right side of this icon image. Now the text is appearing above the icon image. Please help me in resolving this issue.
For your reference I'm putting below my code. I've also added one comment above the code where I'm facing the issue.:

Nice Site

A: Whenever you want to position elements on the same row you have 4 options:

*

*Position absolute / fixed which is bad because it's not a flexible solution and differences in sizes of either element can make this get out of whack.

*Floating right/left which is a pretty common solution and it's good enough but it has a small downside -- the height of the floated element behaving differently that expected. This solution is the go-to for positioning bigger content blocks -- it's uncommon for smaller pieces of text.

*Using inline / inline-block which makes any type of block element such as p work as if it was an inline element such as span which is the go-to solution for making a anchors behave like blocks (buttons) and not like text.

*Using an actual inline such as span which is a more semantic approach because the content is structured according to its role.

Here's an example for 3. and 4.:

Nice Site

            Nice Site

A: Just add padding-left to the text (
 tag)
Fiddle


text:
Q: Most efficient way to populate/distribute indexedDB [datastore] with 350000 records So, I have a main indexedDB objectstore with around 30.000 records on which I have to run full text search queries. Doing this with the ydn fts plugin this generates a second objectstore with around 300.000 records. Now, as generating this 'index' datastore takes quite long I figured it had be faster to distribute the content of the index as well. This in turn generated a zip file of around 7MB which after decompressing on the client side gives more than 40MB of data. Currently I loop over this data inserting it one by one (async, so callback time is used to parse next lines) which takes around 20 minutes. As I am doing this in the background of my application through a webworker this is not entirely unacceptable, but still feels hugely inefficient. Once it has been populated the database is actually fast enough to be even used on mid to high end mobile devices, however the population time of 20 minutes to one hour on mobile devices is just crazy. Any suggestions how this could be improved? Or is the only option minimizing the number of records? (which would mean writing my own full text search... not something I would look forward to)

A: Your data size is quite large for mobile browser. Unless user constantly using your app, it is not worth sending all data to client. You should use server side for full text search, while catching opportunistically as illustrated by this example app. In this way, user don't have to wait for full text search indexing.
Full-text search require to index all tokens (words) except some stemming words. Stemming is activated only when lang is set to en. You should profile your app which parts is taking time. I guess browser is taking most of the time, in that case, you cannot do much optimization other than parallelization. Sending indexed data (as you described above) will not help much (but please confirm by comparing). Also Web worker will not help. I assume your app have no problem with slow respond due to indexing.
Do you have other complaint other than slow indexing time?


text:
Q: How to specify source location in wix How do I make the sources specified in a heat generated file visible to the build?
I've got a project named Foo and a project named FooSetup. They have the same parent directory. To generate the list of files to install I ran in FooSetup:
heat dir "..\Foo\bin\Release" -cg "SomeGroupName" -ag -template:fragment -out heat.wxs

Now when I try to build the installer, I get:
The system cannot find the file 'SourceDir\Foo.dll'.

(that file does exist in the Release directory)
The path to Foo\bin\Release is specified in include paths in the FooSetup project properties.
What am I missing here - why is none of the listed files found?

A:
WiX Learning Resources: A couple of links to resources on WiX:

*

*Click-by-click WiX and Visual Studio

*Long list of WiX links

WiX Preprocessor Variables: What is SourceDir? Rob Mensching (WiX creator) on SourceDir.
As explained here you can change SourceDir to a compiler variable:
Heat.exe: Something like this:
"%WIX%bin\heat.exe" dir . -sfrag -suid -ag -var MyReleasePath -out MySource.wxs

You will get something like this:
<!-- Extract -->

  <Component Id="MyFile.exe" Guid="*">
     <File Id="MyFile.exe" KeyPath="yes" Source="$(MyReleasePath)\MyFile.exe" />
  </Component>

<!-- End of Extract -->

WiX Sample: Then you insert this into your source. Something like this:
<!-- START OF COMPILER VARIABLES: -->
<?define MyVersion = "1.0.0.0" ?>
<?define MyReleasePath = "C:\My Releases\Wix Testing\" ?>
<!-- END OF COMPILER VARIABLES: -->

<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi">

  <Product Id="*" Name="WiX Testing" Language="1033" Version="$(var.MyVersion)"
           Manufacturer="WiX Testing" UpgradeCode="PUT-GUID-HERE">

    <Package InstallerVersion="200" Compressed="yes" InstallScope="perMachine" />
    <MajorUpgrade DowngradeErrorMessage="A newer version of [ProductName] is already installed." />

    <!-- Enable line below for GUI in MSI -->
    <!-- <UIRef Id="WixUI_Mondo" /> -->

    <MediaTemplate EmbedCab="yes" />
    <Feature Id="Main" Title="Main Feature" Level="1" />

    <Directory Id="TARGETDIR" Name="SourceDir">
      <Directory Id="ProgramFilesFolder">
        <Directory Id="INSTALLFOLDER" Name="WiX Testing">

         <!-- Essential part follows: -->

          <Component Feature="Main">
            <File Source="$(var.MyReleasePath)MyFile.exe"></File>
          </Component>

         <!-- End of Essential part -->

        </Directory>
      </Directory>
    </Directory>
  </Product>

</Wix>

Batch File Compile: Visual Studio takes care of most of the build issues once you have defined the variables. If you want to compile "manually", here is a quick sample:
"%WIX%bin\candle.exe" MySource.wxs -ext WixUIExtension >> Build.log
"%WIX%bin\light.exe" -out Test.msi MySource.wixobj -ext WixUIExtension >> Build.log

Links:

*

*WiX sample for other issue at bottom


text:
Q: Basic hypothesis testing of two normal populations Consider this problem in Montgomery's book:

Two types of plastic are suitable for use by an electronics component
manufacturer. The breaking strength of this plastic is important. It
is known that $\sigma_1=\sigma_2=1$ psi. From a random sample of size
$n_1=10$ and $n_2=12$, we obtain $\bar x_1=162.5$ and $\bar
 x_2=155.0$. The company will not adopt plastic 1 unless its mean
breaking strength exceeds that of plastic 2 by at least 10 psi.
(a) Based on the sample information, should it use plastic 1?

In the Solution manual, the hypotheses of the test are:
$H_0: \mu_1-\mu_2=10$ against $H_1:\mu_1-\mu_2>10$. Rejecting the null hypothesis means evidence to support the use of plastic 1.
In my interpretation, the company has to decide whether $\mu_1-\mu_2\geq 10$ holds ("at least 10"). It seems to me that both hypotheses corresponds to $\mu_1-\mu_2\geq 10$.
Question Why the alternative hypothesis is not $H_1:\mu_1-\mu_2<10$ ?

A: If the null hypothesis is $\mu_1-\mu_2<10$, then rejecting the null indicates evidence that plastic 1 is not sufficiently strong to warrant use. This means that failing to reject the null puts you in a position where you lack evidence against the strength of plastic 1. However, this is not the same as having evidence against the strength of plastic 1; it means that you don't know.
The hypothesis given as correct allows for appropriate skepticism about plastic 1. Unless you have considerable evidence that plastic 1 is stronger by at least the required 10 psi, the company will continue using plastic 2.

A:
$H_0: \mu_1-\mu_2=10$ against $H_1:\mu_1-\mu_2>10$. Rejecting the null hypothesis means evidence to support the use of plastic 1.
In my interpretation, the company has to decide whether $\mu_1-\mu_2\geq 10$ holds ("at least 10"). It seems to me that both hypotheses corresponds to $\mu_1-\mu_2\geq 10$.

You could also formulate the hypothesis as

$H_0: \mu_1-\mu_2<10$ against $H_1:\mu_1-\mu_2 \geq 10$

effectively this results in the same criterium for rejecting the null hypothesis. That criterium is when $\bar{x}_1 - \bar{x}_2$ exceeds a certain value.

Why are they the same?
When you test a null hypothesis against some alternative then you choose a rejection criterium in such a way that it is sensitive to rejection when the alternative is true.
For a given type I error (false negative: rejecting the null when it is actually true) you want to minimize the type II error (false positive: the error of not rejecting when the alternative hypothesis is actually true).
When you test the hypothesis $H_0: \mu_1-\mu_2=10$ then you could have some two sided rejection criterium or a one sided rejection criterium. The one sided criterium has a sharper bound and will be more sensitive when the alternative hypothesis is true.
See for instance the graph from this question:
Hypothesis testing: why $\mu > 0$ (or even $\mu > \epsilon$) "seems easier" to substantiate than $\mu \neq 0$?

For a given probability of rejecting the null hypothesis when it is actually true (in the image the 0.05 level where the two curves intersect), the one sided test is more sensitive when the true value of the parameter is on one side.


text:
Q: Cannot modify files hosted on raspi on other computers in the network I'm having a weird issue with my pi. Pi is set up as SMB host, hosting music files for access around the house. I can't modify the files from any of the other computers though, except with sudo.
I have set all permissions recursively on the whole music collection to 0777.
My smb.conf share is set up thus:
[share]
Comment = pi shared folder
Path =/mnt/share
Browseable = yes
Writeable = Yes
only guest = no
create mask = 0777
directory mask = 0777
public = yes
Guest ok = yes
create mask = 0777

If I need to edit a tag, or rename a file, I navigate either in puddletag or nautilus to the file in question, and when I try to edit I get a permission error. If I do either of these things with sudo, however, I can edit freely.
Doing my music maintenance as elevated user is obviously an ok workaround, but a bit annoying. Does anyone know what I've done wrong?
P.S. I'm no pro at this stuff, if I've missed any key info please let me know and I will supply it.
P.P.S The drive I'm sharing is formatted as ext4.

A: Your configuration states only that
Guest ok = yes

This only allows guest to access the service without password and operate within powers of the guest account. But what are they? By default it's nobody. Does he have access to your music collection? Remember that if the collection is inside your /home/you directory, then even if you set wide open permissions on the collection folder, nobody or another user might not even get that far getting stopped by some more restrictive permissions down the way.
Possibly then you just need to overrule the default nobody with someone more privileged:

Default: guest account = nobody # default can be changed at compile-time
Example: guest account = ftp

Or you might move the collection to a more accessible place.
Remember to reload or restart your Samba service after the configuration's been saved.


text:
Q: How to extract data from a filename in python? - convert file name to string? I am trying to extract the meta data for some experiments I'm helping conduct at school. We are naming our data files something like this:
name_date_sample_environment_run#.csv
What I need to do is write a function that separates each piece to a list that'll be output like this:
['name', 'date', 'sample', 'environment', 'run#']
Though I haven't quite figured it out. I think I need to figure out how to load the file, convert the name to a string, then use a delimiter for each underscore to separate each into the given list. I don't know how to load the file so that I can convert it to a string. Any help will be appreciated!
P.S - I will eventually need to figure out a way to save this data into a spreadsheet so we can see how many experiments we do with certain conditions, who performed them, etc. but I can figure that out later. Thanks!

A: If you're just asking how to break down the string into all the components separated by an underscore, then the easiest way would be using the split function.
x = 'name_date_sample_environment_run#.csv'
y = x.split('_')

# y = ['name', 'date', 'sample', 'environment', 'run#.csv']

The split function simply breaks down the string every time it sees the underscore. If you want to remove the .csv part from 'run#.csv' then you can process the original string to remove the last 4 characters.
x = 'name_date_sample_environment_run#.csv'
x = x[:-4]
y = x.split('_')

# y = ['name', 'date', 'sample', 'environment', 'run#]

A: If all your files are structured, and in the same folder you can do this way:
import os
files = os.listdir('.') #insert folder path

structured_files = {}
for file in files:
    name, date, sample, environment = file.split('_')
    structured_files.append({'name':name, 'date':date, 'sample':sample, 'env':env})

Then you'll have a structure dict with your file info.
If you want to, you can import into pandas, and save to an excel sheet:
import os
import pandas as pd

files = os.listdir('.') #insert folder path

structured_files = {}
for file in files:
    name, date, sample, environment = file.split('_')
    structured_files.append({'name':name, 'date':date, 'sample':sample, 'env':env})

pd.from_dict(structured_files).to_excel('files.xlsx')


text:
Q: c#: get class member by name (reflection) I have two lists (list) l1 & l2.
i'm getting from outside the name of the list i want to use (let say l1).
how can i find requested list ?
do i need to use getMember method ?
thanks

A: You can use reflection, but it's fairly expensive.  Here's a question that outlines how to do that:
C# Reflection : Finding Attributes on a Member Field
Given that the list name is known at compile time, you could consider implementing a method that accepts the string name of the list and returns a reference to the appropriate list using a switch statement or if statement.
static IList FindList(string name)
{
  if (name == "l1") { return l1; }
  else if (name == "l2") { return l2; }
  else throw Exception("List " + name + " not found.");
}

That will be faster at runtime than using reflection but requires maintenance (if you have enough lists to warrant the effort, you could code generate that method).


text:
Q: Backbone ID attribute is different than the parameter I need for the API I'm using Backbone Collections and Models from an API. My id attribute is the default id attribute for mongo (_id) but in my API, I use a different unique key to get to a single Model. Something like a slug that is always unique.
The problem now is that when I want to save(), it does a PUT request instead of POST because it assumes that there is already a Model with this key (slug) because the user is able to enter the slug by himself (with proper validations of course).
Is there a way that I can 'say': "Ok, my idAttribute is _id but i want you to use slug when fetching data?

A: Well, I got it working by doing the following:
var page = new PageModel({_id: param}); // no idea why this works tbh
page.fetch();

Have no idea why this works since the model _id is not equal to the param I'm giving but somehow it finds the correct Model anyway.


text:
Q: stickman example using fabric js does not persist line coordinate logic after load from json I am trying to save fabricjs stickman example by using JSON.stringify and load it back using canvas.loadFromJSON, I even add the properties of circle line1, line2, line3 and line4 explicitly to the JSON using the following way
var jsonSave = JSON.stringify(canvas.toJSON(['line1', 'line2', 'line3', 'line4']));
Although i can see that the saved JSON contains the above mentioned properties, but when I load from JSON and try to move the circle I get an error as Uncaught TypeError: p.line1.set is not a function.
I don't understand why before saving set was a function but after saving and load from JSON its not?
Also is there any other way to make the stickman work without using set method so that it doesn't break after we save it and load it from JSON.
I did look up for similar problems and this link was the most similar problem i could find but the solution provided in this answer, also didn't seem to solve the problem of save and load.
loading stickman from json does not persist line coordinate rotation logic
I have also attached the fiddle link below. To reproduce the scenario

*

*Try to move any circle after fiddle loads.

*Click on the save button. (you can go to developers tool and see under the resources tab for the JSON stored in the sessions storage.)

*Click on load button.

*Try to move any circle and look at console tab in developers tool.

http://jsfiddle.net/hkundnani/h0sf3x5h/5/
Any help would be greatly appreciated.. Thanks..

A: When your code creates the circle objects, your code adds extra properties (e.g. line1, line2, line3, line4) to the circle objects. These extra properties are references to existing line objects on the fabric canvas. The issue that you are encountering is that the JSON format has no built-in support for serializing objects by reference. Objects are always serialized by value. As a result, multiple references to the same object will be serialized to the JSON string as multiple objects with the same values. When the JSON string is deserialized, you will have multiple objects with the same values instead of multiple references to the same object. To further compound your problems, FabricJS's loadFromJSON() method with convert the top level objects to FabricJS objects but leave the inner property objects (e.g. circle.line1) as plain objects. These plain objects will not have the FabricJS methods (e.g. no set method).
If you do a Google search of "JSON object references" then you will find articles discussing possible work arounds to the issue of preserving object references in JSON format.
In your case, a possible solution might be to add a custom property (e.g. "$id") to the line objects where the custom property holds an unique identifer for the line object. Save this custom property to the JSON string. After loading the JSON string, you could scan the FabricJS canvas for line objects and create a map from identifiers to line objects. Then you could scan the FabricJS canvas for circle objects and replace their line property values with the line object references from your map. It is not an easy solution but it should work.

A: Possible workaround for fabricjs:
http://jsfiddle.net/h0sf3x5h/9/
(snippet does not run, if you know how to solve it, please tell me)
The point is to write custom code in save and load functions to get the lines attached to your circles again.

var canvas = this.__canvas = new fabric.Canvas('c', { selection: false }), saveNow, loadNow;
  fabric.Object.prototype.originX = fabric.Object.prototype.originY = 'center';

(function() {

  saveNow = (function(){
    var jsonSave = JSON.stringify(canvas.toJSON(['linesID', 'selection', 'id']));
    sessionStorage.canvase = jsonSave;
  });

  function _callBack() {
    var objs = canvas.getObjects();
    var lines = {};
    for(var i = 0; i < objs.length; i++) {
       if (objs[i].type === 'line') {
           lines[objs[i].id] = objs[i];
       }
    }
    for(i = 0; i < objs.length; i++) {
       if (objs[i].type === 'circle') {
           var circle = objs[i];
           if (circle.linesID) {
               circle.line1 = lines[circle.linesID[0]];
               circle.line2 = lines[circle.linesID[1]];
               circle.line3 = lines[circle.linesID[2]];
               circle.line4 = lines[circle.linesID[3]];
           }
       }
    }
    canvas.renderAll();
  }

  loadNow = (function(){
    var jsonLoad = sessionStorage.canvase;
    canvas.loadFromJSON(jsonLoad, _callBack);
  });

document.getElementById('save').addEventListener('click', saveNow);
document.getElementById('load').addEventListener('click', loadNow);
  function makeCircle(left, top, line1, line2, line3, line4) {
    var c = new fabric.Circle({
      left: left,
      top: top,
      strokeWidth: 5,
      radius: 12,
      fill: '#fff',
      stroke: '#666'
    });
    c.hasControls = c.hasBorders = false;

    c.line1 = line1;
    c.line2 = line2;
    c.line3 = line3;
    c.line4 = line4;
    c.linesID = [line1 && line1.id, line2 && line2.id, line3 && line3.id, line4 && line4.id];
    return c;
  }

  function makeLine(coords, id) {
    return new fabric.Line(coords, {
      fill: 'red',
      stroke: 'red',
      strokeWidth: 5,
      selectable: false,
      id: id
    });
  }

  var line = makeLine([ 250, 125, 250, 175 ], 'line1'),
      line2 = makeLine([ 250, 175, 250, 250 ], 'line2'),
      line3 = makeLine([ 250, 250, 300, 350], 'line3'),
      line4 = makeLine([ 250, 250, 200, 350], 'line4'),
      line5 = makeLine([ 250, 175, 175, 225 ], 'line5'),
      line6 = makeLine([ 250, 175, 325, 225 ], 'line6');

  canvas.add(line, line2, line3, line4, line5, line6);

  canvas.add(
    makeCircle(line.get('x1'), line.get('y1'), null, line),
    makeCircle(line.get('x2'), line.get('y2'), line, line2, line5, line6),
    makeCircle(line2.get('x2'), line2.get('y2'), line2, line3, line4),
    makeCircle(line3.get('x2'), line3.get('y2'), line3),
    makeCircle(line4.get('x2'), line4.get('y2'), line4),
    makeCircle(line5.get('x2'), line5.get('y2'), line5),
    makeCircle(line6.get('x2'), line6.get('y2'), line6)
  );

  canvas.on('object:moving', function(e) {
    var p = e.target;
    p.line1 && p.line1.set({ 'x2': p.left, 'y2': p.top });
    p.line2 && p.line2.set({ 'x1': p.left, 'y1': p.top });
    p.line3 && p.line3.set({ 'x1': p.left, 'y1': p.top });
    p.line4 && p.line4.set({ 'x1': p.left, 'y1': p.top });
    canvas.renderAll();
  });
})();
<script src="http://fabricjs.com/lib/fabric.js"></script>
<canvas id="c" width="500" height="500"></canvas>

<button id="save">Save </button>
<button id="load">Load </button>


text:
Q: IE and remember password prompt in web app I have a web app that has text and password input. When i use it to log in IE does not prompt me to remember password. I clear cookies and still do not get prompt. I have also selected all the options in the Content-> Autocomplete settings.
Autocomplete works on another site ie facebook for example.
 <form id="form1" runat="server" onsubmit="javascript:return validateForm()">
   <asp:Panel ID="ViewPanel" runat="server" DefaultButton="btnLogin">

                                Login

                                    Username / ID

                                    <input type="text" maxlength="100" name="Username" class="txt" />

                                    Password

                                    <input type="password" maxlength="100" name="Password" class="txt" />

                                    <asp:LinkButton ID="btnLogin" class="btn" runat="server">Login</asp:LinkButton>

  </asp:Panel>
</form>

A: I wrote extensively on this topic here: http://blogs.msdn.com/b/ieinternals/archive/2009/09/11/troubleshooting-stored-login-problems-in-ie.aspx
Your markup looks okay, so my guess would be that it's related to a no-cache header. Can you provide a live repro URL?


text:
Q: When to set up islargearch UWP I have to set up IsLArgeArc but I can't do it precisely.
UserControl.xaml:
<UserControl
x:Class="Pointer_Answer_UWP.RadialSlider"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Pointer_Answer_UWP"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="207"
d:DesignWidth="207">

<Grid>
    <Grid x:Name="GridBase" Width="207" Height="207" Background="#FFD7B6B6">
        <Ellipse Fill="#FFC7C7C7"/>
        <Grid Height="207" Width="207" HorizontalAlignment="Center" VerticalAlignment="Center">
            <Path Stroke="#FF34A1ED" StrokeThickness="7" x:Name="arcPath" StrokeEndLineCap="Round" StrokeStartLineCap="Round" RenderTransformOrigin="0.5,0.5">
                <Path.RenderTransform>
                    <CompositeTransform TranslateX="3.5" TranslateY="3.5"/>
                </Path.RenderTransform>
                <Path.Data>
                    <PathGeometry>
                        <PathFigure x:Name="myArcStart" StartPoint="7.612,61.6317">
                            <ArcSegment x:Name="myArc" IsLargeArc="False" Point="78.3221,197.6221" Size="100,100"/>
                        </PathFigure>
                    </PathGeometry>
                </Path.Data>
            </Path>
        </Grid>
        <Canvas x:Name="CanvasVolume" Width="207" Height="207" RenderTransformOrigin="0.5,0.5">
            <Canvas.RenderTransform>
                <CompositeTransform x:Name="CompositePoint" Rotation="0"/>
            </Canvas.RenderTransform>
            <Ellipse x:Name="VolumePoint" Width="20" Height="20" Fill="#9923678A" PointerPressed="VolumePoint_PointerPressed" Canvas.Top="{x:Bind TopPosition, Mode=OneWay}" Canvas.Left="{x:Bind LeftPosition, Mode=OneWay}"/>
        </Canvas>
    </Grid>
</Grid>

UserControl.xaml.cs:
public sealed partial class RadialSlider : UserControl, INotifyPropertyChanged
{
    private double topPosition = 55.2317;
    public double TopPosition
    {
        get => topPosition;
        set
        {
            topPosition = value;
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(TopPosition)));
        }
    }

    private double leftPosition = 1.112;
    public double LeftPosition
    {
        get => leftPosition;
        set
        {
            leftPosition = value;
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(LeftPosition)));
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    public RadialSlider()
    {
        this.InitializeComponent();
    }

    private void VolumePoint_PointerPressed(object sender, PointerRoutedEventArgs e)
    {
        RadialSlider radialSlider = this as RadialSlider;
        Point puntopressd = e.GetCurrentPoint(CanvasVolume).Position;

        PointerEventHandler moved = null;
        moved = (s, args) =>
        {
            CanvasVolume.CapturePointer(e.Pointer);
            Point puntomoved = e.GetCurrentPoint(CanvasVolume).Position;

            double puntoX = puntomoved.X;
            double puntoY = puntomoved.Y;
            double raggio = 100;

            double halfWidth = CanvasVolume.ActualHeight / 2;
            double slashLength = Math.Sqrt((Math.Abs(puntoY - halfWidth) * Math.Abs(puntoY - halfWidth) + (Math.Abs(halfWidth - puntoX) * Math.Abs(halfWidth - puntoX))));

            double coordinataX = CanvasVolume.ActualHeight / 2 + ((puntoX - halfWidth) * raggio / slashLength) - VolumePoint.Width / 2;
            double coordinataY = puntoY - ((puntoY - halfWidth) * (slashLength - raggio) / slashLength) - VolumePoint.Width / 2;

            double angolo = GetAngle(new Point((CanvasVolume.ActualHeight / 2 + ((puntoX - halfWidth) * raggio / slashLength)) - 3.5, (puntoY - ((puntoY - halfWidth) * (slashLength - raggio) / slashLength)) - 3.5), new Size(CanvasVolume.Width, CanvasVolume.Width));

            LeftPosition = coordinataX;
            TopPosition = coordinataY;

            //myArc.IsLargeArc = angolo < 113 ? true : false;

            myArc.Point = new Point((CanvasVolume.ActualHeight / 2 + ((puntoX - halfWidth) * raggio / slashLength)) -3.5, (puntoY - ((puntoY - halfWidth) * (slashLength - raggio) / slashLength)) - 3.5);
        };

        PointerEventHandler released = null;
        released = (s, args) =>
        {
            Point puntoreleas = e.GetCurrentPoint(CanvasVolume).Position;

            CanvasVolume.PointerMoved -= moved;
            CanvasVolume.PointerReleased -= released;
        };
        CanvasVolume.PointerMoved += moved;
        CanvasVolume.PointerReleased += released;
    }

    public enum Quadrants : int { nw = 2, ne = 1, sw = 4, se = 3 }
    private double GetAngle(Point point, Size size)
    {
        var X = point.X - (size.Width / 2d);
        var Y = size.Height - point.Y - (size.Height / 2d);
        var Hypot = Math.Sqrt(X * X + Y * Y);
        var Value = Math.Asin(Y / Hypot) * 180 / Math.PI;
        var Quadrant = (X >= 0) ? (Y >= 0) ? Quadrants.ne : Quadrants.se : (Y >= 0) ? Quadrants.nw : Quadrants.sw;
        switch (Quadrant)
        {
            case Quadrants.ne: Value = 090 - Value; break;
            case Quadrants.nw: Value = 270 + Value; break;
            case Quadrants.se: Value = 090 - Value; break;
            case Quadrants.sw: Value = 270 + Value; break;
        }
        return Value;
    }
}

How can I accurately calculate when to set up IsLargeArc to get a correct result? I tried calculating the angle of the ArcSegment when it reaches 180° but I can't get a correct result.
With GetAngle I get the angle but I can't use the data correctly. How can I proceed?
Thanks for help.

A: Taking into account angle-wrapping at 360deg, try utilizing Math.Sin function as follows. By the way, the size to be handed to GetAngle should be Size(raggio * 2, raggio * 2) in this case.
double angolo = GetAngle(new Point(
      (CanvasVolume.ActualHeight / 2 + ((puntoX - halfWidth) * raggio / slashLength)) - 3.5,
      (puntoY - ((puntoY - halfWidth) * (slashLength - raggio) / slashLength)) - 3.5
    ), new Size(raggio * 2, raggio * 2)
);

// BTW, it's also possible to calculate the angle at once with the handy Math.Atan2.
// double angolo = 180.0 - Math.Atan2(puntoX - halfWidth, puntoY - halfWidth) * 180.0 / Math.PI;

myArc.IsLargeArc = Math.Sin((angolo - 113) * Math.PI / 180.0) < 0.0;// ? true : false;


text:
Q: Comment conventions in python It seems like you can use both '''comments...''' and """comments...""" for multi-line comments.  Is there any substantive difference between the two, or is it just a matter of preference?

A: These are not comments, they are docstrings. Python allows you to define multi-line strings using triplets of either apostrophes or quotation marks, but PEP 257 recommends using the quotation marks with docstrings for consistency. It has no effect on the contents of the string, however.

A: It's a matter of preference. I would say it's more common to see double quotes with triple-quoted strings, especially when they're used as docstrings, but there's no functional difference between the two.


text:
Q: Add row to nested repeater in Wordpress Advanced Custom Fields PRO I am running ACF PRO 5.3.9.2, but I think this pertains to any version with nested repeaters.  I am hoping to add rows to a nested repeater (that is a repeater inside a repeater) using the update_field() or update_sub_field() function.
The update_field() function works great for first-level repeater rows, i.e.:
update_field( $field_key, $value, $postID );

but I am uncertain about how to use this for nested repeaters.  This is the ACF Fields structure:
CUSTOM POST TYPE
    Repeater Field - "Media"
         Repeater Field - "Notes"

So, here is the code I am attempting:
$field_key = "field_xxxxxxxxxxxxx"; //NOTES FIELD KEY
$value = get_field($field_key, 12); //GET FIELDS OF POST ID 12, NOTES
$value[] = array("note" => "Here is a new note");
update_field( $field_key, $value, 12 );

But this does nothing.  There is no way to determine WHICH "Media" repeater I am wishing to add a "note" to.
I can successfully "update" the nested repeater field using update_sub_field() like the code below IF and only IF there is a row in the nested repeater field, but it overwrites just the one row and cannot add to it.  It also will not work if there isn't currently a row in the repeater.
update_sub_field( array('media', 1, 'notes', 2, 'note'), 'Here is a new note!', $postID );

What can I do to add rows to a nested repeater whether there is a row already or not?

A: I was able to accomplish this with both a combination of ACF's functions and regular good old PHP.  I can't find another method, but I read other posts where people allude to this method, although they do not elaborate or show code, so here were my long-winded steps to accomplish this:

*

*Obtain the entire array of your parent repeater

*Loop through until you hit the row with the nested repeater you want to edit

*Figure out if it is an array or not (if it isn't, make it an array)

*Append the child repeater row using array_push()

*Save the entire parent array again using update_field()
To help illustrate the parent/child relation, remember I have a repeater field called media and a nested repeater within that called notes, which only has the 1 sub-field note.  So if I use get_field('media') this is the array it would return:
Array
(
    [0] => Array
        (
          [media_title] => 'title 1',
          [notes] => Array
            (
                [0] => Array
                    (
                        [note] => 'HERE IS THE NOTE ADDED'
                    )

                [1] => Array
                    (
                        [note] => 'Here is another note added!'
                    )
            )
    )
    [1] => Array
        (
          [media_title] => 'title 2',
          [notes] =>
    )
 )

So, in this example, I have 2 elements in the parent repeater, one of which has 2 elements in the nested repeater, one that has no elements in the nested repeater.  This is important because you will need to determine if there is already an array established in the nested repeater before you can add to it.
//LOOP THROUGH PARENT REPEATER
if( have_rows('media_item', $postID) ):

    //SET YOUR ROW COUNTER
    $i = 0;

    //MAKE YOUR NEW ARRAY
    $media_item = get_field('media_item', $postID);

    while( have_rows('media_item', $postID) ) : the_row();
        if($i == $arrayRowID) { //IF THIS IS THE ROW WE WANT TO EDIT IN PARENT REPEATER
            //FIND OUT IF IT IS AN ARRAY ALREADY OR NOT
            if( !is_array($media_item[$i]['notes']) ) {  //WE DONT HAVE ANY NOTES
                $media_item[$i]['notes'] = array();
            }
            $addRow = array( //SET YOUR NEW ROW HERE
                'note' => 'This is my new note added!';
            );
            //ADD TO ARRAY
            array_push($media_item[$i]['notes'], $addRow);
        }
    $i++;
    endwhile;
endif;

So, I use $i as a counter to determine which row in the parent repeater I want.  If it was the second item in the array, $i = 1, since the array starts at 0.  You also have to feed it your post ID in this function, but hopefully it makes sense.  Be careful if you have many rows for your parent or child repeaters, as to save it, you have to overwrite the entire parent repeater array with the new one you just created:
$field_key = "field_xxxxxxxxxxxxx" //FIELD KEY OF PARENT REPEATER 'media'
update_field($field_key, $media_item, $postID);

This will save the new array with the rows you appended to your child repeater.  I hope this helps someone as I couldn't find any examples covering this method.  I would love to a function added to ACF like add_row() which works for nested repeaters!

A: This is what I made for me, I hope it will be usefull for you guys.
I made a function that takes parameters and insert inside specific post (taked by id) a repeater with his own fields and inside this repeater insert another one or more than one (because it's a repeater) subrepeater with his own fields.
So if I have something like this:
Spoiler (Repeater)
------------ Nombre Spoiler (input)
------------ Spoiler Tag (input)
------------ Enlaces (Sub-Repeater)
------------------------- Nombre Enlace (input)
------------------------- Enlace (input)
with this function I can insert X "spoiler"s and x "Enlaces"s
here the function:
function insert_field_subfield($repeater_field, $repeater_subfield, $field_values, $subfield_values, $field_key, $postid){

if(get_field($field_key, $postid)){
    $value = get_field($field_key, $postid);
}else{
    $value = array();
}
$value[] = $field_values;

if(update_field( $field_key, $value, $postid)){

    $i = 0;

    if( have_rows($repeater_field, $postid) ){

        $spoiler_item = get_field($repeater_field, $postid);
        $total_rows = count(get_field($repeater_field, $postid)) -1;

        while( have_rows($repeater_field, $postid) ) : the_row();

            if($i == ($total_rows)){

                if( !is_array($spoiler_item[$i][$repeater_subfield]) ) {

                    $spoiler_item[$i][$repeater_subfield] = array();
                }

                if (count($subfield_values) == count($subfield_values, COUNT_RECURSIVE)){ // subfield_values is not multidimensional

                    array_push($spoiler_item[$i][$repeater_subfield], $subfield_values);

                }else{ // subfield_values is multidimensional

                  foreach($subfield_values as $subfield_value){

                    array_push($spoiler_item[$i][$repeater_subfield], $subfield_value);

                  }

                }
            }
            $i++;

        endwhile;

    if(update_field($field_key, $spoiler_item, $postid)){
        return true;
    }else{
        return false;
    }

}

}else{
    return false;
}}

To call:
$addField = array("nombre_spoiler" => "Otro nombre", "spoiler_tag" => "Spoiler tag");

For one value inside subrepeater:
$addSubField = array(
'nombre_enlace' => 'Valor de un array no multidimensional',
'enlace' => 'Valor enlace');

For multiple values:
$addSubField[] = array(
'nombre_enlace' => 'multidimensional',
'enlace' => 'Valor enlace');

$addSubField[] = array(
'nombre_enlace' => '2 multidimensional',
'enlace' => 'Valor enlace 2');

And now the call:
insert_field_subfield('spoiler', 'enlaces', $addField, $addSubField, 'field_586155ce49bf8', 21267);
insert_field_subfield('spoiler', 'enlaces', $addField, $addSubField, 'field_586155ce49bf8', 21267);

I hope this will be useful for somebody!
P.S. I it's not perfect because I don't control the second repeater, but this is something that don't have ACF API.
P.S. field_key is the field key of the first repeater.

A: What did end up working for me when i had a nested repeater was to use add_row with the parent's field name as a prefix. for example when i have nested field documents inside a field builtdocuments I can use
$sub_fields = array(
    'current_document'   => "encrypted_file"
);

add_row( 'builtdocuments_document', $sub_fields);

to add to the nested repeater successfully


text:
Q: Checking if layer is visible in legend using ArcPy? I want to be able to check if a layer is visible in the legend and if so then perform another operation - in python.  I am using ArcGIS 10.2 for Desktop.
I cannot find anywhere how to check if a layer is visible or not in the legend.

A: Assuming that you mean the visibility of the layer in the Table Of Contents, once you get a reference to the layer, it has a visible attribute:
import arcpy

inMXD = "xyz.mxd"
lyrName = "layername"

mxd = arcpy.mapping.MapDocument(inMXD)
df = arcpy.mapping.ListDataFrames(mxd, "Layers")[0] #the first data frame
lyr = arcpy.mapping.ListLayers(mxd, lyrName, df)[0]
if(lyr.visible):
    print(lyr.name + " is visible")
else:
    print(lyr.name + " is not visible")

If the visibility of the layer in the Legend does not match the visibility in the Table Of Contents, you can use listLegendItemLayers ():
legend = arcpy.mapping.ListLayoutElements(mxd, "LEGEND_ELEMENT", "Legend")[0]
legendLayers = legend.listLegendItemLayers()

for idx in range(0, len(legendLayers)):
    legendLayer = legendLayers[idx]
    legendVisibility = legendLayer.visible
    if(legendVisibility == 0):
        print(legendLayer.name + " is not visible on the legend")
    else:
        print(legendLayer.name + " is visible on the legend")


text:
Q: Load only certain language files (arrays) in Laravel I wanted to know if there is any way in Laravel (7) to load only the language files of certain zones/sections. By this I mean that, for example, if a user enters in Users section, load only the "users" and "general" language files.
As far as I know, Laravel seems to always load all the files, which I consider unnecessary. Especially when the number of indexes in the arrays start to become large, I think a solution is needed in this way.
I know that in other Frameworks like CodeIngiter this option is available, but in Laravel I have searched several times for something similar and I can't find anything that solves this problem.
Thank you very much.


text:
Q: How to make asp.net web forms application faster? My last project is a medium size asp.net web forms application. It is built using:

*

*asp.net 3.5

*ling to sql dbml --> sql server database (9 tables)

*ext.net 1.6 (www.ext.net)

*structuremap 2.5.3.0

This time I believed I did my best in terms of architectural design, code and data transfer optimizations. I followed all advice I could to work with the database efficiently through linq to sql and I built layers (model, repository, service, presentation) to separate concerns and lightweight the code in the aspx code behind files.
The problem is: I've installed the application in various web hosting servers with the same pitiful result: the application is struggling to work... pages are loading like in slow motion...
In the past I would say 'OK, I didn't do all I could to speed things up' but in this case I really tried to apply the best practices...
Is there anything else I can do about it? Or is it just asp.net for really small projects only?
thank you.

A: ASP.NET is fine for building large scale websites. As Brad mentioned, StackExchange sites are built using it, and StackOverflow is a very busy site indeed.
What you need to do first is measure performance; until you do that, you're just guessing at where the problem areas are.
So start with the browser - use a tool such as Firebug, or YSLOW, Google Chrome dev tools, whatever takes your fancy and run your site using the tool enabled. The tools can let you know how long things are taking to process eg requests, how long content is taking to download etc.
YSLOW will also give you some tips on anything it finds as being a bit slow e.g. you're making to many HTTP requests, you should consider minifying your CSS/JS files. You will get a general overview of how the site is performing and where problems could be.
To dig a bit deeper, use a tool like RedGate's ANTS Profiler, use the trial version and measure your website, and server side code, with that tool. There are other tools, though I'm not aware of any free ones.

A: My first question is that when its slow. Did you try your project in Local area network. Please check first there. If there slow then you need to improve little bit.
This slow performance depends on many things
such as large data load, multiple logic on one page etc.
Please let me know.
Thanks
Basit.


text:
Q: How to compute the integral of $ \frac{\sqrt{(x^2+1)}}{x^2}$? II have spent hours trying to find the right substitution but I have had no results.
I have tried using $x=\tan u$ but it did not give the result shown in my book.

A: Using Integration by parts,
$$\int\dfrac{\sqrt{1+x^2}}{x^2}dx=\sqrt{1+x^2}\int\dfrac{dx}{x^2}-\int\left(\dfrac{d\sqrt{1+x^2}}{dx}\int\dfrac{dx}{x^2}\right)dx$$
$$=-\dfrac{\sqrt{1+x^2}}x+\int\dfrac{dx}{\sqrt{1+x^2}}$$
Hope you can take it from here!

A: As suggested in the comments, letting $x=\sinh u$ and exploiting $dx = \cosh u\, du$ as well as the identity $\cosh^2u-\sinh^2u=1$, we have
$$
\int \frac{\sqrt{1+x^2}}{x^2}dx=\int\frac{cosh^2 u}{\sinh^2u}du.
$$
Now,
$$
\coth u = \frac{\cosh u}{\sinh u}\implies \left( \coth u \right)'=\frac{\sinh^2 u - \cosh^2u}{\sinh^2 u} = 1-\frac{cosh^2 u}{\sinh^2u}.
$$
So
$$
\int \frac{\sqrt{1+x^2}}{x^2}dx = -\frac{\cosh u}{\sinh u} + u.
$$
In general, as a rule of thumb, you can think of hyperbolic functions as the natural substitution when encountering integrals of radicals of the following type
$$
\sqrt{x^2+a^2} \implies x=a\sinh u
$$
$$
\sqrt{x^2-a^2}\implies x=a\cosh u,
$$
in the same way as trigonometric functions help for radicals like
$$
\sqrt{a^2-u^2}\implies u=a\sin \theta.
$$

A: HINT:
Setting $x=\tan u$ $$\int\dfrac{\sqrt{x^2+1}}{x^2}dx =\int\dfrac{\sec u}{\tan^2u}\sec^2u\ du=\int\dfrac{du}{\cos u\sin^ 2u} =\int\dfrac{\cos u\ du}{\cos^2u\sin^ 2u}$$
Set $\sin u= v$
Hope you can take it from here!

A: $$\int \frac{\sqrt{x^2+1}}{x^2}dx$$
Apply Integration By Parts:$\:\int \:uv'=uv-\int \:u'v$
$u=\sqrt{x^2+1},\:u'=\frac{x}{\sqrt{x^2+1}},\:\:v'=\frac{1}{x^2},\:\:v=-\frac{1}{x}$
Then
$$\int \frac{\sqrt{x^2+1}}{x^2}dx=-\frac{\sqrt{x^2+1}}{x}-\int \:-\frac{1}{\sqrt{x^2+1}}dx$$
$$=-\frac{\sqrt{x^2+1}}{x}-\int \:-\frac{1}{\sqrt{x^2+1}}dx$$
Then Note:
$\int \:-\frac{1}{\sqrt{x^2+1}}dx=-arcsinh \left(x\right)$
So
$$\int \frac{\sqrt{x^2+1}}{x^2}dx=\color{red}{arcsinh \left(x\right)-\frac{\sqrt{x^2+1}}{x}+C}$$


text:
Q: Style (only) decimal of ordered list Is there anyway to bold the decimals in an ordered list using CSS only? The CMS we are using is spitting out li's with no nested p/span/header tag so I can't bold the li and reset the nested tag...
Any ideas?
thanks

A: you may use :first-line pseudo-element for the li, like
li {
  font-weight: bold;
}
li:first-line {
  font-weight: normal;
}

It works for the latest versions of modern browsers, except IE.
For IE you need to use scripting to add nested tag for the li's


text:
Q: loading-environment-modules-within-a-python-script Loading environment modules within a python script
The above solution behaves differently in the python interactive shell and within an executable python file & I need some help in understanding how to get it to work in the exe.py setting, where import statements appear not to be seeing the environment variable PYTHONPATH.
In python shell the solution allows loading of an environment module which modifies PYTHONPATH; I can subsequently import a python module from that amended PYTHONPATH. This is great functionality & exactly what I want it to do in an executable python script.
In a python script (headed #!/usr/bin/env python etc), it works OK up to and including amendment of PYTHONPATH
if 'PYTHONPATH' in os.environ: print 'PYPATH:', os.environ['PYTHONPATH']
# nothing prints

execfile('/usr/local/Modules/default/init/python.py')
module('list')
# No Modulefiles Currently Loaded.

module('load', 'my_module')
print 'loaded my_module'
# loaded my_module
module('list')
#   1) /my_module
if 'PYTHONPATH' in os.environ: print 'PYPATH:', os.environ['PYTHONPATH']
# /home/me/py/my_module

But that's as far as it works in a python.exe
Attempts to import from my_module which work OK in the python shell result in Traceback reports 'ImportError: No Module named module_1
From this I think I can conclude that python is not using or 'seeing' the amended PYTHONPATH when I run this in the python exe (but does see it when in the interactive python shell).
That's kindof where I get stuck! Any ideas? Help much appreciated. I bet there's a really simple solution I've overlooked & I'll be delighted to hear about it.
thanks & have a great day
Mat
Edit:
Some more reading around suggests that python itself adds the content of PYTHONPATH to sys.path, but this is happening in neither the interactive python shell nor when I run the python.exe.
If I use sys.path.insert(1,os.environ['PYTHONPATH']) to do this manually in the exe then I get the functionality I want

A: I think that the pythonpath is read during the initialization for adding paths in sys.path, see some examples in sys.path() and PYTHONPATH issues .
So the variable you need to update is actually only sys.path - when python is already initialized it is too late for updating os.environ['PYTHONPATH']


text:
Q: Unable to clone button with on click function with jQuery I have button to show phone number if clicked with this code:
var shortNumber = $("#phone_ch").text().substring(0,  $("#phone_ch").text().length - 12);
var onClickInfo = "_gaq.push(['_trackEvent', 'EVENT-CATEGORY', 'EVENT-ACTION', 'EVENT-LABEL', VALUE, NON-INTERACTION]);";
$("#phone_ch").hide().after('
' + shortNumber + 'X XXXXXXXX
');
$('section:has(div.price_c,div.contact_name_info,div#clickToShowPc)').addClass('xoom_c');
$("#clickToShowPc , #phone_cc").click(function() {
  $("#phone_ch").show();
  $("#phone_cc").hide();
  $("#clickToShowPc").hide();
});

And I try to clone it with this code:
$( ".phone_c" ).clone(true , true).attr('class', 'phone_c col-lg-6').appendTo( ".main-section" );

And this is the original button HTML:

    012 73962304
  01X XXXXXXXX

Show phone

The button cloned but with showing the hidden elements and If I click it it will show the hidden element on the original one.
Can some one advise me with the correct code please?
I tried to search here and I found that I need to enable the
.clone(true , true)

in my code. And also I found something about duplicating ID's but it was not clear to me and I failed to solve my problem.
Thank you

A: When you clone your div ".phone_c", you will have multiple elements with the same ID. So, when you use the DOM Selector "#phone_cc", it will select the first one because it's how it works. If you had :
<span class="phone_ch" style=...

So you could use the DOM Selector ".phone_cc" and all elements with that class will be selected.
Now, you want to show and hide only elements "near" the cloned clicked element. To do that, you will have to use classes instead of IDs.

  012 73962304

  01X XXXXXXXX

Show phone

Then try to reach the parent element to reach the children :
    var shortNumber = $(".phone_ch").text().substring(0, $(".phone_ch").text().length - 12);
var onClickInfo = "_gaq.push(['_trackEvent', 'EVENT-CATEGORY', 'EVENT-ACTION', 'EVENT-LABEL', VALUE, NON-INTERACTION]);";

$(".phone_ch").hide().after('
' + shortNumber + 'X XXXXXXXX
');

$('section:has(div.price_c,div.contact_name_info,div.clickToShowPc)').addClass('xoom_c');

$(".clickToShowPc , .phone_cc").click(function() {
  var parent = $(this).parent();
  $(".phone_ch", parent).show();
  $(".phone_cc", parent).hide();
  $(".clickToShowPc", parent).hide();
});

I hope this helps.


text:
Q: Why the operation on accumulator doesn't work without collect()? I am learning Spark and following a tutorial. In an exercise I am trying to do some analysis on a data set. This data set has data in each line like:
userid | age | gender | ...

I have the following piece of code:
....

under_age = sc.accumulator(0)
over_age = sc.accumulator(0)

def count_outliers(data):
    global under_age, over_age
    if data[1] == '0-10':
        under_age += 1
    if data[1] == '80+':
        over_age += 1
    return data

data_set.map(count_outliers).collect()
print('Kids: {}, Seniors: {}'.format(under_age, over_age))

I found that I must use the method ".collect()" to make this code work. That is, without calling this method, the code won't count the two accumulators. But in my understanding ".collect()" is used to get the whole dataset to the memory. Why it is necessary here? Is it sth related to lazy evaluation thing? Please advise.

A: Yes, it is due to lazy evaluation.
Spark doesn't calculate anything until you execute an action such as collect, and the accumulators are only updated as a side-effect of that calculation.
Transformations such as map define what work needs to be done, but it's only executed once an action is triggered to "pull" the data through the transformations.
This is described in the documentation:

Accumulators do not change the lazy evaluation model of Spark. If they are being updated within an operation on an RDD, their value is only updated once that RDD is computed as part of an action. Consequently, accumulator updates are not guaranteed to be executed when made within a lazy transformation like map().

It's also important to note that:

In transformations, users should be aware of that each task's update may be applied more than once if tasks or job stages are re-executed.

so your accumulators will not necessarily give correct answers; they may overstate the totals.


text:
Q: Scala trait composition issue I have a class which source I cannot modify:
class Foo {

  def bar() = println("bar")

}

And a trait I'd like to mix into it at runtime
trait Zee { this: Foo =>

  abstract override def bar() = {
    println("before bar")
    super.bar()
  }
}

This is throwing that bar is not a member of Object with ScalaObject
What am I doing wrong? Is it possible to achieve this without modifying Foo source?
The ultimate client code needs to look like this:
val foo = new Foo with Zee
foo.bar() // should print 'before bar' and then 'bar'

A: Your Zee trait has no super traits (except implicit inheritance from ScalaObject) thus super does not contain definition for bar and there is nothing to override or call (super.bar).
why don't you write this without self-reference?
class Foo {

  def bar() = println("bar")

}

trait Zee extends Foo {

  abstract override def bar() = {
    println("before bar")
    super.bar()
  }
}

A: You can just extends the class Foo in your trait:
trait Zee extends Foo

And your code will work.

A: your trait needs to extend foo
trait Zee extends Foo {
  abstract override def bar() = {
    println("before bar")
    super.bar()
  }
}


text:
Q: Parse Notification works on emulator but not working on real device I am working on Parse notifications..to send notifications to all users...The below code works well on emulator but the real device cannot get notifications....
Heres my code :
MainActivity.java
public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ParseAnalytics.trackAppOpenedInBackground(getIntent());
    PushService.setDefaultPushCallback(this, MainActivity.class);
    ParseInstallation.getCurrentInstallation().saveInBackground();
     }
     }

ParseApplication.java
public class ParseApplication extends Application{

@Override
public void onCreate() {
    // TODO Auto-generated method stub
    super.onCreate();
    Parse.initialize(this, "[APP ID]", "[CLIENT KEY]");
    ParseUser.enableAutomaticUser();
    ParseACL defaultACL = new ParseACL();
    defaultACL.setPublicReadAccess(true);
    ParseACL.setDefaultACL(defaultACL, true);

    ParseInstallation.getCurrentInstallation().saveInBackground();
   }

Receiver.java
public class Receiver extends ParsePushBroadcastReceiver{

@Override
protected void onPushOpen(Context arg0, Intent arg1) {
    // TODO Auto-generated method stub
    Intent i = new Intent(arg0,MainActivity.class);
    i.putExtras(arg1.getExtras());
    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    arg0.startActivity(i);

}

AndroidManifest.xml
<uses-sdk
    android:minSdkVersion="11"
    android:targetSdkVersion="11" />
 <uses-permission android:name="android.permission.INTERNET" />
  <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
  <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
  <uses-permission android:name="android.permission.VIBRATE" />
  <uses-permission android:name="android.permission.WAKE_LOCK"/>
  <uses-permission android:name="android.permission.GET_ACCOUNTS" />
  <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
  <permission android:protectionLevel="signature"
  android:name="com.example.parse.permission.C2D_MESSAGE" />
  <uses-permission android:name="com.example.parse.permission.C2D_MESSAGE" />
  <application
    android:allowBackup="true"
    android:name="com.example.parse.ParseApplication"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme"
    >
    <activity
        android:name="com.example.parse.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <service android:name="com.parse.PushService" />
    <receiver android:name="com.parse.ParseBroadcastReceiver" >
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
            <action android:name="android.intent.action.USER_PRESENT" />
        </intent-filter>
    </receiver>
    <receiver
        android:name="com.example.parse.Receiver"
        android:exported="false"  >
        <intent-filter>
            <action android:name="com.parse.push.intent.RECEIVE" />
            <action android:name="com.parse.push.intent.DELETE" />
            <action android:name="com.parse.push.intent.OPEN" />
        </intent-filter>
    </receiver>

  </application>

 </manifest>

A: You do not have subscription set. If you haven't seen it already please follow the link. Parse Android Push Tutorial
In your Application onCreate:
ParsePush.subscribeInBackground("", new SaveCallback() {
  @Override
  public void done(ParseException e) {
    if (e == null) {
      Log.d("com.parse.push", "successfully subscribed to the broadcast channel.");
    } else {
      Log.e("com.parse.push", "failed to subscribe for push", e);
    }
  }
});

As you may be creating your own sample app, pay close attention to the Manifest configuration, ensure you have right package names.
As noted in the Parse docs, they use GCM when Play-Services is available, which actual Android device will have. Where as they use persistent connection on devices without play-service ie. your emulator. Hope this helps.


text:
Q: How to paste multiline SQL statements into the sqlite3 shell I use a script to generate CREATE statements for tables and want to paste these statements into the SQLite command shell. Unfortunately it does not work as expected, because the line break seems to cause trouble.
When I copy the following example table
CREATE TABLE ExampleTable (
    columnA INTEGER,
    columnB VARCHAR(2),
    columnC INTEGER
);

into the SQLite command shell, I get this result:
sqlite>     CREATE TABLE ExampleTable (
   ...>

and the shell waits for input until I press the semicolon (;). Is this linked to the separator? I tried setting it to ';' manually but there was no effect. I would expect the shell to accept the commands regardless of the format of its input string. The very same command works for instance in the Firefox Addon SQLite Manager, also I could read them from a file. For the quick test nevertheless, I would rather just paste the CREATE statements. I am sure that is a very easy thing to do, I just could not find the proper hint. Thanks!

A: *

*Save CREATE statements to txt file

*Open database in SQLite command shell

*Use command .read file_name.txt

A: This issue is discussed in this forum.
What I've found:

*

*sqlite shell v.3.14.1 - has this issue;

*sqlite shell v.3.8.2 - don't have this issue;

*sqlite shell v.3.16.2 (the latest binary that you can download at the moment) - don't have this issue;

So you can just download the new version.


text:
Q: I want to update with string in a table with rdbms function I want to update a table with a string with randomly with selection of rows with rdbms but it gives me error of ORA-00907: missing right parenthesis.
I tried to found where is right parenthesis is missing but didn't get this please help me regarding this I am selecting same table and want to update same table column
what I did is this
UPDATE PAY_IN_OUT
SET ATT_PRESENT ='L'
WHERE EMP_CODE =
( SELECT EMP_CODE
    FROM   PAY_IN_OUT
    ORDER BY DBMS_RANDOM.RANDOM )
WHERE  rownum < 40
AND ATT_DATE BETWEEN DATE '2020-09-01' AND DATE '2021-03-31'
AND  ((TO_CHAR(ATT_DATE, 'DAY'))) != 'SUNDAY';

A: This statement would update some of the rows ATT_PRESENT to L.
MERGE INTO pay_in_out src
     USING (  SELECT 'L' AS NEW_ATT_PRESENT, emp_code
                FROM pay_in_out
               WHERE     ATT_DATE BETWEEN DATE '2020-09-01' AND DATE '2021-03-31'
                     AND ((TO_CHAR (ATT_DATE, 'DAY'))) != 'SUNDAY'
            ORDER BY DBMS_RANDOM.VALUE
               FETCH FIRST 40 ROWS ONLY) d
        ON (src.emp_code = d.emp_code)
WHEN MATCHED
THEN
    UPDATE SET src.att_present = d.new_att_present;

A: Based on your comment, you seem to want something like this:
UPDATE PAY_IN_OUT PO
    SET ATT_PRESENT = 'L'
    WHERE PO.EMP_CODE IN (SELECT PO2.EMP_CODE
                          FROM PAY_IN_OUT PO2
                          WHERE ATT_DATE BETWEEN DATE '2020-09-01' AND DATE '2021-03-31' AND
                              TO_CHAR(ATT_DATE, 'DY') <> 'SUN'
                          ORDER BY DBMS_RANDOM.RANDOM
                          FETCH FIRST 40 ROWS ONLY
                         );

In older versions of Oracle, try:
UPDATE PAY_IN_OUT PO
    SET ATT_PRESENT = 'L'
    WHERE PO.EMP_CODE IN (SELECT PO2.EMP_CODE
                          FROM (SELECT PO2.EMP_CODE
                                FROM PAY_IN_OUT PO2
                                WHERE ATT_DATE BETWEEN DATE '2020-09-01' AND DATE '2021-03-31' AND
                                      TO_CHAR(ATT_DATE, 'DY') <> 'SUN'
                                ORDER BY DBMS_RANDOM.RANDOM
                               ) PO2
                          WHERE rownum <= 40
                         );

This assumes that EMP_CODE is unique in the table.  If not, use the primary key for the comparison.

A: From all the rows in the table between 2020-09-01 and 2021-03-31 except Sundays you want to pick 39 rows randomly and set their att_present = 'L'.
Up to Oracle 11 you had to use Oracle's ROWNUM, because the standard SQL clause FETCH FIRST ROWS was not available.
update pay_in_out
set att_present = 'L'
where rowid in
(
  select random_rowid
  from
  (
    select rowid as random_rowid
    from pay_in_out
    where att_date between date '2020-09-01' and date '2021-03-31'
    and to_char(att_date, 'fmDAY', 'nls_date_language=English') <> 'SUNDAY';
    order by dbms_random.random
  )
  where rownum <= 39
);

In standard SQL there would be no guarantee that the subquery gets shuffled (because subqueries are unordered sets of data, so the ORDER BY clause can get ignored), but Oracle guarantees that, in order to make their ROWNUM method work :-)
ROWID is also Oracle specific. You can use the table's primary key instead, if you want to.

A: Since you tagged PL/SQL, you could try a programmatic approach:
declare
    rows_updated number := 0;
begin
    for r in (
        select rowid as rwd from pay_in_out sample(10)
        where  att_date between date '2020-09-01' and date '2021-03-31'
        and    to_char(att_date, 'DY', 'nls_date_language = English') != 'SUN'
        for update
    )
    loop
        update pay_in_out
        set    att_present = 'L'
        where  rowid = r.rwd;

        rows_updated := rows_updated +1;
        exit when rows_updated >= 40;
    end loop;
end;

Note that sample(10) takes a 10% sample of the table. Whether this is too small or too large depends on  how many rows are in the table. You could query user_tables.num_rows to get an approximate count and then adjust it for the number of non-Sundays in your specified date range, if your stats are not stale, or you could count them.


text:
Q: ionic3 - slow navigation after upgrade I upgraded my application to work with ionic 3 and Angular 4 and after that each navigation on my application became really slow.
My code hasn't changed. When I debugged it I saw the code is arriving at nav.push(SomePage), nothing happens for a second or so and then the page is pushed.
I didn't add support for lazy-loading.
Helppp I don't want to downgrade :(
Update
Updated my package.json to the latest ionic 3.4.0 and it didn't work.
Pleaseee helpppp

A: Found the problem and it was not due to upgrade.
https://forum.ionicframework.com/t/ionic-3-slow-navigation-after-upgrading/94494


text:
Q: Eagle printed PCB scale problem I have made a layout using eagle then save it as PDF to print a test paper before routing.

I didn't design any package its all eagle's packages.
I exported PDF as shown on the image but the problem is :
the atmega16 and l293d and even ne555 packages are all scaled down on the printed paper !
as you can see on the other image i put the real component aligned with the printed paper
 but they didn't match ?!
What did i do wrong ?

A: In order to produce scale-accurate print you need to print the drawing from Eagle. For example, in board editor go to the top menu and select File->Print.In the window that follows pick your options. Scale factor will be one by default. You can also print to PDF from there but then you'd have to be careful with PDF renderer as they all tend to rescale in order to fit the image to the page.
I always check my footprints using the above method and it proved to be quite accurate.

A: Thanks to All replies i found that printing shop was printing it wrongly they print PDF from adobe x ver. 10 without correcting the print setting
adobe has option under print -> size option  -> check Actual size

this has done the job

Thanks All.


text:
Q: how to extract string by Regex with grep? say I have a SQL.txt
select * from table1;
select a,b,c from table2 where a=1;

How can I filter the table name with the command cat SQL.txt|grep
My expected output is:
table1
table2

I'm a newbie to grep command, I appreciate for any help. Thanks.
Update
What I want is knowing how to apply the regex into grep command.
for this case, I can write the regex: from (.*?). The problem is I don't know how to use regex with grep

A: Grep simply takes a pattern and a file as arguments. As explained in man grep:
GREP(1)                          User Commands                         GREP(1)

NAME
       grep, egrep, fgrep - print lines that match patterns

SYNOPSIS
       grep [OPTION...] PATTERNS [FILE...]
       grep [OPTION...] -e PATTERNS ... [FILE...]
       grep [OPTION...] -f PATTERN_FILE ... [FILE...]

DESCRIPTION
       grep  searches  for  PATTERNS  in  each  FILE.  PATTERNS is one or more
       patterns separated by newline characters, and  grep  prints  each  line
       that  matches a pattern.  Typically PATTERNS should be quoted when grep
       is used in a shell command.

So, the general format is grep 'regex' file. So, to use your example regex, you would do:
grep 'from (.*?)' file

That won't work, however, since grep uses Basic Regular Expressions (BRE) which don't treat parentheses as special characters1 and don't understand the non-greedy (find the shortest match) *? operator. What you actually want is:
grep 'from [^[:blank:]]' file

That uses the BRE character class [[:blank:]], but negates it with the ^ ([^[:blank:]]) so that it now matches any non-whitespace character. This is still not what you need, however, since grep will return the entire matching line and not only the portion of the line which matched.
If you have GNU grep (the default on Linux), you have the -o option which tells grep to only return the matching portion:
$ grep -o 'from [^[:blank:]]*' file
from table1;
from table2

Of course, this is still not what you need, there's an extra from, a space and a trailing ; in one of them. Once more, if you have GNU grep, you can use PCRE (Perl Compatible Regular Expressions) which support lookarounds:
$ grep -oP '(?<=from )\w+' file
table1
table2

Here, the -o tells grep to only return the matching portion and the -P enables PCRE support. The (?<=from ) is called a positive lookbehind and means "only match the next part if the previous part matches from". Finally, the \w is a special PCRE class that matches "word characters": letters, numbers and _ (and a bit more, if using Unicode). As explained in man perlre:
\w        [3]  Match a "word" character (alphanumeric plus "_", plus
               other connector punctuation chars plus Unicode
               marks)

PCREs also have the nifty \K feature. This is like a lookbehind but basically means "ignore anything that matched up to here". Using that, we can simplify the regex above to:
$ grep -oP 'from \K\w+' file
table1
table2

A: Tried with AWK command with no piping ,Tested and worked fine
 awk '{for(i=1;i<=NF;i++){if($i ~ /^table/){gsub(";","",$i);print $i}}}' file

output
table1
table2


text:
Q: Convert dictionary values from list to dictionary I have a function which results
dict1 = {'2132': [{'L': {'Y': '452.2'}}, {'L': {'N': '21'}}], '2345': [{'L': {'Y': '87'}}, {'C': {'N': '56'}}, {'6': {'Y': '45.23'}}]

I have another function i need to pass 2132,L,Y values from dict1 as an arguments and it should result 452.2
def getx(a, b, c):
    try:
        return dict1[a][b][c]
    except:
        return None

when i give dict1['2132'] which results [{'L': {'Y': '452.2'}}, {'L': {'N': '21'}}]
i want dict1['2132']['L']['Y'] should result as 452.2
so i need my dictionary
dict1 = {'2132': [{'L': {'Y': '452.2'}}, {'L': {'N': '21'}}], '2345': [{'L': {'Y': '87'}}, {'C': {'N': '56'}}, {'6': {'Y': '45.23'}}]

to show as
dict1 = {'2132': {{'L': {'Y': '452.2'}}, {'L': {'N': '21'}}}, '2345': {{'L': {'Y': '87'}}, {'C': {'N': '56'}}, {'6': {'Y': '45.23'}}}

OR is there any other way that we can pull the 4th value when the dict1 is
dict1 = {'2132': [{'L': {'Y': '452.2'}}, {'L': {'N': '21'}}], '2345': [{'L': {'Y': '87'}}, {'C': {'N': '56'}}, {'6': {'Y': '45.23'}}]

A: How about this:
from collections import defaultdict
for key,values in dict1.items():
    temp_dict = defaultdict(dict)
    for val in values: #values is a list of dict
        for k,v in val.items():
            temp_dict[k].update(v)
    dict1[key] = dict(temp_dict)
print(dict1)
#{'2132': {'L': {'Y': '452.2', 'N': '21'}}, '2345': {'L': {'Y': '87'}, 'C': {'N': '56'}, '6': {'Y': '45.23'}}}

And then
def getx(a, b, c):
    try:
        return dict1[a][b][c]
    except:
        return None
print(getx('2132','L','Y'))
#452.2

A: here is your solution
#v1='2132' v2='L' v3='Y'
def Solution(v1,v2,v3):
    if v1 in dict1.keys():
        for i in dict1[v1]:
            if v2 in i.keys():
                if v3 in i[v2]:
                    return i[v2][v3]
    return None

dict1 = {'2132': [{'L': {'Y': '452.2'}}, {'C': {'N': '21'}}], '2345': [{'L': {'Y': '87'}}, {'C': {'N': '56'}},{'6': {'Y': '45.23'}}]}
print(Solution('2132','L','Y'))


text:
Q: Change on S3 object header doesn't impact on CloudFront Yesterday I went through the objects in a bucket in S3 and added this header:
Cache-Control: max-age=604800

I did it using the change metadata option, since I could apply it easily per folder:

Now if I request the image directly I see the correct header:
Cache-Control: max-age=604800
Date: Fri, 25 May 2018 11:28:53 GMT
ETag: "1abf6cb38c4645f3de14a19beba80019"
Last-Modified: Fri, 25 May 2018 11:11:11 GMT
Server: AmazonS3
x-amz-id-2: qQk8NrWHNCOV5SmLvSQGahvYKuQIkcqQdc2I4Hdm2QLGkhet8cF4n1O+c2HLxhEVl7iBReFSflo=
x-amz-request-id: 97C53C15E86CD3FF

But this is the response when I request the image through CloudFront:
HTTP/1.1 304 Not Modified
Connection: keep-alive
Date: Fri, 25 May 2018 11:28:15 GMT
ETag: "1abf6cb38c4645f3de14a19beba80019"
Server: AmazonS3
Age: 70693
X-Cache: Hit from cloudfront
Via: 1.1 1d7454c76d6ac81147ca3cbd1284c8ae.cloudfront.net (CloudFront)
X-Amz-Cf-Id: CLiExdWbIvxcBFcoND6JYjcKQj54QyQkWl48OyPpUPLupHZl8SPfPQ==

My intention when adding this header was to improve the results on Pingdom for Leverage browser caching, but I still get the urls coming form this bucket through CloudFront listed in that section:
https://d253b1eioa5z7b.cloudfront.net/bc_video_ ... 6_9_576_67de5812-fd82-4476-8b3f-886ad3a4907d.png
https://d253b1eioa5z7b.cloudfront.net/bc_video_ ... 6_9_576_a7ddd1ed-0913-41f6-927e-9db33b582a89.jpg

When I did this same thing to other objects in S3 that I use directly from the website (without CDN) I noticed the effects on the Pingdom results immediately.
Should I wait? Or am I doing something wrong here?

A: The Cache-Control changes you are making in S3 are not updated in CloudFront.  To push your updates to CloudFront, you need to update your Web Distribution in CloudFront and change the setting Use Origin Cache Headers (see image).

This is per the AWS documentation for CloudFront that details the values you can specify when updating a CloudFront Web Distribution - under the Object Caching header.
To make this change, use the steps discussed in AWS page with details on how to Update a Web Distribution with the CloudFront console, and pay close attention to the third bullet under step 5:  Cache behavior settings.  This is where you get to the screen shown above and can make the "Use Origin Cache Header" change.
Try it out and see if your Pingdom results improve.


text:
Q: Entity Framework select from a list of ids obtained from another E.F select query
I'm trying to get ItemsEntity from a E.F query with a where statement. The condition gets item_id from another E.F query which returns more than 1 item_id.
var item_id = (from n in db.OrderDetail where n.OrderId == id select n.item_id);
var itemEntity = (from m in db.ItemsEntity where *m.item_id==item_id* select m);

A: You can use Contains method when you want to use a collection in your Where clause
var listOfIds = (from n in db.OrderDetail where n.OrderId == id select n.item_id);
var itemEntity = (from m in db.ItemsEntity where listOfIds.Contains(m.item_id) select m);

Keep in mind that, with the above code, itemEntity variable will be collection. If you want single item, Use methods like FirstOrDefault() or First() as needed.
The above code can be written as a LINQ method chain as below as well
var listOfIds = db.OrderDetail.Where(n=>n.OrderId == id).Select(x=>x.item_id);
var itemEntity = db.ItemsEntity.Where(m=>listOfIds.Contains(m.item_id));

A: Use First() or FirstOrDefault() at the end of first statement to make item_id variable an actual int type, not IQueriable as it is now.


text:
Q: How to wait until list is not empty? - Flutter futures This is my home screen code:

class HomeScreen extends StatelessWidget {

  @override
  Widget build(BuildContext context) {

    final enterpriseProvider = Provider.of<EnterpriseProvider>(context);
    final resp = enterpriseProvider.indicator;
    final List<IpcData> data = createIpcList(resp);

    print(data);

    return Scaffold(
      appBar: AppBar(
        title: Text('Hola'),
      ),
      body: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Expanded(
            child: Container(
              child: ResultList( formattedData: data )
            ),
          ),
        ],
      )
    );
  }

  createIpcList(List<List<dynamic>> resp) {

    List<IpcData> ipcList = resp.map((e) => IpcData(e[0], e[1])).toList();
    return ipcList;

  }

}

What happens is that the 'resp' value comes from an http request. So when I first call createIpcList(resp); it returns an empty list. The problem here is that the ResultList widget that I use in the Scaffold that´s returned uses that data to build a chart. When I load the app, the chart is blank, as if no data was passed. I noticed that when I make a Hot Restart, it prints an empty list, but some seconds later, it prints the data, as if I called the print again. The problem is that the chart stays blank. I would like to put a condition so if data =! [] it returns me the Scaffold and if not, it returns a loading screen. I know that this can be achieved with Futures, but i don´t know how. I would like to return the Scaffold once I have the data, otherwise my chart will always be empty.

A: For this you've to use a FutureBuilder widget
FutureBuilder(
    future: createIpcList(resp),
    builder: (context, snapshot){
        if (snapshot.hasData)
            return ResultList(formattedData: snapshot.data);
    }
);

If you want you can show a loading indicator while the data is being fethced from the server.


text:
Q: Circular UIScrollView in iPhone I want to implement a UIScrollView that has a circular shape in iPhone, kindly guide me so that I can make it possible.

A: It's easy! Make a UIScrollView that is a perfect square, then do this:
#import <QuartzCore/QuartzCore.h>

scrollView.layer.cornerRadius = scrollView.frame.size.width/2;
I might have my math wrong... I can't test it right now. If it doesn't look right, just fiddle with that cornerRadius property and you'll have a circle in no time :)

A: The strategy I would take is to duplicate the first view and make it also the view after the last view. Once that "fake" first view is shown, shift all the subviews so that the real first view is where the "fake" first view was. Your users won't even know you switched.
Hope this helps!

A: Have a look at this link.It will serve your purpose...
Yu can also download the sample code from there for better understanding...
Cheers


text:
Q: Statistics-Math-Probability An urn is filled with 10 green balls, 4 red balls, and 2 orange balls.  Three balls are selected without replacement.  Calculate the following probabilities:
(a) P(at least one ball is red)
I think the answer is: (4/16)(3/15)(2/14) = .007 or 1/140
(b) P(exactly one ball is orange)
I think the answer is: (2/16)(14/15)(13/14) + (14/16)(2/15)(13/14) + (14/16)(13/15)(2/14) = 13/40 or .325
(c) P(at most one ball is green)
(d) P(neither ball is red)

A: For part (a), I would calculate the probability that $no$ red ball is selected, and subtract the result from one.
For part (b), you are correct, but notice that your three terms are equal. Why is this? Try to find the pattern and generalize it.
For part (c), you can take the sum of $P$(exactly one ball is green), whose calculation mirrors that of part (b), plus $P$(no ball is green), whose calculation mirrors that of part (a).
For part (d), you just need to find P(no ball is red), which you should be able to recycle from part (a).

A: Answer:
Total number of ways you can select 3 balls = ${16\choose3}$
Part a) $$=1-\frac{{12\choose3}}{{16\choose3}} = 0.6071$$
Part b)$$=\frac{{2\choose1}{14\choose2}}{{16\choose3}}=0.325$$
Part c) $$=\frac{{10\choose0}{6\choose3}+{10\choose1}{6\choose2}}{{16\choose3}}=0.3035$$
Part d) $$=\frac{{12\choose3}{4\choose0}}{{16\choose3}}=0.39285$$


text:
Q: Angularjs ng-repeat filtered by one property, property duplicate issue I want to filter my array by teams and show all players in each team, but if the name of the team is similar eg. 'team beta' and 'team beta z' duplicate problem occures.
Player is shown in both teams...
here is example code:
https://jsfiddle.net/lukasz9999/qpqsuvc5/1/
I think problem lays in filtering method

   {{playerPerTeam.team}}

{{player.name}}

$scope.players = [{name: 'Gene', team: 'team alpha'},
                {name: 'George', team: 'team beta'},
                {name: 'Steve', team: 'team gamma'},
                {name: 'Paula', team: 'team beta'},
                {name: 'Paula2', team: 'team beta z'},
                {name: 'Scruath of the 5th sector', team: 'team gamma'}];

var indexedTeams = [];

$scope.playersToFilter = function() {
    indexedTeams = [];
    return $scope.players;

}

$scope.filterTeams = function(player) {

    var teamIsNew = indexedTeams.indexOf(player.team) == -1;
    console.log("nt "+teamIsNew)
    if (teamIsNew) {
        indexedTeams.push(player.team);
    }
    return teamIsNew;
}

*

*this code produces this list:

*team alpha

*

*Gene

*team beta

*

*George

*Paula

*Paula2

*team gamma

*

*Steve

*Scruath of the 5th sector

*team beta z

*

*Paula2

name: Paula2 should be only in "team beta z" but is in "team beta" as well.
thank you for any advices

A: You have to use track by $index at the end of the ng-repeat="" that you use.
By doing this, angular identifies the elements with their index in the array, instead of their value.
Example:
ng-repeat="playerPerTeam in playersToFilter() | filter:filterTeams track by $index"

A: Putting true just after the filter statement would do the trick. So,
filter:{team: playerPerTeam.team}

should be
filter:{team: playerPerTeam.team}:true

for exact match. https://docs.angularjs.org/api/ng/filter/filter
You can see the plunker


text:
Q: Android Google Maps Library freezes on General Mobile Discovery I'm trying to add google maps library to my project. Everything perfectly running on Samsung devices or HTC devices or Sony devices and I can see the map on this devices without any problem. But the map does not shown on General Mobile Discovery and freezes after bottom left corner google icons become visible.
When I try to open my project on GM Discovery App freezes and getting this error on the console and a few minutes later App gives warning "Application not responding"
Is there anybody know why I can't use google maps library on GM Discovery?
12-25 16:26:36.437 5093-5093/com.my.package E/dalvikvm: Could not find class 'android.app.AppOpsManager', referenced from method com.google.android.gms.common.nb.a
12-25 16:26:36.650 5093-5093/com.my.package E/dalvikvm: Could not find class 'android.app.AppOpsManager', referenced from method com.google.android.gms.common.mw.a
12-25 16:26:37.350 5093-6366/com.my.package E/NativeCrypto: ssl=0x606b4488 cert_verify_callback x509_store_ctx=0x62deaab0 arg=0x0
12-25 16:26:37.352 5093-6366/com.my.package E/NativeCrypto: ssl=0x606b4488 cert_verify_callback calling verifyCertificateChain authMethod=ECDHE_ECDSA
12-25 16:26:37.663 5093-6394/com.my.package A/libc: @@@ ABORTING: LIBC: ARGUMENT IS INVALID HEAP ADDRESS IN dlfree addr=0x64be1a48
12-25 16:26:49.647 5093-5098/com.my.package E/dalvikvm: Fatal spin-on-suspend, dumping threads

A: I have the same issue. After long searching I have found a solution, but I dont know how it should be implemented. PLease see it : Fatal error with google Map v2 on Android 4.2.2

A: The bottom line of the issue is Fatal spin-on-suspend, dumping threads. You can find the detailed explanation in this link.

Some devices use a vendor-modified version of Dalvik that gets this wrong, and aborts can happen on tight loops. I wouldn't expect to see a native method at the top of the stack in this case.