text:
Q: Is memorization a good skill to learn to master mathematics? I sometimes spend inordinate amounts of time memorizing math articles or theorems/proofs or formulas. My question is "am I wasting time?" and will 'active thinking' or 'working out problems' be faster way to master mathematics?
I am absolutely a beginner. So at an apprentice stage sometimes I find that best way to grasp a subject is through verbatim scribing. Also, memorization seem to be my forte.
Mathematics is a language and just like when trying to learn the basics one has to memorize grammar, does the same theory apply in this field?
I used to browse MO, this website, wikipedia but since "mathematics is not a spectator sport" I imagine more fruitful way would to be to isolate small problems and work on it?
I am sorry if the question is very general.

A: I think it depends on what your priorities are and what you're trying to achieve. If it is indeed something resembling mastery of maths then my answer would be a resounding no to memorising in the conventional sense being the way to achieve this. If however your requirements are just recollection in the short term then this kind of memorisation is a tried and tested reliable method and perhaps the safest means.
I'd say there are different levels of understanding spanning from just being able to read the words, to following the logic and then to the highest levels where you reconcile with what the mathematician who originally came up with the proof might have been thinking and begin to consider how this could influence your future thoughts on these subjects. If you're under pressure to memorise proofs for a lot of theorems then a way which I think is effective is to break the proof down algorithmically and memorise the algorithm for the proof. Such an algorithm may include steps like "define a such and such set", "sum elements and apply some property". In this way when the time comes to recall it, you can at least do it in a way that still gives you the feel of "doing maths" to some capacity as opposed to just rewriting word for word. It will also help you to develop mathematical technique and you may be able to get through things quicker as there is less to memorise this way.

A: As you say, mathematics is a language. In any language, memorizing vocabulary very quickly becomes useless, if it is not paired with active use. Certainly, memorizing an entire Spanish dictionary before attempting to formulate one's first Spanish sentence is not the right way to learn Spanish. You should learn a few basic words, and practice using them in all sorts of combinations until you are comfortable with their properties; perhaps you must take a few things on faith from a fluent speaker. Then learn a few more words, plus maybe a grammar rule, and practice them intensively as well, using them in sentences together with the words you learned earlier, looking at correct and incorrect instances of that grammar rule. Each time, you expand more and more, bringing in more intricate aspects of the language, learning more vocabulary as a natural part of expanding your general facility with the language.
The most important part is that you practice using the language, expressing your own thoughts with it. Memorizing a dictionary will never teach you the language, nor will memorizing books or articles that use it. Reading with understanding is much better. Reading with understanding, together with using the language in conversation and writing as often as you can, is ideal. It is the best way to practice the vocabulary and grammar you've learned from a teacher or book and checking whether you really understand it. After all, consciously trying to memorize anything will only go so far; if you want to reach the point where you can use the language fluently, you have to practice it, so that each time you learn something new, it becomes ingrained, second-nature. This unconscious memorization is ultimately much more important.
In mathematics, we do not use our mouths, but our minds. Think of exercises from a book as conversation prompts. You should answer in the language of mathematics, as best you can, using the vocabulary and grammar you've learned so far. Note that knowing lots of vocabulary and grammar do  not, in and of themselves, let you participate in even the most rudimentary conversations - you have to have something to say first, and you have to practice expressing it in the language. Those are not things one can practice passively. So, without a doubt, learning mathematics requires an immense amount of active thinking.

You might find this post helpful: How Do You Go About Learning Mathematics?

Here are some relevant quotes:

*

*"What you have been obliged to discover by yourself leaves a path in your mind which you can use again when the need arises." - G. C. Lichtenberg

*"The only way to learn mathematics is to do mathematics." - Paul Halmos

*"Keep in mind that there are millions of theorems but only thousands of proofs, hundreds of proof blocks, and dozens of ideas. Unfortunately, no one has figured out how to transfer the ideas directly yet, so you have to extract them from complicated arguments by yourself." - Fedja Nazarov

*"Don't just read it; fight it! Ask your own questions, look for your own examples, discover your own proofs. Is the hypothesis necessary? Is the converse true? What happens in the classical special case? What about the degenerate cases? Where does the proof use the hypothesis?" - Paul Halmos

A: There are roughly two kinds of memorization: with sufficient understanding and without. Without enough understanding, our memory tends to fade more quickly than we would like it to. So I would say: try to memorize with understanding as much as we can.
From chat by t.b. about "memorizing" theorems and their proofs:

Always ask: what are the hypotheses used for? How does this assumption
  enter the argument? What is the crucial point of the proof, what do I
  need to remember in order to re-prove that result? What is just
  standard technique, what is new to me?
Well, one could certainly ask for an outline of the proof, I believe.
  There are a few main ideas that one can try to isolate. I mean these
  six pages aren't six pages of pure calculation, they certainly are
  divided in some natural steps. Try to partition the proof in such a
  way that it looks natural. This takes a few hours to do, but if for
  some reason you know that this theorem is considered important for
  your exam, you probably need to really grasp these ideas.
If one proof doesn't help me a lot, I need a different angle of
  looking at things. If I find a place where things are presented the
  way I like it, I can then go back and see what the other author
  emphasizes and thus get a more complete picture.

When we are driven by the deadlines of homework and exams and don't have time to digest the ideas, we usually try to memorize them in a hurry.
Courses are sometimes arranged in ways that they contradict their original purposes. That is sad...

A: It is not a waste of time because the fact is when your in a test and it is limited time the faster answers come the better. 9

A: While committing essential information to memory makes sense, we are far from understanding the optimal use of memorization for learning math beyond the elementary stage, in part because little experimental research has been done.  As an analogy to memorization, we can consider distributed practice of problem solving.  Experiments have shown that distributed practice works better than mass practice.  But even there we don't have enough experiments with varied kinds of problems in real-life contexts with diverse students; and we have little sense of what the optimal spacing and amounts of practice might be.  At any rate, if you are going to memorize, it makes sense to distribute your efforts over time.  And, to follow up on the perceptive comment above about figuring out what to memorize, it seems reasonable to determine the key concepts and formulas in a given chapter of a textbook, then rank them from most important to least, and finally to apportion time to memorize them accordingly.  Note that a "formula" might mean a particularly useful worked problem.  It would be very helpful to have an optimal ratio of effort to deploy in memorization versus problem solving, but we don't have any research results to get beyond notional suggestions.

A: Yes to some extend you need to memories.
Example: You must remember what a prime number and a factor is before you can find prime factors of numbers. to remember that you need to memories and it obviously differs from person to person.


