Q:

Using AJAX to send form information to another page using a button

Hello I have two files that are supposed to be connected to one another. I want to send an AJAX request to another page that uses a sql query to send form information.
The application that I'm trying to create is a questionnaire with eight questions, each questions has four answers paired together with the same id (qid) and each answer has a value from the database. After you answer eight questions you will see a button that sends an AJAX request to the page test.php, (named submitAJAX).
The problem is that although my connection with AJAX is working, the values from the form are not being sent to my database. Previously I thought that the problem may lie with the form page, but now I I think the problem lies in this file:
test.php (file with json)
<?php
$localhost = "localhost";
$username = "root";
$password = "";
$connect = mysqli_connect($localhost, $username, $password) or die ("Kunde inte koppla");
mysqli_select_db($connect, 'wildfire');
if(count($_GET) > 0){
   $answerPoint = intval($_GET['radiobtn']);
   $qid = intval($_GET['qid']);
$tid = intval($_GET['tid']);
   $sql2 = "INSERT INTO result (qid, points, tid) VALUES ($qid, $answerPoint, $tid)";
   $connect->query($sql2);
   $lastid = $connect->insert_id;
   if($lastid>0) {
    echo json_encode(array('status'=>1));
}
   else{
    echo json_encode(array('status'=>0));
}
}
?>

