text:
Q: knockout.js How to get values from form and get additional data ASP.NET MVC What i got is:
var post = function(id, message, username, date) {
    this.id = id;
    this.message = message;
    this.username = username;
    this.date = date;
    this.comments = ko.observableArray([]);

    this.addComment = function(context) {

        var comment = $('input[name="comment"]', context).val();
        if (comment.length > 0) {
            $.connection.boardHub.server.addComment(this.id, comment, vm.username())
                .done(function() {
                    $('input[name="comment"]', context).val('');
                });
        }
    };

And View:
<form class="add-comment" data-bind="submit: addComment">

    <input type="text" class="form-control" name="comment" placeholder="" />

    <button class="btn btn-default" type="submit">Answer</button>

And the question is how can i pass to addComment extra value without missing context?
Like:
<form data-bind="submit: function(){ writePost(<context>, '@ViewBag.UserN'); }">

A: As I mentioned in my comment, you are not using knockout correctly. Therefore I'll provide you with a generic example of how you should handle form submits using knockout.
First, you should define a viewmodel which wraps your UI data and connects to services to do any actual logic. In simple cases, many people just write the logic, such as API calls right into the viewmodel instead of a service. For simplicity, I'll just do that, because extracting it into its own 'class' should be simple enough. You should give your viewmodel a more descriptive name than post. Here is an example:
var commentViewModel = function(id, userName) {
    var self = this;

    this.commentText = ko.observable('');

    this.addComment = function() {
        var txt = self.commentText();

        if (txt) {
            $.connection.boardHub.server.addComment(id, txt, userName)
                .done(function() {
                    self.commentText('');
                });
        }
    };
};

var commentVM = new commentViewModel('@ViewBag.Id', '@ViewBag.UserN');
$(function() { ko.applyBindings(commentVM); });

HTML:
<form class="add-comment" data-bind="submit: addComment">

        <input type="text" class="form-control" data-bind="textInput: commentText" />

        <button class="btn btn-default" type="submit">Answer</button>

</form>

Explaination:
The commentVM object contains a commentText member. This is a KO observable, so by exposing it by assigning it to this, you can bind to it. Then you can read the value of it by utilizing the KO binding mechanism instead of mixing jQuery and KO. Bindings exist to simplify your life not to be mixed with plain jQuery stuff, so you should use them wherever you can.
You should also expose an observable array to hold the actual comments, but since that wasn't part of your question I didn't want to introduce it to exclude any additional noise which is not related to what you asked.
In your HTML, you used the submit binding correctly. By binding the submit event to the addComment method, this method will get invoked correctly. But what's different compared to your code is that you read the comment text from the observable you've just defined, and avoid using jQuery. Since the VM itself is the context, you don't have to care about how to pass it -- that is, anything that you intend do use from within the submit method should generally be included in the viewmodel.
If, for whatever reason, you need to pass any extra parameter - such as dynamic content generated by Razor, for example, you can use the bind method. You can read more about it here, it is written just above Note 3. I'd like to note that even though it is documented in the click binding page, you can use it with submit as well (in fact, with any binding that binds to a method). Just for clarity, I'll include the relevant part here as well:
<button data-bind="click: myFunction.bind($data, 'param1', 'param2')">
  Click me
</button>

So all you have to do is to specify the function to which you want to bind, and append a .bind($data, parameter1, parameter2,....) expression to it. Note that here, $data is the context; you should always include it in the .bind call. However, this will not be passed to any method parameter, it is necessary for KO to do its magic, so if you had a function like this:
function a(x,y,z)

then x would be passed param1, y would be passed param2 and z wouldn't be passed anything. If you want to force passing $data, you should include it twice in the bind call as such: .bind($data, $data, ....more params).


text:
Q: How to print from excel to pdf without typing in a filename Is there a way to get around having to type in a filename when sending a document to Adobe PDF printers? My code is:
Application.ActivePrinter = "Adobe PDF on Ne01:"
MyWorkbook.PrintOut From:=1, To:=3, Copies:=2, Collate:=True

This works except that it prompts me for a filename. Would rather find a way to fix this without installing any extra libraries so it would be portable.
Thanks

A: Does this help at all?

"How To: Changing the Adobe PDF
  Printer/Distiller Printer Settings"
"Issue
You wish to automate printing from a
  third party application to either
  Adobe PDF or Distiller print drivers
  so that no UI elements are invoked for
  example 'Do not send fonts to
  Distiller', 'View results in Acrobat',
  'Prompt for PDF Filename', 'Delete log
  files for successful jobs', and the
  'Ask to Replace existing PDF file'
  preferences when you print.
Solution..."

A: I had to solve a similar problem where I had to create PDFs with automatically-generated file names.
In my solution, I installed PDF Creator, which acts like a printer on your computer, except that it saves PDF files when you print to it.  One of its settings allows you to automatically save a PDF to a directory when you print to PDF Creator.
I set up my Excel application to print repeatedly to PDF Creator.  I can't remember which it was (perhaps the name of the worksheet?), but one of the sheet's properties controlled the title of the document and thus the name of the saved file.
This isn't an ideal situation because it requires you to manually toggle a setting in PDF Creator, but it worked very well for a simple application I ran on my own machine.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can't include script angular2 index.html (not found) I have my index.html:
<!doctype html>

  <meta charset="utf-8">
  <title>Aerosmith Messenger</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <link href="https://fonts.googleapis.com/icon?family=Material+Icons"
rel="stylesheet" />
  <link rel="icon" type="image/x-icon" href="favicon.ico" />
  <link rel="stylesheet" href="assets/spinner.css" />

  <am-root>

  </am-root>

I'm trying to include jquery script. And it does not work when i include it like this (commented line). Help me resolve this issue because i need to include some other scripts.
By "does not work" i mean all the time that commented script is not found in console of a browser.

A: npm install --save jquery
npm install -D @types/jquery

In your app.module.ts file :
import $ from 'jquery';

// Works :
$('#foo').value();

A: There's nothing wrong with the way you call it. Maybe you are calling it from a worng path or the js file is not a good prebuilt. Go to the browser and inspect to see if it can find the js file.

A: Make sure your jQuery JavaScript file is located in your project at src/scripts/


text:
Q: Entity Framework One to Optional One relationship I've been trying to figure out how to create a one to optional one relationship in Entity Framework but everything I try seems to result in an exception or with the navigation properties not working correctly. Could anyone explain how to annotate the below so both objects can exist in the database and a link can optionally be made from one to the other?
Many thanks
public class ObjectA
{
    public int ID { get; set; }
    public virtual ObjectB ObjectB { get; set; }
}

public class ObjectB
{
    public int ID { get; set; }
    public virtual ObjectA ObjectA { get; set; }
    public int? ObjectAID { get; set; }

}

Edit:
With the code as it stands I get the following exception:
An exception of type 'System.InvalidOperationException' occurred in EntityFramework.dll but was not handled in user code

Additional information: Unable to determine the principal end of an association between the types 'Namespace.ObjectA' and 'Namespace.ObjectB'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.

A: You need to choose which entity will be a principal and which will be a dependent in this relationship. If it's true that ObjectB is dependent, then you could solve the problem with the following options:
1) Data Annotations. Mark ObjectB's ObjectAID property with RequiredAttribute:
public class ObjectB
{
    public int ID { get; set; }
    public virtual ObjectA ObjectA { get; set; }
    [Required]
    public int? ObjectAID { get; set; }
}

2) Fluent API. Configure Model Builder:
public class AppDbContext : DbContext
{
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<ObjectB>().HasRequired(b => b.ObjectA).WithOptional(a => a.ObjectB);
    }
}


text:
Q: Did the words "come" and "home" historically rhyme? The third stanza of the hymn Amazing Grace is

Thro' many dangers, toils, and snares,
    I have already come;
'Tis grace hath brought me safe thus far,
    And grace will lead me home.

In this hymn second and fourth lines always rhyme: like me/I see, relieved/believed, sun/begun. In the third stanza, the words come and home rhyme graphically, but are AFAIK phonologically quite different: /hoʊm/ and /kʌm/.
Therefore my question: did they rhyme in the past? And if so, was "come" pronounced like nowadays "home," or "home" pronounced like nowadays "come"? Or both in some third way?

A: It is not excluded, but also not very likely. Amazing Grace is

written in 1772 by English Anglican clergyman and poet John Newton (Wikipedia),

that is, quite close to the beginning of Late Modern English. By then, the pronunciation of home had already become /ho:m/ if not already /houm/ or as you put it /hoʊm/.
It is true that home comes from Old English ham (probably pronounced /hʌm/), but  at the end of the 18th century when the poem was written, this pronunciation was no longer in use.
Britannica records the changing of the pronunciation of home throughout different the periods of the English language:

If Chaucer said /hɔ:m/, Shakespeare said /ho:m/.
I do not have access to David Crystal's Oxford Dictionary of Original Shakespearean Pronunciation, but I suppose Shakespeare could have pronounced come as /co:m/. So it is not excluded that home might have rhymed with come in his time. As David Crystal explains in this video about Shakespeare, rhymes, and Original Pronunciation, what today does not rhyme, was a perfect rhyme in Shakespeare's time.
Did John Newton imitate Shakespearean pronunciation for the sake of rhyme? Hard to say, and to be honest I doubt it. Though looking at the other stanzas of the hymn, they ALL rhyme (2nd verse with 4th) so it is quite strange that only one stanza doesn't rhyme.

A: The first pronouncing dictionary in English was John Walker's A critical pronouncing dictionary and expositor of the English language, first published in 1791. In this first edition, home is glossed as having the vowel of no, and come as having the vowel of tub.
This was less than 20 years after Amazing Grace was written, in 1772. So it seems very unlikely that they rhymed at that time.
They do seem to have rhymed earlier. In 1614, John Donne wrote:

but more, now I am come
From having found their walkes, to find their home.
—  To the Countess of Salisbury

I can't tell for sure whether whether for Donne, this was a true rhyme or a near rhyme; Donne also rhymed come with dumb and room, so he certainly used some near rhymes.

A: Use of a short rounded or unrounded vowel (corresponding to that of come) in home was (is?) a feature of many English accents. Prestige English accents today do not have this characteristic, but recall that one and home had the same vowel in Old English but one usually has the same vowel as come today so there is a parallel for home having a shortened, unrounded vowel. Dobson (1968: 509) has an example of this correspondence from 1710 in William Turner's The Art of Reading and Spelling English. Dobson also (p 509 Note 1) cites Joseph Wright's 1905 dictionary as having this pronunciation even in the Home Counties.
Ellis 1869 shows the same vowel used in both home (his keyword 115) and come (keyword 603) not in the southeast of England but further west and north:

*

*Chippenham, Wiltshire (pp 1487-8)

*Vale of Gloucester and Forest of Dean, Gloucestershire (pp 1499-1500)

*Hanbury, Worcestershire (pp 1545-6)

*West Somerset (pp 1585, 1587)

*Mid Shropshire (pp 1617-8)