text:
Q: Can't launch localhost after index.html and path is changed my localhost is not launching. I changed index.html to index.php, then also changed launching path in angular.json
"options": {
        "outputPath": "dist/webas",
        "index": "src/index.php",
        "main": "src/main.ts",
        "polyfills": "src/polyfills.ts",
        "tsConfig": "src/tsconfig.app.json",
        "assets": [
          "src/favicon.ico",
          "src/assets"
        ],

my localhost http://localhost:4200/ after ng serve -o can't be reached/opened
Im using VScode, angular7

A: plz edit index to "index": "src/index.html"
if you want to run it in Php server, you can run ng build --prod and copy the dist folder to xampp/htdocs then open it ( here you should rename index.html to index.php )

redpajama_set_name: RedPajamaStackExchange


text:
Q: File uploader gives null when i want to sent it to my database I was trying to make a file uploader in laravel. But when i want to send it to database it have a null value when i send it to the controller. I don't know where I have to go to with this problem to fix it.
My view:

    <form method="POST" action="/admin/add-album/add">
        @csrf
        Album name
        <input type="text" name="album_name" class="form-control">

        <input id="file-upload" type="file" name="album_picture" accept="image/*">

        <input type="submit" name="submit" class="form-control">
    </form>

My controller:
 public function addAlbumDatabase(Request $request)
{
    request()->validate([
        'album_name' => ['required'],
    ]);

    $slug = $this->slugify(request('album_name'));
    $user = \Auth::user();
    dd($request->file('album_picture'));

    if ($files = $request->album_picture) {
        $destinationPath = 'public/images/';
        $profileImage = date('YmdHis') . "." . $files->getClientOriginalExtension();
        $files->move($destinationPath, $profileImage);
    } else {
        dd("mislukt om de image up te loaden");
    }

    Albums::create([
        'user_id' => $user->id,
        'album_name' => request('album_name'),
        'album_profile_picture' => $profileImage,
        'album_slug'=> $slug
    ]);

    return redirect('admin/add-album');
}

my model:
class Albums extends Model {
protected $fillable = [
    'user_id', 'album_name', 'album_profile_picture', 'album_slug'
];

}

A: Add enctype="multipart/form-data" in your form rule. So:
    <form method="POST" action="/admin/add-album/add" enctype="multipart/form-data">


text:
Q: What could cause a deterministic process to generate floating point errors Having already read this question I'm reasonably certain that a given process using floating point arithmatic with the same input (on the same hardware, compiled with the same compiler) should be deterministic. I'm looking at a case where this isn't true and trying to determine what could have caused this.
I've compiled an executable and I'm feeding it the exact same data, running on a single machine (non-multithreaded) but I'm getting errors of about 3.814697265625e-06 which after careful googling I found is actually equal to 1/4^9 = 1/2^18 = 1/262144. which is pretty close to the precision level of a 32-bit floating point number (approx 7 digits according to wikipedia)
My suspicion is that it has something to do with optimisations that have been applied to the code. I'm using the intel C++ compiler and have turned floating point speculation to fast instead of safe or strict. Could this make a floating point process non-deterministic? Are there other optimisations etc that could lead to this behaviour?
EDIT: As per Pax's suggestion I recompiled the code with floating point speculation turned to safe and I'm now getting stable results. This allows me to clarify this question - what does floating-point-speculation actually do and how can this cause the same binary (i.e. one compilation, multiple runs) to generate different results when applied to the exact same input?
@Ben I'm compiling using Intel(R) C++ 11.0.061 [IA-32] and I'm running on an Intel quadcore processor.

A: In almost any situation where there's a fast mode and a safe mode, you'll find a trade-off of some sort. Otherwise everything would run in fast-safe mode :-).
And, if you're getting different results with the same input, your process is not deterministic, no matter how much you believe it to be (in spite of the empirical evidence).
I would say your explanation is the most likely. Put it in safe mode and see if the non-determinism goes away. That will tell you for sure.
As to whether there are other optimizations, if you're compiling on the same hardware with the same compiler/linker and the same options to those tools, it should generate identical code. I can't see any other possibility other than the fast mode (or bit rot in the memory due to cosmic rays, but that's pretty unlikely).
Following your update:
Intel has a document here which explains some of the things they're not allowed to do in safe mode, including but not limited to:

*

*reassociation: (a+b)+c -> a+(b+c).

*zero folding: x + 0 -> x, x * 0 -> 0.

*reciprocal multiply: a/b -> a*(1/b).

While you state that these operations are compile-time defined, the Intel chips are pretty darned clever. They can re-order instructions to keep pipelines full in multi-CPU set-ups so, unless the code specifically prohibits such behavior, things may change at run-time (not compile-time) to keep things going at full speed.
This is covered (briefly) on page 15 of that linked document that talks about vectorization ("Issue: different results re-running the same binary on the same data on the same processor").
My advice would be to decide whether you need raw grunt or total reproducability of results and then choose the mode based on that.

A: If your program is parallelized, as it might be to run on a quad core, then it may well be non-deterministic.
Imagine that you have 4 processors adding a floating point value to the same memory location.  Then you might get
(((InitialValue+P1fp)+P2fp)+P3fp)+P4fp

or
(((InitialValue+P2fp)+P3fp)+P1fp)+P4fp

or any of the other possible orderings.
Heck, you might even get
 InitialValue+(P2fp+P3fp)+(P1fp+P4fp)

if the compiler is good enough.
Unfortunately, floating point addition is not commutative or associative. Real number arithmetic is, but floating point is not, because of rounding, overflow, and underflow.
Because of this, parallel FP computation is often non-deterministic.  "Often", because programs that look like
  on each processor
    while( there is work to do ) {
       get work
       calculate result
       add to total
    }

will be non-deterministic, because the amount of time that each takes may vary widely - you can't predict the order of operations.  (Worse if the threads interact.)
But not always, because there are styles of parallel programming that are deterministic.
Of course, what many folks who care about determinism do is work in integer or fixed point to avoid the problem.  I am particularly fond of superaccumulators, 512, 1024, or 2048 bit numbers that floating point numbers can be added to, without suffering rounding errors.

As for a single threaded application: the compiler may rearrange the code.  Different compilations may give different answers.  But any particular binary should be deterministic.
Unless... you are working in a dynamic language. That performs optimizatuions that reorder the FP computations, that vary over time.
Or unless...  really long shot: Itanium had some features, like the ALAT, that made even single threaded coded non-deterministic.  You are unlikely to be affected by these.


text:
Q: Htaccess redirect match I'm trying to do some .htaccess redirects, removing the "online" from :
site.com/online/producator-pinguin.html to
site.com/producator-pinguin.html
I have the following .htaccess rule :
RewriteEngine On
RewriteRule ^online/producator-(.*).html$ /producator-$1.html [L,R=301]

This works, but the problem is that it also matches :
site.com/online/producator-pinguin/culoare-rosu.html
In the example, "pinguin" is a brand name, so the rule can not be hardcoded for pinguin, it should work with any word. (producator-x, producato-y, ...)
How can I rewrite the rule so it doesn't match the second example, only the first ?

A: RewriteRule ^online/producator-([^/]+).html$ /producator-$1.html [L,R=301]

The key part is [^/] which will prevent from matching subfolders.


text:
Q: How to identify a browser-window as a popup in Firefox-Extension? We are a bit in trouble.
We show some informations for specific sites in our own firefox extension (for several reasons we use a xul box-Element for that presentation).
We don't wan't the box to show in browser popups.
But: How do we identify a browser-window as a popup in our extension code (javascript)?
Thanks a lot!

A: You may check:

*

*if the window does have an opener => if(window.opener)
to determine if it was opend using javascript

*if the window does have an opener, check if it is  the top-window =>if(self==top)
to determine that the window is not a frame
When both conditions are true, you may assume that the window is a popup.


text:
Q: Double quotes in Jquery I have read several posts regarding usinq quotes in jQuery and have not been able to form my own query.
I have to check a span tag for a particular string.  The string i am searching for is:  role="alert"        (it has double quotes around the word alert.
$("span:contains('role="alert"')").each(function() {
        alert($(this).text());
    });

Can someone provide a query for this?

A: You can simply use:
$('span[role="alert"]').each(function() {
    alert($(this).text());
});

A: $("span:contains('role=\"alert\"')")


text:
Q: Get notifications of new threads / deleted threads under Windows When you create a DLL you can get notifications about new threads / exiting threads in the DllMain function (DLL_THREAD_ATTACH/DLL_THREAD_DETACH).
Is there a way to get these or equivalent notifications from Windows within an (non managed) Executable?

A: Yes - include a small stub DLL in your process that simply monitors DLL_THREAD_ATTACH and DLL_THREAD_DETACH in the way you want.


text:
Q: onBackPressed not called in TabActivity this is my first post and I have written it after scanning for some "likely proposed" solutions for "onBackPressed" and "onKeyDown" problems. I Think they don't fit for my problem.
But enlight me if I am wrong (sorry for that in case).
Ok, here is my simple problem.
I have 2 activites :
A : Starter Activity (normal Activity)
B : MainMenu Activity  (TabActivity)
Splash activity (A) does some init stuff and some checks. If it is satisfied, it simply calls the intent for the main menu Acitvity (B).
Activity B just fills a tabHost for 4 sub activities.
Ok so far it's all fine. But
I want activity B to react on the BACK-button. It should not let the user back to the starter splash screen but instead should send the app to the background (home button pressed).
But activity B never reacts on it. No logcat output is ever written.
This is my code of activity B.
public class StartScreenTab extends TabActivity {
    private final static String TAG = StartScreenTab.class.getSimpleName();
    private MyTabHostWrapper tabHost;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initTab();

    }

    private void initTab() {
        Log.i(TAG, "init Main Tabs...");
        tabHost = new MyTabHostWrapper(this);
        // tab Start
        tabHost.addNewTabSpec("tab-start", R.string.app_name,
                R.drawable.ic_tab_start, StartScreen.class);

        // tab Karte
        tabHost.addNewTabSpec("tab-karte", R.string.umkreis_activity_name,
                R.drawable.ic_tab_karte, UmkreisActivity.class);

        // tab Liste
        tabHost.addNewTabSpec("tab-liste", R.string.liste_activity_name,
                R.drawable.ic_tab_liste, ListeActivity.class);

        // tab Settings
        tabHost.addNewTabSpec("tab-prefs", R.string.menu_settings,
                R.drawable.ic_tab_preferences, MyPrefsActivity.class);

        tabHost.setFontColor("#FFFFFF");

    }

    @Override
    public void onDestroy(){
        Log.i(TAG, "onDestroy called.");
        super.onDestroy();
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Log.i(TAG, "KEY 'back' released");
            onBackPressed();
            return true;
        }
        return super.onKeyUp(keyCode, event);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Log.i(TAG, "KEY 'back' pressed");
            onBackPressed();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        Log.i(TAG, "BACK pressed");
        moveTaskToBack(true);
        return;
    }
}

I can see the logcat output from the init and from the onDestroy. But nothing from onKeyDown, onKeyUp and onBackPressed.
Can you help me please? Thx.

A: The reason is TabActivity lose focus , And I found the solution, invoke the code in your normal Activity
@Override
public void onBackPressed() {
    if (getParent() != null) {
        getParent().onBackPressed();
    } else {
        super.onBackPressed();
    }
}

A: I think it may be caused by the tabHost. I didn't specify any focus command for the activities bound to the tabs, so maybe the "back" event is lost somewhere.
I solved my problem by evading the whole situation. I removed the splash activity (A) and moved its init-functions to the StartScreenTab activity (B).
So I don't need to react on the back-event any further because the standard behaviour is now satisfying.


text:
Q: Invoke two different controls at the same time I am creating a Form and try to show as a modal, providing a parent.
Form modal = new Form();
modal.ShowModal(OtherForm);

The problem is that they are accessed from different threads and raise exceptions. I'm trying to use invoke following "the microsoft way", that means using delegates. However I have two controls modal and OtherForm that need to be invoked at the same time. If I invoke only one of them, I'll get exception that the other one was accessed from a different thread and vice-versa.
The code below is mockup solution which leads to stack overflow due to invoke loop. How this can be solved?
public static void ShowModalForm(Form f, Control parent)
{
    if (parent.InvokeRequired || f.InvokeRequired)
    {
        ShowModalFormCallback d = new ShowModalFormCallback(ShowModalForm);
        f.Invoke(d, new object[] { f, parent });
        parent.Invoke(d, new object[] { f, parent });
    }
    else
    {
        f.ShowDialog(parent);
    }
}

A: I'm just guessing, but this might work?
public static void ShowModalForm(Form f, Control parent)
{
    if (parent.InvokeRequired)
    {
        ShowModalFormCallback d = new ShowModalFormCallback(ShowModalForm);
        parent.Invoke(d, new object[] { f, parent });
    }
    else
    {
        f.ShowDialog(parent);
    }
}

But I really don't understand what you're trying to do. And does f really reference an existing instantiation of a Form object?


text:
Q: How to find the closing price of a historical candle whose bar_index is known I would like to find the closing price of a historical candle whose bar_index  value is known (for example: 4530). I have no other information about this candle. How could I find the closing price of this candle?
I tried to use ta.valuewhen(condition=bar_index == 4530, source=close, occurrence=0), but I get NaN.
Thanks

A: You can use the history reference operator for this.
If target is your target bar_index (4530), it is bar_index - target bars away from the current bar.
So, something like this should do:
target_idx = 4530
target_idx_diff = bar_index - target_idx
is_target_idx_valid = bar_index >= target_idx

float close_at_target_idx = is_target_idx_valid ? close[target_idx_diff] : na


text:
Q: Form in Form is not allowed, but what else I fetch SQL data with a while loop and insert the data into a table. With a form and a  submit button i can save modified values.
My simplified code:

    <?php
//SQL QUERY
//...

while ($row = mysql_fetch_array($sql_header)) {
    $var_ab = $row['ab'];
    $var_id = $row['id'];
?>
          <form id="form1" action="" method="POST">

                   <input type="text" value="<?php echo $var_ab; ?>"

                   <input type="text" value="<?php echo $var_id; ?>"

       //PLACEHOLDER FOR SECOND FORM
       <?php
}
?>

                 <input type="submit" name="save" value="SAVE" class="classsubmit" />

        </form>

