text:
Q: Error: Rack app won't run -- bundler/setup I'm completely new to Ruby (and RoR) and I'm trying to set up a local environment to help work on a site. Ideally, I would work on it locally, and then commit the changes to github and push it further down the pipeline from there.
I'm on a brand new Macbook Pro running OSX Lion.
I have had much trouble trying to get it work:

*

*Installed Xcode Command Line Tools and RVM couldn't install latest version of ruby because it failed to compile with LLVM (Lion default compiler)

*compiled ruby using a special flag it asked me to use (forgot what it was), but then was having trouble with Postgres and Pow

*Tried installing a standalone GCC to compile ruby correctly thinking it may solve the problem. Pow still gave me errors.

I have tried removing and installing everything I could think of, and still nothing. I stress: I'm a noob.
I finally found a script called railsready that sets up ruby and RoR for you (https://github.com/joshfng/railsready) which failed to recognize Xcode since Lion installs it into Applications (the script checked for it by looking for an Xcode .plist file in Library/Developer). The author helped be out by updating the code to look for gcc instead and it tried installing but failed because it couldn't write to my .bash_profile. I removed it and tried it again, and it worked.
I installed Pow so I can have it run on a custom domain (website.dev) and have multiple apps under different domains. Now it's giving me this error and I have no idea what it means or how to go about it.
I would really appreciate any help. Most ruby guys I talk to have no idea what this is about, and why Lion is so much trouble to set up on. They are on older (Snow Leopard) machines.
The Error
Your Rack app raised an exception when Pow tried to run it.
LoadError: no such file to load -- bundler/setup
/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require'
/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/rubygems/custom_require.rb:31:in `require'
~/Github/letsordernow/config/boot.rb:6
~/Github/letsordernow/config/application.rb:1:in `require'
~/Github/letsordernow/config/application.rb:1
~/Github/letsordernow/config/environment.rb:2:in `require'
~/Github/letsordernow/config/environment.rb:2
~/Github/letsordernow/config.ru:3:in `require'
~/Github/letsordernow/config.ru:3
~/Library/Application Support/Pow/Versions/0.3.2/node_modules/nack/lib/nack/builder.rb:4:in `instance_eval'
~/Library/Application    Support/Pow/Versions/0.3.2/node_modules/nack/lib/nack/builder.rb:4:in `initialize'
~/Github/letsordernow/config.ru:1:in `new'
~/Github/letsordernow/config.ru:1

A: Welcome to Ruby On Rails.  :)
You're going to love the new Rails.app Kickstarter project by Yehuda Katz:
http://www.kickstarter.com/projects/1397300529/railsapp
My advice for now:

*

*Standalone GCC is good. You're doing this right.

*To use RVM with Lion and non-LLVM, read about compiling Ruby with clang:  Can't install Ruby under Lion with RVM – GCC issues

*In each of your Rails projects, run this which may clean up your Pow issues:
bundle install

*Make sure each of your projects has a .rvmrc file pointing to the correct ruby version and gemset.

*My two cents is to try to get up and running without RVM and Pow to start. These aren't needed and they have quirks with paths and glitches (IMHO). I personally prefer to use bundler to manage gemsets, and the rbenv tool and ruby-build tool for managing Ruby versions. See https://github.com/sstephenson/rbenv

*Pow is nifty but tricky. It has a history of quirky setup (IMHO). My two cents is to get up and running with webrick first (i.e. make sure you can do "rails s" to start a local server) and then I personally like Apache and Passenger (or Thin). For Pow help on quirky setup see https://github.com/37signals/pow/issues/119


text:
Q: Remove subview from view I want to know how can I remove my HUD subview from the main view
+ (SLHUD *)Mostrar:(UIView *)view{

SLHUD *hudView = [[SLHUD alloc] initWithFrame:view.bounds]; // Creates an instance of the object.

hudView.opaque = NO;
[hudView setTag:899];
[view addSubview:hudView]; // Adds the HUD as a subview on top of the view object.

view.userInteractionEnabled = NO; // Sets the user interaction to no because we don't want the user to interact with the HUD.

[hudView showAnimated]; // Calls the method showAnimated to perform an animation.

return hudView; // Returns the object to the caller.
}

Thanks!

A: SLHUD *hudView = (SLHUD *)[view viewWithTag:899];
[hudView removeFromSuperview];

A: Just [[view viewWithTag:899] removeFromSuperview]

redpajama_set_name: RedPajamaStackExchange


text:
Q: Trying to understand what "save_for_backward" is in Pytorch I have some knowledge in Pytorch,but i don't really understand the mechanisms of classes within Pytorch.
For example in the link: https://pytorch.org/tutorials/beginner/examples_autograd/two_layer_net_custom_function.html
you can find the following code:
import torch

class MyReLU(torch.autograd.Function):

    @staticmethod
    def forward(ctx, input):
        ctx.save_for_backward(input)
        return input.clamp(min=0)

    @staticmethod
    def backward(ctx, grad_output):
        input, = ctx.saved_tensors
        grad_input = grad_output.clone()
        grad_input[input < 0] = 0
        return grad_input

i am only focusing on the forward method of this class,and i am wondering what
ctx.save_for_backward(input)

does.Whether the previous line of code is present or not is irrelevent when i try the forward method on a concrete example:
a=torch.eye(3)
rel=MyReLU()
print(rel.forward(rel,a))

as i get the same result in both cases.Could someone explain me what is happening and why it is useful to add the save_for_backward?
Thank you in advance.

A: The ctx.save_for_backward method is used to store values generated during forward() that will be needed later when performing backward(). The saved values can be accessed during backward() from the ctx.saved_tensors attribute.


text:
Q: What is the quickest / easiest way to create a new file in the command line? I'm sure that there are many ways to do this (cat > foo.txt, vim, etc) a la https://www.cyberciti.biz/faq/create-files-in-linux-unix-from-bash/ but I'm not advanced enough to understand if there's anything else that's being done by using these different commands to create my file (e.g., perhaps a file created in vim has different properties than one created with the cat command above).
Looking to maximize ease, speed and purity (no additional properties) of the file created. Thanks!

A: Very easy is to use touch :
touch myfile


text:
Q: How do I remove an attribute and an element if an ancestor's attribute holds a certain value using xsl I am struggling with the following issue:
In the below XML, I need to remove the attribute restrict="restrict" if the attribute is nested within an element that also contains an attribute restrict="restrict". I also need to remove the element restrict if it is nested within an element containing an attribute restrict="restrict". However, if a restrict="restrict" appears on a nested element whose ancestor does not contain an attribute restrict="restrict", I need to keep it. The same goes for the restrict element. I need to keep it if it is not nested in a restrict element or within an element that does not have the restrict="restrict" attribute.
<book hasrestrict="yes">
<story> <part partno="1"> <parttitle>Title of the Part</parttitle>
<chapter chapno="11"> <chaptertitle>Title of the Chapter</chaptertitle>

<sectiontitle>Title of the Section</sectiontitle>
<toc/>
<subsection1 restrict="restrict">
<date>(09-23-2012)</date>
<title>Subsection Title</title>

Text that makes up the paragraph of the subsetion1. <restrict>This information is
restricted.</restrict>

Here is some text in another paragraph that is
restricted. The restrict attribute of the paragraph needs to be
removed because a restrict attribute is already specified for
subsection1. Everything that appears within the element of subsection
1 is already restricted, so I need to remove the unnecessary restrict
attribute from the paragraph because it is causing havoc when my
publishing system tries to format the document.

<subsection2><title>Title of Subsection2</title>

This is text that appears in a subsecion2 paragraph.
<list>
This is an item in a list <restrict>that has restricted content</restrict>

Second item

Third item
</list>

<subsection3 restrict="restrict">
<title>Title of Subsection3</title>

Text appearing in a paragraph in subsction 3

 <tgroup cols="3" colsep="1" rowsep="1">
<colspec colname="col1"/> <colspec colname="col2"/>
<colspec colname="col3"/>

<row><entry>Entry1</entry>
<entry>Entry2</entry>
<entry>Entry3 <restrict>with restricted information</restrict></entry></row>

<row><entry restrict="restrict">text</entry>
<entry>text</entry>
<entry>text</entry></row>

</tgroup>

</subsection3></subsection2></subsection1>
<subsection1><date>(09-23-2012)</date>
<title>Subsection Title</title>

Text that makes up the paragraph of the subsetion1. <restrict>This information is
restricted.</restrict>

Here is some text in another paragraph that is
restricted.

<subsection2 restrict="restrict"><title>Title of Subsection2</title>

This is text that appears in a subsecion2 paragraph.

</subsection2></subsection1>
</chapter></part></story></book>

I am new to xsl, and have attempted to write the translation, but I am not having much luck.
The desired out put should look like this:
<book hasrestrict="yes">
<story>
<part partno="1">
<parttitle>Title of the Part</parttitle>
<chapter chapno="11">
<chaptertitle>Title of the Chapter</chaptertitle>

<sectiontitle>Title of the Section</sectiontitle>
<toc/>
<subsection1 restrict="restrict"><date>(09-23-2012)</date>
<title>Subsection Title</title>

Text that makes up the paragraph of the subsetion1. This information is restricted.

Here is some text in another paragraph that is restricted. The restrict attribute of the paragraph needs to be removed because a restrict attribute is already specified for subsection1. Everything that appears within the element of subsection1 is already restricted, so I need to remove the unnecessary restrict attribute from the paragraph because it is causing havoc when my publishing system tries to format the document.

<subsection2><title>Title of Subsection2</title>

This is text that appears in a subsecion2 paragraph.
<list>

This is an item in a list that has restricted content

Second item

Third item
</list>

<subsection3><title>Title of Subsection3</title>

Text appearing in a paragraph in subsction 3

<tgroup cols="3" colsep="1" rowsep="1">
<colspec colname="col1"/>
<colspec colname="col2"/>
<colspec colname="col3"/>

<row><entry>Entry1</entry>
<entry>Entry2</entry>
<entry>Entry3 with restricted information</entry></row>

<row>text</entry>
<entry>text</entry>
<entry>text</entry></row>
</tgroup>

</subsection3></subsection2></subsection1>
<subsection1><date>(09-23-2012)</date>
<title>Subsection Title</title>
Text that makes up the paragraph of the subsetion1. <restrict>This information is restricted.</restrict>

Here is some text in another paragraph that is restricted.

<subsection2 restrict="restrict"><title>Title of Subsection2</title>
This is text that appears in a subsecion2 paragraph.
</subsection2></subsection1>
</chapter></part></story></book>

Here is the code I have attempted:
<xsl:transform version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="@* | node()">
  <xsl:copy>
    <xsl:apply-templates select="@* | node()"/>
  </xsl:copy>
</xsl:template>

<xsl:template match="@restrict">
  <xsl:if test="ancestor::*[@restrict='restrict']">
    <xsl:copy>
      <xsl:apply-templates/>
    </xsl:copy>
  </xsl:if>
</xsl:template>

<xsl:template match="restrict">
  <xsl:if test="ancestor::*[@restrict='restrict']">
    <xsl:copy>
      <xsl:apply-templates/>
    </xsl:copy>
  </xsl:if>
</xsl:template>

<xsl:template match="restrict">
  <xsl:if test="ancestor::restrict">
    <xsl:copy>
      <xsl:apply-templates/>
    </xsl:copy>
  </xsl:if>
</xsl:template>
</xsl:transform>

This is not working for me. I receive an error stating
"WARNING org.xml.sax.SAXParseException: The child axis starting at an attribute node will never select anything"
I really don't know how to go about doing this. Any suggestions (and explanation) would be greatly
appreciated.

A: As you are using the identity template, you don't really need to code extra logic for the elements or attributes you wish to keep; whether they are restrict ones or not. You only really need to add templates for the things you wish to remove.
You say "need to remove the attribute restrict="restrict" if the attribute is nested within an element that also contains an attribute restrict="restrict". Well, the template to do this would be like so:
<xsl:template match="../ancestor::*[@restrict='restrict']]" />

(The .. here is to ignore the current element which has the current restrict element)
And to "to remove the element restrict if it is nested within an element containing an attribute restrict="restrict".", the template would look like this
<xsl:template match="restrict[ancestor::*[@restrict='restrict']]" />

Having said that, you mention about keeping restrict elements if they are not nested in a restrict element or within an element that does not have the restrict="restrict" attribute. In this case, the templates may need to look like this:
<xsl:template match="@restrict[../ancestor::restrict or ../ancestor::*[@restrict='restrict']]" />
<xsl:template match="restrict[ancestor::restrict or ancestor::*[@restrict='restrict']]" />

Try this XSLT
<xsl:transform version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
    <xsl:strip-space elements="*"/>
    <xsl:template match="@* | node()">
      <xsl:copy>
        <xsl:apply-templates select="@* | node()"/>
      </xsl:copy>
    </xsl:template>

    <xsl:template match="@restrict[../ancestor::restrict or ../ancestor::*[@restrict='restrict']]" />
    <xsl:template match="restrict[ancestor::restrict or ancestor::*[@restrict='restrict']]" />
</xsl:transform>

A: If I understand this correctly, you want to do:
XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="@restrict[.='restrict'][parent::*/ancestor::*/@restrict='restrict']"/>

<xsl:template match="restrict[ancestor::*/@restrict='restrict']">
    <xsl:apply-templates select="@*|node()"/>
</xsl:template>

</xsl:stylesheet>


text:
Q: Why my php page is not sending mail When I reload the page a link is shown send mail but when I click this link ,it doesnt redirect to send mail, whats wrong with my code?
<?php
echo 'Emil now';
?>

please help, thanks!

A: You are adding // before the mailto this is the main problem with your coding!>I have improved your code bellow, hope this helps!
<?php
echo 'Emil now';
?>

A: Remove the two slashed before "mailto"
<?php
echo 'Emil now';
?>

A: Have a look here:
http://de.selfhtml.org/html/verweise/email.htm
I think you just Need to remove the two // in the link


text:
Q: Print the key of the max value in a dictionary the pythonic way Given a dictionary d where the key values pair consist of a string as key and an integer as value, I want to print the key string where the value is the maximum.
Of course I can loop over d.items(), store the maximum and its key and output the latter after the for loop. But is there a more "pythonic" way just using just a max function construct like
print max(...)

A: print max(d.keys(), key=lambda x: d[x])

or even shorter (from comment):
print max(d, key=d.get)


text:
Q: Multiple values for one variable I have a custom plugin that was written by someone, I can't reach anymore.
It has a search option, that produces a table with seminars in different cities.
Right now I can have a query with this shortcode:
[kurssuche class="course_search" place="1"]

that shows a table with all seminars in the city "1". How can I produce a table which shows seminars for two or more cities?
I'm new to this, any help is much apprechiated!
This is the code:
    if(isset($_REQUEST['search']) || $atts['place']!='')
    {
        if(isset($_REQUEST['city']) && $_REQUEST['city'])
        {
            $where[] = "city = '".$_REQUEST['city']."'";
        }
        else if($atts['place'] && $_REQUEST['city']!=='0')
        {
            $where[] = "city = '".$atts['place']."'";
        }

            $courseplanList = $wpdb->get_results($query);
        }
    }


text:
Q: Python for .NET - Create an instance of a singelton I'm trying to use python to create an instance of a singleton class. The class looks like this:
public sealed class Test
{
    private Test()
    {

    }

    public static Test GetInstance()
    {
       .......
    }
}

I've tried everything from here:
Python for .NET: How to explicitly create instances of C# classes using different versions of the same DLL?
How can I create an instance of this class in python?

A: I have found a solution.
#set reference
ref = clr.AddReference(r'Assemblypath')

#get type
testType= ref.GetType('Namespace.Test')

#GetUninitializedObject
testUninitialize=System.Runtime.Serialization.FormatterServices.GetUninitializedObject(testType);

#Now it's possible to call the method
test = testUninitialize.GetInstance()


text:
Q: Sorting objects in array when 2 property have same value I have array like below. I wanted to sort these based on object parameter a_weight. I am not able to do this and second thing is this key a_weight can have same value in different objects like show below. Any help sorting this?
[0] => stdClass Object
        (
            [a_priority] => 1
            [a_roleobjectid] => 1
            [a_roleid] => 1
            [a_objectid] => 1
            [a_objecttypeid] => 2
            [a_name] => Object Type
            [a_path] => abc/b
            [a_createddate] => 2012-10-08 11:00:00
            [a_createdby] => 1
            [a_modifieddate] => 2012-10-08 11:05:50
            [a_modifiedby] => 1
            [a_weight] => 1
            [a_cancreate] => 1
            [a_canread] => 1
            [a_canupdate] => 1
            [a_candelete] => 1
            [a_canprint] => 1
            [a_canexport] => 1
        )

    [1] => stdClass Object
        (
            [a_priority] => 1
            [a_roleobjectid] => 2
            [a_roleid] => 1
            [a_objectid] => 2
            [a_objecttypeid] => 2
            [a_name] => Object
            [a_path] => abc/a
            [a_createddate] => 2012-10-08 11:00:00
            [a_createdby] => 1
            [a_modifieddate] => 2012-10-08 11:05:50
            [a_modifiedby] => 1
            [a_weight] => 3
            [a_cancreate] => 1
            [a_canread] => 1
            [a_canupdate] => 1
            [a_candelete] => 1
            [a_canprint] => 1
            [a_canexport] => 1
        )
[2] => stdClass Object
        (
            [a_priority] => 1
            [a_roleobjectid] => 3
            [a_roleid] => 1
            [a_objectid] => 3
            [a_objecttypeid] => 2
            [a_name] => Role
            [a_path] => abc/r
            [a_createddate] => 2012-10-08 11:00:00
            [a_createdby] => 1
            [a_modifieddate] => 2012-10-08 15:19:02
            [a_modifiedby] => 1
            [a_weight] => 1
            [a_cancreate] => 1
            [a_canread] => 1
            [a_canupdate] => 1
            [a_candelete] => 1
            [a_canprint] => 1
            [a_canexport] => 1
        )

A: you need to use the uasort function. More info at http://php.net/manual/en/function.uasort.php
an example for your case would be:
function mysort($a, $b){
    return $a->a_weight < $b->a_weight ? -1 : 1;
}
$objects = uasort($objects, 'mysort');


text:
Q: MVC - The call is ambiguous between the following methods or properties I can't figure out why I'm getting this error. I only have one class with one method in my project that looks like:
public static class Extensions
{
    public static string Chop(this string s, int length)
    {
        ...
        return "";
    }
}

I'm calling this in my View like so:  @item.PostContent.Chop(20)
It's giving me a compiler error:
The call is ambiguous between the following methods or properties: 'Extensions.Chop(string, int)' and 'Extensions.Chop(string, int)'

Any help is appreciated. Thank you.

A: I'm guessing that you have put your Extensions class file in an App_Code folder, is that correct? If so, move it outside of App_Code and get rid of the folder. App_Code has no place in MVC applications which by default are created as Web Application projects as opposed to Web Site projects.
Web Applications are compiled to a dll at build time, and anything in App_Code is also compiled into a separate dll at run time. Hence there being two methods and the ambiguity.


text:
Q: Syntax error after "read" only when script invoked with "bash -s
A: The problem is that read reads from stdin -- the same place your code is coming from.
Thus, instead of reading a line from the user, it reads a line from the file of source, consuming the case command, leaving the rest of the source file syntactically invalid.

Simple Answer: Don't Do That.
bash -s <filename makes sense when the <filename is coming from somewhere not accessible to the copy of bash (like the other side of the SSH connection, or a file that can only be read by a different user), but that's not the case for your example. Thus, you can just stop using the -s argument and the redirection:
ssh -i /pathToKeyFile/keyfile.pem user@server2 'bash /pathToScriptFile/script2.sh'

...or make the prompt conditional...
Another approach is to make the read conditional on there actually being a user listening at the TTY:
if [[ -t 0 ]]; then  # test whether FD 0, stdin, is a TTY
  read -p "DB restore completed. Start JBOSS and FACADE (y/n)" startJBOSS
else
  startJBOSS=y       # no TTY, so assume yes
fi

...or make the prompt read from /dev/tty, and make sure SSH passes it through.
An alternate approach is to read from /dev/tty explicitly, and then to arrange for that to be valid in the context of your script by passing appropriate arguments to ssh:
if read -p "DB restore completed. Start JBOSS and FACADE (y/n)" startJBOSS </dev/tty; then
  : "read $startJBOSS from user successfully" # <- will be logged if run with set -x
else
  echo "Unable to read result from user; is this being run with a TTY?" >&2
  exit 1
fi

...and then, on the other side, using the -t argument to SSH, to force there to be a TTY (if one is available to SSH itself; if not, it won't have a means to read from the user out-of-band either):
ssh -t -i /pathToKeyFile/keyfile.pem user@server2 'bash -s < /pathToScriptFile/script2.sh'


text:
Q: How to efficiently extract delimited strings from a data table in R I have a data table in R with text columns of colon delimited data.  I want to return a matrix/data table of results where one of the delimited values is returned for each cell.
The code pasted below demonstrates the problem and is a working solution.  However, my actual data table is large (a few thousand rows and columns), and the pasted method takes on the order of a minute or two to complete.
I'm wondering if there is a more efficient way to perform this task?  It appears that the sep2 option in fread will be very useful for this problem once implemented.
Thanks!
> # Set up data.table
> DT <- data.table(A = c("cat:1:meow", "dog:2:bark", "cow:3:moo"),
                     B = c("dog:3:meow", "dog:4:bark", "frog:3:croak"),
                     C = c("dingo:0:moo", "cat:8:croak", "frog:1:moo"))
> print(DT)

        A            B           C
1: cat:1:meow   dog:3:meow dingo:0:moo
2: dog:2:bark   dog:4:bark cat:8:croak
3: cow:3:moo   frog:3:croak  frog:1:moo

# grab the second delimited value in each cell
> part_index <- 2
> f = function(x) {vapply(t(x), function(x) {unlist(strsplit(x, ":", fixed=T))[part_index]}, character(1))}

> sapply(DT, f)

    A   B   C
[1,] "1" "3" "0"
[2,] "2" "4" "8"
[3,] "3" "3" "1"

A: 1) sub Try this:
DT[, lapply(.SD, sub, pattern = ".*:(.*):.*", replacement = "\\1")]

giving:
   A B C
1: 1 3 0
2: 2 4 8
3: 3 3 1

2) fread or using fread:
DT[, lapply(.SD, function(x) fread(paste(x, collapse = "\n"))$V2)]

3) matrix Note that similar code would work with plain character matrix without data.table:
m <- as.matrix(DT)

replace(m, TRUE, sub(".*:(.*):.*", "\\1", m))

giving:
     A   B   C
[1,] "1" "3" "0"
[2,] "2" "4" "8"
[3,] "3" "3" "1"

3a) Even simpler (no regular expressions) would be:
replace(m, TRUE, read.table(text = m, sep = ":")$V2)

3b) or using fread from data.table:
replace(m, TRUE, fread(paste(m, collapse = "\n"))$V2)


text:
Q: Why do ASP.NET API call freezes if is called as in official documentation? I was having trouble with making a POST query. I was using this method, strictly copied from the Microsoft documentation.
static async Task<Uri> CreateProductAsync(Product product)
{
    HttpResponseMessage response = await client.PostAsJsonAsync("api/products", product);
    response.EnsureSuccessStatusCode();
    // return URI of the created resource.
    return response.Headers.Location;
}

But the application was freezing on the .PostAsJsonAsync() method.
I figured it out, since the method actually isn't an asynchronous method, the await was stopping the parent thread waiting forever.
So I thought it would be a nice try to remove the await and just extract the response with the parameter:
static async Task<Uri> CreateProductAsync(Product product)
{
    HttpResponseMessage response = client.PostAsJsonAsync("api/products", product).Result;
    response.EnsureSuccessStatusCode();

    // return URI of the created resource.
    return response.Headers.Location;
}

And it worked. So, my question is: why the official documentation doesn't work for me? I guess I am doing something wrong... It works, but probably this is not the way.
Thank you in advance.
UPDATE: this is my code:
Button click listener:
int statuscode = AsyncTaskLogin.RunAsync(data).GetAwaiter().GetResult();

RunAsync method:
public static async Task<int> RunAsync(LoginData login)
{
    client.BaseAddress = new Uri("https://jsonplaceholder.typicode.com/");
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    int responsecode = await CreateLoginAsync(login);
    return responsecode;
}

Create Login Async method:
public static async Task<int> CreateLoginAsync(LoginData login)
{
    HttpResponseMessage response = await client.PostAsJsonAsync("posts/", login);
    //not reaching here unless i remove await tag and add .Response
    response.EnsureSuccessStatusCode();
    return (int) response.StatusCode;
}

A: The problem is that your main method is not async. Because of this, you were forced to call your asynchronous methods synchronously, and therefore also wait for them to complete synchronously. This results in a deadlock, as your main/ui thread is waiting for the async method to complete, but your async method expects the main/ui thread to pass it a SynchronizationContext - which of course, it can't actually do, because its blocked!
You have two solutions:

*

*Async all the way. You turn your main method async and you await your asynchronous call as opposed to doing GetAwaiter().GetResult().

*Use ConfigureAwait(false). You need to use it on every asynchronous call you make down the stack - not just one of them. So both CreateLoginAsync() and PostAsJsonAsync() need to have ConfigureAwait(false) tacked on after them. What this does is make it so that your asynchronous call doesn't ask for a SynchronizationContext when its about to callback, that way a deadlock is avoided.
The second point is considered a bad practice however because every single async call you make now has to have this piece of code tacked on - including libraries etc. Only do this if you absolutely cannot turn your main method async.


text:
Q: How to visualize the propagation of a wave? Waves can be visualized as a waveform, with crests, troughs, wavelength and amplitude. Water waves (wind waves) fits excellent in this model. However, there is many kind of waves in nature. Is it correct to say that all waves propagate in this way?

*

*Pressure waves (sound) is more like a compression and rarefaction, which propagate in a straight line. Is the waveform the wrong approach to those waves? Do they really swing up and down? Or is it the right approach, because the amplitude is too low to be noticed normally?

*Is it correct to assign the waveform to classical electromagnetic waves? Do they really swing up and down as the waveform say? If we for example shine a ray of light in one direction, will the light swing up and down, and the meter over sea level will differ very slightly?

*And what about the quantum mechanical photon and other elementary particles? Is it also correct to model them as a waveform? Does they really swing up and down? This sounds unlikely because of the uncertainty principle of quantum mechanics. However, I see everywhere that the path to a particle is pictured as a waveform. Is this approach completely misleading? If so, what is the correct visualization for the propagation of elementary particles? (I guess I am asking how to visualize the wave function).

A: To answer some of your questions. Indeed sound waves can be thought as compression. They are actually longitudinal waves. The sound propagates by the difference in air pressure and by the appearance of a gradient (sudden) change in the density of air molecules. So you need something in the medium to move in order to have the propagation of sound: That's why you can't hear anything in space.
The electromagnetic waves have transversal nature. They are composed of two fields which are oscillating and generating each other as they move. You can see them as bumps (crests, troughs). If you generate an E.M wave and try to record it, you can see it as a sine wave or other forms (most of them oscillating). Photons are waves or particles depending on what kind of experiment are you studying. For example, in interference, the photon can be seen as a wave. But in photoelectric effect, the photons are considered as articles. The idea of wave-particle duality is a key concept in Q.M.. In a way, it is correct to consider all the particles you know as some"clouds", where that cloud represents the probability amplitude that you will find the particle.
If you want to learn more about waves, the feynmann lectures are a great start :)
Hope this helps!

A: The up and down variations of classical systems are variations in amplitude of sinusoidal descriptions of waves. Wave equations fit wave phenomena classically with sine and cosine functions of space and time.
Take the electromagnetic wave, (light is part of the spectrum) the classical solution of maxwell's equations where the amplitude represents electric and magnetic fields, which are dirrectly connected with the energy transferred by the wave.

Electromagnetic waves can be imagined as a self-propagating transverse oscillating wave of electric and magnetic fields. This 3D animation shows a plane linearly polarized wave propagating from left to right. Note that the electric and magnetic fields in such a wave are in-phase with each other, reaching minima and maxima together

The same is true for acoustic waves, the  rarification and compression propagates the energy sinusoidally in space and time.
In general classical waves have a form of "energy waving" , energy is transferred with the wave.

And what about the quantum mechanical photon and other elementary particles? Is it also correct to model them as a waveform?

It is a wave form which is described by the quantum mechanical wavefunctions, but what is "waving"  is the probability distribution for finding a particle at (x,y,z,t). It is not an energy distribution.

Electron buildup over time

In this double slit experiment one electron at a time:
each individual particle seems random, it is the the accumulated probability distribution that shows wave interference.
The same is true for individual photons. Nothing swings up and down except the probability calculated by the wavefunction's Complex conjugate squared.


text:
Q: Core data / NSFetchedResultsController error I'm having some trouble with core data / NSFetchedResultsController. I'm not entirely sure where the error is as the message is quite vague.
I have an issue with inserting more than one object when the fetched results controller has no objects fetched. The following code will crash with the following error if I try and insert several objects with none fetched already. It doesn't crash if I use it to insert one object, and it doesn't crash if there are already objects fetched.
The crash occurs on the save: method. titles in an NSArray and in this example it contains 5 strings.

Serious application error.  Exception
  was caught during Core Data change
  processing: * -[NSCFArray
  objectAtIndex:]: index (4) beyond
  bounds (1) with userInfo (null)
  * Terminating app due to uncaught exception 'NSRangeException', reason:
  '*** -[NSCFArray objectAtIndex:]:
  index (4) beyond bounds (1)'

NSEnumerator *titleEnumerator = [titles objectEnumerator];
NSString *title;
NSMutableArray *tasks = [NSMutableArray array];
Todo *todo;

while(title = [titleEnumerator nextObject])
{
    todo = (Todo *)[NSEntityDescription insertNewObjectForEntityForName:@"Todo" inManagedObjectContext:managedObjectContext];
    todo.title = title;
    todo.state = [NSNumber numberWithInteger:TodoStateIncomplete];
    todo.priority = [NSNumber numberWithInteger:TodoPriorityNormal];
    todo.timeStamp = [NSDate date];
    todo.dueDate = [NSDate distantFuture];
}

NSError *error;

if(![managedObjectContext save:&error])
{
    NSLog(@"Unresolved error %@ %@", error, [error userInfo]);
    abort();
}

A: Here's a tip from Marcus Zarra (author of Core Data book):
Core Data error when deleting row in tableView
"Try breaking on objc_exception_throw and see what method is throwing the exception. That should help track it down"

A: Errors like this on a Core Data save when using the iPhone SDK generally point at an error in the NSFetchedResultsController delegate methods.  Specifically one of the example pieces of code from Apple is incorrect and frequently produces this error.  I would suggest looking at your delegate methods and compare them with the latest example code as you may find that Apple has updated the example code in the documentation and if you re-copy their code this error can go away.
Hope that helps.

A: I know it's unlikely to be the answer, but since the crash is occuring on save: and I do remember having an odd error with this once... The error I had was fixed this way, I reckon it's worth a shot.
So, with that said, try changing
NSError *error;

to
NSError *error = nil;

A: In my case this implementation was helpful (thank's petert):
- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller{ [self.tableView beginUpdates];  }

- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller{
    [self.tableView endUpdates];}

- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath *)newIndexPath{
switch (type) {
    case NSFetchedResultsChangeInsert:

        [self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
        break;

    case NSFetchedResultsChangeDelete:
        [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
        break;

    case NSFetchedResultsChangeUpdate: {

        NSString *sectionKeyPath = [controller sectionNameKeyPath];
        if (sectionKeyPath == nil){
             break;
        }

        [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationNone];

        break;
    }
    case NSFetchedResultsChangeMove: {

        if (newIndexPath != nil) {

            NSUInteger tableSectionCount = [self.tableView numberOfSections];
            NSUInteger frcSectionCount = [[controller sections] count];
            if (frcSectionCount > tableSectionCount)
                [self.tableView insertSections:[NSIndexSet indexSetWithIndex:[newIndexPath section]] withRowAnimation:UITableViewRowAnimationNone];
            else if (frcSectionCount < tableSectionCount && tableSectionCount > 1)
                [self.tableView deleteSections:[NSIndexSet indexSetWithIndex:[indexPath section]] withRowAnimation:UITableViewRowAnimationNone];

            [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
            [self.tableView insertRowsAtIndexPaths: [NSArray arrayWithObject:newIndexPath]
                                  withRowAnimation: UITableViewRowAnimationRight];

        }
        else {
            [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:[indexPath section]] withRowAnimation:UITableViewRowAnimationFade];
        }
        break;
    }
}}
- (void)controller:(NSFetchedResultsController *)controller didChangeSection:(id<NSFetchedResultsSectionInfo>)sectionInfo atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type{
switch (type) {
    case NSFetchedResultsChangeInsert:
        if (!((sectionIndex == 0) && ([self.tableView numberOfSections] == 1)))
            [self.tableView insertSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
        break;
    case NSFetchedResultsChangeDelete:
        if (!((sectionIndex == 0) && ([self.tableView numberOfSections] == 1) ))
            [self.tableView deleteSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];

        break;
    case NSFetchedResultsChangeUpdate:
        break;
    case NSFetchedResultsChangeMove:
        break;
}}


text:
Q: TableView reloadData() not showing all data, even though the array with values is filled (swift) I have a tableview that I fill with results from an http call. The data is passed on into the array called tripTimes. triptimes contains information about certain trips made during a given day. The starting time of every trip of that day is passed into self.tableData and is inserted into the tableView.
After this, I reload the table and... strange results.
The array tableData gets filled properly, but after I call self.tableView.reloadData() almost all cells are properly filled. However, the first cell is left empty until I tap it or if I wait for about 5 seconds and the last cell is also empty, but it gets the same value as the first cell after the same time.
I think it has to do something with the dispatch_async part, but I'm fairly new to swift and iOS, so I have no clue where to look. When I print the contents of self.tableData inside the dispatch_async function, the array contains the proper values.
Below is the code for my viewController
import UIKit
import Foundation
import SwiftHTTP
class TripSelect: UIViewController, UITableViewDataSource, UITableViewDelegate {

    @IBOutlet weak var dateTextField: UITextField!
    @IBOutlet weak var tableView: UITableView!

    @IBAction func showTrips(sender: AnyObject) {

        //if data is already present in tableData, empty it first
        if self.tripTimes.count != 0 && self.tableData.count != 0 {
            for var i=0; i<self.tripTimes.count; i++ {
                self.tableData.removeObjectAtIndex(0)
                let indexPathToRemove = NSIndexPath(forRow: 0, inSection: 0)
                self.tableView.deleteRowsAtIndexPaths([indexPathToRemove], withRowAnimation: .Automatic)
            }
            dispatch_async(dispatch_get_main_queue(), {
                self.tableView.reloadData()
            })
        }
        var request = HTTPTask()
        request.GET("<MY_URL>", parameters: ["date": dateTextField.text], success: {(response: HTTPResponse) in
            if let data = response.responseObject as? NSData {

                let str = NSString(data: data, encoding: NSUTF8StringEncoding) as String
                let str2 = "\"not enough data for this day\""

                if str != str2 {
                    let json:AnyObject = JSON.parse(str)

                    self.dayLatLongs = json["dayLatLongs"] as Array
                    self.tripTimes = json["tripTimes"] as Array

                    var tripLatLongs:[AnyObject] = self.dayLatLongs[0] as Array
                    var firstTrip:[AnyObject] = tripLatLongs[0] as Array
                    var tripStartTime:String = ""
                    for var i=0; i<self.tripTimes.count; i++ {
                        tripStartTime = self.tripTimes[i]["startTime"] as String
                        //println("\(tripStartTime)")
                        self.tableData.addObject(tripStartTime)
                        let indexPath = NSIndexPath(forRow: 0, inSection: 0)
                        self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
                    }
                    dispatch_async(dispatch_get_main_queue(), {
                        println(self.tableData)
                        self.tableView.reloadData()
                    })
                } else {println(str)}
            }
            },failure: {(error: NSError, response: HTTPResponse?) in
                println("error: \(error)")
        })
    }

    var dayLatLongs:[AnyObject] = []
    var tripTimes:[AnyObject] = []
    var tableData: NSMutableArray! = NSMutableArray()

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.tableData.count
    }
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell: UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell
        cell.textLabel?.text = self.tableData.objectAtIndex(indexPath.row) as? String
        return cell
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        var backgroundView = UIView(frame: CGRectZero)
        self.tableView.tableFooterView = backgroundView
        self.tableView.backgroundColor = UIColor.clearColor()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

UPDATE:
var indexPaths:[NSIndexPath] = [NSIndexPath]()
for var i=0; i<self.tripTimes.count; i++ {
    tripStartTime = self.tripTimes[i]["startTime"] as String
    self.tableData.addObject(tripStartTime)
    indexPaths.append(NSIndexPath(forRow: i, inSection: 0))
}
self.tableView.insertRowsAtIndexPaths(indexPaths, withRowAnimation: .Automatic)

Now the results are shown properly, but only after I 'drag' the table a couple of times.

A: Your problem is in the first if-clause:
 if self.tripTimes.count != 0 && self.tableData.count != 0 {
            for var i=0; i<self.tripTimes.count; i++ {
                self.tableData.removeObjectAtIndex(0)
                let indexPathToRemove = NSIndexPath(forRow: 0, inSection: 0)
                self.tableView.deleteRowsAtIndexPaths([indexPathToRemove], withRowAnimation: .Automatic)
            }
            dispatch_async(dispatch_get_main_queue(), {
                self.tableView.reloadData()
            })
        }

You always remove just the value at index 0 and you don't use the i. So replace all hardcoded 0 with your index i:
 if self.tripTimes.count != 0 && self.tableData.count != 0 {
            for var i=0; i<self.tripTimes.count; i++ {
                self.tableData.removeObjectAtIndex(i)
                let indexPathToRemove = NSIndexPath(forRow: i, inSection: 0)
                self.tableView.deleteRowsAtIndexPaths([indexPathToRemove], withRowAnimation: .Automatic)
            }
            dispatch_async(dispatch_get_main_queue(), {
                self.tableView.reloadData()
            })
        }

A: All credit goes to @A-Live for this answer.
Updated with suggested changes:
To remove cells, I changed the function to
dispatch_async(dispatch_get_main_queue(), {
    if self.tripTimes.count != 0 && self.tableData.count != 0 {
        self.tableData = []
        self.tableView.deleteRowsAtIndexPaths(self.indexPaths, withRowAnimation: .Automatic)
        self.indexPaths = []
    }
})

To add cells, I changed the function to
dispatch_async(dispatch_get_main_queue(), {
    for var i=0; i<self.tripTimes.count; i++ {
        tripStartTime = self.tripTimes[i]["startTime"] as String
        self.tableData.addObject(tripStartTime)
        self.indexPaths.append(NSIndexPath(forRow: i, inSection: 0))
    }
    self.tableView.insertRowsAtIndexPaths(self.indexPaths, withRowAnimation: .Automatic)
})


text:
Q: Why does iTunes display a different total play length and size in the status bar in different views? In iTunes 12 (.4.0.119) different total play length times and total media sizes are displayed in the status bar when in different views of the same media type, music.
For example; when in album grid view the status bar displays as below (line one is normal, line two is after being clicked) —
:
630 albums, 16.5 days, 50.97 GB
630 albums, 12:12:05:43 total time, 50.97 GB

When switching to artist or songs (list) view the status bar will display as below (again; line one is normal, line two is after being clicked) —
:
10,287 items, 29.2 days, 88.69 GB
10,287 items, 29:05:09:55 total time, 88.69 GB

Also, when switching from album grid view to album list view the status bar will also change to as it is in the artist and songs list views.
My only theory is that for some reason in album grid view compilations are not included in the results for the status bar though the number of albums (630) must include these still.

A: One way to figure out what's causing the difference involves creating a couple of playlists.

*

*In each library (Albums and Songs), select all, and press command-shift-N (new playlist from selection). Name them anything you like, but let's call these Playlist 1 and Playlist 2.

*From the File menu, create a new Smart Playlist with the following rules:

*

*Playlist is Playlist 1

*Playlist is not Playlist 2

*If the resulting playlist is empty, swap around the is/is not.

You should now see everything that appears in one view but not the other. Like David's comment said, it's most likely due to around 37 GB worth of tracks with a blank album tag, but now you should be able to figure out if it's something else.


text:
Q: How to check if named view exists in vue-router I am implementing a user role based dashboard where route view will be rendered upon role.
root view: (name is changed on user role)
<template v-if="user">
    <router-view :name="user.type"></router-view>
</template>
<template v-else>
    <router-view></router-view>
</template>

and my route:
{
      path: '/recordings',
      name: 'Recording',
      components: { default: NotFoud, shows: Recording },
      meta: {
        requiresAuth: true,
        title: 'Recording'
      },
      children: [],
    },

my concern is, for 'admin' role there is no component defined for /recording route and i want to show some default message if admin user trying to go to recording
how to check if there any named view component named admin for recording route exists and if not then push user to default view

A: I solve the problem of change dashboard for different role user, using the same route, but changing the component to load.
Assuming you have AdminDashboard for admin role and ClientDashboard  for clients.
In my case, when the user is logged, store the role with Vuex
<template>
  <div class="dashboard-container">
    <component :is="currentRole" />
  </div>
</template>

<script>
import { mapGetters } from 'vuex';

import AdminDashboard from '@/views/dashboard/adminDashboard';
import ClientDashboard from '@/views/dashboard/clientDashboard';

export default {
  name: 'Dashboard',
  components: { AdminDashboard , ClientDashboard },
  data() {
    return {
      currentRole: 'AdminDashboard ',
    };
  },
  computed: {
    ...mapGetters([
      'role',
    ]),
  },
  created() {
    if (this.role==='client'){
      this.currentRole = 'ClientDashboard';
    }
  },
};
</script>


text:
Q: How does scipy's Kruskal-Wallis compute its H-value? My textbook states the following formula to calculate the H-value of the Kruskal-Wallis test (without tie ranks):

Let's use this formula to compute H for a really simple example dataset:

*

*group 1 measurements: 10, 20

*group 2 measurements: 30, 40

In the give example dataset the population size $N = 4$. The population consists of two groups each having two members ($n_i = 2$ for all $i$). When we rank the data we see, that group 1 contains rank 1 and 2, while group 2 contains rank 3 and 4. The squared sums of ranks for the groups are therefore $R_1^2=(1+2)^2=9$ and $R_2^2=(3+4)^2=49$. If we fill this into the formula we and up with
$H = \frac{12}{4*3}*(\frac{9}{2}+\frac{49}{2})-3*5 = 14$
So H should be 14. However, if I use the Kruskal-Wallis implementation of scipy I get a H-value of about 2.4.
from scipy.stats import kruskal

res = kruskal(np.array([10, 20]), np.array([30, 40]))
print(res)

What am I doing wrong in my computation?

A: Forget about it, checking the scipy code I realized that the formula in my textbook is just false.
Correct formula starts with $\frac{12}{N(N+1)}$ not with $\frac{12}{N(N-1)}$


text:
Q: if statement not working properly in jquery I have two arrays: arr and myArraycode. Both have some values retrieved from a database. The values of myArraycode are displayed in select on each row. Now I need to disable all rows which have a value not appearing in the arr array.
For example,
arr =["abc","cde"];
myArraycode=["sample","abc","cde"];

I have three table rows which have sample in one row, abc in another and cde in a third. Now i need to disable the row with sample because sample is not in the array arr.
I have tried the following code:
var kt = 0;
var kts = 0;

var sk=0;
var sv =0;

while(kt < myArraycode.length)
{
    if($.inArray(myArraycode[kt],arr) === -1 )
    {

        $("#table tr").find('td').find("select:contains("+myArraycode[kt]+")").closest('tr').find('input[type=text]').attr("disabled","disabled");;

        $("#table tr").find('td').find("select:contains("+myArraycode[kt]+")").closest('tr').find('select').attr("disabled","disabled");;
    }
    kt++;
}

Please help me to solve the problem.
Demo

A: arr =["abc","cde"];
myArraycode=["sample","abc","cde"];

for(var i=0; i < myArraycode.length; i++)
{
   if($.inArray(myArraycode[i],arr) === -1 )
   {
   $('option[selected="selected"]:contains("'+myArraycode[i]+'")').parent().attr('disabled','disabled');
 }
}

I've corrected some of the syntax errors, but this should do the trick for you
For performance reasons you could also either use a decremental for loop or save the array.length value in a variable so the loop doesn't need to recalculate the value every run
I have updated your answer in jsfiddle
Note that the HTML requires the selected attribute for this to work
<option value="sample" selected="selected">sample</option>

A: I tried the following code to disable select box having selected value as sample
$( document ).ready(function(e){

arr =["abc","cde"];
myArraycode=["sample","abc","cde"];

for(var i=0; i < myArraycode.length; i++)
{
   if($.inArray(myArraycode[i],arr) === -1 )
   {
$("select").each(function(){

    if($(this).val() == myArraycode[i])
    {
        $(this).closest('tr').find('select').attr('disabled','disabled');

    }
});

 }
}

});

Demo


text:
Q: How to disable jquery ui combobox? I use standard code taken from this page and try to disable combobox:
$( "#cbCountry" ).combobox({ disabled: true });

But it is still enabled. What is wrong here?

A: I had to disable the combo box on click of button in my web application. Thanks to the people who have commented here. I was able to figure how to disable and enable the combo box as and when required. The code is as follows.
The below code is for disabling the combo box
$("#MyComboboxId").parent().find("input.ui-autocomplete-input").autocomplete("option", "disabled", true).prop("disabled",true);
$("#MyComboboxId").parent().find("a.ui-button").button("disable");

The above JavaScript code finds the HTML elements for the ID and rest is explained in the above posts.
The below code is for enabling the combo box
$("#MyComboboxId").parent().find("input.ui-autocomplete-input").autocomplete("option", "disabled", false).prop("disabled",false);
$("#MyComboboxId").parent().find("a.ui-button").button("enable");

A: That code is for initializing a disabled combobox. If you want to disable an existing combobox, use this:
$("#cbCountry").combobox("option", "disabled", true);

UPDATE
Combobox is a separate jQuery UI widget, and it seems it does not implement these options. I was able to disable it by finding the text field and button inside the widget, and disabling those:
$("#cbCountry").closest(".ui-widget").find("input, button" ).prop("disabled", true)

A: Easy modification to combobox library to use:
$("#cbCountry").combobox('disable');
$("#cbCountry").combobox('enable');

In your combobox.js file add:

*in _create: function() add local variable "a" (after var input, a ...).

*Change input = $("<input>") to input = this.input = $("<input>").

*Change a = $("<a>") to a = this.a = $("<a>").

*Insert after destroy:
disable: function() {
    this.input.prop('disabled',true);
    this.input.autocomplete("disable");
    this.a.button("disable");
},
enable: function() {
    this.input.prop('disabled',false);
    this.input.autocomplete("enable");
    this.a.button("enable");
}


text:
Q: Using Local Storage to Store and Display multiple Answers I'm working on a webpage where i'm trying to display a question, and have viewers submit an answer, which appears on another page. Currently, only the most recent answer is shown on the answer page. I'm not sure how to write my function so that it stores and displays all responses. (I'm new to javascript) Thanks!

         What is good design?
   <input id="q2input" type="text" >

 <button onclick="functionTwo()"
   class="sbuttons">Submit</button>

    <button id="ViewAnswers2" class="vabuttons" >View Answers</button>

A: Use an array instead. Currently, all you are doing is overwriting the current value in the question2 answer slot every time. Arrays are ways to store multiple data values into one variable
function functionTwo() {
  var input = document.getElementById("q2input").value;
  var answers = JSON.parse(localStorage.getItem("question2answers")) || [];
  //Not too sure about the || [];
  answers.push(input);
  localStorage.setItem("question2answers", JSON.stringify(answers));
  window.location.href = "WhatIsGoodDesign.html";
}

You cannot directly put an array into LocalStorage, so you have to pass it in and out as a JSON object. JSON.stringify() will turn it into a string that you can pass into LocalStorage, while JSON.parse() will translate that string back into an array.

A: You currently overwrite the key question2 with the new answer each time. If you want a list of the the last answers. You would have to do something along the lines of:
function functionTwo(){
   var input = document.getElementById("q2input").value;
   var numAnswers = localStorage.getItem("question2numAnswers") || 0;
   localStorage.setItem("question2answer" + numAnswers.toString(), input);
   localStorage.setItem("question2numAnswers", numAnswers + 1);
   window.location.href = "WhatIsGoodDesign.html";
}

This way you keep track of the number of answers with question2numAnswers and each answer with question2answer# and you can loop through the answers on your next page by going from 0 to question2numAnswers that you store.


text:
Q: Why is Datatemplate not working properly? I use the code below to display the data, but the result seems to show the ToString() method of the object.
It seems to be failing to recognize that Model is of type model.
I looked at the solution here. My code should work.
Why is the data not showing? What did i do wrong?
Xaml:
  <Window.DataContext>
        <local:MainWindowViewModel/>
    </Window.DataContext>
    <Window.Resources>
        <DataTemplate x:Key="DT" DataType="{x:Type local:model}">
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="200"/>
                    <ColumnDefinition Width="200"/>
                </Grid.ColumnDefinitions>
                <Grid.RowDefinitions>
                    <RowDefinition Height="50"/>
                    <RowDefinition Height="50"/>
                </Grid.RowDefinitions>
                <TextBlock Grid.Row="0" Grid.Column="0">Id</TextBlock>
                <TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding Id}"></TextBlock>
                <TextBlock Grid.Row="1" Grid.Column="0">Name</TextBlock>
                <TextBlock Grid.Row="1" Grid.Column="1" Text="{Binding Name}"></TextBlock>
            </Grid>
        </DataTemplate>
    </Window.Resources>
    <StackPanel>
        <ContentControl Width="400" Content="{Binding Path=Model}"  />
    </StackPanel>

Codebehind:
public class model : ViewModelBase
  {
    private string name;
    public string Name
    {
      get { return name; }
      set
      {
        name = value;
        this.OnPropertyChanged("Name");
      }
    }
    private int id;
    public int Id
    {
      get { return id; }
      set
      {
        id = value;
        this.OnPropertyChanged("Id");
      }
    }

  }

  public class ViewModelBase : INotifyPropertyChanged
  {
    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
      var handler = PropertyChanged;
      if (handler != null)
        handler(this, new PropertyChangedEventArgs(propertyName));
    }
  }
  public class MainWindowViewModel : ViewModelBase
  {
    private model model;
    public model Model
    {
      get { return model; }
      set
      {
        model=value;
        this.OnPropertyChanged("Model");
      }
    }
    public MainWindowViewModel()
    {
      Model = new model() { Id = 5, Name = "John" };
    }
  }

The result is as follows:

A: You must not set the x:Key attribute on the <DataTemplate>, because that breaks the mechanism that automatically applies the DataTemplate:
<DataTemplate DataType="{x:Type local:model}">

See the DataType Remarks:

... When you set this property to the data type without specifying an x:Key, the DataTemplate gets applied automatically to data objects of that type. Note that when you do that the x:Key is set implicitly.


text:
Q: Get objects from table I wrote this function. I am trying to find an object in a table of objects and return a strings table.
public Server(wine[] d) {
   this.d=d;
}

public String[] getData(String name) {
   String[] data = new String[2];
   int i=0;

   while(i < d.length && s != d[i].id)
      i++;

   if (i < d.length) {
      data[0] = d[i].name;
      data[1] = d[i].price;
      return data;
   }
     else System.out.println(s + " Not Found ");

   data[0] = "error";
   data[1] = "error";
   return data;
 }

I got this error
getData  invocation: system exception was thrown.
org.omg.CORBA.MARSHAL: Cannot marshall null string.

I thik the problem is in these two lines:
data[0]= d[i].name;
data[1]= d[i].price;

A: If I understand what you are asking correctly, you want to get the name and price for a type of wine out of an array of wine objects. try this.
public String[] getData(String name)
{
    String[] data = new String[2];
    boolean wineFound = false;

    for (int i = 0; i < d.length; i++)
    {
        if( d[i].name.equals(name) )
        {
        data[0] = name;
        data[1] = d[i].price;
        wineFound = true;
        }
    }

    if (wineFound == true)
        return data;
    else
    {
    data[0] = "error";
    data[1] = "error";
    return data;
    }
}


text:
Q: first in app purchase transaction not working properly ios i am trying to add in app purhase to my Unity3d-IOS project. I use Storekit. I add in app purchases to itunes account properly, also my code is ok (the same in app purchase logic & code work fine with my previous projects). However, currently, my in app purchase works well except the first purchase transaction.
In the first in app purchase either system gives me the purchase before payment (before i click confirm) or transaction does not go proper SKPaymentTransactionState so that i send message to Unity and get my purchase (i.e. even though i make payment and itunes gives me "successful purchase" dialog, it does not call proper purchase method).
Except the first in app purchase attempt, all in app purchases are successful and works well. As i said i've use same logic with my previous projects (which are totaly ok).
What might i can miss? Can anybody help?
*as you may guess, i use sandbox test accounts.
here is my code:
//
//  IAPController.m
//  Unity-iPhone
//
//  Created by dilara on 23/01/15.
//
//

#import "IAPController.h"

@interface IAPController ()

@end

@implementation IAPController

@synthesize productIdentifier;
@synthesize unityAppController;

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    NSLog(@"in viewDidLoad!!!!!!!!!!");
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(id)init
{
    self.iapViewController = unityAppController.rootViewController;

    return self;
}

-(void)dealloc
{
    [super dealloc];
}

-(void)requestProductwithProductID:(NSString *)productID //called by unity
{

    productIdentifier = productID;
    NSLog(@"in custom method (requestProductwithProductID), self.productIdentifier is %@ %s %@", productIdentifier, "param productID is ", productID);

    if([SKPaymentQueue canMakePayments])
    {
        SKProductsRequest *request = [[SKProductsRequest alloc] initWithProductIdentifiers:[NSSet setWithObject:productIdentifier]];
        request.delegate = self;
        [request start];
    }
    else
        NSLog(@"no product found");
}

-(void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response
{
    NSLog(@"in productRequest of SKProductRequestDelegate");
    NSArray *products = response.products;

    if(products.count != 0)
    {
        NSLog(@"in if of productRequest method");
        self.product = products[0];
        productIdentifier = self.product.productIdentifier;
        SKPayment *payment = [SKPayment paymentWithProduct:self.product];
        [[SKPaymentQueue defaultQueue] addPayment:payment];
        [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
    }
    else
    {
        NSLog(@"in else of productRequest method, product not found");
    }

    products = response.invalidProductIdentifiers;

    for(SKProduct *product in products)
    {
        NSLog(@"Product not found: %@", product);
    }
}

-(void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions
{
    NSLog(@"in paymentQueueMethod of SKPaymentTransactionObserver");
    NSLog(@"initial count of transactions %d", transactions.count);

    for(SKPaymentTransaction *transaction in transactions)
    {
        NSLog(@"transaction is %@", transaction.payment.productIdentifier);
        NSLog(@"transaction id is %@", transaction.payment.productIdentifier);
        NSLog(@"original transaction id is %@", transaction.originalTransaction.payment.productIdentifier);

        switch (transaction.transactionState)
        {
            case SKPaymentTransactionStatePurchasing:
                NSLog(@"purchasing");
                break;

            case SKPaymentTransactionStatePurchased:
                NSLog(@"purchased");
                UnitySendMessage("Panel_Store", "buyItem", [self.productIdentifier cStringUsingEncoding:NSUTF8StringEncoding]);
                [[SKPaymentQueue defaultQueue] removeTransactionObserver:self];
                [[SKPaymentQueue defaultQueue] finishTransaction:transaction];

            case SKPaymentTransactionStateRestored:
                NSLog(@"restored");
                [[SKPaymentQueue defaultQueue] removeTransactionObserver:self];
                [[SKPaymentQueue defaultQueue] finishTransaction:transaction];

            case SKPaymentTransactionStateFailed:
                NSLog(@"failed");
                if(transaction.error.code != SKErrorPaymentCancelled)
                {
                    NSLog(@"An error encountered %@", transaction.error.description);
                }
                else
                {
                    NSLog(@"Cancel button is clicked! %@", transaction.error.description);
                }
                [[SKPaymentQueue defaultQueue] removeTransactionObserver:self];
                [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
            case SKPaymentTransactionStateDeferred:
                NSLog(@"waiting for approval");
                break;
        }
    }
    NSLog(@"count of transactions %d", transactions.count);
}

-(void)paymentQueue:(SKPaymentQueue *)queue removedTransactions:(NSArray *)transactions
{
    NSLog(@"in removedTransactions method of SKPaymentTransactionObserver");
}

-(void)paymentQueue:(SKPaymentQueue *)queue restoreCompletedTransactionsFailedWithError:(NSError *)error
{
    NSLog(@"in restoreCompletedTransactionFailedWithError method of SKPaymentTransactionObserver");
    NSLog(@"error in restoreCompletedTransactionFailedWithError is %@", error.description);
}

-(void)paymentQueueRestoreCompletedTransactionsFinished:(SKPaymentQueue *)queue
{
    NSLog(@"in paymentQueueRestoreCompletedTransactionsFinished method of SKPaymentTransactionObserver");
}

-(void)request:(SKRequest *)request didFailWithError:(NSError *)error
{
    NSLog(@"in requestDidFailWith method of SKRequestDelegate error is %@", error.description);
}

-(void)requestDidFinish:(SKRequest *)request
{
    NSLog(@"in requestDidFinish method of SKRequestDelegate");
}

@end


text:
Q: What are the Hempstocks in "The Ocean at the End of the Lane" by Neil Gaiman? We find out that Ursula Monkton is Skarthach of the Keep or "fleas" as the Hempstocks call them, but I can't recall finding out what the Hempstocks are.
I thought they may have been witches, but this extract states otherwise:

'Rowanberry and red thread, stop a witch in her speed,' I recited. It was something I had read in a book. 'That'd work, and work well,' said Lettie, 'if there was any witches involved in all this. But there's not.'

Lettie of course could have been lying, but I don't think so. Does anyone have any idea what the family could be?

A: Gaiman likes to leave his magic and mythology veiled by... well, mythic mists.
The Hempstocks are definitely an incarnation of the Triple Goddess (Mother-Maiden-Crone), they appear quite often in his works (from Sandman to American Gods).
But all you really need to know is that they are the Hempstocks, beings far bigger and far more noble than we can comprehend.

A: I think the Hempstocks are the Triple Goddess, and also the universal feminine principle of creation, at the same time being multi-dimensional beings like those a modern Cosmologist thinks about. So cool that he makes those things work so well together, keeping the mystery of it all.

A: I think they are more complex and yet more simple: they are guardians and came over from the old country, so some form of gods or guardian spirits. Such as in American Gods where Jinn, Leprechauns and gods came over, the same happens here but they protect the boundaries.
Liza Hempstock from the Graveyard book is a witch and believes herself to be one, so you might say there is witch blood related to this, but the Hempstocks at the farm are the real thing.

A: The way I read it, they are an incarnation of the Norse norns, Urd, Verdande and Skuld. Other goddesses or similar exist in several religions, so it can be anything, but then again, for me, it's the Norse, since I'm close to that.


text:
Q: Create React App Error when trying to run command npx create react app: spawn UNKNOWN When I try to run a simple npx create-react-app i received this error:
D:\>npx create-react-app abc
npx: installed 67 in 4.255s

Creating a new React app in D:\abc.

Installing packages. This might take a couple of minutes.
Installing react, react-dom, and react-scripts with cra-template...

Aborting installation.
Unexpected error. Please report it as a bug:
Error: spawn UNKNOWN
    at ChildProcess.spawn (internal/child_process.js:403:11)
    at Object.spawn (child_process.js:553:9)
    at spawn (C:\Users\Gilang\AppData\Roaming\npm-cache\_npx\17768\node_modules\create-react-app\node_modules\cross-spawn\index.js:12:24)
    at C:\Users\Gilang\AppData\Roaming\npm-cache\_npx\17768\node_modules\create-react-app\createReactApp.js:407:19
    at new Promise (<anonymous>)
    at install (C:\Users\Gilang\AppData\Roaming\npm-cache\_npx\17768\node_modules\create-react-app\createReactApp.js:359:10)
    at C:\Users\Gilang\AppData\Roaming\npm-cache\_npx\17768\node_modules\create-react-app\createReactApp.js:485:16
    at processTicksAndRejections (internal/process/task_queues.js:93:5) {
  errno: -4094,
  code: 'UNKNOWN',
  syscall: 'spawn'
}

Deleting generated file... package.json
Deleting abc/ from D:\
Done.

I'm using windows 10 version 20H2 and node v14.15.4.
I've also made an issue on the official create-react-app github here

A: It seems that there is issue with write permission.
Try running npx create-react-app myapp from cmd with elevated permissions, i.e., run cmd as Admin and then try to create / scaffold your app.

A: None of these solutions worked for me, I just reinstalled create-react-app with the following and it fixed the detected issues:
npm install create-react-app
npm audit fix --force
npx create-react-app my-app

A: I guess this error occurred because of unsupported globally install create-react-app.
There is a tiny point in this problem, and it is there is global installs of create-react-app are no longer supported. So at the first, run this command
npm uninstall -g create-react-app

Then  install create-react-app in this way
npm install create-react-app

Then create your react app
npx create-react-app my-app

A: You can try using:
   npm cache clear --force

and retry again.
As per the website https://create-react-app.dev/docs/getting-started/, it is mentioned :

If you've previously installed create-react-app globally via npm install -g >create->react-app, we recommend you uninstall the package using npm uninstall -g create->react-app or yarn global remove create-react-app to ensure that npx always uses the >latest version.

A: Yesterday I was having the same issue. TBH I didn't know what cause it either but after running through some websites and YouTube tutorials I finally discovered the way to solve this problem.
First of all, you need to know what best node version that work on your PC or laptop base on what system it used.
Second, you go to run administration by clicking windows WIN+r, write %tempt% and delete all the files inside but skip those that can not be deleted, then once again write prefetch on search bar in run administration and also delete all the files inside just like before.
After that open Node.js command prompt (you can find it on search explore bar) but don't forget to already installed the Node.js. Click on the arrow and choose run as administrator with that the command prompt interface would be open.
Notice that the default writing already in C:\Windows\System32>, so you need to make the folder inside System32 section in windows. Let's say you make this examplereactjs ( Make sure using non-cap letters, because I don't know why mine won't run if I used caps letter), after that, you can make your npx just like usual so it would be like this:
C:\Windows\system32>cd examplereactjs

Press enter, it would be like this:
C:\Windows\system32\examplereactjs>npx create-react-app examplereactjs

Press enter, and wait for couple minutes. You can start with npm start to open the local host browser.
This method works for me and I found it by accident actually. If this doesn't work for you, I don't know what else can. I'm still a newbie in this field and I have no idea what would cause if you messing with run administration, well I'm just here to help. Anyway let me know if this method works for you as well.

A: if reinstall create-react-app is fail and also you already try to run cmd with admin privileges but still not fix it. Try to disable your antivirus and run it once again, work like a charm for me.

A: On running this command, if this error occur then try to disable antivirus or simply when pop up comes of antivirus then click on the link in the antivirus pop up then there is no error.
Work for me.

A: Well, I had the same issue, try to use "npm audit fix --force".

A: Just Uninstall the antivirus from your system!

A: In my think, it may be caused by a vaccine program blocking access to the network.
Sometimes a free antivirus program is installed without user consent. And as these are executed in real time, even simple installation commands used by developers are often recognized as access to malicious code.
If you have a recently installed antivirus, uninstall it and run 'npx create-reate-app my-app' again at the terminal.

A: uninstalled your antivirus, and most likely it will work. It worked for me.

A: It happened with me too

You just need to uninstalled the antivirus eg window security->Virus & threat protection then go to Manage settings ->disabled the real-time protection if it is disable and you get declaimer of You're having another antivirus then search for RVC endpoint or RAV Antivirus and uninstalled it and then this will enabled  real-time protection and disable it and then try npx create-react-app app-name
hope this works and if doesn't let me know. Thanks

The exact same error


text:
Q: Variable contains nil value in Swift 2 I declared a variable destinationID on top of my class. The first print shows the right content of the variable while the second one has a nil value.
Does anyone know what the problem is?
import UIKit

class ViewController: UIViewController,UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate{

var destinationUserID = String()

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){

        //Opzoeken wat het bijhorende ID is
        let query = PFQuery(className:"_User")
        query.whereKey("username", equalTo:selectedUsername)
        query.findObjectsInBackgroundWithBlock {
            (objects: [PFObject]?, error: NSError?) -> Void in
            // Do something with the found object
            for object in objects! {
               self.destinationUserID = object.objectId!
              print(self.destinationUserID)
            }
            print("try 1 : " + self.destinationUserID)
        }
         print("try 2 : " + self.destinationUserID)
    }

}

A: The print("try 1... statement is inside the block. The print("try 2... is outside the block. The block is executed in the background which means that the search might not have completed when you get to print("try 2....


text:
Q: Force.com IDE - Easy Push of Single File Through Single Key Combo? As anyone who has worked with a development team using a repo can attest to, using the Force.com IDE can be a bit challenging. My team and I have turned off Build Automatically and I originally was using Build All when I was ready to push changes to the server. Unfortunately, this pushes all changed files which is a problem. For different reasons all of the developers are working out of the same sandbox. We also have a unique setup where we are only pulling in subsets of the metadata based on our current project (there are currently multiple custom applications that are in this org). Here is the scenario (we are using git):

*

*A file gets changed by a different developer (could by any metadata as we put all metadata into our repo for each project (i.e., profiles, layouts, classes, pages, etc)

*I don't want that file to be pulled into my local IDE until that developer commits that change. We are trying to get proper change tracking working with our commit history, so I can't just Refresh from Server or anything like that.

*That developer finishes the change and commits it then pushes it to the remote repo.

*I pull down the latest changes, and run a simple Refresh to simply update the files in my IDE.

Here is where the problem comes in. Now that I have updated my IDE, if I use Ctrl+S to Save and Ctrl+B to Build All, all of the changes I just got from the repo will be flagged as changed so the Ctrl+B will automatically attempt to push those changes. This results in the IDE throwing all kinds of errors telling me that my files are conflicting with changes on the remote server.
So, my question is:
Is there a very easy way to only "build" the file I want to save? I know I can right+click the file > Force.com > Save to Server, but I want to replicate that functionality with a simple key combination. Any ideas?

A: Ugh, sounds like a nightmare. The save/build/refresh process gets pretty sucky pretty fast when dealing with group development.
Josh's pointer to the macro seems like the point solution you're looking for.
Have you considered a different workflow though? I would probably do this in one of two ways.

*

*create a script (probably bound to an Eclipse shortcut key) which diffs your local project filesystem against what is committed in source control. Based on changed files, creates a package.xml and uses the Force.com migration tool (Ant) to deploy just those files to the target environment. This would be basically a "build all" for just the files you've worked on since the last commit and would be as fast as the Eclipse build process (it's doing the exact same thing under the covers, except it would only be deploying your locally changed files.)

*get developers into their own sandboxes (I know there can be reasons for not doing this, like you need a full copy sandbox, or the outlandish fees customers have to pay per sandbox, but for true parallel development this is my preferred setup). This takes away the build all issue. Then add a commit hook to your source control repo which deploys all new commits to an integration sandbox, and reports any deployment issues as build failures blamed on the committer.
None of these situations are ideal, so I'd say your best bet is just the macro tool if your overall process is working for you. Seems like it would create bigger issues than having to click a couple times to save to server :)

A: I attempted to leverage Eclipe's macro plugin PracticallyMacro to do one key deployment but it did not record right clicks.
Before the feature is added I came up with a solution using 'TyperTask' keyboard macro but TyperTask as builder could work too:

*

*'TyperTask' can automate tasks based on typed characters - epic.

*

*the trick is to accommodate the context menu 'Save to server' location changes between different files types.

*it includes a browser page refresh but you must update the WINDOW text: {Control}{Alt}S={controldown}s{controlup}{shiftdown}{F10}{shiftup}.s{Delay=200}{altdown}y{altup}{Delay=2000}{altdown}y{altup}{Delay=12000}WINDOW: News Detail{f5}WINDOW: Force.com -


text:
Q: iOS iPhone how to convert a UIImage into a PDF while preserving scale? I got a 640x960 UIImage of the screen, which is nice and crisp when re-displayed on the retina display. I'm thinking of a way to convert this image into a nice crisp PDF document page.
How would I go about converting a UIImage into a PDF page?
Do I need to make the resulting PDF to be 640x960, or does PDF automatically scale content (ex: 320x480 with the scale factor of 2)?
Thank you!

A: You will have to scale it by yourself. This link would help you in converting view to PDF.

A: UIGraphicsBeginImageContext(CGSize size); - not retina
UIGraphicsBeginImageContextWithOptions(CGSize size, BOOL opaque, CGFloat scale) - retina


text:
Q: Efficient Oracle PLSQL stored procedure to return sys_refcursor for similar, but different, SQL statements Am writing a PL/SQL stored procedure which needs to return a sys_refcursor containing JSON derived from a single table.
The SQL will have a consistent SELECT clause, but 2 different WHERE clauses, depending on inputs, and optional offset and fetch next statements.
While I have a brute force implementation, it feels very inefficient with a lot of duplicated code split between 6 IF statements.
Here's a stylized version of this brute force approach:
procedure query_my_table
(
     in_param_1
     ...
     in_param_n
     ...
    in_limit           number,
    in_offset          number,
    ref            out sys_refcursor
) is
begin
    if in_param_n is null then
        if nvl(in_offset, 0) = 0 then
            open ref for
            select json_object( ... cols ...
                    format json) as json
               from my_table
              where col_1 = in_param_1 and col_2 = in_param_2 and col_3 = in_param_3
        elsif nvl(in_limit, 0) = 0 then
            open ref for
            select json_object( ... cols ...
                    format json) as json
               from my_table
              where col_1 = in_param_1 and col_2 = in_param_2 and col_3 = in_param_3
            offset in_offset rows;
        else
            open ref for
            select json_object( ... cols ...
                    format json) as json
               from my_table
              where col_1 = in_param_1 and col_2 = in_param_2 and col_3 = in_param_3
            offset in_offset rows
            fetch next in_limit rows only;
        end if;
    else
        if nvl(in_offset, 0) = 0 then
            open ref for
            select json_object( ... cols ...
                    format json) as json
               from my_table
              where col_n=in_param_n;
        elsif nvl(in_limit, 0) = 0 then
            open ref for
            select json_object( ... cols ...
                    format json) as json
               from my_table
              where col_n=in_param_n
             offset in_offset rows;
        else
            open ref for
            select json_object( ... cols ...
                    format json) as json
               from my_table
              where col_n=in_param_n
             offset in_offset rows;
            offset in_offset rows
            fetch next in_limit rows only;
        end if;
    end if;
exception
    when others then
        if ref%isopen then
            close ref;
        end if;
        -- handle exception
end query_my_table;

Since the only thing that varies is the WHERE clause (including the fetch/offset), I hope it can be written more efficiently.
I have tried building dynamic SQL, but it fails compilation - the pattern I used was:
the_sql := <string with SELECT statement>;
open ref for
   execute immediate the_sql;

Any suggestions would be appreciated!

A: You can rewrite it as:
PROCEDURE query_my_table
(
  in_param_1
  ...
  in_param_n
  in_limit  IN  number,
  in_offset IN  number,
  ref       OUT sys_refcursor
)
IS
BEGIN
  OPEN ref FOR
    SELECT json
    FROM   (
      SELECT json_object(
               ... cols ...
               format json
             ) as json,
             ROW_NUMBER() OVER (ORDER BY something) AS rn
      FROM   my_table
      WHERE  col_1 = in_param_1
      AND    col_2 = in_param_2
      AND    col_3 = in_param_3
      AND    (col_n = in_param_n OR in_param_n IS NULL)
    )
    WHERE (in_offset IS NULL OR in_offset < rn)
    AND   (in_limit  IS NULL OR rn <= in_limit + COALESCE(in_offset, 0));
END query_my_table;


text:
Q: DZNEmptyDataSet is not showing up I'm creating an empty table view and I have added DZNEmptyDataSet to my app. my table view shows the content of an array that is empty. but DZNEmptyDataSet is not showing up.
here is my code:
override func viewDidLoad() {
    super.viewDidLoad()
    tableView.dataSource = self
    tableView.delegate = self
    tableView.emptyDataSetSource = self
    tableView.emptyDataSetDelegate = self
    tableView.tableFooterView = UIView()
}
var emptyStrings: [String] = []
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return emptyStrings.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
   let cell = tableView.dequeueReusableCell(withIdentifier: "newsIdentifier", for: indexPath)
        cell.textLabel?.text = emptyStrings[indexPath.row]
    return cell

}

A: You should DZNEmotyDataset class.
For examples "Swift 4";
    func title(forEmptyDataSet scrollView: UIScrollView) -> NSAttributedString? {
        let str = "Empty Name"
        let attrs = [NSAttributedStringKey.font: UIFont.preferredFont(forTextStyle: UIFontTextStyle.headline)]
        return NSAttributedString(string: str, attributes: attrs)
    }

    func description(forEmptyDataSet scrollView: UIScrollView) -> NSAttributedString? {
        let str = "Empty Title"
        let attrs = [NSAttributedStringKey.font: UIFont.preferredFont(forTextStyle: UIFontTextStyle.body)]
        return NSAttributedString(string: str, attributes: attrs)
    }

    func image(forEmptyDataSet scrollView: UIScrollView) -> UIImage? {
        return UIImage(named: "emptyImage")
    }


text:
Q: How can I block traffic over wifi before the VPN connects? I'd like to use a VPN when on public wifi for security. In order to establish my OpenVPN tunnel I need a working network connection. When I connect to a public wifi access point there is a window of time after connecting but before my VPN client is launched, connects and updates the route table, during which traffic from my system travels unencrypted over public wifi.
How can I cause wifi to pass no traffic except traffic destined for my OpenVPN server during that window of time?
Extra credit : Is there a way to whitelist wifi networks as trusted (like my home or work wifi) such that all traffic is allowed as I won't be using a VPN?

A: I would try the following with iptables, in this order:
# Allow dhcp
sudo iptables -A OUTPUT -p udp --dport 67:68 --sport 67:68 -j ACCEPT

# Allow outbound VPN traffic
sudo iptables -A OUTPUT -p udp --dport 1194 -d 0.0.0.0/0   -j ACCEPT"

# DROP all outbound WIFI
sudo iptables -A OUTPUT -i wlan0 -j DROP

In office and home network you will have to run:
# Accept all outbound traffic
sudo iptables -D OUTPUT -i wlan0 -j DROP

There might be an iptables extension which will filter using WIFI SSID or some other router identifier, but I am not familiar with any
NOTE: you might need to update the ovpn remote port and/or WIFI network interface name

A: Maybe I have solution for you.
Create script in /etc/NetworkManager/dispatcher.d/vpn-up
#! /bin/bash

REQUIRED_CONNECTION_NAME="<name-of-connection>"
VPN_CONNECTION_NAME="<name-of-vpn-connection>"

activ_con=$(nmcli con status | grep "${REQUIRED_CONNECTION_NAME}")
activ_vpn=$(nmcli con status | grep "${VPN_CONNECTION_NAME}")
if [ "${activ_con}" -a ! "${activ_vpn}" ];
then
    nmcli con up id "${VPN_CONNECTION_NAME}"
fi

Witch mean, if is not connected to REQUIRED_CONNECTION_NAME aka home wifi dispecher will connect to vpn.
This will work only if you use NM for VPN connection.
If not use NM for vpn connection, change in script nmcli con up id "${VPN_CONNECTION_NAME}" with you command for vpn connection to run.


text:
Q: Как создать java web start приложение? Как создать java web start приложение?
A: Обычно для получения результата хватает пройти квест, начиная отсюда
Если же интересует что-то более конкретное, то задавайте более конкретный вопрос


text:
Q: mysql inner joins query having problems with the following inner joins query on my products table -->>
SELECT   products.prod_id, products.prod_name, products.price, suppliers.company_name, customers.phone,
     FROM products
     INNER JOIN suppliers
     ON suppliers.supp_id = suppliers.supp_ID;

A: You are joining on suppliers.supp_id = suppliers.supp_ID;
Both from the suppliers table... you want an attribute from the product table. Something like:
products.supp_id = suppliers.supp_ID;

Which will result in the following query:
    SELECT
       products.prod_id,
       products.prod_name,
       products.price,
       suppliers.company_name,
       customers.phone
    FROM
       products
    INNER JOIN
       suppliers
    ON
       products.supp_id = suppliers.supp_ID;


text:
Q: Unable to install package using docker : kpt not found or ambiguous repo/dir@version specify '.git' in argument I am using below script and it giving me an error #/bin/sh: 1: kpt: not found
FROM nginx
RUN apt update
RUN apt -y install git
RUN apt -y install curl

# install kpt package
RUN mkdir -p ~/bin
RUN curl -L https://github.com/GoogleContainerTools/kpt/releases/download/v1.0.0-beta.1/kpt_linux_amd64 --output ~/bin/kpt && chmod u+x ~/bin/kpt
RUN export PATH=${HOME}/bin:${PATH}
RUN SRC_REPO=https://github.com/kubeflow/manifests
RUN kpt pkg get $SRC_REPO/tf-training@v1.1.0 tf-training

But if I create the image using
FROM nginx
RUN apt update
RUN apt -y install git
RUN apt -y install curl

and perform
docker exec -it container_name bash

and manually do the task then I am able to install kpt package. Sharing below the screenshot of the process

The error changes if I provide the full path to /bin/kpt
Error: ambiguous repo/dir@version specify '.git' in argument
FROM nginx
RUN apt update
RUN apt -y install git
RUN apt -y install curl
RUN mkdir -p ~/bin
RUN curl -L https://github.com/GoogleContainerTools/kpt/releases/download/v1.0.0-beta.1/kpt_linux_amd64 --output ~/bin/kpt && chmod u+x ~/bin/kpt
RUN export PATH=${HOME}/bin:${PATH}
# Below line of code is to ensure that kpt is installed and working fine
RUN ~/bin/kpt pkg get https://github.com/ajinkya101/kpt-demo-repo.git/Packages/Nginx
RUN SRC_REPO=https://github.com/kubeflow/manifests
RUN ~/bin/kpt pkg get $SRC_REPO/tf-training@v1.1.0 tf-training

What is happening when I am using docker and not able to install it?

A: First, make sure SRC_REPO is declared as a Dockerfile environment variable
ENV SRC_REPO=https://github.com/kubeflow/manifests.git
^^^                                               ^^^^

And make sure the URL ends with .git.
As mentioned in kpt get:

In most cases the .git suffix should be specified to delimit the REPO_URI from the PKG_PATH, but this is not required for widely recognized repo prefixes.

Second, to be sure, specify the full path of kpt, without ~ or ${HOME}.
/root/bin/kpt

For testing, add a RUN id -a && pwd to be sure who and where you are when using the nginx image.


text:
Q: Why is the accuracy of my Neural Network not changing? The Task:
So me and a friend have been tasked to make a NeuralNet for a old Kaggle competition which is a regression problem as you have to predict the sales of the shop for upto x amount of months which is Here.

The Dataset:
We've decided to use Keras and Pandas to preprocess the train dataset, The train dataset has the following fields
(The text inside parenthesis are NOT in the dataset but only to show you the range and data type)
Store(1-1115)   DayOfWeek(1-7)  Date(YYYY-MM-DD)    Sales(int)  Customers(int)  Open(0 OR 1)    Promo(0 OR 1)   StateHoliday(0,a,b,c)   SchoolHoliday(0 OR 1)

How We Process/Make The Datasets:
Train.csv
Y:
So we decided to delete 'Sales' from the trainning dataset and to use it as Y, the target which is where I come to the first question. Should we normalise the Y/Sales target data?
X:
Now We process the rest of the trainning data as follows.

*

*We remove the date as we thought it would not provide much use
especially if we put the data in order.

*We have changed State Holiday to a (0 or 1) binary value to state weather it is/isn't a State Holiday. We have also changed it to 0.25/0.5/0.75/1.0 to represent all the State Holidays, we did this in a different iteration of the dataset (the different iteration part is important later)

*We then normalised Customers to between 0-1 just like the sales

*We also removed School Holiday as we thought it didnt hold a strong enough value to the sales target

*We also removed Open as if the shop was shut it got no Sales and just didnt make sense to keep

*We also got rid of Day Of Week in One iteration of the dataset and kept it in another

Now my friend is much more of a mathematician than I am, I'm more of a Computer Scientist. So using another dataset which was also in the competition called Store.csv and it looks like the following: Store.csv
Store(1-1115)   StoreType(a-d)  Assortment(a-c) CompetitionDistance(int Meters) CompetitionOpenSinceMonth(int M)    CompetitionOpenSinceYear(int YYYY)  Promo2(0 OR 1)  Promo2SinceWeek(int)    Promo2SinceYear(YYYY)   PromoInterval(Str months seperated by csv)

Now my friend wrote a distance function to make N clusters for our trainning dataset, the function is as follows(We settled on 5 clusters):

I put the most similiar together based on customer distance store type
  assortment and promo

We then have 5 datasets which are split by our distance function.

We now 5 datasets and we remove the following:

*

*Clusters

*Store

*Sales - save this as Y/Target

So now our final dataset looks like the following:
DayOfWeek(1-7)  Customers(normalised)   Promo(0 OR 1)   StateHoliday(0 OR 1)

The Problem
So far when we train our the Neural Network the accuracy and validation accurcy of our network just converges to a number and does not budge, no matter what epoch or learning rates or momentum we set. We have tried differnt clusters that still converge to different numbers. We made one big dataset with all the clusters and the numebrs still converge.
We made a big datasete with no cluster seperation and the accuracy and validation accuracy just reaches a fixed number after 2/3/4 epochs and never changes.
the network we made looks like the following:
model = Sequential()
model.add(Dense(8, input_dim=4, activation='relu'))
model.add(Dropout(0.1))
model.add(Dense(3, activation='relu'))
model.add(Dense(1, activation='relu'))

# model.add(Dense(1, activation='linear'))

model.compile(loss="MSE", optimizer="nadam", metrics=['accuracy'])

model.fit(x=xt.as_matrix(), y=yt.as_matrix(), validation_data=(xv.as_matrix(), yv.as_matrix()), epochs=5000)

print("stop")

We'v even tried adding removing a few features and the same problem still happens.

Questions

*

*Why is the numbers converging no matter it we change the dataset?

*Could this be a network shape/activation function/loss/optimizer
issue?

*Is the problem with the dataset?

*Is the clustering idea a good idea to pre process the data?

*How would you process this data to get good results?

*What type of layers/neurons would be appropriate?

*Should we normalize the data?