Q: Comparison of 2 string variables in shell script Consider there is a variable line and variable word:
line = 1234 abc xyz 5678
word = 1234

The value of these variables are read from 2 different files.
I want to print the line if it contains the word. How do I do this using shell script? I tried all the suggested solutions given in previous questions. For example, the following code always passed even if the word was not in the line.
if [ "$line"==*"$word"*]; then
    echo $line
fi

A: No need for an if statement;  just use grep:
echo $line | grep "\b$word\b"

A: You can use if [[ "$line" == *"$word"* ]]
Also you need to use the following to assign variables
line="1234 abc xyz 5678"
word="1234"

Working example -- http://ideone.com/drLidd

A: Watch the white spaces!
When you set a variable to a value, don't put white spaces around the equal sign. Also use quotes when your value has spaced in it:
line="1234 abc xyz 5678"   # Must have quotation marks
word=1234                  # Quotation marks are optional

When you use comparisons, you must leave white space around the brackets and the comparison sign:
if [[ $line == *$word* ]]; then
    echo $line
fi

Note that double square brackets. If you are doing pattern matching, you must use the double square brackets and not the single square brackets. The double square brackets mean you're doing a pattern match operation when you use == or =. If you use single square brackets:
if [ "$line" = *"$word"* ]

You're doing equality. Note that double square brackets don't need quotation marks while single brackets it is required in most situations.

A: echo $line | grep "$word"

would be the typical way to do this in a script, of course it does cost a new process

A: You can use the bash match operator =~:
 [[ "$line" =~ "$word" ]] && echo "$line"

Don't forget quotes, as stated in previous answers (especially the one of @Bill).

A: The reason that if [ "$line"==*"$word"* ] does not work as you expect is perhaps a bit obscure.  Assuming that no files exist that cause the glob to expand, then you are merely testing that the string 1234 abc xyz 5678==*1234* is non empty.  Clearly, that is not an empty string, so the condition is always true.  You need to put whitespace around your == operator, but that will not work because you are now testing if the string 1234 abc xyz 5678 is the same as the string to which the glob *1234* expands, so it will be true only if a file named 1234 abc xyz 5678 exists in the current working directory of the process executing the shell script.  There are shell extensions that allow this sort of comparison, but grep works well, or you can use a case statement:
case "$line" in
*$word*) echo $line;;
esac

A: An alternative solution would be using loop:
for w in $line
do
    if [ "$w" == "$word" ]; then
        echo $line
        break
    fi
done

A: Code Snippet:
$a='text'
$b='text'

if [ $a -eq $b ]
 then
   msg='equal'
fi


Q: Javascript Errors when loading Bootstrap Modal a second and third time that contains a form with drop downs I'm a complete beginner...please excuse the mess. Only been learning for about a month.
The structure is like this.
I have a nav.html template I've created for a top level menu across the site. It contains a drop down for creating New entries...and in this case a 'New Job'
Job has two special parts.

*

*I've used Django-autocomplete-light for finding/creating new customers in the one form. This leverages select2 and some other javascript wizards

*A google places autocomplete for finding site addresses

Everything worked fine as just opening in a fresh page. Then I decided I wanted to put the New Job form in to a modal instead. I'm an idiot.
I'm using non-modified bootstrap css and the js for it as well...but pulled them down to be local copies in my static folder. Same goes for jquery and popper.
Got it to actually work/pop up fine but then these happened in the background. Grabs from the google chrome console. These are the errors I see when just opening and closing without entering any data.
I started learning about the javascript event loop and it hurt my brain...but does this all have something to do with that? This kind of feels like things are loading...and then not unloading if I'm making any sense. Every example out there is based on using a button...and I've gone with a drop down selection but I don't feel like that should make any difference. Please help.
Screenshot of the first run error
Screenshot of the second run error
Screenshot of the third run error
Here's the code for all the bits n pieces. If I'm missing something, let me know.
NAV.HTML (contains the dropdown to trigger the modal....towards the bottom called "create-job")
{% load static %}
<!DOCTYPE html>

    <link rel="stylesheet" href="{% static '/css/bootstrap/bootstrap.css'%}">

    <title>Easy Insulation</title>

        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

        </button>

                    Dashboard(current)

                    Planning(current)

                        Jobs

                        Pipelines
                        List

                        Contacts

                        Businesses
                        Contacts

                    Services(current)

                    Admin(current)

                    Meh

            <button type="button" class="btn btn-success dropdown-toggle" data-toggle="dropdown" aria-haspopup="true"
                aria-expanded="false">
                New
            </button>

                Job
                Activity

                Contact
                Organisation

        <form class="form-inline my-2 my-lg-0">
            <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">
            <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
        </form>

    {% block content %}
    You need to build some content here tups
    {% endblock %}
    {% block extra_content %}
    More space for stuff
    {% endblock %}

And this is the code for the Modal that pops up
NEWJOB.HTML
{% load static %}
<!DOCTYPE html>

  <link rel="stylesheet" href="{% static '/css/bootstrap/bootstrap.css'%}">
  <link rel="stylesheet" href="{% static '/css/modal.css'%}">

  {% block content %}

  <form method="post" action="">
    {% csrf_token %}

Create New Job

      <button type="button" class="close" data-dismiss="modal" aria-label="Close">
        ×
      </button>

      {% for field in form %}

        {{ field.label }}
        {{ field }}
        {% for error in field.errors %}

{{ error }}

        {% endfor %}

      {% endfor %}

      <button id="disposeBtn" type="button" class="btn btn-primary" data-dismiss="modal">Close</button>
      <button type="button" class="submit-btn btn btn-primary">Create</button>

  </form>

  {% endblock %}
  {% block extra_content %}
  {{form.media}}
  {% endblock %}

This is the googlepac.js file

var autocomplete;

function initAutocomplete() {
  autocomplete = new google.maps.places.Autocomplete(
      document.getElementById('id_site_address'), {types: ['address']});
  autocomplete.setFields(['address_component']);
}

the query.bootstrap.modal.forms.js from some super smart bro on the internet.
/*
django-bootstrap-modal-forms
version : 1.5.0
Copyright (c) 2019 Uros Trstenjak
https://github.com/trco/django-bootstrap-modal-forms
*/

(function ($) {

    // Open modal & load the form at formURL to the modalContent element
    var newForm = function (modalID, modalContent, modalForm, formURL, errorClass, submitBtn) {
        $(modalID).find(modalContent).load(formURL, function () {
            $(modalID).modal("show");
            $(modalForm).attr("action", formURL);
            // Add click listener to the submitBtn
            addListeners(modalID, modalContent, modalForm, formURL, errorClass, submitBtn);
        });
    };

    // Submit form callback function
    var submitForm = function(modalForm) {
      $(modalForm).submit();
    };

    var addListeners = function (modalID, modalContent, modalForm, formURL, errorClass, submitBtn) {
        // submitBtn click listener
        $(submitBtn).on("click", function (event) {
            isFormValid(modalID, modalContent, modalForm, formURL, errorClass, submitBtn, submitForm);
        });
        // modal close listener
        $(modalID).on('hidden.bs.modal', function (event) {
            $(modalForm).remove();
        });
    };

    // Check if form.is_valid() & either show errors or submit it
    var isFormValid = function (modalID, modalContent, modalForm, formURL, errorClass, submitBtn, callback) {
        $.ajax({
            type: $(modalForm).attr("method"),
            url: $(modalForm).attr("action"),
            // Serialize form data
            data: $(modalForm).serialize(),
            beforeSend: function() {
                $(submitBtn).prop("disabled", true);
            },
            success: function (response) {
                if ($(response).find(errorClass).length > 0) {
                    // Form is not valid, update it with errors
                    $(modalID).find(modalContent).html(response);
                    $(modalForm).attr("action", formURL);
                    // Reinstantiate listeners
                    addListeners(modalID, modalContent, modalForm, formURL, errorClass, submitBtn);
                } else {
                    // Form is valid, submit it
                    callback(modalForm);
                }
            }
        });
    };

    $.fn.modalForm = function (options) {
        // Default settings
        var defaults = {
            modalID: "#modal",
            modalContent: ".modal-content",
            modalForm: ".modal-content form",
            formURL: null,
            errorClass: ".invalid",
            submitBtn: ".submit-btn"
        };

        // Extend default settings with provided options
        var settings = $.extend(defaults, options);

        return this.each(function () {
            // Add click listener to the element with attached modalForm
            $(this).click(function (event) {
                // Instantiate new modalForm in modal
                newForm(settings.modalID,
                    settings.modalContent,
                    settings.modalForm,
                    settings.formURL,
                    settings.errorClass,
                    settings.submitBtn);
            });
        });
    };

}(jQuery));


Q: 'Termination due to memory pressure" in UIWebView I have started receiving app termination due to memory pressures very recently (mostly with iOS 7). The app used to work very well on iOS 6.
The app is mostly uses a UIWebView to display a webpage. However for a few webpages it creates ever increasing Dirty memory with most of it due to Image IO and Performance tool data (see attached instruments screenshots). I am completely clueless as to where to dig next. Could someone guide me what should I do here onwards? In the second screenshot I see a sudden bump in the memory allocations. Is there a way to spot the process/part of the code which caused it?
EDIT One can reproduce these results in a simple demo kept at www.github.com/nikhiljjoshi/iosCrash (just change the site to www.nzz.ch).
Thanks in advance,
Nikhil


Q: Can I use openssl to generate key/cert for tomcat? According to http://tomcat.apache.org/tomcat-7.0-doc/ssl-howto.html#Create_a_local_Certificate_Signing_Request_(CSR) I can use keytool to generate the key and cert for tomcat but can I use openssl?
If yes, is there any openssl guideline for tomcat?
Respond to: Mr Valerio Minetti
Yes, the goal is we want to setup the SSL on a tomcat server.
One of my colleagues created the CSR and sent to Thawte, and Thawte return us cert file.
Because my colleague is busy, he hand over this job to me, to setup the tomcat.
After investigating (not the openssl), the fact is my colleague created the CSR by Symantec SSL assistance.
Symantec generated 2 files:
www_xxxxxxxxxx_com_rsa_csr.txt
www_xxxxxxxxxx_com_rsa_private.key

My colleague use www_xxxxxxxxxx_com_rsa_csr.txt to apply cert from Thawte.
So now I need to  do the following steps?

*

*using the keytool to create keystore

*then import the private key www_xxxxxxxxxx_com_rsa_private.key

*import the chain cert from Thawte

*import our site cert

Am I correct?

A: You can generate certs and keys with openssl, but in order to have tomcat using them you will have to use keytool to import it in a tomcat keystore.
you can find some examples here: link


Q: Estimate number of breakpoints in regression I've been playing around with the package strucchange (and to some extent segmented) in R. I'm trying to determine whether there are changes in slope in a linear regression and more importantly, how many breakpoints. A toy dataset:
x <- c(0, 5, 10, 15, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80)
y <- c(-84.16, -86.67, -87.74, -86.07, -89.15, -91.90, -93.64, -95.92,
  -95.96, -99.19, -100.73, -107.29, -106.10, -107.29)

First problem: if I use the breakpoints function:
breakpoints(y ~ x, data = data.frame(x, y))

I get the following error:
Error in breakpoints.formula(y ~ x, data = data.frame(x, y)) :
minimum segment size must be greater than the number of regressors

