text:
Q: Why wasn't Superman naked when he was lifting Luthor's artificial continent? In the end of Superman Returns, Superman entered the hot magma below the artificial continent to lift it up. Why wasn't Superman's costume burned up due to the tremendous heat of the magma? I think, Superman's powers aren't automatically inherited by his costume.

A: Let us not forget about the aura around Superman that helps protect his clothes (everything, that is, except his cape). According to Ma Kent, young Clark's regularly worn clothes stayed extra clean and surprisingly undamaged, especialy when you consider the fact that the kid wearing them was indestructable. His Supersuit has the benefit of being Kryptonian and of being worn by Superman.

A: Same reason the Hulk is still wearing his trousers:  Having your movie rated PG-13 or higher is going to hurt the box office takings...

A: His suit is made from the blanket which he was wrapped in when he first landed on Earth. It's alien properties make it nigh indestructible.
Additionally, the faq on imdb for the movie states:

In the original Superman movies, based on the silver age comic book superhero, Superman's costume was woven from blankets that arrived with him in the rocket that brought him from Krypton.
Under the Earth's yellow sun, they became invulnerable, just as he does.

And from the wikipedia of Superman Returns:

The film serves as an alternate sequel to Superman (1978) and Superman II (1980).

So the explanation for the suits invulnerability was already given in the previous movies.

A: Each version of Superman had a different origin and advantages. In the early versions of the character, all things Kryptonian acquired an indestructible nature under a yellow sun. It didn't matter if they were living or not, they simply could not be destroyed by anything made on Earth. This included his ship and his swaddling cloth/blankets.
Martha Kent was said to have unwoven the fabrics he was wrapped in and rewoven them into his only costume. The costume was indestructible except to Kal-El's heat vision, which was how she was said to have cut the material, when necessary. Later editors/versions tailored the legend as they saw fit. See: How did Martha Kent modify the Kryptonian Blanket that became Superman's costume?
Golden Age Superman, Earth-2, Pre-Crisis

*

*Kryptonians had superpowers, even on Krypton. Krypton was a super-large, high gravity world. Kryptonian science far exceeded anything on Earth.

*Everything Kryptonian that came to Earth became virtually indestructible due to an interaction with the energy of the yellow sun

*Martha Kent unwove the Kryptonian fabric and rewove it into his costume. It was indestructible, didn't get dirty or torn and neither did his cape. She also created the S-shield.

*Superman debuts as an adult Superman in Action Comics #1.

*Power Girl was considered to be the only other survivor of Krypton on Earth-2. Later retconned out of Superman's continuity. Recently retconned back into continuity as a Kryptonian from another universe.

Silver Age Superman, Pre-Crisis

*

*First reboot of Kryptonians, they had no superpowers except under a yellow sun. Krypton was a super-large, high gravity world. Kryptonian super-science far exceeded anything on Earth. Jor-el could see the Earth from Krypton.

*Everything Kryptonian that came to Earth became virtually indestructible due to an interaction with the energy of the yellow sun.

*Krypton's destruction came with a variety of versions of Kryptonite. One type was created artificially when the Green Kryptonite was affected by a crimson energy cloud making it turn red. Other colors included, white, blue, gold and crystalline.

*Martha Kent unwove the Kryptonian fabric and rewove it into his costume. It was indestructible, didn't get dirty or torn and neither did his cape. She also created the S-shield.

*His cape had special properties and could be used to protect people from environmental hazards. He used it to protect travelers he would fly to his Fortress of Solitude in the Arctic.

*Superman has his powers from childhood and has a career as a young superhero named Superboy.

*Krypton is destroyed, Kal-El was initially believed to be the only survivor. The only other survivors were the Phantom Zone villains. Later it was discovered, Argo City and various animals also survived (and gained superpowers as well).

*This is the Superman most associated with the movies, including Superman Returns. His costume is completely indestructible just like he was.
Modern Age, Post-Crisis, Man of Steel Superman

*

*Krypton was an Earth-sized world with technologically advanced humanoids.

*Kryptonians were trapped on their world due to a genetic technology preventing them from leaving.

*Jor-El modifies Kal-El to allow him to leave and come to Earth.

*Krypton is destroyed by a weapon which introduces instability in the core of the planet. There is only Green Kryptonite.

*Kal-El does not have a history where he becomes Superboy.

*Kal-El's power develop slowly until he reaches maturity.

*His costume is not indestructible, nor is his cape. His suit has no special properties, instead he is surrounded by a skintight, invisible force field which gives him the appearance of invulnerability. This field protects his costume and close fitting clothing but does not protect his cape.


text:
Q: Qhull Convex hull wants me to input at least 3 points
Update: I've decided to try to use a linear programming package in order to determine if the vertices of the two polytopes are linearly separable. (The vertices are really my data, not the polytopes.) I think this will work better, so I no longer need an answer to this question.

I'm writing some code that involves checking if certain polytopes are disjoint. These polytopes are defined by the convex hulls of their vertices, and I'm creating the convex hulls using Qhull. In particular, I'm using the method:
from scipy.spatial import ConvexHull

This works fine, except that sometimes my sets have only 2 or 1 points in them. Qhull doesn't like this, and it spits out this error:

QhullError: QH6214 qhull input error: not enough points(1) to construct initial simplex (need 3)
While executing:  | qhull i Qt
  Options selected for Qhull 2015.2.r 2016/01/18:
   run-id 109084531  incidence  Qtriangulate  _pre-merge  _zero-centrum

While I can deal with this by writing some subroutines that catch the situation that there are less than 3 points, it's frustrating that Qhull doesn't deal with this case. So I'm looking for:
1) A simple way to make Qhull deal with this correctly
or
2) An alternative package to use
Thank you!

A: QHull doesn't really have to handle the polytopes of one or two vertices (or d-1 vertices in dimension d) as they are perforce their own convex hulls (and they are simplices).
Check for a low number and transfer the input to the output.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Problems with SQL Server 2014 CTP 1 installation I tried to install 2014 version a week ago but ended up with some conflicts. Today I tried to install 2012 instead, but when I ran installation, bootstrap did extract 2012 files but then , for some reason, 2014 installation was started. Is there any way to clear the cache or something?

A: I removed this folder C:\Program Files\Microsoft SQL Server\110\Setup Bootstrap. It said SQl server 2012 but it was actually 2014 and installation worked this time


text:
Q: Second order differentiability of subharmonic function almost everywhere? The following general definition of subharmonic function comes from the classical text book [elliptic partial differential equations of second order] by Gilbarg and Trudinger.
We call a function $u$ subharmonic in $\Omega$ if $u \in C^0(\Omega)$ and for every ball $B \subset \subset \Omega$ and every function $h$ harmonic in $B$ satisfying $u \le h$ on $\partial B$, we also have $u \le h$ in $B$.
It is known by Aleksandrov's theorem that convex function has second derivatives almost everywhere, and convex function is subharmonic, so I wonder whether one can prove that a subharmonic function also has second derivatives almost everywhere. Notice that a subharmonic function need not to be convex, for example in $\mathbb{R}^2$, consider $u(z)=log|z|$.
If it is impossible to prove the existence of second derivative, what if we add more conditions on the subharmonic function, for example, we require $u$ to be $W^{1,2}$?  The motivation to ask this question is that, in this case, $\lambda:=\Delta u$ would be a positive Radon measure, then I can prove that for almost every $r>0$ such that $B_r \subset \subset \Omega$, $$\int_{B_r} d\lambda = \int_{\partial B_r} \nabla u \cdot \nu $$where $\nu$ is the unit outer normal. The formula above looks very like the trace theorem for BV functions if thinking $\nabla u$ as a BV vector. In philosophy, if trace theorem is true for a function $u$, then $u$ must have one more derivative in some sense.
Disregarding the further condition for $u$, I think the first claim should be provable by adapting the proof of Aleksandrov's theorem, but If it is a known result, I would like to just accept it without doing by myself.
Any comments or ideas would be really appreciated.

A: Almost everywhere is too strong, but a Lusin-like theorem holds true :
Let $u$ be a subharmonic function in a domain $D\subset\mathbb{R}^n$,
$K\subset D$ a compact set, and $\epsilon>0$. There exist an open set $G_\epsilon$ whose Lebesgue measure is less than $\epsilon$ and a twice continuously differentiable function $f$ such that the restriction of $f$ to $K\setminus G_\epsilon$ coincides with $u$.
This was proved in

S. A. Imomkulov, Twice differentiability of subharmonic functions,
  Russian Acad. Sci. Izv. Math. 41 (1993), no. 1, 157–167

By the way, the above result was also recently mentioned (as an example of an unknown theorem) here:
https://mathoverflow.net/q/296845

A: In fact a weaker version of Aleksandrov's theorem is true for subharmonic functions. Since $\Delta u$ is a Radon measure, the following result follows from Proposition 4.4 in 1.

Theorem. If $u:\Omega\to\mathbb{R}$ is subharmonic and locally integrable, then
for almost all $x\in\Omega$ there exist a vector $Du(x)$ and a matrix $D^2u(x)$ such that
for all $1\leq p<n/(n-2)$ ($1\leq p<\infty$, if $n=2$)
$$
\left(\frac{1}{|B(x,r)|}\int_{B(x,r)}|u(y)-u(x)-Du(x)(y-x)-\frac{1}{2}(y-x)^TD^2u(x)(y-x)|^p\right)^{1/p}\\=o(r^2).
$$

Although it is not stated in [AG] that the matrix $D^2u(x)$ is symmetric, you can always assume that since it appears in a quadratic form and in a quadratic form you can always replace a matrix by a symmetric one since
$$
\langle Ax,x\rangle=\big\langle\frac{1}{2}(A+A^T)x,x\big\rangle.
$$
As a corollary, the authors prove Imomkulov's theorem (see the answer of user111), but they do it independently (21 years later!) since they do not quote the work of Imomkulov.
If you want to compare it with the statement of Aleksandrov's theorem, see Second order differentiability of convex functions and Aleksandrov's proof of the second order differentiability of convex functions.
[AG] G. Alberti, S. Bianchini, C. G. Stefano, On the $L^p$-differentiability of certain classes of functions . Rev. Mat. Iberoam. 30 (2014), no. 1, 349–367.
MathSciNet


text:
Q: How do I dial 1 (one) in a Skype call on Linux? When you dial a Skype username with blogtalkradio it asks you to press 1 to talk to a host. You can see this behavior by trying any number on blogtalkradio. How do you press one in Linux? Skype for Linux is now up to version 4.0.0.8. Does it have this functionality?

A: Interestingly, this question was asked on October 28 by me. Merely 17 days later Skype would react to community demand and put out a new version 4.1 which fixed this problem.
User interface tweaks to improve the experience

We have tweaked the user interface a bit to improve the experience. The tweaks include:

*

*Hotkey "d" added to invoke dialpad during Skype-to-Skype and conference calls

*Pressing ESC will now exit full screen call view

*Notification of unread messages in middle of the call

*Differentiate between local and remote holding of call

Kudos to Skype, find Skype 4.1 here, and find the blog entry of the 4.1 Linux change set here.


text:
Q: How to add Owl-Carousel-2 completeness percent(%) status bar(not progressBar)? First of all this is not about "progressBar", I need a completeness percent(%) status bar for owlCarousel-2, if there is any confusion in my question and description then please check the images below.
I have just created a pen, please check the link - https://codepen.io/tsarkar/pen/NmpGmV

