text:
Q: Global variable not working, help out a noob import random

#--------------------------------------------------------------------#

tieCount = 0
lossCount = 0
winCount = 0
totalPoint = 10
i = 3

#--------------------------------------------------------------------#

def cpuFire(userInput, points):
    if userInput == 0:
        totalPoint = totalPoint + int(0)
        tieCount = tieCount + 1
        lossCount = lossCount + 0
        winCount = winCount + 0
        cpuChoice = "fire"
        wlt = "t"
    elif userInput == 1:
        totalPoint = totalPoint + int(points * -1)
        tieCount = tieCount + 0
        lossCount = lossCount + 1
        winCount = winCount + 0
        cpuChoice = "fire"
        wlt = "l"
    elif userInput == 2:
        totalPoint = totalPoint + int(points)
        tieCount = tieCount + 0
        lossCount = lossCount + 0
        winCount = winCount + 1
        cpuChoice = "fire"
        wlt = "w"

def cpuGrass(userInput, points):
    if userInput == 1:
        print("Tie! Your points remain unchanged")
        totalPoint = totalPoint + int(0)
        tieCount = tieCount + 1
        lossCount = lossCount + 0
        winCount = winCount + 0
        cpuChoice = "grass"
        wlt = "t"
    elif userInput == 2:
        print("You lost the game with X points deducted.")
        totalPoint = totalPoint + int(points * -1)
        tieCount = tieCount + 0
        lossCount = lossCount + 1
        winCount = winCount + 0
        cpuChoice = "grass"
        wlt = "l"
    elif userInput == 0:
        print("You won the game with X points added.")
        totalPoint = totalPoint + int(points)
        tieCount = tieCount + 0
        lossCount = lossCount + 0
        winCount = winCount + 1
        cpuChoice = "grass"
        wlt = "w"

def cpuWater(userInput, points):
    if userInput == 2:
        print("Tie! Your points remain unchanged")
        totalPoint = totalPoint + int(0)
        tieCount = tieCount + 1
        lossCount = lossCount + 0
        winCount = winCount + 0
        cpuChoice = "water"
        wlt = "t"
    elif userInput == 0:
        print("You lost the game with X points deducted.")
        totalPoint = totalPoint + int(points * -1)
        tieCount = tieCount + 0
        lossCount = lossCount + 1
        winCount = winCount + 0
        cpuChoice = "water"
        wlt = "l"
    elif userInput == 1:
        print("You won the game with X points added.")
        totalPoint = totalPoint + int(points)
        tieCount = tieCount + 0
        lossCount = lossCount + 0
        winCount = winCount + 1
        cpuChoice = "water"
        wlt = "w"

def cpuRand():
    cpuList = ["f","g","w"]
    rand = random.choice(cpuList)
    if rand == "f":
        cpuFire(userInput, points)
    elif rand == "g":
        cpuGrass(userInput, points)
    elif rand == "w":
        cpuWater(userInput, points)

#--------------------------------------------------------------------#

while i > 0:
    print("You have " + str(totalPoint) + " points.")
    points = int(input("Enter the number of points to be used for next game: "))
    if points > totalPoint:
        print("You do not have neough points.")
        i = i - 0
    else:
        userInput = int(input("Enter 0(fire), 1(grass) or 2(water): "))
        if userInput > 2 or userInput < 0:
            print("You entered an invalid option, you lost!")
            break
        else:
            cpuRand()
            if wlt == "t":
                print("draw!")
            elif wlt == "l":
                print("You are " + str(userInput) + " and computer is " + str(cpuChoice) + ", you lost!")
            elif wlt == "w":
                print("You are " + str(userInput) + " and computer is " + str(cpuChoice) + ", you won!")
            i = i - 1

I am trying to help a friend out with their assignment, and I keep getting an error
local variable 'totalPoint' referenced before assignment
I have tried putting global totalPoint within the first line of the functions, outside of it and on the top of the code. I can't make this work, how do I solve it?

A: While you can access global variables without the global keyword, if you want to modify them you have to use the global keyword. For example:
def cpuFire(userInput, points):

    # if you want to modify the global variable you need to add this to each local scope
    global totalPoint

    if userInput == 0:
        totalPoint = totalPoint + int(0)
        tieCount = tieCount + 1
        lossCount = lossCount + 0
        winCount = winCount + 0
        cpuChoice = "fire"
        wlt = "t"
    elif userInput == 1:
        totalPoint = totalPoint + int(points * -1)
        tieCount = tieCount + 0
        lossCount = lossCount + 1
        winCount = winCount + 0
        cpuChoice = "fire"
        wlt = "l"
    elif userInput == 2:
        totalPoint = totalPoint + int(points)
        tieCount = tieCount + 0
        lossCount = lossCount + 0
        winCount = winCount + 1
        cpuChoice = "fire"
        wlt = "w"

A: Declaring the variable outside all the functions will by default result in a global variable. However, if you want to create a global variable within a function, then you have to use the global keyword.

A: I solved it, I put my global var inside the if and elif statements, I should put it at the beginning of the function def


text:
Q: how to store and display multiline text in firestore when i store data using
  <vs-textarea  v-model="textarea" label=" Description "  rows="5"  />

e.g.
       abc
       def
       geh

the data is stored in the firestore in the format of string
abc def geh
and same is displayed when retrieved
using
 <vs-collapse>
                <vs-collapse-item>

Read More

                   {{ jobDetails.description }}

                    </vs-collapse-item>
            </vs-collapse>

how can i store multiline text in firestore ?

A: You could add '\n' characters as newline characters and use white-space: pre-wrap css to display them.
https://codepen.io/GuillaumeMeral/pen/NWWNWMr

A: Just format the text with your own delimiter and then split it back. Example:

The quick brown fox^jumps over the lazy dog

Here I use the ^ character as delimiter. Now just use a split like:
import java.util.regex.Pattern;

Pattern pattern = Pattern.compile("^");
String[] result = pattern.split(INPUT_STRING);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Are marcos of myproject.vcxproj available in cake build? Is it possible to use macros like $(OutDir) and $(ProjectName) in cake build?
I want to do further process on the output file of a VC++ project.
For example, I want to protect the binary by calling 'upx myproject.exe', but don't want to hard code the exe name.
I know this could be done in Post-Event of my VC++ project, just want to know if there is way doing same in cake-build.

A: There are a couple of Project Parsers in Cake, which allow you to access things like output file name, and references, etc.  This works well for *.csproj and *.vbproj files,  but I am not sure if this will work for the project type you are using.
http://cakebuild.net/api/Cake.Common.Solution.Project/ProjectAliases/A553D651
If this doesn't work, then you may have to look at creating something similar specifically for this project type.


text:
Q: Scrapy Spider not following Request callback I have read Scrapy: Follow link to get additional Item data? and followed it, but it is not working, probably it is sone simple mistake, so I am putting source code of my Spider.
import scrapy
from scrapy.spider import Spider
from scrapy.selector import Selector

class MySpider1(Spider):
    name = "timeanddate"
    allowed_domains = ["http://www.timeanddate.com"]
    start_urls = (
        'http://www.timeanddate.com/holidays/',
    )

    def parse(self, response):
        countries = Selector(response).xpath('//div[@class="fixed"]//li/a[contains(@href, "/holidays/")]')

        for item in countries:

            link = item.xpath('@href').extract()[0]
            country = item.xpath('text()').extract()[0]

            linkToFollow = self.allowed_domains[0] + link + "/#!hol=1"

            print link  # link
            print country  # text in a HTML tag
            print linkToFollow

            request = scrapy.Request(linkToFollow, callback=self.parse_page2)

    def parse_page2(self, response):
        print "XXXXXX"
        hxs = HtmlXPathSelector(response)

        print hxs

I am trying too get list of all holidays per for each country, that is what I need to get to another page.
I can not understand why parse_page2 is not called.

A: I could make your example work using Link Extractors
Here is an example:
#-*- coding: utf-8 -*-
from scrapy.contrib.spiders import CrawlSpider,Rule
from scrapy.contrib.linkextractors.lxmlhtml import LxmlLinkExtractor

class TimeAndDateSpider(CrawlSpider):
    name = "timeanddate"
    allowed_domains = ["timeanddate.com"]
    start_urls = [
        "http://www.timeanddate.com/holidays/",
    ]

    rules = (
            Rule (LxmlLinkExtractor(restrict_xpaths=('//div[@class="fixed"]//li/a[contains(@href, "/holidays/")]',))
                , callback='second_page'),
            )

    #2nd page
    def second_page(self,response):
        print "second page - %s" % response.url

Will keep trying to make the Request callback example to work


text:
Q: How to create a user and group in chef without 'cloning resource' warning I recently used following recipe to create a specific user, group:
sysadmin = data_bag_item('users','sysadmin')

group 'sysadmin' do
  action :create
  gid sysadmin['gid'].to_i
end

user 'sysadmin' do
  uid sysadmin['uid'].to_i
  gid sysadmin['gid'].to_i
  manage_home true
  shell sysadmin['shell']
  action :create
end

group 'sysadmin' do
  action :modify
  members 'sysadmin'
  append true
end

And get following warnings:
  Cloning resource attributes for group[sysadmin] from prior resource
Previous group[sysadmin]: /var/chef/cache/cookbooks/initialubuntu/recipes/sysadmin_user.rb:16:in `from_file'
Current  group[sysadmin]: /var/chef/cache/cookbooks/initialubuntu/recipes/sysadmin_user.rb:29:in `from_file' at 1 location:

Chef cannot create a user with gid of non-existent system group.
How to merge group resources into one?

A: You would have to rename one of them, for example you could rename the second one:
group 'append sysadmin' do
  group_name 'sysadmin'
  action :modify
  members 'sysadmin'
  append true
end

Alternatively if you upgrade to Chef 13, cloning has been removed at long last so these warnings are impossible now.


text:
Q: My postfix is letting me send emails through it without a username password - how to disable? My postfix is letting me send emails through it without authentication. It has been setup to allow authentication, but it also allows non authenticated sending which I'd like to stop.
What config settings are the relevant ones in this situation?
Here is an output of postconf -n to help debug:
alias_database = hash:/etc/aliases
alias_maps = hash:/etc/aliases
command_directory = /usr/sbin
config_directory = /etc/postfix
daemon_directory = /usr/libexec/postfix
data_directory = /var/lib/postfix
debug_peer_level = 2
html_directory = no
inet_interfaces = all
inet_protocols = all
mail_owner = postfix
mailq_path = /usr/bin/mailq.postfix
manpage_directory = /usr/share/man
mydestination = $myhostname, localhost.$mydomain, localhost, $mydomain,
mydomain = hiddenforprivacy.org
myhostname = mail.hiddenforprivacy.org
myorigin = $myhostname
newaliases_path = /usr/bin/newaliases.postfix
queue_directory = /var/spool/postfix
readme_directory = /usr/share/doc/postfix-2.6.6/README_FILES
sample_directory = /usr/share/doc/postfix-2.6.6/samples
sendmail_path = /usr/sbin/sendmail.postfix
setgid_group = postdrop
smtpd_client_restrictions = permit_mynetworks, permit_sasl_authenticated
smtpd_recipient_restrictions = permit_sasl_authenticated, reject_unauth_destination
smtpd_sasl_auth_enable = yes
smtpd_sasl_path = private/auth
smtpd_sasl_type = dovecot
soft_bounce = no
unknown_local_recipient_reject_code = 550
virtual_alias_domains =
virtual_alias_maps = hash:/etc/postfix/virtual

