text:
Q: Always receive org.apache.http.NoHttpResponseException: The target server failed to respond Android I am working on HTTP post in android. Here is my code:
 SendMail sending = (SendMail) new SendMail()
                                .execute(url + "/mob/android/dummy.php");

    public class SendMail extends AsyncTask<String, String, String> {

    private String endResult;

    @Override
    protected String doInBackground(String... val) {
        String url = val[0];
        Log.i("Url", url + "");

        HttpClient httpclient = new DefaultHttpClient();

        HttpPost httppost = new HttpPost(url);

        try {

            CookieStore cookieStore = new BasicCookieStore();
            ((AbstractHttpClient) httpclient).setCookieStore(cookieStore);

            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("name", post_name));
            nameValuePairs

            nameValuePairs.add(new BasicNameValuePair("email", post_email));
            nameValuePairs.add(new BasicNameValuePair("message",
                    "Requesting appointment from: " + SelectedDr
                            + "  Message: " + post_message));

            Log.i("nameValuePairs:", "" + nameValuePairs);

            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            HttpResponse response = httpclient.execute(httppost);
            BasicResponseHandler myHandler = new BasicResponseHandler();
            endResult = myHandler.handleResponse(response);
            Log.i("nameValuePairs", "" + nameValuePairs);
            Log.i("endResult", "" + endResult);
        } catch (ClientProtocolException e) {

        } catch (IOException e) {

        }

        return null;
    }

    @Override
    protected void onPostExecute(String result) {

        super.onPostExecute(result);
        publishProgress(endResult);

    }

    @Override
    protected void onProgressUpdate(String... values) {

        super.onProgressUpdate(values);
        String result = values[0];

        T_warning.setText("Mail Sent.");
        ET_email.setText("");
        ET_name.setText("");

        ET_message.setText("");

    }

}

Now till
nameValuePairs.add(new BasicNameValuePair("message",
                "Requesting appointment from: " + SelectedDr
                        + "  Message: " + post_message));

it is working fine but on HttpResponse response = httpclient.execute(httppost); it gives no reponse after 3 minutes it gives mail sent but on my mail server I received no mail and also show exception:

org.apache.http.NoHttpResponseException: The target server failed to respond

I am stuck with that I could not understand why this is happening I added all permissions
LOGCAT:
04-05 10:41:57.110: I/exception(3926): org.apache.http.NoHttpResponseException: The target server failed to respond

04-05 10:41:57.110: I/endResult(3926): null

Edited Code gives LOGCAT:
04-05 10:51:17.160: W/System.err(4016): org.apache.http.NoHttpResponseException: The target server failed to respond

04-05 10:51:17.170: W/System.err(4016):     at org.apache.http.impl.conn.DefaultResponseParser.parseHead(DefaultResponseParser.java:85)

04-05 10:51:17.170: W/System.err(4016):     at org.apache.http.impl.io.AbstractMessageParser.parse(AbstractMessageParser.java:174)

04-05 10:51:17.170: W/System.err(4016):     at org.apache.http.impl.AbstractHttpClientConnection.receiveResponseHeader(AbstractHttpClientConnection.java:180)

04-05 10:51:17.170: W/System.err(4016):     at org.apache.http.impl.conn.DefaultClientConnection.receiveResponseHeader(DefaultClientConnection.java:235)

04-05 10:51:17.170: W/System.err(4016):     at org.apache.http.impl.conn.AbstractClientConnAdapter.receiveResponseHeader(AbstractClientConnAdapter.java:259)

04-05 10:51:17.170: W/System.err(4016):     at org.apache.http.protocol.HttpRequestExecutor.doReceiveResponse(HttpRequestExecutor.java:279)

04-05 10:51:17.170: W/System.err(4016):     at org.apache.http.protocol.HttpRequestExecutor.execute(HttpRequestExecutor.java:121)

04-05 10:51:17.170: W/System.err(4016):     at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:428)

04-05 10:51:17.170: W/System.err(4016):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)

04-05 10:51:17.170: W/System.err(4016):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:653)

04-05 10:51:17.170: W/System.err(4016):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:627)

04-05 10:51:17.170: W/System.err(4016):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:616)

04-05 10:51:17.170: W/System.err(4016):     at com.ilmasoft.alina_dental.MailUs$SendMail.doInBackground(MailUs.java:492)

04-05 10:51:17.180: W/System.err(4016):     at com.ilmasoft.alina_dental.MailUs$SendMail.doInBackground(MailUs.java:1)

04-05 10:51:17.180: W/System.err(4016):     at android.os.AsyncTask$2.call(AsyncTask.java:252)

04-05 10:51:17.180: W/System.err(4016):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)

04-05 10:51:17.180: W/System.err(4016):     at java.util.concurrent.FutureTask.run(FutureTask.java:137)

04-05 10:51:17.180: W/System.err(4016):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1081)

04-05 10:51:17.180: W/System.err(4016):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:574)

04-05 10:51:17.180: W/System.err(4016):     at java.lang.Thread.run(Thread.java:1020)

