text:
Q: "has written two essays this morning" vs "has been writing an essay all morning" What is the difference in meaning between these sentences?

*

*
John has written two essays this morning.
  John has been writing an essay all morning.

*
The police sergeant has interviewed two people so far today.
  The detectives have been interviewing people all week.

A: (1) John has written two essays this morning.
So, this means that the essays are finished.
John has been writing an essay all morning.
This means that it is still in progress.
You should be able to expand for the other examples.

A: The present perfect continuous means that it has been happening over a period of time, often a specified time (either in the same sentence, or in further context - especially where the present perfect continuous is used in answer to a question). It usually implies that it is still happening, though it is sometimes used where it has just very recently finished.
The present perfect is for things that happened in the past and are complete, or have ceased happening. Depending on the verb and the object, it may strongly indicate that the task is complete, as in "interviewed two people" or "written two essays".

A: In addition to the other answers: with "how much" and "how many", the present perfect tense is used. "How long" is more common with the present perfect progressive.


text:
Q: Does the java memory model prevent interleaving writes from different threads between volatile variables? I was reading an interesting article about the memory barriers and their role in JVM concurrency, and the example implementation of Dekker's algorithm took my attention
     volatile boolean intentFirst = false;
     volatile boolean intentSecond = false;
     volatile int turn = 0;

     // code run by first thread    // code run by second thread

 1    intentFirst = true;           intentSecond = true;
 2
 3    while (intentSecond) {        while (intentFirst) {     // volatile read
 4      if (turn != 0) {               if (turn != 1) {       // volatile read
 5        intentFirst = false;               intentSecond = false;
 6        while (turn != 0) {}               while (turn != 1) {}
 7        intentFirst = true;                intentSecond = true;
 8      }                              }
 9    }                             }
10    criticalSection();            criticalSection();
11
12    turn = 1;                     turn = 0;                 // volatile write
13    intentFirst = false;          intentSecond = false;     // volatile write

The article mentions that since volatiles are sequentially consistent, the critical section is bound to be executed by one thread, which checks out with the happens-before guarantee. However, does that still hold if the two threads continue to execute the same logic in a loop? My understating is that the underlying OS scheduler may decide to pause the second thread in subsequent execution just before line 7 is executed and leave the first thread hit the critical section, and at the same moment, the OS resume the second thread and hit the critical section simultaneously. Is my understanding correct, and this example is given with the idea that this code is executed only once? If so, I'd assume that the answer to my question is "no" since volatiles are used only for memory visibility guarantees.

A:
My understating is that the underlying OS scheduler may decide to
pause the second thread in subsequent execution just before line 7 is
executed and leave the first thread hit the critical section, and at
the same moment, the OS resume the second thread and hit the critical
section simultaneously.

This will not happen. If the second thread gets suspended and the first thread
is in the critical section, the intentFirst is still true since this is only set to false after the first thread leaves the critical section. So if the second thread wakes up, the intendSecond is set to true, but the second thread will be stuck in the while(intendedFirst) loop and will delay entering the critical section till the first thread has excited.
IMHO the most interesting part of Dekkers algorithm with respect to happens-before is here:
intentSecond=true; // volatile write
while(intendFirst) // volatile read

Modern processors have store buffers and this could lead to older stores being reordered with newer loads to a different address. That is why a [StoreLoad] is needed between the earlier store and the later load to ensure that they are sequentially consistent.

A: The compiler ensures that the compiled code on the platform - in this case the JVM - makes certain guarantees for volatile variables, in terms of reordering of statements (on many levels) and about visibility between threads. On most platforms that have a JVM implementation, this can be done without the involvement of the operating system, and no scheduling is involved.
Guarantees about reordering and memory barriers are themselves no exclusion mechanism, needed to enter a critical section. These can be implemented in many different ways, for example by Dekker's algorithm. Dekker's algorithm is a so-called busy algorithm, that needs the CPU to work for as long as it is not allowed into the critical section. On modern hardware, simpler algorithms are possible that can use CAS operations, for example
// declare an atomic boolean (package java.util.concurrent.atomic)
AtomicBoolean busyFlag = new AtomicBoolean(false);

// the part with the critical section, same for all threads
while (!busyFlag.compareAndSet(false, true)) { /* busy wait */ }
try {
    criticalSection();
}
finally {
    busyFlag.set(false);
}

In this case, [compareAndSet][3] ensures that the flag is atomically set to true if and only if it is false, and returns true when that happens.
However, just like the Dekker algorithm, this is still a busy mechanism that can cost you a lot of CPU if you are unlucky. A synchronized section or a Lock will ask the operating system to suspend the current thread when the lock cannot be obtained. But that has nothing to do with volatile.

redpajama_set_name: RedPajamaStackExchange


text:
Q: PS4 won't enter safe mode I just bought my PS4 and very quickly realized that 500GB is not going to be enough. So I decided to upgrade to a 2TB hdd. I am using a Nyko power bank to hold the hdd. When trying to boot the PS4 into safe mode, so I can initialize the PS4, it simply won't. I have tried multiple times with different solutions but with the same outcome. The thing is, when I put the 500GB hdd back in, it boots up into safe mode with no problems. Does anyone have a solution? I would really appreciate it.

A: See if this YouTube Video is able to help you access recover mode.
Instructions:

*

*Completely turn off the PS4 (do not put it on stand-by mode)

*Press and hold down the power button for around 10 seconds. The
console will beep twice, around 5 seconds apart.

*On the second
beep, let go of the power button and the PS4 will enter safe mode.

*Connect a DualShock 4 controller via the USB port and press
the PS button. You can then use the controller to select the
appropriate mode.

A: I just had this happen to my son's PS4. It wouldn't access safe mode, no matter how I tried: standard method, power cycle, alternate methods (some have waited for 3 beeps), etc.
Here's what worked: replacing the hard drive with a brand new one. As soon as I swapped it, I was able to access it with no issues. Reinstalled the latest firmware and voila: PS4 is back!
Hope this helps.
You can get a hard drive pretty much anywhere. Just make sure it fits and don't go crazy with the storage, some PS4's can only handle up to 2TB.

A: I kept holding down the power button hoping it would beep in 7 seconds but it wouldn't. It kept double beeping at 12 seconds. So I turned it off. then when powering on I held the power button for 7 seconds then released it for a second and then held it for 7 seconds then it beeped once and then I plugged in the controller and pressed the ps button. The grey screen came up but it took a minute for the text to show up. Once I finally got into safe mode I rebuilt the database and boom. It works again.


text:
Q: Creating table with data records as a form I have this code which outputs code1, code2 as a string.
I need:

*

*To print this on the screen in a table

*Create possibility for the admin to add or delete those codes.(each record needs to be a form with the submit button).

*The space for adding new codes need to be at the bottom of the table which lists all the codes

Code:
$db_host = "localhost";
$db_user = "////";
$db_pass = "////";
$db_name = "////";

// Establish a connection with the db
$conn = new mysqli($db_host, $db_user, $db_pass, $db_name);

if($conn->connect_error) {
  die('connection failed');
}

$results = $conn->query('SELECT value FROM dcodes');

if($results->num_rows > 0) {
while($row = $results->fetch_assoc()) {
$row_str=implode(',', $row);
$row_arr[]=$row_str;

}  array_unique($row_arr);
}
$new_row_str = implode(',', $row_arr);
echo $new_row_str;

$conn->close();

Please help me.I don't know how to realize this but must finish this.Thanks in advance.


text:
Q: Do not receive confirmation from the user when making a transaction in Phantom Wallet I am creating a game on the blockchain platform and I am doing the front part using reactjs and for this purpose I am using libraries related to SOLANA and Phantom Wallet. The problem I am facing is that Phantom Wallet asks for confirmation from the user for every transaction that is made. For example, in the game, for each action that the user performs, a message confirming the transaction is displayed. How can this be done without receiving confirmation from the user?
For example, the code that runs to create a game is as follows:

    program.methods
          .setupGame()
          .accounts({
            game: gamePDA,
            authority: wallet.publicKey,
            playerOneAccount: CURRENT_USER_PDA,
          })
          .rpc();


text:
Q: AngularJS How to get selected value but not description of select values? For drop downs in angular, I have select values and also descriptions in the dropdown, but when the value is selected, I'd like to only select the main values (cause). How can this be achieved?

angular.module('ui.bootstrap.demo', ['ngAnimate', 'ngSanitize', 'ui.bootstrap']);
angular.module('ui.bootstrap.demo').controller('TypeaheadCtrl', function($scope, $http) {

  var _selected;

  $scope.selected = undefined;

  var url = 'https://spreadsheets.google.com/feeds/list/1O7M5gaEGlyE5gkOBARJrxJJMBYiTwz2THVjgbaTx9v8/od6/public/values?alt=json';
  var parse = function (entry) {
    console.log(entry);
    var description = entry.gsx$description.$t;
    var cause = entry.gsx$cause.$t;
    return {
       description: description,
       cause: cause
     };
  };
  $http.get(url)
    .then(function (response) {
      var entries = response.data.feed.entry;
      $scope.ready = true;
      $scope.parsedEntries = [];
      for (var key in entries) {
        var content = entries[key];
        $scope.parsedEntries.push(parse(content));
      }
    });
});
<!doctype html>

    <link href="//netdna.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">

Static arrays

Model: {{selected | json}}

      <input type="text" ng-model="selected" typeahead-editable="false" uib-typeahead="cause as cause.cause + ' - ' + cause.description for cause in parsedEntries | filter:$viewValue | limitTo:8" class="form-control">

In case the snippet doesn't work, here's the plunker: https://plnkr.co/edit/aJzQCdX0izh5SnkJVgW3?p=preview

A: Add typeahead-on-select="onChange()" to your directive:
<input type="text" typeahead-on-select="onChange()" ng-model="selected" typeahead-editable="false" uib-typeahead="cause as cause.cause + ' - ' + cause.description for cause in parsedEntries | filter:$viewValue | limitTo:8" class="form-control">

And get the cause property in the change handler:
$scope.onChange = function() {
  console.log($scope.selected.cause);
}


text:
Q: what the standard pdf scale(Millimeters,centimeters,inches)? i'm looking for write a special API to generate PDF, so... i'm using the text atributes/commands to build a pdf document through a simple text file.
I've already downloaded the pdf references manual, but i didn't found what i looking for.
What the standard pdf scale?
I need know the standard pdf scale to measure my line lenght, and change my width of "MediaBox".

A: The MediaBox, CropBox, BleedBox, TrimBox, and ArtBox are rectangles expressed in default user space units, cf. Table 30 – Entries in a page object in ISO 32000-1.
The size of this unit is defined by another Page dictionary entry (cf. the same table):

UserUnit number (Optional; PDF 1.6) A positive number that shall give the size of default user space units, in multiples of 1 ⁄ 72 inch. The range of supported values shall be implementation-dependent. Default value: 1.0 (user space unit is 1 ⁄ 72 inch).

The UserUnit is only used very rarely. Thus, most of the time the unit you are after is 1/72th inch.
BTW, it is called default user space unit because in a content stream you can constantly change the size of a unit in user space by using appropriate changes of the transformation and/or text matrices; thus, in the context of content streams this 1/72th inch is merely a starting value.