A: You should remove the permit_mynetworks directive from smtpd_client_restrictions.  Then, if you are using version 2.10 or later, add:
 smtpd_relay_restrictions = permit_sasl_authenticated, reject_unauth_destination

If you are not there yet, remember this, and when you update, add this directive then.
What this will do is disable any unauthenticated access to your mailserver at all, including from your own networks in $mynetworks.  The one exception is that remote hosts will still be able to submit mail destined for one of your addresses (so you can still recieve mail, as remote MTAs sending mail to you do not authenticate); this is the difference between reject_unauth_destination and reject.  It will also update your relay access control to the 2.10 specification.
If you want to not even accept mail (eg. from other mailservers) to hosts in your domain without authentication, replace reject_unauth_destination with reject.  If you do that you will not get any incoming email through this server.


text:
Q: convert paragraph or new elements into checkbox I have contenteditable div as text editor
Functionality needed is whatever the user writes or copy/paste in text editor turns into checkbox
for eg

Case 1

If User writes the following
Test1(enter key pressed)
Test2(enter key pressed)
Test3(enter key pressed)
then there should be three checkbox for Test1,Test2,Test3 respectively
And

Case2

when the user writes
Parent1 (enter key pressed)

*

*Test1(enter key pressed)

*Test2(enter key pressed)

*Test3(enter key pressed)
In the above case there will be 4 checkbox parent1 and 3 li's
Things i have achieved but i am open to accept new way if more accurate.
$('#checkbox').click(function() {
var $p = "";
     var re = /\S/;
     $p = $('.outputBox');
      $p.contents()
      .filter(function() {
        return this.nodeType == 3&& re.test(this.nodeValue);;
     })
    .wrap(' <input type="checkbox" name="field_1" value="on" />')
});

FIDDLE Demo
Basically a new span,div,br tags or for that matter li's should be created into checkboxes.
If there is any different method which will fulfill both the requirement/basic requirement of creating checkboxes it is most welcome.

A: Here is a possible solution. I have made a traversal to the innermost text element and then convert that into a checkbox.
$('#checkbox').click(function() {
     var $p = "";
     $p = $('.outputBox');
     wrapText($p);
});

function wrapText(domObj) {
    var re = /\S/;
    domObj.contents().filter(function() {
        if (this.nodeType === 1) {
            wrapText($(this));
        } else {
            return (this.nodeType === 3 && re.test(this.nodeValue));
         }
    })
    .wrap(' <input type="checkbox" name="field_1" value="on" />');
}

Here is the fiddle:
http://jsfiddle.net/wLrfqvss/6/
Hope thats what you are looking for.
If you want this to happen for only certain elements, you could always add a check like so:
if (this.nodeType === 1 && this.tagName === 'DIV')

in the above code.

A: you can use template for checkbox instead of hardcoding html

 <input type="checkbox" name="field_1" value="on" />

in code
$('#checkbox').click(function() {});

 function createElement()
{
 var targetElement=$("#template").clone(true);
 targetElement.removeAttr("style");
 targetElement.attr("name","new id");
 var $p = "";
 var re = /\S/;
 $p = $('.outputBox');
  $p.contents()
  .filter(function() {
    return this.nodeType == 3&& re.test(this.nodeValue);;
 })
.wrap(targetElement)
}

this will also provide you flexibility of using any html template as the code is not control specific

A: Almost everybody has given answer to first case of question but i found answer for 2nd case
i added this two lines in the click event of  SHOW CONTENT with CHECKBOX
I guess @arthi sreekumar is also getting me li's into checkbox Upvote to that.
 $('.outputBox').find("ol").find("li").wrapInner((' <input type="checkbox" class="liolChk" name="field_1" value="on" />'));
 $('.outputBox').find("ul").find("li").wrapInner((' <input type="checkbox" class="liolChk" name="field_1" value="on" />'));

Fiddle Demo