So far, so good. So, how can I insert a second form to delete an entry? I've tried to place this code (PLACEHOLDER FOR SECOND FORM - see above)

<form id="form2" action="" method="POST">
       <input type="text" value="<?php echo $var_id;?>"
</form>

but it's not working and it's not allowed to nest forms.
Any suggestions?

A: If you only want to delete an entry on the page or in the database you could try a button or a span with an onclick function.
for example:
    <span onclick="window.location='?delete=<?php echo $row[(unique-value-in-database-from-this-row)]; ?>'; return false">Delete entry

Make sure you add return false or the first form will be submitted. If you use a button make sure it has type="button"
On this page could be a PHP code like this:
   if(isset($_GET['delete']))
   {
      $item = $_GET['delete'];
   //SQL connect
      $result = mysql_query($conection ,"DELETE FROM table WHERE uniquevalue='$item'");
   }

I hope gives an idea for a solution.


text:
Q: Setting table td element to a custom angular directive I want to update a td of a table to utilise a custom angularjs directive.
I have tried td.innerHtml = "<my-directive></my-directive>" and the html for myDirective is

hi

The directive code has
replace: true,
When I inspect the element I have td.innerHtml = "<my-directive></my-directive>" and not
hi

How can I change a table td element to use a custom directive.

A: Angular Limitations
Angular cannot respond to DOM changes that occur after the application is loaded, to do so would cause severe performance issues within the application. In order to resolve this you should limit DOM changes to those that occur within the angular application.
Workaround
If for whatever reason you MUST edit the DOM outside of the angular scope you can compile the elements manually using
$compile(html)


text:
Q: sfdx force source convert not allowing spaces in names I'm using SFDX on a Windows machine.
The following command is giving me errors when running from a bash terminal:
sfdx force:source:convert -d mdapi -n 'My Alias'

It keeps returning this error:
'D:\Program' is not recognized as an internal or external command,
 operable program or batch file.

I've tried using double quotes as well, but the result is the same.

A: Enclose the path in single or double quotes
sfdx force:source:deploy -x "C:\Users\tania.sen\OneDrive - SourceGitREP\GIT_SFDX\manifest\CustomMetadata_Object.xml" -l RunSpecifiedTests -r RecurringBillin_Test --loglevel fatal -c


text:
Q: How to specify region when creating a Watson service using the ibmcloud command line I'd like to create speech-to-text service in specify "Tokyo region" by ibmcloud command.
I knew, I can create speech-to-text service in specify "Tokyo region" by ibmcloud portal.
could you tell me please how to create service specify region.

A: ibmcloud resource service-instance-create myspeechtotext speech-to-text lite jp-tok

Here is how I figured this out:
$ ibmcloud regions
Listing regions...

Name       Display name
au-syd     Sydney
jp-osa     Osaka
jp-tok     Tokyo
eu-de      Frankfurt
eu-gb      London
us-south   Dallas
us-east    Washington DC

$ ibmcloud catalog search speech
Getting catalog entries...
OK
Id                                     Name                 Kind
oss.speech-to-text                     oss.speech-to-text   oss
oss.text-to-speech                     oss.text-to-speech   oss
bc35fb8c-bc5b-431b-859e-3861771d5843   speech-to-text       service
282c1d79-9176-4597-9cff-941a8d6cfd4c   text-to-speech       service

$ ibmcloud catalog entry bc35fb8c-bc5b-431b-859e-3861771d5843
Getting catalog entry...
OK
ID                                     Name             Kind      Group   Provider   Tags
bc35fb8c-bc5b-431b-859e-3861771d5843   speech-to-text   service   false   IBM        apidocs_enabled,eu_access,gc_migrate,ibm_created,ibm_dedicated_public,ibm_release,lite,rc_compatible,watson

$ ibmcloud resource service-instance-create --help
NAME:
  service-instance-create - Create a service instance

USAGE:
   ibmcloud resource service-instance-create NAME (SERVICE_NAME | SERVICE_ID) SERVICE_PLAN_NAME LOCATION [-d, --deployment DEPLOYMENT_NAME] [-p, --parameters @JSON_FILE | JSON_STRING ] [-g RESOURCE_GROUP] [--service-endpoints SERVICE_ENDPOINTS_TYPE]

OPTIONS:
   -d value, --deployment value  Name of deployment
   -p value, --parameters value  JSON file or JSON string of parameters to create service instance
   -g value                      Resource group name
   --service-endpoints value     Types of the service endpoints. Possible values are 'public', 'private', 'public-and-private'.

$ ibmcloud resource service-instance-create myspeechtotext speech-to-text lite jp-tok


text:
Q: Junit with HSQL/H2 without Spring/Hibernate I am trying to use H2 or HSQL for my unit testing. But my application is not of spring and hibernate. It seems most of the references are there only with spring and hibernate for HSQL/H2 in memory db for unit testing.
Can someone point to a right reference where only hsql/h2 is used with junit plainly? Appreciate your time.

A: I ususally do something like this:
In the @Before method I establish a connection to a memory database, something like this:
@Before
public void setup()
{
   this.dbConnection = DriverManager.getConnection("jdbc:hsqldb:mem:testcase;shutdown=true", "sa", null);
}

The connection is stored in an instance variable, so it's available for each test.
Then if all tests share the same tables, I also create those inside the setup() method, otherwise each tests creates its own tables:
@Test
public void foo()
{
   Statement stmt = this.dbConnection.createStatement();
   stmt.execute("create table foo (id integer)");
   this.dbConnection.commit();
   ... now run the test
}

In the @After method I simplic close the connection which means the in-memory database gets wiped and the next test runs with a clean version:
@After
public void tearDown()
  throws Exception
{
   dbConnection.disconnect();
}

Sometimes I do need to run unitt-tests agains a real database server (you can't test Postgres or Oracle specific features using HSQLDB or H2). In that case I establish the connection only once for each Testclass instead of once for each test method. I then have methods to drop all objects in order to cleanup the schema.
This can all be put into a little utility class to avoid some of the boilerplate code. Apache's DbUtils can also make life easier as will DbUnit if you want to externalize the test data somehow.

A: I know I am a little late to the party :-)
I had the same issue a while back and created a JUNIT integration that use the @Rule mechanism to setup an in-memory database for JUnit tests. I found it to be a real easy and good way to be able to test my database integration code. Feedback is more than welcome.
The source code and instructions for use can be found at https://github.com/zapodot/embedded-db-junit


text:
Q: publish a release version of web site I have a web site that is created in visual studio 2010 through: File > New > Web site (it is not a Web Project).
I want to publish a release version of my web site but there is no 'Release' mode in VS and there is no possibility to add 'Release' mode through Build > Configuration manager.
How can I publish a release version of my web site ??(I can not convert my web site to a Web Project)
Thank you very mush for your reply.

A: When you have a website project and your using VS 2010 then somewhere amongst the menu options in the menubar across the top should be an option caled COPY WEBSITE (I think its in the website menu).
So you click WEBSITE > COPY WEBSITE then you will see a new tab appear very similar to an FTP kind of interface, with your LOCAL files on the left and the remmote server hosting on the right.
You could use either FTP or Direct upload but the very last time I could only use it via FTP.
(Of course this may be a personal issue and not affect anyone else).
It goes without saying that if you dontr have a server to upload your website to then it can not be "released" as you called it.
Usually the server or hosting is either on your own server or on a remote (Paid for) server with a service provider.
With reference to the photo below....
Area-1 is where you enter the FTP or HTTP address of the server where you will upload te files.
Loacl-Files This shows your completed website files
Remote-Files This shows the files on the server
Controls These button are used to upload or download files to and from the server
Note that you must have an FTP username and password to use FTP/HTTP transfer,
Some hosts may prefer you to use your admin account username and password.
Hope this helps point you in the right direction


text:
Q: numpy indexing: shouldn't trailing Ellipsis be redundant? While trying to properly understand numpy indexing rules I stumbled across the following. I used to think that a trailing Ellipsis in an index does nothing. Trivial isn't it? Except, it's not actually true:
Python 3.5.2 (default, Nov 11 2016, 04:18:53)
[GCC 4.8.5] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy as np
>>>
>>> D2 = np.arange(4).reshape((2, 2))
>>>
>>> D2[[1, 0]].shape; D2[[1, 0], ...].shape
(2, 2)
(2, 2)
>>> D2[:, [1, 0]].shape; D2[:, [1, 0], ...].shape
(2, 2)
(2, 2)
>>> # so far so expected; now
...
>>> D2[[[1, 0]]].shape; D2[[[1, 0]], ...].shape
(2, 2)
(1, 2, 2)
>>> # ouch!
...
>>> D2[:, [[1, 0]]].shape; D2[:, [[1, 0]], ...].shape
(2, 1, 2)
(2, 1, 2)

Now could someone in the know advise me as to whether this is a bug or a feature?
And if the latter, what's the rationale?
Thanks in advance,
Paul

A: Evidently there's some ambiguity in the interpretation of the [[1, 0]] index.  Possibly the same thing discussed here:
Advanced slicing when passed list instead of tuple in numpy
I'll try a different array, to see if it makes things any clear
In [312]: D2=np.array([[0,0],[1,1],[2,2]])
In [313]: D2
Out[313]:
array([[0, 0],
       [1, 1],
       [2, 2]])

In [316]: D2[[[1,0,0]]]
Out[316]:
array([[1, 1],
       [0, 0],
       [0, 0]])
In [317]: _.shape
Out[317]: (3, 2)

Use of : or ... or making the index list an array, all treat it as a (1,3) index, and expand the dimensions of the result accordingly
In [318]: D2[[[1,0,0]],:]
Out[318]:
array([[[1, 1],
        [0, 0],
        [0, 0]]])
In [319]: _.shape
Out[319]: (1, 3, 2)
In [320]: D2[np.array([[1,0,0]])]
Out[320]:
array([[[1, 1],
        [0, 0],
        [0, 0]]])
In [321]: _.shape
Out[321]: (1, 3, 2)

Note that if I apply transpose to the indexing array I get a (3,1,2) result
In [323]: D2[np.array([[1,0,0]]).T,:]
...
In [324]: _.shape
Out[324]: (3, 1, 2)