(source: testyourprojects.biz)
I just have complete with "Total Item count" and "Current item count", but can't implement the status(%) bar like the images I have posted. Please check my code below.
$(function(){
var owl = $('.ivySlide');
$('.ivySlide').owlCarousel({
  smartSpeed: 500,
  items: 1,
  margin:0,
  nav:true,
  dots:false,
  onInitialized:counter,
  onTranslated:counter
});
function counter(event) {
  var element = event.target;
  var items = event.item.count;
  var item = event.item.index + 1;
  var sldtxt = $('.active .ivySlideTxt').html();
  $('#counter').html(item+" / "+items)
}
});

A: Finally I have got the solutions for this, please check the code below and also the pen.
$(function(){
$('.ivySlide').owlCarousel({
  smartSpeed: 500,
  items: 1,
  margin:0,
  nav:true,
  dots:false,
  onInitialized:counter,
  onTranslated:counter
});
function counter(event) {
  var element = event.target;
  var items = event.item.count;
  var item = event.item.index + 1;
  var sldtxt = $('.active .ivySlideTxt').html();
  var sldWidth = 100;
  var sldPercent = sldWidth * item / items;
  $('#counter').html(item+" / "+items)
  $('.slTxt').html(sldtxt);
  $('.slideState span').css("width", sldPercent + "%");
  $('.slideState span').html(sldPercent + "%")
}
});

You can check my solution here https://codepen.io/tsarkar/pen/NmpGmV


text:
Q: UIAlertController (UIAlertControllerStyleActionSheet) with iOS 7 In iOS 8 to get add photo alert functionality, I do:
UIAlertController * view=   [UIAlertController
                             alertControllerWithTitle:nil
                             message:nil
                             preferredStyle:UIAlertControllerStyleActionSheet];

UIAlertAction* choosePhoto = [UIAlertAction
                     actionWithTitle:@"Choose Exisiting"
                     style:UIAlertActionStyleDefault
                     handler:^(UIAlertAction * action)
                     {
                         [self selectPhoto];

                     }];
[view addAction:choosePhoto];
...

How can I do the same thing in iOS7?
UIAlertController does not work with iOS7.1 and UIAlertView does not provide such functionality.

A: As requested above, I answer my own question:
- (void)updateWithActionSheet:(BOOL)isNew
{
    NSString *destructiveButtonTitle  = nil;
    if (!isNew) {
        destructiveButtonTitle = @"Delete it";
    }

    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil
                                                             delegate:self
                                                    cancelButtonTitle:@"Cancel"
                                               destructiveButtonTitle:destructiveButtonTitle
                                                    otherButtonTitles:@"Choose Exisiting", @"Take Photo", nil];

    [actionSheet showInView:self.view];
}

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSString *buttonTitle = [actionSheet buttonTitleAtIndex:buttonIndex];
    if ([buttonTitle isEqualToString:@"Cancel"]) {
        [self.firstNameTextField becomeFirstResponder];
    }
    if ([buttonTitle isEqualToString:@"Choose Exisiting"]) {
        [self selectPhoto];
    }
    if ([buttonTitle isEqualToString:@"Take Photo"]) {
        [self takePhoto];
    }
    if ([buttonTitle isEqualToString:@"Delete it"]) {
        [self deletePhoto];
    }
}


text:
Q: help for custom spinner? i am getting error while using the custom class for spinner from below link.
How to make an Android Spinner with initial text "Select One"
can anyone suggest me how can i use it
thankx

A: If you are trying to have first item not being selected automatically, then I have answered that query in detail here with code snippets.


text:
Q: Prevent caching of a single js file I have a .js.erb file in my assets directory. This reads some locale specific config.
However when the underlying config changes the new file is not being served to my browser. I get 304 not modified.
If I change the .js.erb file by adding white space the new file is correctly served. Doing that each time I add config would be a pain.
Is there a way to configure rails just to not cache this particular file?
Thanks for any suggestions.
Edit: Done a bit more reading on the asset pipeline
"Assets are compiled and cached on the first request after the server is started. Sprockets sets a must-revalidate Cache-Control HTTP header to reduce request overhead on subsequent requests — on these the browser gets a 304 (Not Modified) response.
If any of the files in the manifest have changed between requests, the server responds with a new compiled file."
So the problem here is the first request is cached - this is a dynamic javascript file. Is perhaps the only way to prevent this being cached to inline the javascript??

A: It sounds like you don't want to use the asset pipeline, which is trying very hard to promote caching.
Rather than trying to fight the asset pipeline, create an actual controller and then you'll be able to set the cache control headers to your liking.
If you have a js.erb template in app/views/controller_name then rails should just render it.
For example if you had a controller called JsController you could add
match '/javascripts/settings.js', :controller => :js, :action => :settings, :format => :js, :as => :setting_js

to your routes.rb file and then stick settings.js.erb in app/views/js
You can then link to it with
= javascript_include_tag settings_js_path

A: Have you tried something like this in the controller method that serves that file?
response.headers["Last-Modified"] = Time.now.httpdate
response.headers["Expires"] = 0
response.headers["Pragma"] = "no-cache"
response.headers["Cache-Control"] = 'no-store, no-cache, must-revalidate, max-age=0, pre-check=0, post-check=0'


text:
Q: Node module based on C++ I just wrote my own node module in C++ with the help of node-gyp. Now I have the following question.
If I want to publish my project now, what has to be in the package.json and can a user install my npm package if he has no Visual Studio (msbuild.exe) installed. Has he recompile it? And if yes, that doesn't really make sense. He should use the binaries only. But how can I achieve this?
Yeah, that are a lot of questions =)
FYI, here is my project: https://github.com/frankred/node-mouzy
Here is my package.json: https://github.com/frankred/node-mouzy/blob/master/package.json
Via the GIT-Repo I only can install the npm package with the following command:
npm install -S "git+https://github.com/frankred/node-mouzy.git"


text:
Q: How to calculate column-wise variance sorting by another variable in R? I have a data frame in this structure, Id represents different people, and they are repeatedly measured in a variable called the Intensity.
Sample data:
Id    intensity
1     11
1     9
1     6
1     7
2     4
2     6
3     8
3     8
3     9
4     3
4     6

I want to calculate the variance of intensity for each Id in R, but I have no idea which function I should use. I visited few sites/googled for an answer, find nothing.
Could anyone help me with that? Thanks a lot!

A: Using base R
aggregate(df$intensity, by=list(df$id), FUN=var)
  Group.1         x
1       1 4.9166667
2       2 2.0000000
3       3 0.3333333
4       4 4.5000000

By dplyr
library(dplyr)
group_by(df, id) %>% summarise(variance =var(intensity))
     id variance
  <dbl>    <dbl>
1     1    4.92
2     2    2
3     3    0.333
4     4    4.5

Data
df = data.frame('id' = c(1,1,1,1,2,2,3,3,3,4,4),
                'intensity' = c(11,9,6,7,4,6,8,8,9,3,6))