*Oakham, Rutland (pp 1689-90)

*Rochdale and Peak Forest, Derbyshire (p 1755)

*North Staffordshire (p 1854)

*Bradwell, Derbyshire (pp 1874-5)

*Holt, Denbighshire (pp 1890-1)

*Cannock, Staffordshire (p 1913)

*Shifnal, Shropshire (p 1915).

A: While it's possible that the words were meant to be pronounced with exactly the same vowel sound, it seems more probable to me that this is either an "eye rhyme" (where non-rhyming words are used as a rhyme because they are spelled the same way) or just a partial/near rhyme (where words ending in the same consonant but with different vowel sounds are used as rhymes).
Given the use of ABAB rhyme scheme in the majority of verses, I would also interpret snares and far as an intended partial or eye rhyme, which would show that this device was being used in the hymn.
Historical development of vowels in home and come
In Old English, home was pronounced [hɑːm] and spelled <ham>, and come was pronounced [kum] <cum>- + inflectional endings (e.g. the past participle was [(je)kumen] <(ge)cumen>; also [(je)kymen] <(ge)cymen>).
In Middle English, the vowel in home regularly became [ɔː], and the word accordingly developed spellings with o like <hom> and  <hoom>. Then in Early Modern English, [ɔː] became [oː] or [oʊ], giving us the modern pronunciation.
The Oxford English Dictionary mentions other spellings of home that seem to correspond to alternative pronunciations in different accents, such as hum and whum—see Kitschgardener's answer for more definite evidence about pronunciations of home with a short vowel. However, I think that these are probably not relevant to the use in Amazing Grace.
The vowel in come remained short [u] in Middle English, and may have continued to have this value up into Early Modern English. By the 17th century, a sound change caused [u] to develop into an unrounded vowel, modern [ʌ], in some words (including come) (the general sound change is mentioned in The Cambridge History of the English Language, Roger Lass, 2000, page 89). It is possible that a variant form of come with a lengthened vowel developed, but lengthening of [u] would be expected to result in Middle English [oː], Early Modern English [uː] (as in doom), which would be close but not identical to the vowel found in home in the accents that the Modern English forms are descended from.
Early Modern English poets do seem to have used near-rhymes
Rather than this pair of words having a completely identical vowel for John Newton when he was writing Amazing Grace, I think it's more likely that the identical spelling, and the historical similarity of the vowels (before the change of short /u/ to /ʌ/, both words had vowels sharing the phonetic features of "back" and "rounded"), meant that there was already a convention in poetry of treating pairs like these as possible rhymes regardless of whether they were or were not perfect ear rhymes for the author.
For comparison, there is evidence that the 18th-century poet Alexander Pope treated as rhymes some pairs of words spelled with o, ow or u that did not have exactly the same vowel sounds; I go over some examples in my answer to the previous question Pronunciation of "lost".

A: The lyrics were written by John Newton, c.1780, an educated man. At this time the pronunciation and spelling of home and come were fairly standard and in the form we would recognise: Home and come did not rhyme. They are what is known as a "half-rhyme" - combinations of consonants and vowel sounds that are not too dissimilar rather than rhyming.
As Meiklejohn wrote "The English language is very poor in rhymes, when compared with Italian or German. Accordingly, half-rhymes are admissible..: sun/gone, love/move, allow/bestow, etc."


text:
Q: Pythonic way of keeping track of a total changing based on an event result 0/1 I am building something which keeps track of bets.
I have a sequence of prices like this:
prices = [Decimal('4.42'), Decimal('2.93'), Decimal('7.47'), Decimal('6.80'), Decimal('23.00'), Decimal('6.47'), Decimal('12.50'), Decimal('4.95'), Decimal('16.19'), Decimal('17.00'), Decimal('12.32'), Decimal('7.15'), Decimal('9.93'), Decimal('6.60'), Decimal('6.68'), Decimal('12.38'), Decimal('18.68'), Decimal('19.00'), Decimal('6.79'), Decimal('4.50'), Decimal('6.90'), Decimal('30.00'), Decimal('140.00'), Decimal('4.80'), Decimal('2.37'), Decimal('199.72'), Decimal('3.08'), Decimal('11.00'), Decimal('9.31'), Decimal('17.50'), Decimal('5.50'), Decimal('19.00'), Decimal('23.00'), Decimal('3.45'), Decimal('38.00'), Decimal('38.00'), Decimal('6.52'), Decimal('15.23'), Decimal('8.67'), Decimal('3.85'), Decimal('6.24'), Decimal('15.68'), Decimal('34.99'), Decimal('5.50'), Decimal('10.74'), Decimal('8.60'), Decimal('7.80'), Decimal('19.69'), Decimal('9.96'), Decimal('6.71'), Decimal('15.48'), Decimal('5.70'), Decimal('11.38'), Decimal('47.36'), Decimal('9.91'), Decimal('11.50'), Decimal('15.26'), Decimal('5.10'), Decimal('17.50'), Decimal('5.40'), Decimal('8.92'), Decimal('16.41'), Decimal('5.64'), Decimal('56.11'), Decimal('8.21'), Decimal('14.57'), Decimal('8.60'), Decimal('4.50'), Decimal('23.00'), Decimal('4.10'), Decimal('2.52'), Decimal('5.68'), Decimal('10.98'), Decimal('11.16'), Decimal('22.00'), Decimal('7.50'), Decimal('4.90'), Decimal('5.70'), Decimal('12.50'), Decimal('5.42'), Decimal('20.17'), Decimal('10.92'), Decimal('8.60'), Decimal('27.00'), Decimal('44.00'), Decimal('10.95'), Decimal('12.39'), Decimal('6.04'), Decimal('3.70'), Decimal('84.93'), Decimal('10.55'), Decimal('12.50'), Decimal('14.92'), Decimal('7.86'), Decimal('7.40'), Decimal('4.56'), Decimal('33.59'), Decimal('3.75'), Decimal('2.71'), Decimal('8.02'), Decimal('5.77'), Decimal('7.39'), Decimal('1.94'), Decimal('8.03'), Decimal('3.90'), Decimal('14.00'), Decimal('16.00'), Decimal('2.54'), Decimal('8.86'), Decimal('5.46'), Decimal('16.64'), Decimal('5.90'), Decimal('144.19'), Decimal('26.00'), Decimal('60.00'), Decimal('1.95'), Decimal('4.10'), Decimal('22.40'), Decimal('7.18'), Decimal('4.80'), Decimal('9.20'), Decimal('5.43'), Decimal('9.00'), Decimal('15.00'), Decimal('198.20'), Decimal('8.00'), Decimal('37.43'), Decimal('4.60'), Decimal('10.50'), Decimal('50.46'), Decimal('18.50'), Decimal('425.39'), Decimal('9.04'), Decimal('2.52'), Decimal('6.00'), Decimal('110.00'), Decimal('8.60'), Decimal('6.00'), Decimal('2.88'), Decimal('8.54'), Decimal('26.00'), Decimal('10.00'), Decimal('7.21'), Decimal('48.00'), Decimal('10.51'), Decimal('6.40'), Decimal('12.96'), Decimal('150.35'), Decimal('29.26'), Decimal('14.57'), Decimal('25.00'), Decimal('3.73'), Decimal('10.50'), Decimal('14.32'), Decimal('8.42'), Decimal('16.58'), Decimal('12.00'), Decimal('17.21')]

I also have a sequence of bits representing a win/loss. The indices correspond left to right in date order:
results = '01011000010011110000000111100010010000011000010000010010000100000001011000000001000001010000000100010110101100010001100000100100000000100010010000100000001000'

initial_balance = 500

I am looking to go through the prices sequence like this:
if results[current_index_in_prices] == 1
 current_balance = 0.05*value*current balance

else:
  # ie 0= loss
   current_balance =- 0.05 *balance

keeping track of the balances as I go.
balance_list.append(current_balance)

I was wondering if there was a clever way of doing this in-memory as we go through the list rather than the method I have tried to sketch out.

A: for bit, value in zip(results, prices):
    diff = 0.05 * value * current_balance
    if bit == '1':
        current_balance += diff
    else:
        current_balance -= diff

or if you prefer:
signs = {'0': -1, '1': 1}
for bit, value in zip(results, prices):
    current_value += signs[bit] * 0.05 * value * current_balance

A: You should employ zip as follows
initial_balance = 500
current_balance = initial_balance
for flag, price in zip(results, prices):
    diff = Decimal(0.05)*price*current_balance*(1 if int(flag) else -1)
    current_balance += diff

But you can make it more functional and hence less ugly and less buggy as follows,
from functools import reduce
from operator import mul
g = (1 + Decimal(0.05)*price*(1 if int(flag) else -1)
        for flag, price in zip(results, prices))
current_balance = initial_balance*reduce(mul, g)

The above code is not giving the correct result. There is something wrong with the increment logic. But the idea is to implement
x_ = x*(1 + r)**n
# in this case, the following
x_ = x*(1+r0)*(1+r2)...*(1+r157)

where r or ris are rates for cumulative change.


text:
Q: get parent object filter by nested child fields Inside teacher, there is child subject, and subject has a child student. I want to get all teachers filter by student_name. Teacher object can be something like this:
{ "id": 5,
  "name": "teacher-one",
  "gender": "male",
  "subject": {
    "id": 10,
    "subject_name": "Maths",
    "student": {
      "id": 1,
      "student_name": "student-one",
       "grade" : "one",
    }
  }
}