I think that the problem may lie in the row where:  if($lastid>0) {
$lastid should always be more than 0, but whenever I check test.php I get this message: {"status":0} What's intended is that I get this message: {"status":1}
<html>
    <head>
        <meta charset="utf-8">
    </head>
    <body>
<?php
$localhost = "localhost";
$username = "root";
$password = "";
$connect = mysqli_connect($localhost, $username, $password) or die ("Kunde inte koppla");
mysqli_select_db($connect, 'wildfire');

$qid = 1;
if(count($_POST) > 0){
    $qid = intval($_POST['qid'])+1;

}

?>

<form method="post" action="">
<input type="hidden" name="qid" id="qid" value="<?=$qid?>">
<?php
$sql1 = mysqli_query($connect,"SELECT * FROM question where answer != '' && qid =".intval($qid));
while($row1=mysqli_fetch_assoc($sql1)){
?>
<input type='radio' name='answer1' class="radiobtn" value="<?php echo $row1['Point'];?>">
<input type='hidden' name='tid' class="tid" value="<?php echo $row1['tid'];?>">
<?php echo $row1['answer'];?><br>
<?php
}
?>
<?php if ($qid <= 8) {  ?>
<button type="button" onclick="history.back();">Tillbaka</button>
<button type="submit">Nästa</button>
<?php } else { ?>
<button id="submitAjax" type="submit">Avsluta provet</button>
     <?php } ?>
</form>

<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
  <script type="text/javascript">
function goBack() {
    window.history.go(-1);
}
$(document).ready(function(){
$("#submitAjax").click(function(){
        if($('.radiobtn').is(':checked')) {
            var radiobtn = $('.radiobtn:checked').val();
            var qid = $('#qid').val();
             var answer = $('input[name=answer1]:radio').val();
            $.ajax(
            {
                type: "GET",
                url: 'test.php',
                dataType: "json",
                data: "radiobtn="+radiobtn+"&qid="+qid,
                success: function (response) {
                    if(response.status == true){
                        alert('points added');
                    }
                    else{
                        alert('points not added');
                    }
                }
            });

            return false;
        }
    });
});
  </script>

    </body>

The values that I want to send to my database from test.php are:
qid(int), tid(int), Point(int)
There is a database connection, and my test.php file's sql query should work, but its not sending form information. Is there something that I need to rewrite or fix to make it work?

A:

First, your data parameter in the AJAX call is not using the correct syntax.  You're missing brackets.  It should look like:
data: JSON.stringify({ radiobtn: radiobtn, qid: qid }),

Second, I'd suggest using POST instead of GET:
type: "POST",

which means that you need to look for your data in $_POST['radiobtn'] and $_POST['qid'] on test.php.  NOTE:  you should check for the key you expect using isset() before assigning the value to a variable, like so:
$myBtn = isset($_POST['radiobtn']) ? $_POST['radiobtn'] : null;

Third, for testing, use a console.log() inside your condition that checks for the checkbox being checked in order to verify that condition is working as expected.
if($('.radiobtn').is(':checked')) {
    console.log('here');

UPDATE:
Fourth:  You should specify the content type in your AJAX call, like so:
contentType: "application/json; charset=utf-8",


Q:

New-Item Behavior Changes When Using Runspace to Run Command Remotely

I am using VB.Net to open a Powershell runspace using WSManConnectionInfo. The connection works fine. I am trying to run a New-Item command in order to create a new virtual directory.
New-Item "IIS:\Sites\ExternalInventory FTP\TestVT"  -Type VirtualDirectory -physicalPath "C:\"

The command works fine when running it locally on the server. However, when ran remotely through the runspace I get an error:

A parameter cannot be found that matches parameter name 'physicalPath'.

I initially tried to use use the New-WebVirtualDirectory command to create the virtual directory, but this led to other errors. I need to use New-Item.
What is causing the difference in behavior of the New-Item command, and how can I use it to create a new virtual directory through the runspace?
Note: I have tried other commands through the runspace and they seem to work as expected.
EDITS
I know that the New-Item command does not have the parameter "physicalPath" listed in the docs: https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.management/new-item?view=powershell-6
The New-Item command is used in multiple places in the docs to create virtual directory with the physicalPath parameter. See links
https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.management/new-item?view=powershell-6
https://forums.iis.net/t/1223546.aspx?New+WebVirtualDirectory+does+not+work+when+invoked+remotely+and+a+UNC+path+is+used

A:

As pointed out in the comments, I needed to include the WebAdministration module in my script.
Thanks TheMadTechnitian


Q:

How do I say "我不是太喜欢旅游." in English?

The translator gives the translation is

I don't like traveling very much.

But it sounds like I hate traveling. But I'm just not a traveling enthusiast. If my family need a traveling, I can go with them. I don't initiatively plan to travel.

A:

Try a slightly different expression:
I don't like travelling that much.


Q:

Realm: rearranging list of objects

Please, tell me, how to rearrange items of Realm's list of objects by index? I.e. I'm looking something like
let movingElement = array[oldIndex]
array.removeAtIndex(oldIndex)
array.insert(movingElement, atIndex: newIndex)

if it was with a casual Swift array of something.
But for List in Realm I can not do the same thing:
let realm = try! Realm()
var all = try! Realm().objects(element)
realm.write {
    all.removeAtIndex() // all of type

Another option is to
let realm = try! Realm()
let element = try! Realm().objects(Element)[oldIndex]
realm.write{
    realm.delete(element)
    realm.add(...)   // How to set index to place new object at?
}

But how to insert element in proper place? May be there is a proper method how to move elements of realm of the same type (class) by index?
Thanks in advance!

A:

You cannot do it with query results, as they are unordered (or in a specific order if you sort them). But if you put them into Realm List (which you can store as member in a Realm object), then you can use both move and swap methods to reorder elements.
Here is the API docs for the the List type: https://realm.io/docs/swift/latest/api/Classes/List.html


Q:

Connecting to Azure VM from Azure App Service

I have an Azure virtual machine, on which a process listens on a certain port. A Node.js application on my local computer is able to connect to this process using the VM's public IP address. But the same Node.js application, deployed as an app service on Azure, is apparently not able to connect using any IP address, despite the fact that the VM allows all incoming traffic on all ports.
(Details: The VM process is running "q" (kdb+), and the Node.js application is using the "node-q" package to connect to it. Both the Azure VM and the Azure app service are Linux, but the local version of the app service is on Windows. The Azure app service is able to connect to my Azure SQL database.)
Any insights into this problem would be appreciated.

A:

It was faulty deployment. I didn't include all dependencies in the upload to Azure. Thank you.


Q:

Is this way of fetching data from sqlite correct?

I am using this query to fetch data from sqlite but only one condition is working but not two at same time.
I am also getting some notification that no such column but it exist.
String lquery = "SELECT SUM(totalcalorie) AS LTotal FROM fooditem
WHERE name = ('" + fname + "') AND foodtype = 'Lunch'";

A:

you might be having null values on those places which you are checking while calling..
go through your code again queries seems write.


Q:

How to prevent WCF message logging from eliding the SOAP body?

I have a WCF client for which I need to log messages. I need the complete SOAP envelope of both requests and replies.
My app.config file has logging set up thusly:
<diagnostics>
  <messageLogging logMalformedMessages="false" logMessagesAtServiceLevel="true"
                  logMessagesAtTransportLevel="false" logEntireMessage="true"
                  maxMessagesToLog="100" maxSizeOfMessageToLog="20000000" />
</diagnostics>

The message log is populated correctly... almost!  For the requests only, the SOAP body is elided like this:
<s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" Id="signature_e">...</s:Body>

Does anyone have any idea now to get the full SOAP body into my log?

A:

It turns out that one of the behaviors I had configured for this endpoint (an IClientMessageInspector) was creating a subclass of Message, and that this subclass didn't override OnBodyToString() which is used for logging. The default implementation of OnBodyToString() just prints out ... an ellipsis!
The Message class is a tricky beast indeed.


Q:

How to answer similar questions without getting my answers deleted?

I recently spent a lot time trying to find a way to send SMS messages with C#. I found some questions/answers on StackOverflow that were of some help, but none of them solved my problem completely.
After a tremendous ammount of effort, I managed to solve my problem.
I thought I should give back a little to the community of StackOverflow and help all the people who had this problem by posting my solution on all the questions that I read while I was trying to solve my issue.
If you look at this questions, they are very similar, however, none of them were closed for being duplicates. I thought I could just post the answer on all of them, since my answer was helpful for all of the questions.

SMS application
https://stackoverflow.com/questions/548911/sending-sms/19056864
Send SMS C#.net
SMS Library in C#
Send SMS using C#
https://stackoverflow.com/questions/12840069/net-sms-sending-libraries/19056918
OpenSource .net SMS library
Sending sms and ussd in a C#.net application
Send a cellphone SMS text without the use of a third-party service
Sending SMS text message from an ASP.NET website

At first, I answered this:

If your GSM phone or GSM modem can be accesed with a serial port (e.g. COM8) and AT commands, you can use a library that I made https://github.com/marcogrcr/NET-SMS-Sender.

To my surprise, my answers were deleted. When I read https://stackoverflow.com/help/deleted-answers searching for the reason that my answers were deleted, I thought that my answers were deleted for this particular reason:

barely more than a link to an external site

I also noticed this other reason:

exact duplicates of other answers

But I thought it meant for exact duplicates of other answers in the same question per se, not on different questions.
So I made a more ellaborate answer:

If your GSM phone or GSM modem can be accesed with a serial port (e.g. COM8) and supports AT commands, you can use the SerialPort class to communicate with it.
For example, to send a SMS message in TEXT MODE (not all GSM phones or GSM modems support TEXT MODE), you can do the following:

var telephoneNumber = 3052345678;
var message = "Hello World!";

using (var port = new SerialPort("COM8"))
{
    port.Open();
    Thread.Sleep(500);

    // Sets the mode to TEXT MODE.
    port.Write("AT+CMGF=1\r\n");
    Thread.Sleep(500);

    // Sets the telephone number.
    port.Write(string.Format("AT+CMGS=\"{0}\"\r\n", telephoneNumber));
    Thread.Sleep(500);

    // Sends the SMS message.
    port.Write(string.Format("{0}\x1A", message));
    Thread.Sleep(3000);
}

SMS messages have a limit of 160 characters. If you want to send a message of more than 160 characters, you need to send a special type of SMS messages called concatenated SMS messages.
If your GSM phone or GSM modem does not support TEXT MODE, you need to send the message in PDU MODE. This mode is more commonly supported by GSM phones and GSM modems than TEXT MODE, and you can do things that are not available in TEXT MODE like sending concatenated SMS messages.
The PDU format can be quite complicated to work with if you don't have any prior experience with SMS or low level instructions for bit manipulation.
Since sending messages in PDU MODE is not a trivial task, I made a simple library to help people with this. Please see https://github.com/marcogrcr/NET-SMS-Sender for more information.

Sadly, my answers were deleted once again. Now it became clear to me that the reason they were being deleted was because I was posting the same answer on different questions, no matter if they were not closed for being too similar or duplicates.
I noticed however that on the second time that my answers were deleted, all the questions except for one were tagged as [on hold], and based on this, it means that they are going to be closed.
So, my question is: How should I address this issue in the future if I happen to come across with this situation again?
I'm no expert on the rules of this community so please be nice :) I give my word that I was doing this with the best of my intentions.

A:

If you have the inclination to write the same answer to a lot of questions, something is wrong.  In almost all cases, either the questions are duplicates of each other (if not exact, then close enough to still be duplicates), or your answer isn't adequately answering each of the questions.  Another possibility (which happens to be much of the case here) is that the questions are simply of very low quality; so low that we just don't want them here.
Of the questions that you linked they are just asking for a library, aren't provding any details as to what they've done or reserached, are too broad, etc.  Pretty much none of those questions are questions that we really want here on this site.
The first thing is that you should stop trying to find a bunch of questions that your answer applies to.  Expect to post it exactly once.  Find the best question that you can on that topic, improve it as best you can, and then provide the answer.  If you can't find any real quality questions to which that would be a good answer then ask your own.  Keep in mind that when asking and self-answering a question the question needs to stand on its own as a good question.  It should be a question others would consider of good quality even if there was no answer posted to it.
If there are other related questions of adequate quality that your answer would answer exactly then it probably means you should flag the questions as duplicates.  If they aren't duplicates then it means your answer almost certainly should be tailored to the question at hand.


Q:

Make 2 fixed-width floating divs center-screen

I have two fixed-width divs, first one 'main box' and the other 'other box'
I want them center-screen
and,
when browser-width permits, next to one another.
I achieve the latter by making them float:left but then since they're "out of the flow" I can't make them center screen (by margin: auto on outer div)?

Is it possible some other way?

A:

Please see demo:
http://jsbin.com/jitus/1
When you set .a and .b to inline-block elements, you can set their parent to text-align center. Then this is your requirement.
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>JS Bin</title>

aaa

bbb


Q:

IdentityRole shows an error at the create page

I have included the following line to use IdentityRole predefined table which contains Name and ID field.
@model IEnumerable<Microsoft.AspNet.Identity.EntityFramework.IdentityRole>

I keep getting a number of errors for not recognizing the model.Name which exists at the class IdentityRole.
The errors that I am getting is:
Severity    Code    Description Project File    Line    Suppression State
Error   CS0411  The type arguments for method 'LabelExtensions.LabelFor<TModel, TValue>(HtmlHelper<TModel>, Expression<Func<TModel, TValue>>, object)' cannot be inferred from the usage. Try specifying the type arguments explicitly. 13_Views_Roles_Create.cshtml    C:\Users\xxx\Desktop\xxxxV2\JobBoardSystem\Views\Roles\Create.cshtml    20  Active

Severity    Code    Description Project File    Line    Suppression State
Error   CS0411  The type arguments for method 'ValidationExtensions.ValidationMessageFor<TModel, TProperty>(HtmlHelper<TModel>, Expression<Func<TModel, TProperty>>, string, object)' cannot be inferred from the usage. Try specifying the type arguments explicitly.  13_Views_Roles_Create.cshtml    C:\Users\xxxx\Desktop\JobBoardSystem V2\xxxx\Views\Roles\Create.cshtml  23  Active

The code is the following:
@model IEnumerable<Microsoft.AspNet.Identity.EntityFramework.IdentityRole>

@{
    ViewBag.Title = "Create";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

Create

@using (Html.BeginForm())

{

@Html.AntiForgeryToken()

RoleViewModel

    @Html.ValidationSummary(true, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })

            <input type="submit" value="Create" class="btn btn-default" />

}

        @Html.ActionLink("Back to List", "Index")

        @section Scripts {
            @Scripts.Render("~/bundles/jqueryval")
        }

A:

The create page usually doesn't deal with a list, just with a single model item. Your model should be
@model Microsoft.AspNet.Identity.EntityFramework.IdentityRole


Q:

Security concerns with compiling latex dynamically on a web server

I'm setting up a website which would allow users to use certain select latex commands to build a document. They would then be able to preview the document, which means I would:

parse the text file to make sure only the allowed commands are there
use PHP to send the user's text to the pdflatex command
display the outputted pdf to the user

How secure is this? Is there a better way of doing this?

A:

It's reasonably secure if you don't enable \write18. Of course you should use chroot and ulimit if you are running Unix. See here for the security of TeXLive 2011. And see here for the answer on TeX.SX.


Q:

Subplot colours by column in `pandas`

I am creating a pandas plot using the following code:
plt = table. \
    reindex_axis(index, axis=1). \
    T. \
    plot. \
    bar(
        subplots=True,
        rot=45,
        stacked=False,
        color=colors,
        width=.4,
        legend=False,
        figsize=(20, 10),
        layout=(3, 4),
        sharex=False,
    )

This gives me plots like this:

Want I want is more like this:

Now I'm quite fine with the bars not being stacked but I really would like the colours to be the same. How can I do that?

A:

Color param accepts colors for each subplot as array.
    color=[colors,colors,colors],

In you case will be enough just one item in a list
    color=[colors],


Q:

How to validate string being typed in EditText without discarding intermediate strings?

I'm trying to use TextWatcher and regex for validating user input. Note that I have a complex regex:
edit.addTextChangedListener(new TextWatcher() {
            private final Pattern m_regex = Pattern.compile("([a-zA-Z]{4}[ ]{0,1}){7}");

            @Override
            public void afterTextChanged(Editable s) {
                  String text = s.toString();
                  int length = text.length();

                  if(!m_regex.matcher(text).matches() && length > 0) {
                       s.delete(length - 1, length);
                  }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {}

        });

The problem here is matcher can only check for 2 string states: match and no match with expression provided, but for input validation you also need to check for intermediate state - when a string doesn't match the pattern but doesn't contradict it either. Is there any way I could use my regex for validating string being typed in EditText?

A:

Do a match against another regex. Sorry if the answer seems silly, but as you said before, matcher can only check for 2 string states: match and no match.
EDIT:
I understood better your question. You can do this: test the input versus this regex
^(([a-zA-Z]{4}[ ]{0,1}){0,6}([a-zA-Z]{0,4})|([a-zA-Z]{4}))$

this will validate the text as being inserted. If it is ok let the user continue. Your regex should be used only when the user has finished to input text! -
OR, if you want to check if the user has finished to write do this: match the regex I wrote to see if the text is correct. If ok match yours and, if it matches, the user has finished inserting text.


Q:

Make a hash from two hashes of different size using logical predicate

Suppose I have two hashes of settings. the 'defaults' hash is initialized on startup and 'settings' hash is persisted in database. Not all settings have default, and not all settings are persisted e.g. on first startup, meaning these hashes could have different keys. I need to produce third hash 'all_settings', which will have all keys of those two, with settings key value overriding the default one if both are present:
all_settings[key] = settings[key] || defaults[key]

I've managed to do it with
all_settings = {}
defaults.each{|name, value| all_settings[name] = settings[name] || defaults[name]}
settings.each{|name, value| all_settings[name] = settings[name] || defaults[name]}

But I feel it's kind of dumb. Is there way to do the same thing using shorter and more conscise syntax?

A:

The method you're looking for is merge:
all_settings = defaults.merge(settings)

... will return a new hash containing all of the key-value pairs from defaults, and all of the key-value pairs from settings. If any key is duplicated, it will use the value from settings.


Q:

Films that push the boundaries of Sound Design?

For example in 'Irreversible', the first 30 minutes there is a underlying sound frequency of 27hz - this makes you feel physically sick and disorientates you. Do you guys know of any films that use similar effects? Or something which aids the sound scape to engage further?

A:

The film Altered States has some very interesting sounds from perceptual tests and research done atnStandord... the basic synopsis, a guy starts taking hallucinogens while in a sensory deprivation tank...
from the book Sound on Film:
"the effects came from Stanford University, where they did all kinds of sound experiments and we got the benefit of it. The director, Ken Russell, got the tracks from stanford, John Cornigliano had written the score, and we got to weave them in and out of each other - they were one.."
Were the Stanford sounds used for the low rumbles and the tank-room sounds?
"yes, a lot of them were"
Were those sounds cut by the sound effects editors?
"They weren't edited, they were just laid in en masse by the effects editors. You just got four hundred feet of material"
So the positioning and editing were done during the mix on the dubbing stage?
"Yes"


Q:

Jump Continuity

I am reading Amann and Escher's trilogy on Analysis and at the very beginning of volume II, the authors begin with the definition of a step functions and what it means for a step function to be "jump continuous". Intuitively, I know what this means but the authors use very unfamiliar notation at this point. Specifically, they use $f(a + 0)$ to denote the limit of $f$ as $x$ approaches $a$ from the right (at least, this is what I think they mean by it) I have rewritten the definition as I understand it using notation that is more familiar and it reads:
A function $f:I\rightarrow E$ from the perfect interval I to the Banach space $(E, ||\cdot||)$ is called a step function if $I$ has a partition $\mathcal{P} = (\alpha_0, \dots, \alpha_n)$  such that $f$ is constant on every open interval $(\alpha_{j-1},\dots \alpha_j)$
Moreover, if the limits $\lim \limits_{x \to \alpha^+}{f(x)}$ and $\lim \limits_{x \to \beta^-}{f(x)}$ exist and the limits
$\lim \limits_{x \to a^-}{f(x)}$ and $\lim \limits_{x \to a^+}{f(x)}$ exist for each $a$ in the interior of $I$ then $f$ is said to be
jump continuous
Can anyone comment on the correctness of the above definition and verify that I have interpreted the authors' meaning correctly?

A:

There isn't much more to say to answer this question, except to confirm that you understood the definition correctly.  I also find the notation $f(a+0)$ for the limit from one side of $a$ of the function $f$ quite strange.
Step functions are fundamental for various reasons; among the most elementary is that they are typically used in the development of the Lebesgue integral, although they (well, their `derivatives') are also typically used to motivate the theory of distributions and generalised functions.
Perhaps one can also store a link to the Wikipedia page here.


Q:

PHP Variables not Calculating Correctly

SOURCE: http://pastebin.com/mBJMGean
Variables are still not calculating correctly,
They always reset every time even with using $_SESSION variables.
This is trying to become a slideshow with 2 buttons that control 'next' and 'prev'
The variable controls are Picture ID and then the buttons control what the variable is.
it somehow loops from 3 to 1 and wont move any more.
Help is needed please. Thanks.

A:

You can't have any output before the session_start().  Move it up above your html and try again.


Q:

Wix Custom Actions with WixUI_Minimal

So, I'm trying to, after an application finishes installing (though in truth, it really doesn't matter when the secondary application is run, since it doesn't interact with the installed files during installation), run another program which is bundled with the application.  Pertinent code (with various stuff replaced with "...":
<directory ...>
  <component ...>
  <File Id="IDINST" ... />
  </component>
</directory>
...
<CustomAction Id="IDACTION" FileKey="IDINST" ExeCommand="..." Return="ignore" />
...
<InstallExecuteSequence>
  <Custom Action="IDACTION" After="CostFinalize" />
</InstallExecuteSequence>

I checked the directory and the file was where I expected, but it was not executed after the install process.  In truth I really don't even want that file to be installed, just run and then deleted.  But I'll ignore that for now.  Anyways, I've seen several examples of triggering actions after dialogs but since I'm currently using <UIRef Id="WixUI_Minimal" /> I don't think that's ideal.

A:

CostFinalize happens long before InstallFiles deferred action runs (that actually places the file).  Thus the CustomAction is failing (because the file isn't available) silently (because Return is ignore)
You need your CustomAction scheduled at least after InstallFiles and be deferred or if the CustomAction can't run deferred then it has to be after InstallFinalize (of course, it can't cause rollback after InstallFinalize).


Q:

MarkLogic - mlcp export of JSON documents

MarkLogic version : 9.0-6.2
MLCP - version - 9.0.6
I am trying to export a collection (customer) of JSON documents with mlcp export, using below code. I am not getting any response from mlcp after I execute the script, and the output file is not created.
mlcp.sh export -ssl \
-host localhost \
-port 8010 \
-username uname \
-password pword \
-mode local \
-out_file_path /test/TestFiles/customer.txt \
-collection_filter customer \
-output_type document

I verified that data-hub-STAGING (8010 port) has a collection named customer with 100 JSON documents. The linux user has execute permissions on the script and write permissions on the output path. The user and password are correct.
Interestingly, when I run below mlcp code from the same directory, with the same linux user, I am able to import the documents into data-hub-STAGING
mlcp.sh import -ssl \
-host localhost \
-port 8010 \
-username uname \
-password pword \
-mode local \
-input_file_path /test/TestFiles/Customer \
-input_file_type documents \
-output_collections customer \
-output_uri_prefix /customer/ \
-output_uri_suffix ".json"

Anything wrong with my export code?

A:

Looks like you have a typo: it is -output_file_path, not -out_file_path. Also, the value that follows that parameter is treated as a directory name, and should not exist yet.
HTH!


Q:

Manage Queue in android with service

I have a activity with recycler-view, and each list item has a download button.inside button click event i manage make call for download-service.so how can i manage queue when user click more than one download button with custom notification update.
I have googled and tried some solutions are:
1.How to Manage Queue of Runnable Tasks in Android
2.how to handle a queue in android?? java
3.Best way to update Activity from a Queue
but doesn't find the correct way to implement queue with notification update.
Here is my DownloadService Code:
public class DownloadApkService extends Service {

    private NotificationCompat.Builder notificationBuilder;
    private NotificationManager notificationManager;

    String downloadLocation;

    String appId = null;
    String appLink = null;
    String appName = null;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e("Queue", "queue");

        appId = intent.getStringExtra(Constants.COM_APP_ID);
        appLink = intent.getStringExtra(Constants.COM_APP_LINK);
        appName = intent.getStringExtra(Constants.COM_APP_NAME);

        Thread thread=new Thread(new MyThread(startId));
        thread.start();

        return START_STICKY;
    }

    final class MyThread implements Runnable {

        int service_id;

        MyThread(int service_id) {
            this.service_id = service_id;
        }

        @Override
        public void run() {

            notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

            notificationBuilder = new NotificationCompat.Builder(DownloadApkService.this)
                    .setSmallIcon(R.drawable.ic_list_app_icon)
                    .setContentTitle(appName).setProgress(0, 0, true)
                    .setContentText("Downloading APK")
                    .setOngoing(true)
                    .setAutoCancel(true);
            notificationManager.notify(0, notificationBuilder.build());

            downloadApk();

        }
    }

    private void downloadApk() {

        downloadLocation = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/";
        String fileName = appName + ".apk";
        downloadLocation += fileName;

        File sourceFile = new File(downloadLocation);
        if (sourceFile.exists()) {
            sourceFile.delete();
        }

        Intent intentResponse = new Intent();
        intentResponse.setAction(Constants.ACTION_DOWNLOADING_APK);
        intentResponse.putExtra(Constants.COM_APP_ID, appId);
        intentResponse.putExtra(Constants.COM_APK_DOWNLOAD_PERCENTAGE, "0");
        sendBroadcast(intentResponse);

        new DownloadFileFromURL().execute(appLink);

    }

    public void installApk(Uri uri) {
        Intent install = new Intent(Intent.ACTION_VIEW);
        install.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        install.setDataAndType(uri,
                "application/vnd.android.package-archive");
        DownloadApkService.this.startActivity(install);

    }

    /**
     * Background Async Task to download file
     */
    class DownloadFileFromURL extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Bar Dialog
         */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        /**
         * Downloading file in background thread
         */
        @Override
        protected String doInBackground(String... f_url) {
            int count;
            try {
                Log.e("ULR", f_url[0]);
                URL url = new URL(f_url[0].trim());
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.connect();

                // this will be useful so that you can show a tipical 0-100%
                // progress bar
                int lenghtOfFile = connection.getContentLength();
                Log.e("Length", lenghtOfFile + "");

                // download the file
                InputStream input = connection.getInputStream();

                downloadLocation = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/";
                String fileName = appName + ".apk";
                downloadLocation += fileName;

                // Output stream
                FileOutputStream output = new FileOutputStream(downloadLocation);

                byte data[] = new byte[1024];

                long total = 0;

                while ((count = input.read(data)) != -1) {
                    total += count;
                    // publishing the progress....
                    // After this onProgressUpdate will be called
                    publishProgress("" + (int) ((total * 100) / lenghtOfFile));

                    // writing data to file
                    output.write(data, 0, count);
                }

                // flushing output
                output.flush();

                // closing streams
                output.close();
                input.close();

            } catch (Exception e) {
                Log.e("Error: ", e.getStackTrace().toString());
            }

            return null;
        }

        /**
         * Updating progress bar
         */
        protected void onProgressUpdate(String... progress) {
            // setting progress percentage
            Intent intentResponse = new Intent();
            intentResponse.setAction(Constants.ACTION_DOWNLOADING_APK);
            intentResponse.putExtra(Constants.COM_APP_ID, appId);
            intentResponse.putExtra(Constants.COM_APK_DOWNLOAD_PERCENTAGE, progress[0]);
            sendBroadcast(intentResponse);
        }

        /**
         * After completing background task Dismiss the progress dialog
         **/
        @Override
        protected void onPostExecute(String file_url) {
            // dismiss the dialog after the file was downloaded
            notificationManager.cancel(0);
            installApk(Uri.fromFile(new File(downloadLocation)));

        }

    }
}

any help would be appriciated...

A:

Finally got answer for my own question.
I managed it with Queue class that is in java.util package.
The code i have been used is below:
public class DownloadApkService extends Service {

    private NotificationManager notificationManager = null;

    String downloadLocation;

    String appId = null;
    String appLink = null;
    String appName = null;
    String isApkFromServer = null;

    public boolean isDownloading = false;

    public static Queue<QueueData> downloadQueue = new LinkedList<>();

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        if (isDownloading) {
            QueueData queueData = new QueueData();
            queueData.setAppId(intent.getStringExtra(Constants.COM_APP_ID));
            queueData.setAppLink(intent.getStringExtra(Constants.COM_APP_LINK));
            queueData.setIsApkFromServer(intent.getStringExtra(Constants.COM_APK_FROM_SERVER));
            queueData.setAppName(intent.getStringExtra(Constants.COM_APP_NAME));

            downloadQueue.add(queueData);
            Intent intentQueueingApk = new Intent();
            intentQueueingApk.setAction(Constants.ACTION_QUEUEING_APK);
            sendBroadcast(intentQueueingApk);
            return START_NOT_STICKY;
        } else {
            appId = intent.getStringExtra(Constants.COM_APP_ID);
            appLink = intent.getStringExtra(Constants.COM_APP_LINK);
            appName = intent.getStringExtra(Constants.COM_APP_NAME);
            isApkFromServer = intent.getStringExtra(Constants.COM_APK_FROM_SERVER);
        }
        Thread thread = new Thread(new MyThread());
        thread.start();

        return START_NOT_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (notificationManager != null) {
            notificationManager.cancel(0);
        }
    }

    class MyThread implements Runnable {

        MyThread() {
        }

        @Override
        public void run() {

            notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

            NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(DownloadApkService.this)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle(appName).setProgress(0, 0, true)
                    .setContentText(getResources().getText(R.string.downloading_notification))
                    .setOngoing(true)
                    .setAutoCancel(true);
            notificationManager.notify(0, notificationBuilder.build());
            new DownloadFileFromURL().execute(appLink);

        }
    }

    public void installApk(Uri uri) {
        Intent install = new Intent(Intent.ACTION_VIEW);
        install.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        install.setDataAndType(uri,
                "application/vnd.android.package-archive");
        DownloadApkService.this.startActivity(install);

    }

    /**
     * Background Async Task to download file
     */
    class DownloadFileFromURL extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Bar Dialog
         */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            isDownloading = true;

            Intent intentResponse = new Intent();
            intentResponse.setAction(Constants.ACTION_DOWNLOADING_APK);
            intentResponse.putExtra(Constants.COM_APP_ID, appId);
            intentResponse.putExtra(Constants.COM_APK_DOWNLOAD_PERCENTAGE, "0");
            sendBroadcast(intentResponse);
        }

        /**
         * Downloading file in background thread
         */
        @Override
        protected String doInBackground(String... f_url) {
            int count;
            HttpURLConnection connection=null;
            try {
                String link=f_url[0].replace(" ","%20");
                URL url = new URL(link);
                connection = (HttpURLConnection) url.openConnection();
                connection.setRequestProperty("Accept-Encoding", "identity");
                int lenghtOfFile = connection.getContentLength();
                connection.connect();

                // this will be useful so that you can show a tipical 0-100%
                // progress bar

                // download the file
                InputStream input = new BufferedInputStream(connection.getInputStream());

                downloadLocation = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/";
                String fileName = appName + ".apk";
                downloadLocation += fileName;

                File sourceFile = new File(downloadLocation);
                if (sourceFile.exists()) {
                    sourceFile.delete();
                }

                // Output stream
                FileOutputStream output = new FileOutputStream(downloadLocation);

                byte data[] = new byte[1024];

                long total = 0;

                while ((count = input.read(data)) != -1) {
                    total += count;
                    // publishing the progress....
                    // After this onProgressUpdate will be called
                    publishProgress("" + (int) ((total * 100) / lenghtOfFile));

                    // writing data to file
                    output.write(data, 0, count);
                }

                // flushing output
                output.flush();

                // closing streams
                output.close();
                input.close();

            } catch (Exception e) {
                return "fail";
            }finally {
                if(connection != null)
                    connection.disconnect();
            }

            return "success";
        }

        /**
         * Updating progress bar
         */
        protected void onProgressUpdate(String... progress) {
            // setting progress percentage
            Intent intentResponse = new Intent();
            intentResponse.setAction(Constants.ACTION_DOWNLOADING_APK);
            intentResponse.putExtra(Constants.COM_APP_ID, appId);
            intentResponse.putExtra(Constants.COM_APK_DOWNLOAD_PERCENTAGE, progress[0]);
            sendBroadcast(intentResponse);

            Intent intentQueueingApk = new Intent();
            intentQueueingApk.setAction(Constants.ACTION_QUEUEING_APK);
            sendBroadcast(intentQueueingApk);
        }

        /**
         * After completing background task Dismiss the progress dialog
         **/
        @Override
        protected void onPostExecute(String file_url) {

            notificationManager.cancel(0);
            if (file_url.equals("success")) {
                Intent intentResponse = new Intent();
                intentResponse.setAction(Constants.ACTION_DOWNLOADING_APK_COMPLETE);
                intentResponse.putExtra(Constants.COM_APP_ID, appId);
                sendBroadcast(intentResponse);

                isDownloading = false;

                if (isApkFromServer!=null && isApkFromServer.equals("0")) {
                    Intent intent = new Intent(DownloadApkService.this, UploadApkService.class);
                    intent.putExtra(Constants.COM_APP_ID, mAppDetails.getId());
                    intent.putExtra(Constants.COM_APK_FILE_PATH, downloadLocation);
                    startService(intent);
                }

                installApk(Uri.fromFile(new File(downloadLocation)));
            } else if (file_url.equals("fail")) {
                isDownloading = false;
                Intent intentResponse = new Intent();
                intentResponse.setAction(Constants.ACTION_DOWNLOADING_APK_FAILED);
                intentResponse.putExtra(Constants.COM_APP_ID, appId);
                sendBroadcast(intentResponse);
            }

            if (/*isDownloading &&*/ !downloadQueue.isEmpty()) {
                QueueData queueData = downloadQueue.poll();
                appId = queueData.getAppId();
                appLink = queueData.getAppLink();
                appName = queueData.getAppName();
                isApkFromServer = queueData.getIsApkFromServer();

                Thread thread = new Thread(new MyThread());
                thread.start();
            }

        }

    }

    @Override
    public void onTaskRemoved(Intent rootIntent) {
        if (notificationManager != null)
            notificationManager.cancel(0);
    }
}

I hope it's going to be helpful for someone.


Q:

Is there any drawback with parsing javascript strings to integer implicitly?

What's the difference between
"2" * 1 + 5

and
parseInt("2") + 5

It's just a to write a more readable code, or there are compatibility issues with the first form.

A:

I don't think there are compatibility issues with using coercion in the first form, it is a language feature that should be widely supported.
However, since you have to add code to do the conversion either way (* 1 vs. parseInt),  I would vote for parseInt from a style perspective because it makes your intention clearer. It is hard enough sometimes to keep types straight in javascript without using implicit conversions.
Someone not familiar with your code or with javascript might wonder what is going on with that first form as well.
Plus, as indicated in the comments, parseInt is faster so it's a win all around.


Q:

Nokogiri vs Hpricot?

Which one would you choose? My important attributes are (not in order):

Support and future enhancements.
Community and general knowledge base (on the Internet).
Comprehensive (I.E., proven to parse a wide range of *.*ml pages).
Performance.
Memory footprint (runtime, not the code-base).

A:

Pick Nokogiri, for all points and especially point one: Hpricot is no longer maintained.
Meta answer: See ruby-toolbox to get an idea of the popularity of different tools in a given area.

A:

Only pick Hpricot if you don't have, or can't install, LibXML on the computer you're using. If this is not the case then choose Nokogiri, it's better in the five mentioned attributes than Hpricot.

A:

The case where I've found Hpricot to be useful is in dealing with broken HTML that you need to remain broken after processing.  Hpricot is good about modifying only the portion of a document you have updated. Unless this is needed, Nokogiri is the way to go.


Q:

How to customize enhanced link attribution for Google Analytics in Google Tag Manager

I'm installing Google Analytics on a website using Google Tag Manager and I want to enable Enhanced Link Attribution.
I've enabled Enhanced Link Attribution in my Google Analytics Property settings and I enabled link tracking on my Google Analytics Settings Variable in Tag Manager. As the documentation states, you can customize the maximum number of levels in the DOM to look for existing IDs, but I can't find an option to change this anywhere in Google Tag Manager.
This is the sample code provided in the documentation link above. The only way I've found to get this working is by uninstalling Google Analytics from Tag Manager and manually installing the tracking code with the modifications to every page of my website.

ga('create', 'UA-XXXXX-Y', 'auto');
ga('require', 'linkid', {
  'cookieName': '_ela',
  'duration': 45,
  'levels': 5
});
ga('send', 'pageview');

A:

In your Google Analytics tag tick "Enable overriding settings in this tag", then click on "More Settings" -> "Fields To Set" and finally "Add Field"
When you click on field name "linkid" should be in the drop-down already, select it and set the value to the object you have in your example. I hope this will work for you.


Q:

Is modifying a texture (painting on it) considered a "state change"?

The convention in graphics is that performing fewer state changes is better than performing more state changes (switching shaders, binding buffers, binding textures, etc.). For textures, it is faster to render many polygons using a single atlas (for rendering sprites/text) than to individually bind a new texture for each polygon.
Does this hold true if I am continually painting to a texture via glTexSubImage2D? I have a stream of data coming in (over a network) that undergoes processing and is then painted to a texture one row at a time. The data is presented visually in an endless scroll.
Would I be better off painting to one texture rendered on one large rectangle (scrolling the painted data into view)? The idea here is that I would have one (or two) textures bound at any given time while I just continue to paint to it.
Or should I paint lots of little rectangles (only revealing the rectangle when painting is done)? I assume I would bind one texture per rectangle.

A:

Updating an area of memory in the graphics device (a texture, buffer, and the like) is not quite the same as changing a rendering state.
What makes a render state change expensive is the amount of work the driver has to do to validate the new state(s) and reorder the pipeline. This will most likely also incur some synchronization between CPU and graphics device. However, the amount of data transferred between the devices should be small for a state change (probably just a few commands).
For a texture/buffer update on the other hand, the main cost lies in the data transfer itself. In theory, unless you're reading the texture data back to the CPU after the update, there should be no synchronization or pipeline stalls. However, another aspect should be considered: API overhead. Even if the amount of data you're sending to the graphics device is small, if you do that often enough, eventually the cost of communicating with the driver/device will become greater then the cost of the data transfer. That's another reason why batching is so important when optimizing a renderer.
So in your case, the best approach, it seems to me, would be to keep a system-memory copy of the texture that you update whenever new data arrives. Set a dirty flag and consolidate as much updates as possible into one glTexSubImage for the whole texture (or a large sequential portion of it). You can also play with Pixel Buffer Objects and try to do asynchronous data transfer to reduce pipeline stalls as much as possible. If you can implement some kind of double buffering, then you can write to one copy of the texture while the other is being rendered with. This tutorial explores that scenario. That's my intuitive approach, I'd try to reduce the number of API calls and "batch" the texture updates. That being said, this is very speculative, and you'd have to profile and compare that to other approaches, like doing several small updates, to know for sure which is the most performant in your usage case.
As a side note, this presentation by NVidia is also relevant and provides a lot of good insights: Approaching Zero Driver Overhead in OpenGL.


Q:

Policy on posts that seem to exist only to promote a link?

What is SO's policy on questions like this fresh one?
To me, it reeks like traffic / PR whoring, even though it might be a legit question.
What to do? Close? Remove the link? Leave as is?
Edit: The question already answered itself:

closed as spam by Michael Todd, AdaTheDev, Chacha102, Andomar, mopoke 15 secs ago

A:

That is what the Close as Spam Button is for.


Q:

Where in the world are cabinets called cupboards?

I understand the difference between cabinet and cupboard.
However, I have spent part of my life redoing houses and I have only ever heard of kitchen cabinets.  In fact if I order "cabinets" the stores and manufacturers refer to them as kitchen cabinets.
I do remember my grandparents using the term cupboards when younger but never hear it anymore in the US.  Is the term cupboard outdated?  I would like to know if it has any usage.
[This question stems from me traveling in Europe the past few weeks.  All non-native English speakers were taught cupboards.]
Just to give the most uncupboard type example.  Something like the picture below was called a cupboard in three different countries over the past week.  Trying to be really specific here.  I am wondering if this is an actual term used, or if it is a term from books that were outdated used to teach English.

To add some of my background I went to the three biggest home improvement store sites (in the US) for some insight.

Lowes (Kitchen Cabinets)
Home depot (Cabinets)
Menard's (Kitchen Cabinets)

A:

Where in the world are cabinets more often referred to as cupboards? In the world of ESL (English as a second language).
I teach English to private students in my spare time and in all the textbooks I have in my possession, be it for nursery school children or adults who are taking advanced level exams, the piece of furniture that the OP refers to as cabinet, is rarely mentioned. In fact, I don't think I've ever seen the word cabinet in any ESL textbook.
Instead, it's cupboards (unless it's a trophy cabinet); wardrobes (never closets); sofas (never couches); and bedroom or kitchen dressers (never hutches) etc. This might well explain why the non-native speakers in Europe were all familiar with the term cupboard but not with cabinet.
Edit 1
And I confirm @Dan Sheppard's statement that the above linked terms are standard British English terms.

Edit 2
I scanned this page from an English coursebook with its accompanying picture. It's taken from Elementary New Headway English Course by Liz and John Soars; published by Oxford University Press. This edition is dated 2000

Headway was first published in 1986 as a two-level course and its
  integrated syllabus, explicit grammar rules and user-friendliness made
  it work equally well in the hands of both experienced and novice
  teachers.  Now in its fourth edition, its continuing popularity has
  resulted in 70 million copies sold and it is estimated that more than
  100 million students in secondary schools, tertiary and teacher
  training institutions in 127 countries have learned English using the
  course.

Edit 3
Not all kitchen cupboards in the UK or for that matter in ESL textbooks are like the ones shown in the image above. There is another type of cupboard, the tall freestanding unit containing shelves complete with one or more doors. In New English File Elementary by Oxford University Press, 2008, there is an exercise where you have to match the words with the pictures.

Take note that AmEng terms such as; stove/range, faucet, couch/loveseat, and cabinets=cupboards, are rarely found in British English coursebooks nor taught to learners. In my experience Italians tend to be taught English by non-native speakers who were themselves taught exclusively in British English. The ubiquitous AmEng terms such as: candy, cookies, (french) fries, soccer, elevator,  and truck, might be taught alongside sweets, biscuits, chips, football, lift and lorry but strangely enough, AmEng named furniture is normally excluded and I don't really know why.  Generally speaking, the teaching of furniture vocabulary is relegated at elementary levels and rarely revised or expanded at higher levels.


Q:

Allocating Array of Pointers on Heap

Does the following create x new objects, or simply allocate space for x objects?:
Vector3D* binArray = new Vector3D[size];

I need to build an array with space for x Vector3D objects on the heap. However, a Vector3D object can only be created when an "add" function is called - this will take the parameters, construct the object on the heap and add its address to the array of Vector3D pointers.

A:

This does create an array of Vector3D objects on the heap.
Each vector is created by calling the Vector3D constructor.
Put a little debugging print statement in the default constructor for Vector3D, and watch the constructor get called the same number of times as you have vectors in your array.
Example:
#include <iostream>
using namespace std;

class C {
public:
  C() { cout << "Hello default constructor here\n"; }
};

int main() {
  C* cs = new C[5];
}

Output is:
Hello default constructor here
Hello default constructor here
Hello default constructor here
Hello default constructor here
Hello default constructor here

If your class does not have a default constructor, you cannot allocate the array in one shot (thank you for the comment @Everyone), so in this case consider using a std::vector or a std::array and adding your Vector3D objects dynamically ---  or even "statically"! Example:
#include <iostream>
#include <vector>
using namespace std;

class Vector3D {
  double i, j, k;
public:
  Vector3D(double i, double j, double k): i(i), j(j), k(k) {}
};

int main() {
  vector<Vector3D> v = {
    Vector3D(3, 4, 5),
    Vector3D(6, 8, 10),
    Vector3D(7, 24, 25)
  };
  v.push_back(Vector3D(1, 2, 3));
  cout << v.size() << '\n';
}

This outputs 4.
You can also make your vector contain pointers to Vector3D objects.


Q:

Is it good idea to use Optional.of() method to make method chaining?

Is it good idea to use Optional.of() method to make method chaining ?
i had a conversation with group of collegues about Optional.of() method.
  currently one of the project they are using Optional.of() method to
  achieve the method chaining functional programming style .
Here i am giving the sample example :
    TxResponse initTxDataResponse = gateway.initiateTx(initTxDataRequest);
    Optional.of(initTxDataResponse)
            .map(initTxDataResponse::getReturnCode)
            .filter(code -> ResponseCode.SUCCESS.getCode().equals(code))
            .map(code -> {
                // doing some business logic ,we are not
                return code;
            }).orElseThrow(() -> new NoTransactionFound());

I feel we are overusing of the Optional.of() method
Is it good practice use the Optional.of() method to achieve functional programming style in jdk 8 ?
Case 2 :
TxResponse response = transactionRepository.getTransacationById(TransactionId).elseThrow(() -> ResourceNotFoundException());

Optional.of(response)
        .map(response::getReturnCode)
        .filter(code -> ResponseCode.SUCCESS.getCode().equals(code))
        .map(code -> {
            // doing some business logic ,we are not
            return code;
        }).orElseThrow(() -> new RuntimeException());

In this case Optional.of() is required to achieve functional programming style ?

A:

If you don’t mind an answer without code, just my 0.02$.
We have been fighting over this at my work place (in code reviews) quite a lot. To be frank I am sometimes lost as to when it is correct (read intended by the creators of it) or not. I don’t even think that at the time of creation, Stuart Marks and the others were sure how this would be (ab)used. Like any other feature in the Java language, it will get abused, be sure of that. But over time, best practices will appear and people will use that.
I tend to be on the side that iff it does not hurt performance, your usage is OK. At least its sooo easy to read (speaking for myself here), compared to if else checks; but again it might be me doing (too) much Java-8 and above code.
That being said, it’s way too easy to turn it into a total mess, where that bound is, is up to you (and most probably your team).


Q:

Understanding a simple crystal oscillator transmitter

I try to understand the AM transmitter on the figure below, but I cannot figure out two essential things. The carrier frequency is created by the crystal oscillator chip.

Why does it suffice to put the audio input in parallel to the battery, in order to add this signal (baseband signal) to the carrier frequency?
Why do we need the capacitor?

A:

This is a very crappy "AM transmitter" circuit which isn't worth its name.
It "works" by modulating the supply voltage with an Audio signal.
The output of a crystal oscillator switches between negative and positive supply. By changing that supply with a signal, the amplitude of the oscillator's output signal will change with that signal.
The "modulation depth" of this circuit will be bad as the crystal will only work for a certain voltage range limiting the amount of AM modulation possible.
It would make more sense to have the 470 ohm resistor in the Bat +5V line instead of the Bat - line as then ground of the audio circuit and this circuit would be the same.
The capacitor is needed to prevent +5 V getting into the audio circuit, without the capacitor the audio circuit might be damaged if it does not have a DC-blocking capacitor of its own.
As I said, this is a really crappy circuit and although it will do "something" it is more a "hack" than a well designed circuit. So don't expect too much from it.


Q:

Can I invoke a delegate/function pointer passed into a remote web service using ASP.NET?

Assuming you have a remote .NET web service(meaning it doesn't reside on the same server as the consuming client) what will the behavior be if you attempt to pass a delegate into the web service and invoke it?

A:

An exception at best -- delegates can't cross system boundaries in that manner.
Now, you can perhaps get to the same plays doing an asynchronous call to create a continuation of sorts . . .


Q:

How to omit to assoc array to consume items in PHP?

I am writing a function that converts MySQL query result into a HTML table. The problem is that first foreach renders multiple  based on first row of the result and "consumes" it from the array. Here's code of the function:
function generate_table($array, $caption = "") {
    $table = '
';

    if($caption) {
        $table .= "
$caption
";
    }

    $table .= "

";
    //The problem
    foreach($array->fetch_assoc() as $key => $value) {
        $table .= "$key	";
    }
    $table .= "

";

    while($row = $array->fetch_assoc()) {
        $table .= "
";
        foreach($row as $key => $value){
            $table .= "$value	";
        }
        $table .= "
";
    }

    $table .= '
';
    return $table;
}

How can I solve the problem?

A:

You can try this after the first foreach:
$array->data_seek(0);

That way you move result pointer to the beggining again.


Q:

NoFollow Entire Website

By default whenever you disable indexing via Admin Settings

[ x ] Discourage search engines from indexing this site

It adds a meta tag in the header like so:
<meta name='robots' content='noindex,follow' />

How do I change that to be nofollow instead of follow?  I find it odd it enables "follow" and overall want it noindex,nofollow.
I could echo directly into wp_head but this doesn't account for pages such as wp-login and the likes.

A:

Thought this was a great question so I went digging.  In default-filters.php on line 208 there's add_action('wp_head', 'noindex', 1); as of WordPress 4.1.  The noindex() function in turn checks to see if you have set blog_public option to 0.  If you have, it calls wp_no_robots() which is simply:
function wp_no_robots() {
    echo "<meta name='robots' content='noindex,follow' />\n";
}

Neither of last methods are filterable, but a simple plugin will do the trick to remove the hook:
/*
 * Declare plugin stuff here
 */

remove_action('wp_head','noindex',1);

Now, you're free to hook your own action on to echo out what you want.
add_action('wp_head', 'my_no_follow', 1);

function my_no_follow() {
    if ( '0' == get_option('blog_public') ) {
        echo "<meta name='robots' content='noindex,nofollow' />\n";
    }
}


Q:

Git difftool in read write mode

I have the following configuration in my ~/.gitconfig
[diff]
    tool = vimdiff
[diftool]
    prompt = false

When I launch git difftool it opens up the buffers in read-only mode by default.
I use it to review the changes before a commit and say I find some small change like a commented out line I have not removed or a JS console.log statement, I am forced to quit the tool and open the file and make the change. I would very much like a way to do the change within the visual diff window itself.
http://gitlog.wordpress.com/2011/03/30/git-1-7-4-2/
says that "“git difftool” didn’t tell (g)vimdiff that the files it is reading are
to be opened read-only." From this I figure that this read-only behavior was desired.

I am curious to know why having a read-only behavior in difftool was chosen as the default.
Is there any way I can configure the difftool to allow read/write?
From git, vimdiff and dirdiff, I see that fugitive plugin for vim and git diffall script are also available as alternatives to make this diff reviewing process easier. Will using fugitive open up the possibility of using a read/write visual diff mode?

A:

If you aren't using fugitive, you can toggle read-only mode (per pane!) with
:set readonly!

or
:set ro!

A:

Fugitive will allow you to change the working copy file while diffing. Just run :Gdiff and a vertical split with the index version will appear. Now you can :diffput (or short dp) inside the working copy to put the chunk into the index file, or alternatively, :diffget (or short do) from the index file to get the chunk from the working copy. Once you have everything in the index file that you want, save it, and that will now be your stashed version.
What really helped me understand the process were the vimcasts #31 to #35 about Fugitive.vim:
http://vimcasts.org/episodes/archive


Q:

Extract Different Date Structures with Text Using RE- Python

I have strings that have dates in different formats. For example,
sample_str_1 = 'this amendment of lease, made and entered as of the  10th day of august, 2016,   by and between john doe and jane smith'

Also, another string that has the date in it as,
sample_str_2 ='this agreement, made and entered as of May 1, 2016, between john doe and jane smith'

In order to extract just the date from the first string, I did something like this,
match = re.findall(r'\S+d{4}\s+', sample_str_1)

this gives an empty list.
For the second string, I used the same method as I used for first string and getting an empty string.
I also, tried datefinder module and it gave me an output like this,
import datefinder
match = datefinder.find_dates(sample_str_1)

for m in match:
    print(m)

>> 2016-08-01 00:00:00

Above output is wrong, which should be 2016-08-10 00:00:00
I tried another way using this older post
match = re.findall(r'\d{2}(?:january|february|march|april|may|june|july|august|september|october|november|december)\d{4}',sample_str_1)

This again gave me an empty list.
How can I extract dates like that from a string? Is there a generic method to extract dates that have text and digits? Any help would be appreciated.

A:

Regex: (?:(\d{1,2})(?:th|nd|rd).* ([a-z]{3})[a-z]*|([a-z]{3})[a-z]* (\d{1,2})),\s*(\d{4})
Python code:
regex = re.compile('(?:(\d{1,2})(?:th|nd|rd).* ([a-z]{3})[a-z]*|([a-z]{3})[a-z]* (\d{1,2})),\s*(\d{4})', re.I)

for x in regex.findall(text):
    if x[0] == '':
        date = '-'.join(filter(None, x))
    else:
        date = '%s-%s-%s' % (x[1],x[0],x[4])

    print(datetime.datetime.strptime(date, '%b-%d-%Y').date())

Output:
2016-08-10
2016-05-01

Code demo


Q:

FileInfo finds file, but File.Copy cannot find the file

I am trying to find a file with the last write date and copy it to a different location. It finds the file correctly, but when I try to copy it, it can't find the file it just found. This is in a SSIS script task.
DirectoryInfo directory = new DirectoryInfo(@"path");
FileInfo[] files = directory.GetFiles();

//files that have been written to in the last 3 days
DateTime lastWrite = DateTime.Now.AddDays(-3);

foreach (FileInfo latestFile in files)
{
    // if its the correct name
    if (latestFile.Name.StartsWith("OMC"))
    {
        // if its in the last 3 days
        if (latestFile.LastWriteTime > lastWrite)
        {
            lastWrite = latestFile.LastWriteTime;

            // this correctly find the file and puts it into the file variable.
            file = latestFile.ToString();

            // this errors out saying it cannot find the file.
            // (Does not even go to the outputFile)
            File.Copy(file, outputFile, true); // <- error

            //backs the file up
            File.Copy(file, backupfile, true);
        }
    }
}

A:

FileInfo.ToString() returns the name of the file, but in order to copy it, you need the full path. Change
file = latestFile.ToString();

To
file = latestFile.FullName;

And give it a shot.


Q:

Can not complete GET request to my localhost or to my external API (express app)

I am building a React app to consume an API that I built using express.js. My React app successfully gets data using fetch or axios to query data using an official API ("https://jsonplaceholder.typicode.com/users"), but I keep getting an error when I try to get from my own API ("XXX.us-east-1.elasticbeanstalk.com/api/v1/users") or from my localhost ("http://localhost:81/api/v1/users").
Questions
Is my GET request wrong?
Is there a problem with the return from my API?
Would you recommend any resources to learn to create a RESTful API with Express.js, set it up in AWS and consume this API with a React app?
Thank you!

The error is:

Access to fetch at 'XXX.us-east-1.elasticbeanstalk.com/api/v1/users' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled

Using fetch:
componentDidMount() {
    fetch
      ('https://jsonplaceholder.typicode.com/posts/1')
      // ('XXX.us-east-1.elasticbeanstalk.com/api/v1/users')
      // ('http://localhost:81/api/v1/users')
      .then(response => response.json())
      .then(data =>
        this.setState({
          title: data.title,
          body: data.body
        })
      );
  }

Using axios:
componentDidMount() {
    axios
      .get('https://jsonplaceholder.typicode.com/users').then(res => this.setState({ users: res.data }))
   // .get('http://localhost:81/api/v1/users', { crossDomain: true }).then(res => this.setState({ users: res.data }))
      .catch(function (error) {
        console.log("Error");
      });
  }

A:

Its actually a cors issue in express, so to solve it add the following in the start file
var express = require('express');
var app = express();
app.use(cors());


Q:

Why has javax.persistence-api been replaced by jakarta.persistence-api in spring data jpa starter?

I've recently started to learn spring boot, data jpa. As I can see from this, the spring boot data jpa starter uses jakarta.persistence-api instead of javax.persistence-api:
   <artifactId>spring-boot-starter-data-jpa</artifactId>
   ...
   <dependencies>
      <dependency>
         <groupId>jakarta.persistence</groupId>
         <artifactId>jakarta.persistence-api</artifactId>
      </dependency>

      <dependency>
         <groupId>org.hibernate</groupId>
         <artifactId>hibernate-core</artifactId>
         <exclusions>
            <exclusion>
               <groupId>javax.persistence</groupId>
               <artifactId>javax.persistence-api</artifactId>
            </exclusion>
            ...
         </exclusions>
      </dependency>
   </dependencies>

What is the differences between jakarta.persistence-api and javax.persistence-api? What is the reason of this replacement?

A:

From wikipedia:

The Java Persistence API (JPA), in 2019 renamed to Jakarta Persistence, is a Java application programming interface specification that describes the management of relational data in applications using Java Platform, Standard Edition and Java Platform, Enterprise Edition/Jakarta EE.

You can read more about it here.


Q:

How macros in embedded C affect memory?

I know that macros in C such as:
#define VARNULL (u8)0

doesn't store this VARNULL in RAM, but this of course will increase the code size in the FLASH.
But what if I have a multi-line macro such as:
#define CALL_FUNCS(x) \
do { \
  func1(x); \
  func2(x); \
  func3(x); \
} while (0)

By knowing that func1, func2, and func3 are functions from different .c files. Does this means that these functions will be stored in RAM?  And of course in the FLASH (the code).
Kindly correct me if I'm wrong?

A:

You keep saying that "of course" the macros will be "stored" in flash memory on your target device, but that is not true.
The macros exist in the source code only; they are replaced with their defined values during compilation. The program in flash memory will not "contain" them in any meaningful way.

A:

Macros, and any other directive prefixed with a # are processed before C compilation by the pre-processor; they do not generate any code, but rather generate source code that is then processed by the compiler as if you had typed in the code directly.  So in your example the code:
int main()
{
    CALL_FUNCS(2) ;
}

Results in the following generated source code:
int main()
{
    do { \
      func1(2);
      func2(2);
      func3(2);
    } while (0) ;
}

Simple as that.  If you never invoke the macro, it will generate exactly no code.  If you invoke it multiple times, it will generate code multiple times.  There is nothing clever going on the macro is merely a textual replacement generated before compilation; what the compiler does with that depends entirely on what the macro expands to and not the fact that it is a macro - the compiler sees only the generated code, not the macro definition.
With respect to const vs #define, a literal constant macro is also jyst a textual replacement and will be placed in the code as a literal constant.  A const on the other hand is a variable.  The compiler may simply insert a literal constant where that generates less code that fetching the constant from memory, in C++ that is guaranteed for simple types, and it would be unusual for a C compiler not to behave in the same way.  However, because it is a variable you can take it's address - if your code does take the address of a const, then the const will necessarily have storage.  Whether that storage is in RAM or ROM depends on your compiler and linker configuration - you should consult the toolchain documentation to see how it handles const storage.
One benefit of using a const is that const variables have strong typing and scope unlike macros.


Q:

Why use virtual functions?

Possible Duplicate:
Can someone explain C++ Virtual Methods?

I have a question regarding to the C++ virtual functions.
Why and when do we use virtual functions? Can anyone give me a real time implementation or use of virtual functions?

A:

You use virtual functions when you want to override a certain behavior (read method) for your derived class rather than the one implemented for the base class and you want to do so at run-time through a pointer to the base class.
The classic example is when you have a base class called Shape and concrete shapes (classes) that derive from it. Each concrete class overrides (implements a virtual method) called Draw().
The class hierarchy is as follows:

The following snippet shows the usage of the example; it creates an array of Shape class pointers wherein each points to a distinct derived class object. At run-time, invoking the Draw() method results in the calling of the method overridden by that derived class and the particular Shape is drawn (or rendered).
Shape *basep[] = { &line_obj, &tri_obj,
                   &rect_obj, &cir_obj};
for (i = 0; i < NO_PICTURES; i++)
    basep[i] -> Draw ();

The above program just uses the pointer to the base class to store addresses of the derived class objects. This provides a loose coupling because the program does not have to change drastically if a new concrete derived class of shape is added anytime. The reason is that there are minimal code segments that actually use (depend) on the concrete Shape type.
The above is a good example of the Open Closed Principle of the famous SOLID design principles.

A:

You use virtual functions when you need handle different objects in the same way. It`s called polymorphism. Let's imagine you have some base class - something like classical Shape:
    class Shape
    {
        public:
           virtual void draw() = 0;
           virtual ~Shape() {}
    };

    class Rectange: public Shape
    {
        public:
            void draw() { // draw rectangle here }
    };

    class Circle: public Shape
    {
        public:
           void draw() { // draw circle here }
    };

Now you can have vector of different shapes:
    vector<Shape*> shapes;
    shapes.push_back(new Rectangle());
    shapes.push_back(new Circle());

And you can draw all shapes like this:
    for(vector<Shape*>::iterator i = shapes.begin(); i != shapes.end(); i++)
    {
          (*i)->draw();
    }

In this way you are drawing different shapes with one virtual method - draw(). Proper version of method is selected based on run time information about type of object behind pointer.
Notice
When you use virtual functions you can declare them as pure virtual(like in class Shape, just place " = 0" after method proto). In this case you won't be able to create instance of object with pure virtual function and it will be called Abstract class.
Also notice "virtual" before destructor. In case when you are planning work with objects through pointers to their base classes you should declare destructor virtual, so when you call "delete" for base class pointer, all chain of destructors will be called and there won't be memory leaks.

A:

Think of animals class, and derived from it are cat, dog and cow. Animal class has a
virtual void SaySomething()
{
    cout << "Something";
}

function.
Animal *a;
a = new Dog();
a->SaySomething();

Instead of printing "Something", dog should say "Bark", cat should say "Meow". In this example you see that a is a Dog, but there are some times that you have an animal pointer and don't know which animal it is. You don't want to know which animal it is, you just want the animal to say something. So you just call virtual function and cats will say "meow" and dogs will say "bark".
Of course, SaySomething function should have been pure virtual to avoid possible errors.


Q:

CIFilter for CategoryDistortionEffect example

Can someone show an example of initializing the CIFilter for kCICategoryDistortionEffect?
I need to create Distortion effect for my photography. I have read that it is possible, with CIFilter in IOS 5.
But I can not find a suitable code how to implement it.

A:

I've been looking for this to.  Thus far it appears that's not available in iOS 5.  Here's the evidence:
If you execute:
NSArray *properties = [CIFilter filterNamesInCategory:
                       kCICategoryBuiltIn];

you'll see that it only returns the following list which doesn't contain any of the kCICategoryDistortionEffect's.  It only contains:
CIAdditionCompositing,
CIAffineTransform,
CICheckerboardGenerator,
CIColorBlendMode,
CIColorBurnBlendMode,
CIColorControls,
CIColorCube,
CIColorDodgeBlendMode,
CIColorInvert,
CIColorMatrix,
CIColorMonochrome,
CIConstantColorGenerator,
CICrop,
CIDarkenBlendMode,
CIDifferenceBlendMode,
CIExclusionBlendMode,
CIExposureAdjust,
CIFalseColor,
CIGammaAdjust,
CIGaussianGradient,
CIHardLightBlendMode,
CIHighlightShadowAdjust,
CIHueAdjust,
CIHueBlendMode,
CILightenBlendMode,
CILinearGradient,
CILuminosityBlendMode,
CIMaximumCompositing,
CIMinimumCompositing,
CIMultiplyBlendMode,
CIMultiplyCompositing,
CIOverlayBlendMode,
CIRadialGradient,
CISaturationBlendMode,
CIScreenBlendMode,
CISepiaTone,
CISoftLightBlendMode,
CISourceAtopCompositing,
CISourceInCompositing,
CISourceOutCompositing,
CISourceOverCompositing,
CIStraightenFilter,
CIStripesGenerator,
CITemperatureAndTint,
CIToneCurve,
CIVibrance,
CIVignette,
CIWhitePointAdjust

and is missing the one's we're interested in:
CICategoryDistortionEffect,
CIBumpDistortion,
CIBumpDistortionLinear,
CICircleSplashDistortion,
CICircularWrap,
CIDisplacementDistortion,
CIGlassDistortion,
CIGlassLozenge,
CIHoleDistortion,
CIPinchDistortion,
CITorusLensDistortion,
CITwirlDistortion,
CIVortexDistortion


Q:

Hausdorff Space vs Van Kampen Theorem

Let X be a Hausdorff space such that X is the union of A and B; where both A and B are homeomorphic to a torus. The intersection of A and B is a singleton. I want to compute the fundamental group of X.
Intuitively/non-rigorously, I can say the fundamental group of X is the free product of the fundamental group of A and that of B. I don't see why the hausdorffness condition is necessary. Can anyone please tell me why we need the hausdorffness condition to apply Van Kempen theorem to solve this problem? Thank you so much.

A:

The key idea is that since $X$ is Hausdorff, any compact subspace of it is closed, and so $A$ and $B$ are both closed in $X$.  This gives you a handle on the topology of $X$ and not just the topologies of $A$ and $B$.  In particular, you can cover $X$ with open sets which deformation-retract to $A$ and $B$ (and whose intersection is contractible), which is what you need in order to use van Kampen.  For instance, you can take $U$ to be $A$ together with a small open disk around the intersection point in $B$ and $V$ to be $B$ together with a small open disk around the intersection point in $A$.  (Exercise: use the fact that $A$ and $B$ are both closed in $X$ to prove that $U$ and $V$ really are open in $X$.)  To prove that $U$ really deformation-retracts to $A$, for instance, you can again use the fact that $A$ and $B$ are closed in $X$, so that by the pasting lemma you can check that a homotopy is continuous by just checking that it is continuous separately on $A$ and $B$.
Note that if $X$ is not Hausdorff, then all sorts of horrible things can happen.  For instance, letting $T$ be a torus and $S$ be $\{0,1\}$ with the indiscrete topology, then $X$ could be $T\times S\setminus\{(x,1)\}$ for some point $x\in T$.  You can then write $X$ as the union of subspaces $A=T\times\{0\}$ and $B=(T\setminus\{x\})\times\{1\}\cup\{(x,0)\}$ which are each homeomorphic to $T$ and intersect only at $(x,0)$.  In this case the projection $X\to T$ is actually a homotopy equivalence, so $\pi_1(X)$ is not the free product of $\pi_1(A)$ and $\pi_1(B)$.  And this is one of the tamer examples of what could happen if $X$ is not Hausdorff; there are many other more complicated possibilities.


Q:

Upload multiple images with asynchronous process

I'm trying to upload images from ajax request. In action I have to save 4 different sizes for that images.
I want to save only one in current thread, and rest 3 image image in another thread, so that user don't have to wait for upload all images, As I only required the path of first Image.
This is what I have done so far.
[HttpPost]
public JsonResult UploadImage(bool isUploadLogo = false)
{
        HttpPostedFileBase file = Request.Files["UploadedImage"];
        if (file != null)
        {
           var getExt = Path.GetExtension(file.FileName).ToLower();
           var getBytesArray = ResizeImage.ConvertToByte(file);
            string fileName = "TestImage" + DateTime.Now.Ticks.ToString() + getExt;
            var smallSizeImageBytes = ResizeImage.ResizeImageBytes(200, 200, getBytesArray, getImageFormat);
            var pic = ImageStore.UploadImage(fileName, file.ContentType, smallSizeImageBytes);

            //Save Slider Image,  Without Wait
            if (!isUploadLogo)
            {
                new Thread(() =>
                {
                    UploadSliderImage(getBytesArray);
                }).Start();
            }
            var result = new
            {
                url = "Folder Path Here" + fileName,
                isSuccess = "true"
            };
            return Json(result, "text/plain", JsonRequestBehavior.AllowGet);
        }
}

public void UploadSliderImage(byte[] CroppedImage)
{
    //Code for upload diffrent size images
}

Although I'm calling UploadSliderImage inside another thread, But In client side I'm not getting the result until UploadSliderImage process complete.
How can I return the data to client side without waiting for uploading remaining images.

A:

I think it's better for you to use Task instead of the Thread class assuming you are using .net 4.0 and above. Here is a sample code that you can base on. It will return the Json Immediately without finishing the Task.
        Debug.WriteLine("Image Upload");

        Task tsk = new Task(() =>
        {
            Thread.Sleep(5000); //This is your UploadSlider Image
            Debug.WriteLine("Done");

        });
        tsk.Start();

        return Json("result", JsonRequestBehavior.AllowGet);


Q:

Two analytic continuations along the same arc are either identical or disjoint (Ahlfors)

I'm struggling with the proof of the following theorem by Ahlfors, on page 289:

Theorem l. Two analytic continuations $\overline{\gamma_1}$ and $\overline{\gamma_2}$ of a global analytic function $\mathbf{f}$ along the same arc $\gamma$ are either identical, or $\overline{\gamma_1}(t) \neq \overline{\gamma_2}(t)$ for all t.

Here  $\gamma:[a,b] \to \mathbb C$ is an arc, and $\overline{\gamma_i}:[a,b] \to \mathfrak{S}_0 (\mathbf{f})$ are analytic continuations of $\mathbf{f}$ along $\gamma$, where $\mathfrak{S}_0(\mathbf{f})$ is the Riemann surface associated with a global analytic function $\mathbf{f}$. This means that $\pi \circ \overline{\gamma_i}=\gamma$, as well that the functions $\{ \overline{\gamma_i} \}$ are continuous on $[a,b]$ in the topology of $\mathfrak{S}_0 (\mathbf{f})$.
Right after stating the theorem Ahlfors claims:

The proof is a triviality. Because $\pi$ is a local homeomorphism the image of $\overline{\gamma_1}-\overline{\gamma_2}$ cannot contain a point of the zero section without being contained in it.

I tried following his guidance in order to prove the theorem:
Suppose there exists some point $t_0 \in [a,b]$ such that $\overline{\gamma_1}(t_0)-\overline{\gamma_2}(t_0)= \mathbf{0}_{\gamma(t_0)}$. Since $\pi$ is a local homeomorphism we may find for each of the germs $\{\overline{\gamma_1}(t)-\overline{\gamma_2}(t) : t \in [a,b] \}$ a neighbourhood $\Delta_t \subset \mathfrak{S}_0 (\mathbf{f})$ which is homeomorphic to some open set $\Omega_t \subset \mathbb C$, which includes the point $\gamma(t)$. The section $\left( \pi \big|_{\Delta_{t_0}} \right)^{-1}\in \Gamma( \Omega_{t_0}, \mathfrak{S})$ vanishes at $\gamma(t_0)$, hence by a previous statement from the book, the only section in $\Delta_{t_0}$ is the zero section.
Since $(\overline{\gamma_1}-\overline{\gamma_2})([a,b])$ is compact, we can restrict the cover $\{ \Delta_t \}_{t \in [a,b]} $ to a finite cover, to which we join $\Delta_{t_0}$ (this clearly induces a finite subcover of $\gamma([a,b])$ as well).  Since $\gamma([a,b])$ is connected we can form (finite) chains from $\Omega_{t_0}$ to any other element of the subcover with consecutive sets having nontrivial intersection. Repeating the argument from before we obtain the desired result.
Is the proof above correct? If not, please help me fix it. Thanks!

A:

The idea is sound, but the way you built the argument feels like   Weierstrass-style proof translated into sheaves. In the earlier question we essentially proved the following

Fact 0. The set of all zero germs is both closed and open in $\mathfrak {S}$.

Indeed: open because the zero germ is determined by $(0,\Omega)$, which determines only other zero germs. The complement is also open because a nonzero germ at $\zeta$ is determined by $(f,\Omega)$ where $f$ does not vanish in $\Omega\setminus\{\zeta\}$, hence it defines only other nonzero germs in $\Omega$.
The rest is general topology: if $A$ is a clopen subset of topological space $Y$, then every connected subset of $Y$ is either contained in $A$ or is disjoint from it. This applied to the image of $\gamma$ under any  continuous  map into $\mathfrak{S}$, in particular to   the analytic continuation.


Q:

Why does Gnosis' MultiSig passes less gas than available in external_call?

Gnosis' MultiSig Wallet substract a fixed amount of gas (34710) when calling an external address.
function external_call(address destination, uint value, uint dataLength, bytes data) internal returns (bool) {
    bool result;
    assembly {
        let x := mload(0x40)   // "Allocate" memory for output (0x40 is where "free memory" pointer is stored by convention)
        let d := add(data, 32) // First 32 bytes are the padded length of data, so exclude that
        result := call(
            sub(gas, 34710),   // 34710 is the value that solidity is currently emitting
                               // It includes callGas (700) + callVeryLow (3, to pay for SUB) + callValueTransferGas (9000) +
                               // callNewAccountGas (25000, in case the destination address does not exist and needs creating)
            destination,
            value,
            d,
            dataLength,        // Size of the input (in bytes) - this is what fixes the padding problem
            x,
            0                  // Output is ignored, therefore the output size is zero
        )
    }
    return result;
}

It seems to reserve some gas for the worst case scenario. But it causes strange behavior in some circumstances.

gas available less than 34710: sub() will overflow, but EVM fill cap gas to the max available, so the call may succeed.
gas available slightly more to 34710: sub() returns a small amount of thas that will make the inner call to fail with out of gas.

Is there any reason for doing that instead of just sending all available gas?

A:

This contract is quite "old" (pragma solidity ^0.4.15;). The logic is actually taken from the solidity compiler. When targeting older versions of the evm it was not possible to send along all gas. The solidity code still exists even now: https://github.com/ethereum/solidity/blob/develop/libsolidity/codegen/ExpressionCompiler.cpp#L2343
Solidity changed this with https://github.com/ethereum/solidity/releases/tag/v0.4.18 (in preparation for 0.5.0):

Code Generator: Always use all available gas for calls as experimental
  0.5.0 feature (previously, some amount was retained in order to work in pre-Tangerine-Whistle EVM versions)

Why this was initially done in assembly in the MultiSig contract?
This is because in older Solidity versions the msg.data of a Solidity call was padded which caused errors with some contracts. (Guards for short address attacks, see https://vessenes.com/the-erc20-short-address-attack-explained/)


Q:

Constructor with bool parameter gets ALWAYS CALLED with _T("...")?

I got a strange beaviour in my program.
I wrote a test which always failed.
While debugging i saw something i don't understand:
I got some multiple Constructors, but this one gets always called if i pass unicode via _T():
IsNullable(bool isNullable)
    : m_bIsNullabe(isNullable), Flag(eNullAllowed)
{};

And here's my way of calling the constructor:
... = new IsNullable(_T("N"));

The strange thing is that the bool Constructor above gets always called...
Why is that so? I would be really pleased if someone got a clue!
Greeds,
Clemens
EDIT:
This Constructor should get called:
IsNullable(wchar_t isNullable)
    : Flag(eNullAllowed)
{...};

A:

The constructor that you want to be called takes a wchar_t character, not a pointer to a wide string. Call it as:
IsNullable( L'N' );

Note that I'm not using the _T macro because your constructor argument type is wchar_t and it is not predicated on whether the UNICODE symbol is defined. So there's no need for that macro in this case.
The reason the other constructor is being called is because the string literal, of type const wchar_t[2] (assuming the _T macro expands to L"N"), decays to a const wchar_t * which is then implicitly converted to a bool.


Q:

Fading Images - Swing

Hi I've been trying to fade from one image to another using trident java animation library, but haven't quite grasped how you choose to interpolate a image. Any solutions?
Thanks anyway

A:

I never used Trident for fading, but I'd suggest to read
1) basic Java 2D Graphics tutorial, and there is accesible to set transparency for JComponents that contains Icon or ImageGraphics
2) How to Create Translucent and Shaped Windows
3) for both ways you have to implements javax.swing.Timer
simple example for Graphics and Timer
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.Color;
import java.awt.AlphaComposite;
import javax.swing.*;
import javax.swing.UIManager.LookAndFeelInfo;

public class ButtonTest {

    private JFrame frame;
    private JButton opaqueButton1;
    private JButton opaqueButton2;
    private SoftJButton softButton1;
    private SoftJButton softButton2;
    private Timer alphaChanger;

    public void createAndShowGUI() {
        opaqueButton1 = new JButton("Opaque Button");
        opaqueButton2 = new JButton("Opaque Button");
        softButton1 = new SoftJButton("Transparent Button");
        softButton2 = new SoftJButton("Transparent Button");
        opaqueButton1.setBackground(Color.GREEN);
        softButton1.setBackground(Color.GREEN);
        frame = new JFrame();
        frame.getContentPane().setLayout(new java.awt.GridLayout(2, 2, 10, 10));
        frame.add(opaqueButton1);
        frame.add(softButton1);
        frame.add(opaqueButton2);
        frame.add(softButton2);
        frame.setSize(700, 300);
        frame.setLocation(150, 100);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
        alphaChanger = new Timer(30, new ActionListener() {

            private float incrementer = -.03f;

            @Override
            public void actionPerformed(ActionEvent e) {
                float newAlpha = softButton1.getAlpha() + incrementer;
                if (newAlpha < 0) {
                    newAlpha = 0;
                    incrementer = -incrementer;
                } else if (newAlpha > 1f) {
                    newAlpha = 1f;
                    incrementer = -incrementer;
                }
                softButton1.setAlpha(newAlpha);
                softButton2.setAlpha(newAlpha);
            }
        });
        alphaChanger.start();
        Timer uiChanger = new Timer(3500, new ActionListener() {

            private final LookAndFeelInfo[] laf = UIManager.getInstalledLookAndFeels();
            private int index = 1;

            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    UIManager.setLookAndFeel(laf[index].getClassName());
                    SwingUtilities.updateComponentTreeUI(frame);
                    opaqueButton1.setText(laf[index].getClassName());
                    softButton1.setText(laf[index].getClassName());
                } catch (Exception exc) {
                    exc.printStackTrace();
                }
                index = (index + 1) % laf.length;
            }
        });
        uiChanger.start();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                new ButtonTest().createAndShowGUI();
            }
        });
    }

    private static class SoftJButton extends JButton {

        private static final JButton lafDeterminer = new JButton();
        private static final long serialVersionUID = 1L;
        private boolean rectangularLAF;
        private float alpha = 1f;

        SoftJButton() {
            this(null, null);
        }

        SoftJButton(String text) {
            this(text, null);
        }

        SoftJButton(String text, Icon icon) {
            super(text, icon);
            setOpaque(false);
            setFocusPainted(false);
        }

        public float getAlpha() {
            return alpha;
        }

        public void setAlpha(float alpha) {
            this.alpha = alpha;
            repaint();
        }

        @Override
        public void paintComponent(java.awt.Graphics g) {
            java.awt.Graphics2D g2 = (java.awt.Graphics2D) g;
            g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
            if (rectangularLAF && isBackgroundSet()) {
                Color c = getBackground();
                g2.setColor(c);
                g.fillRect(0, 0, getWidth(), getHeight());
            }
            super.paintComponent(g2);
        }

        @Override
        public void updateUI() {
            super.updateUI();
            lafDeterminer.updateUI();
            rectangularLAF = lafDeterminer.isOpaque();
        }
    }
}