I think this arises because the default h parameter in the breakpoints command is 0.15 and 14 (the number of observations I have) * 0.15 = 2.1 which, rounded down, is not greater than 2 (the "number of regressors": incidentally, I would have thought the number of regressors would be 1 given my formula but I've learned from other working examples of y ~ x that nreg = 2 in these cases. I guess the intercept counts as a regressor?).
If I set h to 3 or some fraction such that 14 * h >= 3, the command works.
breakpoints(y ~ x, data = data.frame(x, y), h = 3)

Two breakpoints are returned. But the result is sensitive to h. Such that if I use:
breakpoints(y ~ x, data = data.frame(x, y), h = 4)

I get a different solution. In the latter case, a single optimal break is found because the minimum number of observations before a break can be called is higher. Is there a way to somehow determine whether one solution has more support than the other? In other words, how best to optimize not the position of breakpoints, but the number of breakpoints (perhaps across values of h)? I think the Fstats command might be the key but I'm having a lot of trouble understanding the help for this command...

A: Some remarks:

*

*You need to estimate two parameters in each segment (intercept and slope). Hence breakpoints() requires that there are at least three observations in each segment...otherwise you cannot estimate the parameters (without getting a perfect fit).

*But three is the minimal value that is technically possible. Whether or not it leads to meaningful results is a different question. Usually, you probably wouldn't use a regression model for just three observations, would you?

*Therefore the task of identifying 2 breakpoints plus 6 regression coefficients (three intercepts and three slopes) from just 14 observations is really challenging. Without using additional prior knowledge it is probably hard to argue that this does not overfit the data.

*If you set the minimal segment size to 5 (or higher) you cannot estimate 2 breakpoints on 14 observations. Hence, setting h = 3 or h = 4 are the only options that would allow 2 breakpoints. The reason that the latter prefers only 1 breakpoint is that it is not possible anymore to group the last three observations into their own segment.

*More documentation than on the manual page are in the third reference in citation("strucchange") discussing practical problems in breakpoint estimation.
To compare the 1- and 2-breakpoint solution you can first estimate the breakpoints:
bp <- breakpoints(y ~ x, h = 3)

And then you can visualize the fits:
plot(y ~ x, pch = 19)
lines(fitted(bp, breaks = 1) ~ x, col = 4, lwd = 1.5)
lines(fitted(bp, breaks = 2) ~ x, col = 2, lwd = 1.5)

As remarked above: From a purely data-driven perspective, I would probably consider both models overfitting. But maybe one or the other model has a plausible interpretation for you.


Q: Windows Phone 8.1 xbox music Is it any way to control Xbox Music on Windows Phone 8.1 or Windows Phone 8.0 from another application. I want to create an application with different style controls which start local music in background, getting some information from xbox music and so on. Is native Windows Phone 8.1 xbox music provide any API?
Thanks!

A: Have you tried with the official API?
Getting started with the API is on MSDN.

A: the Xbox Music API I could not find it working for windows Phone 8.1 but there are packages for Windows Phone 8 and windows 8.1


Q: Street view panorama doesn't work in a div I'm trying to embed a street view panorama on a website as explained here. It works well when I do that :

but it doesn't work when i put the #map in a other div, like that :

Do you have any idea why ?

A: Can you add width and height map div? If you have blank page instead map, it's probably missing css.


Q: Where did the idea of genetic memory originate? Recently I started re-watching (/playing in the background whilst I work) the Sci-Fi series Andromeda.
In the first series I come to an episode with a familiar sounding premise. The heroes arrive on a planet inhabited by people who pass on memories through the generations. That is, if you have a kid, that kid remembers everything that you remember up to the point it was conceived.
Now, Andromeda is an old series, it's from the turn of the millennium. But this sounds awfully familiar to me.... Assassin's Creed much?
The entire premise of the Assassin's Creed games is based on the idea that locked within our genetic code is the memories of our ancestors and with a special machine these can be unlocked and explored.
It strikes me that an idea such as this cannot possibly have came from an episode of a low budget early 2000s science fiction show. That Andromeda and Assassin's Creed must be taking their influence from earlier works.
Does anyone know where this idea originates? Are there any other prominent examples of it in practice?

A: Trofim Denisovich Lysenko was a Soviet agrobiologist. Lysenko was a strong proponent of soft inheritance -- offspring could acquire learned behavior from their parents' genetic code -- and rejected Mendelian genetics in favor of pseudoscientific ideas termed Lysenkoism.  Lysenkoism was a late addition to the "inheritance of soft characteristics" and was considered a branch of Lamarckism.
This as made official biological dogma in the USSR in 1948.
You can see the attractiveness of this idea, especially for tyrants whose people who have grown up accepting their role in an authoritarian state.  Make one generation totally accepting and you are more or less set for a long stable dictatorship.
Links:
Trofim Lysenko biography   https://en.wikipedia.org/wiki/Trofim_Lysenko
Inheritance of Acquired Characteristics:  https://en.wikipedia.org/wiki/Inheritance_of_acquired_characteristics
Lamarckism:  https://en.wikipedia.org/wiki/Lamarckism
Lysenkoism:  https://en.wikipedia.org/wiki/Lysenkoism


Q: Installation of tools in Azure virtual machine I have a requirement to install tools like Nagios, BigFix and other tools inside an Azure virtual machine once it gets provisioned and joined to the domain. Currently, I have written PowerShell scripts for a remote installation of these tools via Jumpbox once the VM is domain joined.
Is there any other way this can be achieved?


Q: Can we find two other angles of a triangle if we have only one angle? Can we find two other angles of a triangle if we have only one angle? If yes, then how?

A: The sum of all angles of a triangle is constant. On a plane of curvature of zero (a Euclidian plane or flat plane), this is equal to 180 degrees.
ie.
$$180^{\circ} = \theta_1 + \theta_2 + \theta_3$$
In your case you know $\theta_1$ but $\theta_2$ and $\theta_3$ are unknown. This results in one equation with two unknowns.
Thus when one angle is given there is more information needed to find the other two angles.

A: If two triangles are similar, they have the same angles. The criteria needed for similarity of the other triangle are:
$$\text{AA or AAA (at least $2$ angles known)}$$
$$\text{SSS (all $3$ sides known)}$$
$$\text{SAS ($2$ sides and the angle in between is known)}$$
Since one angle known is not in the criteria needed for similarity, you cannot find the two other angles. As ElderNoSpace wrote, you need at least $1$ other angle to find these angles.


Q: How do I change the select option from the component in Angular2? I have a dropdown like below
html
<mat-form-field>
  <mat-select placeholder="Team" [(ngModel)]="selectedTeam" name="team"
              (change)="mainValuesChanged('team',$event,t.value)" #t>
      <mat-option *ngFor="let team of teams" [value]="team.value"  >
      {{ team.viewValue }}
      </mat-option>
  </mat-select>
</mat-form-field>

ts
selectedTeam="team1"
teams = {"value":"t1","viewValue":"team1",
         "value":"t2","viewValue":"team2",
         "value":"newTeam",""viewValue":"Create Team"}

What I'd like to do is when the user clicks on 'Create Team' the previous values(t1:team1 or t2:team2) remain same, while I create a new team by form, etc.
How do I get reference to the select element so that I can change [value] to the previous value?
So far I have this:
mainValuesChanged(term,event:MatSelectChange,tValue){
    if (event.value==="newTeam"){
        this.selectedTeam = getPrevTeamNamefromAService();
        #hack, hack
    }
}

If I could only reference the select element and set the [value] to selectedTeam or just change the selected value from the component without a direct reference, I would be able to do this. How do I achieve this?

A: If you take a look at the API docs for the select, you can see that MatSelect is exported as matSelect. This means that you can get a reference to the select in the template by writing #t="matSelect". If you then pass this #t into your function, you can update the select's value like this:
mainValuesChanged(term, event:MatSelectChange, select: MatSelect){
    if (event.value==="newTeam"){
        select.writeValue(getPrevTeamNamefromAService());
    }
}

Hope this helps.


Q: merging two xmls of same number of nodes I have merged two xml files using java dom parser:
a.xml
<config>
<category name="mimetypes">
<!-- application mime types -->
<mime-type type=1></mime-type>
<!-- eps -->
<mime-type type=2></mime-type>
<!-- octet-stream -->
<mime-type type=3></mime-type>
</category>
</config>

b.xml:
<config>
<category name="mimetypes">
<!-- application mime types -->
<!-- eps -->
<mime-type type=2></mime-type>
<!-- octet-stream -->
<mime-type type=3></mime-type>
<mime-type type=4></mime-type>
</category>
</config>

the output I get
<config>
<category name="mimetypes">
<!-- application mime types -->
<mime-type type=1></mime-type>
<!-- eps -->
<mime-type type=2></mime-type>
<!-- octet-stream -->
<mime-type type=3></mime-type>
</category>
<mime-type type=2></mime-type>
</config>

Expected:
<config>
<category name="mimetypes">
<!-- application mime types -->
<mime-type type=1></mime-type>
<!-- eps -->
<mime-type type=2></mime-type>
<!-- octet-stream -->
<mime-type type=3></mime-type>
<mime-type type=4></mime-type>
</category>
</config>

Code I have tried:
public class MergeXmlDemo {
    public static void main(String args[]){
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = null;
        Document doc = null;
        Document doc2 = null;
                db = dbf.newDocumentBuilder();
                doc = db.parse(new File("second.xml"));
                doc2 = db.parse(new File("first.xml"));
                NodeList ndListFirstFile = doc.getElementsByTagName("config");
                Node nodeArea = doc.importNode(doc2.getElementsByTagName("mime-type").item(0), true);
                ndListFirstFile.item(0).appendChild(nodeArea);
                TransformerFactory tFactory = TransformerFactory.newInstance();
                Transformer transformer = tFactory.newTransformer();
                transformer.setOutputProperty(OutputKeys.INDENT, "yes");
                DOMSource source = new DOMSource(doc);
                //StreamResult result = new StreamResult(new StringWriter());
                StreamResult result = new StreamResult(System.out);
                transformer.transform(source, result);
}

merging two xml files with same number of nodes is giving the file with same number of nodes and type=4 is missing from the output.
Any help is appreciated


Q: Is there any way to extend the prime membership of user from one month to 3 or 6 month using stripe I'am working on an application where user subscribe the premium membership using stripe. The subscription function is working properly with one month of billing cycle. Now I have to update the prime membership of user to 3 or 6 months. Please help me for this. I have implemented the stripe using spring boot REST api.

A: Stripe has a guide to upgrading or downgrading Subscriptions that covers what you're asking about.
The high-level steps are:

*

*Create a new Price representing the new billing period under the Product you already have

*Update the Subscription using the new Price


Q: AS/400 QSYRUSRI API parameters I'm trying to use the QYSRUSRI api to retrieve the number of supplemental groups in an Iseries user profile.
There is an offset pointer to the beginning of the array holding this data. The spec for format USRI0300 mentions this as starting in position 585 of the receiver variable but in my implementation that subfield (suppGrpIdx) contains zero even though the subfield for the number of supplemental groups (suppGrp) contains 6, which is correct for the profile I am analysing.
See below for my DS specifications for the received data.
Any ideas what I'm missing?
D USRI0300        DS                  based(p_usrData) qualified
D   name                        10a   overlay(USRI0300:9)
D   prevSign                     6a   overlay(USRI0300:20)
D   signTries                   10i 0 overlay(USRI0300:33)
D   status                      10a   overlay(USRI0300:37)
D   changed                      8a   overlay(USRI0300:47)
D   expires                      8a   overlay(USRI0300:61)
D   special                     15a   overlay(USRI0300:84)
D   groupprf                    10a   overlay(USRI0300:99)
D   owner                       10a   overlay(USRI0300:109)
D   authority                   10a   overlay(USRI0300:119)
D   initmenu                    20a   overlay(USRI0300:149)
D   initpgm                     20a   overlay(USRI0300:169)
D   jobd                        20a   overlay(USRI0300:290)
D   text                        50a   overlay(USRI0300:199)
D   suppGrpIdx                  10i 0 overlay(USRI0300:585)
D   suppGrp                     10i 0 overlay(USRI0300:589)

Here is my Prototype:-
D QSYRUSRI        PR                  ExtPgm('QSYRUSRI')
D   RcvVar                   32767a   options(*varsize)
D   RcvVarLen                   10i 0 const
D   Format                       8a   const
D   UsrPrf                      10a   const
D   ErrCode                  32767a   options(*varsize)

A: I tried your code, and I put %SIZE(USRI00300) as the second parameter, and I got zero for suppGrpIdx too.
As Charles and Mark Sanderson implied, you have to make the receiver big enough to give all the information and also tell the API how big the receiver is. I'm guessing that since you defined your data structure as based, that you are setting p_usrData to some larger storage. If so, give the length of the larger storage instead of the size of USRI0300.
When I set p_usrData to point to a 32767-length buffer, and put %size(buffer) as the second parameter, I got 722 for suppGrpIdx.


Q: how to display corresponding record from access based on other column in Datagrid in vb6 I am using Vb6 ! I have one datagrid named "Datagrid1" and i display certain contents such as subjectname, subjectcode, theory_practical from the table named "subjectcode" in Datagrid1 from access database.
And i have another table named "feedetail". My doubt is, if the "theory_practical" value is theory means, then it should display the theoryfee from the table named feedetail or if "theroy_practical" value is practical means, then it should display practical fee in the new column named "Fee" in datagrid1.
I am having confusion with the sql statement and displaying in datagrid ! here is my code that i used!
I want to display the corresponding fee in the next column to the Theory_Practical heading ! I can't attach a screenshot file n it shows error! so here is the link of the screenshot file!  Thanks in advance !
    Public con As New ADODB.Connection
    Public rs As New ADODB.Recordset
    Public rs2 As New ADODB.Recordset

    Private Sub Command1_Click()
    Dim semesternew As String
    semesternew = semester.Caption
    Select Case semesternew
    Case "I"
    semester1 = 1
    Case "II"
    semester1 = 2
    Case "III"
    semester1 = 3
    Case "IV"
    semester1 = 4
    Case "V"
    semester1 = 5
    Case "VI"
    semester1 = 6
    End Select
    DataGrid1.ClearFields
    rs.Open "select Subjectcode,Subjectname,Theory_Practical from subjectcode as s where s.Degree='" & Degree & "' and s.Branch='" & course & "' and s.Year1='" & year1 & "' and s.Year2='" & year2 & "' and s.Semester='" & semester1 & "'  ", con, 1, 3
    Set DataGrid1.DataSource = rs
    End Sub

    Private Sub Command2_Click()
    examfee2.Hide
    examfee1.Show
    End Sub

    Private Sub Command4_Click()
    If rs!Theory_Practical = "theory" Then
    rs2.Open "select Theoryfee from Degreelevel", con, 1, 3
    Set DataGrid2.DataSource = rs2
    ElseIf rs!Theory_Practical = "practical" Then
    rs2.Open "select Practicalfee from Degreelevel", con, 1, 3
    Set DataGrid2.DataSource = rs2
    End If
    End Sub

    Private Sub Form_Load()
    Set con = New ADODB.Connection
    con.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=.\college.mdb;Persist Security Info=False"
    con.CursorLocation = adUseClient
    Set rs = New ADODB.Recordset
    End Sub

Fee table:
Heading(Year1,Year2,Theoryfee,Practicalfee)
values (2001,2003,440,320)

All other values like this only with different values !
subjectcode table :
Heading(Year1,Year2,Subjectcode,Subjectname,Theory_Practical)
values (2001,2003,RCCS10CS1,C programming, Theory)

A: You can use a query like so:
SELECT subjectcode.Year1, subjectcode.Year2,
       subjectcode.Subjectcode, subjectcode.Subjectname,
       subjectcode.Theory_Practical, q.fee
FROM subjectcode
INNER JOIN (
       SELECT fees.Year1, fees.Year2, "Theory" As FeeType,
              fees.Theoryfee As Fee
       FROM fees
       UNION ALL
       SELECT fees.Year1, fees.Year2, "Practical" As FeeType,
              fees.Practicalfee As Fee
       FROM fees)  AS q
ON (subjectcode.Theory_Practical = q.FeeType)
   AND (subjectcode.Year2 = q.Year2)
   AND (subjectcode.Year1 = q.Year1)

However, you would be much better off redesigning your fees table to match the data returned by the inner sql, that is, a different line for theory and practical fees:
Year1   Year2   FeeType     Fee
2001    2003    Theory      440
2001    2003    Practical   320


Q: 3 2560x1440 on Mac OS X without Mac Pro I am trying my very best to do this but I am failing to succeed... :/
1) I have a 2011 Mac Mini (1 1280x1024 monitor) (Dual core i5, 8GB RAM)
2) I have a windows PC (3 2560x1440 Korean monitors) (i5 2500K, 16GB RAM)
[b]I need to use MAC OS X 10.8 on 3 2560x1440 (I CAN'T buy a MAC PRO)[/b]. I need it as fast as possible (real time speed if possible).
In my understanding i can do this using:
A) VMWare (slow on single 1080 monitor, must be terrible slow on 2560x1440). Last option.
B) Hackintosh (my PC supports it but will i experience crashes etc?)
C) Remote control the mac (dual Gbit Ethernet on both PC and Mac. Communication speed is 250MB/s) (Team View, RealVNC and lots of other do not support virtual monitors at this resolution...)
A, B or C will work better? If C please help me, what software i need?