Without : or ..., it appears to strip off one layer of [] before applying it to the 1st axis:
In [330]: D2[[1,0,0]].shape
Out[330]: (3, 2)
In [331]: D2[[[1,0,0]]].shape
Out[331]: (3, 2)
In [333]: D2[[[[1,0,0]]]].shape
Out[333]: (1, 3, 2)
In [334]: D2[[[[[1,0,0]]]]].shape
Out[334]: (1, 1, 3, 2)
In [335]: D2[np.array([[[[1,0,0]]]])].shape
Out[335]: (1, 1, 1, 3, 2)

I think there's a backward compatibility issue here. We know that the tuple layer is 'redundant': D2[(1,2)] is the same as D2[1,2].  But for compatibility for early versions of numpy (numeric) that first [] layer may be treated in the same way.
In that November question, I noted:

So at a top level a list and tuple are treated the same - if the list can't interpreted as an advanced indexing list.

The addition of a ... is another way of separating the D2[[[0,1]]] from D2[([0,1],)].
From @eric/s pull request seburg explains

 The tuple normalization is a rather small thing (it basically checks for a non-array sequence of length <= np.MAXDIMS, and if it contains another sequence, slice or None consider it a tuple).

[[1,2]] is a 1 element list with a list, so it is considered a tuple, i.e. ([1,2],).  [[1,2]],... is a tuple already.


text:
Q: Start Acitvity from Fragment I got my MainActivity(FragmentActivity) with ViewPager with FragmentPagerAdapter which creates OrdersFragment in which i have ListView. Now i want to start new Activity OnItemClickListener but i can't figure out how to do this.
This is OrdersFragment class:
public class OrdersFragment extends Fragment {

ListView lv;
private ArrayList<Order> d = new ArrayList<Order>();
private ordersAdapter adapter;

public OrdersFragment (){

}

public OrdersFragment setArguments(ArrayList<Order> orders){
    if(adapter == null) return this;
    adapter.setData(orders);
    Log.d("fragment", "zmiana");
    adapter.notifyDataSetChanged();
    return this;
}

@Override
public View onCreateView(LayoutInflater inflater,
        ViewGroup container, Bundle savedInstanceState) {
    //d.add(new Order());
    Log.d("fragment", "orders fragment created" + d.toString());
    lv = (ListView) inflater.inflate(R.layout.orders_list, container, false);
    lv.setOnItemClickListener(itemClicked);
    adapter = new ordersAdapter(inflater, d);
    lv.setAdapter(adapter);

    return lv;
}

public ArrayList<Order> getOrders(){
    return d;
}

OnItemClickListener itemClicked = new OnItemClickListener(){
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
            long id) {
        Log.d("fragment", "clicked!!" + parent.getItemAtPosition(position).toString());
        startActivity(new Intent(OrdersFragment.this, OrderActivity.class));
    }
};
}

It says that Intent constructor is undefined and also when i move over startActivity it says Note: This element neither has attached source nor attached Javadoc and hence no Javadoc could be found. And it states that this fuction is defined in android.support.v4.app.Fragment.startActivity but I'm acually import this:
import android.app.Activity;
import android.content.Intent;

What I'm doing wrong?

A: In Fragment we have to pass context as getActivity(), replace your code with this below code it will work.
OnItemClickListener itemClicked = new OnItemClickListener() {
   @Override
   public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
       Log.d("fragment", "clicked!!" + parent.getItemAtPosition(position).toString());
       startActivity(new Intent(getActivity(), OrderActivity.class));
   }
};

A: Try this pass context as getActivity() to intent
 OnItemClickListener itemClicked = new OnItemClickListener(){
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                long id) {
            Log.d("fragment", "clicked!!" + parent.getItemAtPosition(position).toString());
            startActivity(new Intent(getActivity(), OrderActivity.class));
        }
    };

A: OnItemClickListener itemClicked = new OnItemClickListener(){
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
            long id) {
        if(getActivity() != null) {
            Log.d("fragment", "clicked!!" + parent.getItemAtPosition(position).toString());
            startActivity(new Intent(getActivity(), OrderActivity.class));
        }
    }
};

getActivity() will give you the Activity context that you can use to start the new Activity. In some rare cases getActivity() can return null so checking getActivity() is not null might not harm in your case.


text:
Q: What is "delayed environment variable expansion" Is there someone to explain exactly what is delayed environment variable expansion in simple terms or point to a post that can understand. Here is my questions

*

*What can't I achieve without this

*In which practical situations uses this

*Any alternative

A: %Var% is expanded when a line is read. As lines can have multiple commands, !var! is expanded when used. In MS-DOS !var! (accessed in script by %!var!%) is a legal variable name so you have to turn on a special mode to access. This is so MS-DOS batch files can run in CMD without editing.


text:
Q: faye authentication with token I am working with faye messaging system and I want to add authentication! I worked my way through the website and followed the tutorial.
On the Client I have an extension for outgoing Messages:
var droneFaye = new faye.Client("/faye", {
            timeout: 120
        });
var USER_TOKEN = 'ifd63cylqwsyaq9c2ptzywjujgtfpxs';

    droneFaye.addExtension({
        outgoing: function(message, callback) {
            if (message.channel !== '/meta/subscribe')
                return callback(message);

            message.ext = message.ext || {};
            message.ext.token = USER_TOKEN;
            console.log(message);
            callback(message);
        }
    });

On the Server:
var token = 'ifd63cylqwsyaq9c2ptzywjujgtfpxs'

    var serverAuth = {
    incoming: function(message, callback) {
        // Let non-subscribe messages through

        if (message.channel !== '/meta/subscribe')
            return callback(message);

        // Get subscribed channel and auth token
        var msgToken = message.ext && message.ext.token;

        // Find the right token for the channel
        if (token !== msgToken) {
            message.error = 'Invalid subscription auth token';
        }
        console.log(message);
        callback(message);
    }
};

var adapter = new faye.NodeAdapter({
    mount:'/faye',
    timeout:45
});
adapter.addExtension(serverAuth);
adapter.attach(httpServer);

I have a subscription on the server like this:
adapter.getClient().subscribe("/drone/move", function(cmd) {});

Alright! So when I start the server and there is NO CLIENT it already calls the extension for the subscriptions and it will output on the console:
{ channel: '/meta/subscribe',
  clientId: '2isdeb0ds77zl0lh82ob1kqu29y1cajnv80',
  subscription: '/drone/move',
  id: '2',
  error: 'Invalid subscription auth token' }

Once a Client connects to the server it will again call the extension and it will output this:
{ channel: '/meta/subscribe',
  clientId: '3kechs0c7smpc05z5o7d0a8qcd301d8zi41',
  subscription: '/drone/move',
  id: '3',
  ext: { userId: 18787, token: 'ifd63cylqwsyaq9c2ptzywjujgtfpxs' } }

So this looks good! But no other messages are going to arrive on the server even though they have the correct token and there is no error message!
Just for information. If you add a error key with a value to the message object it will not pass the message to its subscription...its supposed to be like that!..
Also when I comment out the message.error in the extension it works fine but of course there is not authentication.
So does anyone know why the server calls the extension even though there is no client and second why does faye not give the message to its subscription even though there is no error in the message object?
thx!

A: Question was also asked, and answered here:

This is caused by the call to adapter.getClient().subscribe().
[...] the server-side client (<adapter>.getClient()) returns a connection to the server, thus walks through the same extensions (incoming, outgoing) as the client does.
[...] Attach an outgoing extension and you'll see it being responded to the server-client.


text:
Q: UnboundLocalError happened I am using MNIST dataset to study MLP(multi layer perceptron) in python. While running the code given below I get the following error message:
UnboundLocalError: local variable 'x' referenced before assignment

Where should I insert "global x" or what should I do? Here is my code:
def homework(train_X, train_y, test_X, test_y):

    epoch = 10000
    batch_size = 20
    learning_rate = 1e-3
    input_size = 784
    hidden_size = 100
    output_size = 10
    data_num = train_X.shape[0]

    np.random.seed(0)
    W1 = np.random.randn(input_size, hidden_size)
    b1 = np.zeros(hidden_size)
    W2 = np.random.randn(hidden_size, output_size)
    b2 = np.zeros(output_size)
    for n in range(epoch):
        loss_sum = 0
        for i in range(0, data_num, batch_size):
            x = train_X[i:i+batch_size]
            y = train_y[i:i+batch_size]
            fwd = forward(x)
            loss_sum += cross_entropy(y, fwd['prob'])

            grad = network.gradient(x, y)

            for key in ('W1', 'b1', 'W2', 'b2'):
                network.params[key] -= learning_rate * grad[key]

            loss = network.loss(x, y)
            train_loss_list.append(loss)

        if np.mod(n, 1000) == 0:
            pred_y = np.argmax(forward(test_X)['prob'], axis=1)
            accuracy = f1_score(test_y, pred_y, average='macro')
            print("epoch: %5d, loss_sum: %.5f, accuracy: %.5f" % (n, loss_sum, accuracy))

    pred_y = np.argmax(forward(test_X)['prob'], axis=1)
    return pred_y

def softmax(x):
    x -= np.max(x, axis=1).reshape((-1, 1))
    return np.exp(x) / np.sum(np.exp(x), axis=1).reshape((-1, 1))

def cross_entropy(y, output):
    batch_size = y.shape[0]
    return -np.sum(np.log(output[np.arange(batch_size), y])) / batch_size

def sigmoid(x):
    return 1 / (1 + np.exp(-x))

def forward(x):
    fwd = {}
    fwd['h1'] = sigmoid(np.dot(x, W1) + b1)
    fwd['prob'] = softmax(np.dot(fwd['h1'], W2) + b2)
    return fwd

from sklearn.utils import shuffle
from sklearn.metrics import f1_score
from sklearn.datasets import fetch_mldata
from sklearn.model_selection import train_test_split

import numpy as np

def load_mnist():
    mnist = fetch_mldata('MNIST original')
    mnist_X, mnist_y = shuffle(mnist.data.astype('float32'),
                           mnist.target.astype('int32'), random_state=42)

    mnist_X = mnist_X / 255.0

    return train_test_split(mnist_X, mnist_y,
            test_size=0.2,
            random_state=42)

def validate_homework():
    train_X, test_X, train_y, test_y = load_mnist()

    train_X_mini = train_X[:100]
    train_y_mini = train_y[:100]
    test_X_mini = test_X[:100]
    test_y_mini = test_y[:100]

    pred_y = homework(train_X_mini, train_y_mini, test_X_mini, test_y_mini)
    print(f1_score(test_y_mini, pred_y, average='macro'))