I am looking to filter this out by using find method, something like
Teacher.find(:all, params: {gender: "male'}) which returns all the male teachers. But the following code does not work:
Teacher.find(:all, params: { subject: { student: grade == "one" }})

A: Try this:
Teacher.joins(subject: :student).where(student: {student_name: "Bala"})


text:
Q: Set-DnsClientGlobalSetting - throwing "Access to a CIM resource was not available" I am trying to add a Suffix to list of existing domains on my workstation but am getting the error below. It persist despite running PowerShell as an administrator. I have domains ABC and DEF in the list and want to add xyz.
Set-DnsClientGlobalSetting -SuffixSearchList @("abc.com", "def.com", "xyz.com")

Edit: This is the full error.
 Set-DnsClientGlobalSetting : Access to a CIM resource was not available to the client.
At line:1 char:1
+ Set-DnsClientGlobalSetting -SuffixSearchList @("abc.com", " ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : PermissionDenied: (MSFT_DNSClientG...nstanceID = ""):ROOT/StandardCi...ntGlobalSetting) [Set-DnsClientGlobalSetting], CimException
    + FullyQualifiedErrorId : MI RESULT 2,Set-DnsClientGlobalSetting

A: I believe this is because you have a GPO defining the DNS suffix search list.
I was able to validate this in my environment by having a computer in a test OU and test GPO assigned to it with the DNS suffix search list setting disabled. Make sure this test GPO takes precedence over other GPOs that may define the DNS suffix search list.
After ensuring a GPO wasn't defining the DNS suffix search list, this command should as expected.

A: I was just having a similar issue with a similar error message. Please, try to run PowerShell as an administrator. This may fix your permission issue.


text:
Q: Dependency org.apache.httpcomponents:httpclient:4.5 is ignored for debug as it may be conflicting with the internal version provid I was trying to upload a image to server. As im new for the android i was trying with the others code.
This is my error:Error file
This is my activity file:-
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {

    Button btpic, btnup;
    private Uri fileUri;
    String picturePath;
    Uri selectedImage;
    Bitmap photo;
    String ba1;
    public static String URL = "http://127.0.0.1/image.php";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btpic = (Button) findViewById(R.id.cpic);
        btpic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                clickpic();
            }
        });

        btnup = (Button) findViewById(R.id.up);
        btnup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                upload();
            }
        });
    }

    private void upload() {
        // Image location URL
        Log.e("path", "----------------" + picturePath);

        // Image
        Bitmap bm = BitmapFactory.decodeFile(picturePath);
        ByteArrayOutputStream bao = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.JPEG, 90, bao);
        byte[] ba = bao.toByteArray();
        ba1 = Base64.encodeToString(ba,Base64.DEFAULT);

        Log.e("base64", "-----" + ba1);

        // Upload image to server
        new uploadToServer().execute();

    }

    private void clickpic() {
        // Check Camera
        if (getApplicationContext().getPackageManager().hasSystemFeature(
                PackageManager.FEATURE_CAMERA)) {
            // Open default camera
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);

            // start the image capture Intent
            startActivityForResult(intent, 100);

        } else {
            Toast.makeText(getApplication(), "Camera not supported", Toast.LENGTH_LONG).show();
        }
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 100 && resultCode == RESULT_OK) {

            selectedImage = data.getData();
            photo = (Bitmap) data.getExtras().get("data");

            // Cursor to get image uri to display

            String[] filePathColumn = {MediaStore.Images.Media.DATA};
            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            picturePath = cursor.getString(columnIndex);
            cursor.close();

            Bitmap photo = (Bitmap) data.getExtras().get("data");
            ImageView imageView = (ImageView) findViewById(R.id.Imageprev);
            imageView.setImageBitmap(photo);
        }
    }

    public class uploadToServer extends AsyncTask<Void, Void, String> {

        private ProgressDialog pd = new ProgressDialog(MainActivity.this);
        protected void onPreExecute() {
            super.onPreExecute();
            pd.setMessage("Wait image uploading!");
            pd.show();
        }

        @Override
        protected String doInBackground(Void... params) {

            ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("base64", ba1));
            nameValuePairs.add(new BasicNameValuePair("ImageName", System.currentTimeMillis() + ".jpg"));
            try {
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(URL);
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse response = httpclient.execute(httppost);
                String st = EntityUtils.toString(response.getEntity());
                Log.v("log_tag", "In the try Loop" + st);

            } catch (Exception e) {
                Log.v("log_tag", "Error in http connection " + e.toString());
            }
            return "Success";

        }

        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            pd.hide();
            pd.dismiss();
        }
    }}

gradle page:
enter image description here

A: If you are using target sdk as 23
then inside the build.gradle add:
    android
    {
         useLibrary  'org.apache.http.legacy'
    }

as Apache Http is deprecated with the arrival of Marshmallow.
And according to this question, do not use any of these gradle files as it seems broken,
compile 'org.apache.httpcomponents:httpcore:4.4.1'
compile 'org.apache.httpcomponents:httpclient:4.5'
compile 'org.apache.httpcomponents:httpclient-android:4.3.5.1'

Hope it helps!

A: Way 1:
You need to use in build.gradle
android{
   useLibrary  'org.apache.http.legacy'
}

If you use latest version of android SDK.
Way 2:
Use HttpURLConnection class instead of HTTPClient. HttpURLConnection is more efficient than HTTPClient.


text:
Q: How to conditionally copy data from various places in overview using Google Apps Script based on a phrase? I am trying to figure out how to copy two sets of columns from one sheet to another in the same spreadsheet. This should only happen if it matches a certain phrase or word.
My source sheet contains a wide overview of people, who are divided into groups, such as swimming and football. Withing the groups, the people are further divided into projects, e.g. teens and under 10s.
The things I want to be copied are the names (preferably concatenated and separated by a space) which are in A4:B in the Overview sheet, the project they are working on (columns K and N), and their roles in the swimming group (columns L and O). Simplified overview sheet.
In my target sheet, I am looking for a table. Names of swimming volunteers in the first column, project (such as teens and under 10s) in the second column, and their role (treasurer, orange-slice provider) in the last column. Like so.
Below the script I have been working on. It doesn't work, I think because of the && in weird places.
function swimmingVolunteers() {
  var targetSheet = SpreadsheetApp.getSheetByName("Swimming");
  var targetLastRow = targetSheet.getLastRow();
  var targetSwimming = targetSheet.getRange(2, 4, targetLastRow - 3, 2).getValues();

  // source of data
  var sourceSheet = SpreadsheetApp.getSheetByName("Overview");
  var sourceLastRow = sourceSheet.getLastRow();
  // groups are in range equivalent to J4:J and M4:M
  var sourceGroupCheck = sourceSheet.getRange(4, 10, sourceLastRow - 1, 1 && 4, 13 sourceLastRow - 1, 1).getValues();
  // reference information range to be copied: A4:B (preferably concatenated and separated by a space), K4:L and N4:O
  var sourceRangeGroupInfo = sourceSheet.getRange(4, 1, sourceLastRow - 1, 2 && 4, 11, sourceLastRow - 1, 2 && 4, 14, sourceLastRow - 1, 2).getValues();

  var output = [];
  targetGroupCheck.forEach(function (targetGroup) {
    // search sourceGroupCheck for "swimming"
    var index = searchForArray(sourceGroupCheck, "swimming");
    // if "swimming" is in sourceRangeGroupInfo, save the data on that row for later
    if (index > -1)
      output.push(sourceRangeGroupInfo[index]);
  });
  // if it was found, copy data to target document in column
  if (output.length > 0) {
    targetSheet.getRange(2, 3, output.length, output[0].length).setValues(output);
    // with source A4:B in targetSheet column C (preferably concatenated and separated by a space),
    // source K and N in targetSheet column D, and
    // source L and O in targetSheet column E
  }
}

How would you go about this?


text:
Q: Creating a labeled build with Jenkins, Maven & SVN I created a parameterized job in Jenkins that:

*

*Gets sources based on label "V_x_y_z" (Jenkins-SVN integration)

*Executes Maven passing the label

*POM uses build-helper-maven-plugin to calculate version x.y.z

The resulting artifact is correct, BUT has the wrong version.
I see no way to change the resulting POM version except passing the version in the command line to versions-maven-plugin. But Jenkins has no way of parsing the label and transforming it into a version.
So it seems there are only "bad" options:

*

*Demand user enter both build and label - error prone

*Perform the checkout in Maven, not jenkins - this breaks separation of concerns, as POM itself is a versioned item.

*Wrap maven with a script (say python) - but then I lose the benefits of Jenkins-Maven integration
I would have thought this is a banal use case, and easily supported - am I missing some key ingredient?

A: I think that the best approach to achieve that would be to run 2 pre build steps:

*

*Invoke a shell script that creates a java property file with the manipulated version
echo "MYVERSION=$LABEL" | sed -e 's/_/./g' > new_property_file.properties

*Invoke EnvInject plugin step that reads that property file and inject the newly created env var
After that you could invoke maven plugin with the new env var as input to the maven command.


text:
Q: Blockchain Hyperledger Fabric dev env setup I am very close to set up dev environment for hyperledger fabric and following this link
https://github.com/IBM-Blockchain/learn-chaincode/blob/master/docs/setup.md
When I run this command git clone -b v0.6 http://gerrit.hyperledger.org/r/fabric
and run go build. I get following error:

can't load package: package github.com/hyperledger/fabric: no
  buildable Go source files in
  /Users/test/work/src/github.com/hyperledger/fabric

However when I run step 4 from the link, the build success.
cd $GOPATH/src/github.com//learn-chaincode/start
go build ./
Here build is not succeed only for http://gerrit.hyperledger.org/r/fabric.
Any thoughts?
Please suggest!

A: I think the manual is not precisely written here. You are not supposed to run go build . on the cloned fabric repository. The manual just states here, that if you are getting build errors later, the clone into your go sources did not work. I is not asking you to build the fabric repository. If your  build command is executed in step 4, everything should be set up correctly.

A: Assuming you are setting up the dev environment you want to build things for that after cloning the repo. This is done with make, thus e.g. make all to build and test all.
To build chaincode later on you use go build in the folder where you have the chaincode source file.


text:
Q: In python 3.6, a loose statement that looks like "key: value", but outside of a dictionary context, is valid syntax. What is this syntax used for? I'm guessing this is documented somewhere and has been discussed before, and I will close this question if someone finds a duplicate.
In python 3.6 I can enter the line
foo: "bar"

or
x: 1.2345

and this appears to be valid syntax. That is, any set of characters formatted like a variable name followed by a colon then some object does not raise an error. I've been using python for quite a while so this was really surprising to me. What is the interpreter seeing here? What is this for?
I came across this when reading about python3.7 and the new @dataclass decorator; I noticed the examples use the syntax
@dataclass
class Color:
    lightness: float = 0.5
    hue: float
    saturation: float

and assumed this loose key: value syntax was new. Evidently not.


text:
Q: Java decouple database manipulation code & make it testable I want to write a test for the following method:
public void addItem(Item item) {

    items.add(0, item);
    DatabaseHelper.getInstance().writeOneItem(item);
}

The class is called ItemManager and it's responsibility is to manage Items that the user can save to or remove from a list. It should be kept in sync with an Sqlite database that persists the items on the list.
When the DatabaseHelper (ormlite) is not inited with init(Context context) (which is usually sone when my Andoid app starts, but is not done in my test), it's getInstance() method will return null and the method execution from above will crash.
What should I do here? I could just call init(Context context) from my test or check if DatabaseManager.getInstance() is null before calling anything on it. But that seems more like a workaround. It seems to me like I shouldn't do any Database stuff in this method and try to seperate the ItemManager from the Database as much as possible.
Any ideas on how the ideal solution would look, not in form of a concrete implementation but from a gerneral design standpoint?
I'm new to unit testing and having a hard time decoupling stuff from each other.

A: In my opinion, your class ItemManager has to call the DatabaseHelper to write the item but your unit test just want to make sure that it does. You don't want to test that the DatabaseHelper actually writes the item in the database, that would be another test.
I would modify the design of your class: the DatabaseHelper.getInstance() should not be done directly in the method. Your ItemManager should have a private field with the instance of the DatabaseHelper. That way you can mock it and verify that it is called.
Using Mockito for example:
public void addItem(Item item) {
    items.add(0, item);
    this.databaseHelper.writeOneItem(item);
}