A: Not a full answer, but (B) Hackintosh will definitely be the fastest option - if you can get it to work.
There is a pay-for version of RealVNC as discussed here which has multi-monitor support, so option (C) is possible.
Lastly, if you can get the hardware acceleration of VMWare (or VirtualBox) to work, it should also be possible to get it working at decent speed.


Q: ExtJS - convert json to Model I have a json string that I need to map into a Model, I've been checking this json reader, Ext.data.reader.JsonView, but it seems that it only wokrs with a proxy, I need to pass a string (which contains the json) and map it to my model. Is that possible?
Thanks,
Angelo.

A: Take a look on the Ext.data.model's constructor.
http://docs.sencha.com/extjs/4.2.3/#!/api/Ext.data.Model-method-constructor
You can pass your data into it and it will map it to your model's fields. So you can do something like:
var model = new Ext.data.model(Ext.decode(<yourJsonString>));

Ext.data.model can be replaced with your model class.


Q: Django pagination giving error: Caught TypeError while rendering: 'Page' object is not iterable I am using django pagination, as told in documentation:
view part is :
def list(request):
job_list = Job.objects.all()
paginator = Paginator(job_list, 25) # Show 25 jobs per page

page = request.GET.get('page',1)
try:
    jobs = paginator.page(page)
except PageNotAnInteger:
    # If page is not an integer, deliver first page.
    jobs = paginator.page(1)
except EmptyPage:
    # If page is out of range (e.g. 9999), deliver last page of results.
    jobs = paginator.page(paginator.num_pages)

return render_to_response('jobs/list.html', {"jobs": jobs})