def score_homework():
    train_X, test_X, train_y, test_y = load_mnist()
    pred_y = homework(train_X, train_y, test_X, test_y)
    print(f1_score(test_y, pred_y, average='macro'))

validate_homework()
# score_homework()


text:
Q: NSData( contentsOfURL: url ) return nil var fileu = strData.objectForKey("url") as String
var fileurl:NSURL = NSURL(string: fileu)!

var dataFromUrl:NSData! = NSData(contentsOfURL: fileurl)

println(dataFromUrl);

When I tested the url in the browser, the url is working.
But in
var dataFromUrl:NSData! = NSData(contentsOfURL: fileurl)

return nil.
fileu is "http://localhost/Web/TMS_ReadFile.ashx?FileID=0"

when I dropped it in the address bar, it actually download .
Did anyone face this kind of issue before?
Thanks :)


text:
Q: Returning index of vector I have a vector that looks like this:
c(1,1,1,1,2,2,2,2,3,3,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5..)

I want to get the index of when the element changes, i.e. (1,5,9,...)
I know how to do it with a for loop, but I am trying a faster way as my vector is very large.
Thanks,

A: Try
which(c(TRUE,diff(v1)!=0))

Or
 match(unique(v1), v1)

Or if the vector is sorted
 head(c(1, findInterval(unique(v1), v1)+1),-1)

data
v1 <- c(1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4,
    4, 4, 5, 5, 5, 5, 5)

A: Another fun approach:
v1 <- c(1, 1, 2, 3, 4, 4, 5, 6, 7, 7, 7, 8)
head(c(1, cumsum(rle(v1)$lengths) + 1), -1)

Or if you have magrittr then it can become
library(magrittr)
v1 %>%
  rle %>%
  .$lengths %>%
  cumsum %>%
  add(1) %>%
  c(1, .) %>%
  head(-1)

Result: 1  3  4  5  7  8  9 12
Might look weird but it's fun to think that through :)
Explanation: cumsum(rle(v1)$lengths) gets you almost all the way there, but it'll give you the index of where a sequence ends rather than where the next sequence starts, so that's why we add one to each element, append the index 1, and remove the last element.


text:
Q: List of all facebook events in a given location in the last two years What I am trying to do
I am trying to extract a list of all public facebook events that have happened in a given city in 2012 and 2013. Furthermore for each of them, I want to extract the following:

*

*event name

*event description

*date

*location

*number of people on attending/maybe/declined

What I have tried so far
I have been trying the following query in graph explorer
search?q={Oslo}& [type={event}](#searchtypes)

I have ignored the date range constraint for now. I figure that I can fix that later.
The problem
This is listing status updates (stories), places and everything else, and returning it as JSON objects. However, this won't provide with me with all the data fields that I require. Any ideas?
Sidenote
I have tried looking into FQL but apparently that cannot do a search like this? (If it can, feel free to help out). The closest I got was this:
SELECT eid FROM event_member WHERE uid IN
(SELECT page_id FROM place WHERE
 distance(latitude, longitude, "37.76", "-122.427") < 1000)

But this only gives me events in the future. Maybe if it allowed me to look in the past too?

A: Searching through public objects which you aren't linked to in any way (no participation, no invitation) can only be done through the Graph Search API, not with the Graph API nor FQL.
Currently, this is the only documentation for Graph Search. You will see that this API doesn't offer much possibilities, so if you want to achieve your goal, you will have to cobble something together. There is not any direct way to do this.
If we gather what is being told about events, this is pretty much everything we have:

Search Types
Events: https://graph.facebook.com/search?q=conference&type=event
Fields
You can restrict the fields returned by these searches using the
?fields= URL parameter, in the same way you can when reading other
objects. For example, to get only the names of events, you can do the
following:
Event Names:
https://graph.facebook.com/search?fields=name&q=conference&type=event
Time
When searching for public posts or posts on the user's News Feed, you
can page over the results by using the since, until and limit
parameters. since and until both accept a unix timestamp. When paging
back in time, you should use until in conjunction with limit where
until is the unixtime value of the created_time field in the last
object returned by your previous query. When paging forward in time
you should set since to be the unixtime value of the created_time
field in the first object returned by your previous query. Please
note, you can only search about 1 to 2 weeks back in the News Feed.

The next thing to know is that the result set is composed of the events for which one of their fields contains the string you are looking for (q=Oslo). So, "Oslo" may appear in either the message, in the description, by luck in the  location field and by misfortune in the timezone field.
You will then have to filter out the results "manually". You might just search for events containing "Oslo" and then check if the location indeed contains "Oslo. Or if you easily want to find events with a specific location, I advice you to search for strings formatted as "City, Country", because this is how Facebook format cities. So you might just do:
search?fields=location&q="Oslo, Norway"&type=event&since=1356994800

Where 1356994800 is the unixtime since then you want to retrieve events.
Possible result:
{
  "data": [
    {
      "location": "Oslo, Norway",
      "id": "211893915563330",
      "start_time": "2022-02-08T00:00:00"
    },
    {
      "location": "Lillestrøm, Norway",
      "id": "641379122561097",
      "start_time": "2015-09-06T09:00:00+0200"
    },
    {
      "location": "Oslo, Norway",
      "id": "1434492323451716",
      "start_time": "2014-11-06T20:45:00+0100"
    },
    {
      "location": "Oslo, Norway",
      "id": "563423357073321",
      "start_time": "2014-09-20"
    },

    ...

    {
      "location": "Oslo, Norway",
      "id": "628230923890648",
      "start_time": "2013-01-16T19:00:00+0100"
    }
  ],
}

Then, perhaps use the Google Maps API to find out if the found locations are indeed close to Oslo. I.e. "Lillestrøm, Norway" is quite close from it.

A: Looks like FQL can give you the desired result.
This FQL (which is extension to what you started) will show you all events between 2012 and 2013 with the data about the event you wanted:
select
    eid,
    name,
    description,
    location,
    all_members_count,
    attending_count,
    unsure_count,
    not_replied_count,
    declined_count,
    start_time,
    end_time,
    venue
from
    event
where
    eid in
    (
        select
            eid,
            start_time
        from
            event_member
        where
            uid in
            (
                select
                    page_id
                from
                    place
                where
                    distance(latitude, longitude, "37.76", "-122.427") < 1000
            ) and
            start_time > "2012-01-01"
    ) and
    end_time < "2013-01-01" and
    end_time <> 'null'

And this how one of the results I got for running this query:
{
  "eid": 170775033066718,
  "name": "Lavender Diamond at The Chapel - Dec 11",
  "description": "Get tickets: http://ticketf.ly/SUb4w9\nDetails: http://www.thechapelsf.com/event/184715/\n\nVERY SPECIAL GUEST WILL BE ANNOUNCED DAY OF SHOW",
  "location": "The Chapel",
  "all_members_count": 92,
  "attending_count": 30,
  "unsure_count": 3,
  "not_replied_count": 59,
  "declined_count": 4,
  "start_time": "2012-12-11T20:00:00",
  "end_time": "2012-12-12T00:00:00",
  "venue": {
    "street": "",
    "city": "",
    "state": "",
    "country": "",
    "latitude": 37.760503799154,
    "longitude": -122.42123452518,
    "id": 113634312122520
  }
}


text:
Q: C++ XML parser QT - not working Below is my code & xml file. I am trying to read a xml file and store the contents. But its not working. Please help
int ParseConfigFile::populateUserValues ( string &OS, string &dir, string &logPath )
{
    QDomDocument doc;
    QDomElement element;

    QFile file("config_v1.xml");

    if ( doc.setContent( file.readAll() ) == false )
        return 1;

    element = doc.documentElement();

    QDomNodeList list = element.childNodes();
    QDomElement firstChild = list.at(0).toElement(); // will return the first child
    QDomElement secondChild = list.at(1).toElement();
    QDomElement thirdChild = list.at(2).toElement();

    QString s1,s2,s3;
    s1 = firstChild.text();
    s2 = secondChild.text();
    s3 = thirdChild.text();

    OS = s1.toStdString();
    dir = s2.toStdString();
    logPath = s3.toStdString();

    return 0;
}

and my XML
<?xml version="1.0"?>
<config>
  <type>LINUX</type>
  <dir>/home/</dir>
  <path>/var/log/</path>
</config>

A: You should instantiate the QDomDocument like this and then your code will work:
if ( doc.setContent(&file) == false )
        return 1;

QDomDocument can work with an IO device (like QFile) making this the optimum way to set the QDomDocument's content from a file.
Anyway, if you're trying to write a configuration file reader/writer I suggest you stick with QSettings
QSettings settings("MyCompany", "MyApp");
QString s1,s2,s3;
s1 = settings.value("type").toString();
s2 = secondChild..value("dir").toString();
s3 = thirdChild..value("path").toString();

The configuration file format won't be XML (it will be key=value) but you will hardly ever need to worry about the file itself. To set any value on the file is also easy:
QSettings settings("MyCompany", "MyApp");
settings.setValue("path", "/var/log/");

Your configuration file will look like this:
[General]
path=/var/log/

See: QSettings documentation


text:
Q: encode special characters python for csv output How can I get csv.writer.writerow to output á or è and other special characters along the same lines u, n....etc?
I am getting an error
UnicodeEncodeError: 'ascii' codec can't encode character u'\xed' in position 37: ordinal not in range(128)
Have tried some of the suggestions in this article with no avail
rowPrinter = []

while x < y:
     print "Data in at Line " + str(x + 1)
     rowPrinter.append([a[x], b[x], c[x]]])
     x = x + 1

x = 0
writer = csv.writer(outcsv, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL, lineterminator='\n')
writer.writerow(['a', 'b', 'c'])
while x < y:
    print rowPrinter[x]
    writer.writerow(rowPrinter[x])

A: You need to encode all the data that you are trying to write:
writer.writerow([sub.encode("utf-8") for sub in rowPrinter[x]])

If you have a mixture of data:
writer.writerow([sub.encode("utf-8")  if isinstance(sub, basestring) else sub for sub in rowPrinter[x]])


text:
Q: HiveQL equivalent of MySQL's TRUNCATE()? What is the HiveQL equivalent of MySQL's TRUNCATE()?
In MySQL:
mysql> SELECT TRUNCATE(2.465, 1);
+-------------------+
| TRUNCATE(2.465,1) |
+-------------------+
|               2.4 |
+-------------------+

I only know of HiveQL's ROUND(), however, I do not want any rounding to occur.
Reference: https://www.w3resource.com/mysql/mathematical-functions/mysql-truncate-function.php