text:
Q: overflow 99788px on right My code:
```flutter
Widget _buildActionForTask(TaskInfo task) {
if (task.status == DownloadTaskStatus.undefined) {
  return new RawMaterialButton(
    onPressed: () {
      _requestDownload(task); /*download button*/
    },
    child: new Icon(
      Icons.file_download,
      size: 30,
    ),
    shape: new CircleBorder(),
    constraints: new BoxConstraints(minHeight: 32.0, minWidth: 32.0),
  );
} else if (task.status == DownloadTaskStatus.running) {
  /*there is my stuck*/
   return new RawMaterialButton(
    onPressed: () {
      _pauseDownload(task); /*pause button*/
    },
    child: new Icon(
      Icons.pause,
      size: 30,
      color: Colors.white,
    ),
    shape: new CircleBorder(),
    constraints: new BoxConstraints(minHeight: 32.0, minWidth: 32.0),
  );
} else if (task.status == DownloadTaskStatus.paused) {
  return new RawMaterialButton(
    onPressed: () {
      _resumeDownload(task); /*resume button*/
    },
    child: new Icon(
      Icons.play_arrow,
      size: 30,
      color: Colors.green,
    ),
    shape: new CircleBorder(),
    constraints: new BoxConstraints(minHeight: 32.0, minWidth: 32.0),
  );
}

Here is my appbar:
appBar: AppBar(
      title: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          Text("Image ${this.widget.index}"),
          Builder(
            builder: (context) => _isLoading
                ? Center(
                    child: CircularProgressIndicator(),
                  )
                : _permissionReady
                    ? _buildActionForTask(taskInfo)
                    : FlatButton(
                        onPressed: () {
                          _checkPermission().then((hasGranted) {
                            setState(() {
                              _permissionReady = hasGranted;
                            });
                          });
                        },
                        child: Text(
                          "Thử lại",
                          style: TextStyle(
                              color: Colors.white,
                              fontWeight: FontWeight.bold,
                              fontSize: 20.0),
                        )),
          )
        ],
      ),
      flexibleSpace: GradientBar(),
    ),

I am creating a function to download. After I hit the download button, it encountered this error. Download and delete buttons are displayed normally.
I tried many ways but still got that error. I still don't know how it can overflow 99788px?

A: Don't use a Row inside title, try using just the text widget and move the other widgets (, the one inside builder) to the action parameter, it accepts a list of widgets to the right of the appbar

A: Try wrapping your button with a Container and giving it fixed width.
You can also try to give fixed width to your constraints


text:
Q: Matlab plotting with lines of my X Y dataset For example I have an x values and y values like this :
x = [0.5 , 1.5 , 2.5];
y = [3, 6, 9];

And I want to draw a graph like below. (Red lines and spesific red values on axis are important for me, scale of axis doesnt matter)

I am searching for a while but no luck. How can i do that.

A: Try this. Note that x and y are assumed to be row vectors.
stem(x,y,'r');                             %// plot vertical lines with circles
hold on                                    %// keep current graph; more will be added
plot([zeros(1,numel(x)); x], [y; y], 'r')  %// plot horizontal lines
set(gca, 'xtick',sort(x), 'ytick',sort(y)) %// set ticks on x and y axes
axis([0 6 0 10])                           %// set axis size

A: The code below will pull the automatic x-axis and y-axis labels and add in any additional unique (not already included) axis labels for the lines that you've specified.  IT will also plot any arbitrarily large data set provided.
clc; clear; clf; % // preamble to clear previous data and plots

x = [0.23 , 1.5 , 2.5];
y = [3, 4.5, 9];

hold on
    for i=1:numel(x)
        plot([x(i),x(i)],[0,y(i)],'-r');  % // plots vertical lines
        plot([0,x(i)],[y(i),y(i)],'-r');  % // plots horizontal lines
    end
    scatter(x,y,70,'r','MarkerEdgeColor','r','MarkerFaceColor','w')
hold off

axis([0 max(x)+1 0 max(y)+1]); % // changes axis to be [0 1+max(x)] and [0 1+max(y)]

XTickAutomatic=get(gca,'XTick'); % // retrieves current x-axis tick marks
YTickAutomatic=get(gca,'YTick'); % // retrieves current y-axis tick marks

set(gca,'XTick',sort(unique([XTickAutomatic,x]))) % // create new ticks marks with any unique x-coordinates
set(gca,'YTick',sort(unique([YTickAutomatic,y]))) % // create new ticks marks with any unique y-coordinates


text:
Q: Read xml nodes to dataset, edit values of descendants and save (Visal Studio) - reopen This is my sample.xml file. I'm looking for instruction how to read this and put content from all nodes (subnodes) to DataSet and show it in DataGrid. I can only read single Node (without subnodes).
My code is below:
Private Sub ReadXmlButton_Click() Handles ReadXmlButton.Click

    Dim filePath As String = "C:\Path\"
    DataSet.ReadXml("C:\Path\sample.xml")

    DataGridView1.DataSource = DataSet
    DataGridView1.DataMember = "CART_ID"
End Sub

But it reads only head Node without SubNodes (1000, 10.05, YES, 8, 2). I want to display all informations (example: 1000, 10.05, A1A, Triangle, 10, 1, YES, 8, 2) from first (and all)CART_ID in DataGridView.
My result:

Expected result:

sample.xml
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <XML_FILE>
        <typ>xml</typ>
        <ID>
            <NR>007</NR>
        </ID>
        <PERSONAL>
            <Surname>John</Surname>
            <Name>Smith</Name>
        </PERSONAL>
        <COUNTRY>
            <CName>UK</CName>
        </COUNTRY>
          <CITY>
            <TOWN>
                <TOWN_ID>
                    <PART_ID>
                        <CART_ID>
                            <SIMPLE_ID>1000</SIMPLE_ID>
                            <SIMPLE_AREA_ID>10.05</SIMPLE_AREA_ID>
                            <PLACE_ID>
                                <SPECIFIC_ID>
                                    <id>A1A</id>
                                    <name>Triangle</name>
                                    <area>10</area>
                                    <note>1</note>
                                </SPECIFIC_ID>
                            </PLACE_ID>
                            <Control>YES</Control>
                            <Control_area>8</Control_area>
                            <Control_rest>2</Control_rest>
                        </CART_ID>
                              <CART_ID>
                            <SIMPLE_ID>2000</SIMPLE_ID>
                            <SIMPLE_AREA_ID>20.05</SIMPLE_AREA_ID>
                            <PLACE_ID>
                                <SPECIFIC_ID>
                                    <id>B1B</id>
                                    <name>Triangle</name>
                                    <area>20</area>
                                    <note>2</note>
                                </SPECIFIC_ID>
                            </PLACE_ID>
                            <Control>YES</Control>
                            <Control_area>18</Control_area>
                            <Control_rest>2</Control_rest>
                        </CART_ID>
                    </PART_ID>
                 </TOWN_ID>
            </TOWN>
        </CITY>
</XML_FILE>

UPDATED:
The last thing is how to save modified descendant (for example - manually changed SIMPPLE_ID from 1000 to 5000, etc.)  to original sample.xml file ? Is it possible to do it with this solution or should I look for other way ?

A: @Artec Assuming 3 things:

*

*structure of your cart node is standard

*you know the names of the node

*you're using Windows Form since you have the DataGridView control

... instead of using dataset, first create a class with properties that correspond to the nodes of the data you need
Public Class CartItem

    Public Property Simple_ID As String
    Public Property Simple_Area_ID As String
    Public Property Place_ID As String
    Public Property Place_Name As String
    '...

End Class

Now on your Form class, grab the data from your xml file via XDocument and create a list of CartItem.
Public Class Form1

    Private _CartItems As List(Of CartItem)

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        _CartItems = New List(Of CartItem)

        'TODO: Replace ... below with your file location.
        BuildCart("...\sample.xml")
        DataGridView1.DataSource = _CartItems
    End Sub

    Private Sub BuildCart(XmlSourcePath As String)
        Dim xDoc As XDocument = XDocument.Load(XmlSourcePath)
        For Each cartElement As XElement In xDoc.Root.Descendants("CART_ID")
            Dim item As New CartItem

            With cartElement
                item.Simple_Area_ID = .Descendants("SIMPLE_ID").Value
                item.Simple_ID = .Descendants("SIMPLE_AREA_ID").Value
                item.Place_ID = .Descendants("id").Value
                item.Place_Name = .Descendants("name").Value
                '...
            End With

            _CartItems.Add(item)
        Next
    End Sub
End Class

Note: there are several ways to read xml files like XMLTextReader; XMLDocument; XPathDocument; XMLReader; etc. It's just my personal preference to go with XDocument. You'll have to do some research if you want to check out the other options. It all depends on the complexity of your xml file, your requirements and preference.
This should get you going to the right direction.

A: @Artec I haven't used WinForms for the longest time and I'm not sure if there's an easier way to determine which specific row and column was changed. For now, I'm just going for the simplest and basic solution to set you to the right direction.
First off, we can't just directly replace the dataset back to the xml because of your xml structure. There's no way of telling that the code needs to go few levels deep into the CART_ID element. So, we'll just be reversing the approach of loading the xml.
Using the same CartItem class from my previous answer, we cast the DataGridView dataset to the list of CartItem. Update the xDoc elements with the values of the list and save the xDocument back to the xml.
Public Class Form1

    Private _CartItems As List(Of CartItem)
    'TODO: Replace ... with the file location.
    Private _FilePath As String = "...\source.xml"

    '... Button1_Click and BuildCart in here.

    Private Sub UpdateXmlButton_Click(sender As Object, e As EventArgs) Handles UpdateXmlButton.Click
        _CartItems = DirectCast(DataGridView1.DataSource, List(Of CartItem))
        UpdateXml()
        MessageBox.Show("Update Done.")
    End Sub

    Private Sub UpdateXml()
        Dim xDoc As XDocument = XDocument.Load(_FilePath)
        Dim cartIDs As IEnumerable(Of XElement) = xDoc.Root.Descendants("CART_ID")

        For index As Integer = 0 To cartIDs.Count - 1
            Dim cartElement As XElement = cartIDs.ElementAt(index)
            Dim item As CartItem = _CartItems(index)

            With cartElement
                .Descendants("SIMPLE_ID").Value = item.Simple_Area_ID
                .Descendants("SIMPLE_AREA_ID").Value = item.Simple_ID
                .Descendants("id").Value = item.Place_ID
                .Descendants("name").Value = item.Place_Name
                '...
            End With
        Next

        xDoc.Save(_FilePath)
    End Sub
End Class

You're practically changing the elements of the loaded XDocument in memory and throwing it back into the xml file. There's definitely a lot of improvement that can be done, like:

*

*looping through the properties instead of coding each property in a line. This can be achieved with the combination of reflection and dictionary.

*updating only the elements that were changed instead of changing the entire thing

*etc.

But code above should get you started.


text:
Q: Desktop icons showing files of home I think at some point I might have accidentally moved the Desktop folder onto my Pictures folder, and when I noticed I reverted it. But ever since then, the icons shown in my graphical desktop are of the files and folders in home.
I am on Ubuntu 17.10 with gnome. Tried turning off the option Show Desktop Icons in Tweak Tools and then turning it back on, but it didn't do anything.
My theory is that there was a symlink of some sort that changed, or was deleted, when the Desktop folder wasn't where it was supposed to be. But I don't know where to look to be able to fix it.
Thanks!

A: I have finally found an answer here.I have restarted my computer and now everything is behaving as it should.
The problem seemed to be in  the file~/.config/user-dirs.dirs: there was a line appearing like XDG_DESKTOP_DIR="$HOME" when it should have made reference to $HOME/Desktop.
Why or how it changed I dont know.


text:
Q: Docker image with ubuntu 16.04.1 i'm trying to get Ubuntu 16.04.1 Docker image
lib/ubuntu:16.04 gives me 16.04.5.
is there way to get 16.04.1 image?

A: No, point releases on Ubuntu images aren't tagged. Technically you could pick an image tagged by xenial-YYMMDD where the date is from before 16.04.2 was made available.
The question is why you would want to get an outdated image? The difference between 16.04.1 and 16.04.5 is that the latter has more security updates. The libraries remain on the same version so there is no reason to use 16.04.1 instead of the lastest 16.04 update.


text:
Q: Dotfuscator doesn't support current .NET framework? This is a Dotfuscator noob question -- I'm trying to run it on some assemblies for the first time, but I get an error saying: "Invalid assembly [foo.dll]. Input assembly [foo.dll] was compiled with a version of the .NET Framework (v4.0.30319) that is not supported by this version of Dotfuscator. Please check for an updated version of Dotfuscator."
I'm using the version that shipped with the current version of VS 2010, and I have all service packs etc installed. I have registered the product. Help > Check for updates doesn't do anything at all. I don't see any updated downloads on the Dotfuscator site.

A: (Note:  I work for PreEmptive Solutions on the Dotfuscator team.)
You likely have an older version of Dotfuscator (despite the behavior you are seeing under Check for Updates).  Dotfuscator does work with assemblies targeted at 4.0.30319, and has since the release of VS2010 (and we supported assemblies targeted at the various VS2010 Betas as they were released, too).
Are you using the free version included within Visual Studio?  If so, the version included in VS2008 will not support .NET 4.0 assemblies, and would also not indicate that updates are available.  This would be versioned as Community Edition v4.x.
The free version within VS2010 will handle 4.0.30319 targeted assemblies, and would be versioned as Community Edition 5.x.
The professional editions of Dotfuscator have supported builds against 4.0.30319 since April 2010 (http://www.preemptive.com/support/dotfuscator-support/dotfuscator-pro-change-log/272)
Please let me know which exact version of Dotfuscator you're using if it's a Community Edition version in VS2010 or a professional edition.


text:
Q: Angular Reactive Form Validation Complete Event I have a reactive form which having around 10 fields with 2 async validations each and in that, I have to design autosave feature like when a user navigates from a website and come back later he will get the same state of the form where he left. when autosave data render on UI it again validates all fields.
Is there any way to detect when all form validations complete?

A: Something like this should do the trick
this.form.statusChange(
   filter(status=>status==='VALID'),
   switchMap(_=>this.yourAutoSaveFunction(this.form.value))
).subscribe()

A: You can active that using angular forms
reactive-forms
profileForm = this.fb.group({
    firstName: ['', Validators.required],
    lastName: [''],
    address: this.fb.group({
      street: [''],
      city: [''],
      state: [''],
      zip: ['']
    }),
    aliases: this.fb.array([
      this.fb.control('')
    ])
  });

then on submit
you can get all values
onSubmit() {
    // TODO: Use EventEmitter with form value
    console.log(this.profileForm.value);
  }

then you can save Localstorage it
localStorage
The following snippet accesses the current domain's local Storage object and adds a data item to it using Storage.setItem().
localStorage.setItem('formdata', this.profileForm.value);

The syntax for reading the localStorage item is as follows:
var cat = localStorage.getItem('formdata');

**

UPDATED

**
If you want to get only the status and not the value you can use statusChanges:
export class Component {

    @ViewChild('myForm') myForm;

    this.myForm.statusChanges.subscribe(
        result => console.log(result)
    );
}

If you even want data changes, you can subscribe to the valueChanges of the form and check the status of the form using this.myForm.status:
export class Component {

    @ViewChild('myForm') myForm;

    this.myForm.valueChanges.subscribe(
        result => console.log(this.myForm.status)
    );
}

Possible values of status are: VALID, INVALID, PENDING, or DISABLED.


text:
Q: Nuget prompting credentials I am using Visual Studio 2019. While building a solution its asking for credentials and build is getting failed. api.nuget.org asking username and password.
Note: I am using public default nuget package

A: ZScalar is installed in my system. This was blocking the nuget uri. Hence, the nuget was prompting for credentials. If i use proxy, it didn't prompt for credentials.

A: From the official thread of Visual Studio's developer community, you should consider signing out from all accounts (located on the top-right corner of Visual Studio). This should solve your issue.
After clicking on your profile, go to Account settings... and you'll be prompted this:

Simply remove all the accounts & enjoy!

Note that this problem has a good chance to be related wtih NuGet packages installation permission.

A: The answer here, for me, was the blocking of downloadable executable files by group policy.
.nupkg was classified as executable or just not whitelisted - so a group policy (company enforced internet setting) is what was causing the 403 error (on the command line) and this password prompt to nuget.api.org
The password prompt doesn't really make any sense, in my context, but I suppose if I was a network admin and I entered my network password, it might have worked.


text:
Q: Java Reflection : looking at the lines of code in a method? I want be able to extract the insides of a method using java reflection (or any other method that might exist).
I have a test data where i am generating different styles of charts. I want to be able to display the chart, and then in a panel next to it, display the java code that created that chart.
All I need to do is to get into these methods, and pull out the insides. Does reflection allow this?
chart = TestData.createChart1();
chart.display()
chart = TestData.createChart2();
chart.display()
chart = TestData.createChart3();
    ...
chart = TestData.createChartN();
chart.display()

Inside one of my methods i might have something like this :
public static PieChart createChart1() {

    //I WANT ALL THE CODE FROM HERE....

    ArrayList<Segment> values = new ArrayList<Segment>();
    values.add(new Segment(0, null, 15, "music", Color.RED));
    values.add(new Segment(0, null, 52, "photos", Color.BLUE));
    values.add(new Segment(0, null, 33, "applications", Color.GREEN));

    PieChart pieChart = new PieChart(values, "Disk Space Usage");

    pieChart.width = 600;
    pieChart.height = 600;
    pieChart.topOffset = 50;
    pieChart.leftOffset = 50;
    pieChart.rightOffset = 50;
    pieChart.bottomOffset = 50;
    pieChart.initialWidth = 100;
    pieChart.incrementWidth = 50;

    //TO HERE....

    return pieChart;
}

A: The good part about reflection is that it gives a program access to some aspects of its source code.   The not so good part is that what you can get it is determined and therefore limited by the language designers and implementers.  The raw source code is one part that they reasonably don't want to offer. If they did so, every compiled reflective system would contain it source code and that would create a vast intellectual property leak.
If you want programmatic access to the full content of computer programs (including those in Java), the class of tools called Program Transformation (PTS) systems are ideal.  These tools are generally designed to parse the source code language of interest, build internal compiler data structures (typically  abstract syntax trees or ASTs) containing the complete equivalent of source code (often including precise source code position information).  The really useful part from OP's point of view is that the PTS can usually invert the parsing process, and regenerate the source (or a designated part) from the internal structures.  As an alternative, one can use the precise source position information to extract the original text from the original files; this is mostly only useful if you care about exact formatting and/or what's in the whitespace.
To get OP's effect using our DMS Software Reengineering Toolkit, one would use DMS's Java front end, and code a custom tool with roughly the following code:
       (include `Java~v7/ParserComponent.par')
        ...
       (local (;; [myFile string]
                  [myTree AST:Tree]
              );;
           ...
           (= myFile ... )  ; get a file path from somewhere
           (= myTree (ParserComponent:Parse myFile ...))
           (AST:ScanTree myTree
                 (procedure [subtree AST:Tree]
                     (;;  (ifthen (== (AST:subtree Grammar:Nonterminals:_method_declaration))
                               (;;  (ParserComponent:PrettyPrintFidelity
                                         (AST:GetNthGrammarChild myTree 3) ; the method body
                                         ...
                                     )
                               );;
                          )

                          (return ~t) ; signal to ScanTree to continue looking
                     );;
                 )
           )AST
       )local