and template is:

  {% for job in jobs %}
{# Each "contact" is a Contact model object. #}
{{ job.title|upper }}

{% endfor %}

    {% if contacts.has_previous %}
        previous
    {% endif %}

        Page {{ contacts.number }} of {{ contacts.paginator.num_pages }}.

    {% if contacts.has_next %}
        next
    {% endif %}

But it gives the error saying:
In template d:\programming\django_projects\kaasib\templates\jobs\list.html, error at line 32
Caught TypeError while rendering: 'Page' object is not iterable

I am new in django and this error seems general but very strange. Because in loop there is some other variable, not job. So please tell if anyone have any idea about it.
thanks

A: The error should be clear - the variable you've called jobs actually contains a Page object from the paginator. Which is as it should be, as you assigned jobs to paginator.page(x). So obviously, it contains a Page.
The documentation shows what to do:
{% for job in jobs.object_list %}

etc.


Q: How to get the first and last value that match condition in Google Sheets? I have a table in this format:

I would like to get the first and last date (column A) that hasn't been invoiced (column E) so I can later concatenate: ="Invoice for items between " & FIRST_DATE & " and " & LAST_DATE
I've tried using VLOOKUP but it appears that "" isn't interpreted as an empty match.

A: I would think this would work.
=TEXT(MIN(FILTER(1*LEFT(A2:A;10);A2:A<>"";E2:E=""));"yyyy-mm-dd")

and
=TEXT(MAX(FILTER(1*LEFT(A2:A;10);A2:A<>"";E2:E=""));"yyyy-mm-dd")

Your timestamps are coming from a system other than GoogleSheets.  They need to be "forced" into numbers before they can be MIN()'d and MAX()'d.  That's what 1* LEFT(... , 10) does.
Then they need to get turned back into text before they're concatenated in a text string like your plan.  That's what TEXT(... ,"yyyy-mm-dd") does.


Q: Matplotlib drawing a line with a hint through a plot I have a pcolor in matplotlib where I would like to draw a horizontal line with a caption.
So in a way, as it is drawn on the following picture:

Is there a way to do that?


Q: Rails engine extending views, not overriding I am aware that I can override an applications view from within an engine by simply creating the same file within the engine and removing it from the application (eg: 'users/show.html.erb').
However, what I want is to be able to extend the applications view, not override.
Lets say I have a yield inside 'users/show.html.erb' of the main application:
yield :foo
What I want is for the engine to specify the same file 'users/show.html.erb' and to have a content_for block
content_for :foo {}
Thereby, injecting some template data from the engines view, into the applications view.
Obviously, the above won't work as once it has found the template file in the application, it won't look for one in the engine.
Is there a way to make this work?

A: There is no way to extend views that way in Rails. You can however, accomplish this by using partials. In your engine, write a partial view file users/_show.html.erb and then render it in your app's view:
# app/views/users/show

# will look for a partial called "_show.html.erb" in the engine's and app's view paths.
render partial: 'show'

It's just as easy as your suggestion.
This gem tries to implement partial extension of views, but it works similarly to what I just described: https://github.com/amatsuda/motorhead#partially-extending-views-in-the-main-app


Q: Emulate Excel AverageIFs with Pandas I am trying to emulate Excel's AVERAGEIFs function in Pandas on a date range, and so far have been unsuccessful.  I understand that I need to use apply and groupby, but I obviously don't have the syntax correct as I receive this error:
TypeError: can only concatenate list (not "Timedelta") to list

I am using test data at the moment while I try to figure out the syntax, and the data is below:

For each 'Avg' column I am trying to return the average quantity for the previous 180 days as grouped by 'A' and 'B'.  Therefore, I would expect the 'Avg' column in row 1 to be 1.5 ( (1+2)/2, while leaving out row 5 which is a match but is > 180 days prior).
Here is the code I have at present, which does not work:
import pandas as pd
#Importing the dataset
df = pd.read_excel('Test.xlsx', sheet_name='Sheet1')

df = pd.concat([df, pd.DataFrame(columns=['Avg Qty'])], axis=1)
df['Avg Qty'] = df.apply(df.groupby([(['Date'] <= (['Date']+pd.Timedelta(-1,
    unit='d')) >= (['Date']+pd.Timedelta(-180, unit='d'))), 'A', 'B']))['Qty'].mean()

print(df.head)

Any help would be greatly appreciated.

A: IIUC, I think you want something like this:
df['Avg Qty'] = (df.groupby([pd.Grouper(freq='180D', key='Date'),'A','B'])['Qty']
                   .transform('mean'))

Output:
        Date       A         B  Qty  Cost  Avg Qty
0 2017-12-11  Cancer      Golf    1   100      1.5
1 2017-11-11  Cancer      Golf    2   200      1.5
2 2017-11-11  Cardio      Golf    2   300      2.0
3 2017-10-11  Cardio  Baseball    3   600      3.0
4 2017-04-11  Cancer      Golf    4   150      4.0
5 2016-01-01  Cancer  Football    5   200      5.0

Edit:
df = df.set_index('Date')
df.groupby(['A','B']).apply(lambda x: x.sort_index().rolling('180D')['Qty'].mean()).reset_index()\
   .merge(df.reset_index(), on=['Date','A','B'], suffixes=('_avg',''))

Output:
        A         B       Date  Qty_avg  Qty  Cost
0  Cancer  Football 2016-01-01      5.0    5   200
1  Cancer      Golf 2017-04-11      4.0    4   150
2  Cancer      Golf 2017-11-11      2.0    2   200
3  Cancer      Golf 2017-12-11      1.5    1   100
4  Cardio  Baseball 2017-10-11      3.0    3   600
5  Cardio      Golf 2017-11-11      2.0    2   300


Q: Laravel - additional condition in a join using DB::raw() query I want to add an "OR" conditional to the DB::raw query join
I have this query:
$billings = DB::table("billings")
    ->select("billings.plan", "billings.email",DB::raw("COUNT(billings.plan) as total_plans") ,DB::raw("SUM(billings.amount) as total_amount"))
    ->join("users","users.email","=","billings.email")
    ->groupBy("billings.plan")
    ->orderByRaw('billings.plan ASC');

In it I have:
->join("users","users.email","=","billings.email")

I want to use an "OR" condition:
->join("users","users.email","=","billings.email")

or
->join("users","users.phone","=","billings.phone")

A: try below:
$billings = DB::table("billings")
    ->select("billings.plan", "billings.email", DB::raw("COUNT(billings.plan) as total_plans"), DB::raw("SUM(billings.amount) as total_amount"))
    ->join("users", function ($join) {
        $join->on("users.email", "=", "billings.email")
            ->orOn("users.phone", "=", "billings.phone")
    })
    ->groupBy("billings.plan")
    ->orderByRaw('billings.plan ASC');

A: $billings = DB::table("billings")
           ->select("billings.plan", "billings.email",DB::raw("COUNT(billings.plan) as total_plans") ,DB::raw("SUM(billings.amount) as total_amount"))
            ->join("users",function($join){
                  $join->on("users.email","=","billings.email");
                  $join->orOn("users.phone","=","billings.phone");
             })
            ->groupBy("billings.plan")
            ->orderByRaw('billings.plan ASC');

A: I think for this u need to use advanced join clause.
Something like this:-
DB::table('users')
    ->join('contacts', function ($join) {
        $join->on('users.id', '=', 'contacts.user_id')->orOn(...);
    })
    ->get();


Q: iTextSharp pdf Listbox form control looses right alignment I have a pdf form, and I am using pdfStamper to manipulate the values of listbox.
form.SetListOption("fieldname",String[]{"one","two","three"});
form.SetListSelection("fieldname",String[]{"","",""});

The listbox alignment is set to "right".  If I use a PDF editor and change the values myself, it displays correctly.
If I run it through iTextSharp, the listbox is left aligned.
Is this a bug, or do I need to do something else?


Q: How to distinguish the WM_LBUTTONUP message in a single-click event and a double-click event I want to do something when I receive the WM_LBUTTONUP message in the single-click event, but the WM_LBUTTONUP message in the double-click event should not do these things. How can I ignore it in the function OnLButtonUp() that processes the message?

A: Your computer doesn't have clairvoyant super powers and thus cannot reliably predict whether any observed WM_LBUTTONUP is or isn't followed up by any WM_LBUTTONDBLCLK message.
What you could do is start a timer in your WM_LBUTTONDOWN message handler with a timeout of GetDoubleClickTime, and build up a complex state machine that moves between states on WM_TIMER, WM_LBUTTONUP, and WM_LBUTTONDBLCLK messages.
That's doable, but a lot more complex than you'd expect. Plus, it will necessarily introduce a delay between the user releasing the left mouse button and the action they intended to trigger starting.
What you should be doing instead is solving your UX issue. If you make your single click action unrelated to your double click action, then that is the bug that needs to be addressed. Logical consequences of the way Windows converts single-clicks into double-clicks goes into much more detail, and arrives at the same conclusion: Don't, just don't do it.


Q: Finding all ordered quadruples $(a, b, c, d)$ of primes Find all ordered quadruples $(a, b, c, d)$ of primes such that
\begin{align*}
13a^2 + b^2 + 13c^2 &= 2b(3a + 2c) \\
a^3 −(bc)^3 &= (b+c−a)d+2021.
\end{align*}

A quick WolframAlpha search yielded that the answer to this was no pairs, but I wasn't quite sure how to derive it.

A: The first equation, considered as quadratic equation in $c$, has no real solution in $c$, except for the case $3b=13a$.
Then we have $a=3$ and $b=13$, so that the first equation gives $c=2$. This indeed solves the first equation. However, then the second equation is $6d + 9785=0$, so that $d$ is not an integer. Contradiction.


Q: Android Wear emulator goes into Ambient Mode automatically I've been absent for some times from WearOS development. Now I am back and I have one annoying issue with the latest emulator - it goes automatically in Ambient Mode after few seconds. Not just my app, but the OS itself.
I Checked into the settings, tried clicking on the top of the window, but no luck - is there a settings for this or I should file a bug?

A: *

*Set the emulator to be charging.

*Make sure Settings - Developer options - Stay awake when charging is enabled.(default)

PS: Click Settings - System - About - Build number quickly to enable Developer options.


Q: Prevent node.js from reading node_modules besides immediate folder Say I have this situation:
node_modules/
muh_project/
  node_modules/
  index.js

say I do this:
cd muh_project && node index.js

How can I prevent the node.js runtime from reading node_modules anywhere but the immediate node_modules folder? By default, Node.js will walk up the filesystem looking for node_modules until it reaches $HOME. But for a certain use case (for testing) I want to prevent that behavior.
The only thing I can think of is something like this:
mv_all_node_modules_dirs
node muh_project
mv_all_node_modules_dirs_back_to_original_name

The renaming solution seems really bad, is there another way?
Update: An additional constraint - I am running someone else's program with bash, so whatever I change has to be external to their program, either an env variable or changing directory names, or whatever. Modifying require() or whatnot won't work so good.
A newer idea - I could change permissions, so that the program doesn't have permissions to any files below the current dir? Last time I checked *nix can't really do this (which is super lame).
Here is my rename script, so you get the idea:
'use strict'

const fs = require('fs');
const path = require('path');
let current = path.dirname(process.cwd());
const home = process.env.HOME;

let renameThisDir = 'node_modules';
let renameTo = 'r2g_nodemodules'

if(process.argv[2] === 'undo'){
    // swap the variables
   [renameTo, renameThisDir] = [renameThisDir, renameTo];
}

while (current.length >= home.length) {

    let nm = path.resolve(current, renameThisDir)
    let renamed = path.resolve(current, renameTo)

    fs.stat(nm, (err, stats) => {

        if (!(stats && stats.isDirectory())) {
            return;
        }

        fs.rename(nm, renamed, err => {
            err && console.error(err.message);
        });
    });

    current = path.join(current, '..');
}


Q: Laravel 7 change where file uploads to I have a file upload form in on of my blade files.
However when I upload the file I see its saving the file to /storage//Applications/MAMP/tmp/php/phpIVfP2L.mp4 how do I set this upload to be saved to a specific location like I want them saved in the Laravel public folder that is in the Laravel root directory so the path would be /public/trainingvideos
Below is my controller code where my file upload code is
public function addtraining(Request $req) {
    //Save to a mysql database
    //print_r($req->input());
    $pwdata = new AddTraining;
    $pwdata->userid = $req->userid;
    $pwdata->video_title = $req->trainingtitle;
    $pwdata->video_description = $req->trainingdesc;
    $pwdata->video_url = $req->trainingvideo;

    if($req->hasFile('trainingvideo')) {
        //  Let's do everything here
        if($req->file('trainingvideo')->isValid()) {
            //
            $validated = $req->validate([
                'trainingvideo' => 'mimes:mp4,mov|max:10000',
            ]);
            $extension = $req->trainingvideo->extension();
            $req->trainingvideo->storeAs('public_path()/public/trainingvideos', $req->trainingvideo.".".$extension);
            $url = Storage::url($req->trainingvideo.".".$extension);
            $pwdata->video_url = $url;
            //Session::flash('success', "Success!");

        }
    }
    //abort(500, 'Could not upload video :(');
    $pwdata->save();

A: The /tmp directory is where files are temporarily stored when uploaded.
In your controller you need to go about actually storing that file, the docs cover this in depth; https://laravel.com/docs/7.x/requests#storing-uploaded-files
It's worth mentioning that if you leave the files in your tmp directory, they will be garbage collected at some point and so this is not a safe location to store files.


Q: The formula for a perhaps basic identity (move from stackexchange) The following question is moved from math stackexchange. It seems that this is not a popular question, but I really want to know the answer so I moved it to here. The question reads as follows.
We know the expansion of the following product
$\displaystyle\prod_{k=1}^n(1+x+y_k)$
can be expressed by the formula
$\displaystyle\sum_{k=0}^n(1+x)^{n-k}e_k(y_1, \ldots, y_n),$
where the $e_k$'s are the elementary symmetric functions,
$e_k (x_1 , \ldots , x_n )=\displaystyle\sum_{1\le  j_1 < j_2 < \dots < j_k \le n} x_{j_1} \dotsm x_{j_k}.$
My question is whether we have a nice formula for the expansion of the following product
$\displaystyle\prod_{1\leq k\leq n, 1\leq\ell\leq m}(1+x_\ell+y_k).$
Reference for the nice formula of the above expression will be highly appreciated. (It seems to me that it is related to generating functions, but I have no background in combinatorics.)
Thanks!~

A: I guess the first product is expanded as
$$
\prod_{k=1}^n(1+x+y_k)=(1+x)^n\prod_k(1+y_k(1+x)^{-1})=\sum_{k\geq 0}e_k(y_1,\ldots,y_n)(1+x)^{-k+n}.$$
For the other products you can write
$$
\prod_{j=1}^m\prod_{i=1}^n(1+y_it_j)=\sum_\lambda e_\lambda(y_1,\ldots,y_n)m_\lambda(t_1,\ldots,t_m)=\sum_\lambda e_\lambda(\mathbf{y})m_\lambda(\mathbf{t})$$
where the sum is over $\lambda$ with $\ell(\lambda)\leq m$ and $m_\lambda$ is the monomial symmetric function. It seems that the product you are interested in looks something like
$$
\prod_{j=1}^m\left(\sum_k e_k(y)(1+x_j)^{n-k}\right)=\sum_\lambda e_\lambda(\mathbf{y})m_{\lambda-(n^m)}((\mathbf{1-x})^{-1})
$$
In this formula, $\lambda-(n^m)=(\lambda_1-n,\ldots,\lambda_m-n)$ and you take the obvious definition of $m_\mu$ where $\mu$ is a partition with parts not necessarily positive.
I'm not sure if this is helpful, since I don't know what you want to do with it. Anyway, this is related to a bilinear form on the ring of symmetric functions given by
$$\langle u,v\rangle = (u,\omega(v))$$
where $(\cdot,\cdot)$ is the standard bilinear form having Schur functions as an orthonormal basis and $\omega$ is the automorphism switching the elementary and homogeneous symmetric functions. In particular, I believe this product also can be expanded as
$$\sum_{\lambda} s_{\lambda^t}(\mathbf{y})s_{\lambda-(n^m)}((\mathbf{1-x})^{-1}).$$


Q: Only allow ajax request to fire once (like button) I have a button that on click adds 1 to a table value in my database (i.e a like button).
When the user clicks the button:
  var button_id = $(e.target).closest('div').attr('id');
  var id = button_id.substring(12);
  $.ajax({
    method: 'POST',
    url: 'update_like.php',
    data: {id:id},
    success: function(){
     //
    },
    error: function(){
      //
    }
  })

update_like.php
$id = mysqli_real_escape_string($conn,$_POST['id']);

if (!empty($_POST)){
    mysqli_query($conn,"UPDATE posts SET likes=likes+1 WHERE id='$id'");
}

Q: What way can it check if they already liked it, so that they can only like the post once?
I just thought of something like this:
Have a column called "likers" or something similar, with a long list of user IDs who've liked the post.
i.e.
5 217 16 31893 ... <-- user IDs
In update_like.php, check if the user who's logged in's ID can be found within that string. Something like:
$id = mysqli_real_escape_string($conn,$_POST['id']);

$result = mysqli_query($conn,"SELECT likers FROM posts WHERE id='$id'");
$likers = mysqli_fetch_assoc($result);
$user_id = $_SESSION['id']; // user ID

if (!empty($_POST)){
    if (!(preg_match("/\b$user_id\b/", $likers))){
        mysqli_query($conn,"UPDATE posts SET likes=likes+1 WHERE id='$id'");
    }
}

Is this feasible?

A: You can try this:
var button_id = $(e.target).closest('div').attr('id');
var id = button_id.substring(12);
var idArray = [];
if (idArray.indexOf(id) === -1) {
 ajaxCall = $.ajax({
    method: 'POST',
    url: 'update_like.php',
    data: {id:id},
    success: function(){
     //
      idArray.push(id);
    },
    error: function(){
      //
    }
  });
}

On server side you can try this:
Assuming ID to be a comma separated list.
UPDATE posts
SET likes = likes+1
WHERE id = '$id'
AND FIND_IN_SET('$id', listofuserid) = 0


Q: Awk/Sed Solution for English/Chinese Text? I have a text file. There are hundreds of lines. Each line is either in English or in Chinese characters, but not both (there are a few exceptions but perhaps less than <10, so these are discoverable and manageable). A single line may contain multiple sentences. What I would like to end up with is two files; one in English; the other in Chinese.
The lines tend to alternate languages, but not always. Sometimes there might be two lines in English, followed by one line in Chinese.
Is there a way to use Sed or Awk to divide the languages into two different text files?

A: This one-liner might help:
awk '/[^\x00-\x7f]/{print >"cn.txt";next}{print > "en.txt"}' file

It will generate two files cn.txt and en.txt. It checks if the line contains at least one non-ascii character, if found one, the line would be considered as Chinese line.
Little test:
kent$  cat f
this is line1 in english
你好
this is line2 in english
你好你好
this is line3 in english
this is line4 in english
你好你好你好

kent$  awk '/[^\x00-\x7f]/{print >"cn.txt";next}{print > "en.txt"}' f

kent$  head *.txt
==> cn.txt <==
你好
你好你好
你好你好你好

==> en.txt <==
this is line1 in english
this is line2 in english
this is line3 in english
this is line4 in english


Q: How to use allow: options with eslintrc.js I am having the following eslintrc.js:
module.exports = {
  extends: ['airbnb-typescript/base'],
  parserOptions: {
    project: './tsconfig.json',
    sourceType: 'module',
  },
  ignorePatterns: ['*.js'],
  rules: {
    'no-underscore-dangle': 0,
    ...
  }
};

And I'd like to include some exceptions with allow: [ /** */ ]. But each time when I am adding this as a key: value property in my file, ESLint returns me an error with the following text: unable to use allow on top level. So the question is, how to achieve such results, with allow?
Long story short, I am unable to use my set of rules with MongoDB _id naming, so I have ESLint just to ignore only _id in variable naming, instead of disabling the naming-convention rule itself.
Is there any way to solve this problem?

A: It works for me:
"no-underscore-dangle": ["error", { allow: ["_id"] }]

If you are using the @typescript-eslint/naming-convention rule, you may also need to add this:
"@typescript-eslint/naming-convention": [
  "error",
  {
    selector: ["variable"],
    format: ["strictCamelCase", "PascalCase", "UPPER_CASE"],
    filter: {
      regex: "^_id$",
      match: false,
    },
  },
],


Q: Workarounds for the forward-declared class enumeration problem? I am maintaining a large code base and am using a combination of forward declarations and the pImpl idiom to keep compile times down and reduce dependencies (and it works really well,)
The problem I have is with classes that contain public enumerations.  These enumerations cannot be forward declared so I am left with no option but to include the class header.  For example:
// Foo.h

class Foo
{
public:
  enum Type
  {
    TYPE_A,
    TYPE_B,
  };
  ...
};

// Bar.h

#include "Foo.h" // For Foo::Type

class Bar
{
public:
  void someFunction(Foo::Type type);
  ...
};

So, I'm looking for ways to avoid this and can only think of the following:
Move the class enumerations to a separate 'types' namespace
// FooTypes.h

namespace FooTypes
{
  enum Type
  {
    TYPE_A,
    TYPE_B,
  };
}

// Bar.h

#include "FooTypes.h"

class Bar
{
public:
  void someFunction(FooTypes::Type type);
  ...
};

Use int instead of the enumeration
// Bar.h

class Bar
{
public:
  void someFunction(int type);
  ...
};

What have I missed?  How do other people get around this limitation (not being able to forward declare enumerations.)

A: Put the enumeration in the class containing the PIMPL.

A: Put the enumeration into its own type:
struct FooEnum
{
  enum Type
  {
    TYPE_A,
    TYPE_B,
  };
};

Then Foo and Bar can both access FooEnum::Type and Bar.h doesn't need to include Foo.h.

A: I'd argue that enums are a bad idea to start with, but in general for constants/the many things like constants in C++ none of which are quite constants and all of which have issues. I like to put it into a struct then have the classes using it inherit from the struct.
I'd also argue that the pimpl idiom is bad. Actually I am sure it's a poor way to do things. It's something that works but is awkward and a bit silly. It's also easy to avoid, and the only reason it comes about is due to people using yet other bad design choices.
Usually someone just tacks on OOP stuff to a class they designed to be concrete. Then you get the mixed inheritance case and the plethora of issues it causes such as super slow compile time. Instead, consider pure virtual base classes, then writing your libs to that to avoid templates and avoid the forward declaration problem. Not for everything, but definitely for the cases where you are generating code for lots of classes.


Q: How to install turtlegraphics in python I'm trying my hands on Turtle but I can't get the module installed.
I have searched a lot and people seems to imply that it is included in the Python
standard library with Tkinter but this doesn't seem to be the case for me.
when I do:
import Tkinter

everything seems ok. But when I try
t1 = Turtle()

I get the error
NameError: name 'Turtle' is not defined

As per the tutorial I'm suppose to import like this:
from turtlegraphics import Turtle

But no matter what I've tried I cant find how I can get the library installed.

A: You need to import it from the turtle module.
from turtle import Turtle
t1 = Turtle()
t1.forward(100)

A: Try to check within the library files whether there is a file called turtle in it . I had the same problem and i found the library file and opened it. So check it and see if it will fix your problem. Most probably turtle library file will be in Lib folder.

A: Nothing here worked for me. This is what I did: I checked what configuration I had (in the upper right hand corner). I changed it so it was the python version that ran through the project and not just plain python. Then you also have to go to script path (also a setting in the configuation) and set it to the .py that you are working on :)

A: hey all of you guys just check importing that module ,you dont get any errors its already in standard libraray


Q: FireFox SDK Addon - "Detach content script" on disable/unload? I am having some issues trying to figure out how to handle the detach event when the addon is disabled and uninstalled.
In main.js and my content script, I am capturing the "detach" event which fires in both cases, but the content script is not actually removed from the tab. As a result, my listeners and observers continue to fire after the addon is disabled.
My understanding is that destroy() is fired and that should remove the content script, but if I look in the debugger in dev tools, the script is still listed after I disable.
I can remove the listeners and the observers when handling the detach event, but my understanding was that the content script is removed during the detach so the listeners, should be removed?
I also thought to just remove the content script from the DOM, but the content script is not listed if you do something like:
var scripts = document.getElementsByTagName("script");

for (i=0;i<scripts.length;i++){
    if(scripts[i].src == "content-script.js"){
        console.log("content script found");
    }
}

When you do the detach do you need to need to make another call to something to let it know you finished your cleanup? Anytime I capture the detach event in the main.js or my content script, it hangs when rung using cfx? Is this why its not completing the removal?

A:
My understanding is that destroy() is fired and that should remove the
  content script, but if I look in the debugger in dev tools, the script
  is still listed after I disable.
I can remove the listeners and the observers when handling the detach
  event, but my understanding was that the content script is removed
  during the detach so the listeners, should be removed?

This is a very good question.
The detach event is event is meant to let you know it's time to clean your content script.  Event listeners need to be removed, anything added to the window scope should also be removed,
You don't need to let the main.js script know when you are done.


Q: SBT maven local repository is not searched I want to load some library from local maven repostory. I have configured .sbt/0.13/plugins/plugins.sbt:
resolvers += Resolver.sonatypeRepo("snapshots")
resolvers += Resolver.mavenLocal

addSbtPlugin("org.ensime" % "ensime-sbt" % "0.1.5-SNAPSHOT")

In my project I have set this lines in build.sbt:
name := "hello"
version := "1.0"
scalaVersion := "2.10.4"
libraryDependencies += "opencv" % "opencv" % "2.4.9"
libraryDependencies += "opencv" % "opencv-native" % "2.4.9"

And I can't figure out why it is not working. After running sbt compile in project it logs this:
[info] Resolving opencv#opencv;2.4.9 ...
[info] Resolving opencv#opencv;2.4.9 ...
[warn]  module not found: opencv#opencv;2.4.9

[warn] ==== local: tried
[warn]   C:\Users\Una\.ivy2\local\opencv\opencv\2.4.9\ivys\ivy.xml

[warn] ==== public: tried
[warn]   https://repo1.maven.org/maven2/opencv/opencv/2.4.9/opencv-2.4.9.pom

[info] Resolving opencv#opencv-native;2.4.9 ...
[info] Resolving opencv#opencv-native;2.4.9 ...
[warn]  module not found: opencv#opencv-native;2.4.9

[warn] ==== local: tried
[warn]   C:\Users\Una\.ivy2\local\opencv\opencv-native\2.4.9\ivys\ivy.xml

[warn] ==== public: tried
[warn]   https://repo1.maven.org/maven2/opencv/opencv-native/2.4.9/opencv-native
-2.4.9.pom

[info] Resolving org.scala-lang#scala-compiler;2.10.4 ...
[info] Resolving org.scala-lang#scala-reflect;2.10.4 ...
[info] Resolving org.scala-lang#jline;2.10.4 ...
[info] Resolving org.fusesource.jansi#jansi;1.4 ...
[warn]  ::::::::::::::::::::::::::::::::::::::::::::::
[warn]  ::          UNRESOLVED DEPENDENCIES         ::
[warn]  ::::::::::::::::::::::::::::::::::::::::::::::
[warn]  :: opencv#opencv;2.4.9: not found
[warn]  :: opencv#opencv-native;2.4.9: not found
[warn]  ::::::::::::::::::::::::::::::::::::::::::::::

Why it could be not looking in .m2/repository as said in plugins.sbt?
I have no experience with scala and sbt.

A: Move maven local resolver out of plugins.sbt and into build.sbt. If you want that listed plugin to come from the snapshot resolver listed leave that in plugins.sbt otherwise remove that one as well and move to build.sbt.


Q: how to convert pandas str.split call to to dask I have a dask data frame where the index is a string which looks like this:
12/09/2016 00:00;32.0046;-106.259
12/09/2016 00:00;32.0201;-108.838
12/09/2016 00:00;32.0224;-106.004

(its basically a string encoding the datetime;latitude;longitude of the row)
I'd like to split that while still in the dask context to individual columns representing each of the fields.
I can do that with a pandas dataframe as:
df['date'], df['Lat'], df['Lon'] = df.index.str.split(';', 2).str

But that doesn't work in dask for several of the attempts I've tried.  If I directly substitute the df for a dask df I get the error:
'Index' object has no attribute 'str'

If I use the column name instead of index as:
forecastDf['date'], forecastDf['Lat'], forecastDf['Lon'] = forecastDf['dateLocation'].str.split(';', 2).str

I get the error:
TypeError: 'StringAccessor' object is not iterable

Here is an runnable example of this working in Pandas
import pandas as pd
df = pd.DataFrame()
df['dateLocation'] = ['12/09/2016 00:00;32.0046;-106.259','12/09/2016   00:00;32.0201;-108.838','12/09/2016 00:00;32.0224;-106.004']
df = df.set_index('dateLocation')
df['date'], df['Lat'], df['Lon'] = df.index.str.split(';', 2).str
df.head()

Here is the error I get if I directly convert that to dask
import dask.dataframe as dd
dd = dd.from_pandas(df, npartitions=1)
dd['date'], dd['Lat'], dd['Lon'] = dd.index.str.split(';', 2).str
>>TypeError: 'StringAccessor' object is not iterable

A: forecastDf['date'] = forecastDf['dateLocation'].str.partition(';')[0]
forecastDf['Lat'] = forecastDf['dateLocation'].str.partition(';')[2]
forecastDf['Lon'] = forecastDf['dateLocation'].str.partition(';')[4]

Let me know if this works for you!

A: First make sure the column is string dtype
forecastDD['dateLocation'] = forecastDD['dateLocation'].astype('str')

Then you can use this to split in dask
splitColumns = client.persist(forecastDD['dateLocation'].str.split(';',2))

You can then index the columns in the new dataframe splitColumns and add them back to the original data frame.
forecastDD = forecastDD.assign(Lat=splitColumns.apply(lambda x: x[0], meta=('Lat', 'f8')), Lon=splitColumns.apply(lambda x: x[1], meta=('Lat', 'f8')), date=splitColumns.apply(lambda x: x[2], meta=('Lat', np.dtype(str))))

Unfortunately I couldn't figure out how to do it without calling compute and creating the temp dataframe.


Q: Random variable not changing in "for" loop in windows batch file I'm trying to print out a Random number multiple times but in the for loop I use, it doesn't reset the variable. Here's my code.
@echo off

for %%i in (*.txt) do (

set checker=%Random%
echo %checker%
echo %%i% >> backupF

)

echo Complete

There are 5 text files and so I want it to print 5 different random numbers but it just prints the same random number 5 times. Any help would be greatly appreciated. Thanks!

A: I'm not sure how you've been able to have it print even one random number. In your case, %checker% should evaluate to an empty string, unless you run your script more than once from the same cmd session.
Basically, the reason your script doesn't work as intended is because the variables in the loop body are parsed and evaluated before the loop executes. When the body executes, the vars have already been evaluated and the same values are used in all iterations.
What you need, therefore, is a delayed evaluation, otherwise called delayed expansion. You need first to enable it, then use a special syntax for it.
Here's your script modified so as to use the delayed expansion:
@echo off

setlocal EnableDelayedExpansion

for %%i in (*.txt) do (

set checker=!Random!
echo !checker!
echo %%i% >> backupF

)

endlocal

echo Complete

As you can see, setlocal EnableDelayedExpansion enables special processing for the delayed expansion syntax, which is !s around the variable names instead of %s.
You can still use immediate expansion (using %) where it can work correctly (basically, outside the bracketed command blocks).

A: Try by calling a method.
@echo off
pause

for %%i in (*.txt) do (
    call :makeRandom %%i
)

echo Complete
pause

:makeRandom
    set /a y = %random%
    echo %y%
    echo %~1 >> backupF

A: on my system I have to write
set checker=Random

instead of
set checker=!Random!


Q: Issue with NSNumber -initWithDouble and resulting values I'm using NSNumber to store various values, but sometimes run into issues when doing calculations with the values and initializing new NSNumber objects for the results. I've figured out how to overcome it, but I couldn't for the life of me explain why it works and since my grasp on numerical values in computer environments (doubles, floats, etc) is weak I'd like to ask this question to learn. :-)
First example is when I am converting between different units of measurement, in this particular case it's between mmol/L and mg/dl. Getting an NSNumber which represents a mmol/L value, I extract its double value and perform the calculation. Then I create a new NSNumber with -initWithDouble and return the result.
However, I get odd quirks. If the mmol/L value is 10.0, the corresponding mg/dl value is 180.0 (the rate, obviously, is simply 18). But when I later need to let the user select a new value in a picker view and use the NSNumber -intValue to get the integer digits of the current value (using my own extension for getting the fractional digits), the int is 179! I've checked all the intermediate double values during calculation as well as the new NSNumber's double value and all is fine (180.00000 is the result). Interestingly, this doesn't happen for all values, just some (10.0 being one real example).
The second example is when I retrieve double values from an Sqlite3 database and store them in NSNumbers. Again, most values work fine, but occasionally I get weird stuff back. For instance, if I save 6.7 in the database (checking when it is saved that that is in fact the value), what my NSNumber will show after retrieval is 6.699999. (I can't actually remember at the moment of writing if that's what's in the database as well, but I think it is - I can check later.)
Both of these instances can be circumvented by using an intermediate float value and NSNumber initWithFloat instead of initWithDouble. So in my conversion, for example, I just do a float resultAsFloat = resultAsDouble and use initWithFloat for the new NSNumber.
Apologies for the long-winded question and if it's just my own knowledge about working with numerical values that is lacking, but I would really appreciate if someone could explain this to me!
Thanks,
Anders
* EDIT 1 *
Code for the unit conversion example:
-(NSNumber *)convertNumber:(NSNumber *)aNumber withUnit:(FCUnit *)aUnit {

// if origin unit and target unit are the same, return original number
if ([aUnit.uid isEqualToString:self.target.uid])
    return aNumber;

// determine if origin unit and target unit are comparable
if (aUnit.quantity != self.target.quantity)
    return nil;

// if so, convert the number...

// get bases
double originBase;
double targetBase;
if (aUnit.metre != nil) {

    originBase = [aUnit.metre doubleValue];
    targetBase = [self.target.metre doubleValue];

} else if (aUnit.kilogram != nil) {

    originBase = [aUnit.kilogram doubleValue];
    targetBase = [self.target.kilogram doubleValue];

} else if (aUnit.second != nil) {

    originBase = [aUnit.second doubleValue];
    targetBase = [self.target.second doubleValue];

} else if (aUnit.quantity == FCUnitQuantityGlucose) {

    // special case for glucose

    if ([aUnit.uid isEqualToString:FCKeyUIDGlucoseMillimolesPerLitre]) { // mmol/L -> mg/dl

        originBase = 1;
        targetBase = 0.0555555555555556; // since 1 / 0.0555555555555556 = 18

    } else if ([aUnit.uid isEqualToString:FCKeyUIDGlucoseMilligramsPerDecilitre]) { // mg/dl -> mmol/L

        originBase = 0.0555555555555556;
        targetBase = 1;
    }
}

// find conversion rate
double rate = originBase / targetBase;

// convert the value
double convert = [aNumber doubleValue] * rate;

// TMP FIX: this fixes an issue where the intValue of convertedNumber would be one less
// than it should be if the number was created with a double instead of a float. I have
// no clue as to why...
float convertAsFloat = convert;

// create new number object and return it
NSNumber *convertedNumber = [[NSNumber alloc] initWithFloat:convertAsFloat];
[convertedNumber autorelease];

return convertedNumber;
}

A: Try using NSDecimalNumber. There's a good tutorial here:
http://www.cimgf.com/2008/04/23/cocoa-tutorial-dont-be-lazy-with-nsdecimalnumber-like-me/

A: If I'm not wrong and if I well remember the appropriate course at college i think it's a matter of conversion from reality (where you have infinite values) to virtual (where you have finite values even if you have a lot): so you can't actually represent ALL the numbers. You also have to face with operations you're making: multiplications and divisions generate a lot of this troubles, because you'll have a lot of decimal numbers and, in my opinion, C-Based languages are not the best around to manage this kind of matter.
Hoping this will point you to a better source of information :).