A: Maybe a bit convoluted, but:
floor(2.465 * 10) / 10

A: Using regexp_extract:
select regexp_extract(2.456,'\\d+\\.?\\d?',0)

Result:
2.4

\\d+ means one or more digits,
\\.? means zero or one dot,
\\d? means zero or one digit
You may want to add also - sign at the regexp beginning: -?
The result is of type String. You can cast to float if necessary:
select cast(regexp_extract(2.456,'\\d+\\.?\\d?',0) as float)


text:
Q: For loop not give proper output by defining as below in smarty framework Anybody have an idea how to use for loop in smarty template? I want to define condition as below.
<?php
        $quer = "select * from users";
        $res1 = $conn->query($quer);
        $count = $res1->num_rows;

        $a = $count/10;
        $a = ceil($a);
            echo "
"; echo "
";

I want to convert below for loop in a smarty for loop how it is possible?
        for($b=1; $b<=$a ; $b++){
                ?><a href="home.php?page=<?php echo $b;?>" style="text-decoration:none;"><?php echo $b." ";?><?php
            }

    ?>

A: The code is simple (put it in your template file):
{for $b=1 to $end}
    {$b}
{/for}

Read more about smarty loops in documentation: for, foreach.


text:
Q: How to access Picasa Albums from Android App I am trying to access Picasa Albums using PicasawebService. This service requires authentication. How do I do this from an Android device, similar to what I have to do with Facebook Authentication?
What I mean is that Facebook SDK 4.x has a LoginManager, where I specify that I want to Login to my Facebook account with certain access privileges. If I am not currently logged in into my FB account, then FB login will show up, then it will ask me if I want to allow the user to access that was requested by the LoginManager.
On an Android device, I am already logged in, since I have to have a google account to have an Android device. Can someone point me to some sample code that will accomplish the above.
Thank You,


text:
Q: Countifs with two options I am trying to use a countifs to count the places where a store number has either "UE" or "RX" attached to it (in addition to if it matches one other piece of criteria).  So for example the criteria would be something like "A16= criteria & "500UE" or "600RX".
Here is the formula I have currently:
=COUNTIFS('AUDIT 1'!$C$3:$C$121,$A16,'AUDIT 1'!$A$3:$A$121,"=*UE")

Now I need to add something to the end of this to the effect of:
,'AUDIT 1'!$A$3:$A$121,"=*RX"

But simply adding that results in no count obviously.  I understand that, but I'm not sure what revision (or different formula entirely) I should try.
Thanks in advance!

A: Wrap it ins a SUM() and use an array {}.
=SUM(COUNTIFS('AUDIT 1'!$C$3:$C$121,$A16,'AUDIT 1'!$A$3:$A$121,{"*UE","*RX"}))

It basically does two COUNTIFS and sums the two together.

A: I like Scott Craner's answer, but perhaps you might find it simpler to just add a second countif
=COUNTIFS('AUDIT 1'!$C$3:$C$121,$A16,'AUDIT 1'!$A$3:$A$121,"=*UE")+COUNTIFS('AUDIT 1'!$C$3:$C$121,$A16,'AUDIT 1'!$A$3:$A$121,"=*RX")