Note the tree scan (think of this as a visitor) that hunts for AST nodes of type "method_declaration", a term taken literally from the Java grammar.  Having found such an AST node type, it navigates to the method body and calls DMS's prettyprinter to regenerate text in Fidelity mode, which reproduces the original indentation and line breaks, and the comments, from the original source code.  [All of this information is in DMS's trees].
If OP wants a specifically named method; he would use DMS's NameResolver component, which builds a full symbol table including for each definition a reference (specifically to a tree) to the source code point that provides the definition.  Then one could look up a qualified name using that symbol table, grab the defining tree, and print it.

A: *

*java reflexion doesn't allow to read the line of codes, and the pcode on wich the reflexion rely doesn't contain the source code, only the compiled code, if it was  compiled with debug options, also the line numbers.

*Since your method "createChart" only creates an object, you could only analyze the content of the result object (the "chart")
chart = TestData.createChart1();
analyze(chart);
chart.display();

Then in your "analyze" method do whatever you want to display the objet, like a Json Serialision, Xml ... or simply a toString if the result is exploitable.


text:
Q: Validating API Responses with FlowType So I've figured out so far what window.fetch returns a Response object defined here.
What I want to do now is extend this definition somehow to type check against my specific api. Here's a small example.
I have an endpoint that will asynchronously decrements a number. The response can return with a 400 error or a 200 with some JSON payload.
So I've created an interface to help with these responses:
interface ErrorResponse<S,T> {
  status: S,
  statusText: T,
}

interface JSONResponse<S,J> {
  status: S,
  json(): Promise<J>,
}

I'm using some generics so I can specify exactly what the responses are:
type DecrementJSON = { count: number }
type DecrementResponse = ErrorResponse<400,string>
                       | JSONResponse<200,DecrementJSON>

Then I have my api request:
export const decrement = (count : number) : Promise<DecrementResponse> =>
  fetch('/dec', {
    method: 'POST',
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ count }),
  })

And I get this error:
src/api/index.js:18
 18:   fetch('/dec', {
       ^ function call
 17: export const decrement = (count : number) : Promise<DecrementResponse> =>
                                                         ^^^^^^^^^^^^^^^^^ union: type application of polymorphic type: class type: ErrorResponse | type application of polymorphic type: class type: JSONResponse. This type is incompatible with
704: declare function fetch(input: string | Request, init?: RequestOptions): Promise<Response>;
                                                                                ^^^^^^^^ Response. See lib: /private/tmp/flow/flowlib_2cb52cf2/bom.js:704
  Member 1:
   14: type DecrementResponse = ErrorResponse<400,string>
                                ^^^^^^^^^^^^^^^^^^^^^^^^^ type application of polymorphic type: class type: ErrorResponse
  Error:
   14: type DecrementResponse = ErrorResponse<400,string>
                                              ^^^ number literal `400`. Expected number literal `400`
  664:     status: number;
                   ^^^^^^ number. See lib: /private/tmp/flow/flowlib_2cb52cf2/bom.js:664
  Member 2:
   15:                        | JSONResponse<200,DecrementJSON>
                                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type application of polymorphic type: class type: JSONResponse
  Error:
   15:                        | JSONResponse<200,DecrementJSON>
                                             ^^^ number literal `200`. Expected number literal `200`
  664:     status: number;
                   ^^^^^^ number. See lib: /private/tmp/flow/flowlib_2cb52cf2/bom.js:664

Try it yourself here. Thanks

Thanks @vkurchatkin for pointing out the issue with validation. I've updated the function to do all the validation internally:
type DecrementResponse = { status: 400, error: string }
                       | { status: 200, data: { count: number } }

export const decrement = async (count : number) : Promise<DecrementResponse> => {
  const response = await fetch('/dec', {
    method: 'POST',
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ count }),
  })
  if (response.status === 400) {
    return {
      status: 400,
      error: response.statusText,
    }
  }
  if (response.status === 200) {
    const result = await response.json()
    return {
      status: 200,
      data: result,
    }
  }
  throw new TypeError(`Unknown response status: ${response.status}`)
}

The only thing that doesnt really make since is why I didnt have to validate the actual deserialized json data.

Another simple example that doesnt type check is this one:
/* @flow */

// https://github.com/facebook/flow/blob/master/lib/bom.js#L711
interface StatusResponse<S> {
  status: S
}

type ApiResponse = StatusResponse<200> | StatusResponse<400>

const api = async () : Promise<ApiResponse> => {
  const response = await fetch('www.google.com')
  if (response.status === 200) {
    return response
  } else if (response.status === 200) {
    return response
  }
  throw new TypeError('unknown status')
}

Seems to me like that should work though since we're validating the statuses...


text:
Q: Proving a relation is an equivalence relation specifically proving transitivity I'm currently studying for an exam and I've come across this question:

*

*Define a relation R on Z by
xRy ⇔ 6|($x^{2} − y^{2}$)
for x, y ∈ Z.
Prove that R is an equivalence relation and describe the equivalence classes of R
I understand how to prove it's reflexive, and I've tried to prove it's symmetric but I used the fact that -6|($y^{2}-x^{2}$) which doesn't seem like the correct way to answer this question, and I have no idea how to prove it's transitive, any help would be greatly appreciated. Thanks in advance!

A: Your proof that it's symmetric is almost certainly correct (but if you want to post the details, I could critique it).
To prove transitivity, assume $x \sim y$ and $y\sim z$.
By definition, $6| (x^2-y^2)$ and $6|(y^2-z^2)$.  Another way of putting this would be to say there are integers $m,n$ such that
$x^2-y^2 = 6m$
and
$y^2-z^2 = 6n$.
If we just add those two equations together, we get
$x^2 - z^2 = 6(m+n)$.
That is, $6|(x^2 -z^2)$, or $x\sim z$.


text:
Q: What are the main tactics in proofs of theorems? Can You please help me to answer the following questions.
I never was thinking about such questions since they are not in the core of mathematics. However, from the educational point of view they are very important. I have my own answers, but they don't look exhaustive for me.
1) Why in the proof of a theorem we must use only the facts which are given in the conditions of this theorem?
2) Why in the proof of the theorem we should always understand what do you want to have in the end and sometimes make the proof going from this end?
This questions look to obvious to answer seriously. However, for students they are not really obvious, what make all possible answers interesting.

A: Proofs have different purposes in different places in mathematics. When you're publishing in a research journal you must convince your readers that your claims are true, using the hypotheses in your theorem and any other tools it's reasonable to expect professional mathematicians in your area to know and accept.
When I teach students about writing proofs I know the theorems are true, so they are not trying to convince me. What I want from them is an argument that shows me that they have convinced themselves of the truth for good reasons. Those reasons should include the hypotheses, of course, and any other tools taught in class, or accepted at the level of the course.
Often rather than asking students to prove something, I ask them either to prove it or provide a counterexample, in hopes that will persuade them to think about the mathematical truth rather than the particular shape of the argument.