Q: Creating soql query using getDescribe I currently have a function that creates a soql query with all queryable fields on a sobject
Map<String, Schema.SobjectField> fields = newObj.getSObjectType().getDescribe().fields.getMap();

for (String s : fields.keySet()) {

    Schema.Describefieldresult dfr = fields.get(s).getDescribe();
    if (dfr.isAccessible()) {
        accessibleFields.add(s);
    }
}

String query = 'SELECT '
             + String.join(new List<String>(accessibleFields), ', ')
             + ' FROM ' + objectName;

Just recently I've been getting this error when querying Account
System.QueryException: No such column 'billinglongitude' on entity 'Account'. If you are attempting to use a custom field, be sure to append the '__c' after the custom field name. Please reference your WSDL or the describe call for the appropriate names.

a quick google search shows that this field is a pilot standard field.
Is there a workaround for this that doesn't involve hardcoding which fields to ignore?
Update:
The resolution from the salesforce case is to update the API version to the latest one.
I was using v27 and at the time of this post, the latest is v29
This also means I will periodically update the api version.

A: This type of bug has raised itself before with Apex Describe and pilot features, I've not been able to find a workaround then either. You could argue that in some way all schema features are technically enabled through an Apex Describe, but then i would expect something like isAccessible to help us detect those that have not been switched on, as you have attempted. I would recommend you raise a case and in the meantime regrettably have to concede to whitelisting it in your code.