@Test
public void my_test() {
    // GIVEN
    DatabaseHelper databaseHelper = mock(DatbaseHelper.class);
    ItemManager manager = new ItemManager(databaseHelper);
    Item item = new Item()

    // WHEN
    manager.addItem(item);

    // THEN
    verify(databaseHelper).writeOneItem(item); // This verifies that the method writeOneItem of the "mock" is called with the "item" parameter
}

// Another test would check that the item is added to the "items" collection

Your unit test should be focused on testing ONE method and not the behaviour of the classes it uses.
In my example, I inject the DatabaseHelper in the ItemManager via constructor but you could use any method: constructor, setter, dependency injection framework, etc.

A: Break the static dependance and use a mock framework (like mockito)
class ItemManager {
 ...
 // decoupling
 private DatabaseHelper instance = DatabaseHelper.getInstance();

 public void addItem(Item item) {
    items.add(0, item);
    instance.writeOneItem(item);
 }
}

With mockito :
class ItemManagerTest{
 // declare mock service
 @Mock
 DatabaseHelper instance;

 // inject mock service into your about to be tested class
 @InjectMocks
 ItemManager manager;

 @Test
 public void test() {
  // Given
  Item item = new Item();
  ...

  // When
  manager.addItem(item);

  // Then
  // assert that the service has been called with the right parameters
  verify(instance).writeOneItem(item);
 }

A: You could create you own class that wrap the DatabaseHelper, let say you call it MyDBLayer
class abstract MyDBLayer {
    public void writeOneItem(Item item);
}

class OrmLiteDBLayer {
    public void writeOneItem(Item item) {
        DatabaseHelper.getInstance().writeOneItem(item);
    }
}

class FakeDBLayer {
    public void writeOneItem(Item item) {
        // do nothing
    }
}

Than you could inject FakeDBLayer in test and OrmLiteDBLayer in production.

A: I suppose you want to test the behaviour of the method i.e. if items actually contains the new item, not if the data is written to the database.
I'd use dependency injection and a mock object.
Using something like DatabseHelper.getInstance() is definitely convenient, but hard to test. I'd change the to test to
public class ClassToTest {

  private DatabaseHelper databaseHelper;

  public void setDatabaseHelper(DatabaseHelper databaseHelper) {
    this.databaseHelper = databaseHelper;
  }

  public void addItem(Item item) {
    items.add(0, item);
    databaseHelper.writeOneItem(item);
  }
}

Next, I'd introduce an interface IDatabaseHelper with the method void writeOneItem(Item item) and let DatabaseHelper implement this interface. Additionally, I'd create a MockDatabaseHelper that also implements the interface.
In your regular code you'd then use
ClassToTest myClass = new ClassToTest();
myClass.setDatabaseHelper(DatabaseHelper.getInstance());

and in your Test you'd use
ClassToTest myClass = new ClassToTest();
myClass.setDatabaseHelper(new MockDatabaseHelper());

The implementation in the MockDatabaseHelper could empty or be a simple log statement. If your class uses other methods from DatabaseHelper, you need to add these the interface as well and add an implementation to MockDatabaseHelper that mimicks the behaviour of the real DatabaseHelper.
As others already have mentioned, there are mock frameworks that save you some of the work with writing MockObjects.
Additionally, I'd recommend to check out Dependency Injection in general.


text:
Q: Cannot set property 'innerHTML' of null Why do I get an error or Uncaught TypeError: Cannot set property 'innerHTML' of null?
I thought I understood innerHTML and had it working before.
<!DOCTYPE HTML>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Untitled Document</title>

A: Let us first try to understand the root cause as to why it is happening in first place.

Why do I get an error or Uncaught TypeError: Cannot set property
'innerHTML' of null?

The browser always loads the entire HTML DOM from top to bottom. Any JavaScript code written inside the script tags (present in head section of your HTML file) gets executed by the browser rendering engine even before your whole DOM (various HTML element tags present within body tag) is loaded.  The scripts present in head tag are trying to access an element having id hello even before it has actually been rendered in the DOM. So obviously, JavaScript failed to see the element and hence you end up seeing the null reference error.

How can you make it work as before?

You want to show the hi message on the page as soon as the user lands on your page for the first time. So you need to hook up your code at a point when you are completely sure of the fact that DOM is fully loaded and the hello id element is accessible/available. It is achievable in two ways:

*

*Reorder your scripts: This way your scripts get fired only after the DOM containing your hello id element is already loaded. You can achieve it by simply moving the script tag after all the DOM elements i.e. at the bottom where body tag is ending. Since rendering happens from top to bottom so your scripts get executed in the end and you face no error.

<!DOCTYPE HTML>

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Untitled Document</title>

*Use event hooking: Browser's rendering engine provides an event based hook through window.onload event which gives you the hint that browser has finished loading the DOM. So by the time when this event gets fired, you can be rest assured that your element with id hello already loaded in the DOM and any JavaScript fired thereafter which tries to access this element will not fail. So you do something like below code snippet. Please note that in this case, your script works even though it is present at the top of your HTML document inside the head tag.

<!DOCTYPE HTML>

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Untitled Document</title>

A: Javascript looks good. Try to run it after the the div has loaded. Try to run only when the document is ready. $(document).ready in jquery.

A: Here Is my snippet try  it. I hope  it will helpfull for u.

<!DOCTYPE HTML>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Untitled Document</title>

A:

<!DOCTYPE HTML>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Example</title>

A: You could try using the setTimeout method to make sure your html loads first.

A: You could tell javascript to perform the action "onload"...  Try with this:

A: The root cause is: HTML on a page have to loaded before javascript code.
Resolving in 2 ways:
1) Allow HTML load before the js code.

//or set time out like this:

2) Move js code under HTML code

A: You have to place the hello div before the script, so that it exists when the script is loaded.

A: Just put your JS in window.onload
window.onload = function() {

        what();

        function what() {
            document.getElementById('hello').innerHTML = 'hi';
        };

    }

A: The JavaScript part needs to run once the page is loaded, therefore it is advised to place JavaScript script at the end of the body tag.

<!DOCTYPE HTML>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Example</title>

A:

<!DOCTYPE HTML>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Untitled Document</title>

A: I have had the same problem and it turns out that the null error was because I had not saved the html I was working with.
If the element referred to has not been saved once the page is loaded is 'null', because the document does not contain it at the time of load. Using window.onload also helps debugging.
I hope this was useful to you.

A: This error can appear even if you load your script after the html render is finished. In this given example your code

has no value inside the div. So the error is raised, because there is no value to change inside. It should have been

Some random text to change

then.

A: You need to change div into p. Technically innerHTML means it is inside the <??? id=""></???> part.
Change:

into

Doing:
document.getElementById('hello').innerHTML = 'hi';

will turn

 into this
hi

which actually does not make sense.
You can  also try to change:
document.getElementById('hello').innerHTML = 'hi';

into this
document.getElementById('hello').innerHTML='
 hi
 ';

to make it work.

A: Add jquery into

Use $document.ready() : the code can be in  or in a separate file like main.js
1) using js in same file (add this in the ):

2) using some other file like main.js (add this in the ):

and add the code in main.js file :)

A: The error is self-explaining it is not getting the HTML tag in which You want to set the Data So make tag available to JS then only You can set Data to that.

A: No doubt, most of the answers here are correct, but you can also do this:
document.addEventListener('DOMContentLoaded', function what() {
   document.getElementById('hello').innerHTML = 'hi';
});

A: There are different possible cause as discussed would just like to add this for someone who might have the same issue as mine.
In my case I had a missing close div as shown below
   <!DOCTYPE HTML>

   <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
   <title>Untitled Document</title>

 //I am an open div

Missing a close div can result in disorganization of the transversal from child to parent or parent to child hence resulting in an error when you try to access an element in the DOM

A: Let the DOM load. To do something in the DOM you have to Load it first. In your case You have to load the
 tag first. then you have something to modify. if you load the js first then that function is looking your HTML to do what you asked to do, but when that time your HTML is loading and your function cant find the HTML. So you can put the script in the bottom of the page. inside  tag then the function can access the
 Because DOM is already loaded the time you hit the script.

A:
I have moved my

A: This happened to me when using Django template tags on an if-check to see if there was a value available for a field - if no value I removed everything associated with the value from the page to keep things neat The only problem was the content I removed included the div and id I was trying to work with! If there was a value present there was no issue as the div that contained the id I was working with was present. If there was no value I received the error. Once it hit me that's what was going on then easy fix to just add the div in there if the if-check is false.
Before
{% if model.value %}

{{model.value}}

{% endif %}

After
{% if model.value %}

{{model.value}}

{% else %}

{% endif %}


text:
Q: When initializing variables in C does the compiler store the intial value in the executable When Initializing variables in C I was wondering does the compiler make it so that when the code is loaded at run time the value is already set OR does it have to make an explicit assembly call to set it to an initial value?
The first one would be slightly more efficient because you're not making a second CPU call just to set the value.
e.g.
void foo() {
  int c = 1234;
}

A: A compiler is not required to do either of them. As long as the behavior of the program stays the same it can pretty much do whatever it wants.
Especially when using optimization, crazy stuff can happen. Looking at the assembly code after heavy optimization can be confusing to say the least.
In your example, both the constant 1234 and the variable c would be optimized away since they are not used.

A: If it's a variable with static lifetime, it'll typically become part of the executable's static image, which'll get memcpy'ed, along with other statically known data, into the process's allocated memory when the process is started/loaded.
void take_ptr(int*);

void static_lifetime_var(void)
{
    static int c = 1234;
    take_ptr(&c);
}

x86-64 assembly from gcc -Os:
static_lifetime_var:
        mov     edi, OFFSET FLAT:c.1910
        jmp     take_ptr
c.1910:
        .long   1234

If it's unused, it'll typically vanish:
void unused(void)
{
    int c = 1234;
}

x86-64 assembly from gcc -Os:
unused:
        ret

If it is used, it may not be necessary to put it into the function's frame (its local variables on the stack)—it might be possible to directly embed it into an assembly instruction, or "use it as an immediate":
void take_int(int);

void used_as_an_immediate(int d)
{
  int c = 1234;
  take_int(c*d);
}

x86-64 assembly from gcc -Os:
used_as_an_immediate:
        imul    edi, edi, 1234
        jmp     take_int

If it is used as a true local, it'll need to be loaded into stack-allocated space:
void take_ptr(int*);

void used(int d)
{
  int  c = 1234;
  take_ptr(&c);
}

x86-64 assembly from gcc -Os:
used:
        sub     rsp, 24
        lea     rdi, [rsp+12]
        mov     DWORD PTR [rsp+12], 1234
        call    take_ptr
        add     rsp, 24
        ret

When pondering these things Compiler Explorer along with some basic knowledge of assembly are your friends.

A: TL;DR: Your examples declares and initializes an automatic variable. It has to be initialized each time the function is called. So there will be some instruction to do this.

