text:
Q: Boundary of a set in metric space I'm trying to find the boundary of a set in order to check whether or not the set is open or closed on the metric I'm given. While I understand the latter, I'm not sure how to properly understand the former. The set is given by $$M=\left\{\vec v = \begin{pmatrix}v_1 \\v_2  \\\end{pmatrix} \in \mathbb{R}^2 \ \middle|\  -1 \leq v_1 < 1 \right\}. $$ Am I right in assuming that my set is only bounded to the left and right by $[-1,1)$ and approaches infinity when going "upward" and "downward"? How would I describe the boundaries, then? Thanks for any help or tips.

A: As you say, the set is a vertical band in $\mathbb{R}^2$.  The picture looks like this:

The boundary of a set consists of all of the points that are "close to" the set and also "close to" the complement of the set, where "close to" is a term that I will make rigorous below.  From the picture, it appears that the boundary consists of two vertical lines:  $\{x=-1\}$ and $\{x=1\}$.
Now, to make it rigorous:

Definition: Let $E \subseteq \mathbb{R}^2$ (or, more generally, let $E$ be a subset of a metric space).  A point $x$ is a boundary point of $E$ if for any $\varepsilon > 0$, we have
  $$ B(x,\varepsilon) \cap E \ne \varnothing
\qquad\text{and}\qquad
B(x,\varepsilon) \cap E^\complement \ne \varnothing.$$

In other words, a point is a boundary point if every ball around that point intersects both the set itself, and the complement (that is, all of the points in the boundary are close to both the set and its complement).  In the case of the set $M$ which you define, any ball around a point of the form $(\pm 1, y)$ contains some point in the set, and some point outside of the set, e.g., assuming that $\varepsilon < 2$,
$$ \left(1-\frac{\varepsilon}{2}, 0\right) \in B(1,0) \cap M,
\qquad\text{and}\qquad
\left(1+\frac{\varepsilon}{2}, 0\right) \in B(1,0) \cap M^\complement. $$
On the other hand, if you take any other point $x$ in the plane, then we can find a $\varepsilon > 0$ so small that the ball of radius $\varepsilon$ centered at that point is either completely in $M$ (if $x\in M$), or in the complement of $M$ (if $x\in M^\complement$).

This set is neither open nor closed.  To make sense of this, we require a definition of what it means for a set to be open or closed.  There are many equivalent definitions; I'm going to go with the following:

Definition: A set $U$ is open if for any $x\in U$ there exists some $r > 0$ such that $B(x,r) \subseteq U$.  A set $K$ is closed if it is the complement of an open set.

In the case of $M$, above, it is not open.  To see this, note that $(-1,0)$ is in $M$, but no ball around this point is completely contained in $M$ (this was noted above).  On the other hand, $M^\complement$ is not open either, since no ball around $(1,0)$ is completely contained in $M^\complement$.
This, by the way, suggests another notion of "closed":

Definition: A set is closed if it contains all of its boundary points.  A set is open if it is the complement of a closed set.

Hence we can determine the openess or closedness of a set by examining its boundary, which is likely what this exercise was intended to get at in the first place. ;)


text:
Q: Finite group where product of elements of coprime order has product order is nilpotent Let $G$ be a finite group where for all $a, b \in G$ with $\operatorname{gcd}(o(a), o(b)) = 1$, $o(ab) = o(a)o(b)$. Is $G$ nilpotent?
My try: Let's work by induction on $\lvert G \rvert$. Since every proper subgroup of $G$ is nilpotent it is solvable. Every $p$-complement is nilpotent, thus if $\lvert G \rvert$ has more than $3$ prime divisors it is nilpotent. Since $p$-group is nilpotent, it suffices to show when $\lvert G \rvert$ has $2$ prime divisors. Assume $\operatorname{gcd}(o(a), o(b)) = 1, a \ne e, b \ne e$. If $\langle a, b\rangle < G$, $\langle a, b\rangle$ is nilpotent thus $a$ and $b$ commute. So if $G$ is never generated by two nonidentity elements of coprime order, it is nilpotent. Thus we can assume that $G = \langle a, b\rangle$. Then $o(a)$ and $o(b)$ must be prime powers and the primes are exactly the two prime divisors of $\lvert G \rvert$. How can I proceed? Is there more elementary proof?

redpajama_set_name: RedPajamaStackExchange


text:
Q: TextInput vanishes inside ScrollView React Native Scenario: I want to achieve a situation like the code shown below. Where there will be:

*

*A multiline TextInput with other components and the screen will be scrollable.

*I don't want the TextInput to be scrollable.

Problem: What happens is, after writing a certain amount of lines in the TextInput, the texts vanishes. I can still select the text and get suggestion in the keyboard. It's like the texts and the TextInput became transperant. After the TextInput reaches the height of the phone screen, this problem occurs.
Is this a bug of React-Native? or am I doing something wrong here?
Note: I'm using "expo": "~40.0.0". Also, the code below is just to portrait the situation, not the actual code.
return (
  <ScrollView>
    <View style={styles.block} />
    <View style={styles.block} />
    <TextInput
      value={content}
      onChangeText={setContent}
      placeholder="Start writing from here"
      multiline
    />
    <View style={styles.block} />
    <View style={styles.block} />
  </ScrollView>
);

const styles = StyleSheet.create({
  block: {
    height: 200,
    backgroundColor: 'blue',
  },
});

A: Try out any of following Workarounds:

*

*Enabling scrollEnabled on the TextInput

*Explicitly setting a height on the TextInput (eg. by dynamically measuring the contents)

<ScrollView scrollEnabled style={{ marginTop: 100 }}>
  <TextInput multiline placeholder="type here" scrollEnabled={true} />
</ScrollView>


text:
Q: how to wait for input at end when running / debugging c++ in visual studio I am looking to compete in the Google KickStart programming competition. I am using C++ in Visual Studio. (not visual studio code) Input parameters are given here as Console arguments, where they can be read with std::cin.
I want to paste the test input parameters into a text file and have the IDE pass them to the program as console arguments (held in the cin buffer). I have done this as defined here
But with this method the command line window will close immediately after the program finishes instead of asking for any key to be pressed. I have tried waiting for dummy input but this does not fix the closing error

A: You may easily implement your own wait "Press enter to continue..." at the end of your routine for testing.
int main(int argc, char** argv)
{
...
    int _tmp;
    std::cout << "Press enter to continue..." << std::endl;
    std::cin >> _tmp;
    return 0;
}

A: Probably your linker settings are incorrect. As far as I'm concerned you should set up SubSystem to Console (/SUBSYSTEM:CONSOLE).(Properties -> Linker -> System -> SubSystem)


text:
Q: How to wait for user input when using Adaptive cards in SDK4 Im trying to parse the adaptive card using Waterfallstep in the Virtual Assistant template , its not waiting for the user input to be filled in the card. The below code worked when I used the Multiprompt template but its not working in Virtual Assistant template.
private async Task<DialogTurnResult>
StartTheDialogAsync(WaterfallStepContext sc, CancellationToken
cancellationToken)
{
 var attachment = CreateAdaptiveCardAttachment(cards);
 var replyMessage = sc.Context.Activity.CreateReply();
 replyMessage.Attachments.Add(attachment);
 await sc.Context.SendActivityAsync(replyMessage, cancellationToken);
 return new DialogTurnResult(DialogTurnStatus.Waiting);
 }

A: There's nothing in the Bot Framework that causes a dialog to wait for user input after sending an adaptive card. My guess is that it's working in the MultiPrompt sample coincidentally because of how the sample is coded.
The two ways to force a wait are:

*

*Send a blank text prompt directly after the adaptive card

*Send the adaptive card as an attachment to a blank text prompt

See any of these answers for more details:

*

*Using Adaptive Cards in Waterfall Dialogs

*(optional) Dynamically Changing The Card Before Sending
You basically need three pieces of code:
private async Task<DialogTurnResult> DisplayCardAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
{
    // Create the Adaptive Card
    var cardPath = Path.Combine(".", "AdaptiveCard.json");
    var cardJson = File.ReadAllText(cardPath);
    var cardAttachment = new Attachment()
    {
        ContentType = "application/vnd.microsoft.card.adaptive",
        Content = JsonConvert.DeserializeObject(cardJson),
    };

    // Create the text prompt
    var opts = new PromptOptions
    {
        Prompt = new Activity
        {
            Attachments = new List<Attachment>() { cardAttachment },
            Type = ActivityTypes.Message,
            Text = "waiting for user input...", // You can comment this out if you don't want to display any text. Still works.
        }
    };

    // Display a Text Prompt and wait for input
    return await stepContext.PromptAsync(nameof(TextPrompt), opts);
}

private async Task<DialogTurnResult> HandleResponseAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
{
    // Do something with step.result
    // Adaptive Card submissions are objects, so you likely need to JObject.Parse(step.result)
    await stepContext.Context.SendActivityAsync($"INPUT: {stepContext.Result}");
    return await stepContext.NextAsync();
}

The validator
private async Task<bool> CardValidator(PromptValidatorContext<string> promptContext, CancellationToken cancellationToken)
        {

            var activity = promptContext.Context.Activity;

            if (string.IsNullOrWhiteSpace(activity.Text) && activity.Value != null)
            {
                activity.Text = JsonConvert.SerializeObject(activity.Value);
                return true;
            }
            return false;
        }

and
var activity = turnContext.Activity;

if (string.IsNullOrWhiteSpace(activity.Text) && activity.Value != null)
{
    activity.Text = JsonConvert.SerializeObject(activity.Value);
}

Again, read the linked answers for more details.


text:
Q: How to exclude lines with regexp I have a list of lines with numbers. Need to exclude from it all lines starting with 373.
For example my list is:
37322433151
37323175491
19376717186
79684480273
97246000252
37323175491
37323175491
40745108277

If i do cat ... | egrep '^[^373].*', then it excludes lines that start from 3 or 7, the output is
19376717186
97246000252
40745108277

Even if expression is ^[^(373)].*
I need too exclude only if line starts with 373. Could anyone tell me what expression should be used ?
I also tried '^(?!373).*

A: If you wanna do it with a regex then you can try:
^(37[^3]|3[^7]|[^3])[0-9]+$

A: Use grep -v:
grep -v "^373" file

Using awk:
awk '!/^373/' file

Use grep -P (PCRE): Negative Lookahead
grep -P '^(?!373)' file


text:
Q: Query of files from folder "files" in project I have a folder "files" in my project. I want to create a query of all files in it.
1. How to open that folder without specifying the full path?
2. How to put all files from my folder to this query?
ArrayDeque<File> files = new ArrayDeque<File>();

I wrote some code. But program give me the name of folder instead the name of files in it. So my program don't find a folder in my project-folder. How I can get my folder "folder1" without all path? It's my code
public static void main(String args[])
{
    File file = new File("<folder1>");
    ArrayDeque<File> queue = new ArrayDeque<File>();
    filesQueue(file, queue);
    System.out.print(queue.getFirst());
}

public static ArrayDeque<File> filesQueue(File f,  ArrayDeque<File> queue) {
        if (f.isDirectory()) {
            for (File file : f.listFiles()) {
                filesQueue(file, queue);
            }
        } else {
            queue.addLast(f);
        }

    return queue;
}