text:
Q: Java executes 'catch' block with no error, and somehow still runs 'try' block I have a problem with the following code. First, I am a newbie to Java with experience with several other languages.
When I run the following on Android, it errors at "in.close();", jumps to the catch block and runs Return ""; The thing is, the function doesn't return an empty string, it successfully returns the correct json data even though the debugger says it isn't running return json, but that it's running return "";
public void fetch() {

    // Get the JSON of the image gallery
    String json = getJSON();

    // json somehow has the actual correct json data and not an empty string!

};

private String getJSON() {

    try {
        // Create a URL for the desired page
        URL url = new URL("http://imgur.com/gallery.json");

        // Read all the text returned by the server
        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
        String json = in.readLine();
        in.close();
        return json; // <-- debugger doesn't break here!
    }
    catch(Exception e) {
        Log.e("getJSON", e.getMessage());
        return ""; // <-- debugger breaks here! Cat Log shows nothing!
    }
}

I copy the exact same code into a Java console so that I can output the error message and watch it in the debugger with break points, and the code executes without error.
    try {
        // Create a URL for the desired page
        URL url = new URL("http://imgur.com/gallery.json");

        // Read all the text returned by the server
        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
        String json = in.readLine();
        in.close();
        System.out.println(json);
}
catch(Exception e) {
    System.out.println(e.getMessage());
}

What exactly is going on? Why is my code run on Android erroring when it runs in a Java Console just fine? Why when it errors does it not return what the error is supposed to return; and empty string? How can I view the error message in Android?

A: You should make sure to include the
<uses-permission android:name="android.permission.INTERNET" />

permission in your androidManifext.xml.
You are trying to retrieve data from a remote location.
On Java console you can do it without such permissions, but not in Android.

A: Forget about "System.out.println" in Android.
You can use "Logcat" view in Eclipse. This is used to show every log you want from your device.
Also, you can replace "System.out.println(json);" by "Log.e("MyApp", "Here is my Json: '"+json+"'");" and you'll see your json in the logcat... ;)
About your exception, you have a method in the frameworkthat automatically logs the exceptions in the logcat: "myException.printStackTrace();"

A: A Reader reads text, an InputStream binary data. The bridge InputStreamReader needs a character encoding, and takes in your case the default OS encoding.
So better explicitly use an encoding:
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));

As JSON should better be in UTF-8, I have given that. But the default encoding on Android is UTF-8 and with you probably Cp1252. So there might be something else wrong too.

A: Your code appears to be correct.  If you did see a JSON returned, then you were not getting any IOException from close.
Edit:
Your updated source code clearly shows that there is no return from finally or retry logic in play here.  Good.
Visit the following setting in your environment: Window / Preferences / Run/Debug / Launching / "Launch in debug mode when workspace contains breakpoints"
Set this to Always or Prompt.  (If it was previously Never, you might
have been running in Run mode, thus employing optimizations you did not want.  The two return statements may have been combined into one by the optimizer.)  After you change this setting, you should never see a breakpoint hit at a line different from the line on which it was set.  Please double check your findings with the new setting.
There is also an alternate way of breaking on exceptions (Suspend On Caught Exceptions) that is immune to this kind of optimization, if for any reason you do not want to run in debug mode.


text:
Q: Traverse whole PDF and change blue color to black and remove underlines as well ( But only from text which contains "http//" & "https//" ) + iText I want to change the color of text from blue to black and also wants to remove underline as well. But from only those text which contains "http//" & "https//"
Refrence Links:
Traverse whole PDF and change blue color to black ( Change color of underlines as well) + iText
Traverse whole PDF and Remove underlines of hyperlinks (annotations) only + iText

A: Presenting the complete code of a solution for this task would be beyond the scope of a stack overflow answer. Thus, I'll merely outline here one approach to implement a solution.
Hindrances
The task is more difficult than one might be aware of.
In particular the text of a link is not necessarily drawn using a few consecutive text showing operations (let alone a single one). In the worst case each letter of the link could be drawn in a separate instructions with all these instructions spread in a random order all over the content stream with operations drawing non-link content in-between.
Thus, you cannot look at each content stream instruction by itself and decide immediately what to do with it as was possible in the previous approaches you referenced in your question. Instead you'll have to collect all text and line drawing instructions with their context, sort them in the on page order, find URL texts and nearby lines there-in, manipulate the underlying instructions, and then write out the page content.
Furthermore, the recognition of "blue" in the referenced answers will not yet catch every shade of blue; only RGB colorspace blues are considered there but a blue tint might be generated by other color spaces, too. Also the text may be initially drawn in a different color and have it changed by some overlay. Furthermore, these colorspaces need not necessarily contain a black tint. Thus, the manipulation of the underlying instructions for a general solution is more difficult than simply changing the color value before the recognized link text pieces and lines.
An implementation approach
A solution taking those hindrances into account can still be built based on the PdfCanvasEditor used in the referenced answers (this and this) borrowed from this answer. In contrast to solutions there, though, the instructions must be collected in the write method with some relevant information of the state at the time of their execution, in particular the text and text position for text drawing instructions and the line position for line drawing instructions, and the color.
The iText LocationTextExtractionStrategy already does that, merely without keeping the original instructions in mind. Thus, you can borrow code from that strategy or even integrate it (instead of the dummy render listener by default used in the PdfCanvasEditor) and merely have to reference the corresponding instructions from the text chunks processed by the strategy class.
When all the instructions of the page have been collected with those extra information, you have to sort the text. The LocationTextExtractionStrategy also contains code to sort the text chunks accordingly which you can now use for your task.
In those sorted text chunks you can now look for link texts. Having found them, you can visit all the text drawing instructions associated with those chunks and all the line drawing instruction with positions right under those chunks, check their color for blueness, and (if blue) envelop them in a "change to black color" and "change back to previous color again" instructions bracket.
To also recognize wilder ways to create blue text, you have to improve your analysis of the instructions even more. E.g. if in blend mode Lighten later an area including some text is filled in blue, an originally black-on-white text suddenly becomes blue-on-white.
A possible generalization
This approach actually would give rise to a more generic PDF text manipulator if you somehow exposed the sorted text chunks and created a more flexible interface with methods for a number of changes to apply to the underlying instructions.
As of the approach above will take quite a number of weeks for a solid implementation anyways, you may want to consider such a more generic architecture for possible later re-use and sharing.


text:
Q: I have 4 different dates here in my div I need to apply active color to most recent future date? We have 4 different dates here

The most recent date should be of active class and future and old dates should be inactive class
For example

the above
 should be in green color and the other 3 divs should be of red color

I need javascript or jquery snippet to do this?
Javascript snippet
$(function() {
    var currentDate = Date.now();
    var a = new Date(currentDate);
    $(".grid-item").each(function() {
        var specifiedDate = $(this).data('date');
        var date = Date.parse(specifiedDate);
        var b = new Date(date);
        if (!isNaN(b) && b.getMonth() == a.getMonth() && b.getDay()==
           a.getDay() && b.getYear() == a.getYear()) {
          $(this).addClass('today');
        }
        else if(!isNaN(b) && a - b > 0) {
            $(this).addClass('past');
        }
        else {
        $(this).addClass('future');
    }
});

});
css
.grid-item {
  height: 170px;
  width: 170px;
  float: left;
  background:red;
  margin:10px;
}

.past {
     background:black;
}

.future {
     background:blue;
}

A: You can get all the dates and store it on an array.
Then add class .red to all .grid-item. Filter the div that has the same date with date element 0. And remove the class red add the class green

//Get the dates and sort it
var date = $(".grid-item").map(function(){ return $(this).data('date') }).get().sort(function(a,b){
    var f = function(d){[y,m,d] = d.split("-");return [y,m,d];}
    var t = new Date();
    return Math.abs( t.getTime() - new Date(...f(a)).getTime() ) - Math.abs( t.getTime() - new Date(...f(b)).getTime() );
});

//Assign Class
$(".grid-item").addClass('red').filter(function(){
    return $(this).data('date') === date[0];
}).removeClass('red').addClass('green');
.grid-item {
  border: 1px solid black;
  width: 50px;
  height: 50px;
}

.green {
  background-color: green;
}

.red {
  background-color: red;
}

If you want to base the order from the content and the divs content is just the date, you can:

//Get the dates and sort it
var date = $(".grid-item").map(function() {return $(this).text().trim()}).get().sort(function(a, b) {
  var f = function(d) {[y, m, d] = d.split("-");return [y, m, d];}
  var t = new Date();
  return Math.abs(t.getTime() - new Date(...f(a)).getTime()) - Math.abs(t.getTime() - new Date(...f(b)).getTime());
});

//Assign Class
$(".grid-item").addClass('red').filter(function() {
  return $(this).text().trim() === date[0];
}).removeClass('red').addClass('green');
.grid-item {
  border: 1px solid black;
  width: 100px;
  height: 50px;
}

.green {
  background-color: green;
}

.red {
  background-color: red;
}

2018-03-30

2018-04-29

2015-05-25

2015-07-26

Using just month and day (using the current year)
var date = $(".grid-item").map(function() {return $(this).text().trim()}).get().sort(function(a, b) {
  var f = function(d) {[m, d] = d.split("-");return [(new Date()).getFullYear(), m, d];}
  var t = new Date();
  return Math.abs(t.getTime() - new Date(...f(a)).getTime()) - Math.abs(t.getTime() - new Date(...f(b)).getTime());
});

//Assign Class
$(".grid-item").addClass('red').filter(function() {
  return $(this).text().trim() === date[0];
}).removeClass('red').addClass('green');


text: Q: Critical points in a simple case of manifold with boundary. Let $X$ be a smooth, connected, compact manifold and $Y=X\times [a,b]$. Let $f:Y\to\mathbb{R}$ be a Morse function on $Y$ such that $f|_{X\times \{a\}}=a$ and $f|_{X\times \{b\}}=b$. What can we say about critical points of $f$? I'm looking for a version of Morse inequalities or Poincare-Hopf theorem siutable for this situation.


text:
Q: Error: invalid video mode specification 'text' Booting in blind mode --after invidia installation and update through apt-get update I need some help. After i install nvidia driver for my graphics Card Inno3D GF-GT630 then update through sudo apt-get update and reboot. then this is now the display of my screen..
 error: invalid video specification'text' Booting in blind mode. I tried a lot of solutions but none of them work: like fixing through:
GRUB2 by adding GRUB_CMDLINE_LINUX_DEFAULT='nomodeset quiet splash'then update the grub.
Recovery Mode in root(Drop to root shell prompt) and remove the nvidia drivers but it can't be remove coz it prompt "not installed, not remove,"  in screen and also i tried to mount remount the drive, update with apt but and error will appear and it says like error Fetching blah blah blah .. and the worst is i have only 2 mins to execute some codes in Root(drop to root shell prompt) in Recovery mode because this error [OK]Stopped run ancron jobs and so on... pops up and i have to restart again just to enter in the recovery mode again...by the way im using Ubuntu 16.04.
Is there other way to fix this?
pls. help im newbie

A: This happened to me when the grub configuration (as can be seen by pressing 'e' for "Edit" at boot time) contained: set gfxpayload=text
Just removing it (manually, in grub) fixed the problem.
What's strange is that the same line worked before, on the same computer, before re-running grub2-mkconfig for the Nth time, not sure what happened.
This entry comes from GRUB_GFXPAYLOAD_LINUX=text in /etc/default/grub, for the record.