Q: NSNotifications from web Is it possible create NSNotifications in app and then from any form (apple.com) send push notifications to apps users? How can I do it?

A: To push notification to users, you need a your backend environment with your certificates.
You also have to receive the user device token needed to send the push notification.
Here there is a complete tutorial to make all the necessary for push notifications: http://www.raywenderlich.com/32960/apple-push-notification-services-in-ios-6-tutorial-part-1
NSNotification is another thing and is local..in your app. You can use that to generate notification in your app at certain time or when a certain event happen.


Q: Google analytics: dataLayer.push not working with array of variables? I wonder why gtag.js doesn't work when push to dataLayer array of variables instead of 'arguments'? Here is some code example:
window.dataLayer = window.dataLayer || []

function gtag(first: any, second: any) {
    window.dataLayer.push([first, second])
}

gtag('js', new Date())
gtag('config', trackingCode)

This only works when I replace '[first, second]' with 'arguments'

A: We don't know what you're trying to achieve by overwriting the gtag function so we can't answer the specific question as to what "works" and what doesn't.
What can be said: arguments is an Object and GTM expects an object from dataLayer.push, hence why this follows the intended design (whereas [first, second] is an Array and thus does not).
Note that the push call in itself "works":

However you won't be able to read that data via GTM which as explained above expects .push to pass Objects.
If you want to use the dataLayer in a compeltely free way, you can use the GTM dataLayer helper:
https://github.com/google/data-layer-helper
This does support the array syntax via Meta commands:
dataLayer.push(['abc.push', 4, 5, 6]);