A: try this code within doInBackground
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("name", post_name));
nameValuePairs.add(new BasicNameValuePair("email", post_email));
            nameValuePairs.add(new BasicNameValuePair("message",
                    "Requesting appointment from: " + SelectedDr
                            + "  Message: " + post_message));

        DefaultHttpClient hc = new DefaultHttpClient();
            ResponseHandler<String> res = new BasicResponseHandler();
            HttpPost postMethod = new HttpPost(url);
            String response = null;

            try {
                postMethod.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            try {
                response = hc.execute(postMethod, res);
            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }


text:
Q: Disable the automatic rejection of questions without matching tags Migrations can be automatically rejected, the two major reasons this happens are

*

*the user is question banned on the target site

*the question does not havy any tag that exists on the target site

The first check makes a lot of sense, but I can't see why we would actually want to do the second one. Tagging varies a lot between sites, and it is easily possible to create false positives for this check, questions that would be appropriate for the target site but don't have any tags that match it. One example where this happens is between Math Overflow and Math SE because MO uses arXiv classification as a base for their tags, so they often don't match the MSE tags.
I'm not convinced the check does much good, and there is already a major system that is meant to reduce the number of migrations to completely wrong sites. The community can only migrate to sites on a short list, and those sites are selected carefully and removed if too many bad migrations happen. I think this is sufficient for most cases, and I can't imagine this tag check to prevent any significant volume of bad migrations. For such a question I find the chance for false positivies not worth it.
Another issue is that the rejection is entirely silent, which can easily confuse users.

redpajama_set_name: RedPajamaStackExchange


text:
Q: updating data in MySql database table I am creating a Windows Forms application and now at certain point I need to make a database connection, I have inserted the values to database easily, but now its not updating my data, I am using following query for this purpose:
MySqlCommand sda = new MySqlCommand(@"Update shedulling.tablelayout1 set date = '"
    + date + "',line = " + line + ",col1 = '" + first_textbox.text + "', col2 = '"
    + sec_textbox.text + "',col3_textbox.text = '" + thi_textbox.text
    + "',col4_textbox.text = '" + four + "' where date = '" + date + "' AND line = '"
    + line.ToString() + "' ", conn);

conn is a connection string which is written fine, and date and line are string and integer values send as an argument to this function.

A: You have missed single quotes in line part. Change it like this line = '" + line + "'.
Also there is one more notable thing in your code: you are trying to find the record in the table that is not exist yet in where clause where date = '" + date + "' AND line = '" + line.ToString() + "' note in this line date and line are the new values not old values so no rows affected in the update query. You should use old values of date and line in the where clause.
Also you should always use parameterized queries. This kind of string concatenations are open for SQL Injection.

A: Try debugging the code, there must be INSERT statement executing somewhere in your code.
UPDATE: If "line" is integer variable then you need to convert it into string. You have converted it after WHERE clause but not after SET clause.
You may want to post some more code to get exact answer.


text: Q: Could not create Java Virtual Machine, A fatal Exception has occurred in Eclipse Although this questions has been asked before but I am still unable to resolve this error. I am very new to Eclipse and tomcat. There are various solutions as I can see on the internet but which one will specifically fit for my program is what I want to know. I am using tomcat version 7.0.109 and JDK version 15. Any help will be highly appreciated. Thanks


text:
Q: Get value inside nested object using jQuery I have the following bit of code
for (var i = 0; i < $scope.d.results.length; i++) {
    console.log($scope.d.results[i]);
}

which returns this:

I would like to get the value of the Name field out of this object but I can't think of the syntax to get at it. I've tried a few things with no luck. Can someone explain how to dig down 2 levels and get at it? Thanks!

A: You can use
$scope.d.results[i].Name

As, $scope.d.results[i] returns an object which contains the Name, you can use above syntax to get it from the object.


text:
Q: Using a Wiki for Requirements Management? I have been looking for a collaborative tool for developing functional specifications. I am looking for the ability to:

*

*Have multiple users contribute to the specification.

*Provide some form of traceability, which could be done manually if needed.

*Provide users with the ability to add comments and notes.

*Upload and display Visio documents

*Upload and display mockup screens using Balsamiq Mockup.

My initial impression is that using a wiki could be a good tool for this task. Does anyone have experience with using a wiki for creating functional specifications?  What would be the pros and cons to using a tool like this as opposed to a requirements management tool?
Your input is greatly appreciated!

A: "What would be the pros and cons to using a tool like this as opposed to a requirements management tool?"
While it seems like a great idea, what you run into are people who can't and won't write.
People who can't write -- well -- can't write.  They can't communicate with an email or a wiki or any medium outside voice.

*

*Some people are "disorganized".  Actually, writing is too linear and they don't think linearly.

*Some people don't get the "write to your audience" and write stuff that's incomprehensible.

*Sometimes you can't even figure out what they're talking about, much less what they're writing about.  They talk in jargon or code.  They don't know much but insist on being heard.
Some people won't write.

*

*Some people refuse to make commitments.  Even in a wiki where it can be retracted.  They feel they must pre-discuss everything.

*Some people are in the habit of doing everything by giving direction to someone else.  They either don't write for themselves, or, they make people stand around in their office and listen to them talk and type.

*Some people are generally toxic on any kind of project.  They spring new requirements at the last minute.  Their first response is "that will never work".  They don't brainstorm well.  When they say it work work, and you beg them for an improvement, they don't have one.  They just know it won't work.
My experience is that only programmers can use a Wiki successfully.  And only senior-level programmers.

*

*N00bz don't have enough experience to sort out requirements from design from rumors and management fluff.

*N00bz don't always have the language skills to write clearly.  They may eventually, but one look at their Javadoc comments indicates that they're struggling with the "clarity" part of writing.
It's very appealing.  I'm hoping for people to get better at using wiki's because I think it could have a lot of advantages over more traditional approaches where one person interviews everyone and writes things down.  But it requires a level of confidence and skill in communication that few people seem to have.

A: Consider researching Fog Bugz.  They tout themselves as the best of the
best for project management.  Considering Joel's history I'd give them the
benefit of the doubt.  They use a wiki in the way you've just described.
I would suggest signing up for the free trial, if you're serious.
Depending on the size of your project, buying it might be a very good
option.
At very least you could look at how they've structured it, or read the
forums for ideas on how to build your own stripped down version

A: Specialist tools help keep things on track and introduce a fixed work-flow. This is kind of the point, keeping things focused and functional. Using generic tools like a Wiki might be great for a bunch of programmers but introducing one for 'mixed-mode' work might be bad:

*

*Things can creep and get off-track quickly

*Communication can be lost in the medium

Look at things like Basecamp. They can be thought of as an applied wiki, or collaborative tool. A generic tool for specific purpose needs refining. I don't know if MediaWiki or others have enough customization to keep things clean and focused.
Maybe gather the requirements for your requirements management tool (recursive I know) and what aspects (communication aspects) you can take from the wiki culture and an open-communication mindset. If neither requirements management tools or wikis fit the bill, look at building one. Might be the next big thing. It feels like saying Could I use a wiki instead of Bugzilla?
A fixed work-flow webapp for requirements management with an open-communication emphasis that allows people from many roles to see and understand might be good!

A: We have used TWiki and now FosWiki in that context. There are many things one gets for free (version control, access control, Web-base access, searches, remote management, security patches, ...). In a few minutes, one can define:

*

*a table defining requirements attributes,

*which creates interactive forms with field selection and validation (where you can also document discussions and rationales, embed images, attach documents, link to other requirements...),

*and then queries on these "requirements" and show them as tables that can be sorted, filtered, printed, reported against, etc. (e.g., http://jucmnav.softwareengineering.ca/ucm/bin/view/ProjetSEG/JUCMNavRequirementsVer2).

Obviously, one can easily use hyperlinks and Wiki links along the way. FosWiki also has features that can be used to enforce specific workflows, if needed. It is also easy to support forms for use cases and other paradigms (we have done this in the past, and that works generally well).
Wikis such as FosWiki are extensible and one could develop further modules for addressing weaknesses related to traceability management and impact analysis, table-based modifications of requirements, overall packaging, etc.

A: It's possible to do what you describe, to develop requirements in a collaborative way, in spite of using a wiki.  Nothing about the wiki paradigm assists in this process.
I managed a wiki on the Zend Framework project to track proposals for components.  They're still using it.  Proposals are different from functional specifications, but the usage is similar enough to your question that I think this is relevant.
A wiki doesn't take care of itself.  Unless you have someone responsible for managing it and making sure there is some structure and consistency, it quickly becomes a mess.  The real-world analogy would be to hand each of your team a blank sheet of paper and tell them to write up their part of the requirements.  Problems with this are:

*

*Every contributor has to make up their own document structure, and write about different things in a different order.  So it's impossible to compare one page to another.

*There's no "index page" to organize all the disparate contributions.  No one wants a page to "fall through the cracks," but in a wiki that's the default destiny of any page as soon as it's written.

*There's no feedback loop to make sure the writing actually gets done.

The way to make it work is to apply some process to the project, and use the wiki in accordance with that process.

*

*Give people the ability to create a new page in the wiki, but only through an interface that automatically links the new page into the right index.

*Define a lifecycle for documents, so they are sure to be drafted, reviewed, and approved at the appropriate stages.

*Provide a template for a new page.  Provide the section headings that you need in each of these pages, and make part of the review process a confirmation that head section has been filled out adequately.

A: As a middle ground between a free-form wiki and a requirements management tool, consider using a structured wiki like Foswiki.  I haven't done any formal requirements management (with a wiki or otherwise), but I have used TWiki (the predecessor to Foswiki) for other tasks, and it permits you to define a workflow, form fields, and so on as you need them, while keeping the flexibility of a wiki when you don't need a formal structure.

A: I agree with all (most) of the people above - use of a wiki may sound ok, but wiki's are meant to be present information and be updated as needed, not to be used as an interactive project management tool.  I would strongly suggest SmartSheet (I'm a strong advocate of the product) - it provides a spreadsheet like interface where you can store multiple files per row/task, send out automated updates to users and maintain specification revisions...
The other approach could be the use of Google email, docs and calendar - a free friendly way of team interaction....I would shy away from issue/bug tracking tools for project management - they tend to have differ on focus: PM tools on the entire project/resource/timeline and Issue tracking tools for specific entered issues....

A: This may be a bit old now, but I am currently using Atlassian's "Confluence" and it's been great.  I currently work as a UX engineer playing the role of "Product Owner" within an Agile process.  I can document requirements for discrete interfaces, allow for multiple users' feedback and comments, and intertwine each interface with other interfaces within a larger context (e.g. user story).  Everything is very dynamic and template driven.  It's suiting my current needs very well.


text:
Q: Can you call data from it's own json object?
Possible Duplicate:
Self-references in object literal declarations

Within a .js file I have an object. I'd like to use some of it's data within itself. Something like...?
obj = {
    thing: 'thing',
    things: this.thing + 's'
}

A: You can't create an object that way, however there are a number of alternatives:
var obj;
obj = {
  thing: 'thing'
};
obj.things = obj.thing + 's';

-or-
function Thingy(thing)
{
  this.thing = thing;
  this.things = thing + 's';
}
var obj;
obj = new Thingy('thing');

or if you're using a browser that supports properties:
function Thingy( thing )
{
  this.thing = thing;
}
Thingy.prototype = {
  get things() {
    return this.thing + 's';
  },
  set things(val) {
    //there are a few things horribly wrong with this statement,
    //it's just for an example, not useful for production code
    this.thing = val[val.length - 1] == 's' ? val.substr(0, val.length - 2) : val;
  }
};

If you want to know more about them, Jon Resig has a great post about accessors and mutators, AKA getters and setters.
For cross-browser support, stick with a function call for the plural form and only provide an accessor:
function Thingy( thing ) {
  this.thing = thing;
}
Thingy.prototype = {
  getThings:function(){
    return this.thing + 's';
  }
}


text:
Q: What's wrong with my Seekbar? TAT guys,thanks for view my question(TAT)
i use SeekBar in a videoPlay app,on my device(XiaoMi4,api 23),it is ok.
but on other device(Nexus5 api 22,Nexus 6P,api 22),it looks like this:

here is my xml:
<SeekBar
                android:layout_width="match_parent"
                android:layout_height="50dp"
                style="@style/MediaController_SeekBar"
                android:layout_toRightOf="@+id/video_currentTime"
                android:id="@+id/video_seekBar"
                android:layout_toLeftOf="@+id/video_totalTime"/>

and @style/MediaController_SeekBar:
<style name="MediaController_SeekBar" parent="android:Widget.SeekBar">
    <item name="android:progressDrawable">@drawable/scrubber_progress_horizontal_holo_dark</item>
    <item name="android:indeterminateDrawable">@drawable/scrubber_progress_horizontal_holo_dark</item>
    <item name="android:minHeight">13dip</item>
    <item name="android:maxHeight">13dip</item>
    <item name="android:thumb">@drawable/scrubber_control_selector_holo</item>
    <item name="android:thumbOffset">16dip</item>
    <item name="android:paddingLeft">16dip</item>
    <item name="android:paddingRight">16dip</item>
</style>

it is wrong on api< 23 device
i try to use default style,but it don't work
so,can u help me? thanks a lot!

A: Try setting minHeight and Maxheight to some value on Seekbar .. Hope that will help
    android:maxHeight="40dp"
    android:minHeight="40dp"

A: i think you should use dp for all instead of using dip


text: Q: Is it possible to retrieve information on all active scroll contexts from Elasticsearch? I'm interested in monitoring how many concurrent scroll contexts are open on a given Elasticsearch cluster. Since they are stateful, it seems reasonable that it may be able to retrieve a list. Nothing in /_cat looks relevant though. Is this possible?


text:
Q: Moxy XPath local-name() support I'm trying to use the EclipseLink Moxy library to extract values from XML messages via XPath. My problem is that I do not know in advance the XML namespace prefixes that will be used in the messages, so I need to specify XPaths that can find elements regardless of the prefix used.
Standard XPath supports the local-name() function for this purpose, but I think Moxy only handles a sub-set of XPath which does not seem to include local-name. Can anyone suggest another approach?

A: For the @XmlPath annotation, MOXy leverages the prefix to namespace mappings that are defined in the package level @XmlSchema annotation.  The prefixes don't need to match what is in the XML document or XML Schema.
You can find a full example on my blog:

*

*http://blog.bdoughan.com/2010/09/xpath-based-mapping-geocode-example.html


text:
Q: Unit measurement for brightness and contrast in opencv
contrast = 30,
brightness = 350
what is the suitable unit measurement for contrast and brightness? (for documentation purposes)

A: Those values are not contrast and brightness, although they can be used to adjust contrast and brightness.  The documentation calls then alpha and beta.  What that statement says is "take the range of pixel values in my image, and remap then linearly so that the lowest value is now 30 and the highest value is 350".  If your pixels spanned from 20 to 60 before, this would expand the contrast by using more pixel values.  The conversion would be
new = (old-20) * (350-30) / (60-20) + 30


text:
Q: "attribute nam"e can not be resolved as member of "object" i got this issue a class containing protected attributes :
Test Class:
abstract public class Test extends WithAttachment{
static ISQLTest pISQLTest = null;

// Ajour une refence au campagne ??? pour resoudre le Warning

/**
 * Date de creation du test
 */
protected Date creationDate;

/**
 * Nom complet du concepteur du test
 */
protected String conceptorName;

/**
 * Login du concepteur du test
 */
protected String conceptorLogin;
.....}

Managed bean :
    private Test selectedTest; // with getters and setters

xhtml page :
 <h:panelGrid columns="2" cellpadding="4" header="Test Details">

                                  <h:outputText value="Name of The Test :" />
                                  <h:outputText value="#{projectTestManagementMB.selectedTest.name}" />

                                  <h:outputText value="Creation Date :" />
                                  <h:outputText value="#{projectTestManagementMB.selectedTest.creationDate}" />

                                  <h:outputText value="Executed :" />
                                  <h:outputText value="#{projectTestManagementMB.testExecutedFlag}" />

                                  <h:outputText value="Owner :" />
                                  <h:outputText value="#{projectTestManagementMB.selectedTest.conceptorName} #{projectTestManagementMB.selectedTestconceptorLogin}" />

  </h:panelGrid>

so when i try to access them in my xhtml page in EL expression i get this error ;
t
attribute name can no be resolved as member of selectedTest
So is there a possibility to solve this problem without changing the access type (protected) of class Test attributes .
Any help will be appreciated

A: Well, just as it says - there's no "name" attribute in Test, unless that's in WithAttachment which you haven't shown us.
You've got conceptorName, but not name. Admittedly I don't know whether having a protected field will be good enough anyway - I'd expect a private field and a public getName() property.

A: #{projectTestManagementMB.selectedTest.name}

Where is your attribute name?? in Test class..


text:
Q: Is there any way to download entire collection set stored in Firebase Firestore to the device? I'm using Firebase Cloud Firestore in my iOS app, with persistence enabled option. I want to persist data at the first run of the app and listen to any changes after that.
I only came up with querying every single collection in AppDelegate's application(application:didFinishLaunchingWithOptions:):
let settings = FirestoreSettings()
settings.isPersistenceEnabled = true

let firestore = Firestore.firestore()
firestore.settings = settings

firestore.collection("1").getDocuments { (snap, error) in
    print("Collection 1 persisted.")
}
firestore.collection("2").getDocuments { (snap, error) in
    print("Collection 2 persisted.")
}
firestore.collection("3").getDocuments { (snap, error) in
    print("Collection 3 persisted.")
}
//....and so on

But I don't think this is a good approach. You might have better ideas. Thank you.


text:
Q: PlasmidSeeker, a Perl script cannot run because of "permission denied" error After installing PlasmidSeeker on LinuxMint19, I cannot run its Perl script
It is always "Permission denied" although I've given all the permissions to plasmidseeker.pl
sudo perl plasmidseeker.pl -d db_w20/ -i TH19_1.filtered.fastq -b cereus-ATCC14579.fasta

The output is

Loading database... Converting sample reads to k-mers... Can't exec
  "/home/fox/PlasmidSeeker/GenomeTester4/glistmaker": Permission denied
  at plasmidseeker.pl line 275. Can't exec
  "/home/fox/PlasmidSeeker/GenomeTester4/glistcompare": Permission
  denied at plasmidseeker.pl line 277. Finding coverage of bacterial
  isolate... Can't exec
  "/home/fox/PlasmidSeeker/GenomeTester4/glistmaker": Permission denied
  at plasmidseeker.pl line 283. Can't exec
  "/home/fox/PlasmidSeeker/GenomeTester4/glistcompare": Permission
  denied at plasmidseeker.pl line 152. Can't exec
  "/home/fox/PlasmidSeeker/GenomeTester4/glistcompare": Permission
  denied at plasmidseeker.pl line 153. Can't exec
  "/home/fox/PlasmidSeeker/GenomeTester4/glistcompare": Permission
  denied at plasmidseeker.pl line 159. Can't exec
  "/home/fox/PlasmidSeeker/GenomeTester4/glistcompare": Permission
  denied at plasmidseeker.pl line 160. Bacteria median coverage is 0
  Bacteria median coverage is too low (less than 3). Higher coverage
  dataset is needed or use flag --ponly at plasmidseeker.pl line 287.

I have Googled for possible solutions but found nothing. Could anybody who has some exp with bioinformatics and Perl help me? Thank you very much.

A:
I've given all the permissions to plasmidseeker.pl

But that's not what the error message is complaining about, is it? Take a closer look.

Can't exec "/home/fox/PlasmidSeeker/GenomeTester4/glistmaker": Permission denied at plasmidseeker.pl line 275.
Can't exec "/home/fox/PlasmidSeeker/GenomeTester4/glistcompare": Permission denied at plasmidseeker.pl line 277.

The programs that can't be run are /home/fox/PlasmidSeeker/GenomeTester4/glistmaker and /home/fox/PlasmidSeeker/GenomeTester4/glistcompare. Those are the permissions that you need to fix.
It's important to read error messages, of course. But it's more important to understand them :-)