(Edited - originally said Scott's proposal used an array formula, which it does not)


text:
Q: Does anyone have a clue how to solve this second-order homogenous linear ODE? This example is provided by my workbook and it specifically asked to solve the equation via a substitution.
$$y'' + 2xy' - 2y=0$$.
What I have tried is the substitution $y=u(x) \cdot z, z(x)$ which yields absolutely no answer, because I get a harder ODE to solve than the first one:
$$z'' + (-x^3-3)z=0$$
Right now, there's no apparent substitution to be done. I suspect it has something to do with the coefficient $2x$ but I don't have the knowledge to actually do a substitution and solve it.
Can anyone help? Thanks!

A: The last two terms, as any multiple of $(xy'-y)$, cancel for $y=ax$, the second derivative is then zero too.
A second basis solution will then have the form $y(x)=xz(x)$, inserting gives
$$
0=[xz''+2z']+2x[xz'+z]-2xz=xz''+2(1+x^2)z'
$$
which is separable and solvable as
$$
z'=\frac{e^{-x^2}}{x^2}
$$
fixing the integration constant. Now continue using partial integration
$$
\left(z+\frac{e^{-x^2}}{x}\right)'=-2\frac{e^{-x^2}}{x}\\
\left(z+\frac{e^{-x^2}}{x}+2\ln|x|e^{-x^2}\right)'=-4x\ln|x|e^{-x^2}\\
$$
where the right side is now a continuous function,...


text:
Q: assigning liquid to javascript variable var first = 'one',
    second = 'two.png';
    image = first + second;
console.log('js image: ' + image);
image = '{{ image | asset_url }}';
console.log('liquid image: ' + image);

Produces in the console:
js image: onetwo.png
liquid image:

I cannot get the code to output the code from the liquid filter. I have tried using {% raw %} and looked at a few SO questions (Shopify: Using variables from {% schema %} in Javascript, Using javascript variables in Shopify liquid, Using asset_url within a .js.liquid file) to no avail.
What am I doing wrong here? I am expecting to get:
liquid image: onetwo.png?123456789

Even removing asset_url:
image = '{{ image }}';

Still produces:
liquid image:

A: After chatting with @Subhrajyoti Das there is a hacky way of doing it.
Create the full string with dummy text where the actual filename is:
assetString = '{{ 'filename' | asset_url }}'

This produces:
cdn.shopify.com/s/files/0/0000/0000/0000/t/00/assets/filename?0000000000

Then use string replacement to replace 'filename' with the asset variable:
image = assetString.replace("filename", image);

A: Retrieve the variable in the following way:
image = {{ 'image' | asset_url }};

//console log
js image: image.png
liquid image: image.png


text:
Q: OleDbCommand Return Multiple Rows I am using the following code to select data from a database in some cases this should return multiple results and I'm not sure how to return all matching results such as all booking times into an array and hen use these in a list box.
myConn.ConnectionString = connection.dbdataSource;
OleDbCommand selectServiceNo = myConn.CreateCommand();
selectServiceNo.CommandText =
  "SELECT ID, BookingTime, BookingDate, Description FROM booking";

selectServiceNo.CommandText += " WHERE BookingDate = #";
selectServiceNo.CommandText += dateSelected;
selectServiceNo.CommandText += "#";

myConn.Open();
OleDbDataReader myDR2 = selectServiceNo.ExecuteReader();
while (myDR2.Read())
{
    bTime = Convert.ToString(myDR2["BookingTime"]);
    bDate = Convert.ToString(myDR2["BookingDate"]);
}
myConn.Close();

A: Create a class Booking where you create all relevant properties, like Time, Date (why aren't these two combined in the first place?) and Description).
Then, in your while, create a new Booking and add it to a list (List<Booking>) you created outside of the while loop. Return that list.
(Note: also use using in order to dispose your command. You have memory and handle leaks when an exception is thrown before the commands gets closed. More importantly, your code is vulnerable to SQL injection. Always use SQL parameters.)


text:
Q: Disposable, one-time IMGs for drawImage When I createElement("IMG") solely for the purpose of using it in a 2d canvas using "drawImage", will the temporary IMG be eligible for a garbage collection? or will the canvas hold a reference to it (if so, how can I clear this reference)?

A: It ought to be eligible for garbage collection, but of course each browser could (in theory) implement it differently.
If it is not eligible for garbage collection once you have cleared all references to it then that is a bug.
That being said, I imagine a lot of browsers hold on to the image in cache anyway so even if the Image object is garbage collected, making a new Image object with the same src may load instantly.


text:
Q: graph - Shortest path with Vertex Weight Here is an excise:

In certain graph problems, vertices have can have weights instead of
  or in addi- tion to the weights of edges. Let Cv be the cost of vertex
  v, and C(x,y) the cost of the edge (x, y). This problem is concerned
  with finding the cheapest path between vertices a and b in a graph G.
  The cost of a path is the sum of the costs of the edges and vertices
  encountered on the path.
(a) Suppose that each edge in the graph has a weight of zero (while
  non-edges have a cost of ∞).Assume that Cv =1 for all vertices 1≤v≤n
  (i.e.,all vertices have the same cost). Give an efficient algorithm to
  find the cheapest path from a to b and its time complexity.
(b)  Now suppose that the vertex costs are not constant (but are all
  positive) and the edge costs remain as above. Give an efficient
  algorithm to find the cheapest path from a to b and its time
  complexity.
(c)  Now suppose that both the edge and vertex costs are not constant
  (but are all positive). Give an efficient algorithm to find the
  cheapest path from a to b and its time complexity.

Here is my answer:
(a) use normal BFS;
(b) Use dijkstra's algorithm, but replace weight with vertex weight;
(c)
Also use dijkstra's algorithm
If only considering about edge weight, then for the key part of dijkstra's algorithm, we have:
if (distance[y] > distance[v]+weight) {
    distance[y] = distance[v]+weight; // weight is between v and y
}

Now, by considering about vertex weight, we have:
if (distance[y] > distance[v] + weight + vertexWeight[y]) {
   distance[y] = distance[v] + weight + vertexWeight[y]; // weight is between v and y
}

Am I right?
I guess my answer to (c) is too simple, is it?

A: The vertex weight can be removed by slicing every vertex a in two vertices a1 and a2 with an edge from a1 to a2 with the weight of a.
I think you are right for the adaptation of dijkstra's algorithm.

A: You are on the right track, and the solution is very simple.
In both B,C, Reduce the problem to normal dijkstra, which assumes no weights on the vertices.
For this, you will need to define w':E->R, a new weight function for edges.
w'(u,v) = w(u,v) + vertex_weight(v)

in (b) w(u,v) = 0 (or const), and the solution is robust to fit (c) as well!
The idea behind it is using an edge cost you the weight of the edge, and the cost of reaching the target vertice. The cost of the source was already paid, so you disregard it1.
Reducing a problem, instead of changing an algorithm is usually much simpler to use, prove and analyze!.

(1) In this solution you "miss" the weight of the source, so the shortest path from s to t will be: dijkstra(s,t,w') + vertex_weight(s)_ [where dijkstra(s,t,w') is the distance from s to t using out w'


text:
Q: Hölder continuous functions are uniformly continuous I want to show that Hölder continuous functions are uniformly continuous using  $\epsilon-\delta$. Is it sufficient to find a $\delta>0$ that does not depend on $"x"$ and depends only on $"\epsilon"$? Furthermore is my method correct? Here is the context:
Let $(X,d_x)$ and $(Y,d_y)$ be metric spaces.
Let $\quad f:X\rightarrow Y \quad$ be a Holder continuous function.
Let $\,\epsilon>0,\quad\alpha>0,\quad C>0, \quad \delta =\frac\epsilon{2C}, \quad \gamma>0,\quad x_1,x_2\in X$
Let $\gamma=\delta^{\frac1 \alpha}<1$
As $f$ is continuous we have:  $\,\,d_x(x_1,x_2)<\gamma\implies d_y(f(x_1),f(x_2))<\epsilon$
So in particular: $\,\,d_x(x_1,x_2)^{\alpha}<\delta\implies d_y(f(x_1),f(x_2))<\epsilon$
As $f$ is Hölder continuous, we have:
$\,\,d_y(f(x_1),f(x_2)\le C*d_x(x_1,x_2)^{\alpha}<C*\delta=C*\frac\epsilon{2C}<\epsilon$
As $\delta$ does not depend on $"x"$, and this is true for  all $"\epsilon>0"$, then $f$ is uniformly continuous. $CQFD.$

A:
As $f$ is continuous we have: $d_x(x_1,x_2)<\gamma\implies d_y(f(x_1),f(x_2))<\epsilon$

There are two problems here.  First, why is this true for this specific $\gamma$ you chose? Second, if it's true for some choice of $\gamma$ then you already have uniform continuity, so why continue the proof?

Correct approach. The input is: $\alpha, C$ such that $d_y(f(x_1),f(x_2)\le C\,d_x(x_1,x_2)^{\alpha}$, and an arbitrary $\epsilon>0$.
From this we must come up with $\delta$. I would use $\delta = (\epsilon/C)^{1/\alpha}$; then the verification of
$$d_x(x_1,x_2)<\delta\implies d_y(f(x_1),f(x_2))<\epsilon$$
should be easy.


text:
Q: js is showing [object HTMLButtonElement] onclick? When button clicked JS is showing [object HTMLButtonElement] instead of original value.
I want that whenever a button is clicked the value of button is showed.
like when button having value 3 is pressed it will show 3 and not [object HTMLButtonElement]
this is my html file

    <button onclick="val(this)" id="n1" value="1" type="button" class="btn btn-outline-primary "
        style="width:100%" value="1">1</button>

    <button onclick="val(this)" id="n1" value="2" type="button" class="btn btn-outline-primary "
        style="width:100%" value="2">2</button>

This is my script.js
function val(num) {
  let n = num;
  document.getElementById("ta").innerHTML = n;
}

A: when using this inside the onclick html attribute, it will be valued with the html element firing the event so the object being passed to val() will be the whole element.
If you need to know the value of the button being clicked, you should retrieve its value property

function val(num) {
  let n = num.value;
  document.getElementById("output").innerHTML = n;
}
button{
  cursor: pointer;
}
<button
  type="button" class="btn btn-outline-primary "
  id="n1" value="1" onclick="val(this)">1</button>
<button
  type="button" class="btn btn-outline-primary "
  id="n2" value="2" onclick="val(this)">2</button>

A: Using onClick directly on Elements is not really ideal, try using addEventListener.
Another advantage of addEventListener you can create a delegated event handler, so if you have lots of buttons doing the same thing you can attach one handler to a parent element and all the buttons can be handled.
Buttons don't store values like INPUT, but if you want to associate data with buttons try using the data- attribute.  eg.. data-val="1", you can then access this using the dataset property.
Below is a simple example of using addEventListener as a delegated event handler, plus using data- attributes on buttons.

Update: Buttons do have the value attribute, so you could still do
e.target.value too, but I'll leave the data- attribute as it's
pretty handy anyway.. :)

const d = document.querySelector('div');

document.body.addEventListener('click', e => {
  const val = e.target.dataset.val;
  if (val) d.innerText = val;
});
div {
  border: 1px solid black;
  margin-top: 10px;
  padding: 20px;
  font-size: 30pt;
  font-family: arial;
}
<button data-val="1">1</button>
<button data-val="2">2</button>
<button data-val="3">3</button>
<button data-val="4">4</button>

  Click button above.


text:
Q: Use session name in MySQL statement I'm having problem with my php code.
I need to query db using in WHERE session name from php page.
Below code:
            <?php session_start();
                try {
                  //$con= new PDO('mysql:host=localhost;dbname=wydania_tonery', "sa", "sql");
                  $zmien_kodowanie = $dbo->query("SET names 'utf8'");
                  $sesja = $_SESSION['username'];
                  $query = "SELECT
                                mdl_user.firstname AS 'Imie',
                                mdl_user.lastname AS 'Nazwisko',
                                mdl_user.department AS 'Akronim',
                                reg.data AS 'Region',
                                sta.data AS 'Stanowisko',
                                mdl_user.aim AS 'Stan',
                                NULLIF('Uwagi', 0) AS 'Uwagi'
                            FROM
                                mdl_user
                            LEFT JOIN
                                mdl_user_info_data AS reg ON reg.userid=mdl_user.id AND reg.fieldid='2'
                            LEFT JOIN
                                mdl_user_info_data AS sta ON sta.userid=mdl_user.id AND sta.fieldid='4'
                            WHERE
                                mdl_user.email LIKE 'kierownik.%' AND mdl_user.deleted='0' AND mdl_user_info_data.fieldid = ".$_SESSION['username']." /*AND mdl_user.department='BBT'*/
                            ORDER BY
                                mdl_user.department ASC";

                  //first pass just gets the column name
                  echo "
 \n";
                  $result = $dbo->query($query);
                  //return only the first row (we only need field names)
                  $row = $result->fetch(PDO::FETCH_ASSOC);
                  print "
 \n";
                  foreach ($row as $field => $value){
                   print " $field	 \n";
                  } // end foreach
                  print "
 \n";
                  //second query gets the data
                  $data = $dbo->query($query);
                  $data->setFetchMode(PDO::FETCH_ASSOC);
                  foreach($data as $row){
                   print "
 \n";
                   foreach ($row as $name=>$value){
                   print " $value	 \n";
                   } // end field loop
                   print "
 \n";
                  } // end record loop
                  print "
 \n";
                  } catch(PDOException $e) {
                   echo 'ERROR: ' . $e->getMessage();
                  } // end try
            ?>

When I use standard way (".$variable.") to pass php variable I got error below:

Fatal error: Call to a member function fetch() on boolean in
  Path/to/my/page on line 35

If anyone would like to help me solve my problem I'd be glad to thank him

A: Try
        <?php session_start();
            try {
              //$con= new PDO('mysql:host=localhost;dbname=wydania_tonery', "sa", "sql");
              $zmien_kodowanie = $dbo->query("SET names 'utf8'");
              $sesja = $_SESSION['username'];
              $query = "SELECT
                            mdl_user.firstname AS 'Imie',
                            mdl_user.lastname AS 'Nazwisko',
                            mdl_user.department AS 'Akronim',
                            reg.data AS 'Region',
                            sta.data AS 'Stanowisko',
                            mdl_user.aim AS 'Stan',
                            NULLIF('Uwagi', 0) AS 'Uwagi'
                        FROM
                            mdl_user
                        LEFT JOIN
                            mdl_user_info_data AS reg ON reg.userid=mdl_user.id AND reg.fieldid='2'
                        LEFT JOIN
                            mdl_user_info_data AS sta ON sta.userid=mdl_user.id AND sta.fieldid='4'
                        WHERE
                            mdl_user.email LIKE 'kierownik.%' AND mdl_user.deleted='0' AND mdl_user_info_data.fieldid = ? /*AND mdl_user.department='BBT'*/
                        ORDER BY
                            mdl_user.department ASC";

              //first pass just gets the column name
              echo "
 \n";
              $stmt = $dbo->prepare($query);
              $stmt->bind_param("s", $_SESSION['username']);
              $result = $stmt->execute();

A: Instead of using direct substitution values, you could use below methods to avoid sql injection.
You basically have two options to achieve this:
Using PDO:
$stmt = $pdo->prepare('SELECT * FROM employees WHERE name = :name');

$stmt->execute(array('name' => $name));

foreach ($stmt as $row) {
    // do something with $row
}

Please refer How can I prevent SQL-injection in PHP?


text: Q: Coset representatives of a principal congruence subgroup by another principal congruence subgroup Consider the principal congruence subgroup $\Gamma(N)$, this consists of entries in $\mathrm{SL}_2(\mathbb{Z})$ congruent to the identity modulo $N$. Consider another principal congruence subgroup $\Gamma(M)$ such that $N$ divides $M$, then $\Gamma(M) \subset \Gamma(N)$. Is there a formula for the representatives of the coset $\Gamma(M) / \Gamma(N)$? I know formulas for cosets of $\mathrm{SL}_2(\mathbb{Z})$ but have the cosets mentioned above been studied before? Does it have an "easy" answer?


text:
Q: Centering content in a modal (having a n00b moment) I am trying to center a 3x3 grid in a modal.  I've been stuck on this for a good portion of the day and can't seem to figure out why it won't center.  The content is being templated through a php foreach loop.  Heres the php.

            <?php $themes = ["1", "2", "3", "4", "5", "6", "7", "8", "9"]; ?>
            <?php foreach($themes as $theme):?>
                <div class="span3 themeChoice" data-feedback-selected="false" data-feedback-type="<?= $theme?>">

            <?php endforeach; ?>

As you see, I have this class called centerThemes which I have been playing with. I'd show you the CSS, but everything I have been trying hasn't been working.  Setting the margin to 0 auto, margin-left and margin-right to auto, display:block, and so on. Any yes, I'm using bootstrap but its an older version, where you have to use a class like 'span4' to make a 4 column section.
Not too sure what to do.
Any help is appreciated- thanks!

A: span classes sound like Boostrap 2.
For some weird reason if I embed the snippet grid won't display as desired so I'll just link the fiddle.
Here's an example without PHP using Bootstrap2


text:
Q: How can I extract hashtags from strings and export as a csv? I use the following function to extract hashtags from text data:
a <- c("#aaa", "#bbb", "#ccc")
hashtag_pat <- "#[a-zA-Z0-9_-ー\\.]+"
hashtag <- str_extract_all(a, hashtag_pat)

Here's the output:
[[1]]
[1] "#aaa"

[[2]]
[1] "#bbb"

[[3]]
[1] "#ccc"

I can't, however, export this correctly as a csv. I need all these words in a single cell (separated by spaces). What is the best way to export this?
The following is what 'write.csv' gives me. I appreciate if you could help fix this.

A: Update after clarification:
df <- data.frame(col1 = paste(a,collapse=" "))
df

            col1
1 #aaa #bbb #ccc

Are you looking for such a solution?
hashtag <- sub("^\\#", "", a)
write.csv(data.frame(t(unlist(hashtag))), "my_file.csv")


text:
Q: ASP.NET Cross Domain Web Service & Session State Here's a really loaded question. I would like to implement a shared page using ASP.NET that I can download from a Web Service to include in an ASP, ASP.NET, or PHP page on any domain. The shared page would be hosted on a separate server on a different domain, so I do not have access to the typical ASP.NET Page Methods.
Also, I would need to be able to use jQuery to send AJAX GET and POST requests to the Web Service, and be able to preserve the session state.
Is such an implementation possible in ASP.NET?

A: Don't expect cookies to transit domains. Anything that you try to do in this regard with cookies is likely to be prevented by the security in the web-browser.
Also, there are a number of caveats to attempting cross-domain AJAX requests. See AJAX - Introducing Cross-domain Request (XDR), Getting a cross-domain JSON with jQuery in Internet Explorer 8 and newer versions, and Ticket #8283 Built-in support for XDomainRequest.
You may want to consider one of the following alternatives:

*

*Put your web service on the same site.

*Have the site make the query to the web service on behalf of the user.


text:
Q: How can I persist state in a VS Code WebviewPanel after it is destroyed? After looking at the documentation, I'm able to persist state in the following two cases:

*

*When a WebviewPanel is hidden (ie, the user switches tabs) using getState/setState

*When the user restarts the VS Code by implementing a WebviewPanelSerializer
However, I don't see a way to persist state when the panel is destroyed (ie, the user closes it or calls dispose). Here's my scenario:

*

*I execute a command to show the WebviewPanel

*I have an input box in the HTML content. I type some string in and press a button to save it. Upon saving, I save it using setState and then append a div with the entered text into the webview.

*I close the panel and execute the command again. The panel does not have the appended div.

A: You have 2 options:

*

*Recreate the additional div when you find saved state (e.g. the input from the user).

*Use retainContextWhenHidden to keep the content of the webview, even if it is moved to the background.

The latter won't help when the user closed the webview, however, and is much more resource hungry than the state save/restore operation.


text:
Q: How to extract coordinate pairs of crossing points of two polygons in PostGIS? Extracting coordinate pairs of crossing points of two polygons in PostGIS
Is it possible to extract x,y-coordinate pairs of crossing points of two overlapping polygons in PostGIS?
Suppose there are only 2 overlapping points of the polygons the ST_Intersection function extracts more than two coordinate pairs (also the shared vertices of polygons are included).
SELECT ST_Intersection(geometry geomA , geometry geomB);

I am interested only in the 2 boundary crossing points of polygons.

A: Here is one method that'll work with basic polygons (no inner rings)
SELECT ST_AsText(
    ST_Intersection(
        ST_Boundary(ST_GeomFromText('POLYGON((0 0, 0 1, 1 1, 1 0, 0 0))')),
        ST_Boundary(ST_GeomFromText('POLYGON((0.5 0.5, .5 1.5, 1.5 1.5, 1.5 0.5, 0.5 0.5))'))
    )
);


text:
Q: Difference between QFT In curved spacetime, semiclassical, and quantum gravity? Could someone describe the difference, qualitatively, between QFT in curved spacetime, semiclassical gravity, and quantum gravity? I know that each is an approximation to the next and the end goal is a unification of QFT with GR. I've often heard that the first two are well-formulated but quantum gravity is not? How well formulated are theories of semiclassical gravity vs. say, string theory? What is the critical step to go from semiclassical to quantum gravity? Are there experimental confirmations of any of these?

A: *

*QFT in curved spacetime: The spacetime metric is fixed. It doesn't react to the state of the quantum fields, which are described by operators on a Hilbert space. The fixed metric field defines what "spacelike" means, which is important because observables built from the quantum fields are required to commute with each other at spacelike separation. (This prevents faster-than-light communication.) This approximation is self-consistent. Hawking radiation can be derived using this approximation, but the black hole never evaporates in this approximation, because the spacetime metric does not react to what the quantum fields are doing. A special case of QFT in curved spacetime is QFT in flat spacetime, which of course is very well-tested. I'm not aware of any direct tests of the effect of spacetime curvature on quantum fields, although there are plenty of tests of the effect of spacetime curvature on classical approximations of quantum fields. Tests of quantum effects in free-fall don't count, because they're not sensitive to the curvature.

*Semiclassical gravity: This name often refers to an approximation that attempts to account for how the spacetime metric would react to the quantum fields, but still using a classical description for the metric (so that the metric commutes with all operators on the Hilbert space). The stress-energy tensor $T_{ab}$ is a non-commuting operator, so to describe the behavior of the metric field using something like Einstein's field equation, this approximation uses the expectation value of $T_{ab}$, like this: $R_{ab}-\frac{1}{2}g_{ab}R\propto\langle T_{ab}\rangle$. This approximation is not strictly self-consistent , but it's usable as long as we avoid situations involving quantum superpositions of very different values of $T_{ab}$. It has been used, for example, to try to account for the fact that a black hole should lose mass as it radiates. The inconsistency is explained in this blog post: Luboš Motl (2012), "Why 'semiclassical gravity' isn't self-consistent," https://motls.blogspot.com/2012/01/why-semiclassical-gravity-isnt-self.html

*Quantum gravity: This refers to a fully quantum theory with no fixed background metric (except for its asymptotic structure)$^*$, but which nevertheless exhibits gravity in a way that is well-approximated by general relativity under appropriate conditions. The correct theory of quantum gravity remains to be determined. Currently, the best-understood example of this kind of theory comes from the AdS/CFT correspondence. This can be regarded as defining a theory of quantum gravity (string theory) in asymptotically-AdS spacetime in terms of a conformal quantum field theory (CFT) associated with the asymptotic structure. CFT is relatively well-understood mathematically, but exactly how spacetime and gravity manage to emerge is still an active research area, as is the question of how to extend the idea to spacetimes with more realistic asymptotic conditions (namely de Sitter).

$^*$ I don't know of any well-developed proposals for how to get by without a fixed asymptotic spacetime structure, and I have seen general arguments that such a structure is necessary. Of course, any general argument is only as good as the assumptions that go into it, and since we are on unfamiliar territory when dealing with quantum gravity (due to the lack of any prescribed geometry or even any prescribed causal structure in the bulk of spacetime), it is difficult to know how watertight those general arguments are.


text:
Q: Calculating every n-th row with a different format I'm trying to make a formula work on a time-table, where every 7th row I have a sum of the work-time for a week and then I want them to sum them altogether from beginning of data to current week.
Technically it is possible to just manually add them together, but I would like to have it automated and furthermore to learn how to use the function properly.
Screenshot for better visualization:

In the column "Nadcas" I have listed overtimes from Monday to Tuesday.
Under it is a SUM of those numbers. Right to it, the second highlighted field is the Overtime total. Logically, the first week is going the total of the overtimes to be the same as overtime of the first week.
In the table under it, it's the same deal. However, the overtimes on the right are calculated incorrectly. It should be 0:29 + 1:32 = 2:01.
Biggest issue is, the sumtotal formula doesn't correctly calculate, when the field type is in hours, and some are text fields
Any idea how to do it?

OPTIONAL, can skip if you know the answer:
 I have found a way to make the formula work, in the table here:

You can see the numbers are added up correctly. The formula I used (for the last sum cell, that equates to 11) is:
=SUMPRODUCT(--(MOD(ROW(A12:A23) - ROW(A12) +1; 4)=0); A12:A23)
Sum product does a matrix multiplication, mod returns 1 or 0 depending if X/4 gives .0 as rest and -- negates the result. Easily said, we have two matrices eg. {0; 0; 1} and {1; 2; 3} so the result is 0x1 + 0x2 + 1x3 = 3.
When we visualize that on our formula, it would look like:

[ For more info, I found this explanation pretty helpful, even though it's for columns. https://exceljet.net/formula/sum-every-nth-column ]
This should by all means work on the main table as well, but I guess because of formatting it doesn't.

A: If you are consistent with the format of the sheet, you can make use of the data in the second column "Den"- if we check this column for non blank cells and sum corresponding values in column G, we can have our answer.
Assuming following layout of the sheet, following formula should work:

'=SUM(IF(A$2:A6<>"",B$2:B6))

Executed with Ctrl+Shift+Enter
The fixed referencing in A$2:A6 makes sure that as you copy down the formula, the the entire range from to top to the cell-one-above the current is selected. Hope this helps!


text:
Q: I am not able connect jsp with sql server using eclipse Here is my code

Insert title here

I am getting like this errors
HTTP Status 500 -

type Exception report
message
description The server encountered an internal error () that prevented it from fulfilling this request.
exception
org.apache.jasper.JasperException: javax.servlet.ServletException: java.lang.ClassNotFoundException: net.sourceforge.jtds.jdbc.Driver
    org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:541)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:417)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:320)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:266)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
root cause
javax.servlet.ServletException: java.lang.ClassNotFoundException: net.sourceforge.jtds.jdbc.Driver
    org.apache.jasper.runtime.PageContextImpl.doHandlePageException(PageContextImpl.java:850)
    org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:779)
    org.apache.jsp.userlogin_jsp._jspService(userlogin_jsp.java:96)
    org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:393)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:320)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:266)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
root cause
java.lang.ClassNotFoundException: net.sourceforge.jtds.jdbc.Driver
    org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1358)
    org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1204)
    org.apache.jasper.servlet.JasperLoader.loadClass(JasperLoader.java:128)
    org.apache.jasper.servlet.JasperLoader.loadClass(JasperLoader.java:66)
    java.lang.Class.forName0(Native Method)
    java.lang.Class.forName(Unknown Source)
    org.apache.jsp.userlogin_jsp._jspService(userlogin_jsp.java:77)
    org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:393)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:320)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:266)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
note The full stack trace of the root cause is available in the Apache Tomcat/6.0.14 logs.

Apache Tomcat/6.0.14

A: You'll need to set up on your build the JTDS driver lib.