However GTM by default doesn't support reading this data (once again GTM expects an Object so it can extract values based on the object properties), so to read that data via GTM you would need to use the dataLayer helper within GTM tags and variables.

A: So, at the end, this version of the code works fine for me, without linter errors:
window.dataLayer = window.dataLayer || []

function gtag(..._args: unknown[]) {
    window.dataLayer.push(arguments)
}

gtag('js', new Date())
gtag('config', trackingCode)


Q: How do i convert chr to ord? - Python in my python program i generate a list of numbers which looks like this:
gen1=(random.sample(range(33,126), 8))
            conv=(gen1[0:])

then that list is converted to chr like this:
chr="".join([chr(i) for i in conv])

the printed result for example would look like this:
`&+hs,DY

Now my question is, how do i convert it back to how it was in 'conv' later on in my program, the user enters the generated key and my program need to reverse engineer it back to calculate something, i tried this:
InPut=input("Please enter the key you used to encrypt the above text: ")
        ord_key="".join([ord for d in InPut])

but that doesnt work if there is numbers in the key that was generated earlier
please help me

A: You are not calling ord properly, this should do:
InPut=input("Please enter the key you used to encrypt the above text: ")
ord_key="".join(map(str,[ord(d) for d in InPut]))

if you want to reverse the stringfied '&+hs,DY just map chr to it:
reversed = map(chr, "`&+hs,DY")

If you are using python 3.x transform it to a list:
reversed = list(map(chr, "`&+hs,DY"))


Q: Move first column in file to the last column I am trying to move the first column of a file to be the last column in the file. This is what i have
awk -F ',' '{first = $1; $1=""; OFS = FS; print $0, first}' file.txt

This works if the file has only one row. If the file has multiple rows, it doesn't do nothing. The file is with carriage return and line feed (CRLF).

A: With GNU awk for multi-char RS:
$ printf 'foo,bar,etc\r\n' |
awk 'BEGIN{RS=ORS="\r\n"; FS=OFS=","} {$(NF+1)=$1; sub("[^"FS"]*"FS,"")} 1'
bar,etc,foo

or with any awk:
$ printf 'foo,bar,etc\r\n' |
awk 'BEGIN{ORS="\r\n"; FS=OFS=","} {sub(/\r$/,""); $(NF+1)=$1; sub("[^"FS"]*"FS,"")} 1'
bar,etc,foo

A: You can delete the spurious CR character before filtering and add it again later:
<file.txt tr -d \\015 | awk -F ',' '{for (field=2; field <=NF; field++) { printf "%s", $field FS } print $1}' | sed 's/$/\o015/' > file-new.txt

For example:
# cat | sed 's/$/\o015/' > test.txt
1,2,3,4,5,6,7
a,b,c,d,e,f,g,h
A,B,C,D
0

Ctrl+D
# <test.txt tr -d \\015 | awk -F ',' '{for (field=2; field <=NF; field++) { printf "%s", $field FS } print $1}' | sed 's/$/\o015/'
2,3,4,5,6,7,1
b,c,d,e,f,g,h,a
B,C,D,A
0

A: IF we can/want see the input file as a csv table, you could run something along the lines of
csvcut -c '2:,1' input

This tool (csvkit) see the input as an homogeneous table: example input
a,b,c,d,e
1,2,3,4,5
3,4
6,7,8,9,0

output:
b,c,d,e,a
2,3,4,5,1
4,,,,3              //implicitly added some empty fields
7,8,9,0,6

A: GNU sed in extended regex mode -E:
$ sed -Ee 's/^([^,]*),(.*)(.)$/\2,\1\3/' file | cat -A
2,3,4,1^M$
7,8,9,6^M$
b,c,d,a^M$

With AWK:
$ awk -F ',' '
  BEGIN { OFS = FS }
  NF > 1 {
    first = $1
    cr = substr($NF, length($NF))
    sub(/.$/, "", $NF)
    for (i=1; i<NF; i++)
      $(i) = $(i+1)
    $(NF) = first cr
  }
  1
' file

With perl:
$ perl -F, -pale '
    BEGIN { $" = ","; }         # set OFS to comma
    next unless /,/;            # skip non interesting lines
    chop $F[-1];                # remove last char, the carriage return
    splice @F, @F, 1, shift @F; # move 1st element to the end
    s/.*/@F\r/;
' file


Q: Not connection with SLComposeViewController - Not share Screenshot with Facebook My code for share screenshot of my App in Facebook always shows alertView and never posts in Facebook:
- (UIImage *) screenshot
{
    AppDelegate* app = (((AppDelegate*)[UIApplication sharedApplication].delegate));
    UIGraphicsBeginImageContextWithOptions(app.navController.view.bounds.size, NO, [UIScreen mainScreen].scale);

    [app.navController.view drawViewHierarchyInRect:app.navController.view.bounds afterScreenUpdates:YES];

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

-(void)btnSharedFacebookTapped:(id)sender
{
    [[AudioManager sharedAudioManager]playSoundEffect:kSoundGrilloMenu];

    // Take screenshot
    if([SLComposeViewController isAvailableForServiceType:SLServiceTypeFacebook])
    {
        AppDelegate* app = (((AppDelegate*)[UIApplication sharedApplication].delegate));
        SLComposeViewController *controller = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeFacebook];

        SLComposeViewControllerCompletionHandler myBlock = ^(SLComposeViewControllerResult result)
        {
            if (result == SLComposeViewControllerResultCancelled)
                {
                    NSLog(@"Cancelled");
                } else {
                    NSLog(@"Done");
            }

        [app.navController dismissViewControllerAnimated:YES completion:Nil];
        };

    controller.completionHandler =myBlock;

    //Adding the Text to the facebook post value from iOS
    [controller setInitialText:@"Checkout this app xxxxxx”];
    [controller addImage:[self screenshot]];

    //Adding the URL to the facebook post value from iOS
    [controller addURL:[NSURL URLWithString:@"https://itunes.apple.com/us/app/xxxxxxx/id[xxx]?mt=8"]];

    [app.navController presentViewController:controller animated:YES completion:Nil];

    } else{
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Sorry"
                                                                message:@"You can't send a post right now, make sure your device has an internet connection and you have at least one Facebook account setup."
                                                               delegate:self
                                                      cancelButtonTitle:@"OK"
                                                      otherButtonTitles:nil];
            [alertView show];
      }
}

A: I have created one demo APP for this. In this APP, i am posting status and uploading photo but i have never got fail error.

- (IBAction)btnSocialSharing:(id)sender {
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"Select Social Media"
                                                             delegate:self
                                                    cancelButtonTitle:@"Cancel"
                                               destructiveButtonTitle:nil
                                                    otherButtonTitles:@"Facebook", @"Twitter" ,nil];
    // actionSheet.tag = 100;
    [actionSheet showInView:self.view];
}
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSString *buttonTitle=[actionSheet buttonTitleAtIndex:buttonIndex];
   // NSString *image=[UIImage imageNamed:chooseImage];
    if ([buttonTitle isEqualToString:@"Facebook"])
    {

        SLComposeViewController *controller = [SLComposeViewController
                                               composeViewControllerForServiceType:SLServiceTypeFacebook];
        SLComposeViewControllerCompletionHandler myBlock =
        ^(SLComposeViewControllerResult result){
            if (result == SLComposeViewControllerResultCancelled)
            {
                NSLog(@"Cancelled");
            }
            else
            {
                NSLog(@"Done");
            }
            [controller dismissViewControllerAnimated:YES completion:nil];
        };
        controller.completionHandler =myBlock;
        [controller setInitialText:self.txtStatus.text];
        [controller addImage:chooseImage];
        [self presentViewController:controller animated:YES completion:nil];

    }
   else if ([buttonTitle isEqualToString:@"Twitter"])
    {

        SLComposeViewController *controller = [SLComposeViewController
                                               composeViewControllerForServiceType:SLServiceTypeTwitter];
        SLComposeViewControllerCompletionHandler myBlock =
        ^(SLComposeViewControllerResult result){
            if (result == SLComposeViewControllerResultCancelled)
            {
                NSLog(@"Cancelled");
            }
            else
            {
                NSLog(@"Done");
            }
            [controller dismissViewControllerAnimated:YES completion:nil];
        };
        controller.completionHandler =myBlock;
        [controller setInitialText:self.txtStatus.text];
        [controller addImage:chooseImage];
        [self presentViewController:controller animated:YES completion:nil];

    }
}

- (IBAction)btnSelectPhoto:(id)sender {
    NSLog(@"Select Photos button");
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    picker.allowsEditing = YES;
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;

    [self presentViewController:picker animated:YES completion:NULL];

}
//Image Picker Delegate Methods
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{

    chooseImage = info[UIImagePickerControllerEditedImage];
    [picker dismissViewControllerAnimated:YES completion:NULL];
    [self displayImage];

}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {

    [picker dismissViewControllerAnimated:YES completion:NULL];

}
-(void)displayImage
{
    self.viewImage.image = chooseImage;
}


Q: Real world example of application of the command pattern Command pattern can be used to implement Transactional behavior (and Undo).
But I could not find an example of these by googling. I could only find some trivial examples of a lamp that is switched on or off.
Where can I find a coding example (preferably in Java)of this/these behaviors implemented using the Command Pattern?

A: public final class Ping implements Callable<Boolean> {

  private final InetAddress peer;

  public Ping(final InetAddress peer) {
    this.peer = peer;
  }

  public Boolean call() {
    /* do the ping */
    ...
  }
}
...
final Future<Boolean> result
    = executorService.submit(new Ping(InetAddress.getByName("google.com")));
System.out.println("google.com is " + (result.get() ? "UP" : "DOWN"));

A: In one of our projects, we have the following requirement:

*

*Create a record in DB.

*Call a service to update a related record.

*Call another service to log a ticket.

To perform this in a transactional manner, each operation is implemented as a command with undo operation. At the end of each step, the command is pushed onto a stack. If the operation fails at some step, then we pop the commands from the stack and call undo operation on each of the command popped out. The undo operation of each step is defined in that command implementation to reverse the earlier command.execute().
Hope this helps.

A: Command Patterns are used in a lot of places.

*

*Of course what you see everywhere is a very trivial example of GUI Implementation, switches. It is also used extensively is game development. With this pattern the user can configure his buttons on screen as well.

*It is used in Networking as well, if a command has to be passed to the other end.

*When the programmers want to store all the commands executed by the user, e.g. sometimes a game lets you replay the whole level.

*It is used to implement callbacks.

Here is a site which provides as example of command pattern used for callback. http://www.javaworld.com/article/2077569/core-java/java-tip-68--learn-how-to-implement-the-command-pattern-in-java.html?page=2

*Here's another link which shows command pattern with database. The code is in C#. http://www.codeproject.com/Articles/154606/Command-Pattern-at-Work-in-a-Database-Application