text:
Q: Python: unit tests in different folder than production code? I've read multiple articles and questions on StackOverflow and was wondering why no one uses the following structure for unit tests in Python:
MyProject/
    main/
        module1/
            my_file.py
    test/
        module1/
            test_my_file.py

What I've read is that you either:

*

*Put test_my_file.py in the same directory as my_file.py:
MyProject/
    module1/
        my_file.py
        test_my_file.py

*Put test_my_file.py in a directory named test in the same directory as my_file.py:
MyProject/
    module1/
        my_file.py
        test/
            test_my_file.py

Notes:

*

*I come from a Java world: having unit test code at the same place as production code feels weird to me.

*I'm very new to Python: there's probably some obvious reason I'm missing here. (My first guess would be that it has something to do with modules)

A: Maybe it's because I also wrote a lot of Java code before coming to Python, but I also keep my tests in a separate folder from production code on most of my Python projects. The only hassle is that sometimes you have to mess around with PYTHONPATH or relative imports to help the tests find the production code for importing.
In this project, I set the PYTHONPATH in my tox configuration.
setenv = PYTHONPATH=plugin/PySrc
commands =
     py.test plugin/PySrc/ test/PySrc/ --cov-report term-missing --cov plugin/PySrc/
     coverage xml


text:
Q: thmtools breaks links to algorithms I don't know why, but loading thmtools breaks the links to the algorithm. Just removing this package, or loading after the \numberwithin stuff seems to fix the compilation, but I'm wondering if it is a known issue, and if removing/moving it at a random different line is the correct way to fix this issue.
MWE: (to test, just click on the second link on the last page: you'll go to the wrong theorem)
\documentclass{article}

\usepackage{hyperref}
\usepackage{mathtools}
\usepackage{amssymb, amsthm, amsmath}

%% thmtools is the problem with numberwithin{algorithm}{section}!
\usepackage{thmtools}

\usepackage{algorithm, algorithmicx, algpseudocode}
\floatname{algorithm}{Protocol}
\providecommand*\algorithmautorefname{Protocol}
\numberwithin{algorithm}{section}

\begin{document}

\section{Section with links}

\begin{algorithm}[H]
  \caption{I am an algorithm that attracts all the links} \label{protocol:firstProtocol}
  I attract all the link...
\end{algorithm}

\newpage
\section{Section with no links}

\begin{algorithm}[H]
\caption{Nobody wants to link me :(} \label{protocol:secondProtocol}
Please link to me!!
\end{algorithm}

\newpage

Le premier est \autoref{protocol:firstProtocol} et le deuxième est \autoref{protocol:secondProtocol}.

\end{document}

A: With very few exceptions hyperref is always the last package to be loaded (it has to redefine a lot of other packages, so needs to see that they have been loaded).
Moving hyperref down, and both links hit their right targets for me.


text:
Q: PHP: Can someone explain the rules for instaniating a class/child class, in respect to the order of class declaration? I hope I'm using the correct terminology, if not, please comment and I'll correct.

#1: Works
Instantiate before class declaration
$x = new Abc;

class Abc {
    // code
}

#2: Doesn't Work
Instantiate before child class declaration (child declared before parent)
$x = new Xyz

class Xyz extends Abc {
    // code
}

class Abc {
    // code
}

#3: Works
Instantiate before child class declaration (child declared after parent)
$x = new Xyz

class Abc {
    // code
}

class Xyz extends Abc {
    // code
}

#4: Works
Instantiate after child class declaration (child declared before parent)
class Xyz extends Abc {
    // code
}

$x = new Xyz

class Abc {
    // code
}

Edit
The following quote is from an answer below by @artsylar. I don't know if my shared host has autoloading enabled, but I can't wrap my head around that quote in relation to the examples I've listed.

Note:
Unless autoloading is used, then classes must be defined before they
  are used. If a class extends another, then the parent class must be
  declared before the child class structure. This rule applies to
  classes that inherit other classes and interfaces.

A: I think this link can help you. http://php.net/manual/en/language.oop5.inheritance.php

Note:
Unless autoloading is used, then classes must be defined before they
  are used. If a class extends another, then the parent class must be
  declared before the child class structure. This rule applies to
  classes that inherit other classes and interfaces.


text:
Q: Passing from string to unsigned short I have 2 variables. One should be of type unsigned short array[10] (I am asked to do this), and the other will be an input from scanf that is convenient to be string.
I am passing the values one by one, from the string to the unsigned short with a for loop.
The programs works ok but I am getting warning messages.
"Warning passing argument of strcmp from incobatible pointer type"
and "expected const char * but argument is of type short unsigned int".
I can't seem to find how to pass from a string to unsigned short without warnings.
A short version of my program is here so that you have a clearer view.
Warnings are at lines 28,43.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int i, j, numberofseats;
char phone[11];
char *p;
unsigned short tempphone[10];
typedef struct
{
  char fullname[40];
  unsigned short phonenr[10];
  unsigned int seatnr;
} PASSENGERS;

int main()
{
  PASSENGERS passenger[53];
  printf("Enter Passenger's Phone Nr:");
  scanf("%s", phone);
  i = 0;
  for (p = phone; *p != '\0'; p++)
  {
    (tempphone[i]) = *p - '0';
    i++;
  }
  for (j = 0; j < numberofseats; j++)
  {
    if (strcmp(tempphone, passenger[j].phonenr) == 0)
      printf("Passenger %s has Seat Nr %u already Booked", passenger[j].fullname, passenger[j].seatnr);
  }
}

A: You can use memcmp or casting to char* and use strcmp.
Keep in mind that memcmp requires the size of memory that will be compared as third parameter.
You can use memcmp like this,
memcmp(tempphone, passenger[j].phonenr, sizeof(tempphone));

However, it can result in wrong comparison if the size of the compared phone numbers are not the same and if one ends with the number 0.
Think about the case tempphone is 12345 and passenger[j].phonenr is 1234500000.
memcmp may judge the phone numbers are the same if you don't forget to initiate varibables to 0. You need another variable to keep the length of the phone number, of course, it doesn't matter if the phone numbers are fixed always.
I would keep phone numbers in array of chars instead of array of shorts and use strcmp. Phone numbers are numbers but they are not the objects of mathmatical operations like add or divide. They contains information similar to names.


text:
Q: access 2007 how to return string from function into "in" statement Could you please help me with this problem?
I have a ComboBox in Form and I want return these values into in statement in SQL query:
SELECT *
FROM [Actual_list query]
WHERE ((([Actual_list LSC query].[place]) In (([Forms]![Internal forms]![Places].Value))));

A: You will need to build your SQL in VBA. You can get the list from the combo.
This is for a numeric list, a list of strings needs quotes.
For Each itm In Me.PlacesListbox.ItemsSelected
  listofvalues = listofvalues & "," & Me.PlacesListbox.Column(0, itm)
Next

listofvalues = Mid(listofvalues,2)

sSQL="SELECT * FROM [Actual_list query] " _
    & "WHERE [Actual_list LSC query].[place] In (" & listofvalues & ")"


text:
Q: "Object has no method 'getBounds'" error in OpenLayers I'm using this code to draw a point on a map:
function addPointToMap(pMap){
    var coordinates = new Array();

    // Style Point
    var style_blue = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']);
    style_blue.strokeColor = "blue";
    style_blue.fillColor = "blue";

    // Make Point
    coordinates.push(new OpenLayers.Geometry.Point(33, 33));
    var pointFeature =  new OpenLayers.Feature.Vector(coordinates, null, style_blue);

    // Layer
    var pointsLayer = new OpenLayers.Layer.Vector("Points Layer");
    pointsLayer.addFeatures([pointFeature]);
    pMap.addLayer(pointsLayer);
}

I'm getting this error from the console:
Uncaught TypeError: Object POINT(33, 33) has no method 'getBounds'

What am I doing wrong?

A: The answer is to add a multipoint geometry:
function addPointToMap(pMap){
            var coordinates = new Array();

            // Style Point
            var style_blue = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']);
            style_blue.strokeColor = "blue";
            style_blue.fillColor = "blue";

            // Make Point
            coordinates.push(new OpenLayers.Geometry.Point(lon, lat));
            var pointsGeometry = new OpenLayers.Geometry.MultiPoint(coordinates);
            var pointFeature =  new OpenLayers.Feature.Vector(pointsGeometry, null, style_blue);

            // Layer
            var pointsLayer = new OpenLayers.Layer.Vector("Points Layer");
            pointsLayer.addFeatures([pointFeature]);
            pMap.addLayer(pointsLayer);
        }

A: For the sake of completeness, I received a similar error while adding a polygon (not a point) from raw WKT data. The error that there are no bounds occur because the object was of the wrong type.
When you call addFeatures, it expects an array of OpenLayers.Feature.Vector objects, which are created by Format.read.
var wkt_parser = new OpenLayers.Format.WKT();
var wkt_data_parsed = wkt_parser.read(some_raw_wkt_data_string);
layer.addFeatures([wkt_data_parsed]);

A: Does your map have a 'baselayer'? Otherwise you should add option 'alloverlays'=true to your map options. I'm not sure if this solves your problem though...


text:
Q: how to provide input while running .sh interactive script using python subprocess i am running a scripts using python that prompts for password and path while executing. When running the scripts from the command line, the behavior is below:
# obfuscatePassword.sh
[Password to obfuscate:]
[Path of password file to be created:]passwd.txt
Password file successfully created at passwd.txt
#

I am wondering, I am not able to provide the input data from the python subprocess. Seems the way I am trying to provide those inputs using stdin isn't working. Please see below code:
-----
-----
obfuscatePassword = subprocess.Popen(['obfuscatePassword.sh'],
                                     stdin=subprocess.PIPE,
                                     stdout=subprocess.PIPE,
                                     stderr=subprocess.PIPE,
                                     universal_newlines=True)
obfuscatePassword.stdin.write(password)
obfuscatePassword.stdin.write(passwordFilePath)
stdout, stderr = obfuscatePassword.communicate('through stdin to stdout')

-----
-----

the execution just hangs in console and I have to press ctrl + C to end the python program.
Can any one of you help me understand where I am coding wrong? Thanks very much in advance.


text:
Q: How do I refer to existing footnotes inside a caption? I have a footnote in my latex text that that I am reusing a lot. This article on texfaq.org helped me how to do that. However, sometimes I need to refer to the same footnote within, e.g., a figure caption. Latex document example:
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{graphicx}
\usepackage{hyperref}
\usepackage{footmisc}
\usepackage{lipsum}

\begin{document}
\section*{My text}

Here is text\footnote{Footnote: blah\dots} \\
Here is more text\footnote{\label{fn:info} Footnote: blah blah\dots}

\begin{figure}[h]
    \centering
    \includegraphics[width=0.4\linewidth]{example-image-a}
    % \caption{Important remark\footref{fn:repeat}} %% With footref
    \caption{Important remark\footnotemark[\ref{fn:info}]} %% With footnoteremark
    \label{fig:example-image-a}
\end{figure}

\end{document}

This seems to not work that great. Using \footnoteremark yields:

Argument of @caption has an extra }.

If I try using a \footref (using the "footmisc" package), I get:

Missing \endcsname inserted.

Comment in/put the "caption" lines in the example to see the different outputs. How can I use any of these commands inside captions? If I had to choose, I'd prefer an answer for \footref, as I found that to be neater. Thanks.

A: It is not clear, what is your problem. Solution with commented caption work fine:
\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage{graphicx}
\usepackage{footmisc}
\usepackage{lipsum}
\usepackage{hyperref}

\begin{document}
\lipsum[1-2]
\section*{My text}

Here is text\footnote{Footnote: blah\dots} \\
Here is more text\footnote{\label{fn:info} Footnote: blah blah\dots}

\begin{figure}[h]
    \centering
    \includegraphics[width=0.4\linewidth]{example-image-a}
    \caption{Important remark \footref{fn:info}.} %% With footnoteremark
    \label{fig:example-image-a}
\end{figure}

\end{document}

Note: package hyperref had to be loaded last (with rare exception)- Above MWE produce:

A: You don't need anything special in principle to refer to a footnote. You can simply include a \label in the footnote and refer to it using \ref in the caption of the figure. Here is an example:
\documentclass[11pt,a4paper]{article}
\usepackage{geometry}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{amssymb}
\usepackage{graphicx}

\usepackage{lipsum}

\begin{document}
\textbf{Label in caption}

\lipsum*[2]\footnote{A footnote not related to any figure.}

\lipsum*[3]\footnote{\label{fnInfo} Important information that can be used by different figures.}

\begin{figure}[h]
\centering
\includegraphics[width=0.4\linewidth]{example-image-a}
\caption{See footnote \ref{fnInfo} for details.}
\label{fig:example-image-a}
\end{figure}

\end{document}

A: While the answer by @Zarko pointed out what the issue was (package loading order), the answer by @Andre inspired me to create my own solution that worked fine.
\newcommand{\reffootnote}[1]{$^{\scriptsize \textrm{\ref{#1}}}$}
This creates a command that takes a ref, formats the size and superscripts it. It works anywhere and is quite simple.


text:
Q: Call function once across multiple instances of a class I have been looking around for a while now and can't seem to find an answer to this.
So, if I have several instances of a class, how can I call a function only once from all instances of that class?
For example, if I have a function called myFunc() within a class called myClass and two instances of that class called class1 and class2, then
class1.myFunc() should return 1,
class2.myFunc() should return 0, and
class1.myFunc() should return 0.
How would I do this?
class myClass{
public:
    myClass(){}
    int myFunc(){
        if (myFuncHasBeenCalled){
            return 0;
        }
        else{
            return 1;
        }
    }
}

myClass class1;
myClass class2;
class1.myFunc(); //would output 1
class2.myFunc(); //would output 0
class1.myFunc(); //would output 0

A: You can achieve that by

*

*introducing a class variable, using static keyword for it in class declaration

*define the class variable in a (separate) code file, with initialisation

*check it inside the function, if 0 output 1 else 0

*increase (or set to non-zero) afterwards

*be careful, using synchronisation mechanisms, in case the calls might be from different contexts/threads/tasks/processes (whatever is applicable in your environment)

(If you show your attempts with static variables and explain the problems you had, this could become more detailed.)

A: You have several options available: the idea is that you need to have some value that can be accessed independently of the instances of the class. static is the way to do this in all cases (except when it's not).
Option one is best option -- static variable in member functions
The approach I would recommend is using a static variable in the member function; this avoids polluting the class itself and makes it easier for you to maintain a consistent ABI as well as a consistent API, across updates. It is very easy to reason about your code as you're not allowing anything else to access the variable.
Example:
struct S {
    int F() const {
         static int n = 1;
         if (n == 1) {
              n = 0;
              return 1;
         }

         return n;
    }
};

Option two is bad option -- static variable in class
An alternative, which seems to be popular, is to keep a static member variable. This allows you do to the same thing as the previous example, but makes it harder to maintain the API and the ABI across upgrades. It also makes it harder to reason about your code and makes it easier to introduce bugs -- a static member variable is not much different from a global variable.
Example:
struct S {
    static int n;
    int F() const {
        if (n == 1) {
            n = 0;
            return 1;
        }

        return n;
    }
};

int S::n = 1;

Option three is worst option -- global variables
The worst alternative is to use a global variable. I'm not going to give you an example of this -- don't do it. If you must do it anyway (you don't), declare your variables in an anonymous namespace in your .cpp file.
namespace {
    int n = 0
}

Options four -- good option
Another approach is to use a static member function. This functions is fully independent of all instance of the class. The only difference in the implementation is that you add static to the function declaration -- otherwise, you can use the first two options. This won't be possible in all situations though.
Caveats and other notes
If you need to use the variable to communicate state between two functions, you have to use one of the global options and cannot use a static variable in a member function.
In all cases, if you're not modifying the instance, you should mark your functions const.
You should really use std::atomic variables
You should use some sort of mechanism that guarantees that your code is threadsafe.


text:
Q: iPad DEP asking for credentials - Cisco Meraki MDM I have been using Cisco Meraki for my MDM and it has been working great. I just bought a bunch of new iPads and am setting up DEP for the first time.  I have done all the steps required: Added the order to my Apple DEP account, pushed them to my Cisco Meraki MDM and assigned settings.
Now on the iPad during initial setup I get to a step that says that my organization is going to automatically setup this iPad (which is good).  The next step asks for credentials in a Username and Password.  I have tried my organization ones, my MDM ones but do not know what this password would be for.
Watching this YouTube video, the iPad here does not have this step. I have done everything the same in this video.
Any suggestions?
EDIT: Adding some photos from the iPad setup:
After "Setup iPad as New iPad"

The blanked out bits are my organization name.

A: After ringing Apple support (1.5 hours on hold...) they were able to help me find a configuration error in Cisco Meraki.
Under Systems manager --> Configuration --> General --> User authentication settings.  I had it set to Active Directory authentication.
This is an extra level of security you can add to the DEP process where users must enter their credentials against an AD or OD server.  However for me the link to my AD server was not valid.
After fixing it was all good.


text:
Q: Problems to access a recent a vue app deployed in docker container This is my second VUE web application deploy which I can't access. Inside Docker host Linux running curl localhost:8081, curl: (56) Recv failure: Connection reset by peer
Dockerfile:
FROM node:12

WORKDIR /app_teste

COPY package*.json ./

RUN npm --version

RUN npm install

COPY . .

EXPOSE 8081

CMD ["npm","run","serve"]

dockercompose.yml:
version: '3'
services:
  website:
    build: .
    ports:
      - "8081:8081"
    container_name: dexter_g_website

I was reading here some topics similars which says about binding to 0.0.0.0 would work, however it never happens. Anyone can help/suggest anything?
docker port dexter_g_webiste
8081/tcp -> 0.0.0.0:8081

A: Based on Vue CLI documentation, the default port for serve command is 8080.
If you want to serve it to port 8081, try
CMD npm run serve --port 8081

Some more debugging tips:
You can run curl command inside the docker container to debug your app.

*

*SSH into the running container

docker-compose exec -it <container_id> sh

*Install CURL

*curl the URL and see which is working
curl http://localhost:8080
curl http://localhost:8081


text:
Q: Is GetLastError() kind of design pattern? Is it good mechanism? Windows APIs uses GetLastError() mechanism to retrieve information about an error or failure. I am considering the same mechanism to handle errors as I am writing APIs for a proprietary module. My question is that is it better for API to return the error code directly instead? Does GetLastError() has any particular advantage? Consider the simple Win32 API example below:
HANDLE hFile = CreateFile(sFile,
    GENERIC_WRITE, FILE_SHARE_READ,
    NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL);

if (hFile == INVALID_HANDLE_VALUE)
{
    DWORD lrc = GetLastError();

    if (lrc == ERROR_FILE_EXISTS)
    {
          // msg box and so on
    }
}

As I was writing my own APIs I realized GetLastError() mechanism means that CreateFile() must set the last error code at all exit points. This can be a little error prone if there are many exit points and one of them maybe missed. Dumb question but is this how it is done or there is some kind of design pattern for it?
The alternative would be to provide an extra parameter to the function which can fill in the error code directly so a separate call to GetLastError() will not be needed. Yet another approach can be as below. I will stick with the above Win32 API which is good example to analyzer this. Here I am changing the format to this (hypothetically).
result =  CreateFile(hFile, sFile,
    GENERIC_WRITE, FILE_SHARE_READ,
    NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL);

if (result == SUCCESS)
{
   // hFile has correct value, process it
}
else if (result == FILE_ALREADY_EXIT )
{
   // display message accordingly
  return;
}
else if ( result == INVALID_PATH )
{
   // display message accordingly.
  return;
}

My ultimate question is what is the preferred way to return error code from an API or even just a function since they both are the same?

A: The GetLastError pattern is by far the most prone to error and the least preferred.
Returning a status code enum is a better choice by far.
Another option which you did not mention, but is quite popular, would be to throw exceptions for the failure cases. This requires very careful coding if you want to do it right (and not leak resources or leave objects in half-set-up states) but leads to very elegant-looking code, where all the core logic is in one place and the error handling is neatly separated out.

A: I think GetLastError is a relic from the days before multi-threading. I don't think that pattern should be used any more except in cases where errors are extraordinarily rare. The problem is that the error code has to be per-thread.
The other irritation with GetLastError is that it requires two levels of testing. You first have to check the return code to see if it indicates an error and then you have to call GetLastError to get the error. This means you have to do one of two things, neither particularly elegant:
1) You can return a boolean indicating success or failure. But then, why not just return the error code with zero for success?
2) You can have a different return value test for each function based on a value that is illegal as its primary return value. But then what of functions where any return value is legal? And this is a very error-prone design pattern. (Zero is the only illegal value for some functions, so you return zero for error in that case. But where zero is legal, you may need to use -1 or some such. It's easy to get this test wrong.)

A: I have to say, I think the global error handler style (with proper thread-local storage) is the most realistically applicable when exception-handling cannot be used. This is not an optimal solution for sure, but I think if you are living in my world (a world of lazy developers who don't check for error status as often as they should), it's the most practical.
Rationale: developers just tend to not check error return values as often as they should. How many examples can we point to in real world projects where a function returned some error status only for the caller to ignore them? Or how many times have we seen a function that wasn't even correctly returning error status even though it was, say, allocating memory (something which can fail)? I've seen too many examples like these, and going back and fixing them can sometimes even require massive design or refactoring changes through the codebase.
The global error handler is a lot more forgiving in this respect:

*

*If a function failed to return a boolean or some ErrorStatus type to indicate failure, we don't have to modify its signature or return type to indicate failure and change the client code all over the application. We can just modify its implementation to set a global error status. Granted, we still have to add the checks on the client side, but if we miss an error immediately at a call site, there's still opportunity to catch it later.

*If a client fails to check the error status, we can still catch the error later. Granted, the error may be overwritten by subsequent errors, but we still have an opportunity to see that an error occurred at some point whereas calling code that simply ignored error return values at the call site would never allow the error to be noticed later.
While being a sub-optimal solution, if exception-handling can't be used and we're working with a team of code monkeys who have a terrible habit of ignoring error return values, this is the most practical solution as far as I see.
Of course, exception-handling with proper exception-safety (RAII) is by far the superior method here, but sometimes exception-handling cannot be used (ex: we should not be throwing out of module boundaries). While a global error handler like the Win API's GetLastError or OpenGL's glGetError sounds like an inferior solution from a strict engineering standpoint, it's a lot more forgiving to retrofit into a system than to start making everything return some error code and start forcing everything calling those functions to check for them.
If this pattern is applied, however, one must take careful note to ensure it can work properly with multiple threads, and without significant performance penalties. I actually had to design my own thread-local storage system to do this, but our system predominantly uses exception-handling and only this global error handler to translate errors across module boundaries into exceptions.
All in all, exception-handling is the way to go, but if this is not possible for some reason, I have to disagree with the majority of the answers here and suggest something like GetLastError for larger, less disciplined teams (I'd say return errors through the call stack for smaller, more disciplined ones) on the basis that if a returned error status is ignored, this allows us to at least notice an error later, and it allows us to retrofit error-handling into a function that wasn't properly designed to return errors by simply modifying its implementation without modifying the interface.

A: If your API is in a DLL and you wish to support clients that use a different compiler then you then you cannot use exceptions. There is no binary interface standard for exceptions.
So you pretty much have to use error codes. But don't model the system using GetLastError as your exemplar. If you want a good example of how to return error codes look at COM. Every function returns an HRESULT. This allows callers to write concise code that can convert COM error codes into native exceptions. Like this:
Check(pIntf->DoSomething());

where Check() is a function, written by you, that receives an HRESULT as its single parameter and raises an exception if the HRESULT indicates failure. It is the fact that the return value of the function indicates status that allows this more concise coding. Imagine the alternative of returning the status via a parameter:
pIntf->DoSomething(&status);
Check(status);

Or, even worse, the way it is done in Win32:
if (!pIntf->DoSomething())
    Check(GetLastError());

On the other hand, if you are prepared to dictate that all clients use the same compiler as you, or you deliver the library as source, then use exceptions.

A: Overall, it's a bad design. This is not specific to Windows' GetLastError function, Unix systems have the same concept with a global errno variable. It's a because it's an output of the function which is implicit. This has a few nasty consequences:

*

*Two functions being executed at the same time (in different threads) may overwrite the global error code. So you may need to have a per-thread error code. As pointed out by various comments to this answer, this is exactly what GetLastError and errno do - and if you consider using a global error code for your API then you'll need to do the same in case your API should be usable from multiple threads.

*Two nested function calls may throw away error codes if the outer function overwrites an error code set by the inner.

*It's very easy to ignore the error code. In fact, it's harder to actually remember that it's there because not every function uses it.

*It's easy to forget setting it when you implement a function yourself. There may be many different code paths, and if you don't pay attention one of them may allow the control flow to escape without setting the global error code correctly.
Usually, error conditions are exceptional. They don't happen very often, but they can. A configuration file you need may not be readable - but most of the time it is. For such exceptional errors, you should consider using C++ exceptions. Any C++ book worth it's salt will give a list of reasons why exceptions in any language (not just C++) are good, but there's one important thing to consider before getting all excited:
Exceptions unroll the stack.
This means that when you have a function which yields an exception, it gets propagated to all the callers (until it's caught by someone, possible the C runtime system). This in turn has a few consequences:

*

*All caller code needs to be aware of the presence of exceptions, so all code which acquires resources must be able to release them even in the face of exceptions (in C++, the 'RAII' technique is usually used to tackle them).

*Event loop systems usually don't allow exceptions to escape event handlers. There's no good concept of dealing with them in this case.

*Programs dealing with callbacks (plain function pointers for instance, or even the 'signal & slot' system used by the Qt library) usually don't expect that a called function (a slot) can yield an exception, so they don't bother trying to catch it.
The bottom line is: use exceptions if you know what they are doing. Since you seem to be rather new to the topic, rather stick to return codes of functions for now but keep in mind that this is not a good technique in general. Don't go for a global error variable/function in either case.

A: Exception handling in unmanaged code is not recommended. Dealing with memory leaks without exceptions is a big issue, with exception it becomes nightmare.
Thread local variable for error code is not so bad idea, but as some of the other people said it is a bit error prone.
I personally prefer every method to return an error code. This creates inconvenience for functional methods because instead of:
int a = foo();

you will need to write:
int a;
HANDLE_ERROR(foo(a));

Here HANDLE_ERROR could be a macro that checks the code returned from foo and if it is an error propagates it up (returning it).
If you prepare a good set of macros to handle different situations writhing code with good error handling without exception handling could became possible.
Now when your project start growing you will notice that a call stack information for the error is very important. You could extend your macros to store the call stack info in a thread local storage variable. That is very useful.
Then you will notice that even the call stack is not enough. In many cases an error code for "File not found" at line that say fopen(path, ...); does not give you enough information to find out what is the problem. Which is the file that is not found. At this point you could extend your macros to be able to store massages as well. And then you could provide the actual path of file that was not found.
The question is why bother all of this you could do with exceptions. Several reasons:

*

*Again, Exception handling in unmanaged code is hard to do right

*The macro based code (if done write) happens to be smaller and faster than the code needed for exception handling

*It is way more flexible. You could enable disable features.

In the project that I am working at the moment I implemented such error handling. It took me 2 days to put in a level to be ready to start using it. And for about a year now I probably spend about 2 weeks total time of maintaining and adding features to it.

A: You should also consider a object/structure based error code variable. Like the stdio C library is doing it for FILE streams.
On some of my io objects for example, i just skip all further operations when the error state is set so that the user is fine just when checking the error once after a sequence of operations.
This pattern allows you to finetune the error handling scheme much better.
One of the bad designs of C/C++ comes to full light here when comparing it for example with googles GO language. The return of just one value from a function. GO does not use exceptions instead it always returns two values, the result and the error code.
There is a minor group of people who think that exceptions are most of the time bad and misused because errors are not exceptions but something you have to expect. And it hasn't proved that software becames more reliable and easier. Especially in C++ where the only way to program nowadays is RIIA techniques.


text:
Q: iPhone - Animating "back" to parent controller I want to implement a "Next" feature in my app.  The button appears on a ViewController that is shown by clicking on a row in a UITableView. Ideally what I would like is for Next to do the following (in pseudo code)

*

*Go "back" to the UITableView

*Scroll to next available item in UITableView

*Select that item

I believe I can do 2,3 via selectRowAtIndexPath (please feel free to correct me if I am wrong) but I am unsure how to do Step 1.  I will also have to target a method in the UITableView rather than the UIViewController that hosts the Button.  How would I achieve this?
Update:
I can now target the rootViewController but now do I actually show it? (For reference here is my code, thanks to this question)
NSArray *viewControllers = self.navigationController.viewControllers;
UIViewController *rootViewController = [viewControllers objectAtIndex:viewControllers.count - 2];

UIBarButtonItem *nextButton = [[UIBarButtonItem alloc] initWithTitle:@"Next" style:UIBarButtonItemStyleDone target:rootViewController action:@selector(nextButton:)];

Update 2
I now have the back animation working but it keeps the navigation bar intact, how do I also set this back to the correct (rootViewController) one?
[self.navigationController popToRootViewControllerAnimated:YES];

A: If you have situation like this:

*

*RootViewController - tableView

*NextviewController - some view with Next button which shows after the you click on tableView

When you issue [self.navigationController popToRootViewControllerAnimated:YES]; from the 2. controller by pressing the Next button, it will bring RootViewController to the screen.
Now, on the RootViewController you have to "detect" back action (perhaps in ViewWillAppear) and continue with your steps 2. and 3.


text:
Q: Navbar not aligning to element below it, why? Hosting Folder
If you click the link then click on "all.html", you should see an unfinished navbar with the two items "Sample" and "Text". You should also see the fact that the blue padding cuts into the white background below it.
I've tried playing with the margins and padding of all the elements of and inside the #topnav div to no avail. I've tried changing display, float, and text-align, but that creates more problems if it even solves the current problem. I've tried multiple tutorials and have rewritten both the html and css for this navbar twice at this point, yet I keep getting stuck on this one issue: The blue part of the navbar cuts into the white. The navbar should look as it does here.
Could anyone tell me why the blue is cutting into the white, even with appropriate margin and padding widths? Thank you! (Note that the page is using Bootstrap v3.3.1)
HTML:

           Sample

            Text

CSS:
#topnav{
    display: inline;
}
#topnav *{
    display:inherit;
}
#topnav ul{
    list-style-type: none;
    text-align: center;
    margin: 0;
    margin-bottom: 55px;
    background-color: rgb(0,93,164);
    padding: 15px;
}
#topnav li{
    display: inline-block;
    margin:0;
    padding: 0;
}
#topnav a{
    text-decoration: none;
    color:white;
    margin: 0;
    padding: 0;
}
#topnav a:hover{
    background-color:black;
}

A: This is because your ul element has display: inline. Change it to inline-block or block:
#topnav ul {
  display: block;
}

A: #topnav ul {
    padding-bottom: 0px;
}


text:
Q: How can I check for missing files in R? I have a folder full of files with these names
ts.01094000.crest
ts.01100600.crest

I read dataframe DFX and try to find corresponding files with that filename and perform some operations. If it doesn't exist, I want to skip it and capture it's name. If it exists, I want to move to the else statement. But I am getting this error
Error in if (!file.exists(grep(dfx$gauge[i], allCrestFiles, value = T))) { :
  argument is of length zero

Code:
allFiles <- list.files(path='F:/files/', full.names = TRUE)

a<-0

for(i in 1:nrow(dfx))
{
  if(!file.exists(grep(dfx$gauge[i], allFiles, value = T)))
  {
    a[i]<- grep(dfx$gauge[i], allFiles, value = T)
    next
  }

  else
  {
   pFile <- grep(dfx$gauge[i], allFiles, value = T)
   pDat <- fread(pFile)
  }
}

dfx
structure(list(gauge = c(1094000L, 1100600L, 1100600L, 1100600L,
1100600L, 1100600L, 1100600L, 1100600L, 1100600L, 1100600L),
    eventID = c(2L, 6L, 10L, 43L, 52L, 53L, 60L, 62L, 70L, 71L
    ), start = c("5/14/2006 21:00", "10/21/2011 6:15", "8/29/2011 13:00",
    "5/14/2002 19:00", "9/28/2008 9:00", "7/24/2008 23:30", "5/26/2005 9:15",
    "9/19/2004 15:30", "5/31/2002 5:30", "6/24/2003 1:45"), end = c("5/16/2006 17:45",
    "10/22/2011 3:45", "8/30/2011 18:45", "5/16/2002 0:15", "9/29/2008 22:00",
    "7/27/2008 13:00", "5/28/2005 6:00", "9/20/2004 11:45", "5/31/2002 16:00",
    "6/24/2003 21:15"), peakt = c("5/15/2006 14:00", "10/21/2011 20:45",
    "8/29/2011 22:45", "5/15/2002 7:00", "9/28/2008 22:15", "7/25/2008 21:30",
    "5/27/2005 4:15", "9/19/2004 23:15", "5/31/2002 10:15", "6/24/2003 9:30"
    ), fd = c(44.75, 21.5, 29.75, 29.25, 37, 61.5, 44.75, 20.25,
    10.5, 19.5), tp = c(17, 14.5, 9.75, 12, 13.25, 22, 19, 7.75,
    4.75, 7.75), rt = c(27.75, 7, 20, 17.25, 23.75, 39.5, 25.75,
    12.5, 5.75, 11.75), startTime = structure(c(1147640400, 1319177700,
    1314622800, 1021402800, 1222592400, 1216942200, 1117098900,
    1095607800, 1022823000, 1056419100), tzone = "UTC", class = c("POSIXct",
    "POSIXt")), peakTime = structure(c(1147701600, 1319229900,
    1314657900, 1021446000, 1222640100, 1217021400, 1117167300,
    1095635700, 1022840100, 1056447000), tzone = "UTC", class = c("POSIXct",
    "POSIXt")), endTime = structure(c(1147801500, 1319255100,
    1314729900, 1021508100, 1222725600, 1217163600, 1117260000,
    1095680700, 1022860800, 1056489300), tzone = "UTC", class = c("POSIXct",
    "POSIXt"))), row.names = c(NA, -10L), .Names = c("gauge",
"eventID", "start", "end", "peakt", "fd", "tp", "rt", "startTime",
"peakTime", "endTime"), class = "data.frame")

WORKING SOLUTION
  if((length(v<-grep(dfx$gauge[i], allFiles, value = T))>0 && !file.exists(v))
     {
      a[i]<- dfx$gauge[i]
      next
  }

POSSIBLE SOLUTION THAT WORKS
allFiles <- list.files(path='F:/files/', full.names = TRUE)

a<-0

for(i in 1:nrow(dfx))
{
  fileNamex <- grep(dfx$gauge[i], allFiles, value = T)
  if(identical(fileNamex, character(0))
  {
    a[i]<- dfx$gauge[i]
    next
  }

  else
  {
   pDat <- fread(fileNamex)
  }
}

ERROR MESSAGE: 'input' must be a single character string containing a file name, a command, full path to a file, a URL starting 'http[s]://', 'ftp[s]://' or 'file://', or the input data itself
Why is fread getting triggered? What am I doing wrong with the control?

A: Happy to learn better ways to do this. But I think this works.
allFiles <- list.files(path='F:/files/', full.names = TRUE)

a<-0

for(i in 1:nrow(dfx))
{
  fileNamex <- grep(dfx$gauge[i], allFiles, value = T)
  if(identical(fileNamex, character(0))
  {
    a[i]<- dfx$gauge[i]
    next
  }

  else
  {
   pDat <- fread(fileNamex)
  }
}


text:
Q: How do I add custom, dynamic time period averages to Excel Pivot Table? I have an Excel worksheet that has overtime (OT) data for each person in the company summarized per pay period. My objectives in Excel are as follows:

*

*Show a current pay period summary of OT hours by department (sorted with most hours at top); If the solution is within the PivotTable it would be nice to ONLY show the current pay period (and applicable trend averages) if possible

*Provide simple trend data (4 pay period AVG and YTD AVG) to make the current pay period data more relevant.

*Make the analysis/tool/table easy to refresh by simply adding new rows to raw data; this will be provided to an HR admin so it must be user-friendly for updating every time period.

Here is my raw data:

Here is the pivot table:

Ideally, the user could select the current pay period, and that would display the OT sum for the current pay period and the two averages mentioned above.  From there, I would add conditional formatting to improve the UI for the managers/end users of the data.


text:
Q: sql repeat rows for weekend and holidays I have a table A that we import based on the day that it lands on a location. We dont receive files on weekend and public holidays, and the table has multiple countries data so the public holidays vary. In essence we looking to duplicate a row multiple times till it encounters the next record for that ID (unless its the max date for that ID). A typical record looks like this:
Account Datekey Balance
1   20181012    100
1   20181112    100
1   20181212    100
1   20181512    100
1   20181712    100

And needs to look like this (sat, sun & PH added to indicate the day of week):
Account Datekey Balance
1   20181012    100
1   20181112    100
1   20181212    100
1   20181312    100 Sat
1   20181412    100 Sun
1   20181512    100
1   20181612    100 PH
1   20181712    100

Also Datekey is numeric and not a date. I tried a couple solutions suggested but found that it simply duplicates the previous row multiple times without stopping when the next dates record is found. I need to run it as an update query that would execute daily on table A and add missing records when its executed (sometimes 2 or 3 days later).
Hope you can assist.
Thanks

A: This question has multiple parts:

*

*Converting an obscene date format to a date

*Generating "in-between" rows

*Filling in the new rows with the previous value

*Determining the day of the week

The following does most of this.  I refuse to regenerate the datekey format.  You really need to fix that.
This also assumes that your setting are for English week day names.
with t as (
      select Account, Datekey, Balance, convert(date, left(dkey, 4) + right(dkey, 2) + substring(dkey, 5, 2)) as proper_date
      from yourtable
     ),
     dates as (
      select account, min(proper_date) as dte, max(proper_date) as max_dte
      from t
      group by account
      union all
      select account, dateadd(day, 1, dte), max_dte
      from dates
      where dte < max_dte
     )
select d.account, d.dte, t.balance,
       (case when datename(weekday, d.dte) in ('Saturday', 'Sunday')
             then left(datename(weekday, d.dte), 3)
             else 'PH'
        end) as indicator
from dates d cross apply
     (select top (1) t.*
      from t
      where t.account = d.account and
            t.proper_date <= d.dte
      order by t.proper_date desc
     ) t
option (maxrecursion 0);


text:
Q: Use ng-repeat to generate copies of a template and each with different data I am working on an angular project, and I need to create a series of items (called element.html) in a page called elements.html. Basing myself off of what I've read in the official Angular documentation, I've come up with this:
.controller('elementsController, function($http, $scope, $state){

    //each element.html needs a name and an image URl.
    $scope.elements = [
        {name:'John', image: "url_to_img"},
        {name:'Jessie', image: "url_to_img"},
        {name:'Johanna', image: "url_to_img"},
        {name:'Joy', image: "url_to_img"},
        {name:'Mary', image: "url_to_img"},
        {name:'Peter', image: "url_to_img"},
        {name:'Sebastian', image: "url_to_img"},
        {name:'Erika', image: "url_to_img"},
        {name:'Patrick', image: "url_to_img"},
        {name:'Samantha', image: "url_to_img"}
      ];
})

This is element.html

And the elements.html looks like this:

This is where I become stuck. These are my questions:

*

*How can I tell the ng-controller that the template I want used for each of the elements is element.html?

*How can i plug in the data from each element in $scope.elements to each iteration of the ng-repeat?

All I can think of doing is copying the code from element.html and pasting it into elements.html within the ng-repeat div, but this just seems like such a bad thing to do. Both elements.html and element.html are housed in the templates directory. Any help will be appreciated. Thanks.

A: in your element.html

{{element.name}}

in elements.html

Although this works, you might want to put this in a directive instead.

A: To answer you questions:

*

*You can instruct angular to use the template using ng-include:

*The context variable (element in elements) will be inherited by the included template, so you can simply reference element like so:

{{element.name}}

You can find a working sample here: https://plnkr.co/edit/KCkniNJaJB2vZzLqXlCK?p=preview


text:
Q: How do I get the base URL of my current location? I would like to get the base URL of my current location however, I have 2 scenarios.

*

*http://localhost:6111/Page.aspx
Base URL: localhost:6111

*http://localhost/myApp/Page.aspx
Base URL: localhost/myApp
Am hoping to be able to have one solution to retrieve both base URL.
Do you all have any recommendation?
Thank you.

A: Here is what you should do
get the whole path but then exclude the file part
let absUrl = $location.absUrl();
let expected = absUrl.replace('Page.aspx', '');

or if the file name is not the same all the time
let expected = absUrl.replace(/([a-z]+\.[a-z]+)/i, '');

A: For the first case you can do this (as $location API suggest):
// url -> http://localhost:6111/Page.aspx
let host = $location.host();
// host => localhost:6111

For the second case I think you need to use both $location.host() and $location.url(). Then manipulate url to get only first part.
// url -> http://localhost/myApp/Page.aspx
let host = $location.host(); // localhost
let url = $location.url(); // /myApp/Page.aspx
let splittedUrl = url.split('/'); // ["", "myApp", "Page.aspx"]
let resultBaseUrl = host + "/" + splittedUrl[1]; // localhost/myApp

I'm not completely sure for the second solution, test it and give me a feedback!


text:
Q: Comparing Heroku Postgres and Amazon RDS I'm currently trying to figure out what type of database hosting I should use for a new project. Since I'm not the best at managing and configuring servers, Heroku is my go-to PaaS.
However, someone told me I should look into using Amazon RDS as database instead of Heroku Postgres to get more bang for the buck. I've tried to compare the two, but honestly, I can't figure out if it's worth it since their price models are so different and because I'm not sure how a Heroku Standard-0 instance compares to a RDS t1.micro.
I would love to hear some opinions from someone with experience of both Heroku Postgres and Amazon RDS. Generally, is it worth to use RDS when my app will be on Heroku?
Thanks!

A: It depends on how you view the ease vs cost trade-off. I've found that, very roughly, it's half the cost for HA Postgres Databases in RDS vs those in Heroku.
The cost of Standard-0 is $50/month and the cost of the 64 GB storage is included. The cost of db.t1.micro is $0.026/hour is roughly $18.72/month $6.40 for storage.
So, very roughly it would be:
$25.12/month vs $50/month
If I were starting a project, for ease of setup and management I'd start in Heroku Postgres. I would make sure I had a migration plan in place for when the cost became a factor, and then move to RDS.
Cheers,
   John


text:
Q: How to scan through a Flash .swf or .flv file and extract a specified number of frames from it? I would like to be able to

*

*create a folder for the copied video frames

*access the individual frames frome a .flv video file and/or .swf file

*save these frames to the auto-created folder

I assume one would need to do this using Action Script 3 to scan through the .swf and .flv files and extract the frames.
Are there gudies on how to do this?

A: You need to know WHAT frames do you want to extract.  For example:

*

*extract 20 frames in regular interval from the video clip

*extract frames at 15 seconds interval

*extract frames at keyframes (scene changes)

I guess that you don't have to use as3 to extract frames, but can also create the script in some other language.  Central piece to frame extraction could be ffmpeg, as described in this article.

A: If it is as3 solution i would do following
 - make a loader which loads your fla/flv
 - add enter frame event listener to it and on each frame draw loader object to buffer, if you ever done any loading and drawing, this will probably take you 10-20 minutes to set up.
This is pretty much the only straigt-forward solution if you're dealing with code-based animations, videos can be handled in different and easier ways i guess.
You will face the challenge of saving the output tho. Flash player can save images on your computer, however only by prompting you to save the file. You will need to use functions available only in Air player if you want to save anything without prompts.


text:
Q: Is it possible to know when a user has purchased my other apps in iOS 7? I have a number of apps on the store, including several older paid apps. I'm releasing a new one that includes some of the functionality of the old ones via in-app purchase. I really don't want to double charge customers who have paid for the older apps. Is there a way, within my new app, to detect if a user has purchased my old apps, so that I can unlock the corresponding functionality for free?
In the form of an example:
Say I have three apps, A, B, and C.
A user has purchased App A at some time in the past.
Within App C, can I detect that the user has purchased App A in the past, and unlock some functionality accordingly?
I know with custom URL schemes you can string some of this together, but there is no guarantee that the user still has the older apps installed. Or, if they do, there is no guarantee that they would run an update on them so I could add custom URL schemes. Are there other, more elegant, ways to do this? For example are there any StoreKit methods for detecting installs on a per-publisher basis? Or is there a way to do it using the new identifierForVendor stuff with iOS 7?
Any advice would be much appreciated. Thanks.

A: You used to be able to use canOpenURL but that was kind of deprecated.

Up until iOS 9, apps have been able to call these methods on any
  arbitrary URLs. Starting on iOS 9, apps will have to declare what URL
  schemes they would like to be able to check for and open in the
  configuration files of the app as it is submitted to Apple. This is
  essentially a whitelist that can only be changed or added to by
  submitting an update to Apple. It appears that certain common URLs
  handled by system apps, like "http", "https", do not need to be
  explicitly whitelisted.

http://pxlnv.com/linklog/canopenurl-abuse-blocked-in-ios-9/
Now you have to whitelist the URL schemes you want to check - iOS 9 not opening Instagram app with URL SCHEME


text:
Q: The weak*-topology on a set of probability measures and convergence Let $X$ be a locally compact Hausdorff space and let $\mathcal{P}(X)$ denote the set of Borel probability measures on $(X,\mathscr{B}(X))$. By definition (I learnt it from here and here), a sequence of measures $\mu_n$ converges to $\mu$ in the weak* topology if and only if
$$\int f d\mu_n \to \int f d\mu, \forall f\in C_0(X)$$
I wonder if this is equivalent to
$$\mu_n(A) \to \mu(A), \forall A \in \mathscr{B}(X).$$
If there are some mild condition can be added to $X$ (metrizability, separability, etc) under which this is true, please let me know. I am trying to find a counterexample in the case of $X=\mathbb R, [0,1]$,etc.

A: Let $X$ be a compact metrizable space. Then the following are equivalent:
$$1.\ \int f\ d\mu_n\to \int f\ d\mu\text{ for all }f\in C(X)$$$$2.\ \limsup \mu_n(F)\leq \mu(F)\text{ for all }F\subseteq_{\text{closed}}X$$$$3.\ \liminf \mu_n(U)\geq \mu(U)\text{ for all }U\subseteq_{\text{open}}X$$$$4.\ \text{ For every }A\in\mathscr B(X)\text{ with }\mu\big(\text{boundary}(A)\big)=0\text{ we have }\lim\mu_n(A)= \mu(A).$$
Proof of $(1)\implies (2)$: Let $F$ be closed in $X$ and for $k\in\Bbb N$ let $U_k:=\{x\in X:d(x,F)<1/k\}$. Then, $U_k$ are open and decreses to $F$, so $\mu(U_k)\to \mu(F)$. By Uryshon Lemma choose $f_k\in C(X)$ with $0\leq f_k\leq 1$ and $f_k=1$ on $F$ with $f_k=0$ on $X\backslash U_k$. Then, $$\limsup \mu_n(F)\leq \limsup\int f_k\ d\mu_n=\int f_k\ d\mu\leq \mu(U_k)$$$$\implies\limsup\mu_n(F)\leq \mu(F). $$
Proof of $(2)\implies (3)$: Let $U$ be open in $X$. Then, $$\limsup \mu_n(X\backslash U)\leq \mu(X\backslash U)\implies \liminf\mu_n(U)\geq \mu(U). $$
Proof of $(2)\implies (4)$: Write, $\partial A=$ boundary of $A$, $A^o=$ interior of $A$, and $\overline A=$ closure of $A$. Let $\mu(\partial A)=0$. Then, $\mu(A^o)=\mu(A)=\mu(\overline A)$ and $\limsup\mu_n(\overline A)\leq \mu(\overline A)=\mu(A)$ and $\liminf \mu_n(A^o)\geq \mu(A^o)=\mu(A)$. So, we are done.
I do not write  $(4)\implies (1)$, but one can find the proof easily. For example, see  Theorem 6.1 on page 40 of Probability measures on metric spaces written by K.R. Parthasarathy, Academic Press.


text:
Q: Property 'clear' does not exist on type '{}' I am trying to implement below url code in ionic react app that allows the user to sign on a canvas.
https://codesandbox.io/s/react-signature-canvas-example-xevhz?file=/src/App.js
error

TypeScript error in
D:/wamp/www/demos/ionictest/myApp/src/pages/Tab3.tsx(14,39):
Property 'clear' does not exist on type '{}'.  TS2339
    12 | const sigCanvas = useRef({});
    13 |
  > 14 | const clear = () => sigCanvas.current.clear();
       |                                       ^
    15 |
    16 | const save = () =>
    17 |     setImageURL(sigCanvas.current.getTrimmedCanvas().toDataURL("image/png"));

my code
import { IonContent, IonHeader, IonPage, IonTitle, IonToolbar } from '@ionic/react';
import ExploreContainer from '../components/ExploreContainer';
import './Tab3.css';
import ReactDOM from 'react-dom'
import SignaturePad from 'react-signature-canvas'
import React, { useRef, useState } from "react";
import "./sigCanvas.css";

const Tab3: React.FC = () => {

const [imageURL, setImageURL] = useState(null);
const sigCanvas = useRef({});

const clear = () => sigCanvas.current.clear();

const save = () =>
    setImageURL(sigCanvas.current.getTrimmedCanvas().toDataURL("image/png"));

  return (
    <IonPage>
      <IonHeader>
        <IonToolbar>
          <IonTitle>Tab 3</IonTitle>
        </IonToolbar>
      </IonHeader>
      <IonContent fullscreen>
        <IonHeader collapse="condense">
          <IonToolbar>
            <IonTitle size="large">Tab 3</IonTitle>
          </IonToolbar>
        </IonHeader>
        <SignaturePad
              ref={sigCanvas}
              canvasProps={{
                className: "signatureCanvas"
              }}
            />
    <button onClick={save}>Save</button>
    <button onClick={clear}>Clear</button>

    <br />
      {/* if our we have a non-null image url we should
      show an image and pass our imageURL state to it*/}
      {imageURL ? (
        <img
          src={imageURL}
          alt="my signature"
          style={{
            display: "block",
            margin: "0 auto",
            border: "1px solid black",
            width: "150px"
          }}
        />
      ) : null}

      </IonContent>
    </IonPage>
  );
};

export default Tab3;

How can I resolve this?

A: It seems like you're using typescript, UseRef should have a type
const sigCanvas = useRef<any>()

A: As you're using Typescript, you have to provide a type for your ref
const sigCanvas = React.useRef<React.MutableRefObject<any>>();


text:
Q: Value of the Application.StartupPath of a program I have program1 that will boot from program2 like this:
Process.Start(@"C:\myfolder\myprogram.exe");

In the program2 i have a variable with value: Application.StartupPath.
If i launch the program2 with Process.Start(@"C:\myfolder\myprogram.exe") from the program1 on the desktop the Application.StartupPath of myprogram is desktop and not myfolder. Why? Thank you all

A: This sis because you started the program from desktop. It's a bit like the "start in" box from a windows shortcut. I usually use the code below as it'll never be wrong as it looks at where the current executable is located, but you could also start it with processstartinfo and working directory
https://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.workingdirectory(v=vs.110).aspx
string ThisFolder = new FileInfo(System.Reflection.Assembly.GetExecutingAssembly().Location).Directory.FullName;

Regards
Liam


text:
Q: find int in string Ok if I have an string input of     "3           6"
how do I put those two int in an array? what if you have more than one spaces between them?
let's say I want those numbers to be in an array like {3, 6}
is that possible? thanks

A: Try this, using a regular expression to split the input string whenever a sequence of one or more spaces is found, and then convert the resulting String[] to an int[]:
String numberString = "  1   2 34    7 ";
String[] numbers = numberString.split("\\s+");
int[] ints = new int[numbers.length];
for (int i = 0; i < ints.length; i++)
    ints[i] = Integer.parseInt(numbers[i]);

Now the ints array contains the expected values:
System.out.println(Arrays.toString(ints));
> [1, 2, 34, 7]

A: $string = "3 6 4 879";
preg_match_all('/\d+(?=\s*)/', $string, $arr);

Here's a PHP way of doing it.

A: you can used with split for your problem for example :
Program that splits on spaces [C#]
static void Main()

{
string s = "1 3 2 7";
//
// Split string on spaces.
// ... This will separate all the words.
//
string[] words = s.Split(' ');
foreach (string word in words)
{
    Console.WriteLine(word);
}
}

Output
1
3
2
7

A: Scanner sc = new Scanner(mString);
while (sc.hasNextInt()){
    mArrayList.add(sc.nextInt())
}

Then just convert the ArrayList back to an array.


text:
Q: Can we make a parameter compulsory on conditions? As we know we can use ternary operator like ? and : in Dart for control flow, like :
String name  = 1 == 1 ? "Jhon" : "Ryan";

Is there anyway to make a parameter compulsory on condition ?
The Codes Below Did Not Work, It's Here Just For The Example
class Person{
  final String name;
  final int age;
  const Person({ this.name, name != null ? @required this.age : this.age});
}

A: No you cannot do this.
You can have asserts checking conditions, but that would be runtime, not compile-time.
Your best way to make it happen is indeed having different named constructors for different purposes.
With the coming null-safety feature it would be a nightmare anyway. Not necessarily for the compiler, but for the programmer who has to understand it.

A: Annotations like @required can only be added statically, and not depending on conditions.
To me this looks like a case for asserts as mentioned by @nvoigt
class Person{
  final String name;
  final int age;
  const Person({ this.name, this.age}) : assert(name != null || age != null, "either name or age must be provided");
}


text:
Q: windows doesn't startup when I install visual studio emulator for android I installed Xamarin with Visual studio 2015, they worked well until I installed visual studio emulator for android, every time when I install it, windows couldn't start and stuck at windows logo for hours, Windows couldn't boot unless I restore system..
Do you have any suggestion to solve this problem ? or are there any emulator compatible with visual studio instead ?
p.s. my OS is windows 8.1 x64

A: I have only ever been able to get one VS Android emulator to work, but that is mainly because I use VM for Windows and only have 4GB ram assigned to it, and many of the emulator images need almost all of that.
That said, Google's Android emulators have gotten pretty good, especially if you install the Intel HAXM Accelerator included in the Android SDK. Instructions to install the HAXM Accelerator:
https://software.intel.com/en-us/android/articles/installation-instructions-for-intel-hardware-accelerated-execution-manager-windows
And also make sure you update your Android SDK in the SdK Manager to get all of the latest stuff (with the exception of Preview N packages as Xamarin does not fully support N yet, and also do not install Build Tools version 24. there are issues with those build tools and Xamarin at this point. See https://releases.xamarin.com/technical-bulletin-android-sdk-build-tools-24/

A: Most probably this happens due to the Hyper-V. Microsoft emulator requires Hyper-V but if your computer doesn't support it for a reason or another that might very well happen.
To check this theory, enable Hyper-V by yourself (Programs and Features/Turn Windows features on or off, Hyper-V/Hyper-V Platform).
Other emulators don't require Hyper-V, so, if that's a problem you can still pick among Google's (free), Xamarin's (free) and Genymotion (commercial).


text:
Q: Remove polygon line after shapefile reprojection I have a shapefile of the Bering Sea in the Pacific Ocean I've been working with in R. It was originally split down the middle, so I reprojected it to Mollweide to connect them (image example attached). The only problem is that there's still the boundary line down the middle. How would I get rid of it? They aren't two polygons that can be combined with Dissolve for some reason. Any advice would be greatly appreciatined. Here is my code so far:
library(rgdal)
Bering_Sea<- readOGR("Bering_Sea.shp")

Bering_Transform<- spTransform(Bering_Sea, CRS("+proj=moll +lon_0=150 +ellps=WGS84"))

plot(Bering)
plot(Bering_Transform)


text:
Q: Differentiability of $f : \mathbb{R}^n \rightarrow \mathbb{R}^n$, where $|x-y - (f(x) -f(y))| \leq \frac{1}{2}|x-y|$ Question:
If $f : \mathbb{R}^n \rightarrow \mathbb{R}^n$ is a continuous function that satifies $|x-y - (f(x) -f(y))| \leq \frac{1}{2}|x-y|$ for all $x,y \in \mathbb{R}^n$, prove that $f$ is differentiable at 0.
My attempt:
Let $y=0$. Then $|(f(x)-f(0)) - x| \leq \frac{1}{2}|x|$. Then $\frac{|(f(x)-f(0)) - x|}{|x|} \leq \frac{1}{2}$
I know I need to show that $\frac{|(f(x)-f(0)) - Mx|}{|x|} \rightarrow 0$ for some linear transformation $M$, but I'm at a loss as to how to use the condition. In particular, the $\frac{1}{2}$ is fixed, so I don't see how to proceed.

A: Consider
$$
f(x)=\left\{
\begin{array}{ccc}
x+\frac{1}{2}x\sin(1/x) & \text{if} & x\ne 0, \\
0 & \text{if} & x=0.
\end{array}
\right.
$$
Then
$$
|f(x)-f(0)-x|=\left|\frac{1}{2}x\sin(1/x)\right|\le \frac{1}{2}|x|
$$
Clearly, $f$ is not differentiable at $x=0$.
Note. In fact, there exists a much simpler counterexample:
$$
g(x)=x+\frac{|x|}{2}.
$$


text:
Q: knockout, checkbox not working I have table, and I want check/uncheckcheck box not only by clicking on checkbox, but on clicking on anywere in row too.
Code is here: source
But code works well only when I click on row. When I click on checkbox, logic works well but not checkbox.
PS. Value in array selectedAnimals should be animal object, not only ID or Name
PS2. With jQuery
   $("table").on("click", "tbody tr", function(e){
       ko.dataFor(this).isSelected(!ko.dataFor(this).isSelected())
    })

all working well, but I want do it witout jQuery

A: Here's what's happening when you check the checkbox:

*

*Item gets checked & added to the array (correct).

*The add function is called due to event bubbling (the checkbox is in the TR, which has the click function added).

*This function flips the checkbox again, which will cause it to be removed from the list and unchecks it.

You can't prevent the event bubbling when using the checked: binding, so the best way to do this is remove the add function from the whole TR and move it to it's own TD.
Here's the Fiddle.


text:
Q: Symfony: Best place to catch exception (CQRS/DDD) I've a personal application. I use design pattern CQRS/DDD for a API.
Schema:
User --> Controller (dispatch command) --> Command handler --> some services...
In my Rest API controller
$this->dispatch($cmd);

If a throw a exception in services or specification classes for example, ok, I've a listener to catch exception and create JSON response error.
But if I want to develop an interface module with TWIG, I think I will not use my listener because I don't want a JSON response.
Should I used try/catch in my controller of my new interface module ?
SomeController extends AbstractController
{
    public function getObject($id)
    {
         try {
            $this->dispatch($cmd);
        catch(SomeException $ex) {
            $this->render(....)
        }
    }
}

Where is the best place to catch exception for TWIG ?
Thanks.
Edit:
@Cid
if (some conditions && $form->handleRequest($request)->isValid()) --> My handler don't return bool or values.
Imagine this code. Imagine I want share a service between an API and web view app.
class ApiController
{
    public function register()
    {
        $this->dispatch($cmd);
    }
}

class WebController
{
    public function register()
    {
        $this->dispatch($cmd);
    }
}

class SomeHandler implements CommandHandlerInterface
{

    /** @required */
    public RegisterService $service;

    public function __invoke(SomeCommand $command)
    {
        $this->service->register($command->getEmail())
    }
}

class RegisterService
{
    public function register(string $email)
    {
        // Exception here
    }
}

A: So, I think the best place to handle Exception is EventSubscriber, see here: https://symfony.com/doc/current/reference/events.html#kernel-exception
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;

public function onKernelException(ExceptionEvent $event)
{
    $exception = $event->getThrowable();
    $response = new Response();
    // setup the Response object based on the caught exception
    $event->setResponse($response);

    // you can alternatively set a new Exception
    // $exception = new \Exception('Some special exception');
    // $event->setThrowable($exception);
}