text:
Q: How to support patch rest request with protobuf 3 We often have use cases where we only want to update a subset fields on a resource. So if we have a resource Person:
type Person struct {
    Age int
    Name string
    Otherfield string
}

Say the calling client only wants to update the Age field. How would an endpoint be normally set up to handle this?
I believe this should be done with a PATCH request, with only the fields being set as part of the payload, ie:
{
    Age: 21
}

However, this won't work with proto3 because as far as I know there are no null fields, only default values. This won't work in many cases where the default value is valid.

A: Looking at Google own protobuf files (e.g. here), they use FieldMask for partial update.
FieldMask object is passed along with the request, and has the form (in JSON):
{
   mask: "Person.Age"
}

This allows the client to tell the server which fields they wish to update, without counting on the partial message itself to figure this out.
I think this adds unnecessary complexity on (each!) client, but we couldn't find any other way to achieve partial updates with proto3.
You can see full documentation of FieldMask here.
Note that it can also be used to filter out responses if the client doesn't need the entire object.


text:
Q: Is it possible to include a .dll in a c++ compile Hey so I'm using vscode as my IDE and I was wondering if it was possible to include the dll for glfw3 into my build as whenever I run the finished program I need the glfw3.dll in the same folder as the .exe for it to run. Does anybody know how I would add it and if it is even possible.
Also here is my .vscode tasks.json
    {
            "type": "cppbuild",
            "label": "C/C++: g++.exe build active file",
            "command": "C:\\msys64\\mingw64\\bin\\g++.exe",
            "args": [
                "-fdiagnostics-color=always",
                "-static",
                "-g",
                "-std=c++17",
                "${file}",
                "-I",
                "./include",
                "-L",
                "./lib",
                "-lopengl32",
                "-lglew32",
                "-lglfw3dll",
                "-Wl,--subsystem,windows",
                "-o",
               "${fileDirname}\\${fileBasenameNoExtension}.exe"
            ],
            "options": {
                "cwd": "${fileDirname}"
            },
            "problemMatcher": [
                "$gcc"
            ],
            "group": {
                "kind": "build",
                "isDefault": true
            },
            "detail": "compiler: C:\\msys64\\mingw64\\bin\\g++.exe"
        }

A: You can use a build event to copy the DLL into your exe target directory or put the DLL in your PATH environment variable.


text:
Q: Rename file name before uploading to PHP server I wonder if it is possible to change file name and attributes of
 <input type="file" id="image">

with Javascript or Jquery before uploading using PHP?
I have found that it is possible to rename it on back-end with PHP but I want to have name changed to say Date().getTime() before uploading. On server I would simply move file to location.


text:
Q: What am I doing wrong in applying patch? When trying to apply a patch I am getting this error-
 ssh PATCH_SUPEE-9767_CE_1.9.3.2_v2-2017-07-11-11-06-06.sh
ssh: Could not resolve hostname PATCH_SUPEE-9767_CE_1.9.3.2_v2-2017-07-11-11-
6-06.sh: Name or service not known

When I do ls I can see the patch. I have double and triple checked it is spell correct, and I have all permissions. What does name or service not known mean?

A: The command is bash, not ssh. So in the end:
bash PATCH_SUPEE-9767_CE_1.9.3.2_v2-2017-07-11-11-06-06.sh

Ref: https://support.hypernode.com/knowledgebase/how-to-apply-magento-patches/#Step_4_Apply_the_patch

A: As stated you are using the wrong command. 'SSH' is a command for starting new ssh sessions with a remote host.
e.g.
ssh username@192.168.0.10

'Could not resolve hostname' and 'Name or service not known' errors are just stating that there is no host responding to this command as there is no host with the name of your patch.
'SH' is what i have used to run these commands. Use either of the below to run patches and they should run successfully (i normally run ssh terminals in bin/sh shell):
sh PATCH_SUPEE-9767_CE_1.9.3.2_v2-2017-07-11-11-06-06.sh

or
./PATCH_SUPEE-9767_CE_1.9.3.2_v2-2017-07-11-11-06-06.sh

Also see here for more information from Magento Dev Docs on applying patches:
http://devdocs.magento.com/guides/m1x/other/ht_install-patches.html


text:
Q: USB 2.0 Signal Integrity Using HSETT I am trying to test USB 2.0 Signal integrity (Eye Diagram). For doing that, USB IF Forum lets you download the EHCI HSETT Software from their website. However, I am not able to use it due to one persistent problem: No Host Controllers Found
Even though I have tried reinstalling the software, checking that I have the right 64-bit version and loaded the compliance driver manually(which keeps showing that it has errors in the device manager), I still get the same error. Can anyone help with getting this running?


text:
Q: Is registering a client app in Soundcloud still available in any way? I am trying to register my app through SoundCloud for developers and got redirected to this google form.
I still need to work with SoundCloud in my app. What should I do?


text:
Q: Create a SilverLight application and use SharePoint Object Model inside The idea is to create a SilverLight 3 Application (not a web part) that will be used inside SharePoint 2007 (not a web part but a full aspx page that will be called from a Sharepoint feature), for example, a silverlight application that lists all documents of a SharePoint document Library, and when double-clicking an item it will display it.
How do I use the SharePoint object model (spsite, spweb, splist etc...) inside this SL app?
Is it not possible?

A: To do what you are suggesting you would need access to the Client Object Model which is only available from SharePoint 2010.
However you could use the web services to perform your underlying data accesss to SharePoint from within Silverlight 3 in MOSS or WSS 3.0.

A: You have to remember that Silverlight runs on the client and not on the server. Because of this, the Sharepoint object model is not readily available to client-side apps.
As Charles Lee has already said, the way to do in '2007 is via web services. I believe that there is improved object model support in the 2010 version.

A: Can u include Microsoft.Sharepoint.dll in your application and refer the Sharepoint object model. I have not done this . but looks like this should be the solution


text:
Q: clean a badly-encoded text in Python I have some texts in a Pandas dataframe (in a specific column called text)
here an abstract (converted to list):
['    baby k jax  io ieri sera stavo fuori come arisa stavo piã¹ storta della torre di pisa lui che strusciava ha detto no striscia la visa che quando cala il basso baby senti che ti arriva  tengo duro  no pilota non câx80x99㨠musica solo slogan pussy power  super lova dio perdonami  vulva loca  no  non disturbarmi mentre sto guardando swaggando  please vuole toccare i tasti come alicia keys  mi piace quando fai certe cose certe cose quando fai certe cose mi piace quando piace quando fai certe cose certe cose quando fai certe cose mi piace quando piace quando fai  ero con le bambole coi bomber guardavano le bambole coi bomber qualcuno ha detto andale andale si sono accese fiaccole le trombe sempre in giro come gran turi lenti scure quando fatturi non fare la dura che non duri punta su di me che vado all in  in discoteca bevo fino a diventare analfabeta chi vuoi diventare alfa o beta a giudicare al tuo like zeta zeta zeta vai bello come un tale vous brucio ste barbie faccio un barbecue mi piace il tuo grande cervello sai cosa 㨠meglio fare scopa col settebello  certe cose certe cose quando fai certe cose mi piace quando piace quando fai certe cose certe cose quando fai certe cose mi piace quando piace quando fai certe cose certe cose quando fai certe cose mi piace quando piace quando fai certe cose certe cose quando fai certe cose mi piace quando piace quando fai  cosa c 㨠sotto il tuo gucci tarocco mi piaci quasi troppo mi piaci quando fai   guardo e non tocco manca poco che sbrocco al tuo amico a scrocco mi piaci quando fai    mi piaci quando fai cose che le altre non fanno ãx88 luned㬠sera e brindi come a capodanno bevi cento shot ma reggi bene lâx80x99alcol ãx88 marted㬠in palestra fai squat con il tacco loro slacciano bottoni se fa caldo quando lo fai tu invece suda qualcun altro arrostiscono se al cinema câx80x99㨠una scena di sesso tu invece dici che puoi fare meglio loro a casa con il tipo con la tuta con le felpe fanno foto con roba aderente per i like loro hanno una visa che usano raramente tu hai il reggiseno solo che non usi mai loro seguono la moda tu la fai loro miu miu jimmy choo tu minigonna e nike e se rimango in boxer te ne fotti se non sono calvin klein  mi piace quando fai certe cose certe cose quando fai certe cose mi piace quando piace quando fai certe cose certe cose quando fai certe cose mi piace quando piace quando fai certe cose certe cose quando fai certe cose mi piace quando piace quando fai certe cose certe cose quando fai certe cose mi piace quando piace quando fai ',
 '     volo in alto su  ste cime  e tu stai bene dove stai presa bene come il weekend  eh tu non uccidere il mio vibe non uccidere il mio viiibe  viiibe non uccidere il mio viiibe  viiibe  nuovi trick  nuovi flow  nuova bitch allo show giro con la gang  gli altri fanno wow   nuova she  troppo kitsch  nuova hit porto a casa un altro platino  lo chiamo just eat   poi mi dicono chi si accontenta gode sarãxa0 meglio su instagram ma io lo chiamo frode lui vuole fare il duro ma alla fine 㨠un boy scout bello ciao  lui che dissa me 㨠tipo un coming out dai non fare la monella vedo la tua bella se guarda male grattatina anti iella   ieri sera a fare bello hai fatto glu glu glu mo  mi chiami  sto occupata tipo tu tu tu   ghiaccio dappertutto come a mosca una rockstar firmo tette  passa l uniposca regola uno  nuovo rito se 㨠in giro a fare il figo prendi il suo migliore amico  volo in alto su  ste cime  e tu stai bene dove stai presa bene come il weekend  eh tu non uccidere il mio vibe non uccidere il mio viiibe  viiibe non uccidere il mio viiibe  viiibe  ehi  lei mi chiama baby  io la chiamo baby vuole la mia voce come quella bag fendi  yo lei mi chiama sexy  io la chiamo sexy crazy come lei  pensa piã¹ ai cents che ai sentimenti come vola sul tappeto come cinderella troppo a spasso  ti scarto come una caramella dal mezzo su cui compaio pensi sia una super cena e invece andiamo al mc  ti offro la mela tu quando me la ti 㨠bastato poco  giãxa0 sei fell in love ti 㨠passato il sonno  baby io non ci sarã²   non mi troverai online  sto uccidendo un altra base non uccidere il mio vibe  volo in alto su  ste cime  e tu stai bene dove stai presa bene come il weekend  eh tu non uccidere il mio vibe non uccidere il mio viiibe  viiibe non uccidere il mio viiibe  viiibe  ti leggo nel pensiero please don t give my vibe s㬠mi sa che 㨠vero sai ieri c era una festa sai che c ero ne fumo tanto che dopo ti vedo in bianco e nero bionda sai che hai il culo che 㨠una bomba mi ti porto nella tomba dell amore neanche l ombra piove sempre sembra londra    un bicchiere ogni tre passi ho tanta roba e me la tengo stretta in tasca fra il nome dell etichetta  volo in alto su  ste cime  e tu stai bene dove stai presa bene come il weekend  eh tu non uccidere il mio vibe non uccidere il mio viiibe  viiibe non uccidere il mio viiibe  viiibe  o yeh yeh yeh ai yeh yeh yeh woo baby k vegas jones gemitaiz woo  ',
 '    baby k  andrã©s dvicio  dã©jame bailar contigo  yo  baby k   baby k  faccio un tuffo sotto il sole fa giãxa0 un caldo che si muore questa estate non si dorme me la bevo come un cocktail questo ritmo che mi muove i problemi sono altrove le cuffie sulla testa viaggio sotto l ombrellone prendiamoci le stelle che il resto non ci serve uscire e fare le sette   andrã©s dvicio  ho voglia di andare piã¹ forte non ci basterãxa0 questa notte voglio vedere le luci dell alba cambiare colore voglio ballare con te  soltanto con te non chiedo la luna ma un ballo con te lasciamoci tutto alle spalle io e te fino a che nasce il sole   baby k  spengo tutto per due ore che mi scordo anche il mio nome bevo birra col limone senza ghiaccio per favore andiamo non so dove diplomiamoci in hangover scottiamoci la pelle poi cambiamoci colore prendiamoci le stelle che il resto non ci serve almeno fino a settembre   andrã©s dvicio  ho voglia di andare piã¹ forte non ci basterãxa0 questa notte voglio vedere le luci dell alba cambiare colore voglio ballare con te  soltanto con te non chiedo la luna ma un ballo con te lasciamoci tutto alle spalle io e te fino a che nasce il sole   baby k  le giornate cos㬠lunghe notti sempre troppo corte che ti svegli sulla spiaggia col rumore delle onde e mentre la notte finisce dimmi che male c 㨠se mentre ballo con lui io penso ancora a te   andrã©s dvicio  ho voglia di andare piã¹ forte non ci basterãxa0 questa notte voglio vedere le luci dell alba cambiare colore voglio ballare con te  soltanto con te non chiedo la luna ma un ballo con te lasciamoci tutto alle spalle io e te fino a che nasce il sole   baby k  andrã©s dvicio  voglio ballare con te  soltanto con te dã©jame quiero bailar contigo esta noche bailamos tã¹ y yo   yo  baby k ']