A: You have to define undo(), redo() operations along with execute() in Command interface itself.
example:
interface ChangeI {
    enum State{ READY, DONE, UNDONE, STUCK } ;
    State getState() ;

    void execute() ;
    void undo() ;
    void redo() ;
}

Define a State in your ConcreteCommand class. Depending on current State after execute() method, you have to decide whether command should be added to Undo Stack or Redo Stack and take decision accordingly.
abstract class AbstractChange implements ChangeI {
    State state = State.READY ;

    public State getState() { return state ; }

    public void execute() {
        assert state == State.READY ;
        try { doHook() ; state = State.DONE ; }
        catch( Failure e ) { state = State.STUCK ; }
        catch( Throwable e ) { assert false ; }
    }

    public void undo() {
        assert state == State.DONE ; }
        try { undoHook() ; state = State.UNDONE ; }
        catch( Failure e ) { state = State.STUCK ; }
        catch( Throwable e ) { assert false ; }
    }

    public void redo() {
        assert state == State.UNDONE ;
        try { redoHook() ; state = State.DONE ; }
        catch( Failure e ) { state = State.STUCK ; }
        catch( Throwable e ) { assert false ; }
    }

    protected abstract void doHook() throws Failure ;

    protected abstract void undoHook() throws Failure ;

    protected void redoHook() throws Failure { doHook() ;} ;
}

Have a look at this undo-redo command article for better understanding.


Q: If $\beta$ is a zero of $f(x)=x^2+x+2$ over $\mathbb{Z}_3$, find the other zero If $\beta$ is a zero of $f(x)=x^2+x+2$ over $\mathbb{Z}_3$, find the other zero.
What I tried:
Suppose $B$ is a zero of $f(x)$, so $f(\beta)=\beta^2+\beta+2=0$. I know that $f(x)$ is irreducible in $\mathbb{Z}_3$. Any idea how to proceed?

A: Call the other root $\gamma$. We have:
$x^2 + x + 2 = (x - \beta)(x - \gamma) = x^2 - (\beta + \gamma)x + \beta\gamma$.
Thus we have:
$\gamma = \dfrac{2}{\beta} = 2 - \beta$
Note that $\dfrac{2}{\beta} = 2 - \beta$ tells us that:
$\beta^2 + 2 = 2\beta$, adding $\beta$ to both sides gives us:
$\beta^2 + \beta + 2 = 0$, as we already knew.
We can check that both forms of $\gamma$ give an actual root:
$\left(\dfrac{2}{\beta}\right)^2 + \dfrac{2}{\beta} + 2 = \dfrac{1}{\beta^2} + \dfrac{2\beta}{\beta^2} + \dfrac{2\beta^2}{\beta^2} = \dfrac{2(1 + 2\beta + 2\beta^2)}{2\beta^2}$
$= \dfrac{2 + \beta + \beta^2}{2\beta^2} = \dfrac{0}{2\beta^2} = 0$, and:
$(2 - \beta)^2 + (2 - \beta) + 2 = 1 - \beta + \beta^2 + 2 - \beta + 2 = \beta^2 - 2\beta + 2 = \beta^2 + 3\beta - 2\beta + 2$
$ = \beta^2 + \beta + 2 = 0$.
Finally, it should be clear that:
$(x - \beta)(x - (2 - \beta)) = x^2 - (2 - \beta + \beta)x + (\beta)(2 - \beta)$
$= x^2 - 2x + 2\beta - \beta^2 = x^2 + x  -(\beta + \beta^2) = x^2 + x + 2$.


Q: Convert a  in a My code has
<input class="menu_button" type="submit" value="Log in">
Register

The a href is styled perfectly in my css while the input button with type = submit DOES NOT...
How could I change

Into a a href?
Here is a jsfiddle.
http://jsfiddle.net/26tyd/
SEE HOW THE BUTTONS LOOK different. one higher up and smaller the other is perfect. Please help me figure out how to fix this issue.

A: Add this to your css:
input[type=submit]{
    height: 22px;
    line-height: 18px;
    cursor: pointer;
}

A: Instead of using height and width like you are currently doing you should use padding because then the text is vertically centred.
The reason that the is not being sent is because you are not currently using a form so you need to add a form tag around the stuff that you want in the form so you could use this:
<form action='#' method='get'>
    <input class="menu_button" type="submit" value="Log in" />
</form>

Here is a working fiddle:
http://jsfiddle.net/Hive7/26tyd/3/

A: You just need to add below code in your code:
    box-sizing: border-box;
    -moz-box-sizing: border-box;

And to adjust the hight and with I would sugegst you to play with "min-width" and "padding". As giving "Width" and "Height" can limit your button and if you have more test or padding the height and width will not let the background increase.
Please see the updated code:-
.menu_button {
   -moz-box-shadow:inset 0px -1px 0px 0px #000000;
    -webkit-box-shadow:inset 0px -1px 0px 0px #000000;
    box-shadow:inset 0px -1px 0px 0px #000000;
    background-color:#000000;
    -webkit-border-top-left-radius:0px;
    -moz-border-radius-topleft:0px;
    border-top-left-radius:0px;
    -webkit-border-top-right-radius:0px;
    -moz-border-radius-topright:0px;
    border-top-right-radius:0px;
    -webkit-border-bottom-right-radius:0px;
    -moz-border-radius-bottomright:0px;
    border-bottom-right-radius:0px;
    -webkit-border-bottom-left-radius:0px;
    -moz-border-radius-bottomleft:0px;
    border-bottom-left-radius:0px;
    text-indent:0;
    border:1px solid #fa1e0f;
    display:inline-block;
    color:#ffffff;
    font-family:Arial;
    font-size:12px;
    font-weight:normal;
    font-style:normal;
    text-decoration:none;
    text-align:center;
    text-shadow:1px 1px 0px #33302f;
    box-sizing: border-box; /*ADDED*/
    -moz-box-sizing: border-box; /*ADDED*/
    padding:5px;
}

Hope this helps!

A: Try
margin: 0;
padding: 0;
white-space: normal;
box-sizing: content-box;

The input tags are styled different by the user agent stylesheet than a tags.

A: As I understand you need to style both elements the same?
Here's one solution:
JSFIDDLE DEMO
.menu_button {
    -moz-box-shadow:inset 0px -1px 0px 0px #000000;
    -webkit-box-shadow:inset 0px -1px 0px 0px #000000;
    box-shadow:inset 0px -1px 0px 0px #000000;

    background-color:#000000;
    text-indent: 0;
    border: 1px solid #fa1e0f;
    display: inline-block;
    color: #fff;
    font: normal 12px/1 Arial;
    width: 58px;
    text-decoration: none;
    text-align: center;
    vertical-align: top;
    text-shadow: 1px 1px 0px #33302f;
    padding: 5px 0;
    ouotline: 0 none;
    margin: 0;
}
/*this is needed for firefox and buttons */
.menu_button::-moz-focus-inner { border: 0; padding: 0; outline: none; }


Q: Azure notification hub Cannot read property 'name' of undefined Scenario
I have created azure notification hub on my Visual Studio Enterprise subscription and new namespace in the azure portal according to this tutorial
Problem
After resources are created, I go into overview section of my notification hub in azure portal and I see error Cannot read property 'name' of undefined


Q: I need to convert a Node object to a string in C I am having trouble with a homework assignment. I finished most of it, but I'm stuck at this one part. If you look at the header file, you will see a comment that says:

Convert a Node object to a string.  We require a pointer to the Node object so that we can display the address of the object for further reference

I did as much as I could, but I don't know where to go from here.
The output from this test program looks like:

<0x0022ff40>[value: 2, left: 0x00000000, right: 0x00000000]
<0x0022ff30>[value: 3, left: 0x00000000, right: 0x00000000]
<0x0022ff20>[value: 4, left: 0x00000000, right: 0x00000000]

<0x0022ff10>[value: *, left: 0x0022ff30, right: 0x0022ff20]
<0x0022ff00>[value: +, left: 0x0022ff40, right: 0x0022ff10]
 Tree evaluation: 14

<0x0022ff00>[value: +, left: 0x0022ff40, right: 0x0022ff30]
<0x0022ff10>[value: *, left: 0x0022ff00, right: 0x0022ff20]
 Tree evaluation: 20

<0x0022ff00>[value: ., left: 0x0022ff40, right: 0x0022ff30]
<0x0022ff10>[value: *, left: 0x0022ff00, right: 0x0022ff20]
invalid operator: .

This is my main():
#include <stdio.h>
#include "TreeNode.h"

int main(void)
{
 Node n2, n3, n4, times, plus;

 setNode(&n2, 2, NULL, NULL, true);
 setNode(&n3, 3, NULL, NULL, true);
 setNode(&n4, 4, NULL, NULL, true);
 printf("\n");

 setNode(&times, '*', &n3, &n4, true);
 setNode(&plus, '+', &n2, &times, true);

 printf(" Tree evaluation: %d\n\n", eval(&plus));

 setNode(&plus, '+', &n2, &n3, true);
 setNode(&times, '*', &plus, &n4, true);

 printf(" Tree evaluation: %d\n\n", eval(&times));

 setNode(&plus, '.', &n2, &n3, true);
 setNode(&times, '*', &plus, &n4, true);

 printf(" Tree evaluation: %d\n\n", eval(&times));

 return 0;
}

This is my header:
#include <stdio.h>
#ifndef TREE_NODE
#define TREE_NODE

typedef struct Node_t {
    int value;
    struct Node_t   *left;
    struct Node_t   *right;
} Node, *Node_p;

typedef char* String;

typedef enum {false, true} bool;

/*
 *  Convert a Node object to a string.
 *
 *  We require a pointer to the Node object so that we can display the
 *  address of the object for further reference.
 */
String nodeToString(Node_p np) {
    static char output[0];
    sprintf(output, "<0x%d>\n", np, np->value, np->left, np->right);
    return output;
}

void setNode(Node_p np,
     int    value,
     Node_p    left,
     Node_p    right,
     bool    display) {
        np->value = value;
        np->left = left;
        np->right = right;
     if (display) {
          printf("%s\n", nodeToString(np));
     }

}

int eval(Node_p np){

    switch(np->value) {
        case '+':
               np->value = eval(np->left) + eval(np->right);
               return np->value;
        case '-':
               np->value = eval(np->left) - eval(np->right);
               return np->value;
        case '*':
               np->value = eval(np->left) * eval(np->right);
               return np->value;
        case '/':
               np->value = eval(np->left) / eval(np->right);
               return np->value;
        default:
                exit(1);
    }
    return 0;
}

#endif

A: You are using the same field for operator and value in the struct Node_t. Extend your struct as this:
typedef struct Node_t {
    int value;
    char op; /*operator*/
    struct Node_t   *left;
    struct Node_t   *right;
} Node, *Node_p;

Add a new parameter to the function setNode for the operator (set it to '\0' when Node is a number; you must do the switch of eval over this operator), and add
case '\0':
        return np->value;
        break;

to the switch of eval.


Q: Magento Enterprise Editon URL rewrite IN some scenario for configurable product , when we update the url-key , it is storing in the "catalog_product_entity_url_key" but in the admin panel it is the old key , we also flushed the cache and did reindexing from shell, still it is showing the same  url-key .
Now when we update the description it throws error
Product with the '-------' url_key attribute already exists.
If we update the url-key and the description it gets updated , but url-key is still the same .

A: If your EE is newer then 13, you should also update table *enterprise_url_rewrite*
and set value for field identifier equal to catalog_product_entity_url_key.value

A: If if delete from catalog_product_entity_varchar the  value whose attribute id is url_key i.e., 97 and store id is 1, its solving the issue.