A: The basic idea behind 1) is indeed pretty obvious: don't assume that something is true if you don't know it is true!
A good example are logic puzzles. So here you are given pieces of information like "Bob's shirt is red" or "Sara's shoes are white". Clearly, in a context like this we cannot assume that "John's socks are blue" if that's not given to us. Only work with what's given to you.
Another clear example is formal proofs: here, you are very explicitly given certain premises, and clearly you cannot ad any further premises to that.
In practice, though, it is not always clear what we can assume or not. In fact, look at most of the questions posted here on Math.SE. Often they are something like "Prove that for any natural number $n$ it is true that $n^2+n+3$ is odd". Well, exactly what are we allowed to use as givens here? Can we assume that every natural number is even or odd?  Or do we have to go all the way back some Peano axioms? Or  ...?  Still, even in these cases you common sense and experience will give you a pretty good idea what you can or cannot assume. That every number is even either or odd seems pretty safe.  But that $n^2+n+1$ is odd probably not. And you certainly can;t start with: "Let $n$ be some natural number. $n$ is odd. ..."
Regarding 2): I would put this idea even stronger. It is not just that sometimes we 'make the proof go' from the conclusion backwards, but that we do this pretty much every time!  That is, the nature of the conclusion will tell us whether to set up the proof as a universal proof, a conditional proof, a proof by contradiction, a proof by cases, a proof by induction, etc.  And those proof techniques are what is going to provide the all important 'proof plan' or 'proof skeleton': it provides the structure of the proof to which you then add the details.

A: Regarding your first question $(1)$, sometimes that is not the case. For instance, Euclid proved that there are infinitely many values $a, b, c$ such that $a^2 + b^2 = c^2$. This has been a major theorem, and we can prove it a different way from an approach that is not mentioned in Euclid's proof or in the theorem itself.
We know that for a value $x$, $$(x+1)^2 = x^2 + 1 + 2x;$$ $$(x-1)^2 = x^2 + 1 - 2x.$$ Therefore, $$\begin{align} (x+1)^2(x-1)^2 &= (x^2 + 1 + 2x)(x^2 + 1 - 2x) \\ \Leftrightarrow \big((x+1)(x-1)\big)^2 &= (x^2 + 1)^2 - (2x)^2 \\ \Leftrightarrow (x^2 - 1)^2 + (2x)^2 &= (x^2 + 1)^2.\end{align}$$ Substitute $a = x^2 - 1$, $b = 2x$, $c = x^2 + 1$ and we have proven the theorem. $\qquad\qquad\qquad\quad\,\,\,\Box$
Go here to find proofs of similar sort.


text:
Q: What does it mean the value 5 as the return of get in conflict of cplex? I am using cplex.conflict for a problem and when i use cplex.conflict.refine and then ask for the cplex.conflict.get it gives the value 5 for some of the constraints (an infeasible example). Does anyone knows what it means?
Here is an example in python:
> python
Python 2.7.6 (default, Jun 22 2015, 17:58:13)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import cplex
>>> c = cplex.Cplex()
>>> c.variables.add(names = ["x0"])
>>> c.linear_constraints.add(lin_expr = [[[0], [-1.0]], [[0], [1.0]]], senses = "LL", rhs = [-10,9])
>>> c.conflict.refine(c.conflict.linear_constraints())
>>> c.conflict.get()
[5, 5]
>>>

The api only refers to returned values of -1, 0 or 3.

A: c.conflict.get() may return conflict.constraint_type as well. In your case, the two constraints are members of the conflict and cplex returns types of the constraints:
>>> c.conflict.group_status[5]
None
>>> c.conflict.constraint_type[5]
SOS

i.e., your constraints are of SOS-type which is strange as SOS constraints are for integer variables (binary). If you add a redundant constraint, e.g.
>>> c.linear_constraints.add(lin_expr = [[[0], [-1.0]], [[0], [1.0]], \
[[0], [1.0]]], senses = "LLL", rhs = [-10,9,10])
>>> c.conflict.refine(c.conflict.linear_constraints())
[5, 5, -1]

meaning the last one is excluded as not being a member of the conflict. I would recommend you to use c.conflict.get_groups() for more information.
Edit:
If you specify variables' types when defining everything works fine:
>>> c.variables.add(names = ["x0"], obj=[1.0], types=[c.variables.type.continuous])
...etc...
>>> c.conflict.refine(c.conflict.linear_constraints())
Refine conflict on 3 members...

Iteration  Max Members  Min Members
     1            2            0
     2            2            1
     3            2            2

[3, 3, -1]


text:
Q: update records in a union select query I've two tables with events that I want to union and sort by date and I need a value in the result that I can group the records by for reporting - in this case code2
CREATE TABLE #tbl1 (code1 INT, codeDate DATETIME, code2 INT)
CREATE TABLE #tbl2 (code1 INT, codeDate DATETIME, code2 INT )

INSERT INTO #tbl1 VALUES( 1, '01 jan 2013 12:00:00', 123)
INSERT INTO #tbl1 VALUES( 2, '01 jan 2013 14:00:00', 123)
INSERT INTO #tbl1 VALUES( 1, '01 jan 2013 15:00:00', 234)
INSERT INTO #tbl1 VALUES( 2, '01 jan 2013 18:00:00', 234)

INSERT INTO #tbl2 VALUES( 10, '01 jan 2013 12:10:00', 0)
INSERT INTO #tbl2 VALUES( 20, '01 jan 2013 13:20:00', 0)
INSERT INTO #tbl2 VALUES( 10, '01 jan 2013 15:10:00', 0)
INSERT INTO #tbl2 VALUES( 20, '01 jan 2013 16:20:00', 0)

SELECT * FROM #tbl1 UNION SELECT * FROM  #tbl2  ORDER BY CODEDATE

Returns
code1   codeDate                    code2
1       2013-01-01 12:00:00.000     123
10      2013-01-01 12:10:00.000     0
20      2013-01-01 13:20:00.000     0
2       2013-01-01 14:00:00.000     123
1       2013-01-01 15:00:00.000     234
10      2013-01-01 15:10:00.000     0
20      2013-01-01 16:20:00.000     0
2       2013-01-01 18:00:00.000     234

Id like to get the values in the code2 column to be updated so the tbl2 records that fall between the date values in tbl1 have the code2 value from tbl1. (rows 2,3,6 & 7 in results)  eg:
code1   codeDate                    code2
1       2013-01-01 12:00:00.000     123
10      2013-01-01 12:10:00.000     123
20      2013-01-01 13:20:00.000     123
2       2013-01-01 14:00:00.000     123
1       2013-01-01 15:00:00.000     234
10      2013-01-01 15:10:00.000     234
20      2013-01-01 16:20:00.000     234
2       2013-01-01 18:00:00.000     234

Is this possible with a UNION or do i need a different approach?

A: Try this
update #tbl2
set code2 = t1.code
from
    #tbl2 t2
        inner join
    (

        select
            t1s.codeDate start,
            t1f.codeDate finish,
            t1s.code2 code
         from #tbl1 t1s
            inner join #tbl1 t1f
                on t1s.code2 = t1f.code2
        where t1s.code1=1
        and t1f.code1 = 2
    ) t1
        on t2.codeDate between t1.start and t1.finish

 SELECT * FROM #tbl1 UNION SELECT * FROM  #tbl2  ORDER BY CODEDATE

But really, your data structure needs sorting out (which is what the bulk of the above query attempts to do)


text:
Q: How handle NULL in visualization I have two tables (it is example, of course) that I loaded to app from different sources by script
Table 1:

ID
Attribute T1

1
100

3
200

Table 2:

ID
Attribute T2

1
Value 1

2
Value 2

On a list I create table:
ID
Attribute T1
Attribute T2
Finally I have table

ID
Attribute T1
Attribute T2

1
100
Value 1

2
-
Value 2

3
200
-

So, as You know it limits me in filtering and analyzing data, for example I can't show all data that isn't represented in Table 1, or all data for Attribute T1 not equal 100.
I try to use NullAsValue, but it didn't help. Would be appreciate for idea how to manage my case.

A: To achieve what you're attempting, you'll need to Join or Concatenate your tables. The reason is because Null means something different depending on how the data is loaded.
There's basically two "types" of Null:
"Implied" Null
When you associate several tables in your data model, as you've done in your example, Qlik is essentially treating that as a natural outer join between the tables. But since it's not an actual join that happens when the script executes, the Nulls that arise from data incongruencies (like in your example) are basically implied, since there really is an absence of data there. There's nothing in the data or script that actually says "there are no Attribute T1 values for ID of 2." Because of that, you can't use a function like NullAsValue() or Coalesce() to replace Nulls with another value because those Nulls aren't even there -- there's nothing to actually replace.

The above tables don't have any actual Nulls -- just implied ones from their association and the fact that the ID fields in either table don't have all the same values.
"Realized" Null
If, instead of just using associations, you actually combine the tables using the Join or Concatenate prefixes, then Qlik is forced to actually generate a Null value in the absence of data. Instead of Null being implied, it's actually there in the data model -- it's been realized. In this case, we can actually use functions like NullAsValue() or Coalesce() or Alt() to replace Nulls with another value since we actually have something in our table to replace.

The above joined table has actual Nulls that are realized in the data model, so they can be replaced.
To replace Nulls at that point, you can use the NullAsValue() or Coalesce() functions like this in the Data Load Editor:
table1:
load * inline [
ID  ,   Attribute T1
1   ,   100
3   ,   200
];

table2:
join load * inline [
ID  ,   Attribute T2
1   ,   Value 1
2   ,   Value 2
];

NullAsValue [Attribute T1];
Set NullValue = '-NULL-';

new_table:
NoConcatenate load
    ID
  , [Attribute T1]
  , Coalesce([Attribute T2], '-AlsoNULL-') as [Attribute T2]
Resident table1;

Drop Table table1;

That will result in a table like this:

The Coalesce() and Alt() functions are also available in chart expressions.
Here are some quick links to the things discussed here:

*

*Qlik Null interpretation

*Qlik table associations

*NullAsValue() function

*Coalesce() function

*Alt() function


text:
Q: Why would I want to use a page query instead of page context? When creating pages  programmatically in  gatsby-node.js I can pass context to my page component:
createPage({
  path: path,
  component: docTemplate,
  context: {}, // additional data can be passed via context
})

Seems like I could pass the context needed here to generate my document instead of having to query for it on the individual page again. Any reason why I wouldn't want to do this?

A: Probably just reserve the page context for data that could be relevant to every page. Each different type of page will most likely have different queries so keep those in the page queries.


text:
Q: ArgumentError: Mapper mapped class Users->users could not assemble any primary key columns for mapped table 'users' I am new to SQLAlchemy. Trying to build database in Heroku Postgres
Get error:
ArgumentError: Mapper mapped class Users->users could not assemble any primary key columns for mapped table 'users'
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import (Column, Integer, BigInteger, String, Sequence, TIMESTAMP, Boolean, JSON)
from sqlalchemy import sql
from sqlalchemy import Table, Column, Integer, String, MetaData, Sequence, create_engine

class Users(Base):

    __tablename__ = 'users'

    meta = MetaData()

    users_table = Table(
    'users', meta,
    Column('id', Integer, primary_key=True),
    Column('name',String(50)),
    Column('fullname',String(50)),
    Column('phone',Integer),
               )

    meta.create_all(engine)

    def __repr__(self):
        return "<User(id='{}', fullname='{}', username='{}')>".format(
            self.id, self.full_name, self.username)

A: The main reasons this does not work is that you try to create the table before the class User is created AND also the table you declare is not declared on the correct attribute.  So sqlalchemy cannot find the id column.
I have tried to outline a more idiomatic declarative approach below:

# This implicitly creates metadata, you do not need to make an explicit one.
Base = declarative_base()

class Users(Base):

    __tablename__ = 'users'

    # Using a table explicitly is not required here
    # Just declare the columns as properties.
    id = Column(Integer, primary_key=True)
    name = Column(String(50))
    fullname = Column(String(50))
    phone = Column(Integer)

    # Don't do this here because Users is not done
    # meta.create_all(engine)

    def __repr__(self):
        return "<User(id='{}', fullname='{}', username='{}')>".format(
            self.id, self.full_name, self.username)

# Do this after classes are declared and use Base's metadata.
Base.metadata.create_all(engine)

References:
If you really want to set a table you have to set it with __table__ and use Base.metadata:
https://docs.sqlalchemy.org/en/13/orm/extensions/declarative/table_config.html#using-a-hybrid-approach-with-table


text:
Q: Failed to install Eclipse plugin I have put the plugin jar files under dropins folder (Indigo), the plugin never load as expected as I close and restart Eclipse.
What log I can check to see the error?
I am using Mac.

A: Have you try to launch eclipse using the -clean option?
Where did you get the jar files from?
Try following:

*

*Move all plugin files under dropins to other directory.

*Make new workspace, and launch eclipse

*Close eclipse

*Put all plugin files back in place.

*Open the workspace you have created at #2.


text:
Q: Inexplicable vertical border behavior in a simple table The code below prints the picture below, and I cannot figure out why the vertical borders act like they do. Obviously, I would like the line to go from the toprule to the bottomrule, but for some reason one line goes past the bottomrule while two of them don't start until row number two.
Can anyone help me modify the code to make it look alright? I am in a bit of a rush.
Thank you very much.

\begin{center}
\captionof{table}{Results from running the main model for different scenarios}
\begin{tabular}{l|ccc|c|ccc|ccc}
\toprule
  & \multicolumn{3}{c}{\textbf{Weights}}
  & \textbf{Obj.}
  & \multicolumn{3}{c}{\textbf{Weighted pen.}}
  & \multicolumn{3}{c}{\textbf{Total pen.}} \\
\textbf{Variation}           & 1   & 2   & 3  & \textbf{value}  & 1 & 2 & 3  & 1 & 2 & 3\\
\cmidrule(r){1-11}
Even weights          & 1/3   & 1/3   & 1/3   & 55.67  & 26.67 & 4.33   & 24.67 & 80    & 13    & 74\\
Emphasised 1          & 1/2   & 1/4   & 1/4   & 60.75 & 36   & 4.25  & 20.5 & 72    & 17    & 82\\
Emphasised 2          & 1/4   & 1/2   & 1/4   & 44.5  & 21   & 4.5   & 19   & 84    & 9     & 76\\
Emphasised 3          & 1/4   & 1/4   & 1/2   & 60.25 & 20   & 8.25  & 32   & 80    & 33    & 64\\
No lunch              & 1/3   & 1/3   & 1/3   & 43    & 21   & 2.67  & 19.33& 63    & 8     & 58 \\
No R\&D on lab 4      & 1/3   & 1/3   & 1/3   & 27    & 1.33 & 3.67  & 22   & 4     & 11    & 66 \\
New lab of type 3     & 1/3   & 1/3   & 1/3   & 49    & 24   & 5     & 20   & 72    & 15    & 60 \\
\bottomrule
\label{tab:scenariotable}
\end{tabular}
\end{center}

A: You're missing the | specifiers in the argument to \multicolumn. Also \label is misplaced: it should go just after \caption.
I recommend you not trying to place big tables with center and \captionof: leave them float.
Here's a fixed code, with another version, without vertical rules and with siunitx for better alignment of the numbers.
\documentclass{article}
\usepackage{siunitx,booktabs}
\usepackage{caption}

\begin{document}

\begin{table}
\centering

\caption{Results from running the main model for different scenarios}\label{tab:scenariotable}

\begin{tabular}{l|ccc|c|ccc|ccc}
\toprule
  & \multicolumn{3}{c|}{\textbf{Weights}}
  & \textbf{Obj.}
  & \multicolumn{3}{c|}{\textbf{Weighted pen.}}
  & \multicolumn{3}{c}{\textbf{Total pen.}} \\
\textbf{Variation}           & 1   & 2   & 3  & \textbf{value}  & 1 & 2 & 3  & 1 & 2 & 3\\
\cmidrule(r){1-11}
Even weights          & 1/3   & 1/3   & 1/3   & 55.67  & 26.67 & 4.33   & 24.67 & 80    & 13    & 74\\
Emphasised 1          & 1/2   & 1/4   & 1/4   & 60.75 & 36   & 4.25  & 20.5 & 72    & 17    & 82\\
Emphasised 2          & 1/4   & 1/2   & 1/4   & 44.5  & 21   & 4.5   & 19   & 84    & 9     & 76\\
Emphasised 3          & 1/4   & 1/4   & 1/2   & 60.25 & 20   & 8.25  & 32   & 80    & 33    & 64\\
No lunch              & 1/3   & 1/3   & 1/3   & 43    & 21   & 2.67  & 19.33& 63    & 8     & 58 \\
No R\&D on lab 4      & 1/3   & 1/3   & 1/3   & 27    & 1.33 & 3.67  & 22   & 4     & 11    & 66 \\
New lab of type 3     & 1/3   & 1/3   & 1/3   & 49    & 24   & 5     & 20   & 72    & 15    & 60 \\
\bottomrule
\end{tabular}

\end{table}

\begin{table}
\centering

\caption{Results from running the main model for different scenarios}\label{tab:scenariotablebetter}

\begin{tabular}{
  @{}
  l
  ccc
  S[table-format=2.2]
  S[table-format=2.2]
  S[table-format=1.2]
  S[table-format=2.2]
  S[table-format=2.0]
  S[table-format=2.0]
  S[table-format=2.0]
  @{}
}
\toprule
\textbf{Variation}
  & \multicolumn{3}{c}{\textbf{Weights}}
  & \textbf{Obj.}
  & \multicolumn{3}{c}{\textbf{Weighted pen.}}
  & \multicolumn{3}{c}{\textbf{Total pen.}} \\
  & {1} & {2} & {3} & {\textbf{value}}  & {1} & {2} & {3}  & {1} & {2} & {3} \\
\midrule
Even weights       & 1/3 & 1/3 & 1/3 & 55.67 & 26.67 & 4.33 & 24.67 & 80 & 13 & 74 \\
Emphasised 1       & 1/2 & 1/4 & 1/4 & 60.75 & 36    & 4.25 & 20.5  & 72 & 17 & 82 \\
Emphasised 2       & 1/4 & 1/2 & 1/4 & 44.5  & 21    & 4.5  & 19    & 84 &  9 & 76 \\
Emphasised 3       & 1/4 & 1/4 & 1/2 & 60.25 & 20    & 8.25 & 32    & 80 & 33 & 64 \\
No lunch           & 1/3 & 1/3 & 1/3 & 43    & 2 1   & 2.67 & 19.33 & 63 &  8 & 58 \\
No R\&D on lab 4   & 1/3 & 1/3 & 1/3 & 27    &  1.33 & 3.67 & 22    &  4 & 11 & 66 \\
New lab of type 3  & 1/3 & 1/3 & 1/3 & 49    & 24    & 5    & 20    & 72 & 15 & 60 \\
\bottomrule
\end{tabular}

\end{table}

\end{document}

A: Rather than figure out how to insert the "missing" vertical bars, you may want to think about structuring your table so that it has a more open look, a better-organized header and better-organized numeric data, and actually fits inside the available textblock. In the code below, I employ the S column type of the siunitx package for 7 of the data columns, and a tabular* environment so that the table occupies the full width of the available text block, but no more than that.