As an adjusted duplicate of my answer to How compile time initialization of variables works internally in c?:
The standard defines no exact way of initialization. It depends on the environment your code is developed and run on.
How variables are initialized depends also on their storage duration. You didn't mention it in the text, your example is an automatic variable. (Which is most probably optimized away, as commenters point out.)
Initialized automatic variables will be written each time their declaration is reached. The compiled program executes some machine code for this to happen.
Static variables are always intialized and only once before the program startup.
Examples from the real world:
Most (if not all) PC systems store the initial values of explicitly (and not zero-) initialized static variables in a special section called data that is loaded by the system's loader to RAM. That way those variables get their values before the program startup. Static variables not explicitly initialized or with zero-like values are placed in a section bss and are filled with zeroes by the startup code before program startup.
Many embedded systems have their program in non-volatile memory that can't be changed. On such systems the startup code copies the initial values of the section data into its allocated space in RAM, producing a similar result. The same startup code zeroes also the section bss.
Note 1: The sections don't have to be named liked this. But it is common.
This startup code might be part of the compiled program, or might not. It depends, see above. But speaking of efficience it doesn't matter which program initializes variables. It just has to be done.
Note 2: There are more kinds of storage duration, please see chapter 6.2.4 of the standard.
As long as the standard is met, a system is free to implement any other kind of initialization, including writing the initial values into their variables step by step.

A: Firstly, its important to have a common understanding of the word 'compiler', else we can end-up arguing endlessly.
In simple words,

a compiler is a computer program that translates computer code written
in one programming language (the source language) into another
programming language (the target language). The name compiler is
primarily used for programs that translate source code from a
high-level programming language to a lower level language (e.g.,
assembly language, object code, or machine code) to create an
executable program.

(Ref: Wikipedia)
With this common understanding, let's now find answer you question: The answer is  'yes, the final code contains explicit assembly call to set it to an initial value' for any kind of variables. It is so because finally the variables are either stored in some memory location, or they live in some CPU register in case the number of variables are so less that the variable can be accommodated into some CPU registers such as your code snippet running on lets say most modern servers (Side note: different systems have different number of registers).
For the variables that are stored in registers, there has to be a mov (or equivalent) kind of instruction to load that initial value into the register. Without such an instruction the assigned register cannot be assigned with the intended value.
For the variables that are stored in memory, depending on the architecture and the compiler efficiency, the init value has to be somehow pushed to the given/assigned address, which takes at least a couple of asm instructions.
Does this answer your question?


text:
Q: Create my own loss without interrupting the gradient chain registered by the gradient tape I'm learning Tensorflow 2.10, with Python 3.7.7.
I'm trying to use the tutorial "Tensorflow - Custom training: walkthrough" to use my own loss function.
This is my first version of loss function, and it works:
    def loss(model, x, y):
      output = model(x)
      return tf.norm(y - output)

I have changed to try another one, and it doesn't work:
def my_loss(model, x, y):
  output = model(x)

  # Only valid values for output var are 0.0 and 1.0.
  output_np = np.array(output)
  output_np[output_np >= 0.5] = 1.0
  output_np[output_np < 0.5] = 0.0

  # Counts how many 1.0 are on y var.
  unique, counts = np.unique(y, return_counts=True)
  dict_wmh = dict(zip(unique, counts))
  wmh_count = 0
  if 1.0 in dict_wmh:
    wmh_count = dict_wmh[1.0]

  # Add y and output to get another array.
  c = y + output_np
  unique, counts = np.unique(c, return_counts=True)
  dict_net = dict(zip(unique, counts))

  # Counts how many 2.0 are on this new array.
  net_count = 0
  if 2.0 in dict_net:
    net_count = dict_net[2.0]

  # Return the different between the number of ones in the label and the network output.
  return wmh_count - net_count
  #return tf.convert_to_tensor(wmh_count - net_count, dtype=tf.float32)

I get the error:

Cannot convert value 0 to a TensorFlow DType.

If I change the return with this one:
return tf.convert_to_tensor(wmh_count - net_count, dtype=tf.float32)

I get the error:

No gradients provided for any variable: ['conv1_1/kernel:0',
  'conv1_1/bias:0', ...

On this function:
def grad(model, inputs, targets):
    with tf.GradientTape() as tape:
        tape.watch(model.trainable_variables)
        #loss_value = loss(model, inputs, targets)
        loss_value = my_loss(model, inputs, targets)

    return loss_value, tape.gradient(loss_value, model.trainable_variables)

Because I have asked this SO question, now I know that my new loss function "interrupts the gradient chain registered by the gradient tape".
This new loss function (my_loss) does the following:

*

*Converts the output of the model into an array which values are 0.0 or 1.0.

*Create a new array adding this output to the y (which values are also 0.0 or 1.0).

*Counts how many 2.0 are this new array.

*Counts how many 1.0 are in the y array.

*Returns the different between point 3 and 4.

How can I convert this into Tensors to not "interrupts the gradient chain registered by the gradient tape"?
Maybe there is a native function to do what I am trying to do.
By the way, I have convert it to numpy arrays because I can't do this, output_np[output_np >= 0.5] = 1.0, with Tensors.


text:
Q: Storing images on server I am new to backend programming. I am working on a personal Full stack project where I display all my art works. These art works are lot of images. I read up in some articles that it is better to save files on server than on database. I am using MEAN stack for my application. Can anyone refer me to some links or help me understand how can I achieve storing images on server?

A: If you are using node.js I recommend using multer for uploading your files through it to server and then make a public link to your file and store that link in your database.


text:
Q: Is there any way of extracting the xpath of an HTML element using a javascript code or any other tool?
I am trying to extract and store xpath of some components of an web application for example a comment component of an instagram post. Is there any way either by executing javascript at frontend or by automation through selenium python through which I can get the xpath of such elements?

I tried researching a way through which I can automate the method we use to get the xpath using copy full xpath using chrome developer tool


text:
Q: How to limit the character in textarea if we using 'jQuery InlineEdit' I am using jquery.inlineedit.js for inline edit and i need to control the maximum length of texts inside the textarea. I tried with someother common jquery script to limit, but i can't make it.
Below is the link what i tried so far.
http://jsfiddle.net/LNBRU/4

A: Simply use max-length property for that
<textarea maxlength="20"></textarea>

Fiddle

A: *

*add an event handler for the changing of the input's content

*if it exceeds the character limit, truncate the string


text:
Q: How do I increment a number using 0:00:00 format? I am trying to create a time tracker in the following format; 0:00:00. The first zero represents the hour, then minutes, then seconds. Currently, I have a working function that increments the number every second. I know there is a proper way to do this with getDate() and then modifying the hours, minutes and seconds using getHours(), getMinutes() and so on. I just can't seem to get it all to work together. I've attached a working jsFiddle to show how far I've gotten.
The goal is to have it look something like ... 0:00:59 then turn into 0:01:00 and so on. Thank you.
Full example @ http://jsfiddle.net/London804/628xz9x7/2/
$('#submit').click(function(){
var start = setInterval(updateDisplay, 1000), // every millisecond call updateDisplay
   timer = $('#timer'),
   value = parseInt($(timer).find('.value').text(), 10);

function updateDisplay(){

    value++;
    $(timer).find('.value').text(value);
    if (value >= 60) {
        $('#sec').replaceWith("min");
    }
    if (value >= 3600) {
        $('#sec').replaceWith("hrs");
    }
    if (value >= 86400) {
        value = 0;
        console.log('stop and take a break, you have been working over 24hrs!');

    }
}

$('#stop').click(function(){
    clearInterval(start);
});
$('#reset').click(function(){
    clearInterval(start);
    value = parseInt($(timer).find('.value').text('0'));
});

});

A: When you start the timer, save the current date-time.
var start_dt = Date.now();

When you want to update the display, start by using the following:
var current_dt = Date.now();
var elapsed_ms = current_dt - start_dt;

That gives an accurate count of the elapsed time. Repeatedly incrementing a variable as you are doing will drift.
Now, it's time to format as H:MM:SS
function format_timer(ms) {
   var s = ("0" + Math.floor((ms / (      1000)) % 60)).substr(-2);
   var m = ("0" + Math.floor((ms / (   60*1000)) % 60)).substr(-2);
   var h =        Math.floor((ms / (60*60*1000))     );
   return h + ":" + m + ":" + s;
}

A: Here is a solution that doesn't involve all the slicing and dicing of html elements.  I'm using Date objects to track elapsed time in milliseconds and updating the display by extracting a substring of a standard format string provided by the Date object.
The end result will be more accurate as you are not relying on the timer to tick off seconds but are using an actual elapsed time between calls.
You still have to mess with the final output formatting but the Date object has nice functions that allow you to pull all the components you many need in terms our hours, minutes, seconds etc...

var starting_ms ;
var elapsed ;
var $timer = $('#timer .value');
var $hrs = $('#elapsedtime #hrs');
var $min = $('#elapsedtime #min');
var $sec = $('#elapsedtime #sec');
var start;

function updateDisplay() {
  elapsed.setTime(Date.now() - starting_ms);
  $timer.text(elapsed.toUTCString().substr(20, 5));

  $hrs.text(elapsed.getUTCHours() );
  $min.text(elapsed.getUTCMinutes() );
  $sec.text(elapsed.getUTCSeconds() );
}

$('#submit').click(function() {
  if( start )
    clearInterval(start);
  starting_ms = Date.now();
  elapsed     = new Date(0);

  start = setInterval(updateDisplay, 1000); // every millisecond call updateDisplay
});

$('#stop').click(function() {
  clearInterval(start);
});

$('#reset').click(function() {
  clearInterval(start);
  starting_ms = Date.now();
  updateDisplay();

});
* {
  -webkit-tap-highlight-color: transparent
}
body {
  -webkit-touch-callout: none;
  -webkit-text-size-adjust: none;
  -webkit-user-select: none;
  background-color: #E4E4E4;
  background-image: linear-gradient(top, #A7A7A7 0%, #E4E4E4 51%);
  background-image: -webkit-linear-gradient(top, #A7A7A7 0%, #E4E4E4 51%);
  background-image: -ms-linear-gradient(top, #A7A7A7 0%, #E4E4E4 51%);
  background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0, #A7A7A7), color-stop(0.51, #E4E4E4));
  background-attachment: fixed;
  font-family: 'HelveticaNeue-Light', 'HelveticaNeue', Helvetica, Arial, sans-serif;
  font-size: 12px;
  height: 100%;
  margin: 0px;
  padding: 0px;
  text-transform: uppercase;
  width: 100%
}
.app {
  background: transparent url(../../img/logo.png) no-repeat center top;
  position: absolute;
  left: 50%;
  top: 50%;
  height: 50px;
  width: 225px;
  text-align: center;
  padding: 180px 0px 0px 0px;
  margin: -115px 0px 0px -112px
}
.app #login {
  margin-top: 20px;
  position: relative;
  font-size: 18px;
  text-transform: uppercase
}
.app #login:active {
  color: #cbcbcb
}
#welcome {
  width: 90%;
  margin: 20px auto
}
@media screen and (min-aspect-ratio: 1 / 1) and (min-width: 400px) {
  .app {
    background-position: left center;
    padding: 75px 0px 75px 170px;
    margin: -90px 0px 0px -198px
  }
}
h1 {
  font-size: 24px;
  font-weight: normal;
  margin: 0px;
  overflow: visible;
  padding: 0px;
  text-align: center
}
.event {
  border-radius: 4px;
  -webkit-border-radius: 4px;
  color: #FFFFFF;
  font-size: 12px;
  margin: 0px 30px;
  padding: 2px 0px
}
.event.listening {
  background-color: #333333;
  display: block
}
.event.received {
  background-color: #4B946A;
  display: none
}
@keyframes fade {
  from {
    opacity: 1.0
  }
  50% {
    opacity: 0.4
  }
  to {
    opacity: 1.0
  }
}
@-webkit-keyframes fade {
  from {
    opacity: 1.0
  }
  50% {
    opacity: 0.4
  }
  to {
    opacity: 1.0
  }
}
.blink {
  animation: fade 3000ms infinite;
  -webkit-animation: fade 3000ms infinite
}
#timer-container {
  min-width: 300px;
  max-width: 50%;
  margin: 0 auto
}
#timer-container #timer {
  text-align: center;
  font-size: 20px;
  color: #4887da;
  font-weight: bold
}
#timer-container label {
  display: block
}
#timer-container label input {
  width: 98%
}
#timer-container #button-container {
  text-align: center
}
#timer-container #button-container button {
  -webkit-box-shadow: 0px 1px 5px 3px #9c899c;
  -moz-box-shadow: 0px 1px 5px 3px #9c899c;
  box-shadow: 0px 1px 5px 3px #9c899c;
  width: 35%;
  margin: 10px auto;
  position: relative
}
#timer-container #button-container button:nth-child(2) {
  width: 20%
}
/*# sourceMappingURL=styles.css.map */