is there a way to decode that characters? (like è, à, ç)
here what I tried:
for s in l_text:
    print(s.encode('utf-8').decode('latin-1'))

for s in zz:
    print(s.encode('latin-1').decode('utf-8'))

for s in zz:
    print(s.encode('latin-1').decode('ISO-8859-1'))

and all combination of these encodings, but is not working. everytime it changes symbols (for example ù "-> from ã¹ becomes \xe3\xb9 )
with s.encode('latin-1').decode('utf-8') python gives me the well-known error:
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe3 in position 402: invalid continuation byte

Am I in the correct way? there is some specific encoding that i'm forgetting? or is there another way?
My last option is to drop every word that contains those "uncoded" chars, but I prefer to avoid.
IMPORTANT
I have no possibilites to change the text at the origin, that's what I am so pleas don't ask me where the text come from.. I have just a txt file with a lot of text like this. The problems are just in italian and spanish..I think.
thanks a lot in advance!

A: def string_cleaner(rouge_text):
    return ("".join(rouge_text.strip()).encode('ascii', 'ignore').decode("utf-8"))

Use ignore to ignore errors
Usage
for s in l_text:
 print(string_cleaner(s))


text:
Q: How to add 2 columns together in a call to update_counters I am trying to do this:
User.update_counters(user.id, :counter3 => :counter1 + :counter2)

But I get the error:
NoMethodError: undefined method `+' for

Is this possible to do?

A: Try this
User.update_counters(user.id, :counter3 => (user.counter1 + user.counter2))

this should work...
In your example you're trying to add two symbols (:counter1 + :counter2), but there's no +-method for symbols... and if it were you would set :counter3 to to the result of the addition of the symbols :)


text:
Q: Redux reducer failing to remove array element I'm having problems trying to get my reducer to work correctly in Redux. I'm new to Redux so I might be missing something simple, but I've played with it for a while and can't figure out what's going wrong.
Here is my process:
Define argument:
First I define the index value that I need. When logged, this returns the correct number...
const thisCommentIndex = parseInt(comments.indexOf(comment))

Function Call:

Action:
export function removeComment(index) {
   return {
      type: 'REMOVE_COMMENT',
      index
   }
}

Reducer:
function comments(state = [], action) {
   switch(action.type) {
      case 'REMOVE_COMMENT' :
         console.log('removing comment with index of ' + action.index)
         return [
            ...state.slice(0, action.index), // why isn't this working???
            ...state.slice(action.index)
         ]
      default :
         return state
   }
   return state;
}

When I console.log('removing COMMENT with index of ' + action.index), it logs the action.index correctly, the integer I would expect. But the function doesn't remove the element as expected.
Strangely, if I simply pass the array index instead, it works fine (removes the array element). (I would just do this, but due to the way I have set up my app it won't work in this case).
Am I missing something here? Any help appreciated.

A: You're missing a +1...
return [
  ...state.slice(0, action.index),
  ...state.slice(action.index + 1) // <--- need to actually skip what you want to remove
]

A: @Jack is correct.  Another option would be to use Array.filter instead:
return state.filter( (item, index) => index !== action.index)

You might be interested in the new Structuring Reducers section of the Redux docs.  In particular, the page on Immutable Update Patterns has some related examples.

A: If you want to remove multiple items, then you could work through your array backwards
 for (var i = this.props.items.length -1; i >= 0; --i) {
   if(this.props.items[i]["selected"]) {
     this.props.deleteSelectedItem(i);
   }
 }


text:
Q: send value using __doPostBack I'm sending a value (id) from javascript like this:
__doPostBack('',id)

and at the server side I get it like this:
var id = Request["__EVENTARGUMENT"];

the problem is that sometimes other controls also do stuff and the var id also get's value but not with the value I sent, but some control did.
how do I send this value separately so that in var id only the value that I sent using js can be.

A: One way to hack this I guess is to concat some token prefix like myId_ with id instead of just id as parameter, and parse id back in ASP.NET


text:
Q: Two classes issue I have asked you about GregorianCalendar and Calendar and some people said that Calendar is better. So I did it with Calender class.
I have a problem with one method: JavaApplication1#whichIsEarlier(), always receives error. Please check it, if you can. How to resolve it? I'll appreciate your help.
 public class JavaApplication1 {

public static void main(String[] args) {
    Calendar yy =Calendar.getInstance();
    Calendar xx= Calendar.getInstance();
    xx.set(2001, 10,10);
    Data dt = new Data(yy);
    Data xt = new Data(xx);
    Data dd = new Data( yy, xx);
    System.out.println(dt.toString());
    System.out.println(xt.toString());
    System.out.println(dd.whichIsEarlier());
}
}

class Data {
    private Calendar calendar;
     Calendar cale;
    Data(Calendar x){

    calendar = x;
}

Data(Calendar x, Calendar y){
    calendar = x;
    cale = y;
}

public String toString(){
    String months[] = {"Jan","Feb", "Mar" , "Apr", "Mai", "June", "July","Aug",
        "Sep", "Okt", "Nov", "Dec"};
    String str = "";
    str = "Data: "+ calendar.get(Calendar.DATE) +" "+ months[calendar.get(Calendar.MONTH)]+
        " "+ calendar.get(Calendar.YEAR);
        return str;

    }

    public String whichIsEarlier(Calendar cale){
        String str = "";
        if(calendar.after(cale)) str = calendar.toString() ;
        else str = cale.toString();
        return str +" jest wczesniej";
    }
 }

A: System.out.println(dd.whichIsEarlier());

is problematic as you only define a Data#whichIsEarlier(Calender).
Please make sure that either the whichIsEarlier call passes in a calendar object, or you create a new whichIsEarlier that takes no arguments and has calendars predefined.

A: This is how I would clean up your code:
class Data {
  private Calendar calendar;

  Data(Calendar x) { calendar = x; }

  public String whichIsEarlier(Data other) {
    return (calendar.after(other.calendar)? this : other)
        + " jest wczesniej";
  }

(I have elided toString; I'm not getting into its issues for this answer).
Note:

*

*removed the cale instance variable

*removed the two-argument constructor;

*whichIsEarlier accepts another Data, not another Calendar;

*its return value doesn't call calendar.toString but rather your own object's toString

*and it does it implicitly (string concatenation does that).

And now the main method should go like
public static void main(String[] args) {
  Calendar yy =Calendar.getInstance();
  Calendar xx= Calendar.getInstance();
  xx.set(2001, 10,10);
  Data dt = new Data(yy);
  Data xt = new Data(xx);
  System.out.println(dt.whichIsEarlier(xt));
}


text:
Q: Putting subclass into superclass list I have an abstract superclass named Troop and a few subclasses with different attributes. I am making a game, in my game I have these buttons to add different troops to the gameboard (the subclasses of Troop). I have this method:
public void addTroop(Troop troop)
{
    // Got a list called troopList in my main class
    main.troopList.add(troop);
}

Which is supposed to add the different troops to a list in my main function. But since there are differnet troops, megaTroop, fastTroop etc.. this gets messed up because the list won't take all the different types. The button is calling this addTroop method. I know it fails because I have written:
MegaTroop megaTroop = new MegaTroop();
and tried to insert it into the list which looks like this: public List<Troop> troopList;
I am pretty much in need to somehow cast my subclass as my superclass, any ideas on how to solve this? I hope I gave enough information. Thanks in advance!

A: Troop megaTroop = new MegaTroop();

as all your specific types of Troops are Troops anyway. It's called "programming to an interface". This way you can call your method and put your objects into list.


text:
Q: How to remove all commits in Git except the latest one? I want to clean up my commit history by removing all the previous commits and just keeping the  latest one. How can I do that in git ? I did try
git rebase -i ..but that seems to end in blood where I end up detaching my Head ..
git prune --expire doesn't seem to work either.
so if I have commits 1 to 10. I would just like to keep the 10th one with me now.
All of this is local. So that when I do decide to push I am only pushing 10.

A: The procedure is described in the git book:

Squashing Commits
It's also possible to take a series of commits and squash them down into a single commit with the interactive rebasing tool. The script puts helpful instructions in the rebase message:

#
# Commands:
#  p, pick = use commit
#  e, edit = use commit, but stop for amending
#  s, squash = use commit, but meld into previous commit
#
# If you remove a line here THAT COMMIT WILL BE LOST.
# However, if you remove everything, the rebase will be aborted.
#

If, instead of "pick" or "edit", you specify "squash", Git applies both that change and the change directly before it and makes you merge the commit messages together. So, if you want to make a single commit from these three commits, you make the script look like this:

pick f7f3f6d changed my name a bit
squash 310154e updated README formatting and added blame
squash a5f4a0d added cat-file

If you don't want to squash seceral commits into just one, but actually remove commits completely, then do what the script tells you to do:
# If you remove a line here THAT COMMIT WILL BE LOST.


text:
Q: Parar animação com requestAnimationFrame no canvas Estou utilizando o Canvas para fazer isso https://jsfiddle.net/m42hu8zg/ , só que gostaria de parar a animação ao clicar na div usando alguma funcionalidade do requestAnimationFrame. Eu usei o setInterval mas a animação não fica legal, então resolvi usar o requestAnimationFrame mas nao sei parar a animação apos um click e continuar apos outro click.
O código funciona simplesmente com uma circunferência por cima de uma linha usando o método clip(), e quando clica na  div, a circunferência move no eixo x passando por cima da linha mostrando-a, só que quero parar a animação apos um click e depois continuar (como um botão de play e stop, dando a intenção que a linha parou de crescer).
Seria possível também eu definir um caminho para a circunferência percorrer apos o click ? Exemplo: http://prntscr.com/7y1wpw
*No meu exemplo ele segue um caminho, mas é em linha reta, eu queria que a circunferência move-se por um caminho já pre-definido como no exemplo acima.

A: Consegui, o que eu fiz foi simplesmente colocar:
ctx.clearRect(cx, 0, canvas.width, canvas.heigth)

Com cx movendo para esquerda ou para direita, dai ele dava impressão que a linha crescia ou diminuía!


text:
Q: How to start working on async task in one activity and inform another activity on completion of work in OnBackground I would like to achieve the following behaviour, but I'm not sure how:
   1. User start an activity
   2. Activity starts an AsyncTask
   3. After initiating the AsyncTask,the control is transferred to another activity.
   4. Now,when the AsynTask finishes its work,the 2nd activity should get to know that        AsyncTask has completed its working in the previous activity.

I don't know how to achieve that functionality.I know how to use AsyncTask but i don't know how to inform any activity other than its parent activity about the finishing of its work.Please help me.Thanks in advance.
I want to do it because in 1st activity i want to start some working  in AsyncTask,then the control is transferred to 2nd activity but the AsyncTask is still running.When the AsyncTask will complete its functionality,i want to inform the 2nd activity about it and then want to perform some function in the 2nd activity.

A: You can create interface, pass it to the AsyncTask (in constructor), and then call interface method in onPostExecute..and make your second activity implements this interface..
For example:
Your interface:
public interface OnTaskCompleted {
    void onTaskCompleted();
}

Your second Activity:
public MyActivity implements OnTaskCompleted {
    //your Activity
}

And your AsyncTask:
public YourTask extends AsyncTask<Object,Object,Object> { //change Object to required type
    private OnTaskCompleted listener;

    public YourTask(OnTaskCompleted listener) {
        this.listener=listener;
    }

    //required methods

    protected void onPostExecute(Object o) {
        //your stuff
        listener.onTaskCompleted();
    }
}

A: *

*Create BroadcastReceiver in second activity and register it using
registerReceiver() method.

*sendBroadcast() in AsyncTask    onPostExecute() method of first
Activity.
public class SecondActivity extends Activity {
    private BroadcastReceiver myBroadcastReceiver =
        new BroadcastReceiver() {
            @Override
            public void onReceive(...) {
                ...
            }
       });

    ...

    public void onResume() {
        super.onResume();
        IntentFilter filter = new IntentFilter();
                    filter.addAction("com.example.asynctaskcompleted");
                    filter.addCategory("android.intent.category.DEFAULT");
        registerReceiver(myBroadcastReceiver, filter);
    }

    public void onPause() {
        super.onPause();
        ...
        unregisterReceiver(myBroadcastReceiver);
    }
    ...
}

public class FirstActivity extends Activity {
    private class MyTask extends AsyncTask<Void, Void, Void> {
        protected Void doInBackground(Void... args) {
        ...
    }

    protected void onPostExecute(Void result) {
        Intent intent = new Intent ("com.example.asynctaskcompleted");

        FirstActivity.this.sendBroadcast(intent);
 }

}


text:
Q: Creating a user-defined function to loop a dilution experiment and make a large table from the results I have two data sets, one is a table of gene expression of 20 genes (rows) for about 100 samples (columns).
Or simply:
              x1    x2    x3   ....
   gene1     1.2    1.4   1.5
   gene2     1.6    1.7   1.8
   ....

The other table has a different number of samples with the same number of rows (20).
I'm trying to create a new table that is a dilution between one chosen column of the first table with another chosen column of the second table,
percent_mix <- cbind(1.0, 0.90, 0.80, 0.70, 0.60, 0.50, 0.40, 0.30, 0.20, 0.10, 0)

rep.row<-function(x,n)
{
matrix(rep(x,each=n),nrow=n)
}

mixing_table <- rep.row(percent_mix, 20)

dilute <- function(x, y)
{
z1 <- x*mixing_table
z2 <- y*(1-mixing_table)
z1+z2
}

a <- dilute(table1[,1], table2[,1])

I want to make a loop so that I can dilute the first sample in table1 against all 12 samples in table2 and add all the results into one big table.
Then I need to do the exact same thing then to every column in table1 and add it onto the end that new big table.
I hope this makes sense. I'm looking to get one big table with every sample in table1 diluted against every sample in table2 and all the results in one final table.
Thanks for any tips!
g

A: The example that you gave can be simplified to two lines of code:
pmix <- seq(1, 0, -0.1)
a <- outer(table1[, 1], pmix) + outer(table2[, 1], (1-pmix))

You can insert this into a double loop that will cycle through each column of table1 paired with each column of table2 like this:
results <- array(dim=c(20, 11, dim(table1)[[2]], dim(table2)[[2]]))
for(i in 1:dim(table1)[[2]]) {
for(j in 1:dim(table2)[[2]]) {
    results[, , i, j] <- outer(table1[, i], pmix) + outer(table2[, j], (1-pmix))
    }}

The result will be a four-dimensional array (basically, a matrix of matrices).


text:
Q: How would you calculate the square you are jumping over on a checkerboard without using grid coordinates? Here's the problem, standard checkerboard notation does not use grid positions, instead it uses the following (depending on board orientation):
Black player view
-----------------
   1   2   3   4
 5   6   7   8
   9  10  11  12
13  14  15  16
  17  18  19  20
21  22  23  24
  25  26  27  28
29  30  31  32

White player view
-----------------
  32  31  30  29
28  27  26  25
  24  23  22  21
20  19  18  17
  16  15  14  13
12  11  10   9
   8   7   6   5
 4   3   2   1

When you make a legal capture (jump) move, you skip over a square. I need to determine, with math, what that square is 100% of the time under any direction (forward/back/left/right).
For example, if there was a player on 2, an opponent on 7, and a blank space on 11, a player on 2 could jump to 11.
How would you calculate the following for ANY valid 2 move points on the board (and by ONLY having/knowing those 2 number values available):

*

*The middle square between any two points on the board

*Detecting if a move is jumping to the left or the right

*If move is at an edge as looping around is not allowed (e.g. 12 to 17 is not a valid move to end up on 13. But this is less important as I can figure that out I think..).
I know I  will need to track if the move from is larger or smaller than the move to in order to get if a player is moving up or down the board. That's not the problem. I need the math to figure out the middle square and detect if the player is jumping left or right.
And yes I know this would be MUCH easier if I used a coordinate system like A1 to C3. But all my code and data structures are written around standard checkers notation. I have tried stuff like multiplying by 4, subtracting 1, then re-multiplying by 4.. but this doesn't work in all cases or tell me direction. I guess if I checked if each was divisible by 2,3,4 (else 1) I could perform different math on each case.
Any help would be greatly appreciated and here's a picture too if that helps:

A: Thanks @HighPerformanceMark for a similar idea.
I decided that this is not super easy to do and there's no one equation to calculate. So I wrote two converter functions for translating stuff into and out of grid notation. This allows logic to be done based on coordinate systems and data storage and display to be done via checkers notation:
def notation_to_grid(number):
    coordinate_mapping = {1: 'G1', 2: 'E1', 3: 'C1', 4: 'A1',
                          5: 'H2', 6: 'F2', 7: 'D2', 8: 'B2',
                          9: 'G3', 10: 'E3', 11: 'C3', 12: 'A3',
                          13: 'H4', 14: 'F4', 15: 'D4', 16: 'B4',
                          17: 'G5', 18: 'E5', 19: 'C5', 20: 'A5',
                          21: 'H6', 22: 'F6', 23: 'D6', 24: 'B6',
                          25: 'G7', 26: 'E7', 27: 'C7', 28: 'A7',
                          29: 'H8', 30: 'F8', 31: 'D8', 32: 'B8'}

    return coordinate_mapping[number]

def grid_to_notation(coordinate):
    coordinate_mapping = {'G1': 1, 'E1': 2, 'C1': 3, 'A1': 4,
                          'H2': 5, 'F2': 6, 'D2': 7, 'B2': 8,
                          'G3': 9, 'E3': 10, 'C3': 11, 'A3': 12,
                          'H4': 13, 'F4': 14, 'D4': 15, 'B4': 16,
                          'G5': 17, 'E5': 18, 'C5': 19, 'A5': 20,
                          'H6': 21, 'F6': 22, 'D6': 23, 'B6': 24,
                          'G7': 25, 'E7': 26, 'C7': 27, 'A7': 28,
                          'H8': 29, 'F8': 30, 'D8': 31, 'B8': 32}

    return coordinate_mapping[coordinate.upper()]

A: Given two valid move points, a -> b,
First, take k=(a-1)/4 mod 2 (where / is integer division). For instance:
(12-1)/4 | 2 = 11/4 | 2 = 2 | 2 = 0
(23-1)/4 | 2 = 22/4 | 2 = 5 | 2 = 1

(This tells whether the row is odd or even.)
As you know, if b>a, then it is a move up the board, and if b<a, then it is a move down the board.
if the difference between a and b is 7, it is a jump to the right; if the difference is 9, it is a jump to the left.
The jumped space is (a+b+1-2k)/2


text:
Q: Computed observable function in knockout I have a problem with my knockout implementation. I am new to knockout so would appreciate the help.
I have the following code:
    function updateViewModel() {
        if (typeof groupId == 'undefined') {
            groupId = getDefaultGroupId();
        }

        $.getJSON("api/livestatusgroup/children/" + groupId)
            .done(function (data) {
                ko.mapping.fromJS(data, liveStatusViewModel.groups);
                groupsLoaded();
            });

        $.getJSON("api/livestatusgroup/resources/" + groupId)
            .done(function(data) {
                ko.mapping.fromJS(data, liveStatusViewModel.resources);
                resourcesLoaded();
            });

        this.resourceImagePath = ko.computed(function () {
            return "../Image/" + this.ResID;
        }, this);
    }

    function ViewModel() {
        var self = this;
        self.resources = ko.mapping.fromJS([]);
        self.groups = ko.mapping.fromJS([]);
    }

    var vm = new ViewModel();
    ko.applyBindings(vm);

Unfortunately, the computed observable function resourceImagePath is not correctly capturing the ResID for my resource, so I end up with urls like /Image/undefined.
What am I missing? I have checked and the ResID field definitely exists in the view model.
S

A: When you implement a ko.computed observable, it only creates a dependency for observables that are referenced within the computed function.  Remember that observables must be referenced by executing them, because they are functions - it's this action that allows the computed function to detect and track a dependency.
Otherwise, the computed function will only be able to use the value that is available at the time the computed function is first executed.
This code references this.ResID, but doesn't have any dependency on it due to not treating ResID as an observable.
 this.resourceImagePath = ko.computed(function () {
        return "../Image/" + this.ResID;
    }, this);

Try ensuring that this.ResID is, in fact, an observable, and add parentheses like this:
 this.resourceImagePath = ko.computed(function () {
        return "../Image/" + this.ResID();
    }, this);


text:
Q: Appending characters to a string, what is the difference? auto str = std::string();

auto a = 'a';
auto b = 'b';

//this gives the desired output
str = str + a + b;

//this gives some garbage value
str += a + b;

What is the difference between these two expressions semantically?
Isn't the second one evaluated also as: str = str + a + b; ?

A: Since + has greater precedence than +=, the two characters are added first. Your code is equivalent to:
str += (a + b);

This is clearly not what you want. The addition of the two char values gives a totally different char value as a result, not their concatenation (chars are not strings).

A: //this gives some garbage value
str += a + b;

This is semantically same as
str = str + (a + b);

because all assignment operators have lower precedence than almost anything (C++ operator precedence table here).
And adding two char together performs integer addition of the character codes, producing a higher char code, which is probably above ASCII range, so something which looks garbage or graphical symbol. On ASCII character encoding (basically all PCs use extension of that), 'a' + 'b' == 97 + 98 == 195, which for example in Latin1 character set is 'Ã'.

A: In the first case you have (str + a) + b. If you change it to str = str + (a + b) you will get the same garbage result. a + b chars result to char with ASCII code 195 (97 + 98) and it is added to str.

A: str = str + a + b; will be evaluated as (str + a) + b. The overloaded + operator on std::string for a char type will be used. And this will concatenate a to str. b will follow similarly.
The other expression is undefined if your char type is signed on your platform. This is because a + b is evaluated first, and this could overflow your char type on your platform. If char is unsigned, then the ASCII value 195 will be concatenated to str.


text:
Q: Suggestions on text input in Redux-form I have done quite a bit of searching but I havent found the solution I hoped for.
My goal is to show suggestions to user when he starts typing in the text input. Say I have an array of names that will be suggested. I suppose there will be an onChange handler but Im not sure how to implement this efficiently.
I am grateful for any suggestion!

A: Baically, what you need to do is to create some kind of <AuotoComplete /> input component (or - what one would usually do - use some third party component libary which will provide this functionality out of the box. For example material-ui, react-select, react-autosuggest etc.).
Then you will need to deligate redux-form's <Field />'s onChange and value props to this component in order for it to update your redux-form reducer.
The implementation should look something like this:
   <Field
      name="fieldName"
      component={({ input: { value, onChange } }) => (
        <AutoComplete value={value} onChange={onChange} />
      )}
    />

Here's a working example I created with material-ui's AutoComplete.
(Bear in mind that I used redux-form-material-ui which abstracts the delegation of the onChange and value and allows you to use all of material-ui's AutoComlete's props streight on redux-form's <Field/>)
Hope this helps :)

A: How you could approach it, is to fetch all the array data by dispatching an redux action getNamesArray and then use the filter and map functions in the component:
componentDidMount() {
  this.props.getNamesArray();
}

render(){
  const { namesArray } = this.props; // from redux mapStateToProps
  let namesArrayItems;

  if (namesArrayItems.length > 0) {
    namesArrayItems = namesArray
      .filter(name => {
        // remove names that do not match current filter text
        return name.toLowerCase().indexOf(this.state.name.toLowerCase()) >= 0
      })
      .map(name=> (
        <NameItem key={name._id} name={name} />
      ));
    } else {
      namesArrayItems =
No Names found...
;
        }
  return (
    {namesArrayItems}
  );
}

Then use a text field input that is passed above as this.state.name by using an onChange handler to get user input:
onChange(e) {
  this.setState({ [e.target.name]: e.target.value });
}

And in the return put and text field with the onChange handler:
<input
  type="text"
  name="name"
  value={this.state.name}
  placeholder="Filter Names"
  onChange={this.onChange.bind(this)}
/>

Works fairly efficient for me. The downside to this approach is that you first fetch all your array data, so this make take longer loading times, however the application does not need to fetch data with each user input, making the user experience more seamless.


text:
Q: Is it possible to use Username and Password as a Plain text to get Office 365 Groups and users in c# code using Microsoft Graph API? The question is very straight forward.
Is it possible to use Username and Password as a Plain text to get Office 365 Groups and users in c# code using Microsoft Graph API or any other API?
If yes, then how? I need to develop an application where I need to fetch the Office 365 Groups and Users and display it to the Non Admin Users too.

A: We can use SharePoint Online CSOM(Download SharePoint Online Client Components SDK) to achieve it. The code below for your reference.
string targetSiteURL = @"https://xxx.sharepoint.com/sites/lz";

//set user login name and passsword
var username = "lz@xxx.onmicrosoft.com";
var password = "Password";

var securePassword = new SecureString();
foreach (char c in password){securePassword.AppendChar(c);}

SharePointOnlineCredentials onlineCredentials = new SharePointOnlineCredentials(username, securePassword);

ClientContext ctx = new ClientContext(targetSiteURL);
ctx.Credentials = onlineCredentials;

GroupCollection groups = ctx.Web.SiteGroups;
ctx.Load(groups,gs=>gs.Include(g=>g.Title,g=>g.Users));
ctx.ExecuteQuery();

foreach(Group group in groups)
{
    Console.WriteLine("Group Name:"+group.Title);
    foreach(User user in group.Users)
    {
        Console.WriteLine("   UserName:"+user.Title);
    }
    Console.WriteLine("-------------------------------------------");
}
Console.ReadLine();


text:
Q: IE10 Hover + Pseudo Elements Example: http://codepen.io/mastastealth/pen/gFjhi
Basically, I have an element with an :after element set to opacity 0. On hover, it goes to opacity 1. Apparently it works in IE9 and everywhere else, but not IE10 (unless I click)? Ideas?

A: It appears there is a bug where the selector with a pseudo class followed by a pseudo element is not listened for when an event happens. If you add the listener by simply adding the selector with only the pseudo class your style will be applied on the event occurring.
http://codepen.io/justinphillips/pen/qvHyi
.p:hover:after {
    opacity: 0.7;
  }

.p:hover {}

A: Apparently IE10 continues the horrible bug of not accepting :hover on divs. Example updated using an  element instead and it works fine.


text:
Q: Jquery bind or on is not working for custom event I have a JSP file containing an iframe. On the parent JSP some .js (Timer.js) file is referred in which a custom event is created using this code:
$(document).ready(function(){
    RegEvent();
    $('#time-text').trigger('updateDBTime');
});

function RegEvent()
{
    $('#time-text').bind('updateDBTime',function(e){
        alert('called');
    });

}

#time-text is an span on parent JSP.
The above code works fine.
Now I want to trigger this event from the .js file referred in iframe. I tried:
$('#time-text',window.parent.document).trigger('updateDBTime');
and
$('#time-text').trigger('updateDBTime');
Both versions don't work and log no error on the console.
I am using jquery-1.9.0.min.js

A: This work:
parent.$({selector}).trigger( 'eventName' );
the event triggered inside the iframe will be detected in the parent document.

A: You can try with this:
$(window.parent.document.getElementById('time-text')).trigger('updateDBTime');


text:
Q: How do I view syslogs on a remote server with Windows and a web browser? I have Ubuntu Clients running 12.04 LTS and a Ubuntu machine as the server. Now I have configured Ubuntu machines as syslog clients and they are intended to send their logs to the Ubuntu machine.
But how can I view those logs in my Windows machine? A browser-based solution is preferable.

A: I've used LogAnalyzer, a PHP frontend for rsyslog in conjunction with Ubuntu. It does lag if the volume of records gets to be too much though.


text:
Q: Find and replace text with pattern in R I have a df here below and I need to delete under only the column FRUIT that contains any text with [...].  Please see my df

DATE
FRUIT
LOCATION
VALUE

2010-01-01
Apple [111-112, 1100, 1151-1152]
USA
2

2010-01-01
Pinapple [22]
USA
12

so ideally I want my df to look like this

DATE
FRUIT
LOCATION
VALUE

2010-01-01
Apple
USA
2

2010-01-01
Pinapple
USA
12

I tried to use gsub, but it is not working out.
df$FRUIT<-gsub("[*]", "", df$FRUIT)

A: Perhaps you can try gsub like below
df$FRUIT <- gsub("\\s\\[.*\\]","",df$FRUIT)

and you will get
> df
        DATE    FRUIT LOCATION VALUE
1 2010-01-01    Apple      USA     2
2 2010-01-01 Pinapple      USA    12

Data
> dput(df)
structure(list(DATE = c("2010-01-01", "2010-01-01"), FRUIT = c("Apple [111-112, 1100, 1151-1152]",
"Pinapple [22]"), LOCATION = c("USA", "USA"), VALUE = c(2L, 12L
)), class = "data.frame", row.names = c(NA, -2L))


text:
Q: Can not upload video on facebook page via facebook graph api in python PAGE_ACCESS_TOKEN ='...'
    location_of_video='Pokemon.mp4'
    payload = {
        'access_token':PAGE_ACCESS_TOKEN,
        'source':location_of_video
    }
    headers = {'content-type': 'multipart/form-data'}

    url = 'https://graph-video.facebook.com/v14.0/{}/videos'.format(pageId)
    r = requests.post(url, json=payload, headers=headers)
    print(r.text)

I tried using post request to post video on facebook page. I got error with accesstoken permission
{"error":{"message":"An access token is required to request this resource.","type":"OAuthException","code":104,"fbtrace_id":"ARidN0DcLJynUVOGLaIfQ-t"}}

This is how I get the accesstoken
how can I fix it? Thanks you


text:
Q: как выполнить функцию js после асинхронной загрузки библиотеки На сайте, в блоке head, у всех подключаемых скриптов стоит async, кроме двух:
<script type="text/javascript" src="/java/jquery-1.5.2.min.js"></script>
<script type="text/javascript" src="/java/cusel-min-2.3.1.js"></script>

Где-то в body вызывается функция cuSel, которая находит на странице нужный <select> и превращает его в кучу дивов (для "красоты").
var params = {
changedEl: ".lineForm select",
visRows: 18,
scrollArrows: true
}
cuSel(params);

Для вызова нужно, чтобы cusel-min-2.3.1.js был уже загружен. Сама библиотека cusel-min-2.3.1.js использует jquery-1.5.2.min.js, то есть он должен быть загружен первым, выходит.
Подскажите, можно ли как-то выйти из ситуации и организовать код так, чтобы все это загружалось асинхронно и вызов cuSel(params) происходил после загрузки этих двух библиотек? (я пытался смотреть соседние темы но ответа не нашел)

A: Можно подвязать вызов функции на событие window.onload, оно триггерится после того, как все скрипты будут загружены.


text:
Q: Win 7 Explorer keeps reopening network shared folders? We have a script that runs nightly on our Win2K SP4 server. (I know, we need to upgrade the server OS. We plan to do that soon.)
Sometimes the script has failed when people had left shared folders open from their desktops.
So we have used the net files and net file NNNN /close batch commands to find and close them. This has worked for us.
However as of last week, some folders were left open from a Windows 7 desktop. The script "closed" them as usual, and the log shows The command completed successfully. for each one. But the folders were apparently still open: the script's later operations on those folders failed.
This is confirmed when I log in to the Win2K server and manually close the open folders using Computer Management > Shared Folders > Open Files / Right-click > Close. When I do that, the open folders disappear from the list at first, but then when I refresh the list, those folders are back on it.
Notably, this happens with folders open in Explorer on Windows 7, but not with folders open on Windows XP, for example. If a shared folder is open in Windows Explorer on XP, and I close that folder from the server side, it stays closed. This problem also does not happen with files open in certain other apps; e.g. if I have a file open in Notepad++, and I close it on the server, it stays closed.
On the server side, I have tested this phenomenon in Win2003 Server and Win2008 Server Standard SP2. The result is the same: when you close an open shared folder from the server side, it reappears immediately (or never disappears, in the case of Win2008). But only if it's open from Windows 7; not from e.g. Win2003 Server.
So I wonder if there's been some Windows 7 update recently that causes Explorer to immediately re-open folders that have been closed by the server?
If so, what could I do about it from the server side, to keep those folders closed until our script is done running?
Thanks for any help or suggestions.

A: I dunno if I like this suggestion, but I'll make it anyways.  What about using "net stop server" and then once the process completes "net start server"?  Since the sharing services would be offline, no amount of trying on the part of the client workstations should allow it to reconnect.  I don't know what other side effects this would have in your enterprise.  Printers and other windows services would go offline as well, so just be forewarned.


text:
Q: Asynchronous computation in TensorFlow using Estimator API What would be the answer for this question Asynchronous computation in TensorFlow when we want to perform asynchronous training, using multiple (CPU) threads, but on top of a model implemented using the Estimator API?
For instance on a model like this one?


text:
Q: How to display pop up image when click point in OpenLayers web map I have basic WMS web map showing parcels and points layers which representing buildings of parcel. Then I want to add building images for each and every point. Then when a user clicks on a point image should appear as a pop up window.
I am using  OpenLayers 2.10 Beginner's Guide book and can't find any method to do the above thing.
Is this possible with OpenLayers? If so please give me some advise or some links to help me.
All layer are in WMS form and I am using GeoServer and Tomcat.

A: You need to make a getfeatureinfo request and then display the result in a popup. The basics of this are shown in this example. Once you have this working with your data you will want to format the information returned by the getfeatureinfo request so that it displays the image GeoServer provides a templating language that will allow you to do this - see this tutorial for more details and an example.


text:
Q: Node: Applying express middleware to specific GraphQL query types I have multiple graphql query types. I wish to apply middleware to one query type only for authentication. Is this possible?
Something like this
app.use(
 '/s',
 (request, response, next) => {
  if (request.body.message === 'delete') {
   auth();
  }

  next();
 },
 graphqlHTTP({
  schema: require('./r/s').schema(),
  graphiql: true,
 })
);

The issue is that the format of the body is not JSON.
Maybe I am taking the wrong approach.

A: Yeah, actually you can accomplish that by using graphql-middleware library.
you just define the middleware and then attach it to a specific Query or Mutation.
a grqphql middleware works as a resolver, it takes: parent, args, context, info and in addition to those it also takes "resolve" which is a function we call when the middleware finishes, pretty much like "next()" in express.
asycn function checkIfUserLoggedIn(resolve, parent, args, context, info){
    // check if user logged in or not

   // now we call resolve and pass the arguments to the resolver which is in our case "getSecret" Query
return resolve(parent, args, context, info)
}

const middlewares = {
  Query: {
    getSecret: checkIfUserLoggedIn,
  },
};

const schemaWithMiddleware = applyMiddleware(
  schema,
 ...middlewares
)

and then you edit your graphqlHTTP to:
graphqlHTTP({
  schema: schemaWithMiddleware,
  graphiql: true,
 })


text:
Q: ¿Como crear un archivo excel con Node Js y Vue? Necesito ayuda, deseo crear un archivo excel con node js.Actualmente estoy trabajando node.js, vue.js y Vuetify.
La informacion es consultada desde una api externa, la cual no tengo el codigo y si la consulto me envia como respuestas en formato JSON.
Aqui un ejemplo de la respuesta que recibo.
[
{
    "total": 0,
    "estado": 1,
    "eliminar": 1,
    "_id": "5e627023b41f9913e4cb0f31",
    "nroVale": 1011,
    "cliente": {
        "_id": "5e5e9101dc22821b041057dd",
        "nombre": "Solicitante de Prueba"
    },
    "usuario": {
        "_id": "5e62472fb41f9913e4cb0f30",
        "nombre": "Encargado de Prueba"
    },
    "otVale": "BR-102",
    "comentario": "Es un comentario de Pruba",
    "equipo": {
        "_id": "5e60f7b23c702d1fe0bf1526",
        "nombre": "Sin Equipo"
    },
    "productos": [
        {
            "_id": "5e4af46ad7fab94d8625705d",
            "codigo": "1",
            "unidad": "UN",
            "conversor": "0",
            "tipoConversor": "0",
            "descripcion": "Manguera",
            "cantidad": 10
        },
        {
            "_id": "5e4af448d7fab94d86256ef1",
            "codigo": "3",
            "unidad": "UN",
            "conversor": "0",
            "tipoConversor": "0",
            "descripcion": "Vaso  ",
            "cantidad": 10
        },
        {
            "_id": "5e4af448d7fab94d86256ef3",
            "codigo": "5",
            "unidad": "UN",
            "conversor": "0",
            "tipoConversor": "0",
            "descripcion": "Torta  ",
            "cantidad": 16
        },
        {
            "_id": "5e4af448d7fab94d86256ef4",
            "codigo": "11",
            "unidad": "BL",
            "conversor": "0",
            "tipoConversor": "0",
            "descripcion": "Sillas ",
            "cantidad": 18
        }
    ],
    "Local": {
        "_id": "5e569e05f6316f1940225903",
        "nombre": "Casa Central"
    },
    "empresa": {
        "_id": "5e569e8df6316f1940225906",
        "nombre": "Externo Prueba"
    },
    "actividad": {
        "_id": "5e56a6478fc37f4180fca309",
        "nombre": "Fiesta de Cumpleaño"
    },
    "fecha": "2020-03-04T00:00:00.000Z",
    "centroCosto": {
        "_id": "5e46b42a8ee91743a0c9230d",
        "nombre": "Pago Efectivo"
    },
    "Payaso": {
        "_id": "5e46b42a8ee91743a0c9230d",
        "nombre": "Gorrito"
    },
    "__v": 0
}

]
Yo recibo esta informacion en formato JSON y la almaceno en un array y este array necesito transformarlo en formato .xlsx o  excel
Si tuvieran un ejemplo para asi tomar una idea, se los agradeceria demasiado.

A: Con la libreria XLSX puedes exportarlo de forma sencilla: https://www.npmjs.com/package/xlsx
Un codigo de ejemplo: this.data debe ser un array que contenga tus datos.
exportar() {
    let data = XLSX.utils.json_to_sheet(this.data);
    const workbook = XLSX.utils.book_new();
    const filename = "planilla";
    XLSX.utils.book_append_sheet(workbook, data, filename);
    XLSX.writeFile(workbook, `${filename}.xlsx`);
}


text:
Q: "Datatype mismatch" in C# and SQLite code
private void button1_Click_1(object sender, EventArgs e)
{

    //string sql = "INSERT INTO Product_details(ID,name,qty,r_rate,W_rate,category,Department,taxable,GST_CLASS,hsn_code,s_packing,M_packing,Max_stock,min_stock,status)VALUES(null,'"+txt_box_P_Name.Text+"', '"+txt_box_qty.Text + "','"+txt_box_RRate.Text + "','"+txt_box_WRate.Text+"','"+com_box_Cat.Text+"','"+txt_depart.Text+"','"+gststatus+"','"+txt_box_GST.Text +"','"+txt_box_hsn.Text+"','"+txt_box_std_package.Text+"','"+txt_box_mas_pack.Text+"','"+txt_box_max_stock.Text+"','"+txt_box_min_stock.Text+"','"+comboBox1.Text+"');";
    string sql = "INSERT INTO Product_details  VALUES(    'NULL',                              '"+txt_box_P_Name.Text+"',                                '"+txt_box_qty.Text+"',                                '"+txt_box_RRate.Text+"',                                '"+txt_box_WRate.Text+"',                                '"+ com_box_Cat.Text + "',                                '"+txt_depart.Text+"',                                '"+txt_box_pur_price.Text+"',                                '"+txt_box_GST.Text+"',                                '"+txt_box_hsn.Text+"',                                '"+txt_box_std_package.Text+"',                                '"+txt_box_mas_pack.Text+"',                                '"+txt_box_max_stock.Text+"',                                '"+txt_box_min_stock.Text+"',                                '"+comboBox1.Text+"'                            );            ";
    try
    {
        SQLiteCommand cmd = new SQLiteCommand(sql, con);
        con.Open();
        cmd.ExecuteNonQuery();

        ClearTextBoxes();
        MessageBox.Show("Product Added");
    }
    catch (Exception ex)
    {

        MessageBox.Show(ex.Message);
    }
    finally
    {
        con.Close();
    }

}

A: SOLVED
THANKS C.EVENHUIS & ED PLUNKETT
private void button1_Click_1(object sender, EventArgs e)
    {

        string sql = "INSERT INTO Product_details  VALUES(NULL,'"+txt_box_P_Name.Text+"','"+txt_box_qty.Text+"','"+txt_box_RRate.Text+"','"+txt_box_WRate.Text+"','"+ com_box_Cat.Text + "','"+txt_depart.Text+"','"+txt_box_pur_price.Text+"','"+txt_box_GST.Text+"','"+txt_box_hsn.Text+"','"+txt_box_std_package.Text+"','"+txt_box_mas_pack.Text+"','"+txt_box_max_stock.Text+"','"+txt_box_min_stock.Text+"','"+comboBox1.Text+"');";
        try
        {
            SQLiteCommand cmd = new SQLiteCommand(sql, con);
            con.Open();
            cmd.ExecuteNonQuery();

            ClearTextBoxes();
            MessageBox.Show("Product Added");
        }
        catch (Exception ex)
        {

            MessageBox.Show(ex.Message);
        }
        finally
        {
            con.Close();
        }

    }


text:
Q: Deleting Many-To-Many entry How can one delete a Many-To-Many entry?
I have the entities Client and Restaurant and a relationship table and entity between them: ClientRestaurant having the following columns: ClientID, RestaurantID, DateOfBill.
A client entity has the navigational property ClientRestaurants which is a list of ClientRestaurant.
When I delete an entry from a Client's ClientRestaurants list:

myClient.ClientRestaurants.Remove(myClientRestaurants)

and then try to SaveChanges I get the following error:
Adding a relationship with an entity which is in the deleted state is not allowed.
Update: I set the columns in ClientRestaurants table from SQL Server as Nullable. Now if I do:

myClient.ClientRestaurants.Remove(myClientRestaurants)
  myRestaurant.ClientRestaurants.Remove(myClientRestaurants)

and then SaveChanges it works fine, I mean the entries from relationships are removed, but in DB remains a row with NULL values, and since I have an UNIQUE INDEX for those two columns, I can only have one row with NULL values. There has to be another solution, but it eludes me.
Any help greatly appreciated.
These are the functions that add and remove records to the intermediary table.
Private Function addTehnicianToLucrare(L As Lucrare, T As Tehnician) As TehnicianLucrare
    Dim result As TehnicianLucrare = Nothing
    Dim TL As New TehnicianLucrare
    TL.Tehnician = T
    'T.LucrariTehnician.Add(TL)
    TL.Lucrare = L
    'L.TehnicieniLucrare.Add(TL)
    If TL IsNot Nothing Then result = TL
    Return result
End Function
Private Function removeTehnicianFromLucrare(L As Lucrare, T As Tehnician) As TehnicianLucrare
    Dim result As TehnicianLucrare = Nothing
    Dim TL As TehnicianLucrare = Me._ctx.TehnicieniLucrare.Local.Where(Function(p) p.Tehnician Is T And p.Lucrare Is L).SingleOrDefault
    If TL IsNot Nothing Then
        Me._ctx.TehnicieniLucrare.Remove(TL)
        result = TL
    End If
    Return result
End Function

Consider Lucrare as Restaurant and Tehnician as Client from the above description.

UPDATE: I have these Subs:
Private Sub list_TehnicieniRaport_DoubleClick(sender As Object, e As EventArgs) Handles list_TehnicieniRaport.DoubleClick
    Try
        If Me.list_TehnicieniRaport.SelectedIndex > -1 Then
            Dim curTeh = TryCast(Me.list_TehnicieniRaport.SelectedItem, TehnicianLucrare)
            If curTeh IsNot Nothing Then
                'setProperty("TehnicieniLucrare", curTeh.Tehnician)
                moveToDataTable(curTeh.Tehnician)
                'ChangeTracker.HasChanges() gives error here
            End If
        End If
    Catch ex As Exception
        logError(ex)
    End Try
End Sub

Public Sub moveToDataTable(ByRef pTehnician As Tehnician)
    Try
        setProperty("TehnicieniLucrare", pTehnician)
        If getProperty("Edit") Then selectEchipa()
        selectCar()
    Catch ex As Exception
        logError(ex)
    End Try
    'ChangeTracker.HasChanges() DOES NOT give error here.
End Sub

This way I get the error, and it appears right after the moveToDataTable() sub exits. I had step-by-step debugging and calling _ctx.ChangeTracker.HasChanges() after every step.
If I move the setProperty("TehnicieniLucrare", curTeh.Tehnician) to the list_TehnicieniRaport_DoubleClick(...) sub, then I don't get the error, and everything works just fine. I don't understand.....

A: Excerpt from your question:
having the following columns: ClientID, RestaurantID, DateOfBill.

I get the feeling this intermediary table is not automatically generated by EF, but rather a separate table that you individually defined. My main reasoning behind this is that you're adding the DateofBill, which means you're manually inserting items in the table.
It might act just like an intermediary table, but EF doesn't see it that way.
If you set up a many-to-many via EF (i.e. not managed by you, but autogenerated), there will still be a table, but it will be hidden behind the ORM. Your code snippet applies to this scenario. In this case, you need to remove the relation; and the internal table row will be deleted by EF. Because the table is part of describing the relation.
But if your intermediary table is a separate table that you defined yourself, it is an entity; and you need to handle it just like you would handle any other entity.
The table is a specifically defined table, and it has two relations, to Client and Restaurant.
Remove the ClientRestaurant entity just like you would any other entity:
myContext.ClientRestaurantTable.Remove(myEntityToRemove);

Don't worry about the relations. They are contained in that ClientRestaurant row (ClientID, RestaurantID), there won't be a referential issue.
The key part to keep in mind here is that there is a difference between the tables EF autogenerates for you, and an intermediary table you set up yourself (in most cases, this is only done when you need additional columns in that table, like your DateofBill)


text:
Q: PHP postgres fetch with table prefix The pg_* functions (pg_fetch_array()) return data from postgres.
Executing a query that uses table prefixes, the prefixes get dropped:
pg_query('SELECT a.*, b.* FROM table_a a JOIN table_b b ON a.id = b.id');

Result are the columns from a and b but without a. or b. prefixed.
How to enable the prefixes?

A: First, those aren't prefixes. Those are table aliases.
Second, table aliases don't work that way. (They're not something that can be enabled and disabled in SQL or PHP, although another application language might offer some way to do that.)
The best you can do is to create your own prefixes. Starting with these tables . . .
create table table_a (
    id int primary key
  );

create table table_b (
    id int primary key
  );

insert into table_a values (1);
insert into table_b values (1);

. . . you can alias each column to show which table it came from.
select a.id as a_id, b.id as b_id
from table_a a
inner join table_b b ON a.id = b.id;

a_id  b_id
--
1     1


text:
Q: How do I query MarkLogic to determine cost of re-indexing? I have a multi-terabyte Production database (MarkLogic 9.0-8, RedHat) that I need to add 2 new element range indexes to. Before I can execute the change, I need to get an estimate of the number of documents that will be impacted by the re-index to ensure my maintenance window is sufficient to avoid performance impacts. Will the following code provide me with what I am needing?
xquery version "1.0-ml";

xdmp:estimate(cts:search(fn:doc(), cts:word-query("someTimestamp")));
xdmp:estimate(cts:search(fn:doc(), cts:word-query("someString")));

A: Instead of a word-query I'd rather count the fragments containing the elements of your two new element range indexes using a element-query.
xdmp:estimate(
  cts:search(fn:doc(),
    cts:element-query(xs:QName("your-index-element"), (cts:and-query(())))
  )
)


text:
Q: How to add a skybox to camera and using layer to show it only in main menu? I have 3 scenes and I want that when the main menu scene is active to display a specific skybox.
This is what I did so far :

*

*Added a new layer called it Skybox Planet

*Disabled the player camera.

*Changed the layer in the main menu camera to be Skybox Planet.

*Changed in the main menu camera the Culling Mask to only Skybox Planet

*In Window > Rendering > Lightning Settings > Skybox Material dragged to there my Skybox.

Screenshots :

*

*The Main Menu Camera Inspector settings : You can see in the background in both scene view and game view the skybox and how bad it looks like :

*The Lightning Settings window after dragged the Skybox_0000 and the warning I'm getting there in yellow :

The problems are also mentioned above are :

*

*The skybox is looks very bad in both scene view and game view windows.

*There is a warning in the Lightning Settings window in the Skybox Material field.
Last this is how the skybox should looks like in the sceneview and in the gameview if looking from inside the spaceship :

Update on what I did last :
I changed the skybox material shader to Skybox/6 Sided and then added to each side a skybox texture :
but it seems wrong maybe I added the texture in the wrong order ? When I'm running the game using a script to rotate the skybox it looks like it's moving to the side and not that the camera moving around the skybox. The effect by rotating the skybox should also be looks like the camera is moving around the planet.
You can see on the left the scene view and game view windows how it looks like wrong.

And this is the textures in the Assets :

The effect should be like the skybox is 3d planet and the camera is rotating around it I'm rotating the skybox but this is the effect I want to get.

A: I think the problem is just where you placed the 6 sides. You need to Swap these:

*

*Front +Z is correct

*Back -Z should be the Left +X

*left +X should be Right -X

*Right -X should be Back -Z

*Up +Y is correct

*Down -Y is correct


text:
Q: How reload wordpress page without Cache? I am facing problem from wp cache. I have an contact listing page. When user delete on of his contact from the listed contacts then on the page it show that the record has been deleted and even record also disappear from the page but when the user again come to that page or refresh the page then the deleted record again come in the list. Although in the database that record has been deleted. When I press Ctrl+F5 then all thing is working fine.
After reading many forum I knew that this problem is due to Cache plugins. So I disable wp_supercache plugins and I also disabled the wordpress's own cache but yet I have to press ctrl+F5 to remove the deleted records from the html page.
Please help so that wp cannot set any kind of cache.
Thanks in advance.

A: In the header of the template file in question (probably header.php in the theme directory), try adding:
<?php nocache_headers(); ?>

This doesn't sound like it is a problem with the cache plugins, which basically control caching on the server, it is more likely that this is caching on the client. This will tell the browser not to store a copy of the page.
Reference: http://codex.wordpress.org/Function_Reference/nocache_headers
A quick and nasty solution is to add this as a child of the HTML head element too:
<meta http-equiv="cache-control" content="no-cache" />

Hope that's what you're looking for!


text:
Q: Issue with returning values from invoking same function multiple times Ok, so I'm doing this homework assignment and my teacher's first language is not English and is not always the best at giving directions.  I'm trying to write a program that asks for a midterm score and a final exam score and then adds those two values to display a total score.
My problem is that it doesn't seem to return the entered scores or store them in their respective variables in order to be added together (aka it always displays zero as the total)
Here is my code:
// Lab11P2.cpp

#include<iostream>
using namespace std;

double getNcheckScore(double, double);

int main()
{
    double midterm = 0.0;
    double final = 0.0;
    double total =0.0;

    cout << "MIDTERM EXAM" << endl;
    midterm == getNcheckScore(midterm, final);

    cout << "FINAL EXAM" << endl;
    final == getNcheckScore(midterm, final);

    total = midterm + final;
    cout << "Total score: " << total << endl;

    system("pause");
    return 0;
}

    double getNcheckScore(double midterm, double final)
{
    double score = 0.0;
    cout << "Please enter your score: ";
    cin >> score;
    while (score < 0 || score > 100)
    {
          cout << "Score must be between 0 and 100.  Please enter again: ";
          cin >> score;
    }
    return score;
}

A: You are using == instead of = here:
midterm == getNcheckScore(midterm, final);

and here:
final == getNcheckScore(midterm, final);

So these are not assigning values to these variables at all. Which is a good reason to compile with warning turned on because you would have seen something like this:
warning: value computed is not used [-Wunused-value]
 midterm == getNcheckScore(midterm, final);

which would have been a good clue. Also you are not doing anything with the two arguments to your function:
double getNcheckScore(double midterm, double final)

but if you plan to eventually pass back the data through these arguments they will need to be references, like so:
double getNcheckScore(double &midterm, double &final)

A:
midterm == getNcheckScore(midterm, final);

Don't use ==, this is a comparison operator. Use = for assignment.


text:
Q: Weird Behavior Deploying Azure Cloud Service I have a very weird issue deploying an azure cloud Service. I have 1 Web Role with 5 instances and 1 Cache Role with 2 instances.
When I deploy my MVC 5 WebRole from the Azure Portal, deploying starts on the first web instance, then it tells me that the "The role could not be started" due to an error and stops processing the other instances. I did an RDP to the failed instance and truly the MVC application throws an error that it can't find a certain view file "The layout page "..." could not be found at the following path", even though the view in the path specified does exist. So I did an iisreset and the application worked. after I manually fixed the issue the deployment continues to the next instance and the failed instance becomes "Ready".
Anyone has an idea why things don't deploy smoothly anymore or why an iisreset is necessary?
This is relatively recent, around a month.
My environment is:

*

*.NET Framework 4.5.1

*MVC 5

*Azure SDK 2.4 for VS 2013

Thanks for the help.

A: FINALLY!! I found the issue and fixed it.
I had a Local Storage Resources to store temporary files and local file caches for certain components, and was configured to reset on role restart. One of the components (Lucene.NET for azure) was locking the files in that local storage, causing the problem on deployment that needed to to IIS reset to release the lock.
I configured the component to cache the files on Windows temp storage instead of the Local Resource and things worked out.