A: How about using *(space) to generate li? I used regex and process string to generate it.
function update() {
    var str = $('#inputBox').html();
    $('#outputBox').html(str);
    $('#showHTML').text(str);

    str = str.replace(/(
$)/,'')
             .replace(/(
)/g,'$1\n')
             .replace(/\* (.*)/g, '
$1
')
             .replace(/^(?!
)/gm,'<input type="checkbox" name="field_1" value="on">')
             .replace(/^
(.*)<\/li>/gm,'
<input type="checkbox" name="field_1" value="on">$1
');

    if(str.indexOf('
')!=-1) {
        var index = str.indexOf('
');
        var lastIndex;
        str = str.substring(0, index) + '
' + str.substring(index);
        lastIndex = str.lastIndexOf('
') +  '
'.length+  1;
        str = str.substring(0, lastIndex) + '
' + str.substring(lastIndex);
    }
    $('#translatedBox').html(str);
    $('#translatedHTML').text(str);
}

Here is the jsfiddle

A: Hello I change your js code as follow,
$('div[contenteditable=true]').blur(function() {

    $('.outputBox').append('
').append("<input type='checkbox' value='"+$(this).html()+"' />"+$(this).html());
$(this).html("");

 });

$('div[contenteditable=true]').keydown(function(e) {
    //$('.outputBox').html($(this).html()); i commented this line

I hope its working something like you were looking for..


text:
Q: Pass php array into HTML I want to pass php variable into html for further processing.
this is php variable-
$coords   = array();

array_push($coords,some value);

I want to pass this to html-
var Coordinates = [];
Coordinates.push('<? php $coords; ?>');

But this is not the correct way as it gives error. Someone please help me to achieve this
Thanks.

A: The simplest example is to json_encode this out into the javascript var like so:
var Coordinates = <?= json_encode($coords) ?>

Then simply loop through this like you would any other json.
This question has been asked alot of times before however, so please check here for any further methods.
How to pass variables and data from PHP to JavaScript?

A: Try something like that:
Coordinates.push('<?="[".implode($coords,",")."]" ?>');
http://php.net/manual/en/function.implode.php

A: Server side, you can create a javascript array directly in your rendered html :
<script>
    var Coordinates = [<?php
        echo '"'.implode('","', $coords).'"';
    ?>];
</script>


text:
Q: Balanced KMeans: number of sizes provided must be greater or equal to the number of dimensions in the tensor I'm been trying to make a balanced clusters for my masther thesis using Google Colab (because I don't have a GPU) and balanced k-means Library (https://pypi.org/project/balanced-kmeans/), this is the process that I made:

*

*Install the balanced k-means Library in Google Colab using this command:
!pip install balanced_kmeans

*Import a CSV file to my Google Colab instance:
from google.colab import files

subido=files.upload()

*Create a Pandas dataframe
import pandas as pd
import io
df = pd.read_csv(io.BytesIO(subido['prueba.csv']))

*Then, changed the string data type to integer in the columns than I going to use:
df["bytes"] = pd.to_numeric(df["bytes"],errors='coerce')
df["bytes"] = df["bytes"].fillna(0)

df["paquete"]= pd.to_numeric(df["paquete"],errors='coerce')
df["paquete"]= df["paquete"].fillna(0)

*Once I changed the data type, proceed to create a tensors (in this case 2 colums from the pandas dataframe) then stacked those tensors:
import torch
device = 'cuda'

A= torch.cuda.IntTensor(df['bytes'].values,device=device)

B=torch.cuda.IntTensor(df['paquete'].values,device=device)

prueba=[A,B]

X = (torch.stack(prueba,dim=1))

*Finally I tried to create the clusters:
from balanced_kmeans import kmeans_equal
N=X.shape[0]
num_clusters=100
device='cuda'
cluster_size=N//num_clusters
choices,centers=kmeans_equal(X,num_clusters=num_clusters,cluster_size=cluster_size)
But unfourtanelly I got this error:

RuntimeError Traceback (most recent call last)
in ()
16 #print (W)
17
---> 18 choices, centers = kmeans_equal(X, num_clusters=num_clusters,cluster_size=cluster_size)

1 frames

/usr/local/lib/python3.6/dist-packages/balanced_kmeans/init.py in initialize(X, num_clusters)
16 indices = torch.empty(X.shape[:-1], device=X.device, dtype=torch.long)
17 for i in range(bs):
---> 18 indices = torch.randperm(num_samples, device=X.device)
19 initial_state = torch.gather(X, 1, indices.unsqueeze(-1).repeat(1, 1,X.shape[-1])).reshape(bs,num_clusters, -1, X.shape[-1]).mean(dim=-2)
20 return initial_state

RuntimeError: expand(torch.cuda.LongTensor{[20839]}, size=[]): the number of sizes provided (0) must be greater or equal to the number of dimensions in the tensor (1)

I don't know if this error is caused by the tensor X having a 1 dimention, and in the library the initialization function create a empty tensor with zero dimension (I took this code from initialize method in the init.py):
indices=torch.empty(X.shape[:-1], device=X.device, dtype=torch.long)
for i in range(bs):
  indices[i] = torch.randperm(num_samples, device=X.device)

So Am I doing right? (I'm new using tensors) or there is a bug in the initialization function?
I already checked the solution from PyTorch: The number of sizes provided (0) must be greater or equal to the number of dimensions in the tensor (1) but doesn't work for me becauseI don't need a scalar value.


text:
Q: How to remove unchecked value from list? I need to get all checked values from checkboxes and return them in element.
I have a code:
this.values = [];
if (item.checked) {
        this.values.push(item.value);
    } else {
        this.values.splice(item.value)
    }
 return alert(this.values);

There are few problems:

*

*If I check and uncheck the same item, it pushes to array every time, so there could be same multiple values. (this.values = [1,1,1])

*Splice does not remove from this.values one item.value that was unchecked, it removes all values and make this.values empty (this.values = []);
What I need is:
if I have item values for example: 1 , 2 , 3
And check every item, that my array will become - this.values = [1 , 2 , 3]
If I uncheck item number 2, this.values = [1, 3]

A: Use a common class for all the checkbox, then use document.querySelectorAll to get the checkbox and attach event listener to each of the box.
Now on change even call another function and first filter out the checked checkbox then use map to get an array of the check box value

let elem = [...document.querySelectorAll('.checkBox')]
elem.forEach(item => item.addEventListener('change', getChecked))

function getChecked() {
  let getChex = elem.filter(item => item.checked).map(item => item.value)
  console.log(getChex)
}
<input type="checkbox" value="1" id="one" class="checkBox">
1

<input type="checkbox" value="2" id="two" class="checkBox">
2

<input type="checkbox" value="3" id="three" class="checkBox">
3

A: Ciao, you can do this:
this.values = [];
if (item.checked) {
    if(!this.values.includes(item.value)) {
       this.values.push(item.value);
    }
} else {
    if(indexOf(item.value) !== -1){
       this.values.splice(this.values.indexOf(item.value), 1)
    }
}
return alert(this.values);

Insert item.value only if this.values does not contains value and use splice with index (if item is in this.value).

A: since you didn't show your html file. I just posted the code works for me for your reference.
function getSelectedCheckboxValues(name) {
    const checkboxes = document.querySelectorAll(`input[name="${name}"]:checked`);
    let values = [];
    checkboxes.forEach((checkbox) => {
        values.push(checkbox.value);
    });
    return values;
}

if you are editing js in the HTML,
replace
 const checkboxes = document.querySelectorAll(`input[name="${name}"]:checked`);

with
const checkboxes = document.querySelectorAll('input[name="color"]:checked');

source: https://www.javascripttutorial.net/javascript-dom/javascript-checkbox/


text:
Q: Pass-through authentication for MS SQL 2005 DB from SharePoint? Within our Active Directory domain, we have a MS SQL 2005 server, and a SharePoint (MOSS 3.0 I believe) server.  Both authenticate against our LDAP server.  Would like to allow these authenticated SharePoint visitors to see some of the data from the MS SQL database.  Primary challenge is authentication.
Any tips on getting the pass-through authentication to work?  I have searched (Google) for a proper connection string to use, but keep finding ones that have embedded credentials or other schemes.  I gather that SSPI is what I want to use, but am not sure how to implement.
clarification: we don't have a single-sign-on server (e.g. Shibboleth) setup yet

A: If you are using C# the code and connection string is:
using System.Data.SqlClient;
...
SqlConnection oSQLConn = new SqlConnection();
oSQLConn.ConnectionString =
    "Data Source=(local);" +
    "Initial Catalog=myDatabaseName;" +
    "Integrated Security=SSPI";
 //Or
 // "Server=(local);" +
 // "Database=myDatabaseName;" +
 // "Trusted_Connection=Yes";
oSQLConn.Open();
...
oSQLConn.Close();

An excellent resource for connection strings can be found at Carl Prothman's Blog. Yoy should probably replace (local) with the name of the SQL server.
You will need to either configure SQL server to give the Domain Roles the access privilages you want. In SQL server you will need to go to Security\Logins and make sure you have the Domain\User Role (ie MyCompany\SharpointUsers). In your config you should have

A: Actually Windows Authentication verifies the user is legitimate without passing the username and password over the wire. Whereas Passthrough authentication does pass the username and password over the wire. They are not the same thing. Using the connection string and code provided by Leo Moore causes SQL to use Windows Authentication, which it uses by default - not Passthrough authentication, which the OP asked about.

A: What do you mean by "users of SharePoint"?
Do you mean that they want to see data from inside a SharePoint page?
In that case you have to do impersonation in that page/application, and possible set up Kerberos correctly.
Then you will have to assign those SharePoint users (or better, their AD group) proper privileges on the SQL Server.


text:
Q: Using Web Crypto API in NextJS, but getting error 'crypto is not defined' Can I use web crypto api in NextJS?
I tried to use
crypto.subtle.digest('SHA-256', data)

but getting an error
ReferenceError: crypto is not defined

A: before use crypto module, just import import crypto from "crypto"
here are example for crypto

A: You can use it with
const crypto = require('crypto');
or also by using
import crypto from "crypto"

A: For me, it worked when I used import * as
import * as crypto from 'crypto';


text:
Q: Casbin ABAC on large number of resources/objects I have a simple rest application written in golang where I have 2 entities: orders and users and I am trying to solve the authorization part using casbin. I have really low experience in writing this kind of authorizations so I will try to be clear as possible.
Explanation: Admin can assign users to work on specific orders. Any number of users (2, 4, 5...) can be assigned to work on one order but they can all have different permissions, one can have full write, one partially writes while the last two can have only read for example. These permissions can be revoked or assigned to new users anytime.
For policy storage, I plan to use pg adapter. What would be the most elegant way to handle this kind of authorization per "object/order". From the documentation, I think what I need is ABAC control as I understand it's used for fine-grain authorization and attribute based but what I don't understand how this would affect if the database gets large as I would need to write a lot of policies per each object(order)? Is this approach fine or am I missing something?


text:
Q: c++ typeid returns different values for the same unique_ptr with get() and * I came across one piece of code where typeid is used to get the type of a unique_ptr pointing to a polymorphic object.
class B{virtual void foo()= 0;};
class D:public B{void foo() override{}};

int main()
{
    unique_ptr<B> bd = make_unique<D>();
    if (typeid(*bd) != typeid(bd.get()))
    {
        cout<<"Object types are not same"<<endl;
    }
    cout<<"Type name of *bd.name():      "<<typeid(*bd).name()<<endl;
    cout<<"Type name of bd.get().name(): "<<typeid(bd.get()).name()<<endl;
}

The output is :
Object types are not of same
Type name of *bd.name():      1D
Type name of bd.get().name(): P1B

The output of name() is different for get() and dereferencing with *. One more observation is that when there is no virtual functions defined in the class [without void foo() in above example], both get() and * prints same output.
Questions :
Why the get() and * gives different output when there is no virtual functions in the class ?
Live example : https://gcc.godbolt.org/z/Tiy-Cn
EDIT-1
As per * on a unique_ptr, it says "Returns the object owned by *this, equivalent to *get()."

A: *bd returns a reference.
bd.get() returns a pointer.

Re: your edit: Note that it says "equivalent to *get()" and not "equivalent to get()".


text:
Q: How to permute array into a given order with O(1) auxiliary space? How do I implement the following OrderElements function?
char chars[] = {'a', 'b', 'c', 'd', 'e'};
int want_order[] = {2, 4, 3, 0, 1};
int length = 5;
OrderElements(chars, want_order, length);

// chars now contains: c, e, d, a, b

It's easy when you can use linear extra space, but can it be done with only constant extra space, i.e., directly sorting the chars elements in-place?
P.S.: This was not an exam question; I actually need this function.
CLARIFICATION: There seems to be a misunderstanding about the desired final order of elements. The resulting array in the example should have the following elements, referring to the original chars array:
{chars[2], chars[4], chars[3], chars[0], chars[1]}

which is
{'c', 'e', 'd', 'a', 'b'}.

A: Strictly speaking, though, O(lg length) memory is needed to represent the list index; I'm going to ignore this for this discussion, however, since using a 64-bit i is probably big enough for anything that we can actually reorder.
for (int i = 0; i < length; i++) {
  int t = want_order[i];
  while (t < i) {
    // t has been moved already; we need to find out where the value that started there
    // went. Since we must've put it at want_order[t] before, resume looking there
    t = want_order[t];
    // once t >= i, we know we've not touched that slot more than once, and so our
    // value is there
  }
  swap(chars[i], chars[t]);
}

An intuitive explanation: For each item in the array, we put the goal value in it, storing our old value in the slot that contained our goal value. We have to take care to deal with the case that our goal value was displaced; this is handled by noting that a given slot is only swapped up to twice; once when the value in there is stolen by another value (which couldn't have happened, since this iteration is going to do that) or when the value is displaced to insert the final value (which only happens to lower indices).
An illustration of how this looks on your sample data:
 i | want_order | chars     | t
 0 |  2 4 3 0 1 | a b c d e | 2 (swap)
 1 |  2 4 3 0 1 | c b a d e | 4 (swap)
 2 |  2 4 3 0 1 | c e d a b | 3 (swap)
 3 |  2 4 3 0 1 | c e d a b | 0 (follow)
 3 |  2 4 3 0 1 | c e d a b | 3 (swap - no-op)
 4 |  2 4 3 0 1 | c e d a b | 1 (follow)
 4 |  2 4 3 0 1 | c e d a b | 4 (swap - no-op)

This algorithm uses only O(lg n) memory (for the indices), but I have not attempted to fully analyze its running time. It's obvious that it's at worst O(n^2), however I suspect it will fare better than that in practice. However, there is no real bound on the length of the chains it might have to follow, so in principle it may in fact end up using O(n^2) time with worst-case input.

A: Impossible.
You need at least O(log (list size)) to know the index of the sorted element.

A: This will do the job in O(n²). In each iteration of the outer loop the currently wanted element is swapped down to its correct position (first inner loop) and then the wanted order of the remaining elements is adjusted to reflect the new situation (second inner loop).
for (int i = 0; i < length; i++)
{
    for (int j = wantedOrder[i]; j > i; j--)
    {
        Swap(chars, j, j - 1);
    }

    for (int j = i + 1; j < length; j++)
    {
        if (wantedOrder[j] < wantedOrder[i])
        {
            wantedOrder[j]++;
        }
    }
}

This of course requires destroying the wanted order array. If this is not allowed, I have no idea how to solve the problem (at least at the moment).

A: It can be done If you are allowed to change the want_order array. The algorithm is rather simple as the permutation can be decomposed into cycles. When you iterating one cycle, just mark each one being visited. And the time complexity is O(N). Pseudo code:
char chars[]      = {'a', 'b', 'c', 'd', 'e'};
int  want_order[] = {2, 4, 3, 0, 1};
int  length       = 5;

OrderElements(chars, want_order, length) {
  int i, j, k;

  for(i = 0; i < length; ++i) {
    if (want_order[i] == -1) continue;

    j = startPos = want_order[i];
    c = chars[i];
    do {
      swap(c, chars[j]);
      k = want_order[j];
      want_order[j] = -1;
      j = k
    } while(j != startPos);
  }
}

A: The post above has an error (it inadvertantly overwrites an index). Here is a corrected version:
char chars[]      = {'a', 'b', 'c', 'd', 'e'};
int  want_order[] = {2, 4, 3, 0, 1};
int  length       = 5;

OrderElements(chars, want_order, length) {
  int i, j, k;

  for(i = 0; i < length; ++i) {
    if (want_order[i] == -1) continue;

    j = startPos = want_order[i];
    c = chars[i];
    do {
      swap(c, chars[j]);
      k = want_order[j];
      want_order[j] = -1;
      j = k
    } while(j != startPos);
  }
}

A: Sort Operation with Memory O(1) is Bubblesort, but it have an Performance O(n²)
http://en.wikipedia.org/wiki/Bubble_sort


text:
Q: clearFocus() on SearchView onQueryTextChange just a quick question, I'm using a Search View in a fragment and I have this code:
 mySearch.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String s) {
                ticketmasterApiRequest(getActivity().getApplicationContext(), adapter, c,s);
                mySearch.clearFocus();
                return false;
            }

            @Override
            public boolean onQueryTextChange(String s) {
               if(!StringUtils.isNotBlank(s)){
                   ticketmasterApiRequest(getActivity().getApplicationContext(), adapter, c,"");
                   mySearch.clearFocus();
               }
                return false;
            }
        });

The onQueryTextSubmit method works exactly how it meant to, it sends away the api request and then clears the request. The problem is that onQueryTextChange doesn't work the proper way. The way it should work is that when user hits the x button on the searchview then the api sends a call and the focus is cleared, but what happens is that the api call is made but the focus still stays on the search view. Any ideas how I could fix it?


text:
Q: Confusion understanding PHP namespaces I am learning about and implementing PHP namespaces.
Please refer to the following code:
<?php

namespace Xicor\core;

class App {

  public function __construct() {

    $registry = Registry::getInstance();

    //TODO: init router

    //TODO: call controller@action
    $controllerName = 'Xicor\app\controllers\\'.'Index';
    $action = 'show';

    $controller = new $controllerName();
    $controller->$action();

  }

}

The above code works perfectly.
If I add throw new Exception('Lorem Ipsum') within the constructor, I'll get an error as expected. To make it work, I must use throw new \Exception('Lorem Ipsum') so that we are referring to the global namespace.
But, why does
$controllerName = 'Xicor\app\controllers\\'.'Index'; successfully import the right class.
Why do I not have to use
$controllerName = '\Xicor\app\controllers\\'.'Index'; (with \ prefixed)?
If it affects anything, here's my autoloader:
<?php

spl_autoload_register(function($name) {
  //replace \ with DIRECTORY_SEPARATOR
  $path = str_replace('\\', DS, $name);
  //replace Xicor with root
  $path = str_replace('Xicor', __DIR__, $path); // __DIR__ doesn't return a trailing slash
  //add .php at end
  $path .= '.php';

  if(file_exists($path)) {
    require_once($path);
  }
});

A: As I understand it. PHP will work in the current namespace within a class unless specified otherwise (a preceding \).
Example
namespace Bar;

class Foo {
    function __construct()
    {
        // references current namespace, looks for Bar\Baz;
        $baz = new Baz();
    }
}

class Baz {
    function __construct()
    {
        try {
            // do stuff

            // references global namespace
        } catch(\Exception $e) {
            var_dump($e->getMessage());
        }

    }

    function foo() {

        // This will prepend the current namespace to the class, in actual fact it will first look for "Bar\Bar\Foo"
        // When it isnt found, it will move on and look at spl_autoload_register to try to resolve this class,
        // Failing that you will get a ClassNotFoundException
        $foo = new Bar\Foo();
    }
}

Please see. https://www.php.net/manual/en/language.namespaces.rules.php
and https://www.php.net/manual/en/language.namespaces.faq.php#language.namespaces.faq.full for reference


text:
Q: does adding setTimeout JavaScript/jQuery function help page load quicker Does the JavaScript below allow a webpage load quicker opposed to the a standard function or $(window).load(function(){ OR $(document).ready() if not is there a way to allow the page to load then run JavaScript ?
setTimeout(function(){
// JavaScript OR jQuery to execute
}, 5000);

A: Description
$(document).ready() Specify a function to execute when the DOM is fully loaded.
The function ensures that all html elements (DOM) is loaded. So it is not a good idea to use setTimeout because you cant know if the browser has built the DOM in this time.
You can put your JavaScriptat the end of your document to make sure the browser has built the DOM but thats not the way you should do that in case of using jQuery.
More Information
DOM means Document Object Model

The Document Object Model (DOM) is a cross-platform and language-independent convention for representing and interacting with objects in HTML, XHTML and XML documents. Aspects of the DOM (such as its "Elements") may be addressed and manipulated within the syntax of the programming language in use. The public interface of a DOM is specified in its application programming interface (API).

The following functions are the same (overloads) in jQuery.
$(function()
{
  // DOM is loaded
});

$(document).ready(functions() {
  // DOM is loaded
});

// this is the best way if you want prevent collisions with other JavaScript librarys
jQuery(document).ready(function($) {
  // DOM is loaded
});

- jQuery Documentation - .ready()
- Wikipedia - Document Object Model

A: First, place any JavaScript that is not essential to the construction of the page at the very bottom of the HTML before the closing </body> tag.  This includes any script tags that reference external .js files.
Next, if you are using jQuery (and I hope you are), then insert any JS logic you need into this method:
$(document)ready(function(){
     //do stuff
});

Last, for old school JS, you want to add this to your body tag:
onload="YourFunctionName()"

A: Unless you are doing some massive computation with the JS, then no. The majority of your "load" time is spent downloading the assets, not painting/rendering them on the page. If you had any code that sent out other httprequests (ajax), and those fired before the page was finished loading, you'd want to use an onload method somehow. Or just do as clyfe said and put it at the bottom.


text:
Q: How can we fetch top rated products as collections in magento I am looking to fetch top rated products as collections not as an array.
I have followed this tutorial :-
http://odino.org/retrieve-top-rated-products-in-magento/
But it's returning product array i need results as product collections.
I am using mentioned code:-
 $_productCollection = Mage::getResourceModel('reports/product_collection')
                   ->addAttributeToSelect('*')
                   ->setVisibility(array(2,3,4))
                   ->setPageSize($productCount);

$_productCollection->joinField('rating_summary', 'review/review_aggregate', 'rating_summary', 'entity_pk_value=entity_id',  array('entity_type' => 1, 'store_id' => Mage::app()->getStore()->getId()), 'left');
$_productCollection->setOrder('rating_summary', 'desc');

But the problems I am facing with this code is that it gives fatal error:
Call to member function getRatingSummary() on non object & page breaks here.
Any suggestions??

A: Try this:
$collection = Mage::getModel('catalog/product')->getCollection();

$collection->joinField('rating_summary', 'review/review_aggregate', 'rating_summary', 'entity_pk_value=entity_id',  array('entity_type' => 1, 'store_id' => Mage::app()->getStore()->getId()), 'left');
$collection->setOrder('rating_summary', 'desc')->setPage(1, 5);


text:
Q: Posicion de dato mayor dentro de una matriz filas = int(input("Introduce numero de filas: "))
columnas = int(input("Introduce numero de columnas: "))

matriz = []
for i in range(filas):
    matriz.append([0] * columnas)

for i in range(filas):
    for j in range(columnas):
        matriz[i][j] = int(input("Fila {}, columna {} : " .format(i+1, j+1)))

mayor = max(matriz)
print("El numero mayor de la matriz es: ")
print(mayor)
print("La matriz es:")
print(matriz)

Esto es lo que llevo, me muestra el dato mayor pero dentro de la matriz, y no muesta la posicion

A: La función max aplicada a una lista de listas retorna completa una de las sublistas, no el mayor valor escalar contenido en alguna de ellas.
>>>max([[1, 2], [3, 4]])
Out[8]: [3, 4]

La función index aplicada a una lista de listas retorna el índice de la sublista (retorna un entero, no un par de enteros):
>>>a = [[1, 2], [3, 4]]
>>>b = max(a)
>>>a.index(b)
Out[14]: 1

Por tanto, hay que recorrer trabajosamente la matriz buscando el mayor valor escalar y guardando los indices del valor encontrado.
La forma más rápida es hacer la busqueda junto con el ingreso;
cada vez que encuentra un valor mayor que el resto, anota fila y columna.
filas = int(input("Introduce numero de filas: "))
columnas = int(input("Introduce numero de columnas: "))

matriz = []
for i in range(filas):
    matriz.append([0] * columnas)

mayor = None  # Mayor valor encontrado hasta el momento.
fila = 0      # Fila de `mayor`
columna = 0   # Columna de `mayor`
for i in range(filas):
    for j in range(columnas):
        matriz[i][j] = int(input("Fila {}, columna {} : ".format(i + 1, j + 1)))
        if mayor is None: # Inicializamos mayor aqui.
            mayor = matriz[i][j] - 1
        if matriz[i][j] > mayor:
            mayor = matriz[i][j]
            fila = i
            columna = j

print("El numero mayor de la matriz es: ")
print(mayor)
print("Fila", fila + 1, ", columna", columna + 1)
print("La matriz es:")
print(matriz)

produce
Introduce numero de filas: 2
Introduce numero de columnas: 2
Fila 1, columna 1 : 0
Fila 1, columna 2 : 1
Fila 2, columna 1 : 2
Fila 2, columna 2 : 3
El numero mayor de la matriz es:
3
Fila 2 , columna 2
La matriz es:
[[0, 1], [2, 3]]


text:
Q: adb severe error in xubuntu OK I saw this has been asked a few times but it seems it was all for windows. I am trying to learn some android development with my xubuntu machine. But I am not a linux expert either...
After following along with a tutorial to set up Eclipse and Android SDK-linux I tried to get my first hello world to run and I got this:
    [2012-11-04 09:42:22 - xdasdka] ------------------------------
[2012-11-04 09:42:22 - xdasdka] Android Launch!
[2012-11-04 09:42:22 - xdasdka] The connection to adb is down, and a severe error has occured.
[2012-11-04 09:42:22 - xdasdka] You must restart adb and Eclipse.
[2012-11-04 09:42:22 - xdasdka] Please ensure that adb is correctly located at '/home/orange/code/android-sdk-linux/platform-tools/adb' and can be executed.

I have adb in the path listed. I have also cd to the directory and adb kill-server but it returns adb command not found. Just to make sure I also chmod +x adb and it still does not work.
I almost forgot to add I am on a 64bit machine.
Any ideas?


text:
Q: DEVICE_UNREGISTERED GCM nack message received Java Server is receiving DEVICE_UNREGISTERED GCM nack message when it is sending downstream message to iOS client. The same iOS client app was working earlier with development push certificate.
But now I have created iOS client build with in house enterprise certificate. This production app is able to send the upstream message to java server. However, when server try to send downstream message, server is getting DEVICE_UNREGISTERED nack message from GCM.
But our iOS client app is successfully registered and connected to GCM. It has also received the GCM registration token.
We have android client app.Downstream/upstream messages are working properly for android.
Any help is appreciated to resolve this issue..
GCM Request from the java server:
<message>
    <gcm xmlns='google:mobile:data'>{"to":"l9qEErT1AFE:APA91bEjR4R-eETscNQ7Nw-WeqAIzyisDsY79a_EkKhUACXGAzDoYnRyL7Ge6ca9MSfgZ-fGc7NDevTtI7NozOn126CN5AhpbaZDfuZoWFccqF2ibsdKptFGgxbZpIIK5eVK0DILrCsR","delivery_receipt_requested":true,"priority":"high","data":{"toolconfig":"{\n \"ecb\" : \"app.onNotificationGCM\",\n \"action\" : \"ping\",\n \"senderID\" : \"152585324066\"\n}","action":"com.XXX.XXX.XXXX.ECHO"},"notification":{"sound":"default"},"message_id":"1026274672"}</gcm>
</message>

NACK Response from the GCM:
<message>
    <gcm xmlns='google:mobile:data'>{"message_type":"nack","from":"l9qEErT1AFE:APA91bEjR4R-eETscNQ7Nw-WeqAIzyisDsY79a_EkKhUACXGAzDoYnRyL7Ge6ca9MSfgZ-fGc7NDevTtI7NozOn126CN5AhpbaZDfuZoWFccqF2ibsdKptFGgxbZpIIK5eVK0DILrCsR","message_id":"1026274672","error":"DEVICE_UNREGISTERED","error_description":""}</gcm>
</message>


text:
Q: Can't binding ObservableCollection to ListView on Xamarin Form so I get a problem a binding item to listview
Initialization page
public HomePage()
    {
        Acquaintances = Add();
        //InitializeToolbar();
        InitializeComponent();

    }
private ObservableCollection<Acquaintance> Add()
    {
        return new ObservableCollection<Acquaintance>()
        {

         new Acquaintance(){.....}

On XAML
<ListView x:Name="lstUser" BackgroundColor="White" ItemsSource="{Binding Acquaintances}">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <Grid>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="100"></ColumnDefinition>
                            <ColumnDefinition Width="*"></ColumnDefinition>
                        </Grid.ColumnDefinitions>

                        <Grid Grid.Column="0">
                            <ImageCell ImageSource="{Binding PhotoUrl}" Height="50"></ImageCell>

                        </Grid>

                        <StackLayout Grid.Column="1" Padding="5">

                        </StackLayout>

                    </Grid>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>

ListView can't be binding Acquaintances to items source of ListView. Where is wrong???
In Page:
public ObservableCollection<Acquaintance> Acquaintances { get; }

A: It seems you are forgetting to set the BindingContext property on your page. Without setting that property, the page does not know where to get data from.
To set your context to itself, do it like this:
public HomePage()
{
    Acquaintances = Add();
    //InitializeToolbar();
    InitializeComponent();

    BindingContext = this; // Note that I added this line
}

In the comments you are asking why it fails when you set BindingContext = Acquaintances; and why it works when you set BindingContext = this;.
It is simple, set the BindingContext to the object holding properties that you want to access. By setting the context to this, which is in this case HomePage, you can use bindings such as {Binding Acquaintances}. Because Acquaintances is a property of HomePage.
If you set the BindingContext to a specific property, which can also be a complex type but doesn't have to be, you change the scope. So when you set the BindingContext to Acquaintances, you will have to change the ItemsSource on your list to {Binding .}. The dot means that it will use the object in the BindingContext itself, not a property that is in it.


text:
Q: JSP values are not set to the backing bean I have a JSP page and its backing bean. Values entered on the page are not set to the backing bean.
Following is the sample code
JSP code

        Script Name:

        <h:inputText  id="name" value="#{AddScriptBean.name}" />

Backing bean code is
private String name;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

I guess the button I click to submit the page has something to do with it.
<h:commandButton immediate="true"  id="finishButton"  style="display:none;" action="#{AddScriptBean.finish}" >
    <f:verbatim><feat:Button label="Finish" onclick="submitFinishButton()"/>
    </f:verbatim>
</h:commandButton>

My faces-config.xml is as follows.
<navigation-rule>
    <from-view-id>/wizards/script/add_script_wizard_done.jsp</from-view-id>
    <navigation-case>
        <from-outcome>finish</from-outcome>
        <to-view-id>/ms/contract_delete_closer.jsp</to-view-id>
    </navigation-case>
</navigation-rule>

A: Its because you have given immediate="true" for command button. In that case updating bean values phase will be skipped. Go through this link for better understanding of JSF lifecycle


text:
Q: Lion Resume when Closing Docs without Quitting App I'm dipping my feet into Cocoa for the first time.
Here's a simple question. OS X Lion supports Resuming of window state when an app is terminated and relaunched. Okay, good and fine.
But for document-based apps, can the same Resume feature also manage saving of window state when a document is closed and reopened later but without any quitting of the app? (In other words, can it manage each file's state persistently regardless of whether the app quits or not? Or do I have to manage it myself by saving the information in the documents' files?)
For instance, iWork '09 apps do do this sort of thing: if you close a saved document and reopen it, it will restore the window size, location, and scroller position. I don't know if it does this using Lion's Resume per se.
But, in contrast, OS X Lion's TextEdit restores windows when it is quit and restarted, but it does not remember window states when you close a document and reopen it. This makes me suspicious that using Resume without quitting might not be possible automatically (since maybe Pages keeps window states in its proprietary file format, but TextEdit doesn't since it uses plain text, RTF, HTML, etc. files).

I don't have access to the WWDC 2011 videos yet, and neither the OS X release notes, the OS X Application Programming Guide, nor the NSWindowRestoration API docs talk about this specifically.
So the question again: automatically remembering the state of a document window after closing and reopening it without quitting the app (like iWork does)...does Lion's Restore support this?
Thanks a lot!

A:
But for document-based apps, can the same Resume feature also manage saving of window state when a document is closed and reopened later but without any quitting of the app? (In other words, can it manage each file's state persistently regardless of whether the app quits or not?

Not unassisted, no.

Or do I have to manage it myself by saving the information in the documents' files?)

Or somewhere else, yes.
My untested suggestion is to try using the window-restoration protocol yourself. When closing, send yourself encodeRestorableStateWithCoder:, then stash that data in your document (or wherever you want). When opening a document, if it has restorable state information, pass it to restoreStateWithCoder:.


text:
Q: How to load elements in Heroku Static Web HTML Hosting? I just started doing web development, and using bootstrap from here:
https://startbootstrap.com/template-overviews/clean-blog/
I changed around some padding, font, elements, etc, but overall, I kept to the same format as from the bootstrap code.
Everything looks good locally (running index.html) but I want to host it. But since my application isn't ruby or php web app that Heroku supports, I tried to do a hack I read about by making an index.php and composer.json and pushing my code to Heroku.
Everything seems to be pushed fine to Heroku, but when I check my Heroku app, it looks like a mess, the nav bar is "invisible" to the top left and unclickable (checked location with Firefox console) and some formatting is off.
How do I get the elements to load properly?

A: Heroku isn't really designed to do static hosting. I downloaded the bootstrap code and tested it and the nav bar and bootstrap elements are missing for the most part.
With that said I believe that Heroku is having troubles loading certain css/ scss resources that need to be preloaded, you may need to convert the entire project or try using a script to make gulp work in composer.json and editing your procfile to different host since I assume you are using default heroku-php-apache2.


text:
Q: jQuery DataTables with Node.js So i am trying to implement a pagination table with the datatables plugin, this is my first time using this plugin. I followed the documentation on the plugin and tried to get the values from the server through the use of Ajax, as per presented in the plugins documentation.
I seem to be getting the following error once i make the get request and i am unsure of why?
Error: Uncaught TypeError: Cannot read property 'length' of undefined
On client side i have the following code
viewReports = {
    init: function(){
        $('#paginatedData').DataTable({
            "processing": true,
            "serverSide": true,
            "ajax": '/viewreports'
        });

    }
};

$(document).ready(viewReports.init);

In my server side i have the following
router.get('/viewreports', function(res, req){

    async.parallel({
        viewReports: function(callback){
            restCall('/rest/bugbounty/latest/message/searchReport', 'POST', parameters, function(data){
                callback(null, data);
            });
        }
    }, function(err, result){
        if(!err){
            res.send(result.viewReports);
            res.render('viewreports');
        }
    });
});

Returned JSON:

{ reportList: [ { reportID: 'EIBBP-448', eBayUserID: ' ', reportStatus: 'New', summary: 'BugBounty Report created by Raj', lastUpdatedDate: '2015-06-15 01:05', createdDate: '2015-06-15 01:05', paypalLoginID: 'raaj@paypal.com' } ], searchStatus: 'Success', eBayUserID: '', errorCode: '0', rowCount: '6', pageNumber: '1', paginationValue: '1', paypalLoginID: 'raaj@paypal.com' }

It would be great to know if there is anyone who has worked with node.js server side processing for datatables

A: You need to define dataSrc and columns.data - the following should work :
var table = $('#example').DataTable({
    processing: true,
    serverSide: true,
    ajax: {
        url: "/viewreports",
        dataSrc: "reportList"
    },
    columns: [
        { data : "reportID" },
        { data : "eBayUserID" },
        { data : "reportStatus" },
        { data : "summary" },
        { data : "lastUpdatedDate" },
        { data : "createdDate" },
        { data : "paypalLoginID" }
   ]
});

on an empty table :

*

*dataSrc to specify what the array holding row items is named (cause of "Cannot read property 'length' of undefined")

*columns.data to map item properties to columns

A: You simply don't have to bother with the server side processing.
I used a simple way to trick dataTables initialization.
First, you will need to fetch the data you want to display in the table through your most preferred way, after you have confirm that data displays well, now head to where you initialize dataTables and make it so that it delays before initialization.
setTimeout(() => {
    $('#yourtable').dataTable({
        // datatables customization options
    });
}, 100)

For example, in my case I gave it a delay of 100ms, and it works like a charm.


text:
Q: WPF - Instance subclass from superclass I'm doing and WPF application and I have a ViewModel that I use in several Views and in DataGrids.
Now I have another View that requires an extended or decorated version of that ViewModel. So I decided to go for inheritance in this way:
public class StandardViewModel
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

public class ExtendedViewModel : StandardViewModel
{
    public string Email { get; set; }
}

However, I want to decorate and existing instance of the StandardViewModel. Specifically the selected object in the DataGrid so it can be passed into the other View.
The new View needs access to the properties of both classes (the Email and the FirtsName and LastName)
So I'm thinking of ways to creating a constructor for my ExtendedViewModel.
My idea is to copy the base instance directly.

*

*Is this correct?

*And efficient?

*Is there any other way of doing it?

public class ExtendedViewModel : StandardViewModel
{
    public string Email { get; set; }

    public ExtendedViewModel(StandardViewModel base)
    {
        this = base
    }
}

Edit
I'm doing this for not only one but several classes. And they do not have only two properties so I'm trying to avoid copying the values one by one.

A: Finally I'll avoid using inheritance and I'll create a new class, expose the base class and subscribe to INotifyPropertyChanged as described here and here.
This way I'll be able to have properties that depend on the Base ViewModel updated as done with FullName below.
The resulting ViewModel will look like:
public class ExtendedViewModel
{
    public StandardViewModel Base { get; set; }
    public string Email { get; set; }

    public string FullName {
        get => Base.FirstName + Base.LastName;
    }

    public ExtendedViewModel(StandardViewModel base)
    {
        Base = base
        Base.PropertyChanged += BaseChanged
    }

    private void BaseChanged(object sender, PropertyChangedEventArgs e)
    {
        // Here check if FirstName or LastName changed and
        RaisePropertyChanged("FullName");
    }
}

In the view I will bind directly to Email or to Base.FirstName.

A: In oversimplified terms a decorator owns an instance of the class it decorates and delegates functionality existing in the owned class to that class, while adding new functionality uncoupled from the owned class instance.
public class StandardViewModel
{
    public virtual string FirstName { get; set; }
    public virtual string LastName { get; set; }
}

public class ExtendedViewModel : StandardViewModel
{
    private StandardViewModel _standard;
    public ExtendedViewModel (StandardViewModel standard)
    {
         if (standard.GetType() != typeof(StandardViewModel )) {
            throw new ArgumentException ("Expected a non derived standard view model", nameof(standard));
         }
        _standard = standard;
    }
    public string Email { get; set; }
    public override string FirstName {
        get => _standard.Firstname;
        set  => _standard.Firstname = value;
    }
    public override string LastName {
        get => _standard.LastName;
        set  => _standard.LastName = value;
    }

}


text:
Q: How to handle new tab in cypress .If sub domain is dynamic? URL:-   https://localhost:8008/
Sub domain URL:  https://localhost:8008/datasearch?actionId=772675
I am not able handle new tab in cypress as cy.visit('https://localhost:8008/datasearch?actionId=772675')  as action id keeps on changing after entering data and click on submit button.As subdomain opens on new tab.I need to check the assert the output that is opening in new tab.
Regards
Kushal

A: I assume in your case if your submit button is inside an 'a' tag, then you could do something like this. If you click the Submit button, then it will open as a new tab, so ideally you should be getting the link from the 'a' tag or submit button prior to click and pass to a const and use cy.visit()
context('Open as new tab in cypress', () => {
        it('Test to open a new tab/subdomain in cypress', () => {
          cy.visit('https://localhost:8008/');
          cy.get('.mt-2 > .btn-primary').then(($ele)=>{   // if the button is in an '<a>' tag, you could grab something like this
            const newUrl =  Cypress.$($ele).attr('href');
            cy.visit(newUrl);
          })
        })
    })


text:
Q: Disable file cache for mount point I ran into a bug similar to this one:
RHEL NFS client returns NULL bytes when reading a growing file
So my solution was to check for \0 Bytes and reread the file. Problem here is, that the wrong file, which includes the \0 Bytes, is cached on the system where the java application runs. So it takes quite a while to read the correct file contents.
When I do a sync && echo 2 > /proc/sys/vm/drop_caches it immediately reads the correct content.
I tried to add sync to the NFS mount options without a difference.
Is it possible to disable the file cache for a specific mount point? If so, how to do that?

A:
Resolution
This issue was discussed with Red Hat Engineering under Private Bug 702085, but was not able to be repaired within the RHEL 5 product lifecycle.
Red Hat Product Management have elected not to repair this issue within RHEL 6 for the following reasons:

*

*Customer exposure to this issue is not significant.

*This behaviour is documented on the Customer Portal along with workarounds.

*This behaviour is much harder (takes longer) to reproduce in RHEL 6 compared to RHEL 5.

*The NFS protocol does not guarantee cache coherence.

  Workarounds:

*

*Ensure one client cannot read a file while another client is accessing it by using file locks, such as flock in shell scripts, or fcntl() in C.

*Open the file with O_DIRECT so that the page cache is avoided.

*Do not read past the EOF.

*For example, in Python use os.stat() to get the file size, os.open() to open the file and os.read() to read only up to the file size.

*Avoid running tail -f on files residing on NFS mounts.

*If using RHEL 5, the sync mount option will also avoid this issue. This will not work in RHEL6, as the nfs_readpage_sync() function was removed upstream in between RHEL 5 and RHEL 6, so that function does not exist in RHEL 6.


text:
Q: What is the reason for checking for nullity twice when synchronizing lazy initialization? I came across a lazy initialization method which checks for nullity twice, before and after applying the lock. Code goes like this,
public void initializeTemplate(){
   if(tmeplate == null){
      synchronized(this){
         if(template == null){
              //initialization is done here!
         }
      }
   }
}

I was wondering what could be the reason behind checking for nullity twice? In my understanding checking before applying the lock would have sufficed, right? or am i wrong? Can anyone explain?

A: A null check is cheap, where as synchronized is not, BUT, some other thread might have beaten you to the initialisation of the object between the first null check and the synchronized block, so you check once out side (cheap) and once instead as a precaution.
This is basically trapping a race condition, where two threads pass through the outer check, one thread will block waiting for the synchronized block to provide it the lock, while the other passes through (having secured the lock), creating an instance of the object and assigning the value to template.  When it exists, the waiting thread will then have a chance to execute the code within the synchronized block, but you do a second null check to make sure you're not doing work which has already been done and breaking the single instance requirements and preventing possible reference issues

A: It is called Double-checked locking. This Wikipedia article explains it in detail.
To explain it briefly, obtaining a lock is an expensive operation, in this example it is most probably used to initialize a singleton Class in a multi threaded environment.
The first if statement checks if the object is null, if the object is not null there is no need to obtain a lock to make sure that no other Thread have initialized the Object, since the object is already initialized. However, if the object is null, the Thread has to obtain a lock on the block to make sure that no other Thread is trying to initialize the Object.
The Double-checked locking is considered "broken".


text:
Q: Retroactivly add "am" or "pm" to an excel column I have a column in excel that is a bunch of times something was done. I didn't put AM or PM, but I know every time the actions were done it was between 6am and 5pm. How would I make a formula that takes the whole column, figures out if its am or pm, then puts that on the end of the times?
A small part of the mentioned column

A: From your statement, you will NOT have any AM times that start with 1-5, or any PM times that start with 6 or above hours.  If this is indeed the case, insert a cheater column. In the top row, =IF(AND(HOUR(A1)>=1,HOUR(A1)<=5),A1+0.5,A1)  (obviously edit for the appropriate column the data is in).  Change the format on the new column to Number/Time/1:30 PM.  Then copy, paste values the new column.


text:
Q: Example of Terms of Services for Agile contracting? In my experience as a freelance developper, I've had some difficulties with clients, whom insist on getting an estimate over flimsy requirements. They then expect me to deal with requirements changes, sometimes late in the project, and stick to that estimate.
Since I've never come up myself with some T.O.S. tailored for this situation, I ended up bound by a contract of a more general nature, which inevitably became unsasatisfactory...
Legal lingo not being my forte, I've been lookin for some publicly released T.O.S. to try to remedy this situation. Ideally these would be from an agile shop, under a licensing scheme allowing derivatives. This would help me lay out the contractual groundwork for a sane customer relationship, especially when dealing with changes.

A: Clients wanting you to be agile sounds more like clients that just want to change their mind (which is fine).
It seems like instead of:

*

*Get requirements

*Sign the contract with Julien to deliver X for $Y.

*Julien delivers X

*Julien gets paid Y

They want:

*

*Get very, very vague requirements

*Sign the contract with julien to deliver whatever they want (X? Y? X+Y? Z??), which is undetermined, and pay Julien $Y.

*Julien works toward ever-changing requirements.

*Requirements are never met.

*Julien never gets paid because they are never satisfied.

In this case I would simply charge per-hour.
Don't worry about fixed price or an "agile" contract.  If you try to re-contract for every change, it will eventually become more pain than it is worth.  Your best bet here would be to have a per-hour charge, and have them sign off on timesheets you provide on a per-week or something similar basis.  This way both you and they can be as agile as needed while you have a better guarantee of getting paid.  Just do great work and any good client will see your value.  If not, you're better off just passing on the particular client if you have the opportunity.
For a more Agile approach..
You could, essentially, have a shorter estimate contract per-iteration.  Each 2-week (or whatever time) iteration that you plan, have a shorter contract/amendment that outlines the requirements and estimates just for that iteration.  Let the client change requirements, but only give them that luxury at the end of each iteration when you do the planning for the next iteration.

A: Agile Team & Fixed Price Contract: http://www.infoq.com/articles/agile-team-fixed-price-contract

Fixed price contracts are evil - this is what can often be heard from agilists. On the other hand those contracts are reality which many agile teams have to face. But what if we try to tame it instead of fighting against it? How can a company execute this kind of contract using agile practices to achieve better results with lower risk? This article will try to answer those questions.

A: At a previous company that I worked for, we ran into this issue when delivering websites with lots of custom functionality. It sounds to me like you're suffering from client based scope-creep.
To handle this, we started aligning our own personal development benchmark with sample deliverable benchmarks to make sure that the client was satisfied with the way things were progressing. In addition, as Chris mentions in his post, contracts / T.O.S documents were written up and signed in person that explicitly stated what was included with each project and divided up into a per-benchmark basis. Each item was listed out with what it did and did not do, to the best of our abilities without being clairvoyant.
Be upfront about your charges and let them know what an initial estimate would be (which is your responsibility) but also give them the "additional rate", whether you determine it to be hourly or contract additions. When they start scope-creeping you, you can fall back to the initial contract which has that laid out and simply state your new estimate.
To summarize: All functionality described in contract, supply benchmark samples when applicable and get sign-offs on those too, be up front about additional rates for scope creep items.


text:
Q: Remove back arrow in iOS7
I want to incorporate a custom back button - I'm able to get the above result using
self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back-btn"] style:UIBarButtonItemStylePlain target:nil action:nil];

but how do you remove the native blue button?

A: In iOS7+ you can use navigationBar's backIndicatorImage and backIndicatorTransitionMaskImage to achieve the custom arrow that you want. Swift code below:
self.navigationController?.navigationBar.backIndicatorImage = UIImage(named:"button-backArrow18x15")
self.navigationController?.navigationBar.backIndicatorTransitionMaskImage = UIImage(named:"button-backArrowMask18x15")

If you want to hide the "back" text you can set the title of the previous view to be an single space " " or use a custom UIBarButtonItem that doesn't have a title.

A: You can hide backbutton
 self.navigationItem.hidesBackButton=YES;

To create custom leftbarbutton you can use this:
UIButton* someButton = [UIButton buttonWithType:UIButtonTypeCustom];
[someButton setFrame:frame];
[someButton setBackgroundImage:@"youArroImageName" forState:UIControlStateNormal];
[someButton addTarget:self action:@selector(backButtonAction:) forControlEvents:UIControlEventTouchUpInside];
[someButton setShowsTouchWhenHighlighted:YES];
UIBarButtonItem* someBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:someButton];
[self.navigationItem setLeftBarButtonItem:someBarButtonItem];

A: Check this one:
    UIImage *faceImage = [UIImage imageNamed:@"back_arrow.png"];
    UIButton *face = [UIButton buttonWithType:UIButtonTypeCustom];
    face.bounds = CGRectMake( 10, 0, faceImage.size.width, faceImage.size.height );
    [face addTarget:self action:@selector(handleBack:) forControlEvents:UIControlEventTouchUpInside];
    [face setImage:faceImage forState:UIControlStateNormal];
    UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithCustomView:face];
    self.navigationItem.leftBarButtonItem = backButton;
    [self.navigationItem setHidesBackButton:YES animated:YES];
    [self.navigationItem setBackBarButtonItem:nil];

  -(IBAction)handleBack:(id)sender
  {
     //    [self dismissViewControllerAnimated:YES completion:nil];
     [self.navigationController popViewControllerAnimated:YES];
  }

A: Thanks to all the answerers - found a simpler way of doing it...
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back-btn"] style:UIBarButtonItemStylePlain target:self action:@selector(backButtonAction:)];
self.navigationItem.leftBarButtonItem.tintColor = [UIColor whiteColor];

[self.navigationItem setHidesBackButton:YES animated:NO];
[self.navigationItem setBackBarButtonItem:nil];

-(void) backButtonAction:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

A: Use the below code to hide the back arrow:
self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back-btn"]
                                                                         style:UIBarButtonItemStylePlain
                                                                        target:nil
                                                                        action:nil];

if ([UINavigationBar instancesRespondToSelector:@selector(setBackIndicatorImage:)]) {
    [[UINavigationBar appearance] setBackIndicatorImage:[[UIImage alloc] init]];
    [[UINavigationBar appearance] setBackIndicatorTransitionMaskImage:[[UIImage alloc] init]];
}

A: Swift 4 (if you just want to hide it)
let mask = UIImage()
navigationController?.navigationBar.backIndicatorImage = mask
navigationController?.navigationBar.backIndicatorTransitionMaskImage = mask

A: Why can't you try with the Custom UIButton :
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setFrame:CGRectMake(0.0f, 0.0f, 25.0f, 40.0f)];
    [btn addTarget:self action:@selector(buttonEN:) forControlEvents:UIControlEventTouchUpInside];
    [btn setImage:[UIImage imageNamed:@"back-btn"] forState:UIControlStateNormal];
    UIBarButtonItem *backBtn = [[UIBarButtonItem alloc] initWithCustomView:btn];
    self.navigationItem.backBarButtonItem = backBtn;

A: I just faced the exact same problem, here's what I ended up doing:
// First set the back button text to an empty string
viewController.navigationItem.backBarButtonItem =
     [[UIBarButtonItem alloc] initWithTitle:@""
          style:UIBarButtonItemStylePlain
          target:nil
          action:nil];

// Set the back-indicator image to the custom image (scaled to 20x20)
UIImage *img = [MyUtils imageWithImage:[UIImage imageNamed:@"back"] scaledToSize:CGSizeMake(20, 20)];
[[UINavigationBar appearance] setBackIndicatorImage:img];
[[UINavigationBar appearance] setBackIndicatorTransitionMaskImage:img];

// Set the tint color to WHITE
[[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];

Here's the image-scaling method:
+ (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize {
    UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);
    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

Credit for the scaling method above goes to Paul Lynch on this SO question: (The simplest way to resize an UIImage?)


text:
Q: React component test case coverage of inline functions Can someone help me cover this test case, I am not able to figure out how to cover this inline function
Note: DropdownField is a wrapper component and contains the actual which is imported from
import { Field } from "redux-form";
dropdown input inside
I have tried to call mockfunction and jest.fn() but nothing works, Any help will be appreciated because I am totally blank at the moment. Thanks in advance to all the wonderful devs
import React from "react";
import DropdownField from "components/FormFields/DropdownField";
import get from "lodash/get";

const AddressLookup = props => {
  const {
    change,
    formValues,
    fetchAddressLookup,
    postalCodeOptions,
    type = "delivery",
    placeholder = "type_to_search",
    field
  } = props;
  const selectedDeliveryMethod = get(formValues, "delivery_method", {});

  return (
    <DropdownField
      placeholder={placeholder}
      options={postalCodeOptions}
      {...selectedDeliveryMethod.fields.zip_code}
      isSearchable={true}
      field={field}
      onInputChange={value => {
        if (value.length >= 2) fetchAddressLookup({ q: value });
      }}
      onChange={({ value }) => {
        const [city, state, zipCode] = value.split("-");
        change(field, value);
        change(`${type}_state`, state);
        change(`${type}_city`, city);
        change(`${type}_zip_code`, zipCode);
      }}
    />
  );
};

export default AddressLookup;

I have tried this approach but It failed to cover. First test case covers the UI part only as you can see it is matching to snapshot. In second test cases I removed some code and commented some because nothing works
import * as React from 'react';
import { render, fireEvent, wait } from '@testing-library/react';
import { IntlProvider } from 'react-intl';
import { Provider } from 'react-redux';
import { reduxForm } from 'redux-form';
import configureStore from 'redux-mock-store';

import messages from '__fixtures__/messages.json';
import AddressLookup from '../index';

const DecoratedAddressLookup = reduxForm({ form: 'testForm' })(AddressLookup);

const testProps = {
  change: jest.fn(),
  fetchAddressLookup: jest.fn(),
  postalCodeOptions: [
    {
      name: 'abc-abcd-1234',
      value: 'abc-abcd-1234',
    },
  ],
  formValues: {
    delivery_method: {
      fields: {
        zip_code: 'BD-BDBD-1234',
      },
    },
  },
  field: 'zip_code',
};

describe('<AddressLookup />', () => {
  let testStore;
  let addressField;
  const mockStore = configureStore([]);
  const store = mockStore({});
  const spy = jest.fn();

  beforeAll(() => {
    testStore = store;
  });

  const renderComponent = () => {
    return render(
      <Provider store={testStore}>
        <IntlProvider locale='en' messages={messages}>
          <DecoratedAddressLookup
            {...testProps}
            onInputChange={spy}
            onChange={spy}
          />
        </IntlProvider>
      </Provider>
    );
  };

  it('should render and match the snapshot', () => {
    const {
      getByTestId,
      container: { firstChild },
    } = renderComponent();

    addressField = getByTestId('zip_code');

    expect(firstChild).toMatchSnapshot();
  });

  it('should type a value', async () => {
    addressField = addressField.querySelector('input');
    // expect(addressField).toBeTruthy();
    // console.log('addressField', addressField);
    // const input = screen.getByTestId('add-word-input');
    fireEvent.change(addressField, { target: { value: 'abc-abcd-1234' } });
    expect(addressField).toHaveValue('abc-abcd-1234');
    // expect(testProps.change).toBeCalled();
    await wait(() => {
      expect(spy).toHaveBeenCalledTimes(1);
    });
  });
});


text:
Q: Dependent variable functionally related to independent variable My question pertains to the case where a dependent variable is functionally related to an independent variable in a multiple linear regression. Here is a fictional scenario suppose that $Sales_A,Sales_B,Sales_C,Sales_D,Sales_E$ represent the sales  resulting from products A,B,C,D,E
and Total Sales = $Sales_A +Sales_B +Sales_C + Sales_D + Sales_E$.   Consider the following model:
$$Sales_D = Sales_I + Total Sales + \text{other control variables}$$
Assuming the assumptions for linear regression are met and there is no multicollinearity between the independent variables. If the goal is to determine how increases in $Sales_I$  effect changes in $Sales_D$ would the above model work or does the fact that the dependent variable is "part" of one of the independent variables cause problems?

A: I don't see an issue as formulated it looks like the model would look at how additional sales from product I are cannibalizing or complementing sales from product D assuming observations are stores  or something similar. Others more well informed in statistics may be able to pinpoint where the model is incorrect.


text:
Q: python how to change the global variables I would like to get some kind of confirmation that the upload is success, I have my methods defined similar to the following. However the value of global variable is not changing. Please help
global upload_confirm
upload_confirm = False

def confirm_upload():
    upload_confirm = True

def start_new_upload():
    confirm_upload()
    while (upload_confirm != True):
        print "waiting for upload to be true"
        time.sleep(5)
    if (upload_confirm == True):
        print "start Upload"

start_new_upload()

A: You could try this:
def confirm_upload():
    global upload_confirm
    upload_confirm = True

Since you are doing upload_confirm = True in a local scope, Python treat it like a local variable. Hence, your global variable stays the same.

A: You need to put the global statement in that scope where you want to access the global variable, i.e.:
upload_confirm = False

def confirm_upload():
    global upload_confirm
    upload_confirm = True

A: Try this inside your confirm_upload() method.
def confirm_upload():
    global upload_confirm #Add this line
    upload_confirm = True

You need to declare it as global inside methods else it will be by default local.

A: global statement should be inside the function.
def confirm_upload():
    global upload_confirm
    upload_confirm = True

Otherwise, upload_confirm = .. will create a local variable.


text:
Q: Is there an xhtml.xsd equivalent available for HTML5? I am developing an appplication based on Mozilla XULRunner.
I am using the xhmtl1-strict.xsd provided by the W3C to fetch the attribute. Now the requirement came to add the <video> tag to my application, but my application is not supporting any HTML5 elements or attributes.
So, any suggestions?

A: HTML5 does not have a doctype definition or an XML schema definition. This is because, although it shares the same syntax as its predecessor HTML 4, HTML5 itself is neither based on SGML nor XML. It's a markup language in its own right.
If you are looking to implement a browser with HTML5 capabilities using Mozilla technologies, the latest version of the Gecko layout engine supports HTML5. Get the Gecko/XULRunner SDK here.

A: The packages at http://www.xmlmind.com/xmleditor/download.shtml contain a file addon/config/xhtml/xsd/5.0/xhtml5.xsd which seems to be licensed as open source .

A: There is an HTML5 DTD which is used in the XML Catalog of Komodo, which is an XULRunner application. It can also be used in Eclipse without being converted to an XSD. In addition, there are style sheet and regex based DTD2XSD converters available.

A: To validate XHTML5, use the schema from v.Nu.
For details, see:
https://github.com/unsoup/validator


text:
Q: What is the best practice to use when using PHP and HTML? I have been designing websites for a while now, but there is one thing that I have never been quite sure of when using PHP and HTML. Is it better to have the whole document in PHP and echo HTML like so:
<?php
  doSomething();
  echo "
Content
";
?>

Or have a HTML file like so and just add in the PHP:

  <?php doSomething(); ?>

Content

It seems tidier to echo HTML, especially if lots of PHP gets used throughout the page, but doing so loses all formatting of the HTML i.e. colors in the IDE etc.

A: The syntax highlighting is an important benefit of the second method, as you said. But also, if you're following good practices where logic and presentation are separated, you will naturally find that your files that contain HTML are almost entirely HTML, which then, naturally, leads to your second method again. This is the standard for MVC frameworks and the like. You'll have a bunch of files that are all PHP, doing logic, and then when that's done they'll include a presentation file which is mostly HTML with a sprinkling of PHP.

A: Simple:
More PHP - close HTML in PHP. When you generate HTML code in PHP, when you are doing something like a class, so it is better to make it in echo.
Less PHP - close PHP in HTML. This is stuff like just putting vars into fields of HTML stuff, like forms... And such.

A: The best approach is to separate the HTML from the PHP using template system or at least some kind of HTML skeleton like:

    <top-nav/>
    <left-col>

    </left-col>
    <right-col />

Each node represents a template file e.g. main.php, hrader.php and so on. Than you have to separate the PHP code from the templates as something like functions.php and fineally use your second approach for template files and keeping functions clean of "echos" and HTML.

A: There are varying opinions on this. I think there are two good ways:

*

*Use a templating engine like Smarty that completely separates code and presentation.

*Use your second example, but when mixing PHP into HTML, only output variables. Do all the code logic in one block before outputting anything, or a separate file. Like so:
<?php $content = doSomething();
   // complex calculations
?>

  <?php echo $content; ?>

Content

Most full-fledged application frameworks bring their own styles of doing this; in that case, it's usually best to follow the style provided.

A: If you can, use a template engine instead.
Although it is slightly easier at first to mix your HTML and PHP, separating them makes things much easier to maintain later on.
I would recommend checking out TemplateLite which is based on Smarty but is a little more light weight.

A: I think this would depend on your group's or your own decided convention. And it can and should vary depending on what type of file you're working in. If you follow the MVC pattern then your views should be the latter. If you're writing a class or some non-output script/code then you should use the former.
Try to keep a separation of display or formatting of output and the logic that provides the data. For instance let's say you need to make a quick page that runs a simple query and outputs some data. In this case (where there is no other existing infrastructure or framework) you could place the logic in an include or in the top or the bottom of the file. Example:
<?php
  # define some functions here that provide data in a raw format
?>

  <?php foreach($foo = data_function($some_parameter) as $key => $value): ?>

    <?=$value;?>

  <?php endforeach; ?>

Or you could place the logic and function definitions in an include file or at the bottom of the file.
Now if you're producing some sort of class that has output (it really shouldn't) then you would echo the HTML or return it from the method being called. Preferably return it so that it can be output whenever and however the implementer would like.

A: I've reached a conclusion that using views in MVC framework e.g. Laravel, Yii, CodeIgniter is the best approach even if you are not displaying the html straight away.
Inside the view do all the echoing and looping of prepared variables, don't create or call functions there, unless formatting existing data e.g. date to specific format date('Y-m-d', strtodate(123456789)). It should be used only for creating HTML, not processing it. That's what frameworks have controllers for.
If using plain PHP, create you own view function to pass 3 variables to - html file, array of variables, and if you want to get output as string or print it straight away for the browser. I don't find a need for it as using frameworks is pretty much a standard. (I might improve the answer in the future by creating the function to get view generated HTML) Please see added edit below as a sample.
Frameworks allow you to get the HTML of the view instead of displaying it. So if you need to generate separate tables or other elements, pass the variables to a view, and return HTML.
Different fremeworks may use various type of templating languages e.g. blade. They help formatting the data, and essentially make templates easier to work with. It's also not necessary to use them for displaying data, or if forced to use it by the framework, just do required processing before posting the variables, and just "print" it using something like {{ yourVariable }} or {{ yourVariable.someProperty }}
Edit: here's a plain PHP (not framework PHP) - simple-php-view repository as a sample view library that allows to generate HTML using variables. Could be suitable for school/university projects or such where frameworks may not be allowed.
The repository allows to generate HTML at any time by calling a function and passing required variables to it, similar to frameworks. Separately generated HTML can then be combined by another view.

A: It depends on the context.  If you are outputting a lot of HTML with attributes, you're going to get sick of escaping the quotation marks in PHP strings.  However, there is no need to use ?>
<? instead of echo "
"; either.  It's really just a matter of personal taste.

A: The second method is what I usually use. And it was the default method for me too. It is just to handy to get php to work inside html rather than echo out the html code. But I had to modify the httpd.conf file as my server just commented out the php code.


text:
Q: Scenario that requires to remove or by-pass the filestream's cache/buffer? I am writing a small utility for securely erasing files. Currently, I propose two wipe schemes: random (fill files with garbage data then wipe) and zeroes (fill files with zeroes then wipe). I will add more schemes later.
There is the source code of the method (inspired by this project):
public void WipeFile(string filename, int timesToWrite, WipeScheme scheme)
{
    try
    {
        if (File.Exists(filename))
        {
            // Set the files attributes to normal in case it's read-only.
            File.SetAttributes(filename, FileAttributes.Normal);

            // Calculate the total number of sectors in the file.
            double sectors = Math.Ceiling(new FileInfo(filename).Length / (double)SectorSize);

            // Create a dummy-buffer the size of a sector.
            byte[] dummyBuffer = new byte[SectorSize];

            if (scheme == WipeScheme.Zeroes)
            {
                Array.Clear(dummyBuffer, 0, dummyBuffer.Length);
            }

            // Create a cryptographic Random Number Generator.
            // This is what I use to create the garbage data.
            RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();

            // Open a FileStream to the file.
            using (FileStream inputStream = new FileStream(filename, FileMode.Open))
            {
                for (int currentPass = 0; currentPass < timesToWrite; currentPass++)
                {
                    // Go to the beginning of the stream
                    inputStream.Position = 0;

                    // Loop all sectors
                    for (long sectorsWritten = 0; sectorsWritten < sectors; sectorsWritten++)
                    {
                        if (scheme == WipeScheme.Random)
                        {
                            // Fill the dummy-buffer with random data
                            rng.GetBytes(dummyBuffer);
                        }

                        // Write it to the stream
                        inputStream.Write(dummyBuffer, 0, dummyBuffer.Length);
                    }
                }

                // Truncate the file to 0 bytes.
                // This will hide the original file-length if you try to recover the file.
                inputStream.SetLength(0);

                // Flush the stream.
                inputStream.Flush();
            }

            // As an extra precaution I change the dates of the file so the
            // original dates are hidden if you try to recover the file.
            DateTime dt = new DateTime(1901, 1, 1, 0, 0, 0);
            File.SetCreationTime(filename, dt);
            File.SetLastAccessTime(filename, dt);
            File.SetLastWriteTime(filename, dt);

            // Finally, delete the file
            File.Delete(filename);
        }
    }
    catch (Exception e)
    {
        // TODO
    }
}

The program seems to work fine, but I notice strange results when I do benchmark (I test on an external HDD, multiple times with a file that weights 592 MB):

*

*Wipe with random data: about 7 seconds to wipe, equals write speed of 85 MB/s, seems OK.

*Wipe with zeroes data: about 500 ms to wipe, equals write speed of 1.2 GB/s! What? Impossible!

The last result is very curious, so I decide to disable the deletion from the disk to test if at least the writing is done correctly. For this, I comment inputStream.SetLength(0); and File.Delete(filename);.
Now, the results are following:

*

*Wipe with random data: about 9 seconds to wipe, equals write speed of 67 MB/s. Hm, a little bit slow, but OK because it uses RNGCryptoServiceProvider after all (which is slow).

*Wipe with zeroes data: about 7 seconds to wipe, equals write speed of 85 MB/s. Better than previous and more realistic!

Here's what I think: the writes are first done in a buffer in memory. Then, the buffer is written (flush) on the disk. This is explain why write only zeroes is faster than write garbage data: get random values is very slow. So much so that the buffer has time to be flushed to disk.
But when I delete the file right after, the file is simply deleted from the disk and the buffer (or part of it) is NOT flushed! Why? This is not useful because the file is deleted, or the buffer has not time to be flushed. I don't know.
So, what can I do? Is it possible and adequate here to disable all the cache? Or should I call Flush() in each iteration?
Oh and I give priority to safety over speed!

A: Remove
inputStream.SetLength(0);

from your code.
Probably you have to open the file  a second time (after overwriting) to set its size to zero.


text:
Q: Reversing an array using a stack I am attempting to reverse an array using a stack. However, I get an error on arr[i] = stack.top();, and the suggestion to resolve it in Eclipse is to change it to arr[i] = stack.pop(); or to add a cast. Is there another way about this or have I made a mistake?
I see tutorials and questions asking about how to reverse a string using a stack and I have tried to reverse an array using the same logic, but I'm not entirely sure where I'm going wrong.
public static void reverse(String[] arr){

    Stack stack = new Stack();

    for(int i = 0; i < arr.length; i++) {
        stack.push(arr[i]);

    }
    for(int i = 0; i < arr.length; i++) {
        arr[i] = stack.top();
        stack.pop();
    }
    return;
}

A: When you pop the stack, it returns the object at the top and removes it from the stack. Try this:
public static void reverse(String[] arr){

    Stack stack = new Stack();

    for(int i = 0; i < arr.length; i++) {
        stack.push(arr[i]);

    }
     for(int i = 0; i <arr.length;i++) {

         arr[i] = stack.pop();
     }
}

A: Method top doesn't exist in the Stack of Java. The similar method you're looking for is peek. Take a look at http://docs.oracle.com/javase/7/docs/api/java/util/Stack.html
However, you can use only pop, because it returns the removed object.

A: Reverse int array using stack
static int[] reverseArray(int[] arr) {
Stack < String > stack = new Stack();
int len = arr.length;
String[] strArr = new String[len];

for (int i = 0; i < arr.length; i++) {
    strArr[i] = String.valueOf(arr[i]);
    stack.push(strArr[i]);
}
for (int i = 0; i < strArr.length; i++) {
    strArr[i] = stack.pop();
    arr[i] = Integer.parseInt(strArr[i]);
}
return arr;

}

A: import java.util.Arrays;
import java.util.Stack;

public class reverse {
    public static void main(String[]args){
        Integer arr[] = {3,5,6,8};
        Stack<Integer> st = new Stack<>();
        for(int i =0;i<arr.length;i++){
            st.push(arr[i]);
        }
        for(int i =0;i<arr.length;i++){
            arr[i]=st.peek();
            st.pop();
        }
        System.out.println(Arrays.toString(arr));

    }
}


text:
Q: jquery: watch script on upload I am executing an ajax script to upload files and the PHP file that those the upload not only uploads but also executes MySQL queries.
My question is: is it possible to have a progress bar not only for the file upload but for the entire script? If possible with separated messages for each "Step" inside the php file.
Example (upload.php):
#Step 1
$message = "uploading file";

#Step 2
$message = "Creating Thumbnail";

#Step 3
$message = "Add to Database";