Welcome please log in

Stuff ...

  <fieldset id="timer-container">

0:00  sec

      <button id="submit" type="submit">Start</button>
      <button id='reset' type="reset">Reset</button>
      <button id="stop" type="stop">Stop</button>

  </fieldset>

Just for fun

      Hrs	Min	Sec

A: You can accomplish it with converting your seconds to dateTime format and then with simple regex:
var myDate = new Date(null, null, null, null, null, value).toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/, "$1");

Here is working fiddle: http://jsfiddle.net/628xz9x7/6/

A: if you are certain on implementing this logic by yourself, you can make some use of some basic mathematics.
function updateDisplay(){

    value++;

    // Example for minutes
    if (value >= 60) {
        secs = value % 60;
        mins = (value - secs) / 60;
        $(timer).find('.value').text("00:"+min+":"+secs);
        //$('#sec').replaceWith("hrs");
    }
}

You can add the implementation for the other fields, but what we simply do here is find how many seconds are over the minute, by using modulus and then subtract the seconds from the minutes and divide by 60 to get the amount of minutes elapsed, we can then set the labels with these new values.
One thing you may want to do is provide a formatNumber method:
function formatNumber(number) {
   if (number < 10) {
      return "0" + number;
   }
   return number;
}

What this will do is provide the formatted string for the number to update label for values under 10, a test fiddle is here, I have not implemented all functionality but its a start for you : https://jsfiddle.net/628xz9x7/14/

A: JS Fiddle Demo
Note that I do an iteration every millisecond instead of a second, for faster testing.
var start, value, timer = $('#timer');

$('#submit').click(function(){
   value = readTime(timer.text());
   start = setInterval(updateDisplay, 1); // replace 1 with 1000
});

$('#stop').click(function(){ clearInterval(start); });

$('#reset').click(function(){
    clearInterval(start);
    value = parseInt(timer.text(formatTime(0)));
});

function updateDisplay(){
    value++;
    timer.text(formatTime(value));
    if (value >= 86400) {
        value = 0;
        console.log('stop and take a break, you have been working over 24hrs!');
    }
}

function formatTime(t){
    var h = ('0' + parseInt( t / 3600 ) % 24).slice(-2),
        m = ('0' + parseInt( t / 60 ) % 60).slice(-2),
        s = ('0' + t % 60).slice(-2);
    return h+':'+m+':'+s;
}

function readTime(s){
    var r = s.split(':');
    return parseInt(r[0])*3600 + parseInt(r[1])*60 + parseInt(r[2]);
}


text:
Q: Access Json object name I want to get data with request.data.columns in frontend.I can do it with ViewSet with list method but how to do it with generics.APIView.
Below is my viewsets and generics code:
class TestList(viewsets.ViewSet):
     queryset = Test.objects.all()
     def list(self,request):
         serializer = TestSerializer(self.queryset, many = True)
         return Response({'columns': serializer.data})

class TestList(generics.RetriveAPIView):
    queryset = Test.objects.all()
    serializer_class = TestSerializer

A: class TestList(APIView):
     queryset = Test.objects.all()
     def list(self,request):
         serializer = TestSerializer(self.queryset, many = True)
         return Response({'columns': serializer.data})

change your urls.py like this.
path(r"url", TestList.as_view({"get": "list"}))

A: Correct code:
class TestList(APIView):
     queryset = Test.objects.all()
     def list(self,request):
         queryset = self.get_queryset()
         serializer = TestSerializer(queryset, many = True)
         return Response({'columns': serializer.data})

Details about why i had to add queryset = self.get_queryset() instead of directly access self.queryset.From official drf documentation:
queryset - The queryset that should be used for returning objects from this view. Typically, you must either set this attribute, or override the get_queryset() method. If you are overriding a view method, it is important that you call get_queryset() instead of accessing this property directly, as queryset will get evaluated once, and those results will be cached for all subsequent requests.


text:
Q: Getting 64-bit background geoprocessing running in ArcGIS 10.5? I've got fresh installation of ArcGIS 10.5 on my machine and was wondering from where and how can I get 64-bit background geoprocessing.
Help pages are not explaining anything regarding installation.
In previous versions it was (I think) located on the installation media (similarly as pointed to in this or this questions for 10.2):

My IT department informed me that this is not the case any longer and in some newer thread on geonet forum I found information that for version 10.3 this is downloadable from my.esri.com

(most likely with an institutional account..) but I cannot find any details regarding 10.5 version.
Has anyone managed to get and install it?

A: It's downloadable for 10.5 as well, but you need to have access to the Downloads page for your organization on my.esri.com. Most likely, someone in your organization can either download it for you or they can grant you the ability to download it for yourself. I'm pretty sure I remember this download, and most other addons/patches for ArcGIS Desktop being freely accessible in the past (without signing in to an Esri account).
Here it is on my downloads page. The filename is ArcGIS_Desktop_BackgroundGP_105_154031.exe.


text:
Q: HTML Image won't fit in blank space I am having issues with an image not fitting in my container. Btw the th:each will just do another div class = "profile-picture". Also I noticed that uncommenting float:left will make the image fit and less spaces between the images, but I would like not to use it unless it is the only way.I am not an expert at web designing, but I though this would work as the container width is 1200px, profile picture div is 390px and margin is 5px, so 400px in total. 400px x 3 = 1200px, so it should the 1st of the 2nd row should be in the 1st row, right?
HTML

CSS
/*profile*/

* {
    margin: 0;
    padding: 0;
    font-family: 'Poppins', sans-serif;
}

.container {
    max-width: 1200px;
    margin: auto;
    background: #f2f2f2;
    overflow: auto;
}

.profile-picture {
    margin: 5px;
    /*border: 1px solid #ccc;*/
    /*float: left;*/
    width: 390px;
    display: inline-block;
}

.profile-picture img {
    width: 100%;
    height: 267px;
}

A: When you place inline-block elements next to each other the browser will assume you will want a little blank space between the elements. This is the normal behaviour of inline elements. If you float them the elements will not follow this normal behaviour since you get them out of the normal flow.


text:
Q: Кнопка возврата назад Итак. Есть у меня некая кнопка, которая используется для возврата назад. На случай, если человек зашел из поиска, другого сайта или новой вкладки, есть условие, отправляющее человека на главную страницу.
Назад

Однако, если страница была открыта в новом окне, ссылка перестает работать. Причины данной проблемы мне понятны, а вот можно ли это дело исправить/записать иначе? Чтоб при открытии ссылки в новом окне, при нажатии на эту кнопку так же отправляло на главную страницу?


text:
Q: Second highest value among column values of same row in SQL Sample data:
id score1 score2 score3 score4
1  10     05      30    50
2  05     15      10    00
3  25     10      05    15

Expected result set:
id col_value
1    30
2    10
3    15

A: Use a CASE expression to tell which score to omit in your GREATEST() call.
SELECT id,
    CASE GREATEST(score1, score2, score3, score4)
        WHEN score1 THEN GREATEST(score2, score3, score4)
        WHEN score2 THEN GREATEST(score1, score3, score4)
        WHEN score3 THEN GREATEST(score1, score2, score4)
        ELSE GREATEST(score1, score2, score3)
    END AS col_value
FROM your_table ;

This solution generalizes easily to any number of columns.

and a variation without CASE, using both GREATEST() and LEAST():
SELECT id,
    LEAST(
        GREATEST(score1, score2, score3),
        GREATEST(score2, score3, score4),
        GREATEST(score3, score4, score1),
        GREATEST(score4, score1, score2)
    ) AS col_value
FROM your_table ;

A: Consider the following, which generalizes yet more easily still:
DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table
(id INT NOT NULL
,score_no INT NOT NULL
,score INT NOT NULL
,PRIMARY KEY(id,score_no)
);

INSERT INTO my_table VALUES
(1, 1 ,10),
(1 ,2 ,05),
(1 ,3 ,30),
(1 ,4 ,50),
(2 ,1 ,05),
(2 ,2 ,15),
(2 ,3 ,10),
(2 ,4 ,00),
(3 ,1 ,25),
(3 ,2 ,10),
(3 ,3 ,05),
(3 ,4 ,15);

SELECT id
     , score_no
     , score
  FROM
     ( SELECT x.*
            , CASE WHEN @prev=id THEN @i:=@i+1 ELSE @i:=1 END rank
            , @prev:=id
         FROM my_table x
            , (SELECT @prev:=null,@i:=0) vars
        ORDER
           BY id
            , score DESC
            , score_no
     ) a
 WHERE rank = 2;
 +----+----------+-------+
 | id | score_no | score |
 +----+----------+-------+
 |  1 |        3 |    30 |
 |  2 |        3 |    10 |
 |  3 |        4 |    15 |
 +----+----------+-------+

In the event of tied scores, this solution picks the one with the lower 'score_no'.