A: File file=new File("<folder-name>");
ArrayDeque<File> filesQueue=listFiles(file);

static ArrayDeque<File> fileList=new ArrayDeque<File>();
public ArrayDeque<File> listFiles(File folder) {

    for (File f : folder.listFiles()) {
        if (f.isDirectory()) {
            listFiles(f);
        } else {
           fileList.add(f);
        }
    }
return fileList;
}

A: File folder = new File("src/folder1");


text:
Q: Starting Service on remote server failed I encounter strange behavior when trying to remotely start a service.
on Server A i'm running this line (it's part of bigger script named RunRemoteService.ps1):
Invoke-Command -ComputerName $B_comp -ScriptBlock {Powershell.exe -File "run_service.ps1"} -Credential $cred
And the script run_service.ps1 contains the following line (it's also part of bigger script):
$my_service_name.Start()
Now here's the strange thing, If I run RunRemoteService.ps1 when I have an open remote connection (mstsc) to server B then the script works perfectly and the required service on B is really starting.
However, if I run RunRemoteService.ps1 when there is no mstsc connection with server B then the script failed (service doesn't start).
Why is this happening and how can it be resolved?
EDIT: I explored this issue a bit more and found out that this occurs only when trying to run my specific service.
that means that my service must run from a session of already logged on user (that is why it's working if I mstsc to the server before).
So I guess my new question is - is there a way I can login to remote machine from powershell?
Thanks.

A: If you cannot use Credential delegation as suggested by @EBGreen. Try using psexec.exe for calling the script instead of PowerShell remoting.
psexec \\server "cmd /c powershell.exe -f c:\script.ps1"

Get psexec from sysinternals.com

A: Ok, so my question had evolved and modified on the fly so this solution is to the latest issue I had which is - I couldn't remotely start my service if no user is logged on to remote machine.
The solution is a workaround:

*

*I configured auto-login (using sysinternals auto-login tool) on remote server.

*I used Restart-Computer cmdlet at the beginning of the test.

*Now after the restart is complete and ps-session is restored, user is logged in automatically to server and I can remotely start my service.
Thanks.


text:
Q: Domain computer away from domain network isn't performing dns lookup correctly? I have a laptop that is not connected to the same network as our domain controller (its out of the office) and it is not resolving DNS correctly.
The DNS server (1.1.1.1) is assigned through DHCP and using nslookup this shows correctly:
C:\Users\Administrator\nslookup google.ca
Server: one.one.one.one
Address: 1.1.1.1

Non-authoritative answer:
Name: google.ca.ad.domain.com
Address: 72.74.244.38

I've substituted domain.com for our actual domain name along with a dummy IP address above.
When I ping google.com for example it shows the correct IP address and is able to ping it.
C:\Users\Administrator>ping google.com

Pinging google.com [172.217.165.14] with 32 bytes of data:
Reply from 172.217.165.14: bytes=32 time=975ms TTL=52
Reply from 172.217.165.14: bytes=32 time=685ms TTL=52
Reply from 172.217.165.14: bytes=32 time=722ms TTL=52
Reply from 172.217.165.14: bytes=32 time=709ms TTL=52

Ping statistics for 172.217.165.14:
    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 685ms, Maximum = 975ms, Average = 772ms

The long ping times are because this network is on a satellite internet connection.
I am wondering why our domain is being appended to the NS lookup and why the correct DNS response is not coming through.
Any help would be greatly appreciated.

A: nslookup makes several tries to find the referenced site.
It always begins with the domain name, and only if not found it will try other
possibilities.
What's happening is that your external DNS server is responding that they have
an entry for google.ca.ad.domain.com and is returning the IP address for the site,
which is correct.
This probably indicates that a DNS server in your
domain is over-ambitious and is set to answer queries to DNS queries
as if it was authoritative to their domain, in this way causing the global DNS server
that delegated that query to accept the answer.
In other words, nslookup asks about google.ca.ad.domain.com.
Google DNS delegates the query to the DNS server at domain.com,
which unfortunately goes and searches for google.ca and returns
the right answer to Google DNS. It really shouldn't be doing that.
I believe that your domain's DNS server needs to be set to respond only to queries
for entries it actually has (domain.com, www.domain.com, mail.domain.com, etc.),
not to queries about the entire world.


text:
Q: In Logstash HTTP input, how can I send the error to the client instead of nothing? these are my logstash settings
input {
    http {
        port => 5000
        codec => "json"
    }
}

output {
    elasticsearch {
        hosts => "elasticsearch:9200"
        user => "elastic"
        password => "changeme"
    }
}

if I do curl -XPUT 'http://127.0.0.1:5000' -d '{"message": "hello"}' and get an error I'm not getting any feedback in CURL. I can see the error in my logstash / elastic stack console, but I'd like to get it also in curl.

A: The input and output stages in Logstash are completely disconnected and run asynchronously.
Your http input will always respond 200 OK because your message has been accepted for processing. The fact that the elasticsearch output fails to properly index your message cannot be propagated back to the input, and hence to your curl call.
The sequence goes like this:

*

*you invoke curl on port 5000

*the http input receives your message and responds 200 OK
-> At this point, your curl command returns

*the http input then sends your message through the filter and output pipeline

*the elasticsearch output receives the message to be handled

*the elasticsearch output sends the message to Elasticsearch

*Elasticseach complains about the message and sends 400 Error

*the elasticsearch output dumps that error in the Logstash log

You can read more about the Logstash execution model.


text:
Q: RestAssured Cannot make containsString work This is the response (sort of)
{
  "Cats": [
        {
        "Code": "XXXX",
        "Ven": {
            "Description": "Any"
        },

        },
        "Rate": {
            "Actual": {
                "Amount": "XXX",
                "Currency": "USD"
            },
            "Token": "Cg..........................................",

       {
        "Code2": "2XXXX",
        "Vend": {
            "Code": "2X",
            "Description": "aNY2"
        },

            "Token": "Cg...................................",

}

I need to verify if the response contains the Token value and if this token value contains a certain string, this is the code
    Response responseshop = given().header("Authorization", "Basic
    XXXXXXXXXXX=").header("accept-version","2.0.0").header("Accept",
    "application/xml").
            param("Location", "Geocode,XX.XXXXXX,-XX.XXXXXX").
            param("Pick", "2017-12-12").
            param("Drop", "2017-12-15").
            get("/cats/shop?AppKey=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
        responseshop.then().log().all().
            statusCode(200).
                     body("root.Cats.Rate.Token", containsString("Cg"));
            System.out.println("This is the Response");
            System.out.println(responseshop);
            String Token =responseshop.path("root.Cats.Rate.Token");
           System.out.println("This is the Token");
           System.out.println(Token);

BTW the response is printed out and it passes also the 200 status verification,
But Im getting this assertion error over and over again:
java.lang.AssertionError: 1 expectation failed.
XML path root.Cats.Rate.Token doesn't match.
Expected: a string containing "Cg"
Actual:
Cg........................

Im new with restassured, am I missing something.
Thanks!

A: I think that the one of the problems is that you have a JSON response and want to check an xml content as in the header you set it in the "Accept" header as "application/xml". Try with "application/json" and check your jsonpath as well because it is also smelly.
If you cannot share the json of yours, you try to evaluate and find to correct jsonpath via http://jsonpath.com/ as if you can have multile record under the Cats array it should look like that for the first elem: "Cats[0]..Token"


text:
Q: How do I protect The End using Worldguard I am a moderator on an SMP server.  We have a Bukkit plugin called WorldGuard that we use to set protected plots and disable PvP in certain areas.  Can WorldGuard be used to do the same thing in the End?

A: Whilst I never made regions in The End myself, The End works much in the same way as any other world. There's no reason why it can't work that way.
People used to make all sorts on my servers version of The End and we had it set up so people would have to get their items when they were at The End (rather than walk in with them). As such, you should be able to use WorldGuard for regions.
I hope this helps, please do let me know if it doesn't work.

A: Yes, it should work. If you want to protect the entire End, I would simply go out beyond the edges of the land. If you really don't want people to build anywhere, disable building with a flag.


text:
Q: How to configure the LifeStyle based on a marker interface The question:
How can I configure the lifestyle of my components using the presence (or not) of a marker interface on each of them ?
My rules are:

*

*if a component implements IAutoInstalledComponent then it must be registered

*if the component implements ISingletonComponent then the lifecycle of the component must be Singleton

*if a component implements IAutoInstalledComponent but not ISingletonComponent it will be have a PerWebRequest lifestyle

I've seen an "If" method in the ComponentRegistration given in the ConfigureDelegate of the "Configure" method but could not guess nor get documentation about how to use it.
My current code:
// a marker interface which I implement on my components by convention
// just to know which components to register
public interface IAutoInstalledComponent
{
}

// a marker interface to say that the lifestyle should be Singleton
public interface ISingletonComponent : IAutoInstalledComponent
{
}

// This is my unique installer
public class AutoInstaller : IWindsorInstaller
{
    public void Install(IWindsorContainer container, IConfigurationStore store)
    {
        container.Register(AllTypes.FromThisAssembly()
            .BasedOn<IAutoInstalledComponent>()
             // this is what i want to be Singleton when the component (or service) implements ISingletonComponent
            .Configure(c => c.LifeStyle.PerWebRequest)
        );
    }
}

The context:
Ok, if you have time, here is global explanation of what I'm trying to do. My goal is to do a bulk registration of all the components in the current assembly. But since some components are really slow to initialize (and are totally threadsafe), I want to create only a single instance of them.
Thanks in advance for your help.

A: You may filter components using Where() according to implemented interfaces
            container.Register
            (
                AllTypes.FromThisAssembly()
                .Where(c=> c.GetInterface(typeof(LifestyleUponInterface.InterfaceForSingleton).Name)!=null )
                .Configure( c=> c.LifeStyle.Singleton )
            );
            container.Register
            (
                AllTypes.FromThisAssembly()
                .Where(c => c.GetInterface(typeof(LifestyleUponInterface.InterfaceForTransient).Name) != null)
                //.If(Component.IsInNamespace("<yourNamespace>"))
                .Configure(c => c.LifeStyle.Transient)
            );


text:
Q: Determine $\lim_{n \to \infty} a_n$ Given  $a,b\in\mathbb R$ , defined  $(a_n)_n$ recursively  by setting
$a_1 = a$ ,$ a_2 = b$ ,$ a_{n+1} = \frac{1}{2n}a_{n-1}+\frac{2n-1}{2n}a_n,\;\;n\geq 2 $
Determine  $\displaystyle\lim_{n \to \infty} a_n$
My attempt :  I know   that $a_n = a + (b-a) +.......+ (a_n - a_{n-1})$   after that  I'm not able to procede  further.
any hints/solution will be appreciated
Thank you!

A: Hint:
$$ a_{n+1} - a_n =  - \frac{1}{2n}(a_n - a_{n-1}) $$
Thus $a_{n+1}-a_n = \frac{(-1)^{n-1}}{(2n)!!}(b-a)$
$$
a_n - a = \sum_{i=1}^{n-1}(a_{i+1}- a_{i}) = (a - b) \sum_{i=1}^{n-1} \frac{(-1)^i}{(2i)!!}
$$
The summation certainly converges, but I don't know how to get the converged value
According to wolframalpha, (and thanks to @Minus One Twelfth hint)
$$
\sum_{i=1}^{\infty} \frac{(-1)^i}{(2i)!!} = \sum_{i=0}^{\infty} \frac{1}{i!}\left(-\frac{1}{2}\right)^i - 1 = e^{-1/2} - 1
$$
In summary, $\lim_{n \rightarrow \infty} a_n = \left(1-\frac{1}{\sqrt{e}}\right) b + \frac{1}{\sqrt{e}}a$


text:
Q: How to get all SNMP items using zabbix? Scenario:
OS: CentOS 7.2
Zabbix version: 3.0
Trying to monitor some switches using SNMP protocol

I'm able to monitor them without any problem, all items are working and everything is fine but adding every item is a pain in the ass and I'm not into wasting hours right now so I started googling a bit and found Zabbix Extras, which seems to fix my problem, but not yet, as the last version is for Zabbix 2.4. Anyways, I tried to install it but, as expected, no success at all. I've been trying to find an alternative and got anything so far so this is basically my last chance...
hope someone can help or I'm gonna kill myself before adding +500 items/switch lol

A: You don't have to add items for all interfaces or disks manually - just use the default templates "Template SNMP Interfaces" and "Template SNMP Disks".
That should cover the absolute majority of items/OIDs and the remainder should be a few that one could add manually (in a template, preferably) - or you could see whether there's an existing template for your device already.
Note that you should never monitor everything available over SNMP - there are way, way too many things and you will overload the target device, fill up the Zabbix database and in general gather useless data.

A: mib2zabbix
Perl script will generate a Zabbix v3 Template in XML format from an OID tree in an SNMP MIB file.
Read more here:
https://github.com/cavaliercoder/mib2zabbix


text:
Q: Where is the coding error for the unexpected '}' in this if / else choice of loops? an unexpected '}'  is reported for } else {
<?php
function mg_get_selected_taxonomy_dropdown_term() {
  return isset( $_GET[ 'state' ] ) && $_GET[ 'state' ] ? sanitize_text_field( $_GET[ 'state' ] ) : '';
  }
      $selected_term = mg_get_selected_taxonomy_dropdown_term();
      $states = get_terms('state'); $i = 0;

      if ($selected_term != "ALL") {
        foreach ( $states as $state ) :

        $doctors = new WP_Query(array(
         'post_type'      => 'doctor',
         'orderby'        => 'name',
         'order'          => 'ASC',
         'post_status'    => 'publish',
         'posts_per_page' => -1,
         'tax_query'      => array(
          'relation' => 'AND',
          array(
            'taxonomy' => 'state',
            'field'    => 'slug',
            'terms'    => $state->slug
          ),
          array(
            'taxonomy' => 'state',
            'field'    => 'term_id',
            'terms'    => $selected_term,
          ),
        )
      ));
      } else {
        foreach ( $states as $state ) :

        $doctors = new WP_Query(array(
         'post_type'      => 'doctor',
         'orderby'        => 'name',
         'order'          => 'ASC',
         'post_status'    => 'publish',
         'posts_per_page' => -1,
         'tax_query'      => array(
          array(
            'taxonomy' => 'state',
            'field'    => 'slug',
            'terms'    => $state->slug
          ),
        )
      ));

      }
?>


text:
Q: Different convergence rate of the objective with GPU and Chianer I am working with Chainer1.22.0 to implement a LSTM language model. My code does work with CPU but does NOT with GPU... More precisely, my object function converges pretty fast with CPU but not with GPU.
Do you have any idea about what's going on?
Thank you for your help in advance!
Outputs:
$ python debug.py --gpu -1
cpu mode
objective in epoch  0 :  14.8049154282
objective in epoch  1 :  11.7126655579
objective in epoch  2 :  10.6166152954
objective in epoch  3 :  9.81489753723
objective in epoch  4 :  8.90626144409
objective in epoch  5 :  7.73007297516
objective in epoch  6 :  6.31889343262
objective in epoch  7 :  4.83179998398
objective in epoch  8 :  3.52315592766
objective in epoch  9 :  2.58598852158

$ python debug.py --gpu 0
gpu mode  0
objective in epoch  0 :  14.8049144745
objective in epoch  1 :  14.3081817627
objective in epoch  2 :  14.0404243469
objective in epoch  3 :  13.8618173599
objective in epoch  4 :  13.7236022949
objective in epoch  5 :  13.6082553864
objective in epoch  6 :  13.5111179352
objective in epoch  7 :  13.4323377609
objective in epoch  8 :  13.3735141754
objective in epoch  9 :  13.3361949921

Environments:

*

*Python 2.7.13 (anaconda)

*Chainer1.22.0

*Cuda8.0

My model:
min -sum log P(s_t|s_{t<})
where P(s_t | s{t<}) = LSTM( s_{t<} )

Complete code:
'''
this is a code for asking
'''
import numpy as np
try:
    import cupy as xp
except ImportError:
    pass
import sys
import chainer as ch
import chainer.links as L
import chainer.functions as F

INT = "int32"
FLOAT="float32"
BOOLEAN='bool'

class LSTM(ch.Chain):
    def __init__(self, voc_size, in_size, out_size, batch_size):
        np.random.seed(0)
        w1 = np.random.normal(size=[voc_size, in_size])

        super(LSTM, self).__init__(
            emb=L.EmbedID(voc_size, in_size, initialW =w1),  # word embedding
            enc = L.LSTM(in_size=in_size, out_size=out_size),# LSTM_cell
            scores = L.Linear(out_size, voc_size)            # output transformation
        )
        self.batch_size = batch_size
        self.out_size = out_size
        self.gpu_idx = -1

    #put links on GPU
    def to_gpu(self, device_idx):
        self.gpu_idx = device_idx

        self.emb.to_gpu(device_idx)
        self.scores.to_gpu(device_idx)
        self.enc.to_gpu(device_idx)

    def obj(self, seq):
        #object function is log likelyhood for the each word on the seq
        return -F.sum(self.logL(seq))

    def logL(self, seq):
        '''
        seq ; batch of src seq of length T : List<List<int>>
        RETRUN : R^{batch_size x T} : CP node
        '''
        T = xp if self.gpu_idx>=0 else np
        padded = T.transpose(T.array(seq, dtype=INT)) #Z^{T x batch_size}

        #reset LSTM cell
        self.enc.reset_state()

        logL = []
        #logL for each time step except the first input
        for i in range(0, len(padded)-1):
            #get LSTM output
            h = self.enc(self.emb(padded[i])) #R^{batch_size x hidden_size}

            #probability distribution over vocabrary
            s = self.scores(F.tanh(h))        #R^{batch_size x voc_size}
            s = F.transpose(F.log_softmax(s)) #R^{voc_size x batch_size}

            #likelyhood for the next word
            l = F.embed_id(padded[i+1] , s)     #R^{batch_size x batch_size}
            l = F.sum(l * T.identity(self.batch_size), axis=0) #R^{batch_size}
            logL += [l]

        return F.transpose(F.stack(logL))

GPU_TAG = "--gpu"
if __name__=="__main__":
    args= sys.argv
    gpu_idx = -1
    i=0

    #argument
    while i<len(args):
        if args[i]==GPU_TAG:
            i+=1
            gpu_idx = int(args[i])
        i+=1

    #hyper paramters
    voc_size = 5
    batch_size=3
    in_size = 5
    out_size=2

    #instanciate model
    model = LSTM(voc_size, in_size, out_size, batch_size)

    #GPU mode or CPU mode
    if gpu_idx>=0:
        print "gpu mode ", gpu_idx
        ch.cuda.get_device(gpu_idx).use()
        model.to_gpu(gpu_idx)
    else:
        print "cpu mode"

    #prepare optimizer
    trainer = ch.optimizers.sgd.SGD(lr=0.3)
    trainer.setup(model)

    #seq to train
    x = [[1,2,3,4]]*batch_size

    #main training loop
    for epoch in range(10):
        obj = model.obj(x)  #forward path
        model.cleargrads()  #init grad for backward path
        obj.backward()      #backward path
        print "objective in epoch ",epoch, ": ", obj.data
        trainer.update()    #update

A: I solved the problem by myself somehow... it seems my some operation for the computational graph works with CPU but not with GPU.
The problem is solved by replacing the following code
s = F.transpose(F.log_softmax(s)) #R^{voc_size x batch_size}
#likelyhood for the next word
l = F.embed_id(padded[i+1] , s)
l = F.sum(l * T.identity(self.batch_size), axis=0)

with
s=F.log_softmax(s)
l=F.select_item(s,padded[i+1])

Thank you for your all help!


text:
Q: Why is it not possible to unbox erased types in Java? The two add methods in this class have the same erased signature:
class extend
{
  Integer add (Integer a, Integer b)
  {
    return a + b;
  }

  <Type extends Integer> Type add (Type a, Type b)
  {
    return a + b;
  }
}

This makes it impossible to have them both in the same class. The compiler reports the following error:

extend.java:8: error: name clash: add(Type,Type) and add(Integer,Integer) have the same erasure
   Type add (Type a, Type b)
                              ^
  where Type is a type-variable:
    Type extends Integer declared in method add(Type,Type)

But if they are equivalent, why is the unboxing not done in the second case. The compiler reports the following error:

extend.java:10: error: incompatible types
    return a + b;
             ^
  required: Type
  found:    int
  where Type is a type-variable:
    Type extends Integer declared in method add(Type,Type)

In the first case the compiler knows the erased type and in the second case he forgets it again? Why?

A: Your method <Type extends Integer> Type add (Type a, Type b) can be called with Integer arguments. <Type extends Integer> boundaries allow either a subtype of Integer or Integer.
In case someone writes this code:
Integer i = 1;
Integer k = 2;
add(i, k);

It is impossible to determine which method to call, since they both accept integer arguments, and neither is more specific than the other.
If you had add(Integer, Integer) and add(Number, Number) the integer add would be called because it's more specific. But in your case arguments Integer and Integer or subclass are equally specific if an Integer is used.
Also don't expect + operator to work any subclasses. Unboxing is type specific as it looks for specific types, requires an ability to convert to int and instantiate boxed value.


text:
Q: Disabling file permissions on NFS share I am trying to set up a nfs share for use by non-technical users, and really don't want file permissions messing things up. Everyone should be able to read/write anything on this share without even knowing what file permissions are, much less adjusting them.
Is there a way I can just make the nfs server write everything as 770 or something? It seems like this should be easy, but the best I can come up with is a cronjob to periodically set them to that, which is far from ideal.
The server is a Netgear ReadyNAS. Ideally I would like to stick to doing stuff from within the web interface on it, but I can just root it if needed.

A: Figured out a solution. One can use SGID to force the permissions of all new files/folders in a directory to be the same as that of the directory itself. More info at:
http://www.library.yale.edu/wsg/docs/permissions/sgid.htm


text:
Q: Alternative to JOptionPane? It works, but I need an alternative to the JOptionPane. This is a homework assignment and we are not allowed to use JOptionPane. Here is what I have, which works, it just isn't what the instructor wants.
import java.awt.*;
import javax.swing.*;
@SuppressWarnings("serial")
public class calc extends JApplet {

    double sum;
    double product;
    double difference;
    double quotient;

    public void init() {
        String firstNumber = JOptionPane.showInputDialog("Enter the first number");
        String secondNumber = JOptionPane.showInputDialog("Enter the second number");
        String thirdNumber = JOptionPane.showInputDialog("Enter the third number");
        double number1 = Double.parseDouble(firstNumber);
        double number2 = Double.parseDouble(secondNumber);
        double number3 = Double.parseDouble(thirdNumber);
        sum = number1 + number2 + number3;
        product = number1 * number2 * number3;
        difference = number1 - number2 - number3;
        quotient = number1 % number2 % number3;
    }

    public void paint(Graphics g) {
        super.paint(g);
        g.drawRect(15, 10, 270, 60);
        g.drawString("Sum "+sum, 25, 25);
        g.drawString("Product "+product, 25, 35);
        g.drawString("Difference "+difference, 25, 45);
        g.drawString("Quotient "+quotient, 25, 55);
    }
}

A: You could use the Scanner method and also initialize your variables as doubles so that you don't need to unnecessarily parse strings. Try something like this:
public void init() {
        Scanner input = new Scanner(System.in);

        System.out.println("Enter the first number");
        double number1 = input.nextDouble();

        System.out.println("Enter the second number");
        double number2 = input.nextDouble();

        System.out.println("Enter the third number");
        double number3 = input.nextDouble();

        sum = number1 + number2 + number3;
        product = number1 * number2 * number3;
        difference = number1 - number2 - number3;
        quotient = number1 % number2 % number3;
    }

Then to display without JOptionPane, you would use a line similar to this:
System.out.println("Quotient is " + quotient);

And remember to import as necessary!
import java.util.Scanner;

Some additional clarity in regards to the assignment would make this question much easier to answer, but that is my best guess based on the available information. I assumed the only reason your teacher wouldn't allow you to use JOptionPane is because it hasn't been covered in the course yet, and as JOptionPane is taught relatively early in most Computer Science programs, I would guess the Scanner method is likely what your teacher is looking for. If you've already covered the Scanner method, try looking into the InputStreamReader method. Hope this helps ;)


text:
Q: jQuery UI: Removing class on the change event (nestedSortable plugin) I'm using Manuele Sarfatti's nestedSortable  (http://mjsarfatti.com/sandbox/nestedSortable/) to create a storable and nested list. I've taken the script one step further by making my list collapsible via additional jQuery (I didn't modify the original plugin script).  I wanted to display open and closed arrow icons to the list items to indicate when they are in their collapsed and expanded state.  I almost have this working except I cannot seem to remove the arrow icon when a parent no longer has children.  To create the arrow icon, I add the class 'ArrowOpen'  to any parent that has children and use the jQuery UI change event to remove all instances of the class and then re-apply the class each time the list is sorted (or changed). For example:
$("ul.sortable li:has(ul)").addClass("ArrowOpen");

Here is my jsfiddle working example: http://jsfiddle.net/qbxWd/
To replicate my problem, try this: Drag/nest  Item-2 into Item-1 and you'll see Item-1 will get the 'ArrowOpen' class and will display an open arrow icon. Now, move Item-2 back to the root level and you'll see that Item-1 continues to retain the 'ArrowOpen' class and the open arrow icon is still present.  If this script worked as intended, when Item-2 was moved back to the root, Item-1 should have lost the arrow icon.
If anyone has any suggestions, any help would be welcomed - thanks!
Edit: In full disclosure, I did submit this to the plugin's support forum earlier this week: http://bit.ly/uXbfZY

A: in the stop function add this
$("ul.sortable li:has(ul):has(li)").addClass("ArrowOpen");

as first line, and delete
$("ul.sortable li:has(ul)").addClass("ArrowOpen");

from change function
NOTE:

*

*that it is only a work around and that the arrows will disappear while you drag items, and when you drop them, the arrows appear where it should.

*the "change" function is called several times, if I'm correct, each time you drag it from one item to another without releasing.
I hope this helps!
Fiddle http://jsfiddle.net/envy/qbxWd/5/
EDIT
a even better approach, add the following two lines as first lines in "stop" function
            $("ul.sortable li").removeClass("ArrowOpen");
            $("ul.sortable li:has(ul):has(li)").addClass("ArrowOpen");

and remove everything from "change" function, it will make the desired effect and it won't call "removeClass" each time you move an item without releasing it.
EDIT2
in case you want it to work with many nested sortables, I suggest this other option which uses a recursive function to apply "ArrowOpen" to all li that has a ul with child li.
Fiddle demo
EDIT3
You can take this one step further by avoiding having the collapsed nodes lose their class.
Add not('.collapsed') to the add class statement.
e.g.
$("ul.sortable li:has(ul):has(li) > div > a:not(.ArrowOpen-closed)").addClass('ArrowOpen');


text:
Q: Spec for testing a controller method that calls model methods I'm refactoring my controllers to by moving the logic to the model. I was finding it hard to test my controller methods when they had so much logic (also was not able to reuse logic in controllers). Now I'd like to understand how to write specs for these controllers. I'm following this testing guide.
Here's an example:
def dashboard
  @sorted_deals = Deal.deals_for_user(current_user)
end

This calls a class method that has some logic that finds the relevant deals and sorts them appropriately. It feels like unessary duplication to test deals_for_user again (I already test it in my Model spec). How do I test this method without needless duplication? Is this a case to use mocks or stubs?

A: There is some debate on the usefulness of controller tests in Rails.  Personally I unit test the shit out of my models and the only real tests that I do for controllers are integration testing using a headless browser such as Selenium with capybara.  If you know your method works and is tested, and the view/associated logic works and is tested through integration tests, controller testing is almost a waste of time.  There are other opinions on this and I am in no way a guru but I thought I would put in my $00.02.


text:
Q: vDSP_desamp FIR filter sample history continuity I'm trying to use the vDSP_desamp() routine to perform downsampling of an audio signal that is being constantly captured. According to the Accelerate-framework documentation, this routine performs FIR filtering and decimation.
However I have a conflict, since the API does not provide an input parameter for the circular buffer that to my knowledge, is needed to preserve sample history to perform FIR filtering.  This leads me to believe that the sample history is being reset during each function call or perhaps a different algorithm is being applied from the one I know.
Unfortunately the function is a complete black box and no hint is given on how the filtering is performed or how signal continuity should be ensured.
Do you think it would suffice if I pad each frame with the last N samples (N being the number of filter taps) of the previous buffer, to acquire filtering continuity?  I would discard those padding-sample outputs after calling vDSP_desamp(), but I guess that the sample history line should be correctly initialized after the padding samples are processed.
Any hints on the innards of vDSP_desamp() are welcome.

A: Why do you say the function is a complete black box? The documentation shows this pseudo-code for vDSP_desamp(A, I, F, C, N, P):
for (n = 0; n < N; ++n)
{
    sum = 0;
    for (p = 0; p < P; ++p)
        sum += A[n*I+p] * F[p];
    C[n] = sum;
}

You can also look in /System/Library/Frameworks/Accelerate.framework/Frameworks/vecLib.framework/Headers/vDSP.h on any recent OS X system for information on almost all vDSP routines. It shows the same thing in a different form:
for (n = 0; n < N; ++n)
    C[n] = sum(A[n*I+p] * F[p], 0 <= p < P);

From this, it is clear that each output value C[n] is a function of P input values from A[n*I + 0] to A[n*I + P-1].  Supposing that you want the first output value in the next call to continue in the same pattern from the current call, simply consider the last output value in the current call (the last n will be N-1, so the last output value will be C[N-1]) and what would be the next value, C[N]. This C[N] would be a function of input values starting at A[N*I + 0], which is A[N*I].
Then match that to the first output value, C[0], in the next call. C[0] will be a function of input values starting at A[0*I + 0], which is A[0].
Therefore, to make the next call continue from where the current call ends, you would want to copy values from A[N*I] and beyond to A[0] and beyond. (This presumes you are reusing the array A by moving data in it and then appending new data. You could also continue with the data in place by passing A+N*I as the first parameter to vDSP_desamp.)
The number of values to copy would be the number of values you have in A after (and including) A[N*I]. E.g., if you have Number values in A, you can use:
memcpy(A+N*I, A, (Number - N*I) * sizeof *A);

Then put new data at A[Number - N*I] and beyond. (If the source and destination ranges overlapped, you would need to use memmove rather than memcpy, but this would be unusual with vDSP_desamp; usually the data shared by successive calls is a small portion of the overall buffer.)

Note: The pseudocode expresses the basic mathematics of the operation. The actual arithmetic in vDSP routines may be arranged differently, for performance reasons. So the actual results may have rounding errors different from the values that would be calculated by using the pseudocode directly.


text:
Q: How does ¯¯¯¯¯ become ùùùùùùùùù I have tried: echo ¯¯¯¯¯
but the result becomes
ùùùùùùùùù

this was not the output expected.
the expected output was ¯¯¯¯¯

A: My previous solution, which saves the batch script in Unicode UTF-8 without BOM and codepage 65001 seems to have issues with both console and C runtime as user @eryksun mentioned.
@eryksun also mentioned in our chat:

Like I said, all of the codepages are supersets of ASCII, so what I mean is to limit the rest of the batch script to just ASCII characters, because they can be decoded properly regardless of the console codepage.

Unicode UTF-8
chcp 65001
echo ¯¯¯¯¯
chcp [Original Codepage]

Explanation by @eryksun:

CMD decodes line by line, i.e. you can change to codepage 65001 just for the non-ASCII lines and then switch back to the original codepage.
If you don't use an editor such as Notepad++ that can save UTF-8 without a BOM (byte order mark), CMD will see the first line as an error since it doesn't know to ignore a BOM.


text:
Q: intellij internal webserver using htaccess IntelliJ 14 has a built-in Webserver where you can run html-files on localhost port 63342.
Is there any possibility to use rewrite rules (like modrewrite) within a .htaccess file or something similar?
Or do I have to install a local webserver for this?
Regards,
Jens


text:
Q: Array.prototype.map.call not working for getElementsByClassName objects class_name = document.getElementsByClassName('image');
const map = fn => x => Array.prototype.map.call(x, fn);
map(img => {
console.log(img);
img.addEventListener('mouseover', (e) => {
global = e.target.src;
calledsomething(global);
     });
  })(class_name);

I'm trying to make a simple chrome extension but Array.prototype.map.call doesn't seems to be called. console.log(img) doesn't display anything.
I tested my code using  getElementsByTagName('img') instead of getElementsByClassName and it works.
What might be the problem?
EDIT: The whole code:
var isHovered = false;
var global;
const class_name = document.getElementsByClassName('photo_activity_item__img_wrapper');
const map = fn => x => Array.prototype.map.call(x, fn);
console.log(class_name);
map(img => {

    img.addEventListener('mouseover', (e) => {
        global = e.target.src;
        console.log(global);

        hoveredBox();
    });
    img.addEventListener('mouseleave', (e) => {
        isHovered = false;
    });

})(class_name);

document.addEventListener('keypress', keyDown);

function hoveredBox() {
    isHovered = true;
}

function keyDown(event) {
    if (!isHovered) return;
    var key = event.keyCode;
    if (key === 115) {
        saveFile(global);
    }

}

// Download a file form a url.
function saveFile(url) {
    // Get file name from url.
    filename = url;
    var xhr = new XMLHttpRequest();
    xhr.responseType = 'blob';
    xhr.onload = function () {
        var a = document.createElement('a');
        a.href = window.URL.createObjectURL(xhr.response); // xhr.response is a blob
        console.log(a.href);
        console.log(xhr.response);
        a.download = filename; // Set the file name.
        a.style.display = 'none';
        document.body.appendChild(a);
        a.click();
        delete a;
    };

    xhr.open('GET', url);
    xhr.send();
}

A: While the return of the getElementsByClassName() may be an array like object, it's quite possible it isn't a true Array. I ran into this this morning while attempting to call findIndex() on the Element.children object. Turns out that is a NodeList, and not an actual Array. I was able to get around it though, by using the new Array.from() method like this:
const index = Array.from(parent.children).findIndex(item => item.classList.contains('placeholder'));
Try that Array.from() and see if your issues are resolved.


text:
Q: DIDISOFT PGP file encryption anybody knows how to change @"C:\Test\public_key.asc" from manually input to using openfiledialog?
I tried to do that, there is this red zizag line under the code and when i put my mouse over, it says that it cannot convert System.IO.FileInfo to System.IO.Stream.
using System.IO;
using DidiSoft.Pgp;

class EncryptDemo {
 public void Demo() {
     // create an instance of the library
     PGPLib pgp = new PGPLib();

     // specify should the output be ASCII or binary
     bool asciiArmor = false;
     // should additional integrity information be added
     // set to false for compatibility with older versions of PGP such as 6.5.8.
     bool withIntegrityCheck = false;

     pgp.EncryptFile(@"C:\Test\INPUT.txt",
                     @"C:\Test\public_key.asc",
                     @"C:\Test\OUTPUT.pgp",
                     asciiArmor,
                     withIntegrityCheck);
 }
}

The below does not help us well because it does not open a dialog box for me to choose my file.
    bool asciiArmor = false;
    bool withIntegrityCheck = false;
    using (var publickey = new FileStream(openFileDialog1.FileName, FileMode.Open))
    {
        pgp.EncryptFile(@attachmentTextBox.Text, publickey, @"C:\OUTPUT.pgp", asciiArmor, withIntegrityCheck);
    }

A: Have you tried with:
bool asciiArmor = false;
bool withIntegrityCheck = false;
pgp.EncryptFile(@attachmentTextBox.Text, openFileDialog1.FileName, @"C:\OUTPUT.pgp", asciiArmor, withIntegrityCheck);


text:
Q: Accessing labels within a LoginView I'm using the asp.net LoginView to show different data to authenticated or anonymous users.
<asp:LoginView ID="LoginView1" Runat="server">
    <LoggedInTemplate>
        <asp:Label ID="Foo" runat="server" />
    </LoggedInTemplate>
    <AnonymousTemplate>
        <asp:Label ID="Bar" runat="server" />
    </AnonymousTemplate>
</asp:LoginView>

When I moved Foo and Bar into LoginView1, I was unable to access them from the code behind in this fashion:
Foo.Text = "I am Foo";
Bar.Text = "I am Bar";

I was able to access them in this fashion before moving them into the LoginView. What (clean) method can I use to access these labels?

A: You need to use FindControl on the LoginView, and Cast appropriately as shown below:
var foo = (Label)LoginView1.FindControl("Foo");
foo.Text =  "I am Foo";


text:
Q: How to uninstall containers from Azure VM [smalldisk] Windows Server 1809 Datacenter with Containers Usually Windows Server Core will use ~6GB of OS Disk where as Azure VM [smalldisk] Windows Server 1809 Datacenter with Containers image took ~16GB OS disk space.
I would like to bring it back to core size i.e ~6GB, as I do not use any containers.
As of this posting, Azure does not have any other smalldisk images. However I could use image Windows Server 2019 Core (uses ~6GB) but OS Disk takes 126GB which is no use in my case.
The only way to reduce my cost is to use available smalldisk and uninstall that extra containers.
What are the features that I should turn-off/uninstall?
I tried below but it could frees only ~200MB space.
Disable-WindowsOptionalFeature -Online -FeatureName Microsoft-Hyper-V

Uninstall-Package -Name docker -ProviderName DockerProvider // not found

A: thats just not true, you can use these images:
2008-R2-SP1-smalldisk
2012-Datacenter-smalldisk
2012-datacenter-smalldisk-g2
2012-R2-Datacenter-smalldisk
2012-r2-datacenter-smalldisk-g2
2016-Datacenter-Server-Core-smalldisk
2016-datacenter-server-core-smalldisk-g2
2016-Datacenter-smalldisk
2016-datacenter-smalldisk-g2
2019-Datacenter-Core-smalldisk
2019-datacenter-core-smalldisk-g2
2019-Datacenter-smalldisk
2019-datacenter-smalldisk-g2


text:
Q: Select ALL objects of an array I am wondering that I didn't find a way to select just all of my array objects. Isn't it possible?
My objects array example:

var objects = {
  House: `some stuff`,
  Car: `some stuff`,
  Dog: `some stuff`,
  Boat: `some stuff`
};

var all = ["House", "Car", "Dog", "Boat"];
var find = all.map(name => objects[name]);
var allOutput = Group(find);

For "all" I tried:
var all = [];
var all = [""];
var all = ["*"];

Aso., but nothing worked.
Expected output:
I want to get all the data by every key [name], including the key.

A: maybe something like Object.entries()


text:
Q: Random Hardware Anomalies after accidental reverse polarity Good afternoon everyone,
I have a bit of a weird question for you. About a month ago, I purchased a used Mac Pro 1,1 (2006). I proceeded to slap a GTX 1050ti in it, install windows and everything is running fine (obviously no mac OS as it's too old without hacks to get above lion).
Fast forward to last Saturday. I moved in with a friend pending an apartment change, set up my computer in his basement, and noticed that when the mac changed over to BIOS emulation, it would display the GTX 1050 info, then flash a bright white screen before booting windows. I thought it was no big deal, after all, windows booted fine.
Since then, I've been having progressively worse issues. It started with that bright white screen, then I noticed that the metal ring around my mechanical keyboard seemed to be shocking me when I got the mouse close enough for my thumb to touch it. Maybe the keyboard is defective, tho it's only about 3 weeks old...
Then the booting problems started. It started to freeze during the windows boot process (the little dot circle would stop in place, then the PC would restart). Now I'm starting to wonder if it's a hardware issue. I swapped the original ram sticks back into the machine, thinking maybe it didn't like the 2x8gb kit i added after "upgrading" the SMC/EFI to think it was a Mac Pro 2,1. Still had to fight it to boot.
When it did boot properly (with the 2x8gb kit re-added), I noticed that the bottom row of my keyboard (keys shift all the way right to the numpad enter key) was very dimly lit in comparison to the rest of the keys. On top of this, anything plugged into the rear USB ports on the mac would randomly disconnect every ~20 minutes or so.
Now i'm starting to think it's a ground issue. The outlet happens to be about 15ft across the room, so it's running on a heavy-duty extension cord (15amps max) over to a surge protector. I shut the mac down today, and inspected the extension cord, to which I discovered that my friend had removed the ground pin, and inserted the male end of the extension cord such that its polarity was reversed. Here's a picture of the cord, for reference. This makes me think my suspicion of ground issues was right, plus there's the whole "reverse polarity" thing...
I went to my local hardware store and bought a replacement extension cord with the proper ground pin, brought it home, made sure that the outlet was actually grounded, then swapped the cords.
Unfortunately, this has not resolved ANY of the issues with my PC (I know it's a mac, but I'm using it as a PC). The white screen still persists, it takes me about 6/10 tries to get the PC to boot (including several visits to  windows 10's automatic repair), that row of lights on my keyboard is still extremely dim in comparison to the other keys, I still feel a tingle from the metal rim around it and as I'm typing this, the USB ports in the rear just reset again.
As for the windows automatic repair, it always errors, ending with the following at the bottom of the StrTrail.txt file
Root cause found:
---------------------------
Boot critical file h:\boot\resources\custom\bootres.dll is corrupt.

Repair action: File repair
Result: Failed. Error code =  0x2
Time taken = 3593 ms

My question is, could the reverse polarity/lack of ground caused these issues? I never noticed them before I plugged the pc in at my friend's house which makes me think there might be at least SOME damage done to it.
edit I did /sfc scannnow and it returned

Windows Resource Protection did not find any integrity violations.

I also ran

chkdsk c: /f /r

however I haven't restarted the PC yet as I'm a little weary of it not booting (again).
Also, here's a pic of the keyboard
MechanicalKeyboardPic


text:
Q: Restarting Infinite Ajax Scroll after jQuery .load() I am working on a site where I want to implement infinite scrolling. I found the IAS plugin, and it works great except in one instance. If I load new content into a div using the jQuery .load() function the infinite scrolling stops working.
<script type="text/javascript">

  $(document).ready(function() {

    var ias = $.ias({
      container:    '#load_here',
      item:       'p',
      pagination: '#nav',
      next:       '#nav a'
    });

    $("#reload").click(function(){
      event.preventDefault();

      $("#test").load( "page0.html #load_here", function() {

        // Reinitialize the infinite scrolling here.

      });
    });
  });

</script>

Here is the documentation for the IAS plugin:
http://infiniteajaxscroll.com/docs/overview.html
I found the following questions that seem relevant, but there seem to me to be no clear answers--I apologize they're not links, Stack Overflow won't let me post more than 2 links:

*

*stackoverflow.com/questions/24419462/

*stackoverflow.com/questions/25205507/

*stackoverflow.com/questions/20404493/

*github.com/webcreate/infinite-ajax-scroll/issues/68
It talks about the destroy function, but in my attempts to come up with a solution that seems to do nothing at all. I am very much a hobbyist programmer, I fear I may simply not understand the structure or syntax necessary to implement this correctly.
I have a test page here

*

*http://designforfun.com/flatfile/experiments/scroll/
The infinite scroll loads pages 1, 2, and 3 successfully. If you click the link at the top to load page 0 using a jQuery .load() but then the infinite scrolling stops working. It should scroll down and load page 1, 2, and 3 again.
Thank you.

A: I'm not 100% sure as to WHY this happens, but from running the code, I see that after $("#test").load(..., the scroll event handlers used by ias are no longer firing.
The solution should be to just re-initialize the infinite scroll once the load has completed:
$("#test").load( "page0.html #load_here", function() {

  // Reinitialize the infinite scrolling here.
  var ias = $.ias({
    container:  '#load_here',
    item:       'p',
    pagination: '#nav',
    next:       '#nav a'
  });

});

However, this will not work, because $.ias() attempts to be idempotent by memoizing this method, assigning data with the "ias" key to the global window object.
It appears that the makers of ias have given us a loophole to fix this, though it is not documented. You can pass the string "destroy" to $.ias() and remove the memoized data, allowing us to call it again and reinstall the scroll listeners. (https://github.com/webcreate/infinite-ajax-scroll/blob/master/src/jquery-ias.js#L553)
Here is the resulting code that does what you expect:
var ias;
function setupIAS() {
  ias && $.ias('destroy');
  ias = $.ias({
    container:    '#load_here',
    item:       'p',
    pagination: '#nav',
    next:       '#nav a'
  });
}

$(document).ready(function() {

  setupIAS();

  $("#reload").click(function(){
    event.preventDefault();

    $("#test").load( "page0.html #load_here", function() {

      // Reinitialize the infinite scrolling here.
      setupIAS();

    });
  });
});


text:
Q: What has 'rm -r ~' done to my home directory? gedit creates hidden backup files ending with '~'. I wanted to do a recursive cleanup of my directory tree.
The command rm *~ will delete all local files ending with '~'
I thought rm -r *~ . would delete all files in the whole tree, but I typo-ed rm -r ~.
There was a message some directory could not be deleted and I quit the command. The question is: What have I been deleting?
I did notice that my Filezilla configuration was gone. Does this command delete all hidden directories from the home dir?

A: Yes. An unquoted tilde character as a separate argument gets expanded to your homedir. So rm -r ~ got expanded to rm -r /home/yourusename. So you told rm to recursively delete all files in your homedir.
See http://www.gnu.org/software/bash/manual/bashref.html#Tilde-Expansion for more about how tilde expansion works.

A: You have deleted (almost) all of your home directory!
rm -r something recursively deletes files and directories in/under something; it will only fail on items it does not have permission to delete, either because they are owned by a different user (e.g. root), or because they are in use (e.g. a GVFS mount).
If you did not add -f (as in, rm -rf something), you would get something like:
rm: remove write-protected regular file 'something'?
rm: descend into write-protected directory 'something'?

At this point you can abort and you then likely realise that you executed the wrong command.
Suggestions from the community on how to avoid such accidents

Note: Community wiki, everyone please feel free to contribute.

*

*For a few files, use the -i option to get a confirmation on removing files or directories:
$ rm -ri something/
rm: remove regular file 'something/file~'? y
rm: descend into directory 'something'? y
rm: remove regular file 'something/file'? y
rm: remove directory 'something'? y

*If removing from a current directory, prefix it by a ./ to avoid mistakingly removing a different location.:
$ cd something
$ rm -v ./*~
removed './file~'

The above was for demonstrating the use of ./. If there is a subdirectory, you can of course use rm -v something/*~ as well. Beware: do not think that rm ./.* removes all hidden files in the current directory. See this Serverfault question for workarounds on hidden files globbing.

*Move rather than delete: Rather than deleting files recursively in the first place I got used to move the files I want to get rid of somewhere else before I delete them finally. If something went wrong its easy to restore.
mv -b SOURCE DEST

*Use find (possibly with grep) to preview if you want to recursively delete selected files.  You should try to make this a rare occurrence, but if you have to...

*

*find with no arguments recursively lists all files/directories under the current one. You should try to look up man find on how to make it selective (a treasure trove), but if you don't want to bother, you can just use the familiar grep to filter for the files you want to delete.

*Suppose I'm an uber-l33t kernel hacker, and am bothered by the few KBs of "example" files in my source tree; I want to delete all files containing that in the name. So I type find | grep example, which gives me these 20 files.  That looks good, so I now go and delete those exact files, along with the rm -v verbose output previously mentioned, via xargs:

find | grep example | xargs rm -v

which gives me this output.   Such previewing prevents problems where say, you make a typo and type sample instead of example.

The above solution should not be used if you may have filenames containing spaces, tab characters, newlines, or quotes (" or '), as this will lead xargs to either fail, or feed rm with incomplete filenames, which in worst case could end up removing the wrong files. The safe way to do the above is to do it all with find's operators and actions.
The following will show all files that contain the word example
find . -name "*example*"

If that list is the files you want to remove, use the -exec action to pass the files to rm.
find . -name "*example*" -exec rm -v {} +

See Using Find for more help with using find.


text:
Q: ASP.NET MVC4 Google oAuth Im trying to configure Google oAuth in an MVC 4 Project. Its quite straight forward out of the box as per Hanslemans Excellent Video
Im able to register, log on, log off etc, but the only information I have is the email address. Id like to be able to get the First Name, Last Name and Image from Google
This blog outlines that it is possible - but when I run through it all that is available is the email address. This is obvious as this is all we asked for permission for.
So my question is how do I ask for more information from Google and the how do I access it. I know its possible writing my own oAuth access but I assume its possible using the out of the box MVC 4 code.
Thanks very much in advance

A: I think this falls under a bug that is in DotNetOpenAuth.AspNet version="4.0.3.12153" package. You need to write your own customer provider and then you can get the data from that
http://blogs.msdn.com/b/pranav_rastogi/archive/2012/08/23/plugging-custom-oauth-openid-providers.aspx
You should be able to use GetExtraData to get the data you are looking for!


text:
Q: Why does the SOQL parser give a primitive message like 'Unknown error parsing query'? If you make a mistake/typo in a SOQL query in the Developer Console, you frequently get the - not helpful - message "Unknown error parsing query".
I started programming in the early 80s, in BASIC of course, and all we had back then was: "Syntax error at line NN". So here we are in 2015 and Salesforce gives us its equivalent of Syntax error.
I have studied Computer Science and I graduated in Compiler building, so I know a thing or two about parsers and about what is possible regarding error messages on incorrect syntax.
Anyone here with some inside knowledge who can explain why we do not get more helpful error messages?

A: I would suggest using Force.com IDE plugin for Eclipse, which gives you more detailed error message about syntax error.
Also you can try use other third-party applications which allow you to perform SOQL like workbench or Schema Viewer.
I would agree that error from Developer Console is not the error which we would like to see, probably you can either log a case to Salesforce or suggest your idea to Idea Exchange about this.

A: Unfortunately, as you've noticed, the SOQL parser is a bit rudimentary. Especially when doing direct SOQL calls. You'll get much clearer errors if you use the "Execute Anonymous" item in the Dev Console and run the SOQL in Apex. For some reason, the compiled SOQL errors are much nicer than the dynamic SOQL errors.

A: You can also use the Force.com Explorer to execute the query. I would suggest consulting the SOQL reference guide, especially for the Date related functions. SOQL is similar to SQL, but there are a lot of differences between them.


text:
Q: Redis HMGET unsupported when using Sentinel I have a Redis 5.0.6 cluster with one master and one replica and using Sentinel for high availability. Cluster mode is disabled.
I setup the cluster on Kubernetes using the Redis HA Helm chart https://github.com/helm/charts/blob/master/stable/redis-ha.
I'm using Redis for caching in Moodle, an open source PHP application. I'm using PHP 7.0
The issue I am having is that when I connect to Sentinel from PHP I get Exception - Unsupported operand types when calling HMGET. When I just connect to Redis directly I don't get that error.
When I log into the master Redis container and call HMGET from the Redis command line it works fine.
Why would Sentinel not support HMGET? Is there a way to enable support for HMGET when using Sentinel?


text:
Q: Use the Stokes' Theorem to find the work of the vector field $ \overrightarrow{F}$ I have the following exercise:
"Use the Stokes' Theorem to find the work of the vector field $ \overrightarrow{F}=x^2 \hat{i}+2x \hat{j}+z^2\hat{k}$ along the anti-counterclockwise oriented area of the ellipse $ 4x^2+y^2=4$."
$$$$
I have done the following:
Since the  Ellipse is on the $ xy $ plane,  $ \hat{n}=\hat{k}$.
$ \nabla \times \overrightarrow{F}=2 \hat{k}$
$d \sigma= dxdy $
$\oint_C{\overrightarrow{F}}dR=\iint_S{\nabla \times \overrightarrow{F} \cdot \hat{n} }d \sigma=\iint_S{2\hat{k} \cdot \hat{k}}dxdy=\int_{-1}^1 \int_{-2 \sqrt{1-x^2}}^{2 \sqrt{1-x^2}}{2}dydx=\int_{-1}^1{8 \sqrt{1-x^2}}dx=4 \pi $.
Is my idea correct?

A: Yes, this is right. Also, you don't need to do the integral explicitly, because from $\displaystyle \int_S{2\hat{k} \cdot \hat{k}}\,dx\,dy = 2\int_S\,d\sigma$ you can conclude that the result you are looking for is twice the area of the ellipse.


text:
Q: How to know the JavaScript event source on function scope? Question
Is it possible to know if the function was fired by a user event or an async event (like callback) without having the original event parameter?
Background
I'm trying to determine the event source in a deeper function call which doesn't know who was the original event trigger.
I have to know that in order to call a popup or redirection login system. But this function is called from many places, so I can't pass the event parameter in all callers.
Important: I'm not able to pass parameters to the final function. b('timer') is not allowed.
e.g.:
  call

This will get you the very last possible first argument in the chain of function calls. So if you use "normal" events it will give you the event object. And if you use a timeout it will give you whatever you pass to the first function.
Note that this solution also uses arguments.callee.caller which is supposed to be slow and not supported everywhere. And as robC already mentioned, it is not allowed in strict mode.

A: You could use arguments.callee.caller to access the function object and attach an expando... not sure if this is possible for your situation. Note that this won't work in strict mode as arguments.callee.caller is deprecated.
call


text:
Q: Bro script for reading a list of Ips and domains I am trying to read a file with a list of IP addresses and another one with domains, as a proof of concept of the Input Framework defined in https://docs.zeek.org/en/stable/frameworks/input.html
I´ve prepared the following bro scripts:
reading.bro:
type Idx: record {
        ip: addr;
};

type Idx: record {
        domain: string;
};

global ips: table[addr] of Idx = table();
global domains: table[string] of Idx = table();

event bro_init() {
    Input::add_table([$source="read_ip_bro", $name="ips",
                      $idx=Idx, $destination=ips, $mode=Input::REREAD]);

    Input::add_table([$source="read_domain_bro", $name="domains",
                      $idx=Idx, $destination=domains, $mode=Input::REREAD]);

    Input::remove("ips");
    Input::remove("domains");
}

And the bad_ip.bro script, which check if an IP is in the blacklist, which loads the previous one:
bad_ip.bro
@load reading.bro

module HTTP;

event http_reply(c: connection, version: string, code: count, reason: string)
        {
        if ( c$id$orig_h in ips )
                print fmt("A malicious IP is connecting: %s", c$id$orig_h);
        }

However, when I run bro, I get the error:

error: Input stream ips: Table type does not match index type. Need type 'string':string, got 'addr':addr
Segmentation fault (core dumped)

A: You cannot assign a string type to an addr type.  In order to do so, you must use the utility function to_addr().  Of course, it would be wise to verify that that string contains a valid addr first.  For example:
 if(is_valid_ip(inputString){
   inputAddr = to_addr(inputString)
 } else { print "addr expected, got a string"; }


text:
Q: Изменение массива в методе Java Всем привет
Массив является ссылочным типом данных, тоесть если я сначала обьявил и проинициализировал его, затем изменил его в методе, вызвал этот метод и вывожу этот же массив на экран, мне должно показать измененный массив (так как в методе я работал с ссылкой, а не величиной)
Почему же, после вызова метода с этим массивом, мне выводит массив без изменений ?

A: Потому что Вы не изменили массив, который передали, а создали новый.
d = MethodWith...(d);


text:
Q: How to add multiple worksheet from different workbook to new workbook I have three excel files and by selecting cetain sheets from workbook want to create new worksheet
var App = new Microsoft.Office.Interop.Excel.Application();

Workbook  book1 = App.Workbooks.Open(@"path");
Worksheet sheet1 = book1.Worksheets\[1\];

Workbook  book2 = App.Workbooks.Open(@"path");
Worksheet sheet2 = book2.Worksheets\[1\];

Workbook  book3 = App.Workbooks.Open(@"path");
Worksheet sheet3 = book3.Worksheets\[1\];

var newBook = App.Workbooks.Add();
sheet1.UsedRange.Copy(newBook.Worksheets[1].Range["A1"]);

---first sheet1 is adding perfectly but while adding second worksheet sheet2 it is throwing exception System.Runtime.InteropServices.COMException : Exception from HRESULT : 0x800401A8---

sheet2.UsedRange.Copy(newBook.Worksheets[2].Range["A1"]);
sheet3.UsedRange.Copy(newBook.Worksheets[3].Range["A1"]);
newBook.SaveAs(@"path\newWorkbook.xlsx");
newBook.Close();
App.Quit();

I already tried but same exception -
var sourceRange = sheet2.UsedRange; var targetRange = newBook.Worksheets[2].Range["A1"]; sourceRange.Copy(targetRange);

A: var App = new Microsoft.Office.Interop.Excel.Application();

Workbook  book1 = App.Workbooks.Open(@"path");
Worksheet sheet1 = book1.Worksheets\[1\];

Workbook  book2 = App.Workbooks.Open(@"path");
Worksheet sheet2 = book2.Worksheets\[1\];

Workbook  book3 = App.Workbooks.Open(@"path");
Worksheet sheet3 = book3.Worksheets\[1\];

var newBook = App.Workbooks.Add();

sheet1.Copy(newBook.Worksheets[1]);
sheet2.Copy(newBook.Worksheets[2]);
sheet3.Copy(newBook.Worksheets[3]);

//delete sheet which created by default while creating newBook
newBook.Worksheets[4].delete();

string path = @"path";
if(File.Exits(path))
{
File.Delete(path);
}
newBook.SaveAs(path);
book1.Close();
book2.Close();
book3.Close();
App.Quit();


text:
Q: How to search Youtube videos in WebView? I have an Android app with two activities: one of them is the Youtube Webview and the other one is the mainactivity which gets a string from the keyboard.
Is there any way to show the search in Youtube of the string given when i start the Webview activity?
Thanks

A: Yes you can search & play video in webview

public class UniversalWebViewFragment extends Fragment {

    private static final String GOOGLE_SERACH_URL = "https://www.google.com/search?q=";

    private static final String YOUTUBE_SERACH_URL = "https://www.youtube.com/results?search_query=android";

    private WebView webView;
    private FrameLayout customViewContainer;
    private WebChromeClient.CustomViewCallback customViewCallback;
    private View mCustomView;
    private myWebChromeClient mWebChromeClient;
    private myWebViewClient mWebViewClient;

    public static UniversalWebViewFragment newInstance() {

        return new UniversalWebViewFragment();
    }

    public void searchOnGoogle(String key) {
        webView.loadUrl(GOOGLE_SERACH_URL + key);
    }

    public void searchOnYoutube(String key) {
        webView.loadUrl(YOUTUBE_SERACH_URL + key);
    }

    /**
     * Called when the activity is first created.
     */

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.universal_web_view,
                container, false);

        customViewContainer = (FrameLayout) rootView
                .findViewById(R.id.customViewContainer);
        webView = (WebView) rootView.findViewById(R.id.webView);

        mWebViewClient = new myWebViewClient();
        webView.setWebViewClient(mWebViewClient);

        mWebChromeClient = new myWebChromeClient();
        webView.setWebChromeClient(mWebChromeClient);
        webView.getSettings().setJavaScriptEnabled(true);

        // Important for PayUMoney
        webView.getSettings().setDomStorageEnabled(true);

        webView.getSettings().setAppCacheEnabled(true);
        webView.getSettings().setBuiltInZoomControls(true);
        webView.getSettings().setSaveFormData(true);
        webView.loadUrl(GOOGLE_SERACH_URL);
        // webView.requestFocus();

        // Handle Back keyPress
        rootView.setFocusableInTouchMode(true);
        rootView.requestFocus();
        rootView.setOnKeyListener(new OnKeyListener() {

            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {

                if (keyCode == KeyEvent.KEYCODE_BACK) {

                    return true;

                }
                // return super.onKeyDown(keyCode, event);
                return true;
            }
        });

        return rootView;
    }

    public boolean inCustomView() {
        return (mCustomView != null);
    }

    public void hideCustomView() {
        mWebChromeClient.onHideCustomView();
    }

    @Override
    public void onPause() {
        super.onPause(); // To change body of overridden methods use File |
                            // Settings | File Templates.
        webView.onPause();
    }

    @Override
    public void onResume() {
        super.onResume(); // To change body of overridden methods use File |
                            // Settings | File Templates.
        webView.onResume();
    }

    @Override
    public void onStop() {
        super.onStop(); // To change body of overridden methods use File |
                        // Settings | File Templates.
        if (inCustomView()) {
            hideCustomView();
        }
    }

    class myWebChromeClient extends WebChromeClient {
        private View mVideoProgressView;

        @Override
        public void onShowCustomView(View view, int requestedOrientation,
                CustomViewCallback callback) {
            onShowCustomView(view, callback); // To change body of overridden
                                                // methods use File | Settings |
                                                // File Templates.
        }

        @Override
        public void onShowCustomView(View view, CustomViewCallback callback) {

            // if a view already exists then immediately terminate the new one
            if (mCustomView != null) {
                callback.onCustomViewHidden();
                return;
            }
            mCustomView = view;
            webView.setVisibility(View.GONE);
            customViewContainer.setVisibility(View.VISIBLE);
            customViewContainer.addView(view);
            customViewCallback = callback;
        }

        @Override
        public View getVideoLoadingProgressView() {

            if (mVideoProgressView == null) {
                LayoutInflater inflater = LayoutInflater.from(getActivity());
                mVideoProgressView = inflater.inflate(R.layout.video_progress,
                        null);
            }
            return mVideoProgressView;
        }

        @Override
        public void onHideCustomView() {
            super.onHideCustomView(); // To change body of overridden methods
                                        // use File | Settings | File Templates.
            if (mCustomView == null)
                return;

            webView.setVisibility(View.VISIBLE);
            customViewContainer.setVisibility(View.GONE);

            // Hide the custom view.
            mCustomView.setVisibility(View.GONE);

            // Remove the custom view from its container.
            customViewContainer.removeView(mCustomView);
            customViewCallback.onCustomViewHidden();

            mCustomView = null;
        }
    }

    class myWebViewClient extends WebViewClient {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            return super.shouldOverrideUrlLoading(view, url);
        }

        private int webViewPreviousState;

        private final int PAGE_STARTED = 0x1;

        private final int PAGE_REDIRECTED = 0x2;

        Dialog dialog = new Dialog(getActivity());

        /*
         * (non-Javadoc)
         *
         * /* (non-Javadoc)
         *
         * @see
         * android.webkit.WebViewClient#onPageStarted(android.webkit.WebView,
         * java.lang.String, android.graphics.Bitmap)
         */
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            webViewPreviousState = PAGE_STARTED;

            if (dialog == null || !dialog.isShowing())
                dialog = ProgressDialog.show(getActivity(), "",
                        "Loading Please Wait", true, true,
                        new OnCancelListener() {

                            @Override
                            public void onCancel(DialogInterface dialog) {
                                // do something
                            }
                        });
        }

        @Override
        public void onPageFinished(WebView view, String url) {

            if (webViewPreviousState == PAGE_STARTED) {
                if (null != dialog)
                    dialog.dismiss();
                dialog = null;
            }

        }
    }

}

Here is layout for youtube
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
        >
    <WebView
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:id="@+id/webView"
            android:layout_gravity="center"
            />
    <FrameLayout
            android:id="@+id/customViewContainer"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:visibility="gone"
            />
</LinearLayout>

Layout for youtube progress
  <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                  android:id="@+id/progress_indicator"
                  android:orientation="vertical"
                  android:layout_centerInParent="true"
                  android:layout_width="fill_parent"
                  android:layout_height="fill_parent">

        <ProgressBar android:id="@android:id/progress"
                     style="?android:attr/progressBarStyleLarge"
                     android:layout_gravity="center"
                     android:layout_width="wrap_content"
                     android:layout_height="wrap_content"/>

        <TextView android:paddingTop="5dip"
                  android:layout_width="wrap_content"
                  android:layout_height="wrap_content"
                  android:layout_gravity="center"
                  android:text="loading"
                  android:textSize="14sp"
                  android:textColor="?android:attr/textColorPrimary"/>
    </LinearLayout>

Use it like this
universalWebViewFragment = UniversalWebViewFragment.newInstance();
getFragmentManager().beginTransaction()
        .add(R.id.frame_root, universalWebViewFragment).commit();

Search Videos like this
                    universalWebViewFragment.searchOnYoutube(searchView
                            .getText().toString());

dont forgot to add permission
 <uses-permission android:name="android.permission.INTERNET" />

Find full project here https://github.com/hiteshsahu/UniversalWebPageLoader


text:
Q: Multiplayer game with Cocos2d-Javascript and Node.js It is possible to make a multiplayer browser based game using cocos2d-javascript + node.js? If so, is there any tutorial about that?
Thanks in advance!

A: Your question is more suitable for this stack site in my opinion
https://gamedev.stackexchange.com/


text:
Q: BIND9/DNS lookups stopped working after upgrading our Comcast modem/gateway OK here's our setup, we're running pfSense as our firewall/router. We have a dual-WAN with a Comcast Business Gateway and another local ISP. We're running Samba as the domain controller & Bind9/Named for DNS. Here's the issue, we just upgraded our Comcast service to a higher speed & they replaced the modem/gateway. Once they did that we could no longer browse the internet from inside the LAN over the Comcast pipe. If I disable our Comcast pipe in pfSense we can get to the internet over our other ISP.
I'm pretty sure the issue is with Bind, but not changed on it when the modem was replaced. Here is some output when I run nslookup & dig on the domain controller/bind box. Both nslookup & dig work if I specify an external DNS server, but not when they use the internal DNS bind service.
[root@dc etc]# nslookup comcast.com
Server:         127.0.0.1
Address:        127.0.0.1#53

** server can't find comcast.com: NXDOMAIN

[root@dc etc]# nslookup comcast.com 8.8.8.8
Server:         8.8.8.8
Address:        8.8.8.8#53

Non-authoritative answer:
Name:   comcast.com
Address: 69.252.80.75

[root@dc etc]# dig comcast.com
; <<>> DiG 9.9.4-RedHat-9.9.4-61.el7 <<>> comcast.com
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: SERVFAIL, id: 3360
;; flags: qr rd ra; QUERY: 1, ANSWER: 0, AUTHORITY: 0, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 4096
;; QUESTION SECTION:
;comcast.com.                   IN      A

;; Query time: 1 msec
;; SERVER: 127.0.0.1#53(127.0.0.1)
;; WHEN: Sat Apr 11 17:08:25 PDT 2020
;; MSG SIZE  rcvd: 40

[root@dc etc]# dig @8.8.8.8 comcast.com
; <<>> DiG 9.9.4-RedHat-9.9.4-61.el7 <<>> @8.8.8.8 comcast.com
; (1 server found)
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 26449
;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 4096
;; QUESTION SECTION:
;comcast.com.                   IN      A

;; ANSWER SECTION:
comcast.com.            32      IN      A       69.252.80.75

;; Query time: 4 msec
;; SERVER: 8.8.8.8#53(8.8.8.8)
;; WHEN: Sat Apr 11 17:08:43 PDT 2020
;; MSG SIZE  rcvd: 56

Also, if I disable our Comcast pipe in pfSense and do nslookup comcast.com or dig comcast.com over the other ISP, they return perfectly fine when using the internal DNS bind service.
Here is my named.conf file
acl mynetworks {
    192.168.254.0/24;
    192.168.252.0/24;
    192.168.251.0/24;
    192.168.250.0/24;
 };

options {
    listen-on port 53 { localnets; };
    listen-on-v6 { none; };
    directory   "/var/named";
    dump-file   "/var/named/data/cache_dump.db";
    statistics-file "/var/named/data/named_stats.txt";
    memstatistics-file "/var/named/data/named_mem_stats.txt";
    allow-query     { localhost; mynetworks; };

    recursion yes;
    dnssec-enable yes;
    dnssec-validation auto;
    dnssec-lookaside auto;

    /* Path to ISC DLV key */
    bindkeys-file "/etc/named.iscdlv.key";

    managed-keys-directory "/var/named/dynamic";

    pid-file "/run/named/named.pid";
    session-keyfile "/run/named/session.key";

    # samba BIND9_DLZ
    tkey-gssapi-keytab "/var/lib/samba/private/dns.keytab";
};

logging {
    channel default_debug {
        file "data/named.run";
        severity dynamic;
    };
    channel my_log_file {
        file "/var/log/named/named.log" versions 3 size 3m;
        severity info;
        print-time yes;
        print-severity yes;
        print-category yes;
    };
    channel my_syslog {
        syslog daemon;
        severity info;
        print-time no;
        print-severity no;
        print-category no;
    };
    category default { my_log_file; my_syslog; };
    category dnssec  { my_log_file; };
    category lame-servers { null; };
};

// so we can control the running named process with the rndc utility
include "/etc/rndc.key";

zone "." IN {
    type hint;
    file "named.ca";
};

dlz  "tipping.lan" {
     database "dlopen /usr/lib64/samba/bind9/dlz_bind9_9.so";
};

include "/etc/named.rfc1912.zones";
include "/etc/named.root.key";

If I connect a laptop directly to the Comcast modem, I can get to the internet just fine. Also, if I bypass our domain controller on a LAN workstation to use an external DNS server, I can access the internet over the Comcast pipe.
So why is DNS/Bind working on one pipe, but not the other? Any help would be greatly appreciated.

A: I was able to fix my DNS issues by putting BIND in forwarding mode & not allowing it to use the root authority servers.
Seems Comcast SecurityEdge is blocking the root servers, but not 1.1.1.1 or 8.8.8.8


text:
Q: Accessing a server through VPN We have a webserver which is hosted outside our office.
The firewall of the server limits the access (ssh, sftp, etc) by ip; only the public static ips of our office can access it.
Our problem is that the responsible person has to come to the office to work in case of emergency. We would like to find a solution to allow him to work without the location constraint.
Unfortunately our VDSL router (Zyxel P-870HN-51b) has not VPN capabilities.
We were simply thinking about buying a firewall (ZyXEL ZyWALL USG 40) and have it setup in our office so the remote employee would "get" a whitelisted public ip.
Is it a safe solution? Or would you advice something totally different?

A: You're website's security is partially dependent on your office's network security. You're talking about adding a means of making a remote connection into your office's network. Adding the VPN will provide a new attack vector (hacking the VPN logon or VPN device) so you'll be weakening your existing security.
That said, what you're proposing is a fairly standard configuration and functionality that VPNs are intended to provide. So take care with the VPN configuration and you should be OK.

A: Have you tried Dome9? http://dome9.com
They provide on-demand access from your local IP address, or you can send a invitation to a remote employee.

Dome9's Secure Access Lease Invitations use patent-pending security automation to invite only those you authorize to securely access your cloud servers.
Instead of relying solely on usernames and passwords, which are often shared or lost,  Dome9 lets you lockdown your cloud servers and with just a few clicks, generate one-time secure access invitations for authorized third parties.
Secure Access Lease InvitationInvite your developers, consultants, and other trusted users to securely access your servers, on-demand, without exposing your cloud to brute force attacks and exploits – even if their credentials are compromised!

http://www.dome9.com/overview/secure-access-invitations
I've been using them for the past year. Haven't had any complaints.


text:
Q: Error calculating planetary positions using swiss ephemeris I've used Swiss Ephemeris to calculate planetary positions, using PHP and tested today's date 12-12- 2015, time 18:00 and location Delhi ( 29 N, 77 E)
Here are the results
Sun - 235 vs 236 on other sites (astrosage.com) Moon - 251 vs 249 Ascendant 160 vs 65
I've tried 3 different methods to calculate the longitude of the ascendant, but I've got it wrong all the time. Also the longitudes of the Sun and Moon vary in degrees.
    <?php
$year= 2015;
$month=12;
$date=12;
$time=18;
$geo_lat_delhi= 29;
$geo_long_delhi= 77;
$jul_day_UT = swe_julday($year,$month,$date,$time,SE_GREG_CAL);
$swe_day_ut = swe_sidtime($jul_day_UT);

echo "=======Sun sign===========";
$p = 0;
  $ret_flag_sun = swe_calc_ut($jul_day_UT,$p,SEFLG_SIDEREAL);
  echo '<pre>';
print_r($ret_flag_sun);

echo "=======Moon sign===========";
$p = 1;
  $ret_flag_moon = swe_calc_ut($jul_day_UT,$p,SEFLG_SIDEREAL);
  echo '<pre>';
print_r($ret_flag_moon);

echo "===Method1 Ascendant =Cusp [1]====";
$asc1 = swe_houses($jul_day_UT,$geo_lat_delhi,$geo_long_delhi,'A');
echo '<pre>';
print_r($asc1);

echo "===Method2 Ascendant =Cusp [1]====";
swe_set_sid_mode(SE_SIDM_LAHIRI,0,0);
$asc2 = swe_houses_ex($jul_day_UT,SEFLG_SIDEREAL,$geo_lat_delhi,$geo_long_delhi,'A');
echo '<pre>';
print_r($asc2);

echo "===Method3 Ascendant =Cusp [1]====";
$asc3 = swe_houses_ex($swe_day_ut,SEFLG_SIDEREAL,$geo_lat_delhi,$geo_long_delhi,'A');
echo '<pre>';
print_r($asc3);

exit;
?>

You can view the results here - farfaraway.co/swisscode.php
Do you any idea where am I going wrong, any help will be much appreciated.
Cheers!

A: you need to set more flags than SEFLG_SIDEREAL (for instance SEFLG_SPEED), they are designed to be bitwise OR'd together.


text:
Q: Access Get or Post parameters in MVC Web Api Authorization filter I want to achieve the same as Accessing post or get parameters in custom authorization MVC4 Web Api ,but it only works in the case of a GET request.
So I have written the follwoing action filter for a web api:
 public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext   actionContext)
    {
        var request = actionContext.Request;
        var headers = request.Headers;
        HttpContext ctx = default(HttpContext);
        ctx = HttpContext.Current;

        if (ctx != null)
        {
            var apiKey = (string)actionContext.ActionArguments["apiKey"];
        }
    }

The form that posts looks like:
<form name="form1" method="post" enctype="multipart/form-data" action="@localPostUrl">
<fieldset>
    <legend>File Upload Example</legend>

        Image Caption
        <input name="caption" type="text" />

        Image File
        <input name="image1" type="file" />

        <input type="text" name="apiKey" id="apiKey" value="b2b54e7b-ca0b-4adf-a369-efe839e55120" />
        <input type="submit" value="Submit" />

</fieldset>

So I'm trying to post an image and a string to the Web Api but the actionContext.ActionArguments in the ActionFilter is empty when doing a POST request but is working when doing a GET request.
When compared to the solution provided on top of my question I notice that the action where that posts has an attribute FormUri added to a parameter, but I can't send the ApiKey in the querystring.
Is there a solution to getting the Post paramteres in order to do some form on validation?


text:
Q: Getting Source-Dest IP and PORT data for traffic monitoring in ONOS I am trying to implement a monitoring system using ONOS. I am able to collect the port delta statistics from them using port_stat_changed listener.
In the flow statistics, I get the flow entry, which has selection criterion. This criterion only has only Ethernet information. Is there any way to identify the Source and Destination IP address and Port using ONOS. Any suggestion would be very helpful.

A: The source and destination IP and MAC if they are not in the Switch's rules can be accessed by the application by taking this information from the packets. If your application does not have access to the packages, I do not think the Switches store this kind of information. In case, then, you're going to have to develop a solution by putting a rule in the Switch to pick up that data.


text:
Q: GIT - Force manual merge for branch that would otherwise merge cleanly I have the following situation
git branch
* master

git branch upgrade-project
git checkout upgrade-project

# At this point I run an update script from a third party that replaces
# many files I have already modified.
git checkout master

# I want all conflicts to be marked regardless of weather GIT can merge them automatically.
git merge upgrade-project

The problem there is that it will cleanly merge all files replaced by the update-scripts from the upgrade-project branch as it is ahead of master which makes perfect sense in normal situations.
What I want is that when I merge upgrade-project into master all files that are in conflict are marked as such.
This was I can manually compare and make my modifications as needed.
Is this possible?

A: Merge your branch, but do not commit the changes:
git merge --no-commit upgrade-project

Clean the index, leaving the changes in working directory:
git reset

Resolve any conflict marked with <<<<< if any.
Interactivelly add the "good" changes you need to the index and commit them:
git add -p
git commit

Clean your working directory from unnecessary changes:
git reset --hard

A:
upgrade-project branch is ahead of master.
  Merging upgrade-project back into master would merge cleanly (no conflicts).
  I would like to force conflicts for all files that are not exactly the same

You can get a list of the files which are going to be pulled out before you execute the pull:
git checkout master
git diff --name-only upgrade-project

or:
git log --stat master ^upgrade-project

or
git format-patch master...upgrade-project

The last code sample will create a patch of each commit you have (diffrence between the branches which are going to be merged).


text:
Q: Kendo MVC Grid Data Annotations I Have a solution that used Telerik Grids and we opt to upgrade to Kendo.
But now, Kendo doesn't seem to respect the row's model data annotations for Required, Regular Expressions, etc, on validations.
Anyone can explain if this is how they work or if it is a problem of my own doing?

A: Basically the data annotation attributes should work the same way as they worked with the old MVC extensions. Pick this project and give a try.
http://www.kendoui.com/code-library/mvc/grid/custom-popup-editor.aspx


text: Q: Probability of lines intersecting in a square. Suppose that you select two random line segments in a square, by selecting their endpoints uniformly at random. What is the probability that they intersect?