\documentclass{article}
\usepackage{booktabs,caption,siunitx}
% Utility macro to typeset single-column wrapped header cells:
\newcommand\mycol[1]{\smash{\begin{tabular}[t]{c} #1 \end{tabular}}}
\begin{document}
\begin{center}
\captionof{table}{Results from running the main model for different scenarios}
\label{tab:scenariotable}
\setlength\tabcolsep{0pt} % make LaTeX figure out optimal amount of intercolumn whitespace
\begin{tabular*}{\textwidth}{
                  l @{\extracolsep{\fill}}
                  *{3}{c}
                  *{4}{S[table-format=2.2]}
                  *{3}{S[table-format=3.0]} }
\toprule
  Variation
  & \multicolumn{3}{c}{Weights}
  & {\mycol{Obj.\\value}}
  & \multicolumn{3}{c}{Weighted pen.}
  & \multicolumn{3}{c}{Total pen.} \\
\cmidrule{2-4} \cmidrule{6-8} \cmidrule{9-11}
& 1 & 2 & 3 & & {1} & {2} & {3} & {1} & {2} & {3}\\
\midrule
Even weights          & 1/3   & 1/3   & 1/3   & 55.67  & 26.67 & 4.33   & 24.67 & 80    & 13    & 74\\
Emphasised 1          & 1/2   & 1/4   & 1/4   & 60.75 & 36   & 4.25  & 20.5 & 72    & 17    & 82\\
Emphasised 2          & 1/4   & 1/2   & 1/4   & 44.5  & 21   & 4.5   & 19   & 84    & 9     & 76\\
Emphasised 3          & 1/4   & 1/4   & 1/2   & 60.25 & 20   & 8.25  & 32   & 80    & 33    & 64\\
No lunch              & 1/3   & 1/3   & 1/3   & 43    & 21   & 2.67  & 19.33& 63    & 8     & 58 \\
No R\&D on lab 4      & 1/3   & 1/3   & 1/3   & 27    & 1.33 & 3.67  & 22   & 4     & 11    & 66 \\
New lab of type 3     & 1/3   & 1/3   & 1/3   & 49    & 24   & 5     & 20   & 72    & 15    & 60 \\
\bottomrule
\end{tabular*}
\end{center}
\end{document}


text:
Q: Understanding Dcast from Reshape2 in R
I have a question with regard to melting the data and any idea on how this can be done would be very much helpful.
For example: I have head(dataset) like
 KLIENDIKAARDINR                 TSEKK_ID        KPV   KPV_ID     KELL
1 9233660006737480 201401250001057986117632 2014.01.25 20140125 18:33:19
2 9233660006737480 201401250001057986117632 2014.01.25 20140125 18:33:19
3 9233660006737480 201401250001057986117632 2014.01.25 20140125 18:33:19
4 9233660006737480 201401250001057986117632 2014.01.25 20140125 18:33:19
5 9233660006737480 201401250001057986117632 2014.01.25 20140125 18:33:19
6 9233660006737480 201401250001057986117632 2014.01.25 20140125 18:33:19
       Categories D_INVENTTABLE_PRODUCT_ID  KL_ID
1      cat1                    103573   538151
2      cat2                   119186    538151
3      cat3                   103573    538154
4      cat5                    99298    538151
5      cat2                   116390    538152
6      cat2                   107954    538151
 where there are 78 different barcodes cat1..cat78

and another df contains just unique KL_ID like
head(n,2)
KL_ID  margin_total
10     996.1263
558151 122.337
558152 328.323
 ...   ....

Now to reshape the data in this format :
KL_ID  margin_total cat1 cat2 cat3 cat4 cat5 ...cat78
  10     996.1263   0    0    1     1    0
  558151 122.337    1    1    0     0    1
  558152 328.323    0    1    0     0    1

the logic here is to make cat1..78 as columns and fill them with binary values like with 1 if the exist irrespective of the number of times they occur for each KL_ID and with 0 if this category is not there for the corresponing KL_ID.
Any help on how we can use dcast from reshape to apply on this would be appreciated.Thanks


text:
Q: Trying to pass parameters to HTML page in C# webView2 I am attempting to navigate to an HTML file using parameters for location (lat and long)
This is a WPF application that has a built in browser which shows data from the google maps api.
I want to instantiate my map given the location parameters in C#
I read this thread:
How to pass information from a WPF app to an HTML page
but I still get file not found. The url works fine without the parameters
    String sURL = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\html\\mapview.html";
    Uri uri = new Uri(sURL+"?lat="+lat+"&lng="+lng+"");
    webBrowser1.Source = uri;

Any ideas as to why im getting these errors?
Not allowed to load local resource
and
ERR_FILE_NOT_FOUND

A: As mm8 pointed out, because I'm not using a web server it is not possible to pass parameters to my local file.
Reading various threads I had found a solution of installing a local webserver to the project, but since I didn't want to have to configure the web server and add unnecessary load to my projects, I worked around the issue by dynamically changing the coordinates in the HTML file before loading it in
        private void LoadMap()
        {
            // Before loading map, change the trojan horse coordinates to the latest ones by editing the html file
            string[] lines = File.ReadAllLines(sURL);
            for (int i = 0; i < lines.Length; i++)
            {
                if (lines[i].Contains("var lat"))
                {
                    lines[i] = "<script>var lat = " + lat + "; var lng = " + lng + ";</script>";
                    break;
                }
            }
            File.WriteAllLines(sURL, lines);
            // We can now load in the desired coordinates
            Uri uri = new Uri(sURL);
            webBrowser1.Source = uri;
        }

Note that this will require a new page load each time, but it is a good solution for changing things that need to be done on page load.
Another thing I tested was calling the script asynchronously. This also worked pretty well
        // we need to wait for map initialization (page load) before running our calcRoute script
        private async void NavMapLoading() //starts loading content asynchronously
        {
            await webBrowser1.EnsureCoreWebView2Async(null);
            webBrowser1.CoreWebView2.DOMContentLoaded += OnWebViewDOMContentLoaded;
            Uri uri = new Uri(AppDomain.CurrentDomain.BaseDirectory + "html\\map_route.html");
            webBrowser1.Source = uri;
        }
        private async void OnWebViewDOMContentLoaded(object sender, CoreWebView2DOMContentLoadedEventArgs arg)
        {
            webBrowser1.CoreWebView2.DOMContentLoaded -= OnWebViewDOMContentLoaded;
            webBrowser1.Focus();
            // now we can load destination
            await webBrowser1.ExecuteScriptAsync("calcRoute("+origin+","+dest+");");
        }


text:
Q: Generate same object from yaml I have a class which generated from YAML.
This class generated 10 times.
I want that 3 of the instances of the class will be the same object.
I know that I can generate father to the three but there is a better way?
I am using java (spring boot)


text: Q: Add to cart quantity reset to 1 even i added 2 qty in Arabic store Magento 2 Minicart quantity reset to 1 even I added qty 2 Magento 2. I am having the Arabic store, in the Arabic store only this issue shows, is it the problem with Locales. Please help to solve it.


text:
Q: How can I make a simpler javascript function for the following: There has to be a function that can be used that will greatly simplify, codewise, all these very similar replacements. Would like to be able to make a function that could handle this fall all contractions including I've, Could've  etc.
    // for can't
    s = s.replace(/cant/g, "ca{n't|n{| }not}");
    s = s.replace(/can't/g, "ca{n't|n{| }not}");
    s = s.replace(/Cant/g, "Ca{n't|n{| }not}");
    s = s.replace(/Can't/g, "Ca{n't|n{| }not}");

    //for can not
    s = s.replace(/can not/g, "ca{n't|{| }not}");
    s = s.replace(/Can not/g, "Ca{n't|{| }not}");

    // for won't
    s = s.replace(/wont/g, "w{on't|ill not}");
    s = s.replace(/won't/g, "w{on't|ill not}");
    s = s.replace(/Wont/g, "W{on't|ill not}");
    s = s.replace(/Won't/g, "W{on't|ill not}");

    // for will not
    s = s.replace(/will not/g, "w{on't|ill not}");
    s = s.replace(/Will not/g, "W{on't|ill not}");

    // for hasn't
    s = s.replace(/hasnt/g, "has{n't| not}");
    s = s.replace(/hasn't/g, "has{n't| not}");
    s = s.replace(/Hasnt/g, "Has{n't| not}");
    s = s.replace(/Hasn't/g, "Has{n't| not}");

    // for has not
    s = s.replace(/has not/g, "has{n't| not}");
    s = s.replace(/Has not/g, "Has{n't| not}");

A: For can not and  can't, it could be done in a single step:
s = s.replace(/(C|c)an(?:'?t| not)/g, "ca{n't|n{| }not}");

Or, if you want to match also cannot
s = s.replace(/(C|c)an(?:'?t| ?not)/g, "ca{n't|n{| }not}");

Same principle can be applied for the other has not and will not


text:
Q: System.NullReferenceException based on List I'm trying to loop through rows and get their Indexes (Primary Keys from SQL).  I'm getting a NRE on "this.SelectRowIndexes.Add(ResourceKey)"  I can't figure out why it would matter and how can I fix this?
CODE:
    private void GetIndexes()
    {
        List<int> SelectRowIndexes = new List<int>();
        for (int i = 0; i < gridViewRecords.Rows.Count; i++)
        {
            DataRowView drv = (DataRowView)gridViewRecords.CurrentRow.DataBoundItem;
            DataRow selectedRow = drv.Row;
            ResourceKey = Convert.ToInt32(selectedRow["ResourceAndInstallKey"]);
            this.SelectRowIndexes.Add(ResourceKey);

        }
    }

I also have it up in my class (this has been a ton of troubleshooting, so my code looks terrible)
    public List<int> SelectRowIndexes { get; set; }

I had this prior.  Several of the answers quoted this code.  I changed mine because the if-else was actually used for something else, which has now been deleted
if (this.SelectRowIndexes == null)
{
    this.SelectRowIndexes.Add(ResourceKey);
}
else
{
    this.SelectRowIndexes.Add(ResourceKey);
}

A: If SelectRowIndexes is null then you can't add anything to the list. You first need to initialize an empty list with
this.SelectRowIndexes = new List<int>();

A: You instantiate a local variable
List<int> SelectRowIndexes = new List<int>();

and then you are adding to your class property/field this.SelectedRowIndexes which you are most likely not assigning anywhere and it is null and you get NRE.
this.SelectRowIndexes.Add(ResourceKey);

Change this so
private void GetIndexes()
{
    this.SelectRowIndexes = new List<int>();
    for (int i = 0; i < gridViewRecords.Rows.Count; i++)
    {
        DataRowView drv = (DataRowView)gridViewRecords.CurrentRow.DataBoundItem;
        DataRow selectedRow = drv.Row;
        ResourceKey = Convert.ToInt32(selectedRow["ResourceAndInstallKey"]);
        this.SelectRowIndexes.Add(ResourceKey);
    }
}

A: What do you actually want to do if this.SelectRowIndexes is null? Currently you're just unconditionally calling Add on it, because both branches of your if statement do the same thing.
Note that it definitely wouldn't be null if you'd assigned a new value to it - but instead in this line, you're declaring a new local variable called SelectRowIndexes:
List<int> SelectRowIndexes = new List<int>();

... which you're then completely ignoring. Perhaps you meant to set the value of the property/field instead?
SelectRowIndexes = new List<int>();

With that change, you should avoid the exception - but you'll still have the basically-broken code. You should almost certainly just get rid of the if check... it's not doing you any good right now.
However, I would suggest that you probably should be declaring a separate local variable for resourceKey - the fact that you're updating an instance variable in a loop is somewhat peculiar... as is the fact that you're not using your loop index at all... you're doing the same thing for each iteration of the loop, using the current row rather than row i. Is that deliberate?
Fundamentally, you might well want to start this code again... it looks like you might just want to use LINQ:
private void GetIndexes()
{
    SelectRowIndexes = gridViewRecords.Rows
        .Cast<DataRowView>()
        .Select(drv => (int) drv.Row["ResourceAndInstallKey"])
        .ToList();
}

A: The this keyword allows you to access a member named SelectRowIndexes within the scope of the class. That member is probably not initialized. Remove the List<int> type declaration and it will be perfect.
private List<int> SelectRowIndexes;
private void GetIndexes()
{
    SelectRowIndexes = new List<int>();
    for (int i = 0; i < gridViewRecords.Rows.Count; i++)
    {
        DataRowView drv = (DataRowView)gridViewRecords.CurrentRow.DataBoundItem;
        DataRow selectedRow = drv.Row;
        ResourceKey = Convert.ToInt32(selectedRow["ResourceAndInstallKey"]);
        if (this.SelectRowIndexes == null)
        {
            this.SelectRowIndexes.Add(ResourceKey);
        }
        else
        {
            this.SelectRowIndexes.Add(ResourceKey);
        }
    }
}


text:
Q: Core Data viewContext not receiving updates from newBackgroundContext() with NSFetchedResultsController In my application, I have a NSFetchedResultsController to load Core Data objects in a UITableView.
The fetch request associated with this FRC uses the new viewContext property available for the NSPersistentContainer (iOS10).
When I select a cell, I pass the Core Data object to a new ViewController. This new VC still uses the viewContext.
From this ViewController, I can update the Core Data object from ViewControllers presented modally. To do so, I use newBackgroundContext() for the modal ViewControllers. I can save the update Core Data object without any issue.
The problem is that the FRC is not automatically updated with the update Core Data object from the background context.
It is as if the viewContext was not receivng and handling the Core Data object updates.
If I set automaticallyMergesChangesFromParent to true for the viewContext (app wide), the FRC gets the updated Core Data object when I save the background context. From my understanding, the viewContext should manage the merge of data automatically. The documentation describes the viewContext with: "This context is configured to be generational and to automatically consume save notifications from other contexts."
Can you clarify how to handle the different contexts with a NSFetchedResultsController?

A: I haven't run into this directly, but your issue strikes me as odd if the newBackgroundContext were in fact layered under the viewContext since any save from the new context would only update the viewContext, which would also have to do its own save to get the changes to the persistent store (which you say is occurring properly).  Based on that suspicion, I looked at the developer docs where Apple says:
Invoking this method (newBackgroundContext() ) causes the persistent container to create and return a new NSManagedObjectContext with the concurrencyType set to privateQueueConcurrencyType. This new context will be associated with the NSPersistentStoreCoordinator directly and is set to consume NSManagedObjectContextDidSave broadcasts automatically.
Thus, it would not be in a parent - child relationship with the viewContext.  Based on the guidance, it seems the new context would be notified of changes by the old, but not vice versa, so you'd have to do a refresh on the viewContext when the new context changes, which you could do programmatically if you can track that in your code or perhaps use one of the change notifications in NSManagedObjectsContext to trigger the action.

A: You're seeing the correct behavior.  If you want your viewContext to automatically pick up changes from other contexts, including ones created by newBackgroundContext(), you have to set automaticallyMergesChangesFromParent to true.
I agree that the docs are confusing on that point, "...and to automatically consume save notifications from other contexts."

A: Automatically merge changes from parent needs to set on the viewContext like this:
persistentContainer.viewContext.automaticallyMergesChangesFromParent = true

A: Not worked for me, So I changed save block from
self.persistentContainer.performBackgroundTask { (context) ... }

to
self.persistentContainer.newBackgroundContext().performAndWait { ... }

and of corse setting true automaticallyMergesChangesFromParent to make auto merge work.
lazy var viewContext: NSManagedObjectContext = {
    self.persistentContainer.viewContext.automaticallyMergesChangesFromParent = true
    self.presistentContainer.viewContext.mergePolicy = NSMergePolicy.mergeByPropertyObjectTrump
    return self.persistentContainer.viewContext
}()

I don't know why the context from performBackgroundTask not merged to viewContext.


text:
Q: Get Fragment from ViewPager Android In my MainActivity I have Transaction my MainFragment.
MainFragment mainFragment = new MainFragment();
getSupportFragmentManager().beginTransaction()
            .replace(R.id.fragment_holder, mainFragment)
            .addToBackStack(mainFragment.getClass().getName())
            .commit();

at my MainFragment I'm using a ViewPager together with a FragmentStatePagerAdapter to host My fragment.
public class TaskPagerAdapter extends FragmentStatePagerAdapter {

private String cookieString = null;

private String userString = null;

public TaskPagerAdapter(FragmentManager fm, Cookie cookie) {
    super(fm);
    this.cookieString = HttpUtil.serializeCookie(cookie);
}

@Override
public Fragment getItem(int position) {
    Fragment fragment = null;

    switch (position) {
        case 0:
            fragment = new NotificationFragment();
            break;
//            case 1:
//                break;
//            case 2:
//                break;
//            case 3:
//                break;
//            case 4:
//                break;

    }
    return fragment;
}

@Override
public int getCount() {
    return 1;
}

@Override
public CharSequence getPageTitle(int position) {
    return new String[]{"رویدادها", "توضیحات", "فرم ها"}[position];
}

@Override
public int getItemPosition(Object object) {
    return POSITION_NONE;
}
}

and in my MainFragment:
   @Override
   public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_main, container, false);
   ButterKnife.bind(this, rootView);
        mPagerAdapter = new TaskPagerAdapter(getFragmentManager(),cookie);
    mViewPager.setAdapter(mPagerAdapter);
    mViewPager.setCurrentItem(0);
  return rootView;

according this link I write this commend into main fragment:
                mViewPager.setCurrentItem(0);

    Fragment page = getActivity().getSupportFragmentManager().findFragmentByTag("android:switcher:" +
            R.id.pager + ":" + mViewPager.getCurrentItem());
    NotificationFragment fragment = (NotificationFragment) page;
    fragment.setNotificationCallBack(this);

    mCountNotifyTask.getCountNotifyTask();
    return rootView;

but page retrieve null!! what is you suggestion?
I am using this tutorial
I still got null.
NotificationFragment fragment = (NotificationFragment) mPagerAdapter.getRegisteredFragment(0);

A: Instead of using activities fragment manager, use ChildFragmentManager in your MainFragment
 mPagerAdapter = new TaskPagerAdapter(getChildFragmentManager(),cookie);
 mViewPager.setAdapter(mPagerAdapter);
 mViewPager.setCurrentItem(0);

And to get the fragment use the child fragment manager
Fragment page = getChildFragmentManager().findFragmentByTag("android:switcher:" +
        R.id.pager + ":" + mViewPager.getCurrentItem());
NotificationFragment fragment = (NotificationFragment) page;

Remember: ViewPager adds and removes fragment based on its current position
I would suggest to keep all the fragment instance in the adapter as an ArrayList and retrive them when you need it based on the position index


text:
Q: ModuleNotFoundError: No module named 'impassionuser' I'm using django on vscode, and typed this on terminal:
(impassion) Subinui-MacBook-Pro:impassion_community subin$ python3 manage.py makemigrations

but can't use makemigrations
got this error message
ModuleNotFoundError: No module named 'impassionuser'

how can I solve this problem?
I'm using MacOSX, VSCode, django
and setup virtualenv
I expected to see follow  messages
Migrations for 'impassionuser':
 impassionuser/migrations/0001_initial.py
 -Create model impassionuser

In settings.py, I already added 'impassionuser'
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'impassionuser',
    'board'
]

A: Did you register your model in admin.py.
 # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib import admin
from .models import mymodel

admin.site.register(mymodel)

Hopefully this will help.
Also check this Django Tutorial


text:
Q: How do I reward diversity in the prediction results of my model? For example, say I have two models that try to predict some labels y.
y = [-1, 0, 1]

model 1 prediction:
x = [0, 0, 0]
rmse: 1
mae: 1

model 2 prediction:
x = [-2, 0, 2]
rmse: 1
mae: 1

Both models have the same rmse and mae but clearly model 2 is better because it conveys more information about whether or not the target variable is positive or negative. What loss function can I use to reward diversity in the prediction of model 2?


text:
Q: Try/Catch block does not actually execute the get-eventlog cmdlet For some reason, when I try to use the security option, it does not actually execute the get-eventlog cmdlet, but writes it to the screen as though it were quoted. The other logs work without the try catch block, but whenever I set them up with the try catch block, they still function as though the cmdlet were quoted.
$eventlogname = Read-Host "Which event log category do wish to view? Enter Application, Security, Setup, System, or Forwarded events"
$lognumber = Read-Host "Enter the number of logs you wish to retrieve"

switch
    ($eventlogname)
{
     Security {
            $logseverity = Read-Host "What event severity do you wish to view? Enter Critical, Warning, Error, FailureAudit, SuccessAudit, or Information"
            $computernameeventlog = Read-Host "Please enter the hostname to query"

            if ($computernameeventlog -eq "localhost" )
            {
            try
                {
                    {
                    Get-EventLog -logname $eventlogname -EntryType $logseverity -Newest $lognumber -ErrorAction SilentlyContinue
                    }

                            }
                            catch [System.IO.IOException]
                            {
                                Write-Host "The hostname was incorrect or not available."
                            }
                            catch [System.InvalidOperationException]
                            {
                                Write-Host "The event log does not exist"
                            }
                    }
             else
                {

             try{
                    {
                        Get-EventLog -logname $eventlogname -EntryType $logseverity -ComputerName $computernameeventlog -Newest $lognumber -ErrorAction SilentlyContinue
                    }
                        }
                            catch [System.IO.IOException]
                            {
                                Write-Host "The hostname was incorrect or not available."
                            }
                            catch [System.InvalidOperationException]
                            {
                                Write-Host "The event log does not exist"
                            }
                    }
                }

     "Forwarded events"
     {
        $computernamewinevent = Read-Host "Please enter the hostname to query"
        $logseverity = Read-Host "What event severity do you wish to view? Enter Critical, Warning, Error or Information"
        if ($computernamewinevent -eq "localhost")
        {
            Get-WinEvent -logname forwardedevents -MaxEvents $lognumber | where {$_.leveldisplayname -contains $logseverity}
        }
        else
        {
            Get-WinEvent -logname forwardedevents -MaxEvents $lognumber -ComputerName $computername | where {$_.leveldisplayname -contains $logseverity}
        }
    }
    default
    {
    $logseverity = Read-Host "What event severity do you wish to view? Enter Critical, Warning, Error or Information"
    $computernameeventlog = Read-Host "Please enter the hostname to query"

    if ($computernameeventlog -eq "localhost" )

        {
            Get-EventLog -logname $eventlogname -EntryType $logseverity -Newest $lognumber
        }

    else
        {
            Get-EventLog -logname $eventlogname -EntryType $logseverity -ComputerName $computernameeventlog -Newest $lognumber
        }
}
}

A: In your code you have surrounded the command with brackets ({ }) such as this:
{
Get-EventLog -logname $eventlogname -EntryType $logseverity -ComputerName $computernameeventlog -Newest $lognumber -ErrorAction SilentlyContinue
}

This will produce a script block, which will not execute but output as a string. What you want is remove the brackets.

A: If you were to fix the various bracket issues that Micky mentioned, your Catch block would still never run.  In the Try block, you must force a terminating error.  You forced it to completely ignore errors:
#Note the changed error action:
Get-EventLog -logname $eventlogname -EntryType $logseverity -Newest $lognumber -ErrorAction Stop

#Get some help on the topic:
Get-Help about_Try_Catch_Finally

Further reading that might help:

*

*about_Try_Catch_Finally

*PowerShell.org eBooks - Big Book of PowerShell Error Handling

*An Introduction to Error Handling in PowerShell

Lastly, on an aside, consider more readable formatting.  Some popular choices:
Try
{
    #Do something
}
Catch
{
    #Catch
}

Try {
    #Do something
}
Catch {
    #Catch
}

Many have strong feelings for and against these and other conventions, but as long as you are consistent, you should be good.  I see a bit of the first example, but then some cases where you indent the first curly bracket instead of lining it up with the keyword.
Cheers!


text:
Q: Send XML to a web service c# How I can send XML to a web service from C#(.NET)?
Not using "add references"
And I want get response from the service
This code has no exceptions, but I think app can't autorize in web service
I do so
class Program
{
    static void Main(string[] args)
    {
        string xml = "<message>"+
        "<service id="+"single"+" source = "+"AlphaName"+"/>"+
        "<to>number</to>"+
        "<body content-type="+"text/plain"+">"+
        "This is a sample message"+
        "</body>"+
        "</message>";
        Program prog = new Program();
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://api.life.com.ua/ip2sms/");
        request.Credentials = new NetworkCredential("login", "password");
        byte[] authBytes = Encoding.UTF8.GetBytes("login:password".ToCharArray());
        request.Headers["Authorization"] = Convert.ToBase64String(authBytes);
        prog.requests(xml);

}

}
XML request
String requests(string xml)
    {
        WebResponse result = null;
        WebRequest req = null;
        Stream newStream = null;
        Stream ReceiveStream = null;
        StreamReader sr = null;
        string strOut = "";
        try
        {
            req = WebRequest.Create("https://api.life.com.ua/ip2sms/");
            req.Method = "POST";
            req.Timeout = 120000;
            //req.ContentType = "text/xml; charset = \"utf8\"";
            req.ContentType = "application/x-www-form-urlencoded";
            byte[] SomeBytes = null;
            SomeBytes = UTF8Encoding.UTF8.GetBytes(xml);
            req.ContentLength = SomeBytes.Length;
            newStream = req.GetRequestStream();
            newStream.Write(SomeBytes, 0, SomeBytes.Length);
            newStream.Close();
            // считываем результат работы
            result = req.GetResponse();
            ReceiveStream = result.GetResponseStream();
            Encoding encode = Encoding.UTF8;
            sr = new StreamReader(ReceiveStream, encode);
            Char[] read = new Char[256];
            int count = sr.Read(read, 0, 256);
            while (count > 0)
            {
                String str = new String(read, 0, count);
                strOut += str;
                count = sr.Read(read, 0, 256);
            }

        }
        catch (Exception ex)
        {
        }

        return strOut;
    }

but nothing happens.Thanks!