A: Assuming no ties, you can use a big case expression:
select t.*,
       (case when score1 > score2 and score1 > score3 and score1 < score 4 then score1
             when score1 > score2 and score1 < score3 and score1 > score 4 then score1
             when score1 < score2 and score1 > score3 and score1 > score 4 then score1
             when score2 > score1 and score2 > score3 and score2 < score 4 then score2
             when score2 > score1 and score2 < score3 and score2 > score 4 then score2
             when score2 < score1 and score2 > score3 and score2 > score 4 then score2
             . . .
        end) as second_score
from t;

In general, though, this type of question suggests a problem with the data structure.  I suspect that you should really have a table with one row per id and score (and perhaps a score number).  This is usually easier to manipulate in SQL.

A: Using UNPIVOT try this query
    CREATE TABLE #my_table
(id INT NOT NULL, score1 INT NOT NULL, score2 INT NOT NULL, score3 INT NOT NULL, score4 INT NOT NULL)

INSERT INTO #my_table VALUES(1,  10,     05,      30,    50)
INSERT INTO #my_table VALUES(2,  05,     15,      10,    00)
INSERT INTO #my_table VALUES(3,  25,     10,      05,    15)

;WITH getHighestValue as (
SELECT id, Scores, ScoreText, ROW_NUMBER() OVER(PARTITION BY id ORDER BY Scores DESC) AS Ranks
FROM #my_table
UNPIVOT(
Scores for ScoreText in (score1,score2,score3,score4)
) unpiv
)
SELECT id, Scores as col_value
FROM getHighestValue
WHERE Ranks = 2

Result:


text:
Q: How to abstract away JDBC code when I need to populate from ResultSet before closing ResultSet? I'm working on a Java application that conducts numerous JDBC queries to a database, each specified in a separate method with roughly the following format.
public static void sampleJDBCQuery(String query, DBUtil dbUtil, DataStructure dataStructure) {
    ResultSet rs = null;
    Handle handle = null;
    Connection conn = null;
    Statement stmt = null;
    LOGGER.debug("Executing query = {}", query);
    try {
        handle = dbUtil.getConnectionHandle();
        conn = handle.getConnection();
        if (conn != null) {
            stmt = conn.createStatement();
            if (stmt != null) {
                rs = stmt.executeQuery(query);
                if (rs != null) {
                    while (rs.next()) {
                        // populate dataStructure using rs
                    }
                }
            }
        }
    } catch (Exception e) {
        Metrics.markMeter("vertica.read.error");
        LOGGER.error(e.getMessage(), e);
    } finally {
        DBUtil.closeResultSet(rs);
        DBUtil.closeStatement(stmt);
        DBUtil.close(handle);
        LOGGER.debug("Finished query = {}", query);
    }
}

With many different sample queries (and data structure classes) of the format above, my code base has been growing substantially. My aim is to have a helper method that abstracts away most of this JDBC logic for me. My first thought was to have a method with the following signature.
public static ResultSet executeJDBCQuery(String query, DBUtil dbUtil)

And then I could loop over the rows of the ResultSet and populate the relevant DataStructure for each row. The problem is that I would still have to close the returned ResultSet and closing ResultSet in a different method seems like bad design.
I guess what I'm looking for is maybe something similar to Python's concept of function decorators so that I could "decorate" a JDBC query to take care of most of the boilerplate present in sampleJDBCQuery above. How could I achieve this?

A: You can pass in a strategy to tell the method how to map the row to fields on an object.
This is what spring-jdbc does, it defines a RowMapper as:
public interface RowMapper<T> {
    T mapRow(ResultSet resultSet, int rowNum) throws SQLException;
}

This is how you could change your method, including incorporating the rowMapper:
public static <T> List<T> queryList(String query, Connection conn, RowMapper<T> rowMapper) throws SQLException {
    LOGGER.debug("Executing query = {}", query);
    try {
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery(query);
        List<> list = new ArrayList<>();
        while (rs.next()) {
            list.add(rowMapper.mapRow(rs, list.size() + 1));
        }
        return list;
    } finally {
        DBUtil.closeResultSet(rs);
        DBUtil.closeStatement(stmt);
        LOGGER.debug("Finished query = {}", query);
    }
}

Catching all exceptions here isn't good because you want to be able to use the exception to bail out of the current operation if something is going wrong. Otherwise you will have multiple error stacktraces in the log, one here where the error happens, then another downstream where your code fails when it expects a result to be present that isn't due to the previous error. Just fail fast when the first error happens.
The next step is going to be parameterizing your queries so you don't have to surround parameter values in quotes or worry about sql injection. See this answer for an example of how spring-jdbc handles this.
I moved the connection stuff out of the method; passing in a connection allows you to have multiple sql statements execute in the same JDBC local transaction. (The connection still needs to get closed, this is just the wrong place to do it.)
Also passing in this handle thing here is a violation of the Law of Demeter:

In particular, an object should avoid invoking methods of a member object returned by another method. For many modern object oriented languages that use a dot as field identifier, the law can be stated simply as "use only one dot". That is, the code a.b.Method() breaks the law where a.Method() does not. As an analogy, when one wants a dog to walk, one does not command the dog's legs to walk directly; instead one commands the dog which then commands its own legs.

Even if you're only doing read-only stuff, having queries share a transaction can improve consistency and be better for performance. Using transactions is less painful with Spring, you can implement transactions declaratively using annotations to show where you want the boundaries to be.
The big-picture answer here is: it would be better to adopt a pre-existing tool (spring-jdbc or something similar), where they have already solved problems you haven't even gotten around to considering yet, than to reinvent it piecemeal, which is the road you're evidently headed down.


text:
Q: php Dynamic HTML cell generates unexpectedly I am currently working on interface part a framework to generate HTML tags. Problem i am facing is while generating tags for nested tables and cells.
for this purpose, I have one html class which define common expectation of tags. Another class is htmlTable which is inherited from hrml class and customised for table, TR, TD. While i want to add nested tables on a particular cell, the result is unexpected. It generates hundreds of TDs and TRs.
Following code is customised to post here as putting all code will make long and too confusing.
And one more thing, I am only concentrated to solve logical error to get exact parent, child and nested elements of HTML tag.
I have tried as much as i could but couldnot get this fixed. This might be easy for some of you. So please advice me your solution. I have got to go to work so will reply only once i get back.
Thnak you
<?php
// scHTML.php
class HTML
{
    protected $tag;
    protected $id;

    protected $values;
    protected $childList;

    protected $body;

    public function __construct($tag,$id)
    {
        $this->tag=$tag;
        $value= array('id'=>$id);
        $this->setValues($value);
    }

    // to add nested tag
    public function addChildTag(HTML $child)
    {
        $this->childList[]=$child;
    }

    // to add key and value on opening tag
    public function setValues($values)
    {
        if(count($values)>0)
        {
            foreach($values as $key=>$value)
            {
                $this->values[$key]=$values;
            }
        }
    }

    // value inside tag
    public function setBody($body)
    {
        $this->body=$body;
    }

    // generate HTML code
    public function getHTML()
    {
        $return= '<'.$this->tag;
        if(count($this->values)>0)
        {
            foreach($this->values as $key=>$value)
            {
                $return.=' '.$key.'= "'.$value.'" ';
            }
        }
        $return.= '>
        ';
        if(count($this->childList)>0)
        {
            $return.=
                            $this->body
                            ;
            foreach($this->childList as $child)
            {
                $return.=
                                $child->getHTML();
            }
        }
        $return.=' </'.$this->tag.'>';
        return $return;
    }

    public function __toString()
    {
        return $this->getHTML();
    }
}
?>

and here is the inherited class for table
<?php
//scHTMLTable.php
include_once("scHTML.php");
class HTMLTable extends HTML
{
    protected $cells; // logical grid of cells for current table
    protected $row;
    protected $column;

    public function __construct($row,$column,$id)
    {
        $this->row=$row;
        $this->column=$column;
        $this->initiateTable();
        $values['border']='1px';
        $this->setValues($values);

        parent::__construct("table",$id);

    }

    // initaite table cells according to row and column provided
    private function initiateTable()
    {
        $td=new HTML("td",NULL);
        $td->setBody(' ');
        for($i=1;$i<=$this->row;$i++)
        {
            for($j=1;$j<=$this->column;$j++)
            {
                $this->addCell($i,$j,$td);
            }
        }
    }

    // set child element as body on a cell
    public function addChildOnCell($row,$column,HTML $child)
    {
        $td=$this->cells[$row][$column];
        $td->addChildTag($child);
        $this->addCell($row,$column,$child);
    }

    // set cell
    public function addCell($row,$column,HTML $cell)
    {
        $this->cells[$row][$column]=$cell;
    }

    // set TR as child and call parent method to generate html code.
    public function getHTML()
    {
        for($i=1;$i<=$this->row;$i++)
        {
            $tr=new HTML("tr",NULL);
            for($j=1;$j<=$this->column;$j++)
            {
                $td=$this->cells[$i][$j];
                $tr->addChildTag($td);
            }
            $this->addChildTag($tr);
        }
        return parent::getHTML();
    }

    public function __toString()
    {
        return $this->getHTML();
    }
}

?>

And here is the implementation.
<?php
include_once("scHTML.php");
include_once("scHTMLTable.php");

$html= new HTML("html",NULL);
$body=new HTML("body",NULL);

// three table to be tested
$a= new HTMLTable(3,3,"grandparent");
$b=new HTMLTable(3,3,"parent");
$c=new HTMLTable(1,1,"child");

$b->addChildOnCell(2,2,$c);
$a->addChildOnCell(2,2,$b);

$body->addChildTag($a);
$html->addChildTag($body);

echo $html;
?>

Output  i am looking as source code is somewhere near this

A: It's 2015, you should not be manually including files; there are clear coding-standards, so you should have namespaces and register an auto-loader in your main App.
Also as long as you are going to string build in this way, using the __toString() method on objects representing the tables, you should just have other classes for the nested parts, each with their own __toString method; so you can have HTMLElement class (you've got), with table (you have but it's not ideal), table-row, table-cell.
Extending this, you should if you take this route extend all HTMLElements, and have a rawString HTMLElement extended class for when you feel like just getting things done parrot fashion.

*

*table row __toString method would just iterate over contained cells and return their __toString methods

*table would iterate over rows and call their __toString method

*table cell (the most / least difficult part), would take instances implementing HTMLElement, and iterate over them calling their __toString method

It's a lot cleaner method of working than the current, and then as each outputs it's own DOM, you should be free of the nasty bug you have now.
If the table gets too large, you are going to wish you had just coded a series of views that work with one-level of XYdata, or simplified in another way; but the data structures to this sort of nested view, unless you are working with JSON or XML anyway (in the case of XML, just use XSL); are not going to be nice to retrieve from say SQL Server, MySQL, search upon, or really to do that many useful things with...

A: I agree with MrMesees in that I think your table class is doing too much and that each node type is only responsible for generating it's own DOM representation.  Any to-string / to-html recursion should only move downward through the DOM, though (no calls to parents for rendering assistance).  Here is a quick demo using some of your custom API method names:
  class HTML
  {
    private $tagName;
    protected $attributes = [];
    protected $children = [];
    private $text = '';

    public function __construct($tagName, $text='') {
      $this->tagName = strtolower($tagName);
      $this->text = $text;
    }

    public function addChildTag(HTML $n) {
      $this->children[] = $n;
      return $this;
    }

    public function getHTML($depth=0) {
      $padding = str_repeat("\t", $depth);
      $result = "$padding<$this->tagName";
      foreach($this->attributes as $k => $v) {
        $result .= " $k=\"".htmlspecialchars($v)."\"";
      }
      if (count($this->children) == 0 && strlen($this->text) == 0) {
        $result .= " />\n";
      }
      else {
        $result .= ">";
        $result .= $this->text;
        if (count($this->children) > 0) $result .= "\n";
        foreach($this->children as $c) {
          $result .= $c->getHTML($depth+1);
        }
        $result .= "$padding</$this->tagName>\n";
      }
      return $result;
    }

    public function tagName() { return $this->tagName; }

    public function findChild($tagName, $index=0) {
      $nodes = array_filter($this->children, function($e) use ($tagName) {  return $e->tagName() == $tagName;  });
      return count($nodes) ? $nodes[$index] : null;
    }

    public function __toString() { return $this->getHTML(); }
  }

  class HTMLTable extends HTML {
    public function __construct($rows, $cols, $id) {
      parent::__construct("table");
      $this->attributes['id'] = $id;
      $this->attributes['border'] = '1px';
      for($r=0; $r<$rows; $r++) {
        $row = new HTML("tr");
        for($c=0; $c<$cols; $c++) {
          $cell = new HTML("td");
          $row->addChildTag($cell);
        }
        $this->addChildTag($row);
      }
    }

    public function addChildOnCell($row, $col, HTML $child) {
      return $this->findChild("tr", $row-1)->findChild("td", $col-1)->addChildTag($child);
    }
  }

  $html= new HTML("html");
  $body=new HTML("body");

  // three table to be tested
  $a= new HTMLTable(3,3,"grandparent");
  $b=new HTMLTable(3,3,"parent");
  $c=new HTMLTable(1,1,"child");

  $b->addChildOnCell(2,2,$c);
  $a->addChildOnCell(2,2,$b);

  $body->addChildTag($a);
  $html->addChildTag($body);

  echo $html;

Which results in output:


text:
Q: Nodejs array object not updating I am getting a data from mongoose database. And It have some array which have ids which data I need to get from other api. All is working but when I change the object of array like this in for loop team[i].teamPlayersDetails = playerss; Its not changing I can even see playerss have data but its not changing the team.
const getAllTeams = async (req, res) => {
    let team = await Team.find();
    var userids = [];
    var usersdata = [];

    for (let i = 0; i < team.length; i++) {
        for (let j = 0; j < team[i].teamPlayers.length; j++) {
            userids.push(team[i].teamPlayers[j])
        }
    }
    var data = {
        'ids': userids
    }

    await axios.post(`http://localhost:3000/auth/getMultipleUserByUserID`, data)
        .then(async function (response) {
            usersdata = response.data.data
        });

    for (let i = 0; i < team.length; i++) {
        playerss = [];

        team[i].teamPlayers.forEach(player_id => {
            playerss.push(usersdata.find(p => p.userID === player_id.toString()))
            team[i].teamPlayersDetails = playerss;
        })
    }

    if (!team) {
        return res.status(200).json({ message: "user not found", success: false })
    }

    return res.status(200).json({ message: "success", success: true, data: team })
};

A: use lean and then check
let team = await Team.find().lean();

A: You logic has a flaw. You are updating the team[I].teamPlayersDetails over each player_id iterated upon. You should be only performing the update when all player_ids have been iterated.
You are better using the map operator function to transform the player_ids to their respective details hence no need for the intermediary playerss array.
If you would like your changes to be reflected in the database, you should perform the update explicitly using updateOne or updateMany collection methods.
const getAllTeams = async (req, res) => {
    let team = await Team.find();
    const userids = [];

    for (let i = 0; i < team.length; i++) {
        for (let j = 0; j < team[i].teamPlayers.length; j++) {
            userids.push(team[i].teamPlayers[j]);
        }
    }

    const usersResponse = await axios.post(`http://localhost:3000/auth/getMultipleUserByUserID`, { 'ids': userids });
    const usersdata = usersResponse.data.data;

    for (let i = 0; i < team.length; i++) {
        const teamPlayersDetails = team[i].teamPlayers.map(player_id => usersdata.find(p => p.userID === player_id.toString()));
        await Team.updateOne({ _id: team[I]._id.toString() }, { $set: { teamPlayersDetails } });
    }

    // ...
};

A: Instead of forEach i suggest you to use classic for loop


text:
Q: Find a point so that the triangle is equilateral We have O(0,0), A(3,4) and B(x,y). Find $x,y\in{R}$ so that the OAB triangle is equilateral.
I tried using the fact that the median is also the altitude(height) of the equilateral triangle. I calculated that distance from O to A(it's 5), meaning all the sides of the triangle have to be 5. Then, I computed the line equation for OA. I set M as the middle point of line OA. I then computed the equation for the line BB' which would be perpendicular on line OA(I knew the slope, since I knew the slope of line OA and I knew that M was a point on the line) and pass through point M(the median/height of the triangle).
After all this I could say that:
$$d(O,B)=\sqrt{x^2+y^2}=5$$
and $$d(A,B)=\sqrt{(3-x)^2+(4-y)^2}=5$$
The solutions I get from this equation system should be in the form of x,y, where x and y are the coordinates of point B. The system should return me more than one solution, but in order for it to be right I must also check that the points I get are also on line BB'.
Anyway, that was my thought process. The problem is that I'm getting into really 'icky' equations that I deem hard to solve, giving me really odd solutions for my coordinates.
Isn't there a better way to solve this problem? I've been busting my brain on this one for about 3 hours now.

A: How about using complex numbers?
Let $x+iy$ be the point we want where $x,y\in\mathbb R$.
We have
$$x+iy=(3+4i)\left(\cos\left(\pm\frac{\pi}{3}\right)+i\sin\left(\pm\frac{\pi}{3}\right)\right),$$
i.e.
$$x+iy=3\cos\left(\pm\frac{\pi}{3}\right)-4\sin\left(\pm\frac{\pi}{3}\right)+i\left(3\sin\left(\pm\frac{\pi}{3}\right)+4\cos\left(\pm\frac{\pi}{3}\right)\right)$$
Hence, we have
$$(x,y)=\left(3\cos\left(+\frac{\pi}{3}\right)-4\sin\left(+\frac{\pi}{3}\right),3\sin\left(+\frac{\pi}{3}\right)+4\cos\left(+\frac{\pi}{3}\right)\right),\left(3\cos\left(-\frac{\pi}{3}\right)-4\sin\left(-\frac{\pi}{3}\right),3\sin\left(-\frac{\pi}{3}\right)+4\cos\left(-\frac{\pi}{3}\right)\right)$$

A: If complex are forbidden (are not in your program), you could consider solving trinomials.
You know that $x^2 + y^2 = 25$ and $(3-x)^2 + (4-y)^2 = 25$. Develop the second equality into $25 + x^2 + y^2 - 6x - 8y = 25$. Since $x^2 + y^2 = 25$, it turns into $6x + 8y = 25$, hence $x = \frac{25}{6} - \frac{4}{3}y$.
Now replace $x$ with this expression in the first equation and you will get a classic trinomial in $y$. Use the technique seen in class to solve it. You should get two solutions. You easily derive the value of $x$ then.
Your solutions should be something like $y = 2 \pm \frac{3\sqrt{3}}{2}$ once simplified.

A: 1351957
Given:
$P_0(x_0\mid y_0)$
$P_1(x_1\mid y_1)$ .
Object:
Find $P_2(x_2\mid y_2)$, such that $P_0P_1P_2$ mark an equilateral triangle.
Solution:
$x_2=\frac{x_1+x_0\mp(y_1-y_0)\sqrt3}2$
$y_2=\frac{y_1+y_0\pm(x_1-x_0)\sqrt3}2$
Choose the upper sign for anticlockwise,
lower sign for clockwise.

A: Using rotation transformation rotate the vector on x-axis,  $ 5\,i, $  by angle
$$ \pi/3 + tan^{-1} \frac 43 $$
for vector tip to get to required position $(x,y).$ It simplifies easily.


text:
Q: generate image and share with intent without permission I have a function that allow the user to share a text on social media and other messaging apps.
I would like to allow the user to send this text as an image. I found how to generate image from text but it always require permissions and I can't figure out if there is a way that would work without requiring any permission. Is this something possible?
Current function:
        Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
        sharingIntent.setType("text/plain");
        sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, getTitle());
        sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, getText());
        startActivity(Intent.createChooser(sharingIntent, "share using"));

I searched around and tried to find if I could generate it to cache and or a folder that don't require permission but haven't found anything that would work yet.
Any insight on this is appreciated, thank you for taking the time to help!

A: After some researches using the suggestion of CommonsWare I managed to make it work with the following code:
TextPaint tPaint = new TextPaint();
tPaint.setTextSize(30);
tPaint.setColor(Color.BLACK);
tPaint.setStyle(Paint.Style.FILL);

StaticLayout layoutBody = new StaticLayout(textToShare, tPaint, 600, Layout.Alignment.ALIGN_CENTER, 1, 1, false);
Bitmap image = Bitmap.createBitmap(layoutBody.getWidth(), layoutBody.getHeight(), Bitmap.Config.ARGB_8888);

Canvas cs = new Canvas(image);
layoutBody.draw(cs);
cs.drawBitmap(dest, 0, 0, null);

Followed by what I found here posting it here in case it helps anyone


text:
Q: Well-defined $\xi$-weighted (Euclidean) norm Suppose $\xi$ is a vector, that is used for $\parallel z\parallel_\xi$ calculation. Should every element of $\xi$ be positive, $\xi(i)>0$?

A: The answer depends on how you define the weighted norm. For
$$\|z\|_\xi = \left(\sum_i z_i^2 \xi_i\right)^{1/2}$$
Then yes, $\xi_i>0$ is required for this to be a true norm. If instead you define it as
$$\|z\|_\xi = \left(\sum_i (\xi_i z_i)^2\right)^{1/2}$$
then the condition is simply $\xi_i\neq 0$.


text:
Q: Smartphone Browser resolution I've been writing a HTML5/jQuery responsive template for a website based on viewport dimensions.  I'm using an HTC 8X for some testing and while the screen resolution for the device is 1280x720 the width of the viewport in the browser is reported as 320px portrait and 480 in landscape (reversed for portrait orientation)?
While this isn't a problem as such, I wondered why this happens?  And does this happen across all smartphones (iOS, 'Droid and Windows Phone).
Thanks in advance.

A: the browser in windows mobile and iOS support the meta MobileOptimized to tell the browser what res to report.
ie. you can tell the browser to report and react as if it was 320 wide by using
<meta name="MobileOptimized" content="320"/>